소스 검색

Merge branch 'master' of https://github.com/libigl/libigl

Conflicts:
	tutorial/607_LIM/main.cpp

Former-commit-id: 2bae5b6002557235224942acb717a312d5ee1d22
schuellc 11 년 전
부모
커밋
96d0f0f75c
100개의 변경된 파일6089개의 추가작업 그리고 1932개의 파일을 삭제
  1. 2 1
      .gitignore
  2. 759 0
      include/igl/angle_bound_frame_fields.cpp
  3. 61 0
      include/igl/angle_bound_frame_fields.h
  4. 1 0
      include/igl/bbw/bbw.cpp
  5. 5 7
      include/igl/column_to_quats.h
  6. 801 0
      include/igl/conjugate_frame_fields.cpp
  7. 61 0
      include/igl/conjugate_frame_fields.h
  8. 0 30
      include/igl/cross_field_missmatch.cpp
  9. 49 0
      include/igl/deform_skeleton.cpp
  10. 39 0
      include/igl/deform_skeleton.h
  11. 27 0
      include/igl/directed_edge_parents.cpp
  12. 32 0
      include/igl/directed_edge_parents.h
  13. 21 21
      include/igl/edge_topology.cpp
  14. 3 2
      include/igl/edge_topology.h
  15. 34 0
      include/igl/find.cpp
  16. 10 0
      include/igl/find.h
  17. 27 13
      include/igl/harmonic.cpp
  18. 11 5
      include/igl/harmonic.h
  19. 1 1
      include/igl/local_basis.cpp
  20. 498 0
      include/igl/n_polyvector.cpp
  21. 41 0
      include/igl/n_polyvector.h
  22. 58 0
      include/igl/nchoosek.cpp
  23. 38 0
      include/igl/nchoosek.h
  24. 35 0
      include/igl/polyroots.cpp
  25. 37 0
      include/igl/polyroots.h
  26. 33 4
      include/igl/project.cpp
  27. 19 4
      include/igl/project.h
  28. 2 2
      include/igl/readOBJ.cpp
  29. 1 0
      include/igl/unproject.h
  30. 183 0
      include/igl/viewer/OpenGL_shader.cpp
  31. 86 0
      include/igl/viewer/OpenGL_shader.h
  32. 485 0
      include/igl/viewer/OpenGL_state.cpp
  33. 115 0
      include/igl/viewer/OpenGL_state.h
  34. 3 1
      include/igl/viewer/TODOs.txt
  35. 118 0
      include/igl/viewer/TextRenderer.cpp
  36. 55 0
      include/igl/viewer/TextRenderer.h
  37. 102 1261
      include/igl/viewer/Viewer.cpp
  38. 28 459
      include/igl/viewer/Viewer.h
  39. 409 0
      include/igl/viewer/ViewerCore.cpp
  40. 134 0
      include/igl/viewer/ViewerCore.h
  41. 394 0
      include/igl/viewer/ViewerData.cpp
  42. 152 0
      include/igl/viewer/ViewerData.h
  43. 141 0
      include/igl/viewer/ViewerPlugin.h
  44. 2 2
      tutorial/101_FileIO/CMakeLists.txt
  45. 2 2
      tutorial/102_DrawMesh/CMakeLists.txt
  46. 2 2
      tutorial/103_Events/CMakeLists.txt
  47. 3 4
      tutorial/103_Events/main.cpp
  48. 2 2
      tutorial/104_Colors/CMakeLists.txt
  49. 5 12
      tutorial/104_Colors/main.cpp
  50. 2 2
      tutorial/105_Overlays/CMakeLists.txt
  51. 0 3
      tutorial/105_Overlays/main.cpp
  52. 2 2
      tutorial/106_Picking/CMakeLists.txt
  53. 4 2
      tutorial/106_Picking/main.cpp
  54. 2 2
      tutorial/201_Normals/CMakeLists.txt
  55. 1 1
      tutorial/201_Normals/main.cpp
  56. 2 2
      tutorial/202_GaussianCurvature/CMakeLists.txt
  57. 2 2
      tutorial/203_CurvatureDirections/CMakeLists.txt
  58. 1 1
      tutorial/203_CurvatureDirections/main.cpp
  59. 2 2
      tutorial/204_Gradient/CMakeLists.txt
  60. 1 1
      tutorial/204_Gradient/main.cpp
  61. 2 2
      tutorial/205_Laplacian/CMakeLists.txt
  62. 2 2
      tutorial/301_Slice/CMakeLists.txt
  63. 2 2
      tutorial/302_Sort/CMakeLists.txt
  64. 2 2
      tutorial/303_LaplaceEquation/CMakeLists.txt
  65. 1 1
      tutorial/303_LaplaceEquation/main.cpp
  66. 2 2
      tutorial/304_LinearEqualityConstraints/CMakeLists.txt
  67. 1 1
      tutorial/304_LinearEqualityConstraints/main.cpp
  68. 2 2
      tutorial/305_QuadraticProgramming/CMakeLists.txt
  69. 1 1
      tutorial/305_QuadraticProgramming/main.cpp
  70. 11 0
      tutorial/401_BiharmonicDeformation/CMakeLists.txt
  71. 121 0
      tutorial/401_BiharmonicDeformation/main.cpp
  72. 11 0
      tutorial/402_PolyharmonicDeformation/CMakeLists.txt
  73. 105 0
      tutorial/402_PolyharmonicDeformation/main.cpp
  74. 11 0
      tutorial/403_BoundedBiharmonicWeights/CMakeLists.txt
  75. 160 0
      tutorial/403_BoundedBiharmonicWeights/main.cpp
  76. 2 2
      tutorial/501_HarmonicParam/CMakeLists.txt
  77. 2 2
      tutorial/501_HarmonicParam/main.cpp
  78. 2 2
      tutorial/502_LSCMParam/CMakeLists.txt
  79. 2 2
      tutorial/502_LSCMParam/main.cpp
  80. 2 2
      tutorial/503_ARAPParam/CMakeLists.txt
  81. 2 2
      tutorial/503_ARAPParam/main.cpp
  82. 3 3
      tutorial/504_NRosyDesign/CMakeLists.txt
  83. 14 14
      tutorial/504_NRosyDesign/main.cpp
  84. 2 2
      tutorial/505_MIQ/CMakeLists.txt
  85. 41 8
      tutorial/505_MIQ/main.cpp
  86. 2 2
      tutorial/506_FrameField/CMakeLists.txt
  87. 10 10
      tutorial/506_FrameField/main.cpp
  88. 11 0
      tutorial/507_PolyVectorField/CMakeLists.txt
  89. 111 0
      tutorial/507_PolyVectorField/main.cpp
  90. 11 0
      tutorial/508_ConjugateField/CMakeLists.txt
  91. 157 0
      tutorial/508_ConjugateField/main.cpp
  92. 11 0
      tutorial/509_Planarization/CMakeLists.txt
  93. 113 0
      tutorial/509_Planarization/main.cpp
  94. 2 2
      tutorial/601_Serialization/CMakeLists.txt
  95. 1 1
      tutorial/601_Serialization/main.cpp
  96. 2 2
      tutorial/602_Matlab/CMakeLists.txt
  97. 1 1
      tutorial/602_Matlab/main.cpp
  98. 1 1
      tutorial/602_Matlab/run.sh
  99. 2 2
      tutorial/604_Triangle/CMakeLists.txt
  100. 2 2
      tutorial/605_Tetgen/CMakeLists.txt

+ 2 - 1
.gitignore

@@ -1,6 +1,6 @@
 # use glob syntax.
-scripts/change_name.sh
 syntax: glob
+scripts/change_name.sh
 *.o
 *.a
 *.dylib
@@ -62,5 +62,6 @@ tutorial/readme.html
 tutorial/*/build/*
 tutorial/*/Makefile
 external/glew/build
+external/glfw/build
 *buildXcode*
 tutorial/build*

+ 759 - 0
include/igl/angle_bound_frame_fields.cpp

