/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Damien
	CALISTE, laboratoire L_Sim, (2001-2009)
  
	Adresse 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 : Damien
	CALISTE, laboratoire L_Sim, (2001-2009)

	E-mail address:
	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 COPYING.
*/
#include "shade.h"

#include <string.h>

#include <openGLFunctions/objectList.h>
#include <openGLFunctions/text.h>
#include <coreTools/toolColor.h>

/**
 * SECTION:shade
 * @short_description: Draw a frame with the representation of a color shade.
 *
 * <para>This extension draws a frame on top of the rendering area
 * with a color shade. One can setup printed values and draw
 * additional marks inside the shade.</para>
 *
 * Since: 3.7
 */

#define SHADE_LEGEND_N_QUADS 50

/**
 * VisuGlExtShadeClass:
 * @parent: the parent class;
 *
 * A short way to identify #_VisuGlExtShadeClass structure.
 *
 * Since: 3.7
 */
/**
 * VisuGlExtShade:
 *
 * An opaque structure.
 *
 * Since: 3.7
 */
/**
 * VisuGlExtShadePrivate:
 *
 * Private fields for #VisuGlExtShade objects.
 *
 * Since: 3.7
 */
struct _VisuGlExtShadePrivate
{
  /* Shade definition. */
  ToolShade *shade;

  /* Parameters. */
  float minMax[2];
  ToolMatrixScalingFlag scaling;
  GArray *marks;
};

enum {
  PROP_0,
  PROP_SHADE,
  PROP_MM,
  N_PROPS
};
static GParamSpec *_properties[N_PROPS];

static void visu_gl_ext_shade_finalize(GObject* obj);
static void visu_gl_ext_shade_get_property(GObject* obj, guint property_id,
                                           GValue *value, GParamSpec *pspec);
static void visu_gl_ext_shade_set_property(GObject* obj, guint property_id,
                                           const GValue *value, GParamSpec *pspec);
static gboolean visu_gl_ext_shade_isValid(const VisuGlExtFrame *frame);
static void visu_gl_ext_shade_draw(const VisuGlExtFrame *frame);
static void visu_gl_ext_shade_rebuild(VisuGlExt *ext);

G_DEFINE_TYPE_WITH_CODE(VisuGlExtShade, visu_gl_ext_shade, VISU_TYPE_GL_EXT_FRAME,
                        G_ADD_PRIVATE(VisuGlExtShade))

