source: opengl-game/sdl-game.cpp@ 8b823e7

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

Create an error-checking macro to check Vulkan function results, which will print a custom message, the error code, and the line number for all results besides VK_SUCCESS, and update the imgui error-checking callback with similar functionality.

  • 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 // Main loop
264 bool done = false;
265 while (!done) {
266 // Poll and handle events (inputs, window resize, etc.)
267 // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
268 // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
269 // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
270 // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
271 SDL_Event event;
272 while (SDL_PollEvent(&event)) {
273 ImGui_ImplSDL2_ProcessEvent(&event);
274 if (event.type == SDL_QUIT)
275 done = true;
276 if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window))
277 done = true;
278 }
279
280 // Resize swap chain?
281 if (g_SwapChainRebuild) {
282 int width, height;
283 SDL_GetWindowSize(window, &width, &height);
284 if (width > 0 && height > 0) {
285 // TODO: This should be used if the min image count changes, presumably because a new surface was created
286 // with a different image count or something like that. Maybe I want to add code to query for a new min image count
287 // during swapchain recreation to take advantage of this
288 ImGui_ImplVulkan_SetMinImageCount(swapChainMinImageCount);
289
290 recreateSwapChain();
291
292 imageIndex = 0;
293 g_SwapChainRebuild = false;
294 }
295 }
296
297 // Start the Dear ImGui frame
298 ImGui_ImplVulkan_NewFrame();
299 ImGui_ImplSDL2_NewFrame(window);
300 ImGui::NewFrame();
301
302 // 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!).
303 if (show_demo_window)
304 ImGui::ShowDemoWindow(&show_demo_window);
305
306 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
307 {
308 static int counter = 0;
309
310 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
311
312 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
313 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
314 ImGui::Checkbox("Another Window", &show_another_window);
315
316 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
317 counter++;
318 ImGui::SameLine();
319 ImGui::Text("counter = %d", counter);
320
321 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
322 ImGui::End();
323 }
324
325 // 3. Show another simple window.
326 if (show_another_window)
327 {
328 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)
329 ImGui::Text("Hello from another window!");
330 if (ImGui::Button("Close Me"))
331 show_another_window = false;
332 ImGui::End();
333 }
334
335 // Rendering
336 ImGui::Render();
337 ImDrawData* draw_data = ImGui::GetDrawData();
338 const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f);
339 if (!is_minimized) {
340 FrameRender(draw_data);
341 FramePresent();
342 }
343 }
344
345 cleanup();
346
347 close_log();
348}
349
350bool VulkanGame::initUI(int width, int height, unsigned char guiFlags) {
351 // TODO: Create a game-gui function to get the gui version and retrieve it that way
352
353 SDL_VERSION(&sdlVersion); // This gets the compile-time version
354 SDL_GetVersion(&sdlVersion); // This gets the runtime version
355
356 cout << "SDL " <<
357 to_string(sdlVersion.major) << "." <<
358 to_string(sdlVersion.minor) << "." <<
359 to_string(sdlVersion.patch) << endl;
360
361 // TODO: Refactor the logger api to be more flexible,
362 // esp. since gl_log() and gl_log_err() have issues printing anything besides strings
363 restart_gl_log();
364 gl_log("starting SDL\n%s.%s.%s",
365 to_string(sdlVersion.major).c_str(),
366 to_string(sdlVersion.minor).c_str(),
367 to_string(sdlVersion.patch).c_str());
368
369 // TODO: Use open_Log() and related functions instead of gl_log ones
370 // TODO: In addition, delete the gl_log functions
371 open_log();
372 get_log() << "starting SDL" << endl;
373 get_log() <<
374 (int)sdlVersion.major << "." <<
375 (int)sdlVersion.minor << "." <<
376 (int)sdlVersion.patch << endl;
377
378 // TODO: Put all fonts, textures, and images in the assets folder
379 gui = new GameGui_SDL();
380
381 if (gui->init() == RTWO_ERROR) {
382 // TODO: Also print these sorts of errors to the log
383 cout << "UI library could not be initialized!" << endl;
384 cout << gui->getError() << endl;
385 return RTWO_ERROR;
386 }
387
388 window = (SDL_Window*)gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
389 if (window == nullptr) {
390 cout << "Window could not be created!" << endl;
391 cout << gui->getError() << endl;
392 return RTWO_ERROR;
393 }
394
395 cout << "Target window size: (" << width << ", " << height << ")" << endl;
396 cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
397
398 return RTWO_SUCCESS;
399}
400
401void VulkanGame::initVulkan() {
402 const vector<const char*> validationLayers = {
403 "VK_LAYER_KHRONOS_validation"
404 };
405 const vector<const char*> deviceExtensions = {
406 VK_KHR_SWAPCHAIN_EXTENSION_NAME
407 };
408
409 createVulkanInstance(validationLayers);
410 setupDebugMessenger();
411 createVulkanSurface();
412 pickPhysicalDevice(deviceExtensions);
413 createLogicalDevice(validationLayers, deviceExtensions);
414 chooseSwapChainProperties();
415 createSwapChain();
416 createImageViews();
417 createRenderPass();
418 createResourceCommandPool();
419
420 createCommandPools();
421
422 VulkanUtils::createDepthImage(device, physicalDevice, resourceCommandPool, findDepthFormat(), swapChainExtent,
423 depthImage, graphicsQueue);
424
425 createFramebuffers();
426
427 // TODO: Initialize pipelines here
428
429 createCommandBuffers();
430
431 createSyncObjects();
432}
433
434void VulkanGame::cleanup() {
435 // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals)
436 //vkQueueWaitIdle(g_Queue);
437 if (vkDeviceWaitIdle(device) != VK_SUCCESS) {
438 throw runtime_error("failed to wait for device!");
439 }
440
441 ImGui_ImplVulkan_Shutdown();
442 ImGui_ImplSDL2_Shutdown();
443 ImGui::DestroyContext();
444
445 cleanupSwapChain();
446
447 // this would actually be destroyed in the pipeline class
448 vkDestroyDescriptorPool(device, descriptorPool, nullptr);
449
450 vkDestroyCommandPool(device, resourceCommandPool, nullptr);
451
452 vkDestroyDevice(device, nullptr);
453 vkDestroySurfaceKHR(instance, surface, nullptr);
454
455 if (ENABLE_VALIDATION_LAYERS) {
456 VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
457 }
458
459 vkDestroyInstance(instance, nullptr);
460
461 gui->destroyWindow();
462 gui->shutdown();
463 delete gui;
464}
465
466void VulkanGame::createVulkanInstance(const vector<const char*>& validationLayers) {
467 if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
468 throw runtime_error("validation layers requested, but not available!");
469 }
470
471 VkApplicationInfo appInfo = {};
472 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
473 appInfo.pApplicationName = "Vulkan Game";
474 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
475 appInfo.pEngineName = "No Engine";
476 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
477 appInfo.apiVersion = VK_API_VERSION_1_0;
478
479 VkInstanceCreateInfo createInfo = {};
480 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
481 createInfo.pApplicationInfo = &appInfo;
482
483 vector<const char*> extensions = gui->getRequiredExtensions();
484 if (ENABLE_VALIDATION_LAYERS) {
485 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
486 }
487
488 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
489 createInfo.ppEnabledExtensionNames = extensions.data();
490
491 cout << endl << "Extensions:" << endl;
492 for (const char* extensionName : extensions) {
493 cout << extensionName << endl;
494 }
495 cout << endl;
496
497 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
498 if (ENABLE_VALIDATION_LAYERS) {
499 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
500 createInfo.ppEnabledLayerNames = validationLayers.data();
501
502 populateDebugMessengerCreateInfo(debugCreateInfo);
503 createInfo.pNext = &debugCreateInfo;
504 }
505 else {
506 createInfo.enabledLayerCount = 0;
507
508 createInfo.pNext = nullptr;
509 }
510
511 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
512 throw runtime_error("failed to create instance!");
513 }
514}
515
516void VulkanGame::setupDebugMessenger() {
517 if (!ENABLE_VALIDATION_LAYERS) {
518 return;
519 }
520
521 VkDebugUtilsMessengerCreateInfoEXT createInfo;
522 populateDebugMessengerCreateInfo(createInfo);
523
524 if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
525 throw runtime_error("failed to set up debug messenger!");
526 }
527}
528
529void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
530 createInfo = {};
531 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
532 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;
533 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;
534 createInfo.pfnUserCallback = debugCallback;
535}
536
537void VulkanGame::createVulkanSurface() {
538 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
539 throw runtime_error("failed to create window surface!");
540 }
541}
542
543void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
544 uint32_t deviceCount = 0;
545 // TODO: Check VkResult
546 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
547
548 if (deviceCount == 0) {
549 throw runtime_error("failed to find GPUs with Vulkan support!");
550 }
551
552 vector<VkPhysicalDevice> devices(deviceCount);
553 // TODO: Check VkResult
554 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
555
556 cout << endl << "Graphics cards:" << endl;
557 for (const VkPhysicalDevice& device : devices) {
558 if (isDeviceSuitable(device, deviceExtensions)) {
559 physicalDevice = device;
560 break;
561 }
562 }
563 cout << endl;
564
565 if (physicalDevice == VK_NULL_HANDLE) {
566 throw runtime_error("failed to find a suitable GPU!");
567 }
568}
569
570bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions) {
571 VkPhysicalDeviceProperties deviceProperties;
572 vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
573
574 cout << "Device: " << deviceProperties.deviceName << endl;
575
576 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
577 bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
578 bool swapChainAdequate = false;
579
580 if (extensionsSupported) {
581 vector<VkSurfaceFormatKHR> formats = VulkanUtils::querySwapChainFormats(physicalDevice, surface);
582 vector<VkPresentModeKHR> presentModes = VulkanUtils::querySwapChainPresentModes(physicalDevice, surface);
583
584 swapChainAdequate = !formats.empty() && !presentModes.empty();
585 }
586
587 VkPhysicalDeviceFeatures supportedFeatures;
588 vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
589
590 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
591}
592
593void VulkanGame::createLogicalDevice(const vector<const char*>& validationLayers,
594 const vector<const char*>& deviceExtensions) {
595 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
596
597 if (!indices.isComplete()) {
598 throw runtime_error("failed to find required queue families!");
599 }
600
601 // TODO: Using separate graphics and present queues currently works, but I should verify that I'm
602 // using them correctly to get the most benefit out of separate queues
603
604 vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
605 set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
606
607 float queuePriority = 1.0f;
608 for (uint32_t queueFamily : uniqueQueueFamilies) {
609 VkDeviceQueueCreateInfo queueCreateInfo = {};
610 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
611 queueCreateInfo.queueCount = 1;
612 queueCreateInfo.queueFamilyIndex = queueFamily;
613 queueCreateInfo.pQueuePriorities = &queuePriority;
614
615 queueCreateInfoList.push_back(queueCreateInfo);
616 }
617
618 VkPhysicalDeviceFeatures deviceFeatures = {};
619 deviceFeatures.samplerAnisotropy = VK_TRUE;
620
621 VkDeviceCreateInfo createInfo = {};
622 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
623
624 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
625 createInfo.pQueueCreateInfos = queueCreateInfoList.data();
626
627 createInfo.pEnabledFeatures = &deviceFeatures;
628
629 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
630 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
631
632 // These fields are ignored by up-to-date Vulkan implementations,
633 // but it's a good idea to set them for backwards compatibility
634 if (ENABLE_VALIDATION_LAYERS) {
635 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
636 createInfo.ppEnabledLayerNames = validationLayers.data();
637 }
638 else {
639 createInfo.enabledLayerCount = 0;
640 }
641
642 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
643 throw runtime_error("failed to create logical device!");
644 }
645
646 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
647 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
648}
649
650void VulkanGame::chooseSwapChainProperties() {
651 vector<VkSurfaceFormatKHR> availableFormats = VulkanUtils::querySwapChainFormats(physicalDevice, surface);
652 vector<VkPresentModeKHR> availablePresentModes = VulkanUtils::querySwapChainPresentModes(physicalDevice, surface);
653
654 // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
655 // Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format
656 // Additionally several new color spaces were introduced with Vulkan Spec v1.0.40,
657 // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used.
658 swapChainSurfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(availableFormats,
659 { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM },
660 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR);
661
662#ifdef IMGUI_UNLIMITED_FRAME_RATE
663 vector<VkPresentModeKHR> presentModes{
664 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR
665 };
666#else
667 vector<VkPresentModeKHR> presentModes{ VK_PRESENT_MODE_FIFO_KHR };
668#endif
669
670 swapChainPresentMode = VulkanUtils::chooseSwapPresentMode(availablePresentModes, presentModes);
671
672 cout << "[vulkan] Selected PresentMode = " << swapChainPresentMode << endl;
673
674 VkSurfaceCapabilitiesKHR capabilities = VulkanUtils::querySwapChainCapabilities(physicalDevice, surface);
675
676 // If min image count was not specified, request different count of images dependent on selected present mode
677 if (swapChainMinImageCount == 0) {
678 if (swapChainPresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
679 swapChainMinImageCount = 3;
680 }
681 else if (swapChainPresentMode == VK_PRESENT_MODE_FIFO_KHR || swapChainPresentMode == VK_PRESENT_MODE_FIFO_RELAXED_KHR) {
682 swapChainMinImageCount = 2;
683 }
684 else if (swapChainPresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
685 swapChainMinImageCount = 1;
686 }
687 else {
688 throw runtime_error("unexpected present mode!");
689 }
690 }
691
692 if (swapChainMinImageCount < capabilities.minImageCount) {
693 swapChainMinImageCount = capabilities.minImageCount;
694 }
695 else if (capabilities.maxImageCount != 0 && swapChainMinImageCount > capabilities.maxImageCount) {
696 swapChainMinImageCount = capabilities.maxImageCount;
697 }
698}
699
700void VulkanGame::createSwapChain() {
701 VkSurfaceCapabilitiesKHR capabilities = VulkanUtils::querySwapChainCapabilities(physicalDevice, surface);
702
703 swapChainExtent = VulkanUtils::chooseSwapExtent(capabilities, gui->getWindowWidth(), gui->getWindowHeight());
704
705 VkSwapchainCreateInfoKHR createInfo = {};
706 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
707 createInfo.surface = surface;
708 createInfo.minImageCount = swapChainMinImageCount;
709 createInfo.imageFormat = swapChainSurfaceFormat.format;
710 createInfo.imageColorSpace = swapChainSurfaceFormat.colorSpace;
711 createInfo.imageExtent = swapChainExtent;
712 createInfo.imageArrayLayers = 1;
713 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
714
715 // TODO: Maybe save this result so I don't have to recalculate it every time
716 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
717 uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
718
719 if (indices.graphicsFamily != indices.presentFamily) {
720 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
721 createInfo.queueFamilyIndexCount = 2;
722 createInfo.pQueueFamilyIndices = queueFamilyIndices;
723 }
724 else {
725 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
726 createInfo.queueFamilyIndexCount = 0;
727 createInfo.pQueueFamilyIndices = nullptr;
728 }
729
730 createInfo.preTransform = capabilities.currentTransform;
731 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
732 createInfo.presentMode = swapChainPresentMode;
733 createInfo.clipped = VK_TRUE;
734 createInfo.oldSwapchain = VK_NULL_HANDLE;
735
736 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
737 throw runtime_error("failed to create swap chain!");
738 }
739
740 if (vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, nullptr) != VK_SUCCESS) {
741 throw runtime_error("failed to get swap chain image count!");
742 }
743
744 swapChainImages.resize(swapChainImageCount);
745 if (vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, swapChainImages.data()) != VK_SUCCESS) {
746 throw runtime_error("failed to get swap chain images!");
747 }
748}
749
750void VulkanGame::createImageViews() {
751 swapChainImageViews.resize(swapChainImageCount);
752
753 for (uint32_t i = 0; i < swapChainImageViews.size(); i++) {
754 swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainSurfaceFormat.format,
755 VK_IMAGE_ASPECT_COLOR_BIT);
756 }
757}
758
759void VulkanGame::createRenderPass() {
760 VkAttachmentDescription colorAttachment = {};
761 colorAttachment.format = swapChainSurfaceFormat.format;
762 colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
763 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // Set to VK_ATTACHMENT_LOAD_OP_DONT_CARE to disable clearing
764 colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
765 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
766 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
767 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
768 colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
769
770 VkAttachmentReference colorAttachmentRef = {};
771 colorAttachmentRef.attachment = 0;
772 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
773
774 VkAttachmentDescription depthAttachment = {};
775 depthAttachment.format = findDepthFormat();
776 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
777 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
778 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
779 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
780 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
781 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
782 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
783
784 VkAttachmentReference depthAttachmentRef = {};
785 depthAttachmentRef.attachment = 1;
786 depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
787
788 VkSubpassDescription subpass = {};
789 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
790 subpass.colorAttachmentCount = 1;
791 subpass.pColorAttachments = &colorAttachmentRef;
792 //subpass.pDepthStencilAttachment = &depthAttachmentRef;
793
794 VkSubpassDependency dependency = {};
795 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
796 dependency.dstSubpass = 0;
797 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
798 dependency.srcAccessMask = 0;
799 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
800 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
801
802 array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
803 VkRenderPassCreateInfo renderPassInfo = {};
804 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
805 renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
806 renderPassInfo.pAttachments = attachments.data();
807 renderPassInfo.subpassCount = 1;
808 renderPassInfo.pSubpasses = &subpass;
809 renderPassInfo.dependencyCount = 1;
810 renderPassInfo.pDependencies = &dependency;
811
812 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
813 throw runtime_error("failed to create render pass!");
814 }
815
816 // We do not create a pipeline by default as this is also used by examples' main.cpp,
817 // but secondary viewport in multi-viewport mode may want to create one with:
818 //ImGui_ImplVulkan_CreatePipeline(device, g_Allocator, VK_NULL_HANDLE, g_MainWindowData.RenderPass, VK_SAMPLE_COUNT_1_BIT, &g_MainWindowData.Pipeline);
819}
820
821VkFormat VulkanGame::findDepthFormat() {
822 return VulkanUtils::findSupportedFormat(
823 physicalDevice,
824 { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
825 VK_IMAGE_TILING_OPTIMAL,
826 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
827 );
828}
829
830void VulkanGame::createResourceCommandPool() {
831 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
832
833 VkCommandPoolCreateInfo poolInfo = {};
834 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
835 poolInfo.queueFamilyIndex = indices.graphicsFamily.value();
836 poolInfo.flags = 0;
837
838 if (vkCreateCommandPool(device, &poolInfo, nullptr, &resourceCommandPool) != VK_SUCCESS) {
839 throw runtime_error("failed to create resource command pool!");
840 }
841}
842
843void VulkanGame::createCommandPools() {
844 commandPools.resize(swapChainImageCount);
845
846 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
847
848 for (size_t i = 0; i < swapChainImageCount; i++) {
849 VkCommandPoolCreateInfo poolInfo = {};
850 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
851 poolInfo.queueFamilyIndex = indices.graphicsFamily.value();
852 poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
853 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPools[i]) != VK_SUCCESS) {
854 throw runtime_error("failed to create graphics command pool!");
855 }
856 }
857}
858
859void VulkanGame::createFramebuffers() {
860 swapChainFramebuffers.resize(swapChainImageCount);
861
862 VkFramebufferCreateInfo framebufferInfo = {};
863 framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
864 framebufferInfo.renderPass = renderPass;
865 framebufferInfo.width = swapChainExtent.width;
866 framebufferInfo.height = swapChainExtent.height;
867 framebufferInfo.layers = 1;
868
869 for (size_t i = 0; i < swapChainImageCount; i++) {
870 array<VkImageView, 2> attachments = {
871 swapChainImageViews[i],
872 depthImage.imageView
873 };
874
875 framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
876 framebufferInfo.pAttachments = attachments.data();
877
878 if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
879 throw runtime_error("failed to create framebuffer!");
880 }
881 }
882}
883
884void VulkanGame::createCommandBuffers() {
885 commandBuffers.resize(swapChainImageCount);
886
887 for (size_t i = 0; i < swapChainImageCount; i++) {
888 VkCommandBufferAllocateInfo allocInfo = {};
889 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
890 allocInfo.commandPool = commandPools[i];
891 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
892 allocInfo.commandBufferCount = 1;
893
894 if (vkAllocateCommandBuffers(device, &allocInfo, &commandBuffers[i]) != VK_SUCCESS) {
895 throw runtime_error("failed to allocate command buffers!");
896 }
897 }
898}
899
900void VulkanGame::createSyncObjects() {
901 imageAcquiredSemaphores.resize(swapChainImageCount);
902 renderCompleteSemaphores.resize(swapChainImageCount);
903 inFlightFences.resize(swapChainImageCount);
904
905 VkSemaphoreCreateInfo semaphoreInfo = {};
906 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
907
908 VkFenceCreateInfo fenceInfo = {};
909 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
910 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
911
912 for (size_t i = 0; i < swapChainImageCount; i++) {
913 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAcquiredSemaphores[i]) != VK_SUCCESS) {
914 throw runtime_error("failed to create image acquired sempahore for a frame!");
915 }
916
917 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderCompleteSemaphores[i]) != VK_SUCCESS) {
918 throw runtime_error("failed to create render complete sempahore for a frame!");
919 }
920
921 if (vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) {
922 throw runtime_error("failed to create fence for a frame!");
923 }
924 }
925}
926
927void VulkanGame::recreateSwapChain() {
928 if (vkDeviceWaitIdle(device) != VK_SUCCESS) {
929 throw runtime_error("failed to wait for device!");
930 }
931
932 cleanupSwapChain();
933
934 createSwapChain();
935 createImageViews();
936 createRenderPass();
937
938 createCommandPools();
939
940 // The depth buffer does need to be recreated with the swap chain since its dimensions depend on the window size
941 // and resizing the window is a common reason to recreate the swapchain
942 VulkanUtils::createDepthImage(device, physicalDevice, resourceCommandPool, findDepthFormat(), swapChainExtent,
943 depthImage, graphicsQueue);
944
945 createFramebuffers();
946
947 // TODO: Update pipelines here
948
949 createCommandBuffers();
950
951 createSyncObjects();
952}
953
954void VulkanGame::cleanupSwapChain() {
955 VulkanUtils::destroyVulkanImage(device, depthImage);
956
957 for (VkFramebuffer framebuffer : swapChainFramebuffers) {
958 vkDestroyFramebuffer(device, framebuffer, nullptr);
959 }
960
961 for (uint32_t i = 0; i < swapChainImageCount; i++) {
962 vkFreeCommandBuffers(device, commandPools[i], 1, &commandBuffers[i]);
963 vkDestroyCommandPool(device, commandPools[i], nullptr);
964 }
965
966 for (uint32_t i = 0; i < swapChainImageCount; i++) {
967 vkDestroySemaphore(device, imageAcquiredSemaphores[i], nullptr);
968 vkDestroySemaphore(device, renderCompleteSemaphores[i], nullptr);
969 vkDestroyFence(device, inFlightFences[i], nullptr);
970 }
971
972 vkDestroyRenderPass(device, renderPass, nullptr);
973
974 for (VkImageView imageView : swapChainImageViews) {
975 vkDestroyImageView(device, imageView, nullptr);
976 }
977
978 vkDestroySwapchainKHR(device, swapChain, nullptr);
979}
980
981/********************************************** END OF NEW CODE **********************************************/
Note: See TracBrowser for help on using the repository browser.