source: opengl-game/sdl-game.cpp@ c6f0793

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

Use done instead of quit as the game loop flag and change it to an instance variable in SDLGame

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