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