rotation_matrix_from_directions.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>, Olga Diamanti <olga.diam@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 "rotation_matrix_from_directions.h"
  9. #include <Eigen/Geometry>
  10. template <typename Scalar>
  11. IGL_INLINE Eigen::Matrix<Scalar, 3, 3> igl::rotation_matrix_from_directions(const Eigen::Matrix<Scalar, 3, 1> v0,
  12. const Eigen::Matrix<Scalar, 3, 1> v1,
  13. bool normalized)
  14. {
  15. Eigen::Matrix<Scalar, 3, 3> rotM;
  16. const double epsilon=0.00001;
  17. // if (!normalized)
  18. // {
  19. // v0.normalize();
  20. // v1.normalize();
  21. // }
  22. Scalar dot=v0.normalized().dot(v1.normalized());
  23. ///control if there is no rotation
  24. if (dot>((double)1-epsilon))
  25. {
  26. rotM = Eigen::Matrix<Scalar, 3, 3>::Identity();
  27. return rotM;
  28. }
  29. ///find the axis of rotation
  30. Eigen::Matrix<Scalar, 3, 1> axis;
  31. axis=v0.cross(v1);
  32. axis.normalize();
  33. ///construct rotation matrix
  34. Scalar u=axis(0);
  35. Scalar v=axis(1);
  36. Scalar w=axis(2);
  37. Scalar phi=acos(dot);
  38. Scalar rcos = cos(phi);
  39. Scalar rsin = sin(phi);
  40. rotM(0,0) = rcos + u*u*(1-rcos);
  41. rotM(1,0) = w * rsin + v*u*(1-rcos);
  42. rotM(2,0) = -v * rsin + w*u*(1-rcos);
  43. rotM(0,1) = -w * rsin + u*v*(1-rcos);
  44. rotM(1,1) = rcos + v*v*(1-rcos);
  45. rotM(2,1) = u * rsin + w*v*(1-rcos);
  46. rotM(0,2) = v * rsin + u*w*(1-rcos);
  47. rotM(1,2) = -u * rsin + v*w*(1-rcos);
  48. rotM(2,2) = rcos + w*w*(1-rcos);
  49. return rotM;
  50. }
  51. #ifdef IGL_STATIC_LIBRARY
  52. // Explicit template specialization
  53. template Eigen::Matrix<double, 3, 3, 0, 3, 3> igl::rotation_matrix_from_directions<double>(const Eigen::Matrix<double, 3, 1, 0, 3, 1>, const Eigen::Matrix<double, 3, 1, 0, 3, 1>, const bool);
  54. #endif