@@ -0,0 +1,759 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#include <igl/angle_bound_frame_fields.h>
+#include <igl/edge_topology.h>
+#include <igl/local_basis.h>
+#include <igl/sparse.h>
+#include <igl/speye.h>
+#include <igl/slice.h>
+#include <igl/polyroots.h>
+#include <igl/colon.h>
+#include <Eigen/Sparse>
+
+#include <iostream>
+
+namespace igl {
+
+  template <typename DerivedV, typename DerivedF>
+  class AngleBoundFFSolverData
+  {
+    public:
+      const Eigen::PlainObjectBase<DerivedV> &V; int numV;
+      const Eigen::PlainObjectBase<DerivedF> &F; int numF;
+
+      Eigen::MatrixXi EV; int numE;
+      Eigen::MatrixXi F2E;
+      Eigen::MatrixXi E2F;
+      Eigen::VectorXd K;
+
+      Eigen::VectorXi isBorderEdge;
+      int numInteriorEdges;
+      Eigen::Matrix<int,Eigen::Dynamic,2> E2F_int;
+      Eigen::VectorXi indInteriorToFull;
+      Eigen::VectorXi indFullToInterior;
+
+      Eigen::PlainObjectBase<DerivedV> B1, B2, FN;
+
+      //laplacians
+      Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>> DDA, DDB;
+
+  private:
+    IGL_INLINE void computeLaplacians();
+    IGL_INLINE void computek();
+    IGL_INLINE void computeCoefficientLaplacian(int n, Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &D);
+    IGL_INLINE void precomputeInteriorEdges();
+
+public:
+      IGL_INLINE AngleBoundFFSolverData(const Eigen::PlainObjectBase<DerivedV> &_V,
+                                   const Eigen::PlainObjectBase<DerivedF> &_F);
+  };
+
+  template <typename DerivedV, typename DerivedF, typename DerivedO>
+  class AngleBoundFFSolver
+  {
+  public:
+    IGL_INLINE AngleBoundFFSolver(const AngleBoundFFSolverData<DerivedV, DerivedF> &_data,
+                                  const typename DerivedV::Scalar &_thetaMin = 30,
+                                 int _maxIter = 50,
+                                 const typename DerivedV::Scalar &_lambdaInit = 100,
+                                 const typename DerivedV::Scalar &_lambdaMultFactor = 1.01,
+                                const bool _doHardConstraints = false);
+    IGL_INLINE bool solve(const Eigen::VectorXi &isConstrained,
+                          const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+                          Eigen::PlainObjectBase<DerivedO> &output,
+                          typename DerivedV::Scalar *lambdaOut = NULL);
+
+  private:
+
+    const AngleBoundFFSolverData<DerivedV, DerivedF> &data;
+
+    //polyVF data
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> Acoeff, Bcoeff;
+    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2> pvU, pvV;
+    typename DerivedV::Scalar lambda;
+
+    //parameters
+    typename DerivedV::Scalar lambdaInit,lambdaMultFactor;
+    int maxIter;
+    typename DerivedV::Scalar thetaMin;
+    bool doHardConstraints;
+
+    typename DerivedV::Scalar computeAngle(const std::complex<typename DerivedV::Scalar> &u,
+                                           const std::complex<typename DerivedV::Scalar> &v);
+//    IGL_INLINE void computeAngles(Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> &angles);
+
+    IGL_INLINE int getNumOutOfBounds();
+
+    IGL_INLINE void rotateAroundBisector(const std::complex<typename DerivedV::Scalar> &uin,
+                         const std::complex<typename DerivedV::Scalar> &vin,
+                         const typename DerivedV::Scalar theta,
+                         std::complex<typename DerivedV::Scalar> &uout,
+                         std::complex<typename DerivedV::Scalar> &vout);
+
+    IGL_INLINE void localStep();
+
+    IGL_INLINE void globalStep(const Eigen::Matrix<int, Eigen::Dynamic, 1>  &isConstrained,
+                               const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Ak,
+                               const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Bk);
+
+    IGL_INLINE void minQuadWithKnownMini(const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &Q,
+                         const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &f,
+                         const Eigen::VectorXi isConstrained,
+                         const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &xknown,
+                                         Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &x);
+    IGL_INLINE void setFieldFromCoefficients();
+    IGL_INLINE void setCoefficientsFromField();
+
+  };
+}
+
+//Implementation
+/***************************** Data ***********************************/
+
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE igl::AngleBoundFFSolverData<DerivedV, DerivedF>::
+AngleBoundFFSolverData(const Eigen::PlainObjectBase<DerivedV> &_V,
+                  const Eigen::PlainObjectBase<DerivedF> &_F):
+V(_V),
+numV(_V.rows()),
+F(_F),
+numF(_F.rows())
+{
+  igl::edge_topology(V,F,EV,F2E,E2F);
+  numE = EV.rows();
+
+  precomputeInteriorEdges();
+
+  igl::local_basis(V,F,B1,B2,FN);
+
+  computek();
+
+  computeLaplacians();
+
+};
+
+
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::AngleBoundFFSolverData<DerivedV, DerivedF>::computeLaplacians()
+{
+  computeCoefficientLaplacian(2, DDA);
+
+  computeCoefficientLaplacian(4, DDB);
+}
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::AngleBoundFFSolverData<DerivedV, DerivedF>::
+precomputeInteriorEdges()
+{
+  // Flag border edges
+  numInteriorEdges = 0;
+  isBorderEdge.setZero(numE,1);
+  indFullToInterior = -1.*Eigen::VectorXi::Ones(numE,1);
+
+  for(unsigned i=0; i<numE; ++i)
+  {
+    if ((E2F(i,0) == -1) || ((E2F(i,1) == -1)))
+      isBorderEdge[i] = 1;
+    else
+    {
+      indFullToInterior[i] = numInteriorEdges;
+      numInteriorEdges++;
+    }
+  }
+
+  E2F_int.resize(numInteriorEdges, 2);
+  indInteriorToFull.setZero(numInteriorEdges,1);
+  int ii = 0;
+  for (int k=0; k<numE; ++k)
+  {
+    if (isBorderEdge[k])
+      continue;
+    E2F_int.row(ii) = E2F.row(k);
+    indInteriorToFull[ii] = k;
+    ii++;
+  }
+
+}
+
+
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::AngleBoundFFSolverData<DerivedV, DerivedF>::
+computeCoefficientLaplacian(int n, Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &D)
+{
+  std::vector<Eigen::Triplet<std::complex<typename DerivedV::Scalar> >> tripletList;
+
+  // For every non-border edge
+  for (unsigned eid=0; eid<numE; ++eid)
+  {
+    if (!isBorderEdge[eid])
+    {
+      int fid0 = E2F(eid,0);
+      int fid1 = E2F(eid,1);
+
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid0,
+                                                                                     fid0,
+                                                                                     std::complex<typename DerivedV::Scalar>(1.)));
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid1,
+                                                                                     fid1,
+                                                                                     std::complex<typename DerivedV::Scalar>(1.)));
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid0,
+                                                                                     fid1,
+                                                                                     -1.*std::polar(1.,-1.*n*K[eid])));
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid1,
+                                                                                     fid0,
+                                                                                     -1.*std::polar(1.,1.*n*K[eid])));
+
+    }
+  }
+  D.resize(numF,numF);
+  D.setFromTriplets(tripletList.begin(), tripletList.end());
+
+
+}
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::AngleBoundFFSolverData<DerivedV, DerivedF>::
+computek()
+{
+  K.setZero(numE);
+  // For every non-border edge
+  for (unsigned eid=0; eid<numE; ++eid)
+  {
+    if (!isBorderEdge[eid])
+    {
+      int fid0 = E2F(eid,0);
+      int fid1 = E2F(eid,1);
+
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N0 = FN.row(fid0);
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N1 = FN.row(fid1);
+
+      // find common edge on triangle 0 and 1
+      int fid0_vc = -1;
+      int fid1_vc = -1;
+      for (unsigned i=0;i<3;++i)
+      {
+        if (F2E(fid0,i) == eid)
+          fid0_vc = i;
+        if (F2E(fid1,i) == eid)
+          fid1_vc = i;
+      }
+      assert(fid0_vc != -1);
+      assert(fid1_vc != -1);
+
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> common_edge = V.row(F(fid0,(fid0_vc+1)%3)) - V.row(F(fid0,fid0_vc));
+      common_edge.normalize();
+
+      // Map the two triangles in a new space where the common edge is the x axis and the N0 the z axis
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> P;
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> o = V.row(F(fid0,fid0_vc));
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> tmp = -N0.cross(common_edge);
+      P << common_edge, tmp, N0;
+      //      P.transposeInPlace();
+
+
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V0;
+      V0.row(0) = V.row(F(fid0,0)) -o;
+      V0.row(1) = V.row(F(fid0,1)) -o;
+      V0.row(2) = V.row(F(fid0,2)) -o;
+
+      V0 = (P*V0.transpose()).transpose();
+
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V1;
+      V1.row(0) = V.row(F(fid1,0)) -o;
+      V1.row(1) = V.row(F(fid1,1)) -o;
+      V1.row(2) = V.row(F(fid1,2)) -o;
+      V1 = (P*V1.transpose()).transpose();
+
+      // compute rotation R such that R * N1 = N0
+      // i.e. map both triangles to the same plane
+      double alpha = -atan2(V1((fid1_vc+2)%3,2),V1((fid1_vc+2)%3,1));
+
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> R;
+      R << 1,          0,            0,
+      0, cos(alpha), -sin(alpha) ,
+      0, sin(alpha),  cos(alpha);
+      V1 = (R*V1.transpose()).transpose();
+
+      // measure the angle between the reference frames
+      // k_ij is the angle between the triangle on the left and the one on the right
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref0 = V0.row(1) - V0.row(0);
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref1 = V1.row(1) - V1.row(0);
+
+      ref0.normalize();
+      ref1.normalize();
+
+      double ktemp = atan2(ref1(1),ref1(0)) - atan2(ref0(1),ref0(0));
+
+      // just to be sure, rotate ref0 using angle ktemp...
+      Eigen::Matrix<typename DerivedV::Scalar, 2, 2> R2;
+      R2 << cos(ktemp), -sin(ktemp), sin(ktemp), cos(ktemp);
+
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 2> tmp1 = R2*(ref0.head(2)).transpose();
+
+      K[eid] = ktemp;
+    }
+  }
+
+}
+
+
+/***************************** Solver ***********************************/
+template <typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+AngleBoundFFSolver(const AngleBoundFFSolverData<DerivedV, DerivedF> &_data,
+                   const typename DerivedV::Scalar &_thetaMin,
+                  int _maxIter,
+                  const typename DerivedV::Scalar &_lambdaInit,
+                  const typename DerivedV::Scalar &_lambdaMultFactor,
+                   const bool _doHardConstraints):
+data(_data),
+lambdaInit(_lambdaInit),
+maxIter(_maxIter),
+lambdaMultFactor(_lambdaMultFactor),
+doHardConstraints(_doHardConstraints),
+thetaMin(_thetaMin)
+{
+  Acoeff.resize(data.numF,1);
+  Bcoeff.resize(data.numF,1);
+  pvU.setZero(data.numF, 2);
+  pvV.setZero(data.numF, 2);
+};
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+rotateAroundBisector(const std::complex<typename DerivedV::Scalar> &uin,
+                          const std::complex<typename DerivedV::Scalar> &vin,
+                          const typename DerivedV::Scalar diff,
+                          std::complex<typename DerivedV::Scalar> &uout,
+                          std::complex<typename DerivedV::Scalar> &vout)
+{
+  //rotate 2D complex vectors u and v around their bisector so that their
+  //angle is at least theta
+
+  uout = uin;
+  vout = vin;
+  typename DerivedV::Scalar au = arg(uin);
+  typename DerivedV::Scalar av = arg(vin);
+  if (au<av)
+  {
+    uout = std::polar (1.0,-.5*diff)*uin;
+    vout = std::polar (1.0, .5*diff)*vin;
+  }
+  else
+  {
+    uout = std::polar (1.0, .5*diff)*uin;
+    vout = std::polar (1.0,-.5*diff)*vin;
+  }
+
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+localStep()
+{
+  for (int j =0; j<data.numF; ++j)
+  {
+
+    std::complex<typename DerivedV::Scalar> u(pvU(j,0),pvU(j,1));
+    std::complex<typename DerivedV::Scalar> v(pvV(j,0),pvV(j,1));
+
+    typename DerivedV::Scalar current_angle = computeAngle(u, v);
+    if (current_angle<thetaMin*M_PI/180)
+    {
+      // bring all to 1st or 4th quarter plane
+      if ((arg(u)>=0.5*M_PI || arg(u)<-0.5*M_PI ))
+        u = -u;
+      if ((arg(v)>=0.5*M_PI || arg(v)<-0.5*M_PI ))
+        v = -v;
+      assert(fabs(computeAngle(u, v) - current_angle)<1e-5);
+
+      if ( fabs(arg(u) - arg(v)) >0.5*M_PI )
+        v = -v;
+      assert(fabs(computeAngle(u, v) - current_angle)<1e-5);
+
+      std::complex<typename DerivedV::Scalar> u1, v1;
+      typename DerivedV::Scalar diff = thetaMin*M_PI/180 - current_angle + 1e-6;
+      rotateAroundBisector(u, v, diff, u1, v1);
+
+      if (computeAngle(u1, v1)<thetaMin*M_PI/180)
+      {
+        std::cerr<<"u = ["<<real(u)<<","<<imag(u)<< "]; v= ["<<real(v)<<","<<imag(v)<<"];"<<std::endl;
+        std::cerr<<"u1 = ["<<real(u1)<<","<<imag(u1)<< "]; v1= ["<<real(v1)<<","<<imag(v1)<<"];"<<std::endl;
+        std::cerr<<"current_angle = "<<current_angle<<std::endl;
+        std::cerr<<"aout = "<<computeAngle(u1, v1)<< "; theta= "<<thetaMin*M_PI/180<<";"<<std::endl;
+      }
+      assert(computeAngle(u1, v1)>=thetaMin*M_PI/180);
+
+
+      pvU.row(j) << real(u1),imag(u1);
+      pvV.row(j) << real(v1),imag(v1);
+    }
+  }
+
+}
+
+
+//
+//template<typename DerivedV, typename DerivedF, typename DerivedO>
+//IGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+//computeAngles(Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> &angles)
+//{
+//  angles.resize(data.numF,1);
+//  for (int i =0; i<data.numF; ++i)
+//  {
+//    std::complex<typename DerivedV::Scalar> u(pvU(i,0),pvU(i,1));
+//    std::complex<typename DerivedV::Scalar> v(pvV(i,0),pvV(i,1));
+//    angles[i] = fabs(arg(u) - arg(v));
+//    if (angles[i]>M_PI)
+//      angles[i] = 2*M_PI-angles[i];
+//    if (angles[i]>.5*M_PI)
+//      angles[i] = M_PI-angles[i];
+//  }
+//}
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE typename DerivedV::Scalar igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+computeAngle(const std::complex<typename DerivedV::Scalar> &u,
+             const std::complex<typename DerivedV::Scalar> &v)
+{
+  typename DerivedV::Scalar angle = std::min(fabs(arg(u*conj(v))), fabs(arg(u*conj(-v))));
+
+//  typename DerivedV::Scalar angle;
+//  typename DerivedV::Scalar a1 = fabs(arg(u*conj(v)));
+//  typename DerivedV::Scalar a2 = fabs(arg(u*conj(-v)));
+//  if (a1 < a2)
+//    angle = a1;
+//  else
+//  {
+//    angle = a2; v = -v;
+//  }
+
+//  typename DerivedV::Scalar angle = fabs(arg(u) - arg(v));
+//  if (angle>M_PI)
+//  {
+//    u = -u;
+//    angle = fabs(arg(u) - arg(v));
+//  };
+//
+//  if (angle>.5*M_PI)
+//  {
+//    v = -v;
+//    angle = fabs(arg(u) - arg(v));
+//  };
+//
+//  assert(fabs(angle-angle1)<1e-6);
+
+//  if (angle>M_PI)
+//    angle = 2*M_PI-angle;
+//  if (angle>.5*M_PI)
+//    angle = M_PI-angle;
+
+//  typename DerivedV::Scalar angle = fabs(arg(u) - arg(v));
+//    if (angle>M_PI)
+//      angle = 2*M_PI-angle;
+//    if (angle>.5*M_PI)
+//      angle = M_PI-angle;
+
+  assert(angle <= .5*M_PI && angle >0);
+
+  return angle;
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE int igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+getNumOutOfBounds()
+{
+  Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> angles;
+//  computeAngles(angles);
+  int numOoB = 0;
+  for (int i =0; i<data.numF; ++i)
+  {
+    std::complex<typename DerivedV::Scalar> u(pvU(i,0),pvU(i,1));
+    std::complex<typename DerivedV::Scalar> v(pvV(i,0),pvV(i,1));
+    typename DerivedV::Scalar angle = computeAngle(u,v);
+//    if (angles[i] <thetaMin*M_PI/180)
+    if (angle <thetaMin*M_PI/180)
+      numOoB ++;
+  }
+  return numOoB;
+}
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+setCoefficientsFromField()
+{
+  for (int i = 0; i <data.numF; ++i)
+  {
+    std::complex<typename DerivedV::Scalar> u(pvU(i,0),pvU(i,1));
+    std::complex<typename DerivedV::Scalar> v(pvV(i,0),pvV(i,1));
+    Acoeff(i) = u*u+v*v;
+    Bcoeff(i) = u*u*v*v;
+  }
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+globalStep(const Eigen::Matrix<int, Eigen::Dynamic, 1>  &isConstrained,
+           const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Ak,
+           const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Bk)
+{
+  setCoefficientsFromField();
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > I;
+  igl::speye(data.numF, data.numF, I);
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > QA = data.DDA+lambda*I;
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fA = (-2*lambda*Acoeff).sparseView();
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > QB = data.DDB+lambda*I;
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fB = (-2*lambda*I*Bcoeff).sparseView();
+
+  if(doHardConstraints)
+  {
+    minQuadWithKnownMini(QA, fA, isConstrained, Ak, Acoeff);
+    minQuadWithKnownMini(QB, fB, isConstrained, Bk, Bcoeff);
+  }
+  else
+  {
+    Eigen::Matrix<int, Eigen::Dynamic, 1>isknown_; isknown_.setZero(data.numF,1);
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> xknown_; xknown_.setZero(0,1);
+    minQuadWithKnownMini(QA, fA, isknown_, xknown_, Acoeff);
+    minQuadWithKnownMini(QB, fB, isknown_, xknown_, Bcoeff);
+  }
+  setFieldFromCoefficients();
+
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+setFieldFromCoefficients()
+{
+  for (int i = 0; i <data.numF; ++i)
+  {
+    //    poly coefficients: 1, 0, -Acoeff, 0, Bcoeff
+    //    matlab code from roots (given there are no trailing zeros in the polynomial coefficients)
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> polyCoeff(5,1);
+    polyCoeff<<1., 0., -Acoeff(i), 0., Bcoeff(i);
+
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> roots;
+    polyRoots<std::complex<typename DerivedV::Scalar>>(polyCoeff,roots);
+
+    std::complex<typename DerivedV::Scalar> u = roots[0];
+    int maxi = -1;
+    float maxd = -1;
+    for (int k =1; k<4; ++k)
+    {
+      float dist = abs(roots[k]+u);
+      if (dist>maxd)
+      {
+        maxd = dist;
+        maxi = k;
+      }
+    }
+    std::complex<typename DerivedV::Scalar> v = roots[maxi];
+    pvU(i,0) = real(u); pvU(i,1) = imag(u);
+    pvV(i,0) = real(v); pvV(i,1) = imag(v);
+  }
+
+}
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+minQuadWithKnownMini(const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &Q,
+                     const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &f,
+                     const Eigen::VectorXi isConstrained,
+                     const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &xknown,
+                     Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &x)
+{
+  int N = Q.rows();
+
+  int nc = xknown.rows();
+  Eigen::VectorXi known; known.setZero(nc,1);
+  Eigen::VectorXi unknown; unknown.setZero(N-nc,1);
+
+  int indk = 0, indu = 0;
+  for (int i = 0; i<N; ++i)
+    if (isConstrained[i])
+    {
+      known[indk] = i;
+      indk++;
+    }
+    else
+    {
+      unknown[indu] = i;
+      indu++;
+    }
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>> Quu, Quk;
+
+  igl::slice(Q,unknown, unknown, Quu);
+  igl::slice(Q,unknown, known, Quk);
+
+
+  std::vector<typename Eigen::Triplet<std::complex<typename DerivedV::Scalar> > > tripletList;
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fu(N-nc,1);
+
+  igl::slice(f,unknown, Eigen::VectorXi::Zero(1,1), fu);
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > rhs = (Quk*xknown).sparseView()+.5*fu;
+
+  Eigen::SparseLU< Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>>> solver;
+  solver.compute(-Quu);
+  if(solver.info()!=Eigen::Success)
+  {
+    std::cerr<<"Decomposition failed!"<<std::endl;
+    return;
+  }
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>>  b  = solver.solve(rhs);
+  if(solver.info()!=Eigen::Success)
+  {
+    std::cerr<<"Solving failed!"<<std::endl;
+    return;
+  }
+
+  indk = 0, indu = 0;
+  x.setZero(N,1);
+  for (int i = 0; i<N; ++i)
+    if (isConstrained[i])
+      x[i] = xknown[indk++];
+    else
+      x[i] = b.coeff(indu++,0);
+
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE bool igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::
+solve(const Eigen::VectorXi &isConstrained,
+      const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+      Eigen::PlainObjectBase<DerivedO> &output,
+      typename DerivedV::Scalar *lambdaOut)
+{
+  int numConstrained = isConstrained.sum();
+  // coefficient values
+  Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> Ak, Bk;
+
+  pvU.resize(data.numF,2);
+  pvV.resize(data.numF,2);
+  for (int fi = 0; fi <data.numF; ++fi)
+  {
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = data.B1.row(fi);
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = data.B2.row(fi);
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &u3 = initialSolution.block(fi,0,1,3);
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &v3 = initialSolution.block(fi,3,1,3);
+    pvU.row(fi)<< u3.dot(b1), u3.dot(b2);
+    pvV.row(fi)<< v3.dot(b1), v3.dot(b2);
+  }
+  setCoefficientsFromField();
+  Ak.resize(numConstrained,1);
+  Bk.resize(numConstrained,1);
+  int ind = 0;
+  for (int i = 0; i <data.numF; ++i)
+  {
+    if(isConstrained[i])
+    {
+      Ak(ind) = Acoeff[i];
+      Bk(ind) = Bcoeff[i];
+      ind ++;
+    }
+  }
+
+
+
+  typename DerivedV::Scalar smoothnessValue;
+  int oob;
+
+  smoothnessValue = (Acoeff.adjoint()*data.DDA*Acoeff + Bcoeff.adjoint()*data.DDB*Bcoeff).real()[0];
+  printf("\n\nInitial smoothness: %.5g\n",smoothnessValue);
+  oob = getNumOutOfBounds();
+  printf("\n\nInitial out-of-bounds: %d\n",oob);
+  printf(" %d %.5g %d\n",-1, smoothnessValue, oob);
+
+  lambda = lambdaInit;
+  for (int iter = 0; iter<maxIter; ++iter)
+  {
+    printf("\n\n--- Iteration %d ---\n",iter);
+
+    localStep();
+    globalStep(isConstrained, Ak, Bk);
+
+
+    smoothnessValue = (Acoeff.adjoint()*data.DDA*Acoeff + Bcoeff.adjoint()*data.DDB*Bcoeff).real()[0];
+
+    printf("Smoothness: %.5g\n",smoothnessValue);
+
+    oob = getNumOutOfBounds();
+
+    bool stoppingCriterion = (oob == 0) ;
+    if (stoppingCriterion)
+      break;
+    lambda = lambda*lambdaMultFactor;
+    printf(" %d %.5g %d\n",iter, smoothnessValue, oob);
+
+  }
+
+  output.setZero(data.numF,6);
+  for (int fi=0; fi<data.numF; ++fi)
+  {
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = data.B1.row(fi);
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = data.B2.row(fi);
+    output.block(fi,0, 1, 3) = pvU(fi,0)*b1 + pvU(fi,1)*b2;
+    output.block(fi,3, 1, 3) = pvV(fi,0)*b1 + pvV(fi,1)*b2;
+  }
+
+  if (lambdaOut)
+    *lambdaOut = lambda;
+
+
+  return (oob==0);
+}
+
+
+
+template <typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE bool igl::angle_bound_frame_fields(const Eigen::PlainObjectBase<DerivedV> &V,
+                                            const Eigen::PlainObjectBase<DerivedF> &F,
+                                              const typename DerivedV::Scalar &thetaMin,
+                                            const Eigen::VectorXi &isConstrained,
+                                            const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+                                            Eigen::PlainObjectBase<DerivedO> &output,
+                                            int maxIter,
+                                            const typename DerivedV::Scalar &lambdaInit,
+                                            const typename DerivedV::Scalar &lambdaMultFactor,
+                                              const bool doHardConstraints)
+{
+  igl::AngleBoundFFSolverData<DerivedV, DerivedF> csdata(V, F);
+  igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO> cs(csdata, thetaMin, maxIter, lambdaInit, lambdaMultFactor, doHardConstraints);
+  return (cs.solve(isConstrained, initialSolution, output));
+}
+
+template <typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE bool igl::angle_bound_frame_fields(const igl::AngleBoundFFSolverData<DerivedV, DerivedF> &csdata,
+                                              const typename DerivedV::Scalar &thetaMin,
+                                            const Eigen::VectorXi &isConstrained,
+                                            const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+                                            Eigen::PlainObjectBase<DerivedO> &output,
+                                            int maxIter,
+                                            const typename DerivedV::Scalar &lambdaInit,
+                                            const typename DerivedV::Scalar &lambdaMultFactor,
+                                              const bool doHardConstraints,
+                                            typename DerivedV::Scalar *lambdaOut)
+{
+  igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO> cs(csdata, thetaMin, maxIter, lambdaInit, lambdaMultFactor, doHardConstraints);
+  return (cs.solve(isConstrained, initialSolution, output, lambdaOut));
+}
+
+#ifdef IGL_STATIC_LIBRARY
+// Explicit template specialization
+#endif

+ 61 - 0
include/igl/angle_bound_frame_fields.h

@@ -0,0 +1,61 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef IGL_ANGLE_BOUND_FRAME_FIELDS
+#define IGL_ANGLE_BOUND_FRAME_FIELDS
+#include "igl_inline.h"
+
+#include <Eigen/Core>
+#include <vector>
+
+namespace igl {
+  //todo
+  /// Given 2 vectors centered on origin calculate the rotation matrix from first to the second
+
+  // Inputs:
+  //   v0, v1         the two #3 by 1 vectors
+  //   normalized     boolean, if false, then the vectors are normalized prior to the calculation
+  // Output:
+  //                  3 by 3 rotation matrix that takes v0 to v1
+  //
+  template <typename DerivedV, typename DerivedF>
+  class AngleBoundFFSolverData;
+
+  template <typename DerivedV, typename DerivedF, typename DerivedO>
+  IGL_INLINE bool angle_bound_frame_fields(const Eigen::PlainObjectBase<DerivedV> &V,
+                                         const Eigen::PlainObjectBase<DerivedF> &F,
+                                           const typename DerivedV::Scalar &thetaMin,
+                                         const Eigen::VectorXi &isConstrained,
+                                         const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+                                         Eigen::PlainObjectBase<DerivedO> &output,
+                                         int _maxIter = 50,
+                                         const typename DerivedV::Scalar &_lambdaInit = 100,
+                                         const typename DerivedV::Scalar &_lambdaMultFactor = 1.5,
+                                           const bool _doHardConstraints = false);
+
+  template <typename DerivedV, typename DerivedF, typename DerivedO>
+  IGL_INLINE bool angle_bound_frame_fields(const AngleBoundFFSolverData<DerivedV, DerivedF> &csdata,
+                                           const typename DerivedV::Scalar &thetaMin,
+                                         const Eigen::VectorXi &isConstrained,
+                                         const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+                                         Eigen::PlainObjectBase<DerivedO> &output,
+                                         int _maxIter = 50,
+                                         const typename DerivedV::Scalar &_lambdaInit = 100,
+                                         const typename DerivedV::Scalar &_lambdaMultFactor = 1.5,
+                                           const bool _doHardConstraints = false,
+                                         typename DerivedV::Scalar *lambdaOut = NULL);
+
+};
+
+
+#ifndef IGL_STATIC_LIBRARY
+#include "angle_bound_frame_fields.cpp"
+#endif
+
+
+#endif /* defined(IGL_ANGLE_BOUND_FRAME_FIELDS) */

+ 1 - 0
include/igl/bbw/bbw.cpp

@@ -106,6 +106,7 @@ IGL_INLINE bool igl::bbw(
       {
         //if(data.verbosity >= 1)
         //{
+          cout<<"BBW: max_iter: "<<data.active_set_params.max_iter<<endl;
           cout<<"BBW: max_iter: "<<eff_params.max_iter<<endl;
         //}
         if(data.verbosity >= 1)

+ 5 - 7
include/igl/column_to_quats.h

@@ -1,9 +1,9 @@
 // This file is part of libigl, a simple c++ geometry processing library.
-// 
+//
 // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
-// 
-// This Source Code Form is subject to the terms of the Mozilla Public License 
-// v. 2.0. If a copy of the MPL was not distributed with this file, You can 
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
 // obtain one at http://mozilla.org/MPL/2.0/.
 #ifndef IGL_COLUMN_TO_QUATS_H
 #define IGL_COLUMN_TO_QUATS_H
@@ -28,9 +28,7 @@ namespace igl
 }
 
 #ifndef IGL_STATIC_LIBRARY
-#  include "columns_to_quats.cpp"
+#  include "column_to_quats.cpp"
 #endif
 
 #endif
-
-

+ 801 - 0
include/igl/conjugate_frame_fields.cpp

@@ -0,0 +1,801 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#include <igl/conjugate_frame_fields.h>
+#include <igl/edge_topology.h>
+#include <igl/local_basis.h>
+#include <igl/nchoosek.h>
+#include <igl/sparse.h>
+#include <igl/speye.h>
+#include <igl/slice.h>
+#include <igl/polyroots.h>
+#include <igl/colon.h>
+#include <igl/false_barycentric_subdivision.h>
+#include <igl/principal_curvature.h>
+#include <Eigen/Sparse>
+
+#include <iostream>
+
+namespace igl {
+
+  template <typename DerivedV, typename DerivedF>
+  class ConjugateFFSolverData
+  {
+    public:
+      const Eigen::PlainObjectBase<DerivedV> &V; int numV;
+      const Eigen::PlainObjectBase<DerivedF> &F; int numF;
+
+      Eigen::MatrixXi EV; int numE;
+      Eigen::MatrixXi F2E;
+      Eigen::MatrixXi E2F;
+      Eigen::VectorXd K;
+
+      Eigen::VectorXi isBorderEdge;
+      int numInteriorEdges;
+      Eigen::Matrix<int,Eigen::Dynamic,2> E2F_int;
+      Eigen::VectorXi indInteriorToFull;
+      Eigen::VectorXi indFullToInterior;
+
+      Eigen::PlainObjectBase<DerivedV> B1, B2, FN;
+
+
+      Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic,1> kmin, kmax;
+      Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic,2> dmin, dmax;
+      Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic,3> dmin3, dmax3;
+
+      Eigen::VectorXd nonPlanarityMeasure;
+      Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > planarityWeight;
+
+      //conjugacy matrix
+      std::vector<Eigen::Matrix<typename DerivedV::Scalar, 4,4> > H;
+
+      //conjugacy matrix eigenvectors and (scaled) eigenvalues
+      std::vector<Eigen::Matrix<typename DerivedV::Scalar, 4,4> > UH;
+      std::vector<Eigen::Matrix<typename DerivedV::Scalar, 4,1> > s;
+
+      //laplacians
+      Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>> DDA, DDB;
+
+  private:
+    IGL_INLINE void computeCurvatureAndPrincipals();
+    IGL_INLINE void precomputeConjugacyStuff();
+    IGL_INLINE void computeLaplacians();
+    IGL_INLINE void computek();
+    IGL_INLINE void computeCoefficientLaplacian(int n, Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &D);
+    
+    IGL_INLINE void precomputeInteriorEdges();
+
+public:
+      IGL_INLINE ConjugateFFSolverData(const Eigen::PlainObjectBase<DerivedV> &_V,
+                                   const Eigen::PlainObjectBase<DerivedF> &_F);
+  };
+
+  template <typename DerivedV, typename DerivedF, typename DerivedO>
+  class ConjugateFFSolver
+  {
+  public:
+    IGL_INLINE ConjugateFFSolver(const ConjugateFFSolverData<DerivedV, DerivedF> &_data,
+                                 int _maxIter = 50,
+                                 const typename DerivedV::Scalar &_lambdaOrtho = .1,
+                                 const typename DerivedV::Scalar &_lambdaInit = 100,
+                                 const typename DerivedV::Scalar &_lambdaMultFactor = 1.01,
+                                 bool _doHardConstraints = true);
+    IGL_INLINE bool solve(const Eigen::VectorXi &isConstrained,
+                          const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+                          Eigen::PlainObjectBase<DerivedO> &output,
+                          typename DerivedV::Scalar *lambdaOut = NULL);
+
+  private:
+
+    const ConjugateFFSolverData<DerivedV, DerivedF> &data;
+
+    //polyVF data
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> Acoeff, Bcoeff;
+    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2> pvU, pvV;
+    typename DerivedV::Scalar lambda;
+
+    //parameters
+    typename DerivedV::Scalar lambdaOrtho;
+    typename DerivedV::Scalar lambdaInit,lambdaMultFactor;
+    int maxIter;
+    bool doHardConstraints;
+
+
+
+    IGL_INLINE void evaluateConjugacy(Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> &conjValues);
+
+
+
+    IGL_INLINE void localStep();
+    IGL_INLINE void getPolyCoeffsForLocalSolve(const Eigen::Matrix<typename DerivedV::Scalar, 4, 1> &s,
+                                               const Eigen::Matrix<typename DerivedV::Scalar, 4, 1> &z,
+                                               Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> &polyCoeff);
+
+    IGL_INLINE void globalStep(const Eigen::Matrix<int, Eigen::Dynamic, 1>  &isConstrained,
+                               const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Ak,
+                               const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Bk);
+    IGL_INLINE void minQuadWithKnownMini(const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &Q,
+                         const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &f,
+                         const Eigen::VectorXi isConstrained,
+                         const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &xknown,
+                                         Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &x);
+    IGL_INLINE void setFieldFromCoefficients();
+    IGL_INLINE void setCoefficientsFromField();
+
+  };
+}
+
+//Implementation
+/***************************** Data ***********************************/
+
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE igl::ConjugateFFSolverData<DerivedV, DerivedF>::
+ConjugateFFSolverData(const Eigen::PlainObjectBase<DerivedV> &_V,
+                  const Eigen::PlainObjectBase<DerivedF> &_F):
+V(_V),
+numV(_V.rows()),
+F(_F),
+numF(_F.rows())
+{
+  igl::edge_topology(V,F,EV,F2E,E2F);
+  numE = EV.rows();
+
+  precomputeInteriorEdges();
+
+  igl::local_basis(V,F,B1,B2,FN);
+
+  computek();
+
+  computeLaplacians();
+
+  computeCurvatureAndPrincipals();
+  precomputeConjugacyStuff();
+
+};
+
+
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::ConjugateFFSolverData<DerivedV, DerivedF>::computeCurvatureAndPrincipals()
+{
+  Eigen::MatrixXd VCBary;
+  Eigen::MatrixXi FCBary;
+
+  VCBary.setZero(numV+numF,3);
+  FCBary.setZero(3*numF,3);
+  igl::false_barycentric_subdivision(V, F, VCBary, FCBary);
+
+  Eigen::MatrixXd dmax3_,dmin3_;
+  igl::principal_curvature(VCBary, FCBary, dmax3_, dmin3_, kmax, kmin, 5,true);
+
+  dmax3 = dmax3_.bottomRows(numF);
+  dmin3 = dmin3_.bottomRows(numF);
+
+  kmax = kmax.bottomRows(numF);
+  kmin = kmin.bottomRows(numF);
+
+  //  kmax = dmax3.rowwise().norm();
+  //  kmin = dmin3.rowwise().norm();
+
+  dmin3.rowwise().normalize();
+  dmax3.rowwise().normalize();
+  dmax.setZero(numF,2);
+  dmin.setZero(numF,2);
+  for (int i= 0; i <numF; ++i)
+  {
+    if(kmin[i] != kmin[i] || kmax[i] != kmax[i] || (dmin3.row(i).array() != dmin3.row(i).array()).any() || (dmax3.row(i).array() != dmax3.row(i).array()).any())
+    {
+      kmin[i] = 0;
+      kmax[i] = 0;
+      dmin3.row(i) = B1.row(i);
+      dmax3.row(i) = B2.row(i);
+    }
+    else
+    {
+      dmax3.row(i) = (dmax3.row(i) - (dmax3.row(i).dot(FN.row(i)))*FN.row(i)).normalized();
+      dmin3.row(i) = dmin3.row(i) - (dmin3.row(i).dot(FN.row(i)))*FN.row(i);
+      dmin3.row(i) = (dmin3.row(i) - (dmin3.row(i).dot(dmax3.row(i)))*dmax3.row(i)).normalized();
+      if ((dmin3.row(i).cross(dmax3.row(i))).dot(FN.row(i))<0)
+        dmin3.row(i) = -dmin3.row(i);
+    }
+    dmax.row(i) << dmax3.row(i).dot(B1.row(i)), dmax3.row(i).dot(B2.row(i));
+    dmax.row(i).normalize();
+    dmin.row(i) << dmin3.row(i).dot(B1.row(i)), dmin3.row(i).dot(B2.row(i));
+    dmin.row(i).normalize();
+
+  }
+
+  nonPlanarityMeasure = kmax.cwiseAbs().array()*kmin.cwiseAbs().array();
+  typename DerivedV::Scalar minP = nonPlanarityMeasure.minCoeff();
+  typename DerivedV::Scalar maxP = nonPlanarityMeasure.maxCoeff();
+  nonPlanarityMeasure = (nonPlanarityMeasure.array()-minP)/(maxP-minP);
+  Eigen::VectorXi I = igl::colon<typename DerivedF::Scalar>(0, numF-1);
+  igl::sparse(I, I, nonPlanarityMeasure, numF, numF, planarityWeight);
+
+}
+
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::ConjugateFFSolverData<DerivedV, DerivedF>::precomputeConjugacyStuff()
+{
+  H.resize(numF);
+  UH.resize(numF);
+  s.resize(numF);
+
+  for (int i = 0; i<numF; ++i)
+  {
+    //compute conjugacy matrix
+    typename DerivedV::Scalar e1x = dmin(i,0), e1y = dmin(i,1), e2x = dmax(i,0), e2y = dmax(i,1), k1 = kmin[i], k2 = kmax[i];
+
+    H[i]<<
+    0,          0, k1*e1x*e1x, k1*e1x*e1y,
+    0,          0, k1*e1x*e1y, k1*e1y*e1y,
+    k2*e2x*e2x, k2*e2x*e2y,          0,          0,
+    k2*e2x*e2y, k2*e2y*e2y,          0,          0;
+    Eigen::Matrix<typename DerivedV::Scalar, 4, 4> Ht = H[i].transpose();
+    H[i] = .5*(H[i]+Ht);
+
+    Eigen::EigenSolver<Eigen::Matrix<typename DerivedV::Scalar, 4, 4> > es(H[i]);
+    s[i] = es.eigenvalues().real();//ok to do this because H symmetric
+    //scale
+    s[i] = s[i]/(s[i].cwiseAbs().minCoeff());
+    UH[i] = es.eigenvectors().real();
+
+
+  }
+}
+
+
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::ConjugateFFSolverData<DerivedV, DerivedF>::computeLaplacians()
+{
+  computeCoefficientLaplacian(2, DDA);
+
+  computeCoefficientLaplacian(4, DDB);
+}
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::ConjugateFFSolverData<DerivedV, DerivedF>::
+precomputeInteriorEdges()
+{
+  // Flag border edges
+  numInteriorEdges = 0;
+  isBorderEdge.setZero(numE,1);
+  indFullToInterior = -1.*Eigen::VectorXi::Ones(numE,1);
+
+  for(unsigned i=0; i<numE; ++i)
+  {
+    if ((E2F(i,0) == -1) || ((E2F(i,1) == -1)))
+      isBorderEdge[i] = 1;
+    else
+    {
+      indFullToInterior[i] = numInteriorEdges;
+      numInteriorEdges++;
+    }
+  }
+
+  E2F_int.resize(numInteriorEdges, 2);
+  indInteriorToFull.setZero(numInteriorEdges,1);
+  int ii = 0;
+  for (int k=0; k<numE; ++k)
+  {
+    if (isBorderEdge[k])
+      continue;
+    E2F_int.row(ii) = E2F.row(k);
+    indInteriorToFull[ii] = k;
+    ii++;
+  }
+
+}
+
+
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::ConjugateFFSolverData<DerivedV, DerivedF>::
+computeCoefficientLaplacian(int n, Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &D)
+{
+  std::vector<Eigen::Triplet<std::complex<typename DerivedV::Scalar> >> tripletList;
+
+  // For every non-border edge
+  for (unsigned eid=0; eid<numE; ++eid)
+  {
+    if (!isBorderEdge[eid])
+    {
+      int fid0 = E2F(eid,0);
+      int fid1 = E2F(eid,1);
+
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid0,
+                                                                                     fid0,
+                                                                                     std::complex<typename DerivedV::Scalar>(1.)));
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid1,
+                                                                                     fid1,
+                                                                                     std::complex<typename DerivedV::Scalar>(1.)));
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid0,
+                                                                                     fid1,
+                                                                                     -1.*std::polar(1.,-1.*n*K[eid])));
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid1,
+                                                                                     fid0,
+                                                                                     -1.*std::polar(1.,1.*n*K[eid])));
+
+    }
+  }
+  D.resize(numF,numF);
+  D.setFromTriplets(tripletList.begin(), tripletList.end());
+
+
+}
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::ConjugateFFSolverData<DerivedV, DerivedF>::
+computek()
+{
+  K.setZero(numE);
+  // For every non-border edge
+  for (unsigned eid=0; eid<numE; ++eid)
+  {
+    if (!isBorderEdge[eid])
+    {
+      int fid0 = E2F(eid,0);
+      int fid1 = E2F(eid,1);
+
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N0 = FN.row(fid0);
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N1 = FN.row(fid1);
+
+      // find common edge on triangle 0 and 1
+      int fid0_vc = -1;
+      int fid1_vc = -1;
+      for (unsigned i=0;i<3;++i)
+      {
+        if (F2E(fid0,i) == eid)
+          fid0_vc = i;
+        if (F2E(fid1,i) == eid)
+          fid1_vc = i;
+      }
+      assert(fid0_vc != -1);
+      assert(fid1_vc != -1);
+
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> common_edge = V.row(F(fid0,(fid0_vc+1)%3)) - V.row(F(fid0,fid0_vc));
+      common_edge.normalize();
+
+      // Map the two triangles in a new space where the common edge is the x axis and the N0 the z axis
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> P;
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> o = V.row(F(fid0,fid0_vc));
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> tmp = -N0.cross(common_edge);
+      P << common_edge, tmp, N0;
+      //      P.transposeInPlace();
+
+
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V0;
+      V0.row(0) = V.row(F(fid0,0)) -o;
+      V0.row(1) = V.row(F(fid0,1)) -o;
+      V0.row(2) = V.row(F(fid0,2)) -o;
+
+      V0 = (P*V0.transpose()).transpose();
+
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V1;
+      V1.row(0) = V.row(F(fid1,0)) -o;
+      V1.row(1) = V.row(F(fid1,1)) -o;
+      V1.row(2) = V.row(F(fid1,2)) -o;
+      V1 = (P*V1.transpose()).transpose();
+
+      // compute rotation R such that R * N1 = N0
+      // i.e. map both triangles to the same plane
+      double alpha = -atan2(V1((fid1_vc+2)%3,2),V1((fid1_vc+2)%3,1));
+
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> R;
+      R << 1,          0,            0,
+      0, cos(alpha), -sin(alpha) ,
+      0, sin(alpha),  cos(alpha);
+      V1 = (R*V1.transpose()).transpose();
+
+      // measure the angle between the reference frames
+      // k_ij is the angle between the triangle on the left and the one on the right
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref0 = V0.row(1) - V0.row(0);
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref1 = V1.row(1) - V1.row(0);
+
+      ref0.normalize();
+      ref1.normalize();
+
+      double ktemp = atan2(ref1(1),ref1(0)) - atan2(ref0(1),ref0(0));
+
+      // just to be sure, rotate ref0 using angle ktemp...
+      Eigen::Matrix<typename DerivedV::Scalar, 2, 2> R2;
+      R2 << cos(ktemp), -sin(ktemp), sin(ktemp), cos(ktemp);
+
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 2> tmp1 = R2*(ref0.head(2)).transpose();
+
+      K[eid] = ktemp;
+    }
+  }
+
+}
+
+
+/***************************** Solver ***********************************/
+template <typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO>::
+ConjugateFFSolver(const ConjugateFFSolverData<DerivedV, DerivedF> &_data,
+                  int _maxIter,
+                  const typename DerivedV::Scalar &_lambdaOrtho,
+                  const typename DerivedV::Scalar &_lambdaInit,
+                  const typename DerivedV::Scalar &_lambdaMultFactor,
+                  bool _doHardConstraints):
+data(_data),
+lambdaOrtho(_lambdaOrtho),
+lambdaInit(_lambdaInit),
+maxIter(_maxIter),
+lambdaMultFactor(_lambdaMultFactor),
+doHardConstraints(_doHardConstraints)
+{
+  Acoeff.resize(data.numF,1);
+  Bcoeff.resize(data.numF,1);
+  pvU.setZero(data.numF, 2);
+  pvV.setZero(data.numF, 2);
+};
+
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO>::
+evaluateConjugacy(Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> &conjValues)
+{
+  conjValues.resize(data.numF,1);
+  for (int j =0; j<data.numF; ++j)
+  {
+    Eigen::Matrix<typename DerivedV::Scalar, 4, 1> x; x<<pvU.row(j).transpose(), pvV.row(j).transpose();
+    conjValues[j] = x.transpose()*data.H[j]*x;
+  }
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO>::
+getPolyCoeffsForLocalSolve(const Eigen::Matrix<typename DerivedV::Scalar, 4, 1> &s,
+                           const Eigen::Matrix<typename DerivedV::Scalar, 4, 1> &z,
+                           Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> &polyCoeff)
+{
+  typename DerivedV::Scalar s0 = s(0);
+  typename DerivedV::Scalar s1 = s(1);
+  typename DerivedV::Scalar s2 = s(2);
+  typename DerivedV::Scalar s3 = s(3);
+  typename DerivedV::Scalar z0 = z(0);
+  typename DerivedV::Scalar z1 = z(1);
+  typename DerivedV::Scalar z2 = z(2);
+  typename DerivedV::Scalar z3 = z(3);
+
+  polyCoeff.resize(7,1);
+  polyCoeff(0) =  s0*s0* s1*s1* s2*s2* s3* z3*z3 +  s0*s0* s1*s1* s2* s3*s3* z2*z2 +  s0*s0* s1* s2*s2* s3*s3* z1*z1 +  s0* s1*s1* s2*s2* s3*s3* z0*z0 ;
+  polyCoeff(1) = 2* s0*s0* s1*s1* s2* s3* z2*z2 + 2* s0*s0* s1*s1* s2* s3* z3*z3 + 2* s0*s0* s1* s2*s2* s3* z1*z1 + 2* s0*s0* s1* s2*s2* s3* z3*z3 + 2* s0*s0* s1* s2* s3*s3* z1*z1 + 2* s0*s0* s1* s2* s3*s3* z2*z2 + 2* s0* s1*s1* s2*s2* s3* z0*z0 + 2* s0* s1*s1* s2*s2* s3* z3*z3 + 2* s0* s1*s1* s2* s3*s3* z0*z0 + 2* s0* s1*s1* s2* s3*s3* z2*z2 + 2* s0* s1* s2*s2* s3*s3* z0*z0 + 2* s0* s1* s2*s2* s3*s3* z1*z1 ;
+  polyCoeff(2) =  s0*s0* s1*s1* s2* z2*z2 +  s0*s0* s1*s1* s3* z3*z3 +  s0*s0* s1* s2*s2* z1*z1 + 4* s0*s0* s1* s2* s3* z1*z1 + 4* s0*s0* s1* s2* s3* z2*z2 + 4* s0*s0* s1* s2* s3* z3*z3 +  s0*s0* s1* s3*s3* z1*z1 +  s0*s0* s2*s2* s3* z3*z3 +  s0*s0* s2* s3*s3* z2*z2 +  s0* s1*s1* s2*s2* z0*z0 + 4* s0* s1*s1* s2* s3* z0*z0 + 4* s0* s1*s1* s2* s3* z2*z2 + 4* s0* s1*s1* s2* s3* z3*z3 +  s0* s1*s1* s3*s3* z0*z0 + 4* s0* s1* s2*s2* s3* z0*z0 + 4* s0* s1* s2*s2* s3* z1*z1 + 4* s0* s1* s2*s2* s3* z3*z3 + 4* s0* s1* s2* s3*s3* z0*z0 + 4* s0* s1* s2* s3*s3* z1*z1 + 4* s0* s1* s2* s3*s3* z2*z2 +  s0* s2*s2* s3*s3* z0*z0 +  s1*s1* s2*s2* s3* z3*z3 +  s1*s1* s2* s3*s3* z2*z2 +  s1* s2*s2* s3*s3* z1*z1;
+  polyCoeff(3) = 2* s0*s0* s1* s2* z1*z1 + 2* s0*s0* s1* s2* z2*z2 + 2* s0*s0* s1* s3* z1*z1 + 2* s0*s0* s1* s3* z3*z3 + 2* s0*s0* s2* s3* z2*z2 + 2* s0*s0* s2* s3* z3*z3 + 2* s0* s1*s1* s2* z0*z0 + 2* s0* s1*s1* s2* z2*z2 + 2* s0* s1*s1* s3* z0*z0 + 2* s0* s1*s1* s3* z3*z3 + 2* s0* s1* s2*s2* z0*z0 + 2* s0* s1* s2*s2* z1*z1 + 8* s0* s1* s2* s3* z0*z0 + 8* s0* s1* s2* s3* z1*z1 + 8* s0* s1* s2* s3* z2*z2 + 8* s0* s1* s2* s3* z3*z3 + 2* s0* s1* s3*s3* z0*z0 + 2* s0* s1* s3*s3* z1*z1 + 2* s0* s2*s2* s3* z0*z0 + 2* s0* s2*s2* s3* z3*z3 + 2* s0* s2* s3*s3* z0*z0 + 2* s0* s2* s3*s3* z2*z2 + 2* s1*s1* s2* s3* z2*z2 + 2* s1*s1* s2* s3* z3*z3 + 2* s1* s2*s2* s3* z1*z1 + 2* s1* s2*s2* s3* z3*z3 + 2* s1* s2* s3*s3* z1*z1 + 2* s1* s2* s3*s3* z2*z2 ;
+  polyCoeff(4) =  s0*s0* s1* z1*z1 +  s0*s0* s2* z2*z2 +  s0*s0* s3* z3*z3 +  s0* s1*s1* z0*z0 + 4* s0* s1* s2* z0*z0 + 4* s0* s1* s2* z1*z1 + 4* s0* s1* s2* z2*z2 + 4* s0* s1* s3* z0*z0 + 4* s0* s1* s3* z1*z1 + 4* s0* s1* s3* z3*z3 +  s0* s2*s2* z0*z0 + 4* s0* s2* s3* z0*z0 + 4* s0* s2* s3* z2*z2 + 4* s0* s2* s3* z3*z3 +  s0* s3*s3* z0*z0 +  s1*s1* s2* z2*z2 +  s1*s1* s3* z3*z3 +  s1* s2*s2* z1*z1 + 4* s1* s2* s3* z1*z1 + 4* s1* s2* s3* z2*z2 + 4* s1* s2* s3* z3*z3 +  s1* s3*s3* z1*z1 +  s2*s2* s3* z3*z3 +  s2* s3*s3* z2*z2;
+  polyCoeff(5) = 2* s0* s1* z0*z0 + 2* s0* s1* z1*z1 + 2* s0* s2* z0*z0 + 2* s0* s2* z2*z2 + 2* s0* s3* z0*z0 + 2* s0* s3* z3*z3 + 2* s1* s2* z1*z1 + 2* s1* s2* z2*z2 + 2* s1* s3* z1*z1 + 2* s1* s3* z3*z3 + 2* s2* s3* z2*z2 + 2* s2* s3* z3*z3 ;
+  polyCoeff(6) =  s0* z0*z0 +  s1* z1*z1 +  s2* z2*z2 +  s3* z3*z3;
+
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO>::
+localStep()
+{
+  for (int j =0; j<data.numF; ++j)
+  {
+    Eigen::Matrix<typename DerivedV::Scalar, 4, 1> xproj; xproj << pvU.row(j).transpose(),pvV.row(j).transpose();
+    Eigen::Matrix<typename DerivedV::Scalar, 4, 1> z = data.UH[j].transpose()*xproj;
+    Eigen::Matrix<typename DerivedV::Scalar, 4, 1> x;
+
+    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> polyCoeff;
+    getPolyCoeffsForLocalSolve(data.s[j], z, polyCoeff);
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> roots;
+    igl::polyRoots<typename DerivedV::Scalar, typename DerivedV::Scalar> (polyCoeff, roots );
+
+    //  find closest real root to xproj
+    typename DerivedV::Scalar minDist = 1e10;
+    for (int i =0; i< 6; ++i)
+    {
+      if (fabs(imag(roots[i]))>1e-10)
+        continue;
+      Eigen::Matrix<typename DerivedV::Scalar, 4, 4> D = ((Eigen::Matrix<typename DerivedV::Scalar, 4, 1>::Ones()+real(roots(i))*data.s[j]).array().inverse()).matrix().asDiagonal();
+      Eigen::Matrix<typename DerivedV::Scalar, 4, 1> candidate = data.UH[j]*D*z;
+      typename DerivedV::Scalar dist = (candidate-xproj).norm();
+      if (dist<minDist)
+      {
+        minDist = dist;
+        x = candidate;
+      }
+
+    }
+
+    pvU.row(j) << x(0),x(1);
+    pvV.row(j) << x(2),x(3);
+  }
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO>::
+setCoefficientsFromField()
+{
+  for (int i = 0; i <data.numF; ++i)
+  {
+    std::complex<typename DerivedV::Scalar> u(pvU(i,0),pvU(i,1));
+    std::complex<typename DerivedV::Scalar> v(pvV(i,0),pvV(i,1));
+    Acoeff(i) = u*u+v*v;
+    Bcoeff(i) = u*u*v*v;
+  }
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO>::
+globalStep(const Eigen::Matrix<int, Eigen::Dynamic, 1>  &isConstrained,
+           const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Ak,
+           const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Bk)
+{
+  setCoefficientsFromField();
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > I;
+  igl::speye(data.numF, data.numF, I);
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > QA = data.DDA+lambda*data.planarityWeight+lambdaOrtho*I;
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fA = (-2*lambda*data.planarityWeight*Acoeff).sparseView();
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > QB = data.DDB+lambda*data.planarityWeight;
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fB = (-2*lambda*data.planarityWeight*Bcoeff).sparseView();
+
+  if(doHardConstraints)
+  {
+    minQuadWithKnownMini(QA, fA, isConstrained, Ak, Acoeff);
+    minQuadWithKnownMini(QB, fB, isConstrained, Bk, Bcoeff);
+  }
+  else
+  {
+    Eigen::Matrix<int, Eigen::Dynamic, 1>isknown_; isknown_.setZero(data.numF,1);
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> xknown_; xknown_.setZero(0,1);
+    minQuadWithKnownMini(QA, fA, isknown_, xknown_, Acoeff);
+    minQuadWithKnownMini(QB, fB, isknown_, xknown_, Bcoeff);
+  }
+  setFieldFromCoefficients();
+
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO>::
+setFieldFromCoefficients()
+{
+  for (int i = 0; i <data.numF; ++i)
+  {
+    //    poly coefficients: 1, 0, -Acoeff, 0, Bcoeff
+    //    matlab code from roots (given there are no trailing zeros in the polynomial coefficients)
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> polyCoeff(5,1);
+    polyCoeff<<1., 0., -Acoeff(i), 0., Bcoeff(i);
+
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> roots;
+    polyRoots<std::complex<typename DerivedV::Scalar>>(polyCoeff,roots);
+
+    std::complex<typename DerivedV::Scalar> u = roots[0];
+    int maxi = -1;
+    float maxd = -1;
+    for (int k =1; k<4; ++k)
+    {
+      float dist = abs(roots[k]+u);
+      if (dist>maxd)
+      {
+        maxd = dist;
+        maxi = k;
+      }
+    }
+    std::complex<typename DerivedV::Scalar> v = roots[maxi];
+    pvU(i,0) = real(u); pvU(i,1) = imag(u);
+    pvV(i,0) = real(v); pvV(i,1) = imag(v);
+  }
+
+}
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO>::
+minQuadWithKnownMini(const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &Q,
+                     const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &f,
+                     const Eigen::VectorXi isConstrained,
+                     const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &xknown,
+                     Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &x)
+{
+  int N = Q.rows();
+
+  int nc = xknown.rows();
+  Eigen::VectorXi known; known.setZero(nc,1);
+  Eigen::VectorXi unknown; unknown.setZero(N-nc,1);
+
+  int indk = 0, indu = 0;
+  for (int i = 0; i<N; ++i)
+    if (isConstrained[i])
+    {
+      known[indk] = i;
+      indk++;
+    }
+    else
+    {
+      unknown[indu] = i;
+      indu++;
+    }
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>> Quu, Quk;
+
+  igl::slice(Q,unknown, unknown, Quu);
+  igl::slice(Q,unknown, known, Quk);
+
+
+  std::vector<typename Eigen::Triplet<std::complex<typename DerivedV::Scalar> > > tripletList;
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fu(N-nc,1);
+
+  igl::slice(f,unknown, Eigen::VectorXi::Zero(1,1), fu);
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > rhs = (Quk*xknown).sparseView()+.5*fu;
+
+  Eigen::SparseLU< Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>>> solver;
+  solver.compute(-Quu);
+  if(solver.info()!=Eigen::Success)
+  {
+    std::cerr<<"Decomposition failed!"<<std::endl;
+    return;
+  }
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>>  b  = solver.solve(rhs);
+  if(solver.info()!=Eigen::Success)
+  {
+    std::cerr<<"Solving failed!"<<std::endl;
+    return;
+  }
+
+  indk = 0, indu = 0;
+  x.setZero(N,1);
+  for (int i = 0; i<N; ++i)
+    if (isConstrained[i])
+      x[i] = xknown[indk++];
+    else
+      x[i] = b.coeff(indu++,0);
+
+}
+
+
+template<typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE bool igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO>::
+solve(const Eigen::VectorXi &isConstrained,
+      const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+      Eigen::PlainObjectBase<DerivedO> &output,
+      typename DerivedV::Scalar *lambdaOut)
+{
+  int numConstrained = isConstrained.sum();
+  // coefficient values
+  Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> Ak, Bk;
+
+  pvU.resize(data.numF,2);
+  pvV.resize(data.numF,2);
+  for (int fi = 0; fi <data.numF; ++fi)
+  {
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = data.B1.row(fi);
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = data.B2.row(fi);
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &u3 = initialSolution.block(fi,0,1,3);
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &v3 = initialSolution.block(fi,3,1,3);
+    pvU.row(fi)<< u3.dot(b1), u3.dot(b2);
+    pvV.row(fi)<< v3.dot(b1), v3.dot(b2);
+  }
+  setCoefficientsFromField();
+  Ak.resize(numConstrained,1);
+  Bk.resize(numConstrained,1);
+  int ind = 0;
+  for (int i = 0; i <data.numF; ++i)
+  {
+    if(isConstrained[i])
+    {
+      Ak(ind) = Acoeff[i];
+      Bk(ind) = Bcoeff[i];
+      ind ++;
+    }
+  }
+
+
+
+  typename DerivedV::Scalar smoothnessValue;
+  Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> conjValues;
+  typename DerivedV::Scalar meanConj;
+  typename DerivedV::Scalar maxConj;
+
+  evaluateConjugacy(conjValues);
+  meanConj = conjValues.cwiseAbs().mean();
+  maxConj = conjValues.cwiseAbs().maxCoeff();
+  printf("Initial max non-conjugacy: %.5g\n",maxConj);
+
+  smoothnessValue = (Acoeff.adjoint()*data.DDA*Acoeff + Bcoeff.adjoint()*data.DDB*Bcoeff).real()[0];
+  printf("\n\nInitial smoothness: %.5g\n",smoothnessValue);
+
+  lambda = lambdaInit;
+
+  bool doit = false;
+  for (int iter = 0; iter<maxIter; ++iter)
+  {
+    printf("\n\n--- Iteration %d ---\n",iter);
+
+    typename DerivedV::Scalar oldMeanConj = meanConj;
+
+    localStep();
+    globalStep(isConstrained, Ak, Bk);
+
+
+    smoothnessValue = (Acoeff.adjoint()*data.DDA*Acoeff + Bcoeff.adjoint()*data.DDB*Bcoeff).real()[0];
+
+    printf("Smoothness: %.5g\n",smoothnessValue);
+
+    evaluateConjugacy(conjValues);
+    meanConj = conjValues.cwiseAbs().mean();
+    maxConj = conjValues.cwiseAbs().maxCoeff();
+    printf("Mean/Max non-conjugacy: %.5g, %.5g\n",meanConj,maxConj);
+    typename DerivedV::Scalar diffMeanConj = fabs(oldMeanConj-meanConj);
+
+    if (diffMeanConj<1e-4)
+      doit = true;
+
+    if (doit)
+      lambda = lambda*lambdaMultFactor;
+    printf(" %d %.5g %.5g\n",iter, smoothnessValue,maxConj);
+
+  }
+
+  output.setZero(data.numF,6);
+  for (int fi=0; fi<data.numF; ++fi)
+  {
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = data.B1.row(fi);
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = data.B2.row(fi);
+    output.block(fi,0, 1, 3) = pvU(fi,0)*b1 + pvU(fi,1)*b2;
+    output.block(fi,3, 1, 3) = pvV(fi,0)*b1 + pvV(fi,1)*b2;
+  }
+
+  if (lambdaOut)
+    *lambdaOut = lambda;
+
+
+  return true;
+}
+
+
+
+template <typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::conjugate_frame_fields(const Eigen::PlainObjectBase<DerivedV> &V,
+                                            const Eigen::PlainObjectBase<DerivedF> &F,
+                                            const Eigen::VectorXi &isConstrained,
+                                            const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+                                            Eigen::PlainObjectBase<DerivedO> &output,
+                                            int maxIter,
+                                            const typename DerivedV::Scalar &lambdaOrtho,
+                                            const typename DerivedV::Scalar &lambdaInit,
+                                            const typename DerivedV::Scalar &lambdaMultFactor,
+                                            bool doHardConstraints)
+{
+  igl::ConjugateFFSolverData<DerivedV, DerivedF> csdata(V, F);
+  igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO> cs(csdata, maxIter, lambdaOrtho, lambdaInit, lambdaMultFactor, doHardConstraints);
+  cs.solve(isConstrained, initialSolution, output);
+}
+
+template <typename DerivedV, typename DerivedF, typename DerivedO>
+IGL_INLINE void igl::conjugate_frame_fields(const igl::ConjugateFFSolverData<DerivedV, DerivedF> &csdata,
+                                            const Eigen::VectorXi &isConstrained,
+                                            const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+                                            Eigen::PlainObjectBase<DerivedO> &output,
+                                            int maxIter,
+                                            const typename DerivedV::Scalar &lambdaOrtho,
+                                            const typename DerivedV::Scalar &lambdaInit,
+                                            const typename DerivedV::Scalar &lambdaMultFactor,
+                                            bool doHardConstraints,
+                                            typename DerivedV::Scalar *lambdaOut)
+{
+  igl::ConjugateFFSolver<DerivedV, DerivedF, DerivedO> cs(csdata, maxIter, lambdaOrtho, lambdaInit, lambdaMultFactor, doHardConstraints);
+  cs.solve(isConstrained, initialSolution, output, lambdaOut);
+}
+
+#ifdef IGL_STATIC_LIBRARY
+// Explicit template specialization
+#endif

+ 61 - 0
include/igl/conjugate_frame_fields.h

@@ -0,0 +1,61 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef IGL_CONJUGATE_FRAME_FIELDS
+#define IGL_CONJUGATE_FRAME_FIELDS
+#include "igl_inline.h"
+
+#include <Eigen/Core>
+#include <vector>
+
+namespace igl {
+  //todo
+  /// Given 2 vectors centered on origin calculate the rotation matrix from first to the second
+  
+  // Inputs:
+  //   v0, v1         the two #3 by 1 vectors
+  //   normalized     boolean, if false, then the vectors are normalized prior to the calculation
+  // Output:
+  //                  3 by 3 rotation matrix that takes v0 to v1
+  //
+  template <typename DerivedV, typename DerivedF>
+  class ConjugateFFSolverData;
+  
+  template <typename DerivedV, typename DerivedF, typename DerivedO>
+  IGL_INLINE void conjugate_frame_fields(const Eigen::PlainObjectBase<DerivedV> &V,
+                                         const Eigen::PlainObjectBase<DerivedF> &F,
+                                         const Eigen::VectorXi &isConstrained,
+                                         const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+                                         Eigen::PlainObjectBase<DerivedO> &output,
+                                         int _maxIter = 50,
+                                         const typename DerivedV::Scalar &_lambdaOrtho = .1,
+                                         const typename DerivedV::Scalar &_lambdaInit = 100,
+                                         const typename DerivedV::Scalar &_lambdaMultFactor = 1.01,
+                                         bool _doHardConstraints = true);
+  
+  template <typename DerivedV, typename DerivedF, typename DerivedO>
+  IGL_INLINE void conjugate_frame_fields(const ConjugateFFSolverData<DerivedV, DerivedF> &csdata,
+                                         const Eigen::VectorXi &isConstrained,
+                                         const Eigen::PlainObjectBase<DerivedO> &initialSolution,
+                                         Eigen::PlainObjectBase<DerivedO> &output,
+                                         int _maxIter = 50,
+                                         const typename DerivedV::Scalar &_lambdaOrtho = .1,
+                                         const typename DerivedV::Scalar &_lambdaInit = 100,
+                                         const typename DerivedV::Scalar &_lambdaMultFactor = 1.01,
+                                         bool _doHardConstraints = true,
+                                         typename DerivedV::Scalar *lambdaOut = NULL);
+  
+};
+
+
+#ifndef IGL_STATIC_LIBRARY
+#include "conjugate_frame_fields.cpp"
+#endif
+
+
+#endif /* defined(IGL_CONJUGATE_FRAME_FIELDS) */

+ 0 - 30
include/igl/cross_field_missmatch.cpp

@@ -40,36 +40,6 @@ namespace igl {
 
 
   private:
-
-    // Alec: Not compiling... Handle_MMatch not declared.
-    /////return true if a vertex is singluar by looking at initialized missmatches
-    //// possible bugs, verify deleted flag vs IsD()
-    //// not sorted vf, but should not make a difference
-    //// olga: TODO: this returns the index modulo 4.
-    //inline int oneRingMissMatch(const int vid)
-    //{
-    //  ///check that is on border..
-    //  if (V_border[vid])
-    //    return 0;
-    //
-    //  int missmatch=0;
-    //  for (unsigned int i=0;i<VF[vid].size();i++)
-    //  {
-    //    // look for the vertex
-    //    int j=-1;
-    //    for (unsigned z=0; z<3; ++z)
-    //      if (F(VF[vid][i],z) == vid)
-    //        j=z;
-    //    assert(j!=-1);
-    //
-    //    missmatch+=Handle_MMatch(VF[vid][i],j);
-    //  }
-    //
-    //  missmatch=missmatch%4;
-    //  return missmatch;
-    //}
-
-
     ///compute the mismatch between 2 faces
     inline int MissMatchByCross(const int f0,
                          const int f1)

+ 49 - 0
include/igl/deform_skeleton.cpp

@@ -0,0 +1,49 @@
+#include "deform_skeleton.h"
+void igl::deform_skeleton(
+  const Eigen::MatrixXd & C,
+  const Eigen::MatrixXi & BE,
+  const std::vector<
+    Eigen::Affine3d,Eigen::aligned_allocator<Eigen::Affine3d> > & vA,
+  Eigen::MatrixXd & CT,
+  Eigen::MatrixXi & BET)
+{
+  using namespace Eigen;
+  assert(BE.rows() == (int)vA.size());
+  CT.resize(2*BE.rows(),C.cols());
+  BET.resize(BE.rows(),2);
+  for(int e = 0;e<BE.rows();e++)
+  {
+    BET(e,0) = 2*e;
+    BET(e,1) = 2*e+1;
+    Affine3d a = vA[e];
+    Vector3d c0 = C.row(BE(e,0));
+    Vector3d c1 = C.row(BE(e,1));
+    CT.row(2*e) =   a * c0;
+    CT.row(2*e+1) = a * c1;
+  }
+
+}
+
+IGL_INLINE void igl::deform_skeleton(
+  const Eigen::MatrixXd & C,
+  const Eigen::MatrixXi & BE,
+  const Eigen::MatrixXd & T,
+  Eigen::MatrixXd & CT,
+  Eigen::MatrixXi & BET)
+{
+  using namespace Eigen;
+  //assert(BE.rows() == (int)vA.size());
+  CT.resize(2*BE.rows(),C.cols());
+  BET.resize(BE.rows(),2);
+  for(int e = 0;e<BE.rows();e++)
+  {
+    BET(e,0) = 2*e;
+    BET(e,1) = 2*e+1;
+    Affine3d a;
+    a.matrix() = T.block(e*4,0,4,3).transpose();
+    Vector3d c0 = C.row(BE(e,0));
+    Vector3d c1 = C.row(BE(e,1));
+    CT.row(2*e) =   a * c0;
+    CT.row(2*e+1) = a * c1;
+  }
+}

+ 39 - 0
include/igl/deform_skeleton.h

@@ -0,0 +1,39 @@
+#ifndef IGL_DEFORM_SKELETON_H
+#define IGL_DEFORM_SKELETON_H
+#include "igl_inline.h"
+#include <Eigen/Core>
+#include <Eigen/Geometry>
+#include <vector>
+namespace igl
+{
+  // Deform a skeleton.
+  //
+  // Inputs:
+  //   C  #C by 3 list of joint positions
+  //   BE  #BE by 2 list of bone edge indices
+  //   vA  #BE list of bone transformations
+  // Outputs
+  //   CT  #BE*2 by 3 list of deformed joint positions
+  //   BET  #BE by 2 list of bone edge indices (maintains order)
+  //
+  IGL_INLINE void deform_skeleton(
+    const Eigen::MatrixXd & C,
+    const Eigen::MatrixXi & BE,
+    const std::vector<
+      Eigen::Affine3d,Eigen::aligned_allocator<Eigen::Affine3d> > & vA,
+    Eigen::MatrixXd & CT,
+    Eigen::MatrixXi & BET);
+  // Inputs:
+  //   T  #BE*4 by 3 list of stacked transformation matrix
+  IGL_INLINE void deform_skeleton(
+    const Eigen::MatrixXd & C,
+    const Eigen::MatrixXi & BE,
+    const Eigen::MatrixXd & T,
+    Eigen::MatrixXd & CT,
+    Eigen::MatrixXi & BET);
+}
+  
+#ifndef IGL_STATIC_LIBRARY
+#  include "deform_skeleton.cpp"
+#endif
+#endif

+ 27 - 0
include/igl/directed_edge_parents.cpp

@@ -0,0 +1,27 @@
+#include "directed_edge_parents.h"
+#include "slice_into.h"
+#include "slice.h"
+#include "colon.h"
+#include "setdiff.h"
+#include <algorithm>
+
+template <typename DerivedE, typename DerivedP>
+IGL_INLINE void igl::directed_edge_parents(
+  const Eigen::PlainObjectBase<DerivedE> & E,
+  Eigen::PlainObjectBase<DerivedP> & P)
+{
+  using namespace Eigen;
+  using namespace std;
+  VectorXi I = VectorXi::Constant(E.maxCoeff()+1,1,-1);
+  //I(E.col(1)) = 0:E.rows()-1
+  slice_into(colon<int>(0,E.rows()-1),E.col(1).eval(),I);
+  VectorXi roots,_;
+  setdiff(E.col(0).eval(),E.col(1).eval(),roots,_);
+  for_each(roots.data(),roots.data()+roots.size(),[&](int r){I(r)=-1;});
+  slice(I,E.col(0).eval(),P);
+}
+
+#ifdef IGL_STATIC_LIBRARY
+// Explicit template instanciation
+template void igl::directed_edge_parents<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
+#endif

+ 32 - 0
include/igl/directed_edge_parents.h

@@ -0,0 +1,32 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+// 
+// Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com>
+// 
+// This Source Code Form is subject to the terms of the Mozilla Public License 
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can 
+// obtain one at http://mozilla.org/MPL/2.0/.
+#ifndef IGL_DIRECTED_EDGE_PARENTS_H
+#define IGL_DIRECTED_EDGE_PARENTS_H
+#include "igl_inline.h"
+
+#include <Eigen/Dense>
+
+namespace igl
+{
+  // Recover "parents" (preceeding edges) in a tree given just directed edges.
+  //
+  // Inputs:
+  //   E  #E by 2 list of directed edges
+  // Outputs:
+  //   P  #E list of parent indices into E (-1) means root
+  //
+  template <typename DerivedE, typename DerivedP>
+  IGL_INLINE void directed_edge_parents(
+    const Eigen::PlainObjectBase<DerivedE> & E,
+    Eigen::PlainObjectBase<DerivedP> & P);
+}
+
+#ifndef IGL_STATIC_LIBRARY
+#  include "directed_edge_parents.cpp"
+#endif
+#endif

+ 21 - 21
include/igl/edge_topology.cpp

@@ -1,21 +1,21 @@
 // This file is part of libigl, a simple c++ geometry processing library.
-// 
+//
 // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
-// 
-// This Source Code Form is subject to the terms of the Mozilla Public License 
-// v. 2.0. If a copy of the MPL was not distributed with this file, You can 
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
 // obtain one at http://mozilla.org/MPL/2.0/.
 #include "edge_topology.h"
 #include <algorithm>
 #include "is_edge_manifold.h"
 
-
+template<typename DerivedV, typename DerivedF>
 IGL_INLINE void igl::edge_topology(
-  const Eigen::MatrixXd& V, 
-  const Eigen::MatrixXi& F, 
-  Eigen::MatrixXi& EV, 
-  Eigen::MatrixXi& FE, 
-  Eigen::MatrixXi& EF)
+                                   const Eigen::PlainObjectBase<DerivedV>& V,
+                                   const Eigen::PlainObjectBase<DerivedF>& F,
+                                   Eigen::MatrixXi& EV,
+                                   Eigen::MatrixXi& FE,
+                                   Eigen::MatrixXi& EF)
 {
   // Only needs to be edge-manifold
   assert(igl::is_edge_manifold(V,F));
@@ -23,7 +23,7 @@ IGL_INLINE void igl::edge_topology(
   for(int f=0;f<F.rows();++f)
     for (int i=0;i<3;++i)
     {
-      // v1 v2 f vi 
+      // v1 v2 f vi
       int v1 = F(f,i);
       int v2 = F(f,(i+1)%3);
       if (v1 > v2) std::swap(v1,v2);
@@ -33,23 +33,23 @@ IGL_INLINE void igl::edge_topology(
       ETT.push_back(r);
     }
   std::sort(ETT.begin(),ETT.end());
-  
+
   // count the number of edges (assume manifoldness)
   int En = 1; // the last is always counted
   for(unsigned i=0;i<ETT.size()-1;++i)
     if (!((ETT[i][0] == ETT[i+1][0]) && (ETT[i][1] == ETT[i+1][1])))
       ++En;
-  
+
   EV = Eigen::MatrixXi::Constant((int)(En),2,-1);
   FE = Eigen::MatrixXi::Constant((int)(F.rows()),3,-1);
   EF = Eigen::MatrixXi::Constant((int)(En),2,-1);
   En = 0;
-  
+
   for(unsigned i=0;i<ETT.size();++i)
   {
     if (i == ETT.size()-1 ||
-      !((ETT[i][0] == ETT[i+1][0]) && (ETT[i][1] == ETT[i+1][1]))
-      )
+        !((ETT[i][0] == ETT[i+1][0]) && (ETT[i][1] == ETT[i+1][1]))
+        )
     {
       // Border edge
       std::vector<int>& r1 = ETT[i];
@@ -57,7 +57,7 @@ IGL_INLINE void igl::edge_topology(
       EV(En,1)     = r1[1];
       EF(En,0)    = r1[2];
       FE(r1[2],r1[3]) = En;
-    } 
+    }
     else
     {
       std::vector<int>& r1 = ETT[i];
@@ -72,10 +72,10 @@ IGL_INLINE void igl::edge_topology(
     }
     ++En;
   }
-  
+
   // Sort the relation EF, accordingly to EV
   // the first one is the face on the left of the edge
-  
+
   for(unsigned i=0; i<EF.rows(); ++i)
   {
     int fid = EF(i,0);
@@ -86,7 +86,7 @@ IGL_INLINE void igl::edge_topology(
       if ((F(fid,j) == EV(i,0)) && (F(fid,(j+1)%3) == EV(i,1)))
         flip = false;
     }
-    
+
     if (flip)
     {
       int tmp = EF(i,0);
@@ -94,7 +94,7 @@ IGL_INLINE void igl::edge_topology(
       EF(i,1) = tmp;
     }
   }
-  
+
 }
 
 #ifdef IGL_STATIC_LIBRARY

+ 3 - 2
include/igl/edge_topology.h

@@ -21,9 +21,10 @@ namespace igl
   // EV  : #Ex2, Stores the edge description as pair of indices to vertices
   // FE : #Fx3, Stores the Triangle-Edge relation
   // EF : #Ex2: Stores the Edge-Triangle relation
+template <typename DerivedV, typename DerivedF>
   IGL_INLINE void edge_topology(
-    const Eigen::MatrixXd& V, 
-    const Eigen::MatrixXi& F, 
+    const Eigen::PlainObjectBase<DerivedV>& V,
+    const Eigen::PlainObjectBase<DerivedF>& F, 
     Eigen::MatrixXi& EV, 
     Eigen::MatrixXi& FE, 
     Eigen::MatrixXi& EF);

+ 34 - 0
include/igl/find.cpp

@@ -8,6 +8,7 @@
 #include "find.h"
 
 #include "verbose.h"
+#include <iostream>
   
 template <
   typename T, 
@@ -39,6 +40,39 @@ IGL_INLINE void igl::find(
     }
   }
 }
+
+template <
+  typename DerivedX,
+  typename DerivedI, 
+  typename DerivedJ,
+  typename DerivedV>
+IGL_INLINE void igl::find(
+  const Eigen::PlainObjectBase<DerivedX>& X,
+  Eigen::PlainObjectBase<DerivedI> & I,
+  Eigen::PlainObjectBase<DerivedJ> & J,
+  Eigen::PlainObjectBase<DerivedV> & V)
+{
+  const int nnz = X.template cast<bool>().template cast<int>().sum();
+  I.resize(nnz,1);
+  J.resize(nnz,1);
+  V.resize(nnz,1);
+  {
+    int k = 0;
+    for(int j = 0;j<X.cols();j++)
+    {
+      for(int i = 0;i<X.rows();i++)
+      {
+        if(X(i,j))
+        {
+          I(k) = i;
+          J(k) = j;
+          V(k) = X(i,j);
+          k++;
+        }
+      }
+    }
+  }
+}
   
 template <typename T>
 IGL_INLINE void igl::find(

+ 10 - 0
include/igl/find.h

@@ -35,6 +35,16 @@ namespace igl
     Eigen::MatrixBase<DerivedI> & I,
     Eigen::MatrixBase<DerivedJ> & J,
     Eigen::MatrixBase<DerivedV> & V);
+  template <
+    typename DerivedX,
+    typename DerivedI, 
+    typename DerivedJ,
+    typename DerivedV>
+  IGL_INLINE void find(
+    const Eigen::PlainObjectBase<DerivedX>& X,
+    Eigen::PlainObjectBase<DerivedI> & I,
+    Eigen::PlainObjectBase<DerivedJ> & J,
+    Eigen::PlainObjectBase<DerivedV> & V);
   // Find the non-zero entries and there respective indices in a sparse vector.
   // Similar to matlab's [I,J,V] = find(X), but instead of [I,J] being
   // subscripts into X, since X is a vector we just return I, a list of indices

+ 27 - 13
include/igl/harmonic.cpp

@@ -12,17 +12,25 @@
 #include "min_quad_with_fixed.h"
 #include <Eigen/Sparse>
 
+template <
+  typename DerivedV,
+  typename DerivedF,
+  typename Derivedb,
+  typename Derivedbc,
+  typename DerivedW>
 IGL_INLINE bool igl::harmonic(
-  const Eigen::MatrixXd & V,
-  const Eigen::MatrixXi & F,
-  const Eigen::VectorXi & b,
-  const Eigen::MatrixXd & bc,
+  const Eigen::PlainObjectBase<DerivedV> & V,
+  const Eigen::PlainObjectBase<DerivedF> & F,
+  const Eigen::PlainObjectBase<Derivedb> & b,
+  const Eigen::PlainObjectBase<Derivedbc> & bc,
   const int k,
-  Eigen::MatrixXd & W)
+  Eigen::PlainObjectBase<DerivedW> & W)
 {
   using namespace igl;
   using namespace Eigen;
-  SparseMatrix<double> L,M,Mi;
+  typedef typename DerivedV::Scalar Scalar;
+  typedef Matrix<Scalar,Dynamic,1> VectorXS;
+  SparseMatrix<Scalar> L,M,Mi;
   cotmatrix(V,F,L);
   switch(F.cols())
   {
@@ -35,20 +43,20 @@ IGL_INLINE bool igl::harmonic(
       break;
   }
   invert_diag(M,Mi);
-  SparseMatrix<double> Q = -L;
+  SparseMatrix<Scalar> Q = -L;
   for(int p = 1;p<k;p++)
   {
     Q = (Q*Mi*-L).eval();
   }
-  const VectorXd B = VectorXd::Zero(V.rows(),1);
-  min_quad_with_fixed_data<double> data;
-  min_quad_with_fixed_precompute(Q,b,SparseMatrix<double>(),true,data);
+  const VectorXS B = VectorXS::Zero(V.rows(),1);
+  min_quad_with_fixed_data<Scalar> data;
+  min_quad_with_fixed_precompute(Q,b,SparseMatrix<Scalar>(),true,data);
   W.resize(V.rows(),bc.cols());
   for(int w = 0;w<bc.cols();w++)
   {
-    const VectorXd bcw = bc.col(w);
-    VectorXd Ww;
-    if(!min_quad_with_fixed_solve(data,B,bcw,VectorXd(),Ww))
+    const VectorXS bcw = bc.col(w);
+    VectorXS Ww;
+    if(!min_quad_with_fixed_solve(data,B,bcw,VectorXS(),Ww))
     {
       return false;
     }
@@ -56,3 +64,9 @@ IGL_INLINE bool igl::harmonic(
   }
   return true;
 }
+
+#ifdef IGL_STATIC_LIBRARY
+// Explicit template instanciation
+template bool igl::harmonic<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&); 
+template bool igl::harmonic<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
+#endif

+ 11 - 5
include/igl/harmonic.h

@@ -23,13 +23,19 @@ namespace igl
   // Outputs:
   //   W  #V by #W list of weights
   //
+  template <
+    typename DerivedV,
+    typename DerivedF,
+    typename Derivedb,
+    typename Derivedbc,
+    typename DerivedW>
   IGL_INLINE bool harmonic(
-    const Eigen::MatrixXd & V,
-    const Eigen::MatrixXi & F,
-    const Eigen::VectorXi & b,
-    const Eigen::MatrixXd & bc,
+    const Eigen::PlainObjectBase<DerivedV> & V,
+    const Eigen::PlainObjectBase<DerivedF> & F,
+    const Eigen::PlainObjectBase<Derivedb> & b,
+    const Eigen::PlainObjectBase<Derivedbc> & bc,
     const int k,
-    Eigen::MatrixXd & W);
+    Eigen::PlainObjectBase<DerivedW> & W);
 };
 #ifndef IGL_STATIC_LIBRARY
 #include "harmonic.cpp"

+ 1 - 1
include/igl/local_basis.cpp

@@ -38,7 +38,7 @@ IGL_INLINE void igl::local_basis(
       Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v2 = v1.cross(v3).normalized();
 
       B1.row(i) = v1;
-      B2.row(i) = v2;
+      B2.row(i) = -v2;
       B3.row(i) = v3;
   }
 }

+ 498 - 0
include/igl/n_polyvector.cpp

@@ -0,0 +1,498 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#include <igl/n_polyvector.h>
+#include <igl/edge_topology.h>
+#include <igl/local_basis.h>
+#include <igl/nchoosek.h>
+#include <igl/slice.h>
+#include <igl/polyroots.h>
+#include <Eigen/Sparse>
+
+#include <iostream>
+
+namespace igl {
+  template <typename DerivedV, typename DerivedF>
+  class PolyVectorFieldFinder
+  {
+  private:
+    const Eigen::PlainObjectBase<DerivedV> &V;
+    const Eigen::PlainObjectBase<DerivedF> &F; int numF;
+    const int n;
+
+    Eigen::MatrixXi EV; int numE;
+    Eigen::MatrixXi F2E;
+    Eigen::MatrixXi E2F;
+    Eigen::VectorXd K;
+
+    Eigen::VectorXi isBorderEdge;
+    int numInteriorEdges;
+    Eigen::Matrix<int,Eigen::Dynamic,2> E2F_int;
+    Eigen::VectorXi indInteriorToFull;
+    Eigen::VectorXi indFullToInterior;
+
+    Eigen::PlainObjectBase<DerivedV> B1, B2, FN;
+
+    IGL_INLINE void computek();
+    IGL_INLINE void setFieldFromGeneralCoefficients(const  std::vector<Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1>> &coeffs,
+                                                    std::vector<Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2> > &pv);
+    IGL_INLINE void computeCoefficientLaplacian(int n, Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &D);
+    IGL_INLINE void getGeneralCoeffConstraints(const Eigen::VectorXi &isConstrained,
+                                    const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,
+                                    int k,
+                                    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> &Ck);
+    IGL_INLINE void precomputeInteriorEdges();
+
+
+    IGL_INLINE void minQuadWithKnownMini(const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &Q,
+                                         const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &f,
+                                         const Eigen::VectorXi isConstrained,
+                                         const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &xknown,
+                                         Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &x);
+
+  public:
+    IGL_INLINE PolyVectorFieldFinder(const Eigen::PlainObjectBase<DerivedV> &_V,
+                                     const Eigen::PlainObjectBase<DerivedF> &_F,
+                                     const int &_n);
+    IGL_INLINE bool solve(const Eigen::VectorXi &isConstrained,
+               const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,
+               Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &output);
+
+  };
+}
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE igl::PolyVectorFieldFinder<DerivedV, DerivedF>::
+          PolyVectorFieldFinder(const Eigen::PlainObjectBase<DerivedV> &_V,
+                                const Eigen::PlainObjectBase<DerivedF> &_F,
+                                const int &_n):
+V(_V),
+F(_F),
+numF(_F.rows()),
+n(_n)
+{
+
+  igl::edge_topology(V,F,EV,F2E,E2F);
+  numE = EV.rows();
+
+
+  precomputeInteriorEdges();
+
+  igl::local_basis(V,F,B1,B2,FN);
+
+  computek();
+
+};
+
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::
+precomputeInteriorEdges()
+{
+  // Flag border edges
+  numInteriorEdges = 0;
+  isBorderEdge.setZero(numE,1);
+  indFullToInterior = -1.*Eigen::VectorXi::Ones(numE,1);
+
+  for(unsigned i=0; i<numE; ++i)
+  {
+    if ((E2F(i,0) == -1) || ((E2F(i,1) == -1)))
+      isBorderEdge[i] = 1;
+      else
+      {
+        indFullToInterior[i] = numInteriorEdges;
+        numInteriorEdges++;
+      }
+  }
+
+  E2F_int.resize(numInteriorEdges, 2);
+  indInteriorToFull.setZero(numInteriorEdges,1);
+  int ii = 0;
+  for (int k=0; k<numE; ++k)
+  {
+    if (isBorderEdge[k])
+      continue;
+    E2F_int.row(ii) = E2F.row(k);
+    indInteriorToFull[ii] = k;
+    ii++;
+  }
+
+}
+
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::
+minQuadWithKnownMini(const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &Q,
+                          const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &f,
+                     const Eigen::VectorXi isConstrained,
+                          const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &xknown,
+                          Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &x)
+{
+  int N = Q.rows();
+
+  int nc = xknown.rows();
+  Eigen::VectorXi known; known.setZero(nc,1);
+  Eigen::VectorXi unknown; unknown.setZero(N-nc,1);
+
+  int indk = 0, indu = 0;
+  for (int i = 0; i<N; ++i)
+    if (isConstrained[i])
+    {
+      known[indk] = i;
+      indk++;
+    }
+    else
+    {
+      unknown[indu] = i;
+      indu++;
+    }
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>> Quu, Quk;
+
+  igl::slice(Q,unknown, unknown, Quu);
+  igl::slice(Q,unknown, known, Quk);
+
+
+  std::vector<typename Eigen::Triplet<std::complex<typename DerivedV::Scalar> > > tripletList;
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fu(N-nc,1);
+
+  igl::slice(f,unknown, Eigen::VectorXi::Zero(1,1), fu);
+
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > rhs = (Quk*xknown).sparseView()+.5*fu;
+
+  Eigen::SparseLU< Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>>> solver;
+  solver.compute(-Quu);
+  if(solver.info()!=Eigen::Success)
+  {
+    std::cerr<<"Decomposition failed!"<<std::endl;
+    return;
+  }
+  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>>  b  = solver.solve(rhs);
+  if(solver.info()!=Eigen::Success)
+  {
+    std::cerr<<"Solving failed!"<<std::endl;
+    return;
+  }
+
+  indk = 0, indu = 0;
+  x.setZero(N,1);
+  for (int i = 0; i<N; ++i)
+    if (isConstrained[i])
+      x[i] = xknown[indk++];
+    else
+      x[i] = b.coeff(indu++,0);
+
+}
+
+
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE bool igl::PolyVectorFieldFinder<DerivedV, DerivedF>::
+                     solve(const Eigen::VectorXi &isConstrained,
+                           const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,
+                           Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &output)
+{
+
+  // polynomial is of the form:
+  // (-1)^0 z^(2n) +
+  // (-1)^1 c[0]z^(2n-2) +
+  // (-1)^2 c[1]z^(2n-4) +
+  // (-1)^3 c[2]z^(2n-6) +
+  // ... +
+  // (-1)^n c[n-1]
+
+  std::vector<Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1>> coeffs(n,Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1>::Zero(numF, 1));
+
+  for (int i =0; i<n; ++i)
+  {
+    int degree = 2*(i+1);
+
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> Ck;
+    getGeneralCoeffConstraints(isConstrained,
+                               cfW,
+                               i,
+                               Ck);
+
+    Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > DD;
+    computeCoefficientLaplacian(degree, DD);
+    Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > f; f.resize(numF,1);
+
+    minQuadWithKnownMini(DD, f, isConstrained, Ck, coeffs[i]);
+  }
+
+  std::vector<Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2> > pv;
+  setFieldFromGeneralCoefficients(coeffs, pv);
+
+  output.setZero(numF,3*n);
+  for (int fi=0; fi<numF; ++fi)
+  {
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = B1.row(fi);
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = B2.row(fi);
+    for (int i=0; i<n; ++i)
+      output.block(fi,3*i, 1, 3) = pv[i](fi,0)*b1 + pv[i](fi,1)*b2;
+  }
+  return true;
+}
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::setFieldFromGeneralCoefficients(const  std::vector<Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1>> &coeffs,
+                                                            std::vector<Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2>> &pv)
+{
+  pv.assign(n, Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2>::Zero(numF, 2));
+  for (int i = 0; i <numF; ++i)
+  {
+
+    //    poly coefficients: 1, 0, -Acoeff, 0, Bcoeff
+    //    matlab code from roots (given there are no trailing zeros in the polynomial coefficients)
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> polyCoeff;
+    polyCoeff.setZero(2*n+1,1);
+    polyCoeff[0] = 1.;
+    int sign = 1;
+    for (int k =0; k<n; ++k)
+    {
+      sign = -sign;
+      int degree = 2*(k+1);
+      polyCoeff[degree] = (1.*sign)*coeffs[k](i);
+    }
+
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> roots;
+    igl::polyRoots<std::complex<typename DerivedV::Scalar>, typename DerivedV::Scalar >(polyCoeff,roots);
+
+    Eigen::VectorXi done; done.setZero(2*n,1);
+
+    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> u(n,1);
+    int ind =0;
+    for (int k=0; k<2*n; ++k)
+    {
+      if (done[k])
+        continue;
+      u[ind] = roots[k];
+      done[k] = 1;
+
+      int mini = -1;
+      double mind = 1e10;
+      for (int l =k+1; l<2*n; ++l)
+      {
+        double dist = abs(roots[l]+u[ind]);
+        if (dist<mind)
+        {
+          mind = dist;
+          mini = l;
+        }
+      }
+      done[mini] = 1;
+      ind ++;
+    }
+    for (int k=0; k<n; ++k)
+    {
+      pv[k](i,0) = real(u[k]);
+      pv[k](i,1) = imag(u[k]);
+    }
+  }
+
+}
+
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::computeCoefficientLaplacian(int n, Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &D)
+{
+  std::vector<Eigen::Triplet<std::complex<typename DerivedV::Scalar> >> tripletList;
+
+  // For every non-border edge
+  for (unsigned eid=0; eid<numE; ++eid)
+  {
+    if (!isBorderEdge[eid])
+    {
+      int fid0 = E2F(eid,0);
+      int fid1 = E2F(eid,1);
+
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid0,
+                                           fid0,
+                                           std::complex<typename DerivedV::Scalar>(1.)));
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid1,
+                                           fid1,
+                                           std::complex<typename DerivedV::Scalar>(1.)));
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid0,
+                                           fid1,
+                                                                                     -1.*std::polar(1.,-1.*n*K[eid])));
+      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid1,
+                                           fid0,
+                                                                                     -1.*std::polar(1.,1.*n*K[eid])));
+
+    }
+  }
+  D.resize(numF,numF);
+  D.setFromTriplets(tripletList.begin(), tripletList.end());
+
+
+}
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::getGeneralCoeffConstraints(const Eigen::VectorXi &isConstrained,
+                                                       const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,
+                                                       int k,
+                                                       Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> &Ck)
+{
+  int numConstrained = isConstrained.sum();
+  Ck.resize(numConstrained,1);
+  int n = cfW.cols()/3;
+
+  std::vector<std::vector<int>> allCombs;
+  igl::nchoosek(0,k+1,n,allCombs);
+
+  int ind = 0;
+  for (int fi = 0; fi <numF; ++fi)
+  {
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = B1.row(fi);
+    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = B2.row(fi);
+    if(isConstrained[fi])
+    {
+      std::complex<typename DerivedV::Scalar> ck(0);
+
+      for (int j = 0; j < allCombs.size(); ++j)
+      {
+        std::complex<typename DerivedV::Scalar> tk(1.);
+        //collect products
+        for (int i = 0; i < allCombs[j].size(); ++i)
+        {
+          int index = allCombs[j][i];
+
+          const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &w = cfW.block(fi,3*index,1,3);
+          typename DerivedV::Scalar w0 = w.dot(b1);
+          typename DerivedV::Scalar w1 = w.dot(b2);
+          std::complex<typename DerivedV::Scalar> u(w0,w1);
+          tk*= u*u;
+        }
+        //collect sum
+        ck += tk;
+      }
+      Ck(ind) = ck;
+      ind ++;
+    }
+  }
+
+
+}
+
+template<typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::computek()
+{
+  K.setZero(numE);
+  // For every non-border edge
+  for (unsigned eid=0; eid<numE; ++eid)
+  {
+    if (!isBorderEdge[eid])
+    {
+      int fid0 = E2F(eid,0);
+      int fid1 = E2F(eid,1);
+
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N0 = FN.row(fid0);
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N1 = FN.row(fid1);
+
+      // find common edge on triangle 0 and 1
+      int fid0_vc = -1;
+      int fid1_vc = -1;
+      for (unsigned i=0;i<3;++i)
+      {
+        if (F2E(fid0,i) == eid)
+          fid0_vc = i;
+        if (F2E(fid1,i) == eid)
+          fid1_vc = i;
+      }
+      assert(fid0_vc != -1);
+      assert(fid1_vc != -1);
+
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> common_edge = V.row(F(fid0,(fid0_vc+1)%3)) - V.row(F(fid0,fid0_vc));
+      common_edge.normalize();
+
+      // Map the two triangles in a new space where the common edge is the x axis and the N0 the z axis
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> P;
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> o = V.row(F(fid0,fid0_vc));
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> tmp = -N0.cross(common_edge);
+      P << common_edge, tmp, N0;
+//      P.transposeInPlace();
+
+
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V0;
+      V0.row(0) = V.row(F(fid0,0)) -o;
+      V0.row(1) = V.row(F(fid0,1)) -o;
+      V0.row(2) = V.row(F(fid0,2)) -o;
+
+      V0 = (P*V0.transpose()).transpose();
+
+//      assert(V0(0,2) < 1e-10);
+//      assert(V0(1,2) < 1e-10);
+//      assert(V0(2,2) < 1e-10);
+
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V1;
+      V1.row(0) = V.row(F(fid1,0)) -o;
+      V1.row(1) = V.row(F(fid1,1)) -o;
+      V1.row(2) = V.row(F(fid1,2)) -o;
+      V1 = (P*V1.transpose()).transpose();
+
+//      assert(V1(fid1_vc,2) < 10e-10);
+//      assert(V1((fid1_vc+1)%3,2) < 10e-10);
+
+      // compute rotation R such that R * N1 = N0
+      // i.e. map both triangles to the same plane
+      double alpha = -atan2(V1((fid1_vc+2)%3,2),V1((fid1_vc+2)%3,1));
+
+      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> R;
+      R << 1,          0,            0,
+      0, cos(alpha), -sin(alpha) ,
+      0, sin(alpha),  cos(alpha);
+      V1 = (R*V1.transpose()).transpose();
+
+//      assert(V1(0,2) < 1e-10);
+//      assert(V1(1,2) < 1e-10);
+//      assert(V1(2,2) < 1e-10);
+
+      // measure the angle between the reference frames
+      // k_ij is the angle between the triangle on the left and the one on the right
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref0 = V0.row(1) - V0.row(0);
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref1 = V1.row(1) - V1.row(0);
+
+      ref0.normalize();
+      ref1.normalize();
+
+      double ktemp = atan2(ref1(1),ref1(0)) - atan2(ref0(1),ref0(0));
+
+      // just to be sure, rotate ref0 using angle ktemp...
+      Eigen::Matrix<typename DerivedV::Scalar, 2, 2> R2;
+      R2 << cos(ktemp), -sin(ktemp), sin(ktemp), cos(ktemp);
+
+      Eigen::Matrix<typename DerivedV::Scalar, 1, 2> tmp1 = R2*(ref0.head(2)).transpose();
+
+//      assert(tmp1(0) - ref1(0) < 1e-10);
+//      assert(tmp1(1) - ref1(1) < 1e-10);
+
+      K[eid] = ktemp;
+    }
+  }
+
+}
+
+
+template <typename DerivedV, typename DerivedF>
+IGL_INLINE void igl::n_polyvector(const Eigen::PlainObjectBase<DerivedV> &V,
+                             const Eigen::PlainObjectBase<DerivedF> &F,
+                             const Eigen::VectorXi &isConstrained,
+                             const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,
+                             Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &output)
+{
+  int n = cfW.cols()/3;
+  igl::PolyVectorFieldFinder<DerivedV, DerivedF> pvff(V,F,n);
+  pvff.solve(isConstrained, cfW, output);
+}
+
+
+#ifdef IGL_STATIC_LIBRARY
+// Explicit template specialization
+template void igl::n_polyvector<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<int, -1, 1, 0, -1, 1> const&, Eigen::Matrix<Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, -1, -1, 0, -1, -1> const&, Eigen::Matrix<Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, -1, -1, 0, -1, -1>&);
+#endif

