source: opengl-game/vulkan-game.cpp@ 721e8be

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

Add reusable functions that generate a descriptor set layout, a descriptor pool, and descriptor sets for a pipeline given a configuration for the pipeline's uniforms

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