/***********************************************************************************/
/*  visualisation.c : programme pour la visualisation et la texture mapping        */
/*                    des objets definis dans objects.c                            */
/*                                                                                 */
/*   Author : Christophe Morel, Jian-jin LI                                        */
/*                                                                                 */
/*  Thanks to David G. Yu for his envphong.c program from which mine is strongly   */
/*            inspired                                                             */
/*                                                                                 */
/***********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/* Library to load .rgb images into textures */
#include "gltx.h"
#include "objects.h"
#include "lectFich.h"
#include "capture.h" 
#include "tr.h"
#include "captureauto.h"

#define T_PI 3.14159265358979

/* Constant for the menu */
enum 
{
  M_NONE, 
  M_VERTEXES,
  M_LINELOOP,
  M_TRIANGLE_STRIP,
  M_POLYGONS,
  M_LIGHTING,
  M_SPHERE1,
  M_SPHERE2,
  M_RECTANGLE
};

/* Constant for the animations */
enum 
{
  T_UP,
  T_DOWN,
  T_RIGHT,
  T_LEFT
};
/* angle of rotation of the object   */
GLfloat T_SPEED = 1 ;
/* constant for the direction of rotation */
int T_TURN = -1 ;

/*  Global Variable to parameter the display */

static int window;                    /* Window identifier                         */
static int useLighting = GL_TRUE;     /* Indicate if we use lighting               */
       int useTexture  = GL_FALSE;

static int moveLight   = GL_FALSE;    /* Indicate if the motion is a light motion  */
static int moveObject  = GL_FALSE;    /* Indicate if the motion is a object motion */
static int resolution  = 20;          /* Resolution to draw stuff                  */

static GLfloat lightRotX, lightRotY;  /* Rotation parameter for light              */
GLfloat objectRotX=90 , objectRotY;/* Rotation parameter for object             */

static int curx, cury;                /* Position of the mouse                     */

int width, height;					  /* Dimension of the window                   */ 
int texWidth, texHeight;			/* Dimension of the image saved				*/


int    displayStyle = GL_POLYGON;
int    useObject    = M_SPHERE1  ;    /* Indicate the object used                  */

//GLfloat zoom = 5 ;					  /* zoom of the camera						   */			
GLfloat zoom = 2.6131 ;					  /* zoom of the camera						   */
GLfloat angle_cam = 0.0;			
float cam_x = 0 ;					  /* position x of the camera				   */
float cam_y = 0 ;					  /* position y of the camera				   */

double  *ListTri;
double  *texture;
double	*ListCoordX;
double	*ListCoordY;
double	*ListCoordZ;
double	*ListCoordX_E;
double	*ListCoordY_E;
double	*ListCoordZ_E;
double  *texture_E;
double *ListCoordX_tore;
double *ListCoordY_tore;
double *ListCoordZ_tore;
double *texture_tore;
double	*texture_E_Affiche;
double	*ListTheta;
double	*ListPhi;
int		 NbLat;
int		 NbPts;
int      NBTri;
int maillage;			/* maillage = 0 maillage de subdivision */
						/* maillage = 1 maillage equiangulaire  */

/* boolean for the video and screenshot    */
int captureVideo = 0 ;  
int captureImage = 0 ;
int captureImage_auto = 0 ;
int rotationLibre = 0 ;
int elevation = 0;
int fich_elevation = 0;
GLfloat coef_elevation = 0.00;
GLfloat zoom_elevation;
int tore = 0;
int type_image = 0;

/* step for the angle of rotation*/
GLfloat pas_rotation = 0.1 ;

/* number of screenshoot to do		       */
int nbimage;

int display_cursor = 0 ;			  /* boolean for the display of the cursor     */		
int display_axis = 0 ;				  /* boolean for the display of the axisr     */
int display_mult = 0;
avi_t * movie ;						  /* pointer on the movie					   */


/*	Donnees necessaires pour les noms de images	*/
char *vue;
char *serie;