+ 41 - 0
include/igl/n_polyvector.h

@@ -0,0 +1,41 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef IGL_N_POLYVECTOR
+#define IGL_N_POLYVECTOR
+#include "igl_inline.h"
+
+#include <Eigen/Core>
+#include <vector>
+
+namespace igl {
+  //todo
+  /// Given 2 vectors centered on origin calculate the rotation matrix from first to the second
+
+  // Inputs:
+  //   v0, v1         the two #3 by 1 vectors
+  //   normalized     boolean, if false, then the vectors are normalized prior to the calculation
+  // Output:
+  //                  3 by 3 rotation matrix that takes v0 to v1
+  //
+  template <typename DerivedV, typename DerivedF>
+  IGL_INLINE void n_polyvector(const Eigen::PlainObjectBase<DerivedV> &V,
+                               const Eigen::PlainObjectBase<DerivedF> &F,
+                               const Eigen::VectorXi &isConstrained,
+                               const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,
+                               Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &output);
+
+};
+
+
+#ifndef IGL_STATIC_LIBRARY
+#include "n_polyvector.cpp"
+#endif
+
+
+#endif /* defined(IGL_N_POLYVECTOR) */

+ 58 - 0
include/igl/nchoosek.cpp

@@ -0,0 +1,58 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#include "nchoosek.h"
+
+namespace igl {
+  class CombinationFinder
+  {
+  private:
+    std::vector<int> combinations;
+    void add(const std::vector<int>& v,
+             std::vector<std::vector<int>> &allCombs)
+    {
+      allCombs.push_back(v);
+    }
+
+  public:
+    void doCombs(int offset,
+                 int k,
+                 int N,
+                 std::vector<std::vector<int>> &allCombs)
+    {
+      if (k == 0) {
+        add(combinations,allCombs);
+        return;
+      }
+      for (int i = offset; i <= N - k; ++i) {
+        combinations.push_back(i);
+        doCombs(i+1, k-1, N,allCombs);
+        combinations.pop_back();
+      }
+    }
+
+  };
+
+
+}
+
+IGL_INLINE void igl::nchoosek(int offset,
+                              int k,
+                              int N,
+                              std::vector<std::vector<int>> &allCombs)
+{
+  CombinationFinder cmbf;
+  allCombs.clear();
+  cmbf.doCombs(offset,k,N,allCombs);
+}
+
+
+
+#ifdef IGL_STATIC_LIBRARY
+// Explicit template specialization
+#endif

