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

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

Expand on the upgrade TODO list and remove game-gui-glfw as a dependency from vulkangame and spacegame

  • 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-sdl.hpp"
24
25using namespace std;
26using namespace glm;
27
28const int SCREEN_WIDTH = 800;
29const int SCREEN_HEIGHT = 600;
30
31const int MAX_FRAMES_IN_FLIGHT = 2;
32
33#ifdef NDEBUG
34 const bool enableValidationLayers = false;
35#else
36 const bool enableValidationLayers = true;
37#endif
38
39const vector<const char*> validationLayers = {
40 "VK_LAYER_KHRONOS_validation"
41};
42
43const vector<const char*> deviceExtensions = {
44 VK_KHR_SWAPCHAIN_EXTENSION_NAME
45};
46
47struct QueueFamilyIndices {
48 optional<uint32_t> graphicsFamily;
49 optional<uint32_t> presentFamily;
50
51 bool isComplete() {
52 return graphicsFamily.has_value() && presentFamily.has_value();
53 }
54};
55
56struct SwapChainSupportDetails {
57 VkSurfaceCapabilitiesKHR capabilities;
58 vector<VkSurfaceFormatKHR> formats;
59 vector<VkPresentModeKHR> presentModes;
60};
61
62struct Vertex {
63 glm::vec3 pos;
64 glm::vec3 color;
65 glm::vec2 texCoord;
66};
67
68struct OverlayVertex {
69 glm::vec3 pos;
70 glm::vec2 texCoord;
71};
72
73struct UniformBufferObject {
74 alignas(16) mat4 model;
75 alignas(16) mat4 view;
76 alignas(16) mat4 proj;
77};
78
79struct DescriptorInfo {
80 VkDescriptorType type;
81 VkShaderStageFlags stageFlags;
82
83 vector<VkDescriptorBufferInfo>* bufferDataList;
84 VkDescriptorImageInfo* imageData;
85};
86
87struct GraphicsPipelineInfo {
88 VkPipelineLayout pipelineLayout;
89 VkPipeline pipeline;
90
91 VkVertexInputBindingDescription bindingDescription;
92 vector<VkVertexInputAttributeDescription> attributeDescriptions;
93
94 vector<DescriptorInfo> descriptorInfoList;
95
96 VkDescriptorPool descriptorPool;
97 VkDescriptorSetLayout descriptorSetLayout;
98 vector<VkDescriptorSet> descriptorSets;
99
100 size_t numVertices; // Currently unused
101 VkBuffer vertexBuffer;
102 VkDeviceMemory vertexBufferMemory;
103
104 size_t numIndices;
105 VkBuffer indexBuffer;
106 VkDeviceMemory indexBufferMemory;
107};
108
109VkResult CreateDebugUtilsMessengerEXT(VkInstance instance,
110 const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
111 const VkAllocationCallbacks* pAllocator,
112 VkDebugUtilsMessengerEXT* pDebugMessenger) {
113 auto func = (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
114
115 if (func != nullptr) {
116 return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
117 } else {
118 return VK_ERROR_EXTENSION_NOT_PRESENT;
119 }
120}
121
122void DestroyDebugUtilsMessengerEXT(VkInstance instance,
123 VkDebugUtilsMessengerEXT debugMessenger,
124 const VkAllocationCallbacks* pAllocator) {
125 auto func = (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
126
127 if (func != nullptr) {
128 func(instance, debugMessenger, pAllocator);
129 }
130}
131
132class VulkanGame {
133 public:
134 void run() {
135 if (initWindow() == RTWO_ERROR) {
136 return;
137 }
138 initVulkan();
139 mainLoop();
140 cleanup();
141 }
142
143 private:
144 GameGui* gui = new GameGui_SDL();
145 SDL_version sdlVersion;
146 SDL_Window* window = nullptr;
147
148 // TODO: Come up with more descriptive names for these
149 SDL_Renderer* gRenderer = nullptr;
150 SDL_Texture* uiOverlay = nullptr;
151
152 TTF_Font* gFont = nullptr;
153 SDL_Texture* uiText = nullptr;
154 SDL_Texture* uiImage = nullptr;
155
156 VkInstance instance;
157 VkDebugUtilsMessengerEXT debugMessenger;
158 VkSurfaceKHR surface;
159
160 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
161 VkDevice device;
162
163 VkQueue graphicsQueue;
164 VkQueue presentQueue;
165
166 VkSwapchainKHR swapChain;
167 vector<VkImage> swapChainImages;
168 VkFormat swapChainImageFormat;
169 VkExtent2D swapChainExtent;
170 vector<VkImageView> swapChainImageViews;
171 vector<VkFramebuffer> swapChainFramebuffers;
172
173 VkRenderPass renderPass;
174
175 VkCommandPool commandPool;
176 vector<VkCommandBuffer> commandBuffers;
177
178 // The images and the sampler are used to store data for specific attributes. I probably
179 // want to keep them separate from the GraphicsPipelineInfo objects and start passing
180 // references to them once I start defining uniform and varying attributes in GraphicsPipelineInfo objects
181
182 VkImage depthImage;
183 VkDeviceMemory depthImageMemory;
184 VkImageView depthImageView;
185
186 VkImage textureImage;
187 VkDeviceMemory textureImageMemory;
188 VkImageView textureImageView;
189
190 VkImage overlayImage;
191 VkDeviceMemory overlayImageMemory;
192 VkImageView overlayImageView;
193
194 VkImage sdlOverlayImage;
195 VkDeviceMemory sdlOverlayImageMemory;
196 VkImageView sdlOverlayImageView;
197
198 VkSampler textureSampler;
199
200 // These are currently to store the MVP matrix
201 // I should figure out if it makes sense to use them for other uniforms in the future
202 // If not, I should rename them to better indicate their puprose.
203 // I should also decide if I can use these for all shaders, or if I need a separapte set of buffers for each one
204 vector<VkBuffer> uniformBuffers;
205 vector<VkDeviceMemory> uniformBuffersMemory;
206
207 VkDescriptorImageInfo sceneImageInfo;
208 VkDescriptorImageInfo overlayImageInfo;
209
210 vector<VkDescriptorBufferInfo> uniformBufferInfoList;
211
212 GraphicsPipelineInfo scenePipeline;
213 GraphicsPipelineInfo overlayPipeline;
214
215 vector<VkSemaphore> imageAvailableSemaphores;
216 vector<VkSemaphore> renderFinishedSemaphores;
217 vector<VkFence> inFlightFences;
218
219 size_t currentFrame = 0;
220
221 bool framebufferResized = false;
222
223 // TODO: Make make some more initi functions, or call this initUI if the
224 // amount of things initialized here keeps growing
225 bool initWindow() {
226 // TODO: Put all fonts, textures, and images in the assets folder
227
228 if (gui->Init() == RTWO_ERROR) {
229 cout << "UI library could not be initialized!" << endl;
230 cout << SDL_GetError() << endl;
231 return RTWO_ERROR;
232 }
233 cout << "GUI init succeeded" << endl;
234
235 window = (SDL_Window*) gui->CreateWindow("Vulkan Game", SCREEN_WIDTH, SCREEN_HEIGHT);
236 if (window == nullptr) {
237 cout << "Window could not be created!" << endl;
238 return RTWO_ERROR;
239 }
240
241 gRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
242 if (gRenderer == nullptr) {
243 cout << "Renderer could not be created! SDL Error: " << SDL_GetError() << endl;
244 return RTWO_ERROR;
245 }
246
247 SDL_VERSION(&sdlVersion);
248
249 // In SDL 2.0.10 (currently, the latest), SDL_TEXTUREACCESS_TARGET is required to get a transparent overlay working
250 // However, the latest SDL version available through homebrew on Mac is 2.0.9, which requires SDL_TEXTUREACCESS_STREAMING
251 // 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
252 // until the homebrew recipe is updated
253 if (sdlVersion.major == 2 && sdlVersion.minor == 0 && sdlVersion.patch == 9) {
254 uiOverlay = SDL_CreateTexture(gRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT);
255 } else {
256 uiOverlay = SDL_CreateTexture(gRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT);
257 }
258
259 if (uiOverlay == nullptr) {
260 cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << endl;
261 }
262 if (SDL_SetTextureBlendMode(uiOverlay, SDL_BLENDMODE_BLEND) != 0) {
263 cout << "Unable to set texture blend mode! SDL Error: " << SDL_GetError() << endl;
264 }
265
266 gFont = TTF_OpenFont("fonts/lazy.ttf", 28);
267 if (gFont == nullptr) {
268 cout << "Failed to load lazy font! SDL_ttf Error: " << TTF_GetError() << endl;
269 return RTWO_ERROR;
270 }
271
272 SDL_Color textColor = { 0, 0, 0 };
273
274 SDL_Surface* textSurface = TTF_RenderText_Solid(gFont, "Great sucess!", textColor);
275 if (textSurface == nullptr) {
276 cout << "Unable to render text surface! SDL_ttf Error: " << TTF_GetError() << endl;
277 return RTWO_ERROR;
278 }
279
280 uiText = SDL_CreateTextureFromSurface(gRenderer, textSurface);
281 if (uiText == nullptr) {
282 cout << "Unable to create texture from rendered text! SDL Error: " << SDL_GetError() << endl;
283 SDL_FreeSurface(textSurface);
284 return RTWO_ERROR;
285 }
286
287 SDL_FreeSurface(textSurface);
288
289 // TODO: Load a PNG instead
290 SDL_Surface* uiImageSurface = SDL_LoadBMP("assets/images/spaceship.bmp");
291 if (uiImageSurface == nullptr) {
292 cout << "Unable to load image " << "spaceship.bmp" << "! SDL Error: " << SDL_GetError() << endl;
293 return RTWO_ERROR;
294 }
295
296 uiImage = SDL_CreateTextureFromSurface(gRenderer, uiImageSurface);
297 if (uiImage == nullptr) {
298 cout << "Unable to create texture from BMP surface! SDL Error: " << SDL_GetError() << endl;
299 SDL_FreeSurface(uiImageSurface);
300 return RTWO_ERROR;
301 }
302
303 SDL_FreeSurface(uiImageSurface);
304
305 return RTWO_SUCCESS;
306 }
307
308 void initVulkan() {
309 createInstance();
310 setupDebugMessenger();
311 createSurface();
312 pickPhysicalDevice();
313 createLogicalDevice();
314 createSwapChain();
315 createImageViews();
316 createRenderPass();
317
318 createCommandPool();
319
320 createImageResources("textures/texture.jpg", textureImage, textureImageMemory, textureImageView);
321 createImageResourcesFromSDLTexture(uiOverlay, sdlOverlayImage, sdlOverlayImageMemory, sdlOverlayImageView);
322 createTextureSampler();
323
324 sceneImageInfo = {};
325 sceneImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
326 sceneImageInfo.imageView = textureImageView;
327 sceneImageInfo.sampler = textureSampler;
328
329 overlayImageInfo = {};
330 overlayImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
331 overlayImageInfo.imageView = sdlOverlayImageView;
332 overlayImageInfo.sampler = textureSampler;
333
334 vector<Vertex> sceneVertices = {
335 {{-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
336 {{ 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
337 {{ 0.5f, 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
338 {{-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}},
339
340 {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
341 {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
342 {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
343 {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
344 };
345 vector<uint16_t> sceneIndices = {
346 0, 1, 2, 2, 3, 0,
347 4, 5, 6, 6, 7, 4
348 };
349
350 initGraphicsPipelineInfo(scenePipeline,
351 sceneVertices.data(), sizeof(Vertex), sceneVertices.size(),
352 sceneIndices.data(), sizeof(uint16_t), sceneIndices.size());
353
354 addAttributeDescription(scenePipeline, VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::pos));
355 addAttributeDescription(scenePipeline, VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::color));
356 addAttributeDescription(scenePipeline, VK_FORMAT_R32G32_SFLOAT, offset_of(&Vertex::texCoord));
357
358 addDescriptorInfo(scenePipeline, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, &uniformBufferInfoList, nullptr);
359 addDescriptorInfo(scenePipeline, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr, &sceneImageInfo);
360
361 createDescriptorSetLayout(scenePipeline);
362
363
364 vector<OverlayVertex> overlayVertices = {
365 {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}},
366 {{ 1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
367 {{ 1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}},
368 {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}}
369 };
370 vector<uint16_t> overlayIndices = {
371 0, 1, 2, 2, 3, 0
372 };
373
374 initGraphicsPipelineInfo(overlayPipeline,
375 overlayVertices.data(), sizeof(OverlayVertex), overlayVertices.size(),
376 overlayIndices.data(), sizeof(uint16_t), overlayIndices.size());
377
378 addAttributeDescription(overlayPipeline, VK_FORMAT_R32G32B32_SFLOAT, offset_of(&OverlayVertex::pos));
379 addAttributeDescription(overlayPipeline, VK_FORMAT_R32G32_SFLOAT, offset_of(&OverlayVertex::texCoord));
380
381 addDescriptorInfo(overlayPipeline, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr, &overlayImageInfo);
382
383 createDescriptorSetLayout(overlayPipeline);
384
385 createBufferResources();
386
387 createSyncObjects();
388 }
389
390 void createInstance() {
391 if (enableValidationLayers && !checkValidationLayerSupport()) {
392 throw runtime_error("validation layers requested, but not available!");
393 }
394
395 VkApplicationInfo appInfo = {};
396 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
397 appInfo.pApplicationName = "Vulkan Game";
398 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
399 appInfo.pEngineName = "No Engine";
400 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
401 appInfo.apiVersion = VK_API_VERSION_1_0;
402
403 VkInstanceCreateInfo createInfo = {};
404 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
405 createInfo.pApplicationInfo = &appInfo;
406
407 vector<const char*> extensions = getRequiredExtensions();
408 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
409 createInfo.ppEnabledExtensionNames = extensions.data();
410
411 cout << endl << "Extensions:" << endl;
412 for (const char* extensionName : extensions) {
413 cout << extensionName << endl;
414 }
415 cout << endl;
416
417 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
418 if (enableValidationLayers) {
419 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
420 createInfo.ppEnabledLayerNames = validationLayers.data();
421
422 populateDebugMessengerCreateInfo(debugCreateInfo);
423 createInfo.pNext = &debugCreateInfo;
424 } else {
425 createInfo.enabledLayerCount = 0;
426
427 createInfo.pNext = nullptr;
428 }
429
430 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
431 throw runtime_error("failed to create instance!");
432 }
433 }
434
435 bool checkValidationLayerSupport() {
436 uint32_t layerCount;
437 vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
438
439 vector<VkLayerProperties> availableLayers(layerCount);
440 vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
441
442 for (const char* layerName : validationLayers) {
443 bool layerFound = false;
444
445 for (const auto& layerProperties : availableLayers) {
446 if (strcmp(layerName, layerProperties.layerName) == 0) {
447 layerFound = true;
448 break;
449 }
450 }
451
452 if (!layerFound) {
453 return false;
454 }
455 }
456
457 return true;
458 }
459
460 vector<const char*> getRequiredExtensions() {
461 vector<const char*> extensions = gui->GetRequiredExtensions();
462
463 if (enableValidationLayers) {
464 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
465 }
466
467 return extensions;
468 }
469
470 void setupDebugMessenger() {
471 if (!enableValidationLayers) return;
472
473 VkDebugUtilsMessengerCreateInfoEXT createInfo;
474 populateDebugMessengerCreateInfo(createInfo);
475
476 if (CreateDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
477 throw runtime_error("failed to set up debug messenger!");
478 }
479 }
480
481 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
482 createInfo = {};
483 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
484 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;
485 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;
486 createInfo.pfnUserCallback = debugCallback;
487 }
488
489 void createSurface() {
490 if (gui->CreateVulkanSurface(instance, &surface) == RTWO_ERROR) {
491 throw runtime_error("failed to create window surface!");
492 }
493 }
494
495 void pickPhysicalDevice() {
496 uint32_t deviceCount = 0;
497 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
498
499 if (deviceCount == 0) {
500 throw runtime_error("failed to find GPUs with Vulkan support!");
501 }
502
503 vector<VkPhysicalDevice> devices(deviceCount);
504 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
505
506 cout << endl << "Graphics cards:" << endl;
507 for (const VkPhysicalDevice& device : devices) {
508 if (isDeviceSuitable(device)) {
509 physicalDevice = device;
510 break;
511 }
512 }
513 cout << endl;
514
515 if (physicalDevice == VK_NULL_HANDLE) {
516 throw runtime_error("failed to find a suitable GPU!");
517 }
518 }
519
520 bool isDeviceSuitable(VkPhysicalDevice device) {
521 VkPhysicalDeviceProperties deviceProperties;
522 vkGetPhysicalDeviceProperties(device, &deviceProperties);
523
524 cout << "Device: " << deviceProperties.deviceName << endl;
525
526 QueueFamilyIndices indices = findQueueFamilies(device);
527 bool extensionsSupported = checkDeviceExtensionSupport(device);
528 bool swapChainAdequate = false;
529
530 if (extensionsSupported) {
531 SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device);
532 swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
533 }
534
535 VkPhysicalDeviceFeatures supportedFeatures;
536 vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
537
538 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
539 }
540
541 bool checkDeviceExtensionSupport(VkPhysicalDevice device) {
542 uint32_t extensionCount;
543 vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
544
545 vector<VkExtensionProperties> availableExtensions(extensionCount);
546 vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
547
548 set<string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
549
550 for (const auto& extension : availableExtensions) {
551 requiredExtensions.erase(extension.extensionName);
552 }
553
554 return requiredExtensions.empty();
555 }
556
557 void createLogicalDevice() {
558 QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
559
560 vector<VkDeviceQueueCreateInfo> queueCreateInfos;
561 set<uint32_t> uniqueQueueFamilies = {indices.graphicsFamily.value(), indices.presentFamily.value()};
562
563 float queuePriority = 1.0f;
564 for (uint32_t queueFamily : uniqueQueueFamilies) {
565 VkDeviceQueueCreateInfo queueCreateInfo = {};
566 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
567 queueCreateInfo.queueFamilyIndex = queueFamily;
568 queueCreateInfo.queueCount = 1;
569 queueCreateInfo.pQueuePriorities = &queuePriority;
570
571 queueCreateInfos.push_back(queueCreateInfo);
572 }
573
574 VkPhysicalDeviceFeatures deviceFeatures = {};
575 deviceFeatures.samplerAnisotropy = VK_TRUE;
576
577 VkDeviceCreateInfo createInfo = {};
578 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
579 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
580 createInfo.pQueueCreateInfos = queueCreateInfos.data();
581
582 createInfo.pEnabledFeatures = &deviceFeatures;
583
584 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
585 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
586
587 // These fields are ignored by up-to-date Vulkan implementations,
588 // but it's a good idea to set them for backwards compatibility
589 if (enableValidationLayers) {
590 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
591 createInfo.ppEnabledLayerNames = validationLayers.data();
592 } else {
593 createInfo.enabledLayerCount = 0;
594 }
595
596 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
597 throw runtime_error("failed to create logical device!");
598 }
599
600 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
601 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
602 }
603
604 void createSwapChain() {
605 SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
606
607 VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
608 VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
609 VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
610
611 uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
612 if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
613 imageCount = swapChainSupport.capabilities.maxImageCount;
614 }
615
616 VkSwapchainCreateInfoKHR createInfo = {};
617 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
618 createInfo.surface = surface;
619 createInfo.minImageCount = imageCount;
620 createInfo.imageFormat = surfaceFormat.format;
621 createInfo.imageColorSpace = surfaceFormat.colorSpace;
622 createInfo.imageExtent = extent;
623 createInfo.imageArrayLayers = 1;
624 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
625
626 QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
627 uint32_t queueFamilyIndices[] = {indices.graphicsFamily.value(), indices.presentFamily.value()};
628
629 if (indices.graphicsFamily != indices.presentFamily) {
630 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
631 createInfo.queueFamilyIndexCount = 2;
632 createInfo.pQueueFamilyIndices = queueFamilyIndices;
633 } else {
634 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
635 createInfo.queueFamilyIndexCount = 0;
636 createInfo.pQueueFamilyIndices = nullptr;
637 }
638
639 createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
640 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
641 createInfo.presentMode = presentMode;
642 createInfo.clipped = VK_TRUE;
643 createInfo.oldSwapchain = VK_NULL_HANDLE;
644
645 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
646 throw runtime_error("failed to create swap chain!");
647 }
648
649 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
650 swapChainImages.resize(imageCount);
651 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
652
653 swapChainImageFormat = surfaceFormat.format;
654 swapChainExtent = extent;
655 }
656
657 SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device) {
658 SwapChainSupportDetails details;
659
660 vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
661
662 uint32_t formatCount;
663 vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
664
665 if (formatCount != 0) {
666 details.formats.resize(formatCount);
667 vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
668 }
669
670 uint32_t presentModeCount;
671 vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
672
673 if (presentModeCount != 0) {
674 details.presentModes.resize(presentModeCount);
675 vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
676 }
677
678 return details;
679 }
680
681 VkSurfaceFormatKHR chooseSwapSurfaceFormat(const vector<VkSurfaceFormatKHR>& availableFormats) {
682 for (const auto& availableFormat : availableFormats) {
683 if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
684 return availableFormat;
685 }
686 }
687
688 return availableFormats[0];
689 }
690
691 VkPresentModeKHR chooseSwapPresentMode(const vector<VkPresentModeKHR>& availablePresentModes) {
692 VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR;
693
694 for (const auto& availablePresentMode : availablePresentModes) {
695 if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
696 return availablePresentMode;
697 }
698 else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
699 bestMode = availablePresentMode;
700 }
701 }
702
703 return bestMode;
704 }
705
706 VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) {
707 if (capabilities.currentExtent.width != numeric_limits<uint32_t>::max()) {
708 return capabilities.currentExtent;
709 }
710 else {
711 int width, height;
712 gui->GetWindowSize(&width, &height);
713
714 VkExtent2D actualExtent = {
715 static_cast<uint32_t>(width),
716 static_cast<uint32_t>(height)
717 };
718
719 actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width));
720 actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height));
721
722 return actualExtent;
723 }
724 }
725
726 void createImageViews() {
727 swapChainImageViews.resize(swapChainImages.size());
728
729 for (size_t i = 0; i < swapChainImages.size(); i++) {
730 swapChainImageViews[i] = createImageView(swapChainImages[i], swapChainImageFormat, VK_IMAGE_ASPECT_COLOR_BIT);
731 }
732 }
733
734 void createRenderPass() {
735 VkAttachmentDescription colorAttachment = {};
736 colorAttachment.format = swapChainImageFormat;
737 colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
738 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
739 colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
740 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
741 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
742 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
743 colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
744
745 VkAttachmentReference colorAttachmentRef = {};
746 colorAttachmentRef.attachment = 0;
747 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
748
749 VkAttachmentDescription depthAttachment = {};
750 depthAttachment.format = findDepthFormat();
751 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
752 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
753 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
754 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
755 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
756 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
757 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
758
759 VkAttachmentReference depthAttachmentRef = {};
760 depthAttachmentRef.attachment = 1;
761 depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
762
763 VkSubpassDescription subpass = {};
764 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
765 subpass.colorAttachmentCount = 1;
766 subpass.pColorAttachments = &colorAttachmentRef;
767 subpass.pDepthStencilAttachment = &depthAttachmentRef;
768
769 VkSubpassDependency dependency = {};
770 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
771 dependency.dstSubpass = 0;
772 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
773 dependency.srcAccessMask = 0;
774 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
775 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
776
777 array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
778 VkRenderPassCreateInfo renderPassInfo = {};
779 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
780 renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
781 renderPassInfo.pAttachments = attachments.data();
782 renderPassInfo.subpassCount = 1;
783 renderPassInfo.pSubpasses = &subpass;
784 renderPassInfo.dependencyCount = 1;
785 renderPassInfo.pDependencies = &dependency;
786
787 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
788 throw runtime_error("failed to create render pass!");
789 }
790 }
791
792 void initGraphicsPipelineInfo(GraphicsPipelineInfo& info,
793 const void* vertexData, int vertexSize, size_t numVertices,
794 const void* indexData, int indexSize, size_t numIndices) {
795 // Since there is only one array of vertex data, we use binding = 0
796 // I'll probably do that for the foreseeable future
797 // I can calculate the stride myself given info about all the varying attributes
798
799 info.bindingDescription.binding = 0;
800 info.bindingDescription.stride = vertexSize;
801 info.bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
802
803 info.numVertices = numVertices;
804 createVertexBuffer(info, vertexData, vertexSize * numVertices);
805
806 info.numIndices = numIndices;
807 createIndexBuffer(info, indexData, indexSize * numIndices);
808 }
809
810 void addAttributeDescription(GraphicsPipelineInfo& info, VkFormat format, size_t offset) {
811 VkVertexInputAttributeDescription attributeDesc = {};
812
813 attributeDesc.binding = 0;
814 attributeDesc.location = info.attributeDescriptions.size();
815 attributeDesc.format = format;
816 attributeDesc.offset = offset;
817
818 info.attributeDescriptions.push_back(attributeDesc);
819 }
820
821 void addDescriptorInfo(GraphicsPipelineInfo& info, VkDescriptorType type, VkShaderStageFlags stageFlags, vector<VkDescriptorBufferInfo>* bufferData, VkDescriptorImageInfo* imageData) {
822 info.descriptorInfoList.push_back({ type, stageFlags, bufferData, imageData });
823 }
824
825 void createDescriptorSetLayout(GraphicsPipelineInfo& info) {
826 vector<VkDescriptorSetLayoutBinding> bindings(info.descriptorInfoList.size());
827
828 for (size_t i = 0; i < bindings.size(); i++) {
829 bindings[i].binding = i;
830 bindings[i].descriptorCount = 1;
831 bindings[i].descriptorType = info.descriptorInfoList[i].type;
832 bindings[i].stageFlags = info.descriptorInfoList[i].stageFlags;
833 bindings[i].pImmutableSamplers = nullptr;
834 }
835
836 VkDescriptorSetLayoutCreateInfo layoutInfo = {};
837 layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
838 layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
839 layoutInfo.pBindings = bindings.data();
840
841 if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &info.descriptorSetLayout) != VK_SUCCESS) {
842 throw runtime_error("failed to create descriptor set layout!");
843 }
844 }
845
846 void createGraphicsPipeline(string vertShaderFile, string fragShaderFile, GraphicsPipelineInfo& info) {
847 auto vertShaderCode = readFile(vertShaderFile);
848 auto fragShaderCode = readFile(fragShaderFile);
849
850 VkShaderModule vertShaderModule = createShaderModule(vertShaderCode);
851 VkShaderModule fragShaderModule = createShaderModule(fragShaderCode);
852
853 VkPipelineShaderStageCreateInfo vertShaderStageInfo = {};
854 vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
855 vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
856 vertShaderStageInfo.module = vertShaderModule;
857 vertShaderStageInfo.pName = "main";
858
859 VkPipelineShaderStageCreateInfo fragShaderStageInfo = {};
860 fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
861 fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
862 fragShaderStageInfo.module = fragShaderModule;
863 fragShaderStageInfo.pName = "main";
864
865 VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo };
866
867 VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
868 vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
869
870 vertexInputInfo.vertexBindingDescriptionCount = 1;
871 vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(info.attributeDescriptions.size());
872 vertexInputInfo.pVertexBindingDescriptions = &info.bindingDescription;
873 vertexInputInfo.pVertexAttributeDescriptions = info.attributeDescriptions.data();
874
875 VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
876 inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
877 inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
878 inputAssembly.primitiveRestartEnable = VK_FALSE;
879
880 VkViewport viewport = {};
881 viewport.x = 0.0f;
882 viewport.y = 0.0f;
883 viewport.width = (float) swapChainExtent.width;
884 viewport.height = (float) swapChainExtent.height;
885 viewport.minDepth = 0.0f;
886 viewport.maxDepth = 1.0f;
887
888 VkRect2D scissor = {};
889 scissor.offset = { 0, 0 };
890 scissor.extent = swapChainExtent;
891
892 VkPipelineViewportStateCreateInfo viewportState = {};
893 viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
894 viewportState.viewportCount = 1;
895 viewportState.pViewports = &viewport;
896 viewportState.scissorCount = 1;
897 viewportState.pScissors = &scissor;
898
899 VkPipelineRasterizationStateCreateInfo rasterizer = {};
900 rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
901 rasterizer.depthClampEnable = VK_FALSE;
902 rasterizer.rasterizerDiscardEnable = VK_FALSE;
903 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
904 rasterizer.lineWidth = 1.0f;
905 rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
906 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
907 rasterizer.depthBiasEnable = VK_FALSE;
908
909 VkPipelineMultisampleStateCreateInfo multisampling = {};
910 multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
911 multisampling.sampleShadingEnable = VK_FALSE;
912 multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
913
914 VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
915 colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
916 colorBlendAttachment.blendEnable = VK_TRUE;
917 colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
918 colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
919 colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
920 colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
921 colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
922 colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
923
924 VkPipelineColorBlendStateCreateInfo colorBlending = {};
925 colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
926 colorBlending.logicOpEnable = VK_FALSE;
927 colorBlending.logicOp = VK_LOGIC_OP_COPY;
928 colorBlending.attachmentCount = 1;
929 colorBlending.pAttachments = &colorBlendAttachment;
930 colorBlending.blendConstants[0] = 0.0f;
931 colorBlending.blendConstants[1] = 0.0f;
932 colorBlending.blendConstants[2] = 0.0f;
933 colorBlending.blendConstants[3] = 0.0f;
934
935 VkPipelineDepthStencilStateCreateInfo depthStencil = {};
936 depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
937 depthStencil.depthTestEnable = VK_TRUE;
938 depthStencil.depthWriteEnable = VK_TRUE;
939 depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
940 depthStencil.depthBoundsTestEnable = VK_FALSE;
941 depthStencil.minDepthBounds = 0.0f;
942 depthStencil.maxDepthBounds = 1.0f;
943 depthStencil.stencilTestEnable = VK_FALSE;
944 depthStencil.front = {};
945 depthStencil.back = {};
946
947 VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
948 pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
949 pipelineLayoutInfo.setLayoutCount = 1;
950 pipelineLayoutInfo.pSetLayouts = &info.descriptorSetLayout;
951 pipelineLayoutInfo.pushConstantRangeCount = 0;
952
953 if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &info.pipelineLayout) != VK_SUCCESS) {
954 throw runtime_error("failed to create pipeline layout!");
955 }
956
957 VkGraphicsPipelineCreateInfo pipelineInfo = {};
958 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
959 pipelineInfo.stageCount = 2;
960 pipelineInfo.pStages = shaderStages;
961 pipelineInfo.pVertexInputState = &vertexInputInfo;
962 pipelineInfo.pInputAssemblyState = &inputAssembly;
963 pipelineInfo.pViewportState = &viewportState;
964 pipelineInfo.pRasterizationState = &rasterizer;
965 pipelineInfo.pMultisampleState = &multisampling;
966 pipelineInfo.pDepthStencilState = &depthStencil;
967 pipelineInfo.pColorBlendState = &colorBlending;
968 pipelineInfo.pDynamicState = nullptr;
969 pipelineInfo.layout = info.pipelineLayout;
970 pipelineInfo.renderPass = renderPass;
971 pipelineInfo.subpass = 0;
972 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
973 pipelineInfo.basePipelineIndex = -1;
974
975 if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &info.pipeline) != VK_SUCCESS) {
976 throw runtime_error("failed to create graphics pipeline!");
977 }
978
979 vkDestroyShaderModule(device, vertShaderModule, nullptr);
980 vkDestroyShaderModule(device, fragShaderModule, nullptr);
981 }
982
983 VkShaderModule createShaderModule(const vector<char>& code) {
984 VkShaderModuleCreateInfo createInfo = {};
985 createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
986 createInfo.codeSize = code.size();
987 createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data());
988
989 VkShaderModule shaderModule;
990 if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
991 throw runtime_error("failed to create shader module!");
992 }
993
994 return shaderModule;
995 }
996
997 void createFramebuffers() {
998 swapChainFramebuffers.resize(swapChainImageViews.size());
999
1000 for (size_t i = 0; i < swapChainImageViews.size(); i++) {
1001 array <VkImageView, 2> attachments = {
1002 swapChainImageViews[i],
1003 depthImageView
1004 };
1005
1006 VkFramebufferCreateInfo framebufferInfo = {};
1007 framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1008 framebufferInfo.renderPass = renderPass;
1009 framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
1010 framebufferInfo.pAttachments = attachments.data();
1011 framebufferInfo.width = swapChainExtent.width;
1012 framebufferInfo.height = swapChainExtent.height;
1013 framebufferInfo.layers = 1;
1014
1015 if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
1016 throw runtime_error("failed to create framebuffer!");
1017 }
1018 }
1019 }
1020
1021 void createCommandPool() {
1022 QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
1023
1024 VkCommandPoolCreateInfo poolInfo = {};
1025 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1026 poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
1027 poolInfo.flags = 0;
1028
1029 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
1030 throw runtime_error("failed to create graphics command pool!");
1031 }
1032 }
1033
1034 QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) {
1035 QueueFamilyIndices indices;
1036
1037 uint32_t queueFamilyCount = 0;
1038 vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
1039
1040 vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
1041 vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
1042
1043 int i = 0;
1044 for (const auto& queueFamily : queueFamilies) {
1045 if (queueFamily.queueCount > 0 && queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
1046 indices.graphicsFamily = i;
1047 }
1048
1049 VkBool32 presentSupport = false;
1050 vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
1051
1052 if (queueFamily.queueCount > 0 && presentSupport) {
1053 indices.presentFamily = i;
1054 }
1055
1056 if (indices.isComplete()) {
1057 break;
1058 }
1059
1060 i++;
1061 }
1062
1063 return indices;
1064 }
1065
1066 void createDepthResources() {
1067 VkFormat depthFormat = findDepthFormat();
1068
1069 createImage(swapChainExtent.width, swapChainExtent.height, depthFormat, VK_IMAGE_TILING_OPTIMAL,
1070 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, depthImage, depthImageMemory);
1071 depthImageView = createImageView(depthImage, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT);
1072
1073 transitionImageLayout(depthImage, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
1074 }
1075
1076 VkFormat findDepthFormat() {
1077 return findSupportedFormat(
1078 { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
1079 VK_IMAGE_TILING_OPTIMAL,
1080 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
1081 );
1082 }
1083
1084 VkFormat findSupportedFormat(const vector<VkFormat>& candidates, VkImageTiling tiling,
1085 VkFormatFeatureFlags features) {
1086 for (VkFormat format : candidates) {
1087 VkFormatProperties props;
1088 vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &props);
1089
1090 if (tiling == VK_IMAGE_TILING_LINEAR &&
1091 (props.linearTilingFeatures & features) == features) {
1092 return format;
1093 } else if (tiling == VK_IMAGE_TILING_OPTIMAL &&
1094 (props.optimalTilingFeatures & features) == features) {
1095 return format;
1096 }
1097 }
1098
1099 throw runtime_error("failed to find supported format!");
1100 }
1101
1102 bool hasStencilComponent(VkFormat format) {
1103 return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT;
1104 }
1105
1106 void createImageResources(string filename, VkImage& image, VkDeviceMemory& imageMemory, VkImageView& view) {
1107 int texWidth, texHeight, texChannels;
1108
1109 stbi_uc* pixels = stbi_load(filename.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
1110 VkDeviceSize imageSize = texWidth * texHeight * 4;
1111
1112 if (!pixels) {
1113 throw runtime_error("failed to load texture image!");
1114 }
1115
1116 VkBuffer stagingBuffer;
1117 VkDeviceMemory stagingBufferMemory;
1118
1119 createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1120 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1121 stagingBuffer, stagingBufferMemory);
1122
1123 void* data;
1124
1125 vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &data);
1126 memcpy(data, pixels, static_cast<size_t>(imageSize));
1127 vkUnmapMemory(device, stagingBufferMemory);
1128
1129 stbi_image_free(pixels);
1130
1131 createImage(texWidth, texHeight, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
1132 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
1133 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image, imageMemory);
1134
1135 transitionImageLayout(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1136 copyBufferToImage(stagingBuffer, image, static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight));
1137 transitionImageLayout(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
1138
1139 vkDestroyBuffer(device, stagingBuffer, nullptr);
1140 vkFreeMemory(device, stagingBufferMemory, nullptr);
1141
1142 view = createImageView(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
1143 }
1144
1145 void createImageResourcesFromSDLTexture(SDL_Texture* texture, VkImage& image, VkDeviceMemory& imageMemory, VkImageView& view) {
1146 int a, w, h;
1147
1148 // I only need this here for the width and height, which are constants, so just use those instead
1149 SDL_QueryTexture(texture, nullptr, &a, &w, &h);
1150
1151 createImage(w, h, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
1152 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
1153 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image, imageMemory);
1154
1155 view = createImageView(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
1156 }
1157
1158 void populateImageFromSDLTexture(SDL_Texture* texture, VkImage& image) {
1159 int a, w, h;
1160
1161 SDL_QueryTexture(texture, nullptr, &a, &w, &h);
1162
1163 VkDeviceSize imageSize = w * h * 4;
1164 unsigned char* pixels = new unsigned char[imageSize];
1165
1166 SDL_RenderReadPixels(gRenderer, nullptr, SDL_PIXELFORMAT_ABGR8888, pixels, w * 4);
1167
1168 VkBuffer stagingBuffer;
1169 VkDeviceMemory stagingBufferMemory;
1170
1171 createBuffer(imageSize,
1172 VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1173 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
1174 stagingBuffer, stagingBufferMemory);
1175
1176 void* data;
1177
1178 vkMapMemory(device, stagingBufferMemory, 0, VK_WHOLE_SIZE, 0, &data);
1179 memcpy(data, pixels, static_cast<size_t>(imageSize));
1180
1181 VkMappedMemoryRange mappedMemoryRange = {};
1182 mappedMemoryRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1183 mappedMemoryRange.memory = stagingBufferMemory;
1184 mappedMemoryRange.offset = 0;
1185 mappedMemoryRange.size = VK_WHOLE_SIZE;
1186
1187 // TODO: Should probably check that the function succeeded
1188 vkFlushMappedMemoryRanges(device, 1, &mappedMemoryRange);
1189 vkUnmapMemory(device, stagingBufferMemory);
1190
1191 delete[] pixels;
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.