source: opengl-game/vulkan-ref.cpp@ f985231

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

In vulkangame, update the MVP matrix and copy it to the uniform buffer to correctly display the scene

  • Property mode set to 100644
File size: 83.5 KB
Line 
1#define STB_IMAGE_IMPLEMENTATION
2#include "stb_image.h" // TODO: Probably switch to SDL_image
3
4//#define _USE_MATH_DEFINES // Will be needed when/if I need to # include <cmath>
5
6#define GLM_FORCE_RADIANS
7#define GLM_FORCE_DEPTH_ZERO_TO_ONE
8
9#include <glm/glm.hpp>
10#include <glm/gtc/matrix_transform.hpp>
11
12#include <iostream>
13#include <fstream>
14#include <algorithm>
15#include <vector>
16#include <array>
17#include <set>
18#include <optional>
19#include <chrono>
20
21#include "consts.hpp"
22#include "utils.hpp"
23
24#include "game-gui-sdl.hpp"
25
26using namespace std;
27using namespace glm;
28
29/*** START OF REFACTORED CODE ***/
30const int SCREEN_WIDTH = 800;
31const int SCREEN_HEIGHT = 600;
32
33const int MAX_FRAMES_IN_FLIGHT = 2;
34
35#ifdef NDEBUG
36 const bool enableValidationLayers = false;
37#else
38 const bool enableValidationLayers = true;
39#endif
40
41const vector<const char*> validationLayers = {
42 "VK_LAYER_KHRONOS_validation"
43};
44
45const vector<const char*> deviceExtensions = {
46 VK_KHR_SWAPCHAIN_EXTENSION_NAME
47};
48
49struct QueueFamilyIndices {
50 optional<uint32_t> graphicsFamily;
51 optional<uint32_t> presentFamily;
52
53 bool isComplete() {
54 return graphicsFamily.has_value() && presentFamily.has_value();
55 }
56};
57
58struct SwapChainSupportDetails {
59 VkSurfaceCapabilitiesKHR capabilities;
60 vector<VkSurfaceFormatKHR> formats;
61 vector<VkPresentModeKHR> presentModes;
62};
63
64struct Vertex {
65 glm::vec3 pos;
66 glm::vec3 color;
67 glm::vec2 texCoord;
68};
69
70struct OverlayVertex {
71 glm::vec3 pos;
72 glm::vec2 texCoord;
73};
74
75struct UniformBufferObject {
76 alignas(16) mat4 model;
77 alignas(16) mat4 view;
78 alignas(16) mat4 proj;
79};
80
81struct DescriptorInfo {
82 VkDescriptorType type;
83 VkShaderStageFlags stageFlags;
84
85 vector<VkDescriptorBufferInfo>* bufferDataList;
86 VkDescriptorImageInfo* imageData;
87};
88
89struct GraphicsPipelineInfo {
90 VkPipelineLayout pipelineLayout;
91 VkPipeline pipeline;
92
93 VkVertexInputBindingDescription bindingDescription;
94 vector<VkVertexInputAttributeDescription> attributeDescriptions;
95
96 vector<DescriptorInfo> descriptorInfoList;
97
98 VkDescriptorPool descriptorPool;
99 VkDescriptorSetLayout descriptorSetLayout;
100 vector<VkDescriptorSet> descriptorSets;
101
102 size_t numVertices;
103 size_t vertexCapacity;
104 VkBuffer vertexBuffer;
105 VkDeviceMemory vertexBufferMemory;
106
107 size_t numIndices;
108 size_t indexCapacity;
109 VkBuffer indexBuffer;
110 VkDeviceMemory indexBufferMemory;
111};
112
113VkResult CreateDebugUtilsMessengerEXT(VkInstance instance,
114 const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
115 const VkAllocationCallbacks* pAllocator,
116 VkDebugUtilsMessengerEXT* pDebugMessenger) {
117 auto func = (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
118
119 if (func != nullptr) {
120 return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
121 } else {
122 return VK_ERROR_EXTENSION_NOT_PRESENT;
123 }
124}
125
126void DestroyDebugUtilsMessengerEXT(VkInstance instance,
127 VkDebugUtilsMessengerEXT debugMessenger,
128 const VkAllocationCallbacks* pAllocator) {
129 auto func = (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
130
131 if (func != nullptr) {
132 func(instance, debugMessenger, pAllocator);
133 }
134}
135
136class VulkanGame {
137 public:
138 void run() {
139 if (initWindow() == RTWO_ERROR) {
140 return;
141 }
142 initVulkan();
143 mainLoop();
144 cleanup();
145 }
146
147 private:
148 GameGui* gui = new GameGui_SDL();
149
150 SDL_version sdlVersion;
151 SDL_Window* window = nullptr;
152 SDL_Renderer* gRenderer = nullptr;
153 SDL_Texture* uiOverlay = nullptr;
154/*** END OF REFACTORED CODE ***/
155
156 TTF_Font* gFont = nullptr;
157 SDL_Texture* uiText = nullptr;
158 SDL_Texture* uiImage = nullptr;
159
160/*** START OF REFACTORED CODE ***/
161 VkInstance instance;
162 VkDebugUtilsMessengerEXT debugMessenger;
163 VkSurfaceKHR surface;
164
165 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
166 VkDevice device;
167
168 VkQueue graphicsQueue;
169 VkQueue presentQueue;
170
171 VkSwapchainKHR swapChain;
172 vector<VkImage> swapChainImages;
173 VkFormat swapChainImageFormat;
174 VkExtent2D swapChainExtent;
175 vector<VkImageView> swapChainImageViews;
176 vector<VkFramebuffer> swapChainFramebuffers;
177
178 VkRenderPass renderPass;
179
180 VkCommandPool commandPool;
181 vector<VkCommandBuffer> commandBuffers;
182
183 // The images and the sampler are used to store data for specific attributes. I probably
184 // want to keep them separate from the GraphicsPipelineInfo objects and start passing
185 // references to them once I start defining uniform and varying attributes in GraphicsPipelineInfo objects
186
187 VkImage depthImage;
188 VkDeviceMemory depthImageMemory;
189 VkImageView depthImageView;
190
191 VkImage textureImage;
192 VkDeviceMemory textureImageMemory;
193 VkImageView textureImageView;
194
195 VkImage sdlOverlayImage;
196 VkDeviceMemory sdlOverlayImageMemory;
197 VkImageView sdlOverlayImageView;
198
199 VkSampler textureSampler;
200
201 // These are currently to store the MVP matrix
202 // I should figure out if it makes sense to use them for other uniforms in the future
203 // If not, I should rename them to better indicate their purpose.
204 // I should also decide if I can use these for all shaders, or if I need a separapte set of buffers for each one
205 vector<VkBuffer> uniformBuffers;
206 vector<VkDeviceMemory> uniformBuffersMemory;
207
208 VkDescriptorImageInfo sceneImageInfo;
209 VkDescriptorImageInfo overlayImageInfo;
210
211 vector<VkDescriptorBufferInfo> uniformBufferInfoList;
212
213 GraphicsPipelineInfo scenePipeline;
214 GraphicsPipelineInfo overlayPipeline;
215
216 vector<VkSemaphore> imageAvailableSemaphores;
217 vector<VkSemaphore> renderFinishedSemaphores;
218 vector<VkFence> inFlightFences;
219
220 size_t currentFrame = 0;
221/*** END OF REFACTORED CODE ***/
222
223 size_t numPlanes = 0; // temp
224
225/*** START OF REFACTORED CODE ***/
226 bool framebufferResized = false;
227
228 bool initWindow() {
229 if (gui->init() == RTWO_ERROR) {
230 cout << "UI library could not be initialized!" << endl;
231 cout << SDL_GetError() << endl;
232 return RTWO_ERROR;
233 }
234 cout << "GUI init succeeded" << endl;
235
236 window = (SDL_Window*) gui->createWindow("Vulkan Game", SCREEN_WIDTH, SCREEN_HEIGHT, true);
237 if (window == nullptr) {
238 cout << "Window could not be created!" << endl;
239 return RTWO_ERROR;
240 }
241
242 gRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
243 if (gRenderer == nullptr) {
244 cout << "Renderer could not be created! SDL Error: " << SDL_GetError() << endl;
245 return RTWO_ERROR;
246 }
247
248 SDL_VERSION(&sdlVersion);
249
250 // In SDL 2.0.10 (currently, the latest), SDL_TEXTUREACCESS_TARGET is required to get a transparent overlay working
251 // However, the latest SDL version available through homebrew on Mac is 2.0.9, which requires SDL_TEXTUREACCESS_STREAMING
252 // 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
253 // until the homebrew recipe is updated
254 if (sdlVersion.major == 2 && sdlVersion.minor == 0 && sdlVersion.patch == 9) {
255 uiOverlay = SDL_CreateTexture(gRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT);
256 } else {
257 uiOverlay = SDL_CreateTexture(gRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT);
258 }
259
260 if (uiOverlay == nullptr) {
261 cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << endl;
262 }
263 if (SDL_SetTextureBlendMode(uiOverlay, SDL_BLENDMODE_BLEND) != 0) {
264 cout << "Unable to set texture blend mode! SDL Error: " << SDL_GetError() << endl;
265 }
266/*** END OF REFACTORED CODE ***/
267
268 gFont = TTF_OpenFont("fonts/lazy.ttf", 28);
269 if (gFont == nullptr) {
270 cout << "Failed to load lazy font! SDL_ttf Error: " << TTF_GetError() << endl;
271 return RTWO_ERROR;
272 }
273
274 SDL_Color textColor = { 0, 0, 0 };
275
276 SDL_Surface* textSurface = TTF_RenderText_Solid(gFont, "Great sucess!", textColor);
277 if (textSurface == nullptr) {
278 cout << "Unable to render text surface! SDL_ttf Error: " << TTF_GetError() << endl;
279 return RTWO_ERROR;
280 }
281
282 uiText = SDL_CreateTextureFromSurface(gRenderer, textSurface);
283 if (uiText == nullptr) {
284 cout << "Unable to create texture from rendered text! SDL Error: " << SDL_GetError() << endl;
285 SDL_FreeSurface(textSurface);
286 return RTWO_ERROR;
287 }
288
289 SDL_FreeSurface(textSurface);
290
291 // TODO: Load a PNG instead
292 SDL_Surface* uiImageSurface = SDL_LoadBMP("assets/images/spaceship.bmp");
293 if (uiImageSurface == nullptr) {
294 cout << "Unable to load image " << "spaceship.bmp" << "! SDL Error: " << SDL_GetError() << endl;
295 return RTWO_ERROR;
296 }
297
298 uiImage = SDL_CreateTextureFromSurface(gRenderer, uiImageSurface);
299 if (uiImage == nullptr) {
300 cout << "Unable to create texture from BMP surface! SDL Error: " << SDL_GetError() << endl;
301 SDL_FreeSurface(uiImageSurface);
302 return RTWO_ERROR;
303 }
304
305 SDL_FreeSurface(uiImageSurface);
306
307 return RTWO_SUCCESS;
308 }
309
310/*** START OF REFACTORED CODE ***/
311 void initVulkan() {
312 createInstance();
313 setupDebugMessenger();
314 createSurface();
315 pickPhysicalDevice();
316 createLogicalDevice();
317 createSwapChain();
318 createImageViews();
319 createRenderPass();
320
321 createCommandPool();
322
323 createImageResources("textures/texture.jpg", textureImage, textureImageMemory, textureImageView);
324 createImageResourcesFromSDLTexture(uiOverlay, sdlOverlayImage, sdlOverlayImageMemory, sdlOverlayImageView);
325 createTextureSampler();
326
327 sceneImageInfo = {};
328 sceneImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
329 sceneImageInfo.imageView = textureImageView;
330 sceneImageInfo.sampler = textureSampler;
331
332 overlayImageInfo = {};
333 overlayImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
334 overlayImageInfo.imageView = sdlOverlayImageView;
335 overlayImageInfo.sampler = textureSampler;
336
337 // SHADER-SPECIFIC STUFF STARTS HERE
338
339 vector<Vertex> sceneVertices = {
340 {{-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
341 {{ 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
342 {{ 0.5f, 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
343 {{-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}},
344
345 {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
346 {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
347 {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
348 {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
349 };
350 vector<uint16_t> sceneIndices = {
351 0, 1, 2, 2, 3, 0,
352 4, 5, 6, 6, 7, 4
353 };
354
355 initGraphicsPipelineInfo(scenePipeline,
356 sceneVertices.data(), sizeof(Vertex), sceneVertices.size(),
357 sceneIndices.data(), sizeof(uint16_t), sceneIndices.size());
358
359 addAttributeDescription(scenePipeline, VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::pos));
360 addAttributeDescription(scenePipeline, VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::color));
361 addAttributeDescription(scenePipeline, VK_FORMAT_R32G32_SFLOAT, offset_of(&Vertex::texCoord));
362
363 addDescriptorInfo(scenePipeline, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, &uniformBufferInfoList, nullptr);
364 addDescriptorInfo(scenePipeline, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr, &sceneImageInfo);
365
366 createDescriptorSetLayout(scenePipeline);
367
368 numPlanes = 2;
369
370 vector<OverlayVertex> overlayVertices = {
371 {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}},
372 {{ 1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
373 {{ 1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}},
374 {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}}
375 };
376 vector<uint16_t> overlayIndices = {
377 0, 1, 2, 2, 3, 0
378 };
379
380 initGraphicsPipelineInfo(overlayPipeline,
381 overlayVertices.data(), sizeof(OverlayVertex), overlayVertices.size(),
382 overlayIndices.data(), sizeof(uint16_t), overlayIndices.size());
383
384 addAttributeDescription(overlayPipeline, VK_FORMAT_R32G32B32_SFLOAT, offset_of(&OverlayVertex::pos));
385 addAttributeDescription(overlayPipeline, VK_FORMAT_R32G32_SFLOAT, offset_of(&OverlayVertex::texCoord));
386
387 addDescriptorInfo(overlayPipeline, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr, &overlayImageInfo);
388
389 createDescriptorSetLayout(overlayPipeline);
390
391 createBufferResources();
392
393 createSyncObjects();
394 }
395
396 void createInstance() {
397 if (enableValidationLayers && !checkValidationLayerSupport()) {
398 throw runtime_error("validation layers requested, but not available!");
399 }
400
401 VkApplicationInfo appInfo = {};
402 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
403 appInfo.pApplicationName = "Vulkan Game";
404 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
405 appInfo.pEngineName = "No Engine";
406 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
407 appInfo.apiVersion = VK_API_VERSION_1_0;
408
409 VkInstanceCreateInfo createInfo = {};
410 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
411 createInfo.pApplicationInfo = &appInfo;
412
413 vector<const char*> extensions = getRequiredExtensions();
414 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
415 createInfo.ppEnabledExtensionNames = extensions.data();
416
417 cout << endl << "Extensions:" << endl;
418 for (const char* extensionName : extensions) {
419 cout << extensionName << endl;
420 }
421 cout << endl;
422
423 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
424 if (enableValidationLayers) {
425 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
426 createInfo.ppEnabledLayerNames = validationLayers.data();
427
428 populateDebugMessengerCreateInfo(debugCreateInfo);
429 createInfo.pNext = &debugCreateInfo;
430 } else {
431 createInfo.enabledLayerCount = 0;
432
433 createInfo.pNext = nullptr;
434 }
435
436 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
437 throw runtime_error("failed to create instance!");
438 }
439 }
440
441 bool checkValidationLayerSupport() {
442 uint32_t layerCount;
443 vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
444
445 vector<VkLayerProperties> availableLayers(layerCount);
446 vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
447
448 for (const char* layerName : validationLayers) {
449 bool layerFound = false;
450
451 for (const auto& layerProperties : availableLayers) {
452 if (strcmp(layerName, layerProperties.layerName) == 0) {
453 layerFound = true;
454 break;
455 }
456 }
457
458 if (!layerFound) {
459 return false;
460 }
461 }
462
463 return true;
464 }
465
466 vector<const char*> getRequiredExtensions() {
467 vector<const char*> extensions = gui->getRequiredExtensions();
468
469 if (enableValidationLayers) {
470 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
471 }
472
473 return extensions;
474 }
475
476 void setupDebugMessenger() {
477 if (!enableValidationLayers) return;
478
479 VkDebugUtilsMessengerCreateInfoEXT createInfo;
480 populateDebugMessengerCreateInfo(createInfo);
481
482 if (CreateDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
483 throw runtime_error("failed to set up debug messenger!");
484 }
485 }
486
487 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
488 createInfo = {};
489 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
490 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;
491 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;
492 createInfo.pfnUserCallback = debugCallback;
493 }
494
495 void createSurface() {
496 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
497 throw runtime_error("failed to create window surface!");
498 }
499 }
500
501 void pickPhysicalDevice() {
502 uint32_t deviceCount = 0;
503 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
504
505 if (deviceCount == 0) {
506 throw runtime_error("failed to find GPUs with Vulkan support!");
507 }
508
509 vector<VkPhysicalDevice> devices(deviceCount);
510 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
511
512 cout << endl << "Graphics cards:" << endl;
513 for (const VkPhysicalDevice& device : devices) {
514 if (isDeviceSuitable(device)) {
515 physicalDevice = device;
516 break;
517 }
518 }
519 cout << endl;
520
521 if (physicalDevice == VK_NULL_HANDLE) {
522 throw runtime_error("failed to find a suitable GPU!");
523 }
524 }
525
526 bool isDeviceSuitable(VkPhysicalDevice device) {
527 VkPhysicalDeviceProperties deviceProperties;
528 vkGetPhysicalDeviceProperties(device, &deviceProperties);
529
530 cout << "Device: " << deviceProperties.deviceName << endl;
531
532 QueueFamilyIndices indices = findQueueFamilies(device);
533 bool extensionsSupported = checkDeviceExtensionSupport(device);
534 bool swapChainAdequate = false;
535
536 if (extensionsSupported) {
537 SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device);
538 swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
539 }
540
541 VkPhysicalDeviceFeatures supportedFeatures;
542 vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
543
544 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
545 }
546
547 bool checkDeviceExtensionSupport(VkPhysicalDevice device) {
548 uint32_t extensionCount;
549 vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
550
551 vector<VkExtensionProperties> availableExtensions(extensionCount);
552 vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
553
554 set<string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
555
556 for (const auto& extension : availableExtensions) {
557 requiredExtensions.erase(extension.extensionName);
558 }
559
560 return requiredExtensions.empty();
561 }
562
563 void createLogicalDevice() {
564 QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
565
566 vector<VkDeviceQueueCreateInfo> queueCreateInfos;
567 set<uint32_t> uniqueQueueFamilies = {indices.graphicsFamily.value(), indices.presentFamily.value()};
568
569 float queuePriority = 1.0f;
570 for (uint32_t queueFamily : uniqueQueueFamilies) {
571 VkDeviceQueueCreateInfo queueCreateInfo = {};
572 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
573 queueCreateInfo.queueFamilyIndex = queueFamily;
574 queueCreateInfo.queueCount = 1;
575 queueCreateInfo.pQueuePriorities = &queuePriority;
576
577 queueCreateInfos.push_back(queueCreateInfo);
578 }
579
580 VkPhysicalDeviceFeatures deviceFeatures = {};
581 deviceFeatures.samplerAnisotropy = VK_TRUE;
582
583 VkDeviceCreateInfo createInfo = {};
584 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
585 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
586 createInfo.pQueueCreateInfos = queueCreateInfos.data();
587
588 createInfo.pEnabledFeatures = &deviceFeatures;
589
590 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
591 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
592
593 // These fields are ignored by up-to-date Vulkan implementations,
594 // but it's a good idea to set them for backwards compatibility
595 if (enableValidationLayers) {
596 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
597 createInfo.ppEnabledLayerNames = validationLayers.data();
598 } else {
599 createInfo.enabledLayerCount = 0;
600 }
601
602 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
603 throw runtime_error("failed to create logical device!");
604 }
605
606 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
607 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
608 }
609
610 void createSwapChain() {
611 SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
612
613 VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
614 VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
615 VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
616
617 uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
618 if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
619 imageCount = swapChainSupport.capabilities.maxImageCount;
620 }
621
622 VkSwapchainCreateInfoKHR createInfo = {};
623 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
624 createInfo.surface = surface;
625 createInfo.minImageCount = imageCount;
626 createInfo.imageFormat = surfaceFormat.format;
627 createInfo.imageColorSpace = surfaceFormat.colorSpace;
628 createInfo.imageExtent = extent;
629 createInfo.imageArrayLayers = 1;
630 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
631
632 QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
633 uint32_t queueFamilyIndices[] = {indices.graphicsFamily.value(), indices.presentFamily.value()};
634
635 if (indices.graphicsFamily != indices.presentFamily) {
636 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
637 createInfo.queueFamilyIndexCount = 2;
638 createInfo.pQueueFamilyIndices = queueFamilyIndices;
639 } else {
640 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
641 createInfo.queueFamilyIndexCount = 0;
642 createInfo.pQueueFamilyIndices = nullptr;
643 }
644
645 createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
646 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
647 createInfo.presentMode = presentMode;
648 createInfo.clipped = VK_TRUE;
649 createInfo.oldSwapchain = VK_NULL_HANDLE;
650
651 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
652 throw runtime_error("failed to create swap chain!");
653 }
654
655 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
656 swapChainImages.resize(imageCount);
657 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
658
659 swapChainImageFormat = surfaceFormat.format;
660 swapChainExtent = extent;
661 }
662
663 SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device) {
664 SwapChainSupportDetails details;
665
666 vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
667
668 uint32_t formatCount;
669 vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
670
671 if (formatCount != 0) {
672 details.formats.resize(formatCount);
673 vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
674 }
675
676 uint32_t presentModeCount;
677 vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
678
679 if (presentModeCount != 0) {
680 details.presentModes.resize(presentModeCount);
681 vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
682 }
683
684 return details;
685 }
686
687 VkSurfaceFormatKHR chooseSwapSurfaceFormat(const vector<VkSurfaceFormatKHR>& availableFormats) {
688 for (const auto& availableFormat : availableFormats) {
689 if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
690 return availableFormat;
691 }
692 }
693
694 return availableFormats[0];
695 }
696
697 VkPresentModeKHR chooseSwapPresentMode(const vector<VkPresentModeKHR>& availablePresentModes) {
698 VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR;
699
700 for (const auto& availablePresentMode : availablePresentModes) {
701 if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
702 return availablePresentMode;
703 }
704 else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
705 bestMode = availablePresentMode;
706 }
707 }
708
709 return bestMode;
710 }
711
712 VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) {
713 if (capabilities.currentExtent.width != numeric_limits<uint32_t>::max()) {
714 return capabilities.currentExtent;
715 } else {
716 VkExtent2D actualExtent = {
717 static_cast<uint32_t>(gui->getWindowWidth()),
718 static_cast<uint32_t>(gui->getWindowHeight())
719 };
720
721 actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width));
722 actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height));
723
724 return actualExtent;
725 }
726 }
727
728 void createImageViews() {
729 swapChainImageViews.resize(swapChainImages.size());
730
731 for (size_t i = 0; i < swapChainImages.size(); i++) {
732 swapChainImageViews[i] = createImageView(swapChainImages[i], swapChainImageFormat, VK_IMAGE_ASPECT_COLOR_BIT);
733 }
734 }
735
736 void createRenderPass() {
737 VkAttachmentDescription colorAttachment = {};
738 colorAttachment.format = swapChainImageFormat;
739 colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
740 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
741 colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
742 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
743 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
744 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
745 colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
746
747 VkAttachmentReference colorAttachmentRef = {};
748 colorAttachmentRef.attachment = 0;
749 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
750
751 VkAttachmentDescription depthAttachment = {};
752 depthAttachment.format = findDepthFormat();
753 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
754 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
755 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
756 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
757 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
758 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
759 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
760
761 VkAttachmentReference depthAttachmentRef = {};
762 depthAttachmentRef.attachment = 1;
763 depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
764
765 VkSubpassDescription subpass = {};
766 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
767 subpass.colorAttachmentCount = 1;
768 subpass.pColorAttachments = &colorAttachmentRef;
769 subpass.pDepthStencilAttachment = &depthAttachmentRef;
770
771 VkSubpassDependency dependency = {};
772 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
773 dependency.dstSubpass = 0;
774 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
775 dependency.srcAccessMask = 0;
776 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
777 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
778
779 array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
780 VkRenderPassCreateInfo renderPassInfo = {};
781 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
782 renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
783 renderPassInfo.pAttachments = attachments.data();
784 renderPassInfo.subpassCount = 1;
785 renderPassInfo.pSubpasses = &subpass;
786 renderPassInfo.dependencyCount = 1;
787 renderPassInfo.pDependencies = &dependency;
788
789 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
790 throw runtime_error("failed to create render pass!");
791 }
792 }
793
794 void initGraphicsPipelineInfo(GraphicsPipelineInfo& info,
795 const void* vertexData, int vertexSize, size_t numVertices,
796 const void* indexData, int indexSize, size_t numIndices) {
797 // Since there is only one array of vertex data, we use binding = 0
798 // I'll probably do that for the foreseeable future
799 // I can calculate the stride myself given info about all the varying attributes
800
801 info.bindingDescription.binding = 0;
802 info.bindingDescription.stride = vertexSize;
803 info.bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
804
805 info.numVertices = numVertices;
806 info.vertexCapacity = numVertices * 2;
807 createVertexBuffer(info, vertexData, vertexSize);
808
809 info.numIndices = numIndices;
810 info.indexCapacity = numIndices * 2;
811 createIndexBuffer(info, indexData, indexSize);
812 }
813
814 void addAttributeDescription(GraphicsPipelineInfo& info, VkFormat format, size_t offset) {
815 VkVertexInputAttributeDescription attributeDesc = {};
816
817 attributeDesc.binding = 0;
818 attributeDesc.location = info.attributeDescriptions.size();
819 attributeDesc.format = format;
820 attributeDesc.offset = offset;
821
822 info.attributeDescriptions.push_back(attributeDesc);
823 }
824
825 void addDescriptorInfo(GraphicsPipelineInfo& info, VkDescriptorType type, VkShaderStageFlags stageFlags, vector<VkDescriptorBufferInfo>* bufferData, VkDescriptorImageInfo* imageData) {
826 info.descriptorInfoList.push_back({ type, stageFlags, bufferData, imageData });
827 }
828
829 void createDescriptorSetLayout(GraphicsPipelineInfo& info) {
830 vector<VkDescriptorSetLayoutBinding> bindings(info.descriptorInfoList.size());
831
832 for (size_t i = 0; i < bindings.size(); i++) {
833 bindings[i].binding = i;
834 bindings[i].descriptorCount = 1;
835 bindings[i].descriptorType = info.descriptorInfoList[i].type;
836 bindings[i].stageFlags = info.descriptorInfoList[i].stageFlags;
837 bindings[i].pImmutableSamplers = nullptr;
838 }
839
840 VkDescriptorSetLayoutCreateInfo layoutInfo = {};
841 layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
842 layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
843 layoutInfo.pBindings = bindings.data();
844
845 if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &info.descriptorSetLayout) != VK_SUCCESS) {
846 throw runtime_error("failed to create descriptor set layout!");
847 }
848 }
849
850 void createGraphicsPipeline(string vertShaderFile, string fragShaderFile, GraphicsPipelineInfo& info) {
851 vector<char> vertShaderCode = readFile(vertShaderFile);
852 vector<char> fragShaderCode = readFile(fragShaderFile);
853
854 VkShaderModule vertShaderModule = createShaderModule(vertShaderCode);
855 VkShaderModule fragShaderModule = createShaderModule(fragShaderCode);
856
857 VkPipelineShaderStageCreateInfo vertShaderStageInfo = {};
858 vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
859 vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
860 vertShaderStageInfo.module = vertShaderModule;
861 vertShaderStageInfo.pName = "main";
862
863 VkPipelineShaderStageCreateInfo fragShaderStageInfo = {};
864 fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
865 fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
866 fragShaderStageInfo.module = fragShaderModule;
867 fragShaderStageInfo.pName = "main";
868
869 VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo };
870
871 VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
872 vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
873
874 vertexInputInfo.vertexBindingDescriptionCount = 1;
875 vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(info.attributeDescriptions.size());
876 vertexInputInfo.pVertexBindingDescriptions = &info.bindingDescription;
877 vertexInputInfo.pVertexAttributeDescriptions = info.attributeDescriptions.data();
878
879 VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
880 inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
881 inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
882 inputAssembly.primitiveRestartEnable = VK_FALSE;
883
884 VkViewport viewport = {};
885 viewport.x = 0.0f;
886 viewport.y = 0.0f;
887 viewport.width = (float) swapChainExtent.width;
888 viewport.height = (float) swapChainExtent.height;
889 viewport.minDepth = 0.0f;
890 viewport.maxDepth = 1.0f;
891
892 VkRect2D scissor = {};
893 scissor.offset = { 0, 0 };
894 scissor.extent = swapChainExtent;
895
896 VkPipelineViewportStateCreateInfo viewportState = {};
897 viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
898 viewportState.viewportCount = 1;
899 viewportState.pViewports = &viewport;
900 viewportState.scissorCount = 1;
901 viewportState.pScissors = &scissor;
902
903 VkPipelineRasterizationStateCreateInfo rasterizer = {};
904 rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
905 rasterizer.depthClampEnable = VK_FALSE;
906 rasterizer.rasterizerDiscardEnable = VK_FALSE;
907 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
908 rasterizer.lineWidth = 1.0f;
909 rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
910 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
911 rasterizer.depthBiasEnable = VK_FALSE;
912
913 VkPipelineMultisampleStateCreateInfo multisampling = {};
914 multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
915 multisampling.sampleShadingEnable = VK_FALSE;
916 multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
917
918 VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
919 colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
920 colorBlendAttachment.blendEnable = VK_TRUE;
921 colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
922 colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
923 colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
924 colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
925 colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
926 colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
927
928 VkPipelineColorBlendStateCreateInfo colorBlending = {};
929 colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
930 colorBlending.logicOpEnable = VK_FALSE;
931 colorBlending.logicOp = VK_LOGIC_OP_COPY;
932 colorBlending.attachmentCount = 1;
933 colorBlending.pAttachments = &colorBlendAttachment;
934 colorBlending.blendConstants[0] = 0.0f;
935 colorBlending.blendConstants[1] = 0.0f;
936 colorBlending.blendConstants[2] = 0.0f;
937 colorBlending.blendConstants[3] = 0.0f;
938
939 VkPipelineDepthStencilStateCreateInfo depthStencil = {};
940 depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
941 depthStencil.depthTestEnable = VK_TRUE;
942 depthStencil.depthWriteEnable = VK_TRUE;
943 depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
944 depthStencil.depthBoundsTestEnable = VK_FALSE;
945 depthStencil.minDepthBounds = 0.0f;
946 depthStencil.maxDepthBounds = 1.0f;
947 depthStencil.stencilTestEnable = VK_FALSE;
948 depthStencil.front = {};
949 depthStencil.back = {};
950
951 VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
952 pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
953 pipelineLayoutInfo.setLayoutCount = 1;
954 pipelineLayoutInfo.pSetLayouts = &info.descriptorSetLayout;
955 pipelineLayoutInfo.pushConstantRangeCount = 0;
956
957 if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &info.pipelineLayout) != VK_SUCCESS) {
958 throw runtime_error("failed to create pipeline layout!");
959 }
960
961 VkGraphicsPipelineCreateInfo pipelineInfo = {};
962 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
963 pipelineInfo.stageCount = 2;
964 pipelineInfo.pStages = shaderStages;
965 pipelineInfo.pVertexInputState = &vertexInputInfo;
966 pipelineInfo.pInputAssemblyState = &inputAssembly;
967 pipelineInfo.pViewportState = &viewportState;
968 pipelineInfo.pRasterizationState = &rasterizer;
969 pipelineInfo.pMultisampleState = &multisampling;
970 pipelineInfo.pDepthStencilState = &depthStencil;
971 pipelineInfo.pColorBlendState = &colorBlending;
972 pipelineInfo.pDynamicState = nullptr;
973 pipelineInfo.layout = info.pipelineLayout;
974 pipelineInfo.renderPass = renderPass;
975 pipelineInfo.subpass = 0;
976 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
977 pipelineInfo.basePipelineIndex = -1;
978
979 if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &info.pipeline) != VK_SUCCESS) {
980 throw runtime_error("failed to create graphics pipeline!");
981 }
982
983 vkDestroyShaderModule(device, vertShaderModule, nullptr);
984 vkDestroyShaderModule(device, fragShaderModule, nullptr);
985 }
986
987 VkShaderModule createShaderModule(const vector<char>& code) {
988 VkShaderModuleCreateInfo createInfo = {};
989 createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
990 createInfo.codeSize = code.size();
991 createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data());
992
993 VkShaderModule shaderModule;
994 if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
995 throw runtime_error("failed to create shader module!");
996 }
997
998 return shaderModule;
999 }
1000
1001 void createFramebuffers() {
1002 swapChainFramebuffers.resize(swapChainImageViews.size());
1003
1004 for (size_t i = 0; i < swapChainImageViews.size(); i++) {
1005 array<VkImageView, 2> attachments = {
1006 swapChainImageViews[i],
1007 depthImageView
1008 };
1009
1010 VkFramebufferCreateInfo framebufferInfo = {};
1011 framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1012 framebufferInfo.renderPass = renderPass;
1013 framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
1014 framebufferInfo.pAttachments = attachments.data();
1015 framebufferInfo.width = swapChainExtent.width;
1016 framebufferInfo.height = swapChainExtent.height;
1017 framebufferInfo.layers = 1;
1018
1019 if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
1020 throw runtime_error("failed to create framebuffer!");
1021 }
1022 }
1023 }
1024
1025 void createCommandPool() {
1026 QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
1027
1028 VkCommandPoolCreateInfo poolInfo = {};
1029 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1030 poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
1031 poolInfo.flags = 0;
1032
1033 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
1034 throw runtime_error("failed to create graphics command pool!");
1035 }
1036 }
1037
1038 QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) {
1039 QueueFamilyIndices indices;
1040
1041 uint32_t queueFamilyCount = 0;
1042 vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
1043
1044 vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
1045 vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
1046
1047 int i = 0;
1048 for (const auto& queueFamily : queueFamilies) {
1049 if (queueFamily.queueCount > 0 && queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
1050 indices.graphicsFamily = i;
1051 }
1052
1053 VkBool32 presentSupport = false;
1054 vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
1055
1056 if (queueFamily.queueCount > 0 && presentSupport) {
1057 indices.presentFamily = i;
1058 }
1059
1060 if (indices.isComplete()) {
1061 break;
1062 }
1063
1064 i++;
1065 }
1066
1067 return indices;
1068 }
1069
1070 void createDepthResources() {
1071 VkFormat depthFormat = findDepthFormat();
1072
1073 createImage(swapChainExtent.width, swapChainExtent.height, depthFormat, VK_IMAGE_TILING_OPTIMAL,
1074 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, depthImage, depthImageMemory);
1075 depthImageView = createImageView(depthImage, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT);
1076
1077 transitionImageLayout(depthImage, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
1078 }
1079
1080 VkFormat findDepthFormat() {
1081 return findSupportedFormat(
1082 { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
1083 VK_IMAGE_TILING_OPTIMAL,
1084 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
1085 );
1086 }
1087
1088 VkFormat findSupportedFormat(const vector<VkFormat>& candidates, VkImageTiling tiling,
1089 VkFormatFeatureFlags features) {
1090 for (VkFormat format : candidates) {
1091 VkFormatProperties props;
1092 vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &props);
1093
1094 if (tiling == VK_IMAGE_TILING_LINEAR &&
1095 (props.linearTilingFeatures & features) == features) {
1096 return format;
1097 } else if (tiling == VK_IMAGE_TILING_OPTIMAL &&
1098 (props.optimalTilingFeatures & features) == features) {
1099 return format;
1100 }
1101 }
1102
1103 throw runtime_error("failed to find supported format!");
1104 }
1105
1106 bool hasStencilComponent(VkFormat format) {
1107 return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT;
1108 }
1109
1110 void createImageResources(string filename, VkImage& image, VkDeviceMemory& imageMemory, VkImageView& view) {
1111 int texWidth, texHeight, texChannels;
1112
1113 stbi_uc* pixels = stbi_load(filename.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
1114 VkDeviceSize imageSize = texWidth * texHeight * 4;
1115
1116 if (!pixels) {
1117 throw runtime_error("failed to load texture image!");
1118 }
1119
1120 VkBuffer stagingBuffer;
1121 VkDeviceMemory stagingBufferMemory;
1122
1123 createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1124 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1125 stagingBuffer, stagingBufferMemory);
1126
1127 void* data;
1128
1129 vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &data);
1130 memcpy(data, pixels, static_cast<size_t>(imageSize));
1131 vkUnmapMemory(device, stagingBufferMemory);
1132
1133 stbi_image_free(pixels);
1134
1135 createImage(texWidth, texHeight, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
1136 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
1137 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image, imageMemory);
1138
1139 transitionImageLayout(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1140 copyBufferToImage(stagingBuffer, image, static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight));
1141 transitionImageLayout(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
1142
1143 vkDestroyBuffer(device, stagingBuffer, nullptr);
1144 vkFreeMemory(device, stagingBufferMemory, nullptr);
1145
1146 view = createImageView(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
1147 }
1148
1149 void createImageResourcesFromSDLTexture(SDL_Texture* texture, VkImage& image, VkDeviceMemory& imageMemory, VkImageView& view) {
1150 int a, w, h;
1151
1152 // I only need this here for the width and height, which are constants, so just use those instead
1153 SDL_QueryTexture(texture, nullptr, &a, &w, &h);
1154
1155 createImage(w, h, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
1156 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
1157 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image, imageMemory);
1158
1159 view = createImageView(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
1160 }
1161
1162 void populateImageFromSDLTexture(SDL_Texture* texture, VkImage& image) {
1163 int a, w, h;
1164
1165 SDL_QueryTexture(texture, nullptr, &a, &w, &h);
1166
1167 VkDeviceSize imageSize = w * h * 4;
1168 unsigned char* pixels = new unsigned char[imageSize];
1169
1170 SDL_RenderReadPixels(gRenderer, nullptr, SDL_PIXELFORMAT_ABGR8888, pixels, w * 4);
1171
1172 VkBuffer stagingBuffer;
1173 VkDeviceMemory stagingBufferMemory;
1174
1175 createBuffer(imageSize,
1176 VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1177 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
1178 stagingBuffer, stagingBufferMemory);
1179
1180 void* data;
1181
1182 vkMapMemory(device, stagingBufferMemory, 0, VK_WHOLE_SIZE, 0, &data);
1183 memcpy(data, pixels, static_cast<size_t>(imageSize));
1184
1185 VkMappedMemoryRange mappedMemoryRange = {};
1186 mappedMemoryRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1187 mappedMemoryRange.memory = stagingBufferMemory;
1188 mappedMemoryRange.offset = 0;
1189 mappedMemoryRange.size = VK_WHOLE_SIZE;
1190
1191 // TODO: Should probably check that the function succeeded
1192 vkFlushMappedMemoryRanges(device, 1, &mappedMemoryRange);
1193 vkUnmapMemory(device, stagingBufferMemory);
1194
1195 delete[] pixels;
1196
1197 transitionImageLayout(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1198 copyBufferToImage(stagingBuffer, image, static_cast<uint32_t>(w), static_cast<uint32_t>(h));
1199 transitionImageLayout(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
1200
1201 vkDestroyBuffer(device, stagingBuffer, nullptr);
1202 vkFreeMemory(device, stagingBufferMemory, nullptr);
1203 }
1204
1205 void createImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage,
1206 VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory) {
1207 VkImageCreateInfo imageInfo = {};
1208 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1209 imageInfo.imageType = VK_IMAGE_TYPE_2D;
1210 imageInfo.extent.width = width;
1211 imageInfo.extent.height = height;
1212 imageInfo.extent.depth = 1;
1213 imageInfo.mipLevels = 1;
1214 imageInfo.arrayLayers = 1;
1215 imageInfo.format = format;
1216 imageInfo.tiling = tiling;
1217 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1218 imageInfo.usage = usage;
1219 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
1220 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1221
1222 if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS) {
1223 throw runtime_error("failed to create image!");
1224 }
1225
1226 VkMemoryRequirements memRequirements;
1227 vkGetImageMemoryRequirements(device, image, &memRequirements);
1228
1229 VkMemoryAllocateInfo allocInfo = {};
1230 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1231 allocInfo.allocationSize = memRequirements.size;
1232 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties);
1233
1234 if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS) {
1235 throw runtime_error("failed to allocate image memory!");
1236 }
1237
1238 vkBindImageMemory(device, image, imageMemory, 0);
1239 }
1240
1241 void transitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout) {
1242 VkCommandBuffer commandBuffer = beginSingleTimeCommands();
1243
1244 VkImageMemoryBarrier barrier = {};
1245 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1246 barrier.oldLayout = oldLayout;
1247 barrier.newLayout = newLayout;
1248 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1249 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1250 barrier.image = image;
1251
1252 if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
1253 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
1254
1255 if (hasStencilComponent(format)) {
1256 barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
1257 }
1258 } else {
1259 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1260 }
1261
1262 barrier.subresourceRange.baseMipLevel = 0;
1263 barrier.subresourceRange.levelCount = 1;
1264 barrier.subresourceRange.baseArrayLayer = 0;
1265 barrier.subresourceRange.layerCount = 1;
1266
1267 VkPipelineStageFlags sourceStage;
1268 VkPipelineStageFlags destinationStage;
1269
1270 if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
1271 barrier.srcAccessMask = 0;
1272 barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1273
1274 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1275 destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
1276 } else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
1277 barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1278 barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
1279
1280 sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
1281 destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
1282 } else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
1283 barrier.srcAccessMask = 0;
1284 barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
1285
1286 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1287 destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
1288 } else {
1289 throw invalid_argument("unsupported layout transition!");
1290 }
1291
1292 vkCmdPipelineBarrier(
1293 commandBuffer,
1294 sourceStage, destinationStage,
1295 0,
1296 0, nullptr,
1297 0, nullptr,
1298 1, &barrier
1299 );
1300
1301 endSingleTimeCommands(commandBuffer);
1302 }
1303
1304 void copyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height) {
1305 VkCommandBuffer commandBuffer = beginSingleTimeCommands();
1306
1307 VkBufferImageCopy region = {};
1308 region.bufferOffset = 0;
1309 region.bufferRowLength = 0;
1310 region.bufferImageHeight = 0;
1311 region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1312 region.imageSubresource.mipLevel = 0;
1313 region.imageSubresource.baseArrayLayer = 0;
1314 region.imageSubresource.layerCount = 1;
1315 region.imageOffset = { 0, 0, 0 };
1316 region.imageExtent = { width, height, 1 };
1317
1318 vkCmdCopyBufferToImage(
1319 commandBuffer,
1320 buffer,
1321 image,
1322 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1323 1,
1324 &region
1325 );
1326
1327 endSingleTimeCommands(commandBuffer);
1328 }
1329
1330 VkImageView createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags) {
1331 VkImageViewCreateInfo viewInfo = {};
1332 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1333 viewInfo.image = image;
1334 viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
1335 viewInfo.format = format;
1336
1337 viewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
1338 viewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
1339 viewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
1340 viewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
1341
1342 viewInfo.subresourceRange.aspectMask = aspectFlags;
1343 viewInfo.subresourceRange.baseMipLevel = 0;
1344 viewInfo.subresourceRange.levelCount = 1;
1345 viewInfo.subresourceRange.baseArrayLayer = 0;
1346 viewInfo.subresourceRange.layerCount = 1;
1347
1348 VkImageView imageView;
1349 if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS) {
1350 throw runtime_error("failed to create texture image view!");
1351 }
1352
1353 return imageView;
1354 }
1355
1356 void createTextureSampler() {
1357 VkSamplerCreateInfo samplerInfo = {};
1358 samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
1359 samplerInfo.magFilter = VK_FILTER_LINEAR;
1360 samplerInfo.minFilter = VK_FILTER_LINEAR;
1361
1362 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1363 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1364 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1365
1366 samplerInfo.anisotropyEnable = VK_TRUE;
1367 samplerInfo.maxAnisotropy = 16;
1368 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
1369 samplerInfo.unnormalizedCoordinates = VK_FALSE;
1370 samplerInfo.compareEnable = VK_FALSE;
1371 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
1372 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
1373 samplerInfo.mipLodBias = 0.0f;
1374 samplerInfo.minLod = 0.0f;
1375 samplerInfo.maxLod = 0.0f;
1376
1377 if (vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) {
1378 throw runtime_error("failed to create texture sampler!");
1379 }
1380 }
1381
1382 void createVertexBuffer(GraphicsPipelineInfo& info, const void* vertexData, int vertexSize) {
1383 VkDeviceSize bufferSize = info.numVertices * vertexSize;
1384 VkDeviceSize bufferCapacity = info.vertexCapacity * vertexSize;
1385
1386 VkBuffer stagingBuffer;
1387 VkDeviceMemory stagingBufferMemory;
1388 createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1389 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1390 stagingBuffer, stagingBufferMemory);
1391
1392 void* data;
1393 vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data);
1394 memcpy(data, vertexData, (size_t) bufferSize);
1395 vkUnmapMemory(device, stagingBufferMemory);
1396
1397 createBuffer(bufferCapacity, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
1398 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, info.vertexBuffer, info.vertexBufferMemory);
1399
1400 copyBuffer(stagingBuffer, info.vertexBuffer, 0, 0, bufferSize);
1401
1402 vkDestroyBuffer(device, stagingBuffer, nullptr);
1403 vkFreeMemory(device, stagingBufferMemory, nullptr);
1404 }
1405
1406 void createIndexBuffer(GraphicsPipelineInfo& info, const void* indexData, int indexSize) {
1407 VkDeviceSize bufferSize = info.numIndices * indexSize;
1408 VkDeviceSize bufferCapacity = info.indexCapacity * indexSize;
1409
1410 VkBuffer stagingBuffer;
1411 VkDeviceMemory stagingBufferMemory;
1412 createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1413 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1414 stagingBuffer, stagingBufferMemory);
1415
1416 void* data;
1417 vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data);
1418 memcpy(data, indexData, (size_t) bufferSize);
1419 vkUnmapMemory(device, stagingBufferMemory);
1420
1421 createBuffer(bufferCapacity, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
1422 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, info.indexBuffer, info.indexBufferMemory);
1423
1424 copyBuffer(stagingBuffer, info.indexBuffer, 0, 0, bufferSize);
1425
1426 vkDestroyBuffer(device, stagingBuffer, nullptr);
1427 vkFreeMemory(device, stagingBufferMemory, nullptr);
1428 }
1429
1430 void createUniformBuffers() {
1431 VkDeviceSize bufferSize = sizeof(UniformBufferObject);
1432
1433 uniformBuffers.resize(swapChainImages.size());
1434 uniformBuffersMemory.resize(swapChainImages.size());
1435 uniformBufferInfoList.resize(swapChainImages.size());
1436
1437 for (size_t i = 0; i < swapChainImages.size(); i++) {
1438 createBuffer(bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
1439 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1440 uniformBuffers[i], uniformBuffersMemory[i]);
1441
1442 uniformBufferInfoList[i].buffer = uniformBuffers[i];
1443 uniformBufferInfoList[i].offset = 0;
1444 uniformBufferInfoList[i].range = sizeof(UniformBufferObject);
1445 }
1446 }
1447
1448 void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) {
1449 VkBufferCreateInfo bufferInfo = {};
1450 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
1451 bufferInfo.size = size;
1452 bufferInfo.usage = usage;
1453 bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1454
1455 if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) {
1456 throw runtime_error("failed to create buffer!");
1457 }
1458
1459 VkMemoryRequirements memRequirements;
1460 vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
1461
1462 VkMemoryAllocateInfo allocInfo = {};
1463 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1464 allocInfo.allocationSize = memRequirements.size;
1465 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties);
1466
1467 if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) {
1468 throw runtime_error("failed to allocate buffer memory!");
1469 }
1470
1471 vkBindBufferMemory(device, buffer, bufferMemory, 0);
1472 }
1473/*** END OF REFACTORED CODE ***/
1474
1475 void copyDataToBuffer(const void* srcData, VkBuffer dst, VkDeviceSize dstOffset, VkDeviceSize dataSize) {
1476 VkBuffer stagingBuffer;
1477 VkDeviceMemory stagingBufferMemory;
1478 createBuffer(dataSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1479 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1480 stagingBuffer, stagingBufferMemory);
1481
1482 void* data;
1483 vkMapMemory(device, stagingBufferMemory, 0, dataSize, 0, &data);
1484 memcpy(data, srcData, (size_t) dataSize);
1485 vkUnmapMemory(device, stagingBufferMemory);
1486
1487 copyBuffer(stagingBuffer, dst, 0, dstOffset, dataSize);
1488
1489 vkDestroyBuffer(device, stagingBuffer, nullptr);
1490 vkFreeMemory(device, stagingBufferMemory, nullptr);
1491 }
1492
1493/*** START OF REFACTORED CODE ***/
1494 void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize srcOffset, VkDeviceSize dstOffset,
1495 VkDeviceSize size) {
1496 VkCommandBuffer commandBuffer = beginSingleTimeCommands();
1497
1498 VkBufferCopy copyRegion = { srcOffset, dstOffset, size };
1499 vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion);
1500
1501 endSingleTimeCommands(commandBuffer);
1502 }
1503
1504 VkCommandBuffer beginSingleTimeCommands() {
1505 VkCommandBufferAllocateInfo allocInfo = {};
1506 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1507 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1508 allocInfo.commandPool = commandPool;
1509 allocInfo.commandBufferCount = 1;
1510
1511 VkCommandBuffer commandBuffer;
1512 vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
1513
1514 VkCommandBufferBeginInfo beginInfo = {};
1515 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1516 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
1517
1518 vkBeginCommandBuffer(commandBuffer, &beginInfo);
1519
1520 return commandBuffer;
1521 }
1522
1523 void endSingleTimeCommands(VkCommandBuffer commandBuffer) {
1524 vkEndCommandBuffer(commandBuffer);
1525
1526 VkSubmitInfo submitInfo = {};
1527 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1528 submitInfo.commandBufferCount = 1;
1529 submitInfo.pCommandBuffers = &commandBuffer;
1530
1531 vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
1532 vkQueueWaitIdle(graphicsQueue);
1533
1534 vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
1535 }
1536
1537 uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties) {
1538 VkPhysicalDeviceMemoryProperties memProperties;
1539 vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
1540
1541 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
1542 if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) {
1543 return i;
1544 }
1545 }
1546
1547 throw runtime_error("failed to find suitable memory type!");
1548 }
1549
1550 void createDescriptorPool(GraphicsPipelineInfo& info) {
1551 vector<VkDescriptorPoolSize> poolSizes(info.descriptorInfoList.size());
1552
1553 for (size_t i = 0; i < poolSizes.size(); i++) {
1554 poolSizes[i].type = info.descriptorInfoList[i].type;
1555 poolSizes[i].descriptorCount = static_cast<uint32_t>(swapChainImages.size());
1556 }
1557
1558 VkDescriptorPoolCreateInfo poolInfo = {};
1559 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
1560 poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
1561 poolInfo.pPoolSizes = poolSizes.data();
1562 poolInfo.maxSets = static_cast<uint32_t>(swapChainImages.size());
1563
1564 if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &info.descriptorPool) != VK_SUCCESS) {
1565 throw runtime_error("failed to create descriptor pool!");
1566 }
1567 }
1568
1569 void createDescriptorSets(GraphicsPipelineInfo& info) {
1570 vector<VkDescriptorSetLayout> layouts(swapChainImages.size(), info.descriptorSetLayout);
1571
1572 VkDescriptorSetAllocateInfo allocInfo = {};
1573 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
1574 allocInfo.descriptorPool = info.descriptorPool;
1575 allocInfo.descriptorSetCount = static_cast<uint32_t>(swapChainImages.size());
1576 allocInfo.pSetLayouts = layouts.data();
1577
1578 info.descriptorSets.resize(swapChainImages.size());
1579 if (vkAllocateDescriptorSets(device, &allocInfo, info.descriptorSets.data()) != VK_SUCCESS) {
1580 throw runtime_error("failed to allocate descriptor sets!");
1581 }
1582
1583 for (size_t i = 0; i < swapChainImages.size(); i++) {
1584 vector<VkWriteDescriptorSet> descriptorWrites(info.descriptorInfoList.size());
1585
1586 for (size_t j = 0; j < descriptorWrites.size(); j++) {
1587 descriptorWrites[j].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1588 descriptorWrites[j].dstSet = info.descriptorSets[i];
1589 descriptorWrites[j].dstBinding = j;
1590 descriptorWrites[j].dstArrayElement = 0;
1591 descriptorWrites[j].descriptorType = info.descriptorInfoList[j].type;
1592 descriptorWrites[j].descriptorCount = 1;
1593 descriptorWrites[j].pBufferInfo = nullptr;
1594 descriptorWrites[j].pImageInfo = nullptr;
1595 descriptorWrites[j].pTexelBufferView = nullptr;
1596
1597 switch (descriptorWrites[j].descriptorType) {
1598 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
1599 descriptorWrites[j].pBufferInfo = &(*info.descriptorInfoList[j].bufferDataList)[i];
1600 break;
1601 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
1602 descriptorWrites[j].pImageInfo = info.descriptorInfoList[j].imageData;
1603 break;
1604 default:
1605 cout << "Unknown descriptor type: " << descriptorWrites[j].descriptorType << endl;
1606 }
1607 }
1608
1609 vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
1610 }
1611 }
1612
1613 void createCommandBuffers() {
1614 commandBuffers.resize(swapChainFramebuffers.size());
1615
1616 VkCommandBufferAllocateInfo allocInfo = {};
1617 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1618 allocInfo.commandPool = commandPool;
1619 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1620 allocInfo.commandBufferCount = (uint32_t) commandBuffers.size();
1621
1622 if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) {
1623 throw runtime_error("failed to allocate command buffers!");
1624 }
1625
1626 for (size_t i = 0; i < commandBuffers.size(); i++) {
1627 VkCommandBufferBeginInfo beginInfo = {};
1628 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1629 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
1630 beginInfo.pInheritanceInfo = nullptr;
1631
1632 if (vkBeginCommandBuffer(commandBuffers[i], &beginInfo) != VK_SUCCESS) {
1633 throw runtime_error("failed to begin recording command buffer!");
1634 }
1635
1636 VkRenderPassBeginInfo renderPassInfo = {};
1637 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
1638 renderPassInfo.renderPass = renderPass;
1639 renderPassInfo.framebuffer = swapChainFramebuffers[i];
1640 renderPassInfo.renderArea.offset = { 0, 0 };
1641 renderPassInfo.renderArea.extent = swapChainExtent;
1642
1643 array<VkClearValue, 2> clearValues = {};
1644 clearValues[0].color = {{ 0.0f, 0.0f, 0.0f, 1.0f }};
1645 clearValues[1].depthStencil = { 1.0f, 0 };
1646
1647 renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
1648 renderPassInfo.pClearValues = clearValues.data();
1649
1650 vkCmdBeginRenderPass(commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
1651
1652 createGraphicsPipelineCommands(scenePipeline, i);
1653 createGraphicsPipelineCommands(overlayPipeline, i);
1654
1655 vkCmdEndRenderPass(commandBuffers[i]);
1656
1657 if (vkEndCommandBuffer(commandBuffers[i]) != VK_SUCCESS) {
1658 throw runtime_error("failed to record command buffer!");
1659 }
1660 }
1661 }
1662
1663 void createGraphicsPipelineCommands(GraphicsPipelineInfo& info, uint32_t currentImage) {
1664 vkCmdBindPipeline(commandBuffers[currentImage], VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline);
1665 vkCmdBindDescriptorSets(commandBuffers[currentImage], VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipelineLayout, 0, 1,
1666 &info.descriptorSets[currentImage], 0, nullptr);
1667
1668 VkBuffer vertexBuffers[] = { info.vertexBuffer };
1669 VkDeviceSize offsets[] = { 0 };
1670 vkCmdBindVertexBuffers(commandBuffers[currentImage], 0, 1, vertexBuffers, offsets);
1671
1672 vkCmdBindIndexBuffer(commandBuffers[currentImage], info.indexBuffer, 0, VK_INDEX_TYPE_UINT16);
1673
1674 vkCmdDrawIndexed(commandBuffers[currentImage], static_cast<uint32_t>(info.numIndices), 1, 0, 0, 0);
1675 }
1676
1677 void createSyncObjects() {
1678 imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
1679 renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
1680 inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
1681
1682 VkSemaphoreCreateInfo semaphoreInfo = {};
1683 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
1684
1685 VkFenceCreateInfo fenceInfo = {};
1686 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1687 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
1688
1689 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
1690 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
1691 vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
1692 vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) {
1693 throw runtime_error("failed to create synchronization objects for a frame!");
1694 }
1695 }
1696 }
1697/*** END OF REFACTORED CODE ***/
1698
1699 bool addObjectToScene(GraphicsPipelineInfo& info,
1700 const void* vertexData, int vertexSize, size_t numVertices,
1701 vector<uint16_t>& indices, size_t numIndices) {
1702 int indexSize = sizeof(uint16_t);
1703
1704 for (uint16_t& idx : indices) {
1705 idx += info.numVertices;
1706 }
1707
1708 if (info.numVertices + numVertices > info.vertexCapacity) {
1709 cout << "ERROR: Need to resize vertex buffers" << endl;
1710 } else if (info.numIndices + numIndices > info.indexCapacity) {
1711 cout << "ERROR: Need to resize index buffers" << endl;
1712 } else {
1713 cout << "Added object to scene" << endl;
1714
1715 copyDataToBuffer(vertexData, info.vertexBuffer, info.numVertices * vertexSize, numVertices * vertexSize);
1716 info.numVertices += numVertices;
1717
1718 copyDataToBuffer(indices.data(), info.indexBuffer, info.numIndices * indexSize, numIndices * indexSize);
1719 info.numIndices += numIndices;
1720
1721 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
1722 createCommandBuffers();
1723
1724 return true;
1725 }
1726
1727 return false;
1728 }
1729
1730/*** START OF REFACTORED CODE ***/
1731 void mainLoop() {
1732 // TODO: Create some generic event-handling functions in game-gui-*
1733 SDL_Event e;
1734 bool quit = false;
1735
1736 while (!quit) {
1737 while (SDL_PollEvent(&e)) {
1738 if (e.type == SDL_QUIT) {
1739 quit = true;
1740 }
1741 if (e.type == SDL_KEYDOWN) {
1742 if (e.key.keysym.sym == SDLK_SPACE) {
1743 float zOffset = -0.5f + (0.5f * numPlanes);
1744 vector<Vertex> vertices = {
1745 {{-0.5f, -0.5f, zOffset}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
1746 {{ 0.5f, -0.5f, zOffset}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
1747 {{ 0.5f, 0.5f, zOffset}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
1748 {{-0.5f, 0.5f, zOffset}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
1749 };
1750 vector<uint16_t> indices = {
1751 0, 1, 2, 2, 3, 0
1752 };
1753
1754 if (addObjectToScene(scenePipeline,
1755 vertices.data(), sizeof(Vertex), vertices.size(),
1756 indices, indices.size())) {
1757 numPlanes++;
1758 }
1759 } else if (e.key.keysym.sym == SDLK_ESCAPE) {
1760 quit = true;
1761 }
1762 }
1763 if (e.type == SDL_MOUSEBUTTONDOWN) {
1764 quit = true;
1765 }
1766 if (e.type == SDL_WINDOWEVENT) {
1767 if (e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED ||
1768 e.window.event == SDL_WINDOWEVENT_MINIMIZED) {
1769 framebufferResized = true;
1770 }
1771 }
1772 }
1773
1774 drawUI();
1775
1776 drawFrame();
1777 }
1778
1779 vkDeviceWaitIdle(device);
1780 }
1781
1782 void drawFrame() {
1783 vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, numeric_limits<uint64_t>::max());
1784
1785 uint32_t imageIndex;
1786
1787 VkResult result = vkAcquireNextImageKHR(device, swapChain, numeric_limits<uint64_t>::max(),
1788 imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
1789
1790 if (result == VK_ERROR_OUT_OF_DATE_KHR) {
1791 recreateSwapChain();
1792 return;
1793 } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
1794 throw runtime_error("failed to acquire swap chain image!");
1795 }
1796
1797 updateUniformBuffer(imageIndex);
1798
1799 VkSubmitInfo submitInfo = {};
1800 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1801
1802 VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] };
1803 VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
1804
1805 submitInfo.waitSemaphoreCount = 1;
1806 submitInfo.pWaitSemaphores = waitSemaphores;
1807 submitInfo.pWaitDstStageMask = waitStages;
1808 submitInfo.commandBufferCount = 1;
1809 submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
1810
1811 VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] };
1812
1813 submitInfo.signalSemaphoreCount = 1;
1814 submitInfo.pSignalSemaphores = signalSemaphores;
1815
1816 vkResetFences(device, 1, &inFlightFences[currentFrame]);
1817
1818 if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS) {
1819 throw runtime_error("failed to submit draw command buffer!");
1820 }
1821
1822 VkPresentInfoKHR presentInfo = {};
1823 presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
1824 presentInfo.waitSemaphoreCount = 1;
1825 presentInfo.pWaitSemaphores = signalSemaphores;
1826
1827 VkSwapchainKHR swapChains[] = { swapChain };
1828 presentInfo.swapchainCount = 1;
1829 presentInfo.pSwapchains = swapChains;
1830 presentInfo.pImageIndices = &imageIndex;
1831 presentInfo.pResults = nullptr;
1832
1833 result = vkQueuePresentKHR(presentQueue, &presentInfo);
1834
1835 if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
1836 framebufferResized = false;
1837 recreateSwapChain();
1838 } else if (result != VK_SUCCESS) {
1839 throw runtime_error("failed to present swap chain image!");
1840 }
1841
1842 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
1843 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
1844 }
1845
1846 void drawUI() {
1847 // TODO: Since I currently don't use any other render targets,
1848 // I may as well set this once before the render loop
1849 SDL_SetRenderTarget(gRenderer, uiOverlay);
1850
1851 SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0x00, 0x00);
1852 SDL_RenderClear(gRenderer);
1853/*** END OF REFACTORED CODE ***/
1854
1855 SDL_Rect rect;
1856
1857 rect = {280, 220, 100, 100};
1858 SDL_SetRenderDrawColor(gRenderer, 0x00, 0xFF, 0x00, 0xFF);
1859 SDL_RenderFillRect(gRenderer, &rect);
1860 SDL_SetRenderDrawColor(gRenderer, 0x00, 0x9F, 0x9F, 0xFF);
1861
1862 rect = {10, 10, 0, 0};
1863 SDL_QueryTexture(uiText, nullptr, nullptr, &(rect.w), &(rect.h));
1864 SDL_RenderCopy(gRenderer, uiText, nullptr, &rect);
1865
1866 rect = {10, 80, 0, 0};
1867 SDL_QueryTexture(uiImage, nullptr, nullptr, &(rect.w), &(rect.h));
1868 SDL_RenderCopy(gRenderer, uiImage, nullptr, &rect);
1869
1870/*** START OF REFACTORED CODE ***/
1871 SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0xFF, 0xFF);
1872 SDL_RenderDrawLine(gRenderer, 50, 5, 150, 500);
1873
1874 populateImageFromSDLTexture(uiOverlay, sdlOverlayImage);
1875 }
1876
1877 void updateUniformBuffer(uint32_t currentImage) {
1878 static auto startTime = chrono::high_resolution_clock::now();
1879
1880 auto currentTime = chrono::high_resolution_clock::now();
1881 float time = chrono::duration<float, chrono::seconds::period>(currentTime - startTime).count();
1882
1883 UniformBufferObject ubo = {};
1884 ubo.model = rotate(glm::mat4(1.0f), time * glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f));
1885 ubo.view = lookAt(glm::vec3(0.0f, 2.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
1886 ubo.proj = perspective(radians(45.0f), swapChainExtent.width / (float)swapChainExtent.height, 0.1f, 10.0f);
1887 ubo.proj[1][1] *= -1; // flip the y-axis so that +y is up
1888
1889 void* data;
1890 vkMapMemory(device, uniformBuffersMemory[currentImage], 0, sizeof(ubo), 0, &data);
1891 memcpy(data, &ubo, sizeof(ubo));
1892 vkUnmapMemory(device, uniformBuffersMemory[currentImage]);
1893 }
1894
1895 void recreateSwapChain() {
1896 gui->refreshWindowSize();
1897
1898 while (gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0 ||
1899 (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0) {
1900 SDL_WaitEvent(nullptr);
1901 gui->refreshWindowSize();
1902 }
1903
1904 vkDeviceWaitIdle(device);
1905/*** END OF REFACTORED CODE ***/
1906
1907 cleanupSwapChain();
1908
1909 createSwapChain();
1910 createImageViews();
1911 createRenderPass();
1912
1913 createBufferResources();
1914/*** START OF REFACTORED CODE ***/
1915 }
1916
1917 void createBufferResources() {
1918 createDepthResources();
1919 createFramebuffers();
1920 createUniformBuffers();
1921
1922 createGraphicsPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv", scenePipeline);
1923 createDescriptorPool(scenePipeline);
1924 createDescriptorSets(scenePipeline);
1925
1926 createGraphicsPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv", overlayPipeline);
1927 createDescriptorPool(overlayPipeline);
1928 createDescriptorSets(overlayPipeline);
1929
1930 createCommandBuffers();
1931 }
1932
1933 void cleanup() {
1934 cleanupSwapChain();
1935
1936 vkDestroySampler(device, textureSampler, nullptr);
1937
1938 vkDestroyImageView(device, textureImageView, nullptr);
1939 vkDestroyImage(device, textureImage, nullptr);
1940 vkFreeMemory(device, textureImageMemory, nullptr);
1941
1942 vkDestroyImageView(device, sdlOverlayImageView, nullptr);
1943 vkDestroyImage(device, sdlOverlayImage, nullptr);
1944 vkFreeMemory(device, sdlOverlayImageMemory, nullptr);
1945
1946 cleanupPipelineBuffers(scenePipeline);
1947 cleanupPipelineBuffers(overlayPipeline);
1948
1949 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
1950 vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
1951 vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
1952 vkDestroyFence(device, inFlightFences[i], nullptr);
1953 }
1954
1955 vkDestroyCommandPool(device, commandPool, nullptr);
1956 vkDestroyDevice(device, nullptr);
1957 vkDestroySurfaceKHR(instance, surface, nullptr);
1958
1959 if (enableValidationLayers) {
1960 DestroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
1961 }
1962
1963 vkDestroyInstance(instance, nullptr);
1964
1965 // TODO: Check if any of these functions accept null parameters
1966 // If they do, I don't need to check for that
1967
1968 if (uiOverlay != nullptr) {
1969 SDL_DestroyTexture(uiOverlay);
1970 uiOverlay = nullptr;
1971 }
1972/*** END OF REFACTORED CODE ***/
1973
1974 TTF_CloseFont(gFont);
1975 gFont = nullptr;
1976
1977 if (uiText != nullptr) {
1978 SDL_DestroyTexture(uiText);
1979 uiText = nullptr;
1980 }
1981
1982 if (uiImage != nullptr) {
1983 SDL_DestroyTexture(uiImage);
1984 uiImage = nullptr;
1985 }
1986
1987/*** START OF REFACTORED CODE ***/
1988 SDL_DestroyRenderer(gRenderer);
1989 gRenderer = nullptr;
1990
1991 gui->destroyWindow();
1992 gui->shutdown();
1993 delete gui;
1994 }
1995
1996 void cleanupSwapChain() {
1997 vkDestroyImageView(device, depthImageView, nullptr);
1998 vkDestroyImage(device, depthImage, nullptr);
1999 vkFreeMemory(device, depthImageMemory, nullptr);
2000
2001 for (auto framebuffer : swapChainFramebuffers) {
2002 vkDestroyFramebuffer(device, framebuffer, nullptr);
2003 }
2004
2005 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
2006
2007 cleanupPipeline(scenePipeline);
2008 cleanupPipeline(overlayPipeline);
2009
2010 vkDestroyRenderPass(device, renderPass, nullptr);
2011
2012 for (auto imageView : swapChainImageViews) {
2013 vkDestroyImageView(device, imageView, nullptr);
2014 }
2015
2016 vkDestroySwapchainKHR(device, swapChain, nullptr);
2017
2018 for (size_t i = 0; i < swapChainImages.size(); i++) {
2019 vkDestroyBuffer(device, uniformBuffers[i], nullptr);
2020 vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
2021 }
2022 }
2023
2024 void cleanupPipeline(GraphicsPipelineInfo& pipeline) {
2025 vkDestroyPipeline(device, pipeline.pipeline, nullptr);
2026 vkDestroyDescriptorPool(device, pipeline.descriptorPool, nullptr);
2027 vkDestroyPipelineLayout(device, pipeline.pipelineLayout, nullptr);
2028 }
2029
2030 void cleanupPipelineBuffers(GraphicsPipelineInfo& pipeline) {
2031 vkDestroyDescriptorSetLayout(device, pipeline.descriptorSetLayout, nullptr);
2032
2033 vkDestroyBuffer(device, pipeline.vertexBuffer, nullptr);
2034 vkFreeMemory(device, pipeline.vertexBufferMemory, nullptr);
2035 vkDestroyBuffer(device, pipeline.indexBuffer, nullptr);
2036 vkFreeMemory(device, pipeline.indexBufferMemory, nullptr);
2037 }
2038
2039 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
2040 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
2041 VkDebugUtilsMessageTypeFlagsEXT messageType,
2042 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
2043 void* pUserData) {
2044 cerr << "validation layer: " << pCallbackData->pMessage << endl;
2045
2046 return VK_FALSE;
2047 }
2048
2049 static vector<char> readFile(const string& filename) {
2050 ifstream file(filename, ios::ate | ios::binary);
2051
2052 if (!file.is_open()) {
2053 throw runtime_error("failed to open file!");
2054 }
2055
2056 size_t fileSize = (size_t) file.tellg();
2057 vector<char> buffer(fileSize);
2058
2059 file.seekg(0);
2060 file.read(buffer.data(), fileSize);
2061
2062 file.close();
2063
2064 return buffer;
2065 }
2066};
2067
2068int main(int argc, char* argv[]) {
2069
2070#ifdef NDEBUG
2071 cout << "DEBUGGING IS OFF" << endl;
2072#else
2073 cout << "DEBUGGING IS ON" << endl;
2074#endif
2075
2076 cout << "Starting Vulkan game..." << endl;
2077
2078 VulkanGame game;
2079
2080 try {
2081 game.run();
2082 } catch (const exception& e) {
2083 cerr << e.what() << endl;
2084 return EXIT_FAILURE;
2085 }
2086
2087 cout << "Finished running the game" << endl;
2088
2089 return EXIT_SUCCESS;
2090}
2091/*** END OF REFACTORED CODE ***/
Note: See TracBrowser for help on using the repository browser.