+ 38 - 0
include/igl/nchoosek.h

@@ -0,0 +1,38 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef IGL_NCHOOSEK
+#define IGL_NCHOOSEK
+#include "igl_inline.h"
+#include <vector>
+
+#include <Eigen/Core>
+
+namespace igl {
+  //todo
+  /// Given 2 vectors centered on origin calculate the rotation matrix from first to the second
+
+  // Inputs:
+  //   v0, v1         the two #3 by 1 vectors
+  //   normalized     boolean, if false, then the vectors are normalized prior to the calculation
+  // Output:
+  //                  3 by 3 rotation matrix that takes v0 to v1
+  //
+  IGL_INLINE void nchoosek(int offset,
+                           int k,
+                           int N,
+                           std::vector<std::vector<int>> &allCombs);
+}
+
+
+#ifndef IGL_STATIC_LIBRARY
+#include "nchoosek.cpp"
+#endif
+
+
+#endif /* defined(IGL_NCHOOSEK) */

+ 35 - 0
include/igl/polyroots.cpp

@@ -0,0 +1,35 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#include "polyroots.h"
+
+template <typename S, typename T>
+IGL_INLINE void igl::polyRoots(Eigen::Matrix<S, Eigen::Dynamic,1> &polyCoeff, //real or comples coefficients
+                          Eigen::Matrix<std::complex<T>, Eigen::Dynamic,1> &roots // complex roots (double or float)
+)
+{
+  //  degree
+  int n = polyCoeff.rows() - 1;
+
+  Eigen::Matrix<S, Eigen::Dynamic, 1> d (n,1);
+  d = polyCoeff.tail(n)/polyCoeff(0);
+
+  Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic> I; I.setIdentity(n-1,n-1);
+  Eigen::Matrix<S, Eigen::Dynamic, 1> z; z.setZero(n-1,1);
+
+  Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic> a(n,n);
+  a<<-d.transpose(),I,z;
+  roots = a.eigenvalues();
+
+}
+
+
+
+#ifdef IGL_STATIC_LIBRARY
+// Explicit template specialization
+#endif

+ 37 - 0
include/igl/polyroots.h

@@ -0,0 +1,37 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef IGL_POLYROOTS
+#define IGL_POLYROOTS
+#include "igl_inline.h"
+
+#include <Eigen/Core>
+
+namespace igl {
+  //todo
+  /// Given 2 vectors centered on origin calculate the rotation matrix from first to the second
+
+  // Inputs:
+  //   v0, v1         the two #3 by 1 vectors
+  //   normalized     boolean, if false, then the vectors are normalized prior to the calculation
+  // Output:
+  //                  3 by 3 rotation matrix that takes v0 to v1
+  //
+  template <typename S, typename T>
+  IGL_INLINE void polyRoots(Eigen::Matrix<S, Eigen::Dynamic,1> &polyCoeff, //real or comples coefficients
+                            Eigen::Matrix<std::complex<T>, Eigen::Dynamic,1> &roots // complex roots (double or float)
+                            );
+}
+
+
+#ifndef IGL_STATIC_LIBRARY
+#include "polyroots.cpp"
+#endif
+
+
+#endif /* defined(IGL_NCHOOSEK) */

+ 33 - 4
include/igl/project.cpp

@@ -1,12 +1,13 @@
 // This file is part of libigl, a simple c++ geometry processing library.
-// 
+//
 // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
-// 
-// This Source Code Form is subject to the terms of the Mozilla Public License 
-// v. 2.0. If a copy of the MPL was not distributed with this file, You can 
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
 // obtain one at http://mozilla.org/MPL/2.0/.
 #include "project.h"
 #ifndef IGL_NO_OPENGL
+#ifndef IGL_OPENGL_4
 #include <iostream>
 #include "report_gl_error.h"
 
@@ -110,7 +111,34 @@ IGL_INLINE Eigen::PlainObjectBase<Derivedobj> igl::project(
   return win;
 }
 
+#endif
+#endif
+
+Eigen::Vector3f igl::project(const Eigen::Vector3f&  obj,
+                        const Eigen::Matrix4f& model,
+                        const Eigen::Matrix4f& proj,
+                        const Eigen::Vector4f&  viewport)
+{
+  Eigen::Vector4f tmp;
+  tmp << obj,1;
+
+  tmp = model * tmp;
+
+  tmp = proj * tmp;
+
+  tmp = tmp.array() / tmp(3);
+  tmp = tmp.array() * 0.5f + 0.5f;
+  tmp(0) = tmp(0) * viewport(2) + viewport(0);
+  tmp(1) = tmp(1) * viewport(3) + viewport(1);
+
+  return tmp.head(3);
+}
+
+
 #ifdef IGL_STATIC_LIBRARY
+
+#ifndef IGL_NO_OPENGL
+#ifndef IGL_OPENGL_4
 // Explicit template instanciations
 template int igl::project<Eigen::Matrix<double, 3, 1, 0, 3, 1>, Eigen::Matrix<double, 3, 1, 0, 3, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 1, 0, 3, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 1, 0, 3, 1> >&);
 template Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 1, 0, 3, 1> > igl::project<Eigen::Matrix<double, 3, 1, 0, 3, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 1, 0, 3, 1> > const&);
@@ -119,5 +147,6 @@ template Eigen::PlainObjectBase<Eigen::Matrix<float, 3, 1, 0, 3, 1> > igl::proje
 template Eigen::PlainObjectBase<Eigen::Matrix<double, 1, -1, 1, 1, -1> > igl::project<Eigen::Matrix<double, 1, -1, 1, 1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, 1, -1, 1, 1, -1> > const&);
 template int igl::project<Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<double, 1, 3, 1, 1, 3> >(Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> >&);
 #endif
+#endif
 
 #endif

+ 19 - 4
include/igl/project.h

@@ -1,9 +1,9 @@
 // This file is part of libigl, a simple c++ geometry processing library.
-// 
+//
 // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
-// 
-// This Source Code Form is subject to the terms of the Mozilla Public License 
-// v. 2.0. If a copy of the MPL was not distributed with this file, You can 
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
 // obtain one at http://mozilla.org/MPL/2.0/.
 #ifndef IGL_PROJECT_H
 #define IGL_PROJECT_H
@@ -34,6 +34,21 @@ namespace igl
   template <typename Derivedobj>
   IGL_INLINE Eigen::PlainObjectBase<Derivedobj> project(
     const Eigen::PlainObjectBase<Derivedobj> & obj);
+
+  // Eigen reimplementation of gluProject
+// Inputs:
+//   obj*  3D objects' x, y, and z coordinates respectively
+// model        model matrix
+// proj         projection matrix
+// viewport     viewport vector
+// Returns:
+//   screen space x, y, and z coordinates respectively
+// Returns return value of gluProject call
+  Eigen::Vector3f project(const Eigen::Vector3f&  obj,
+                          const Eigen::Matrix4f& model,
+                          const Eigen::Matrix4f& proj,
+                          const Eigen::Vector4f&  viewport);
+
 }
 
 #ifndef IGL_STATIC_LIBRARY

+ 2 - 2
include/igl/readOBJ.cpp

@@ -244,7 +244,7 @@ IGL_INLINE bool igl::readOBJ(
     }
   }
 
-  if(!vFN.empty())
+  if(!vFN.empty() && !vFN[0].empty())
   {
     bool FN_rect = igl::list_to_matrix(vFN,FN);
     if(!FN_rect)
@@ -264,7 +264,7 @@ IGL_INLINE bool igl::readOBJ(
       return false;
     }
   }
-  if(!vFTC.empty())
+  if(!vFTC.empty()&& !vFTC[0].empty())
   {
 
     bool FTC_rect = igl::list_to_matrix(vFTC,FTC);

+ 1 - 0
include/igl/unproject.h

@@ -44,6 +44,7 @@ namespace igl
     const Eigen::Matrix4f& model,
     const Eigen::Matrix4f& proj,
     const Eigen::Vector4f& viewport);
+    
   template <typename Derivedwin, typename Derivedobj>
   IGL_INLINE int unproject(
     const Eigen::PlainObjectBase<Derivedwin> & win,

+ 183 - 0
include/igl/viewer/OpenGL_shader.cpp

@@ -0,0 +1,183 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Wenzel Jacob <wenzel@inf.ethz.ch>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#include "OpenGL_shader.h"
+
+#ifdef __APPLE__
+#   include <OpenGL/gl3.h>
+#   define __gl_h_ /* Prevent inclusion of the old gl.h */
+#else
+#   ifdef _WIN32
+#       include <windows.h>
+#   endif
+#   include <GL/gl.h>
+#endif
+
+#include <iostream>
+#include <fstream>
+
+IGL_INLINE bool igl::OpenGL_shader::init_from_files(
+  const std::string &vertex_shader_filename,
+  const std::string &fragment_shader_filename,
+  const std::string &fragment_data_name,
+  const std::string &geometry_shader_filename,
+  int geometry_shader_max_vertices)
+{
+  auto file_to_string = [](const std::string &filename)
+  {
+    std::ifstream t(filename);
+    return std::string((std::istreambuf_iterator<char>(t)),
+                        std::istreambuf_iterator<char>());
+  };
+
+  return init(
+    file_to_string(vertex_shader_filename),
+    file_to_string(fragment_shader_filename),
+    fragment_data_name,
+    file_to_string(geometry_shader_filename),
+    geometry_shader_max_vertices
+ );
+}
+
+IGL_INLINE bool igl::OpenGL_shader::init(
+  const std::string &vertex_shader_string,
+  const std::string &fragment_shader_string,
+  const std::string &fragment_data_name,
+  const std::string &geometry_shader_string,
+  int geometry_shader_max_vertices)
+{
+  using namespace std;
+  vertex_shader = create_shader_helper(GL_VERTEX_SHADER, vertex_shader_string);
+  geometry_shader = create_shader_helper(GL_GEOMETRY_SHADER, geometry_shader_string);
+  fragment_shader = create_shader_helper(GL_FRAGMENT_SHADER, fragment_shader_string);
+
+  if (!vertex_shader || !fragment_shader)
+    return false;
+
+  program_shader = glCreateProgram();
+
+  glAttachShader(program_shader, vertex_shader);
+  glAttachShader(program_shader, fragment_shader);
+
+  if (geometry_shader)
+  {
+    glAttachShader(program_shader, geometry_shader);
+
+    /* This covers only basic cases and may need to be modified */
+    glProgramParameteri(program_shader, GL_GEOMETRY_INPUT_TYPE, GL_TRIANGLES);
+    glProgramParameteri(program_shader, GL_GEOMETRY_OUTPUT_TYPE, GL_TRIANGLES);
+    glProgramParameteri(program_shader, GL_GEOMETRY_VERTICES_OUT, geometry_shader_max_vertices);
+  }
+
+  glBindFragDataLocation(program_shader, 0, fragment_data_name.c_str());
+  glLinkProgram(program_shader);
+
+  GLint status;
+  glGetProgramiv(program_shader, GL_LINK_STATUS, &status);
+
+  if (status != GL_TRUE)
+  {
+    char buffer[512];
+    glGetProgramInfoLog(program_shader, 512, NULL, buffer);
+    cerr << "Linker error: " << endl << buffer << endl;
+    program_shader = 0;
+    return false;
+  }
+
+  return true;
+}
+
+IGL_INLINE void igl::OpenGL_shader::bind()
+{
+  glUseProgram(program_shader);
+}
+
+IGL_INLINE GLint igl::OpenGL_shader::attrib(const std::string &name) const
+{
+  return glGetAttribLocation(program_shader, name.c_str());
+}
+
+IGL_INLINE GLint igl::OpenGL_shader::uniform(const std::string &name) const
+{
+  return glGetUniformLocation(program_shader, name.c_str());
+}
+
+IGL_INLINE GLint igl::OpenGL_shader::bindVertexAttribArray(
+  const std::string &name, GLuint bufferID, const Eigen::MatrixXf &M, bool refresh) const
+{
+  GLint id = attrib(name);
+  if (id < 0)
+    return id;
+  if (M.size() == 0)
+  {
+    glDisableVertexAttribArray(id);
+    return id;
+  }
+  glBindBuffer(GL_ARRAY_BUFFER, bufferID);
+  if (refresh)
+    glBufferData(GL_ARRAY_BUFFER, sizeof(float)*M.size(), M.data(), GL_DYNAMIC_DRAW);
+  glVertexAttribPointer(id, M.rows(), GL_FLOAT, GL_FALSE, 0, 0);
+  glEnableVertexAttribArray(id);
+  return id;
+}
+
+IGL_INLINE void igl::OpenGL_shader::free()
+{
+  if (program_shader)
+  {
+    glDeleteProgram(program_shader);
+    program_shader = 0;
+  }
+  if (vertex_shader)
+  {
+    glDeleteShader(vertex_shader);
+    vertex_shader = 0;
+  }
+  if (fragment_shader)
+  {
+    glDeleteShader(fragment_shader);
+    fragment_shader = 0;
+  }
+  if (geometry_shader)
+  {
+    glDeleteShader(geometry_shader);
+    geometry_shader = 0;
+  }
+}
+
+IGL_INLINE GLuint igl::OpenGL_shader::create_shader_helper(GLint type, const std::string &shader_string)
+{
+  using namespace std;
+  if (shader_string.empty())
+    return (GLuint) 0;
+
+  GLuint id = glCreateShader(type);
+  const char *shader_string_const = shader_string.c_str();
+  glShaderSource(id, 1, &shader_string_const, NULL);
+  glCompileShader(id);
+
+  GLint status;
+  glGetShaderiv(id, GL_COMPILE_STATUS, &status);
+
+  if (status != GL_TRUE)
+  {
+    char buffer[512];
+    if (type == GL_VERTEX_SHADER)
+      cerr << "Vertex shader:" << endl;
+    else if (type == GL_FRAGMENT_SHADER)
+      cerr << "Fragment shader:" << endl;
+    else if (type == GL_GEOMETRY_SHADER)
+      cerr << "Geometry shader:" << endl;
+    cerr << shader_string << endl << endl;
+    glGetShaderInfoLog(id, 512, NULL, buffer);
+    cerr << "Error: " << endl << buffer << endl;
+    return (GLuint) 0;
+  }
+
+  return id;
+}

+ 86 - 0
include/igl/viewer/OpenGL_shader.h

@@ -0,0 +1,86 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Wenzel Jacob <wenzel@inf.ethz.ch>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef IGL_OPENGL_SHADER_H
+#define IGL_OPENGL_SHADER_H
+
+#include <igl/igl_inline.h>
+#include <string>
+#include <Eigen/Core>
+
+#ifdef __APPLE__
+#   include <OpenGL/gl3.h>
+#   define __gl_h_ /* Prevent inclusion of the old gl.h */
+#else
+#   ifdef _WIN32
+#       include <windows.h>
+#   endif
+#   include <GL/gl.h>
+#endif
+
+namespace igl
+{
+
+// This class wraps an OpenGL program composed of three shaders
+// TODO: write documentation
+
+class OpenGL_shader
+{
+public:
+  typedef unsigned int GLuint;
+  typedef int GLint;
+
+  GLuint vertex_shader;
+  GLuint fragment_shader;
+  GLuint geometry_shader;
+  GLuint program_shader;
+
+  IGL_INLINE OpenGL_shader() : vertex_shader(0), fragment_shader(0),
+    geometry_shader(0), program_shader(0) { }
+
+  // Create a new shader from the specified source strings
+  IGL_INLINE bool init(const std::string &vertex_shader_string,
+    const std::string &fragment_shader_string,
+    const std::string &fragment_data_name,
+    const std::string &geometry_shader_string = "",
+    int geometry_shader_max_vertices = 3);
+
+  // Create a new shader from the specified files on disk
+  IGL_INLINE bool init_from_files(const std::string &vertex_shader_filename,
+    const std::string &fragment_shader_filename,
+    const std::string &fragment_data_name,
+    const std::string &geometry_shader_filename = "",
+    int geometry_shader_max_vertices = 3);
+
+  // Select this shader for subsequent draw calls
+  IGL_INLINE void bind();
+
+  // Release all OpenGL objects
+  IGL_INLINE void free();
+
+  // Return the OpenGL handle of a named shader attribute (-1 if it does not exist)
+  IGL_INLINE GLint attrib(const std::string &name) const;
+
+  // Return the OpenGL handle of a uniform attribute (-1 if it does not exist)
+  IGL_INLINE GLint uniform(const std::string &name) const;
+
+  // Bind a per-vertex array attribute and refresh its contents from an Eigen amtrix
+  IGL_INLINE GLint bindVertexAttribArray(const std::string &name, GLuint bufferID,
+    const Eigen::MatrixXf &M, bool refresh) const;
+
+  IGL_INLINE GLuint create_shader_helper(GLint type, const std::string &shader_string);
+
+};
+
+}
+
+#ifndef IGL_STATIC_LIBRARY
+#  include "OpenGL_shader.cpp"
+#endif
+
+#endif

+ 485 - 0
include/igl/viewer/OpenGL_state.cpp

@@ -0,0 +1,485 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#include "OpenGL_state.h"
+
+IGL_INLINE void igl::OpenGL_state::init_buffers()
+{
+  // Mesh: Vertex Array Object & Buffer objects
+  glGenVertexArrays(1, &vao_mesh);
+  glBindVertexArray(vao_mesh);
+  glGenBuffers(1, &vbo_V);
+  glGenBuffers(1, &vbo_V_normals);
+  glGenBuffers(1, &vbo_V_ambient);
+  glGenBuffers(1, &vbo_V_diffuse);
+  glGenBuffers(1, &vbo_V_specular);
+  glGenBuffers(1, &vbo_V_uv);
+  glGenBuffers(1, &vbo_F);
+  glGenTextures(1, &vbo_tex);
+
+  // Line overlay
+  glGenVertexArrays(1, &vao_overlay_lines);
+  glBindVertexArray(vao_overlay_lines);
+  glGenBuffers(1, &vbo_lines_F);
+  glGenBuffers(1, &vbo_lines_V);
+  glGenBuffers(1, &vbo_lines_V_colors);
+
+  // Point overlay
+  glGenVertexArrays(1, &vao_overlay_points);
+  glBindVertexArray(vao_overlay_points);
+  glGenBuffers(1, &vbo_points_F);
+  glGenBuffers(1, &vbo_points_V);
+  glGenBuffers(1, &vbo_points_V_colors);
+
+  dirty = ViewerData::DIRTY_ALL;
+}
+
+IGL_INLINE void igl::OpenGL_state::free_buffers()
+{
+  glDeleteVertexArrays(1, &vao_mesh);
+  glDeleteVertexArrays(1, &vao_overlay_lines);
+  glDeleteVertexArrays(1, &vao_overlay_points);
+
+  glDeleteBuffers(1, &vbo_V);
+  glDeleteBuffers(1, &vbo_V_normals);
+  glDeleteBuffers(1, &vbo_V_ambient);
+  glDeleteBuffers(1, &vbo_V_diffuse);
+  glDeleteBuffers(1, &vbo_V_specular);
+  glDeleteBuffers(1, &vbo_V_uv);
+  glDeleteBuffers(1, &vbo_F);
+  glDeleteBuffers(1, &vbo_lines_F);
+  glDeleteBuffers(1, &vbo_lines_V);
+  glDeleteBuffers(1, &vbo_lines_V_colors);
+  glDeleteBuffers(1, &vbo_points_F);
+  glDeleteBuffers(1, &vbo_points_V);
+  glDeleteBuffers(1, &vbo_points_V_colors);
+
+  glDeleteTextures(1, &vbo_tex);
+}
+
+IGL_INLINE void igl::OpenGL_state::set_data(const igl::ViewerData &data, bool invert_normals)
+{
+  bool per_corner_uv = (data.F_uv.rows() == data.F.rows());
+  bool per_corner_normals = (data.F_normals.rows() == 3 * data.F.rows());
+
+  dirty |= data.dirty;
+
+  if (!data.face_based)
+  {
+    if (!per_corner_uv)
+    {
+      // Vertex positions
+      if (dirty & ViewerData::DIRTY_POSITION)
+        V_vbo = (data.V.transpose()).cast<float>();
+
+      // Vertex normals
+      if (dirty & ViewerData::DIRTY_NORMAL)
+      {
+        V_normals_vbo = (data.V_normals.transpose()).cast<float>();
+        if (invert_normals)
+          V_normals_vbo = -V_normals_vbo;
+      }
+
+      // Per-vertex material settings
+      if (dirty & ViewerData::DIRTY_AMBIENT)
+        V_ambient_vbo = (data.V_material_ambient.transpose()).cast<float>();
+      if (dirty & ViewerData::DIRTY_DIFFUSE)
+        V_diffuse_vbo = (data.V_material_diffuse.transpose()).cast<float>();
+      if (dirty & ViewerData::DIRTY_SPECULAR)
+        V_specular_vbo = (data.V_material_specular.transpose()).cast<float>();
+
+      // Face indices
+      if (dirty & ViewerData::DIRTY_FACE)
+        F_vbo = (data.F.transpose()).cast<unsigned>();
+
+      // Texture coordinates
+      if (dirty & ViewerData::DIRTY_UV)
+        V_uv_vbo = (data.V_uv.transpose()).cast<float>();
+    }
+    else
+    {
+      // Per vertex properties with per corner UVs
+      if (dirty & ViewerData::DIRTY_POSITION)
+      {
+        V_vbo.resize(3,data.F.rows()*3);
+        for (unsigned i=0; i<data.F.rows();++i)
+          for (unsigned j=0;j<3;++j)
+            V_vbo.col(i*3+j) = data.V.row(data.F(i,j)).transpose().cast<float>();
+      }
+
+      if (dirty & ViewerData::DIRTY_AMBIENT)
+      {
+        V_ambient_vbo.resize(3,data.F.rows()*3);
+        for (unsigned i=0; i<data.F.rows();++i)
+          for (unsigned j=0;j<3;++j)
+            V_ambient_vbo.col (i*3+j) = data.V_material_ambient.row(data.F(i,j)).transpose().cast<float>();
+      }
+
+      if (dirty & ViewerData::DIRTY_DIFFUSE)
+      {
+        V_diffuse_vbo.resize(3,data.F.rows()*3);
+        for (unsigned i=0; i<data.F.rows();++i)
+          for (unsigned j=0;j<3;++j)
+            V_diffuse_vbo.col (i*3+j) = data.V_material_diffuse.row(data.F(i,j)).transpose().cast<float>();
+      }
+
+      if (dirty & ViewerData::DIRTY_SPECULAR)
+      {
+        V_specular_vbo.resize(3,data.F.rows()*3);
+        for (unsigned i=0; i<data.F.rows();++i)
+          for (unsigned j=0;j<3;++j)
+            V_specular_vbo.col(i*3+j) = data.V_material_specular.row(data.F(i,j)).transpose().cast<float>();
+      }
+
+      if (dirty & ViewerData::DIRTY_NORMAL)
+      {
+        V_normals_vbo.resize(3,data.F.rows()*3);
+        for (unsigned i=0; i<data.F.rows();++i)
+          for (unsigned j=0;j<3;++j)
+            V_normals_vbo.col (i*3+j) = data.V_normals.row(data.F(i,j)).transpose().cast<float>();
+
+        if (invert_normals)
+          V_normals_vbo = -V_normals_vbo;
+      }
+
+      if (dirty & ViewerData::DIRTY_FACE)
+      {
+        F_vbo.resize(3,data.F.rows());
+        for (unsigned i=0; i<data.F.rows();++i)
+          F_vbo.col(i) << i*3+0, i*3+1, i*3+2;
+      }
+
+      if (dirty & ViewerData::DIRTY_UV)
+      {
+        V_uv_vbo.resize(2,data.F.rows()*3);
+        for (unsigned i=0; i<data.F.rows();++i)
+          for (unsigned j=0;j<3;++j)
+            V_uv_vbo.col(i*3+j) = data.V_uv.row(data.F(i,j)).transpose().cast<float>();
+      }
+    }
+  }
+  else
+  {
+    if (dirty & ViewerData::DIRTY_POSITION)
+    {
+      V_vbo.resize(3,data.F.rows()*3);
+      for (unsigned i=0; i<data.F.rows();++i)
+        for (unsigned j=0;j<3;++j)
+          V_vbo.col(i*3+j) = data.V.row(data.F(i,j)).transpose().cast<float>();
+    }
+
+    if (dirty & ViewerData::DIRTY_AMBIENT)
+    {
+      V_ambient_vbo.resize(3,data.F.rows()*3);
+      for (unsigned i=0; i<data.F.rows();++i)
+        for (unsigned j=0;j<3;++j)
+          V_ambient_vbo.col (i*3+j) = data.F_material_ambient.row(i).transpose().cast<float>();
+    }
+
+    if (dirty & ViewerData::DIRTY_DIFFUSE)
+    {
+      V_diffuse_vbo.resize(3,data.F.rows()*3);
+      for (unsigned i=0; i<data.F.rows();++i)
+        for (unsigned j=0;j<3;++j)
+          V_diffuse_vbo.col (i*3+j) = data.F_material_diffuse.row(i).transpose().cast<float>();
+    }
+
+    if (dirty & ViewerData::DIRTY_SPECULAR)
+    {
+      V_specular_vbo.resize(3,data.F.rows()*3);
+      for (unsigned i=0; i<data.F.rows();++i)
+        for (unsigned j=0;j<3;++j)
+          V_specular_vbo.col(i*3+j) = data.F_material_specular.row(i).transpose().cast<float>();
+    }
+
+    if (dirty & ViewerData::DIRTY_NORMAL)
+    {
+      V_normals_vbo.resize(3,data.F.rows()*3);
+      for (unsigned i=0; i<data.F.rows();++i)
+        for (unsigned j=0;j<3;++j)
+          V_normals_vbo.col (i*3+j) =
+             per_corner_normals ?
+               data.F_normals.row(i*3+j).transpose().cast<float>() :
+               data.F_normals.row(i).transpose().cast<float>();
+
+      if (invert_normals)
+        V_normals_vbo = -V_normals_vbo;
+    }
+
+    if (dirty & ViewerData::DIRTY_FACE)
+    {
+      F_vbo.resize(3,data.F.rows());
+      for (unsigned i=0; i<data.F.rows();++i)
+        F_vbo.col(i) << i*3+0, i*3+1, i*3+2;
+    }
+
+    if (dirty & ViewerData::DIRTY_UV)
+    {
+        V_uv_vbo.resize(2,data.F.rows()*3);
+        for (unsigned i=0; i<data.F.rows();++i)
+          for (unsigned j=0;j<3;++j)
+            V_uv_vbo.col(i*3+j) = data.V_uv.row(per_corner_uv ? data.F_uv(i,j) : data.F(i,j)).transpose().cast<float>();
+    }
+  }
+
+  if (dirty & ViewerData::DIRTY_TEXTURE)
+  {
+    tex_u = data.texture_R.rows();
+    tex_v = data.texture_R.cols();
+    tex.resize(data.texture_R.size()*3);
+    for (unsigned i=0;i<data.texture_R.size();++i)
+    {
+      tex(i*3+0) = data.texture_R(i);
+      tex(i*3+1) = data.texture_G(i);
+      tex(i*3+2) = data.texture_B(i);
+    }
+  }
+
+  if (dirty & ViewerData::DIRTY_OVERLAY_LINES)
+  {
+    lines_V_vbo.resize(3, data.lines.rows()*2);
+    lines_V_colors_vbo.resize(3, data.lines.rows()*2);
+    lines_F_vbo.resize(1, data.lines.rows()*2);
+    for (unsigned i=0; i<data.lines.rows();++i)
+    {
+      lines_V_vbo.col(2*i+0) = data.lines.block<1, 3>(i, 0).transpose().cast<float>();
+      lines_V_vbo.col(2*i+1) = data.lines.block<1, 3>(i, 3).transpose().cast<float>();
+      lines_V_colors_vbo.col(2*i+0) = data.lines.block<1, 3>(i, 6).transpose().cast<float>();
+      lines_V_colors_vbo.col(2*i+1) = data.lines.block<1, 3>(i, 6).transpose().cast<float>();
+      lines_F_vbo(2*i+0) = 2*i+0;
+      lines_F_vbo(2*i+1) = 2*i+1;
+    }
+  }
+
+  if (dirty & ViewerData::DIRTY_OVERLAY_POINTS)
+  {
+    points_V_vbo.resize(3, data.points.rows());
+    points_V_colors_vbo.resize(3, data.points.rows());
+    points_F_vbo.resize(1, data.points.rows());
+    for (unsigned i=0; i<data.points.rows();++i)
+    {
+      points_V_vbo.col(i) = data.points.block<1, 3>(i, 0).transpose().cast<float>();
+      points_V_colors_vbo.col(i) = data.points.block<1, 3>(i, 3).transpose().cast<float>();
+      points_F_vbo(i) = i;
+    }
+  }
+}
+
+IGL_INLINE void igl::OpenGL_state::bind_mesh()
+{
+  glBindVertexArray(vao_mesh);
+  shader_mesh.bind();
+  shader_mesh.bindVertexAttribArray("position", vbo_V, V_vbo, dirty & ViewerData::DIRTY_POSITION);
+  shader_mesh.bindVertexAttribArray("normal", vbo_V_normals, V_normals_vbo, dirty & ViewerData::DIRTY_NORMAL);
+  shader_mesh.bindVertexAttribArray("Ka", vbo_V_ambient, V_ambient_vbo, dirty & ViewerData::DIRTY_AMBIENT);
+  shader_mesh.bindVertexAttribArray("Kd", vbo_V_diffuse, V_diffuse_vbo, dirty & ViewerData::DIRTY_DIFFUSE);
+  shader_mesh.bindVertexAttribArray("Ks", vbo_V_specular, V_specular_vbo, dirty & ViewerData::DIRTY_SPECULAR);
+  shader_mesh.bindVertexAttribArray("texcoord", vbo_V_uv, V_uv_vbo, dirty & ViewerData::DIRTY_UV);
+
+  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_F);
+  if (dirty & ViewerData::DIRTY_FACE)
+    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*F_vbo.size(), F_vbo.data(), GL_DYNAMIC_DRAW);
+
+  glActiveTexture(GL_TEXTURE0);
+  glBindTexture(GL_TEXTURE_2D, vbo_tex);
+  if (dirty & ViewerData::DIRTY_TEXTURE)
+  {
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_u, tex_v, 0, GL_RGB, GL_UNSIGNED_BYTE, tex.data());
+  }
+  glUniform1i(shader_mesh.uniform("tex"), 0);
+  dirty &= ~ViewerData::DIRTY_MESH;
+}
+
+IGL_INLINE void igl::OpenGL_state::bind_overlay_lines()
+{
+  bool is_dirty = dirty & ViewerData::DIRTY_OVERLAY_LINES;
+
+  glBindVertexArray(vao_overlay_lines);
+  shader_overlay_lines.bind();
+  shader_overlay_lines.bindVertexAttribArray("position", vbo_lines_V, lines_V_vbo, is_dirty);
+  shader_overlay_lines.bindVertexAttribArray("color", vbo_lines_V_colors, lines_V_colors_vbo, is_dirty);
+
+  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_lines_F);
+  if (is_dirty)
+    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*lines_F_vbo.size(), lines_F_vbo.data(), GL_DYNAMIC_DRAW);
+
+  dirty &= ~ViewerData::DIRTY_OVERLAY_LINES;
+}
+
+IGL_INLINE void igl::OpenGL_state::bind_overlay_points()
+{
+  bool is_dirty = dirty & ViewerData::DIRTY_OVERLAY_POINTS;
+
+  glBindVertexArray(vao_overlay_points);
+  shader_overlay_points.bind();
+  shader_overlay_points.bindVertexAttribArray("position", vbo_points_V, points_V_vbo, is_dirty);
+  shader_overlay_points.bindVertexAttribArray("color", vbo_points_V_colors, points_V_colors_vbo, is_dirty);
+
+  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_points_F);
+  if (is_dirty)
+    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*points_F_vbo.size(), points_F_vbo.data(), GL_DYNAMIC_DRAW);
+
+  dirty &= ~ViewerData::DIRTY_OVERLAY_POINTS;
+}
+
+IGL_INLINE void igl::OpenGL_state::draw_mesh(bool solid)
+{
+  glPolygonMode(GL_FRONT_AND_BACK, solid ? GL_FILL : GL_LINE);
+
+  /* Avoid Z-buffer fighting between filled triangles & wireframe lines */
+  if (solid)
+  {
+    glEnable(GL_POLYGON_OFFSET_FILL);
+    glPolygonOffset(1.0, 1.0);
+  }
+  glDrawElements(GL_TRIANGLES, 3*F_vbo.cols(), GL_UNSIGNED_INT, 0);
+
+  glDisable(GL_POLYGON_OFFSET_FILL);
+  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+}
+
+IGL_INLINE void igl::OpenGL_state::draw_overlay_lines()
+{
+  glDrawElements(GL_LINES, lines_F_vbo.cols(), GL_UNSIGNED_INT, 0);
+}
+
+IGL_INLINE void igl::OpenGL_state::draw_overlay_points()
+{
+  glDrawElements(GL_POINTS, points_F_vbo.cols(), GL_UNSIGNED_INT, 0);
+}
+
+IGL_INLINE void igl::OpenGL_state::init()
+{
+  std::string mesh_vertex_shader_string =
+  "#version 150\n"
+  "uniform mat4 model;"
+  "uniform mat4 view;"
+  "uniform mat4 proj;"
+  "in vec3 position;"
+  "in vec3 normal;"
+  "out vec3 position_eye;"
+  "out vec3 normal_eye;"
+  "in vec3 Ka;"
+  "in vec3 Kd;"
+  "in vec3 Ks;"
+  "in vec2 texcoord;"
+  "out vec2 texcoordi;"
+  "out vec3 Kai;"
+  "out vec3 Kdi;"
+  "out vec3 Ksi;"
+
+  "void main()"
+  "{"
+  "  position_eye = vec3 (view * model * vec4 (position, 1.0));"
+  "  normal_eye = vec3 (view * model * vec4 (normal, 0.0));"
+  "  normal_eye = normalize(normal_eye);"
+  "  gl_Position = proj * vec4 (position_eye, 1.0);" //proj * view * model * vec4(position, 1.0);"
+  "  Kai = Ka;"
+  "  Kdi = Kd;"
+  "  Ksi = Ks;"
+  "  texcoordi = texcoord;"
+  "}";
+
+  std::string mesh_fragment_shader_string =
+  "#version 150\n"
+  "uniform mat4 model;"
+  "uniform mat4 view;"
+  "uniform mat4 proj;"
+  "uniform vec4 fixed_color;"
+  "in vec3 position_eye;"
+  "in vec3 normal_eye;"
+  "uniform vec3 light_position_world;"
+  "vec3 Ls = vec3 (1, 1, 1);"
+  "vec3 Ld = vec3 (1, 1, 1);"
+  "vec3 La = vec3 (1, 1, 1);"
+  "in vec3 Ksi;"
+  "in vec3 Kdi;"
+  "in vec3 Kai;"
+  "in vec2 texcoordi;"
+  "uniform sampler2D tex;"
+  "uniform float specular_exponent;"
+  "uniform float lighting_factor;"
+  "uniform float texture_factor;"
+  "out vec4 outColor;"
+  "void main()"
+  "{"
+  "vec3 Ia = La * Kai;"    // ambient intensity
+
+  "vec3 light_position_eye = vec3 (view * vec4 (light_position_world, 1.0));"
+  "vec3 distance_to_light_eye = light_position_eye - position_eye;"
+  "vec3 direction_to_light_eye = normalize (distance_to_light_eye);"
+  "float dot_prod = dot (direction_to_light_eye, normal_eye);"
+  "dot_prod = max (dot_prod, 0.0);"
+  "vec3 Id = Ld * Kdi * dot_prod;"    // Diffuse intensity
+
+  "vec3 reflection_eye = reflect (-direction_to_light_eye, normal_eye);"
+  "vec3 surface_to_viewer_eye = normalize (-position_eye);"
+  "float dot_prod_specular = dot (reflection_eye, surface_to_viewer_eye);"
+  "dot_prod_specular = max (dot_prod_specular, 0.0);"
+  "float specular_factor = pow (dot_prod_specular, specular_exponent);"
+  "vec3 Is = Ls * Ksi * specular_factor;"    // specular intensity
+  "vec4 color = vec4(lighting_factor * (Is + Id) + Ia, 1.0) + vec4((1.0-lighting_factor) * Kdi,1.0);"
+  "outColor = mix(vec4(1,1,1,1), texture(tex, texcoordi), texture_factor) * color;"
+  "if (fixed_color != vec4(0.0)) outColor = fixed_color;"
+  "}";
+
+  std::string overlay_vertex_shader_string =
+  "#version 150\n"
+  "uniform mat4 model;"
+  "uniform mat4 view;"
+  "uniform mat4 proj;"
+  "in vec3 position;"
+  "in vec3 color;"
+  "out vec3 color_frag;"
+
+  "void main()"
+  "{"
+  "  gl_Position = proj * view * model * vec4 (position, 1.0);"
+  "  color_frag = color;"
+  "}";
+
+  std::string overlay_fragment_shader_string =
+  "#version 150\n"
+  "in vec3 color_frag;"
+  "out vec4 outColor;"
+  "void main()"
+  "{"
+  "  outColor = vec4(color_frag, 1.0);"
+  "}";
+
+  std::string overlay_point_fragment_shader_string =
+  "#version 150\n"
+  "in vec3 color_frag;"
+  "out vec4 outColor;"
+  "void main()"
+  "{"
+  "  if (length(gl_PointCoord - vec2(0.5)) > 0.5)"
+  "    discard;"
+  "  outColor = vec4(color_frag, 1.0);"
+  "}";
+
+  init_buffers();
+  shader_mesh.init(mesh_vertex_shader_string,
+      mesh_fragment_shader_string, "outColor");
+  shader_overlay_lines.init(overlay_vertex_shader_string,
+      overlay_fragment_shader_string, "outColor");
+  shader_overlay_points.init(overlay_vertex_shader_string,
+      overlay_point_fragment_shader_string, "outColor");
+}
+
+IGL_INLINE void igl::OpenGL_state::free()
+{
+  shader_mesh.free();
+  shader_overlay_lines.free();
+  shader_overlay_points.free();
+  free_buffers();
+}

