/*-------------------------------------------------------------------------------------------
  
  File        : mcf_levelsets3D.cpp

  Description : Implementation of the Mean Curvature Flow on Surfaces
                using the framework of Level Sets 3D.

  Copyright  : David Tschumperle - http://www.greyc.ensicaen.fr/~dtschump/

  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". 

  As a counterpart to the access to the source code and  rights to copy,
  modify and redistribute granted by the license, users are provided only
  with a limited warranty  and the software's author,  the holder of the
  economic rights,  and the successive licensors  have only  limited
  liability. 

  In this respect, the user's attention is drawn to the risks associated
  with loading,  using,  modifying and/or developing or reproducing the
  software by the user in light of its specific status of free software,
  that may mean  that it is complicated to manipulate,  and  that  also
  therefore means  that it is reserved for developers  and  experienced
  professionals having in-depth computer knowledge. Users are therefore
  encouraged to load and test the software's suitability as regards their
  requirements in conditions enabling the security of their systems and/or 
  data to be ensured and,  more generally, to use and operate it in the 
  same conditions as regards security. 

  The fact that you are presently reading this means that you have had
  knowledge of the CeCILL license and that you accept its terms.

-----------------------------------------------------------------------------------------*/

#include "../CImg.h"
using namespace cimg_library;
// The lines below are necessary for compilation with non-standart C++ compilers.
#if (( defined(_MSC_VER) && _MSC_VER<=1200 ) || defined(__DMC__))
#define std
#endif

// Apply the 3D Eikonal PDE used to init and re-init distance function
//---------------------------------------------------------------------
template<typename T> 
CImg<T>& eikonal_PDE(CImg<T>& img, const unsigned int nb_iter=10,
		     const float dt=1, const float narrow=4.0f) {
  CImg<T> veloc(img.dimx(),img.dimy(),img.dimz(),img.dimv());
  CImg_3x3x3(I,float);
  for (unsigned int iter=0; iter<nb_iter; iter++) {
    cimg_map3x3x3(img,x,y,z,0,I) if (cimg::abs(Iccc)<narrow && Iccc*Incc>0 && Iccc*Ipcc>0 && Iccc*Icnc>0 && Iccc*Icpc>0 && Iccc*Iccp>0 && Iccc*Iccn>0) {
      const float
	gx = 0.5f*(Incc-Ipcc),
	gy = 0.5f*(Icnc-Icpc),
	gz = 0.5f*(Iccn-Iccp),
	sgn = -(float)cimg::sign(Iccc),
	ix = (gx*sgn)>0?(Incc-Iccc):(Iccc-Ipcc),
	iy = (gy*sgn)>0?(Icnc-Iccc):(Iccc-Icpc),
	iz = (gz*sgn)>0?(Iccn-Iccc):(Iccc-Iccp),
	ng = (float)std::sqrt(gx*gx+gy*gy+gz*gz),
	ngx = ng>1e-5f?gx/ng:0,
	ngy = ng>1e-5f?gy/ng:0,
	ngz = ng>1e-5f?gz/ng:0;
      veloc(x,y,z) = (T)sgn*(ngx*ix + ngy*iy + ngz*iz - 1);
    } else veloc(x,y,z) = 0;
    const CImgStats stats(veloc,false);
    const double xdt = dt/cimg::max(cimg::abs(stats.min),cimg::abs(stats.max));
    img+=xdt*veloc;
  }
  return img;
}

// Apply the Mean curvature flow PDE
//-----------------------------------
template<typename T> CImg<T>& mcf_PDE(CImg<T>& img, const unsigned int nb_iter,
				      const float dt=0.25f, const float narrow=4.0f) {
  CImg<T> veloc(img.dimx(),img.dimy(),img.dimz(),img.dimv());
  CImg_3x3x3(I,float);
  for (unsigned int iter=0; iter<nb_iter; iter++) {
    cimg_map3x3x3(img,x,y,z,0,I) if (cimg::abs(Iccc)<narrow) {
      const float
	ix = 0.5f*(Incc-Ipcc),
	iy = 0.5f*(Icnc-Icpc),
	iz = 0.5f*(Iccn-Iccp),
	norm = (float)std::sqrt(1e-5f+ix*ix+iy*iy+iz*iz),
	ixx = Incc+Ipcc-2*Iccc,
	ixy = 0.25f*(Ippc+Innc-Inpc-Ipnc),
	ixz = 0.25f*(Ipcp+Incn-Incp-Ipcn),
	iyy = Icnc+Icpc-2*Iccc,	
	iyz = 0.25f*(Icpp+Icnn-Icnp-Icpn),
	izz = Iccn+Iccp-2*Iccc,
	a = ix/norm,
	b = iy/norm,
	c = iz/norm,
	inn = a*a*ixx + b*b*iyy + c*c*izz + 2*a*b*ixy + 2*a*c*ixz + 2*b*c*iyz;
      veloc(x,y,z) = ixx+iyy+izz-inn;
    } else veloc(x,y,z) = 0;
    const CImgStats stats(veloc,false);
    const double xdt = dt/cimg::max(cimg::abs(stats.min),cimg::abs(stats.max));
    img+=xdt*veloc;
  }
  return img;
}