static void visu_gl_ext_shade_class_init(VisuGlExtShadeClass *klass)
{
  DBG_fprintf(stderr, "Extension Shade: creating the class of the object.\n");
  /* DBG_fprintf(stderr, "                - adding new signals ;\n"); */

  /* DBG_fprintf(stderr, "                - adding new resources ;\n"); */

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->finalize = visu_gl_ext_shade_finalize;
  G_OBJECT_CLASS(klass)->set_property = visu_gl_ext_shade_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_gl_ext_shade_get_property;
  VISU_GL_EXT_CLASS(klass)->rebuild = visu_gl_ext_shade_rebuild;
  VISU_GL_EXT_FRAME_CLASS(klass)->isValid = visu_gl_ext_shade_isValid;
  VISU_GL_EXT_FRAME_CLASS(klass)->draw = visu_gl_ext_shade_draw;

  /**
   * VisuGlExtShade::shade:
   *
   * The colour shade.
   *
   * Since: 3.8
   */
  _properties[PROP_SHADE] =
    g_param_spec_boxed("shade", "Shade", "colorization scheme",
                       TOOL_TYPE_SHADE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  /**
   * VisuGlExtShade::range-min-max:
   *
   * Min / max range as used to normalise data.
   *
   * Since: 3.8
   */
  _properties[PROP_MM] = g_param_spec_boxed("range-min-max", "Range min/max",
                                            "min / max range to normalise data",
                                            G_TYPE_ARRAY,
                                            G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

  g_object_class_install_properties(G_OBJECT_CLASS(klass), N_PROPS, _properties);
}

static void visu_gl_ext_shade_init(VisuGlExtShade *obj)
{
  DBG_fprintf(stderr, "Extension Shade: initializing a new object (%p).\n",
	      (gpointer)obj);
  
  obj->priv = visu_gl_ext_shade_get_instance_private(obj);

  /* Private data. */
  obj->priv->marks      = g_array_new(FALSE, FALSE, sizeof(float));
  obj->priv->scaling    = TOOL_MATRIX_SCALING_LINEAR;
  obj->priv->minMax[0]  = G_MAXFLOAT;
  obj->priv->minMax[1]  = -G_MAXFLOAT;
  obj->priv->shade      = (ToolShade*)0;
}
static void visu_gl_ext_shade_get_property(GObject* obj, guint property_id,
                                           GValue *value, GParamSpec *pspec)
{
  VisuGlExtShade *self = VISU_GL_EXT_SHADE(obj);
  GArray *arr;

  DBG_fprintf(stderr, "Extension Shade: get property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case PROP_SHADE:
      g_value_set_boxed(value, self->priv->shade);
      DBG_fprintf(stderr, "%p.\n", (gpointer)self->priv->shade);
      break;
    case PROP_MM:
      DBG_fprintf(stderr, "%g / %g.\n", self->priv->minMax[0], self->priv->minMax[1]);
      arr = g_array_sized_new(FALSE, FALSE, sizeof(float), 2);
      g_array_index(arr, float, 0) = self->priv->minMax[0];
      g_array_index(arr, float, 1) = self->priv->minMax[1];
      g_value_take_boxed(value, arr);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_gl_ext_shade_set_property(GObject* obj, guint property_id,
                                           const GValue *value, GParamSpec *pspec)
{
  VisuGlExtShade *self = VISU_GL_EXT_SHADE(obj);
  GArray *arr;

  DBG_fprintf(stderr, "Visu Data Colorizer Fragment: set property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case PROP_SHADE:
      DBG_fprintf(stderr, "%p.\n", g_value_get_boxed(value));
      visu_gl_ext_shade_setShade(self, (ToolShade*)g_value_get_boxed(value));
      break;
    case PROP_MM:
      DBG_fprintf(stderr, "%p.\n", g_value_get_boxed(value));
      arr = (GArray*)g_value_get_boxed(value);
      visu_gl_ext_shade_setMinMax(self, g_array_index(arr, float, 0),
                                  g_array_index(arr, float, 1));
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}

static void visu_gl_ext_shade_finalize(GObject* obj)
{
  VisuGlExtShade *shade;

  g_return_if_fail(obj);

  DBG_fprintf(stderr, "Extension Shade: finalize object %p.\n", (gpointer)obj);

  shade = VISU_GL_EXT_SHADE(obj);

  /* Free privs elements. */
  DBG_fprintf(stderr, "Extension Shade: free private shade.\n");
  tool_shade_free(shade->priv->shade);
  g_array_unref(shade->priv->marks);

  /* Chain up to the parent class */
  DBG_fprintf(stderr, "Extension Shade: chain to parent.\n");
  G_OBJECT_CLASS(visu_gl_ext_shade_parent_class)->finalize(obj);
  DBG_fprintf(stderr, "Extension Shade: freeing ... OK.\n");
}

/**
 * visu_gl_ext_shade_new:
 * @name: (allow-none): the name to give to the extension (default is #VISU_GL_EXT_SHADE_ID).
 *
 * Creates a new #VisuGlExt to draw a shade.
 *
 * Since: 3.7
 *
 * Returns: a pointer to the #VisuGlExt it created or
 * NULL otherwise.
 */
VisuGlExtShade* visu_gl_ext_shade_new(const gchar *name)
{
  char *name_ = VISU_GL_EXT_SHADE_ID;
  char *description = _("Draw the legend of a color shade.");
  VisuGlExt *shade;
#define SHADE_LEGEND_WIDTH  20.f
#define SHADE_LEGEND_HEIGHT 175.f

  DBG_fprintf(stderr,"Extension Shade: new object.\n");
  
  shade = g_object_new(VISU_TYPE_GL_EXT_SHADE,
                       "name", (name)?name:name_, "label", _(name),
                       "description", description, "saveState", TRUE,
                       "nGlObj", 1, "priority", VISU_GL_EXT_PRIORITY_LAST, NULL);
  visu_gl_ext_frame_setPosition(VISU_GL_EXT_FRAME(shade), 0.f, 0.f);
  visu_gl_ext_frame_setRequisition(VISU_GL_EXT_FRAME(shade),
                                   SHADE_LEGEND_WIDTH + 5 + 12 * 7,
                                   SHADE_LEGEND_HEIGHT);

  return VISU_GL_EXT_SHADE(shade);
}
/**
 * visu_gl_ext_shade_setShade:
 * @ext: The #VisuGlExtShade to attached to.
 * @shade: the shade to get the color of.
 *
 * Attach an #VisuGlView to render to and setup the shade.
 *
 * Since: 3.7
 *
 * Returns: TRUE if internal shade is changed.
 **/
gboolean visu_gl_ext_shade_setShade(VisuGlExtShade *ext, const ToolShade *shade)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_SHADE(ext), FALSE);

  if (tool_shade_compare(ext->priv->shade, shade))
    return FALSE;

  tool_shade_free(ext->priv->shade);
  ext->priv->shade = tool_shade_copy(shade);

  g_object_notify_by_pspec(G_OBJECT(ext), _properties[PROP_SHADE]);

  visu_gl_ext_setDirty(VISU_GL_EXT(ext), TRUE);
  return TRUE;
}
/**
 * visu_gl_ext_shade_setMinMax:
 * @shade: the #VisuGlExtShade to update.
 * @minV: a value.
 * @maxV: another value.
 *
 * Change the minimum and maximum values used on the legend.
 *
 * Since: 3.7
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_gl_ext_shade_setMinMax(VisuGlExtShade *shade, float minV, float maxV)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_SHADE(shade), FALSE);
  g_return_val_if_fail(minV <= maxV, FALSE);

  if (shade->priv->minMax[0] == minV && shade->priv->minMax[1] == maxV)
    return FALSE;

  shade->priv->minMax[0] = minV;
  shade->priv->minMax[1] = maxV;

  g_object_notify_by_pspec(G_OBJECT(shade), _properties[PROP_MM]);

  visu_gl_ext_setDirty(VISU_GL_EXT(shade), TRUE);
  return TRUE;
}
/**
 * visu_gl_ext_shade_setScaling:
 * @shade: the #VisuGlExtShade to update.
 * @scaling: a #ToolMatrixScalingFlag value.
 *
 * Change the scaling variation of the shade between the minimum and
 * the maximum values, see visu_gl_ext_shade_setMinMax().
 *
 * Since: 3.7
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_gl_ext_shade_setScaling(VisuGlExtShade *shade, ToolMatrixScalingFlag scaling)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_SHADE(shade), FALSE);

  if (shade->priv->scaling == scaling)
    return FALSE;

  shade->priv->scaling = scaling;

  visu_gl_ext_setDirty(VISU_GL_EXT(shade), TRUE);
  return TRUE;
}
/**
 * visu_gl_ext_shade_setMarks:
 * @shade: the #VisuGlExtShade to update.
 * @marks: (array length=n): a list of float values in [0;1].
 * @n: the length of @marks.
 *
 * The legend can draw additional marks in the shade. Setup these
 * marks with this routine. The first and the last marks of the list will be
 * rendered bigger than the next ones.
 *
 * Since: 3.7
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_gl_ext_shade_setMarks(VisuGlExtShade *shade, float *marks, guint n)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_SHADE(shade), FALSE);

  g_array_set_size(shade->priv->marks, n);
  memcpy(shade->priv->marks->data, marks, sizeof(float) * n);

  visu_gl_ext_setDirty(VISU_GL_EXT(shade), TRUE);
  return TRUE;
}

static void visu_gl_ext_shade_rebuild(VisuGlExt *ext)
{
  visu_gl_text_rebuildFontList();
  if (VISU_GL_EXT_GET_CLASS(ext)->draw)
    VISU_GL_EXT_GET_CLASS(ext)->draw(ext);
}

static gboolean visu_gl_ext_shade_isValid(const VisuGlExtFrame *frame)
{
  VisuGlExtShade *shade;

  g_return_val_if_fail(VISU_IS_GL_EXT_SHADE(frame), FALSE);
  shade = VISU_GL_EXT_SHADE(frame);

  return (shade->priv->shade && shade->priv->minMax[0] < shade->priv->minMax[1]);
}

static void visu_gl_ext_shade_draw(const VisuGlExtFrame *frame)
{
  guint i;
  float yStep, xbuf, scale, sW;
  float rgba[4];
  char value[16];
  tool_matrix_getScaledValue get_inv;
  VisuGlExtShade *shade;

  g_return_if_fail(VISU_IS_GL_EXT_SHADE(frame));
  shade = VISU_GL_EXT_SHADE(frame);

  scale = visu_gl_ext_frame_getScale(frame);
  sW = SHADE_LEGEND_WIDTH * scale;

  /* We draw the colored bar. */
  tool_shade_valueToRGB(shade->priv->shade, rgba, 0.);
  glColor4fv(rgba);
  yStep = (float)frame->height / (float)SHADE_LEGEND_N_QUADS;
  glBegin(GL_QUAD_STRIP);
  for (i = 0; i <= SHADE_LEGEND_N_QUADS; i++)
    {
      glVertex2f(0, (float)i * yStep);
      glVertex2f(sW, (float)i * yStep);
      tool_shade_valueToRGB(shade->priv->shade, rgba,
                            (float)i / (float)SHADE_LEGEND_N_QUADS);
      glColor4fv(rgba);
    }
  glEnd();

  switch (shade->priv->scaling)
    {
    case TOOL_MATRIX_SCALING_LINEAR:
      get_inv = tool_matrix_getScaledLinearInv;
      break;
    case TOOL_MATRIX_SCALING_LOG:
      get_inv = tool_matrix_getScaledLogInv;
      break;
    case TOOL_MATRIX_SCALING_ZERO_CENTRED_LOG:
      get_inv = tool_matrix_getScaledZeroCentredLogInv;
      break;
    default:
      get_inv = (tool_matrix_getScaledValue)0;
      break;
    }
  g_return_if_fail(get_inv);

  glDisable(GL_LINE_SMOOTH);

  /* We draw some marks. */
  if (shade->priv->marks)
    {
      DBG_fprintf(stderr, "Extension Shade: put %d marks.\n", shade->priv->marks->len);
      xbuf = 0.f;
      for (i = 0; i < shade->priv->marks->len; i++)
	{
          if (i == 0 || i == shade->priv->marks->len - 1)
            {
              glLineWidth(2 * scale);
              xbuf = 3.f;
            }
          else if (i == 1)
            {
              glLineWidth(scale);
              xbuf = 8.f;
            }
	  yStep = CLAMP(g_array_index(shade->priv->marks, float, i), 0., 1.);
	  tool_shade_valueToRGB(shade->priv->shade, rgba, yStep);
	  rgba[0] = 1. - rgba[0];
	  rgba[1] = 1. - rgba[1];
	  rgba[2] = 1. - rgba[2];
	  glColor4fv(rgba);
	  yStep *= (float)frame->height;
          yStep = CLAMP(yStep, 2.f * scale, frame->height - scale);
          glBegin(GL_LINES);
	  glVertex2f(xbuf, yStep);
          glVertex2f(sW - xbuf, yStep);
          DBG_fprintf(stderr, " - %g.\n", yStep);
          glEnd();
	}
    }

  glColor3fv(frame->fontRGB);
  glLineWidth(scale);

  /* We draw the frame around. */
  DBG_fprintf(stderr, "Extension Shade: frame actual size is %dx%d.\n",
              frame->width, frame->height);
  glBegin(GL_LINE_STRIP);
  glVertex2i(1, 1);
  glVertex2i(sW, 1);
  glVertex2i(sW, frame->height);
  glVertex2i(1, frame->height);
  glVertex2i(1, 1);
  glEnd();
  /* We draw the tics. */
  glBegin(GL_LINES);
  glVertex2i(sW    , 1);
  glVertex2i(sW + 3, 1);
  glVertex2i(sW    , frame->height / 3);
  glVertex2i(sW + 3, frame->height / 3);
  glVertex2i(sW    , 2 * frame->height / 3);
  glVertex2i(sW + 3, 2 * frame->height / 3);
  glVertex2i(sW    , frame->height);
  glVertex2i(sW + 3, frame->height);
  glEnd();
  
  /* We print the labels. */
  sprintf(value, "%.3g", get_inv(0.f, shade->priv->minMax));
  glRasterPos2i(sW + 5, 0);
  visu_gl_text_drawChars(value, VISU_GL_TEXT_NORMAL); 
  sprintf(value, "%.3g", get_inv(0.33333f, shade->priv->minMax));
  glRasterPos2i(sW + 5, frame->height / 3 - 5);
  visu_gl_text_drawChars(value, VISU_GL_TEXT_NORMAL); 
  sprintf(value, "%.3g", get_inv(0.66667f, shade->priv->minMax));
  glRasterPos2i(sW + 5, 2 * frame->height / 3 - 5);
  visu_gl_text_drawChars(value, VISU_GL_TEXT_NORMAL);
  sprintf(value, "%.3g", get_inv(1.f, shade->priv->minMax));
  glRasterPos2i(sW + 5, frame->height - 10);
  visu_gl_text_drawChars(value, VISU_GL_TEXT_NORMAL);
}
