Contents / Previous / Next


OpenGL Depthbuffer Example Program

Depth Test: For each pixel on the screen, the depth buffer keeps track of the distance between the viewpoint and the object occupying that pixel. Then, if the specified depth test passes, the incoming depth value replaces the one already in the depth buffer.
In this way, only objects that aren't obscured by other items remain after the entire scene has been rendered.

During initialization, the depth buffer is typically filled with a value that's as far from the viewpoint as possible, so any object is nearer than that. If this is how you want to use the depth buffer, you simply have to enable it by passing GL_DEPTH_TEST to glEnable() and remember to clear the depth buffer before you redraw each frame:

  public void init(GLDrawable drawable)
    {
      ...

      gl.glEnable( GL.GL_DEPTH_TEST );
      gl.glDepthFunc(GL.GL_LEQUAL);

      ...
    }

  public void display(GLDrawable drawable)
    {
      ...
      gl.glClear( GL.GL_COLOR_BUFFER_BIT | 
		  GL.GL_DEPTH_BUFFER_BIT );
      ...
    }


You can also choose a different comparison function for the depth test with glDepthFunc():
  void glDepthFunc(GLenum func);
Sets the comparison function for the depth test. The value for func must be GL_NEVER, GL_ALWAYS, GL_LESS, GL_LEQUAL, GL_EQUAL, GL_GEQUAL, GL_GREATER, or GL_NOTEQUAL. An incoming fragment passes the depth test if its z value has the specified relation to the value already stored in the depth buffer. The default is GL_LESS, which means that an incoming fragment passes the test if its z value is less than that already stored in the depth buffer. In this case, the z value represents the distance from the object to the viewpoint, and smaller values mean the corresponding objects are closer to the viewpoint.