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

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

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

#include <visu_tools.h>
#include <visu_data.h>
#include <visu_configFile.h>
#include <opengl.h>

void changeLightForWire();
void restoreLightAfterWire();

/* This function details how to read what is needed by PairsData. */
gboolean readWireGeneralWidth(gchar **lines, int nbLines,
			      int position, GString *errorMessage);
gboolean readWireWidth(gchar **lines, int nbLines,
		       int position, GString *errorMessage);
/* This function details how to read the parameter FLAG_PARAMETER_PAIRS. */
gboolean readWireNonLinear(gchar **lines, int nbLines,
			   int position, GString *errorMessage);
/* This function writes the parameter. */
gboolean exportParametersWire(GString *data, int *nbLinesWritten);
/* This function save the resources. */
gboolean exportResourcesWire(GString *data, int *nbLinesWritten);

#define FLAG_PARAMETER_WIRE   "wire_nonLinear"
#define DESC_PARAMETER_WIRE   "If the color of the pairs are corrected by their length ; boolean 0 or 1"
#define PARAMETER_WIRE_DEFAULT 0
int wireNonLinear;

#define FLAG_RESOURCES_PAIR_WIDTH "pairWire_pairWidth"
#define DESC_RESOURCES_PAIR_WIDTH "Widths detail for each pair drawn ; 0 < integer < 50"
#define FLAG_RESOURCES_WIRE_WIDTH "pairWire_width"
#define DESC_RESOURCES_WIRE_WIDTH "This value is the width for all pairs drawn ; 0 < integer < 50"
#define RESOURCES_WIRE_WIDTH_DEFAULT 2
#define RESOURCES_WIRE_WIDTH_MAX 50
int wireWidth;

/* The variation of the color intensity if stored in
   an array whose values are stored when wireNonLinear became true.
   The size of the array is controlled by a define. */
#define NB_SAMPLE_COLOR_LENGTH 101
float **colorLengthSample;


void setColorAndWidth(VisuElement *ele1, VisuElement *ele2, PairsData *data)
{
  Color *color;
  int *width;

  width = (int*)getPairsProperty(data, "width");
  if (width)
    glLineWidth(*width);
  else
    glLineWidth(wireWidth);
  color = (Color*)getPairsProperty(data, "color");
  if (color)
    glColor3f(color->rgba[PAIRS_COLOR_R], color->rgba[PAIRS_COLOR_G],
	      color->rgba[PAIRS_COLOR_B]);
}

void drawWirePairs(VisuElement *ele1, VisuElement *ele2, PairsData *data,
		   OpenGLView *view, double x1, double y1, double z1,
		   double x2, double y2, double z2, float d2)
{
  float length;
  int prop;
  

  if (wireNonLinear)
    {
      length = sqrt(d2);
      prop = (int)( (length - data->minMax[PAIRS_MIN]) /
		    (data->minMax[PAIRS_MAX] - data->minMax[PAIRS_MIN]) *
		    (float)(NB_SAMPLE_COLOR_LENGTH - 1));
/*       fprintf(stderr, "This length %f is at position %d %f (%f %f)\n", length, prop, colorLengthSample[0][prop], data->minMax[PAIRS_MAX], data->minMax[PAIRS_MIN]); */
      glColor3f(colorLengthSample[0][prop],
		colorLengthSample[1][prop],
		colorLengthSample[2][prop]);
    }

  glBegin(GL_LINES);
  glVertex3d(x1, y1, z1);
  glVertex3d(x2, y2, z2);
  glEnd();
}

