8static VKAPI_ATTR VkBool32 VKAPI_CALL
debugCallback(
const VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
const VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
void *pUserData)
10 (void) pUserData; (void) messageSeverity; (void) messageType;
12 std::cerr <<
"validation layer: " << pCallbackData->pMessage <<
'\n';
16VkResult
CreateDebugUtilsMessengerEXT(
const VkInstance instance,
const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT *pDebugMessenger)
18 if (
const auto func =
reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT
>(vkGetInstanceProcAddr(instance,
"vkCreateDebugUtilsMessengerEXT")); func !=
nullptr) {
19 return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
22 return VK_ERROR_EXTENSION_NOT_PRESENT;
27 if (
const auto func =
reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT
>(vkGetInstanceProcAddr(instance,
"vkDestroyDebugUtilsMessengerEXT")); func !=
nullptr) {
28 func(instance, debugMessenger, pAllocator);
44 vkDestroyCommandPool(m_device, m_commandPool,
nullptr);
45 vkDestroyDevice(m_device,
nullptr);
47 if (enableValidationLayers) {
51 vkDestroySurfaceKHR(m_instance, m_surface,
nullptr);
52 vkDestroyInstance(m_instance,
nullptr);
57 if (enableValidationLayers && !checkValidationLayerSupport()) {
58 throw std::runtime_error(
"validation layers requested, but not available!");
61 constexpr VkApplicationInfo appInfo = {
62 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
64 .pApplicationName =
"VEngine App",
65 .applicationVersion = VK_MAKE_VERSION(1, 0, 0),
66 .pEngineName =
"VEngine",
67 .engineVersion = VK_MAKE_VERSION(1, 0, 0),
68 .apiVersion = VK_API_VERSION_1_0
71 VkInstanceCreateInfo createInfo = {};
72 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
73 createInfo.pApplicationInfo = &appInfo;
75 const std::vector<const char *> extensions = getRequiredExtensions();
76 createInfo.enabledExtensionCount =
static_cast<uint32_t
>(extensions.size());
77 createInfo.ppEnabledExtensionNames = extensions.data();
79 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
80 if (enableValidationLayers) {
81 createInfo.enabledLayerCount =
static_cast<uint32_t
>(m_validationLayers.size());
82 createInfo.ppEnabledLayerNames = m_validationLayers.data();
84 populateDebugMessengerCreateInfo(debugCreateInfo);
85 createInfo.pNext = &debugCreateInfo;
87 createInfo.enabledLayerCount = 0;
88 createInfo.pNext =
nullptr;
91 if (vkCreateInstance(&createInfo,
nullptr, &m_instance) != VK_SUCCESS) {
92 throw std::runtime_error(
"failed to create instance!");
95 hasGlfwRequiredInstanceExtensions();
100 uint32_t deviceCount = 0;
101 vkEnumeratePhysicalDevices(m_instance, &deviceCount,
nullptr);
102 if (deviceCount == 0) {
103 throw std::runtime_error(
"failed to find GPUs with Vulkan support!");
105 std::cout <<
"Device count: " << deviceCount <<
'\n';
106 std::vector<VkPhysicalDevice> devices(deviceCount);
107 vkEnumeratePhysicalDevices(m_instance, &deviceCount, devices.data());
109 for (
const auto &device : devices) {
110 if (isDeviceSuitable(device)) {
111 m_physicalDevice = device;
116 if (m_physicalDevice == VK_NULL_HANDLE) {
117 throw std::runtime_error(
"failed to find a suitable GPU!");
120 vkGetPhysicalDeviceProperties(m_physicalDevice, &m_properties);
121 std::cout <<
"physical device: " << m_properties.deviceName <<
'\n';
126 const auto [graphicsFamily, presentFamily, graphicsFamilyHasValue, presentFamilyHasValue] = findQueueFamilies(m_physicalDevice);
128 std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
129 const std::set<uint32_t> uniqueQueueFamilies = {graphicsFamily, presentFamily};
130 float queuePriority = 1.0F;
132 for (
const uint32_t queueFamily : uniqueQueueFamilies) {
133 VkDeviceQueueCreateInfo queueCreateInfo = {};
134 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
135 queueCreateInfo.queueFamilyIndex = queueFamily;
136 queueCreateInfo.queueCount = 1;
137 queueCreateInfo.pQueuePriorities = &queuePriority;
138 queueCreateInfos.push_back(queueCreateInfo);
141 VkPhysicalDeviceFeatures deviceFeatures = {};
142 deviceFeatures.samplerAnisotropy = VK_TRUE;
144 VkDeviceCreateInfo createInfo = {};
145 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
147 createInfo.queueCreateInfoCount =
static_cast<uint32_t
>(queueCreateInfos.size());
148 createInfo.pQueueCreateInfos = queueCreateInfos.data();
150 createInfo.pEnabledFeatures = &deviceFeatures;
151 createInfo.enabledExtensionCount =
static_cast<uint32_t
>(m_deviceExtensions.size());
152 createInfo.ppEnabledExtensionNames = m_deviceExtensions.data();
156 if (enableValidationLayers) {
157 createInfo.enabledLayerCount =
static_cast<uint32_t
>(m_validationLayers.size());
158 createInfo.ppEnabledLayerNames = m_validationLayers.data();
160 createInfo.enabledLayerCount = 0;
163 if (vkCreateDevice(m_physicalDevice, &createInfo,
nullptr, &m_device) != VK_SUCCESS) {
164 throw std::runtime_error(
"failed to create logical device!");
167 vkGetDeviceQueue(m_device, graphicsFamily, 0, &m_graphicsQueue);
168 vkGetDeviceQueue(m_device, presentFamily, 0, &m_presentQueue);
173 const auto [graphicsFamily, presentFamily, graphicsFamilyHasValue, presentFamilyHasValue] = findPhysicalQueueFamilies();
175 const VkCommandPoolCreateInfo poolInfo = {
176 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
178 .flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
179 .queueFamilyIndex = graphicsFamily
182 if (vkCreateCommandPool(m_device, &poolInfo,
nullptr, &m_commandPool) != VK_SUCCESS) {
183 throw std::runtime_error(
"failed to create command pool!");
190 const bool extensionsSupported = checkDeviceExtensionSupport(device);
191 bool swapChainAdequate =
false;
193 if (extensionsSupported) {
194 auto [capabilities, formats, presentModes] = querySwapChainSupport(device);
195 swapChainAdequate = !formats.empty() && !presentModes.empty();
198 VkPhysicalDeviceFeatures supportedFeatures;
199 vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
201 return indices.
isComplete() && extensionsSupported && swapChainAdequate && (supportedFeatures.samplerAnisotropy != 0U);
207 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
208 createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
209 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
210 createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
211 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
212 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
214 createInfo.pUserData =
nullptr;
229 uint32_t layerCount = 0;
230 vkEnumerateInstanceLayerProperties(&layerCount,
nullptr);
232 std::vector<VkLayerProperties> availableLayers(layerCount);
233 vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
235 for (
const char *validationLayer : m_validationLayers) {
236 bool layerFound =
false;
238 for (
const auto &[layerName, specVersion, implementationVersion, description] : availableLayers) {
239 if (strcmp(layerName, validationLayer) == 0) {
254 uint32_t glfwExtensionCount = 0;
255 const char **glfwExtensions =
nullptr;
256 glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
258 std::vector<const char *> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
260 if (enableValidationLayers) {
261 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
269 uint32_t extensionCount = 0;
270 vkEnumerateInstanceExtensionProperties(
nullptr, &extensionCount,
nullptr);
271 std::vector<VkExtensionProperties> extensions(extensionCount);
272 vkEnumerateInstanceExtensionProperties(
nullptr, &extensionCount, extensions.data());
274 std::cout <<
"available extensions:\n";
275 std::unordered_set<std::string> available;
276 for (
const auto &[extensionName, specVersion] : extensions) {
277 std::cout <<
'\t' << extensionName <<
'\n';
278 available.insert(extensionName);
281 std::cout <<
"required extensions:\n";
282 for (
const std::vector<const char *> requiredExtensions = getRequiredExtensions();
const auto &required : requiredExtensions) {
283 std::cout <<
"\t" << required <<
'\n';
284 if (!available.contains(required)) {
285 throw std::runtime_error(
"Missing required glfw extension");
292 uint32_t extensionCount = 0;
293 vkEnumerateDeviceExtensionProperties(device,
nullptr, &extensionCount,
nullptr);
295 std::vector<VkExtensionProperties> availableExtensions(extensionCount);
296 vkEnumerateDeviceExtensionProperties(device,
nullptr, &extensionCount, availableExtensions.data());
298 std::set<std::string> requiredExtensions(m_deviceExtensions.begin(), m_deviceExtensions.end());
299 for (
const auto &[extensionName, specVersion] : availableExtensions) {
300 requiredExtensions.erase(extensionName);
303 return requiredExtensions.empty();
309 uint32_t queueFamilyCount = 0;
311 vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount,
nullptr);
312 std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
313 vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
315 for (
const auto &[queueFlags, queueCount, timestampValidBits, minImageTransferGranularity] : queueFamilies) {
316 if (queueCount > 0 && ((queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0U)) {
320 VkBool32 presentSupport = 0U;
321 vkGetPhysicalDeviceSurfaceSupportKHR(device, index, m_surface, &presentSupport);
322 if (queueCount > 0 && (presentSupport != 0U)) {
336 uint32_t formatCount = 0;
337 uint32_t presentModeCount = 0;
339 vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, m_surface, &details.
capabilities);
341 vkGetPhysicalDeviceSurfaceFormatsKHR(device, m_surface, &formatCount,
nullptr);
342 if (formatCount != 0) {
343 details.
formats.resize(formatCount);
344 vkGetPhysicalDeviceSurfaceFormatsKHR(device, m_surface, &formatCount, details.
formats.data());
346 vkGetPhysicalDeviceSurfacePresentModesKHR(device, m_surface, &presentModeCount,
nullptr);
347 if (presentModeCount != 0) {
349 vkGetPhysicalDeviceSurfacePresentModesKHR(device, m_surface, &presentModeCount, details.
presentModes.data());
357 for (
const VkFormat format : candidates) {
358 VkFormatProperties props;
359 vkGetPhysicalDeviceFormatProperties(m_physicalDevice, format, &props);
360 if (tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & features) == features) {
362 }
if (tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & features) == features) {
366 throw std::runtime_error(
"failed to find supported format!");
371 VkPhysicalDeviceMemoryProperties memProperties;
372 vkGetPhysicalDeviceMemoryProperties(m_physicalDevice, &memProperties);
374 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
375 if (((typeFilter & (1 << i)) != 0U) &&
376 (memProperties.memoryTypes[i].propertyFlags & properties) == properties) {
381 throw std::runtime_error(
"failed to find suitable m_memory type!");
384void ven::Device::createBuffer(
const VkDeviceSize size,
const VkBufferUsageFlags usage,
const VkMemoryPropertyFlags properties, VkBuffer &buffer, VkDeviceMemory &bufferMemory)
const
386 VkBufferCreateInfo bufferInfo{};
387 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
388 bufferInfo.size = size;
389 bufferInfo.usage = usage;
390 bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
392 if (vkCreateBuffer(m_device, &bufferInfo,
nullptr, &buffer) != VK_SUCCESS) {
393 throw std::runtime_error(
"failed to create vertex m_buffer!");
396 VkMemoryRequirements memRequirements;
397 vkGetBufferMemoryRequirements(m_device, buffer, &memRequirements);
399 const VkMemoryAllocateInfo allocInfo{
400 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
402 .allocationSize = memRequirements.size,
403 .memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties)
406 if (vkAllocateMemory(m_device, &allocInfo,
nullptr, &bufferMemory) != VK_SUCCESS) {
407 throw std::runtime_error(
"failed to allocate vertex m_buffer m_memory!");
410 vkBindBufferMemory(m_device, buffer, bufferMemory, 0);
415 VkCommandBufferAllocateInfo allocInfo{};
416 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
417 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
418 allocInfo.commandPool = m_commandPool;
419 allocInfo.commandBufferCount = 1;
421 VkCommandBuffer commandBuffer =
nullptr;
422 vkAllocateCommandBuffers(m_device, &allocInfo, &commandBuffer);
424 VkCommandBufferBeginInfo beginInfo{};
425 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
426 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
428 vkBeginCommandBuffer(commandBuffer, &beginInfo);
429 return commandBuffer;
434 vkEndCommandBuffer(commandBuffer);
436 VkSubmitInfo submitInfo{};
437 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
438 submitInfo.commandBufferCount = 1;
439 submitInfo.pCommandBuffers = &commandBuffer;
441 vkQueueSubmit(m_graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
442 vkQueueWaitIdle(m_graphicsQueue);
444 vkFreeCommandBuffers(m_device, m_commandPool, 1, &commandBuffer);
449 const VkCommandBuffer commandBuffer = beginSingleTimeCommands();
451 VkBufferCopy copyRegion{};
452 copyRegion.srcOffset = 0;
453 copyRegion.dstOffset = 0;
454 copyRegion.size = size;
455 vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
457 endSingleTimeCommands(commandBuffer);
462 const VkCommandBuffer commandBuffer = beginSingleTimeCommands();
463 const VkBufferImageCopy region{
465 .bufferRowLength = 0,
466 .bufferImageHeight = 0,
467 .imageSubresource = {
468 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
471 .layerCount = layerCount
473 .imageOffset = {0, 0, 0},
474 .imageExtent = {width, height, 1}
477 vkCmdCopyBufferToImage(commandBuffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
478 endSingleTimeCommands(commandBuffer);
483 if (vkCreateImage(m_device, &imageInfo,
nullptr, &image) != VK_SUCCESS) {
484 throw std::runtime_error(
"failed to create image!");
487 VkMemoryRequirements memRequirements;
488 vkGetImageMemoryRequirements(m_device, image, &memRequirements);
490 VkMemoryAllocateInfo allocInfo{};
491 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
492 allocInfo.allocationSize = memRequirements.size;
493 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties);
495 if (vkAllocateMemory(m_device, &allocInfo,
nullptr, &imageMemory) != VK_SUCCESS) {
496 throw std::runtime_error(
"failed to allocate image memory!");
499 if (vkBindImageMemory(m_device, image, imageMemory, 0) != VK_SUCCESS) {
500 throw std::runtime_error(
"failed to bind image memory!");
504void ven::Device::transitionImageLayout(
const VkImage image,
const VkFormat format,
const VkImageLayout oldLayout,
const VkImageLayout newLayout,
const uint32_t mipLevels,
const uint32_t layerCount)
const {
508 const VkCommandBuffer commandBuffer = beginSingleTimeCommands();
510 VkImageMemoryBarrier barrier{};
511 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
512 barrier.oldLayout = oldLayout;
513 barrier.newLayout = newLayout;
515 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
516 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
518 barrier.image = image;
519 barrier.subresourceRange.baseMipLevel = 0;
520 barrier.subresourceRange.levelCount = mipLevels;
521 barrier.subresourceRange.baseArrayLayer = 0;
522 barrier.subresourceRange.layerCount = layerCount;
524 if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
525 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
526 if (format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT) {
527 barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
530 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
533 VkPipelineStageFlags sourceStage = 0;
534 VkPipelineStageFlags destinationStage = 0;
536 if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
537 barrier.srcAccessMask = 0;
538 barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
540 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
541 destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
543 oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
544 barrier.srcAccessMask = 0;
545 barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
547 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
548 destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
550 oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL &&
551 newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
552 barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
553 barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
555 sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
556 destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
558 oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
559 newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
560 barrier.srcAccessMask = 0;
561 barrier.dstAccessMask =
562 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
564 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
565 destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
567 throw std::invalid_argument(
"unsupported layout transition!");
569 vkCmdPipelineBarrier(
581 endSingleTimeCommands(commandBuffer);
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(const VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, const VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, void *pUserData)