source: opengl-game/vulkan-utils.cpp@ 6a39266

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

In vulkan-game, throw an error if either a graphics or present queue could not be found

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