/*   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 "box.h"

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

#include <visu_object.h>
#include <visu_tools.h>
#include <visu_configFile.h>
#include <renderingBackend/visu_windowInterface.h>
#include <openGLFunctions/objectList.h>

static float boxRGBDefault[3] = {1.0, 0.5, 0.1};
static gboolean boxHasBeenBuilt;

/* Parameters & resources*/
/* This is a boolean to control is the box is render or not. */
#define FLAG_RESOURCE_BOX_USED   "box_is_on"
#define DESC_RESOURCE_BOX_USED   "Control if a box a drawn around the rendering area ; boolean (0 or 1)"
#define RESOURCE_BOX_USED_DEFAULT 0
gboolean readBoxIsOn(gchar **lines, int nbLines,
		       int position, GString *errorMessage);
/* A resource to control the color used to render the lines of the box. */
#define FLAG_RESOURCE_BOX_COLOR   "box_color"
#define DESC_RESOURCE_BOX_COLOR   "Define the color of the box ; three floating point values (0. <= v <= 1.)"
float boxRGB[3];
gboolean readBoxColor(gchar **lines, int nbLines,
		       int position, GString *errorMessage);
/* A resource to control the width to render the lines of the box. */
#define FLAG_RESOURCE_BOX_LINE   "box_line_width"
#define DESC_RESOURCE_BOX_LINE   "Define the width of the lines of the box ; one floating point values (1. <= v <= 10.)"
#define RESOURCE_BOX_LINE_DEFAULT 1.
float boxLineWidth;
gboolean readBoxLineWidth(gchar **lines, int nbLines,
			   int position, GString *errorMessage);

/* Export function that is called by visu_module to write the
   values of resources to a file. */
gboolean exportResourcesBox(GString *data, int *nbLinesWritten);

void rebuildBox(VisuData *dataObj);
void rebuildBoxOnDataReady(GObject *obj, VisuData *dataObj, gpointer data);
static void rebuildBoxOnResources(GObject *obj, gpointer data);

OpenGLExtension* initExtensionBox()
{
  char *name = "Box";
  char *description = _("Draw a box representing the limit of the area.");
  int listBox;
  VisuConfigFileEntry *resourceEntry;

  DBG_fprintf(stderr,"Initialising the box OpenGL extension...\n");
  listBox = openGLObjectList_new(1);
  extensionBox = OpenGLExtension_new(name, description, listBox, rebuildBox);
  OpenGLExtensionSet_priority(extensionBox, OPENGL_EXTENSION_PRIORITY_LOW);

  g_signal_connect(G_OBJECT(visu), "dataReadyForRendering",
		   G_CALLBACK(rebuildBoxOnDataReady), (gpointer)0);
  g_signal_connect(G_OBJECT(visu), "resourcesLoaded",
 		   G_CALLBACK(rebuildBoxOnResources), (gpointer)0);

  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCE_BOX_USED,
					  DESC_RESOURCE_BOX_USED,
					  1, readBoxIsOn);
  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCE_BOX_COLOR,
					  DESC_RESOURCE_BOX_COLOR,
					  1, readBoxColor);
  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCE_BOX_LINE,
					  DESC_RESOURCE_BOX_LINE,
					  1, readBoxLineWidth);
  visuConfigFileAdd_exportFunction(VISU_CONFIGFILE_RESOURCE,
				   exportResourcesBox);

  /* Initialisation des valeurs par défaut. */
  boxSet_RGBValues(boxRGBDefault, MASK_RGB_ALL);
  extensionBox->used = RESOURCE_BOX_USED_DEFAULT;
  boxLineWidth = RESOURCE_BOX_LINE_DEFAULT;
  boxHasBeenBuilt = FALSE;

  return extensionBox;
}

