source: opengl-game/vulkan-game.cpp@ 8e02b6b

feature/imgui-sdl points-test
Last change on this file since 8e02b6b was 8e02b6b, checked in by Dmitry Portnoy <dmitry.portnoy@…>, 5 years ago

To move to a more generic way of updating the scene, rename updateUniformBuffers() to updateScene() in VulkanGame and move the code to copy the data into a new copyDataToMemory() function in VulkanUtils.

  • Property mode set to 100644
File size: 38.9 KB
Line 
1#include "vulkan-game.hpp"
2
3#define GLM_FORCE_RADIANS
4#define GLM_FORCE_DEPTH_ZERO_TO_ONE
5
6#include <array>
7#include <chrono>
8#include <iostream>
9#include <set>
10
11#include "consts.hpp"
12#include "logger.hpp"
13
14#include "utils.hpp"
15
16using namespace std;
17
18VulkanGame::VulkanGame(int maxFramesInFlight) : MAX_FRAMES_IN_FLIGHT(maxFramesInFlight) {
19 gui = nullptr;
20 window = nullptr;
21 font = nullptr;
22 fontSDLTexture = nullptr;
23 imageSDLTexture = nullptr;
24
25 currentFrame = 0;
26 framebufferResized = false;
27
28 modelMvpMats = {};
29}
30
31VulkanGame::~VulkanGame() {
32}
33
34void VulkanGame::run(int width, int height, unsigned char guiFlags) {
35 cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
36
37 cout << "Vulkan Game" << endl;
38
39 // This gets the runtime version, use SDL_VERSION() for the comppile-time version
40 // TODO: Create a game-gui function to get the gui version and retrieve it that way
41 SDL_GetVersion(&sdlVersion);
42
43 // TODO: Refactor the logger api to be more flexible,
44 // esp. since gl_log() and gl_log_err() have issues printing anything besides stirngs
45 restart_gl_log();
46 gl_log("starting SDL\n%s.%s.%s",
47 to_string(sdlVersion.major).c_str(),
48 to_string(sdlVersion.minor).c_str(),
49 to_string(sdlVersion.patch).c_str());
50
51 open_log();
52 get_log() << "starting SDL" << endl;
53 get_log() <<
54 (int)sdlVersion.major << "." <<
55 (int)sdlVersion.minor << "." <<
56 (int)sdlVersion.patch << endl;
57
58 if (initWindow(width, height, guiFlags) == RTWO_ERROR) {
59 return;
60 }
61
62 initVulkan();
63 initMatrices();
64 mainLoop();
65 cleanup();
66
67 close_log();
68}
69
70// TODO: Make some more init functions, or call this initUI if the
71// amount of things initialized here keeps growing
72bool VulkanGame::initWindow(int width, int height, unsigned char guiFlags) {
73 // TODO: Put all fonts, textures, and images in the assets folder
74 gui = new GameGui_SDL();
75
76 if (gui->init() == RTWO_ERROR) {
77 // TODO: Also print these sorts of errors to the log
78 cout << "UI library could not be initialized!" << endl;
79 cout << gui->getError() << endl;
80 return RTWO_ERROR;
81 }
82
83 window = (SDL_Window*) gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
84 if (window == nullptr) {
85 cout << "Window could not be created!" << endl;
86 cout << gui->getError() << endl;
87 return RTWO_ERROR;
88 }
89
90 cout << "Target window size: (" << width << ", " << height << ")" << endl;
91 cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
92
93 renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
94 if (renderer == nullptr) {
95 cout << "Renderer could not be created!" << endl;
96 cout << gui->getError() << endl;
97 return RTWO_ERROR;
98 }
99
100 SDL_VERSION(&sdlVersion);
101
102 cout << "SDL " << sdlVersion.major << "." << sdlVersion.minor << "." << sdlVersion.patch << endl;
103
104 font = TTF_OpenFont("assets/fonts/lazy.ttf", 28);
105 if (font == nullptr) {
106 cout << "Failed to load lazy font! SDL_ttf Error: " << TTF_GetError() << endl;
107 return RTWO_ERROR;
108 }
109
110 SDL_Surface* fontSDLSurface = TTF_RenderText_Solid(font, "Great success!", { 255, 255, 255 });
111 if (fontSDLSurface == nullptr) {
112 cout << "Unable to render text surface! SDL_ttf Error: " << TTF_GetError() << endl;
113 return RTWO_ERROR;
114 }
115
116 fontSDLTexture = SDL_CreateTextureFromSurface(renderer, fontSDLSurface);
117 if (fontSDLTexture == nullptr) {
118 cout << "Unable to create texture from rendered text! SDL Error: " << SDL_GetError() << endl;
119 SDL_FreeSurface(fontSDLSurface);
120 return RTWO_ERROR;
121 }
122
123 SDL_FreeSurface(fontSDLSurface);
124
125 // TODO: Load a PNG instead
126 SDL_Surface* imageSDLSurface = SDL_LoadBMP("assets/images/spaceship.bmp");
127 if (imageSDLSurface == nullptr) {
128 cout << "Unable to load image " << "spaceship.bmp" << "! SDL Error: " << SDL_GetError() << endl;
129 return RTWO_ERROR;
130 }
131
132 imageSDLTexture = SDL_CreateTextureFromSurface(renderer, imageSDLSurface);
133 if (imageSDLTexture == nullptr) {
134 cout << "Unable to create texture from BMP surface! SDL Error: " << SDL_GetError() << endl;
135 SDL_FreeSurface(imageSDLSurface);
136 return RTWO_ERROR;
137 }
138
139 SDL_FreeSurface(imageSDLSurface);
140
141 // In SDL 2.0.10 (currently, the latest), SDL_TEXTUREACCESS_TARGET is required to get a transparent overlay working
142 // However, the latest SDL version available through homebrew on Mac is 2.0.9, which requires SDL_TEXTUREACCESS_STREAMING
143 // I tried building sdl 2.0.10 (and sdl_image and sdl_ttf) from source on Mac, but had some issues, so this is easier
144 // until the homebrew recipe is updated
145 if (sdlVersion.major == 2 && sdlVersion.minor == 0 && sdlVersion.patch == 9) {
146 uiOverlay = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING,
147 gui->getWindowWidth(), gui->getWindowHeight());
148 } else {
149 uiOverlay = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET,
150 gui->getWindowWidth(), gui->getWindowHeight());
151 }
152
153 if (uiOverlay == nullptr) {
154 cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << endl;
155 return RTWO_ERROR;
156 }
157 if (SDL_SetTextureBlendMode(uiOverlay, SDL_BLENDMODE_BLEND) != 0) {
158 cout << "Unable to set texture blend mode! SDL Error: " << SDL_GetError() << endl;
159 return RTWO_ERROR;
160 }
161
162 SDL_SetRenderTarget(renderer, uiOverlay);
163
164 return RTWO_SUCCESS;
165}
166
167void VulkanGame::initVulkan() {
168 const vector<const char*> validationLayers = {
169 "VK_LAYER_KHRONOS_validation"
170 };
171 const vector<const char*> deviceExtensions = {
172 VK_KHR_SWAPCHAIN_EXTENSION_NAME
173 };
174
175 createVulkanInstance(validationLayers);
176 setupDebugMessenger();
177 createVulkanSurface();
178 pickPhysicalDevice(deviceExtensions);
179 createLogicalDevice(validationLayers, deviceExtensions);
180 createSwapChain();
181 createImageViews();
182 createRenderPass();
183 createCommandPool();
184
185 createImageResources();
186
187 createFramebuffers();
188 createUniformBuffers();
189
190 modelPipeline = GraphicsPipeline_Vulkan<ModelVertex>(physicalDevice, device, renderPass,
191 { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, 16, 24);
192
193 modelPipeline.addObject({
194 {{-0.5f, -0.5f, -2.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
195 {{ 0.5f, -0.5f, -2.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
196 {{ 0.5f, 0.5f, -2.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
197 {{-0.5f, 0.5f, -2.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
198 }, {
199 0, 1, 2, 2, 3, 0
200 }, commandPool, graphicsQueue);
201
202 modelPipeline.addObject({
203 {{-0.5f, -0.5f, -1.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
204 {{ 0.5f, -0.5f, -1.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
205 {{ 0.5f, 0.5f, -1.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
206 {{-0.5f, 0.5f, -1.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
207 }, {
208 0, 1, 2, 2, 3, 0
209 }, commandPool, graphicsQueue);
210
211 modelPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&ModelVertex::pos));
212 modelPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&ModelVertex::color));
213 modelPipeline.addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&ModelVertex::texCoord));
214
215 modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
216 VK_SHADER_STAGE_VERTEX_BIT, &uniformBufferInfoList);
217 modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
218 VK_SHADER_STAGE_FRAGMENT_BIT, &floorTextureImageDescriptor);
219
220 modelPipeline.createDescriptorSetLayout();
221 modelPipeline.createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
222 modelPipeline.createDescriptorPool(swapChainImages);
223 modelPipeline.createDescriptorSets(swapChainImages);
224
225 overlayPipeline = GraphicsPipeline_Vulkan<OverlayVertex>(physicalDevice, device, renderPass,
226 { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, 4, 6);
227
228 overlayPipeline.addObject({
229 {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}},
230 {{ 1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
231 {{ 1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}},
232 {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}}
233 }, {
234 0, 1, 2, 2, 3, 0
235 }, commandPool, graphicsQueue);
236
237 overlayPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&OverlayVertex::pos));
238 overlayPipeline.addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&OverlayVertex::texCoord));
239
240 overlayPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
241 VK_SHADER_STAGE_FRAGMENT_BIT, &sdlOverlayImageDescriptor);
242
243 overlayPipeline.createDescriptorSetLayout();
244 overlayPipeline.createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
245 overlayPipeline.createDescriptorPool(swapChainImages);
246 overlayPipeline.createDescriptorSets(swapChainImages);
247
248 cout << "Created all the graphics pipelines" << endl;
249
250 createCommandBuffers();
251
252 createSyncObjects();
253}
254
255// TODO: Maybe changes the name to initScene() or something similar
256void VulkanGame::initMatrices() {
257 cam_pos = vec3(0.0f, 0.0f, 2.0f);
258
259 float cam_yaw = 0.0f;
260 float cam_pitch = -50.0f;
261
262 mat4 yaw_mat = rotate(mat4(1.0f), radians(-cam_yaw), vec3(0.0f, 1.0f, 0.0f));
263 mat4 pitch_mat = rotate(mat4(1.0f), radians(-cam_pitch), vec3(1.0f, 0.0f, 0.0f));
264
265 mat4 R = pitch_mat * yaw_mat;
266 mat4 T = translate(mat4(1.0f), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z));
267
268 modelMvpMats.view = R * T;
269
270 modelMvpMats.proj = perspective(radians(FOV_ANGLE), (float)swapChainExtent.width / (float)swapChainExtent.height, NEAR_CLIP, FAR_CLIP);
271 modelMvpMats.proj[1][1] *= -1; // flip the y-axis so that +y is up
272}
273
274void VulkanGame::mainLoop() {
275 UIEvent e;
276 bool quit = false;
277
278 while (!quit) {
279 gui->processEvents();
280
281 while (gui->pollEvent(&e)) {
282 switch(e.type) {
283 case UI_EVENT_QUIT:
284 cout << "Quit event detected" << endl;
285 quit = true;
286 break;
287 case UI_EVENT_WINDOW:
288 cout << "Window event detected" << endl;
289 // Currently unused
290 break;
291 case UI_EVENT_WINDOWRESIZE:
292 cout << "Window resize event detected" << endl;
293 framebufferResized = true;
294 break;
295 case UI_EVENT_KEYDOWN:
296 if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
297 quit = true;
298 } else if (e.key.keycode == SDL_SCANCODE_SPACE) {
299 cout << "Adding a plane" << endl;
300 float zOffset = -2.0f + (0.5f * modelPipeline.getObjects().size());
301
302 vkDeviceWaitIdle(device);
303 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
304
305 modelPipeline.addObject({
306 {{-0.5f, -0.5f, zOffset}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
307 {{ 0.5f, -0.5f, zOffset}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
308 {{ 0.5f, 0.5f, zOffset}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
309 {{-0.5f, 0.5f, zOffset}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
310 }, {
311 0, 1, 2, 2, 3, 0
312 }, commandPool, graphicsQueue);
313
314 createCommandBuffers();
315 } else {
316 cout << "Key event detected" << endl;
317 }
318 break;
319 case UI_EVENT_KEYUP:
320 break;
321 case UI_EVENT_MOUSEBUTTONDOWN:
322 cout << "Mouse button down event detected" << endl;
323 break;
324 case UI_EVENT_MOUSEBUTTONUP:
325 cout << "Mouse button up event detected" << endl;
326 break;
327 case UI_EVENT_MOUSEMOTION:
328 break;
329 case UI_EVENT_UNKNOWN:
330 cout << "Unknown event type: 0x" << hex << e.unknown.eventType << dec << endl;
331 break;
332 default:
333 cout << "Unhandled UI event: " << e.type << endl;
334 }
335 }
336
337 renderUI();
338 renderScene();
339 }
340
341 vkDeviceWaitIdle(device);
342}
343
344void VulkanGame::updateScene(uint32_t currentImage) {
345 static auto startTime = chrono::high_resolution_clock::now();
346
347 auto currentTime = chrono::high_resolution_clock::now();
348 float time = chrono::duration<float, chrono::seconds::period>(currentTime - startTime).count();
349
350 modelMvpMats.model =
351 translate(mat4(1.0f), vec3(0.0f, -2.0f, -0.0f)) *
352 rotate(mat4(1.0f), time * radians(90.0f), vec3(0.0f, 0.0f, 1.0f));
353
354 VulkanUtils::copyDataToMemory(device, uniformBuffersMemory[currentImage], modelMvpMats);
355}
356
357void VulkanGame::renderUI() {
358 SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
359 SDL_RenderClear(renderer);
360
361 SDL_Rect rect = {280, 220, 100, 100};
362 SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
363 SDL_RenderFillRect(renderer, &rect);
364
365 rect = {10, 10, 0, 0};
366 SDL_QueryTexture(fontSDLTexture, nullptr, nullptr, &(rect.w), &(rect.h));
367 SDL_RenderCopy(renderer, fontSDLTexture, nullptr, &rect);
368
369 rect = {10, 80, 0, 0};
370 SDL_QueryTexture(imageSDLTexture, nullptr, nullptr, &(rect.w), &(rect.h));
371 SDL_RenderCopy(renderer, imageSDLTexture, nullptr, &rect);
372
373 SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0xFF, 0xFF);
374 SDL_RenderDrawLine(renderer, 50, 5, 150, 500);
375
376 VulkanUtils::populateVulkanImageFromSDLTexture(device, physicalDevice, commandPool, uiOverlay, renderer,
377 sdlOverlayImage, graphicsQueue);
378}
379
380void VulkanGame::renderScene() {
381 vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, numeric_limits<uint64_t>::max());
382
383 uint32_t imageIndex;
384
385 VkResult result = vkAcquireNextImageKHR(device, swapChain, numeric_limits<uint64_t>::max(),
386 imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
387
388 if (result == VK_ERROR_OUT_OF_DATE_KHR) {
389 recreateSwapChain();
390 return;
391 } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
392 throw runtime_error("failed to acquire swap chain image!");
393 }
394
395 // TODO: Figure out a more elegant way to only do updates and render the UI once per scene render
396 // Probably move some of the renderScene() code into a higher function that updates the UI, and renders
397 // the UI and scene
398 updateScene(imageIndex);
399
400 VkSubmitInfo submitInfo = {};
401 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
402
403 VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] };
404 VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
405
406 submitInfo.waitSemaphoreCount = 1;
407 submitInfo.pWaitSemaphores = waitSemaphores;
408 submitInfo.pWaitDstStageMask = waitStages;
409 submitInfo.commandBufferCount = 1;
410 submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
411
412 VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] };
413
414 submitInfo.signalSemaphoreCount = 1;
415 submitInfo.pSignalSemaphores = signalSemaphores;
416
417 vkResetFences(device, 1, &inFlightFences[currentFrame]);
418
419 if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS) {
420 throw runtime_error("failed to submit draw command buffer!");
421 }
422
423 VkPresentInfoKHR presentInfo = {};
424 presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
425 presentInfo.waitSemaphoreCount = 1;
426 presentInfo.pWaitSemaphores = signalSemaphores;
427
428 VkSwapchainKHR swapChains[] = { swapChain };
429 presentInfo.swapchainCount = 1;
430 presentInfo.pSwapchains = swapChains;
431 presentInfo.pImageIndices = &imageIndex;
432 presentInfo.pResults = nullptr;
433
434 result = vkQueuePresentKHR(presentQueue, &presentInfo);
435
436 if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
437 framebufferResized = false;
438 recreateSwapChain();
439 } else if (result != VK_SUCCESS) {
440 throw runtime_error("failed to present swap chain image!");
441 }
442
443 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
444 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
445}
446
447void VulkanGame::cleanup() {
448 cleanupSwapChain();
449
450 VulkanUtils::destroyVulkanImage(device, floorTextureImage);
451 VulkanUtils::destroyVulkanImage(device, sdlOverlayImage);
452
453 vkDestroySampler(device, textureSampler, nullptr);
454
455 modelPipeline.cleanupBuffers();
456 overlayPipeline.cleanupBuffers();
457
458 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
459 vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
460 vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
461 vkDestroyFence(device, inFlightFences[i], nullptr);
462 }
463
464 vkDestroyCommandPool(device, commandPool, nullptr);
465 vkDestroyDevice(device, nullptr);
466 vkDestroySurfaceKHR(instance, surface, nullptr);
467
468 if (ENABLE_VALIDATION_LAYERS) {
469 VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
470 }
471
472 vkDestroyInstance(instance, nullptr);
473
474 // TODO: Check if any of these functions accept null parameters
475 // If they do, I don't need to check for that
476
477 if (uiOverlay != nullptr) {
478 SDL_DestroyTexture(uiOverlay);
479 uiOverlay = nullptr;
480 }
481
482 if (fontSDLTexture != nullptr) {
483 SDL_DestroyTexture(fontSDLTexture);
484 fontSDLTexture = nullptr;
485 }
486
487 if (imageSDLTexture != nullptr) {
488 SDL_DestroyTexture(imageSDLTexture);
489 imageSDLTexture = nullptr;
490 }
491
492 TTF_CloseFont(font);
493 font = nullptr;
494
495 SDL_DestroyRenderer(renderer);
496 renderer = nullptr;
497
498 gui->destroyWindow();
499 gui->shutdown();
500 delete gui;
501}
502
503void VulkanGame::createVulkanInstance(const vector<const char*> &validationLayers) {
504 if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
505 throw runtime_error("validation layers requested, but not available!");
506 }
507
508 VkApplicationInfo appInfo = {};
509 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
510 appInfo.pApplicationName = "Vulkan Game";
511 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
512 appInfo.pEngineName = "No Engine";
513 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
514 appInfo.apiVersion = VK_API_VERSION_1_0;
515
516 VkInstanceCreateInfo createInfo = {};
517 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
518 createInfo.pApplicationInfo = &appInfo;
519
520 vector<const char*> extensions = gui->getRequiredExtensions();
521 if (ENABLE_VALIDATION_LAYERS) {
522 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
523 }
524
525 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
526 createInfo.ppEnabledExtensionNames = extensions.data();
527
528 cout << endl << "Extensions:" << endl;
529 for (const char* extensionName : extensions) {
530 cout << extensionName << endl;
531 }
532 cout << endl;
533
534 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
535 if (ENABLE_VALIDATION_LAYERS) {
536 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
537 createInfo.ppEnabledLayerNames = validationLayers.data();
538
539 populateDebugMessengerCreateInfo(debugCreateInfo);
540 createInfo.pNext = &debugCreateInfo;
541 } else {
542 createInfo.enabledLayerCount = 0;
543
544 createInfo.pNext = nullptr;
545 }
546
547 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
548 throw runtime_error("failed to create instance!");
549 }
550}
551
552void VulkanGame::setupDebugMessenger() {
553 if (!ENABLE_VALIDATION_LAYERS) return;
554
555 VkDebugUtilsMessengerCreateInfoEXT createInfo;
556 populateDebugMessengerCreateInfo(createInfo);
557
558 if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
559 throw runtime_error("failed to set up debug messenger!");
560 }
561}
562
563void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
564 createInfo = {};
565 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
566 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;
567 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;
568 createInfo.pfnUserCallback = debugCallback;
569}
570
571VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
572 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
573 VkDebugUtilsMessageTypeFlagsEXT messageType,
574 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
575 void* pUserData) {
576 cerr << "validation layer: " << pCallbackData->pMessage << endl;
577
578 return VK_FALSE;
579}
580
581void VulkanGame::createVulkanSurface() {
582 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
583 throw runtime_error("failed to create window surface!");
584 }
585}
586
587void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
588 uint32_t deviceCount = 0;
589 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
590
591 if (deviceCount == 0) {
592 throw runtime_error("failed to find GPUs with Vulkan support!");
593 }
594
595 vector<VkPhysicalDevice> devices(deviceCount);
596 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
597
598 cout << endl << "Graphics cards:" << endl;
599 for (const VkPhysicalDevice& device : devices) {
600 if (isDeviceSuitable(device, deviceExtensions)) {
601 physicalDevice = device;
602 break;
603 }
604 }
605 cout << endl;
606
607 if (physicalDevice == VK_NULL_HANDLE) {
608 throw runtime_error("failed to find a suitable GPU!");
609 }
610}
611
612bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice,
613 const vector<const char*>& deviceExtensions) {
614 VkPhysicalDeviceProperties deviceProperties;
615 vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
616
617 cout << "Device: " << deviceProperties.deviceName << endl;
618
619 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
620 bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
621 bool swapChainAdequate = false;
622
623 if (extensionsSupported) {
624 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
625 swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
626 }
627
628 VkPhysicalDeviceFeatures supportedFeatures;
629 vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
630
631 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
632}
633
634void VulkanGame::createLogicalDevice(
635 const vector<const char*> validationLayers,
636 const vector<const char*>& deviceExtensions) {
637 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
638
639 vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
640 set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
641
642 float queuePriority = 1.0f;
643 for (uint32_t queueFamily : uniqueQueueFamilies) {
644 VkDeviceQueueCreateInfo queueCreateInfo = {};
645 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
646 queueCreateInfo.queueFamilyIndex = queueFamily;
647 queueCreateInfo.queueCount = 1;
648 queueCreateInfo.pQueuePriorities = &queuePriority;
649
650 queueCreateInfoList.push_back(queueCreateInfo);
651 }
652
653 VkPhysicalDeviceFeatures deviceFeatures = {};
654 deviceFeatures.samplerAnisotropy = VK_TRUE;
655
656 VkDeviceCreateInfo createInfo = {};
657 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
658 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
659 createInfo.pQueueCreateInfos = queueCreateInfoList.data();
660
661 createInfo.pEnabledFeatures = &deviceFeatures;
662
663 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
664 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
665
666 // These fields are ignored by up-to-date Vulkan implementations,
667 // but it's a good idea to set them for backwards compatibility
668 if (ENABLE_VALIDATION_LAYERS) {
669 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
670 createInfo.ppEnabledLayerNames = validationLayers.data();
671 } else {
672 createInfo.enabledLayerCount = 0;
673 }
674
675 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
676 throw runtime_error("failed to create logical device!");
677 }
678
679 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
680 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
681}
682
683void VulkanGame::createSwapChain() {
684 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
685
686 VkSurfaceFormatKHR surfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(swapChainSupport.formats);
687 VkPresentModeKHR presentMode = VulkanUtils::chooseSwapPresentMode(swapChainSupport.presentModes);
688 VkExtent2D extent = VulkanUtils::chooseSwapExtent(swapChainSupport.capabilities, gui->getWindowWidth(), gui->getWindowHeight());
689
690 uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
691 if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
692 imageCount = swapChainSupport.capabilities.maxImageCount;
693 }
694
695 VkSwapchainCreateInfoKHR createInfo = {};
696 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
697 createInfo.surface = surface;
698 createInfo.minImageCount = imageCount;
699 createInfo.imageFormat = surfaceFormat.format;
700 createInfo.imageColorSpace = surfaceFormat.colorSpace;
701 createInfo.imageExtent = extent;
702 createInfo.imageArrayLayers = 1;
703 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
704
705 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
706 uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
707
708 if (indices.graphicsFamily != indices.presentFamily) {
709 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
710 createInfo.queueFamilyIndexCount = 2;
711 createInfo.pQueueFamilyIndices = queueFamilyIndices;
712 } else {
713 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
714 createInfo.queueFamilyIndexCount = 0;
715 createInfo.pQueueFamilyIndices = nullptr;
716 }
717
718 createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
719 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
720 createInfo.presentMode = presentMode;
721 createInfo.clipped = VK_TRUE;
722 createInfo.oldSwapchain = VK_NULL_HANDLE;
723
724 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
725 throw runtime_error("failed to create swap chain!");
726 }
727
728 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
729 swapChainImages.resize(imageCount);
730 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
731
732 swapChainImageFormat = surfaceFormat.format;
733 swapChainExtent = extent;
734}
735
736void VulkanGame::createImageViews() {
737 swapChainImageViews.resize(swapChainImages.size());
738
739 for (size_t i = 0; i < swapChainImages.size(); i++) {
740 swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainImageFormat,
741 VK_IMAGE_ASPECT_COLOR_BIT);
742 }
743}
744
745void VulkanGame::createRenderPass() {
746 VkAttachmentDescription colorAttachment = {};
747 colorAttachment.format = swapChainImageFormat;
748 colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
749 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
750 colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
751 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
752 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
753 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
754 colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
755
756 VkAttachmentReference colorAttachmentRef = {};
757 colorAttachmentRef.attachment = 0;
758 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
759
760 VkAttachmentDescription depthAttachment = {};
761 depthAttachment.format = findDepthFormat();
762 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
763 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
764 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
765 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
766 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
767 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
768 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
769
770 VkAttachmentReference depthAttachmentRef = {};
771 depthAttachmentRef.attachment = 1;
772 depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
773
774 VkSubpassDescription subpass = {};
775 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
776 subpass.colorAttachmentCount = 1;
777 subpass.pColorAttachments = &colorAttachmentRef;
778 subpass.pDepthStencilAttachment = &depthAttachmentRef;
779
780 VkSubpassDependency dependency = {};
781 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
782 dependency.dstSubpass = 0;
783 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
784 dependency.srcAccessMask = 0;
785 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
786 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
787
788 array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
789 VkRenderPassCreateInfo renderPassInfo = {};
790 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
791 renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
792 renderPassInfo.pAttachments = attachments.data();
793 renderPassInfo.subpassCount = 1;
794 renderPassInfo.pSubpasses = &subpass;
795 renderPassInfo.dependencyCount = 1;
796 renderPassInfo.pDependencies = &dependency;
797
798 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
799 throw runtime_error("failed to create render pass!");
800 }
801}
802
803VkFormat VulkanGame::findDepthFormat() {
804 return VulkanUtils::findSupportedFormat(
805 physicalDevice,
806 { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
807 VK_IMAGE_TILING_OPTIMAL,
808 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
809 );
810}
811
812void VulkanGame::createCommandPool() {
813 QueueFamilyIndices queueFamilyIndices = VulkanUtils::findQueueFamilies(physicalDevice, surface);;
814
815 VkCommandPoolCreateInfo poolInfo = {};
816 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
817 poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
818 poolInfo.flags = 0;
819
820 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
821 throw runtime_error("failed to create graphics command pool!");
822 }
823}
824
825void VulkanGame::createImageResources() {
826 VulkanUtils::createDepthImage(device, physicalDevice, commandPool, findDepthFormat(), swapChainExtent,
827 depthImage, graphicsQueue);
828
829 createTextureSampler();
830
831 VulkanUtils::createVulkanImageFromFile(device, physicalDevice, commandPool, "textures/texture.jpg",
832 floorTextureImage, graphicsQueue);
833
834 floorTextureImageDescriptor = {};
835 floorTextureImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
836 floorTextureImageDescriptor.imageView = floorTextureImage.imageView;
837 floorTextureImageDescriptor.sampler = textureSampler;
838
839 VulkanUtils::createVulkanImageFromSDLTexture(device, physicalDevice, uiOverlay, sdlOverlayImage);
840
841 sdlOverlayImageDescriptor = {};
842 sdlOverlayImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
843 sdlOverlayImageDescriptor.imageView = sdlOverlayImage.imageView;
844 sdlOverlayImageDescriptor.sampler = textureSampler;
845}
846
847void VulkanGame::createTextureSampler() {
848 VkSamplerCreateInfo samplerInfo = {};
849 samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
850 samplerInfo.magFilter = VK_FILTER_LINEAR;
851 samplerInfo.minFilter = VK_FILTER_LINEAR;
852
853 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
854 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
855 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
856
857 samplerInfo.anisotropyEnable = VK_TRUE;
858 samplerInfo.maxAnisotropy = 16;
859 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
860 samplerInfo.unnormalizedCoordinates = VK_FALSE;
861 samplerInfo.compareEnable = VK_FALSE;
862 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
863 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
864 samplerInfo.mipLodBias = 0.0f;
865 samplerInfo.minLod = 0.0f;
866 samplerInfo.maxLod = 0.0f;
867
868 if (vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) {
869 throw runtime_error("failed to create texture sampler!");
870 }
871}
872
873void VulkanGame::createFramebuffers() {
874 swapChainFramebuffers.resize(swapChainImageViews.size());
875
876 for (size_t i = 0; i < swapChainImageViews.size(); i++) {
877 array<VkImageView, 2> attachments = {
878 swapChainImageViews[i],
879 depthImage.imageView
880 };
881
882 VkFramebufferCreateInfo framebufferInfo = {};
883 framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
884 framebufferInfo.renderPass = renderPass;
885 framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
886 framebufferInfo.pAttachments = attachments.data();
887 framebufferInfo.width = swapChainExtent.width;
888 framebufferInfo.height = swapChainExtent.height;
889 framebufferInfo.layers = 1;
890
891 if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
892 throw runtime_error("failed to create framebuffer!");
893 }
894 }
895}
896
897void VulkanGame::createUniformBuffers() {
898 VkDeviceSize bufferSize = sizeof(UBO_MvpMat);
899
900 uniformBuffers.resize(swapChainImages.size());
901 uniformBuffersMemory.resize(swapChainImages.size());
902 uniformBufferInfoList.resize(swapChainImages.size());
903
904 for (size_t i = 0; i < swapChainImages.size(); i++) {
905 VulkanUtils::createBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
906 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
907 uniformBuffers[i], uniformBuffersMemory[i]);
908
909 uniformBufferInfoList[i].buffer = uniformBuffers[i];
910 uniformBufferInfoList[i].offset = 0;
911 uniformBufferInfoList[i].range = sizeof(UBO_MvpMat);
912 }
913}
914
915void VulkanGame::createCommandBuffers() {
916 commandBuffers.resize(swapChainImages.size());
917
918 VkCommandBufferAllocateInfo allocInfo = {};
919 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
920 allocInfo.commandPool = commandPool;
921 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
922 allocInfo.commandBufferCount = (uint32_t) commandBuffers.size();
923
924 if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) {
925 throw runtime_error("failed to allocate command buffers!");
926 }
927
928 for (size_t i = 0; i < commandBuffers.size(); i++) {
929 VkCommandBufferBeginInfo beginInfo = {};
930 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
931 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
932 beginInfo.pInheritanceInfo = nullptr;
933
934 if (vkBeginCommandBuffer(commandBuffers[i], &beginInfo) != VK_SUCCESS) {
935 throw runtime_error("failed to begin recording command buffer!");
936 }
937
938 VkRenderPassBeginInfo renderPassInfo = {};
939 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
940 renderPassInfo.renderPass = renderPass;
941 renderPassInfo.framebuffer = swapChainFramebuffers[i];
942 renderPassInfo.renderArea.offset = { 0, 0 };
943 renderPassInfo.renderArea.extent = swapChainExtent;
944
945 array<VkClearValue, 2> clearValues = {};
946 clearValues[0].color = {{ 0.0f, 0.0f, 0.0f, 1.0f }};
947 clearValues[1].depthStencil = { 1.0f, 0 };
948
949 renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
950 renderPassInfo.pClearValues = clearValues.data();
951
952 vkCmdBeginRenderPass(commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
953
954 modelPipeline.createRenderCommands(commandBuffers[i], i);
955 overlayPipeline.createRenderCommands(commandBuffers[i], i);
956
957 vkCmdEndRenderPass(commandBuffers[i]);
958
959 if (vkEndCommandBuffer(commandBuffers[i]) != VK_SUCCESS) {
960 throw runtime_error("failed to record command buffer!");
961 }
962 }
963}
964
965void VulkanGame::createSyncObjects() {
966 imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
967 renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
968 inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
969
970 VkSemaphoreCreateInfo semaphoreInfo = {};
971 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
972
973 VkFenceCreateInfo fenceInfo = {};
974 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
975 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
976
977 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
978 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
979 vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
980 vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) {
981 throw runtime_error("failed to create synchronization objects for a frame!");
982 }
983 }
984}
985
986// TODO: Fix the crash that happens when alt-tabbing
987void VulkanGame::recreateSwapChain() {
988 cout << "Recreating swap chain" << endl;
989 gui->refreshWindowSize();
990
991 while (gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0 ||
992 (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0) {
993 SDL_WaitEvent(nullptr);
994 gui->refreshWindowSize();
995 }
996
997 vkDeviceWaitIdle(device);
998
999 cleanupSwapChain();
1000
1001 createSwapChain();
1002 createImageViews();
1003 createRenderPass();
1004
1005 VulkanUtils::createDepthImage(device, physicalDevice, commandPool, findDepthFormat(), swapChainExtent,
1006 depthImage, graphicsQueue);
1007 createFramebuffers();
1008 createUniformBuffers();
1009
1010 modelPipeline.updateRenderPass(renderPass);
1011 modelPipeline.createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
1012 modelPipeline.createDescriptorPool(swapChainImages);
1013 modelPipeline.createDescriptorSets(swapChainImages);
1014
1015 overlayPipeline.updateRenderPass(renderPass);
1016 overlayPipeline.createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
1017 overlayPipeline.createDescriptorPool(swapChainImages);
1018 overlayPipeline.createDescriptorSets(swapChainImages);
1019
1020 createCommandBuffers();
1021}
1022
1023void VulkanGame::cleanupSwapChain() {
1024 VulkanUtils::destroyVulkanImage(device, depthImage);
1025
1026 for (VkFramebuffer framebuffer : swapChainFramebuffers) {
1027 vkDestroyFramebuffer(device, framebuffer, nullptr);
1028 }
1029
1030 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
1031
1032 modelPipeline.cleanup();
1033 overlayPipeline.cleanup();
1034
1035 vkDestroyRenderPass(device, renderPass, nullptr);
1036
1037 for (VkImageView imageView : swapChainImageViews) {
1038 vkDestroyImageView(device, imageView, nullptr);
1039 }
1040
1041 vkDestroySwapchainKHR(device, swapChain, nullptr);
1042
1043 for (size_t i = 0; i < uniformBuffers.size(); i++) {
1044 vkDestroyBuffer(device, uniformBuffers[i], nullptr);
1045 vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
1046 }
1047}
Note: See TracBrowser for help on using the repository browser.