source: opengl-game/sdl-game.cpp@ 4e2c709

feature/imgui-sdl
Last change on this file since 4e2c709 was 4e2c709, checked in by Dmitry Portnoy <dportnoy@…>, 4 years ago

In VulkanGame, separate renderScene() into renderFrame() and presentFrame(), and in SDLGame, rename FrameRender() and FramePresent() to renderFrame() and presentFrame()

  • Property mode set to 100644
File size: 37.6 KB
Line 
1#include "sdl-game.hpp"
2
3#include <array>
4#include <iostream>
5#include <set>
6#include <stdexcept>
7
8#include <SDL2/SDL_vulkan.h>
9
10#include "IMGUI/imgui_impl_sdl.h"
11
12#include "logger.hpp"
13
14using namespace std;
15
16#define IMGUI_UNLIMITED_FRAME_RATE
17
18static bool g_SwapChainRebuild = false;
19
20static void check_imgui_vk_result(VkResult res) {
21 if (res == VK_SUCCESS) {
22 return;
23 }
24
25 ostringstream oss;
26 oss << "[imgui] Vulkan error! VkResult is \"" << VulkanUtils::resultString(res) << "\"" << __LINE__;
27 if (res < 0) {
28 throw runtime_error("Fatal: " + oss.str());
29 } else {
30 cerr << oss.str();
31 }
32}
33
34VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
35 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
36 VkDebugUtilsMessageTypeFlagsEXT messageType,
37 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
38 void* pUserData) {
39 cerr << "validation layer: " << pCallbackData->pMessage << endl;
40
41 return VK_FALSE;
42}
43
44VulkanGame::VulkanGame() {
45 // TODO: Double-check whether initialization should happen in the header, where the variables are declared, or here
46 // Also, decide whether to use this-> for all instance variables, or only when necessary
47
48 this->debugMessenger = VK_NULL_HANDLE;
49
50 this->gui = nullptr;
51 this->window = nullptr;
52
53 this->swapChainPresentMode = VK_PRESENT_MODE_MAX_ENUM_KHR;
54 this->swapChainMinImageCount = 0;
55}
56
57VulkanGame::~VulkanGame() {
58}
59
60void VulkanGame::run(int width, int height, unsigned char guiFlags) {
61 cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
62
63 cout << "Vulkan Game" << endl;
64
65 if (initUI(width, height, guiFlags) == RTWO_ERROR) {
66 return;
67 }
68
69 initVulkan();
70
71 // Create Descriptor Pool
72 {
73 VkDescriptorPoolSize pool_sizes[] =
74 {
75 { VK_DESCRIPTOR_TYPE_SAMPLER, 1000 },
76 { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 },
77 { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 },
78 { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 },
79 { VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 },
80 { VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 },
81 { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 },
82 { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 },
83 { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 },
84 { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 },
85 { VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 }
86 };
87 VkDescriptorPoolCreateInfo pool_info = {};
88 pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
89 pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
90 pool_info.maxSets = 1000 * IM_ARRAYSIZE(pool_sizes);
91 pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes);
92 pool_info.pPoolSizes = pool_sizes;
93
94 VKUTIL_CHECK_RESULT(vkCreateDescriptorPool(device, &pool_info, nullptr, &descriptorPool),
95 "failed to create descriptor pool");
96 }
97
98 // TODO: Do this in one place and save it instead of redoing it every time I need a queue family index
99 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
100
101 // Setup Dear ImGui context
102 IMGUI_CHECKVERSION();
103 ImGui::CreateContext();
104 ImGuiIO& io = ImGui::GetIO();
105 //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
106 //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
107
108 // Setup Dear ImGui style
109 ImGui::StyleColorsDark();
110 //ImGui::StyleColorsClassic();
111
112 // Setup Platform/Renderer bindings
113 ImGui_ImplSDL2_InitForVulkan(window);
114 ImGui_ImplVulkan_InitInfo init_info = {};
115 init_info.Instance = instance;
116 init_info.PhysicalDevice = physicalDevice;
117 init_info.Device = device;
118 init_info.QueueFamily = indices.graphicsFamily.value();
119 init_info.Queue = graphicsQueue;
120 init_info.DescriptorPool = descriptorPool;
121 init_info.Allocator = nullptr;
122 init_info.MinImageCount = swapChainMinImageCount;
123 init_info.ImageCount = swapChainImageCount;
124 init_info.CheckVkResultFn = check_imgui_vk_result;
125 ImGui_ImplVulkan_Init(&init_info, renderPass);
126
127 // Load Fonts
128 // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
129 // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
130 // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
131 // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
132 // - Read 'docs/FONTS.md' for more instructions and details.
133 // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
134 //io.Fonts->AddFontDefault();
135 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
136 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
137 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
138 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
139 //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
140 //assert(font != NULL);
141
142 // Upload Fonts
143 {
144 VkCommandBuffer commandBuffer = VulkanUtils::beginSingleTimeCommands(device, resourceCommandPool);
145
146 ImGui_ImplVulkan_CreateFontsTexture(commandBuffer);
147
148 VulkanUtils::endSingleTimeCommands(device, resourceCommandPool, commandBuffer, graphicsQueue);
149
150 ImGui_ImplVulkan_DestroyFontUploadObjects();
151 }
152
153 // Our state
154 bool show_demo_window = true;
155 bool show_another_window = false;
156
157 done = false;
158 while (!done) {
159 // Poll and handle events (inputs, window resize, etc.)
160 // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
161 // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
162 // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
163 // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
164 SDL_Event event;
165 while (SDL_PollEvent(&event)) {
166 ImGui_ImplSDL2_ProcessEvent(&event);
167 if (event.type == SDL_QUIT)
168 done = true;
169 if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window))
170 done = true;
171 }
172
173 // Resize swap chain?
174 if (g_SwapChainRebuild) {
175 int width, height;
176 SDL_GetWindowSize(window, &width, &height);
177 if (width > 0 && height > 0) {
178 // TODO: This should be used if the min image count changes, presumably because a new surface was created
179 // with a different image count or something like that. Maybe I want to add code to query for a new min image count
180 // during swapchain recreation to take advantage of this
181 ImGui_ImplVulkan_SetMinImageCount(swapChainMinImageCount);
182
183 recreateSwapChain();
184
185 imageIndex = 0;
186 g_SwapChainRebuild = false;
187 }
188 }
189
190 // Start the Dear ImGui frame
191 ImGui_ImplVulkan_NewFrame();
192 ImGui_ImplSDL2_NewFrame(window);
193 ImGui::NewFrame();
194
195 // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
196 if (show_demo_window)
197 ImGui::ShowDemoWindow(&show_demo_window);
198
199 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
200 {
201 static int counter = 0;
202
203 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
204
205 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
206 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
207 ImGui::Checkbox("Another Window", &show_another_window);
208
209 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
210 counter++;
211 ImGui::SameLine();
212 ImGui::Text("counter = %d", counter);
213
214 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
215 ImGui::End();
216 }
217
218 // 3. Show another simple window.
219 if (show_another_window)
220 {
221 ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
222 ImGui::Text("Hello from another window!");
223 if (ImGui::Button("Close Me"))
224 show_another_window = false;
225 ImGui::End();
226 }
227
228 // Rendering
229 ImGui::Render();
230 ImDrawData* draw_data = ImGui::GetDrawData();
231 const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f);
232 if (!is_minimized) {
233 renderFrame(draw_data);
234 presentFrame();
235 }
236 }
237
238 cleanup();
239
240 close_log();
241}
242
243bool VulkanGame::initUI(int width, int height, unsigned char guiFlags) {
244 // TODO: Create a game-gui function to get the gui version and retrieve it that way
245
246 SDL_VERSION(&sdlVersion); // This gets the compile-time version
247 SDL_GetVersion(&sdlVersion); // This gets the runtime version
248
249 cout << "SDL " <<
250 to_string(sdlVersion.major) << "." <<
251 to_string(sdlVersion.minor) << "." <<
252 to_string(sdlVersion.patch) << endl;
253
254 // TODO: Refactor the logger api to be more flexible,
255 // esp. since gl_log() and gl_log_err() have issues printing anything besides strings
256 restart_gl_log();
257 gl_log("starting SDL\n%s.%s.%s",
258 to_string(sdlVersion.major).c_str(),
259 to_string(sdlVersion.minor).c_str(),
260 to_string(sdlVersion.patch).c_str());
261
262 // TODO: Use open_Log() and related functions instead of gl_log ones
263 // TODO: In addition, delete the gl_log functions
264 open_log();
265 get_log() << "starting SDL" << endl;
266 get_log() <<
267 (int)sdlVersion.major << "." <<
268 (int)sdlVersion.minor << "." <<
269 (int)sdlVersion.patch << endl;
270
271 // TODO: Put all fonts, textures, and images in the assets folder
272 gui = new GameGui_SDL();
273
274 if (gui->init() == RTWO_ERROR) {
275 // TODO: Also print these sorts of errors to the log
276 cout << "UI library could not be initialized!" << endl;
277 cout << gui->getError() << endl;
278 return RTWO_ERROR;
279 }
280
281 window = (SDL_Window*)gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
282 if (window == nullptr) {
283 cout << "Window could not be created!" << endl;
284 cout << gui->getError() << endl;
285 return RTWO_ERROR;
286 }
287
288 cout << "Target window size: (" << width << ", " << height << ")" << endl;
289 cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
290
291 return RTWO_SUCCESS;
292}
293
294void VulkanGame::initVulkan() {
295 const vector<const char*> validationLayers = {
296 "VK_LAYER_KHRONOS_validation"
297 };
298 const vector<const char*> deviceExtensions = {
299 VK_KHR_SWAPCHAIN_EXTENSION_NAME
300 };
301
302 createVulkanInstance(validationLayers);
303 setupDebugMessenger();
304 createVulkanSurface();
305 pickPhysicalDevice(deviceExtensions);
306 createLogicalDevice(validationLayers, deviceExtensions);
307 chooseSwapChainProperties();
308 createSwapChain();
309 createImageViews();
310 createRenderPass();
311 createResourceCommandPool();
312
313 createCommandPools();
314
315 VulkanUtils::createDepthImage(device, physicalDevice, resourceCommandPool, findDepthFormat(), swapChainExtent,
316 depthImage, graphicsQueue);
317
318 createFramebuffers();
319
320 // TODO: Initialize pipelines here
321
322 createCommandBuffers();
323
324 createSyncObjects();
325}
326
327void VulkanGame::cleanup() {
328 // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals)
329 //vkQueueWaitIdle(g_Queue);
330 if (vkDeviceWaitIdle(device) != VK_SUCCESS) {
331 throw runtime_error("failed to wait for device!");
332 }
333
334 ImGui_ImplVulkan_Shutdown();
335 ImGui_ImplSDL2_Shutdown();
336 ImGui::DestroyContext();
337
338 cleanupSwapChain();
339
340 // this would actually be destroyed in the pipeline class
341 vkDestroyDescriptorPool(device, descriptorPool, nullptr);
342
343 vkDestroyCommandPool(device, resourceCommandPool, nullptr);
344
345 vkDestroyDevice(device, nullptr);
346 vkDestroySurfaceKHR(instance, surface, nullptr);
347
348 if (ENABLE_VALIDATION_LAYERS) {
349 VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
350 }
351
352 vkDestroyInstance(instance, nullptr);
353
354 gui->destroyWindow();
355 gui->shutdown();
356 delete gui;
357}
358
359void VulkanGame::createVulkanInstance(const vector<const char*>& validationLayers) {
360 if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
361 throw runtime_error("validation layers requested, but not available!");
362 }
363
364 VkApplicationInfo appInfo = {};
365 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
366 appInfo.pApplicationName = "Vulkan Game";
367 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
368 appInfo.pEngineName = "No Engine";
369 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
370 appInfo.apiVersion = VK_API_VERSION_1_0;
371
372 VkInstanceCreateInfo createInfo = {};
373 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
374 createInfo.pApplicationInfo = &appInfo;
375
376 vector<const char*> extensions = gui->getRequiredExtensions();
377 if (ENABLE_VALIDATION_LAYERS) {
378 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
379 }
380
381 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
382 createInfo.ppEnabledExtensionNames = extensions.data();
383
384 cout << endl << "Extensions:" << endl;
385 for (const char* extensionName : extensions) {
386 cout << extensionName << endl;
387 }
388 cout << endl;
389
390 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
391 if (ENABLE_VALIDATION_LAYERS) {
392 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
393 createInfo.ppEnabledLayerNames = validationLayers.data();
394
395 populateDebugMessengerCreateInfo(debugCreateInfo);
396 createInfo.pNext = &debugCreateInfo;
397 }
398 else {
399 createInfo.enabledLayerCount = 0;
400
401 createInfo.pNext = nullptr;
402 }
403
404 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
405 throw runtime_error("failed to create instance!");
406 }
407}
408
409void VulkanGame::setupDebugMessenger() {
410 if (!ENABLE_VALIDATION_LAYERS) {
411 return;
412 }
413
414 VkDebugUtilsMessengerCreateInfoEXT createInfo;
415 populateDebugMessengerCreateInfo(createInfo);
416
417 if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
418 throw runtime_error("failed to set up debug messenger!");
419 }
420}
421
422void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
423 createInfo = {};
424 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
425 createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
426 createInfo.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;
427 createInfo.pfnUserCallback = debugCallback;
428}
429
430void VulkanGame::createVulkanSurface() {
431 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
432 throw runtime_error("failed to create window surface!");
433 }
434}
435
436void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
437 uint32_t deviceCount = 0;
438 // TODO: Check VkResult
439 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
440
441 if (deviceCount == 0) {
442 throw runtime_error("failed to find GPUs with Vulkan support!");
443 }
444
445 vector<VkPhysicalDevice> devices(deviceCount);
446 // TODO: Check VkResult
447 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
448
449 cout << endl << "Graphics cards:" << endl;
450 for (const VkPhysicalDevice& device : devices) {
451 if (isDeviceSuitable(device, deviceExtensions)) {
452 physicalDevice = device;
453 break;
454 }
455 }
456 cout << endl;
457
458 if (physicalDevice == VK_NULL_HANDLE) {
459 throw runtime_error("failed to find a suitable GPU!");
460 }
461}
462
463bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions) {
464 VkPhysicalDeviceProperties deviceProperties;
465 vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
466
467 cout << "Device: " << deviceProperties.deviceName << endl;
468
469 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
470 bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
471 bool swapChainAdequate = false;
472
473 if (extensionsSupported) {
474 vector<VkSurfaceFormatKHR> formats = VulkanUtils::querySwapChainFormats(physicalDevice, surface);
475 vector<VkPresentModeKHR> presentModes = VulkanUtils::querySwapChainPresentModes(physicalDevice, surface);
476
477 swapChainAdequate = !formats.empty() && !presentModes.empty();
478 }
479
480 VkPhysicalDeviceFeatures supportedFeatures;
481 vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
482
483 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
484}
485
486void VulkanGame::createLogicalDevice(const vector<const char*>& validationLayers,
487 const vector<const char*>& deviceExtensions) {
488 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
489
490 if (!indices.isComplete()) {
491 throw runtime_error("failed to find required queue families!");
492 }
493
494 // TODO: Using separate graphics and present queues currently works, but I should verify that I'm
495 // using them correctly to get the most benefit out of separate queues
496
497 vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
498 set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
499
500 float queuePriority = 1.0f;
501 for (uint32_t queueFamily : uniqueQueueFamilies) {
502 VkDeviceQueueCreateInfo queueCreateInfo = {};
503 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
504 queueCreateInfo.queueCount = 1;
505 queueCreateInfo.queueFamilyIndex = queueFamily;
506 queueCreateInfo.pQueuePriorities = &queuePriority;
507
508 queueCreateInfoList.push_back(queueCreateInfo);
509 }
510
511 VkPhysicalDeviceFeatures deviceFeatures = {};
512 deviceFeatures.samplerAnisotropy = VK_TRUE;
513
514 VkDeviceCreateInfo createInfo = {};
515 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
516
517 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
518 createInfo.pQueueCreateInfos = queueCreateInfoList.data();
519
520 createInfo.pEnabledFeatures = &deviceFeatures;
521
522 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
523 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
524
525 // These fields are ignored by up-to-date Vulkan implementations,
526 // but it's a good idea to set them for backwards compatibility
527 if (ENABLE_VALIDATION_LAYERS) {
528 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
529 createInfo.ppEnabledLayerNames = validationLayers.data();
530 }
531 else {
532 createInfo.enabledLayerCount = 0;
533 }
534
535 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
536 throw runtime_error("failed to create logical device!");
537 }
538
539 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
540 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
541}
542
543void VulkanGame::chooseSwapChainProperties() {
544 vector<VkSurfaceFormatKHR> availableFormats = VulkanUtils::querySwapChainFormats(physicalDevice, surface);
545 vector<VkPresentModeKHR> availablePresentModes = VulkanUtils::querySwapChainPresentModes(physicalDevice, surface);
546
547 // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
548 // Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format
549 // Additionally several new color spaces were introduced with Vulkan Spec v1.0.40,
550 // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used.
551 swapChainSurfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(availableFormats,
552 { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM },
553 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR);
554
555#ifdef IMGUI_UNLIMITED_FRAME_RATE
556 vector<VkPresentModeKHR> presentModes{
557 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR
558 };
559#else
560 vector<VkPresentModeKHR> presentModes{ VK_PRESENT_MODE_FIFO_KHR };
561#endif
562
563 swapChainPresentMode = VulkanUtils::chooseSwapPresentMode(availablePresentModes, presentModes);
564
565 cout << "[vulkan] Selected PresentMode = " << swapChainPresentMode << endl;
566
567 VkSurfaceCapabilitiesKHR capabilities = VulkanUtils::querySwapChainCapabilities(physicalDevice, surface);
568
569 // If min image count was not specified, request different count of images dependent on selected present mode
570 if (swapChainMinImageCount == 0) {
571 if (swapChainPresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
572 swapChainMinImageCount = 3;
573 }
574 else if (swapChainPresentMode == VK_PRESENT_MODE_FIFO_KHR || swapChainPresentMode == VK_PRESENT_MODE_FIFO_RELAXED_KHR) {
575 swapChainMinImageCount = 2;
576 }
577 else if (swapChainPresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
578 swapChainMinImageCount = 1;
579 }
580 else {
581 throw runtime_error("unexpected present mode!");
582 }
583 }
584
585 if (swapChainMinImageCount < capabilities.minImageCount) {
586 swapChainMinImageCount = capabilities.minImageCount;
587 }
588 else if (capabilities.maxImageCount != 0 && swapChainMinImageCount > capabilities.maxImageCount) {
589 swapChainMinImageCount = capabilities.maxImageCount;
590 }
591}
592
593void VulkanGame::createSwapChain() {
594 VkSurfaceCapabilitiesKHR capabilities = VulkanUtils::querySwapChainCapabilities(physicalDevice, surface);
595
596 swapChainExtent = VulkanUtils::chooseSwapExtent(capabilities, gui->getWindowWidth(), gui->getWindowHeight());
597
598 VkSwapchainCreateInfoKHR createInfo = {};
599 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
600 createInfo.surface = surface;
601 createInfo.minImageCount = swapChainMinImageCount;
602 createInfo.imageFormat = swapChainSurfaceFormat.format;
603 createInfo.imageColorSpace = swapChainSurfaceFormat.colorSpace;
604 createInfo.imageExtent = swapChainExtent;
605 createInfo.imageArrayLayers = 1;
606 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
607
608 // TODO: Maybe save this result so I don't have to recalculate it every time
609 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
610 uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
611
612 if (indices.graphicsFamily != indices.presentFamily) {
613 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
614 createInfo.queueFamilyIndexCount = 2;
615 createInfo.pQueueFamilyIndices = queueFamilyIndices;
616 }
617 else {
618 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
619 createInfo.queueFamilyIndexCount = 0;
620 createInfo.pQueueFamilyIndices = nullptr;
621 }
622
623 createInfo.preTransform = capabilities.currentTransform;
624 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
625 createInfo.presentMode = swapChainPresentMode;
626 createInfo.clipped = VK_TRUE;
627 createInfo.oldSwapchain = VK_NULL_HANDLE;
628
629 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
630 throw runtime_error("failed to create swap chain!");
631 }
632
633 if (vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, nullptr) != VK_SUCCESS) {
634 throw runtime_error("failed to get swap chain image count!");
635 }
636
637 swapChainImages.resize(swapChainImageCount);
638 if (vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, swapChainImages.data()) != VK_SUCCESS) {
639 throw runtime_error("failed to get swap chain images!");
640 }
641}
642
643void VulkanGame::createImageViews() {
644 swapChainImageViews.resize(swapChainImageCount);
645
646 for (uint32_t i = 0; i < swapChainImageViews.size(); i++) {
647 swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainSurfaceFormat.format,
648 VK_IMAGE_ASPECT_COLOR_BIT);
649 }
650}
651
652void VulkanGame::createRenderPass() {
653 VkAttachmentDescription colorAttachment = {};
654 colorAttachment.format = swapChainSurfaceFormat.format;
655 colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
656 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // Set to VK_ATTACHMENT_LOAD_OP_DONT_CARE to disable clearing
657 colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
658 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
659 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
660 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
661 colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
662
663 VkAttachmentReference colorAttachmentRef = {};
664 colorAttachmentRef.attachment = 0;
665 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
666
667 VkAttachmentDescription depthAttachment = {};
668 depthAttachment.format = findDepthFormat();
669 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
670 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
671 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
672 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
673 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
674 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
675 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
676
677 VkAttachmentReference depthAttachmentRef = {};
678 depthAttachmentRef.attachment = 1;
679 depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
680
681 VkSubpassDescription subpass = {};
682 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
683 subpass.colorAttachmentCount = 1;
684 subpass.pColorAttachments = &colorAttachmentRef;
685 //subpass.pDepthStencilAttachment = &depthAttachmentRef;
686
687 VkSubpassDependency dependency = {};
688 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
689 dependency.dstSubpass = 0;
690 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
691 dependency.srcAccessMask = 0;
692 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
693 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
694
695 array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
696 VkRenderPassCreateInfo renderPassInfo = {};
697 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
698 renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
699 renderPassInfo.pAttachments = attachments.data();
700 renderPassInfo.subpassCount = 1;
701 renderPassInfo.pSubpasses = &subpass;
702 renderPassInfo.dependencyCount = 1;
703 renderPassInfo.pDependencies = &dependency;
704
705 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
706 throw runtime_error("failed to create render pass!");
707 }
708
709 // We do not create a pipeline by default as this is also used by examples' main.cpp,
710 // but secondary viewport in multi-viewport mode may want to create one with:
711 //ImGui_ImplVulkan_CreatePipeline(device, g_Allocator, VK_NULL_HANDLE, g_MainWindowData.RenderPass, VK_SAMPLE_COUNT_1_BIT, &g_MainWindowData.Pipeline);
712}
713
714VkFormat VulkanGame::findDepthFormat() {
715 return VulkanUtils::findSupportedFormat(
716 physicalDevice,
717 { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
718 VK_IMAGE_TILING_OPTIMAL,
719 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
720 );
721}
722
723void VulkanGame::createResourceCommandPool() {
724 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
725
726 VkCommandPoolCreateInfo poolInfo = {};
727 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
728 poolInfo.queueFamilyIndex = indices.graphicsFamily.value();
729 poolInfo.flags = 0;
730
731 if (vkCreateCommandPool(device, &poolInfo, nullptr, &resourceCommandPool) != VK_SUCCESS) {
732 throw runtime_error("failed to create resource command pool!");
733 }
734}
735
736void VulkanGame::createCommandPools() {
737 commandPools.resize(swapChainImageCount);
738
739 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
740
741 for (size_t i = 0; i < swapChainImageCount; i++) {
742 VkCommandPoolCreateInfo poolInfo = {};
743 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
744 poolInfo.queueFamilyIndex = indices.graphicsFamily.value();
745 poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
746 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPools[i]) != VK_SUCCESS) {
747 throw runtime_error("failed to create graphics command pool!");
748 }
749 }
750}
751
752void VulkanGame::createFramebuffers() {
753 swapChainFramebuffers.resize(swapChainImageCount);
754
755 VkFramebufferCreateInfo framebufferInfo = {};
756 framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
757 framebufferInfo.renderPass = renderPass;
758 framebufferInfo.width = swapChainExtent.width;
759 framebufferInfo.height = swapChainExtent.height;
760 framebufferInfo.layers = 1;
761
762 for (size_t i = 0; i < swapChainImageCount; i++) {
763 array<VkImageView, 2> attachments = {
764 swapChainImageViews[i],
765 depthImage.imageView
766 };
767
768 framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
769 framebufferInfo.pAttachments = attachments.data();
770
771 if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
772 throw runtime_error("failed to create framebuffer!");
773 }
774 }
775}
776
777void VulkanGame::createCommandBuffers() {
778 commandBuffers.resize(swapChainImageCount);
779
780 for (size_t i = 0; i < swapChainImageCount; i++) {
781 VkCommandBufferAllocateInfo allocInfo = {};
782 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
783 allocInfo.commandPool = commandPools[i];
784 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
785 allocInfo.commandBufferCount = 1;
786
787 if (vkAllocateCommandBuffers(device, &allocInfo, &commandBuffers[i]) != VK_SUCCESS) {
788 throw runtime_error("failed to allocate command buffers!");
789 }
790 }
791}
792
793void VulkanGame::createSyncObjects() {
794 imageAcquiredSemaphores.resize(swapChainImageCount);
795 renderCompleteSemaphores.resize(swapChainImageCount);
796 inFlightFences.resize(swapChainImageCount);
797
798 VkSemaphoreCreateInfo semaphoreInfo = {};
799 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
800
801 VkFenceCreateInfo fenceInfo = {};
802 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
803 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
804
805 for (size_t i = 0; i < swapChainImageCount; i++) {
806 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAcquiredSemaphores[i]) != VK_SUCCESS) {
807 throw runtime_error("failed to create image acquired sempahore for a frame!");
808 }
809
810 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderCompleteSemaphores[i]) != VK_SUCCESS) {
811 throw runtime_error("failed to create render complete sempahore for a frame!");
812 }
813
814 if (vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) {
815 throw runtime_error("failed to create fence for a frame!");
816 }
817 }
818}
819
820void VulkanGame::renderFrame(ImDrawData* draw_data) {
821 VkResult result = vkAcquireNextImageKHR(device, swapChain, numeric_limits<uint64_t>::max(),
822 imageAcquiredSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
823
824 if (result == VK_ERROR_OUT_OF_DATE_KHR) {
825 g_SwapChainRebuild = true;
826 return;
827 }
828 else {
829 VKUTIL_CHECK_RESULT(result, "failed to acquire swap chain image!");
830 }
831
832 VKUTIL_CHECK_RESULT(vkWaitForFences(device, 1, &inFlightFences[imageIndex], VK_TRUE, numeric_limits<uint64_t>::max()),
833 "failed waiting for fence!");
834
835 VKUTIL_CHECK_RESULT(vkResetFences(device, 1, &inFlightFences[imageIndex]),
836 "failed to reset fence!");
837
838 // START OF NEW CODE
839 // I don't have analogous code in vulkan-game right now because I record command buffers once
840 // before the render loop ever starts. I should change this
841
842 VKUTIL_CHECK_RESULT(vkResetCommandPool(device, commandPools[imageIndex], 0),
843 "failed to reset command pool!");
844
845 VkCommandBufferBeginInfo info = {};
846 info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
847 info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
848
849 VKUTIL_CHECK_RESULT(vkBeginCommandBuffer(commandBuffers[imageIndex], &info),
850 "failed to begin recording command buffer!");
851
852 VkRenderPassBeginInfo renderPassInfo = {};
853 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
854 renderPassInfo.renderPass = renderPass;
855 renderPassInfo.framebuffer = swapChainFramebuffers[imageIndex];
856 renderPassInfo.renderArea.extent = swapChainExtent;
857
858 array<VkClearValue, 2> clearValues = {};
859 clearValues[0].color = { { 0.45f, 0.55f, 0.60f, 1.00f } };
860 clearValues[1].depthStencil = { 1.0f, 0 };
861
862 renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
863 renderPassInfo.pClearValues = clearValues.data();
864
865 vkCmdBeginRenderPass(commandBuffers[imageIndex], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
866
867 // Record dear imgui primitives into command buffer
868 ImGui_ImplVulkan_RenderDrawData(draw_data, commandBuffers[imageIndex]);
869
870 // Submit command buffer
871 vkCmdEndRenderPass(commandBuffers[imageIndex]);
872
873 VKUTIL_CHECK_RESULT(vkEndCommandBuffer(commandBuffers[imageIndex]),
874 "failed to record command buffer!");
875
876 // END OF NEW CODE
877
878 VkSemaphore waitSemaphores[] = { imageAcquiredSemaphores[currentFrame] };
879 VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
880 VkSemaphore signalSemaphores[] = { renderCompleteSemaphores[currentFrame] };
881
882 VkSubmitInfo submitInfo = {};
883 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
884 submitInfo.waitSemaphoreCount = 1;
885 submitInfo.pWaitSemaphores = waitSemaphores;
886 submitInfo.pWaitDstStageMask = &wait_stage;
887 submitInfo.commandBufferCount = 1;
888 submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
889 submitInfo.signalSemaphoreCount = 1;
890 submitInfo.pSignalSemaphores = signalSemaphores;
891
892 VKUTIL_CHECK_RESULT(vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[imageIndex]),
893 "failed to submit draw command buffer!");
894}
895
896void VulkanGame::presentFrame() {
897 if (g_SwapChainRebuild)
898 return;
899
900 VkSemaphore signalSemaphores[] = { renderCompleteSemaphores[currentFrame] };
901
902 VkPresentInfoKHR presentInfo = {};
903 presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
904 presentInfo.waitSemaphoreCount = 1;
905 presentInfo.pWaitSemaphores = signalSemaphores;
906 presentInfo.swapchainCount = 1;
907 presentInfo.pSwapchains = &swapChain;
908 presentInfo.pImageIndices = &imageIndex;
909 presentInfo.pResults = nullptr;
910
911 VkResult result = vkQueuePresentKHR(presentQueue, &presentInfo);
912
913 // In vulkan-game, I also handle VK_SUBOPTIMAL_KHR and framebufferResized. g_SwapChainRebuild is kind of similar
914 // to framebufferResized, but not quite the same
915 if (result == VK_ERROR_OUT_OF_DATE_KHR) {
916 g_SwapChainRebuild = true;
917 return;
918 }
919 else if (result != VK_SUCCESS) {
920 throw runtime_error("failed to present swap chain image!");
921 }
922
923 currentFrame = (currentFrame + 1) % swapChainImageCount;
924}
925
926void VulkanGame::recreateSwapChain() {
927 if (vkDeviceWaitIdle(device) != VK_SUCCESS) {
928 throw runtime_error("failed to wait for device!");
929 }
930
931 cleanupSwapChain();
932
933 createSwapChain();
934 createImageViews();
935 createRenderPass();
936
937 createCommandPools();
938
939 // The depth buffer does need to be recreated with the swap chain since its dimensions depend on the window size
940 // and resizing the window is a common reason to recreate the swapchain
941 VulkanUtils::createDepthImage(device, physicalDevice, resourceCommandPool, findDepthFormat(), swapChainExtent,
942 depthImage, graphicsQueue);
943
944 createFramebuffers();
945
946 // TODO: Update pipelines here
947
948 createCommandBuffers();
949
950 createSyncObjects();
951}
952
953void VulkanGame::cleanupSwapChain() {
954 VulkanUtils::destroyVulkanImage(device, depthImage);
955
956 for (VkFramebuffer framebuffer : swapChainFramebuffers) {
957 vkDestroyFramebuffer(device, framebuffer, nullptr);
958 }
959
960 for (uint32_t i = 0; i < swapChainImageCount; i++) {
961 vkFreeCommandBuffers(device, commandPools[i], 1, &commandBuffers[i]);
962 vkDestroyCommandPool(device, commandPools[i], nullptr);
963 }
964
965 for (uint32_t i = 0; i < swapChainImageCount; i++) {
966 vkDestroySemaphore(device, imageAcquiredSemaphores[i], nullptr);
967 vkDestroySemaphore(device, renderCompleteSemaphores[i], nullptr);
968 vkDestroyFence(device, inFlightFences[i], nullptr);
969 }
970
971 vkDestroyRenderPass(device, renderPass, nullptr);
972
973 for (VkImageView imageView : swapChainImageViews) {
974 vkDestroyImageView(device, imageView, nullptr);
975 }
976
977 vkDestroySwapchainKHR(device, swapChain, nullptr);
978}
Note: See TracBrowser for help on using the repository browser.