+ 115 - 0
include/igl/viewer/OpenGL_state.h

@@ -0,0 +1,115 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef IGL_OPENGL_STATE_H
+#define IGL_OPENGL_STATE_H
+
+// Coverts mesh data inside a igl::ViewerData class in an OpenGL compatible format
+// The class includes a shader and the opengl calls to plot the data
+
+#include <igl/igl_inline.h>
+#include <igl/viewer/OpenGL_shader.h>
+#include <igl/viewer/ViewerData.h>
+
+namespace igl
+{
+
+class OpenGL_state
+{
+public:
+  typedef unsigned int GLuint;
+
+  GLuint vao_mesh;
+  GLuint vao_overlay_lines;
+  GLuint vao_overlay_points;
+  OpenGL_shader shader_mesh;
+  OpenGL_shader shader_overlay_lines;
+  OpenGL_shader shader_overlay_points;
+
+  GLuint vbo_V; // Vertices of the current mesh (#V x 3)
+  GLuint vbo_V_uv; // UV coordinates for the current mesh (#V x 2)
+  GLuint vbo_V_normals; // Vertices of the current mesh (#V x 3)
+  GLuint vbo_V_ambient; // Ambient material  (#V x 3)
+  GLuint vbo_V_diffuse; // Diffuse material  (#V x 3)
+  GLuint vbo_V_specular; // Specular material  (#V x 3)
+
+  GLuint vbo_F; // Faces of the mesh (#F x 3)
+  GLuint vbo_tex; // Texture
+
+  GLuint vbo_lines_F;         // Indices of the line overlay
+  GLuint vbo_lines_V;         // Vertices of the line overlay
+  GLuint vbo_lines_V_colors;  // Color values of the line overlay
+  GLuint vbo_points_F;        // Indices of the point overlay
+  GLuint vbo_points_V;        // Vertices of the point overlay
+  GLuint vbo_points_V_colors; // Color values of the point overlay
+
+  // Temporary copy of the content of each VBO
+  Eigen::MatrixXf V_vbo;
+  Eigen::MatrixXf V_normals_vbo;
+  Eigen::MatrixXf V_ambient_vbo;
+  Eigen::MatrixXf V_diffuse_vbo;
+  Eigen::MatrixXf V_specular_vbo;
+  Eigen::MatrixXf V_uv_vbo;
+  Eigen::MatrixXf lines_V_vbo;
+  Eigen::MatrixXf lines_V_colors_vbo;
+  Eigen::MatrixXf points_V_vbo;
+  Eigen::MatrixXf points_V_colors_vbo;
+
+  int tex_u;
+  int tex_v;
+  Eigen::Matrix<char,Eigen::Dynamic,1> tex;
+
+  Eigen::Matrix<unsigned, Eigen::Dynamic, Eigen::Dynamic> F_vbo;
+  Eigen::Matrix<unsigned, Eigen::Dynamic, Eigen::Dynamic> lines_F_vbo;
+  Eigen::Matrix<unsigned, Eigen::Dynamic, Eigen::Dynamic> points_F_vbo;
+
+  // Marks dirty buffers that need to be uploaded to OpenGL
+  uint32_t dirty;
+
+  // Initialize shaders and buffers
+  IGL_INLINE void init();
+
+  // Release all resources
+  IGL_INLINE void free();
+
+  // Create a new set of OpenGL buffer objects
+  IGL_INLINE void init_buffers();
+
+  // Update contents from a 'Data' instance
+  IGL_INLINE void set_data(const igl::ViewerData &data, bool invert_normals);
+
+  // Bind the underlying OpenGL buffer objects for subsequent mesh draw calls
+  IGL_INLINE void bind_mesh();
+
+  /// Draw the currently buffered mesh (either solid or wireframe)
+  IGL_INLINE void draw_mesh(bool solid);
+
+  // Bind the underlying OpenGL buffer objects for subsequent line overlay draw calls
+  IGL_INLINE void bind_overlay_lines();
+
+  /// Draw the currently buffered line overlay
+  IGL_INLINE void draw_overlay_lines();
+
+  // Bind the underlying OpenGL buffer objects for subsequent point overlay draw calls
+  IGL_INLINE void bind_overlay_points();
+
+  /// Draw the currently buffered point overlay
+  IGL_INLINE void draw_overlay_points();
+
+  // Release the OpenGL buffer objects
+  IGL_INLINE void free_buffers();
+
+};
+
+}
+
+#ifndef IGL_STATIC_LIBRARY
+#  include "OpenGL_state.cpp"
+#endif
+
+#endif

+ 3 - 1
include/igl/viewer/TODOs.txt

@@ -1,5 +1,6 @@
+- depth test for overlays cannot be disabled
+- data.lines, data.points should not concatenate colors with coordinates
 - snap to canonical recenters origin but trackball does not
-+ snap to canonical view key shortcut is not working
 - rewrite in libigl style
 - separate various class into their own .h/.cpp pairs
 - remove use of double underscores (http://stackoverflow.com/a/224420/148668)
@@ -14,6 +15,7 @@
 - zoom with pan rather than scaling
 - refresh draw while resizing
 - use constructor initializer list rather than complicated constructor
++ snap to canonical view key shortcut is not working
 + resize TwBar with window
 + trackball should be able to drag over TwBar
 + don't zoom on horizontal scale

+ 118 - 0
include/igl/viewer/TextRenderer.cpp

@@ -0,0 +1,118 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Wenzel Jacob <wenzel@inf.ethz.ch>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+#include "TextRenderer.h"
+#include <igl/project.h>
+
+  IGL_INLINE igl::TextRenderer::TextRenderer() : m_shaderHandleBackup(0) { }
+
+  IGL_INLINE int igl::TextRenderer::Init()
+  {
+    int retval = CTwGraphOpenGLCore::Init();
+    if (retval == 1)
+    {
+      std::string vertexShader =
+          "#version 150\n"
+          "uniform vec2 offset;"
+          "uniform vec2 wndSize;"
+          "uniform vec4 color;"
+          "uniform float depth;"
+          "in vec2 vertex;"
+          "in vec2 uv;"
+          "out vec4 fcolor;"
+          "out vec2 fuv;"
+          "void main() {"
+          "  gl_Position = vec4(2.0*(vertex.x+offset.x-0.5)/wndSize.x - 1.0,"
+          "                     1.0 - 2.0*(vertex.y+offset.y-0.5)/wndSize.y,"
+          "                     depth, 1);"
+          " fuv = uv;"
+          " fcolor = color;"
+          "}";
+
+      std::string fragmentShader =
+        "#version 150\n"
+        "uniform sampler2D tex;"
+        "in vec2 fuv;"
+        "in vec4 fcolor;"
+        "out vec4 outColor;"
+        "void main() { outColor.rgb = fcolor.bgr; outColor.a = fcolor.a * texture(tex, fuv).r; }";
+
+      if (!m_shader.init(vertexShader, fragmentShader, "outColor"))
+        return 0;
+
+      /* Adjust location bindings */
+      glBindAttribLocation(m_shader.program_shader, 0, "vertex");
+      glBindAttribLocation(m_shader.program_shader, 1, "uv");
+      glBindAttribLocation(m_shader.program_shader, 2, "color");
+      glLinkProgram(m_shader.program_shader);
+
+      m_shaderHandleBackup = m_TriTexUniProgram;
+      m_TriTexUniProgram = m_shader.program_shader;
+      m_TriTexUniLocationOffset = m_shader.uniform("offset");
+      m_TriTexUniLocationWndSize = m_shader.uniform("wndSize");
+      m_TriTexUniLocationColor = m_shader.uniform("color");
+      m_TriTexUniLocationTexture = m_shader.uniform("tex");
+      m_TriTexUniLocationDepth = m_shader.uniform("depth");
+    }
+    return retval;
+  }
+
+  IGL_INLINE int igl::TextRenderer::Shut()
+  {
+    for (auto kv : m_textObjects)
+      DeleteTextObj(kv.second);
+    m_shader.free();
+    m_TriTexUniProgram = m_shaderHandleBackup;
+    return CTwGraphOpenGLCore::Shut();
+  }
+
+  IGL_INLINE void igl::TextRenderer::BeginDraw(const Eigen::Matrix4f &view, const Eigen::Matrix4f &proj,
+    const Eigen::Vector4f &_viewport, float _object_scale)
+  {
+    viewport = _viewport;
+    proj_matrix = proj;
+    view_matrix = view;
+    CTwGraphOpenGLCore::BeginDraw(viewport[2], viewport[3]);
+    glEnable(GL_DEPTH_TEST);
+    glDepthMask(GL_FALSE);
+    object_scale = _object_scale;
+  }
+
+  IGL_INLINE void igl::TextRenderer::EndDraw()
+  {
+    /* Limit the number of cached text objects */
+    for (auto it = m_textObjects.cbegin(); it != m_textObjects.cend(); )
+    {
+      if (m_textObjects.size() < 1000000)
+        break;
+      DeleteTextObj(it->second);
+      m_textObjects.erase(it++);
+    }
+
+    glDepthMask(GL_TRUE);
+    CTwGraphOpenGLCore::EndDraw();
+  }
+
+  IGL_INLINE void igl::TextRenderer::DrawText(Eigen::Vector3d pos, Eigen::Vector3d normal, const std::string &text)
+  {
+    pos += normal * 0.005f * object_scale;
+    Eigen::Vector3f coord = igl::project(Eigen::Vector3f(pos(0), pos(1), pos(2)),
+        view_matrix, proj_matrix, viewport);
+    auto it = m_textObjects.find(text);
+    void *text_obj = nullptr;
+    if (it == m_textObjects.end())
+    {
+      text_obj = NewTextObj();
+      BuildText(text_obj, &text, NULL, NULL, 1, g_DefaultNormalFont, 0, 0);
+      m_textObjects[text] = text_obj;
+    } else {
+      text_obj = it->second;
+    }
+    m_shader.bind();
+    glUniform1f(m_TriTexUniLocationDepth, 2*(coord(2)-0.5f));
+    CTwGraphOpenGLCore::DrawText(text_obj, coord[0], viewport[3] - coord[1], COLOR32_BLUE, 0);
+  }

+ 55 - 0
include/igl/viewer/TextRenderer.h

@@ -0,0 +1,55 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Wenzel Jacob <wenzel@inf.ethz.ch>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+/* This class extends the font rendering code in AntTweakBar
+   so that it can be used to render text at arbitrary 3D positions */
+
+#ifndef IGL_TEXT_RENDERER_H
+#define IGL_TEXT_RENDERER_H
+
+#include <igl/igl_inline.h>
+#include <igl/viewer/OpenGL_shader.h>
+#include <TwOpenGLCore.h>
+#include <map>
+
+
+namespace igl
+{
+
+class TextRenderer : public CTwGraphOpenGLCore
+{
+public:
+  IGL_INLINE TextRenderer();
+
+  IGL_INLINE virtual int Init();
+  IGL_INLINE virtual int Shut();
+
+  IGL_INLINE void BeginDraw(const Eigen::Matrix4f &view, const Eigen::Matrix4f &proj,
+    const Eigen::Vector4f &_viewport, float _object_scale);
+
+  IGL_INLINE void EndDraw();
+
+  IGL_INLINE void DrawText(Eigen::Vector3d pos, Eigen::Vector3d normal, const std::string &text);
+
+protected:
+  igl::OpenGL_shader m_shader;
+  std::map<std::string, void *> m_textObjects;
+  GLuint m_shaderHandleBackup;
+  GLuint m_TriTexUniLocationDepth;
+  Eigen::Matrix4f view_matrix, proj_matrix;
+  Eigen::Vector4f viewport;
+  float object_scale;
+};
+
+}
+
+#ifndef IGL_STATIC_LIBRARY
+#  include "TextRenderer.cpp"
+#endif
+
+#endif

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 102 - 1261
include/igl/viewer/Viewer.cpp


+ 28 - 459
include/igl/viewer/Viewer.h

@@ -1,4 +1,10 @@
-// Main class of the Viewer
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
 
 #ifndef IGL_VIEWER_H
 #define IGL_VIEWER_H
@@ -20,301 +26,34 @@
 #endif
 
 #include <Eigen/Core>
+#include <Eigen/Geometry>
+#include <igl/viewer/OpenGL_shader.h>
+#include <igl/viewer/ViewerData.h>
+#include <igl/viewer/OpenGL_state.h>
+#include <igl/viewer/ViewerPlugin.h>
+#include <igl/viewer/ViewerCore.h>
 
 namespace igl
 {
-
-  class Plugin_manager;
-
+  // GLFW-based mesh viewer
   class Viewer
   {
   public:
 
     int launch(std::string filename = "");
-    void init(Plugin_manager* pm);
-
-    class Options
-    #ifdef ENABLE_XML_SERIALIZATION
-    : public ::igl::XMLSerialization
-    #endif
-    {
-    public:
-      Options()
-      #ifdef ENABLE_XML_SERIALIZATION
-      : XMLSerialization("Options")
-      #endif
-      {};
-      void InitSerialization();
-
-      // Shape material
-      float shininess;
-
-      // Colors
-      Eigen::Vector3f background_color;
-      Eigen::Vector3f line_color;
-
-      // Lighting
-      Eigen::Vector3f light_position;
-      float lighting_factor;
-
-      // Trackball angle (quaternion)
-      Eigen::Vector4f trackball_angle;
-
-      // Model viewing parameters
-      float model_zoom;
-      Eigen::Vector3f model_translation;
-
-      // Model viewing paramters (uv coordinates)
-      float model_zoom_uv;
-      Eigen::Vector3f model_translation_uv;
-
-      // Camera parameters
-      float camera_zoom;
-      bool orthographic;
-      Eigen::Vector3f camera_eye;
-      Eigen::Vector3f camera_up;
-      Eigen::Vector3f camera_center;
-      float camera_view_angle;
-      float camera_dnear;
-      float camera_dfar;
-
-      // Visualization options
-      bool show_overlay;
-      bool show_overlay_depth;
-      bool show_texture;
-      bool show_faces;
-      bool show_lines;
-      bool show_vertid;
-      bool show_faceid;
-      bool invert_normals;
-
-      // Point size / line width
-      float point_size;
-      float line_width;
-
-      // Enable per-face colors and normals
-      bool face_based;
-    };
-
-    enum DirtyFlags
-    {
-      DIRTY_NONE           = 0x0000,
-      DIRTY_POSITION       = 0x0001,
-      DIRTY_UV             = 0x0002,
-      DIRTY_NORMAL         = 0x0004,
-      DIRTY_AMBIENT        = 0x0008,
-      DIRTY_DIFFUSE        = 0x0010,
-      DIRTY_SPECULAR       = 0x0020,
-      DIRTY_TEXTURE        = 0x0040,
-      DIRTY_FACE           = 0x0080,
-      DIRTY_MESH           = 0x00FF,
-      DIRTY_OVERLAY_LINES  = 0x0100,
-      DIRTY_OVERLAY_POINTS = 0x0200,
-      DIRTY_ALL            = 0x03FF
-    };
-
-    class Data
-    #ifdef ENABLE_XML_SERIALIZATION
-    : public ::igl::XMLSerialization
-    #endif
-    {
-    public:
-      Data()
-      #ifdef ENABLE_XML_SERIALIZATION
-      : XMLSerialization("Data"), dirty(DIRTY_ALL)
-      #endif
-      {};
-
-      void InitSerialization();
-
-      Eigen::MatrixXd V; // Vertices of the current mesh (#V x 3)
-      Eigen::MatrixXi F; // Faces of the mesh (#F x 3)
-
-      // Per face attributes
-      Eigen::MatrixXd F_normals; // One normal per face
-
-      Eigen::MatrixXd F_material_ambient; // Per face ambient color
-      Eigen::MatrixXd F_material_diffuse; // Per face diffuse color
-      Eigen::MatrixXd F_material_specular; // Per face specular color
-
-      // Per vertex attributes
-      Eigen::MatrixXd V_normals; // One normal per vertex
-
-      Eigen::MatrixXd V_material_ambient; // Per vertex ambient color
-      Eigen::MatrixXd V_material_diffuse; // Per vertex diffuse color
-      Eigen::MatrixXd V_material_specular; // Per vertex specular color
-
-      // UV parametrization
-      Eigen::MatrixXd V_uv; // UV vertices
-      Eigen::MatrixXi F_uv; // optional faces for UVs
-
-      // Texture
-      Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> texture_R;
-      Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> texture_G;
-      Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> texture_B;
-
-      // Overlays
-
-      // Lines plotted over the scene
-      // (Every row contains 9 doubles in the following format S_x, S_y, S_z, T_x, T_y, T_z, C_r, C_g, C_b),
-      // with S and T the coordinates of the two vertices of the line in global coordinates, and C the color in floating point rgb format
-      Eigen::MatrixXd lines;
-
-      // Points plotted over the scene
-      // (Every row contains 6 doubles in the following format P_x, P_y, P_z, C_r, C_g, C_b),
-      // with P the position in global coordinates of the center of the point, and C the color in floating point rgb format
-      Eigen::MatrixXd points;
-
-      // Text labels plotted over the scene
-      // Textp contains, in the i-th row, the position in global coordinates where the i-th label should be anchored
-      // Texts contains in the i-th position the text of the i-th label
-      Eigen::MatrixXd           labels_positions;
-      std::vector<std::string > labels_strings;
-
-      // Marks dirty buffers that need to be uploaded to OpenGL
-      uint32_t dirty;
-
-      // Caches the two-norm between the min/max point of the bounding box
-      float object_scale;
-      /*********************************/
-    };
-
-    class OpenGL_shader
-    {
-    public:
-      typedef unsigned int GLuint;
-      typedef int GLint;
-
-      GLuint vertex_shader;
-      GLuint fragment_shader;
-      GLuint geometry_shader;
-      GLuint program_shader;
-
-      OpenGL_shader() : vertex_shader(0), fragment_shader(0),
-        geometry_shader(0), program_shader(0) { }
-
-      // Create a new shader from the specified source strings
-      bool init(const std::string &vertex_shader_string,
-        const std::string &fragment_shader_string,
-        const std::string &fragment_data_name,
-        const std::string &geometry_shader_string = "",
-        int geometry_shader_max_vertices = 3);
-
-      // Create a new shader from the specified files on disk
-      bool init_from_files(const std::string &vertex_shader_filename,
-        const std::string &fragment_shader_filename,
-        const std::string &fragment_data_name,
-        const std::string &geometry_shader_filename = "",
-        int geometry_shader_max_vertices = 3);
-
-      // Select this shader for subsequent draw calls
-      void bind();
-
-      // Release all OpenGL objects
-      void free();
-
-      // Return the OpenGL handle of a named shader attribute (-1 if it does not exist)
-      GLint attrib(const std::string &name) const;
-
-      // Return the OpenGL handle of a uniform attribute (-1 if it does not exist)
-      GLint uniform(const std::string &name) const;
-
-      // Bind a per-vertex array attribute and refresh its contents from an Eigen amtrix
-      GLint bindVertexAttribArray(const std::string &name, GLuint bufferID,
-        const Eigen::MatrixXf &M, bool refresh) const;
-    };
-
-    class OpenGL_state
-    {
-    public:
-      typedef unsigned int GLuint;
-
-      GLuint vao_mesh;
-      GLuint vao_overlay_lines;
-      GLuint vao_overlay_points;
-      OpenGL_shader shader_mesh;
-      OpenGL_shader shader_overlay_lines;
-      OpenGL_shader shader_overlay_points;
-
-      GLuint vbo_V; // Vertices of the current mesh (#V x 3)
-      GLuint vbo_V_uv; // UV coordinates for the current mesh (#V x 2)
-      GLuint vbo_V_normals; // Vertices of the current mesh (#V x 3)
-      GLuint vbo_V_ambient; // Ambient material  (#V x 3)
-      GLuint vbo_V_diffuse; // Diffuse material  (#V x 3)
-      GLuint vbo_V_specular; // Specular material  (#V x 3)
-
-      GLuint vbo_F; // Faces of the mesh (#F x 3)
-      GLuint vbo_tex; // Texture
-
-      GLuint vbo_lines_F;         // Indices of the line overlay
-      GLuint vbo_lines_V;         // Vertices of the line overlay
-      GLuint vbo_lines_V_colors;  // Color values of the line overlay
-      GLuint vbo_points_F;        // Indices of the point overlay
-      GLuint vbo_points_V;        // Vertices of the point overlay
-      GLuint vbo_points_V_colors; // Color values of the point overlay
-
-      // Temporary copy of the content of each VBO
-      Eigen::MatrixXf V_vbo;
-      Eigen::MatrixXf V_normals_vbo;
-      Eigen::MatrixXf V_ambient_vbo;
-      Eigen::MatrixXf V_diffuse_vbo;
-      Eigen::MatrixXf V_specular_vbo;
-      Eigen::MatrixXf V_uv_vbo;
-      Eigen::MatrixXf lines_V_vbo;
-      Eigen::MatrixXf lines_V_colors_vbo;
-      Eigen::MatrixXf points_V_vbo;
-      Eigen::MatrixXf points_V_colors_vbo;
-
-      int tex_u;
-      int tex_v;
-      Eigen::Matrix<char,Eigen::Dynamic,1> tex;
-
-      Eigen::Matrix<unsigned, Eigen::Dynamic, Eigen::Dynamic> F_vbo;
-      Eigen::Matrix<unsigned, Eigen::Dynamic, Eigen::Dynamic> lines_F_vbo;
-      Eigen::Matrix<unsigned, Eigen::Dynamic, Eigen::Dynamic> points_F_vbo;
-
-      // Marks dirty buffers that need to be uploaded to OpenGL
-      uint32_t dirty;
-
-      // Create a new set of OpenGL buffer objects
-      void init();
-
-      // Update contents from a 'Data' instance
-      void set_data(const Data &data, bool face_based, bool invert_normals);
-
-      // Bind the underlying OpenGL buffer objects for subsequent mesh draw calls
-      void bind_mesh();
-
-      /// Draw the currently buffered mesh (either solid or wireframe)
-      void draw_mesh(bool solid);
-
-      // Bind the underlying OpenGL buffer objects for subsequent line overlay draw calls
-      void bind_overlay_lines();
-
-      /// Draw the currently buffered line overlay
-      void draw_overlay_lines();
-
-      // Bind the underlying OpenGL buffer objects for subsequent point overlay draw calls
-      void bind_overlay_points();
-
-      /// Draw the currently buffered point overlay
-      void draw_overlay_points();
-
-      // Release the OpenGL buffer objects
-      void free();
-    };
+    void init();
 
     // Stores all the viewing options
-    Options options;
+    igl::ViewerCore core;
 
     // Stores all the data that should be visualized
-    Data data;
+    igl::ViewerData data;
 
     // Stores the vbos indices and opengl related settings
-    OpenGL_state opengl;
+    igl::OpenGL_state opengl;
 
-    // Pointer to the plugin_manager (usually it will be a global variable)
-    Plugin_manager* plugin_manager;
+    // List of registered plugins
+    std::vector<ViewerPlugin*> plugins;
     void init_plugins();
     void shutdown_plugins();
 
@@ -327,36 +66,25 @@ namespace igl
     float down_mouse_z;
     Eigen::Vector3f down_translation;
     bool down;
+    bool hack_never_moved;
 
     // Anttweak bar
     TwBar* bar;
 
-    // Window size
-    int width;
-    int height;
-
     // Keep track of the global position of the scrollwheel
     float scroll_position;
 
-    // Useful functions
-    void compute_normals(); // Computes the normals of the mesh
-    void uniform_colors(Eigen::Vector3d ambient, Eigen::Vector3d diffuse, Eigen::Vector3d specular); // assign uniform colors to all faces/vertices
-    void grid_texture(); // Generate a default grid texture
+    // Wrappers for ViewerCore functions
+    void align_camera_center();
 
-    void clear_mesh();      // Clear the mesh data
-    void align_camera_center(); // Adjust the view to see the entire model
+    // Wrappers for ViewerData functions
 
-    // Change the visualization mode, invalidating the cache if necessary
+    void clear();
+    void compute_normals();
     void set_face_based(bool newvalue);
-
-    // Helpers that can draw the most common meshes
     void set_mesh(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F);
     void set_vertices(const Eigen::MatrixXd& V);
     void set_normals(const Eigen::MatrixXd& N);
-    // Set the color of the mesh
-    //
-    // Inputs:
-    //   C  #V|#F|1 by 3 list of colors
     void set_colors(const Eigen::MatrixXd &C);
     void set_uv(const Eigen::MatrixXd& UV);
     void set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F);
@@ -366,15 +94,10 @@ namespace igl
                       const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& B);
 
     void add_points(const Eigen::MatrixXd& P,  const Eigen::MatrixXd& C);
+    void set_edges (const Eigen::MatrixXd& P, const Eigen::MatrixXi& E, const Eigen::MatrixXd& C);
     void add_edges (const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C);
     void add_label (const Eigen::VectorXd& P,  const std::string& str);
 
-    // Save the OpenGL transformation matrices used for the previous rendering pass
-    Eigen::Matrix4f view;
-    Eigen::Matrix4f model;
-    Eigen::Matrix4f proj;
-
-    Eigen::Vector4f viewport;
 
     // UI Enumerations
     enum MouseButton {IGL_LEFT, IGL_MIDDLE, IGL_RIGHT};
@@ -402,19 +125,6 @@ namespace igl
     bool load_scene();
     bool save_scene();
 
-    // Determines how much to zoom and shift such that the mesh fills the unit
-    // box (centered at the origin)
-    static void get_scale_and_shift_to_fit_mesh(
-      const Eigen::MatrixXd& V,
-      const Eigen::MatrixXi& F,
-      float & zoom,
-      Eigen::Vector3f& shift);
-
-
-    // Init opengl shaders and VBOs
-    void init_opengl();
-    void free_opengl();
-
     // Draw everything
     void draw();
 
@@ -453,151 +163,10 @@ namespace igl
     static void TW_CALL get_face_based_cb(void *param, void *clientData);
     static void TW_CALL set_invert_normals_cb(const void *param, void *clientData);
     static void TW_CALL get_invert_normals_cb(void *param, void *clientData);
-  };
-
-
-  // Abstract class for plugins
-  // All plugins MUST have this class as their parent and implement all the callbacks
-  // For an example of a basic plugins see plugins/skeleton.h
-  //
-  // Return value of callbacks: returning true to any of the callbacks tells Preview3D that the event has been
-  // handled and that it should not be passed to other plugins or to other internal functions of Preview3D
-
-  class Viewer_plugin
-  #ifdef ENABLE_XML_SERIALIZATION
-  : public ::igl::XMLSerialization
-  #endif
-  {
   public:
-    Viewer_plugin()
-    #ifdef ENABLE_XML_SERIALIZATION
-    : XMLSerialization("dummy")
-    #endif
-    {plugin_name = "dummy";};
-
-    ~Viewer_plugin(){};
-
-    // This function is called when the viewer is initialized (no mesh will be loaded at this stage)
-    virtual void init(igl::Viewer *_viewer)
-    {
-      viewer = _viewer;
-    }
-
-    // This function is called before shutdown
-    virtual void shutdown()
-    {
-    }
-
-    // This function is called before a mesh is loaded
-    virtual bool load(std::string filename)
-    {
-      return false;
-    }
-
-    // This function is called before a mesh is saved
-    virtual bool save(std::string filename)
-    {
-      return false;
-    }
-
-    // Runs immediately after a new mesh had been loaded.
-    virtual bool post_load()
-    {
-      return false;
-    }
-
-    // This function is called before the draw procedure of Preview3D
-    virtual bool pre_draw()
-    {
-      return false;
-    }
-
-    // This function is called after the draw procedure of Preview3D
-    virtual bool post_draw()
-    {
-      return false;
-    }
-
-    // This function is called when the mouse button is pressed
-    // - button can be GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON or GLUT_RIGHT_BUTTON
-    // - modifiers is a bitfield that might one or more of the following bits Preview3D::NO_KEY, Preview3D::SHIFT, Preview3D::CTRL, Preview3D::ALT;
-    virtual bool mouse_down(int button, int modifier)
-    {
-      return false;
-    }
-
-    // This function is called when the mouse button is released
-    // - button can be GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON or GLUT_RIGHT_BUTTON
-    // - modifiers is a bitfield that might one or more of the following bits Preview3D::NO_KEY, Preview3D::SHIFT, Preview3D::CTRL, Preview3D::ALT;
-    virtual bool mouse_up(int button, int modifier)
-    {
-      return false;
-    }
-
-    // This function is called every time the mouse is moved
-    // - mouse_x and mouse_y are the new coordinates of the mouse pointer in screen coordinates
-    virtual bool mouse_move(int mouse_x, int mouse_y)
-    {
-      return false;
-    }
-
-    // This function is called every time the scroll wheel is moved
-    // Note: this callback is not working with every glut implementation
-    virtual bool mouse_scroll(float delta_y)
-    {
-      return false;
-    }
-
-    // This function is called when a keyboard key is pressed
-    // - modifiers is a bitfield that might one or more of the following bits Preview3D::NO_KEY, Preview3D::SHIFT, Preview3D::CTRL, Preview3D::ALT;
-    virtual bool key_down(unsigned char key, int modifiers)
-    {
-      return false;
-    }
-
-    // This function is called when a keyboard key is release
-    // - modifiers is a bitfield that might one or more of the following bits Preview3D::NO_KEY, Preview3D::SHIFT, Preview3D::CTRL, Preview3D::ALT;
-    virtual bool key_up(unsigned char key, int modifiers)
-    {
-      return false;
-    }
-
-    // Priority of the plugin (use only positive numbers, negative are reserved for internal use)
-    // The plugins will be initialized in increasing priority
-    virtual int priority()
-    {
-      return 0;
-    }
-
-    std::string plugin_name;
-  protected:
-    // Pointer to the main Preview3D class
-    Viewer *viewer;
+      EIGEN_MAKE_ALIGNED_OPERATOR_NEW
   };
 
