Search code examples
c#opengl2dopentkdepth-buffer

OpenTK vertices seem to always write to 0 in depth buffer


So I have a 2D game engine I was working on adding a depth buffer to so I could draw stuff behind and in front of each other at will. I asked my GameWindow to create a depth buffer on initialization, enabled depth testing, changed the depthFunction to DepthFunction.Less, set the DepthMask to true, set the DepthRange to 0.0-1.0, and changed all my GL.Vector2 calls to GL.Vector3 calls with the z being the depth I want it to draw at. However whenever I draw anything it seems to draw at a depth of 0 regardless of the z value I pass to GL.Vector3. I have three rectangles being draw on top of each other with slightly difference offsets. The red is at 0 depth, blue is at 1 depth, and the purple is at 0.5f depth, they are being drawn in that order (red-blue-purple), and it looks like image1. However if I change the DepthFunc to DepthFunction.Lequal I get the result in image2. Is there something I need to set when drawing my vertices to define their depth besides just the z-value of the vertex? Also I have an orthographic matrix setup with this code:

GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(-window.ClientSize.Width / 2f, window.ClientSize.Width / 2f,
window.ClientSize.Height / 2f, -window.ClientSize.Height / 2f, 0.0f, 1.0);

Does That have anything to do with it?

image1: https://i.sstatic.net/bqUT0.png image2: https://i.sstatic.net/EUaMk.png


Solution

  • Alright so after hours of debugging I seem to have gotten it to work. For future reference I think what I did to fix it was move my GL.DepthFunc() and GL.DepthMask() calls to right after I call GL.ClearDepth() in my draw function rather than where I had them in the initialize function next to GL.Enable(EnableCap.DepthTest) and GL.DepthRange(0.1f, 1.0f). Hope this helps someone in the future.