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
Line 
1#include "vulkan-game.hpp"
2
3#define GLM_FORCE_RADIANS
4#define GLM_FORCE_DEPTH_ZERO_TO_ONE
5
6#include <glm/gtc/matrix_transform.hpp>
7
8#include <array>
9#include <chrono>
10#include <iostream>
11#include <set>
12
13#include "consts.hpp"
14#include "logger.hpp"
15
16#include "utils.hpp"
17
18using namespace std;
19using namespace glm;
20
21struct UniformBufferObject {
22 alignas(16) mat4 model;
23 alignas(16) mat4 view;
24 alignas(16) mat4 proj;
25};
26
27VulkanGame::VulkanGame(int maxFramesInFlight) : MAX_FRAMES_IN_FLIGHT(maxFramesInFlight) {
28 gui = nullptr;
29 window = nullptr;
30 font = nullptr;
31 fontSDLTexture = nullptr;
32 imageSDLTexture = nullptr;
33
34 currentFrame = 0;
35 framebufferResized = false;
36}
37
38VulkanGame::~VulkanGame() {
39}
40
41void VulkanGame::run(int width, int height, unsigned char guiFlags) {
42 cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
43
44 cout << "Vulkan Game" << endl;
45
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
65 if (initWindow(width, height, guiFlags) == RTWO_ERROR) {
66 return;
67 }
68
69 initVulkan();
70 mainLoop();
71 cleanup();
72
73 close_log();
74}
75
76// TODO: Make some more init functions, or call this initUI if the
77// amount of things initialized here keeps growing
78bool VulkanGame::initWindow(int width, int height, unsigned char guiFlags) {
79 // TODO: Put all fonts, textures, and images in the assets folder
80 gui = new GameGui_SDL();
81
82 if (gui->init() == RTWO_ERROR) {
83 // TODO: Also print these sorts of errors to the log
84 cout << "UI library could not be initialized!" << endl;
85 cout << gui->getError() << endl;
86 return RTWO_ERROR;
87 }
88
89 window = (SDL_Window*) gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
90 if (window == nullptr) {
91 cout << "Window could not be created!" << endl;
92 cout << gui->getError() << endl;
93 return RTWO_ERROR;
94 }
95
96 cout << "Target window size: (" << width << ", " << height << ")" << endl;
97 cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
98
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
106 SDL_VERSION(&sdlVersion);
107
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
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;
161 return RTWO_ERROR;
162 }
163 if (SDL_SetTextureBlendMode(uiOverlay, SDL_BLENDMODE_BLEND) != 0) {
164 cout << "Unable to set texture blend mode! SDL Error: " << SDL_GetError() << endl;
165 return RTWO_ERROR;
166 }
167
168 SDL_SetRenderTarget(renderer, uiOverlay);
169
170 return RTWO_SUCCESS;
171}
172
173void VulkanGame::initVulkan() {
174 const vector<const char*> validationLayers = {
175 "VK_LAYER_KHRONOS_validation"
176 };
177 const vector<const char*> deviceExtensions = {
178 VK_KHR_SWAPCHAIN_EXTENSION_NAME
179 };
180
181 createVulkanInstance(validationLayers);
182 setupDebugMessenger();
183 createVulkanSurface();
184 pickPhysicalDevice(deviceExtensions);
185 createLogicalDevice(validationLayers, deviceExtensions);
186 createSwapChain();
187 createImageViews();
188 createRenderPass();
189 createCommandPool();
190
191 createImageResources();
192
193 createFramebuffers();
194 createUniformBuffers();
195
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}}
206 };
207 vector<uint16_t> sceneIndices = {
208 0, 1, 2, 2, 3, 0,
209 4, 5, 6, 6, 7, 4
210 };
211
212 modelPipeline = GraphicsPipeline_Vulkan<ModelVertex>(physicalDevice, device, renderPass,
213 { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, sizeof(ModelVertex));
214
215 modelPipeline.bindData(sceneVertices, sceneIndices, commandPool, graphicsQueue);
216
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));
220
221 modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
222 VK_SHADER_STAGE_VERTEX_BIT, &uniformBufferInfoList);
223 modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
224 VK_SHADER_STAGE_FRAGMENT_BIT, &floorTextureImageDescriptor);
225
226 modelPipeline.createDescriptorSetLayout();
227 modelPipeline.createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
228 modelPipeline.createDescriptorPool(swapChainImages);
229 modelPipeline.createDescriptorSets(swapChainImages);
230
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
241 overlayPipeline = GraphicsPipeline_Vulkan<OverlayVertex>(physicalDevice, device, renderPass,
242 { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, sizeof(OverlayVertex));
243
244 overlayPipeline.bindData(overlayVertices, overlayIndices, commandPool, graphicsQueue);
245
246 overlayPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&OverlayVertex::pos));
247 overlayPipeline.addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&OverlayVertex::texCoord));
248
249 overlayPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
250 VK_SHADER_STAGE_FRAGMENT_BIT, &sdlOverlayImageDescriptor);
251
252 overlayPipeline.createDescriptorSetLayout();
253 overlayPipeline.createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
254 overlayPipeline.createDescriptorPool(swapChainImages);
255 overlayPipeline.createDescriptorSets(swapChainImages);
256
257 cout << "Created all the graphics pipelines" << endl;
258
259 numPlanes = 2;
260
261 createCommandBuffers();
262
263 createSyncObjects();
264}
265
266void VulkanGame::mainLoop() {
267 UIEvent e;
268 bool quit = false;
269
270 while (!quit) {
271 gui->processEvents();
272
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;
283 case UI_EVENT_WINDOWRESIZE:
284 cout << "Window resize event detected" << endl;
285 framebufferResized = true;
286 break;
287 case UI_EVENT_KEYDOWN:
288 if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
289 quit = true;
290 } else if (e.key.keycode == SDL_SCANCODE_SPACE) {
291 cout << "Adding a plane" << endl;
292 float zOffset = -2.0f + (0.5f * numPlanes);
293 vector<ModelVertex> vertices = {
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
303 // TODO: Encapsulate these lines into an addObject() function in vulkan-game
304
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++;
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;
325 case UI_EVENT_UNKNOWN:
326 cout << "Unknown event type: 0x" << hex << e.unknown.eventType << dec << endl;
327 break;
328 default:
329 cout << "Unhandled UI event: " << e.type << endl;
330 }
331 }
332
333 renderUI();
334 renderScene();
335 }
336
337 vkDeviceWaitIdle(device);
338}
339
340void VulkanGame::renderUI() {
341 SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
342 SDL_RenderClear(renderer);
343
344 SDL_Rect rect = {280, 220, 100, 100};
345 SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
346 SDL_RenderFillRect(renderer, &rect);
347
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
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);
361}
362
363void VulkanGame::renderScene() {
364 vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, numeric_limits<uint64_t>::max());
365
366 uint32_t imageIndex;
367
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
378 updateUniformBuffer(imageIndex);
379
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
423 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
424 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
425}
426
427void VulkanGame::cleanup() {
428 cleanupSwapChain();
429
430 VulkanUtils::destroyVulkanImage(device, floorTextureImage);
431 VulkanUtils::destroyVulkanImage(device, sdlOverlayImage);
432
433 vkDestroySampler(device, textureSampler, nullptr);
434
435 modelPipeline.cleanupBuffers();
436 overlayPipeline.cleanupBuffers();
437
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
444 vkDestroyCommandPool(device, commandPool, nullptr);
445 vkDestroyDevice(device, nullptr);
446 vkDestroySurfaceKHR(instance, surface, nullptr);
447
448 if (ENABLE_VALIDATION_LAYERS) {
449 VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
450 }
451
452 vkDestroyInstance(instance, nullptr);
453
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
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
475 SDL_DestroyRenderer(renderer);
476 renderer = nullptr;
477
478 gui->destroyWindow();
479 gui->shutdown();
480 delete gui;
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}
560
561void VulkanGame::createVulkanSurface() {
562 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
563 throw runtime_error("failed to create window surface!");
564 }
565}
566
567void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
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) {
580 if (isDeviceSuitable(device, deviceExtensions)) {
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
592bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice,
593 const vector<const char*>& deviceExtensions) {
594 VkPhysicalDeviceProperties deviceProperties;
595 vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
596
597 cout << "Device: " << deviceProperties.deviceName << endl;
598
599 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
600 bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
601 bool swapChainAdequate = false;
602
603 if (extensionsSupported) {
604 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
605 swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
606 }
607
608 VkPhysicalDeviceFeatures supportedFeatures;
609 vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
610
611 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
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
619 vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
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
630 queueCreateInfoList.push_back(queueCreateInfo);
631 }
632
633 VkPhysicalDeviceFeatures deviceFeatures = {};
634 deviceFeatures.samplerAnisotropy = VK_TRUE;
635
636 VkDeviceCreateInfo createInfo = {};
637 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
638 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
639 createInfo.pQueueCreateInfos = queueCreateInfoList.data();
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);
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;
692 } else {
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;
713 swapChainExtent = extent;
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
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
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
805void VulkanGame::createImageResources() {
806 VulkanUtils::createDepthImage(device, physicalDevice, commandPool, findDepthFormat(), swapChainExtent,
807 depthImage, graphicsQueue);
808
809 createTextureSampler();
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
819 VulkanUtils::createVulkanImageFromSDLTexture(device, physicalDevice, uiOverlay, sdlOverlayImage);
820
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
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
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
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
934 modelPipeline.createRenderCommands(commandBuffers[i], i);
935 overlayPipeline.createRenderCommands(commandBuffers[i], i);
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
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
966// TODO: Fix the crash that happens when alt-tabbing
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
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
990 modelPipeline.updateRenderPass(renderPass);
991 modelPipeline.createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
992 modelPipeline.createDescriptorPool(swapChainImages);
993 modelPipeline.createDescriptorSets(swapChainImages);
994
995 overlayPipeline.updateRenderPass(renderPass);
996 overlayPipeline.createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
997 overlayPipeline.createDescriptorPool(swapChainImages);
998 overlayPipeline.createDescriptorSets(swapChainImages);
999
1000 createCommandBuffers();
1001}
1002
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 = {};
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));
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
1021void VulkanGame::cleanupSwapChain() {
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
1030 modelPipeline.cleanup();
1031 overlayPipeline.cleanup();
1032
1033 vkDestroyRenderPass(device, renderPass, nullptr);
1034
1035 for (VkImageView imageView : swapChainImageViews) {
1036 vkDestroyImageView(device, imageView, nullptr);
1037 }
1038
1039 vkDestroySwapchainKHR(device, swapChain, nullptr);
1040
1041 for (size_t i = 0; i < uniformBuffers.size(); i++) {
1042 vkDestroyBuffer(device, uniformBuffers[i], nullptr);
1043 vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
1044 }
1045}
Note: See TracBrowser for help on using the repository browser.