-  // Keeps the lists of plugins
-  class Plugin_manager
-  {
-  public:
-
-    Plugin_manager() {}
-
-    /** Registers a new plugin. A call to this function should be
-     implemented in the constructor of all classes derived from PreviewPlugin. */
-    bool register_plugin(Viewer_plugin* p)
-    {
-      auto it = plugin_list.begin();
-      while(it != plugin_list.end() && (*it)->priority() < p->priority())
-        ++it;
-
-      plugin_list.insert(it,p);
-      return true;
-    }
-
-    std::vector<Viewer_plugin*> plugin_list;
-  };
-
-
 } // end namespace
 
 #ifndef IGL_STATIC_LIBRARY

+ 409 - 0
include/igl/viewer/ViewerCore.cpp

@@ -0,0 +1,409 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#include "ViewerCore.h"
+#include <igl/quat_to_mat.h>
+#include <Eigen/Geometry>
+
+
+Eigen::Matrix4f lookAt (
+                        const Eigen::Vector3f& eye,
+                        const Eigen::Vector3f& center,
+                        const Eigen::Vector3f& up)
+{
+  Eigen::Vector3f f = (center - eye).normalized();
+  Eigen::Vector3f s = f.cross(up).normalized();
+  Eigen::Vector3f u = s.cross(f);
+
+  Eigen::Matrix4f Result = Eigen::Matrix4f::Identity();
+  Result(0,0) = s(0);
+  Result(0,1) = s(1);
+  Result(0,2) = s(2);
+  Result(1,0) = u(0);
+  Result(1,1) = u(1);
+  Result(1,2) = u(2);
+  Result(2,0) =-f(0);
+  Result(2,1) =-f(1);
+  Result(2,2) =-f(2);
+  Result(0,3) =-s.transpose() * eye;
+  Result(1,3) =-u.transpose() * eye;
+  Result(2,3) = f.transpose() * eye;
+  return Result;
+}
+
+Eigen::Matrix4f ortho (
+                       const float left,
+                       const float right,
+                       const float bottom,
+                       const float top,
+                       const float zNear,
+                       const float zFar
+                       )
+{
+  Eigen::Matrix4f Result = Eigen::Matrix4f::Identity();
+  Result(0,0) = 2.0f / (right - left);
+  Result(1,1) = 2.0f / (top - bottom);
+  Result(2,2) = - 2.0f / (zFar - zNear);
+  Result(0,3) = - (right + left) / (right - left);
+  Result(1,3) = - (top + bottom) / (top - bottom);
+  Result(2,3) = - (zFar + zNear) / (zFar - zNear);
+  return Result;
+}
+
+Eigen::Matrix4f frustum (
+                         const float left,
+                         const float right,
+                         const float bottom,
+                         const float top,
+                         const float nearVal,
+                         const float farVal)
+{
+  Eigen::Matrix4f Result = Eigen::Matrix4f::Zero();
+  Result(0,0) = (2.0f * nearVal) / (right - left);
+  Result(1,1) = (2.0f * nearVal) / (top - bottom);
+  Result(0,2) = (right + left) / (right - left);
+  Result(1,2) = (top + bottom) / (top - bottom);
+  Result(2,2) = -(farVal + nearVal) / (farVal - nearVal);
+  Result(3,2) = -1.0f;
+  Result(2,3) = -(2.0f * farVal * nearVal) / (farVal - nearVal);
+  return Result;
+}
+
+Eigen::Matrix4f scale (const Eigen::Matrix4f& m,
+                       const Eigen::Vector3f& v)
+{
+  Eigen::Matrix4f Result;
+  Result.col(0) = m.col(0).array() * v(0);
+  Result.col(1) = m.col(1).array() * v(1);
+  Result.col(2) = m.col(2).array() * v(2);
+  Result.col(3) = m.col(3);
+  return Result;
+}
+
+Eigen::Matrix4f translate(
+                          const Eigen::Matrix4f& m,
+                          const Eigen::Vector3f& v)
+{
+  Eigen::Matrix4f Result = m;
+  Result.col(3) = m.col(0).array() * v(0) + m.col(1).array() * v(1) + m.col(2).array() * v(2) + m.col(3).array();
+  return Result;
+}
+
+
+
+void igl::ViewerCore::InitSerialization()
+{
+  #ifdef ENABLE_XML_SERIALIZATION
+  xmlSerializer->Add(shininess, "shininess");
+  xmlSerializer->Add(background_color, "background_color");
+  xmlSerializer->Add(line_color, "line_color");
+  xmlSerializer->Add(light_position, "light_position");
+  xmlSerializer->Add(lighting_factor, "lighting_factor");
+  xmlSerializer->Add(trackball_angle, "trackball_angle");
+  xmlSerializer->Add(model_zoom, "model_zoom");
+  xmlSerializer->Add(model_translation, "model_translation");
+  xmlSerializer->Add(model_zoom_uv, "model_zoom_uv");
+  xmlSerializer->Add(model_translation_uv, "model_translation_uv");
+  xmlSerializer->Add(camera_zoom, "camera_zoom");
+  xmlSerializer->Add(orthographic, "orthographic");
+  xmlSerializer->Add(camera_eye, "camera_eye");
+  xmlSerializer->Add(camera_up, "camera_up");
+  xmlSerializer->Add(camera_center, "camera_center");
+  xmlSerializer->Add(camera_view_angle, "camera_view_angle");
+  xmlSerializer->Add(camera_dnear, "camera_dnear");
+  xmlSerializer->Add(camera_dfar, "camera_dfar");
+  xmlSerializer->Add(show_overlay, "show_overlay");
+  xmlSerializer->Add(show_overlay_depth, "show_overlay_depth");
+  xmlSerializer->Add(show_texture, "show_texture");
+  xmlSerializer->Add(show_faces, "show_faces");
+  xmlSerializer->Add(show_lines, "show_lines");
+  xmlSerializer->Add(show_vertid, "show_vertid");
+  xmlSerializer->Add(show_faceid, "show_faceid");
+  xmlSerializer->Add(point_size, "point_size");
+  xmlSerializer->Add(line_width, "line_width");
+  xmlSerializer->Add(invert_normals, "invert_normals");
+  xmlSerializer->Add(face_based, "face_based");
+  xmlSerializer->Add(face_based, "object_scale");
+  xmlSerializer->Add(viewport, "viewport");
+  xmlSerializer->Add(view, "view");
+  xmlSerializer->Add(model, "model");
+  xmlSerializer->Add(proj, "proj");
+
+  #endif
+}
+
+IGL_INLINE void igl::ViewerCore::align_camera_center(const Eigen::MatrixXd& V)
+{
+  get_scale_and_shift_to_fit_mesh(V,model_zoom,model_translation);
+  object_scale = (V.colwise().maxCoeff() - V.colwise().minCoeff()).norm();
+}
+
+IGL_INLINE void igl::ViewerCore::get_scale_and_shift_to_fit_mesh(
+  const Eigen::MatrixXd& V,
+  float& zoom,
+  Eigen::Vector3f& shift)
+{
+  if (V.rows() == 0)
+    return;
+
+  Eigen::RowVector3d min_point = V.colwise().minCoeff();
+  Eigen::RowVector3d max_point = V.colwise().maxCoeff();
+  Eigen::RowVector3d centroid  = (max_point.array() + min_point.array())/2;
+
+  shift = -centroid.cast<float>();
+  double x_scale = fabs(max_point[0] - min_point[0]);
+  double y_scale = fabs(max_point[1] - min_point[1]);
+  double z_scale = fabs(max_point[2] - min_point[2]);
+  zoom = 2.0/ std::max(z_scale,std::max(x_scale,y_scale));
+}
+
+IGL_INLINE void igl::ViewerCore::clear_framebuffers()
+{
+  glClearColor(background_color[0],
+               background_color[1],
+               background_color[2],
+               1.0f);
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+}
+
+IGL_INLINE void igl::ViewerCore::draw(ViewerData& data, OpenGL_state& opengl)
+{
+  using namespace std;
+  using namespace Eigen;
+
+  glEnable(GL_DEPTH_TEST);
+
+  /* Bind and potentially refresh mesh/line/point data */
+  if (data.dirty)
+  {
+    opengl.set_data(data, invert_normals);
+    data.dirty = ViewerData::DIRTY_NONE;
+  }
+  opengl.bind_mesh();
+
+  // Initialize uniform
+  glViewport(viewport(0), viewport(1), viewport(2), viewport(3));
+
+  model = Eigen::Matrix4f::Identity();
+  view  = Eigen::Matrix4f::Identity();
+  proj  = Eigen::Matrix4f::Identity();
+
+  // Set view
+  view = lookAt(Eigen::Vector3f(camera_eye[0], camera_eye[1], camera_eye[2]),
+                Eigen::Vector3f(camera_center[0], camera_center[1], camera_center[2]),
+                Eigen::Vector3f(camera_up[0], camera_up[1], camera_up[2]));
+
+  float width  = viewport(2);
+  float height = viewport(3);
+
+  // Set projection
+  if (orthographic)
+  {
+    float length = (camera_eye - camera_center).norm();
+    float h = tan(camera_view_angle/360.0 * M_PI) * (length);
+    proj = ortho(-h*width/height, h*width/height, -h, h, camera_dnear, camera_dfar);
+  }
+  else
+  {
+    float fH = tan(camera_view_angle / 360.0 * M_PI) * camera_dnear;
+    float fW = fH * (double)width/(double)height;
+    proj = frustum(-fW, fW, -fH, fH, camera_dnear, camera_dfar);
+  }
+  // end projection
+
+  // Set model transformation
+  float mat[16];
+  igl::quat_to_mat(trackball_angle.data(), mat);
+
+  for (unsigned i=0;i<4;++i)
+    for (unsigned j=0;j<4;++j)
+      model(i,j) = mat[i+4*j];
+
+  model = scale(model, Eigen::Vector3f(camera_zoom,camera_zoom,camera_zoom));
+  model = scale(model, Eigen::Vector3f(model_zoom,model_zoom,model_zoom));
+  model = translate(model, Eigen::Vector3f(model_translation[0],model_translation[1],model_translation[2]));
+
+  // Send transformations to the GPU
+  GLint modeli = opengl.shader_mesh.uniform("model");
+  GLint viewi  = opengl.shader_mesh.uniform("view");
+  GLint proji  = opengl.shader_mesh.uniform("proj");
+  glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
+  glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
+  glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
+
+  // Light parameters
+  GLint specular_exponenti    = opengl.shader_mesh.uniform("specular_exponent");
+  GLint light_position_worldi = opengl.shader_mesh.uniform("light_position_world");
+  GLint lighting_factori      = opengl.shader_mesh.uniform("lighting_factor");
+  GLint fixed_colori          = opengl.shader_mesh.uniform("fixed_color");
+  GLint texture_factori       = opengl.shader_mesh.uniform("texture_factor");
+
+  glUniform1f(specular_exponenti, shininess);
+  Vector3f rev_light = -1.*light_position;
+  glUniform3fv(light_position_worldi, 1, rev_light.data());
+  glUniform1f(lighting_factori, lighting_factor); // enables lighting
+  glUniform4f(fixed_colori, 0.0, 0.0, 0.0, 0.0);
+
+  if (data.V.rows()>0)
+  {
+    // Render fill
+    if (show_faces)
+    {
+      // Texture
+      glUniform1f(texture_factori, show_texture ? 1.0f : 0.0f);
+      opengl.draw_mesh(true);
+      glUniform1f(texture_factori, 0.0f);
+    }
+
+    // Render wireframe
+    if (show_lines)
+    {
+      glLineWidth(line_width);
+      glUniform4f(fixed_colori, line_color[0], line_color[1],
+        line_color[2], 1.0f);
+      opengl.draw_mesh(false);
+      glUniform4f(fixed_colori, 0.0f, 0.0f, 0.0f, 0.0f);
+    }
+
+    if (show_vertid)
+    {
+      textrenderer.BeginDraw(view*model, proj, viewport, object_scale);
+      for (int i=0; i<data.V.rows(); ++i)
+        textrenderer.DrawText(data.V.row(i), data.V_normals.row(i), to_string(i));
+      textrenderer.EndDraw();
+    }
+
+    if (show_faceid)
+    {
+      textrenderer.BeginDraw(view*model, proj, viewport, object_scale);
+
+      for (int i=0; i<data.F.rows(); ++i)
+      {
+        Eigen::RowVector3d p = Eigen::RowVector3d::Zero();
+        for (int j=0;j<data.F.cols();++j)
+          p += data.V.row(data.F(i,j));
+        p /= data.F.cols();
+
+        textrenderer.DrawText(p, data.F_normals.row(i), to_string(i));
+      }
+      textrenderer.EndDraw();
+    }
+  }
+
+  if (show_overlay)
+  {
+    if (show_overlay_depth)
+      glEnable(GL_DEPTH_TEST);
+    else
+      glDisable(GL_DEPTH_TEST);
+
+    if (data.lines.rows() > 0)
+    {
+      opengl.bind_overlay_lines();
+      modeli = opengl.shader_overlay_lines.uniform("model");
+      viewi  = opengl.shader_overlay_lines.uniform("view");
+      proji  = opengl.shader_overlay_lines.uniform("proj");
+
+      glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
+      glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
+      glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
+      // This must be enabled, otherwise glLineWidth has no effect
+      glEnable(GL_LINE_SMOOTH);
+      glLineWidth(line_width);
+
+      opengl.draw_overlay_lines();
+    }
+
+    if (data.points.rows() > 0)
+    {
+      opengl.bind_overlay_points();
+      modeli = opengl.shader_overlay_points.uniform("model");
+      viewi  = opengl.shader_overlay_points.uniform("view");
+      proji  = opengl.shader_overlay_points.uniform("proj");
+
+      glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
+      glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
+      glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
+      glPointSize(point_size);
+
+      opengl.draw_overlay_points();
+    }
+
+    if (data.labels_positions.rows() > 0)
+    {
+      textrenderer.BeginDraw(view*model, proj, viewport, object_scale);
+      for (int i=0; i<data.labels_positions.rows(); ++i)
+        textrenderer.DrawText(data.labels_positions.row(i), Eigen::Vector3d(0.0,0.0,0.0),
+            data.labels_strings[i]);
+      textrenderer.EndDraw();
+    }
+
+    glEnable(GL_DEPTH_TEST);
+  }
+
+}
+
+IGL_INLINE igl::ViewerCore::ViewerCore()
+#ifdef ENABLE_XML_SERIALIZATION
+: XMLSerialization("Core")
+#endif
+{
+  // Default shininess
+  shininess = 35.0f;
+
+  // Default colors
+  background_color << 0.3f, 0.3f, 0.5f;
+  line_color << 0.0f, 0.0f, 0.0f;
+
+  // Default lights settings
+  light_position << 0.0f, -0.30f, -5.0f;
+  lighting_factor = 1.0f; //on
+
+  // Default trackball
+  trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
+
+  // Defalut model viewing parameters
+  model_zoom = 1.0f;
+  model_translation << 0,0,0;
+
+  // Camera parameters
+  camera_zoom = 1.0f;
+  orthographic = false;
+  camera_view_angle = 45.0;
+  camera_dnear = 1.0;
+  camera_dfar = 100.0;
+  camera_eye << 0, 0, 5;
+  camera_center << 0, 0, 0;
+  camera_up << 0, 1, 0;
+
+  // Default visualization options
+  show_faces = true;
+  show_lines = true;
+  invert_normals = false;
+  show_overlay = true;
+  show_overlay_depth = true;
+  show_vertid = false;
+  show_faceid = false;
+  show_texture = false;
+
+  // Default point size / line width
+  point_size = 15;
+  line_width = 0.5f;
+  is_animating = false;
+  animation_max_fps = 30.;
+}
+
+IGL_INLINE void igl::ViewerCore::init()
+{
+  textrenderer.Init();
+}
+
+IGL_INLINE void igl::ViewerCore::shut()
+{
+  textrenderer.Shut();
+}

+ 134 - 0
include/igl/viewer/ViewerCore.h

@@ -0,0 +1,134 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef IGL_VIEWER_CORE_H
+#define IGL_VIEWER_CORE_H
+
+#include <igl/igl_inline.h>
+#include <igl/viewer/TextRenderer.h>
+#include <igl/viewer/ViewerData.h>
+#include <igl/viewer/OpenGL_state.h>
+
+namespace igl
+{
+
+// Basic class of the 3D mesh viewer
+// TODO: write documentation
+
+class ViewerCore
+#ifdef ENABLE_XML_SERIALIZATION
+: public ::igl::XMLSerialization
+#endif
+{
+public:
+  IGL_INLINE ViewerCore();
+
+  // Initialization
+  IGL_INLINE void init();
+
+  // Shutdown
+  IGL_INLINE void shut();
+
+  // Serialization code
+  IGL_INLINE void InitSerialization();
+
+
+  // ------------------- Camera control functions
+
+  // Adjust the view to see the entire model
+  IGL_INLINE void align_camera_center(const Eigen::MatrixXd& V);
+
+  // Determines how much to zoom and shift such that the mesh fills the unit
+  // box (centered at the origin)
+  IGL_INLINE void get_scale_and_shift_to_fit_mesh(
+    const Eigen::MatrixXd& V,
+    float & zoom,
+    Eigen::Vector3f& shift);
+
+  // ------------------- Drawing functions
+
+  // Clear the frame buffers
+  IGL_INLINE void clear_framebuffers();
+
+  // Draw everything
+  IGL_INLINE void draw(ViewerData& data, OpenGL_state& opengl);
+
+  // ------------------- Properties
+
+  // Text rendering helper
+  TextRenderer textrenderer;
+
+  // Shape material
+  float shininess;
+
+  // Colors
+  Eigen::Vector3f background_color;
+  Eigen::Vector3f line_color;
+
+  // Lighting
+  Eigen::Vector3f light_position;
+  float lighting_factor;
+
+  // Trackball angle (quaternion)
+  Eigen::Vector4f trackball_angle;
+
+  // Model viewing parameters
+  float model_zoom;
+  Eigen::Vector3f model_translation;
+
+  // Model viewing paramters (uv coordinates)
+  float model_zoom_uv;
+  Eigen::Vector3f model_translation_uv;
+
+  // Camera parameters
+  float camera_zoom;
+  bool orthographic;
+  Eigen::Vector3f camera_eye;
+  Eigen::Vector3f camera_up;
+  Eigen::Vector3f camera_center;
+  float camera_view_angle;
+  float camera_dnear;
+  float camera_dfar;
+
+  // Visualization options
+  bool show_overlay;
+  bool show_overlay_depth;
+  bool show_texture;
+  bool show_faces;
+  bool show_lines;
+  bool show_vertid;
+  bool show_faceid;
+  bool invert_normals;
+
+  // Point size / line width
+  float point_size;
+  float line_width;
+
+  // Animation
+  bool is_animating;
+  double animation_max_fps;
+
+  // Caches the two-norm between the min/max point of the bounding box
+  float object_scale;
+
+  // Viewport size
+  Eigen::Vector4f viewport;
+
+  // Save the OpenGL transformation matrices used for the previous rendering pass
+  Eigen::Matrix4f view;
+  Eigen::Matrix4f model;
+  Eigen::Matrix4f proj;
+};
+
+}
+
+#ifndef IGL_STATIC_LIBRARY
+#  include "ViewerCore.cpp"
+#endif
+
+#endif

+ 394 - 0
include/igl/viewer/ViewerData.cpp

