source: opengl-game/sdl-game.cpp@ 8dcbf62

feature/imgui-sdl
Last change on this file since 8dcbf62 was 8dcbf62, checked in by Dmitry Portnoy <dportnoy@…>, 3 years ago

Add some functionality to VulkanBuffer, and modify VulkanGame::addObject() to call VulkanBuffer::add()

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