/***********************************************************************************/
/* Setup the light parameters                                                      */
/*                                                                                 */
/***********************************************************************************/
void setLight(void)
{
	//glDisable(GL_LIGHTING);
	glEnable(GL_LIGHTING);
	GLfloat light0Pos[4] = {5.0, 5.0, 5.0, 1.00};
	GLfloat light0Amb[4] = {1.00, 0.00, 1.00, 1.00};
	GLfloat light0Diff[4] = {0.00, 1.00, 0.00, 1.00};
	GLfloat light0Spec[4] = {1.00, 0.00, 0.00, 1.00};
	/*GLfloat light0Amb[4] = {0.10, 0.10, 0.10, 1.00};
	GLfloat light0Diff[4] = {0.10, 0.10, 0.10, 1.00};
	GLfloat light0Spec[4] = {0.10, 0.10, 0.10, 1.00};*/
	//GLfloat light0Pos[4] = {0.0, 0.0, 0.0, 1.00};
	/*GLfloat light0Amb[4] = {0.00, 0.00, 0.00, 1.00};
	GLfloat light0Diff[4] = {0.00, 0.00, 0.00, 1.00};
	GLfloat light0Spec[4] = {0.00, 0.00, 0.00, 1.00};*/
  /*GLfloat light0Atten0 = 0.00;
  GLfloat light0Atten1 = 0.00;
  GLfloat light0Atten2 = 1.00;*/

  glEnable(GL_LIGHT0);
  glLightfv(GL_LIGHT0, GL_POSITION, light0Pos);
  glLightfv(GL_LIGHT0, GL_AMBIENT, light0Amb);
  glLightfv(GL_LIGHT0, GL_DIFFUSE, light0Diff);
  glLightfv(GL_LIGHT0, GL_SPECULAR, light0Spec);
  /*glLightf (GL_LIGHT0, GL_CONSTANT_ATTENUATION, light0Atten0);
  glLightf (GL_LIGHT0, GL_LINEAR_ATTENUATION, light0Atten1);
  glLightf (GL_LIGHT0, GL_QUADRATIC_ATTENUATION, light0Atten2);*/
	glColorMaterial(GL_FRONT, GL_EMISSION);
	glEnable(GL_COLOR_MATERIAL);
  /*//GLfloat light0Pos[4] = {0.0, 0.0, 0.0, 1.00};

  //glEnable(GL_LIGHTING);

  //glLightfv(GL_LIGHT0, GL_POSITION, light0Pos);
  glPushMatrix();
  glEnable(GL_LIGHT1);
  GLfloat light1Pos[4] = {0.0, 0.0, 0.0, 1.0};
  glLightfv(GL_LIGHT1, GL_POSITION, light1Pos);
  GLfloat light0Emis[4] = {0.0, 0.0, 0.10, 1.00};
  glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, light0Emis);
  glPopMatrix();*/
  
  /*glEnable(GL_LIGHTING);
  glColorMaterial(GL_FRONT, GL_EMISSION);
  glEnable(GL_COLOR_MATERIAL);*/
  
}


/***********************************************************************************/
/* Initialize the program                                                          */
/*                                                                                 */
/***********************************************************************************/
void initialize(void)
{
  /* glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10.0);*/

  /* glOrtho(-2.0, 2.0, -2.0, 2.0, 1.0, 10.0);

  //glMatrixMode(GL_MODELVIEW);
  

  glDepthFunc(GL_LEQUAL);

  glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);*/
  //glTranslatef(0.0, 0.0, -1.0);
  //glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
  glShadeModel(GL_SMOOTH);
  glDepthFunc(GL_LEQUAL);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  //glTranslatef(0.0, 0.0, 0.4);
  //printf("coucou");
  //gluPerspective(45, 1, 1, 100);
  //glOrtho(-1.0,1.0,-1.0,1.0,1,10);
  glOrtho(-1.0,1.0,-1.0,1.0,1,10);
  //setLight();
}




