/* Cube et cylindre modelises par facettes      */
/*                                              */
/* Auteur: Nicolas JANEY                        */
/* nicolas.janey@univ-fcomte.fr                 */
/* Janvier 2017                                 */

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>

/* Variables et constantes globales             */
/* pour les angles et les couleurs utilises     */

#ifndef M_PI
#define M_PI 3.14159
#endif

static int obj = 0;
static float rx = 0.0F;
static float ry = 0.0F;
static float rz = 0.0F;
static const float noir[] = { 0.0F,0.0F,0.0F,1.0F };
static const float blanc[] = { 1.0F,1.0F,1.0F,1.0F };
static const float gris[] = { 0.7F,0.7F,0.7F,1.0F };
static const float jaune[] = { 1.0F,1.0F,0.0F,1.0F };
static const float rouge[] = { 1.0F,0.0F,0.0F,1.0F };
static const float vert[] = { 0.0F,1.0F,0.0F,1.0F };
static const float bleu[] = { 0.0F,0.0F,1.0F,1.0F };
static int n = 36;
static int m = 12;

/* Fonction d'initialisation des parametres     */
/* OpenGL ne changeant pas au cours de la vie   */
/* du programme                                 */

static void init(void) {
  const GLfloat shininess[] = { 50.0 };
  glMaterialfv(GL_FRONT,GL_AMBIENT,noir);
  glMaterialfv(GL_FRONT,GL_DIFFUSE,blanc);
  glMaterialfv(GL_FRONT,GL_SPECULAR,blanc);
  glMaterialfv(GL_FRONT,GL_SHININESS,shininess);
  glLightfv(GL_LIGHT0,GL_DIFFUSE,rouge);
  glLightfv(GL_LIGHT1,GL_DIFFUSE,jaune);
  glLightfv(GL_LIGHT2,GL_DIFFUSE,bleu);
  glEnable(GL_LIGHT0);
  glEnable(GL_LIGHT1);
  glEnable(GL_LIGHT2);
  glDepthFunc(GL_LESS);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_NORMALIZE);
  glEnable(GL_AUTO_NORMAL);
  glEnable(GL_LIGHTING);
}

//////////////////////////////////////////////////

/* Scenes dessinees                             */

static void mySolidCubeSansNormales(double ct) {
  float c =(float) ct/2.0F;
  glPushMatrix();
  glBegin(GL_QUADS);
  { glVertex3f(-c, c,-c);
    glVertex3f(-c,-c,-c);
    glVertex3f( c,-c,-c);
    glVertex3f( c, c,-c); }
  { glVertex3f( c, c, c);
    glVertex3f(-c, c, c);
    glVertex3f(-c,-c, c);
    glVertex3f( c,-c, c); }
  { glVertex3f(-c, c,-c);
    glVertex3f(-c,-c,-c);
    glVertex3f(-c,-c, c);
    glVertex3f(-c, c, c); }
  { glVertex3f( c, c, c);
    glVertex3f( c,-c, c);
    glVertex3f( c,-c,-c);
    glVertex3f( c, c,-c); }
  { glVertex3f(-c,-c, c);
    glVertex3f(-c,-c,-c);
    glVertex3f( c,-c,-c);
    glVertex3f( c,-c, c); }
  { glVertex3f( c, c, c);
    glVertex3f( c, c,-c);
    glVertex3f(-c, c,-c);
    glVertex3f(-c, c, c); }
  glEnd();
  glPopMatrix();
}

