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

	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 "cylinder_renderer.h"
#include "iface_cylinder.h"

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

#include <opengl.h>
#include <renderingMethods/elementAtomic.h>

/**
 * SECTION:cylinder_renderer
 * @short_description: a class to render #VisuPairLink as cylinders.
 *
 * <para>This class is used to render #VisuPairLink as cylinders.</para>
 */

struct _ElementRenderer
{
  VisuElementRenderer *ele;
  gulong mat_sig, col_sig, siz_sig;
};

struct _NodeColorizer
{
  VisuDataColorizer *colorizer;
  gulong dirty_sig;
};

struct _VisuPairCylinderRendererPrivate
{
  gboolean dispose_has_run;

  guint nlat;
  gfloat radius;
  GLUquadricObj *obj;

  struct _NodeColorizer nodes;
  struct _ElementRenderer ele1;
  struct _ElementRenderer ele2;

  VisuGlView *view;
  gulong detail_signal;
};

static void visu_pair_cylinder_renderer_dispose(GObject* obj);

static void _start(VisuPairLinkRenderer *self, VisuPairLink *data,
                   VisuElementRenderer *ele1, VisuElementRenderer *ele2,
                   VisuDataColorizer *colorizer);
static void _stop(VisuPairLinkRenderer *self, VisuPairLink *data);
static void _draw(VisuPairLinkRenderer *self, const VisuPairLinkIter *iter);
static gboolean _set_view(VisuPairLinkRenderer *renderer, VisuGlView *view);
static void _setElementRenderer(VisuPairCylinderRenderer *self,
                                struct _ElementRenderer *ele,
                                VisuElementRenderer *renderer);
static void _setNodeColorizer(VisuPairCylinderRenderer *self,
                              struct _NodeColorizer *node,
                              VisuDataColorizer *colorizer);

enum
  {
    PROP_0,
    ID_PROP,
    LABEL_PROP,
    DESCR_PROP,
    N_PROP
  };

G_DEFINE_TYPE_WITH_CODE(VisuPairCylinderRenderer, visu_pair_cylinder_renderer, VISU_TYPE_PAIR_LINK_RENDERER,
                        G_ADD_PRIVATE(VisuPairCylinderRenderer))

static void visu_pair_cylinder_renderer_class_init(VisuPairCylinderRendererClass *klass)
{
  DBG_fprintf(stderr, "Visu Cylinder Renderer: creating the class of the object.\n");

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->dispose = visu_pair_cylinder_renderer_dispose;
  VISU_PAIR_LINK_RENDERER_CLASS(klass)->start = _start;
  VISU_PAIR_LINK_RENDERER_CLASS(klass)->stop = _stop;
  VISU_PAIR_LINK_RENDERER_CLASS(klass)->draw = _draw;
  VISU_PAIR_LINK_RENDERER_CLASS(klass)->set_view = _set_view;
}
static void visu_pair_cylinder_renderer_init(VisuPairCylinderRenderer *obj)
{
  DBG_fprintf(stderr, "Visu Cylinder Renderer: initializing a new object (%p).\n",
	      (gpointer)obj);

  obj->priv = visu_pair_cylinder_renderer_get_instance_private(obj);

  obj->priv->dispose_has_run = FALSE;
  obj->priv->ele1.ele = (VisuElementRenderer*)0;
  obj->priv->ele2.ele = (VisuElementRenderer*)0;
  obj->priv->view = (VisuGlView*)0;
}
static void visu_pair_cylinder_renderer_dispose(GObject* obj)
{
  VisuPairCylinderRenderer *data;

  data = VISU_PAIR_CYLINDER_RENDERER(obj);
  if (data->priv->dispose_has_run)
    return;
  data->priv->dispose_has_run = TRUE;

  _set_view(VISU_PAIR_LINK_RENDERER(data), (VisuGlView*)0);
  _setNodeColorizer(data, &data->priv->nodes, (VisuDataColorizer*)0);
  _setElementRenderer(data, &data->priv->ele1, (VisuElementRenderer*)0);
  _setElementRenderer(data, &data->priv->ele2, (VisuElementRenderer*)0);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_pair_cylinder_renderer_parent_class)->dispose(obj);
}
/**
 * visu_pair_cylinder_renderer_new:
 *
 * The default renderer to draw linsk as cylinders.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): the default #VisuPairCylinderRenderer object.
 */
