I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//currentCommandBuffer = commandBuffers[currentFrame];
currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2;
currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex];
vkBeginCommandBuffer(currentCommandBuffer, &beginInfo);
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffers[imageIndex];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
// Set the clear color to black
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
void Renderer::ChoosePhysicalDevice()
{
// Enumerate the available physical devices and choose one that supports required features
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0)
{
throw std::runtime_error("Failed to find a GPU with Vulkan support.");
}
std::vector<VkPhysicalDevice> allDevices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data());
for (const auto& testDevice : allDevices)
{
if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) &&
CheckPhysicalDeviceExtensionSupport(testDevice).empty() &&
GetQueueFamilyIndices(testDevice).IsComplete())
{
physicalDevice = testDevice;
break;
}
}
if (physicalDevice == VK_NULL_HANDLE)
{
throw std::runtime_error("Failed to find a suitable GPU.");
}
}
void Renderer::CreateDevice()
{
// Get the GPU’s queue family indices
const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice);
// Set up the device queue create info
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() };
float queuePriority = 1.0f;
for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices)
{
VkDeviceQueueCreateInfo queueCreateInfo{};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
// Set up the physical device features
VkPhysicalDeviceFeatures deviceFeatures{};
// Set up the device create info
VkDeviceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
// Create the logical device
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a logical device.");
}
// Retrieve the graphics queue and the present queue
vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
void Renderer::CreateCommandPool()
{
// Find a queue family index that supports graphics operations
QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice);
// Create a command pool for the queue family
VkCommandPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
poolInfo.flags = 0;
if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create command pool.");
}
CreateCommandBuffers(); // Create command buffers after creating the command pool
}
void Renderer::CleanupCommandPool()
{
// Clean up Vulkan command pool
CleanupCommandBuffers(); // Add this line to clean up command buffers before destroying the command pool
vkDestroyCommandPool(device, commandPool, nullptr);
}
void Renderer::CreateFramebuffers()
{
// Check if the framebuffers vector is not empty, and call CleanupFramebuffers()
if (!framebuffers.empty()) {
CleanupFramebuffers();
}
It does this after renderering several frames, but then just stops progressing past this line. Any ideas of what the issue could be?
It appears that the issue might be related to the synchronization of the in-flight frames. The call to vkBeginCommandBuffer may block if the command buffer is still being used by the GPU. To address this issue, you should consider the following modifications:
Instead of using a single set of semaphores and fences for all frames, provide an individual set for each frame. Modify the BeginFrame() method to wait for the fence of the current frame, reset it, and then associate that fence with the current command buffer through vkQueueSubmit().
When updating the value of currentCmdBufferIndex, make sure it is not greater than the number of frames in flight. A simple solution is to use a % operator with kMaxFramesInFlight.
Make sure to call vkQueueWaitIdle() for both graphics and present queues before destroying or recreating any resources that are associated with those queues. This includes swapchain images and framebuffers.
Here are the suggested modifications:
Renderer.h:
...
// Add variables to store semaphores and fences per frame
std::vector<std::vector<VkSemaphore>> imageAvailableSemaphoresPerFrame;
std::vector<std::vector<VkSemaphore>> renderFinishedSemaphoresPerFrame;
std::vector<VkFence> commandBufferFences;
...
Renderer.cpp:
...
void Renderer::Initialize(GLFWwindow* window)
{
...
CreateSyncObjects();
// Allocate space for per-frame synchronization objects
imageAvailableSemaphoresPerFrame.resize(kMaxFramesInFlight, imageAvailableSemaphores);
renderFinishedSemaphoresPerFrame.resize(kMaxFramesInFlight, renderFinishedSemaphores);
commandBufferFences.resize(kMaxFramesInFlight);
}
void Renderer::BeginFrame()
{
// Wait for the current command buffer fence instead of the previous inFlightFences
vkWaitForFences(device, 1, &commandBufferFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &commandBufferFences[currentFrame]);
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphoresPerFrame[currentFrame][currentCmdBufferIndex], VK_NULL_HANDLE, &imageIndex);
...
}
void Renderer::EndFrame()
{
...
vkQueueSubmit(graphicsQueue, 1, &submitInfo, commandBufferFences[currentFrame]);
...
currentCmdBufferIndex = (currentCmdBufferIndex + 1) % kMaxFramesInFlight; // Note the % operator to keep the index within the range
currentFrame = (currentFrame + 1) % kMaxFramesInFlight;
}
...
These modifications should help address the synchronization issue and prevent hanging at vkBeginCommandBuffer().