static void mySolidCubeAvecNormales(double ct) {
  float c =(float) ct/2.0F;
  /* Protection contre la modification de la normale */
  /* et du flag normalisation                        */
  GLboolean nm = glIsEnabled(GL_NORMALIZE);
  if ( !nm )
    glEnable(GL_NORMALIZE);
  float normale[4];
  glGetFloatv(GL_CURRENT_NORMAL,normale);
  /* Modelisation geometrique */
  glPushMatrix();
  glBegin(GL_QUADS);
  { glNormal3f(0.0F,0.0F,-1.0F);
    glTexCoord2f(0.0F,0.0F);
    glVertex3f( c, c,-c);
    glTexCoord2f(0.0F,1.0F);
    glVertex3f( c,-c,-c);
    glTexCoord2f(1.0F,1.0F);
    glVertex3f(-c,-c,-c);
    glTexCoord2f(1.0F,0.0F);
    glVertex3f(-c, c,-c); }
  { glNormal3f(0.0F,0.0F,1.0F);
    glTexCoord2f(0.0F,0.0F);
    glVertex3f( c, c, c);
    glTexCoord2f(0.0F,1.0F);
    glVertex3f(-c, c, c);
    glTexCoord2f(1.0F,1.0F);
    glVertex3f(-c,-c, c);
    glTexCoord2f(1.0F,0.0F);
    glVertex3f( c,-c, c); }
  { glNormal3f(-1.0F,0.0F,0.0F);
    glTexCoord2f(0.0F,0.0F);
    glVertex3f(-c, c,-c);
    glTexCoord2f(0.0F,1.0F);
    glVertex3f(-c,-c,-c);
    glTexCoord2f(1.0F,1.0F);
    glVertex3f(-c,-c, c);
    glTexCoord2f(1.0F,0.0F);
    glVertex3f(-c, c, c); }
  { glNormal3f(1.0F,0.0F,0.0F);
    glTexCoord2f(0.0F,0.0F);
    glVertex3f( c, c, c);
    glTexCoord2f(0.0F,1.0F);
    glVertex3f( c,-c, c);
    glTexCoord2f(1.0F,1.0F);
    glVertex3f( c,-c,-c);
    glTexCoord2f(1.0F,0.0F);
    glVertex3f( c, c,-c); }
  { glNormal3f(0.0F,-1.0F,0.0F);
    glTexCoord2f(0.0F,0.0F);
    glVertex3f(-c,-c, c);
    glTexCoord2f(0.0F,1.0F);
    glVertex3f(-c,-c,-c);
    glTexCoord2f(1.0F,1.0F);
    glVertex3f( c,-c,-c);
    glTexCoord2f(1.0F,0.0F);
    glVertex3f( c,-c, c); }
  { glNormal3f(0.0F,1.0F,0.0F);
    glTexCoord2f(0.0F,0.0F);
    glVertex3f( c, c, c);
    glTexCoord2f(0.0F,1.0F);
    glVertex3f( c, c,-c);
    glTexCoord2f(1.0F,1.0F);
    glVertex3f(-c, c,-c);
    glTexCoord2f(1.0F,0.0F);
    glVertex3f(-c, c, c); }
  glEnd();
  glPopMatrix();
  /* Restoration de la normale et du flag normalisation */
  glNormal3f(normale[0],normale[1],normale[2]);
  if ( !nm )
    glDisable(GL_NORMALIZE);
}

static void mySolidCylindre(double hauteur,double rayon,int ns) {
  /* Protection contre la modification de la normale */
  /* et du flag normalisation                        */
  GLboolean nm = glIsEnabled(GL_NORMALIZE);
  if ( !nm )
    glEnable(GL_NORMALIZE);
  float normale[4];
  glGetFloatv(GL_CURRENT_NORMAL,normale);
  /* Modelisation geometrique */
  glPushMatrix();
  hauteur /= 2.0F;
  glBegin(GL_QUAD_STRIP);
  for( int i = 0 ; i <= ns ; i++ ){
    float a = (2*M_PI*i)/ns;
    float cs = cos(a);
    float sn = -sin(a);
    glNormal3f(cs,0.0F,sn);
    float x = rayon*cs;
    float z = rayon*sn;
    glVertex3f(x,hauteur,z);
    glVertex3f(x,-hauteur,z); }
  glEnd();
  glPopMatrix();
  /* Restoration de la normale et du flag normalisation */
  glNormal3f(normale[0],normale[1],normale[2]);
  if ( !nm )
    glDisable(GL_NORMALIZE);
}

static void mySolidCylindre(double hauteur,double rayon,int ns,int nl) {
  GLboolean nm = glIsEnabled(GL_NORMALIZE);
  if ( !nm )
    glEnable(GL_NORMALIZE);
  float normale[4];
  glGetFloatv(GL_CURRENT_NORMAL,normale);
  glPushMatrix();
  for ( int j = 0 ; j < nl ; j++ ) {
    float hi = hauteur/2-j*hauteur/nl;
    float hf = hi-hauteur/nl;
    glBegin(GL_QUAD_STRIP);
    for( int i = 0 ; i <= ns ; i++ ) {
      float a = (2*M_PI*i)/ns;
      float cs = cos(a);
      float sn = -sin(a);
      glNormal3f(cs,0.0F,sn);
      float x = rayon*cs;
      float z = rayon*sn;
      glVertex3f(x,hi,z);
      glVertex3f(x,hf,z); }
    glEnd(); }
  glPopMatrix();
  glNormal3f(normale[0],normale[1],normale[2]);
  if ( !nm )
    glDisable(GL_NORMALIZE);
}