PairsExtension* initPairsWire()
{
  char *name = _("Wire pairs");
  char *desc = _("Pairs are rendered by flat lines."
		 " The color and the width can by chosen.");
  PairsExtension *extension;
  VisuConfigFileEntry *resourceEntry;
  int i, j;

  extension = pairsExtension_new("Wire pairs", name, desc, 0,
				 changeLightForWire, restoreLightAfterWire,
				 setColorAndWidth, (startEndPairsFunc)0,
				 drawWirePairs);

  wireWidth = RESOURCES_WIRE_WIDTH_DEFAULT;
  wireNonLinear = PARAMETER_WIRE_DEFAULT;

  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCES_WIRE_WIDTH,
					  DESC_RESOURCES_WIRE_WIDTH,
					  1, readWireGeneralWidth);
  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCES_PAIR_WIDTH,
					  DESC_RESOURCES_PAIR_WIDTH,
					  1, readWireWidth);
  visuConfigFileAdd_exportFunction(VISU_CONFIGFILE_RESOURCE,
				   exportResourcesWire);
  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_PARAMETER,
					  FLAG_PARAMETER_WIRE,
					  DESC_PARAMETER_WIRE,
					  1, readWireNonLinear);
  visuConfigFileAdd_exportFunction(VISU_CONFIGFILE_PARAMETER,
				   exportParametersWire);

  colorLengthSample = malloc(sizeof(float*) * 3);
  if (!colorLengthSample)
    {
      allocationProblems();
      exit(1);
    }
  for (i = 0; i < 3; i++)
    {
      colorLengthSample[i] = malloc(sizeof(float) * NB_SAMPLE_COLOR_LENGTH);
      if (!colorLengthSample[i])
	{
	  allocationProblems();
	  exit(1);
	}
      for ( j = 0; j < NB_SAMPLE_COLOR_LENGTH; j++)
	colorLengthSample[i][j] = (float)j / (float)(NB_SAMPLE_COLOR_LENGTH - 1);
    }

  pointerToPairExtension_wire = extension;
  return extension;
}

void changeLightForWire()
{
  glDisable(GL_LIGHTING);
  glDisable(GL_DITHER);
}
void restoreLightAfterWire()
{
  glEnable(GL_DITHER); /* WARNING: it is the default! */
  glEnable(GL_LIGHTING);
}


int setWireGeneralWidth(int val)
{
  DBG_fprintf(stderr, "Pairs Wire : set the wire thickness to %d.\n", val);
  if (val <= 0 || val > RESOURCES_WIRE_WIDTH_MAX || val == wireWidth)
    return 0;

  setPairsAreOutOfDate();
  wireWidth = val;
  return 1;
}
int getWireGeneralWidth()
{
  return wireWidth;
}
int setWireWidth(PairsData *data, int val)
{
  int *width;

  if (!data)
    return 0;

  width = getPairsProperty(data, "width");
  if (!width)
    {
      width = malloc(sizeof(int));
      if (!width)
	{
	    allocationProblems();
	    exit(1);
	}
      setPairsProperty(data, "width", (gpointer)width);
      *width = val;
      setPairsAreOutOfDate();
      return 1;
    }
  else
    if (*width != val)
      {
	*width = val;
	setPairsAreOutOfDate();
	return 1;
      }

  return 0;
}
int getWireWidth(PairsData *data)
{
  int *width;

  if (!data)
    return 0;

  width = getPairsProperty(data, "width");
  if (width)
    return *width;
  else
    return wireWidth;
}
int setWireNonLinear(int val)
{
  DBG_fprintf(stderr, "Pairs Wire : set the wire color dependent of wire length to %d.\n", val);
  if (val == wireNonLinear)
    return 0;

  setPairsAreOutOfDate();
  wireNonLinear = val;
  return 1;
}
int getWireNonLinear()
{
  return wireNonLinear;
}
float* getLengthSampleForColor(int color, int *size)
{
  if (color < 0 || color > 2 || !size)
    {
      fprintf(stderr, "WARNING! Wrong parameter in the call of getLengthSampleForColor.\n");
      return (float*)0;
    }
  
  *size = NB_SAMPLE_COLOR_LENGTH;
  return colorLengthSample[color];
}

/*****************************************/
/* Dealing with parameters and resources */
/*****************************************/

