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.
It appears that you might be facing a synchronization issue. The vkBeginCommandBuffer() function might be waiting for the resources to be available, which causes the program to hang.
You should wait for the fences associated with the swapchain image you are going to use (imageIndex) before starting recording commands into the command buffer related to that specific swapchain image.
In your Renderer::BeginFrame() method, instead of waiting for the fence related to the currentFrame, you should wait for the fence related to the imageIndex acquired.
Replace:
cpp
User
I have made those adjustment, but I now have an error saying "vector subscript out of range"
Assistant
The error is caused by accessing an element in a vector with an index out of range. Based on the changes you've made, it appears that the error may be related to the inFlightFences vector's length, which is still kMaxFramesInFlight.
You should change the inFlightFences vector size to match the number of swapchain images to ensure that you have one fence for each image in the swap chain. To do this, adjust the CreateSyncObjects() method as follows:
User
Although this does fix the "vector subscript out of range" error, it seems the original changes did not fix the hanging issue at vkBeginCommandBuffer
Assistant
I apologize for the confusion. In this case, let's take a different approach by returning to using the currentFrame variable for fences and semaphores. The issue might be caused by the incorrect handling of the currentCmdBufferIndex variable.
First, revert back to using currentFrame in the BeginFrame() and EndFrame() methods as was done in your original code:
Next, let's modify how the currentCmdBufferIndex is calculated in the BeginFrame() function. Replace this:
cpp
User
It seems this has not fixed the issue. It seems to be getting caught on Current Frame 1, Buffer Index 2, Image Index 2
Assistant
I apologize for the confusion. Now let's try another approach using only one command buffer per frame and without double-buffering the command buffers, which should simplify the synchronization in the BeginFrame() method.
First, revert the changes to the command buffer index calculation in the BeginFrame() method:
Then, change the allocation size for the commandBuffers vector to match the number of frames in flight (kMaxFramesInFlight):
cpp
commandBuffers.resize(kMaxFramesInFlight);
Since you are not using double-buffering for command buffers anymore, you don't have to cycle through the entire range of available command buffers. Therefore, you're using only one command buffer per frame.
After implementing these changes, your application should continue rendering without hanging at the vkBeginCommandBuffer() call.
User
Unfortunately that didn't work either. The problem could be related to cycling back to the first image index.
Assistant
After reexamining the problem, there might be an issue with image acquisition, swapchain recreation, or window resizing. We can try a different approach by recreating the necessary objects when the swapchain becomes out of date or suboptimal.
First, let's create a function to handle recreating the swapchain in Renderer class:
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]);
code
// 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);
code
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);
code
// 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);
code
// 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?
// 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]);
With:
cpp
// 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);
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[imageIndex], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[imageIndex]);
if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
Finally, when you submit your queue in the Renderer::EndFrame() method, you need to pass the fence related to the imageIndex instead of the currentFrame.
This change ensures that the currentCmdBufferIndex cycles through the entire range of available command buffers instead of switching between only two each frame.
With this change, your application should continue rendering without hanging at the vkBeginCommandBuffer() call.