title: Depth Test in opengl
body: <p>My program refuses to do depth testing. The two sphere objects are always drawn in the order they are created, not according to their position. Sphere alpha is positioned at (0, 0, 1) and Sphere beta is positioned (0, 0, -10), yet OpenGL still draws beta on top of alpha. I set depth test to enabled in my program. </p>
  
  <p>Nothing appears to work. I want OpenGL to do depth test automatically on any objects drawn in the window. Any help or advise would be greatly appreciated. Here is the full code. </p>
  
  <pre><code>#include "GL/freeglut.h"
  #include "GL/gl.h"
  #include "GL/glu.h"
  
  const int SPHERE_RES = 200;   
  double Z_INIT = -28.0;       
  double RADIUS = 2;          
  double Red[3] = {1, 0, 0};   
  double Blue[3] = {0, 0, 1};  
  
  using namespace std;
  
  
  /*
   * Method handles resize of the window
  */ 
  
  void handleResize (int w, int h) {    
  
      glViewport(0, 0, w, h); 
      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      double ratio = (float)w/ (float)h;
      gluPerspective(45.0, ratio, 1.0, 100.0);
  }
  
  
  /*
   * Color and depth is enabled and in this method
  */
  
  void configureColor(void)
  {
  
       glClearColor(1.0f, 1.0f, 1.0f, 0.0f); //Set background to white
       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear window.
       glDepthFunc(GL_ALWAYS);
       glEnable(GL_DEPTH_TEST);
  
       glEnable(GL_COLOR_MATERIAL);        
       glEnable(GL_LIGHTING);
       glEnable(GL_LIGHT0);
  
  }
  
  void display (void) {    
  
       configureColor();
  
       glMatrixMode(GL_MODELVIEW);
       glLoadIdentity();
  
  
       GLfloat sun_direction[] = { 0.0, 0.0, -1.0, 0.0};
       glLightfv(GL_LIGHT0, GL_POSITION, sun_direction);
       GLUquadric* quad =  gluNewQuadric();
  
       //first sphere is drawn
       glColor3f(Red[0], Red[1], Red[2]);
       glPushMatrix();
           glLoadIdentity();
           glTranslatef(0, 0, Z_INIT);
           glTranslatef(0, 0, 1.0);
           gluSphere(quad, RADIUS, SPHERE_RES, SPHERE_RES);
       glPopMatrix();
  
       //second sphere is supposed to be drawn behind it, 
       //but it is drawn on top. 
      glColor3f(Blue[0], Blue[1], Blue[2]);
       glPushMatrix();
           glLoadIdentity();
           glTranslatef(0, 0, Z_INIT);
           glTranslatef(0, 0, -10.0);
           gluSphere(quad, RADIUS, SPHERE_RES, SPHERE_RES);
       glPopMatrix();
  
      free(quad);
       glFlush();
  } 
  
  int main(int argc, char** argv)
  {
  
      glutInit(&amp;argc, argv); //initializes the GLUT
      glutInitDisplayMode(GLUT_SINGLE);
      glutInitWindowSize(600,600);
      glutInitWindowPosition(100,100);
      glutCreateWindow("OpenGL - First window demo");  
      glutReshapeFunc(handleResize);
      glutDisplayFunc(display);
  
      glutMainLoop();    
      return 0;
  }
  </code></pre>
  
  <p>I am using Ubuntu 14.04 operating system.</p>