@@ -0,0 +1,394 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#include "ViewerData.h"
+
+#include <igl/per_face_normals.h>
+#include <igl/per_vertex_normals.h>
+#include <iostream>
+
+IGL_INLINE igl::ViewerData::ViewerData()
+#ifdef ENABLE_XML_SERIALIZATION
+: XMLSerialization("Data"), dirty(DIRTY_ALL)
+#endif
+{
+  clear();
+};
+
+IGL_INLINE void igl::ViewerData::InitSerialization()
+{
+  #ifdef ENABLE_XML_SERIALIZATION
+  xmlSerializer->Add(V,"V");
+  xmlSerializer->Add(F,"F");
+  xmlSerializer->Add(F_normals,"F_normals");
+
+  xmlSerializer->Add(F_material_ambient,"F_material_ambient");
+  xmlSerializer->Add(F_material_diffuse,"F_material_diffuse");
+  xmlSerializer->Add(F_material_specular,"F_material_specular");
+
+  xmlSerializer->Add(V_normals,"V_normals");
+  xmlSerializer->Add(V_material_ambient,"V_material_ambient");
+  xmlSerializer->Add(V_material_diffuse,"V_material_diffuse");
+  xmlSerializer->Add(V_material_specular,"V_material_specular");
+
+  xmlSerializer->Add(V_uv,"V_uv");
+  xmlSerializer->Add(F_uv,"F_uv");
+  xmlSerializer->Add(texture_R,"texture_R");
+  xmlSerializer->Add(texture_G,"texture_G");
+  xmlSerializer->Add(texture_B,"texture_B");
+  xmlSerializer->Add(lines,"lines");
+  xmlSerializer->Add(points,"points");
+
+  xmlSerializer->Add(labels_positions,"labels_positions");
+  xmlSerializer->Add(labels_strings,"labels_strings");
+
+  xmlSerializer->Add(face_based,"face_based");
+
+  #endif
+}
+
+IGL_INLINE void igl::ViewerData::set_face_based(bool newvalue)
+{
+  if (face_based != newvalue)
+  {
+    face_based = newvalue;
+    dirty = DIRTY_ALL;
+  }
+}
+
+// Helpers that draws the most common meshes
+IGL_INLINE void igl::ViewerData::set_mesh(const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F)
+{
+  using namespace std;
+
+  Eigen::MatrixXd V_temp;
+
+  // If V only has two columns, pad with a column of zeros
+  if (_V.cols() == 2)
+  {
+    V_temp = Eigen::MatrixXd::Zero(V.rows(),3);
+    V_temp.block(0,0,V.rows(),2) = _V;
+  }
+  else
+    V_temp = _V;
+
+  if (V.rows() == 0 && F.rows() == 0)
+  {
+    clear();
+    V = V_temp;
+    F = _F;
+
+    compute_normals();
+    uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
+                   Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
+                   Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
+
+    grid_texture();
+  }
+  else
+  {
+    if (V.rows() == V.rows() && F.rows() == F.rows())
+    {
+      V = V_temp;
+      F = _F;
+    }
+    else
+      cerr << "ERROR (set_mesh): The new mesh has a different number of vertices/faces. Please clear the mesh before plotting.";
+  }
+  dirty |= DIRTY_FACE | DIRTY_POSITION;
+}
+
+IGL_INLINE void igl::ViewerData::set_vertices(const Eigen::MatrixXd& _V)
+{
+  V = _V;
+  assert(F.size() == 0 || F.maxCoeff() < V.rows());
+  dirty |= DIRTY_POSITION;
+}
+
+IGL_INLINE void igl::ViewerData::set_normals(const Eigen::MatrixXd& N)
+{
+  using namespace std;
+  if (N.rows() == V.rows())
+  {
+    set_face_based(false);
+    V_normals = N;
+  }
+  else if (N.rows() == F.rows() || N.rows() == F.rows()*3)
+  {
+    set_face_based(true);
+    F_normals = N;
+  }
+  else
+    cerr << "ERROR (set_normals): Please provide a normal per face, per corner or per vertex.";
+  dirty |= DIRTY_NORMAL;
+}
+
+IGL_INLINE void igl::ViewerData::set_colors(const Eigen::MatrixXd &C)
+{
+  using namespace std;
+  using namespace Eigen;
+  // Ambient color should be darker color
+  const auto ambient = [](const MatrixXd & C)->MatrixXd
+  {
+    return 0.1*C;
+  };
+  // Specular color should be a less saturated and darker color: dampened
+  // highlights
+  const auto specular = [](const MatrixXd & C)->MatrixXd
+  {
+    const double grey = 0.3;
+    return grey+0.1*(C.array()-grey);
+  };
+  if (C.rows() == 1)
+  {
+    for (unsigned i=0;i<V_material_diffuse.rows();++i)
+    {
+      V_material_diffuse.row(i) = C.row(0);
+    }
+    V_material_ambient = ambient(V_material_diffuse);
+    V_material_specular = specular(V_material_diffuse);
+
+    for (unsigned i=0;i<F_material_diffuse.rows();++i)
+    {
+      F_material_diffuse.row(i) = C.row(0);
+    }
+    F_material_ambient = ambient(F_material_diffuse);
+    F_material_specular = specular(F_material_diffuse);
+  }
+  else if (C.rows() == V.rows())
+  {
+    set_face_based(false);
+    V_material_diffuse = C;
+    V_material_ambient = ambient(V_material_diffuse);
+    V_material_specular = specular(V_material_diffuse);
+  }
+  else if (C.rows() == F.rows())
+  {
+    set_face_based(true);
+    F_material_diffuse = C;
+    F_material_ambient = ambient(F_material_diffuse);
+    F_material_specular = specular(F_material_diffuse);
+  }
+  else
+    cerr << "ERROR (set_colors): Please provide a single color, or a color per face or per vertex.";
+  dirty |= DIRTY_DIFFUSE;
+
+}
+
+IGL_INLINE void igl::ViewerData::set_uv(const Eigen::MatrixXd& UV)
+{
+  using namespace std;
+  if (UV.rows() == V.rows())
+  {
+    set_face_based(false);
+    V_uv = UV;
+  }
+  else
+    cerr << "ERROR (set_UV): Please provide uv per vertex.";
+  dirty |= DIRTY_UV;
+}
+
+IGL_INLINE void igl::ViewerData::set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F)
+{
+  set_face_based(true);
+  V_uv = UV_V;
+  F_uv = UV_F;
+  dirty |= DIRTY_UV;
+}
+
+
+IGL_INLINE void igl::ViewerData::set_texture(
+  const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& R,
+  const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& G,
+  const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& B)
+{
+  texture_R = R;
+  texture_G = G;
+  texture_B = B;
+  dirty |= DIRTY_TEXTURE;
+}
+
+IGL_INLINE void igl::ViewerData::add_points(const Eigen::MatrixXd& P,  const Eigen::MatrixXd& C)
+{
+  Eigen::MatrixXd P_temp;
+
+  // If P only has two columns, pad with a column of zeros
+  if (P.cols() == 2)
+  {
+    P_temp = Eigen::MatrixXd::Zero(P.rows(),3);
+    P_temp.block(0,0,P.rows(),2) = P;
+  }
+  else
+    P_temp = P;
+
+  int lastid = points.rows();
+  points.conservativeResize(points.rows() + P_temp.rows(),6);
+  for (unsigned i=0; i<P_temp.rows(); ++i)
+    points.row(lastid+i) << P_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
+
+  dirty |= DIRTY_OVERLAY_POINTS;
+}
+
+IGL_INLINE void igl::ViewerData::set_edges(
+  const Eigen::MatrixXd& P,
+  const Eigen::MatrixXi& E,
+  const Eigen::MatrixXd& C)
+{
+  using namespace Eigen;
+  lines.resize(E.rows(),9);
+  assert(C.cols() == 3);
+  for(int e = 0;e<E.rows();e++)
+  {
+    RowVector3d color;
+    if(C.size() == 3)
+    {
+      color<<C;
+    }else if(C.rows() == E.rows())
+    {
+      color<<C.row(e);
+    }
+    lines.row(e)<< P.row(E(e,0)), P.row(E(e,1)), color;
+  }
+  dirty |= DIRTY_OVERLAY_LINES;
+}
+
+IGL_INLINE void igl::ViewerData::add_edges(const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C)
+{
+  Eigen::MatrixXd P1_temp,P2_temp;
+
+  // If P1 only has two columns, pad with a column of zeros
+  if (P1.cols() == 2)
+  {
+    P1_temp = Eigen::MatrixXd::Zero(P1.rows(),3);
+    P1_temp.block(0,0,P1.rows(),2) = P1;
+    P2_temp = Eigen::MatrixXd::Zero(P2.rows(),3);
+    P2_temp.block(0,0,P2.rows(),2) = P2;
+  }
+  else
+  {
+    P1_temp = P1;
+    P2_temp = P2;
+  }
+
+  int lastid = lines.rows();
+  lines.conservativeResize(lines.rows() + P1_temp.rows(),9);
+  for (unsigned i=0; i<P1_temp.rows(); ++i)
+    lines.row(lastid+i) << P1_temp.row(i), P2_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
+
+  dirty |= DIRTY_OVERLAY_LINES;
+}
+
+IGL_INLINE void igl::ViewerData::add_label(const Eigen::VectorXd& P,  const std::string& str)
+{
+  Eigen::RowVectorXd P_temp;
+
+  // If P only has two columns, pad with a column of zeros
+  if (P.size() == 2)
+  {
+    P_temp = Eigen::RowVectorXd::Zero(3);
+    P_temp << P, 0;
+  }
+  else
+    P_temp = P;
+
+  int lastid = labels_positions.rows();
+  labels_positions.conservativeResize(lastid+1, 3);
+  labels_positions.row(lastid) = P_temp;
+  labels_strings.push_back(str);
+}
+
+IGL_INLINE void igl::ViewerData::clear()
+{
+  V                       = Eigen::MatrixXd (0,3);
+  F                       = Eigen::MatrixXi (0,3);
+
+  F_material_ambient      = Eigen::MatrixXd (0,3);
+  F_material_diffuse      = Eigen::MatrixXd (0,3);
+  F_material_specular     = Eigen::MatrixXd (0,3);
+
+  V_material_ambient      = Eigen::MatrixXd (0,3);
+  V_material_diffuse      = Eigen::MatrixXd (0,3);
+  V_material_specular     = Eigen::MatrixXd (0,3);
+
+  F_normals               = Eigen::MatrixXd (0,3);
+  V_normals               = Eigen::MatrixXd (0,3);
+
+  V_uv                    = Eigen::MatrixXd (0,2);
+  F_uv                    = Eigen::MatrixXi (0,3);
+
+  lines                   = Eigen::MatrixXd (0,9);
+  points                  = Eigen::MatrixXd (0,6);
+  labels_positions        = Eigen::MatrixXd (0,3);
+  labels_strings.clear();
+
+  face_based = false;
+}
+
+IGL_INLINE void igl::ViewerData::compute_normals()
+{
+  igl::per_face_normals(V, F, F_normals);
+  igl::per_vertex_normals(V, F, F_normals, V_normals);
+  dirty |= DIRTY_NORMAL;
+}
+
+IGL_INLINE void igl::ViewerData::uniform_colors(Eigen::Vector3d ambient, Eigen::Vector3d diffuse, Eigen::Vector3d specular)
+{
+  V_material_ambient.resize(V.rows(),3);
+  V_material_diffuse.resize(V.rows(),3);
+  V_material_specular.resize(V.rows(),3);
+
+  for (unsigned i=0; i<V.rows();++i)
+  {
+    V_material_ambient.row(i) = ambient;
+    V_material_diffuse.row(i) = diffuse;
+    V_material_specular.row(i) = specular;
+  }
+
+  F_material_ambient.resize(F.rows(),3);
+  F_material_diffuse.resize(F.rows(),3);
+  F_material_specular.resize(F.rows(),3);
+
+  for (unsigned i=0; i<F.rows();++i)
+  {
+    F_material_ambient.row(i) = ambient;
+    F_material_diffuse.row(i) = diffuse;
+    F_material_specular.row(i) = specular;
+  }
+  dirty |= DIRTY_SPECULAR | DIRTY_DIFFUSE | DIRTY_AMBIENT;
+}
+
+IGL_INLINE void igl::ViewerData::grid_texture()
+{
+  if (V_uv.rows() == 0)
+  {
+    V_uv = V.block(0, 0, V.rows(), 2);
+    V_uv.col(0) = V_uv.col(0).array() - V_uv.col(0).minCoeff();
+    V_uv.col(0) = V_uv.col(0).array() / V_uv.col(0).maxCoeff();
+    V_uv.col(1) = V_uv.col(1).array() - V_uv.col(1).minCoeff();
+    V_uv.col(1) = V_uv.col(1).array() / V_uv.col(1).maxCoeff();
+    V_uv = V_uv.array() * 10;
+    dirty |= DIRTY_TEXTURE;
+  }
+
+  unsigned size = 128;
+  unsigned size2 = size/2;
+  texture_R.resize(size, size);
+  for (unsigned i=0; i<size; ++i)
+  {
+    for (unsigned j=0; j<size; ++j)
+    {
+      texture_R(i,j) = 0;
+      if ((i<size2 && j<size2) || (i>=size2 && j>=size2))
+        texture_R(i,j) = 255;
+    }
+  }
+
+  texture_G = texture_R;
+  texture_B = texture_R;
+  dirty |= DIRTY_TEXTURE;
+}

+ 152 - 0
include/igl/viewer/ViewerData.h

@@ -0,0 +1,152 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef IGL_VIEWER_DATA_H
+#define IGL_VIEWER_DATA_H
+
+#include <igl/igl_inline.h>
+#include <Eigen/Core>
+
+namespace igl
+{
+
+// Store the data visualized by ViewerCore
+// TODO: write documentation
+
+class ViewerData
+#ifdef ENABLE_XML_SERIALIZATION
+: public ::igl::XMLSerialization
+#endif
+{
+public:
+  ViewerData();
+
+  enum DirtyFlags
+  {
+    DIRTY_NONE           = 0x0000,
+    DIRTY_POSITION       = 0x0001,
+    DIRTY_UV             = 0x0002,
+    DIRTY_NORMAL         = 0x0004,
+    DIRTY_AMBIENT        = 0x0008,
+    DIRTY_DIFFUSE        = 0x0010,
+    DIRTY_SPECULAR       = 0x0020,
+    DIRTY_TEXTURE        = 0x0040,
+    DIRTY_FACE           = 0x0080,
+    DIRTY_MESH           = 0x00FF,
+    DIRTY_OVERLAY_LINES  = 0x0100,
+    DIRTY_OVERLAY_POINTS = 0x0200,
+    DIRTY_ALL            = 0x03FF
+  };
+
+  // Empy all fields
+  IGL_INLINE void clear();
+
+  // Change the visualization mode, invalidating the cache if necessary
+  IGL_INLINE void set_face_based(bool newvalue);
+
+  // Helpers that can draw the most common meshes
+  IGL_INLINE void set_mesh(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F);
+  IGL_INLINE void set_vertices(const Eigen::MatrixXd& V);
+  IGL_INLINE void set_normals(const Eigen::MatrixXd& N);
+
+  // Set the color of the mesh
+  //
+  // Inputs:
+  //   C  #V|#F|1 by 3 list of colors
+  IGL_INLINE void set_colors(const Eigen::MatrixXd &C);
+  IGL_INLINE void set_uv(const Eigen::MatrixXd& UV);
+  IGL_INLINE void set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F);
+  IGL_INLINE void set_texture(
+                    const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& R,
+                    const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& G,
+                    const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& B);
+
+  IGL_INLINE void add_points(const Eigen::MatrixXd& P,  const Eigen::MatrixXd& C);
+  // Sets edges given a list of edge vertices and edge indices. In constrast
+  // to `add_edges` this will (purposefully) clober existing edges.
+  //
+  // Inputs:
+  //   P  #P by 3 list of vertex positions
+  //   E  #E by 2 list of edge indices into P
+  //   C  #E|1 by 3 color(s)
+  IGL_INLINE void set_edges (const Eigen::MatrixXd& P, const Eigen::MatrixXi& E, const Eigen::MatrixXd& C);
+  IGL_INLINE void add_edges (const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C);
+  IGL_INLINE void add_label (const Eigen::VectorXd& P,  const std::string& str);
+
+  // Computes the normals of the mesh
+  IGL_INLINE void compute_normals();
+
+  // Assigns uniform colors to all faces/vertices
+  IGL_INLINE void uniform_colors(Eigen::Vector3d ambient, Eigen::Vector3d diffuse, Eigen::Vector3d specular);
+
+  // Generates a default grid texture
+  IGL_INLINE void grid_texture();
+
+  // Serialization code
+  IGL_INLINE void InitSerialization();
+
+  Eigen::MatrixXd V; // Vertices of the current mesh (#V x 3)
+  Eigen::MatrixXi F; // Faces of the mesh (#F x 3)
+
+  // Per face attributes
+  Eigen::MatrixXd F_normals; // One normal per face
+
+  Eigen::MatrixXd F_material_ambient; // Per face ambient color
+  Eigen::MatrixXd F_material_diffuse; // Per face diffuse color
+  Eigen::MatrixXd F_material_specular; // Per face specular color
+
+  // Per vertex attributes
+  Eigen::MatrixXd V_normals; // One normal per vertex
+
+  Eigen::MatrixXd V_material_ambient; // Per vertex ambient color
+  Eigen::MatrixXd V_material_diffuse; // Per vertex diffuse color
+  Eigen::MatrixXd V_material_specular; // Per vertex specular color
+
+  // UV parametrization
+  Eigen::MatrixXd V_uv; // UV vertices
+  Eigen::MatrixXi F_uv; // optional faces for UVs
+
+  // Texture
+  Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> texture_R;
+  Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> texture_G;
+  Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> texture_B;
+
+  // Overlays
+
+  // Lines plotted over the scene
+  // (Every row contains 9 doubles in the following format S_x, S_y, S_z, T_x, T_y, T_z, C_r, C_g, C_b),
+  // with S and T the coordinates of the two vertices of the line in global coordinates, and C the color in floating point rgb format
+  Eigen::MatrixXd lines;
+
+  // Points plotted over the scene
+  // (Every row contains 6 doubles in the following format P_x, P_y, P_z, C_r, C_g, C_b),
+  // with P the position in global coordinates of the center of the point, and C the color in floating point rgb format
+  Eigen::MatrixXd points;
+
+  // Text labels plotted over the scene
+  // Textp contains, in the i-th row, the position in global coordinates where the i-th label should be anchored
+  // Texts contains in the i-th position the text of the i-th label
+  Eigen::MatrixXd           labels_positions;
+  std::vector<std::string > labels_strings;
+
+  // Marks dirty buffers that need to be uploaded to OpenGL
+  uint32_t dirty;
+
+  // Enable per-face or per-vertex properties
+  bool face_based;
+  /*********************************/
+};
+
+
+}
+
+#ifndef IGL_STATIC_LIBRARY
+#  include "ViewerData.cpp"
+#endif
+
+#endif

+ 141 - 0
include/igl/viewer/ViewerPlugin.h

@@ -0,0 +1,141 @@
+// This file is part of libigl, a simple c++ geometry processing library.
+//
+// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
+//
+// This Source Code Form is subject to the terms of the Mozilla Public License
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef IGL_VIEWER_PLUGIN_H
+#define IGL_VIEWER_PLUGIN_H
+
+#include <igl/igl_inline.h>
+
+#ifdef ENABLE_XML_SERIALIZATION
+  #include <igl/xml/XMLSerializer.h>
+  #include <igl/xml/XMLSerialization.h>
+#endif
+
+namespace igl
+{
+
+// Abstract class for plugins
+// All plugins MUST have this class as their parent and implement all the callbacks
+// For an example of a basic plugins see plugins/skeleton.h
+//
+// Return value of callbacks: returning true to any of the callbacks tells Preview3D that the event has been
+// handled and that it should not be passed to other plugins or to other internal functions of Preview3D
+
+// Forward declaration of the viewer
+class Viewer;
+
+class ViewerPlugin
+#ifdef ENABLE_XML_SERIALIZATION
+: public ::igl::XMLSerialization
+#endif
+{
+public:
+  IGL_INLINE ViewerPlugin()
+  #ifdef ENABLE_XML_SERIALIZATION
+  : XMLSerialization("dummy")
+  #endif
+  {plugin_name = "dummy";};
+
+  ~ViewerPlugin(){};
+
+  // This function is called when the viewer is initialized (no mesh will be loaded at this stage)
+  IGL_INLINE virtual void init(igl::Viewer *_viewer)
+  {
+    viewer = _viewer;
+  }
+
+  // This function is called before shutdown
+  IGL_INLINE virtual void shutdown()
+  {
+  }
+
+  // This function is called before a mesh is loaded
+  IGL_INLINE virtual bool load(std::string filename)
+  {
+    return false;
+  }
+
+  // This function is called before a mesh is saved
+  IGL_INLINE virtual bool save(std::string filename)
+  {
+    return false;
+  }
+
+  // Runs immediately after a new mesh had been loaded.
+  IGL_INLINE virtual bool post_load()
+  {
+    return false;
+  }
+
+  // This function is called before the draw procedure of Preview3D
+  IGL_INLINE virtual bool pre_draw()
+  {
+    return false;
+  }
+
+  // This function is called after the draw procedure of Preview3D
+  IGL_INLINE virtual bool post_draw()
+  {
+    return false;
+  }
+
+  // This function is called when the mouse button is pressed
+  // - button can be GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON or GLUT_RIGHT_BUTTON
+  // - modifiers is a bitfield that might one or more of the following bits Preview3D::NO_KEY, Preview3D::SHIFT, Preview3D::CTRL, Preview3D::ALT;
+  IGL_INLINE virtual bool mouse_down(int button, int modifier)
+  {
+    return false;
+  }
+
+  // This function is called when the mouse button is released
+  // - button can be GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON or GLUT_RIGHT_BUTTON
+  // - modifiers is a bitfield that might one or more of the following bits Preview3D::NO_KEY, Preview3D::SHIFT, Preview3D::CTRL, Preview3D::ALT;
+  IGL_INLINE virtual bool mouse_up(int button, int modifier)
+  {
+    return false;
+  }
+
+  // This function is called every time the mouse is moved
+  // - mouse_x and mouse_y are the new coordinates of the mouse pointer in screen coordinates
+  IGL_INLINE virtual bool mouse_move(int mouse_x, int mouse_y)
+  {
+    return false;
+  }
+
+  // This function is called every time the scroll wheel is moved
+  // Note: this callback is not working with every glut implementation
+  IGL_INLINE virtual bool mouse_scroll(float delta_y)
+  {
+    return false;
+  }
+
+  // This function is called when a keyboard key is pressed
+  // - modifiers is a bitfield that might one or more of the following bits Preview3D::NO_KEY, Preview3D::SHIFT, Preview3D::CTRL, Preview3D::ALT;
+  IGL_INLINE virtual bool key_down(unsigned char key, int modifiers)
+  {
+    return false;
+  }
+
+  // This function is called when a keyboard key is release
+  // - modifiers is a bitfield that might one or more of the following bits Preview3D::NO_KEY, Preview3D::SHIFT, Preview3D::CTRL, Preview3D::ALT;
+  IGL_INLINE virtual bool key_up(unsigned char key, int modifiers)
+  {
+    return false;
+  }
+
+  std::string plugin_name;
+protected:
+  // Pointer to the main Preview3D class
+  Viewer *viewer;
+public:
+    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
+};
+
+}
+
+#endif

+ 2 - 2
tutorial/101_FileIO/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 2 - 2
tutorial/102_DrawMesh/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 2 - 2
tutorial/103_Events/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 3 - 4
tutorial/103_Events/main.cpp

@@ -1,4 +1,3 @@
-#define IGL_HEADER_ONLY
 #include <igl/readOFF.h>
 #include <igl/viewer/Viewer.h>
 
@@ -10,8 +9,8 @@ bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
 {
   if (key == '1')
   {
-    // Clear mesh should be called before drawing the mesh
-    viewer.clear_mesh();
+    // Clear should be called before drawing the mesh
+    viewer.clear();
     // Draw_mesh creates or updates the vertices and faces of the displayed mesh.
     // If a mesh is already displayed, draw_mesh returns an error if the given V and
     // F have size different than the current ones
@@ -19,7 +18,7 @@ bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
   }
   else if (key == '2')
   {
-    viewer.clear_mesh();
+    viewer.clear();
     viewer.set_mesh(V2, F2);
   }
 

+ 2 - 2
tutorial/104_Colors/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 5 - 12
tutorial/104_Colors/main.cpp

@@ -5,6 +5,7 @@
 
 Eigen::MatrixXd V;
 Eigen::MatrixXi F;
+Eigen::MatrixXd C;
 
 int main(int argc, char *argv[])
 {
@@ -15,19 +16,11 @@ int main(int argc, char *argv[])
   igl::Viewer viewer;
   viewer.set_mesh(V, F);
 
+  // Use the x coordinate as a scalar field over the surface
+  Eigen::VectorXd x = V.col(2);
 
-  // Normalize x coordinate between 0 and 1
-  Eigen::VectorXd value = V.col(0).array() - V.col(0).minCoeff();
-  value = value.array() / value.maxCoeff();
-
-  // Map to colors using jet colorramp
-  Eigen::MatrixXd C(V.rows(),3);
-  for (unsigned i=0; i<V.rows(); ++i)
-  {
-    double r,g,b;
-    igl::jet(value(i),r,g,b);
-    C.row(i) << r,g,b;
-  }
+  // Compute per-vertex colors
+  igl::jet(x,true,C);
 
   // Add per-vertex colors
   viewer.set_colors(C);

+ 2 - 2
tutorial/105_Overlays/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 0 - 3
tutorial/105_Overlays/main.cpp

@@ -59,9 +59,6 @@ int main(int argc, char *argv[])
       Eigen::RowVector3d(1,0,0)
     );
 
-  // Increase the thickness of the lines
-  viewer.options.line_width = 2.0f;
-
   // Plot labels with the coordinates of bounding box vertices
   std::stringstream l1;
   l1 << m(0) << ", " << m(1) << ", " << m(2);

+ 2 - 2
tutorial/106_Picking/CMakeLists.txt

@@ -11,5 +11,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES} ${EMBREE_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES} ${EMBREE_LIBRARIES})

+ 4 - 2
tutorial/106_Picking/main.cpp

@@ -25,7 +25,9 @@ bool mouse_down(igl::Viewer& viewer, int button, int modifier)
   int vid, fid;
 
   // Cast a ray in the view direction starting from the mouse position
-  bool hit = unproject_in_mesh(Vector2f(viewer.current_mouse_x,viewer.viewport(3) - viewer.current_mouse_y),
+  double x = viewer.current_mouse_x;
+  double y = viewer.viewport(3) - viewer.current_mouse_y;
+  bool hit = unproject_in_mesh(Vector2f(x,y),
                                 F,
                                 viewer.view * viewer.model,
                                 viewer.proj,
@@ -63,6 +65,6 @@ int main(int argc, char *argv[])
   viewer.set_mesh(V, F);
   viewer.callback_mouse_down = &mouse_down;
   viewer.set_colors(C);
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
   viewer.launch();
 }

+ 2 - 2
tutorial/201_Normals/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 1 - 1
tutorial/201_Normals/main.cpp

@@ -48,7 +48,7 @@ int main(int argc, char *argv[])
   // Plot the mesh
   igl::Viewer viewer;
   viewer.callback_key_down = &key_down;
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
   viewer.set_mesh(V, F);
   viewer.set_normals(N_vertices);
   viewer.launch();

+ 2 - 2
tutorial/202_GaussianCurvature/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 2 - 2
tutorial/203_CurvatureDirections/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 1 - 1
tutorial/203_CurvatureDirections/main.cpp

@@ -57,7 +57,7 @@ int main(int argc, char *argv[])
   viewer.add_edges(V + PD2*avg, V - PD2*avg, blue);
 
   // Hide wireframe
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
 
   viewer.launch();
 }

+ 2 - 2
tutorial/204_Gradient/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 1 - 1
tutorial/204_Gradient/main.cpp

@@ -50,7 +50,7 @@ int main(int argc, char *argv[])
   viewer.add_edges(BC,BC+max_size*GU, black);
 
   // Hide wireframe
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
 
   viewer.launch();
 }

+ 2 - 2
tutorial/205_Laplacian/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 2 - 2
tutorial/301_Slice/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 2 - 2
tutorial/302_Sort/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 2 - 2
tutorial/303_LaplaceEquation/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 1 - 1
tutorial/303_LaplaceEquation/main.cpp

@@ -65,7 +65,7 @@ int main(int argc, char *argv[])
   // Plot the mesh with pseudocolors
   igl::Viewer viewer;
   viewer.set_mesh(V, F);
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
   viewer.set_colors(C);
   viewer.launch();
 }

+ 2 - 2
tutorial/304_LinearEqualityConstraints/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 1 - 1
tutorial/304_LinearEqualityConstraints/main.cpp

@@ -72,7 +72,7 @@ int main(int argc, char *argv[])
   // Plot the mesh with pseudocolors
   igl::Viewer viewer;
   viewer.set_mesh(V, F);
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
   viewer.set_colors(data.C);
 
   viewer.callback_key_down = 

+ 2 - 2
tutorial/305_QuadraticProgramming/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 1 - 1
tutorial/305_QuadraticProgramming/main.cpp

@@ -58,7 +58,7 @@ int main(int argc, char *argv[])
   // Plot the mesh
   igl::Viewer viewer;
   viewer.set_mesh(V, F);
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
   viewer.callback_key_down = &key_down;
 
   // One fixed point

+ 11 - 0
tutorial/401_BiharmonicDeformation/CMakeLists.txt

@@ -0,0 +1,11 @@
+cmake_minimum_required(VERSION 2.6)
+project(401_BiharmonicDeformation)
+
+include("../CMakeLists.shared")
+
+set(SOURCES
+${PROJECT_SOURCE_DIR}/main.cpp
+)
+
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 121 - 0
tutorial/401_BiharmonicDeformation/main.cpp

@@ -0,0 +1,121 @@
+#include <igl/colon.h>
+#include <igl/harmonic.h>
+#include <igl/readOBJ.h>
+#include <igl/readDMAT.h>
+#include <igl/viewer/Viewer.h>
+#include <algorithm>
+#include <iostream>
+
+double bc_frac = 1.0;
+double bc_dir = -0.03;
+bool deformation_field = false;
+Eigen::MatrixXd V,U,V_bc,U_bc;
+Eigen::VectorXd Z;
+Eigen::MatrixXi F;
+Eigen::VectorXi b;
+
+bool pre_draw(igl::Viewer & viewer)
+{
+  using namespace Eigen;
+  // Determine boundary conditions
+  if(viewer.core.is_animating)
+  {
+    bc_frac += bc_dir;
+    bc_dir *= (bc_frac>=1.0 || bc_frac<=0.0?-1.0:1.0);
+  }
+
+  const MatrixXd U_bc_anim = V_bc+bc_frac*(U_bc-V_bc);
+  if(deformation_field)
+  {
+    MatrixXd D;
+    MatrixXd D_bc = U_bc_anim - V_bc;
+    igl::harmonic(V,F,b,D_bc,2,D);
+    U = V+D;
+  }else
+  {
+    igl::harmonic(V,F,b,U_bc_anim,2,U);
+  }
+  viewer.set_vertices(U);
+  viewer.compute_normals();
+  return false;
+}
+
+bool key_down(igl::Viewer &viewer, unsigned char key, int mods)
+{
+  switch(key)
+  {
+    case ' ':
+      viewer.core.is_animating = !viewer.core.is_animating;
+      break;
+    case 'D':
+    case 'd':
+      deformation_field = !deformation_field;
+      break;
+  }
+}
+
+int main(int argc, char *argv[])
+{
+  using namespace Eigen;
+  using namespace std;
+  igl::readOBJ("../shared/decimated-max.obj",V,F);
+  U=V;
+  // S(i) = j: j<0 (vertex i not in handle), j >= 0 (vertex i in handle j)
+  VectorXi S;
+  igl::readDMAT("../shared/decimated-max-selection.dmat",S);
+  igl::colon<int>(0,V.rows()-1,b);
+  b.conservativeResize(stable_partition( b.data(), b.data()+b.size(), 
+   [&S](int i)->bool{return S(i)>=0;})-b.data());
+
+  // Boundary conditions directly on deformed positions
+  U_bc.resize(b.size(),V.cols());
+  V_bc.resize(b.size(),V.cols());
+  for(int bi = 0;bi<b.size();bi++)
+  {
+    V_bc.row(bi) = V.row(b(bi));
+    switch(S(b(bi)))
+    {
+      case 0:
+        // Don't move handle 0
+        U_bc.row(bi) = V.row(b(bi));
+        break;
+      case 1:
+        // move handle 1 down
+        U_bc.row(bi) = V.row(b(bi)) + RowVector3d(0,-50,0);
+        break;
+      case 2:
+      default:
+        // move other handles forward
+        U_bc.row(bi) = V.row(b(bi)) + RowVector3d(0,0,-25);
+        break;
+    }
+  }
+
+  // Pseudo-color based on selection
+  MatrixXd C(F.rows(),3);
+  RowVector3d purple(80.0/255.0,64.0/255.0,255.0/255.0);
+  RowVector3d gold(255.0/255.0,228.0/255.0,58.0/255.0);
+  for(int f = 0;f<F.rows();f++)
+  {
+    if( S(F(f,0))>=0 && S(F(f,1))>=0 && S(F(f,2))>=0)
+    {
+      C.row(f) = purple;
+    }else
+    {
+      C.row(f) = gold;
+    }
+  }
+
+  // Plot the mesh with pseudocolors
+  igl::Viewer viewer;
+  viewer.set_mesh(U, F);
+  viewer.core.show_lines = false;
+  viewer.set_colors(C);
+  viewer.core.trackball_angle << 0,sqrt(2.0),0,sqrt(2.0);
+  viewer.core.trackball_angle.normalize();
+  viewer.callback_pre_draw = &pre_draw;
+  viewer.callback_key_down = &key_down;
+  //viewer.core.is_animating = true;
+  viewer.core.animation_max_fps = 30.;
+  viewer.launch();
+}

+ 11 - 0
tutorial/402_PolyharmonicDeformation/CMakeLists.txt

@@ -0,0 +1,11 @@
+cmake_minimum_required(VERSION 2.6)
+project(402_PolyharmonicDeformation)
+
+include("../CMakeLists.shared")
+
+set(SOURCES
+${PROJECT_SOURCE_DIR}/main.cpp
+)
+
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 105 - 0
tutorial/402_PolyharmonicDeformation/main.cpp

@@ -0,0 +1,105 @@
+#include <igl/colon.h>
+#include <igl/harmonic.h>
+#include <igl/readOBJ.h>
+#include <igl/viewer/Viewer.h>
+#include <algorithm>
+#include <iostream>
+
+double z_max = 1.0;
+double z_dir = -0.03;
+int k = 2;
+bool resolve = true;
+Eigen::MatrixXd V,U;
+Eigen::VectorXd Z;
+Eigen::MatrixXi F;
+Eigen::VectorXi b;
+Eigen::VectorXd bc;
+
+bool pre_draw(igl::Viewer & viewer)
+{
+  using namespace Eigen;
+  if(resolve)
+  {
+    igl::harmonic(V,F,b,bc,k,Z);
+    resolve = false;
+  }
+  U.col(2) = z_max*Z;
+  viewer.set_vertices(U);
+  viewer.compute_normals();
+  if(viewer.core.is_animating)
+  {
+    z_max += z_dir;
+    z_dir *= (z_max>=1.0 || z_max<=0.0?-1.0:1.0);
+  }
+  return false;
+}
+
+bool key_down(igl::Viewer &viewer, unsigned char key, int mods)
+{
+  switch(key)
+  {
+    case ' ':
+      viewer.core.is_animating = !viewer.core.is_animating;
+      break;
+    case '.':
+      k++;
+      k = (k>4?4:k);
+      resolve = true;
+      break;
+    case ',':
+      k--;
+      k = (k<1?1:k);
+      resolve = true;
+      break;
+  }
+}
+
+int main(int argc, char *argv[])
+{
+  using namespace Eigen;
+  using namespace std;
+  igl::readOBJ("../shared/bump-domain.obj",V,F);
+  U=V;
+  // Find boundary vertices outside annulus
+  typedef Matrix<bool,Dynamic,1> VectorXb;
+  VectorXb is_outer = (V.rowwise().norm().array()-1.0)>-1e-15;
+  VectorXb is_inner = (V.rowwise().norm().array()-0.15)<1e-15;
+  VectorXb in_b = is_outer.array() || is_inner.array();
+  igl::colon<int>(0,V.rows()-1,b);
+  b.conservativeResize(stable_partition( b.data(), b.data()+b.size(), 
+   [&in_b](int i)->bool{return in_b(i);})-b.data());
+  bc.resize(b.size(),1);
+  for(int bi = 0;bi<b.size();bi++)
+  {
+    bc(bi) = (is_outer(b(bi))?0.0:1.0);
+  }
+
+
+  // Pseudo-color based on selection
+  MatrixXd C(F.rows(),3);
+  RowVector3d purple(80.0/255.0,64.0/255.0,255.0/255.0);
+  RowVector3d gold(255.0/255.0,228.0/255.0,58.0/255.0);
+  for(int f = 0;f<F.rows();f++)
+  {
+    if( in_b(F(f,0)) && in_b(F(f,1)) && in_b(F(f,2)))
+    {
+      C.row(f) = purple;
+    }else
+    {
+      C.row(f) = gold;
+    }
+  }
+
+  // Plot the mesh with pseudocolors
+  igl::Viewer viewer;
+  viewer.set_mesh(U, F);
+  viewer.core.show_lines = false;
+  viewer.set_colors(C);
+  viewer.core.trackball_angle << -0.58,-0.03,-0.03,0.81;
+  viewer.core.trackball_angle.normalize();
+  viewer.callback_pre_draw = &pre_draw;
+  viewer.callback_key_down = &key_down;
+  viewer.core.is_animating = true;
+  viewer.core.animation_max_fps = 30.;
+  viewer.launch();
+}

+ 11 - 0
tutorial/403_BoundedBiharmonicWeights/CMakeLists.txt

@@ -0,0 +1,11 @@
+cmake_minimum_required(VERSION 2.6)
+project(403_BoundedBiharmonicWeights)
+
+include("../CMakeLists.shared")
+
+set(SOURCES
+${PROJECT_SOURCE_DIR}/main.cpp
+)
+
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 160 - 0
tutorial/403_BoundedBiharmonicWeights/main.cpp

