ok i guess we do need exceptions

This commit is contained in:
Mars 2024-10-06 18:14:15 -04:00
parent f4f4b7898b
commit 61a2e9367b
2 changed files with 49 additions and 236 deletions

View file

@ -2,7 +2,7 @@ project(
'graphics-test', 'graphics-test',
'cpp', 'cpp',
version: '0.1.0', version: '0.1.0',
default_options: ['cpp_std=c++20', 'warning_level=everything', 'buildtype=debugoptimized'], default_options: ['cpp_std=c++20', 'warning_level=everything', 'buildtype=debug'],
) )
cpp = meson.get_compiler('cpp') cpp = meson.get_compiler('cpp')

View file

@ -6,7 +6,6 @@
#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1 #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
#define VK_ENABLE_BETA_EXTENSIONS #define VK_ENABLE_BETA_EXTENSIONS
#define VULKAN_HPP_NO_CONSTRUCTORS #define VULKAN_HPP_NO_CONSTRUCTORS
#define VULKAN_HPP_NO_EXCEPTIONS
#include <vulkan/vulkan.hpp> #include <vulkan/vulkan.hpp>
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
@ -151,10 +150,7 @@ class VulkanApp {
drawFrame(); drawFrame();
} }
auto result = mDevice->waitIdle(); mDevice->waitIdle();
if (result != vk::Result::eSuccess)
throw std::runtime_error("Failed to wait for idle!");
} }
fn cleanupSwapChain() -> void { fn cleanupSwapChain() -> void {
@ -175,10 +171,7 @@ class VulkanApp {
vkfw::waitEvents(); vkfw::waitEvents();
} }
auto result = mDevice->waitIdle(); mDevice->waitIdle();
if (result != vk::Result::eSuccess)
throw std::runtime_error("Failed to wait for idle!");
cleanupSwapChain(); cleanupSwapChain();
@ -226,15 +219,7 @@ class VulkanApp {
for (const char* extension : extensions) fmt::println("\t{}", extension); for (const char* extension : extensions) fmt::println("\t{}", extension);
#endif #endif
vk::Result instanceResult = vk::Result::eSuccess; mInstance = vk::createInstanceUnique(createInfo);
vk::UniqueInstance instanceValue;
std::tie(instanceResult, instanceValue) = vk::createInstanceUnique(createInfo).asTuple();
if (instanceResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create instance!");
mInstance = std::move(instanceValue);
VULKAN_HPP_DEFAULT_DISPATCHER.init(mInstance.get()); VULKAN_HPP_DEFAULT_DISPATCHER.init(mInstance.get());
} }
@ -253,36 +238,22 @@ class VulkanApp {
.pfnUserCallback = debugCallback, .pfnUserCallback = debugCallback,
}; };
vk::Result debugMessengerResult = vk::Result::eSuccess; mDebugMessenger = mInstance->createDebugUtilsMessengerEXTUnique(messengerCreateInfo, nullptr);
vk::UniqueDebugUtilsMessengerEXT debugMessengerValue;
std::tie(debugMessengerResult, debugMessengerValue) =
mInstance->createDebugUtilsMessengerEXTUnique(messengerCreateInfo, nullptr).asTuple();
if (debugMessengerResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to set up debug messenger!");
mDebugMessenger = std::move(debugMessengerValue);
} }
fn createSurface() -> void { mSurface = vkfw::createWindowSurfaceUnique(mInstance.get(), mWindow.get()); } fn createSurface() -> void { mSurface = vkfw::createWindowSurfaceUnique(mInstance.get(), mWindow.get()); }
fn pickPhysicalDevice() -> void { fn pickPhysicalDevice() -> void {
vk::Result devicesResult = vk::Result::eSuccess; std::vector<vk::PhysicalDevice> devices = mInstance->enumeratePhysicalDevices();
std::vector<vk::PhysicalDevice> devicesValue;
std::tie(devicesResult, devicesValue) = mInstance->enumeratePhysicalDevices();
if (devicesResult != vk::Result::eSuccess) if (devices.empty())
throw std::runtime_error("Failed to enumerate physical devices!");
if (devicesValue.empty())
throw std::runtime_error("Failed to find GPUs with Vulkan support!"); throw std::runtime_error("Failed to find GPUs with Vulkan support!");
#ifndef NDEBUG #ifndef NDEBUG
fmt::println("Available devices:"); fmt::println("Available devices:");
#endif #endif
for (const vk::PhysicalDevice& device : devicesValue) { for (const vk::PhysicalDevice& device : devices) {
#ifndef NDEBUG #ifndef NDEBUG
vk::PhysicalDeviceProperties properties = device.getProperties(); vk::PhysicalDeviceProperties properties = device.getProperties();
fmt::println("\t{}", properties.deviceName.data()); fmt::println("\t{}", properties.deviceName.data());
@ -322,17 +293,7 @@ class VulkanApp {
.ppEnabledExtensionNames = deviceExtensions.data(), .ppEnabledExtensionNames = deviceExtensions.data(),
.pEnabledFeatures = &deviceFeatures }; .pEnabledFeatures = &deviceFeatures };
vk::Result createDeviceResult = vk::Result::eSuccess; mDevice = mPhysicalDevice.createDeviceUnique(createInfo);
vk::UniqueDevice createDeviceValue;
std::tie(createDeviceResult, createDeviceValue) =
mPhysicalDevice.createDeviceUnique(createInfo).asTuple();
if (createDeviceResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create logical device!");
mDevice = std::move(createDeviceValue);
mGraphicsQueue = mDevice->getQueue(indices.graphics_family.value(), 0); mGraphicsQueue = mDevice->getQueue(indices.graphics_family.value(), 0);
mPresentQueue = mDevice->getQueue(indices.present_family.value(), 0); mPresentQueue = mDevice->getQueue(indices.present_family.value(), 0);
} }
@ -374,24 +335,9 @@ class VulkanApp {
.oldSwapchain = nullptr, .oldSwapchain = nullptr,
}; };
vk::Result swapChainResult = vk::Result::eSuccess; mSwapChain = mDevice->createSwapchainKHRUnique(createInfo);
vk::UniqueSwapchainKHR swapChainValue;
std::tie(swapChainResult, swapChainValue) = mDevice->createSwapchainKHRUnique(createInfo).asTuple(); mSwapChainImages = mDevice->getSwapchainImagesKHR(mSwapChain.get());
if (swapChainResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create swap chain!");
mSwapChain = std::move(swapChainValue);
vk::Result swapChainImagesResult = vk::Result::eSuccess;
std::vector<vk::Image> mSwapChainImagesValue;
std::tie(swapChainImagesResult, mSwapChainImagesValue) = mDevice->getSwapchainImagesKHR(mSwapChain.get());
if (swapChainImagesResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to get swap chain images!");
mSwapChainImages = std::move(mSwapChainImagesValue);
mSwapChainImageFormat = surfaceFormat.format; mSwapChainImageFormat = surfaceFormat.format;
mSwapChainExtent = extent; mSwapChainExtent = extent;
} }
@ -417,15 +363,7 @@ class VulkanApp {
// clang-format on // clang-format on
}; };
vk::Result createImageViewResult = vk::Result::eSuccess; mSwapChainImageViews[i] = mDevice->createImageViewUnique(createInfo);
vk::UniqueImageView imageViewValue;
std::tie(createImageViewResult, imageViewValue) = mDevice->createImageViewUnique(createInfo).asTuple();
if (createImageViewResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create image views!");
mSwapChainImageViews[i] = std::move(imageViewValue);
} }
} }
@ -459,15 +397,7 @@ class VulkanApp {
.pSubpasses = &subpass, .pSubpasses = &subpass,
}; };
vk::Result renderPassResult = vk::Result::eSuccess; mRenderPass = mDevice->createRenderPassUnique(renderPassInfo);
vk::UniqueRenderPass renderPassValue;
std::tie(renderPassResult, renderPassValue) = mDevice->createRenderPassUnique(renderPassInfo).asTuple();
if (renderPassResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create render pass!");
mRenderPass = std::move(renderPassValue);
} }
fn createGraphicsPipeline() -> void { fn createGraphicsPipeline() -> void {
@ -549,16 +479,7 @@ class VulkanApp {
.pushConstantRangeCount = 0, .pushConstantRangeCount = 0,
}; };
vk::Result pipelineLayoutResult = vk::Result::eSuccess; mPipelineLayout = mDevice->createPipelineLayoutUnique(pipelineLayoutInfo);
vk::UniquePipelineLayout pipelineLayoutValue;
std::tie(pipelineLayoutResult, pipelineLayoutValue) =
mDevice->createPipelineLayoutUnique(pipelineLayoutInfo).asTuple();
if (pipelineLayoutResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create pipeline layout!");
mPipelineLayout = std::move(pipelineLayoutValue);
vk::GraphicsPipelineCreateInfo pipelineInfo { vk::GraphicsPipelineCreateInfo pipelineInfo {
.stageCount = static_cast<u32>(shaderStages.size()), .stageCount = static_cast<u32>(shaderStages.size()),
@ -600,16 +521,7 @@ class VulkanApp {
.layers = 1, .layers = 1,
}; };
vk::Result framebufferResult = vk::Result::eSuccess; mSwapChainFramebuffers[i] = mDevice->createFramebufferUnique(framebufferInfo);
vk::UniqueFramebuffer framebufferValue;
std::tie(framebufferResult, framebufferValue) =
mDevice->createFramebufferUnique(framebufferInfo).asTuple();
if (framebufferResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create framebuffer!");
mSwapChainFramebuffers[i] = std::move(framebufferValue);
} }
} }
@ -621,15 +533,7 @@ class VulkanApp {
.queueFamilyIndex = queueFamilyIndices.graphics_family.value(), .queueFamilyIndex = queueFamilyIndices.graphics_family.value(),
}; };
vk::Result commandPoolResult = vk::Result::eSuccess; mCommandPool = mDevice->createCommandPoolUnique(poolInfo);
vk::UniqueCommandPool commandPoolValue;
std::tie(commandPoolResult, commandPoolValue) = mDevice->createCommandPoolUnique(poolInfo).asTuple();
if (commandPoolResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create command pool!");
mCommandPool = std::move(commandPoolValue);
} }
fn createCommandBuffers() -> void { fn createCommandBuffers() -> void {
@ -640,25 +544,13 @@ class VulkanApp {
.commandBufferCount = .commandBufferCount =
static_cast<u32>(mCommandBuffers.size()) }; static_cast<u32>(mCommandBuffers.size()) };
vk::Result commandBufferResult = vk::Result::eSuccess; mCommandBuffers = mDevice->allocateCommandBuffersUnique(allocInfo);
std::vector<vk::UniqueCommandBuffer> commandBufferValue;
std::tie(commandBufferResult, commandBufferValue) =
mDevice->allocateCommandBuffersUnique(allocInfo).asTuple();
if (commandBufferResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to allocate command buffers!");
mCommandBuffers = std::move(commandBufferValue);
} }
fn recordCommandBuffer(vk::CommandBuffer commandBuffer, u32 imageIndex) -> void { fn recordCommandBuffer(vk::CommandBuffer commandBuffer, u32 imageIndex) -> void {
vk::CommandBufferBeginInfo beginInfo {}; vk::CommandBufferBeginInfo beginInfo {};
vk::Result beginResult = commandBuffer.begin(beginInfo); commandBuffer.begin(beginInfo);
if (beginResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to begin command buffer!");
vk::ClearValue clearColor { .color = { .float32 = std::array<float, 4> { 0.0F, 0.0F, 0.0F, 1.0F } } }; vk::ClearValue clearColor { .color = { .float32 = std::array<float, 4> { 0.0F, 0.0F, 0.0F, 1.0F } } };
@ -693,10 +585,7 @@ class VulkanApp {
commandBuffer.endRenderPass(); commandBuffer.endRenderPass();
vk::Result endResult = commandBuffer.end(); commandBuffer.end();
if (endResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to end command buffer!");
} }
fn createSyncObjects() -> void { fn createSyncObjects() -> void {
@ -708,37 +597,9 @@ class VulkanApp {
vk::FenceCreateInfo fenceInfo { .flags = vk::FenceCreateFlagBits::eSignaled }; vk::FenceCreateInfo fenceInfo { .flags = vk::FenceCreateFlagBits::eSignaled };
for (usize idx = 0; idx < MAX_FRAMES_IN_FLIGHT; idx++) { for (usize idx = 0; idx < MAX_FRAMES_IN_FLIGHT; idx++) {
vk::Result imageAvailableSemaphoreResult = vk::Result::eSuccess; mImageAvailableSemaphores[idx] = mDevice->createSemaphoreUnique(semaphoreInfo);
vk::UniqueSemaphore imageAvailableSemaphoreValue; mRenderFinishedSemaphores[idx] = mDevice->createSemaphoreUnique(semaphoreInfo);
mInFlightFences[idx] = mDevice->createFenceUnique(fenceInfo);
std::tie(imageAvailableSemaphoreResult, imageAvailableSemaphoreValue) =
mDevice->createSemaphoreUnique(semaphoreInfo).asTuple();
if (imageAvailableSemaphoreResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create semaphores!");
mImageAvailableSemaphores[idx] = std::move(imageAvailableSemaphoreValue);
vk::Result renderFinishedSemaphoreResult = vk::Result::eSuccess;
vk::UniqueSemaphore renderFinishedSemaphoreValue;
std::tie(renderFinishedSemaphoreResult, renderFinishedSemaphoreValue) =
mDevice->createSemaphoreUnique(semaphoreInfo).asTuple();
if (imageAvailableSemaphoreResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create semaphores!");
mRenderFinishedSemaphores[idx] = std::move(renderFinishedSemaphoreValue);
vk::Result fenceResult = vk::Result::eSuccess;
vk::UniqueFence fenceValue;
std::tie(fenceResult, fenceValue) = mDevice->createFenceUnique(fenceInfo).asTuple();
if (fenceResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create fences!");
mInFlightFences[idx] = std::move(fenceValue);
} }
} }
@ -781,10 +642,7 @@ class VulkanApp {
.pSignalSemaphores = &mRenderFinishedSemaphores[mCurrentFrame].get(), .pSignalSemaphores = &mRenderFinishedSemaphores[mCurrentFrame].get(),
}; };
vk::Result submitResult = mGraphicsQueue.submit(submitInfo, mInFlightFences[mCurrentFrame].get()); mGraphicsQueue.submit(submitInfo, mInFlightFences[mCurrentFrame].get());
if (submitResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to submit draw command buffer!");
vk::PresentInfoKHR presentInfo { vk::PresentInfoKHR presentInfo {
.waitSemaphoreCount = 1, .waitSemaphoreCount = 1,
@ -794,32 +652,33 @@ class VulkanApp {
.pImageIndices = &imageIndexValue, .pImageIndices = &imageIndexValue,
}; };
vk::Result presentResult = mPresentQueue.presentKHR(presentInfo); try {
vk::Result presentResult = mPresentQueue.presentKHR(presentInfo);
if (presentResult == vk::Result::eErrorOutOfDateKHR || presentResult == vk::Result::eSuboptimalKHR || fmt::println("Present result: {}", vk::to_string(presentResult));
mFramebufferResized) {
if (presentResult == vk::Result::eErrorOutOfDateKHR || presentResult == vk::Result::eSuboptimalKHR ||
mFramebufferResized) {
mFramebufferResized = false;
recreateSwapChain();
} else if (presentResult != vk::Result::eSuccess) {
throw std::runtime_error("Failed to present swap chain image!");
}
mCurrentFrame = (mCurrentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
} catch (vk::OutOfDateKHRError& err) {
fmt::println("Caught OutOfDateKHRError: {}", err.what());
mFramebufferResized = false; mFramebufferResized = false;
recreateSwapChain(); recreateSwapChain();
} else if (presentResult != vk::Result::eSuccess) { return;
throw std::runtime_error("Failed to present swap chain image!");
} }
mCurrentFrame = (mCurrentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
} }
fn createShaderModule(const std::vector<char>& code) -> vk::UniqueShaderModule { fn createShaderModule(const std::vector<char>& code) -> vk::UniqueShaderModule {
vk::ShaderModuleCreateInfo createInfo { .codeSize = code.size(), vk::ShaderModuleCreateInfo createInfo { .codeSize = code.size(),
.pCode = std::bit_cast<const u32*>(code.data()) }; .pCode = std::bit_cast<const u32*>(code.data()) };
vk::Result shaderModuleResult = vk::Result::eSuccess; return mDevice->createShaderModuleUnique(createInfo);
vk::UniqueShaderModule shaderModuleValue;
std::tie(shaderModuleResult, shaderModuleValue) = mDevice->createShaderModuleUnique(createInfo).asTuple();
if (shaderModuleResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to create shader module!");
return shaderModuleValue;
} }
static fn chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats static fn chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats
@ -861,36 +720,9 @@ class VulkanApp {
fn querySwapChainSupport(vk::PhysicalDevice device) -> SwapChainSupportDetails { fn querySwapChainSupport(vk::PhysicalDevice device) -> SwapChainSupportDetails {
SwapChainSupportDetails details; SwapChainSupportDetails details;
vk::Result surfaceCapabilitiesResult = vk::Result::eSuccess; details.capabilities = device.getSurfaceCapabilitiesKHR(mSurface.get());
vk::SurfaceCapabilitiesKHR surfaceCapabilitiesValue; details.formats = device.getSurfaceFormatsKHR(mSurface.get());
details.present_modes = device.getSurfacePresentModesKHR(mSurface.get());
std::tie(surfaceCapabilitiesResult, surfaceCapabilitiesValue) =
device.getSurfaceCapabilitiesKHR(mSurface.get());
if (surfaceCapabilitiesResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to get surface capabilities!");
details.capabilities = surfaceCapabilitiesValue;
vk::Result surfaceFormatsResult = vk::Result::eSuccess;
std::vector<vk::SurfaceFormatKHR> surfaceFormatsValue;
std::tie(surfaceFormatsResult, surfaceFormatsValue) = device.getSurfaceFormatsKHR(mSurface.get());
if (surfaceFormatsResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to get surface formats!");
details.formats = surfaceFormatsValue;
vk::Result presentModesResult = vk::Result::eSuccess;
std::vector<vk::PresentModeKHR> presentModesValue;
std::tie(presentModesResult, presentModesValue) = device.getSurfacePresentModesKHR(mSurface.get());
if (presentModesResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to get surface present modes!");
details.present_modes = presentModesValue;
return details; return details;
} }
@ -911,18 +743,11 @@ class VulkanApp {
} }
static fn checkDeviceExtensionSupport(vk::PhysicalDevice device) -> bool { static fn checkDeviceExtensionSupport(vk::PhysicalDevice device) -> bool {
vk::Result availableExtensionsResult = vk::Result::eSuccess; std::vector<vk::ExtensionProperties> availableExtensions = device.enumerateDeviceExtensionProperties();
std::vector<vk::ExtensionProperties> availableExtensionsValue;
std::tie(availableExtensionsResult, availableExtensionsValue) =
device.enumerateDeviceExtensionProperties();
if (availableExtensionsResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to enumerate device extensions!");
std::set<string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); std::set<string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
for (const vk::ExtensionProperties& extension : availableExtensionsValue) for (const vk::ExtensionProperties& extension : availableExtensions)
requiredExtensions.erase(extension.extensionName); requiredExtensions.erase(extension.extensionName);
return requiredExtensions.empty(); return requiredExtensions.empty();
@ -937,16 +762,9 @@ class VulkanApp {
if (queueFamilies[i].queueFlags & vk::QueueFlagBits::eGraphics) if (queueFamilies[i].queueFlags & vk::QueueFlagBits::eGraphics)
indices.graphics_family = i; indices.graphics_family = i;
vk::Result queuePresentSupportResult = vk::Result::eSuccess; vk::Bool32 queuePresentSupport = device.getSurfaceSupportKHR(i, mSurface.get());
vk::Bool32 queuePresentSupportValue = 0;
std::tie(queuePresentSupportResult, queuePresentSupportValue) = if (queuePresentSupport)
device.getSurfaceSupportKHR(i, mSurface.get());
if (queuePresentSupportResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to get surface support!");
if (queuePresentSupportValue)
indices.present_family = i; indices.present_family = i;
if (indices.isComplete()) if (indices.isComplete())
@ -968,17 +786,12 @@ class VulkanApp {
} }
static fn checkValidationLayerSupport() -> bool { static fn checkValidationLayerSupport() -> bool {
vk::Result availableLayersResult = vk::Result::eSuccess; std::vector<vk::LayerProperties> availableLayers = vk::enumerateInstanceLayerProperties();
std::vector<vk::LayerProperties> availableLayersValue;
std::tie(availableLayersResult, availableLayersValue) = vk::enumerateInstanceLayerProperties();
if (availableLayersResult != vk::Result::eSuccess)
throw std::runtime_error("Failed to enumerate validation layers!");
for (const char* layerName : validationLayers) { for (const char* layerName : validationLayers) {
bool layerFound = false; bool layerFound = false;
for (const vk::LayerProperties& layerProperties : availableLayersValue) for (const vk::LayerProperties& layerProperties : availableLayers)
if (strcmp(layerName, layerProperties.layerName) == 0) { if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true; layerFound = true;
break; break;