/* See {salamic_slicer_trivial.h} */
/* Last edited on 2015-10-16 18:03:04 by stolfilocal */

#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <math.h>

#include <bool.h>
#include <vec.h>
#include <affirm.h>

#include <stmesh.h>
#include <salamic_slicer.h>
#include <salamic_closer.h>
#include <salamic_stats.h>

#include <salamic_slicer_trivial.h>

/* ??? Replace the vec {PlaneZ} by separate {np} and {pZ} ??? */

void salamic_slicer_trivial_slice
  ( stmesh_t mesh,
    int_vec_t *planeZ, 
    char *closer, 
    char *outPrefix, 
    salamic_stats_t *st
  )
  {
    uint32_t nf = stmesh_face_count(mesh);   /* Number of faces (triangles) in {mesh}. */
    uint32_t np = planeZ->ne; /* Number of slicing planes. */
    float eps = stmesh_get_eps(mesh);
    bool_t verbose = TRUE;
    
    /* The faces that intercept the plane: */
    stmesh_face_t *f = notnull(malloc(nf*sizeof(stmesh_face_t)), "no mem");
    
    /* Enumerate the slicing planes: */
    uint32_t ixp;
    for (ixp = 0; ixp < np; ixp++)
      { int32_t pZ = planeZ->e[ixp];
        uint32_t ns = 0; /* Number of faces abschnitt by this plane. */
        /* Enumerate the mesh faces: */
        stmesh_face_unx_t uxf;
        for (uxf = 0; uxf < nf; uxf++)
          { stmesh_face_t fk = stmesh_get_face(mesh, uxf); /*Current face.*/
            /*Does the plane intersect the face?:*/
            int32_t fminZ, fmaxZ;
            stmesh_face_get_zrange(fk, &fminZ, &fmaxZ);
            if ((fminZ < pZ) && (fmaxZ > pZ)) 
              { /* Save triangle index: */
                f[ns] = fk;
                ns++;
              }
          }
             
        if (verbose)
          { fprintf(stderr, "plane %4u at %+11d (%+.8f mm) - %u intersections\n", ixp, pZ, pZ*(double)eps, ns); }
          
        if (strcmp(closer, "NONE") != 0)
          { salamic_closer_close(mesh, pZ, ns, f, closer, outPrefix, st); }
      }
    /* Free the face vector: */
    free(f);
  }
