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.
As a start, this engine will render a basic spinning box with uniform color. However, it will then expand to cover the full functionality of the game engine.
I have written the basic code for the engine and it is compiling correctly. I want to verify that there are not noticeable errors in the code or anything that is missing. 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.
For the most part, your code structure and class organization look good. However, there are few improvements and suggestions you can consider:
User
Assistant
Overall, the Renderer.cpp implementation looks good and should function as intended. There are a couple of suggestions and improvements you can consider:
You might want to refactor the code to create separate functions for each Vulkan object's creation, if not already done so in the elided parts (e.g., CreateSwapchain() seems to include image views creation). This will improve the code readability and maintainability in the long run.
In the EndFrame() function, you should handle the case where the swapchain recreation is required (e.g., due to window resizing). As already pointed out by the comment, you can call a function to recreate the swapchain and its dependent objects, like framebuffers, command buffers, etc., when VK_ERROR_OUT_OF_DATE_KHR or VK_SUBOPTIMAL_KHR is returned.
Error handling should be consistent across all functions. For instance, in the CreateCommandPool() function, you are not checking the return value of vkCreateCommandPool, which might result in issues if the function call fails.
private:
static void FramebufferResizeCallback(GLFWwindow* window, int width, int height);
code
int width;
int height;
const char* title;
GLFWwindow* window;
double lastFrameTime;
};
Is there anything that is missing or might need to be changed?
In Renderer.h, create a VulkanDeleter so that you don't have to manually call the cleanup functions for each Vulkan object in Renderer::Shutdown. This would make your code more maintainable and less prone to human error. You can use std::unique_ptr with a custom deleter for this purpose.
In the Initialize() functions of the classes, consider adding proper error handling or checks to ensure that they haven't been called before, and the object is in a correct state to be initialized.
Make sure to include proper error handling and checks throughout your code, especially in your Vulkan functions. Vulkan can provide a lot of error codes that can be helpful for diagnosing issues, so make sure you check and handle them appropriately.
In Texture.h, you are using VkPhysicalDevice, VkCommandPool, and VkQueue only in the LoadFromFile() function. Consider passing them as arguments instead of storing them as member variables.
You seem to have mesh and material objects as part of the GameObject class. Depending on your requirements and how you handle resource management, you might want to have external resource managers that handle the meshes and materials and have the GameObject store references or IDs instead. This would allow better resource sharing between multiple game objects and improve memory usage.
In Engine.h, since you are using a singleton pattern, ensure that you either prevent the copy constructor and copy assignment operator to avoid multiple instances of Engine, or you make them private.
Depending on the scope of your engine and game requirements, you may need to add more functionality to handle events, input mapping, or more advanced scene-management features like grouping, parenting, or hierarchical culling.
Consider making full use of RAII, and make sure you are cleaning up all your resources in your destructors. For example, some of your header files don't include destructors, while others contain a Shutdown function. Be consistent with your methods for cleaning up resources.
Keep in mind that as you continue to develop and refine your engine, you may encounter additional requirements, optimizations, or further improvements that can be made to the codebase.
Here is the code for Renderer.cpp. Are there any errors, missing components or obvious improvements that could be made?
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::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);
}
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const auto& queueFamily : queueFamilies)
{
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
indices.graphicsFamily = i;
}
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport);
if (presentSupport)
{
indices.presentFamily = i;
}
if (indices.IsComplete())
{
break;
}
i++;
}
return indices;
}
In the CleanupSwapchain() function, there is a comment "// Clean up Vulkan swapchain" but no code is provided that performs the cleanup. Be sure to add the appropriate cleanup code for the swapchain (e.g., vkDestroySwapchainKHR) and its dependent objects, like image views.
Make sure to re-evaluate your error handling and checks throughout your code, especially during the Vulkan initialization and creation steps. Be consistent and make