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 have written the code for the foundations of the engine. I want to modify this code to render a simple black screen. I will later extend it to render 3d object.
The basic class structure is as follows:
Core:
class Engine
This is the main class that will initialize, run, and shut down other subsystems of the engine (e.g., Window, Renderer, Input, etc.)
Window:
class Window
This class will handle window creation, resizing, and destruction using GLFW. It should also handle keyboard and mouse input events.
Renderer:
class Renderer
This class will manage Vulkan objects (e.g., instance, device, swapchain, command buffers) and rendering pipelines.
class Shader
To handle shader modules creation and destruction.
class Texture
To handle texture loading and destruction.
class Pipeline
To encapsulate the description and creation of a Vulkan graphics or compute pipeline.
Scene:
class Scene
This class will manage the list of objects in the vector, update their transforms, and send them to the Renderer for rendering.
class GameObject
To represent individual objects in the scene, store their transformation matrices, and bind the relevant data like vertices and indices.
class Camera
To store and manage camera properties such as position, rotation, view, and projection matrices.
class Mesh
To handle mesh data (e.g., vertices, indices, etc.) for individual objects.
class Material
To store and manage material properties such as colors, shaders, and textures.
Math:
Utilize GLM library to handle vector and matrix math operations.
I am having some issues with the Renderer class. Here is are the header and source files for the Renderer class:
The issue could be caused by out-of-order execution of your command buffers or improper synchronization between different pipeline stages. To fix this, you can make the following changes in your code:
Move the vkWaitForFences() function to the BeginFrame() method, right before vkAcquireNextImageKHR(). This ensures that we start acquiring the next swapchain image only after rendering the previous frame is complete.
In the EndFrame() method, after submitting the command buffer to the queue using , wait for the execution of command buffers to complete using . This ensures that all command buffers submitted to the graphics queue have been executed before calling .
User
It seems that hasn't resolved the issue. The code is still getting stuck on vkWaitForFences in the EndFrame method. Is there something else that might be causing the issue?
Assistant
I apologize for the confusion in my previous response. I overlooked the fact that you had the vkWaitForFences() function in the EndFrame() method. You should move it to the BeginFrame() method, as initially mentioned. However, you should not use in the method because it defeats the purpose of using multiple frames in flight.
User
I am now getting an access violation error message in the CleanupSyncObjects method. Do you have any idea how to fix this issue?
Assistant
The access violation error in the CleanupSyncObjects() method might be caused by attempting to destroy uninitialized synchronization objects or trying to destroy them while they are still in use. To avoid this issue, you can make several adjustments:
Ensure that the CleanupSyncObjects() method is called after the rendering loop is finished, and no more rendering operations are in progress.
Make sure that the synchronization objects are created properly in the CreateSyncObjects() method.
User
I am still getting an access violation error. However, I have noticed it is logging a runtime error in the EndFrame method, which may be the cause of the access violation error. It is triggering the "Failed to acquire next swapchain image." message. How would I alter the code to fix this error?
void Renderer::BeginFrame()
{
// Acquire an image from the swapchain, then begin recording commands for the current frame.
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
void Renderer::EndFrame()
{
// 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
vkCmdEndRenderPass(currentCommandBuffer);
// Acquire the next available swapchain image
uint32_t imageIndex;
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (acquireResult == VK_ERROR_OUT_OF_DATE_KHR) {
// Handle swapchain recreation if needed, e.g. due to resizing the window or other swapchain properties changes
return;
}
else if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
// Finish recording commands, then present the rendered frame back to the swapchain.
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame];
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = ¤tCommandBuffer;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame];
vkEndCommandBuffer(currentCommandBuffer);
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]);
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 if needed, e.g. 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.");
}
currentFrame = (currentFrame + 1) % kMaxFramesInFlight;
}
void Renderer::CreateSurface()
{
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a window surface.");
}
}
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);
}
Do you know why this might be the case any how to fix it?
vkQueueSubmit()
vkQueueWaitIdle(graphicsQueue)
vkQueuePresentKHR()
Here is the modified BeginFrame() and EndFrame() methods with these changes:
cpp
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.
uint32_t imageIndex;
vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
// ... rest of the code
}
void Renderer::EndFrame()
{
// ... code before vkQueueSubmit()
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]);
// Wait for the execution of command buffers to complete.
vkQueueWaitIdle(graphicsQueue);
// ... code related to vkQueuePresentKHR() and currentFrame update
}
With these changes, the issue with the code getting stuck at vkWaitForFences() should be resolved, and you should be able to display a simple black screen using your Renderer class.
vkQueueWaitIdle()
EndFrame()
Given that the issue still persists, that means there might be another issue caused by improper synchronization. You could try the following adjustments in your code to address potential synchronization problems:
In the BeginFrame() method, move the vkResetFences() function to after the vkAcquireNextImageKHR() call to reset the fence associated with the acquired image:
cpp
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
// Acquire the next available swapchain image
uint32_t imageIndex;
vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
// Reset the fence for the current frame after acquiring the image
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// ... rest of the code
}
Additionally, in the EndFrame() method, pass inFlightFences[currentFrame] to the vkQueueSubmit() function as a signal fence. This way, the fence will be signaled when the command buffer has completed execution:
cpp
void Renderer::EndFrame()
{
// ... code before vkQueueSubmit()
// Pass the inFlightFences[currentFrame] as the signal fence to vkQueueSubmit()
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]);
// ... code related to vkQueuePresentKHR() and currentFrame update
}
These modifications should help ensure that the synchronization between frames and command buffer execution is working correctly. Make sure to remove any vkQueueWaitIdle() calls from the EndFrame() method if you added them earlier.
If you still encounter issues despite applying these changes, please let me know so I could further investigate the problem.
Initialize the synchronization objects to VK_NULL_HANDLE before creating them. This will help ensure they have a default value and will not cause access violation errors when destroying them.
Update the CreateSyncObjects() method to initialize the synchronization objects to VK_NULL_HANDLE:
cpp
void Renderer::CreateSyncObjects()
{
imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
// ... rest of the code
}
Now, update the CleanupSyncObjects() method to destroy the synchronization objects only if they are not null:
cpp
void Renderer::CleanupSyncObjects()
{
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (renderFinishedSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
if (imageAvailableSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
if (inFlightFences[i] != VK_NULL_HANDLE)
vkDestroyFence(device, inFlightFences[i], nullptr);
}
}
With these changes, you should be able to prevent the access violation error in the CleanupSyncObjects() method.
I apologize for the confusion in my previous responses. The reason you are getting the "Failed to acquire next swapchain image." error is that the vkAcquireNextImageKHR() function is being called twice in the BeginFrame() and EndFrame() methods, leading to incorrect synchronization.
To fix the issue, you should remove the vkAcquireNextImageKHR() function from the EndFrame() method and keep it only in the BeginFrame() method.
Update the BeginFrame() and EndFrame() methods as follows:
cpp
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.
uint32_t imageIndex;
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.");
}
// ... rest of the code
}
void Renderer::EndFrame()
{
// ... vkEndCommandBuffer(currentCommandBuffer) and other code
// Submit the command buffer to the graphics queue
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]);
// Present the rendered frame back to the swapchain
VkPresentInfoKHR presentInfo{};
// ... other configurations for presentInfo
VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo);
// Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes
// You can implement a function like recreateSwapchain() to handle resizing and other changes
if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) {
recreateSwapchain();
}
else if (queuePresentResult != VK_SUCCESS) {
throw std::runtime_error("Failed to present the swapchain image.");
}
currentFrame = (currentFrame + 1) % kMaxFramesInFlight;
}
These adjustments should fix the "Failed to acquire next swapchain image." message and correctly synchronize swapchain image acquisition and presentation.
Additionally, ensure you have the proper cleanup order when shutting down. In the destructor of the Renderer class, you should call Shutdown():
cpp
Renderer::~Renderer()
{
Shutdown();
}
In the Shutdown() method, you should call CleanupSyncObjects() before CleanupFramebuffers() and after CleanupSwapchain(). In this case, the Shutdown() method should look like this: