grad.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "grad.h"
  9. template <typename T, typename S>
  10. IGL_INLINE void igl::grad(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &V,
  11. const Eigen::Matrix<S, Eigen::Dynamic, Eigen::Dynamic> &F,
  12. const Eigen::Matrix<T, Eigen::Dynamic, 1>&X,
  13. Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &G )
  14. {
  15. G = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Zero(F.rows(),3);
  16. for (int i = 0; i<F.rows(); ++i)
  17. {
  18. // renaming indices of vertices of triangles for convenience
  19. int i1 = F(i,0);
  20. int i2 = F(i,1);
  21. int i3 = F(i,2);
  22. // #F x 3 matrices of triangle edge vectors, named after opposite vertices
  23. Eigen::Matrix<T, 1, 3> v32 = V.row(i3) - V.row(i2);
  24. Eigen::Matrix<T, 1, 3> v13 = V.row(i1) - V.row(i3);
  25. Eigen::Matrix<T, 1, 3> v21 = V.row(i2) - V.row(i1);
  26. // area of parallelogram is twice area of triangle
  27. // area of parallelogram is || v1 x v2 ||
  28. Eigen::Matrix<T, 1, 3> n = v32.cross(v13);
  29. // This does correct l2 norm of rows, so that it contains #F list of twice
  30. // triangle areas
  31. double dblA = std::sqrt(n.dot(n));
  32. // now normalize normals to get unit normals
  33. Eigen::Matrix<T, 1, 3> u = n / dblA;
  34. // rotate each vector 90 degrees around normal
  35. double norm21 = std::sqrt(v21.dot(v21));
  36. double norm13 = std::sqrt(v13.dot(v13));
  37. Eigen::Matrix<T, 1, 3> eperp21 = u.cross(v21);
  38. eperp21 = eperp21 / std::sqrt(eperp21.dot(eperp21));
  39. eperp21 *= norm21;
  40. Eigen::Matrix<T, 1, 3> eperp13 = u.cross(v13);
  41. eperp13 = eperp13 / std::sqrt(eperp13.dot(eperp13));
  42. eperp13 *= norm13;
  43. G.row(i) = ((X[i2] -X[i1]) *eperp13 + (X[i3] - X[i1]) *eperp21) / dblA;
  44. };
  45. }
  46. #ifndef IGL_HEADER_ONLY
  47. // Explicit template specialization
  48. #endif