@@ -0,0 +1,160 @@
+// Don't use static library for this example because of Mosek complications
+//#define IGL_NO_MOSEK
+//#ifdef IGL_NO_MOSEK
+//#undef IGL_STATIC_LIBRARY
+//#endif
+#include <igl/boundary_conditions.h>
+#include <igl/colon.h>
+#include <igl/column_to_quats.h>
+#include <igl/directed_edge_parents.h>
+#include <igl/forward_kinematics.h>
+#include <igl/jet.h>
+#include <igl/lbs_matrix.h>
+#include <igl/deform_skeleton.h>
+#include <igl/normalize_row_sums.h>
+#include <igl/readDMAT.h>
+#include <igl/readMESH.h>
+#include <igl/readTGF.h>
+#include <igl/viewer/Viewer.h>
+#include <igl/bbw/bbw.h>
+
+#include <Eigen/Geometry>
+#include <Eigen/StdVector>
+#include <vector>
+#include <algorithm>
+#include <iostream>
+
+typedef 
+  std::vector<Eigen::Quaterniond,Eigen::aligned_allocator<Eigen::Quaterniond> >
+  RotationList;
+
+const Eigen::RowVector3d sea_green(70./255.,252./255.,167./255.);
+int selected = 0;
+Eigen::MatrixXd V,W,U,C,M;
+Eigen::MatrixXi T,F,BE;
+Eigen::VectorXi P;
+RotationList pose;
+double anim_t = 1.0;
+double anim_t_dir = -0.03;
+
+bool pre_draw(igl::Viewer & viewer)
+{
+  using namespace Eigen;
+  using namespace std;
+  if(viewer.core.is_animating)
+  {
+    // Interpolate pose and identity
+    RotationList anim_pose(pose.size());
+    for(int e = 0;e<pose.size();e++)
+    {
+      anim_pose[e] = pose[e].slerp(anim_t,Quaterniond::Identity());
+    }
+    // Propogate relative rotations via FK to retrieve absolute transformations
+    RotationList vQ;
+    vector<Vector3d> vT;
+    igl::forward_kinematics(C,BE,P,anim_pose,vQ,vT);
+    const int dim = C.cols();
+    MatrixXd T(BE.rows()*(dim+1),dim);
+    for(int e = 0;e<BE.rows();e++)
+    {
+      Affine3d a = Affine3d::Identity();
+      a.translate(vT[e]);
+      a.rotate(vQ[e]);
+      T.block(e*(dim+1),0,dim+1,dim) =
+        a.matrix().transpose().block(0,0,dim+1,dim);
+    }
+    // Compute deformation via LBS as matrix multiplication
+    U = M*T;
+
+    // Also deform skeleton edges
+    MatrixXd CT;
+    MatrixXi BET;
+    igl::deform_skeleton(C,BE,T,CT,BET);
+    
+    viewer.set_vertices(U);
+    viewer.set_edges(CT,BET,sea_green);
+    viewer.compute_normals();
+    anim_t += anim_t_dir;
+    anim_t_dir *= (anim_t>=1.0 || anim_t<=0.0?-1.0:1.0);
+  }
+  return false;
+}
+
+void set_color(igl::Viewer &viewer)
+{
+  Eigen::MatrixXd C;
+  igl::jet(W.col(selected).eval(),true,C);
+  viewer.set_colors(C);
+}
+
+bool key_down(igl::Viewer &viewer, unsigned char key, int mods)
+{
+  switch(key)
+  {
+    case ' ':
+      viewer.core.is_animating = !viewer.core.is_animating;
+      break;
+    case '.':
+      selected++;
+      selected = std::min(std::max(selected,0),(int)W.cols()-1);
+      set_color(viewer);
+      break;
+    case ',':
+      selected--;
+      selected = std::min(std::max(selected,0),(int)W.cols()-1);
+      set_color(viewer);
+      break;
+  }
+}
+
+int main(int argc, char *argv[])
+{
+  using namespace Eigen;
+  using namespace std;
+  igl::readMESH("../shared/hand.mesh",V,T,F);
+  U=V;
+  igl::readTGF("../shared/hand.tgf",C,BE);
+  // retrieve parents for forward kinematics
+  igl::directed_edge_parents(BE,P);
+
+  // Read pose as matrix of quaternions per row
+  MatrixXd Q;
+  igl::readDMAT("../shared/hand-pose.dmat",Q);
+  igl::column_to_quats(Q,pose);
+  assert(pose.size() == BE.rows());
+
+  // List of boundary indices (aka fixed value indices into VV)
+  VectorXi b;
+  // List of boundary conditions of each weight function
+  MatrixXd bc;
+  igl::boundary_conditions(V,T,C,VectorXi(),BE,MatrixXi(),b,bc);
+
+  // compute BBW weights matrix
+  igl::BBWData bbw_data;
+  // only a few iterations for sake of demo
+  bbw_data.active_set_params.max_iter = 8;
+  bbw_data.verbosity = 2;
+  if(!igl::bbw(V,T,b,bc,bbw_data,W))
+  {
+    return false;
+  }
+  // Normalize weights to sum to one
+  igl::normalize_row_sums(W,W);
+  // precompute linear blend skinning matrix
+  igl::lbs_matrix(V,W,M);
+
+  // Plot the mesh with pseudocolors
+  igl::Viewer viewer;
+  viewer.set_mesh(U, F);
+  set_color(viewer);
+  viewer.set_edges(C,BE,sea_green);
+  viewer.core.show_lines = false;
+  viewer.core.show_overlay_depth = false;
+  viewer.core.line_width = 1;
+  viewer.core.trackball_angle.normalize();
+  viewer.callback_pre_draw = &pre_draw;
+  viewer.callback_key_down = &key_down;
+  viewer.core.is_animating = false;
+  viewer.core.animation_max_fps = 30.;
+  viewer.launch();
+}

+ 2 - 2
tutorial/501_HarmonicParam/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 2 - 2
tutorial/501_HarmonicParam/main.cpp

@@ -48,10 +48,10 @@ int main(int argc, char *argv[])
   viewer.callback_key_down = &key_down;
 
   // Disable wireframe
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
 
   // Draw checkerboard texture
-  viewer.options.show_texture = true;
+  viewer.core.show_texture = true;
 
   // Launch the viewer
   viewer.launch();

+ 2 - 2
tutorial/502_LSCMParam/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 2 - 2
tutorial/502_LSCMParam/main.cpp

@@ -52,10 +52,10 @@ int main(int argc, char *argv[])
   viewer.callback_key_down = &key_down;
 
   // Disable wireframe
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
 
   // Draw checkerboard texture
-  viewer.options.show_texture = true;
+  viewer.core.show_texture = true;
 
   // Launch the viewer
   viewer.launch();

+ 2 - 2
tutorial/503_ARAPParam/CMakeLists.txt

@@ -7,5 +7,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 2 - 2
tutorial/503_ARAPParam/main.cpp

@@ -74,10 +74,10 @@ int main(int argc, char *argv[])
   viewer.callback_key_down = &key_down;
 
   // Disable wireframe
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
 
   // Draw checkerboard texture
-  viewer.options.show_texture = true;
+  viewer.core.show_texture = true;
 
   // Launch the viewer
   viewer.launch();

+ 3 - 3
tutorial/504_NRosyDesign/CMakeLists.txt

@@ -1,5 +1,5 @@
 cmake_minimum_required(VERSION 2.6)
-project(504_NRoSyDesign)
+project(504_NRosyDesign)
 
 include("../CMakeLists.shared")
 
@@ -11,5 +11,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})

+ 14 - 14
tutorial/504_NRosyDesign/main.cpp

@@ -26,16 +26,16 @@ int N = 4;
 void representative_to_nrosy(const MatrixXd& V, const MatrixXi& F, const MatrixXd& R, const int N, MatrixXd& Y)
 {
   MatrixXd B1, B2, B3;
-  
+
   igl::local_basis(V,F,B1,B2,B3);
-  
+
   Y.resize(F.rows()*N,3);
   for (unsigned i=0;i<F.rows();++i)
   {
     double x = R.row(i) * B1.row(i).transpose();
     double y = R.row(i) * B2.row(i).transpose();
     double angle = atan2(y,x);
-    
+
     for (unsigned j=0; j<N;++j)
     {
       double anglej = angle + 2*M_PI*double(j)/double(N);
@@ -51,24 +51,24 @@ void representative_to_nrosy(const MatrixXd& V, const MatrixXi& F, const MatrixX
 void plot_mesh_nrosy(igl::Viewer& viewer, MatrixXd& V, MatrixXi& F, int N, MatrixXd& PD1, VectorXd& S, VectorXi& b)
 {
   // Clear the mesh
-  viewer.clear_mesh();
+  viewer.clear();
   viewer.set_mesh(V,F);
-  
+
   // Expand the representative vectors in the full vector set and plot them as lines
   double avg = igl::avg_edge_length(V, F);
   MatrixXd Y;
   representative_to_nrosy(V, F, PD1, N, Y);
-  
+
   MatrixXd B;
   igl::barycenter(V,F,B);
-  
+
   MatrixXd Be(B.rows()*N,3);
   for(unsigned i=0; i<B.rows();++i)
     for(unsigned j=0; j<N; ++j)
       Be.row(i*N+j) = B.row(i);
-  
+
   viewer.add_edges(Be,Be+Y*(avg/2),RowVector3d(0,0,1));
-  
+
   // Plot the singularities as colored dots (red for negative, blue for positive)
   for (unsigned i=0; i<S.size();++i)
   {
@@ -77,7 +77,7 @@ void plot_mesh_nrosy(igl::Viewer& viewer, MatrixXd& V, MatrixXi& F, int N, Matri
     else if (S(i) > 0.001)
       viewer.add_points(V.row(i),RowVector3d(0,1,0));
   }
-  
+
   // Highlight in red the constrained faces
   MatrixXd C = MatrixXd::Constant(F.rows(),3,1);
   for (unsigned i=0; i<b.size();++i)
@@ -93,10 +93,10 @@ bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
 
   MatrixXd R;
   VectorXd S;
-  
+
   igl::nrosy(V,F,b,bc,VectorXi(),VectorXd(),MatrixXd(),N,0.5,R,S);
   plot_mesh_nrosy(viewer,V,F,N,R,S,b);
-  
+
   return false;
 }
 
@@ -118,13 +118,13 @@ int main(int argc, char *argv[])
 
   // Interpolate the field and plot
   key_down(viewer, '4', 0);
-  
+
   // Plot the mesh
   viewer.set_mesh(V, F);
   viewer.callback_key_down = &key_down;
 
   // Disable wireframe
-  viewer.options.show_lines = false;
+  viewer.core.show_lines = false;
 
   // Launch the viewer
   viewer.launch();

+ 2 - 2
tutorial/505_MIQ/CMakeLists.txt

@@ -11,5 +11,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})

+ 41 - 8
tutorial/505_MIQ/main.cpp

@@ -38,6 +38,11 @@ Eigen::MatrixXi Seams;
 // Combed field
 Eigen::MatrixXd X1_combed, X2_combed;
 
+
+// Global parametrization (with seams)
+Eigen::MatrixXd UV_seams;
+Eigen::MatrixXi FUV_seams;
+
 // Global parametrization
 Eigen::MatrixXd UV;
 Eigen::MatrixXi FUV;
@@ -65,12 +70,12 @@ void line_texture(Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> &texture_R,
 
 bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
 {
-  if (key <'1' || key >'7')
+  if (key <'1' || key >'8')
     return false;
 
-  viewer.clear_mesh();
-  viewer.options.show_lines = false;
-  viewer.options.show_texture = false;
+  viewer.clear();
+  viewer.core.show_lines = false;
+  viewer.core.show_texture = false;
 
   if (key == '1')
   {
@@ -175,7 +180,7 @@ bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
     // Global parametrization UV
     viewer.set_mesh(UV, FUV);
     viewer.set_uv(UV);
-    viewer.options.show_lines = true;
+    viewer.core.show_lines = true;
   }
 
   if (key == '7')
@@ -183,7 +188,15 @@ bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
     // Global parametrization in 3D
     viewer.set_mesh(V, F);
     viewer.set_uv(UV,FUV);
-    viewer.options.show_texture = true;
+    viewer.core.show_texture = true;
+  }
+
+  if (key == '8')
+  {
+    // Global parametrization in 3D with seams
+    viewer.set_mesh(V, F);
+    viewer.set_uv(UV_seams,FUV_seams);
+    viewer.core.show_texture = true;
   }
 
   viewer.set_colors(Eigen::RowVector3d(1,1,1));
@@ -242,10 +255,10 @@ int main(int argc, char *argv[])
   // Find the singularities
   igl::find_cross_field_singularities(V, F, MMatch, isSingularity, singularityIndex);
 
-  // Cut the mes, duplicating all vertices on the seams
+  // Cut the mesh, duplicating all vertices on the seams
   igl::cut_mesh_from_singularities(V, F, MMatch, isSingularity, singularityIndex, Seams);
 
-  // Comb the cross-field accordingly
+  // Comb the frame-field accordingly
   igl::comb_frame_field(V, F, X1, X2, BIS1_combed, BIS2_combed, X1_combed, X2_combed);
 
   // Global parametrization
@@ -268,6 +281,26 @@ int main(int argc, char *argv[])
            5,
            true);
 
+// Global parametrization (with seams, only for demonstration)
+igl::miq(V,
+         F,
+         X1_combed,
+         X2_combed,
+         BIS1_combed,
+         BIS2_combed,
+         MMatch,
+         isSingularity,
+         singularityIndex,
+         Seams,
+         UV_seams,
+         FUV_seams,
+         gradient_size,
+         stiffness,
+         direct_round,
+         iter,
+         5,
+         false);
+
   // Plot the mesh
   igl::Viewer viewer;
 

+ 2 - 2
tutorial/506_FrameField/CMakeLists.txt

@@ -11,5 +11,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})

+ 10 - 10
tutorial/506_FrameField/main.cpp

@@ -59,7 +59,7 @@ void line_texture(Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic> &texture_R,
   for (unsigned i=size2-lineWidth; i<=size2+lineWidth; ++i)
     for (unsigned j=0; j<size; ++j)
       texture_R(i,j) = 0;
-  
+
   texture_G = texture_R;
   texture_B = texture_R;
 }
@@ -72,9 +72,9 @@ bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
   if (key <'1' || key >'6')
     return false;
 
-  viewer.clear_mesh();
-  viewer.options.show_lines = false;
-  viewer.options.show_texture = false;
+  viewer.clear();
+  viewer.core.show_lines = false;
+  viewer.core.show_texture = false;
 
   if (key == '1')
   {
@@ -149,7 +149,7 @@ bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
     viewer.set_mesh(V_deformed, F);
     viewer.set_uv(V_uv,F_uv);
     viewer.set_colors(RowVector3d(1,1,1));
-    viewer.options.show_texture = true;
+    viewer.core.show_texture = true;
   }
 
   if (key == '6')
@@ -158,7 +158,7 @@ bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
     viewer.set_mesh(V, F);
     viewer.set_uv(V_uv,F_uv);
     viewer.set_colors(RowVector3d(1,1,1));
-    viewer.options.show_texture = true;
+    viewer.core.show_texture = true;
   }
 
   // Replace the standard texture with an integer shift invariant texture
@@ -189,7 +189,7 @@ int main(int argc, char *argv[])
   b   = temp.block(0,0,temp.rows(),1).cast<int>();
   bc1 = temp.block(0,1,temp.rows(),3);
   bc2 = temp.block(0,4,temp.rows(),3);
-  
+
   // Interpolate the frame field
   igl::frame_field(V, F, b, bc1, bc2, FF1, FF2);
 
@@ -201,12 +201,12 @@ int main(int argc, char *argv[])
 
   // Find the closest crossfield to the deformed frame field
   igl::frame_to_cross_field(V,F,FF1_deformed,FF2_deformed,X1_deformed);
-  
+
   // Find a smooth crossfield that interpolates the deformed constraints
   MatrixXd bc_x(b.size(),3);
   for (unsigned i=0; i<b.size();++i)
     bc_x.row(i) = X1_deformed.row(b(i));
-  
+
   VectorXd S;
   igl::nrosy(
              V,
@@ -236,7 +236,7 @@ int main(int argc, char *argv[])
            60.0,
            5.0,
            false,
-           0);
+           2);
 
   igl::Viewer viewer;
   // Plot the original mesh with a texture parametrization

+ 11 - 0
tutorial/507_PolyVectorField/CMakeLists.txt

@@ -0,0 +1,11 @@
+cmake_minimum_required(VERSION 2.6)
+project(507_PolyVectorField)
+
+include("../CMakeLists.shared")
+
+set(SOURCES
+${PROJECT_SOURCE_DIR}/main.cpp
+)
+
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})

+ 111 - 0
tutorial/507_PolyVectorField/main.cpp

@@ -0,0 +1,111 @@
+#include <igl/readOBJ.h>
+#include <igl/readDMAT.h>
+#include <igl/viewer/Viewer.h>
+#include <igl/barycenter.h>
+#include <igl/avg_edge_length.h>
+#include <vector>
+#include <igl/n_polyvector.h>
+#include <stdlib.h>
+
+// Input mesh
+Eigen::MatrixXd V;
+Eigen::MatrixXi F;
+
+// Face barycenters
+Eigen::MatrixXd B;
+
+// Scale for visualizing the fields
+double global_scale;
+
+// Input constraints
+Eigen::VectorXi isConstrained;
+std::vector<Eigen::MatrixXd> constraints;
+
+bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
+{
+  using namespace std;
+  using namespace Eigen;
+
+  if (key <'1' || key >'4')
+    return false;
+
+  viewer.clear();
+  viewer.set_mesh(V, F);
+  viewer.core.show_lines = false;
+  viewer.core.show_texture = false;
+
+  int num = key  - '0';
+
+  // Interpolate
+  cerr<<"Interpolating N-PolyVector field for N = "<<num<<"... ";
+
+  // Interpolated PolyVector field
+  Eigen::MatrixXd pvf;
+  igl::n_polyvector(V, F, isConstrained, constraints[num-1], pvf);
+
+  // Highlight in red the constrained faces
+  MatrixXd C = MatrixXd::Constant(F.rows(),3,1);
+  for (unsigned i=0; i<F.rows();++i)
+    if (isConstrained[i])
+    C.row(i) << 1, 0, 0;
+  viewer.set_colors(C);
+
+  for (int n=0; n<num; ++n)
+  {
+    // Frame field constraints
+    MatrixXd F_t = MatrixXd::Zero(F.rows(),3);
+    for (unsigned i=0; i<F.rows();++i)
+      if (isConstrained[i])
+        F_t.row(i) = constraints[num-1].block(i,n*3,1,3);
+    viewer.add_edges (B, B + global_scale*F_t , Eigen::RowVector3d(0,0,1));
+
+    const Eigen::MatrixXd &pvf_t = pvf.block(0,n*3,F.rows(),3);
+    for (unsigned i=0; i<F.rows();++i)
+      if (isConstrained[i])
+        F_t.row(i) *= 0;
+
+    viewer.add_edges (B, B + global_scale*pvf_t , Eigen::RowVector3d(0,0,1));
+  }
+
+
+  return false;
+}
+
+int main(int argc, char *argv[])
+{
+  using namespace Eigen;
+  using namespace std;
+  // Load a mesh in OBJ format
+  igl::readOBJ("../shared/snail.obj", V, F);
+
+  // Compute face barycenters
+  igl::barycenter(V, F, B);
+
+  // Compute scale for visualizing fields
+  global_scale =  .2*igl::avg_edge_length(V, F);
+
+  // Allocate constraints and polyvector field
+  constraints.resize(4);
+
+  // Load constraints
+  MatrixXd temp;
+  for (int n =0; n<=3; ++n)
+  {
+    char cfile[1024]; sprintf(cfile, "../shared/snail%d.dmat",n+1);
+
+    igl::readDMAT(cfile,temp);
+    if (n == 0)
+      isConstrained = temp.block(0,0,temp.rows(),1).cast<int>();
+
+    constraints[n] = temp.block(0,1,temp.rows(),temp.cols()-1);
+  }
+
+
+  igl::Viewer viewer;
+
+  key_down(viewer,'5',0);
+
+  // Launch the viewer
+  viewer.callback_key_down = &key_down;
+  viewer.launch();
+}

+ 11 - 0
tutorial/508_ConjugateField/CMakeLists.txt

@@ -0,0 +1,11 @@
+cmake_minimum_required(VERSION 2.6)
+project(508_ConjugateField)
+
+include("../CMakeLists.shared")
+
+set(SOURCES
+${PROJECT_SOURCE_DIR}/main.cpp
+)
+
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})

+ 157 - 0
tutorial/508_ConjugateField/main.cpp

@@ -0,0 +1,157 @@
+#undef IGL_STATIC_LIBRARY
+#include <igl/readOBJ.h>
+#include <igl/readDMAT.h>
+#include <igl/viewer/Viewer.h>
+#include <igl/barycenter.h>
+#include <igl/avg_edge_length.h>
+#include <vector>
+#include <igl/n_polyvector.h>
+#include <igl/conjugate_frame_fields.h>
+#include <stdlib.h>
+#include <igl/readOFF.h>
+#include <igl/jet.h>
+#include <igl/quad_planarity.h>
+#include <igl/planarize_quad_mesh.h>
+
+// Input mesh
+Eigen::MatrixXd V;
+Eigen::MatrixXi F;
+
+// Face barycenters
+Eigen::MatrixXd B;
+
+
+// Quad mesh generated from smooth field
+Eigen::MatrixXd VQS;
+Eigen::MatrixXi FQS;
+Eigen::MatrixXi FQStri;
+Eigen::MatrixXd PQS0, PQS1, PQS2, PQS3;
+
+// Quad mesh generated from conjugate field
+Eigen::MatrixXd VQC;
+Eigen::MatrixXi FQC;
+Eigen::MatrixXi FQCtri;
+Eigen::MatrixXd VQCplan;
+Eigen::MatrixXd PQC0, PQC1, PQC2, PQC3;
+Eigen::MatrixXd PQCp0, PQCp1, PQCp2, PQCp3;
+
+// Scale for visualizing the fields
+double global_scale;
+
+// Input constraints
+Eigen::VectorXi isConstrained;
+Eigen::MatrixXd constraints;
+
+Eigen::MatrixXd smooth_pvf;
+Eigen::MatrixXd conjugate_pvf;
+
+igl::ConjugateFFSolverData<Eigen::MatrixXd, Eigen::MatrixXi> *csdata;
+
+bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
+{
+  using namespace std;
+  using namespace Eigen;
+
+  if (key <'1' || key >'3')
+    return false;
+
+  viewer.clear();
+  viewer.core.show_lines = false;
+  viewer.core.show_texture = false;
+
+  viewer.set_mesh(V, F);
+
+  // Highlight in red the constrained faces
+  MatrixXd C = MatrixXd::Constant(F.rows(),3,1);
+  for (unsigned i=0; i<F.rows();++i)
+    if (isConstrained[i])
+      C.row(i) << 1, 0, 0;
+  viewer.set_colors(C);
+
+  if (key == '1')
+  {
+    // Frame field constraints
+    MatrixXd F1_t = MatrixXd::Zero(F.rows(),3);
+    MatrixXd F2_t = MatrixXd::Zero(F.rows(),3);
+
+    for (unsigned i=0; i<F.rows();++i)
+      if (isConstrained[i])
+      {
+        F1_t.row(i) = constraints.block(i,0,1,3);
+        F2_t.row(i) = constraints.block(i,3,1,3);
+      }
+
+    viewer.add_edges (B - global_scale*F1_t, B + global_scale*F1_t , Eigen::RowVector3d(0,0,1));
+    viewer.add_edges (B - global_scale*F2_t, B + global_scale*F2_t , Eigen::RowVector3d(0,0,1));
+  }
+
+  if (key == '2')
+  {
+    // Interpolated result
+    viewer.add_edges (B - global_scale*smooth_pvf.block(0,0,F.rows(),3),
+                      B + global_scale*smooth_pvf.block(0,0,F.rows(),3),
+                      Eigen::RowVector3d(0,0,1));
+    viewer.add_edges (B - global_scale*smooth_pvf.block(0,3,F.rows(),3),
+                      B + global_scale*smooth_pvf.block(0,3,F.rows(),3),
+                      Eigen::RowVector3d(0,0,1));
+  }
+
+  if (key == '3')
+  {
+    // Conjugate field
+    viewer.add_edges (B - global_scale*conjugate_pvf.block(0,0,F.rows(),3),
+                      B + global_scale*conjugate_pvf.block(0,0,F.rows(),3),
+                      Eigen::RowVector3d(0,0,1));
+    viewer.add_edges (B - global_scale*conjugate_pvf.block(0,3,F.rows(),3),
+                      B + global_scale*conjugate_pvf.block(0,3,F.rows(),3),
+                      Eigen::RowVector3d(0,0,1));
+  }
+
+  return false;
+}
+
+int main(int argc, char *argv[])
+{
+  using namespace Eigen;
+  using namespace std;
+
+  // Load a mesh in OBJ format
+  igl::readOBJ("../shared/inspired_mesh.obj", V, F);
+
+  // Compute face barycenters
+  igl::barycenter(V, F, B);
+
+  // Compute scale for visualizing fields
+  global_scale =  .4*igl::avg_edge_length(V, F);
+
+  // Load constraints
+  MatrixXd temp;
+  igl::readDMAT("../shared/inspired_mesh.dmat",temp);
+  isConstrained = temp.block(0,0,temp.rows(),1).cast<int>();
+  constraints = temp.block(0,1,temp.rows(),temp.cols()-1);
+
+  // Interpolate to get a smooth field
+  igl::n_polyvector(V, F, isConstrained, constraints, smooth_pvf);
+
+  // Initialize conjugate field with smooth field
+  csdata = new igl::ConjugateFFSolverData<Eigen::MatrixXd,Eigen::MatrixXi>(V,F);
+  conjugate_pvf = smooth_pvf;
+
+  // Optimize the field
+  int conjIter = 20;
+  int totalConjIter = 0;
+  double lambdaOrtho = .1;
+  double lambdaInit = 100;
+  double lambdaMultFactor = 1.01;
+  bool doHardConstraints = true;
+  double lambdaOut;
+  igl::conjugate_frame_fields(*csdata, isConstrained, conjugate_pvf, conjugate_pvf, conjIter, lambdaOrtho, lambdaInit, lambdaMultFactor, doHardConstraints,
+                              &lambdaOut);
+
+  // Launch the viewer
+  igl::Viewer viewer;
+  key_down(viewer,'3',0);
+  viewer.core.invert_normals = true;
+  viewer.callback_key_down = &key_down;
+  viewer.launch();
+}

+ 11 - 0
tutorial/509_Planarization/CMakeLists.txt

@@ -0,0 +1,11 @@
+cmake_minimum_required(VERSION 2.6)
+project(509_Planarization)
+
+include("../CMakeLists.shared")
+
+set(SOURCES
+${PROJECT_SOURCE_DIR}/main.cpp
+)
+
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES} ${LIBCOMISO_LIBRARY})

+ 113 - 0
tutorial/509_Planarization/main.cpp

@@ -0,0 +1,113 @@
+#include <igl/readOBJ.h>
+#include <igl/readDMAT.h>
+#include <igl/viewer/Viewer.h>
+#include <igl/barycenter.h>
+#include <igl/avg_edge_length.h>
+#include <vector>
+#include <stdlib.h>
+#include <igl/jet.h>
+#include <igl/quad_planarity.h>
+#include <igl/planarize_quad_mesh.h>
+#include <igl/slice.h>
+
+// Quad mesh generated from conjugate field
+Eigen::MatrixXd VQC;
+Eigen::MatrixXi FQC;
+Eigen::MatrixXi FQCtri;
+Eigen::MatrixXd PQC0, PQC1, PQC2, PQC3;
+
+// Planarized quad mesh
+Eigen::MatrixXd VQCplan;
+Eigen::MatrixXi FQCtriplan;
+Eigen::MatrixXd PQC0plan, PQC1plan, PQC2plan, PQC3plan;
+
+
+// Scale for visualizing the fields
+double global_scale;
+
+
+bool key_down(igl::Viewer& viewer, unsigned char key, int modifier)
+{
+  using namespace std;
+  using namespace Eigen;
+
+  // Plot the original quad mesh
+  if (key == '1')
+  {
+    // Draw the triangulated quad mesh
+    viewer.set_mesh(VQC, FQCtri);
+
+    // Assign a color to each quad that corresponds to its planarity
+    VectorXd planarity;
+    igl::quad_planarity( VQC, FQC, planarity);
+    MatrixXd Ct;
+    igl::jet(planarity, 0, 0.02, Ct);
+    MatrixXd C(FQCtri.rows(),3);
+    C << Ct, Ct;
+    viewer.set_colors(C);
+
+    // Plot a line for each edge of the quad mesh
+    viewer.add_edges (PQC0, PQC1, Eigen::RowVector3d(0,0,0));
+    viewer.add_edges (PQC1, PQC2, Eigen::RowVector3d(0,0,0));
+    viewer.add_edges (PQC2, PQC3, Eigen::RowVector3d(0,0,0));
+    viewer.add_edges (PQC3, PQC0, Eigen::RowVector3d(0,0,0));
+  }
+
+  // Plot the planarized quad mesh
+  if (key == '2')
+  {
+    // Draw the triangulated quad mesh
+    viewer.set_mesh(VQCplan, FQCtri);
+
+    // Assign a color to each quad that corresponds to its planarity
+    VectorXd planarity;
+    igl::quad_planarity( VQCplan, FQC, planarity);
+    MatrixXd Ct;
+    igl::jet(planarity, 0, 0.02, Ct);
+    MatrixXd C(FQCtri.rows(),3);
+    C << Ct, Ct;
+    viewer.set_colors(C);
+
+    // Plot a line for each edge of the quad mesh
+    viewer.add_edges (PQC0plan, PQC1plan, Eigen::RowVector3d(0,0,0));
+    viewer.add_edges (PQC1plan, PQC2plan, Eigen::RowVector3d(0,0,0));
+    viewer.add_edges (PQC2plan, PQC3plan, Eigen::RowVector3d(0,0,0));
+    viewer.add_edges (PQC3plan, PQC0plan, Eigen::RowVector3d(0,0,0));
+  }
+
+  return false;
+}
+
+int main(int argc, char *argv[])
+{
+  using namespace Eigen;
+  using namespace std;
+
+  // Load a quad mesh generated by a conjugate field
+  igl::readOFF("../shared/inspired_mesh_quads_Conjugate.off", VQC, FQC);
+
+  // Convert it in a triangle mesh
+  FQCtri.resize(2*FQC.rows(), 3);
+  FQCtri <<  FQC.col(0),FQC.col(1),FQC.col(2),
+             FQC.col(2),FQC.col(3),FQC.col(0);
+  igl::slice( VQC, FQC.col(0), 1, PQC0);
+  igl::slice( VQC, FQC.col(1), 1, PQC1);
+  igl::slice( VQC, FQC.col(2), 1, PQC2);
+  igl::slice( VQC, FQC.col(3), 1, PQC3);
+
+  // Planarize it
+  igl::planarize_quad_mesh(VQC, FQC, 100, 0.005, VQCplan);
+
+  // Convert the planarized mesh to triangles
+  igl::slice( VQCplan, FQC.col(0), 1, PQC0plan);
+  igl::slice( VQCplan, FQC.col(1), 1, PQC1plan);
+  igl::slice( VQCplan, FQC.col(2), 1, PQC2plan);
+  igl::slice( VQCplan, FQC.col(3), 1, PQC3plan);
+
+  // Launch the viewer
+  igl::Viewer viewer;
+  key_down(viewer,'2',0);
+  viewer.core.invert_normals = true;
+  viewer.callback_key_down = &key_down;
+  viewer.launch();
+}

+ 2 - 2
tutorial/601_Serialization/CMakeLists.txt

@@ -11,5 +11,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES} ${TINYXML2_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES} ${TINYXML2_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 1 - 1
tutorial/601_Serialization/main.cpp

@@ -32,7 +32,7 @@ int main(int argc, char *argv[])
   State state;
 
   // Load a mesh in OFF format
-  igl::readOFF("../shared/cube.off", state.V, state.F);
+  igl::readOFF("../shared/2triangles.off", state.V, state.F);
 
   // Save some integers in a vector
   state.ids.push_back(6);

+ 2 - 2
tutorial/602_Matlab/CMakeLists.txt

@@ -14,5 +14,5 @@ if(APPLE)
   set(CMAKE_EXE_LINKER_FLAGS "-rpath ${MATLAB_INCLUDE_DIR}/../../bin/maci64"})
 endif (APPLE) #APPLE
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES} ${MATLAB_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES} ${MATLAB_LIBRARIES})

+ 1 - 1
tutorial/602_Matlab/main.cpp

@@ -57,7 +57,7 @@ int main(int argc, char *argv[])
   // Send Laplacian matrix to matlab
   igl::mlsetmatrix(&engine,"L",L);
 
-  // Plot the laplacian matri using matlab spy
+  // Plot the laplacian matrix using matlab spy
   igl::mleval(&engine,"spy(L)");
 
   // Extract the first 10 eigenvectors

+ 1 - 1
tutorial/602_Matlab/run.sh

@@ -7,4 +7,4 @@
 
 export DYLD_LIBRARY_PATH=/Applications/MATLAB_R2012b.app/bin/maci64/
 
-./build/602_Matlab
+./build/602_Matlab_bin

+ 2 - 2
tutorial/604_Triangle/CMakeLists.txt

@@ -10,5 +10,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES} ${TRIANGLE_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES} ${TRIANGLE_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

+ 2 - 2
tutorial/605_Tetgen/CMakeLists.txt

@@ -10,5 +10,5 @@ set(SOURCES
 ${PROJECT_SOURCE_DIR}/main.cpp
 )
 
-add_executable(${PROJECT_NAME} ${SOURCES} ${SHARED_SOURCES} ${TETGEN_SOURCES})
-target_link_libraries(${PROJECT_NAME} ${SHARED_LIBRARIES})
+add_executable(${PROJECT_NAME}_bin ${SOURCES} ${SHARED_SOURCES} ${TETGEN_SOURCES})
+target_link_libraries(${PROJECT_NAME}_bin ${SHARED_LIBRARIES})

이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.