/* display_list.c */

#include <GL/glut.h>

GLfloat angle1 = 0;
GLfloat angle2 = 0;

GLuint list;

static void
init (void)
{
  /* We want to fill the color buffer with black */
  glClearColor (0, 0, 0, 0);

  /* Set the projection matrix once for all... */
  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();
  glOrtho (-1,1, -1,1, -1,1);
  glEnable (GL_DEPTH_TEST);
  list = glGenLists (1);
  glNewList (list, GL_COMPILE);
    glBegin (GL_QUADS);
      /* A red quad */
      glColor3f (1, 0, 0);
      glVertex3f (-0.5f, -0.5f, 0.5f); glVertex3f ( 0.5f, -0.5f, 0.5f);
      glVertex3f ( 0.5f,  0.5f, 0.5f); glVertex3f (-0.5f,  0.5f, 0.5f);
      /* A light blue quad */
      glColor3f (0, 1, 1);
      glVertex3f (-0.5f, -0.5f, -0.5f); glVertex3f ( 0.5f, -0.5f, -0.5f);
      glVertex3f ( 0.5f,  0.5f, -0.5f); glVertex3f (-0.5f,  0.5f, -0.5f);
      /* A green quad */
      glColor3f (0, 1, 0);
      glVertex3f (-0.5f, -0.5f,-0.5f); glVertex3f (-0.5f, -0.5f, 0.5f);
      glVertex3f ( 0.5f, -0.5f, 0.5f); glVertex3f ( 0.5f, -0.5f,-0.5f);
      /* A purple quad */
      glColor3f (1, 0, 1);
      glVertex3f (-0.5f,  0.5f, -0.5f); glVertex3f (-0.5f,  0.5f,  0.5f);
      glVertex3f ( 0.5f,  0.5f,  0.5f); glVertex3f ( 0.5f,  0.5f, -0.5f);
      /* A blue quad */
      glColor3f (0, 0, 1);
      glVertex3f (-0.5f, -0.5f,-0.5f); glVertex3f (-0.5f, -0.5f, 0.5f);
      glVertex3f (-0.5f,  0.5f, 0.5f); glVertex3f (-0.5f,  0.5f,-0.5f);
      /* A yellow quad */
      glColor3f (1, 1, 0);
      glVertex3f ( 0.5f, -0.5f, -0.5f); glVertex3f ( 0.5f, -0.5f,  0.5f);
      glVertex3f ( 0.5f,  0.5f,  0.5f); glVertex3f ( 0.5f,  0.5f, -0.5f);
    glEnd ();
  glEndList ();

}

static void
display_callback (void)
{
  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  /* The modelview matrix is only used here to rotate the cube */
  glMatrixMode (GL_MODELVIEW);
  glLoadIdentity ();
  glRotatef (angle1, 0,1,0);
  glRotatef (angle2, 1,0,0);

  glCallList (list);

  glutSwapBuffers ();
}

static void
special_callback (int key, int x, int y)
{
  /* use the left and right arrow keys to rotate the quads around the y axis */
  switch (key)
    {
    case GLUT_KEY_RIGHT:
      angle1 += 5.f;
      break;
    case GLUT_KEY_LEFT:
      angle1 -= 5.f;
      break;
    case GLUT_KEY_UP:
      angle2 += 5.f;
      break;
    case GLUT_KEY_DOWN:
      angle2 -= 5.f;
      break;
    }

  /* We need to be redisplayed */
  glutPostRedisplay ();
}

int
main(int argc, char** argv)
{
  glutInit (&argc, argv);
  glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
  glutInitWindowSize (250, 250);
  glutInitWindowPosition (100, 100);
  glutCreateWindow ("Flat Cube");
  init ();
  glutDisplayFunc (display_callback);
  glutSpecialFunc (special_callback);

  glutMainLoop ();

  return 0;
}