/***********************************************************************************/
/* Draw function                                                                   */
/*                                                                                 */
/***********************************************************************************/
void redraw(void)
{
	glClearColor(0.1, 0.1, 0.1, 1.0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glMatrixMode(GL_MODELVIEW); 
	glLoadIdentity();
	gluLookAt( cam_x,  cam_y, zoom
              , cam_x, cam_y, 0
              , 0, 1, 0  );  

	glEnable(GL_DEPTH_TEST);

	glPushMatrix();

	glRotatef(objectRotY, 0.0, 1.0, 0.0);
	// printf("objectRotY = %5.3f",objectRotY);
	glRotatef(objectRotX, 1.0, 0.0, 0.0);
	// printf("objectRotX = %5.3f",objectRotX);

	/* ##### (Put here the objects to be tested) ##### */
	if (maillage == 0)
	{
		switch (useObject) 
		{
			case M_SPHERE1 :
				drawListTriangles();
				break;
			case M_SPHERE2 :
				drawSphere(resolution, 1.0, 0);
				break;
			case M_RECTANGLE :
				//   drawRectangle(resolution, resolution, 2.0, 2.0, 1.0);
				drawRectangle2(1);
				break;
			default :
				fprintf(stderr, "Object is not choosen !\n");
				break;
		}
	}
	else if (maillage == 1)
	{
		if (elevation == 0)
			drawSphereEqui();
		else
			drawSphereEqui_Elevation();
	}
	else if (maillage == 2)
		drawSphereHEALPix();
	if (tore == 1)
		drawTore();
  
    glPopMatrix();
	glDisable(GL_DEPTH_TEST);


  // Drawn a cursor in the position of the camera
  if(display_cursor)
  {
	glPushMatrix();
	//glRotatef(objectRotY, 0.0, 1.0, 0.0);
	glRotatef(objectRotX, 1.0, 0.0, 0.0);
	draw_mask();
	glPopMatrix();
  }

  // Drawn the axis
  if(display_axis)
  {
	glPushMatrix();

	glRotatef(objectRotY, 0.0, 1.0, 0.0);
	glRotatef(objectRotX, 1.0, 0.0, 0.0);
	    
	glColor3f(1,0,0) ;

	glBegin(GL_LINES);
	glVertex2d(0, 2);
	glVertex2d(0, 0);
	glVertex2d(2, 0);
	glVertex2d(0, 0);
	glEnd();

	glColor3f(0,0,1) ;

	glBegin(GL_LINES);
	glVertex2d(0, 0);
	glVertex2d(0, -2);
	glVertex2d(0, 0);
	glVertex2d(-2, 0);
	glEnd();

	glPopMatrix();

  }
  
}


/***********************************************************************************/
/* Check the errors state and print a message on screen if one occur               */
/*                                                                                 */
/***********************************************************************************/
void checkErrors(void)
{
  GLenum error;
  while ((error = glGetError()) != GL_NO_ERROR) {
    fprintf(stderr, "Error: %s\n", (char *) gluErrorString(error));
  }
}

/***********************************************************************************/
/* Handle the motion of the object and the light with the mouse                    */
/*                                                                                 */
/***********************************************************************************/
void motion(int x, int y)
{
  if (moveLight || moveObject) 
  {    
    GLfloat dx = -(y - cury) * 360.0 / height;
    GLfloat dy = (x - curx) * 360.0 / width;
	 /* printf("curx = %d \n",curx);
	  printf("cury = %d \n",cury);
	  printf("x = %d \n",x);
	  printf("y = %d \n",y);
	  printf("dx = %4.2f \n",dx);
	  printf("dy = %4.2f \n",dy);*/
	  
	if (moveLight) 
    {    
      /* We move the light */
      lightRotX += dx;
      if (lightRotX > 360)
        lightRotX -= 360;
      if (lightRotX < 0)
        lightRotX += 360;
      lightRotY += dy;
      if (lightRotY > 360)
        lightRotY -= 360;
      if (lightRotY < 0)
        lightRotY += 360;
    } 
    else if (moveObject) 
    {
      /* We move the object */
      objectRotX += dx;
      if (objectRotX > 360)
        objectRotX -= 360;
      if (objectRotX < 0)
        objectRotX += 360;
      objectRotY += dy;
      if (objectRotY > 360)
        objectRotY -= 360;
      if (objectRotY < 0)
        objectRotY += 360;
    }
    /* We move nothing, we just save the mouse position */
    curx = x;
    cury = y;
  }
  glutPostRedisplay();
}

/***********************************************************************************/
/* Handle the mouse events                                                         */
/*                                                                                 */
/***********************************************************************************/
void mouse(int button, int state, int x, int y)
{
  if (state == GLUT_DOWN) {
    switch (button) {
    case GLUT_LEFT_BUTTON:
	  moveObject = GL_TRUE;
      motion(curx = x, cury = y);
      break;
    case GLUT_MIDDLE_BUTTON:
      moveLight = GL_TRUE;
      motion(curx = x, cury = y);
      break;
    }
  } else if (state == GLUT_UP) {
    switch (button) {
    case GLUT_LEFT_BUTTON:
      moveObject = GL_FALSE;
      break;
    case GLUT_MIDDLE_BUTTON:
      moveLight = GL_FALSE;
      break;
    }
  }
}

/***********************************************************************************/
/* Handle the display                                                              */
/*                                                                                 */
/***********************************************************************************/
void display(void)
{
	redraw(); 
	glFlush();
	glutSwapBuffers();	
	checkErrors();
}

/***********************************************************************************/
/* Handle the size change of the window                                            */
/*                                                                                 */
/***********************************************************************************/
void reshape(int w, int h)
{
	//GLint * new_w ;
	
    //printf("reshape 1 %d\t%d\n",width,height);
	//glGetIntegerv(GL_MAX_VIEWPORT_DIMS,new_w);
	/* printf("new_w %d\t new_h %d\n",new_w[0],new_w[1]) */
    //glViewport(0, 0, width = w, height = h);
	glViewport(0,0,width, height);
    //printf("reshape 2 %d\t%d\n",width,height);
}



/***********************************************************************************/
/* Handle the keyboard events                                                      */
/*                                                                                 */
/***********************************************************************************/
void keyboard(unsigned char key, int x, int y)
{
  GLfloat limite;
  //printf("%d",key);
  switch (key) 
  {	
	case 'h' : /* display help */ 
			   printf("===================================================================\n");
			   printf("=                              Aide                               =\n");
			   printf("===================================================================\n");
			   printf("==> Rotation dans un sens                                         =\n");
			   printf("=   |-  Appuyez une fois pour activer, une autre pour desactiver  =\n");
			   printf("=   |-  'z','s','q','d' ( haut, bas, gauche, droite)              =\n");
			   printf("=                                                                 =\n");
			   printf("==> Translation de la camera                                      =\n");
			   printf("=   |-  'Z','S','Q','D' ( haut, bas, gauche, droite)              =\n");
			   printf("=   |-  Espace pour revenir au centre de la sphere                =\n");
			   printf("=                                                                 =\n");
			   printf("==> Zoom                                                          =\n");
			   printf("=   |-  'p','m' (plus , moins)                                    =\n");
			   printf("=   |-  Espace pour revenir au centre de la sphere                =\n");
			   printf("=                                                                 =\n");
			   printf("==> Capture en video ( avi ) non compresse                        =\n");
			   printf("=   |-  Appuyez une fois pour activer, une autre pour desactiver  =\n");
			   printf("=   |-  'V'                                                       =\n");
			   printf("=                                                                 =\n");
			   printf("==> Capture une image en tga                                      =\n");
			   printf("=   |-  Appuyez une fois pour declencher la saisie des parametres =\n");
			   printf("=   |-  'I'                                                       =\n");
			   printf("=                                                                 =\n");
			   printf("==> Afficher la croix de ciblage    'x'                           =\n");
               printf("=   |-  Appuyez une fois pour activer, une autre pour desactiver  =\n");
			   printf("==> Afficher les axes			   'X'                           =\n");
               printf("=   |-  Appuyez une fois pour activer, une autre pour desactiver  =\n");
			   printf("=                                                                 =\n");
			   printf("==> Controle de l'angle de rotation    'r'                        =\n");
			   printf("=    |-  Appuyez une fois pour saisir un angle, une autre pour    =\n");
			   printf("=    |-  desactiver												 =\n");
			   printf("=    |-  Actif: - la rotation n'est plus en fonction du zoom      =\n");
			   printf("=		       - 'P' et 'M' sont actif et permettent d'augmenter =\n");
			   printf("=			     ou diminuer la rotation de	1 degre              =\n");
			   printf("=                                                                 =\n");
			   printf("==> Affichage en elevation		'E'								 =\n");
			   printf("=   |-  Appuyez une fois pour activer, une autre pour desactiver  =\n");
			   printf("===================================================================\n");
			   break;

	case 'x' : /* display the cursor */
				if(display_cursor)
					display_cursor = 0 ;
				else
					display_cursor = 1 ;
				break ;
	case 'X' : /* display the axis */
				if(display_axis)
					display_axis = 0 ;
				else
					display_axis = 1 ;
				break ;			
	case 'I' : /* screenshot */
				printf(" I-> %d\t%d\n",width,height);
				display_cursor = 1;
				faireCaptureImage();
				break ;
	case 'V' : /* video */
				if(captureVideo == 0)
				{
					display_cursor = 0 ;
					redraw() ;
					movie = openMovie() ;
					captureVideo = 1 ;
				}
				else
				{
					closeMovie(movie) ;
					captureVideo = 0 ;
				}
				break ;
	case ' ' : /* move the camera to the center */
			cam_y = cam_x = 0 ; break;
    case 'Z' : /* move the camera to the top */
			cam_y +=((zoom)/30);
			printf("Zoom: %f Position camera ( y ): %f\n", zoom,cam_y); break ;
	case 'S' : /* move the camera to the bottom */
			cam_y -=((zoom)/30);
			printf("Zoom: %f Position camera ( y ): %f\n", zoom,cam_y); break ;
	case 'D' : /* move the camera to the right */
			cam_x +=((zoom)/30);
			printf("Zoom: %f Position camera ( x ): %f\n", zoom,cam_x);break ;
	case 'Q' : /* move the camera to the left */
			cam_x -=((zoom)/30);
			printf("Zoom: %f Position camera ( x ): %f\n", zoom,cam_x); break ;
	case 'r' : /* free rotation*/
			faireRotationLibre() ; break ;
	case 'P' : /* increase angle of rotation */
		if(rotationLibre && T_SPEED < 360) 
		{
			T_SPEED += pas_rotation ;
			printf("Angle de rotation : %f \n", T_SPEED) ;
		}
		break ;
    case 'M' : /* decrease angle of rotation */
		if(rotationLibre && T_SPEED > 0) 
		{
			T_SPEED -= pas_rotation ;
			printf("Angle de rotation : %f \n", T_SPEED) ;
		}
		break ;
    case 'p' : /* zoom */
		limite = sqrt(1 - ((cam_y )*(cam_y )) - ((cam_x )*(cam_x ))) ;	
		//printf("%f\n", limite);
		if( zoom - ( ( zoom - limite - 1 ) / 10 ) > limite + 1 )
			zoom -= ( ( zoom - limite - 1) / 10);
			
		printf("Zoom: %f %f\n", zoom, limite );
		if( !rotationLibre) T_SPEED = zoom ;
		break ;
    case 'm' : /* dezoom */
		zoom += 0.5;
		if( !rotationLibre) T_SPEED = zoom ;
		printf("Zoom: %f  \n", zoom);
		break ;
	case 'd': /* launch or stop the rotation to the right */
		if(T_TURN == T_RIGHT)
			T_TURN = -1 ;
		else
		{
			T_TURN = T_RIGHT ;
		}
		break ;
	case 'q' : /* launch or stop the rotation to the left */
		if(T_TURN == T_LEFT)
			T_TURN = -1 ;
		else
		{
			T_TURN = T_LEFT ;
		}
		break ;
	case 'z' : /* launch or stop the rotation to the top */
		if(T_TURN == T_UP)
			T_TURN = -1 ;
		else
		{
			T_TURN = T_UP ;
		}
		break ;
	case 's' :  /* launch or stop the rotation to the bottom */
		if(T_TURN == T_DOWN)
			T_TURN = -1 ;
		else
		{
			T_TURN = T_DOWN ;
		}
		break ;
	case '+' :  /* increase resolution */
		resolution++;
		printf("Resolution %d\n",resolution);
		break;
	case '-' :  /* decrease resolution */
		resolution--;
		printf("Resolution %d\n",resolution);
		break;
	case 'E' :
		if(elevation)
		{
			elevation = 0 ;
			zoom_elevation = 1.0;
			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();
			glOrtho(-1.0*zoom_elevation,1.0*zoom_elevation,-1.0*zoom_elevation,1.0*zoom_elevation,1,10);
			glMatrixMode(GL_MODELVIEW); 
		}
		else
		{	
			elevation = 1 ;
			Elevation();

		}
		break;
	case 'A' :
		//essai_capture_1();
		captureAuto();
		printf("fini2\n");
		break;
	
	case 'g':
		ajust_texturerange();
		break;

	case '\033': /* exit */ 
		exit(0);
  }
  glutPostRedisplay();
}

void timer(int v)
{

	GLfloat dx, dy ;
//	printf("T_SPEED= %5.3f",T_SPEED);

//	printf("timer");

	switch ( T_TURN )
	{
	case T_DOWN : dx = T_SPEED ;
				  dy = 0 ;
				  break ;
	case T_UP :	  dx = - T_SPEED ;
				  dy = 0 ;
				  break ;		
	case T_RIGHT :dx = 0 ;
				  dy = T_SPEED ;
				  break ;		
	case T_LEFT : dx = 0 ;
				  dy = - T_SPEED ;
				  break ;
	}
	
	if(T_TURN >= 0)
	{
		objectRotX += dx;
		if (objectRotX > 360)
			objectRotX -= 360;
		if (objectRotX < 0)
			objectRotX += 360;
		objectRotY += dy;
		if (objectRotY > 360)
			objectRotY -= 360;
		if (objectRotY < 0)
			objectRotY += 360;
	}
	glutPostRedisplay() ;
	
	 /* video */
	if(captureVideo)
		  addFrame(movie) ;

	 /* screenshoot */
	if(captureImage)
	{
		if (type_image == 0)
			dobmp_TGA();
		else
			dobmp_FITS();
	}
	glutTimerFunc(100, timer, v + 1);
}

void faireRotationLibre()
{
//		printf("faireRotationLibre");

	if(rotationLibre)
	{
		rotationLibre = 0 ;
	    T_SPEED =  zoom ;
	    //T_SPEED =  1./zoom ;
	}
	else
	{
		printf("Angle pour la rotation ? ");
		
		scanf("%f", &T_SPEED);
		fflush(stdin);
		rotationLibre = 1 ;
	}
		
}



void faireCaptureImage(void) 
{
	display_cursor = 0 ;	
	//redraw() ;
	printf("Combien d'image ? ");
	scanf("%d", &nbimage);
	printf("Taille de l'image ?\n");
	scanf("%d %d", &texWidth, &texHeight);
	printf("Type de l'image ? 0 = TGA, 1 = FITS\n");
	scanf("%d", &type_image);
	fflush(stdin);

	
	if( nbimage == 1 ) 
	{
		captureImage = 1 ;
		if (type_image == 0)
			dobmp_TGA();
		else
			dobmp_FITS();
	}
	else
	{
		captureImage = nbimage ;
		printf("Angle pour la rotation ? ");
		
		scanf("%f", &T_SPEED);
		fflush(stdin);
		T_TURN = T_RIGHT ;
		if (type_image == 0)
			dobmp_TGA();
		else
			dobmp_FITS();
	}
}

/*****************/
/*	capture automatique	*/
/*****************/

void captureAuto(void)
{
	double angle_texture = 20, a_t, *texture_int;
	int count = 0, count_int1 = 0, count_int2 = 0, ele, tmp, tmp2, *angles_vue, i, j, k, delta_elevation, angle_tmp;
	
	char nb[5] ;
	char *name = new char[30];
	char *char_tmp = new char[10];
	
	FILE *fp_test;
	
	texWidth = 1240;
	texHeight = 1240;

	angle_texture = 10;
	angles_vue = new int [4];
	angles_vue[0] = 2;
	angles_vue[1] = 7;
	angles_vue[2] = 21;
	angles_vue[3] = 40;
	
	texture_int = new double[NbLat*NbLat];
	for (i=0; i<NbLat*NbLat; i++)
		texture_int[i] = texture_E[i];
	
	
	vue = new char[5];
	
	serie = new char[20]; 
	printf("serie ? ");
	scanf("%s", serie);
	printf("serie = %s\n", serie);
	fflush(stdin);
	printf("elevation ? (0 = non, 1 = oui) ");
	scanf("%d", &elevation);
	printf("elevation = %d\n", elevation);
	fflush(stdin);
	printf("compteur de debut ? ");
	scanf("%d", &count_int1);
	printf("compteur = %d\n", count_int1);
	fflush(stdin);
	
	if (elevation)
		coef_elevation = 1.0;
	
	//delta_elevation = 20;
	angle_texture = 20;
	delta_elevation = ceil(20*NbLat/360.0);
	
	a_t = 0.0;
	//8
	for (tmp = 0; tmp<8; tmp++)
	{		
		angle_tmp = angles_vue[count];
		printf("angle = %d\n", angle_tmp);
		if (count == 3)
			count = 0;
		else
			count ++;
		if (tmp<4)
			T_TURN = T_LEFT;
		else
			T_TURN = T_RIGHT;
		T_SPEED = angle_tmp/2.0;
		timer(0);
		glutPostRedisplay() ;
		//glutTimerFunc(1, timer, 1);
		T_SPEED = 0;
		if (elevation)
			Elevation();
				
			/***	Boucle pour faire le tour de la sphere	***/
		//floor(360.0/angle_texture)
		count_int2 = count_int1;
		for (tmp2 = 0; tmp2<floor(360.0/angle_texture); tmp2++)
		{
				/***	Nom de l'image	***/
			if (tmp<4)
				vue = "B_";
			else
				vue = "A_";
			//strcpy(name, vue);
			if (strcmp(serie,"raycst")==0)
				strcpy(name, "serie_rayonconstant");
			else if (strcmp(serie,"patte1")==0)
				strcpy(name, "serie_mire1");
			else
				strcpy(name, serie);
			strcat(name, "/angle_");
			if (angle_tmp<10)
				strcat(name, "0");
			sprintf(char_tmp,"%d",angle_tmp);
			strcat(name, char_tmp);
			strcat(name, "/");
			
			strcat(name, vue);
			strcat(name, serie);
			strcat(name, "_a");
			if (angle_tmp<10)
				strcat(name, "0");
			sprintf(char_tmp,"%d",angle_tmp);
			strcat(name, char_tmp);
			strcat(name, "_");
			if (coef_elevation<0.09 && coef_elevation > 0.0)
				strcat(name, "00");
			else if (coef_elevation == 0.0)
				strcat(name, "0");
			ele = int(coef_elevation*100);
			sprintf(char_tmp, "%d", ele);
			strcat(name, char_tmp);
			strcat(name, "pc_");
			sprintf(nb, "%d", count_int2) ;
			if (count_int2<10)
				strcat(name, "0");
			strcat(name, nb) ;
			strcat(name, ".fits") ;
			
			fp_test = fopen(name, "wb");
			if (fp_test)
				remove(name);
		
			captureImage_auto = 1;
			nbimage = 1;
			angle_cam = 0;
			dobmp_FITS_name(name);
			
			k=0;
			if (elevation)
			{
				elevation = 0;
				zoom_elevation = 1.0;
				glMatrixMode(GL_PROJECTION);
				glLoadIdentity();
				glOrtho(-1.0*zoom_elevation,1.0*zoom_elevation,-1.0*zoom_elevation,1.0*zoom_elevation,1,10);
				glMatrixMode(GL_MODELVIEW);
				
				/*strcpy(name, "B_elevation0_a");
				if (angle_tmp<10)
					strcat(name, "0");
				sprintf(char_tmp,"%d",angle_tmp);
				strcat(name, char_tmp);
				sprintf(nb, "%d", tmp2) ;
				if (tmp2<10)
					strcat(name, "0");
				strcat(name, nb) ;
				strcat(name, ".fits");
				dobmp_FITS_name(name);*/
				
				for (i = 0; i< NbLat; i++)
				{
					for (j=0; j<NbLat; j++)
					{
						delta_elevation = ceil(angle_texture*(tmp2+1)*NbLat/360.0);
						k = j+delta_elevation;
						if (k>= NbLat)
							k=k-NbLat;
						texture_E[i*NbLat+j] = texture_int[i*NbLat+k];
					}
				}
				elevation = 1;
				//coef_elevation = 1.0;
				Elevation();
				
				/*strcpy(name, "B_elevation1_a");
				if (angle_tmp<10)
					strcat(name, "0");
				sprintf(char_tmp,"%d",angle_tmp);
				strcat(name, char_tmp);
				sprintf(nb, "%d", tmp2) ;
				if (tmp2<10)
					strcat(name, "0");
				strcat(name, nb) ;
				strcat(name, ".fits");
				dobmp_FITS_name(name);*/
			}
			
			T_TURN = T_LEFT;//T_RIGHT;
			T_SPEED = angle_texture;
			timer(0);
			glutPostRedisplay() ;
			T_SPEED = 0;
			
			count_int2 ++;
		
		}
		

		T_TURN = T_RIGHT;//T_LEFT;
		T_SPEED = tmp2*angle_texture;
		timer(0);
		glutPostRedisplay() ;
		//glutTimerFunc(1, timer, 1);
		T_SPEED = 0;
		if (tmp<4)
			T_TURN = T_RIGHT;
		else
			T_TURN = T_LEFT;
		T_SPEED = angle_tmp/2.0;
		timer(0);
		glutPostRedisplay() ;
		//glutTimerFunc(1, timer, 1);
		T_SPEED = 0;
		
		if (elevation)
		{
			elevation = 0;
			zoom_elevation = 1.0;
			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();
			glOrtho(-1.0*zoom_elevation,1.0*zoom_elevation,-1.0*zoom_elevation,1.0*zoom_elevation,1,10);
			glMatrixMode(GL_MODELVIEW);
			
			for (i = 0; i< NbLat; i++)
			{
				for (j=0; j<NbLat; j++)
				{
					texture_E[i*NbLat+j] = texture_int[i*NbLat+j];
				}
			}
			elevation = 1;
			//coef_elevation = 1.0;
			Elevation();
		}
		
		/*if (tmp<4)
			strcpy(name, "B_verification_a");
		else
			strcpy(name, "A_verification_a");
		if (angle_tmp<10)
			strcat(name, "0");
		sprintf(char_tmp,"%d",angle_tmp);
		strcat(name, char_tmp);
		strcat(name, ".fits");
		dobmp_FITS_name(name);*/
	
	}
	
	printf("fini\n");

}


/****	Ajustement de la valeur des niveaux de gris de l'image dans la gamme [0,1] visualisable par OpenGL	****/
void ajust_texturerange(void)
{
	double max, min;
	int i;
	
	max = 0;
	min = 500;
	for(i=0; i<NbLat*NbLat; i++)
	{
		if (texture[i] >= max)
			max = texture[i] ;
		if (texture[i]  <= min)
			min = texture[i] ;
	}
	for(i=0; i<NbLat*NbLat; i++)
		texture[i]  = (texture[i] -min)/(max-min);
}


void Elevation(void)
{
	int j;
	double x, y, z, r, phi, theta, max=0.0;
	
	if (coef_elevation == 0.0)
	{
		printf("Coefficient de l'elevation ? ");
		scanf("%f", &coef_elevation);
		fflush(stdin);
		printf("coef = %f\n", coef_elevation);
	}
	
	for (j = 0; j< NbLat*NbLat; j++)
	{
		x = ListCoordX[j]; y = ListCoordY[j]; z = ListCoordZ[j];
		phi = atan2(y,x); theta = atan2(sqrt(x*x+y*y),z);
		if (fich_elevation == 0)
			//r = (sqrt(x*x+y*y+z*z) + coef_elevation*(1-texture[j]));
			r = (sqrt(x*x+y*y+z*z) + coef_elevation*(texture[j]));
		else
			//r = (sqrt(x*x+y*y+z*z) + coef_elevation*(1-texture_E[j]));
			r = (sqrt(x*x+y*y+z*z) + coef_elevation*(texture_E[j]));
		if (r>max)
			max = r;
		x = r*sin(theta)*cos(phi);
		y = r*sin(theta)*sin(phi);
		z = r*cos(theta);
		ListCoordX_E[j] = x; ListCoordY_E[j] = y; ListCoordZ_E[j] = z;
		texture_E_Affiche[j] = texture[j];
	}
	//printf("max %f\n", max);
	//zoom_elevation = max;
	zoom_elevation = 1.0;
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-1.0*zoom_elevation,1.0*zoom_elevation,-1.0*zoom_elevation,1.0*zoom_elevation,1,10);
	glMatrixMode(GL_MODELVIEW);
}



