Consider this class for a 3D model. I can have multiple instances of the class. I am able to add, and remove my 3D models in the scene.
class My3DModel
{
int VertexArrayObject;
int VertexBufferObject;
int ShaderProgram;
int UniformLocationColor;
public My3DModel()
{
VertexArrayObject = GL.GenVertexArray();
VertexBufferObject = GL.GenBuffer();
ShaderProgram = BuildShaders();
UniformLocationColor = GL.GetUniformLocation(ShaderProgram, "uniColor");
}
~My3DModel()
{
// [1] In destructor, I'm deleting the VAO, VBO, and Shader program.
// This is all I'm using, no textures, no extra buffer objects used.
GL.DeleteBuffer(VertexBufferObject);
GL.DeleteVertexArray(VertexArrayObject);
GL.DeleteProgram(ShaderProgram);
}
// Render function, etc. Shaders and rendering work fine
}
How I build my shaders:
int BuildShaders()
{
int iPgm = GL.CreateProgram();
int VertexShader = CreateAndCompileVS();
int FragmentShader = CreateAndCompileFS();
GL.AttachShader(iPgm, VertexShader);
GL.AttachShader(iPgm, FragmentShader);
GL.LinkProgram(iPgm);
// [2] After linking program, we detach the two shaders and delete them
GL.DetachShader(iPgm, VertexShader);
GL.DeleteShader(VertexShader);
GL.DetachShader(iPgm, FragmentShader);
GL.DeleteShader(FragmentShader);
return iPgm;
}
To test for memory leaks, I'm using a loop where I create a new instance of the class, render it, then immediately assign it to null, however my RAM usage goes up. This happens only when doing this, which is what brought me to this conclusion. This may not be a specific case for OpenTK, but I am currently convinced that it is, since I do not get this problem with memory when I strip the class from its Buffer objects and shaders and regularly use its members.
void RenderLoop()
{
My3DModel temp_model = new My3DModel();
// Note that I'm not pushing any data to the vertex buffer, I'm only calling the render func for the sake of it. Despite this, RAM still goes up!
temp_model.Render();
temp_model = null; // Even without doing this, my RAM goes up.
}
What causes this exactly, and what am I missing in the destructor, if there is something I am missing?
I am using OpenTK 3.3.1
, which is the latest supported OpenTK for WinForms using .NET Framework 4.7.2
, and I do not intend to migrate my project to WPF
, for the record.