source: opengl-game/vulkan-game.cpp@ b8777b7

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

Templatize GraphicsPipeline_Vulkan by adding a VertexType parameter and moving all the function definitions into the header file, separate the model and overlay pipelines into separate variables in VulkanGame instead of storing them in a vector

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