VisuPairCylinderRenderer* visu_pair_cylinder_renderer_new()
{
  return VISU_PAIR_CYLINDER_RENDERER(g_object_new(VISU_TYPE_PAIR_CYLINDER_RENDERER, "id", "Cylinder pairs", "label", _("Cylinder pairs"), "description", _("Pairs are rendered by cylinders."
                                                                                                                                                           " The color and the width can by chosen."), NULL));
}

static void _setElementRenderer(VisuPairCylinderRenderer *self,
                                struct _ElementRenderer *ele,
                                VisuElementRenderer *renderer)
{
  if (ele->ele == renderer)
    return;

  if (ele->ele)
    {
      g_signal_handler_disconnect(ele->ele, ele->mat_sig);
      g_signal_handler_disconnect(ele->ele, ele->col_sig);
      g_signal_handler_disconnect(ele->ele, ele->siz_sig);
      g_object_unref(ele->ele);
    }
  ele->ele = renderer;
  if (renderer)
    {
      g_object_ref(renderer);
      ele->mat_sig = g_signal_connect_swapped(renderer, "notify::material",
                                              G_CALLBACK(visu_pair_link_renderer_emitDirty), self);
      ele->col_sig = g_signal_connect_swapped(renderer, "notify::color",
                                              G_CALLBACK(visu_pair_link_renderer_emitDirty), self);
      ele->siz_sig = g_signal_connect_swapped(renderer, "size-changed",
                                              G_CALLBACK(visu_pair_link_renderer_emitDirty), self);
    }
}

static void _setNodeColorizer(VisuPairCylinderRenderer *self,
                              struct _NodeColorizer *node,
                              VisuDataColorizer *colorizer)
{
  if (node->colorizer == colorizer)
    return;

  if (node->colorizer)
    {
      g_signal_handler_disconnect(node->colorizer, node->dirty_sig);
      g_object_unref(node->colorizer);
    }
  node->colorizer = colorizer;
  if (colorizer)
    {
      g_object_ref(colorizer);
      node->dirty_sig = g_signal_connect_swapped(colorizer, "dirty",
                                                 G_CALLBACK(visu_pair_link_renderer_emitDirty), self);
    }
}

static void _start(VisuPairLinkRenderer *self, VisuPairLink *data,
                   VisuElementRenderer *ele1, VisuElementRenderer *ele2,
                   VisuDataColorizer *colorizer)
{
  VisuPairCylinderRenderer *renderer;
  VisuPairCylinderColorId id;

  renderer = VISU_PAIR_CYLINDER_RENDERER(self);

  renderer->priv->radius = visu_pair_cylinder_getRadius(VISU_PAIR_CYLINDER(data));
  renderer->priv->nlat = visu_gl_view_getDetailLevel(renderer->priv->view,
                                                     renderer->priv->radius);

  id = visu_pair_cylinder_getColorType(VISU_PAIR_CYLINDER(data));
  if (id == VISU_CYLINDER_COLOR_ELEMENT || id == VISU_CYLINDER_COLOR_NODE)
    {
      _setElementRenderer(renderer, &renderer->priv->ele1, ele1);
      _setElementRenderer(renderer, &renderer->priv->ele2, ele2);
    }
  else
    {
      _setElementRenderer(renderer, &renderer->priv->ele1, (VisuElementRenderer*)0);
      _setElementRenderer(renderer, &renderer->priv->ele2, (VisuElementRenderer*)0);
    }
  if (id == VISU_CYLINDER_COLOR_NODE)
    {
      _setNodeColorizer(renderer, &renderer->priv->nodes, colorizer);
    }
  else
    {
      _setNodeColorizer(renderer, &renderer->priv->nodes, (VisuDataColorizer*)0);
    }

  renderer->priv->obj = gluNewQuadric();
}

