source: opengl-game/vulkan-utils.cpp@ d2d9286

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

In vulkangame, implement the renderScene function to draw a frame in Vulkan and implement a test UI overlay

  • Property mode set to 100644
File size: 21.1 KB
Line 
1#include "vulkan-utils.hpp"
2
3#include <algorithm>
4#include <set>
5#include <stdexcept>
6
7#define STB_IMAGE_IMPLEMENTATION
8#include "stb_image.h" // TODO: Probably switch to SDL_image
9
10// TODO: Remove all instances of auto
11
12bool VulkanUtils::checkValidationLayerSupport(const vector<const char*> &validationLayers) {
13 uint32_t layerCount;
14 vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
15
16 vector<VkLayerProperties> availableLayers(layerCount);
17 vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
18
19 for (const char* layerName : validationLayers) {
20 bool layerFound = false;
21
22 for (const auto& layerProperties : availableLayers) {
23 if (strcmp(layerName, layerProperties.layerName) == 0) {
24 layerFound = true;
25 break;
26 }
27 }
28
29 if (!layerFound) {
30 return false;
31 }
32 }
33
34 return true;
35}
36
37VkResult VulkanUtils::createDebugUtilsMessengerEXT(VkInstance instance,
38 const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
39 const VkAllocationCallbacks* pAllocator,
40 VkDebugUtilsMessengerEXT* pDebugMessenger) {
41 auto func = (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
42
43 if (func != nullptr) {
44 return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
45 } else {
46 return VK_ERROR_EXTENSION_NOT_PRESENT;
47 }
48}
49
50void VulkanUtils::destroyDebugUtilsMessengerEXT(VkInstance instance,
51 VkDebugUtilsMessengerEXT debugMessenger,
52 const VkAllocationCallbacks* pAllocator) {
53 auto func = (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
54
55 if (func != nullptr) {
56 func(instance, debugMessenger, pAllocator);
57 }
58}
59
60QueueFamilyIndices VulkanUtils::findQueueFamilies(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface) {
61 QueueFamilyIndices indices;
62
63 uint32_t queueFamilyCount = 0;
64 vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr);
65
66 vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
67 vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data());
68
69 int i = 0;
70 for (const auto& queueFamily : queueFamilies) {
71 if (queueFamily.queueCount > 0 && queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
72 indices.graphicsFamily = i;
73 }
74
75 VkBool32 presentSupport = false;
76 vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport);
77
78 if (queueFamily.queueCount > 0 && presentSupport) {
79 indices.presentFamily = i;
80 }
81
82 if (indices.isComplete()) {
83 break;
84 }
85
86 i++;
87 }
88
89 return indices;
90}
91
92bool VulkanUtils::checkDeviceExtensionSupport(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions) {
93 uint32_t extensionCount;
94 vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr);
95
96 vector<VkExtensionProperties> availableExtensions(extensionCount);
97 vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data());
98
99 set<string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
100
101 for (const auto& extension : availableExtensions) {
102 requiredExtensions.erase(extension.extensionName);
103 }
104
105 return requiredExtensions.empty();
106}
107
108SwapChainSupportDetails VulkanUtils::querySwapChainSupport(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface) {
109 SwapChainSupportDetails details;
110
111 vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &details.capabilities);
112
113 uint32_t formatCount;
114 vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, nullptr);
115
116 if (formatCount != 0) {
117 details.formats.resize(formatCount);
118 vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, details.formats.data());
119 }
120
121 uint32_t presentModeCount;
122 vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, nullptr);
123
124 if (presentModeCount != 0) {
125 details.presentModes.resize(presentModeCount);
126 vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, details.presentModes.data());
127 }
128
129 return details;
130}
131
132VkSurfaceFormatKHR VulkanUtils::chooseSwapSurfaceFormat(const vector<VkSurfaceFormatKHR>& availableFormats) {
133 for (const auto& availableFormat : availableFormats) {
134 if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
135 return availableFormat;
136 }
137 }
138
139 return availableFormats[0];
140}
141
142VkPresentModeKHR VulkanUtils::chooseSwapPresentMode(const vector<VkPresentModeKHR>& availablePresentModes) {
143 VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR;
144
145 for (const auto& availablePresentMode : availablePresentModes) {
146 if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
147 return availablePresentMode;
148 }
149 else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
150 bestMode = availablePresentMode;
151 }
152 }
153
154 return bestMode;
155}
156
157VkExtent2D VulkanUtils::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, int width, int height) {
158 if (capabilities.currentExtent.width != numeric_limits<uint32_t>::max()) {
159 return capabilities.currentExtent;
160 } else {
161 VkExtent2D actualExtent = {
162 static_cast<uint32_t>(width),
163 static_cast<uint32_t>(height)
164 };
165
166 actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width));
167 actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height));
168
169 return actualExtent;
170 }
171}
172
173VkImageView VulkanUtils::createImageView(VkDevice device, VkImage image, VkFormat format, VkImageAspectFlags aspectFlags) {
174 VkImageViewCreateInfo viewInfo = {};
175 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
176 viewInfo.image = image;
177 viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
178 viewInfo.format = format;
179
180 viewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
181 viewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
182 viewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
183 viewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
184
185 viewInfo.subresourceRange.aspectMask = aspectFlags;
186 viewInfo.subresourceRange.baseMipLevel = 0;
187 viewInfo.subresourceRange.levelCount = 1;
188 viewInfo.subresourceRange.baseArrayLayer = 0;
189 viewInfo.subresourceRange.layerCount = 1;
190
191 VkImageView imageView;
192 if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS) {
193 throw runtime_error("failed to create image view!");
194 }
195
196 return imageView;
197}
198
199VkFormat VulkanUtils::findSupportedFormat(VkPhysicalDevice physicalDevice, const vector<VkFormat>& candidates,
200 VkImageTiling tiling, VkFormatFeatureFlags features) {
201 for (VkFormat format : candidates) {
202 VkFormatProperties props;
203 vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &props);
204
205 if (tiling == VK_IMAGE_TILING_LINEAR &&
206 (props.linearTilingFeatures & features) == features) {
207 return format;
208 } else if (tiling == VK_IMAGE_TILING_OPTIMAL &&
209 (props.optimalTilingFeatures & features) == features) {
210 return format;
211 }
212 }
213
214 throw runtime_error("failed to find supported format!");
215}
216
217void VulkanUtils::createBuffer(VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage,
218 VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) {
219 VkBufferCreateInfo bufferInfo = {};
220 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
221 bufferInfo.size = size;
222 bufferInfo.usage = usage;
223 bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
224
225 if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) {
226 throw runtime_error("failed to create buffer!");
227 }
228
229 VkMemoryRequirements memRequirements;
230 vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
231
232 VkMemoryAllocateInfo allocInfo = {};
233 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
234 allocInfo.allocationSize = memRequirements.size;
235 allocInfo.memoryTypeIndex = findMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
236
237 if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) {
238 throw runtime_error("failed to allocate buffer memory!");
239 }
240
241 vkBindBufferMemory(device, buffer, bufferMemory, 0);
242}
243
244uint32_t VulkanUtils::findMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties) {
245 VkPhysicalDeviceMemoryProperties memProperties;
246 vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
247
248 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
249 if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) {
250 return i;
251 }
252 }
253
254 throw runtime_error("failed to find suitable memory type!");
255}
256
257void VulkanUtils::createVulkanImageFromFile(VkDevice device, VkPhysicalDevice physicalDevice,
258 VkCommandPool commandPool, string filename, VulkanImage& image, VkQueue graphicsQueue) {
259 int texWidth, texHeight, texChannels;
260
261 stbi_uc* pixels = stbi_load(filename.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
262 VkDeviceSize imageSize = texWidth * texHeight * 4;
263
264 if (!pixels) {
265 throw runtime_error("failed to load texture image!");
266 }
267
268 VkBuffer stagingBuffer;
269 VkDeviceMemory stagingBufferMemory;
270
271 createBuffer(device, physicalDevice, imageSize,
272 VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
273 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
274 stagingBuffer, stagingBufferMemory);
275
276 void* data;
277
278 vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &data);
279 memcpy(data, pixels, static_cast<size_t>(imageSize));
280 vkUnmapMemory(device, stagingBufferMemory);
281
282 stbi_image_free(pixels);
283
284 createImage(device, physicalDevice, texWidth, texHeight, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
285 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image);
286
287 transitionImageLayout(device, commandPool, image.image, VK_FORMAT_R8G8B8A8_UNORM,
288 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, graphicsQueue);
289 copyBufferToImage(device, commandPool, stagingBuffer, image.image,
290 static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight), graphicsQueue);
291 transitionImageLayout(device, commandPool, image.image, VK_FORMAT_R8G8B8A8_UNORM,
292 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, graphicsQueue);
293
294 vkDestroyBuffer(device, stagingBuffer, nullptr);
295 vkFreeMemory(device, stagingBufferMemory, nullptr);
296
297 image.imageView = createImageView(device, image.image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
298}
299
300void VulkanUtils::createVulkanImageFromSDLTexture(VkDevice device, VkPhysicalDevice physicalDevice,
301 SDL_Texture* texture, VulkanImage& image) {
302 int a, w, h;
303
304 // I only need this here for the width and height, which are constants, so just use those instead
305 SDL_QueryTexture(texture, nullptr, &a, &w, &h);
306
307 createImage(device, physicalDevice, w, h, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
308 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image);
309
310 image.imageView = createImageView(device, image.image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
311}
312
313void VulkanUtils::populateVulkanImageFromSDLTexture(VkDevice device, VkPhysicalDevice physicalDevice,
314 VkCommandPool commandPool, SDL_Texture* texture, SDL_Renderer* renderer, VulkanImage& image,
315 VkQueue graphicsQueue) {
316 int a, w, h;
317
318 SDL_QueryTexture(texture, nullptr, &a, &w, &h);
319
320 VkDeviceSize imageSize = w * h * 4;
321 unsigned char* pixels = new unsigned char[imageSize];
322
323 SDL_RenderReadPixels(renderer, nullptr, SDL_PIXELFORMAT_ABGR8888, pixels, w * 4);
324
325 VkBuffer stagingBuffer;
326 VkDeviceMemory stagingBufferMemory;
327
328 createBuffer(device, physicalDevice, imageSize,
329 VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
330 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
331 stagingBuffer, stagingBufferMemory);
332
333 void* data;
334
335 vkMapMemory(device, stagingBufferMemory, 0, VK_WHOLE_SIZE, 0, &data);
336 memcpy(data, pixels, static_cast<size_t>(imageSize));
337
338 VkMappedMemoryRange mappedMemoryRange = {};
339 mappedMemoryRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
340 mappedMemoryRange.memory = stagingBufferMemory;
341 mappedMemoryRange.offset = 0;
342 mappedMemoryRange.size = VK_WHOLE_SIZE;
343
344 // TODO: Should probably check that the function succeeded
345 vkFlushMappedMemoryRanges(device, 1, &mappedMemoryRange);
346 vkUnmapMemory(device, stagingBufferMemory);
347
348 delete[] pixels;
349
350 transitionImageLayout(device, commandPool, image.image, VK_FORMAT_R8G8B8A8_UNORM,
351 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, graphicsQueue);
352 copyBufferToImage(device, commandPool, stagingBuffer, image.image,
353 static_cast<uint32_t>(w), static_cast<uint32_t>(h), graphicsQueue);
354 transitionImageLayout(device, commandPool, image.image, VK_FORMAT_R8G8B8A8_UNORM,
355 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, graphicsQueue);
356
357 vkDestroyBuffer(device, stagingBuffer, nullptr);
358 vkFreeMemory(device, stagingBufferMemory, nullptr);
359}
360
361void VulkanUtils::createDepthImage(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool,
362 VkFormat depthFormat, VkExtent2D extent, VulkanImage& image, VkQueue graphicsQueue) {
363 createImage(device, physicalDevice, extent.width, extent.height, depthFormat, VK_IMAGE_TILING_OPTIMAL,
364 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image);
365 image.imageView = createImageView(device, image.image, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT);
366
367 transitionImageLayout(device, commandPool, image.image, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED,
368 VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, graphicsQueue);
369}
370
371void VulkanUtils::createImage(VkDevice device, VkPhysicalDevice physicalDevice, uint32_t width, uint32_t height,
372 VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties,
373 VulkanImage& image) {
374 VkImageCreateInfo imageInfo = {};
375 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
376 imageInfo.imageType = VK_IMAGE_TYPE_2D;
377 imageInfo.extent.width = width;
378 imageInfo.extent.height = height;
379 imageInfo.extent.depth = 1;
380 imageInfo.mipLevels = 1;
381 imageInfo.arrayLayers = 1;
382 imageInfo.format = format;
383 imageInfo.tiling = tiling;
384 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
385 imageInfo.usage = usage;
386 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
387 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
388
389 if (vkCreateImage(device, &imageInfo, nullptr, &image.image) != VK_SUCCESS) {
390 throw runtime_error("failed to create image!");
391 }
392
393 VkMemoryRequirements memRequirements;
394 vkGetImageMemoryRequirements(device, image.image, &memRequirements);
395
396 VkMemoryAllocateInfo allocInfo = {};
397 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
398 allocInfo.allocationSize = memRequirements.size;
399 allocInfo.memoryTypeIndex = findMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
400
401 if (vkAllocateMemory(device, &allocInfo, nullptr, &image.imageMemory) != VK_SUCCESS) {
402 throw runtime_error("failed to allocate image memory!");
403 }
404
405 vkBindImageMemory(device, image.image, image.imageMemory, 0);
406}
407
408void VulkanUtils::transitionImageLayout(VkDevice device, VkCommandPool commandPool, VkImage image,
409 VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout, VkQueue graphicsQueue) {
410 VkCommandBuffer commandBuffer = beginSingleTimeCommands(device, commandPool);
411
412 VkImageMemoryBarrier barrier = {};
413 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
414 barrier.oldLayout = oldLayout;
415 barrier.newLayout = newLayout;
416 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
417 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
418 barrier.image = image;
419
420 if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
421 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
422
423 if (hasStencilComponent(format)) {
424 barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
425 }
426 } else {
427 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
428 }
429
430 barrier.subresourceRange.baseMipLevel = 0;
431 barrier.subresourceRange.levelCount = 1;
432 barrier.subresourceRange.baseArrayLayer = 0;
433 barrier.subresourceRange.layerCount = 1;
434
435 VkPipelineStageFlags sourceStage;
436 VkPipelineStageFlags destinationStage;
437
438 if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
439 barrier.srcAccessMask = 0;
440 barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
441
442 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
443 destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
444 } else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
445 barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
446 barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
447
448 sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
449 destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
450 } else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
451 barrier.srcAccessMask = 0;
452 barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
453
454 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
455 destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
456 } else {
457 throw invalid_argument("unsupported layout transition!");
458 }
459
460 vkCmdPipelineBarrier(
461 commandBuffer,
462 sourceStage, destinationStage,
463 0,
464 0, nullptr,
465 0, nullptr,
466 1, &barrier
467 );
468
469 endSingleTimeCommands(device, commandPool, commandBuffer, graphicsQueue);
470}
471
472VkCommandBuffer VulkanUtils::beginSingleTimeCommands(VkDevice device, VkCommandPool commandPool) {
473 VkCommandBufferAllocateInfo allocInfo = {};
474 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
475 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
476 allocInfo.commandPool = commandPool;
477 allocInfo.commandBufferCount = 1;
478
479 VkCommandBuffer commandBuffer;
480 vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
481
482 VkCommandBufferBeginInfo beginInfo = {};
483 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
484 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
485
486 vkBeginCommandBuffer(commandBuffer, &beginInfo);
487
488 return commandBuffer;
489}
490
491void VulkanUtils::endSingleTimeCommands(VkDevice device, VkCommandPool commandPool,
492 VkCommandBuffer commandBuffer, VkQueue graphicsQueue) {
493 vkEndCommandBuffer(commandBuffer);
494
495 VkSubmitInfo submitInfo = {};
496 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
497 submitInfo.commandBufferCount = 1;
498 submitInfo.pCommandBuffers = &commandBuffer;
499
500 vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
501 vkQueueWaitIdle(graphicsQueue);
502
503 vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
504}
505
506void VulkanUtils::copyBufferToImage(VkDevice device, VkCommandPool commandPool, VkBuffer buffer,
507 VkImage image, uint32_t width, uint32_t height, VkQueue graphicsQueue) {
508 VkCommandBuffer commandBuffer = beginSingleTimeCommands(device, commandPool);
509
510 VkBufferImageCopy region = {};
511 region.bufferOffset = 0;
512 region.bufferRowLength = 0;
513 region.bufferImageHeight = 0;
514 region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
515 region.imageSubresource.mipLevel = 0;
516 region.imageSubresource.baseArrayLayer = 0;
517 region.imageSubresource.layerCount = 1;
518 region.imageOffset = { 0, 0, 0 };
519 region.imageExtent = { width, height, 1 };
520
521 vkCmdCopyBufferToImage(
522 commandBuffer,
523 buffer,
524 image,
525 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
526 1,
527 &region
528 );
529
530 endSingleTimeCommands(device, commandPool, commandBuffer, graphicsQueue);
531}
532
533void VulkanUtils::copyBuffer(VkDevice device, VkCommandPool commandPool, VkBuffer srcBuffer,
534 VkBuffer dstBuffer, VkDeviceSize srcOffset, VkDeviceSize dstOffset, VkDeviceSize size,
535 VkQueue graphicsQueue) {
536 VkCommandBuffer commandBuffer = beginSingleTimeCommands(device, commandPool);
537
538 VkBufferCopy copyRegion = { srcOffset, dstOffset, size };
539 vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion);
540
541 endSingleTimeCommands(device, commandPool, commandBuffer, graphicsQueue);
542}
543
544bool VulkanUtils::hasStencilComponent(VkFormat format) {
545 return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT;
546}
547
548void VulkanUtils::destroyVulkanImage(VkDevice& device, VulkanImage& image) {
549 vkDestroyImageView(device, image.imageView, nullptr);
550 vkDestroyImage(device, image.image, nullptr);
551 vkFreeMemory(device, image.imageMemory, nullptr);
552}
Note: See TracBrowser for help on using the repository browser.