source: opengl-game/vulkan-game.cpp@ 502bd0b

feature/imgui-sdl points-test
Last change on this file since 502bd0b was 502bd0b, checked in by Dmitry Portnoy <dmp1488@…>, 5 years ago

In vulkangame, add code to create a swap chain

  • Property mode set to 100644
File size: 14.1 KB
Line 
1#include "vulkan-game.hpp"
2
3#include <iostream>
4#include <set>
5
6#include "consts.hpp"
7#include "logger.hpp"
8
9#include "vulkan-utils.hpp"
10
11using namespace std;
12
13VulkanGame::VulkanGame() {
14 gui = nullptr;
15 window = nullptr;
16}
17
18VulkanGame::~VulkanGame() {
19}
20
21void VulkanGame::run(int width, int height, unsigned char guiFlags) {
22 cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
23
24 cout << "Vulkan Game" << endl;
25
26 // This gets the runtime version, use SDL_VERSION() for the comppile-time version
27 // TODO: Create a game-gui function to get the gui version and retrieve it that way
28 SDL_GetVersion(&sdlVersion);
29
30 // TODO: Refactor the logger api to be more flexible,
31 // esp. since gl_log() and gl_log_err() have issues printing anything besides stirngs
32 restart_gl_log();
33 gl_log("starting SDL\n%s.%s.%s",
34 to_string(sdlVersion.major).c_str(),
35 to_string(sdlVersion.minor).c_str(),
36 to_string(sdlVersion.patch).c_str());
37
38 open_log();
39 get_log() << "starting SDL" << endl;
40 get_log() <<
41 (int)sdlVersion.major << "." <<
42 (int)sdlVersion.minor << "." <<
43 (int)sdlVersion.patch << endl;
44
45 if (initWindow(width, height, guiFlags) == RTWO_ERROR) {
46 return;
47 }
48
49 initVulkan();
50 mainLoop();
51 cleanup();
52
53 close_log();
54}
55
56// TODO: Make some more initi functions, or call this initUI if the
57// amount of things initialized here keeps growing
58bool VulkanGame::initWindow(int width, int height, unsigned char guiFlags) {
59 // TODO: Put all fonts, textures, and images in the assets folder
60 gui = new GameGui_SDL();
61
62 if (gui->init() == RTWO_ERROR) {
63 // TODO: Also print these sorts of errors to the log
64 cout << "UI library could not be initialized!" << endl;
65 cout << gui->getError() << endl;
66 return RTWO_ERROR;
67 }
68
69 window = (SDL_Window*) gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
70 if (window == nullptr) {
71 cout << "Window could not be created!" << endl;
72 cout << gui->getError() << endl;
73 return RTWO_ERROR;
74 }
75
76 cout << "Target window size: (" << width << ", " << height << ")" << endl;
77 cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
78
79 renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
80 if (renderer == nullptr) {
81 cout << "Renderer could not be created!" << endl;
82 cout << gui->getError() << endl;
83 return RTWO_ERROR;
84 }
85
86 return RTWO_SUCCESS;
87}
88
89void VulkanGame::initVulkan() {
90 const vector<const char*> validationLayers = {
91 "VK_LAYER_KHRONOS_validation"
92 };
93 const vector<const char*> deviceExtensions = {
94 VK_KHR_SWAPCHAIN_EXTENSION_NAME
95 };
96
97 createVulkanInstance(validationLayers);
98 setupDebugMessenger();
99 createVulkanSurface();
100 pickPhysicalDevice(deviceExtensions);
101 createLogicalDevice(validationLayers, deviceExtensions);
102 createSwapChain();
103}
104
105void VulkanGame::mainLoop() {
106 UIEvent e;
107 bool quit = false;
108
109 SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
110
111 while (!quit) {
112 gui->processEvents();
113
114 while (gui->pollEvent(&e)) {
115 switch(e.type) {
116 case UI_EVENT_QUIT:
117 cout << "Quit event detected" << endl;
118 quit = true;
119 break;
120 case UI_EVENT_WINDOW:
121 cout << "Window event detected" << endl;
122 // Currently unused
123 break;
124 case UI_EVENT_KEY:
125 if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
126 quit = true;
127 } else {
128 cout << "Key event detected" << endl;
129 }
130 break;
131 case UI_EVENT_MOUSEBUTTONDOWN:
132 cout << "Mouse button down event detected" << endl;
133 break;
134 case UI_EVENT_MOUSEBUTTONUP:
135 cout << "Mouse button up event detected" << endl;
136 break;
137 case UI_EVENT_MOUSEMOTION:
138 break;
139 default:
140 cout << "Unhandled UI event: " << e.type << endl;
141 }
142 }
143
144 renderUI();
145 renderScene();
146 }
147
148 vkDeviceWaitIdle(device);
149}
150
151void VulkanGame::renderUI() {
152 SDL_RenderClear(renderer);
153 SDL_RenderPresent(renderer);
154}
155
156void VulkanGame::renderScene() {
157}
158
159void VulkanGame::cleanup() {
160 cleanupSwapChain();
161
162 vkDestroyDevice(device, nullptr);
163 vkDestroySurfaceKHR(instance, surface, nullptr);
164
165 if (ENABLE_VALIDATION_LAYERS) {
166 VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
167 }
168
169 vkDestroyInstance(instance, nullptr);
170
171 SDL_DestroyRenderer(renderer);
172 renderer = nullptr;
173
174 gui->destroyWindow();
175 gui->shutdown();
176 delete gui;
177}
178
179void VulkanGame::cleanupSwapChain() {
180 vkDestroySwapchainKHR(device, swapChain, nullptr);
181}
182
183void VulkanGame::createVulkanInstance(const vector<const char*> &validationLayers) {
184 if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
185 throw runtime_error("validation layers requested, but not available!");
186 }
187
188 VkApplicationInfo appInfo = {};
189 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
190 appInfo.pApplicationName = "Vulkan Game";
191 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
192 appInfo.pEngineName = "No Engine";
193 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
194 appInfo.apiVersion = VK_API_VERSION_1_0;
195
196 VkInstanceCreateInfo createInfo = {};
197 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
198 createInfo.pApplicationInfo = &appInfo;
199
200 vector<const char*> extensions = gui->getRequiredExtensions();
201 if (ENABLE_VALIDATION_LAYERS) {
202 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
203 }
204
205 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
206 createInfo.ppEnabledExtensionNames = extensions.data();
207
208 cout << endl << "Extensions:" << endl;
209 for (const char* extensionName : extensions) {
210 cout << extensionName << endl;
211 }
212 cout << endl;
213
214 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
215 if (ENABLE_VALIDATION_LAYERS) {
216 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
217 createInfo.ppEnabledLayerNames = validationLayers.data();
218
219 populateDebugMessengerCreateInfo(debugCreateInfo);
220 createInfo.pNext = &debugCreateInfo;
221 } else {
222 createInfo.enabledLayerCount = 0;
223
224 createInfo.pNext = nullptr;
225 }
226
227 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
228 throw runtime_error("failed to create instance!");
229 }
230}
231
232void VulkanGame::setupDebugMessenger() {
233 if (!ENABLE_VALIDATION_LAYERS) return;
234
235 VkDebugUtilsMessengerCreateInfoEXT createInfo;
236 populateDebugMessengerCreateInfo(createInfo);
237
238 if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
239 throw runtime_error("failed to set up debug messenger!");
240 }
241}
242
243void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
244 createInfo = {};
245 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
246 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;
247 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;
248 createInfo.pfnUserCallback = debugCallback;
249}
250
251VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
252 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
253 VkDebugUtilsMessageTypeFlagsEXT messageType,
254 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
255 void* pUserData) {
256 cerr << "validation layer: " << pCallbackData->pMessage << endl;
257
258 return VK_FALSE;
259}
260
261void VulkanGame::createVulkanSurface() {
262 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
263 throw runtime_error("failed to create window surface!");
264 }
265}
266
267void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
268 uint32_t deviceCount = 0;
269 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
270
271 if (deviceCount == 0) {
272 throw runtime_error("failed to find GPUs with Vulkan support!");
273 }
274
275 vector<VkPhysicalDevice> devices(deviceCount);
276 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
277
278 cout << endl << "Graphics cards:" << endl;
279 for (const VkPhysicalDevice& device : devices) {
280 if (isDeviceSuitable(device, deviceExtensions)) {
281 physicalDevice = device;
282 break;
283 }
284 }
285 cout << endl;
286
287 if (physicalDevice == VK_NULL_HANDLE) {
288 throw runtime_error("failed to find a suitable GPU!");
289 }
290}
291
292bool VulkanGame::isDeviceSuitable(VkPhysicalDevice device, const vector<const char*>& deviceExtensions) {
293 VkPhysicalDeviceProperties deviceProperties;
294 vkGetPhysicalDeviceProperties(device, &deviceProperties);
295
296 cout << "Device: " << deviceProperties.deviceName << endl;
297
298 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(device, surface);
299 bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(device, deviceExtensions);
300 bool swapChainAdequate = false;
301
302 if (extensionsSupported) {
303 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(device, surface);
304 swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
305 }
306
307 VkPhysicalDeviceFeatures supportedFeatures;
308 vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
309
310 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
311}
312
313void VulkanGame::createLogicalDevice(
314 const vector<const char*> validationLayers,
315 const vector<const char*>& deviceExtensions) {
316 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
317
318 vector<VkDeviceQueueCreateInfo> queueCreateInfos;
319 set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
320
321 float queuePriority = 1.0f;
322 for (uint32_t queueFamily : uniqueQueueFamilies) {
323 VkDeviceQueueCreateInfo queueCreateInfo = {};
324 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
325 queueCreateInfo.queueFamilyIndex = queueFamily;
326 queueCreateInfo.queueCount = 1;
327 queueCreateInfo.pQueuePriorities = &queuePriority;
328
329 queueCreateInfos.push_back(queueCreateInfo);
330 }
331
332 VkPhysicalDeviceFeatures deviceFeatures = {};
333 deviceFeatures.samplerAnisotropy = VK_TRUE;
334
335 VkDeviceCreateInfo createInfo = {};
336 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
337 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
338 createInfo.pQueueCreateInfos = queueCreateInfos.data();
339
340 createInfo.pEnabledFeatures = &deviceFeatures;
341
342 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
343 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
344
345 // These fields are ignored by up-to-date Vulkan implementations,
346 // but it's a good idea to set them for backwards compatibility
347 if (ENABLE_VALIDATION_LAYERS) {
348 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
349 createInfo.ppEnabledLayerNames = validationLayers.data();
350 } else {
351 createInfo.enabledLayerCount = 0;
352 }
353
354 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
355 throw runtime_error("failed to create logical device!");
356 }
357
358 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
359 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
360}
361
362void VulkanGame::createSwapChain() {
363 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
364
365 VkSurfaceFormatKHR surfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(swapChainSupport.formats);
366 VkPresentModeKHR presentMode = VulkanUtils::chooseSwapPresentMode(swapChainSupport.presentModes);
367 VkExtent2D extent = VulkanUtils::chooseSwapExtent(swapChainSupport.capabilities, gui->getWindowWidth(), gui->getWindowHeight());
368
369 uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
370 if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
371 imageCount = swapChainSupport.capabilities.maxImageCount;
372 }
373
374 VkSwapchainCreateInfoKHR createInfo = {};
375 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
376 createInfo.surface = surface;
377 createInfo.minImageCount = imageCount;
378 createInfo.imageFormat = surfaceFormat.format;
379 createInfo.imageColorSpace = surfaceFormat.colorSpace;
380 createInfo.imageExtent = extent;
381 createInfo.imageArrayLayers = 1;
382 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
383
384 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
385 uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
386
387 if (indices.graphicsFamily != indices.presentFamily) {
388 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
389 createInfo.queueFamilyIndexCount = 2;
390 createInfo.pQueueFamilyIndices = queueFamilyIndices;
391 }
392 else {
393 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
394 createInfo.queueFamilyIndexCount = 0;
395 createInfo.pQueueFamilyIndices = nullptr;
396 }
397
398 createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
399 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
400 createInfo.presentMode = presentMode;
401 createInfo.clipped = VK_TRUE;
402 createInfo.oldSwapchain = VK_NULL_HANDLE;
403
404 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
405 throw runtime_error("failed to create swap chain!");
406 }
407
408 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
409 swapChainImages.resize(imageCount);
410 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
411
412 swapChainImageFormat = surfaceFormat.format;
413 swapChainExtent = extent;
414}
Note: See TracBrowser for help on using the repository browser.