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

	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 "neighbours.h"
#include <math.h>

/**
 * SECTION:neighbours
 * @short_description: node neighbours handling.
 *
 * <para>Define an object to store information about neighbours, see
 * visu_node_neighbours_new() and an iterator to run over neighbours.</para>
 */

struct _VisuNodeNeighboursPrivate
{
  gboolean dispose_has_run;

  /* The data the neighbours are computed from. */
  VisuData *data;
  /*gulong widthHeight_signal;*/

  gboolean dirty;
  gfloat factor;
  guint idMax;
  guint *keynei;
  GArray *nei;
};

enum
  {
    PROP_0,
    DATA_PROP,
    FACTOR_PROP,
    N_PROP
  };
static GParamSpec *properties[N_PROP];

static void visu_node_neighbours_dispose     (GObject* obj);
static void visu_node_neighbours_finalize    (GObject* obj);
static void visu_node_neighbours_get_property(GObject* obj, guint property_id,
                                         GValue *value, GParamSpec *pspec);
static void visu_node_neighbours_set_property(GObject* obj, guint property_id,
                                         const GValue *value, GParamSpec *pspec);

G_DEFINE_TYPE_WITH_CODE(VisuNodeNeighbours, visu_node_neighbours, VISU_TYPE_OBJECT,
                        G_ADD_PRIVATE(VisuNodeNeighbours))

static void visu_node_neighbours_class_init(VisuNodeNeighboursClass *klass)
{
  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->dispose  = visu_node_neighbours_dispose;
  G_OBJECT_CLASS(klass)->finalize = visu_node_neighbours_finalize;
  G_OBJECT_CLASS(klass)->set_property = visu_node_neighbours_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_node_neighbours_get_property;
  
  /**
   * VisuNodeNeighbours::data:
   *
   * The #VisuData the neighbour list is built for.
   *
   * Since: 3.8
   */
  properties[DATA_PROP] = g_param_spec_object("data", "Data",
                                              "the Data the neighbours are for",
                                              VISU_TYPE_DATA, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY);
  /**
   * VisuNodeNeighbours::factor:
   *
   * The additional percentage to add to the Bohr radii of elements.
   *
   * Since: 3.8
   */
  properties[FACTOR_PROP] = g_param_spec_float("factor", "Factor",
                                               "additional percentage on radii",
                                               0.f, 1.5f, 0.2f, G_PARAM_READWRITE);
  
  g_object_class_install_properties(G_OBJECT_CLASS(klass), N_PROP, properties);
}

static void visu_node_neighbours_init(VisuNodeNeighbours *nei)
{
  nei->priv = visu_node_neighbours_get_instance_private(nei);
  nei->priv->dispose_has_run = FALSE;

  nei->priv->dirty = TRUE;
  nei->priv->factor = .2f;
  nei->priv->keynei = (guint*)0;
  nei->priv->nei = g_array_new(FALSE, FALSE, sizeof(guint));
}

