/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2006)
  
	Adresse mèl :
	BILLARD, non joignable par mèl ;
	CALISTE, damien P caliste AT cea P fr.

	Ce logiciel est un programme informatique servant à visualiser des
	structures atomiques dans un rendu pseudo-3D. 

	Ce logiciel est régi par la licence CeCILL soumise au droit français et
	respectant les principes de diffusion des logiciels libres. Vous pouvez
	utiliser, modifier et/ou redistribuer ce programme sous les conditions
	de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA 
	sur le site "http://www.cecill.info".

	Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
	pris connaissance de la licence CeCILL, et que vous en avez accepté les
	termes (cf. le fichier Documentation/licence.fr.txt fourni avec ce logiciel).
*/

/*   LICENCE SUM UP
	Copyright CEA, contributors : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2006)

	E-mail address:
	BILLARD, not reachable any more ;
	CALISTE, damien P caliste AT cea P fr.

	This software is a computer program whose purpose is to visualize atomic
	configurations in 3D.

	This software is governed by the CeCILL  license under French law and
	abiding by the rules of distribution of free software.  You can  use, 
	modify and/ or redistribute the software under the terms of the CeCILL
	license as circulated by CEA, CNRS and INRIA at the following URL
	"http://www.cecill.info". 

	The fact that you are presently reading this means that you have had
	knowledge of the CeCILL license and that you accept its terms. You can
	find a copy of this licence shipped with this software at Documentation/licence.en.txt.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "opengl.h"

#include "visu_extension.h"
#include "visu_tools.h"
#include "visu_object.h"
#include "visu_configFile.h"
#include "openGLFunctions/renderingMode.h"
#include "openGLFunctions/interactive.h"
#include "openGLFunctions/view.h"
#include "openGLFunctions/objectList.h"
#include "renderingBackend/visu_windowInterface.h"

/******************************************************************************/

/* static int stereo; */

#define FLAG_PARAMETER_OPENGL_IMMEDIATE   "opengl_immediateDrawing"
#define DESC_PARAMETER_OPENGL_IMMEDIATE   "If true, changes of parameters means immediate redrawing ; boolean 0 or 1"
#define PARAMETER_OPENGL_IMMEDIATE_DEFAULT 1
int opengl_immediate;
gboolean readOpenGLImmediate(gchar **lines, int nbLines,
			     int position, GString *errorMessage);

#define FLAG_PARAMETER_OPENGL_ANTIALIAS "opengl_antialias"
#define DESC_PARAMETER_OPENGL_ANTIALIAS "If true, lines are drawn smoother ; boolean 0 or 1"
#define PARAMETER_OPENGL_ANTIALIAS_DEFAULT 0
int antialias;
gboolean readOpenGLAntialias(gchar **lines, int nbLines,
			     int position, GString *errorMessage);

#define FLAG_PARAMETER_OPENGL_FAKEBS "opengl_fakeBackingStore"
#define DESC_PARAMETER_OPENGL_FAKEBS "If true, V_Sim catches the Expose event from the X server and calls a redraw ; boolean 0 or 1"
#define PARAMETER_OPENGL_FAKEBS_DEFAULT 0
int fakeBackingStore;


/* Store an Id for the empty rendering. */
int openGlEmptyDrawingId;

/* Local methods. */
void redrawForBackingStore(void);

void glSetAntiAlias();
/* Private - This initialise the opengl redering (light...) */
void newFileLoaded(GObject *obj, VisuData *dataObj, gpointer data);
void gl_new_data(GenericRenderingWindow window, VisuData *data);


/******************************************************************************/

