Im learning opengl and wrote a simple program that uses buffer object(colors,positions, normals, element indices) to draw a shape like below. Even with the deleting and unbinding, GPU monitor program shows increasing memory usage after each button click. Memory is only released when I close app. If I click button many times, GPU ram fills to 2GB and starts spilling to host ram. How can I release the resources/buffers properly?
Program flow is like:
When I click a button, the below program is executed:
glControl1.MakeCurrent();
GL.GenBuffers(4,buf)
GL.BindBuffer(BufferTarget.ArrayBuffer,buf[0])
GL.BufferData(BufferTarget.ArrayBuffer,......)
same for buf[1] buf[2] and buf[3](this one ElementArrayBuffer)
Console.WriteLine(GL.GetError()); // no error
GL.Finish();
[iteration loop]
glControl1.MakeCurrent();
GL.BindBuffer(BufferTarget.ArrayBuffer,buf[0])
GL.ColorBuffer(....)
GL.BindBuffer(BufferTarget.ArrayBuffer,buf[1])
GL.VertexBuffer(....)
GL.BindBuffer(BufferTarget.ArrayBuffer,buf[2])
GL.NormalBuffer(....)
GL.BindBuffer(BufferTarget.ElementArrayBuffer,buf[3])
GL.EnableClientStates(.....)
GL.DrawElements(.....) //draws the thing
GL.DisableClientStates(.....)
GL.BindBuffer(BufferTarget.ElementArrayBuffer,0) //is this unbinding?
GL.BindBuffer(BufferTarget.ArrayBuffer,0)
GL.BindBuffer(BufferTarget.ArrayBuffer,0)
GL.BindBuffer(BufferTarget.ArrayBuffer,0)
GL.Finish();
[loop end]
//deleting buffers
glControl1.MakeCurrent()
GL.DeleteBuffers(4,buf)
Console.WriteLine(GL.GetError()); // no error comes
GL.Finish();
As far as I can tell, you're generating and populating a new buffer when you click, and not deleting them. At the end you only delete the 4 buffers you created LAST.
When you call glGenBuffers
it simply generates a new buffer and returns the handle, it does not detect whether a given handle is already in use or something similar. Thus when you give the same handles as you used before, it generates new handles, overwrites the ones you're currently keeping track off, effectively removing any reference to the old buffers. But it does not deallocate those buffers. Thus you continuously populate more memory.
Now, if you want to simply write new data to already existing buffers, you would simply call glBufferSubData
. If you want to resize the buffer as well, you call glBufferData
, which deletes previous data. But you don't have to generate new buffers, as you already have handles to buffers.