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.
Instead of having vkBeginCommandBuffer after waiting for fences and acquiring the next image, try moving the vkBeginCommandBuffer call right before starting the render pass. This can prevent any discrepancy in synchronization between the two calls.
First, move vkBeginCommandBuffer and its related code to a separate method you can call when needed:
Then call this method right before the render pass starts in the BeginFrame method:
void Renderer::BeginFrame()
{
// ...
// Replace the vkBeginCommandBuffer call with the new BeginCommandBuffer method
BeginCommandBuffer();
// ...
vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
}
User
The suggested changes are already part of the code. There must be something else causing the issue.
Assistant
User
I've made the changes, but it now hangs on the new vkResetCommandBuffer in BeginFrame. Here is the last lines of the console output:
Current Frame: 1 | Cmd Buffer Index: 0 | Image Index: 1
Calling vkBeginCommandBuffer
vkBeginCommandBuffer called
Frame rendered: 1
Assistant
I apologize for the confusion in previous suggestions, and I appreciate your patience. After carefully re-reading your code, I identified an issue with how you set up the synchronization objects.
You are using the currentFrame index to index imageAvailableSemaphores, renderFinishedSemaphores, and inFlightFences. These are indexed by frame number (0 or 1), while imageIndex is the swapchain image index (0, 1, 2, or higher).
Change the BeginFrame() and EndFrame() methods to use imageIndex for synchronization objects.
Here's the updated BeginFrame() method:
void Renderer::BeginFrame()
{
// 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]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[imageIndex], VK_NULL_HANDLE, &imageIndex);
// Rest of the code...
}
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::CreateCommandBuffers()
{
commandBuffers.resize(swapChainImages.size());
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = commandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size());
if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate command buffers.");
}
// Set the initial value of the currentCommandBuffer
currentCommandBuffer = commandBuffers[currentFrame];
void Renderer::CreateFramebuffers()
{
// Check if the framebuffers vector is not empty, and call CleanupFramebuffers()
if (!framebuffers.empty()) {
CleanupFramebuffers();
}
It compeltes a full cycle of imageindices, but still hangs a bit later. Here is the last lines of console outputs:
Current Frame: 0 | Cmd Buffer Index: 1 | Image Index: 1
Calling vkBeginCommandBuffer
What changes to the code would fix this?
Remember to properly handle any RESOURCES and objects between frames. In general, always ensure that the current swapchain image is idle before you use it by properly synchronizing your resources.
If the problem persists, consider checking synchronization mechanisms like semaphores and fences and verify if they are set up correctly. Additionally, you can validate the application using the VK_LAYER_KHRONOS_validation layer. This might give you clues on any potential issue with the Vulkan calls.
I apologize for the oversight. I see that you're only resetting the fence after waiting on it but not resetting the command buffer. We should reset the command buffer after calling vkWaitForFences so that it is in a clean state before reusing it.
Modify the BeginFrame() method to include resetting the command buffer:
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]);
// Reset the command buffer
vkResetCommandBuffer(currentCommandBuffer, 0);
// 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);
// ...
// Call vkBeginCommandBuffer
BeginCommandBuffer();
// Rest of the code...
}
A better solution to this issue could be to use separate command buffers for each frame. Instead of reusing the command buffers via resetting them, you create as many command buffers as you have swapchain images. This way, you can eliminate potential synchronization issues related to reusing command buffers.
To implement this, change the code to allocate as many command buffers as you have swapchain images: