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

	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 Documentation/licence.en.txt.
*/

#include "vectorProp.h"
#include <coreTools/toolMatrix.h>
#include <coreTools/toolPhysic.h>

#include <math.h>

/**
 * SECTION:vectorProp
 * @short_description: define a #VisuNodeValues object to handle
 * vectorial node information.
 *
 * <para>Defines a #VisuNodeValues object to store a vector
 * information on nodes. One can set and retrieve vector on each node
 * as cartesian (see visu_node_values_vector_setAt() or
 * visu_node_values_vector_getAt() functions) or spherical coordinates
 * (see visu_node_values_vector_setAtSpherical() and
 * visu_node_values_vector_getAtSpherical() functions).</para>
 */

static gboolean _setAt(VisuNodeValues *vals, const VisuNode *node,
                       GValue *value);
static gfloat _nrm2(const VisuNodeValuesFarray *vect, const GValue *value);
static void _shift(const VisuNodeValuesVector *vect, const VisuNode *node,
                   gfloat dxyz[3]);
static gboolean _parse(VisuNodeValues *vals, VisuNode *node, const gchar *from);
static gchar* _serialize(const VisuNodeValues *vals, const VisuNode *node);


G_DEFINE_TYPE(VisuNodeValuesVector, visu_node_values_vector, VISU_TYPE_NODE_VALUES_FARRAY)

static void visu_node_values_vector_class_init(VisuNodeValuesVectorClass *klass)
{
  /* Connect the overloading methods. */
  VISU_NODE_VALUES_CLASS(klass)->setAt = _setAt;
  VISU_NODE_VALUES_CLASS(klass)->parse = _parse;
  VISU_NODE_VALUES_CLASS(klass)->serialize = _serialize;
  VISU_NODE_VALUES_FARRAY_CLASS(klass)->nrm2 = _nrm2;
  klass->shift = _shift;
}

static void visu_node_values_vector_init(VisuNodeValuesVector *self _U_)
{
}

static gfloat _nrm2(const VisuNodeValuesFarray *vect _U_, const GValue *value)
{
  gfloat *diff;

  diff = (gfloat*)g_value_get_pointer(value);
  if (diff)
    return diff[3] * diff[3];
  else
    return -1.f;
}
static gboolean _parse(VisuNodeValues *vals, VisuNode *node, const gchar *from)
{
  gfloat fvals[6];
  gchar **datas;
  guint i;
  GValue value = {0, {{0}, {0}}};

  g_return_val_if_fail(from, FALSE);

  datas = g_strsplit_set(from, "(;)", 3);
  for (i = 0; datas[i]; i++)
    if (sscanf(from, "%f", fvals + i) != 1)
      {
        g_strfreev(datas);
        return FALSE;
      }
  g_strfreev(datas);
  g_value_init(&value, G_TYPE_POINTER);
  g_value_set_pointer(&value, fvals);
  return _setAt(vals, node, &value);
}
static gchar* _serialize(const VisuNodeValues *vals, const VisuNode *node)
{
  GValue value = {0, {{0}, {0}}};
  float *fvals;

  if (!visu_node_values_getAt(vals, node, &value))
    return (gchar*)0;

  fvals = (float*)g_value_get_pointer(&value);
  if (fvals)
    return g_strdup_printf("(%#.3g ; %#.3g ; %#.3g)", fvals[0], fvals[1], fvals[2]);
  else
    return (gchar*)0;
}

/**
 * visu_node_values_vector_new:
 * @arr: a #VisuNodeArray object.
 * @label: a translatable label.
 *
 * Create a new vector field located on nodes.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a newly created #VisuNodeValuesVector object.
 **/
VisuNodeValuesVector* visu_node_values_vector_new(VisuNodeArray *arr,
                                                  const gchar *label)
{
  VisuNodeValuesVector *vals;

  vals = VISU_NODE_VALUES_VECTOR(g_object_new(VISU_TYPE_NODE_VALUES_VECTOR,
                                              "nodes", arr, "label", label,
                                              "type", G_TYPE_FLOAT,
                                              "n-elements", 6, NULL));
  return vals;
}

