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.
The issue is likely due to improper synchronization between frames when using the double buffering technique with your command buffers (2 command buffers per frame). The hang occurs when starting the second cycle on Image Index 0 because it has not finished its rendering from the previous cycle yet.
To fix this issue, you should wait for the corresponding inFlightFences of the Image Index before resetting it. Modify the BeginFrame() method as follows:
Update the vkWaitForFences call at the beginning of the BeginFrame() method to wait for the inFlightFences corresponding to the current image index rather than the current frame.
In step 2 of your instructions, where should I put these lines of code?
Assistant
My apologies for the confusion. You should add those lines of code within the Renderer::Initialize() method, after creating the swap chain. It should look like this:
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
// Initialize the currentFramePerImage vector after creating the swap chain
currentFramePerImage.resize(swapChainImages.size(), 0);
}
This way, the currentFramePerImage vector will be properly initialized and resized based on the number of images in the swap chain.
User
I am getting a vector subscript out of range error. Based on the debug console outputs, it seems to be trying to access an imageindex beyond the range of the vector.
Assistant
The error could occur if the BeginFrame() and EndFrame() methods are not properly synchronized. To ensure better synchronization and prevent this "vector subscript out of range" error, update the EndFrame() method as follows:
Replace the vkQueuePresentKHR call with a custom function that presents the image and properly waits for the correct image index.
Add this custom Present() function to the Renderer class:
User
The application now exits with an error "Failed to acquire next swapchain image." This happens after Image Index 1 in the console outputs.
Assistant
The "Failed to acquire next swapchain image" error occurs when the vkAcquireNextImageKHR function returns an error. This often happens when the window is minimized or resized. To handle this case, update the Renderer::BeginFrame() method as follows:
Add a boolean variable called to the Renderer class. Set this variable to initially to trigger the swapchain recreation on startup.
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();
}
The issue seems to occur after completing an full cycle of the image indices and cycling back to Image Index 0. Any ideas of what the issue could be?
Instead of using a single currentFrame variable and cycling it after each frame, create a separate vector of size swapChainImages.size() to store the current frame index for each image index and initialize all elements to 0.
With these changes, your engine should properly synchronize between frames for each image index and avoid hanging in the Renderer::BeginFrame method.
void Renderer::Present()
{
vkQueueWaitIdle(presentQueue); // Wait for the presentQueue to be idle
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame];
VkSwapchainKHR swapChains[] = { swapchain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo);
if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) {
// Handle swapchain recreation due to resizing the window or other swapchain properties changes
}
else if (queuePresentResult != VK_SUCCESS) {
throw std::runtime_error("Failed to present the swapchain image.");
}
// Cycle the current frame index for the current image index
currentFramePerImage[imageIndex] = (currentFramePerImage[imageIndex] + 1) % kMaxFramesInFlight;
// Update currentFrame
currentFrame = currentFramePerImage[imageIndex];
}
In the EndFrame() method, replace the vkQueuePresentKHR with the new Present() function:
void Renderer::EndFrame()
{
// ...
vkEndCommandBuffer(currentCommandBuffer);
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[imageIndex]);
// Call the custom Present() function to properly wait for the correct image index
Present();
}
With these changes, the synchronization between BeginFrame() and EndFrame() should work correctly, and you should no longer encounter the "vector subscript out of range" error.
Update the Renderer::BeginFrame() method to check and handle the error when acquiring the swapchain image. Additionally, handle swapchain recreation when the framebuffer is resized or the swapchain becomes suboptimal.
void Renderer::BeginFrame()
{
// ...
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
// Handle swapchain recreation when the framebuffer is resized or the swapchain becomes suboptimal
if (acquireResult == VK_ERROR_OUT_OF_DATE_KHR || acquireResult == VK_SUBOPTIMAL_KHR || framebufferResized)
{
// Recreate swapchain and necessary components
Shutdown();
Initialize(window);
// Reset the framebufferResized flag
framebufferResized = false;
return;
}
else if (acquireResult != VK_SUCCESS)
{
throw std::runtime_error("Failed to acquire next swapchain image.");
}
// ...
}
Finally, connect the OnFramebufferResized() method to a window resize callback. You can do this with the GLFWwindow, for example, by calling glfwSetFramebufferSizeCallback() when setting up the GLFWwindow:
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
auto renderer = static_cast<Renderer*>(glfwGetWindowUserPointer(window));
renderer->OnFramebufferResized();
}
int main()
{
// ...
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// ...
}
With these changes, the application should properly handle the case when the framebuffer is resized or the acquired swapchain image is suboptimal, and the "Failed to acquire next swap