OpenGL depth test not working as expected
I have a simple program to use depth test. It is not working as expected. The program draws X, Y axis and a sphere near the origin. If I don't turn on the GL_DEPTH_TEST, the sphere is drawn over the axis. If I turn on the GL_DEPTH_TEST, the axis are drawn over the sphere which I was not expecting. Can someone tell me what I did wrong ?
void
glwid::initializeGL()
{
glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
}
void
glwid::resizeGL(int width, int height)
{
glViewport( 0, 0, (GLint)width, (GLint)height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective ( 90, (GLint)width/ (GLint)height, 0.0, 200.0 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity()开发者_运维知识库;
glEnable (GL_DEPTH_TEST);
}
void
glwid::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity();
gluLookAt (0, 0, 100, 0, 0, 0, 0, 1, 0);
//
// X axis
//
glBegin( GL_LINES );
qglColor( green );
glVertex3f (-100.0, 0, 0. );
glVertex3f (100.0, 0, 0. );
glEnd();
//
// Y axis
//
glBegin( GL_LINES );
qglColor( red );
glVertex3f (0.0, 100.0, 0. );
glVertex3f (0.0, -100, 0. );
glEnd();
//
// sun
//
glTranslated (5, 0, 20);
GLUquadricObj *sphere_quadric = gluNewQuadric();
glColor3ub (255, 255, 0);
gluQuadricDrawStyle(sphere_quadric, (GLenum)GLU_SMOOTH);
gluSphere(sphere_quadric, 10, 36, 36);
}
I've tried your code. The problem is in resizeGL()
function.
The problem was your putting to
gluPerspective ( 90, (GLint)width/ (GLint)height, 0.0, 200.0 );
0.0 value as a third argument. Put 0.01 for example - and everything will be ok. that's because this parameter should always be positive: http://www.opengl.org/sdk/docs/man/xhtml/gluPerspective.xml
Also change (GLint)width/ (GLint)height
to (GLfloat)width/ (GLfloat)height
otherwise the result will be strange.
And it's better to put glEnable(GL_DEPTH_TEST)
into initializeGL()
function
Your axis starts at Z location 0. The Sphere is at Z location 20 (farther away from the "camera") therefore the axis is in-front of the sphere and is being shown.
As you currently have it setup, as Z values go up they move away from the screen. As they go down, they are going closer to the screen.
You have two options: Disable depth testing while drawing your axis (therefore it will always be behind everything). Or move your axis to Z position 100 or so and scale it up to make it look the same size. Option one is probably better.
Simply wrapping your axis drawing routines in glDisable(GL_DEPTH_TEST);
and glEnable (GL_DEPTH_TEST);
should do the trick
精彩评论