/* Method used to change the value of the parameter box_color. */
int boxSet_RGBValues(float rgb[3], int mask)
{
  int diff = 0;
  
  if (mask & MASK_RGB_R && boxRGB[0] != rgb[0])
    {
      boxRGB[0] = rgb[0];
      diff = 1;
    }
  if (mask & MASK_RGB_G && boxRGB[1] != rgb[1])
    {
      boxRGB[1] = rgb[1];
      diff = 1;
    }
  if (mask & MASK_RGB_B && boxRGB[2] != rgb[2])
    {
      boxRGB[2] = rgb[2];
      diff = 1;
    }
  if (!diff)
    return 0;

  /* Il faut recréer la boîte puisque des param ont changés. */
  boxHasBeenBuilt = FALSE;
/*   boxDraw(); */
  return extensionBox->used;
}
/* Method used to change the value of the parameter box_line_width. */
int boxSet_lineWidth(float width)
{
  if (width < 1. || width > 10. || width == boxLineWidth)
    return 0;

  boxLineWidth = width;
  /* Il faut recréer la boîte puisque des param ont changés. */
  boxHasBeenBuilt = FALSE;
/*   boxDraw(); */
  return extensionBox->used;
}
/* Method used to change the value of the parameter box_is_on. */
int boxSet_isOn(int value)
{
  if (value == extensionBox->used)
    return 0;

  extensionBox->used = value;
  return (value && !boxHasBeenBuilt);
}
/* Get methods. */
float boxGet_redValue()
{
  return boxRGB[0];
}
float boxGet_greenValue()
{
  return boxRGB[1];
}
float boxGet_blueValue()
{
  return boxRGB[2];
}
int boxGet_isOn()
{
  if (extensionBox)
    return extensionBox->used;
  else
    return 0;
}
float boxGet_lineWidth()
{
  return boxLineWidth;
}


/****************/
/* Private part */
/****************/

void rebuildBox(VisuData *dataObj)
{
  /* Force redraw. */
  boxHasBeenBuilt = FALSE;
  boxDraw(dataObj);
}
void rebuildBoxOnDataReady(GObject *obj, VisuData *dataObj, gpointer data)
{
  if (dataObj)
    {
      DBG_fprintf(stderr, "Extension box : caught the 'dataReadyForRendering' signal.\n");
      boxHasBeenBuilt = FALSE;
      boxDraw(dataObj);
    }
}
static void rebuildBoxOnResources(GObject *obj, gpointer data)
{
  GList *tmpLst;

  tmpLst = visuDataGet_allObjects();
  while (tmpLst)
    {
      boxDraw(VISU_DATA(tmpLst->data));
      tmpLst = g_list_next(tmpLst);
    }
}

void boxDraw(VisuData *data)
{
  OpenGLBox *box;

  if (boxHasBeenBuilt)
    return;

  DBG_fprintf(stderr, "Extension box : creating box for"
	      " VisuData %p.\n", (gpointer)data);
  boxHasBeenBuilt = TRUE;
  box = (visuDataGet_openGLView(data))->box;
  glDeleteLists(extensionBox->objectListId, 1);
  glNewList(extensionBox->objectListId, GL_COMPILE);
  glLineWidth(boxLineWidth);
  glColor3f(boxRGB[0], boxRGB[1], boxRGB[2]);
  glDisable(GL_LIGHTING);
  glDisable(GL_DITHER);
  glPushMatrix();
  glTranslated(-box->dxxs2, -box->dyys2, -box->dzzs2);
  glBegin(GL_LINES);
  glVertex3d(box->p1[0], box->p1[1], box->p1[2]);
  glVertex3d(box->p2[0], box->p2[1], box->p2[2]);
  glVertex3d(box->p2[0], box->p2[1], box->p2[2]);
  glVertex3d(box->p3[0], box->p3[1], box->p3[2]);
  glVertex3d(box->p3[0], box->p3[1], box->p3[2]);
  glVertex3d(box->p4[0], box->p4[1], box->p4[2]);
  glVertex3d(box->p4[0], box->p4[1], box->p4[2]);
  glVertex3d(box->p1[0], box->p1[1], box->p1[2]);
  glVertex3d(box->p5[0], box->p5[1], box->p5[2]);
  glVertex3d(box->p6[0], box->p6[1], box->p6[2]);
  glVertex3d(box->p6[0], box->p6[1], box->p6[2]);
  glVertex3d(box->p7[0], box->p7[1], box->p7[2]);
  glVertex3d(box->p7[0], box->p7[1], box->p7[2]);
  glVertex3d(box->p8[0], box->p8[1], box->p8[2]);
  glVertex3d(box->p8[0], box->p8[1], box->p8[2]);
  glVertex3d(box->p5[0], box->p5[1], box->p5[2]);
  glVertex3d(box->p1[0], box->p1[1], box->p1[2]);
  glVertex3d(box->p5[0], box->p5[1], box->p5[2]);
  glVertex3d(box->p2[0], box->p2[1], box->p2[2]);
  glVertex3d(box->p6[0], box->p6[1], box->p6[2]);
  glVertex3d(box->p3[0], box->p3[1], box->p3[2]);
  glVertex3d(box->p7[0], box->p7[1], box->p7[2]);
  glVertex3d(box->p4[0], box->p4[1], box->p4[2]);
  glVertex3d(box->p8[0], box->p8[1], box->p8[2]);
  glEnd();
  glPopMatrix();  
  glEnable(GL_LIGHTING);
  glEnable(GL_DITHER); /* WARNING: it is the default! */
  glLineWidth(1.);
  glEndList();
}

