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

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

/**
 * SECTION:planes
 * @short_description: Draw a list of #VisuPlane.
 *
 * <para>This extension draws a list of #VisuPlane. Planes are
 * outlined with a black line and also the intersections of planes.</para>
 *
 * Since: 3.7
 */

/**
 * VisuGlExtPlanesClass:
 * @parent: the parent class;
 *
 * A short way to identify #_VisuGlExtPlanesClass structure.
 *
 * Since: 3.7
 */
/**
 * VisuGlExtPlanes:
 *
 * An opaque structure.
 *
 * Since: 3.7
 */
/**
 * VisuGlExtPlanesPrivate:
 *
 * Private fields for #VisuGlExtPlanes objects.
 *
 * Since: 3.7
 */
struct _VisuGlExtPlanesPrivate
{
  gboolean dispose_has_run;

  VisuBox *box;
};

typedef struct _PlaneHandleStruct
{
  gulong move_signal, rendering_signal;
} _PlaneHandle;

static void visu_gl_ext_planes_dispose(GObject* obj);
static void visu_gl_ext_planes_rebuild(VisuGlExt *ext);
static void visu_gl_ext_planes_draw(VisuGlExt *planes);

/* Local callbacks. */
static void onSetChanged(VisuGlExt *ext);
static void onPlaneMoved(VisuGlExt *ext, VisuPlane *plane);
static void onPlaneRendering(VisuGlExt *ext);

/* Local routines. */
static void _freePlaneHandle(VisuPlane *plane, gpointer obj)
{
  _PlaneHandle *phd;

  phd = (_PlaneHandle*)obj;
  g_signal_handler_disconnect(G_OBJECT(plane), phd->move_signal);
  g_signal_handler_disconnect(G_OBJECT(plane), phd->rendering_signal);
#if GLIB_MINOR_VERSION > 9
  g_slice_free1(sizeof(_PlaneHandle), obj);
#else
  g_free(obj);
#endif
}
static gpointer _newPlaneHandle(VisuPlane *plane, gpointer data)
{
  _PlaneHandle *phd;

#if GLIB_MINOR_VERSION > 9
  phd = g_slice_alloc(sizeof(_PlaneHandle));
#else
  phd = g_malloc(sizeof(_PlaneHandle));
#endif
  phd->move_signal = g_signal_connect_swapped(G_OBJECT(plane), "moved",
                                              G_CALLBACK(onPlaneMoved), data);
  phd->rendering_signal = g_signal_connect_swapped(G_OBJECT(plane), "rendering",
                                                   G_CALLBACK(onPlaneRendering), data);
  return (gpointer)phd;
}

G_DEFINE_TYPE_WITH_CODE(VisuGlExtPlanes, visu_gl_ext_planes, VISU_TYPE_GL_EXT,
                        G_ADD_PRIVATE(VisuGlExtPlanes))

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

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->dispose  = visu_gl_ext_planes_dispose;
  VISU_GL_EXT_CLASS(klass)->rebuild = visu_gl_ext_planes_rebuild;
  VISU_GL_EXT_CLASS(klass)->draw = visu_gl_ext_planes_draw;
}

static void visu_gl_ext_planes_init(VisuGlExtPlanes *obj)
{
  DBG_fprintf(stderr, "Extension Planes: initializing a new object (%p).\n",
	      (gpointer)obj);
  
  obj->priv = visu_gl_ext_planes_get_instance_private(obj);
  obj->priv->dispose_has_run = FALSE;

  obj->priv->box = (VisuBox*)0;

  /* Private data. */
  obj->planes = visu_plane_set_newFull(_newPlaneHandle, _freePlaneHandle, (gpointer)obj);
  g_signal_connect_object(G_OBJECT(obj->planes), "added",
                          G_CALLBACK(onSetChanged), obj, G_CONNECT_SWAPPED);
  g_signal_connect_object(G_OBJECT(obj->planes), "removed",
                          G_CALLBACK(onSetChanged), obj, G_CONNECT_SWAPPED);
  g_object_bind_property(obj, "active", obj->planes, "masking", G_BINDING_SYNC_CREATE);
}

/* This method can be called several times.
   It should unref all of its reference to
   GObjects. */
static void visu_gl_ext_planes_dispose(GObject* obj)
{
  VisuGlExtPlanes *planes;

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

  planes = VISU_GL_EXT_PLANES(obj);
  if (planes->priv->dispose_has_run)
    return;
  planes->priv->dispose_has_run = TRUE;

  g_object_unref(planes->planes);
  visu_gl_ext_planes_setBox(planes, (VisuBox*)0);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_gl_ext_planes_parent_class)->dispose(obj);
}

/**
 * visu_gl_ext_planes_new:
 * @name: (allow-none): the name to give to the extension (default is #VISU_GL_EXT_PLANES_ID).
 *
 * Creates a new #VisuGlExt to draw a list of planes.
 *
 * Since: 3.7
 *
 * Returns: a pointer to the #VisuGlExt it created or
 * NULL otherwise.
 */
VisuGlExtPlanes* visu_gl_ext_planes_new(const gchar *name)
{
  char *name_ = VISU_GL_EXT_PLANES_ID;
  char *description = _("Draw some planes.");
#define PLANES_HEIGHT 30

  DBG_fprintf(stderr,"Extension Planes: new object.\n");
  
  return g_object_new(VISU_TYPE_GL_EXT_PLANES,
                      "name", (name)?name:name_, "label", _(name),
                      "description", description,
                      "nGlObj", 1, "priority", VISU_GL_EXT_PRIORITY_NORMAL + 1, NULL);
}

