source: opengl-game/vulkan-utils.cpp@ 4a9416a

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

Create a pipeline and shaders to render explosions

  • Property mode set to 100644
File size: 21.2 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 // TODO: Since the image loaded here will be used as a texture, display a warning if it has
260 // non power-of-two dimensions
261 int texWidth, texHeight, texChannels;
262
263 stbi_uc* pixels = stbi_load(filename.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
264 VkDeviceSize imageSize = texWidth * texHeight * 4;
265
266 if (!pixels) {
267 throw runtime_error("failed to load texture image!");
268 }
269
270 VkBuffer stagingBuffer;
271 VkDeviceMemory stagingBufferMemory;
272
273 createBuffer(device, physicalDevice, imageSize,
274 VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
275 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
276 stagingBuffer, stagingBufferMemory);
277
278 void* data;
279
280 vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &data);
281 memcpy(data, pixels, static_cast<size_t>(imageSize));
282 vkUnmapMemory(device, stagingBufferMemory);
283
284 stbi_image_free(pixels);
285
286 createImage(device, physicalDevice, texWidth, texHeight, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
287 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image);
288
289 transitionImageLayout(device, commandPool, image.image, VK_FORMAT_R8G8B8A8_UNORM,
290 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, graphicsQueue);
291 copyBufferToImage(device, commandPool, stagingBuffer, image.image,
292 static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight), graphicsQueue);
293 transitionImageLayout(device, commandPool, image.image, VK_FORMAT_R8G8B8A8_UNORM,
294 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, graphicsQueue);
295
296 vkDestroyBuffer(device, stagingBuffer, nullptr);
297 vkFreeMemory(device, stagingBufferMemory, nullptr);
298
299 image.imageView = createImageView(device, image.image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
300}
301
302void VulkanUtils::createVulkanImageFromSDLTexture(VkDevice device, VkPhysicalDevice physicalDevice,
303 SDL_Texture* texture, VulkanImage& image) {
304 int a, w, h;
305
306 // I only need this here for the width and height, which are constants, so just use those instead
307 SDL_QueryTexture(texture, nullptr, &a, &w, &h);
308
309 createImage(device, physicalDevice, w, h, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
310 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image);
311
312 image.imageView = createImageView(device, image.image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
313}
314
315void VulkanUtils::populateVulkanImageFromSDLTexture(VkDevice device, VkPhysicalDevice physicalDevice,
316 VkCommandPool commandPool, SDL_Texture* texture, SDL_Renderer* renderer, VulkanImage& image,
317 VkQueue graphicsQueue) {
318 int a, w, h;
319
320 SDL_QueryTexture(texture, nullptr, &a, &w, &h);
321
322 VkDeviceSize imageSize = w * h * 4;
323 unsigned char* pixels = new unsigned char[imageSize];
324
325 SDL_RenderReadPixels(renderer, nullptr, SDL_PIXELFORMAT_ABGR8888, pixels, w * 4);
326
327 VkBuffer stagingBuffer;
328 VkDeviceMemory stagingBufferMemory;
329
330 createBuffer(device, physicalDevice, imageSize,
331 VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
332 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
333 stagingBuffer, stagingBufferMemory);
334
335 void* data;
336
337 vkMapMemory(device, stagingBufferMemory, 0, VK_WHOLE_SIZE, 0, &data);
338 memcpy(data, pixels, static_cast<size_t>(imageSize));
339
340 VkMappedMemoryRange mappedMemoryRange = {};
341 mappedMemoryRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
342 mappedMemoryRange.memory = stagingBufferMemory;
343 mappedMemoryRange.offset = 0;
344 mappedMemoryRange.size = VK_WHOLE_SIZE;
345
346 // TODO: Should probably check that the function succeeded
347 vkFlushMappedMemoryRanges(device, 1, &mappedMemoryRange);
348 vkUnmapMemory(device, stagingBufferMemory);
349
350 delete[] pixels;
351
352 transitionImageLayout(device, commandPool, image.image, VK_FORMAT_R8G8B8A8_UNORM,
353 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, graphicsQueue);
354 copyBufferToImage(device, commandPool, stagingBuffer, image.image,
355 static_cast<uint32_t>(w), static_cast<uint32_t>(h), graphicsQueue);
356 transitionImageLayout(device, commandPool, image.image, VK_FORMAT_R8G8B8A8_UNORM,
357 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, graphicsQueue);
358
359 vkDestroyBuffer(device, stagingBuffer, nullptr);
360 vkFreeMemory(device, stagingBufferMemory, nullptr);
361}
362
363void VulkanUtils::createDepthImage(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool,
364 VkFormat depthFormat, VkExtent2D extent, VulkanImage& image, VkQueue graphicsQueue) {
365 createImage(device, physicalDevice, extent.width, extent.height, depthFormat, VK_IMAGE_TILING_OPTIMAL,
366 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image);
367 image.imageView = createImageView(device, image.image, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT);
368
369 transitionImageLayout(device, commandPool, image.image, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED,
370 VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, graphicsQueue);
371}
372
373void VulkanUtils::createImage(VkDevice device, VkPhysicalDevice physicalDevice, uint32_t width, uint32_t height,
374 VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties,
375 VulkanImage& image) {
376 VkImageCreateInfo imageInfo = {};
377 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
378 imageInfo.imageType = VK_IMAGE_TYPE_2D;
379 imageInfo.extent.width = width;
380 imageInfo.extent.height = height;
381 imageInfo.extent.depth = 1;
382 imageInfo.mipLevels = 1;
383 imageInfo.arrayLayers = 1;
384 imageInfo.format = format;
385 imageInfo.tiling = tiling;
386 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
387 imageInfo.usage = usage;
388 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
389 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
390
391 if (vkCreateImage(device, &imageInfo, nullptr, &image.image) != VK_SUCCESS) {
392 throw runtime_error("failed to create image!");
393 }
394
395 VkMemoryRequirements memRequirements;
396 vkGetImageMemoryRequirements(device, image.image, &memRequirements);
397
398 VkMemoryAllocateInfo allocInfo = {};
399 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
400 allocInfo.allocationSize = memRequirements.size;
401 allocInfo.memoryTypeIndex = findMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
402
403 if (vkAllocateMemory(device, &allocInfo, nullptr, &image.imageMemory) != VK_SUCCESS) {
404 throw runtime_error("failed to allocate image memory!");
405 }
406
407 vkBindImageMemory(device, image.image, image.imageMemory, 0);
408}
409
410void VulkanUtils::transitionImageLayout(VkDevice device, VkCommandPool commandPool, VkImage image,
411 VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout, VkQueue graphicsQueue) {
412 VkCommandBuffer commandBuffer = beginSingleTimeCommands(device, commandPool);
413
414 VkImageMemoryBarrier barrier = {};
415 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
416 barrier.oldLayout = oldLayout;
417 barrier.newLayout = newLayout;
418 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
419 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
420 barrier.image = image;
421
422 if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
423 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
424
425 if (hasStencilComponent(format)) {
426 barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
427 }
428 } else {
429 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
430 }
431
432 barrier.subresourceRange.baseMipLevel = 0;
433 barrier.subresourceRange.levelCount = 1;
434 barrier.subresourceRange.baseArrayLayer = 0;
435 barrier.subresourceRange.layerCount = 1;
436
437 VkPipelineStageFlags sourceStage;
438 VkPipelineStageFlags destinationStage;
439
440 if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
441 barrier.srcAccessMask = 0;
442 barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
443
444 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
445 destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
446 } else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
447 barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
448 barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
449
450 sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
451 destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
452 } else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
453 barrier.srcAccessMask = 0;
454 barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
455
456 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
457 destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
458 } else {
459 throw invalid_argument("unsupported layout transition!");
460 }
461
462 vkCmdPipelineBarrier(
463 commandBuffer,
464 sourceStage, destinationStage,
465 0,
466 0, nullptr,
467 0, nullptr,
468 1, &barrier
469 );
470
471 endSingleTimeCommands(device, commandPool, commandBuffer, graphicsQueue);
472}
473
474VkCommandBuffer VulkanUtils::beginSingleTimeCommands(VkDevice device, VkCommandPool commandPool) {
475 VkCommandBufferAllocateInfo allocInfo = {};
476 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
477 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
478 allocInfo.commandPool = commandPool;
479 allocInfo.commandBufferCount = 1;
480
481 VkCommandBuffer commandBuffer;
482 vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
483
484 VkCommandBufferBeginInfo beginInfo = {};
485 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
486 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
487
488 vkBeginCommandBuffer(commandBuffer, &beginInfo);
489
490 return commandBuffer;
491}
492
493void VulkanUtils::endSingleTimeCommands(VkDevice device, VkCommandPool commandPool,
494 VkCommandBuffer commandBuffer, VkQueue graphicsQueue) {
495 vkEndCommandBuffer(commandBuffer);
496
497 VkSubmitInfo submitInfo = {};
498 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
499 submitInfo.commandBufferCount = 1;
500 submitInfo.pCommandBuffers = &commandBuffer;
501
502 vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
503 vkQueueWaitIdle(graphicsQueue);
504
505 vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
506}
507
508void VulkanUtils::copyBufferToImage(VkDevice device, VkCommandPool commandPool, VkBuffer buffer,
509 VkImage image, uint32_t width, uint32_t height, VkQueue graphicsQueue) {
510 VkCommandBuffer commandBuffer = beginSingleTimeCommands(device, commandPool);
511
512 VkBufferImageCopy region = {};
513 region.bufferOffset = 0;
514 region.bufferRowLength = 0;
515 region.bufferImageHeight = 0;
516 region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
517 region.imageSubresource.mipLevel = 0;
518 region.imageSubresource.baseArrayLayer = 0;
519 region.imageSubresource.layerCount = 1;
520 region.imageOffset = { 0, 0, 0 };
521 region.imageExtent = { width, height, 1 };
522
523 vkCmdCopyBufferToImage(
524 commandBuffer,
525 buffer,
526 image,
527 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
528 1,
529 &region
530 );
531
532 endSingleTimeCommands(device, commandPool, commandBuffer, graphicsQueue);
533}
534
535void VulkanUtils::copyBuffer(VkDevice device, VkCommandPool commandPool, VkBuffer srcBuffer,
536 VkBuffer dstBuffer, VkDeviceSize srcOffset, VkDeviceSize dstOffset, VkDeviceSize size,
537 VkQueue graphicsQueue) {
538 VkCommandBuffer commandBuffer = beginSingleTimeCommands(device, commandPool);
539
540 VkBufferCopy copyRegion = { srcOffset, dstOffset, size };
541 vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion);
542
543 endSingleTimeCommands(device, commandPool, commandBuffer, graphicsQueue);
544}
545
546bool VulkanUtils::hasStencilComponent(VkFormat format) {
547 return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT;
548}
549
550void VulkanUtils::destroyVulkanImage(VkDevice& device, VulkanImage& image) {
551 vkDestroyImageView(device, image.imageView, nullptr);
552 vkDestroyImage(device, image.image, nullptr);
553 vkFreeMemory(device, image.imageMemory, nullptr);
554}
Note: See TracBrowser for help on using the repository browser.