/***********************************************************************************/
/* Handle the menu                                                                 */
/*                                                                                 */
/***********************************************************************************/
void menu(int value)
{
  switch (value) 
  {
  case M_NONE:
    break;
  case M_VERTEXES:
     displayStyle = GL_POINTS;
    break;
  case M_LINELOOP:
     displayStyle = GL_LINE_LOOP;
    break;
  case M_TRIANGLE_STRIP:
     displayStyle = GL_TRIANGLE_STRIP;
    break;
  case M_POLYGONS:
     displayStyle = GL_POLYGON;
    break;

  case M_LIGHTING:
    useLighting = !useLighting;
    break;

  case M_SPHERE1:
    useObject = M_SPHERE1;
    break;
  case M_SPHERE2:
    useObject = M_SPHERE2;
    break;
  case M_RECTANGLE:
    useObject = M_RECTANGLE;
    break;
  }

  glutPostRedisplay();
}

/***********************************************************************************/
/* Main                                                                            */
/*                                                                                 */
/***********************************************************************************/
int main(int argc, char **argv)
{
	int i = 0, indic = 0;
	char ftexture[100], ftore[100], felevation[100];
	FILE *fptexture, *fptore, *fpelevation;
	int type, tmp;
	
	while (++i < argc)
	{
		if ( strcmp( argv[i], "-f" ) == 0 )
		{
			indic += 1;
			strcpy( ftexture, argv[++i] );
			fptexture = fopen( ftexture, "r" );
			if ( !fptexture ) 
			{
				fprintf( stderr, "Error d'ouverture du fichier %s\n", ftexture );
				exit( 1 );
			}
			
			printf( "Lecture du fichier d'entree...\n");
			
			fscanf( fptexture, "%d", &type );
			printf("type=%d\n", type); 
			
			fscanf( fptexture, "%d", &maillage );
			
			if (maillage == 0)
			{
				printf("Maillage de subdivision\n");
				if ( type == 3 ) LectFich3d( &NBTri, fptexture );
				else if ( type == 4 ) 
				{
					useTexture = GL_TRUE;
					LectFich4d( &NBTri, fptexture );
				}
				else 
				{
					fprintf( stderr, " Type de fichier inconnu\n" );
					exit( 3 );
				}	
			}
			else if(maillage == 1)
			{
				printf("Maillage equiangulaire\n");
				LectFichEqui4d(&NbLat, fptexture);
				//printf("%d\n", NbLat);
			}
			else if(maillage == 2)
			{
				printf("Maillage HEALPix\n");
				LectFichHEALPix4d(&NbPts, fptexture);
			}
		}
		if ( strcmp( argv[i], "-t" ) == 0 )
		{
			indic += 1;
			strcpy( ftore, argv[++i] );
			fptore = fopen( ftore, "r" );
			if ( !fptore ) 
			{
				fprintf( stderr, "Error d'ouverture du fichier %s\n", ftore );
				exit( 1 );
			}
			fscanf(fptore, "%d", &NbPts);
			printf( "Lecture du fichier du tore...\n");
			LectFichTore(fptore);
			tore = 1;

		}
		if ( strcmp( argv[i], "-e" ) == 0 )
		{	
			indic += 1;
			strcpy( felevation, argv[++i] );
			fpelevation = fopen( felevation, "r" );
			if ( !fpelevation ) 
			{
				fprintf( stderr, "Error d'ouverture du fichier %s\n", felevation );
				exit( 1 );
			}
			
			printf( "Lecture du fichier d'elevation...\n");
			LectFichElevation(fpelevation);
			fich_elevation = 1;
		}
	}
	if ( indic < 1 )
	{
		fprintf(stderr, "Usage complet : -f ftexture -t ftore -e felevation\n");
		fprintf(stderr, "Usage minimum : -f ftexture\n");
		fprintf(stderr, "      ftexture	: fichier de texture\n");
		fprintf(stderr, "      ftore	: fichier du tore\n");
		fprintf(stderr, "      felevation	: fichier d'elevation\n");
		exit( 1 );
	} 

	

  glutInit(&argc, argv);
  /* reglage taille image */
/* Version initiale :  */
  glutInitWindowSize(width = 512, height = 512); 
  //glutInitWindowSize(width = 976, height = 976); 
  //glutInitWindowSize(width = 2048, height = 2048); 
  glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
  window = glutCreateWindow("Object Creator");
  glutDisplayFunc(display);
  glutKeyboardFunc(keyboard);
  glutReshapeFunc(reshape);
  glutMouseFunc(mouse);
  glutMotionFunc(motion);
  glutCreateMenu(menu);
  glutAddMenuEntry("Drawing Method    ", M_NONE          );  
  glutAddMenuEntry("   Points         ", M_VERTEXES      );
  glutAddMenuEntry("   LineLoop       ", M_LINELOOP      );
  glutAddMenuEntry("   Triangle strip ", M_TRIANGLE_STRIP);
  glutAddMenuEntry("   Polygons       ", M_POLYGONS      );
  glutAddMenuEntry("                  ", M_NONE          );
  glutAddMenuEntry("Other parameters  ", M_NONE          );  
  glutAddMenuEntry("   Toggle lighting", M_LIGHTING      );
  glutAddMenuEntry("                  ", M_NONE          );
  glutAddMenuEntry("Objects           ", M_NONE          );  
  glutAddMenuEntry("   Sphere 1       ", M_SPHERE1       );
  glutAddMenuEntry("   Sphere 2       ", M_SPHERE2       );
  glutAddMenuEntry("   Rectangle      ", M_RECTANGLE     );
  glutAttachMenu(GLUT_RIGHT_BUTTON);

  initialize();

  T_SPEED =  zoom ;

  timer(0) ;

  printf( "MainLoop...\n");
  glutMainLoop();
  return 0;             /* ANSI C requires main to return int. */
}