/**
 * visu_gl_ext_planes_setBox:
 * @ext: a #VisuGlExtPlanes object.
 * @box: a #VisuBox object.
 *
 * Apply @box on every plane rendered by @ext.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the box is actually changed.
 **/
gboolean visu_gl_ext_planes_setBox(VisuGlExtPlanes *ext, VisuBox *box)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_PLANES(ext), FALSE);

  DBG_fprintf(stderr, "Extension Planes: set box %p.\n", (gpointer)box);

  if (ext->priv->box == box)
    return FALSE;

  if (ext->priv->box)
    g_object_unref(ext->priv->box);
  ext->priv->box = box;
  if (!box)
    return TRUE;

  g_object_ref(box);
  visu_boxed_setBox(VISU_BOXED(ext->planes), VISU_BOXED(box));

  return TRUE;
}

static void visu_gl_ext_planes_rebuild(VisuGlExt *ext)
{
  visu_gl_ext_setDirty(ext, TRUE);
  visu_gl_ext_planes_draw(ext);
}

static void onSetChanged(VisuGlExt *ext)
{
  DBG_fprintf(stderr, "Extension Planes: caught added/removed signals on model.\n");
  visu_gl_ext_setDirty(ext, TRUE);
}
static void onPlaneMoved(VisuGlExt *ext, VisuPlane *plane)
{
  DBG_fprintf(stderr, "Extension Planes: caught 'plane moved' signal (%d).\n",
              visu_plane_getRendered(plane));
  if (visu_plane_getRendered(plane))
    visu_gl_ext_setDirty(ext, TRUE);
}
static void onPlaneRendering(VisuGlExt *ext)
{
  visu_gl_ext_setDirty(ext, TRUE);
}

static void visu_plane_draw(VisuPlane* plane)
{
  GList *inter, *tmpLst;
  const ToolColor *color;

  if (!visu_boxed_getBox(VISU_BOXED(plane)))
    return;

  inter = visu_plane_getIntersection(plane);
  if (inter && visu_plane_getRendered(plane))
    {
      DBG_fprintf(stderr, " | plane %p\n", (gpointer)plane);
      glLineWidth(1.f);
      glColor4f(0.f, 0.f, 0.f, visu_plane_getOpacity(plane));
      glBegin(GL_LINE_LOOP);
      for (tmpLst = inter; tmpLst; tmpLst = g_list_next(tmpLst))
        glVertex3fv((float*)tmpLst->data);
      glEnd();

      glDisable(GL_CULL_FACE);

      color = visu_plane_getColor(plane);
      glColor4f(color->rgba[0], color->rgba[1], color->rgba[2],
                MIN(visu_plane_getOpacity(plane), color->rgba[3]));
      glBegin(GL_POLYGON);
      for (tmpLst = inter; tmpLst; tmpLst = g_list_next(tmpLst))
        glVertex3fv((float*)tmpLst->data);
      glEnd();

      glEnable(GL_CULL_FACE);
      glCullFace(GL_BACK);
    }
}
static void visu_gl_ext_planes_draw(VisuGlExt *ext)
{
  float A[3], B[3];
  VisuGlExtPlanes *planes = VISU_GL_EXT_PLANES(ext);
  VisuPlaneSetIter iter, iter2;

  g_return_if_fail(VISU_IS_GL_EXT_PLANES(ext));

  glDeleteLists(visu_gl_ext_getGlList(ext), 1);
  visu_gl_ext_setDirty(ext, FALSE);

  if (!planes)
    return;

  visu_gl_ext_startDrawing(ext);

  /* Set blend if not present. */
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glDisable(GL_LIGHTING);
  glDisable(GL_DITHER);

  glLineWidth(1.f);
  glBegin(GL_LINES);
  DBG_fprintf(stderr, "VisuPlane: intersection list of planes %p.\n",
              (gpointer)planes);
  visu_plane_set_iter_new(planes->planes, &iter);
  for (visu_plane_set_iter_next(&iter); iter.plane; visu_plane_set_iter_next(&iter))
    for (iter2 = iter, visu_plane_set_iter_next(&iter2);
         iter2.plane; visu_plane_set_iter_next(&iter2))
      if (visu_plane_getRendered(iter.plane) &&
          visu_plane_getRendered(iter2.plane) &&
          visu_plane_getPlaneIntersection(iter.plane, iter2.plane, A, B))
        {
          glColor4f(0.f, 0.f, 0.f, MAX(visu_plane_getOpacity(iter.plane),
                                       visu_plane_getOpacity(iter2.plane)));
          glVertex3fv(A);
          glVertex3fv(B);
        }
  glEnd();

  DBG_fprintf(stderr, "VisuPlane: drawing list of planes %p.\n",
              (gpointer)planes);
  visu_plane_set_iter_new(planes->planes, &iter);
  for (visu_plane_set_iter_next(&iter); iter.plane; visu_plane_set_iter_next(&iter))
    if (visu_plane_getColor(iter.plane)->rgba[3] == 1.f &&
        visu_plane_getOpacity(iter.plane) == 1.f)
      visu_plane_draw(iter.plane);
  visu_plane_set_iter_new(planes->planes, &iter);
  for (visu_plane_set_iter_next(&iter); iter.plane; visu_plane_set_iter_next(&iter))
    if (visu_plane_getColor(iter.plane)->rgba[3] < 1.f ||
        visu_plane_getOpacity(iter.plane) < 1.f)
      visu_plane_draw(iter.plane);

  glEnable(GL_LIGHTING);
  glEnable(GL_DITHER); /* WARNING: it is the default! */

  visu_gl_ext_completeDrawing(ext);
}