/* This function details how to read what is needed by PairsData. */
gboolean readWireWidth(gchar **lines, int nbLines,
		       int position, GString *errorMessage)
{
  char *cursor;
  VisuElement* ele1, *ele2;
  int res, errorFlag;
  int val;
  PairsData *data;

  cursor = lines[0];
  ele1 = visuElementGet_fromValueLine(&cursor, -1, &errorFlag);
  if (!ele1 )
    {
      if (errorMessage)
	visuElementPrint_errorFromValueLine(errorMessage, position, errorFlag);
      return FALSE;
    }
  ele2 = visuElementGet_fromValueLine(&cursor, -1, &errorFlag);
  if (!ele2 )
    {
      if (errorMessage)
	visuElementPrint_errorFromValueLine(errorMessage, position, errorFlag);
      return FALSE;
    }
  data = getPairsData(ele1, ele2);
  if (!data)
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! unexpected internal error.\n"));
      fprintf(stderr, "INTERNAL ERROR! Can't find the VisuData associated to"
	      " elements '%s' and '%s'.\n", ele1->name, ele2->name);
      return FALSE;
    }
  res = sscanf(cursor, "%d", &val);
  if (res != 1 || val <= 0 || val > RESOURCES_WIRE_WIDTH_MAX)
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d,"
					       " 1 integer value must appear"
					       " after the %s markup.\n"),
			       position, FLAG_RESOURCES_PAIR_WIDTH);
      setWireWidth(data, RESOURCES_WIRE_WIDTH_DEFAULT);
      return FALSE;
    }
  res = setWireWidth(data, val);
/*   if (res) */
/*     createPairs(); */
  
  return TRUE;
}
/* This function details how to read what is needed by PairsData. */
gboolean readWireGeneralWidth(gchar **lines, int nbLines,
			      int position, GString *errorMessage)
{
  int res, width;

  res = sscanf(lines[0], "%d", &width);
  if (res != 1 || width <= 0 || width > RESOURCES_WIRE_WIDTH_MAX)
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d,"
					       " 1 integer value must appear"
					       " after the %s markup.\n"),
			       position, FLAG_RESOURCES_WIRE_WIDTH);
      setWireGeneralWidth(RESOURCES_WIRE_WIDTH_DEFAULT);
      return FALSE;
    }
  setWireGeneralWidth(width);
  return TRUE;
}
/* This function details how to read the parameter FLAG_PARAMETER_PAIRS. */
gboolean readWireNonLinear(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_PARAMETER_WIRE);
      setWireNonLinear(PARAMETER_WIRE_DEFAULT);
      return FALSE;
    }
  setWireNonLinear(val);
  return TRUE;
}
/* This function writes the parameter. */
gboolean exportParametersWire(GString *data, int *nbLinesWritten)
{
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_WIRE);
  g_string_append_printf(data, "%s: %i\n\n", FLAG_PARAMETER_WIRE, wireNonLinear);
  *nbLinesWritten = 3;

  return TRUE;
}
void exportPairsWidth(PairsData *data, gpointer userData)
{
  struct foreachFuncExport_struct *str;
  int *width;

  width = (int*)getPairsProperty(data, "width");
  if (width)
    {
      str = ( struct foreachFuncExport_struct*)userData;
      g_string_append_printf(str->data, "%s:\n    %s %s %d\n", FLAG_RESOURCES_PAIR_WIDTH,
			     data->name1, data->name2, *width);
      *str->nbLinesWritten += 2;
    }
}
gboolean exportResourcesWire(GString *data, int *nbLinesWritten)
{
  struct foreachFuncExport_struct str;

  g_string_append_printf(data, "# %s\n", DESC_RESOURCES_WIRE_WIDTH);
  g_string_append_printf(data, "%s:\n    %d\n", FLAG_RESOURCES_WIRE_WIDTH, wireWidth);
  *nbLinesWritten = 3;
  str.data = data;
  str.nbLinesWritten = nbLinesWritten;
  g_string_append_printf(data, "# %s\n", DESC_RESOURCES_PAIR_WIDTH);
  foreachPairsData(exportPairsWidth, &str);
  g_string_append_printf(data, "\n");
  *nbLinesWritten += 2;

  return TRUE;
}
