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.
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
Assistant
The error you're encountering is because the VkDescriptorSetLayout objects were not destroyed before destroying the VkDevice, and this violates the Vulkan Specification.
In the code, the Descriptor Set Layouts are created inside the Material object, and it's the Material's responsibility to destroy them in their Cleanup() function. However, the Material's Cleanup() function is not being called before the device gets destroyed.
A possible solution is to ensure that the Material's Cleanup() function is called before destroying your device. You can do this by adding the following line to the Renderer::CleanupDevice() function, right before the line pipeline.reset();:
if (material) {
material->Cleanup();
}
Please make sure to declare a member variable inside your class and initialize it to . Then, modify your function to set this member variable:
User
I have checked using breakpoints during debug mode and I can confirm that the descriptor sets in Material are being destroyed before the command to destroy the device is run. Could there be some other descriptor sets that aren't being managed correctly, or perhaps the Material Cleanup method isn't working as intended?
Assistant
Based on your description, I see that you confirmed the descriptor sets in Material are being destroyed before trying to destroy the device. In that case, it might be another descriptor set layout that is not being managed correctly.
User
I'm getting an error for instanceEnabledLayers. This variable has not been declared. Where should it be declared and does it need to be initalized?
Assistant
My apologies for the confusion, I overlooked that part. instanceEnabledLayers should be a member variable of your Renderer class that stores the enabled layer names for your instance.
In your Renderer.h, include it as a member variable.
std::vector<const char*> instanceEnabledLayers;
In Renderer.cpp, when you create your instance, you will initialize this variable with the enabled validation layers:
// List of validation layers
const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation"
};
// Function to check if all requested validation layers are supported by the Vulkan implementation
bool checkValidationLayerSupport(const std::vector<const char*>& requestedLayers) {
uint32_t availableLayerCount;
vkEnumerateInstanceLayerProperties(&availableLayerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(availableLayerCount);
vkEnumerateInstanceLayerProperties(&availableLayerCount, availableLayers.data());
for (const char* requestedLayer : requestedLayers) {
bool layerFound = false;
for (const auto& availableLayer : availableLayers) {
if (strcmp(requestedLayer, availableLayer.layerName) == 0) {
layerFound = true;
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include
#include // Don’t forget to include
#include
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
This should allow the descriptor set layouts to be cleaned up before the VkDevice is destroyed and resolve the error.
Please let me know if you have any other questions.
To debug this further, a practical way is to add names (also known as debug names or debug markers) to your Vulkan objects. This will make it easier to identify which objects are not being destroyed correctly when the validation layers throw an error.
To do this, you can use the following utility function to set names for your Vulkan resources:
// Utility function to set object names in Renderer class
void Renderer::setObjectName(uint64_t objectHandle, VkObjectType objectType, const std::string& name)
{
if (!instanceEnabledLayers.empty())
{
VkDebugUtilsObjectNameInfoEXT nameInfo = {};
nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
nameInfo.pNext = nullptr;
nameInfo.objectType = objectType;
nameInfo.objectHandle = objectHandle;
nameInfo.pObjectName = name.c_str();
auto func = (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(instance, "vkSetDebugUtilsObjectNameEXT");
if (func != nullptr) {
if (func(device, &nameInfo) != VK_SUCCESS) {
throw std::runtime_error("Could not set object name.");
}
}
}
}
Now, in your Renderer::CreateDescriptorSetLayout and Renderer::CreateSamplerDescriptorSetLayout functions, you can add a line to set the object names right after creating the descriptor set layout:
_vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout);
setObjectName((uint64_t)descriptorSetLayout, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, "My Descriptor Set Layout");
Adjust the name string such as "My Sampler Descriptor Set Layout" for the sampler descriptor set layout.
Once you've added names to your Vulkan descriptor set layouts, you can recompile your program and run it. The validation layer errors should now show more helpful information in the last line of the error message, including the name you set.
With this detailed information about the potentially leaked descriptor set layouts, you will be able to debug more effectively and identify which layout is not being managed correctly or where the issue is.