int initOpengl()
{
  VisuConfigFileEntry *resourceEntry;

  DBG_fprintf(stderr, "OpenGl : initialization.\n");

  obj = gluNewQuadric();
   
/*   glViewport(0, 0, width, height); */

  /* Deals with lights. */
  currentLights = lightEnvironnement_new();
  lightEnvironnementAdd_light(currentLights, light_newDefault());

  /* Parameters */
  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_PARAMETER,
					  FLAG_PARAMETER_OPENGL_ANTIALIAS,
					  DESC_PARAMETER_OPENGL_ANTIALIAS,
					  1, readOpenGLAntialias);
  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_PARAMETER,
					  FLAG_PARAMETER_OPENGL_IMMEDIATE,
					  DESC_PARAMETER_OPENGL_IMMEDIATE,
					  1, readOpenGLImmediate);
  visuConfigFileAdd_exportFunction(VISU_CONFIGFILE_PARAMETER,
				   exportParametersOpenGL);
  
  /* Initialise others sub-modules dealing with OpenGL. */
  openGLObjectList_init();
  openGLInit_renderingMode();
  OpenGLViewInit();
  openGLInteractive_init();

  isOBJECTReady = 0;
  antialias = PARAMETER_OPENGL_ANTIALIAS_DEFAULT;
  fakeBackingStore = PARAMETER_OPENGL_FAKEBS_DEFAULT;
  opengl_immediate = PARAMETER_OPENGL_IMMEDIATE_DEFAULT;
  openGlEmptyDrawingId = -1;

  /* Add a callback to reinitialisate the data when a new file is loaded. */
  g_signal_connect(G_OBJECT(visu), "dataReadyForRendering",
		   G_CALLBACK(newFileLoaded), (gpointer)0);
  g_signal_connect(G_OBJECT(visu), "OpenGLAskForReDraw",
		   G_CALLBACK(reDraw), (gpointer)0);
  g_signal_connect(G_OBJECT(visu), "OpenGLForceReDraw",
		   G_CALLBACK(reDraw), (gpointer)1);

  return 1;
}

/******************************************************************************/

void setOpenGlMaterial(float* material, float* rgba)
{
  float mm[4] = {0.0f, 0.0f, 0.0f, 0.0f};

  mm[3] = rgba[3];
  mm[0] = material[amb] * rgba[0];
  mm[1] = material[amb] * rgba[1];
  mm[2] = material[amb] * rgba[2];
  glMaterialfv(GL_FRONT, GL_AMBIENT, mm);
  mm[0] = material[dif] * rgba[0];
  mm[1] = material[dif] * rgba[1];
  mm[2] = material[dif] * rgba[2];
  glMaterialfv(GL_FRONT, GL_DIFFUSE, mm);
  glMaterialf(GL_FRONT, GL_SHININESS, material[shi] * 128.0f);
  mm[0] = material[spe];
  mm[1] = material[spe];
  mm[2] = material[spe];
  glMaterialfv(GL_FRONT, GL_SPECULAR, mm);
  mm[0] = material[emi] * rgba[0];
  mm[1] = material[emi] * rgba[1];
  mm[2] = material[emi] * rgba[2];
  glMaterialfv(GL_FRONT, GL_EMISSION, mm);
}

int setOpenGLContext(gboolean contextIsPixmap, DumpImage **dumpData,
		     guint width, guint height)
{
  int res;

  DBG_fprintf(stderr, "Opengl : changing Opengl context.\n");

  if (contextIsPixmap)
    {
      /* Change the context to have a indirect rendering to
	 be able to write to a glxpixmap. */
      *dumpData = dumpImageNew(width, height);
      if (!*dumpData)
	return 1;
  
      res = attachOpenGlContext(TRUE, dumpImageGet_buffer(*dumpData));
      if (!res)
	{
	  dumpImageFree(*dumpData);
	  return 1;
	}
    }
  else
    {
      g_warning("Should use this method only for pixmap."
		" Use visuRenderingWindowSet_context() instead.");
      res = attachOpenGlContext(FALSE, (gpointer)0);
      if (!res)
	return 1;
    }
  openGLInit_context();
  return 0;
}

void openGLInit_context()
{
  /* Set the openGL flags. */
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
  glDepthRange(0.0, 1.0);
  glClearDepth(1.0);

  glEnable(GL_CULL_FACE);
  glCullFace(GL_BACK);

  glEnable(GL_NORMALIZE);

  lightEnvironnementApply(currentLights);
  openGLApply_renderingMode(openGLGet_globalRenderingOption());

  glSetAntiAlias();

/*   OpenGLViewSet_windowSize(view, wi, he); */
}

/******************************************************************************/

void reDraw(GObject* obj, gpointer data)
{
  if (!isOBJECTReady)
    {
      DBG_fprintf(stderr, "Redraw rejected since we've got no valid OBJECT list."
		  " Draw to empty instead.\n");
      drawToEmpty();
      return;
    }
  if (!opengl_immediate && !GPOINTER_TO_INT(data))
    {
      DBG_fprintf(stderr, "Redraw rejected since drawing is deferred and not forced.\n");
      return;
    }
    
  DBG_fprintf(stderr, "Redraw accepted let's go...\n");

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  callAllExtensionsLists();

  /* display (and prepare next buffer for write in) */
  callSwapGLBuffer();
}

