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

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

In vulkangame, add the ability to create vulkan resoirces and descriptor sets for shader uniforms (images and ubos)

  • Property mode set to 100644
File size: 24.7 KB
Line 
1#include "vulkan-game.hpp"
2
3#include <array>
4#include <iostream>
5#include <set>
6
7#include "consts.hpp"
8#include "logger.hpp"
9
10#include "utils.hpp"
11
12using namespace std;
13
14struct UniformBufferObject {
15 alignas(16) mat4 model;
16 alignas(16) mat4 view;
17 alignas(16) mat4 proj;
18};
19
20VulkanGame::VulkanGame() {
21 gui = nullptr;
22 window = nullptr;
23}
24
25VulkanGame::~VulkanGame() {
26}
27
28void VulkanGame::run(int width, int height, unsigned char guiFlags) {
29 cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
30
31 cout << "Vulkan Game" << endl;
32
33 // This gets the runtime version, use SDL_VERSION() for the comppile-time version
34 // TODO: Create a game-gui function to get the gui version and retrieve it that way
35 SDL_GetVersion(&sdlVersion);
36
37 // TODO: Refactor the logger api to be more flexible,
38 // esp. since gl_log() and gl_log_err() have issues printing anything besides stirngs
39 restart_gl_log();
40 gl_log("starting SDL\n%s.%s.%s",
41 to_string(sdlVersion.major).c_str(),
42 to_string(sdlVersion.minor).c_str(),
43 to_string(sdlVersion.patch).c_str());
44
45 open_log();
46 get_log() << "starting SDL" << endl;
47 get_log() <<
48 (int)sdlVersion.major << "." <<
49 (int)sdlVersion.minor << "." <<
50 (int)sdlVersion.patch << endl;
51
52 if (initWindow(width, height, guiFlags) == RTWO_ERROR) {
53 return;
54 }
55
56 initVulkan();
57 mainLoop();
58 cleanup();
59
60 close_log();
61}
62
63// TODO: Make some more initi functions, or call this initUI if the
64// amount of things initialized here keeps growing
65bool VulkanGame::initWindow(int width, int height, unsigned char guiFlags) {
66 // TODO: Put all fonts, textures, and images in the assets folder
67 gui = new GameGui_SDL();
68
69 if (gui->init() == RTWO_ERROR) {
70 // TODO: Also print these sorts of errors to the log
71 cout << "UI library could not be initialized!" << endl;
72 cout << gui->getError() << endl;
73 return RTWO_ERROR;
74 }
75
76 window = (SDL_Window*) gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
77 if (window == nullptr) {
78 cout << "Window could not be created!" << endl;
79 cout << gui->getError() << endl;
80 return RTWO_ERROR;
81 }
82
83 cout << "Target window size: (" << width << ", " << height << ")" << endl;
84 cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
85
86 renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
87 if (renderer == nullptr) {
88 cout << "Renderer could not be created!" << endl;
89 cout << gui->getError() << endl;
90 return RTWO_ERROR;
91 }
92
93 SDL_VERSION(&sdlVersion);
94
95 // In SDL 2.0.10 (currently, the latest), SDL_TEXTUREACCESS_TARGET is required to get a transparent overlay working
96 // However, the latest SDL version available through homebrew on Mac is 2.0.9, which requires SDL_TEXTUREACCESS_STREAMING
97 // I tried building sdl 2.0.10 (and sdl_image and sdl_ttf) from source on Mac, but had some issues, so this is easier
98 // until the homebrew recipe is updated
99 if (sdlVersion.major == 2 && sdlVersion.minor == 0 && sdlVersion.patch == 9) {
100 uiOverlay = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING,
101 gui->getWindowWidth(), gui->getWindowHeight());
102 } else {
103 uiOverlay = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET,
104 gui->getWindowWidth(), gui->getWindowHeight());
105 }
106
107 if (uiOverlay == nullptr) {
108 cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << endl;
109 }
110 if (SDL_SetTextureBlendMode(uiOverlay, SDL_BLENDMODE_BLEND) != 0) {
111 cout << "Unable to set texture blend mode! SDL Error: " << SDL_GetError() << endl;
112 }
113
114 return RTWO_SUCCESS;
115}
116
117void VulkanGame::initVulkan() {
118 const vector<const char*> validationLayers = {
119 "VK_LAYER_KHRONOS_validation"
120 };
121 const vector<const char*> deviceExtensions = {
122 VK_KHR_SWAPCHAIN_EXTENSION_NAME
123 };
124
125 createVulkanInstance(validationLayers);
126 setupDebugMessenger();
127 createVulkanSurface();
128 pickPhysicalDevice(deviceExtensions);
129 createLogicalDevice(validationLayers, deviceExtensions);
130 createSwapChain();
131 createImageViews();
132 createRenderPass();
133 createCommandPool();
134
135 createVulkanResources();
136
137 graphicsPipelines.push_back(GraphicsPipeline_Vulkan(device, renderPass, viewport, sizeof(Vertex)));
138
139 graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::pos));
140 graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::color));
141 graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&Vertex::texCoord));
142
143 graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
144 VK_SHADER_STAGE_VERTEX_BIT, &uniformBufferInfoList);
145 graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
146 VK_SHADER_STAGE_FRAGMENT_BIT, &floorTextureImageDescriptor);
147
148 graphicsPipelines.back().createDescriptorSetLayout();
149 graphicsPipelines.back().createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
150 graphicsPipelines.back().createDescriptorPool(swapChainImages);
151 graphicsPipelines.back().createDescriptorSets(swapChainImages);
152
153 graphicsPipelines.push_back(GraphicsPipeline_Vulkan(device, renderPass, viewport, sizeof(OverlayVertex)));
154
155 graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&OverlayVertex::pos));
156 graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&OverlayVertex::texCoord));
157
158 graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
159 VK_SHADER_STAGE_FRAGMENT_BIT, &sdlOverlayImageDescriptor);
160
161 graphicsPipelines.back().createDescriptorSetLayout();
162 graphicsPipelines.back().createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
163 graphicsPipelines.back().createDescriptorPool(swapChainImages);
164 graphicsPipelines.back().createDescriptorSets(swapChainImages);
165
166 cout << "Created " << graphicsPipelines.size() << " graphics pipelines" << endl;
167}
168
169void VulkanGame::mainLoop() {
170 UIEvent e;
171 bool quit = false;
172
173 SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
174
175 while (!quit) {
176 gui->processEvents();
177
178 while (gui->pollEvent(&e)) {
179 switch(e.type) {
180 case UI_EVENT_QUIT:
181 cout << "Quit event detected" << endl;
182 quit = true;
183 break;
184 case UI_EVENT_WINDOW:
185 cout << "Window event detected" << endl;
186 // Currently unused
187 break;
188 case UI_EVENT_WINDOWRESIZE:
189 cout << "Window resize event detected" << endl;
190 framebufferResized = true;
191 break;
192 case UI_EVENT_KEY:
193 if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
194 quit = true;
195 } else {
196 cout << "Key event detected" << endl;
197 }
198 break;
199 case UI_EVENT_MOUSEBUTTONDOWN:
200 cout << "Mouse button down event detected" << endl;
201 break;
202 case UI_EVENT_MOUSEBUTTONUP:
203 cout << "Mouse button up event detected" << endl;
204 break;
205 case UI_EVENT_MOUSEMOTION:
206 break;
207 case UI_EVENT_UNKNOWN:
208 cout << "Unknown event type: 0x" << hex << e.unknown.eventType << dec << endl;
209 break;
210 default:
211 cout << "Unhandled UI event: " << e.type << endl;
212 }
213 }
214
215 renderUI();
216 renderScene();
217 }
218
219 vkDeviceWaitIdle(device);
220}
221
222void VulkanGame::renderUI() {
223 SDL_RenderClear(renderer);
224 SDL_RenderPresent(renderer);
225}
226
227void VulkanGame::renderScene() {
228}
229
230void VulkanGame::cleanup() {
231 cleanupSwapChain();
232
233 for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
234 pipeline.cleanupBuffers();
235 }
236
237 vkDestroyCommandPool(device, commandPool, nullptr);
238 vkDestroyDevice(device, nullptr);
239 vkDestroySurfaceKHR(instance, surface, nullptr);
240
241 if (ENABLE_VALIDATION_LAYERS) {
242 VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
243 }
244
245 vkDestroyInstance(instance, nullptr);
246
247 // TODO: Check if any of these functions accept null parameters
248 // If they do, I don't need to check for that
249
250 if (uiOverlay != nullptr) {
251 SDL_DestroyTexture(uiOverlay);
252 uiOverlay = nullptr;
253 }
254
255 SDL_DestroyRenderer(renderer);
256 renderer = nullptr;
257
258 gui->destroyWindow();
259 gui->shutdown();
260 delete gui;
261}
262
263void VulkanGame::createVulkanInstance(const vector<const char*> &validationLayers) {
264 if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
265 throw runtime_error("validation layers requested, but not available!");
266 }
267
268 VkApplicationInfo appInfo = {};
269 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
270 appInfo.pApplicationName = "Vulkan Game";
271 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
272 appInfo.pEngineName = "No Engine";
273 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
274 appInfo.apiVersion = VK_API_VERSION_1_0;
275
276 VkInstanceCreateInfo createInfo = {};
277 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
278 createInfo.pApplicationInfo = &appInfo;
279
280 vector<const char*> extensions = gui->getRequiredExtensions();
281 if (ENABLE_VALIDATION_LAYERS) {
282 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
283 }
284
285 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
286 createInfo.ppEnabledExtensionNames = extensions.data();
287
288 cout << endl << "Extensions:" << endl;
289 for (const char* extensionName : extensions) {
290 cout << extensionName << endl;
291 }
292 cout << endl;
293
294 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
295 if (ENABLE_VALIDATION_LAYERS) {
296 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
297 createInfo.ppEnabledLayerNames = validationLayers.data();
298
299 populateDebugMessengerCreateInfo(debugCreateInfo);
300 createInfo.pNext = &debugCreateInfo;
301 } else {
302 createInfo.enabledLayerCount = 0;
303
304 createInfo.pNext = nullptr;
305 }
306
307 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
308 throw runtime_error("failed to create instance!");
309 }
310}
311
312void VulkanGame::setupDebugMessenger() {
313 if (!ENABLE_VALIDATION_LAYERS) return;
314
315 VkDebugUtilsMessengerCreateInfoEXT createInfo;
316 populateDebugMessengerCreateInfo(createInfo);
317
318 if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
319 throw runtime_error("failed to set up debug messenger!");
320 }
321}
322
323void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
324 createInfo = {};
325 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
326 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;
327 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;
328 createInfo.pfnUserCallback = debugCallback;
329}
330
331VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
332 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
333 VkDebugUtilsMessageTypeFlagsEXT messageType,
334 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
335 void* pUserData) {
336 cerr << "validation layer: " << pCallbackData->pMessage << endl;
337
338 return VK_FALSE;
339}
340
341void VulkanGame::createVulkanSurface() {
342 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
343 throw runtime_error("failed to create window surface!");
344 }
345}
346
347void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
348 uint32_t deviceCount = 0;
349 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
350
351 if (deviceCount == 0) {
352 throw runtime_error("failed to find GPUs with Vulkan support!");
353 }
354
355 vector<VkPhysicalDevice> devices(deviceCount);
356 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
357
358 cout << endl << "Graphics cards:" << endl;
359 for (const VkPhysicalDevice& device : devices) {
360 if (isDeviceSuitable(device, deviceExtensions)) {
361 physicalDevice = device;
362 break;
363 }
364 }
365 cout << endl;
366
367 if (physicalDevice == VK_NULL_HANDLE) {
368 throw runtime_error("failed to find a suitable GPU!");
369 }
370}
371
372bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice,
373 const vector<const char*>& deviceExtensions) {
374 VkPhysicalDeviceProperties deviceProperties;
375 vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
376
377 cout << "Device: " << deviceProperties.deviceName << endl;
378
379 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
380 bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
381 bool swapChainAdequate = false;
382
383 if (extensionsSupported) {
384 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
385 swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
386 }
387
388 VkPhysicalDeviceFeatures supportedFeatures;
389 vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
390
391 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
392}
393
394void VulkanGame::createLogicalDevice(
395 const vector<const char*> validationLayers,
396 const vector<const char*>& deviceExtensions) {
397 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
398
399 vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
400 set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
401
402 float queuePriority = 1.0f;
403 for (uint32_t queueFamily : uniqueQueueFamilies) {
404 VkDeviceQueueCreateInfo queueCreateInfo = {};
405 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
406 queueCreateInfo.queueFamilyIndex = queueFamily;
407 queueCreateInfo.queueCount = 1;
408 queueCreateInfo.pQueuePriorities = &queuePriority;
409
410 queueCreateInfoList.push_back(queueCreateInfo);
411 }
412
413 VkPhysicalDeviceFeatures deviceFeatures = {};
414 deviceFeatures.samplerAnisotropy = VK_TRUE;
415
416 VkDeviceCreateInfo createInfo = {};
417 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
418 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
419 createInfo.pQueueCreateInfos = queueCreateInfoList.data();
420
421 createInfo.pEnabledFeatures = &deviceFeatures;
422
423 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
424 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
425
426 // These fields are ignored by up-to-date Vulkan implementations,
427 // but it's a good idea to set them for backwards compatibility
428 if (ENABLE_VALIDATION_LAYERS) {
429 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
430 createInfo.ppEnabledLayerNames = validationLayers.data();
431 } else {
432 createInfo.enabledLayerCount = 0;
433 }
434
435 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
436 throw runtime_error("failed to create logical device!");
437 }
438
439 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
440 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
441}
442
443void VulkanGame::createSwapChain() {
444 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
445
446 VkSurfaceFormatKHR surfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(swapChainSupport.formats);
447 VkPresentModeKHR presentMode = VulkanUtils::chooseSwapPresentMode(swapChainSupport.presentModes);
448 VkExtent2D extent = VulkanUtils::chooseSwapExtent(swapChainSupport.capabilities, gui->getWindowWidth(), gui->getWindowHeight());
449
450 uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
451 if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
452 imageCount = swapChainSupport.capabilities.maxImageCount;
453 }
454
455 VkSwapchainCreateInfoKHR createInfo = {};
456 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
457 createInfo.surface = surface;
458 createInfo.minImageCount = imageCount;
459 createInfo.imageFormat = surfaceFormat.format;
460 createInfo.imageColorSpace = surfaceFormat.colorSpace;
461 createInfo.imageExtent = extent;
462 createInfo.imageArrayLayers = 1;
463 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
464
465 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
466 uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
467
468 if (indices.graphicsFamily != indices.presentFamily) {
469 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
470 createInfo.queueFamilyIndexCount = 2;
471 createInfo.pQueueFamilyIndices = queueFamilyIndices;
472 } else {
473 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
474 createInfo.queueFamilyIndexCount = 0;
475 createInfo.pQueueFamilyIndices = nullptr;
476 }
477
478 createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
479 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
480 createInfo.presentMode = presentMode;
481 createInfo.clipped = VK_TRUE;
482 createInfo.oldSwapchain = VK_NULL_HANDLE;
483
484 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
485 throw runtime_error("failed to create swap chain!");
486 }
487
488 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
489 swapChainImages.resize(imageCount);
490 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
491
492 swapChainImageFormat = surfaceFormat.format;
493 viewport = { 0, 0, (int)extent.width, (int)extent.height };
494}
495
496void VulkanGame::createImageViews() {
497 swapChainImageViews.resize(swapChainImages.size());
498
499 for (size_t i = 0; i < swapChainImages.size(); i++) {
500 swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainImageFormat,
501 VK_IMAGE_ASPECT_COLOR_BIT);
502 }
503}
504
505void VulkanGame::createRenderPass() {
506 VkAttachmentDescription colorAttachment = {};
507 colorAttachment.format = swapChainImageFormat;
508 colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
509 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
510 colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
511 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
512 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
513 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
514 colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
515
516 VkAttachmentReference colorAttachmentRef = {};
517 colorAttachmentRef.attachment = 0;
518 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
519
520 VkAttachmentDescription depthAttachment = {};
521 depthAttachment.format = findDepthFormat();
522 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
523 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
524 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
525 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
526 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
527 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
528 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
529
530 VkAttachmentReference depthAttachmentRef = {};
531 depthAttachmentRef.attachment = 1;
532 depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
533
534 VkSubpassDescription subpass = {};
535 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
536 subpass.colorAttachmentCount = 1;
537 subpass.pColorAttachments = &colorAttachmentRef;
538 subpass.pDepthStencilAttachment = &depthAttachmentRef;
539
540 VkSubpassDependency dependency = {};
541 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
542 dependency.dstSubpass = 0;
543 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
544 dependency.srcAccessMask = 0;
545 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
546 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
547
548 array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
549 VkRenderPassCreateInfo renderPassInfo = {};
550 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
551 renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
552 renderPassInfo.pAttachments = attachments.data();
553 renderPassInfo.subpassCount = 1;
554 renderPassInfo.pSubpasses = &subpass;
555 renderPassInfo.dependencyCount = 1;
556 renderPassInfo.pDependencies = &dependency;
557
558 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
559 throw runtime_error("failed to create render pass!");
560 }
561}
562
563VkFormat VulkanGame::findDepthFormat() {
564 return VulkanUtils::findSupportedFormat(
565 physicalDevice,
566 { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
567 VK_IMAGE_TILING_OPTIMAL,
568 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
569 );
570}
571
572void VulkanGame::createCommandPool() {
573 QueueFamilyIndices queueFamilyIndices = VulkanUtils::findQueueFamilies(physicalDevice, surface);;
574
575 VkCommandPoolCreateInfo poolInfo = {};
576 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
577 poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
578 poolInfo.flags = 0;
579
580 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
581 throw runtime_error("failed to create graphics command pool!");
582 }
583}
584
585void VulkanGame::createVulkanResources() {
586 createTextureSampler();
587 createUniformBuffers();
588
589 // TODO: Make sure that Vulkan complains about these images not being destroyed and then destroy them
590
591 VulkanUtils::createVulkanImageFromFile(device, physicalDevice, commandPool, "textures/texture.jpg",
592 floorTextureImage, graphicsQueue);
593 VulkanUtils::createVulkanImageFromSDLTexture(device, physicalDevice, uiOverlay, sdlOverlayImage);
594
595 floorTextureImageDescriptor = {};
596 floorTextureImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
597 floorTextureImageDescriptor.imageView = floorTextureImage.imageView;
598 floorTextureImageDescriptor.sampler = textureSampler;
599
600 sdlOverlayImageDescriptor = {};
601 sdlOverlayImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
602 sdlOverlayImageDescriptor.imageView = sdlOverlayImage.imageView;
603 sdlOverlayImageDescriptor.sampler = textureSampler;
604}
605
606void VulkanGame::createTextureSampler() {
607 VkSamplerCreateInfo samplerInfo = {};
608 samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
609 samplerInfo.magFilter = VK_FILTER_LINEAR;
610 samplerInfo.minFilter = VK_FILTER_LINEAR;
611
612 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
613 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
614 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
615
616 samplerInfo.anisotropyEnable = VK_TRUE;
617 samplerInfo.maxAnisotropy = 16;
618 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
619 samplerInfo.unnormalizedCoordinates = VK_FALSE;
620 samplerInfo.compareEnable = VK_FALSE;
621 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
622 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
623 samplerInfo.mipLodBias = 0.0f;
624 samplerInfo.minLod = 0.0f;
625 samplerInfo.maxLod = 0.0f;
626
627 if (vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) {
628 throw runtime_error("failed to create texture sampler!");
629 }
630}
631
632void VulkanGame::createUniformBuffers() {
633 VkDeviceSize bufferSize = sizeof(UniformBufferObject);
634
635 uniformBuffers.resize(swapChainImages.size());
636 uniformBuffersMemory.resize(swapChainImages.size());
637 uniformBufferInfoList.resize(swapChainImages.size());
638
639 for (size_t i = 0; i < swapChainImages.size(); i++) {
640 VulkanUtils::createBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
641 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
642 uniformBuffers[i], uniformBuffersMemory[i]);
643
644 uniformBufferInfoList[i].buffer = uniformBuffers[i];
645 uniformBufferInfoList[i].offset = 0;
646 uniformBufferInfoList[i].range = sizeof(UniformBufferObject);
647 }
648}
649
650void VulkanGame::cleanupSwapChain() {
651 for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
652 pipeline.cleanup();
653 }
654
655 vkDestroyRenderPass(device, renderPass, nullptr);
656
657 for (VkImageView imageView : swapChainImageViews) {
658 vkDestroyImageView(device, imageView, nullptr);
659 }
660
661 vkDestroySwapchainKHR(device, swapChain, nullptr);
662}
Note: See TracBrowser for help on using the repository browser.