static const gfloat zeros[3] = {0.f, 0.f, 0.f};
/**
 * visu_node_values_vector_getAt:
 * @vect: a #VisuNodeValuesVector object.
 * @node: a #VisuNode object.
 *
 * Retrieves the vector hosted on @node.
 *
 * Since: 3.8
 *
 * Returns: (array fixed-size=3) (transfer none): the coordinates of
 * vector for @node.
 **/
const gfloat* visu_node_values_vector_getAt(const VisuNodeValuesVector *vect,
                                            const VisuNode *node)
{
  GValue diffValue = G_VALUE_INIT;
  const gfloat *diff;

  g_return_val_if_fail(VISU_IS_NODE_VALUES_VECTOR(vect), zeros);

  visu_node_values_getAt(VISU_NODE_VALUES(vect), node, &diffValue);
  diff = (const gfloat*)g_value_get_pointer(&diffValue);
  return (diff) ? diff : zeros;
}
/**
 * visu_node_values_vector_getAtSpherical:
 * @vect: a #VisuNodeValuesVector object.
 * @node: a #VisuNode object.
 *
 * Retrieves the vector hosted on @node in spherical coordinates.
 *
 * Since: 3.8
 *
 * Returns: (array fixed-size=3) (allow-none): the spherical coordinates.
 **/
const gfloat* visu_node_values_vector_getAtSpherical(const VisuNodeValuesVector *vect,
                                                     const VisuNode *node)
{
  GValue diffValue = G_VALUE_INIT;
  const gfloat *diff;

  g_return_val_if_fail(VISU_IS_NODE_VALUES_VECTOR(vect), FALSE);

  visu_node_values_getAt(VISU_NODE_VALUES(vect), node, &diffValue);
  diff = (const gfloat*)g_value_get_pointer(&diffValue);
  if (!diff)
    return (const gfloat*)0;

  return diff + 3;
}
/**
 * visu_node_values_vector_getAtIterSpherical:
 * @vect: a #VisuNodeValuesVector object.
 * @iter: a #VisuNodeValuesIter object.
 *
 * Retrieves the vector hosted on @iter in spherical coordinates.
 *
 * Since: 3.8
 *
 * Returns: (array fixed-size=3) (allow-none): the spherical coordinates.
 **/
const gfloat* visu_node_values_vector_getAtIterSpherical(const VisuNodeValuesVector *vect,
                                                         const VisuNodeValuesIter *iter)
{
  const gfloat *diff;

  g_return_val_if_fail(VISU_IS_NODE_VALUES_VECTOR(vect) && iter, (const gfloat*)0);                      

  diff = (const gfloat*)g_value_get_pointer(&iter->value);
  if (!diff)
    return (const gfloat*)0;

  return diff + 3;
}
static void _shift(const VisuNodeValuesVector *vect _U_, const VisuNode *node _U_,
                   gfloat dxyz[3])
{
  dxyz[0] = 0.f;
  dxyz[1] = 0.f;
  dxyz[2] = 0.f;
}
/**
 * visu_node_values_vector_getShift:
 * @vect: a #VisuNodeValuesVector object.
 * @node: a #VisuNode pointer.
 * @dxyz: (out caller-allocates) (array fixed-size=3): a vector
 * location.
 *
 * Get the shift value that is applied to every vector of @vect. 
 *
 * Since: 3.8
 **/
void visu_node_values_vector_getShift(const VisuNodeValuesVector *vect,
                                      const VisuNode *node, gfloat dxyz[3])
{
  VisuNodeValuesVectorClass *klass = VISU_NODE_VALUES_VECTOR_GET_CLASS(vect);

  g_return_if_fail(klass && klass->shift);
  klass->shift(vect, node, dxyz);
}

static gboolean _setAt(VisuNodeValues *vect, const VisuNode *node,
                       GValue *value)
{  
  gfloat *vals;
  gboolean res;

  vals = (gfloat*)g_value_get_pointer(value);
  if (vals[3] == G_MAXFLOAT)
    tool_matrix_cartesianToSpherical(vals + 3, vals);
  else
    tool_matrix_sphericalToCartesian(vals, vals + 3);
  
  /* Chain up to parent. */
  res = VISU_NODE_VALUES_CLASS(visu_node_values_vector_parent_class)->setAt(vect, node, value);

  return res;
}
/**
 * visu_node_values_vector_setAt:
 * @vect: a #VisuNodeValuesVector object.
 * @node: a #VisuNode object.
 * @dxyz: (array fixed-size=3): vector coordinates.
 *
 * Changes the vector hosted at @node for one of coordinates defined
 * by @dxyz.
 *
 * Since: 3.8
 *
 * Returns: TRUE if vector for @node is indeed changed.
 **/
