/*-------------------------------------------------------------------------------------------
  
  File        : image_surface.cpp

  Description : This tool allows to show an image as a 3D surface

  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

// Main procedure
//----------------
int main(int argc,char **argv) {

  // Read command line arguments
  cimg_usage("Render an image as a surface");
  const char *file_i = cimg_option("-i","img/logo.ppm","Input image");
  const float sigma = cimg_option("-smooth",1.0f,"Amount of image smoothing");  
  const float ratioz = cimg_option("-z",0.25f,"Aspect ratio along z-axis");
  const unsigned int di = cimg_option("-di",10,"Step for isophote skipping");

  // Init data
  std::fprintf(stderr,"\n- Load file '%s'",cimg::basename(file_i)); std::fflush(stderr);
  const CImg<unsigned char> img = CImg<>(file_i).blur(sigma).resize(-100,-100,1,3);
  const CImg<unsigned char> norm = img.get_norm_pointwise().normalize(0,255);
  CImg<> points, isopoints;
  CImgl<unsigned int> primitives, isoprimitives;
  CImgl<unsigned char> colors, isocolors;

  // Compute surface with isophotes
  std::fprintf(stderr,"\n- Compute isophotes"); std::fflush(stderr);
  CImgl<> lpoints;
  for (unsigned int i=0; i<255; i+=di) norm.marching_squares((float)i,lpoints,isoprimitives);
  cimgl_map(isoprimitives,l) {
    const unsigned int i0 = isoprimitives(l,0);
    const float x0 = lpoints(i0,0), y0 = lpoints(i0,1);
    const unsigned char
      r = (unsigned char)img.linear_pix2d(x0,y0,0),
      g = (unsigned char)img.linear_pix2d(x0,y0,1),
      b = (unsigned char)img.linear_pix2d(x0,y0,2);
    isocolors.insert(CImg<unsigned char>::vector(r,g,b));
  }
  isopoints = lpoints.get_append('x').resize(-100,3,1,1,0);
  cimg_mapX(isopoints,ll) isopoints(ll,2) = -ratioz*norm.linear_pix2d(isopoints(ll,0),isopoints(ll,1));

  // Compute surface with triangles
  std::fprintf(stderr,"\n- Create image surface"); std::fflush(stderr);
  const unsigned int w = img.width+1, h = img.height+1;
  points.assign(w*h,3);
  cimg_mapXY(img,x,y) {
    points(x+y*w,0) = points(x+1+y*w,0) = points(x+1+(y+1)*w,0) = points(x+(y+1)*w,0) = (float)x;
    points(x+y*w,1) = points(x+1+y*w,1) = points(x+1+(y+1)*w,1) = points(x+(y+1)*w,1) = (float)y;
    points(x+y*w,2) = points(x+1+y*w,2) = points(x+1+(y+1)*w,2) = points(x+(y+1)*w,2) = -ratioz*norm(x,y);
    const unsigned int
      i0 = x + y*w, i1 = (x+1) + y*w,
      i2 = (x+1) + (y+1)*w, i3 = x + (y+1)*w;
    primitives.insert(CImg<unsigned int>::vector(i0,i1,i2,i3));
    const unsigned char
      r = (unsigned char)img(x,y,0),
      g = (unsigned char)img(x,y,1),
      b = (unsigned char)img(x,y,2);	  
    colors.insert(CImg<unsigned char>::vector(r,g,b));
  }
    
  // Enter event loop
  std::fprintf(stderr,
	       "\n- Enter interactive loop.\n\n"
	       "Reminder : \n"
	       " + Use mouse to rotate and zoom object\n"
	       " + key 'F' : Toggle fullscreen\n"
	       " + key 'Q' : Quit\n"
	       " + Any other key : Change rendering type\n\n"); std::fflush(stderr);
  const char *const title = "Image viewed as a surface";
  CImgDisplay disp(800,600,title,0);
  unsigned int rtype = 2;
  CImg<float> pose = CImg<float>::identity_matrix(4);

  while (!disp.is_closed) {    
    const unsigned char white[3]={255,255,255};
    CImg<unsigned char> visu(disp.dimx(), disp.dimy(),1,3,0);
    visu.draw_text(10,10,white,0,19,1.0f,"Render : %s",
		rtype==0?"Points":(rtype==1?"Lines":(rtype==2?"Faces":(rtype==3?"Flat-shaded faces":
	       (rtype==4?"Gouraud-shaded faces":(rtype==5?"Phong-shaded faces":"Isophotes"))))));
    if (rtype==6) visu.display_object3d(isopoints,isoprimitives,isocolors,disp,true,1,-1,true,500.0f,0.05f,1.0f,true,pose.ptr());
    else visu.display_object3d(points,primitives,colors,disp,true,rtype,-1,true,500.0f,0.05f,1.0f,true,pose.ptr());
    switch (disp.key) {
    case 0: break;
    case cimg::keyBACKSPACE: rtype = (7+rtype-1)%7; break;
    case cimg::keyQ:
    case cimg::keyESC: disp.close(); break;
    case cimg::keyF: 
      if (disp.is_fullscreen) disp.resize(800,600); else disp.resize(disp.screen_dimx(),disp.screen_dimy());
      disp.toggle_fullscreen();
      break;
    default: rtype = (rtype+1)%7; break;
    }
  }
  
  return 0;
}