// Main procedure
//----------------
int main(int argc,char **argv) {
  cimg_usage("Mean curvature flow of a surface, using 3D level sets");
  const char *file_i = cimg_option("-i",(char*)0,"Input image");
  const float dt = cimg_option("-dt",0.05f,"PDE Time step");
  const float narrow = cimg_option("-band",5.0f,"Size of the narrow band");
  const bool show = cimg_option("-both",false,"Show both evolving and initial surface");

  // Define the signed distance map of the initial surface
  CImg<> img;
  if (file_i) {
    const float sigma = cimg_option("-sigma",1.2f,"Segmentation regularity");
    const float alpha = cimg_option("-alpha",5.0f,"Region growing tolerance");
    img.load(file_i).channel(0);
    int s[6]; s[0]=-1;
    CImgDisplay disp(img,"Please select a starting point");
    while (s[0]<0) img.feature_selection(s,0,disp);
    CImg<> region;
    float tmp[1]={0};
    img.draw_fill(s[0],s[1],s[2],tmp,region,alpha);
    ((img = region.normalize(-1,1))*=-1).blur(sigma);
    
  }
  else { // Create synthetic implicit function
    img.assign(60,60,60);
    const float exte[1]={1}, inte[1]={-1};
    img.fill(*exte).draw_rectangle(15,15,15,45,45,45,inte).draw_rectangle(25,25,0,35,35,img.dimz()-1,exte).
      draw_rectangle(0,25,25,img.dimx()-1,35,35,exte).draw_rectangle(25,0,25,35,img.dimy()-1,35,exte);
  }
  eikonal_PDE(img,10,0.1f);

  // Compute corresponding surface triangularization by the marching cube algorithm (isovalue 0)
  CImgl<> points0;
  CImgl<unsigned int> faces0;
  if (show) img.marching_cubes(0,points0,faces0);
  const CImgl<unsigned char> colors0(faces0.size,CImg<unsigned char>::vector(100,200,255));
  const CImgl<> opacities0(faces0.size,1,1,1,1,0.2f);

  // Perform MCF evolution
  CImgDisplay disp(256,256,""), disp3d(512,512,"",0,2);
  float alpha = 0, beta = 0;
  for (unsigned int iter=0; !disp.is_closed && !disp3d.is_closed && disp.key!=cimg::keyESC && disp3d.key!=cimg::keyESC &&
	 disp.key!=cimg::keyQ && disp3d.key!=cimg::keyQ; iter++) {
    disp.set_title("3D implicit Function (iter. %u)",iter);
    disp3d.set_title("Mean curvature flow 3D - Isosurface (iter. %u)",iter);
    
    // Apply PDE on the distance function
    mcf_PDE(img,1,dt,narrow);                       // Do one iteration of mean curvature flow
    if (!(iter%10)) eikonal_PDE(img,1,0.5f,narrow); // Every 10 steps, do one iteration of distance function re-initialization
        
    // Compute surface triangularization by the marching cube algorithm (isovalue 0)
    CImgl<> points(points0), opacities(opacities0);
    CImgl<unsigned int> faces(faces0);
    CImgl<unsigned char> colors(colors0);
    img.marching_cubes(0,points,faces);
    opacities.insert(faces.size-colors.size,CImg<>::vector(1.0f));
    colors.insert(faces.size-colors.size,CImg<unsigned char>::vector(200,128,100));
    const float fact = 3*cimg::max(disp3d.dimx(),disp3d.dimy())/(4.0f*cimg::max(img.dimx(),img.dimy()));
    cimgl_map(points,l) { // center and rescale the object
      points[l](0)=(points[l](0)-img.dimx()/2)*fact;
      points[l](1)=(points[l](1)-img.dimy()/2)*fact;
      points[l](2)=(points[l](2)-img.dimz()/2)*fact; 
    }

    // Display 3D object on the display window.
    CImg<unsigned char> visu(disp3d.dimx(),disp3d.dimy(),1,3,0);
    const CImg<> rot = CImg<>::rotation_matrix(1,0,0,(beta+=0.01f))*CImg<>::rotation_matrix(0,1,1,(alpha+=0.05f));
    cimgl_map(points,ll) points[ll] = rot*points[ll];     
    visu.draw_object3d(visu.dimx()/2.0f,visu.dimy()/2.0f,0.0f,
		       points,faces,colors,opacities,3,
		       false,500.0,0.0f,0.0f,-8000.0f,0.02f).display(disp3d);
    img.display(disp.wait(20));

    if (disp3d.button || disp3d.key) { 
      unsigned char white[3]={ 255,255,255 };
      visu.fill(0).draw_text("Time stopped, press any key to start again",10,10,white).
	display_object3d(points,faces,colors,opacities,disp3d);
      disp3d.key = 0; 
    }
    if (disp.is_resized)   disp.resize(false);
    if (disp3d.is_resized) disp3d.resize(false);
  }
  
  // Exit    
  return 0;
}
