PDA

View Full Version : depth test doesn't work?



linsey
12-22-2005, 06:32 AM
OS:WINXP SP2
DEV: Visual Studio .Net 2003

I wrote some code to realize the depth test, which is supposed to draw a near small green rect first and then a further bigger red rect. But it turned out that only the red one which is drew later to be showed on the screen and the green one is totally missed. Here I post my code, thanks for any help!

#include <windows.h>
#include <gl/glut.h>
#include <stdlib.h>

void draw_far()
{

glBegin(GL_POLYGON);
glColor3f (1.0, 0.0, 0.0);
glVertex3f (0.05, 0.40, 0.5);
glVertex3f (0.05, 0.80, 0.5);
glVertex3f (0.25, 0.80, 0.5);
glVertex3f (0.25, 0.40, 0.5);
glEnd();

}

void draw_near()
{

glBegin(GL_POLYGON);
glColor3f (0.0, 1.0, 0.0);
glVertex3f (0.10, 0.50, 0.3);
glVertex3f (0.10, 0.70, 0.3);
glVertex3f (0.15, 0.70, 0.3);
glVertex3f (0.15, 0.50, 0.3);
glEnd();

}

void display(void)
{

glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

draw_near();

draw_far();

glFlush ();
}

void init (void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glClearDepth (1.0);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}

int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_DEPTH | GLUT_RGB);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
glutInitWindowSize (250, 250);
glutInitWindowPosition (100, 100);
glutCreateWindow ("hello");
init ();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Bob
12-22-2005, 09:02 AM
There are two problems with your code.

First. You enable the depth test before creating the window. The rendering context, which is required for any OpenGL function to work, is created when the window is created, which means any gl-call before glutCreateWindow have no effect.

Second. The positive Z-axis is pointing towards you, meaning, unless you changed the view matrices which you don't in this case, larger Z-values are actually closer and should be drawn on top of smaller Z-values. So ignoring the first point, the green square should actually be drawn behind the red square.

linsey
12-22-2005, 05:54 PM
It works! A million thanks!