source: opengl-game/vulkan-game.cpp@ 15104a8

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

In vulkangame, nitialize the view and projection metrices to what they were in the original OpenGL game

  • Property mode set to 100644
File size: 38.7 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 ubo = {};
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 numPlanes = 2;
251
252 createCommandBuffers();
253
254 createSyncObjects();
255}
256
257void VulkanGame::initMatrices() {
258 cam_pos = vec3(0.0f, 0.0f, 2.0f);
259
260 float cam_yaw = 0.0f;
261 float cam_pitch = -50.0f;
262
263 mat4 yaw_mat = rotate(mat4(1.0f), radians(-cam_yaw), vec3(0.0f, 1.0f, 0.0f));
264 mat4 pitch_mat = rotate(mat4(1.0f), radians(-cam_pitch), vec3(1.0f, 0.0f, 0.0f));
265
266 mat4 R = pitch_mat * yaw_mat;
267 mat4 T = translate(mat4(1.0f), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z));
268
269 ubo.view = R * T;
270
271 ubo.proj = perspective(radians(FOV_ANGLE), (float)swapChainExtent.width / (float)swapChainExtent.height, NEAR_CLIP, FAR_CLIP);
272 ubo.proj[1][1] *= -1; // flip the y-axis so that +y is up
273}
274
275void VulkanGame::mainLoop() {
276 UIEvent e;
277 bool quit = false;
278
279 while (!quit) {
280 gui->processEvents();
281
282 while (gui->pollEvent(&e)) {
283 switch(e.type) {
284 case UI_EVENT_QUIT:
285 cout << "Quit event detected" << endl;
286 quit = true;
287 break;
288 case UI_EVENT_WINDOW:
289 cout << "Window event detected" << endl;
290 // Currently unused
291 break;
292 case UI_EVENT_WINDOWRESIZE:
293 cout << "Window resize event detected" << endl;
294 framebufferResized = true;
295 break;
296 case UI_EVENT_KEYDOWN:
297 if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
298 quit = true;
299 } else if (e.key.keycode == SDL_SCANCODE_SPACE) {
300 cout << "Adding a plane" << endl;
301 float zOffset = -2.0f + (0.5f * numPlanes);
302
303 vkDeviceWaitIdle(device);
304 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
305
306 modelPipeline.addObject({
307 {{-0.5f, -0.5f, zOffset}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
308 {{ 0.5f, -0.5f, zOffset}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
309 {{ 0.5f, 0.5f, zOffset}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
310 {{-0.5f, 0.5f, zOffset}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
311 }, {
312 0, 1, 2, 2, 3, 0
313 }, commandPool, graphicsQueue);
314
315 createCommandBuffers();
316
317 numPlanes++;
318 } else {
319 cout << "Key event detected" << endl;
320 }
321 break;
322 case UI_EVENT_KEYUP:
323 break;
324 case UI_EVENT_MOUSEBUTTONDOWN:
325 cout << "Mouse button down event detected" << endl;
326 break;
327 case UI_EVENT_MOUSEBUTTONUP:
328 cout << "Mouse button up event detected" << endl;
329 break;
330 case UI_EVENT_MOUSEMOTION:
331 break;
332 case UI_EVENT_UNKNOWN:
333 cout << "Unknown event type: 0x" << hex << e.unknown.eventType << dec << endl;
334 break;
335 default:
336 cout << "Unhandled UI event: " << e.type << endl;
337 }
338 }
339
340 renderUI();
341 renderScene();
342 }
343
344 vkDeviceWaitIdle(device);
345}
346
347void VulkanGame::renderUI() {
348 SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
349 SDL_RenderClear(renderer);
350
351 SDL_Rect rect = {280, 220, 100, 100};
352 SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
353 SDL_RenderFillRect(renderer, &rect);
354
355 rect = {10, 10, 0, 0};
356 SDL_QueryTexture(fontSDLTexture, nullptr, nullptr, &(rect.w), &(rect.h));
357 SDL_RenderCopy(renderer, fontSDLTexture, nullptr, &rect);
358
359 rect = {10, 80, 0, 0};
360 SDL_QueryTexture(imageSDLTexture, nullptr, nullptr, &(rect.w), &(rect.h));
361 SDL_RenderCopy(renderer, imageSDLTexture, nullptr, &rect);
362
363 SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0xFF, 0xFF);
364 SDL_RenderDrawLine(renderer, 50, 5, 150, 500);
365
366 VulkanUtils::populateVulkanImageFromSDLTexture(device, physicalDevice, commandPool, uiOverlay, renderer,
367 sdlOverlayImage, graphicsQueue);
368}
369
370void VulkanGame::renderScene() {
371 vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, numeric_limits<uint64_t>::max());
372
373 uint32_t imageIndex;
374
375 VkResult result = vkAcquireNextImageKHR(device, swapChain, numeric_limits<uint64_t>::max(),
376 imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
377
378 if (result == VK_ERROR_OUT_OF_DATE_KHR) {
379 recreateSwapChain();
380 return;
381 } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
382 throw runtime_error("failed to acquire swap chain image!");
383 }
384
385 updateUniformBuffer(imageIndex);
386
387 VkSubmitInfo submitInfo = {};
388 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
389
390 VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] };
391 VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
392
393 submitInfo.waitSemaphoreCount = 1;
394 submitInfo.pWaitSemaphores = waitSemaphores;
395 submitInfo.pWaitDstStageMask = waitStages;
396 submitInfo.commandBufferCount = 1;
397 submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
398
399 VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] };
400
401 submitInfo.signalSemaphoreCount = 1;
402 submitInfo.pSignalSemaphores = signalSemaphores;
403
404 vkResetFences(device, 1, &inFlightFences[currentFrame]);
405
406 if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS) {
407 throw runtime_error("failed to submit draw command buffer!");
408 }
409
410 VkPresentInfoKHR presentInfo = {};
411 presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
412 presentInfo.waitSemaphoreCount = 1;
413 presentInfo.pWaitSemaphores = signalSemaphores;
414
415 VkSwapchainKHR swapChains[] = { swapChain };
416 presentInfo.swapchainCount = 1;
417 presentInfo.pSwapchains = swapChains;
418 presentInfo.pImageIndices = &imageIndex;
419 presentInfo.pResults = nullptr;
420
421 result = vkQueuePresentKHR(presentQueue, &presentInfo);
422
423 if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
424 framebufferResized = false;
425 recreateSwapChain();
426 } else if (result != VK_SUCCESS) {
427 throw runtime_error("failed to present swap chain image!");
428 }
429
430 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
431 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
432}
433
434void VulkanGame::cleanup() {
435 cleanupSwapChain();
436
437 VulkanUtils::destroyVulkanImage(device, floorTextureImage);
438 VulkanUtils::destroyVulkanImage(device, sdlOverlayImage);
439
440 vkDestroySampler(device, textureSampler, nullptr);
441
442 modelPipeline.cleanupBuffers();
443 overlayPipeline.cleanupBuffers();
444
445 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
446 vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
447 vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
448 vkDestroyFence(device, inFlightFences[i], nullptr);
449 }
450
451 vkDestroyCommandPool(device, commandPool, nullptr);
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 // TODO: Check if any of these functions accept null parameters
462 // If they do, I don't need to check for that
463
464 if (uiOverlay != nullptr) {
465 SDL_DestroyTexture(uiOverlay);
466 uiOverlay = nullptr;
467 }
468
469 if (fontSDLTexture != nullptr) {
470 SDL_DestroyTexture(fontSDLTexture);
471 fontSDLTexture = nullptr;
472 }
473
474 if (imageSDLTexture != nullptr) {
475 SDL_DestroyTexture(imageSDLTexture);
476 imageSDLTexture = nullptr;
477 }
478
479 TTF_CloseFont(font);
480 font = nullptr;
481
482 SDL_DestroyRenderer(renderer);
483 renderer = nullptr;
484
485 gui->destroyWindow();
486 gui->shutdown();
487 delete gui;
488}
489
490void VulkanGame::createVulkanInstance(const vector<const char*> &validationLayers) {
491 if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
492 throw runtime_error("validation layers requested, but not available!");
493 }
494
495 VkApplicationInfo appInfo = {};
496 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
497 appInfo.pApplicationName = "Vulkan Game";
498 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
499 appInfo.pEngineName = "No Engine";
500 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
501 appInfo.apiVersion = VK_API_VERSION_1_0;
502
503 VkInstanceCreateInfo createInfo = {};
504 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
505 createInfo.pApplicationInfo = &appInfo;
506
507 vector<const char*> extensions = gui->getRequiredExtensions();
508 if (ENABLE_VALIDATION_LAYERS) {
509 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
510 }
511
512 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
513 createInfo.ppEnabledExtensionNames = extensions.data();
514
515 cout << endl << "Extensions:" << endl;
516 for (const char* extensionName : extensions) {
517 cout << extensionName << endl;
518 }
519 cout << endl;
520
521 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
522 if (ENABLE_VALIDATION_LAYERS) {
523 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
524 createInfo.ppEnabledLayerNames = validationLayers.data();
525
526 populateDebugMessengerCreateInfo(debugCreateInfo);
527 createInfo.pNext = &debugCreateInfo;
528 } else {
529 createInfo.enabledLayerCount = 0;
530
531 createInfo.pNext = nullptr;
532 }
533
534 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
535 throw runtime_error("failed to create instance!");
536 }
537}
538
539void VulkanGame::setupDebugMessenger() {
540 if (!ENABLE_VALIDATION_LAYERS) return;
541
542 VkDebugUtilsMessengerCreateInfoEXT createInfo;
543 populateDebugMessengerCreateInfo(createInfo);
544
545 if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
546 throw runtime_error("failed to set up debug messenger!");
547 }
548}
549
550void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
551 createInfo = {};
552 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
553 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;
554 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;
555 createInfo.pfnUserCallback = debugCallback;
556}
557
558VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
559 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
560 VkDebugUtilsMessageTypeFlagsEXT messageType,
561 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
562 void* pUserData) {
563 cerr << "validation layer: " << pCallbackData->pMessage << endl;
564
565 return VK_FALSE;
566}
567
568void VulkanGame::createVulkanSurface() {
569 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
570 throw runtime_error("failed to create window surface!");
571 }
572}
573
574void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
575 uint32_t deviceCount = 0;
576 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
577
578 if (deviceCount == 0) {
579 throw runtime_error("failed to find GPUs with Vulkan support!");
580 }
581
582 vector<VkPhysicalDevice> devices(deviceCount);
583 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
584
585 cout << endl << "Graphics cards:" << endl;
586 for (const VkPhysicalDevice& device : devices) {
587 if (isDeviceSuitable(device, deviceExtensions)) {
588 physicalDevice = device;
589 break;
590 }
591 }
592 cout << endl;
593
594 if (physicalDevice == VK_NULL_HANDLE) {
595 throw runtime_error("failed to find a suitable GPU!");
596 }
597}
598
599bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice,
600 const vector<const char*>& deviceExtensions) {
601 VkPhysicalDeviceProperties deviceProperties;
602 vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
603
604 cout << "Device: " << deviceProperties.deviceName << endl;
605
606 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
607 bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
608 bool swapChainAdequate = false;
609
610 if (extensionsSupported) {
611 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
612 swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
613 }
614
615 VkPhysicalDeviceFeatures supportedFeatures;
616 vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
617
618 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
619}
620
621void VulkanGame::createLogicalDevice(
622 const vector<const char*> validationLayers,
623 const vector<const char*>& deviceExtensions) {
624 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
625
626 vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
627 set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
628
629 float queuePriority = 1.0f;
630 for (uint32_t queueFamily : uniqueQueueFamilies) {
631 VkDeviceQueueCreateInfo queueCreateInfo = {};
632 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
633 queueCreateInfo.queueFamilyIndex = queueFamily;
634 queueCreateInfo.queueCount = 1;
635 queueCreateInfo.pQueuePriorities = &queuePriority;
636
637 queueCreateInfoList.push_back(queueCreateInfo);
638 }
639
640 VkPhysicalDeviceFeatures deviceFeatures = {};
641 deviceFeatures.samplerAnisotropy = VK_TRUE;
642
643 VkDeviceCreateInfo createInfo = {};
644 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
645 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
646 createInfo.pQueueCreateInfos = queueCreateInfoList.data();
647
648 createInfo.pEnabledFeatures = &deviceFeatures;
649
650 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
651 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
652
653 // These fields are ignored by up-to-date Vulkan implementations,
654 // but it's a good idea to set them for backwards compatibility
655 if (ENABLE_VALIDATION_LAYERS) {
656 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
657 createInfo.ppEnabledLayerNames = validationLayers.data();
658 } else {
659 createInfo.enabledLayerCount = 0;
660 }
661
662 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
663 throw runtime_error("failed to create logical device!");
664 }
665
666 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
667 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
668}
669
670void VulkanGame::createSwapChain() {
671 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
672
673 VkSurfaceFormatKHR surfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(swapChainSupport.formats);
674 VkPresentModeKHR presentMode = VulkanUtils::chooseSwapPresentMode(swapChainSupport.presentModes);
675 VkExtent2D extent = VulkanUtils::chooseSwapExtent(swapChainSupport.capabilities, gui->getWindowWidth(), gui->getWindowHeight());
676
677 uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
678 if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
679 imageCount = swapChainSupport.capabilities.maxImageCount;
680 }
681
682 VkSwapchainCreateInfoKHR createInfo = {};
683 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
684 createInfo.surface = surface;
685 createInfo.minImageCount = imageCount;
686 createInfo.imageFormat = surfaceFormat.format;
687 createInfo.imageColorSpace = surfaceFormat.colorSpace;
688 createInfo.imageExtent = extent;
689 createInfo.imageArrayLayers = 1;
690 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
691
692 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
693 uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
694
695 if (indices.graphicsFamily != indices.presentFamily) {
696 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
697 createInfo.queueFamilyIndexCount = 2;
698 createInfo.pQueueFamilyIndices = queueFamilyIndices;
699 } else {
700 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
701 createInfo.queueFamilyIndexCount = 0;
702 createInfo.pQueueFamilyIndices = nullptr;
703 }
704
705 createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
706 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
707 createInfo.presentMode = presentMode;
708 createInfo.clipped = VK_TRUE;
709 createInfo.oldSwapchain = VK_NULL_HANDLE;
710
711 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
712 throw runtime_error("failed to create swap chain!");
713 }
714
715 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
716 swapChainImages.resize(imageCount);
717 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
718
719 swapChainImageFormat = surfaceFormat.format;
720 swapChainExtent = extent;
721}
722
723void VulkanGame::createImageViews() {
724 swapChainImageViews.resize(swapChainImages.size());
725
726 for (size_t i = 0; i < swapChainImages.size(); i++) {
727 swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainImageFormat,
728 VK_IMAGE_ASPECT_COLOR_BIT);
729 }
730}
731
732void VulkanGame::createRenderPass() {
733 VkAttachmentDescription colorAttachment = {};
734 colorAttachment.format = swapChainImageFormat;
735 colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
736 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
737 colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
738 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
739 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
740 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
741 colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
742
743 VkAttachmentReference colorAttachmentRef = {};
744 colorAttachmentRef.attachment = 0;
745 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
746
747 VkAttachmentDescription depthAttachment = {};
748 depthAttachment.format = findDepthFormat();
749 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
750 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
751 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
752 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
753 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
754 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
755 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
756
757 VkAttachmentReference depthAttachmentRef = {};
758 depthAttachmentRef.attachment = 1;
759 depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
760
761 VkSubpassDescription subpass = {};
762 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
763 subpass.colorAttachmentCount = 1;
764 subpass.pColorAttachments = &colorAttachmentRef;
765 subpass.pDepthStencilAttachment = &depthAttachmentRef;
766
767 VkSubpassDependency dependency = {};
768 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
769 dependency.dstSubpass = 0;
770 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
771 dependency.srcAccessMask = 0;
772 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
773 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
774
775 array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
776 VkRenderPassCreateInfo renderPassInfo = {};
777 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
778 renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
779 renderPassInfo.pAttachments = attachments.data();
780 renderPassInfo.subpassCount = 1;
781 renderPassInfo.pSubpasses = &subpass;
782 renderPassInfo.dependencyCount = 1;
783 renderPassInfo.pDependencies = &dependency;
784
785 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
786 throw runtime_error("failed to create render pass!");
787 }
788}
789
790VkFormat VulkanGame::findDepthFormat() {
791 return VulkanUtils::findSupportedFormat(
792 physicalDevice,
793 { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
794 VK_IMAGE_TILING_OPTIMAL,
795 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
796 );
797}
798
799void VulkanGame::createCommandPool() {
800 QueueFamilyIndices queueFamilyIndices = VulkanUtils::findQueueFamilies(physicalDevice, surface);;
801
802 VkCommandPoolCreateInfo poolInfo = {};
803 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
804 poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
805 poolInfo.flags = 0;
806
807 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
808 throw runtime_error("failed to create graphics command pool!");
809 }
810}
811
812void VulkanGame::createImageResources() {
813 VulkanUtils::createDepthImage(device, physicalDevice, commandPool, findDepthFormat(), swapChainExtent,
814 depthImage, graphicsQueue);
815
816 createTextureSampler();
817
818 VulkanUtils::createVulkanImageFromFile(device, physicalDevice, commandPool, "textures/texture.jpg",
819 floorTextureImage, graphicsQueue);
820
821 floorTextureImageDescriptor = {};
822 floorTextureImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
823 floorTextureImageDescriptor.imageView = floorTextureImage.imageView;
824 floorTextureImageDescriptor.sampler = textureSampler;
825
826 VulkanUtils::createVulkanImageFromSDLTexture(device, physicalDevice, uiOverlay, sdlOverlayImage);
827
828 sdlOverlayImageDescriptor = {};
829 sdlOverlayImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
830 sdlOverlayImageDescriptor.imageView = sdlOverlayImage.imageView;
831 sdlOverlayImageDescriptor.sampler = textureSampler;
832}
833
834void VulkanGame::createTextureSampler() {
835 VkSamplerCreateInfo samplerInfo = {};
836 samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
837 samplerInfo.magFilter = VK_FILTER_LINEAR;
838 samplerInfo.minFilter = VK_FILTER_LINEAR;
839
840 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
841 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
842 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
843
844 samplerInfo.anisotropyEnable = VK_TRUE;
845 samplerInfo.maxAnisotropy = 16;
846 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
847 samplerInfo.unnormalizedCoordinates = VK_FALSE;
848 samplerInfo.compareEnable = VK_FALSE;
849 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
850 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
851 samplerInfo.mipLodBias = 0.0f;
852 samplerInfo.minLod = 0.0f;
853 samplerInfo.maxLod = 0.0f;
854
855 if (vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) {
856 throw runtime_error("failed to create texture sampler!");
857 }
858}
859
860void VulkanGame::createFramebuffers() {
861 swapChainFramebuffers.resize(swapChainImageViews.size());
862
863 for (size_t i = 0; i < swapChainImageViews.size(); i++) {
864 array<VkImageView, 2> attachments = {
865 swapChainImageViews[i],
866 depthImage.imageView
867 };
868
869 VkFramebufferCreateInfo framebufferInfo = {};
870 framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
871 framebufferInfo.renderPass = renderPass;
872 framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
873 framebufferInfo.pAttachments = attachments.data();
874 framebufferInfo.width = swapChainExtent.width;
875 framebufferInfo.height = swapChainExtent.height;
876 framebufferInfo.layers = 1;
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::createUniformBuffers() {
885 VkDeviceSize bufferSize = sizeof(UniformBufferObject);
886
887 uniformBuffers.resize(swapChainImages.size());
888 uniformBuffersMemory.resize(swapChainImages.size());
889 uniformBufferInfoList.resize(swapChainImages.size());
890
891 for (size_t i = 0; i < swapChainImages.size(); i++) {
892 VulkanUtils::createBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
893 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
894 uniformBuffers[i], uniformBuffersMemory[i]);
895
896 uniformBufferInfoList[i].buffer = uniformBuffers[i];
897 uniformBufferInfoList[i].offset = 0;
898 uniformBufferInfoList[i].range = sizeof(UniformBufferObject);
899 }
900}
901
902void VulkanGame::createCommandBuffers() {
903 commandBuffers.resize(swapChainImages.size());
904
905 VkCommandBufferAllocateInfo allocInfo = {};
906 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
907 allocInfo.commandPool = commandPool;
908 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
909 allocInfo.commandBufferCount = (uint32_t) commandBuffers.size();
910
911 if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) {
912 throw runtime_error("failed to allocate command buffers!");
913 }
914
915 for (size_t i = 0; i < commandBuffers.size(); i++) {
916 VkCommandBufferBeginInfo beginInfo = {};
917 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
918 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
919 beginInfo.pInheritanceInfo = nullptr;
920
921 if (vkBeginCommandBuffer(commandBuffers[i], &beginInfo) != VK_SUCCESS) {
922 throw runtime_error("failed to begin recording command buffer!");
923 }
924
925 VkRenderPassBeginInfo renderPassInfo = {};
926 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
927 renderPassInfo.renderPass = renderPass;
928 renderPassInfo.framebuffer = swapChainFramebuffers[i];
929 renderPassInfo.renderArea.offset = { 0, 0 };
930 renderPassInfo.renderArea.extent = swapChainExtent;
931
932 array<VkClearValue, 2> clearValues = {};
933 clearValues[0].color = {{ 0.0f, 0.0f, 0.0f, 1.0f }};
934 clearValues[1].depthStencil = { 1.0f, 0 };
935
936 renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
937 renderPassInfo.pClearValues = clearValues.data();
938
939 vkCmdBeginRenderPass(commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
940
941 modelPipeline.createRenderCommands(commandBuffers[i], i);
942 overlayPipeline.createRenderCommands(commandBuffers[i], i);
943
944 vkCmdEndRenderPass(commandBuffers[i]);
945
946 if (vkEndCommandBuffer(commandBuffers[i]) != VK_SUCCESS) {
947 throw runtime_error("failed to record command buffer!");
948 }
949 }
950}
951
952void VulkanGame::createSyncObjects() {
953 imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
954 renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
955 inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
956
957 VkSemaphoreCreateInfo semaphoreInfo = {};
958 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
959
960 VkFenceCreateInfo fenceInfo = {};
961 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
962 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
963
964 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
965 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
966 vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
967 vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) {
968 throw runtime_error("failed to create synchronization objects for a frame!");
969 }
970 }
971}
972
973// TODO: Fix the crash that happens when alt-tabbing
974void VulkanGame::recreateSwapChain() {
975 cout << "Recreating swap chain" << endl;
976 gui->refreshWindowSize();
977
978 while (gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0 ||
979 (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0) {
980 SDL_WaitEvent(nullptr);
981 gui->refreshWindowSize();
982 }
983
984 vkDeviceWaitIdle(device);
985
986 cleanupSwapChain();
987
988 createSwapChain();
989 createImageViews();
990 createRenderPass();
991
992 VulkanUtils::createDepthImage(device, physicalDevice, commandPool, findDepthFormat(), swapChainExtent,
993 depthImage, graphicsQueue);
994 createFramebuffers();
995 createUniformBuffers();
996
997 modelPipeline.updateRenderPass(renderPass);
998 modelPipeline.createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
999 modelPipeline.createDescriptorPool(swapChainImages);
1000 modelPipeline.createDescriptorSets(swapChainImages);
1001
1002 overlayPipeline.updateRenderPass(renderPass);
1003 overlayPipeline.createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
1004 overlayPipeline.createDescriptorPool(swapChainImages);
1005 overlayPipeline.createDescriptorSets(swapChainImages);
1006
1007 createCommandBuffers();
1008}
1009
1010void VulkanGame::updateUniformBuffer(uint32_t currentImage) {
1011 static auto startTime = chrono::high_resolution_clock::now();
1012
1013 auto currentTime = chrono::high_resolution_clock::now();
1014 float time = chrono::duration<float, chrono::seconds::period>(currentTime - startTime).count();
1015
1016 ubo.model =
1017 translate(mat4(1.0f), vec3(0.0f, -2.0f, -0.0f)) *
1018 rotate(mat4(1.0f), time * radians(90.0f), vec3(0.0f, 0.0f, 1.0f));
1019
1020 void* data;
1021 vkMapMemory(device, uniformBuffersMemory[currentImage], 0, sizeof(ubo), 0, &data);
1022 memcpy(data, &ubo, sizeof(ubo));
1023 vkUnmapMemory(device, uniformBuffersMemory[currentImage]);
1024}
1025
1026void VulkanGame::cleanupSwapChain() {
1027 VulkanUtils::destroyVulkanImage(device, depthImage);
1028
1029 for (VkFramebuffer framebuffer : swapChainFramebuffers) {
1030 vkDestroyFramebuffer(device, framebuffer, nullptr);
1031 }
1032
1033 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
1034
1035 modelPipeline.cleanup();
1036 overlayPipeline.cleanup();
1037
1038 vkDestroyRenderPass(device, renderPass, nullptr);
1039
1040 for (VkImageView imageView : swapChainImageViews) {
1041 vkDestroyImageView(device, imageView, nullptr);
1042 }
1043
1044 vkDestroySwapchainKHR(device, swapChain, nullptr);
1045
1046 for (size_t i = 0; i < uniformBuffers.size(); i++) {
1047 vkDestroyBuffer(device, uniformBuffers[i], nullptr);
1048 vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
1049 }
1050}
Note: See TracBrowser for help on using the repository browser.