static void visu_node_neighbours_dispose(GObject* obj)
{
  VisuNodeNeighbours *nei;

  nei = VISU_NODE_NEIGHBOURS(obj);
  if (nei->priv->dispose_has_run)
    return;
  nei->priv->dispose_has_run = TRUE;

  if (nei->priv->data)
    g_object_unref(nei->priv->data);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_node_neighbours_parent_class)->dispose(obj);
}
static void visu_node_neighbours_finalize(GObject* obj)
{
  VisuNodeNeighbours *nei;

  nei = VISU_NODE_NEIGHBOURS(obj);
  g_return_if_fail(nei);

  g_free(nei->priv->keynei);
  g_array_unref(nei->priv->nei);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_node_neighbours_parent_class)->finalize(obj);
}
static void visu_node_neighbours_get_property(GObject* obj, guint property_id,
                                              GValue *value, GParamSpec *pspec)
{
  VisuNodeNeighbours *self = VISU_NODE_NEIGHBOURS(obj);

  switch (property_id)
    {
    case DATA_PROP:
      g_value_set_object(value, self->priv->data);
      break;
    case FACTOR_PROP:
      g_value_set_float(value, self->priv->factor);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_node_neighbours_set_property(GObject* obj, guint property_id,
                                         const GValue *value, GParamSpec *pspec)
{
  VisuNodeNeighbours *self = VISU_NODE_NEIGHBOURS(obj);
  GObject *dt;

  switch (property_id)
    {
    case DATA_PROP:
      dt = g_value_dup_object(value);
      if (dt)
        {
          self->priv->data = VISU_DATA(dt);
          /* Connect here to population signals. */
        }
      break;
    case FACTOR_PROP:
      self->priv->factor = g_value_get_float(value);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}

/**
 * visu_node_neighbours_new:
 * @data: a #VisuData object.
 *
 * Create an object to handle a set of neighbours for @data.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a newly created #VisuNodeNeighbours object.
 **/
VisuNodeNeighbours* visu_node_neighbours_new(VisuData *data)
{
  VisuNodeNeighbours *nei;

  nei = VISU_NODE_NEIGHBOURS(g_object_new(VISU_TYPE_NODE_NEIGHBOURS,
                                          "data", data, NULL));
  return nei;
}

static void _computeNeighbours(VisuNodeNeighbours *nei)
{
  VisuBox *box;
  VisuNodeArray *array;
  VisuNodeArrayIter iter, iter2;
  GArray **arr;
  float *rcuts;
  float factor, xyz[3], xyz2[3];
  int z_;

  nei->priv->dirty = FALSE;

  if (!nei->priv->data)
    return;

  box = visu_boxed_getBox(VISU_BOXED(nei->priv->data));
  array = VISU_NODE_ARRAY(nei->priv->data);
  visu_node_array_iter_new(array, &iter);
  nei->priv->idMax = iter.idMax + 1;

  nei->priv->keynei = g_realloc(nei->priv->keynei, sizeof(guint) * nei->priv->idMax * 2);
  g_array_set_size(nei->priv->nei, 0);
               
  factor = 1.f + nei->priv->factor;
  if (visu_box_getUnit(box) != TOOL_UNITS_UNDEFINED)
    factor *= tool_physic_getUnitValueInMeter(TOOL_UNITS_ANGSTROEM) /
      tool_physic_getUnitValueInMeter(visu_box_getUnit(box));
  rcuts = g_malloc(sizeof(float) * iter.nElements);
  for (visu_node_array_iterStart(array, &iter); iter.element;
       visu_node_array_iterNextElement(array, &iter, FALSE))
    {
      if (!tool_physic_getZFromSymbol(&z_, rcuts + iter.iElement, (float*)0,
                                      visu_element_getName(iter.element)))
        rcuts[iter.iElement] = 0.;
      else
        rcuts[iter.iElement] *= factor;
      DBG_fprintf(stderr, " | element %d -> rcut = %g (%g).\n",
                  iter.iElement, rcuts[iter.iElement], factor);
    }

  arr = g_malloc(sizeof(GArray*) * nei->priv->idMax);
  for (visu_node_array_iterStart(array, &iter); iter.node;
       visu_node_array_iterNext(array, &iter))
    arr[iter.node->number] = g_array_new(FALSE, FALSE, sizeof(guint));
  for (visu_node_array_iterStart(array, &iter); iter.node;
       visu_node_array_iterNext(array, &iter))
    {
      visu_data_getNodePosition(nei->priv->data, iter.node, xyz);
      iter2 = iter;
      for (visu_node_array_iterNext(array, &iter2);
           iter2.node; visu_node_array_iterNext(array, &iter2))
        {
          visu_data_getNodePosition(nei->priv->data, iter2.node, xyz2);
          xyz2[0] -= xyz[0];
          xyz2[1] -= xyz[1];
          xyz2[2] -= xyz[2];
          visu_box_getPeriodicVector(box, xyz2);
          if (xyz2[0] * xyz2[0] + xyz2[1] * xyz2[1] + xyz2[2] * xyz2[2] <
              (rcuts[iter.iElement] + rcuts[iter2.iElement]) *
              (rcuts[iter.iElement] + rcuts[iter2.iElement]))
            {
              g_array_append_val(arr[iter.node->number], iter2.node->number);
              g_array_append_val(arr[iter2.node->number], iter.node->number);
            }
        }
    }
  for (visu_node_array_iterStart(array, &iter); iter.node;
       visu_node_array_iterNext(array, &iter))
    {
      nei->priv->keynei[2 * iter.node->number + 0] = nei->priv->nei->len;
      nei->priv->keynei[2 * iter.node->number + 1] = arr[iter.node->number]->len;
      DBG_fprintf(stderr, " - node #%d -> %d\n", iter.node->number,
                  arr[iter.node->number]->len);
      g_array_append_vals(nei->priv->nei,
                          arr[iter.node->number]->data,
                          arr[iter.node->number]->len);
      g_array_free(arr[iter.node->number], TRUE);
    }
  g_free(rcuts);
  g_free(arr);
}

/**
 * visu_node_neighbours_iter:
 * @nei: a #VisuNodeNeighbours object to iterate on.
 * @iter: (out caller-allocates): a #VisuNodeNeighboursIter structure.
 * @nodeId: the node id to obtain neighbours of.
 *
 * Initialise @iter to iterate over the neighbours of node @nodeId.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the iterator is valid.
 **/
gboolean visu_node_neighbours_iter(VisuNodeNeighbours *nei,
                                   VisuNodeNeighboursIter *iter, guint nodeId)
{
  g_return_val_if_fail(VISU_IS_NODE_NEIGHBOURS(nei) && iter, FALSE);

  iter->nodeId = nodeId;
  iter->nei = nei;
  iter->index = 0;

  return visu_node_neighbours_iter_next(iter);
}
/**
 * visu_node_neighbours_iter_next:
 * @iter: a #VisuNodeNeighboursIter iterator.
 *
 * Look to the next neighbour, see visu_node_neighbours_iter().
 *
 * Since: 3.8
 *
 * Returns: TRUE if the iterator is valid.
 **/
gboolean visu_node_neighbours_iter_next(VisuNodeNeighboursIter *iter)
{
  g_return_val_if_fail(iter, FALSE);
  
  if (iter->nei->priv->dirty)
    _computeNeighbours(iter->nei);

  if (!iter->nei->priv->keynei || !iter->nei->priv->nei ||
      iter->nodeId >= iter->nei->priv->idMax)
    return FALSE;

  iter->nnei = iter->nei->priv->keynei[2 * iter->nodeId + 1];
  if (iter->index >= iter->nnei)
    return FALSE;

  iter->neiId =
    g_array_index(iter->nei->priv->nei, guint,
                  iter->nei->priv->keynei[2 * iter->nodeId + 0] + iter->index);
  iter->index += 1;

  return TRUE;
}
/**
 * visu_node_neighbours_iter___iter__:
 * @iter: a #VisuNodeNeighboursIter structure.
 * @out: (out caller-allocates): a #VisuNodeNeighboursIter structure.
 *
 * Used for Python binding only.
 *
 * Since: 3.8
 **/
void visu_node_neighbours_iter___iter__(const VisuNodeNeighboursIter *iter,
                                        VisuNodeNeighboursIter *out)
{
  *out = *iter;
  out->index = 0;
}

static int _closeTo(const VisuSurfacePoint *pt, VisuSurfaceDefinition *def,
                    const int offsets[3], const gfloat ref[3])
{
  gfloat d2, dRef;
  VisuSurfacePoint *pt2;
  VisuSurfacePoly *poly;
  guint i, j, k, n;
  guint matches[27];
  
  dRef = (ref[0] - pt->at[0]) * (ref[0] - pt->at[0]) +
    (ref[1] - pt->at[1]) * (ref[1] - pt->at[1]) +
    (ref[2] - pt->at[2]) * (ref[2] - pt->at[2]);
  n = 0;
  for (i = 0; i < 3; i++)
    if (offsets[i] >= 0)
      {
        for (j = 0; j < 3; j++)
          {
            poly = &g_array_index(def->polys, VisuSurfacePoly, offsets[i] + j);
            for (k = 0; k < 3; k++)
              {
                pt2 = &g_array_index(def->points, VisuSurfacePoint, poly->indices[k]);
                d2 = (pt2->at[0] - pt->at[0]) * (pt2->at[0] - pt->at[0]) +
                  (pt2->at[1] - pt->at[1]) * (pt2->at[1] - pt->at[1]) +
                  (pt2->at[2] - pt->at[2]) * (pt2->at[2] - pt->at[2]);
                if (d2 < 0.1f * dRef)
                  matches[n++] = poly->indices[k];
              }
          }
      }

  if (!n)
    return -1;

  for (i = 1; i < n; i++)
    g_array_index(def->points, VisuSurfacePoint, matches[i]) =
      g_array_index(def->points, VisuSurfacePoint, matches[0]);
  return matches[0];
}

static int _addSurfaceAt(VisuNodeNeighbours *nei, VisuNode *node,
                         VisuSurfaceDefinition *def, float refNrm[3],
                         VisuNodeProperty *done)
{
  VisuNodeNeighboursIter iter;
  gboolean valid;
  float scal, ref;
  float xyzM[3], xyz[3][3];
  float A[3][3], B[3], inv[3][3], out[3];
  guint i, j1, j2, offset, poffset;
  int pid[3];
  int poffsets[3];
  VisuSurfacePoint pt;
  VisuSurfacePoly poly;
  GValue val = G_VALUE_INIT;

  g_return_val_if_fail(VISU_IS_NODE_NEIGHBOURS(nei), 0);

  visu_data_getNodePosition(nei->priv->data, node, xyzM);

  valid = visu_node_neighbours_iter(nei, &iter, node->number);
  DBG_fprintf(stderr, "Visu Neighbours: node id %d has %d neighbours.\n",
              node->number, iter.nnei);
  if (!valid || iter.nnei < 3)
    return 0;

  g_return_val_if_fail(def, 0);

  g_value_init(&val, G_TYPE_INT);
  poffsets[0] = 0;
  poffsets[1] = 0;
  poffsets[2] = 0;
  /* Try to find three neighbours more or less orthogonal to the
     refNrm. */
  ref = sqrt(refNrm[0] * refNrm[0] + refNrm[1] * refNrm[1] + refNrm[2] * refNrm[2]);
  for (i = 0; valid && i < 3; valid = visu_node_neighbours_iter_next(&iter))
    {
      node = visu_node_array_getFromId(VISU_NODE_ARRAY(nei->priv->data), iter.neiId);
      if (done)
        {
          visu_node_property_getValue(done, node, &val);
          poffsets[i] = g_value_get_int(&val) - 1;
        }
      visu_data_getNodePosition(nei->priv->data, node, xyz[i]);
      scal = ABS((xyz[i][0] - xyzM[0]) * refNrm[0] +
                 (xyz[i][1] - xyzM[1]) * refNrm[1] +
                 (xyz[i][2] - xyzM[2]) * refNrm[2]) / ref;
      scal /= sqrt((xyz[i][0] - xyzM[0]) * (xyz[i][0] - xyzM[0]) +
                   (xyz[i][1] - xyzM[1]) * (xyz[i][1] - xyzM[1]) +
                   (xyz[i][2] - xyzM[2]) * (xyz[i][2] - xyzM[2]));
      if (ref == 0.f || scal < 0.1)
        i += 1;
    }
  if (i != 3)
    return 0;

  /* Add this node. */
  pt.at[0] = xyzM[0];
  pt.at[1] = xyzM[1];
  pt.at[2] = xyzM[2];
  pt.normal[0] = (xyz[1][1] - xyz[0][1]) * (xyz[2][2] - xyz[0][2]) -
    (xyz[1][2] - xyz[0][2]) * (xyz[2][1] - xyz[0][1]);
  pt.normal[1] = (xyz[1][2] - xyz[0][2]) * (xyz[2][0] - xyz[0][0]) -
    (xyz[1][0] - xyz[0][0]) * (xyz[2][2] - xyz[0][2]);
  pt.normal[2] = (xyz[1][0] - xyz[0][0]) * (xyz[2][1] - xyz[0][1]) -
    (xyz[1][1] - xyz[0][1]) * (xyz[2][0] - xyz[0][0]);
  if (ref == 0.f)
    {
      refNrm[0] = pt.normal[0];
      refNrm[1] = pt.normal[1];
      refNrm[2] = pt.normal[2];
    }
  else if (refNrm[0] * pt.normal[0] +
           refNrm[1] * pt.normal[1] +
           refNrm[2] * pt.normal[2] < 0.f)
    {
      pt.normal[0] = -pt.normal[0];
      pt.normal[1] = -pt.normal[1];
      pt.normal[2] = -pt.normal[2];
    }
  offset = def->points->len;
  g_array_append_val(def->points, pt);

  /* Dealing with neighbour i. */
  for (i = 0; i < 3; i++)
    {
      j1 = (i + 1) % 3; /* First half-way plane. */
      A[0][0] = xyz[j1][0] - xyzM[0];
      A[0][1] = xyz[j1][1] - xyzM[1];
      A[0][2] = xyz[j1][2] - xyzM[2];
      B[0] =
        A[0][0] * (xyz[j1][0] + xyzM[0]) / 2.f +
        A[0][1] * (xyz[j1][1] + xyzM[1]) / 2.f +
        A[0][2] * (xyz[j1][2] + xyzM[2]) / 2.f;

      j2 = (i + 2) % 3; /* Second half-way plane. */
      A[1][0] = xyz[j2][0] - xyzM[0];
      A[1][1] = xyz[j2][1] - xyzM[1];
      A[1][2] = xyz[j2][2] - xyzM[2];
      B[1] =
        A[1][0] * (xyz[j2][0] + xyzM[0]) / 2.f +
        A[1][1] * (xyz[j2][1] + xyzM[1]) / 2.f +
        A[1][2] * (xyz[j2][2] + xyzM[2]) / 2.f;

      /* In-plane */
      A[2][0] = (xyz[j1][1] - xyzM[1]) * (xyz[j2][2] - xyzM[2]) -
        (xyz[j1][2] - xyzM[2]) * (xyz[j2][1] - xyzM[1]);
      A[2][1] = (xyz[j1][2] - xyzM[2]) * (xyz[j2][0] - xyzM[0]) -
        (xyz[j1][0] - xyzM[0]) * (xyz[j2][2] - xyzM[2]);
      A[2][2] = (xyz[j1][0] - xyzM[0]) * (xyz[j2][1] - xyzM[1]) -
        (xyz[j1][1] - xyzM[1]) * (xyz[j2][0] - xyzM[0]);
      B[2] = A[2][0] * xyzM[0] + A[2][1] * xyzM[1] + A[2][2] * xyzM[2];

      tool_matrix_invert(inv, A);
      tool_matrix_productVector(out, inv, B);
      pt.at[0] = out[0];
      pt.at[1] = out[1];
      pt.at[2] = out[2];

      /* Try to attach the new point to one of already computed for
         the neighbours. */
      pid[i] = _closeTo(&pt, def, poffsets, xyzM);
      if (pid[i] < 0)
        {
          pt.normal[0] = A[2][0];
          pt.normal[1] = A[2][1];
          pt.normal[2] = A[2][2];
          if (refNrm[0] * A[2][0] + refNrm[1] * A[2][1] + refNrm[2] * A[2][2] < 0.f)
            {
              pt.normal[0] = -pt.normal[0];
              pt.normal[1] = -pt.normal[1];
              pt.normal[2] = -pt.normal[2];
            }
          pid[i] = def->points->len;
          g_array_append_val(def->points, pt);
        }
    }
  poffset = def->polys->len;
  poly.nvertices = 3;
  poly.indices[0] = offset;
  poly.indices[1] = pid[0];
  poly.indices[2] = pid[1];
  g_array_append_val(def->polys, poly);
  poly.indices[1] = pid[1];
  poly.indices[2] = pid[2];
  g_array_append_val(def->polys, poly);
  poly.indices[1] = pid[2];
  poly.indices[2] = pid[0];
  g_array_append_val(def->polys, poly);

  return poffset + 1;
}
/**
 * visu_node_neighbours_getSurfaceAt:
 * @nei: a #VisuNodeNeighbours object.
 * @nodeId: a node number.
 * @def: (out caller-allocates): a place to store points and polys.
 *
 * Generate a surface definition around atom @nodeId.
 *
 * Since: 3.8
 *
 * Returns: TRUE if @def is generated.
 **/
gboolean visu_node_neighbours_getSurfaceAt(VisuNodeNeighbours *nei, guint nodeId,
                                           VisuSurfaceDefinition *def)
{
  float nrm[3];

  g_return_val_if_fail(def, FALSE);

  def->points = g_array_sized_new(FALSE, FALSE, sizeof(VisuSurfacePoint), 4);
  def->polys  = g_array_sized_new(FALSE, FALSE, sizeof(VisuSurfacePoly), 3);

  nrm[0] = 0.f;
  nrm[1] = 0.f;
  nrm[2] = 0.f;
  return (_addSurfaceAt(nei, visu_node_array_getFromId(VISU_NODE_ARRAY(nei->priv->data), nodeId), def, nrm, (VisuNodeProperty*)0) != FALSE);
}
static void _addSurfaceFrom(VisuNodeNeighbours *nei, VisuNodeProperty *done,
                            VisuNode *node, VisuSurfaceDefinition *def, float refNrm[3])
{
  VisuNodeNeighboursIter iter;
  int offset;
  gboolean valid;
  GValue val = G_VALUE_INIT;

  g_value_init(&val, G_TYPE_INT);
  visu_node_property_getValue(done, node, &val);
  if (g_value_get_int(&val) == 0 && (offset = _addSurfaceAt(nei, node, def, refNrm, done)))
    {
      g_value_set_int(&val, offset);
      visu_node_property_setValue(done, node, &val);
      for (valid = visu_node_neighbours_iter(nei, &iter, node->number);
           valid; valid = visu_node_neighbours_iter_next(&iter))
        _addSurfaceFrom(nei, done,
                        visu_node_array_getFromId(VISU_NODE_ARRAY(nei->priv->data),
                                                  iter.neiId), def, refNrm);
    }
}
/**
 * visu_node_neighbours_getSurfaceFrom:
 * @nei: a #VisuNodeNeighbours object.
 * @nodeId: a node id.
 * @def: (out caller-allocates): a place to store points and polys.
 *
 * Generate a surface definition around atom @nodeId and all its neighbours.
 *
 * Since: 3.8
 *
 * Returns: TRUE if there is any generated surface.
 **/
gboolean visu_node_neighbours_getSurfaceFrom(VisuNodeNeighbours *nei, guint nodeId,
                                             VisuSurfaceDefinition *def)
{
  VisuNodeProperty *done;
  float nrm[3];

  g_return_val_if_fail(def, FALSE);

  done = visu_node_array_property_newInteger(VISU_NODE_ARRAY(nei->priv->data),
                                             "_NeighboursDone");

  def->points = g_array_new(FALSE, FALSE, sizeof(VisuSurfacePoint));
  def->polys  = g_array_new(FALSE, FALSE, sizeof(VisuSurfacePoly));

  nrm[0] = 0.f;
  nrm[1] = 0.f;
  nrm[2] = 0.f;
  _addSurfaceFrom(nei, done, visu_node_array_getFromId(VISU_NODE_ARRAY(nei->priv->data), nodeId), def, nrm);

  if (!def->points->len || !def->polys->len)
    {
      g_array_free(def->points, TRUE);
      g_array_free(def->polys, TRUE);
      return FALSE;
    }
  return TRUE;
}