static void mySolidCylindre(double hauteur,double rayon,int ns,int nl,int bases) {
  GLboolean nm = glIsEnabled(GL_NORMALIZE);
  if ( !nm )
    glEnable(GL_NORMALIZE);
  float normale[4];
  glGetFloatv(GL_CURRENT_NORMAL,normale);
  glPushMatrix();
  for ( int j = 0 ; j < nl ; j++ ) {
    float hi = hauteur/2-j*hauteur/nl;
    float hf = hi-hauteur/nl;
    glBegin(GL_QUAD_STRIP);
    for( int i = 0 ; i <= ns ; i++ ) {
      float a = (2*M_PI*i)/ns;
      float cs = cos(a);
      float sn = -sin(a);
      glNormal3f(cs,0.0F,sn);
      float x = rayon*cs;
      float z = rayon*sn;
      glVertex3f(x,hi,z);
      glVertex3f(x,hf,z); }
    glEnd(); }
  if ( bases ) {
    glBegin(GL_POLYGON);
    glNormal3f(0.0F,1.0F,0.0F);
    for( int i = 0 ; i < ns ; i++ ) {
      float a = (2*M_PI*i)/ns;
      float cs = cos(a);
      float sn = -sin(a);
      float x = rayon*cs;
      float z = rayon*sn;
      glVertex3f(x,hauteur/2.0F,z); }
    glEnd();
    glBegin(GL_POLYGON);
    glNormal3f(0.0F,-1.0F,0.0F);
    for( int i = 0 ; i < ns ; i++ ) {
      float a = (2*M_PI*i)/ns;
      float cs = cos(a);
      float sn = sin(a);
      float x = rayon*cs;
      float z = rayon*sn;
      glVertex3f(x,-hauteur/2.0F,z); }
    glEnd(); }
  glPopMatrix();
  glNormal3f(normale[0],normale[1],normale[2]);
  if ( !nm )
    glDisable(GL_NORMALIZE);
}

//////////////////////////////////////////////////

static void scene() {
  glPushMatrix();
  switch ( obj ) {
    case 0 :
      mySolidCubeAvecNormales(1.0F);
      break;
    case 1 :
      mySolidCubeSansNormales(1.0F);
      break;
    case 2 :
      mySolidCylindre(1.0F,0.5F,n);
      break;
    case 3 :
      mySolidCylindre(1.0F,0.5F,n,m);
      break;
    case 4 :
      mySolidCylindre(1.0F,0.5F,n,m,1);
      break; }
  glPopMatrix();
}

/* Fonction executee lors d'un rafraichissement */
/* de la fenetre de dessin                      */

static void display(void) {
  glClearColor(0.75F,0.75F,0.75F,1.0F);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glPushMatrix();
  glRotatef(rx,1.0F,0.0F,0.0F);
  glRotatef(ry,0.0F,1.0F,0.0F);
  glRotatef(rz,0.0F,0.0F,1.0F);
  if ( obj >= 2 ) {
    const GLfloat light0_pos[] = {  0.5F, 0.7F, 0.5F, 1.0F };
    const GLfloat light1_pos[] = { -0.5F, 0.0F, 0.5F, 1.0F };
    const GLfloat light2_pos[] = {  0.5F,-0.7F,-0.5F, 1.0F };
    glLightfv(GL_LIGHT0,GL_POSITION,light0_pos);
    glLightfv(GL_LIGHT1,GL_POSITION,light1_pos);
    glLightfv(GL_LIGHT2,GL_POSITION,light2_pos);
    glDisable(GL_LIGHTING);
    glPushMatrix();
    glTranslatef(light0_pos[0],light0_pos[1],light0_pos[2]);
    glColor3fv(rouge);
    glutSolidSphere(0.02,36,36);
    glPopMatrix();
    glPushMatrix();
    glTranslatef(light1_pos[0],light1_pos[1],light1_pos[2]);
    glColor3fv(jaune);
    glutSolidSphere(0.02,36,36);
    glPopMatrix();
    glPushMatrix();
    glTranslatef(light2_pos[0],light2_pos[1],light2_pos[2]);
    glColor3fv(bleu);
    glutSolidSphere(0.02,36,36);
    glPopMatrix();
    glEnable(GL_LIGHTING); }
    else {
    const GLfloat light0_dir[] = {  0.7F, 0.3F, 0.7F,0.0F };
    const GLfloat light1_dir[] = { -0.7F, 0.0F, 0.7F,0.0F };
    const GLfloat light2_dir[] = {  0.7F,-0.3F,-0.7F,0.0F };
    glLightfv(GL_LIGHT0,GL_POSITION,light0_dir);
    glLightfv(GL_LIGHT1,GL_POSITION,light1_dir);
    glLightfv(GL_LIGHT2,GL_POSITION,light2_dir); }
  scene();
  glPopMatrix();
  glFlush();
  glutSwapBuffers();
  int error = glGetError();
  if ( error != GL_NO_ERROR )
    printf("Erreur OpenGL: %d\n",error);
}

