OpenGL depth buffer isn't working

Tag: opengl , buffer , depth Author: greme Date: 2013-01-14

I am attempting to make a simple drawing using openGL. However, the depth buffer doesn't appear to be working.

Other people with a similar problem are typically doing one of two things wrong:

  1. Not including glEnable(GL_DEPTH_TEST)

  2. Bad clipping values

However, my code does not have either of these problems.

...
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

gluPerspective(25.0,1.0,10.0,200.0);

// Set the camera location
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(20.0, 10.0, 50.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

// Enable depth test
glEnable(GL_DEPTH_TEST);

// Cull backfacing polygons
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE)

drawCoordinateAxis();

drawBox(5.0,2.0,5.0,0.8,0.0,0.0);

glTranslated(1.0,-1.0,1.0); //The box is 5x2x5, it is shifted 1 unit down and 1 in the x and z directions
drawBox(5.0,2.0,5.0,0.0,1.0,1.0);
...

When I execute my code, this is drawn. http://imgur.com/G9y41O1

Note that the blue box and the red box collide, so the red box should be covering part of the blue box.

The functions drawCoordinateAxis() and drawBox() just draw a few primitives, nothing fancy inside.

I am running this on Debian squeeze.

Do you request a depth buffer when you create your GL context?

Other Answer1

void reshape(GLint width, GLint height)
{
   g_Width = width;
   g_Height = height;
   glViewport(0, 0, g_Width, g_Height);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   gluPerspective(65.0, (float)g_Width / g_Height, g_nearPlane, g_farPlane);
   glMatrixMode(GL_MODELVIEW);
}

So set Matrix Mode to GL_PROJECTION first, then gluPerspective.... and then back to MODELVIEW mode.

comments:

This code is better placed in the display functions. As soon as you want a HUD or other kinds of indicators you must adjust the viewport and projection within the rendering process anyway. The reshape handler should be reserved to costly operations happening when resizing the window, like recreation of post-processing FBO attachments.