static void _stop(VisuPairLinkRenderer *self, VisuPairLink *data _U_)
{
  gluDeleteQuadric(VISU_PAIR_CYLINDER_RENDERER(self)->priv->obj);
}

static void _setElementColor(VisuElementRenderer *ele, float coeff)
{
  const ToolColor *color;
  float rgba[4];

  color = visu_element_renderer_getColor(ele);
  rgba[0] = color->rgba[0];
  rgba[1] = color->rgba[1];
  rgba[2] = color->rgba[2];
  rgba[3] = coeff * color->rgba[3];
  visu_gl_setColor((VisuGl*)0, visu_element_renderer_getMaterial(ele), rgba);
}

static void _setNodeColor(VisuElementRenderer *ele, VisuDataColorizer *colorizer,
                          float coeff, VisuData *data, VisuNode *node)
{
  const ToolColor *color;
  float rgba[4];

  if (!colorizer || !visu_data_colorizer_getColor(colorizer, rgba, data, node))
    {
      color = visu_element_renderer_getColor(ele);
      rgba[0] = color->rgba[0];
      rgba[1] = color->rgba[1];
      rgba[2] = color->rgba[2];
      rgba[3] = color->rgba[3];
    }
  rgba[3] *= coeff;
  visu_gl_setColor((VisuGl*)0, visu_element_renderer_getMaterial(ele), rgba);
}