/* Fonction executee lorsqu'aucun evenement     */
/* n'est en file d'attente                      */

static void idle(void) {
  rx += 0.14256F ;
  ry += 0.06117F ;
  rz += 0.04174F ;
  glutPostRedisplay() ;
}

/* Fonction executee lors d'un changement       */
/* de la taille de la fenetre OpenGL            */

static void reshape(int x,int y) {
  glViewport(0,0,x,y); 
  glMatrixMode(GL_PROJECTION) ;
  glLoadIdentity() ;
  gluPerspective(7.0F,(float) x/y,1.0,40.0) ;
  glMatrixMode(GL_MODELVIEW) ;
  glLoadIdentity() ;
  gluLookAt(0.0,0.0,20.0,0.0,0.0,0.0,0.0,1.0,0.0);
}

/* Fonction executee lors de l'appui            */
/* d'une touche alphanumerique du clavier       */

static void keyboard(unsigned char key,int x,int y) {
  switch (key) {
    case 'n' :
      n--;
      if ( n < 3 )
        n = 3;
      glutPostRedisplay();
      break;
    case 'N' :
      n++;
      glutPostRedisplay();
      break;
    case 'm' :
      m--;
      if ( m < 1 )
        m = 1;
      glutPostRedisplay();
      break;
    case 'M' :
      m++;
      glutPostRedisplay();
      break;
    case 'l' :
      { static int lumiere = 0;
        lumiere = !lumiere;
        if ( lumiere ) {
          glLightfv(GL_LIGHT0,GL_DIFFUSE,gris);
          glLightfv(GL_LIGHT1,GL_DIFFUSE,gris);
          glLightfv(GL_LIGHT2,GL_DIFFUSE,gris); }
          else {
          glLightfv(GL_LIGHT0,GL_DIFFUSE,rouge);
          glLightfv(GL_LIGHT1,GL_DIFFUSE,jaune);
          glLightfv(GL_LIGHT2,GL_DIFFUSE,bleu); } }
      glutPostRedisplay();
      break;
    case 'c' :
      { static int culling = 0;
        culling = !culling;
        if ( culling )
          glEnable(GL_CULL_FACE);
          else
          glDisable(GL_CULL_FACE); }
      glutPostRedisplay();
      break;
    case 'f' :
      { static int face = 1;
        face = !face;
        glPolygonMode(GL_FRONT_AND_BACK,( face ) ? GL_FILL : GL_LINE); }
      glutPostRedisplay();
      break;
    case 0x20 :
      obj = (obj+1)%5;
      glutPostRedisplay();
      break;
    case 0x0D :
      { static int anim = 1;
        anim = !anim;
        glutIdleFunc(( anim ) ? idle : NULL); }
      break;
    case 0x1B :
      exit(0);
      break; }
}

/* Fonction executee lors de l'appui            */
/* d'une touche de curseur ou d'une touche      */
/* page up ou page down                         */

static void special(int key,int x,int y) {
  switch(key) {
    case GLUT_KEY_UP :
      rx++;
      glutPostRedisplay() ;
      break;
    case GLUT_KEY_DOWN :
      rx--;
      glutPostRedisplay() ;
      break;
    case GLUT_KEY_LEFT :
      ry++;
      glutPostRedisplay() ;
      break;
    case GLUT_KEY_RIGHT :
      ry--;
      glutPostRedisplay() ;
      break;
    case GLUT_KEY_PAGE_UP :
      rz++;
      glutPostRedisplay() ;
      break;
    case GLUT_KEY_PAGE_DOWN :
      rz--;
      glutPostRedisplay() ;
      break; }
}

/* Fonction principale                          */

int main(int argc,char **argv) {
  glutInit(&argc,argv);
  glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE);
  glutInitWindowSize(300,300); 
  glutInitWindowPosition(50,50); 
  glutCreateWindow("Cubes et cylindre par facettes"); 
  init();
  glutKeyboardFunc(keyboard);
  glutSpecialFunc(special);
  glutReshapeFunc(reshape);
  glutIdleFunc(idle);
  glutDisplayFunc(display);
  glutMainLoop();
  return(0);
}