gboolean visu_node_values_vector_setAt(VisuNodeValuesVector *vect,
                                       const VisuNode *node,
                                       const gfloat dxyz[3])
{
  gfloat *vals, diff[6];
  GValue diffValue = G_VALUE_INIT;

  visu_node_values_getAt(VISU_NODE_VALUES(vect), node, &diffValue);
  vals = (gfloat*)g_value_get_pointer(&diffValue);
  if (vals && vals[0] == dxyz[0] && vals[1] == dxyz[1] && vals[2] == dxyz[2])
    return FALSE;

  diff[0] = dxyz[0];
  diff[1] = dxyz[1];
  diff[2] = dxyz[2];
  diff[3] = G_MAXFLOAT;
  g_value_set_pointer(&diffValue, (gpointer)diff);
  return visu_node_values_setAt(VISU_NODE_VALUES(vect), node, &diffValue);
}
/**
 * visu_node_values_vector_setAtDbl:
 * @vect: a #VisuNodeValuesVector object.
 * @node: a #VisuNode object.
 * @dxyz: (array fixed-size=3): vector coordinates.
 *
 * Same as visu_node_values_vector_setAt() but for double values.
 *
 * Since: 3.8
 *
 * Returns: TRUE if vector for @node is indeed changed.
 **/
gboolean visu_node_values_vector_setAtDbl(VisuNodeValuesVector *vect,
                                          const VisuNode *node,
                                          const double dxyz[3])
{
  gfloat fxyz[3];

  fxyz[0] = dxyz[0];
  fxyz[1] = dxyz[1];
  fxyz[2] = dxyz[2];
  return visu_node_values_vector_setAt(vect, node, fxyz);
}
/**
 * visu_node_values_vector_setAtSpherical:
 * @vect: a #VisuNodeValuesVector object.
 * @node: a #VisuNode object.
 * @sph: (array fixed-size=3): spherical coordinates.
 *
 * Same as visu_node_values_vector_setAt() but using a spherical
 * coordinate description.
 *
 * Since: 3.8
 *
 * Returns: TRUE if vector for @node is indeed changed.
 **/
gboolean visu_node_values_vector_setAtSpherical(VisuNodeValuesVector *vect,
                                                const VisuNode *node,
                                                const gfloat sph[3])
{
  gfloat *vals, diff[6];
  GValue diffValue = G_VALUE_INIT;

  visu_node_values_getAt(VISU_NODE_VALUES(vect), node, &diffValue);
  vals = (gfloat*)g_value_get_pointer(&diffValue);
  if (vals && vals[3] == sph[0] && vals[4] == sph[1] && vals[5] == sph[2])
    return FALSE;

  diff[0] = G_MAXFLOAT;
  diff[3] = sph[0];
  diff[4] = sph[1];
  diff[5] = sph[2];
  g_value_set_pointer(&diffValue, (gpointer)diff);
  return visu_node_values_setAt(VISU_NODE_VALUES(vect), node, &diffValue);
}
/**
 * visu_node_values_vector_set:
 * @vect: a #VisuNodeValuesVector object.
 * @data: (element-type float): some vector coordinates.
 *
 * Assigns the coordinates stored in @data to each nodes in @vect.
 *
 * Since: 3.8
 *
 * Returns: TRUE if @data has the same size as @vect.
 **/
gboolean visu_node_values_vector_set(VisuNodeValuesVector *vect,
                                     const GArray *data)
{
  guint i;
  gboolean valid;
  VisuNodeValuesIter iter;

  g_object_freeze_notify(G_OBJECT(vect));

  i = 0;
  valid = visu_node_values_iter_new(&iter, ITER_NODES_BY_NUMBER,
                                    VISU_NODE_VALUES(vect));
  while (valid && i + 3 <= data->len)
    {
      visu_node_values_vector_setAt(vect, iter.iter.node,
                                    &g_array_index(data, float, i));
      i += 3;
      valid = visu_node_values_iter_next(&iter);
    }

  g_object_thaw_notify(G_OBJECT(vect));

  return (i == data->len);
}
