Part of the Khronos Group
OpenGL.org

The Industry's Foundation for High Performance Graphics

from games to virtual reality, mobile phones to supercomputers

Results 1 to 3 of 3

Thread: depth test doesn't work?

  1. #1
    Junior Member Newbie
    Join Date
    Dec 2005
    Posts
    2

    depth test doesn't work?

    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;
    }

  2. #2
    Senior Member OpenGL Guru
    Join Date
    Feb 2000
    Location
    Sweden
    Posts
    3,115

    Re: depth test doesn't work?

    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.

  3. #3
    Junior Member Newbie
    Join Date
    Dec 2005
    Posts
    2

    Re: depth test doesn't work?

    It works! A million thanks!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •