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