/* Parameters & resources*/

/* This is a boolean to control is the box is render or not. */
gboolean readBoxIsOn(gchar **lines, int nbLines,
		     int position, GString *errorMessage)
{
  int res, val;

  res = sscanf(lines[0],"%d", &val);
  if (res != 1)
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d,"
					       " 1 boolean value must appear"
					       " after the %s markup.\n"),
			       position, FLAG_RESOURCE_BOX_USED);
      boxSet_isOn(RESOURCE_BOX_USED_DEFAULT);
      return FALSE;
    }

  boxSet_isOn(val);
  return TRUE;
}
/* A resource to control the color used to render the lines of the box. */
gboolean readBoxColor(gchar **lines, int nbLines,
		      int position, GString *errorMessage)
{
  int res;
  float rgb[3];
  
  res = sscanf(lines[0],"%f %f %f", &rgb[0], &rgb[1], &rgb[2]);
  if (res != 3 ||
      visuConfigFileSet_floatValue(&rgb[0], rgb[0], 0., 1.) ||
      visuConfigFileSet_floatValue(&rgb[1], rgb[1], 0., 1.) ||
      visuConfigFileSet_floatValue(&rgb[2], rgb[2], 0., 1.))
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d, 3 floating "
					       "point values (0 <= v <= 1) must appear after"
					       " the %s markup.\n"),
			       position, FLAG_RESOURCE_BOX_COLOR);
      boxSet_RGBValues(boxRGBDefault, MASK_RGB_ALL);
      return FALSE;
    }
  boxSet_RGBValues(rgb, MASK_RGB_ALL);

  return TRUE;
}
/* A resource to control the width to render the lines of the box. */
gboolean readBoxLineWidth(gchar **lines, int nbLines,
			  int position, GString *errorMessage)
{
  int res;
  float width;
  
  res = sscanf(lines[0],"%f", &width);
  if (res != 1 ||
      visuConfigFileSet_floatValue(&width, width, 1., 10.))
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d, 1 floating "
					       "point value (1 <= v <= 10) must appear after"
					       " the %s markup.\n"),
			       position, FLAG_RESOURCE_BOX_COLOR);
      boxSet_lineWidth(RESOURCE_BOX_LINE_DEFAULT);
      return FALSE;
    }
  boxSet_lineWidth(width);

  return TRUE;
}

/* Export function that is called by visu_module to write the
   values of resources to a file. */
gboolean exportResourcesBox(GString *data, int *nbLinesWritten)
{
  g_string_append_printf(data, "# %s\n", DESC_RESOURCE_BOX_USED);
  g_string_append_printf(data, "%s:\n", FLAG_RESOURCE_BOX_USED);
  g_string_append_printf(data, "    %d\n", extensionBox->used);
  g_string_append_printf(data, "# %s\n", DESC_RESOURCE_BOX_COLOR);
  g_string_append_printf(data, "%s:\n", FLAG_RESOURCE_BOX_COLOR);
  g_string_append_printf(data, "    %4.3f %4.3f %4.3f\n",
	  boxRGB[0], boxRGB[1], boxRGB[2]);
  g_string_append_printf(data, "# %s\n", DESC_RESOURCE_BOX_LINE);
  g_string_append_printf(data, "%s:\n", FLAG_RESOURCE_BOX_LINE);
  g_string_append_printf(data, "    %4.0f\n", boxLineWidth);
  g_string_append_printf(data, "\n");
  *nbLinesWritten += 10;

  return TRUE;
}