void initDrawToEmpty()
{
  float rgb[3];
  gpointer image;
  int width, height;
  guchar *imageData;
  gboolean alpha;
  int x, y;

  DBG_fprintf(stderr, "Opengl : init draw to empty special list.\n");

  openGlEmptyDrawingId = openGLObjectList_new(1);
  glNewList(openGlEmptyDrawingId, GL_COMPILE);
  visuRenderingWindowGet_backgroundColor(visuRenderingWindowGet_current(), rgb);
  DBG_fprintf(stderr, "Opengl : set background color to (%f,%f,%f).\n", rgb[0], rgb[1], rgb[2]);
  glClearColor(rgb[0], rgb[1], rgb[2], 0.25f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  image = visuRenderingWindowGet_backgroundImage(visuRenderingWindowGet_current(),
						&imageData, &alpha, &width, &height);
  if (image)
    {
      glDisable(GL_FOG);
      glEnable(GL_BLEND);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

      /* We can use fixed value for width and height since we project then
	 in a 2D ortho with these values. */
      x = (600 - width) / 2;
      y = (600 + height) / 2;
      glMatrixMode(GL_PROJECTION);
      glPushMatrix();
      glLoadIdentity();
      gluOrtho2D(0.0, 600., 0., 600.);
   
      glMatrixMode(GL_MODELVIEW);
      glPushMatrix();
      glLoadIdentity();

      glRasterPos2i(x, y);

      glPixelZoom(1., -1.);
      if (alpha)
	glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
      else
	glDrawPixels(width, height, GL_RGB, GL_UNSIGNED_BYTE, imageData);
      glPixelZoom(1., 1.);

      glPopMatrix();
      glMatrixMode(GL_PROJECTION);
      glPopMatrix();
      glMatrixMode(GL_MODELVIEW);
    }
  glEndList();
}

void drawToEmpty()
{
  if (openGlEmptyDrawingId < 0)
    initDrawToEmpty();

  glPushAttrib(GL_ENABLE_BIT);
  glCallList(openGlEmptyDrawingId);
  glPopAttrib();

  callSwapGLBuffer();
} 

/******************************************************************************/

void newFileLoaded(GObject *obj, VisuData *dataObj, gpointer data)
{
  if (!dataObj)
    {
      drawToEmpty();
      isOBJECTReady = 0;
      return;
    }
  isOBJECTReady = 1;
}

/******************************************************************************/

unsigned char * dumpViewToImage(VisuData *dataObj, GString *buffer, int *width, int *height)
{
  char *row_tab;
  int row_length, m, n1, n2, j;
  unsigned char *image;
  int res;
  DumpImage *dumpData;
  int resetOpenGl;
  int widthDump, heightDump, widthPrev, heightPrev;
  OpenGLView *view;

  g_return_val_if_fail(dataObj && width && height, (unsigned char *)0);

  view = visuDataGet_openGLView(dataObj);
  widthPrev = view->window->width;
  heightPrev = view->window->height;
  widthDump = (*width > 0)?*width:widthPrev;
  heightDump = (*height > 0)?*height:heightPrev;
  *width = widthDump;
  *height = heightDump;

  resetOpenGl = !OpenGLIsPixmap();
  if (resetOpenGl)
    {
      DBG_fprintf(stderr, "Opengl : changing Opengl context to"
		  " indirect rendering for dump process.\n");
      storeOpenGLContext();
      res = setOpenGLContext(TRUE, &dumpData, (guint)widthDump, (guint)heightDump);
      if (res)
	return (unsigned char*)0;
      visuDataSet_sizeOfView(dataObj, (guint)widthDump, (guint)heightDump);
    }

  /* Allocate our buffer for one row */
  row_length = 3 * widthDump;
  row_tab = malloc(row_length*sizeof(char));
  if(!row_tab)
    {
      g_string_append(buffer, _("Cannot allocate memory for row_tab:\n"
				"Window dump cancelled"));
      dumpImageFree(dumpData);
      return (unsigned char*)0;
    }
       
  /* Allocate our buffer for the image */
  image = 0; /* because of gcc on portable PC !?? */
  image = malloc(row_length * heightDump * sizeof(unsigned char));
  if(!image)
    {
      g_string_append(buffer, _("Cannot allocate memory for image:\n"
				"Window dump cancelled"));
      dumpImageFree(dumpData);
      return (unsigned char*)0;
    }
      
/*   image_width = width; */
/*   image_height = height; */

  DBG_fprintf(stderr, "Opengl : Beginning dump process.\n");

  /* Recreate the buffer... not necessary but...*/
  if (resetOpenGl)
    {
      openGLViewCompute_matrixAndView(visuDataGet_openGLView(dataObj));
      rebuildAllExtensionsLists(dataObj);
    }
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  callAllExtensionsLists();
/*   callSwapGLBuffer(); */

  glPixelStorei(GL_PACK_ALIGNMENT,1); /* just in case */

  /* Copy the image into our buffer */
  n2 = 0;
  for(m = heightDump-1; m>= 0; m--)
    {
      glReadPixels(0,m,widthDump,1,GL_RGB,GL_UNSIGNED_BYTE,row_tab);
      n1 = n2;
      n2 = n1 + row_length;
      for(j=n1; j<n2; j++)
	image[j] = row_tab[j-n1];
    }
  
  (void)free(row_tab);

  OpenGLViewSet_windowSize(visuDataGet_openGLView(dataObj), (guint)widthPrev, (guint)heightPrev);  
  if (resetOpenGl)
    {
      DBG_fprintf(stderr, "Opengl : changing back Opengl context to direct rendering.\n");
      restoreOpenGLContext();
      dumpImageFree(dumpData);
/*       OpenGLViewSet_windowSize((unsigned int)widthPrev, (unsigned int)heightPrev);   */
/*       project(); */
/*       modelize(); */
/*       glSetRendering(); */
/*       glSetAntiAlias(); */
/*       rebuildAllExtensionsLists(); */
    }
   
  return image;
}

/******************************************************************************/

/* To set the antialiasing on lines. */
void glSetAntiAlias()
{
  if (antialias)
    {
      /* Set blend if not present */
      glEnable(GL_BLEND);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

      /* Antialias */
      glEnable(GL_LINE_SMOOTH);
      glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
    }
  else
    {
      glDisable(GL_LINE_SMOOTH);
/*       glDisable(GL_BLEND); */
    }
}
int setAntialias(int value)
{
  if (value == antialias)
    return 0;

  antialias = value;
  glSetAntiAlias();
  
  return 1;
}
/* Get the value of the antialiasing parameter. */
int getAntialias()
{
  return antialias;
}

/* If on this create a function that call redraw if
   the expose event is raised. */
void setFakeBackingStore(int bool)
{
  if (bool == fakeBackingStore)
    return;

  fakeBackingStore = bool;

  if (bool)
    {
      /* Add the expose event to the existing mask. */
      addExposureEvent(visuRenderingWindowGet_current(), redrawForBackingStore);
    }
  else
    {
      /* Remove the expose event from the existing mask. */
      removeExposureEvent(visuRenderingWindowGet_current());
    }
}
int getFakeBackingStore()
{
  return fakeBackingStore;
}
void redrawForBackingStore(void)
{
  reDraw((GObject*)0, GINT_TO_POINTER(1));
}

/* If true all changes are applied only when the refresh button
   is pushed. */
void setImmediateDrawing(int bool)
{
  if (bool == opengl_immediate)
    return;

  opengl_immediate = bool;
}
int getImmediateDrawing()
{
  return opengl_immediate;
}


/***************************/
/* Dealing with parameters */
/***************************/

gboolean readOpenGLAntialias(gchar **lines, int nbLines,
			     int position, GString *errorMessage)
{
  int res;
  int val;

  res = sscanf(lines[0],"%d", &val);
  if (res != 1)
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d,"
					       " 1 integer value (v > 0) must appear"
					       " after the %s markup.\n"),
			       position, FLAG_PARAMETER_OPENGL_ANTIALIAS);
      setAntialias(PARAMETER_OPENGL_ANTIALIAS_DEFAULT);
      return FALSE;
    }
  else
    setAntialias(val);

  return TRUE;
}

gboolean readOpenGLImmediate(gchar **lines, int nbLines,
			     int position, GString *errorMessage)
{
  int res;
  int val;

  res = sscanf(lines[0],"%d", &val);
  if (res != 1)
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d, 1 integer"
					       " value (v > 0) must appear"
					       " after the %s markup.\n"),
			       position, FLAG_PARAMETER_OPENGL_IMMEDIATE);
      setAntialias(PARAMETER_OPENGL_IMMEDIATE_DEFAULT);
      return FALSE;
    }
  else
    setImmediateDrawing(val);

  return TRUE;
}
gboolean exportParametersOpenGL(GString *data, int *nbLinesWritten)
{
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_ANTIALIAS);
  g_string_append_printf(data, "%s: %d\n\n", FLAG_PARAMETER_OPENGL_ANTIALIAS,
	  antialias);
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_IMMEDIATE);
  g_string_append_printf(data, "%s: %d\n\n", FLAG_PARAMETER_OPENGL_IMMEDIATE,
	  opengl_immediate);
  *nbLinesWritten = 6;
  return TRUE;
}
