OpenGL 3.0 Square is being drawn behind another Square
-
Im writing a paint program in openGL 3.0, it works fine so far except that when I try and draw a square over another square it is drawn behind it instead of on top of it. How can I fix this so that I can draw on top of an image? Why would this happen?
C++ OpenGL3.0
-
Im writing a paint program in openGL 3.0, it works fine so far except that when I try and draw a square over another square it is drawn behind it instead of on top of it. How can I fix this so that I can draw on top of an image? Why would this happen?
C++ OpenGL3.0
Enable Depth test to draw objects beyond others. glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LESS ); // Near objects will be displayed. object with z -3 displayed on top of object with z -4 If you are creating an app similar to MSPAINT, setup projection matrix with glOrtho(). glOrtho() is used because it creates an orthographic projection, therefore the size of rendered image of same size with different z value will be same. Provide different z values for each objects, based on their z order in the screen. ie, z value of the object drawn at first should be as small, say 1. Then increase z value of each new objects. Render code should be like this.
// set depth range and clear depth value.
glDepthRange(-100, 100);
glClearDepth(100);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);// Set projection.
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho(-20,20,-20,20,0, 100 );glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LESS );// No model view transformation.
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();// Draw object 1
glColor3f(0,0,1);
glBegin( GL_TRIANGLES );
glVertex3f( 0,0, -3 );
glVertex3f( 1,1, -3 );
glVertex3f( 0,1, -3 );
glEnd();// Draw Object 2. Here z is -2, it will be displayed on top of object -3
glColor3f(1,0,0);
glBegin( GL_TRIANGLES );
glVertex3f( 0,1, -2 );
glVertex3f( 1,1, -2 );
glVertex3f( 1,0, -2 );
glEnd();SwapBuffers( m_hDC );