[3b7d497] | 1 | #include "sdl-game.hpp"
|
---|
| 2 |
|
---|
[ce9dc9f] | 3 | #include <array>
|
---|
[3b7d497] | 4 | #include <iostream>
|
---|
| 5 | #include <set>
|
---|
| 6 |
|
---|
[ce9dc9f] | 7 | #include "IMGUI/imgui_impl_sdl.h"
|
---|
[3b7d497] | 8 |
|
---|
[ce9dc9f] | 9 | #include "logger.hpp"
|
---|
[4a777d2] | 10 | #include "utils.hpp"
|
---|
[3b7d497] | 11 |
|
---|
[85b5fec] | 12 | #include "gui/imgui/button-imgui.hpp"
|
---|
| 13 |
|
---|
[3b7d497] | 14 | using namespace std;
|
---|
| 15 |
|
---|
[ce9dc9f] | 16 | #define IMGUI_UNLIMITED_FRAME_RATE
|
---|
[3b7d497] | 17 |
|
---|
[8b823e7] | 18 | static void check_imgui_vk_result(VkResult res) {
|
---|
| 19 | if (res == VK_SUCCESS) {
|
---|
[3b7d497] | 20 | return;
|
---|
[ce9dc9f] | 21 | }
|
---|
[8b823e7] | 22 |
|
---|
| 23 | ostringstream oss;
|
---|
| 24 | oss << "[imgui] Vulkan error! VkResult is \"" << VulkanUtils::resultString(res) << "\"" << __LINE__;
|
---|
| 25 | if (res < 0) {
|
---|
| 26 | throw runtime_error("Fatal: " + oss.str());
|
---|
| 27 | } else {
|
---|
| 28 | cerr << oss.str();
|
---|
[ce9dc9f] | 29 | }
|
---|
[3b7d497] | 30 | }
|
---|
| 31 |
|
---|
| 32 | VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
|
---|
[737c26a] | 33 | VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
|
---|
| 34 | VkDebugUtilsMessageTypeFlagsEXT messageType,
|
---|
| 35 | const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
|
---|
| 36 | void* pUserData) {
|
---|
[3b7d497] | 37 | cerr << "validation layer: " << pCallbackData->pMessage << endl;
|
---|
| 38 |
|
---|
[737c26a] | 39 | // TODO: Figure out what the return value means and if it should always be VK_FALSE
|
---|
[3b7d497] | 40 | return VK_FALSE;
|
---|
| 41 | }
|
---|
| 42 |
|
---|
[7865c5b] | 43 | VulkanGame::VulkanGame()
|
---|
| 44 | : swapChainImageCount(0)
|
---|
| 45 | , swapChainMinImageCount(0)
|
---|
| 46 | , swapChainSurfaceFormat({})
|
---|
| 47 | , swapChainPresentMode(VK_PRESENT_MODE_MAX_ENUM_KHR)
|
---|
| 48 | , swapChainExtent{ 0, 0 }
|
---|
| 49 | , swapChain(VK_NULL_HANDLE)
|
---|
| 50 | , vulkanSurface(VK_NULL_HANDLE)
|
---|
| 51 | , sdlVersion({ 0, 0, 0 })
|
---|
| 52 | , instance(VK_NULL_HANDLE)
|
---|
| 53 | , physicalDevice(VK_NULL_HANDLE)
|
---|
| 54 | , device(VK_NULL_HANDLE)
|
---|
| 55 | , debugMessenger(VK_NULL_HANDLE)
|
---|
| 56 | , resourceCommandPool(VK_NULL_HANDLE)
|
---|
| 57 | , renderPass(VK_NULL_HANDLE)
|
---|
| 58 | , graphicsQueue(VK_NULL_HANDLE)
|
---|
| 59 | , presentQueue(VK_NULL_HANDLE)
|
---|
| 60 | , depthImage({})
|
---|
| 61 | , shouldRecreateSwapChain(false)
|
---|
| 62 | , frameCount(0)
|
---|
[e469aed] | 63 | , currentFrame(0)
|
---|
[7865c5b] | 64 | , imageIndex(0)
|
---|
| 65 | , fpsStartTime(0.0f)
|
---|
| 66 | , curTime(0.0f)
|
---|
| 67 | , done(false)
|
---|
| 68 | , currentRenderScreenFn(nullptr)
|
---|
[e469aed] | 69 | , imguiDescriptorPool(VK_NULL_HANDLE)
|
---|
[7865c5b] | 70 | , gui(nullptr)
|
---|
| 71 | , window(nullptr)
|
---|
[a3cefaa] | 72 | , objects_modelPipeline()
|
---|
[7865c5b] | 73 | , score(0)
|
---|
| 74 | , fps(0.0f) {
|
---|
[3b7d497] | 75 | }
|
---|
| 76 |
|
---|
| 77 | VulkanGame::~VulkanGame() {
|
---|
| 78 | }
|
---|
| 79 |
|
---|
| 80 | void VulkanGame::run(int width, int height, unsigned char guiFlags) {
|
---|
| 81 | cout << "Vulkan Game" << endl;
|
---|
| 82 |
|
---|
[b8072d3] | 83 | cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
|
---|
| 84 |
|
---|
[3b7d497] | 85 | if (initUI(width, height, guiFlags) == RTWO_ERROR) {
|
---|
| 86 | return;
|
---|
| 87 | }
|
---|
| 88 |
|
---|
| 89 | initVulkan();
|
---|
| 90 |
|
---|
[a3cefaa] | 91 | VkPhysicalDeviceProperties deviceProperties;
|
---|
| 92 | vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
|
---|
| 93 |
|
---|
[b7fc3c2] | 94 | objects_modelPipeline = VulkanBuffer<SSBO_ModelObject>(10, deviceProperties.limits.maxStorageBufferRange,
|
---|
| 95 | deviceProperties.limits.minStorageBufferOffsetAlignment);
|
---|
[a3cefaa] | 96 |
|
---|
[e469aed] | 97 | initImGuiOverlay();
|
---|
[3b7d497] | 98 |
|
---|
[4a777d2] | 99 | // TODO: Figure out how much of ubo creation and associated variables should be in the pipeline class
|
---|
| 100 | // Maybe combine the ubo-related objects into a new class
|
---|
| 101 |
|
---|
| 102 | initGraphicsPipelines();
|
---|
| 103 |
|
---|
| 104 | initMatrices();
|
---|
| 105 |
|
---|
| 106 | modelPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&ModelVertex::pos));
|
---|
| 107 | modelPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&ModelVertex::color));
|
---|
| 108 | modelPipeline.addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&ModelVertex::texCoord));
|
---|
| 109 | modelPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&ModelVertex::normal));
|
---|
| 110 | modelPipeline.addAttribute(VK_FORMAT_R32_UINT, offset_of(&ModelVertex::objIndex));
|
---|
| 111 |
|
---|
[9d21aac] | 112 | createBufferSet(sizeof(UBO_VP_mats),
|
---|
[6486ba8] | 113 | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
---|
| 114 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
---|
| 115 | uniformBuffers_modelPipeline);
|
---|
| 116 |
|
---|
| 117 | createBufferSet(objects_modelPipeline.capacity * sizeof(SSBO_ModelObject),
|
---|
| 118 | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT
|
---|
| 119 | | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
|
---|
| 120 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
---|
| 121 | storageBuffers_modelPipeline);
|
---|
[4a777d2] | 122 |
|
---|
| 123 | modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
|
---|
[c163d81] | 124 | VK_SHADER_STAGE_VERTEX_BIT, &uniformBuffers_modelPipeline.infoSet);
|
---|
[9d21aac] | 125 | modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
---|
[996dd3e] | 126 | VK_SHADER_STAGE_VERTEX_BIT, &storageBuffers_modelPipeline.infoSet);
|
---|
[4a777d2] | 127 | modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
---|
| 128 | VK_SHADER_STAGE_FRAGMENT_BIT, &floorTextureImageDescriptor);
|
---|
| 129 |
|
---|
[6486ba8] | 130 | SceneObject<ModelVertex>* texturedSquare = nullptr;
|
---|
[4a777d2] | 131 |
|
---|
| 132 | texturedSquare = &addObject(modelObjects, modelPipeline,
|
---|
| 133 | addObjectIndex<ModelVertex>(modelObjects.size(),
|
---|
| 134 | addVertexNormals<ModelVertex>({
|
---|
[6486ba8] | 135 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
|
---|
| 136 | {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
|
---|
| 137 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
|
---|
| 138 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
|
---|
| 139 | {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}},
|
---|
| 140 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}}
|
---|
[1abebc1] | 141 | })),
|
---|
| 142 | {
|
---|
| 143 | 0, 1, 2, 3, 4, 5
|
---|
[8dcbf62] | 144 | }, objects_modelPipeline, {
|
---|
[4a777d2] | 145 | mat4(1.0f)
|
---|
[1abebc1] | 146 | });
|
---|
[996dd3e] | 147 |
|
---|
[4a777d2] | 148 | texturedSquare->model_base =
|
---|
| 149 | translate(mat4(1.0f), vec3(0.0f, 0.0f, -2.0f));
|
---|
| 150 |
|
---|
| 151 | texturedSquare = &addObject(modelObjects, modelPipeline,
|
---|
| 152 | addObjectIndex<ModelVertex>(modelObjects.size(),
|
---|
| 153 | addVertexNormals<ModelVertex>({
|
---|
| 154 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
|
---|
| 155 | {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
|
---|
| 156 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
|
---|
| 157 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
|
---|
| 158 | {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}},
|
---|
| 159 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}}
|
---|
| 160 | })), {
|
---|
| 161 | 0, 1, 2, 3, 4, 5
|
---|
[8dcbf62] | 162 | }, objects_modelPipeline, {
|
---|
[4a777d2] | 163 | mat4(1.0f)
|
---|
[1abebc1] | 164 | });
|
---|
[996dd3e] | 165 |
|
---|
[4a777d2] | 166 | texturedSquare->model_base =
|
---|
| 167 | translate(mat4(1.0f), vec3(0.0f, 0.0f, -1.5f));
|
---|
| 168 |
|
---|
| 169 | modelPipeline.createDescriptorSetLayout();
|
---|
| 170 | modelPipeline.createPipeline("shaders/model-vert.spv", "shaders/model-frag.spv");
|
---|
[58453c3] | 171 | modelPipeline.createDescriptorPool(swapChainImages.size());
|
---|
| 172 | modelPipeline.createDescriptorSets(swapChainImages.size());
|
---|
[4a777d2] | 173 |
|
---|
[e469aed] | 174 | currentRenderScreenFn = &VulkanGame::renderMainScreen;
|
---|
[ce9dc9f] | 175 |
|
---|
| 176 | ImGuiIO& io = ImGui::GetIO();
|
---|
[6053b24] | 177 |
|
---|
[40eb092] | 178 | initGuiValueLists(valueLists);
|
---|
[6053b24] | 179 |
|
---|
[40eb092] | 180 | valueLists["stats value list"].push_back(UIValue(UIVALUE_INT, "Score", &score));
|
---|
| 181 | valueLists["stats value list"].push_back(UIValue(UIVALUE_DOUBLE, "FPS", &fps));
|
---|
| 182 | valueLists["stats value list"].push_back(UIValue(UIVALUE_DOUBLE, "IMGUI FPS", &io.Framerate));
|
---|
[3b7d497] | 183 |
|
---|
[40eb092] | 184 | renderLoop();
|
---|
[3b7d497] | 185 | cleanup();
|
---|
| 186 |
|
---|
| 187 | close_log();
|
---|
| 188 | }
|
---|
| 189 |
|
---|
| 190 | bool VulkanGame::initUI(int width, int height, unsigned char guiFlags) {
|
---|
| 191 | // TODO: Create a game-gui function to get the gui version and retrieve it that way
|
---|
| 192 |
|
---|
| 193 | SDL_VERSION(&sdlVersion); // This gets the compile-time version
|
---|
| 194 | SDL_GetVersion(&sdlVersion); // This gets the runtime version
|
---|
| 195 |
|
---|
| 196 | cout << "SDL " <<
|
---|
| 197 | to_string(sdlVersion.major) << "." <<
|
---|
| 198 | to_string(sdlVersion.minor) << "." <<
|
---|
| 199 | to_string(sdlVersion.patch) << endl;
|
---|
| 200 |
|
---|
| 201 | // TODO: Refactor the logger api to be more flexible,
|
---|
| 202 | // esp. since gl_log() and gl_log_err() have issues printing anything besides strings
|
---|
| 203 | restart_gl_log();
|
---|
| 204 | gl_log("starting SDL\n%s.%s.%s",
|
---|
| 205 | to_string(sdlVersion.major).c_str(),
|
---|
| 206 | to_string(sdlVersion.minor).c_str(),
|
---|
| 207 | to_string(sdlVersion.patch).c_str());
|
---|
| 208 |
|
---|
| 209 | // TODO: Use open_Log() and related functions instead of gl_log ones
|
---|
| 210 | // TODO: In addition, delete the gl_log functions
|
---|
| 211 | open_log();
|
---|
| 212 | get_log() << "starting SDL" << endl;
|
---|
| 213 | get_log() <<
|
---|
| 214 | (int)sdlVersion.major << "." <<
|
---|
| 215 | (int)sdlVersion.minor << "." <<
|
---|
| 216 | (int)sdlVersion.patch << endl;
|
---|
| 217 |
|
---|
| 218 | // TODO: Put all fonts, textures, and images in the assets folder
|
---|
| 219 | gui = new GameGui_SDL();
|
---|
| 220 |
|
---|
| 221 | if (gui->init() == RTWO_ERROR) {
|
---|
| 222 | // TODO: Also print these sorts of errors to the log
|
---|
| 223 | cout << "UI library could not be initialized!" << endl;
|
---|
| 224 | cout << gui->getError() << endl;
|
---|
[e469aed] | 225 | // TODO: Rename RTWO_ERROR to something else
|
---|
[3b7d497] | 226 | return RTWO_ERROR;
|
---|
| 227 | }
|
---|
| 228 |
|
---|
| 229 | window = (SDL_Window*)gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
|
---|
| 230 | if (window == nullptr) {
|
---|
| 231 | cout << "Window could not be created!" << endl;
|
---|
| 232 | cout << gui->getError() << endl;
|
---|
| 233 | return RTWO_ERROR;
|
---|
| 234 | }
|
---|
| 235 |
|
---|
| 236 | cout << "Target window size: (" << width << ", " << height << ")" << endl;
|
---|
| 237 | cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
|
---|
| 238 |
|
---|
| 239 | return RTWO_SUCCESS;
|
---|
| 240 | }
|
---|
| 241 |
|
---|
| 242 | void VulkanGame::initVulkan() {
|
---|
| 243 | const vector<const char*> validationLayers = {
|
---|
| 244 | "VK_LAYER_KHRONOS_validation"
|
---|
| 245 | };
|
---|
| 246 | const vector<const char*> deviceExtensions = {
|
---|
| 247 | VK_KHR_SWAPCHAIN_EXTENSION_NAME
|
---|
| 248 | };
|
---|
| 249 |
|
---|
| 250 | createVulkanInstance(validationLayers);
|
---|
| 251 | setupDebugMessenger();
|
---|
| 252 | createVulkanSurface();
|
---|
| 253 | pickPhysicalDevice(deviceExtensions);
|
---|
| 254 | createLogicalDevice(validationLayers, deviceExtensions);
|
---|
[ce9dc9f] | 255 | chooseSwapChainProperties();
|
---|
| 256 | createSwapChain();
|
---|
| 257 | createImageViews();
|
---|
| 258 |
|
---|
[737c26a] | 259 | createResourceCommandPool();
|
---|
[e469aed] | 260 | createImageResources();
|
---|
[ce9dc9f] | 261 |
|
---|
[e469aed] | 262 | createRenderPass();
|
---|
| 263 | createCommandPools();
|
---|
[ce9dc9f] | 264 | createFramebuffers();
|
---|
| 265 | createCommandBuffers();
|
---|
| 266 | createSyncObjects();
|
---|
[3b7d497] | 267 | }
|
---|
| 268 |
|
---|
[4a777d2] | 269 | void VulkanGame::initGraphicsPipelines() {
|
---|
[9d21aac] | 270 | modelPipeline = GraphicsPipeline_Vulkan<ModelVertex>(
|
---|
[4a777d2] | 271 | VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, physicalDevice, device, renderPass,
|
---|
[58453c3] | 272 | { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, 16, 24);
|
---|
[4a777d2] | 273 | }
|
---|
| 274 |
|
---|
| 275 | // TODO: Maybe change the name to initScene() or something similar
|
---|
| 276 | void VulkanGame::initMatrices() {
|
---|
| 277 | cam_pos = vec3(0.0f, 0.0f, 2.0f);
|
---|
| 278 |
|
---|
| 279 | float cam_yaw = 0.0f;
|
---|
| 280 | float cam_pitch = -50.0f;
|
---|
| 281 |
|
---|
| 282 | mat4 yaw_mat = rotate(mat4(1.0f), radians(-cam_yaw), vec3(0.0f, 1.0f, 0.0f));
|
---|
| 283 | mat4 pitch_mat = rotate(mat4(1.0f), radians(-cam_pitch), vec3(1.0f, 0.0f, 0.0f));
|
---|
| 284 |
|
---|
| 285 | mat4 R_view = pitch_mat * yaw_mat;
|
---|
| 286 | mat4 T_view = translate(mat4(1.0f), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z));
|
---|
| 287 | viewMat = R_view * T_view;
|
---|
| 288 |
|
---|
| 289 | projMat = perspective(radians(FOV_ANGLE), (float)swapChainExtent.width / (float)swapChainExtent.height, NEAR_CLIP, FAR_CLIP);
|
---|
| 290 | projMat[1][1] *= -1; // flip the y-axis so that +y is up
|
---|
| 291 |
|
---|
| 292 | object_VP_mats.view = viewMat;
|
---|
| 293 | object_VP_mats.proj = projMat;
|
---|
| 294 | }
|
---|
| 295 |
|
---|
[40eb092] | 296 | void VulkanGame::renderLoop() {
|
---|
[187b0f5] | 297 | startTime = steady_clock::now();
|
---|
| 298 | curTime = duration<float, seconds::period>(steady_clock::now() - startTime).count();
|
---|
[40eb092] | 299 |
|
---|
| 300 | fpsStartTime = curTime;
|
---|
| 301 | frameCount = 0;
|
---|
| 302 |
|
---|
| 303 | ImGuiIO& io = ImGui::GetIO();
|
---|
| 304 |
|
---|
| 305 | done = false;
|
---|
| 306 | while (!done) {
|
---|
| 307 |
|
---|
[5081b9a] | 308 | prevTime = curTime;
|
---|
[187b0f5] | 309 | curTime = duration<float, seconds::period>(steady_clock::now() - startTime).count();
|
---|
[5081b9a] | 310 | elapsedTime = curTime - prevTime;
|
---|
[40eb092] | 311 |
|
---|
| 312 | if (curTime - fpsStartTime >= 1.0f) {
|
---|
| 313 | fps = (float)frameCount / (curTime - fpsStartTime);
|
---|
| 314 |
|
---|
| 315 | frameCount = 0;
|
---|
| 316 | fpsStartTime = curTime;
|
---|
| 317 | }
|
---|
| 318 |
|
---|
| 319 | frameCount++;
|
---|
| 320 |
|
---|
| 321 | gui->processEvents();
|
---|
| 322 |
|
---|
| 323 | UIEvent uiEvent;
|
---|
| 324 | while (gui->pollEvent(&uiEvent)) {
|
---|
| 325 | GameEvent& e = uiEvent.event;
|
---|
| 326 | SDL_Event sdlEvent = uiEvent.rawEvent.sdl;
|
---|
| 327 |
|
---|
| 328 | ImGui_ImplSDL2_ProcessEvent(&sdlEvent);
|
---|
[5081b9a] | 329 | if ((e.type == UI_EVENT_MOUSEBUTTONDOWN || e.type == UI_EVENT_MOUSEBUTTONUP || e.type == UI_EVENT_UNKNOWN) &&
|
---|
| 330 | io.WantCaptureMouse) {
|
---|
| 331 | if (sdlEvent.type == SDL_MOUSEWHEEL || sdlEvent.type == SDL_MOUSEBUTTONDOWN ||
|
---|
| 332 | sdlEvent.type == SDL_MOUSEBUTTONUP) {
|
---|
[40eb092] | 333 | continue;
|
---|
| 334 | }
|
---|
| 335 | }
|
---|
[5081b9a] | 336 | if ((e.type == UI_EVENT_KEYDOWN || e.type == UI_EVENT_KEYUP) && io.WantCaptureKeyboard) {
|
---|
[40eb092] | 337 | if (sdlEvent.type == SDL_KEYDOWN || sdlEvent.type == SDL_KEYUP) {
|
---|
| 338 | continue;
|
---|
| 339 | }
|
---|
| 340 | }
|
---|
| 341 | if (io.WantTextInput) {
|
---|
| 342 | // show onscreen keyboard if on mobile
|
---|
| 343 | }
|
---|
| 344 |
|
---|
| 345 | switch (e.type) {
|
---|
[5081b9a] | 346 | case UI_EVENT_QUIT:
|
---|
| 347 | cout << "Quit event detected" << endl;
|
---|
| 348 | done = true;
|
---|
| 349 | break;
|
---|
| 350 | case UI_EVENT_WINDOWRESIZE:
|
---|
| 351 | cout << "Window resize event detected" << endl;
|
---|
| 352 | shouldRecreateSwapChain = true;
|
---|
| 353 | break;
|
---|
[4a777d2] | 354 | case UI_EVENT_KEYDOWN:
|
---|
| 355 | if (e.key.repeat) {
|
---|
| 356 | break;
|
---|
| 357 | }
|
---|
| 358 |
|
---|
| 359 | if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
|
---|
| 360 | done = true;
|
---|
| 361 | } else if (e.key.keycode == SDL_SCANCODE_SPACE) {
|
---|
| 362 | cout << "Adding a plane" << endl;
|
---|
| 363 | float zOffset = -2.0f + (0.5f * modelObjects.size());
|
---|
| 364 |
|
---|
[6486ba8] | 365 | SceneObject<ModelVertex>& texturedSquare = addObject(modelObjects, modelPipeline,
|
---|
| 366 | addObjectIndex<ModelVertex>(modelObjects.size(),
|
---|
| 367 | addVertexNormals<ModelVertex>({
|
---|
| 368 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
|
---|
| 369 | {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
|
---|
| 370 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
|
---|
| 371 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
|
---|
| 372 | {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}},
|
---|
| 373 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}}
|
---|
| 374 | })),
|
---|
| 375 | {
|
---|
| 376 | 0, 1, 2, 3, 4, 5
|
---|
| 377 | }, objects_modelPipeline, {
|
---|
| 378 | mat4(1.0f)
|
---|
| 379 | });
|
---|
[996dd3e] | 380 |
|
---|
[4a777d2] | 381 | texturedSquare.model_base =
|
---|
| 382 | translate(mat4(1.0f), vec3(0.0f, 0.0f, zOffset));
|
---|
| 383 | // START UNREVIEWED SECTION
|
---|
| 384 | // END UNREVIEWED SECTION
|
---|
| 385 | } else {
|
---|
| 386 | cout << "Key event detected" << endl;
|
---|
| 387 | }
|
---|
| 388 | break;
|
---|
[5081b9a] | 389 | case UI_EVENT_KEYUP:
|
---|
| 390 | // START UNREVIEWED SECTION
|
---|
| 391 | // END UNREVIEWED SECTION
|
---|
| 392 | break;
|
---|
| 393 | case UI_EVENT_WINDOW:
|
---|
| 394 | case UI_EVENT_MOUSEBUTTONDOWN:
|
---|
| 395 | case UI_EVENT_MOUSEBUTTONUP:
|
---|
| 396 | case UI_EVENT_MOUSEMOTION:
|
---|
| 397 | break;
|
---|
| 398 | case UI_EVENT_UNHANDLED:
|
---|
| 399 | cout << "Unhandled event type: 0x" << hex << sdlEvent.type << dec << endl;
|
---|
| 400 | break;
|
---|
| 401 | case UI_EVENT_UNKNOWN:
|
---|
| 402 | default:
|
---|
| 403 | cout << "Unknown event type: 0x" << hex << sdlEvent.type << dec << endl;
|
---|
| 404 | break;
|
---|
[40eb092] | 405 | }
|
---|
| 406 | }
|
---|
| 407 |
|
---|
| 408 | if (shouldRecreateSwapChain) {
|
---|
| 409 | gui->refreshWindowSize();
|
---|
| 410 | const bool isMinimized = gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0;
|
---|
| 411 |
|
---|
| 412 | if (!isMinimized) {
|
---|
| 413 | // TODO: This should be used if the min image count changes, presumably because a new surface was created
|
---|
| 414 | // with a different image count or something like that. Maybe I want to add code to query for a new min image count
|
---|
| 415 | // during swapchain recreation to take advantage of this
|
---|
| 416 | ImGui_ImplVulkan_SetMinImageCount(swapChainMinImageCount);
|
---|
| 417 |
|
---|
| 418 | recreateSwapChain();
|
---|
| 419 |
|
---|
| 420 | shouldRecreateSwapChain = false;
|
---|
| 421 | }
|
---|
| 422 | }
|
---|
| 423 |
|
---|
[4a777d2] | 424 | updateScene();
|
---|
| 425 |
|
---|
[e469aed] | 426 | // TODO: Move this into a renderImGuiOverlay() function
|
---|
[40eb092] | 427 | ImGui_ImplVulkan_NewFrame();
|
---|
| 428 | ImGui_ImplSDL2_NewFrame(window);
|
---|
| 429 | ImGui::NewFrame();
|
---|
| 430 |
|
---|
[85b5fec] | 431 | (this->*currentRenderScreenFn)(gui->getWindowWidth(), gui->getWindowHeight());
|
---|
[40eb092] | 432 |
|
---|
| 433 | ImGui::Render();
|
---|
| 434 |
|
---|
| 435 | gui->refreshWindowSize();
|
---|
| 436 | const bool isMinimized = gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0;
|
---|
| 437 |
|
---|
| 438 | if (!isMinimized) {
|
---|
| 439 | renderFrame(ImGui::GetDrawData());
|
---|
| 440 | presentFrame();
|
---|
| 441 | }
|
---|
| 442 | }
|
---|
| 443 | }
|
---|
| 444 |
|
---|
[4a777d2] | 445 | void VulkanGame::updateScene() {
|
---|
[a3cefaa] | 446 | // TODO: Probably move the resizing to the VulkanBuffer class
|
---|
[6bac215] | 447 | if (objects_modelPipeline.resized) {
|
---|
[b7fc3c2] | 448 | resizeBufferSet(storageBuffers_modelPipeline, objects_modelPipeline.memorySize(), resourceCommandPool,
|
---|
| 449 | graphicsQueue, true);
|
---|
[6bac215] | 450 |
|
---|
| 451 | objects_modelPipeline.resize();
|
---|
[bb76950] | 452 |
|
---|
| 453 | modelPipeline.updateDescriptorInfo(1, &storageBuffers_modelPipeline.infoSet, swapChainImages.size());
|
---|
[a3cefaa] | 454 | }
|
---|
| 455 |
|
---|
[4a777d2] | 456 | for (size_t i = 0; i < modelObjects.size(); i++) {
|
---|
[6486ba8] | 457 | SceneObject<ModelVertex>& obj = modelObjects[i];
|
---|
| 458 | SSBO_ModelObject& objData = objects_modelPipeline.get(i);
|
---|
[b7fc3c2] | 459 |
|
---|
| 460 | // Rotate the textured squares
|
---|
| 461 | obj.model_transform =
|
---|
| 462 | translate(mat4(1.0f), vec3(0.0f, -2.0f, -0.0f)) *
|
---|
| 463 | rotate(mat4(1.0f), curTime * radians(90.0f), vec3(0.0f, 0.0f, 1.0f));
|
---|
| 464 |
|
---|
[c1ec4f6] | 465 | objData.model = obj.model_transform * obj.model_base;
|
---|
| 466 | obj.center = vec3(objData.model * vec4(0.0f, 0.0f, 0.0f, 1.0f));
|
---|
[4a777d2] | 467 | }
|
---|
| 468 |
|
---|
[5ea0a37] | 469 | VulkanUtils::copyDataToMemory(device, objects_modelPipeline.data(), storageBuffers_modelPipeline.memory[imageIndex],
|
---|
| 470 | 0, objects_modelPipeline.memorySize(), false);
|
---|
| 471 |
|
---|
[c074f81] | 472 | VulkanUtils::copyDataToMemory(device, &object_VP_mats, uniformBuffers_modelPipeline.memory[imageIndex], 0,
|
---|
| 473 | sizeof(object_VP_mats), false);
|
---|
[4a777d2] | 474 | }
|
---|
| 475 |
|
---|
[3b7d497] | 476 | void VulkanGame::cleanup() {
|
---|
[ce9dc9f] | 477 | // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals)
|
---|
| 478 | //vkQueueWaitIdle(g_Queue);
|
---|
[880cfc2] | 479 | VKUTIL_CHECK_RESULT(vkDeviceWaitIdle(device), "failed to wait for device!");
|
---|
[ce9dc9f] | 480 |
|
---|
[e469aed] | 481 | cleanupImGuiOverlay();
|
---|
[ce9dc9f] | 482 |
|
---|
| 483 | cleanupSwapChain();
|
---|
| 484 |
|
---|
[4a777d2] | 485 | VulkanUtils::destroyVulkanImage(device, floorTextureImage);
|
---|
| 486 | // START UNREVIEWED SECTION
|
---|
| 487 |
|
---|
| 488 | vkDestroySampler(device, textureSampler, nullptr);
|
---|
| 489 |
|
---|
| 490 | modelPipeline.cleanupBuffers();
|
---|
| 491 |
|
---|
| 492 | // END UNREVIEWED SECTION
|
---|
| 493 |
|
---|
[ce9dc9f] | 494 | vkDestroyCommandPool(device, resourceCommandPool, nullptr);
|
---|
| 495 |
|
---|
| 496 | vkDestroyDevice(device, nullptr);
|
---|
[7865c5b] | 497 | vkDestroySurfaceKHR(instance, vulkanSurface, nullptr);
|
---|
[3b7d497] | 498 |
|
---|
| 499 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
[ce9dc9f] | 500 | VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
|
---|
[3b7d497] | 501 | }
|
---|
| 502 |
|
---|
[ce9dc9f] | 503 | vkDestroyInstance(instance, nullptr);
|
---|
[3b7d497] | 504 |
|
---|
| 505 | gui->destroyWindow();
|
---|
| 506 | gui->shutdown();
|
---|
| 507 | delete gui;
|
---|
| 508 | }
|
---|
| 509 |
|
---|
| 510 | void VulkanGame::createVulkanInstance(const vector<const char*>& validationLayers) {
|
---|
| 511 | if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
|
---|
| 512 | throw runtime_error("validation layers requested, but not available!");
|
---|
| 513 | }
|
---|
| 514 |
|
---|
| 515 | VkApplicationInfo appInfo = {};
|
---|
| 516 | appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
|
---|
| 517 | appInfo.pApplicationName = "Vulkan Game";
|
---|
| 518 | appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
|
---|
| 519 | appInfo.pEngineName = "No Engine";
|
---|
| 520 | appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
|
---|
| 521 | appInfo.apiVersion = VK_API_VERSION_1_0;
|
---|
| 522 |
|
---|
| 523 | VkInstanceCreateInfo createInfo = {};
|
---|
| 524 | createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
---|
| 525 | createInfo.pApplicationInfo = &appInfo;
|
---|
| 526 |
|
---|
| 527 | vector<const char*> extensions = gui->getRequiredExtensions();
|
---|
| 528 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
| 529 | extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
---|
| 530 | }
|
---|
| 531 |
|
---|
| 532 | createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
|
---|
| 533 | createInfo.ppEnabledExtensionNames = extensions.data();
|
---|
| 534 |
|
---|
| 535 | cout << endl << "Extensions:" << endl;
|
---|
| 536 | for (const char* extensionName : extensions) {
|
---|
| 537 | cout << extensionName << endl;
|
---|
| 538 | }
|
---|
| 539 | cout << endl;
|
---|
| 540 |
|
---|
| 541 | VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
|
---|
| 542 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
| 543 | createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
|
---|
| 544 | createInfo.ppEnabledLayerNames = validationLayers.data();
|
---|
| 545 |
|
---|
| 546 | populateDebugMessengerCreateInfo(debugCreateInfo);
|
---|
| 547 | createInfo.pNext = &debugCreateInfo;
|
---|
[ce9dc9f] | 548 | }
|
---|
| 549 | else {
|
---|
[3b7d497] | 550 | createInfo.enabledLayerCount = 0;
|
---|
| 551 |
|
---|
| 552 | createInfo.pNext = nullptr;
|
---|
| 553 | }
|
---|
| 554 |
|
---|
[ce9dc9f] | 555 | if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
|
---|
[3b7d497] | 556 | throw runtime_error("failed to create instance!");
|
---|
| 557 | }
|
---|
| 558 | }
|
---|
| 559 |
|
---|
| 560 | void VulkanGame::setupDebugMessenger() {
|
---|
| 561 | if (!ENABLE_VALIDATION_LAYERS) {
|
---|
| 562 | return;
|
---|
| 563 | }
|
---|
| 564 |
|
---|
| 565 | VkDebugUtilsMessengerCreateInfoEXT createInfo;
|
---|
| 566 | populateDebugMessengerCreateInfo(createInfo);
|
---|
| 567 |
|
---|
[ce9dc9f] | 568 | if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
|
---|
[3b7d497] | 569 | throw runtime_error("failed to set up debug messenger!");
|
---|
| 570 | }
|
---|
| 571 | }
|
---|
| 572 |
|
---|
| 573 | void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
|
---|
| 574 | createInfo = {};
|
---|
| 575 | createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
|
---|
| 576 | 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;
|
---|
| 577 | 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;
|
---|
| 578 | createInfo.pfnUserCallback = debugCallback;
|
---|
| 579 | }
|
---|
| 580 |
|
---|
| 581 | void VulkanGame::createVulkanSurface() {
|
---|
[7865c5b] | 582 | if (gui->createVulkanSurface(instance, &vulkanSurface) == RTWO_ERROR) {
|
---|
[3b7d497] | 583 | throw runtime_error("failed to create window surface!");
|
---|
| 584 | }
|
---|
| 585 | }
|
---|
| 586 |
|
---|
| 587 | void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
|
---|
| 588 | uint32_t deviceCount = 0;
|
---|
| 589 | // TODO: Check VkResult
|
---|
[ce9dc9f] | 590 | vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
|
---|
[3b7d497] | 591 |
|
---|
| 592 | if (deviceCount == 0) {
|
---|
| 593 | throw runtime_error("failed to find GPUs with Vulkan support!");
|
---|
| 594 | }
|
---|
| 595 |
|
---|
| 596 | vector<VkPhysicalDevice> devices(deviceCount);
|
---|
| 597 | // TODO: Check VkResult
|
---|
[ce9dc9f] | 598 | vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
|
---|
[3b7d497] | 599 |
|
---|
| 600 | cout << endl << "Graphics cards:" << endl;
|
---|
| 601 | for (const VkPhysicalDevice& device : devices) {
|
---|
| 602 | if (isDeviceSuitable(device, deviceExtensions)) {
|
---|
[ce9dc9f] | 603 | physicalDevice = device;
|
---|
[3b7d497] | 604 | break;
|
---|
| 605 | }
|
---|
| 606 | }
|
---|
| 607 | cout << endl;
|
---|
| 608 |
|
---|
[ce9dc9f] | 609 | if (physicalDevice == VK_NULL_HANDLE) {
|
---|
[3b7d497] | 610 | throw runtime_error("failed to find a suitable GPU!");
|
---|
| 611 | }
|
---|
| 612 | }
|
---|
| 613 |
|
---|
| 614 | bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions) {
|
---|
| 615 | VkPhysicalDeviceProperties deviceProperties;
|
---|
| 616 | vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
|
---|
| 617 |
|
---|
| 618 | cout << "Device: " << deviceProperties.deviceName << endl;
|
---|
| 619 |
|
---|
[187b0f5] | 620 | // TODO: Eventually, maybe let the user pick out of a set of GPUs in case the user does want to use
|
---|
| 621 | // an integrated GPU. On my laptop, this function returns TRUE for the integrated GPU, but crashes
|
---|
| 622 | // when trying to use it to render. Maybe I just need to figure out which other extensions and features
|
---|
| 623 | // to check.
|
---|
| 624 | if (deviceProperties.deviceType != VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
|
---|
| 625 | return false;
|
---|
| 626 | }
|
---|
| 627 |
|
---|
[7865c5b] | 628 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
[3b7d497] | 629 | bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
|
---|
| 630 | bool swapChainAdequate = false;
|
---|
| 631 |
|
---|
| 632 | if (extensionsSupported) {
|
---|
[7865c5b] | 633 | vector<VkSurfaceFormatKHR> formats = VulkanUtils::querySwapChainFormats(physicalDevice, vulkanSurface);
|
---|
| 634 | vector<VkPresentModeKHR> presentModes = VulkanUtils::querySwapChainPresentModes(physicalDevice, vulkanSurface);
|
---|
[ce9dc9f] | 635 |
|
---|
| 636 | swapChainAdequate = !formats.empty() && !presentModes.empty();
|
---|
[3b7d497] | 637 | }
|
---|
| 638 |
|
---|
| 639 | VkPhysicalDeviceFeatures supportedFeatures;
|
---|
| 640 | vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
|
---|
| 641 |
|
---|
| 642 | return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
|
---|
| 643 | }
|
---|
| 644 |
|
---|
| 645 | void VulkanGame::createLogicalDevice(const vector<const char*>& validationLayers,
|
---|
[ce9dc9f] | 646 | const vector<const char*>& deviceExtensions) {
|
---|
[7865c5b] | 647 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
[6493e43] | 648 |
|
---|
| 649 | if (!indices.isComplete()) {
|
---|
| 650 | throw runtime_error("failed to find required queue families!");
|
---|
| 651 | }
|
---|
| 652 |
|
---|
| 653 | // TODO: Using separate graphics and present queues currently works, but I should verify that I'm
|
---|
| 654 | // using them correctly to get the most benefit out of separate queues
|
---|
[3b7d497] | 655 |
|
---|
| 656 | vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
|
---|
[6493e43] | 657 | set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
|
---|
[3b7d497] | 658 |
|
---|
| 659 | float queuePriority = 1.0f;
|
---|
| 660 | for (uint32_t queueFamily : uniqueQueueFamilies) {
|
---|
| 661 | VkDeviceQueueCreateInfo queueCreateInfo = {};
|
---|
| 662 | queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
---|
| 663 | queueCreateInfo.queueCount = 1;
|
---|
| 664 | queueCreateInfo.queueFamilyIndex = queueFamily;
|
---|
| 665 | queueCreateInfo.pQueuePriorities = &queuePriority;
|
---|
| 666 |
|
---|
| 667 | queueCreateInfoList.push_back(queueCreateInfo);
|
---|
| 668 | }
|
---|
| 669 |
|
---|
| 670 | VkPhysicalDeviceFeatures deviceFeatures = {};
|
---|
| 671 | deviceFeatures.samplerAnisotropy = VK_TRUE;
|
---|
| 672 |
|
---|
| 673 | VkDeviceCreateInfo createInfo = {};
|
---|
| 674 | createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
---|
| 675 |
|
---|
| 676 | createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
|
---|
| 677 | createInfo.pQueueCreateInfos = queueCreateInfoList.data();
|
---|
| 678 |
|
---|
| 679 | createInfo.pEnabledFeatures = &deviceFeatures;
|
---|
| 680 |
|
---|
| 681 | createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
|
---|
| 682 | createInfo.ppEnabledExtensionNames = deviceExtensions.data();
|
---|
| 683 |
|
---|
| 684 | // These fields are ignored by up-to-date Vulkan implementations,
|
---|
| 685 | // but it's a good idea to set them for backwards compatibility
|
---|
| 686 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
| 687 | createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
|
---|
| 688 | createInfo.ppEnabledLayerNames = validationLayers.data();
|
---|
[ce9dc9f] | 689 | }
|
---|
| 690 | else {
|
---|
[3b7d497] | 691 | createInfo.enabledLayerCount = 0;
|
---|
| 692 | }
|
---|
| 693 |
|
---|
[ce9dc9f] | 694 | if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
|
---|
[3b7d497] | 695 | throw runtime_error("failed to create logical device!");
|
---|
| 696 | }
|
---|
| 697 |
|
---|
[ce9dc9f] | 698 | vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
|
---|
| 699 | vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
|
---|
| 700 | }
|
---|
| 701 |
|
---|
| 702 | void VulkanGame::chooseSwapChainProperties() {
|
---|
[7865c5b] | 703 | vector<VkSurfaceFormatKHR> availableFormats = VulkanUtils::querySwapChainFormats(physicalDevice, vulkanSurface);
|
---|
| 704 | vector<VkPresentModeKHR> availablePresentModes = VulkanUtils::querySwapChainPresentModes(physicalDevice, vulkanSurface);
|
---|
[ce9dc9f] | 705 |
|
---|
| 706 | // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
|
---|
| 707 | // Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format
|
---|
| 708 | // Additionally several new color spaces were introduced with Vulkan Spec v1.0.40,
|
---|
| 709 | // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used.
|
---|
| 710 | swapChainSurfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(availableFormats,
|
---|
| 711 | { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM },
|
---|
| 712 | VK_COLOR_SPACE_SRGB_NONLINEAR_KHR);
|
---|
| 713 |
|
---|
| 714 | #ifdef IMGUI_UNLIMITED_FRAME_RATE
|
---|
| 715 | vector<VkPresentModeKHR> presentModes{
|
---|
| 716 | VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR
|
---|
| 717 | };
|
---|
| 718 | #else
|
---|
| 719 | vector<VkPresentModeKHR> presentModes{ VK_PRESENT_MODE_FIFO_KHR };
|
---|
| 720 | #endif
|
---|
| 721 |
|
---|
| 722 | swapChainPresentMode = VulkanUtils::chooseSwapPresentMode(availablePresentModes, presentModes);
|
---|
| 723 |
|
---|
| 724 | cout << "[vulkan] Selected PresentMode = " << swapChainPresentMode << endl;
|
---|
| 725 |
|
---|
[7865c5b] | 726 | VkSurfaceCapabilitiesKHR capabilities = VulkanUtils::querySwapChainCapabilities(physicalDevice, vulkanSurface);
|
---|
[ce9dc9f] | 727 |
|
---|
| 728 | // If min image count was not specified, request different count of images dependent on selected present mode
|
---|
| 729 | if (swapChainMinImageCount == 0) {
|
---|
| 730 | if (swapChainPresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
|
---|
| 731 | swapChainMinImageCount = 3;
|
---|
| 732 | }
|
---|
| 733 | else if (swapChainPresentMode == VK_PRESENT_MODE_FIFO_KHR || swapChainPresentMode == VK_PRESENT_MODE_FIFO_RELAXED_KHR) {
|
---|
| 734 | swapChainMinImageCount = 2;
|
---|
| 735 | }
|
---|
| 736 | else if (swapChainPresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
|
---|
| 737 | swapChainMinImageCount = 1;
|
---|
| 738 | }
|
---|
| 739 | else {
|
---|
| 740 | throw runtime_error("unexpected present mode!");
|
---|
| 741 | }
|
---|
| 742 | }
|
---|
| 743 |
|
---|
| 744 | if (swapChainMinImageCount < capabilities.minImageCount) {
|
---|
| 745 | swapChainMinImageCount = capabilities.minImageCount;
|
---|
| 746 | }
|
---|
| 747 | else if (capabilities.maxImageCount != 0 && swapChainMinImageCount > capabilities.maxImageCount) {
|
---|
| 748 | swapChainMinImageCount = capabilities.maxImageCount;
|
---|
| 749 | }
|
---|
| 750 | }
|
---|
| 751 |
|
---|
| 752 | void VulkanGame::createSwapChain() {
|
---|
[7865c5b] | 753 | VkSurfaceCapabilitiesKHR capabilities = VulkanUtils::querySwapChainCapabilities(physicalDevice, vulkanSurface);
|
---|
[ce9dc9f] | 754 |
|
---|
| 755 | swapChainExtent = VulkanUtils::chooseSwapExtent(capabilities, gui->getWindowWidth(), gui->getWindowHeight());
|
---|
| 756 |
|
---|
| 757 | VkSwapchainCreateInfoKHR createInfo = {};
|
---|
| 758 | createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
|
---|
[7865c5b] | 759 | createInfo.surface = vulkanSurface;
|
---|
[ce9dc9f] | 760 | createInfo.minImageCount = swapChainMinImageCount;
|
---|
| 761 | createInfo.imageFormat = swapChainSurfaceFormat.format;
|
---|
| 762 | createInfo.imageColorSpace = swapChainSurfaceFormat.colorSpace;
|
---|
| 763 | createInfo.imageExtent = swapChainExtent;
|
---|
| 764 | createInfo.imageArrayLayers = 1;
|
---|
| 765 | createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
|
---|
| 766 |
|
---|
| 767 | // TODO: Maybe save this result so I don't have to recalculate it every time
|
---|
[7865c5b] | 768 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
[ce9dc9f] | 769 | uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
|
---|
[6493e43] | 770 |
|
---|
[ce9dc9f] | 771 | if (indices.graphicsFamily != indices.presentFamily) {
|
---|
| 772 | createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
|
---|
| 773 | createInfo.queueFamilyIndexCount = 2;
|
---|
| 774 | createInfo.pQueueFamilyIndices = queueFamilyIndices;
|
---|
| 775 | }
|
---|
| 776 | else {
|
---|
| 777 | createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
---|
| 778 | createInfo.queueFamilyIndexCount = 0;
|
---|
| 779 | createInfo.pQueueFamilyIndices = nullptr;
|
---|
| 780 | }
|
---|
| 781 |
|
---|
| 782 | createInfo.preTransform = capabilities.currentTransform;
|
---|
| 783 | createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
|
---|
| 784 | createInfo.presentMode = swapChainPresentMode;
|
---|
| 785 | createInfo.clipped = VK_TRUE;
|
---|
| 786 | createInfo.oldSwapchain = VK_NULL_HANDLE;
|
---|
| 787 |
|
---|
| 788 | if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
|
---|
| 789 | throw runtime_error("failed to create swap chain!");
|
---|
| 790 | }
|
---|
| 791 |
|
---|
| 792 | if (vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, nullptr) != VK_SUCCESS) {
|
---|
| 793 | throw runtime_error("failed to get swap chain image count!");
|
---|
| 794 | }
|
---|
| 795 |
|
---|
| 796 | swapChainImages.resize(swapChainImageCount);
|
---|
| 797 | if (vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, swapChainImages.data()) != VK_SUCCESS) {
|
---|
| 798 | throw runtime_error("failed to get swap chain images!");
|
---|
| 799 | }
|
---|
[3b7d497] | 800 | }
|
---|
| 801 |
|
---|
[ce9dc9f] | 802 | void VulkanGame::createImageViews() {
|
---|
| 803 | swapChainImageViews.resize(swapChainImageCount);
|
---|
[6493e43] | 804 |
|
---|
[ce9dc9f] | 805 | for (uint32_t i = 0; i < swapChainImageViews.size(); i++) {
|
---|
| 806 | swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainSurfaceFormat.format,
|
---|
| 807 | VK_IMAGE_ASPECT_COLOR_BIT);
|
---|
| 808 | }
|
---|
[6493e43] | 809 | }
|
---|
| 810 |
|
---|
[e469aed] | 811 | void VulkanGame::createResourceCommandPool() {
|
---|
| 812 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
| 813 |
|
---|
| 814 | VkCommandPoolCreateInfo poolInfo = {};
|
---|
| 815 | poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
|
---|
| 816 | poolInfo.queueFamilyIndex = indices.graphicsFamily.value();
|
---|
| 817 | poolInfo.flags = 0;
|
---|
| 818 |
|
---|
| 819 | if (vkCreateCommandPool(device, &poolInfo, nullptr, &resourceCommandPool) != VK_SUCCESS) {
|
---|
| 820 | throw runtime_error("failed to create resource command pool!");
|
---|
| 821 | }
|
---|
| 822 | }
|
---|
| 823 |
|
---|
| 824 | void VulkanGame::createImageResources() {
|
---|
| 825 | VulkanUtils::createDepthImage(device, physicalDevice, resourceCommandPool, findDepthFormat(), swapChainExtent,
|
---|
[8dcbf62] | 826 | depthImage, graphicsQueue);
|
---|
[4a777d2] | 827 |
|
---|
| 828 | createTextureSampler();
|
---|
| 829 |
|
---|
| 830 | // TODO: Move all images/textures somewhere into the assets folder
|
---|
| 831 |
|
---|
| 832 | VulkanUtils::createVulkanImageFromFile(device, physicalDevice, resourceCommandPool, "textures/texture.jpg",
|
---|
| 833 | floorTextureImage, graphicsQueue);
|
---|
| 834 |
|
---|
| 835 | floorTextureImageDescriptor = {};
|
---|
| 836 | floorTextureImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
---|
| 837 | floorTextureImageDescriptor.imageView = floorTextureImage.imageView;
|
---|
| 838 | floorTextureImageDescriptor.sampler = textureSampler;
|
---|
[e469aed] | 839 | }
|
---|
| 840 |
|
---|
| 841 | VkFormat VulkanGame::findDepthFormat() {
|
---|
| 842 | return VulkanUtils::findSupportedFormat(
|
---|
| 843 | physicalDevice,
|
---|
[a3cefaa] | 844 | { VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT },
|
---|
[e469aed] | 845 | VK_IMAGE_TILING_OPTIMAL,
|
---|
| 846 | VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
|
---|
| 847 | );
|
---|
| 848 | }
|
---|
| 849 |
|
---|
[ce9dc9f] | 850 | void VulkanGame::createRenderPass() {
|
---|
| 851 | VkAttachmentDescription colorAttachment = {};
|
---|
| 852 | colorAttachment.format = swapChainSurfaceFormat.format;
|
---|
| 853 | colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
|
---|
| 854 | colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // Set to VK_ATTACHMENT_LOAD_OP_DONT_CARE to disable clearing
|
---|
| 855 | colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
|
---|
| 856 | colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
---|
| 857 | colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
| 858 | colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
---|
| 859 | colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
|
---|
| 860 |
|
---|
| 861 | VkAttachmentReference colorAttachmentRef = {};
|
---|
| 862 | colorAttachmentRef.attachment = 0;
|
---|
| 863 | colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
---|
| 864 |
|
---|
| 865 | VkAttachmentDescription depthAttachment = {};
|
---|
| 866 | depthAttachment.format = findDepthFormat();
|
---|
| 867 | depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
|
---|
| 868 | depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
---|
| 869 | depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
| 870 | depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
---|
| 871 | depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
| 872 | depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
---|
| 873 | depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
---|
| 874 |
|
---|
| 875 | VkAttachmentReference depthAttachmentRef = {};
|
---|
| 876 | depthAttachmentRef.attachment = 1;
|
---|
| 877 | depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
---|
| 878 |
|
---|
| 879 | VkSubpassDescription subpass = {};
|
---|
| 880 | subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
|
---|
| 881 | subpass.colorAttachmentCount = 1;
|
---|
| 882 | subpass.pColorAttachments = &colorAttachmentRef;
|
---|
| 883 | //subpass.pDepthStencilAttachment = &depthAttachmentRef;
|
---|
| 884 |
|
---|
| 885 | VkSubpassDependency dependency = {};
|
---|
| 886 | dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
|
---|
| 887 | dependency.dstSubpass = 0;
|
---|
| 888 | dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
---|
| 889 | dependency.srcAccessMask = 0;
|
---|
| 890 | dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
---|
| 891 | dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
|
---|
| 892 |
|
---|
| 893 | array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
|
---|
| 894 | VkRenderPassCreateInfo renderPassInfo = {};
|
---|
| 895 | renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
|
---|
| 896 | renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
---|
| 897 | renderPassInfo.pAttachments = attachments.data();
|
---|
| 898 | renderPassInfo.subpassCount = 1;
|
---|
| 899 | renderPassInfo.pSubpasses = &subpass;
|
---|
| 900 | renderPassInfo.dependencyCount = 1;
|
---|
| 901 | renderPassInfo.pDependencies = &dependency;
|
---|
| 902 |
|
---|
| 903 | if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
|
---|
| 904 | throw runtime_error("failed to create render pass!");
|
---|
| 905 | }
|
---|
| 906 |
|
---|
| 907 | // We do not create a pipeline by default as this is also used by examples' main.cpp,
|
---|
| 908 | // but secondary viewport in multi-viewport mode may want to create one with:
|
---|
| 909 | //ImGui_ImplVulkan_CreatePipeline(device, g_Allocator, VK_NULL_HANDLE, g_MainWindowData.RenderPass, VK_SAMPLE_COUNT_1_BIT, &g_MainWindowData.Pipeline);
|
---|
| 910 | }
|
---|
| 911 |
|
---|
| 912 | void VulkanGame::createCommandPools() {
|
---|
| 913 | commandPools.resize(swapChainImageCount);
|
---|
| 914 |
|
---|
[7865c5b] | 915 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
[ce9dc9f] | 916 |
|
---|
| 917 | for (size_t i = 0; i < swapChainImageCount; i++) {
|
---|
| 918 | VkCommandPoolCreateInfo poolInfo = {};
|
---|
| 919 | poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
|
---|
| 920 | poolInfo.queueFamilyIndex = indices.graphicsFamily.value();
|
---|
| 921 | poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
|
---|
[880cfc2] | 922 |
|
---|
[ce9dc9f] | 923 | if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPools[i]) != VK_SUCCESS) {
|
---|
| 924 | throw runtime_error("failed to create graphics command pool!");
|
---|
| 925 | }
|
---|
[6493e43] | 926 | }
|
---|
[ce9dc9f] | 927 | }
|
---|
[6493e43] | 928 |
|
---|
[4a777d2] | 929 | void VulkanGame::createTextureSampler() {
|
---|
| 930 | VkSamplerCreateInfo samplerInfo = {};
|
---|
| 931 | samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
|
---|
| 932 | samplerInfo.magFilter = VK_FILTER_LINEAR;
|
---|
| 933 | samplerInfo.minFilter = VK_FILTER_LINEAR;
|
---|
| 934 |
|
---|
| 935 | samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
| 936 | samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
| 937 | samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
| 938 |
|
---|
| 939 | samplerInfo.anisotropyEnable = VK_TRUE;
|
---|
| 940 | samplerInfo.maxAnisotropy = 16;
|
---|
| 941 | samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
|
---|
| 942 | samplerInfo.unnormalizedCoordinates = VK_FALSE;
|
---|
| 943 | samplerInfo.compareEnable = VK_FALSE;
|
---|
| 944 | samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
|
---|
| 945 | samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
|
---|
| 946 | samplerInfo.mipLodBias = 0.0f;
|
---|
| 947 | samplerInfo.minLod = 0.0f;
|
---|
| 948 | samplerInfo.maxLod = 0.0f;
|
---|
| 949 |
|
---|
| 950 | VKUTIL_CHECK_RESULT(vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler),
|
---|
| 951 | "failed to create texture sampler!");
|
---|
| 952 | }
|
---|
| 953 |
|
---|
[ce9dc9f] | 954 | void VulkanGame::createFramebuffers() {
|
---|
| 955 | swapChainFramebuffers.resize(swapChainImageCount);
|
---|
| 956 |
|
---|
| 957 | VkFramebufferCreateInfo framebufferInfo = {};
|
---|
| 958 | framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
---|
| 959 | framebufferInfo.renderPass = renderPass;
|
---|
| 960 | framebufferInfo.width = swapChainExtent.width;
|
---|
| 961 | framebufferInfo.height = swapChainExtent.height;
|
---|
| 962 | framebufferInfo.layers = 1;
|
---|
| 963 |
|
---|
| 964 | for (size_t i = 0; i < swapChainImageCount; i++) {
|
---|
| 965 | array<VkImageView, 2> attachments = {
|
---|
| 966 | swapChainImageViews[i],
|
---|
| 967 | depthImage.imageView
|
---|
| 968 | };
|
---|
| 969 |
|
---|
| 970 | framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
---|
| 971 | framebufferInfo.pAttachments = attachments.data();
|
---|
| 972 |
|
---|
| 973 | if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
|
---|
| 974 | throw runtime_error("failed to create framebuffer!");
|
---|
| 975 | }
|
---|
| 976 | }
|
---|
| 977 | }
|
---|
| 978 |
|
---|
| 979 | void VulkanGame::createCommandBuffers() {
|
---|
| 980 | commandBuffers.resize(swapChainImageCount);
|
---|
| 981 |
|
---|
| 982 | for (size_t i = 0; i < swapChainImageCount; i++) {
|
---|
| 983 | VkCommandBufferAllocateInfo allocInfo = {};
|
---|
| 984 | allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
|
---|
| 985 | allocInfo.commandPool = commandPools[i];
|
---|
| 986 | allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
|
---|
| 987 | allocInfo.commandBufferCount = 1;
|
---|
| 988 |
|
---|
| 989 | if (vkAllocateCommandBuffers(device, &allocInfo, &commandBuffers[i]) != VK_SUCCESS) {
|
---|
[880cfc2] | 990 | throw runtime_error("failed to allocate command buffer!");
|
---|
[6493e43] | 991 | }
|
---|
[ce9dc9f] | 992 | }
|
---|
| 993 | }
|
---|
| 994 |
|
---|
| 995 | void VulkanGame::createSyncObjects() {
|
---|
| 996 | imageAcquiredSemaphores.resize(swapChainImageCount);
|
---|
| 997 | renderCompleteSemaphores.resize(swapChainImageCount);
|
---|
| 998 | inFlightFences.resize(swapChainImageCount);
|
---|
[6493e43] | 999 |
|
---|
[ce9dc9f] | 1000 | VkSemaphoreCreateInfo semaphoreInfo = {};
|
---|
| 1001 | semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
|
---|
| 1002 |
|
---|
| 1003 | VkFenceCreateInfo fenceInfo = {};
|
---|
| 1004 | fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
|
---|
| 1005 | fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
|
---|
| 1006 |
|
---|
| 1007 | for (size_t i = 0; i < swapChainImageCount; i++) {
|
---|
[e469aed] | 1008 | VKUTIL_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAcquiredSemaphores[i]),
|
---|
| 1009 | "failed to create image acquired sempahore for a frame!");
|
---|
[ce9dc9f] | 1010 |
|
---|
[e469aed] | 1011 | VKUTIL_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderCompleteSemaphores[i]),
|
---|
| 1012 | "failed to create render complete sempahore for a frame!");
|
---|
[ce9dc9f] | 1013 |
|
---|
[e469aed] | 1014 | VKUTIL_CHECK_RESULT(vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]),
|
---|
| 1015 | "failed to create fence for a frame!");
|
---|
[6493e43] | 1016 | }
|
---|
[ce9dc9f] | 1017 | }
|
---|
| 1018 |
|
---|
[e469aed] | 1019 | void VulkanGame::initImGuiOverlay() {
|
---|
| 1020 | vector<VkDescriptorPoolSize> pool_sizes {
|
---|
| 1021 | { VK_DESCRIPTOR_TYPE_SAMPLER, 1000 },
|
---|
| 1022 | { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 },
|
---|
| 1023 | { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 },
|
---|
| 1024 | { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 },
|
---|
| 1025 | { VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 },
|
---|
| 1026 | { VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 },
|
---|
| 1027 | { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 },
|
---|
| 1028 | { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 },
|
---|
| 1029 | { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 },
|
---|
| 1030 | { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 },
|
---|
| 1031 | { VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 }
|
---|
| 1032 | };
|
---|
| 1033 |
|
---|
| 1034 | VkDescriptorPoolCreateInfo pool_info = {};
|
---|
| 1035 | pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
|
---|
| 1036 | pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
|
---|
| 1037 | pool_info.maxSets = 1000 * pool_sizes.size();
|
---|
| 1038 | pool_info.poolSizeCount = static_cast<uint32_t>(pool_sizes.size());
|
---|
| 1039 | pool_info.pPoolSizes = pool_sizes.data();
|
---|
| 1040 |
|
---|
| 1041 | VKUTIL_CHECK_RESULT(vkCreateDescriptorPool(device, &pool_info, nullptr, &imguiDescriptorPool),
|
---|
| 1042 | "failed to create IMGUI descriptor pool!");
|
---|
| 1043 |
|
---|
| 1044 | // TODO: Do this in one place and save it instead of redoing it every time I need a queue family index
|
---|
| 1045 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
| 1046 |
|
---|
| 1047 | // Setup Dear ImGui context
|
---|
| 1048 | IMGUI_CHECKVERSION();
|
---|
| 1049 | ImGui::CreateContext();
|
---|
| 1050 | ImGuiIO& io = ImGui::GetIO();
|
---|
| 1051 | //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
|
---|
| 1052 | //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
|
---|
| 1053 |
|
---|
| 1054 | // Setup Dear ImGui style
|
---|
| 1055 | ImGui::StyleColorsDark();
|
---|
| 1056 | //ImGui::StyleColorsClassic();
|
---|
| 1057 |
|
---|
| 1058 | // Setup Platform/Renderer bindings
|
---|
| 1059 | ImGui_ImplSDL2_InitForVulkan(window);
|
---|
| 1060 | ImGui_ImplVulkan_InitInfo init_info = {};
|
---|
| 1061 | init_info.Instance = instance;
|
---|
| 1062 | init_info.PhysicalDevice = physicalDevice;
|
---|
| 1063 | init_info.Device = device;
|
---|
| 1064 | init_info.QueueFamily = indices.graphicsFamily.value();
|
---|
| 1065 | init_info.Queue = graphicsQueue;
|
---|
| 1066 | init_info.DescriptorPool = imguiDescriptorPool;
|
---|
| 1067 | init_info.Allocator = nullptr;
|
---|
| 1068 | init_info.MinImageCount = swapChainMinImageCount;
|
---|
| 1069 | init_info.ImageCount = swapChainImageCount;
|
---|
| 1070 | init_info.CheckVkResultFn = check_imgui_vk_result;
|
---|
| 1071 | ImGui_ImplVulkan_Init(&init_info, renderPass);
|
---|
| 1072 |
|
---|
| 1073 | // Load Fonts
|
---|
| 1074 | // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
|
---|
| 1075 | // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
|
---|
| 1076 | // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
|
---|
| 1077 | // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
|
---|
| 1078 | // - Read 'docs/FONTS.md' for more instructions and details.
|
---|
| 1079 | // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
|
---|
| 1080 | //io.Fonts->AddFontDefault();
|
---|
| 1081 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
|
---|
| 1082 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
|
---|
| 1083 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
|
---|
| 1084 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
|
---|
| 1085 | //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
|
---|
| 1086 | //assert(font != NULL);
|
---|
| 1087 |
|
---|
| 1088 | // Upload Fonts
|
---|
| 1089 |
|
---|
| 1090 | VkCommandBuffer commandBuffer = VulkanUtils::beginSingleTimeCommands(device, resourceCommandPool);
|
---|
| 1091 |
|
---|
| 1092 | ImGui_ImplVulkan_CreateFontsTexture(commandBuffer);
|
---|
| 1093 |
|
---|
| 1094 | VulkanUtils::endSingleTimeCommands(device, resourceCommandPool, commandBuffer, graphicsQueue);
|
---|
| 1095 |
|
---|
| 1096 | ImGui_ImplVulkan_DestroyFontUploadObjects();
|
---|
| 1097 | }
|
---|
| 1098 |
|
---|
| 1099 | void VulkanGame::cleanupImGuiOverlay() {
|
---|
| 1100 | ImGui_ImplVulkan_Shutdown();
|
---|
| 1101 | ImGui_ImplSDL2_Shutdown();
|
---|
| 1102 | ImGui::DestroyContext();
|
---|
| 1103 |
|
---|
| 1104 | vkDestroyDescriptorPool(device, imguiDescriptorPool, nullptr);
|
---|
| 1105 | }
|
---|
| 1106 |
|
---|
[8aa4888] | 1107 | void VulkanGame::createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags usages, VkMemoryPropertyFlags properties,
|
---|
[c163d81] | 1108 | BufferSet& set) {
|
---|
[8aa4888] | 1109 | set.usages = usages;
|
---|
| 1110 | set.properties = properties;
|
---|
| 1111 |
|
---|
[c163d81] | 1112 | set.buffers.resize(swapChainImageCount);
|
---|
| 1113 | set.memory.resize(swapChainImageCount);
|
---|
| 1114 | set.infoSet.resize(swapChainImageCount);
|
---|
[4a777d2] | 1115 |
|
---|
| 1116 | for (size_t i = 0; i < swapChainImageCount; i++) {
|
---|
[8aa4888] | 1117 | VulkanUtils::createBuffer(device, physicalDevice, bufferSize, usages, properties, set.buffers[i], set.memory[i]);
|
---|
[4a777d2] | 1118 |
|
---|
[c163d81] | 1119 | set.infoSet[i].buffer = set.buffers[i];
|
---|
| 1120 | set.infoSet[i].offset = 0; // This is the offset from the start of the buffer, so always 0 for now
|
---|
| 1121 | set.infoSet[i].range = bufferSize; // Size of the update starting from offset, or VK_WHOLE_SIZE
|
---|
[4a777d2] | 1122 | }
|
---|
| 1123 | }
|
---|
| 1124 |
|
---|
[bb76950] | 1125 | void VulkanGame::resizeBufferSet(BufferSet& set, VkDeviceSize newSize, VkCommandPool commandPool,
|
---|
| 1126 | VkQueue graphicsQueue, bool copyData) {
|
---|
| 1127 | for (size_t i = 0; i < set.buffers.size(); i++) {
|
---|
| 1128 | VkBuffer newBuffer;
|
---|
| 1129 | VkDeviceMemory newMemory;
|
---|
| 1130 |
|
---|
| 1131 | VulkanUtils::createBuffer(device, physicalDevice, newSize, set.usages, set.properties, newBuffer, newMemory);
|
---|
| 1132 |
|
---|
| 1133 | if (copyData) {
|
---|
| 1134 | VulkanUtils::copyBuffer(device, commandPool, set.buffers[i], newBuffer, 0, 0, set.infoSet[i].range,
|
---|
| 1135 | graphicsQueue);
|
---|
| 1136 | }
|
---|
| 1137 |
|
---|
| 1138 | vkDestroyBuffer(device, set.buffers[i], nullptr);
|
---|
| 1139 | vkFreeMemory(device, set.memory[i], nullptr);
|
---|
| 1140 |
|
---|
| 1141 | set.buffers[i] = newBuffer;
|
---|
| 1142 | set.memory[i] = newMemory;
|
---|
| 1143 |
|
---|
| 1144 | set.infoSet[i].buffer = set.buffers[i];
|
---|
| 1145 | set.infoSet[i].offset = 0; // This is the offset from the start of the buffer, so always 0 for now
|
---|
| 1146 | set.infoSet[i].range = newSize; // Size of the update starting from offset, or VK_WHOLE_SIZE
|
---|
| 1147 | }
|
---|
| 1148 | }
|
---|
| 1149 |
|
---|
[4e2c709] | 1150 | void VulkanGame::renderFrame(ImDrawData* draw_data) {
|
---|
| 1151 | VkResult result = vkAcquireNextImageKHR(device, swapChain, numeric_limits<uint64_t>::max(),
|
---|
| 1152 | imageAcquiredSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
|
---|
| 1153 |
|
---|
[880cfc2] | 1154 | if (result == VK_SUBOPTIMAL_KHR) {
|
---|
| 1155 | shouldRecreateSwapChain = true;
|
---|
| 1156 | } else if (result == VK_ERROR_OUT_OF_DATE_KHR) {
|
---|
[28ea92f] | 1157 | shouldRecreateSwapChain = true;
|
---|
[4e2c709] | 1158 | return;
|
---|
[28ea92f] | 1159 | } else {
|
---|
[4e2c709] | 1160 | VKUTIL_CHECK_RESULT(result, "failed to acquire swap chain image!");
|
---|
| 1161 | }
|
---|
| 1162 |
|
---|
[880cfc2] | 1163 | VKUTIL_CHECK_RESULT(
|
---|
| 1164 | vkWaitForFences(device, 1, &inFlightFences[imageIndex], VK_TRUE, numeric_limits<uint64_t>::max()),
|
---|
[4e2c709] | 1165 | "failed waiting for fence!");
|
---|
| 1166 |
|
---|
| 1167 | VKUTIL_CHECK_RESULT(vkResetFences(device, 1, &inFlightFences[imageIndex]),
|
---|
| 1168 | "failed to reset fence!");
|
---|
| 1169 |
|
---|
| 1170 | VKUTIL_CHECK_RESULT(vkResetCommandPool(device, commandPools[imageIndex], 0),
|
---|
| 1171 | "failed to reset command pool!");
|
---|
| 1172 |
|
---|
[880cfc2] | 1173 | VkCommandBufferBeginInfo beginInfo = {};
|
---|
| 1174 | beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
---|
[e469aed] | 1175 | beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
|
---|
[4e2c709] | 1176 |
|
---|
[880cfc2] | 1177 | VKUTIL_CHECK_RESULT(vkBeginCommandBuffer(commandBuffers[imageIndex], &beginInfo),
|
---|
[4e2c709] | 1178 | "failed to begin recording command buffer!");
|
---|
| 1179 |
|
---|
| 1180 | VkRenderPassBeginInfo renderPassInfo = {};
|
---|
| 1181 | renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
|
---|
| 1182 | renderPassInfo.renderPass = renderPass;
|
---|
| 1183 | renderPassInfo.framebuffer = swapChainFramebuffers[imageIndex];
|
---|
[e469aed] | 1184 | renderPassInfo.renderArea.offset = { 0, 0 };
|
---|
[4e2c709] | 1185 | renderPassInfo.renderArea.extent = swapChainExtent;
|
---|
| 1186 |
|
---|
| 1187 | array<VkClearValue, 2> clearValues = {};
|
---|
[e469aed] | 1188 | clearValues[0].color = { { 0.0f, 0.0f, 0.0f, 1.0f } };
|
---|
[4e2c709] | 1189 | clearValues[1].depthStencil = { 1.0f, 0 };
|
---|
| 1190 |
|
---|
| 1191 | renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
|
---|
| 1192 | renderPassInfo.pClearValues = clearValues.data();
|
---|
| 1193 |
|
---|
| 1194 | vkCmdBeginRenderPass(commandBuffers[imageIndex], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
|
---|
| 1195 |
|
---|
[4a777d2] | 1196 | // TODO: Find a more elegant, per-screen solution for this
|
---|
| 1197 | if (currentRenderScreenFn == &VulkanGame::renderGameScreen) {
|
---|
[567fa88] | 1198 | modelPipeline.createRenderCommands(commandBuffers[imageIndex], imageIndex, {});
|
---|
[4a777d2] | 1199 |
|
---|
| 1200 |
|
---|
| 1201 |
|
---|
| 1202 |
|
---|
| 1203 | }
|
---|
| 1204 |
|
---|
[4e2c709] | 1205 | ImGui_ImplVulkan_RenderDrawData(draw_data, commandBuffers[imageIndex]);
|
---|
| 1206 |
|
---|
| 1207 | vkCmdEndRenderPass(commandBuffers[imageIndex]);
|
---|
| 1208 |
|
---|
| 1209 | VKUTIL_CHECK_RESULT(vkEndCommandBuffer(commandBuffers[imageIndex]),
|
---|
| 1210 | "failed to record command buffer!");
|
---|
| 1211 |
|
---|
| 1212 | VkSemaphore waitSemaphores[] = { imageAcquiredSemaphores[currentFrame] };
|
---|
[880cfc2] | 1213 | VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
|
---|
[4e2c709] | 1214 | VkSemaphore signalSemaphores[] = { renderCompleteSemaphores[currentFrame] };
|
---|
| 1215 |
|
---|
| 1216 | VkSubmitInfo submitInfo = {};
|
---|
| 1217 | submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
---|
| 1218 | submitInfo.waitSemaphoreCount = 1;
|
---|
| 1219 | submitInfo.pWaitSemaphores = waitSemaphores;
|
---|
[880cfc2] | 1220 | submitInfo.pWaitDstStageMask = waitStages;
|
---|
[4e2c709] | 1221 | submitInfo.commandBufferCount = 1;
|
---|
| 1222 | submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
|
---|
| 1223 | submitInfo.signalSemaphoreCount = 1;
|
---|
| 1224 | submitInfo.pSignalSemaphores = signalSemaphores;
|
---|
| 1225 |
|
---|
| 1226 | VKUTIL_CHECK_RESULT(vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[imageIndex]),
|
---|
| 1227 | "failed to submit draw command buffer!");
|
---|
| 1228 | }
|
---|
| 1229 |
|
---|
| 1230 | void VulkanGame::presentFrame() {
|
---|
| 1231 | VkSemaphore signalSemaphores[] = { renderCompleteSemaphores[currentFrame] };
|
---|
| 1232 |
|
---|
| 1233 | VkPresentInfoKHR presentInfo = {};
|
---|
| 1234 | presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
|
---|
| 1235 | presentInfo.waitSemaphoreCount = 1;
|
---|
| 1236 | presentInfo.pWaitSemaphores = signalSemaphores;
|
---|
| 1237 | presentInfo.swapchainCount = 1;
|
---|
| 1238 | presentInfo.pSwapchains = &swapChain;
|
---|
| 1239 | presentInfo.pImageIndices = &imageIndex;
|
---|
| 1240 | presentInfo.pResults = nullptr;
|
---|
| 1241 |
|
---|
| 1242 | VkResult result = vkQueuePresentKHR(presentQueue, &presentInfo);
|
---|
| 1243 |
|
---|
[880cfc2] | 1244 | if (result == VK_SUBOPTIMAL_KHR) {
|
---|
| 1245 | shouldRecreateSwapChain = true;
|
---|
| 1246 | } else if (result == VK_ERROR_OUT_OF_DATE_KHR) {
|
---|
[28ea92f] | 1247 | shouldRecreateSwapChain = true;
|
---|
[4e2c709] | 1248 | return;
|
---|
[880cfc2] | 1249 | } else {
|
---|
| 1250 | VKUTIL_CHECK_RESULT(result, "failed to present swap chain image!");
|
---|
[4e2c709] | 1251 | }
|
---|
| 1252 |
|
---|
| 1253 | currentFrame = (currentFrame + 1) % swapChainImageCount;
|
---|
| 1254 | }
|
---|
| 1255 |
|
---|
[ce9dc9f] | 1256 | void VulkanGame::recreateSwapChain() {
|
---|
| 1257 | if (vkDeviceWaitIdle(device) != VK_SUCCESS) {
|
---|
| 1258 | throw runtime_error("failed to wait for device!");
|
---|
[6493e43] | 1259 | }
|
---|
| 1260 |
|
---|
[ce9dc9f] | 1261 | cleanupSwapChain();
|
---|
| 1262 |
|
---|
| 1263 | createSwapChain();
|
---|
| 1264 | createImageViews();
|
---|
| 1265 |
|
---|
| 1266 | // The depth buffer does need to be recreated with the swap chain since its dimensions depend on the window size
|
---|
| 1267 | // and resizing the window is a common reason to recreate the swapchain
|
---|
| 1268 | VulkanUtils::createDepthImage(device, physicalDevice, resourceCommandPool, findDepthFormat(), swapChainExtent,
|
---|
[8dcbf62] | 1269 | depthImage, graphicsQueue);
|
---|
[ce9dc9f] | 1270 |
|
---|
[e469aed] | 1271 | createRenderPass();
|
---|
| 1272 | createCommandPools();
|
---|
[ce9dc9f] | 1273 | createFramebuffers();
|
---|
| 1274 | createCommandBuffers();
|
---|
| 1275 | createSyncObjects();
|
---|
[187b0f5] | 1276 |
|
---|
[9d21aac] | 1277 | createBufferSet(sizeof(UBO_VP_mats),
|
---|
[6486ba8] | 1278 | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
---|
| 1279 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
---|
| 1280 | uniformBuffers_modelPipeline);
|
---|
| 1281 |
|
---|
| 1282 | createBufferSet(objects_modelPipeline.memorySize(),
|
---|
| 1283 | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT
|
---|
| 1284 | | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
|
---|
| 1285 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
---|
| 1286 | storageBuffers_modelPipeline);
|
---|
[4a777d2] | 1287 |
|
---|
| 1288 | modelPipeline.updateRenderPass(renderPass);
|
---|
| 1289 | modelPipeline.createPipeline("shaders/model-vert.spv", "shaders/model-frag.spv");
|
---|
[58453c3] | 1290 | modelPipeline.createDescriptorPool(swapChainImages.size());
|
---|
| 1291 | modelPipeline.createDescriptorSets(swapChainImages.size());
|
---|
[e469aed] | 1292 |
|
---|
[187b0f5] | 1293 | imageIndex = 0;
|
---|
[ce9dc9f] | 1294 | }
|
---|
| 1295 |
|
---|
| 1296 | void VulkanGame::cleanupSwapChain() {
|
---|
| 1297 | VulkanUtils::destroyVulkanImage(device, depthImage);
|
---|
| 1298 |
|
---|
| 1299 | for (VkFramebuffer framebuffer : swapChainFramebuffers) {
|
---|
| 1300 | vkDestroyFramebuffer(device, framebuffer, nullptr);
|
---|
[6493e43] | 1301 | }
|
---|
| 1302 |
|
---|
[ce9dc9f] | 1303 | for (uint32_t i = 0; i < swapChainImageCount; i++) {
|
---|
| 1304 | vkFreeCommandBuffers(device, commandPools[i], 1, &commandBuffers[i]);
|
---|
| 1305 | vkDestroyCommandPool(device, commandPools[i], nullptr);
|
---|
| 1306 | }
|
---|
| 1307 |
|
---|
[4a777d2] | 1308 | modelPipeline.cleanup();
|
---|
| 1309 |
|
---|
[c163d81] | 1310 | for (size_t i = 0; i < uniformBuffers_modelPipeline.buffers.size(); i++) {
|
---|
| 1311 | vkDestroyBuffer(device, uniformBuffers_modelPipeline.buffers[i], nullptr);
|
---|
| 1312 | vkFreeMemory(device, uniformBuffers_modelPipeline.memory[i], nullptr);
|
---|
[4a777d2] | 1313 | }
|
---|
| 1314 |
|
---|
[6486ba8] | 1315 | for (size_t i = 0; i < storageBuffers_modelPipeline.buffers.size(); i++) {
|
---|
| 1316 | vkDestroyBuffer(device, storageBuffers_modelPipeline.buffers[i], nullptr);
|
---|
| 1317 | vkFreeMemory(device, storageBuffers_modelPipeline.memory[i], nullptr);
|
---|
| 1318 | }
|
---|
| 1319 |
|
---|
[ce9dc9f] | 1320 | for (uint32_t i = 0; i < swapChainImageCount; i++) {
|
---|
| 1321 | vkDestroySemaphore(device, imageAcquiredSemaphores[i], nullptr);
|
---|
| 1322 | vkDestroySemaphore(device, renderCompleteSemaphores[i], nullptr);
|
---|
| 1323 | vkDestroyFence(device, inFlightFences[i], nullptr);
|
---|
[6493e43] | 1324 | }
|
---|
[ce9dc9f] | 1325 |
|
---|
| 1326 | vkDestroyRenderPass(device, renderPass, nullptr);
|
---|
| 1327 |
|
---|
| 1328 | for (VkImageView imageView : swapChainImageViews) {
|
---|
| 1329 | vkDestroyImageView(device, imageView, nullptr);
|
---|
| 1330 | }
|
---|
| 1331 |
|
---|
| 1332 | vkDestroySwapchainKHR(device, swapChain, nullptr);
|
---|
[6493e43] | 1333 | }
|
---|
[40eb092] | 1334 |
|
---|
[85b5fec] | 1335 | void VulkanGame::renderMainScreen(int width, int height) {
|
---|
[40eb092] | 1336 | {
|
---|
| 1337 | int padding = 4;
|
---|
[85b5fec] | 1338 | ImGui::SetNextWindowPos(vec2(-padding, -padding), ImGuiCond_Once);
|
---|
| 1339 | ImGui::SetNextWindowSize(vec2(width + 2 * padding, height + 2 * padding), ImGuiCond_Always);
|
---|
[40eb092] | 1340 | ImGui::Begin("WndMain", nullptr,
|
---|
| 1341 | ImGuiWindowFlags_NoTitleBar |
|
---|
| 1342 | ImGuiWindowFlags_NoResize |
|
---|
| 1343 | ImGuiWindowFlags_NoMove);
|
---|
| 1344 |
|
---|
[85b5fec] | 1345 | ButtonImGui btn("New Game");
|
---|
| 1346 |
|
---|
| 1347 | ImGui::InvisibleButton("", vec2(10, height / 6));
|
---|
| 1348 | if (btn.draw((width - btn.getWidth()) / 2)) {
|
---|
[40eb092] | 1349 | goToScreen(&VulkanGame::renderGameScreen);
|
---|
| 1350 | }
|
---|
| 1351 |
|
---|
[85b5fec] | 1352 | ButtonImGui btn2("Quit");
|
---|
| 1353 |
|
---|
| 1354 | ImGui::InvisibleButton("", vec2(10, 15));
|
---|
| 1355 | if (btn2.draw((width - btn2.getWidth()) / 2)) {
|
---|
[40eb092] | 1356 | quitGame();
|
---|
| 1357 | }
|
---|
| 1358 |
|
---|
| 1359 | ImGui::End();
|
---|
| 1360 | }
|
---|
| 1361 | }
|
---|
| 1362 |
|
---|
[85b5fec] | 1363 | void VulkanGame::renderGameScreen(int width, int height) {
|
---|
[40eb092] | 1364 | {
|
---|
[85b5fec] | 1365 | ImGui::SetNextWindowSize(vec2(130, 65), ImGuiCond_Once);
|
---|
| 1366 | ImGui::SetNextWindowPos(vec2(10, 50), ImGuiCond_Once);
|
---|
[40eb092] | 1367 | ImGui::Begin("WndStats", nullptr,
|
---|
| 1368 | ImGuiWindowFlags_NoTitleBar |
|
---|
| 1369 | ImGuiWindowFlags_NoResize |
|
---|
| 1370 | ImGuiWindowFlags_NoMove);
|
---|
| 1371 |
|
---|
| 1372 | //ImGui::Text(ImGui::GetIO().Framerate);
|
---|
| 1373 | renderGuiValueList(valueLists["stats value list"]);
|
---|
| 1374 |
|
---|
| 1375 | ImGui::End();
|
---|
| 1376 | }
|
---|
| 1377 |
|
---|
| 1378 | {
|
---|
[85b5fec] | 1379 | ImGui::SetNextWindowSize(vec2(250, 35), ImGuiCond_Once);
|
---|
| 1380 | ImGui::SetNextWindowPos(vec2(width - 260, 10), ImGuiCond_Always);
|
---|
[40eb092] | 1381 | ImGui::Begin("WndMenubar", nullptr,
|
---|
| 1382 | ImGuiWindowFlags_NoTitleBar |
|
---|
| 1383 | ImGuiWindowFlags_NoResize |
|
---|
| 1384 | ImGuiWindowFlags_NoMove);
|
---|
[85b5fec] | 1385 | ImGui::InvisibleButton("", vec2(155, 18));
|
---|
[40eb092] | 1386 | ImGui::SameLine();
|
---|
| 1387 | if (ImGui::Button("Main Menu")) {
|
---|
| 1388 | goToScreen(&VulkanGame::renderMainScreen);
|
---|
| 1389 | }
|
---|
| 1390 | ImGui::End();
|
---|
| 1391 | }
|
---|
| 1392 |
|
---|
| 1393 | {
|
---|
[85b5fec] | 1394 | ImGui::SetNextWindowSize(vec2(200, 200), ImGuiCond_Once);
|
---|
| 1395 | ImGui::SetNextWindowPos(vec2(width - 210, 60), ImGuiCond_Always);
|
---|
[40eb092] | 1396 | ImGui::Begin("WndDebug", nullptr,
|
---|
| 1397 | ImGuiWindowFlags_NoTitleBar |
|
---|
| 1398 | ImGuiWindowFlags_NoResize |
|
---|
| 1399 | ImGuiWindowFlags_NoMove);
|
---|
| 1400 |
|
---|
| 1401 | renderGuiValueList(valueLists["debug value list"]);
|
---|
| 1402 |
|
---|
| 1403 | ImGui::End();
|
---|
| 1404 | }
|
---|
| 1405 | }
|
---|
| 1406 |
|
---|
| 1407 | void VulkanGame::initGuiValueLists(map<string, vector<UIValue>>& valueLists) {
|
---|
| 1408 | valueLists["stats value list"] = vector<UIValue>();
|
---|
| 1409 | valueLists["debug value list"] = vector<UIValue>();
|
---|
| 1410 | }
|
---|
| 1411 |
|
---|
[85b5fec] | 1412 | // TODO: Probably turn this into a UI widget class
|
---|
[40eb092] | 1413 | void VulkanGame::renderGuiValueList(vector<UIValue>& values) {
|
---|
| 1414 | float maxWidth = 0.0f;
|
---|
| 1415 | float cursorStartPos = ImGui::GetCursorPosX();
|
---|
| 1416 |
|
---|
| 1417 | for (vector<UIValue>::iterator it = values.begin(); it != values.end(); it++) {
|
---|
| 1418 | float textWidth = ImGui::CalcTextSize(it->label.c_str()).x;
|
---|
| 1419 |
|
---|
| 1420 | if (maxWidth < textWidth)
|
---|
| 1421 | maxWidth = textWidth;
|
---|
| 1422 | }
|
---|
| 1423 |
|
---|
| 1424 | stringstream ss;
|
---|
| 1425 |
|
---|
| 1426 | // TODO: Possibly implement this based on gui/ui-value.hpp instead and use templates
|
---|
| 1427 | // to keep track of the type. This should make it a bit easier to use and maintain
|
---|
| 1428 | // Also, implement this in a way that's agnostic to the UI renderer.
|
---|
| 1429 | for (vector<UIValue>::iterator it = values.begin(); it != values.end(); it++) {
|
---|
| 1430 | ss.str("");
|
---|
| 1431 | ss.clear();
|
---|
| 1432 |
|
---|
| 1433 | switch (it->type) {
|
---|
| 1434 | case UIVALUE_INT:
|
---|
| 1435 | ss << it->label << ": " << *(unsigned int*)it->value;
|
---|
| 1436 | break;
|
---|
| 1437 | case UIVALUE_DOUBLE:
|
---|
| 1438 | ss << it->label << ": " << *(double*)it->value;
|
---|
| 1439 | break;
|
---|
| 1440 | }
|
---|
| 1441 |
|
---|
| 1442 | float textWidth = ImGui::CalcTextSize(it->label.c_str()).x;
|
---|
| 1443 |
|
---|
| 1444 | ImGui::SetCursorPosX(cursorStartPos + maxWidth - textWidth);
|
---|
| 1445 | //ImGui::Text("%s", ss.str().c_str());
|
---|
| 1446 | ImGui::Text("%s: %.1f", it->label.c_str(), *(float*)it->value);
|
---|
| 1447 | }
|
---|
| 1448 | }
|
---|
| 1449 |
|
---|
[85b5fec] | 1450 | void VulkanGame::goToScreen(void (VulkanGame::* renderScreenFn)(int width, int height)) {
|
---|
[40eb092] | 1451 | currentRenderScreenFn = renderScreenFn;
|
---|
[85b5fec] | 1452 |
|
---|
| 1453 | // TODO: Maybe just set shouldRecreateSwapChain to true instead. Check this render loop logic
|
---|
| 1454 | // to make sure there'd be no issues
|
---|
| 1455 | //recreateSwapChain();
|
---|
[40eb092] | 1456 | }
|
---|
| 1457 |
|
---|
| 1458 | void VulkanGame::quitGame() {
|
---|
| 1459 | done = true;
|
---|
| 1460 | }
|
---|