static void _draw(VisuPairLinkRenderer *self, const VisuPairLinkIter *iter)
{
  float rgba[4], mm[5] = {0.5, 0.5, 0., 0. , 0.};
  const ToolColor *color;
  double vNorm[3]; /* vecteur normal aux vecteurs (0,0,1) et (x2-x1, y2-y1, z2-z1) */
  double phi;
  #define RADTODEG 57.29577951
  VisuPairCylinderRenderer *renderer;
  gfloat tSize, ratio, d;

  renderer = VISU_PAIR_CYLINDER_RENDERER(self);

  d = sqrt(iter->d2);
  if (iter->dxyz[0] != 0 || iter->dxyz[1] != 0)
    {
      vNorm[0] = - iter->dxyz[1];
      vNorm[1] = iter->dxyz[0];
      vNorm[2] = 0.;
      phi = acos(CLAMP(iter->dxyz[2] / d, -1., 1.)) * RADTODEG;
    }
  else
    {
      vNorm[0] = 1.;
      vNorm[1] = 0.;
      vNorm[2] = 0.;
      if (iter->dxyz[2] < 0.)
	phi = 180.;
      else
	phi = 0.;
    }
  glPushMatrix();
  switch (visu_pair_cylinder_getColorType(VISU_PAIR_CYLINDER(iter->parent)))
    {
    case VISU_CYLINDER_COLOR_USER:
      /* Color is set by the _start() method
         before for this family of pairs, we change need to change it
         because of alpha. */
      color = visu_pair_link_getColor(iter->parent);
      rgba[0] = color->rgba[0];
      rgba[1] = color->rgba[1];
      rgba[2] = color->rgba[2];
      rgba[3] = iter->coeff * color->rgba[3];
      visu_gl_setColor((VisuGl*)0, mm, rgba);

      glTranslated(iter->xyz1[0], iter->xyz1[1], iter->xyz1[2]);
      glRotated(phi, vNorm[0], vNorm[1], vNorm[2]);
      gluCylinder(renderer->priv->obj, renderer->priv->radius, renderer->priv->radius,
		  (GLdouble)d * ((iter->periodic) ? 0.5 : 1.),
                  (GLint)renderer->priv->nlat, (GLint)1);
      if (iter->periodic)
        {
          glTranslated(0, 0, d * 0.5);
          gluDisk(renderer->priv->obj, 0, renderer->priv->radius*1.03,
                  renderer->priv->nlat, 1);      
          glPopMatrix();
          glPushMatrix();
          glTranslated(iter->xyz2[0], iter->xyz2[1], iter->xyz2[2]);
          glRotated(phi - 180., vNorm[0], vNorm[1], vNorm[2]);
          gluCylinder(renderer->priv->obj, renderer->priv->radius, renderer->priv->radius,
                      (GLdouble)d * 0.5,
                      (GLint)renderer->priv->nlat, (GLint)1);
          glTranslated(0, 0, d * 0.5);
          gluDisk(renderer->priv->obj, 0, renderer->priv->radius*1.03,
                  renderer->priv->nlat, 1);      
        }
      break;
    case VISU_CYLINDER_COLOR_ELEMENT:
    case VISU_CYLINDER_COLOR_NODE:
      tSize = visu_element_renderer_getExtent(renderer->priv->ele1.ele) +
        visu_element_renderer_getExtent(renderer->priv->ele2.ele);
      ratio = visu_element_renderer_getExtent(renderer->priv->ele1.ele) / tSize;
      glTranslated(iter->xyz1[0], iter->xyz1[1], iter->xyz1[2]);
      glRotated(phi, vNorm[0], vNorm[1], vNorm[2]);
      if (visu_pair_cylinder_getColorType(VISU_PAIR_CYLINDER(iter->parent)) ==
          VISU_CYLINDER_COLOR_ELEMENT)
        _setElementColor(renderer->priv->ele1.ele, iter->coeff);
      else
        _setNodeColor(renderer->priv->ele1.ele, renderer->priv->nodes.colorizer,
                      iter->coeff, iter->data, iter->iter1.node);
      gluCylinder(renderer->priv->obj, renderer->priv->radius, renderer->priv->radius,
		  (GLdouble)d * ratio, (GLint)renderer->priv->nlat, (GLint)1);
      if (!iter->periodic)
        {
          glPopMatrix();
          glPushMatrix();
          glTranslated(iter->xyz1[0] + ratio * iter->dxyz[0],
                       iter->xyz1[1] + ratio * iter->dxyz[1],
                       iter->xyz1[2] + ratio * iter->dxyz[2]);
          glRotated(phi, vNorm[0], vNorm[1], vNorm[2]);
        }
      else
        {
          glPopMatrix();
          glPushMatrix();
          glTranslated(iter->xyz2[0], iter->xyz2[1], iter->xyz2[2]);
          glRotated(phi - 180., vNorm[0], vNorm[1], vNorm[2]);
        }
      if (visu_pair_cylinder_getColorType(VISU_PAIR_CYLINDER(iter->parent)) ==
          VISU_CYLINDER_COLOR_ELEMENT)
        _setElementColor(renderer->priv->ele2.ele, iter->coeff);
      else
        _setNodeColor(renderer->priv->ele2.ele, renderer->priv->nodes.colorizer,
                      iter->coeff, iter->data, iter->iter2.node);
      gluCylinder(renderer->priv->obj, renderer->priv->radius, renderer->priv->radius,
                  (GLdouble)d * (1.f - ratio), (GLint)renderer->priv->nlat, (GLint)1);
      break;
    default:
      break;
    }
  glPopMatrix();
}

static gboolean _set_view(VisuPairLinkRenderer *renderer, VisuGlView *view)
{
  VisuPairCylinderRenderer *self;

  g_return_val_if_fail(VISU_IS_PAIR_CYLINDER_RENDERER(renderer), FALSE);

  self = VISU_PAIR_CYLINDER_RENDERER(renderer);

  if (self->priv->view == view)
    return FALSE;

  if (self->priv->view)
    {
      g_signal_handler_disconnect(G_OBJECT(self->priv->view), self->priv->detail_signal);
      g_object_unref(self->priv->view);
    }
  if (view)
    {
      g_object_ref(view);
      self->priv->detail_signal =
        g_signal_connect_swapped(G_OBJECT(view), "DetailLevelChanged",
                                 G_CALLBACK(visu_pair_link_renderer_emitDirty), (gpointer)self);
    }

  self->priv->view = view;
  return TRUE;
}
