rotation_matrix_from_directions.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. template <typename Scalar>
  10. IGL_INLINE Eigen::Matrix<Scalar, 3, 3> igl::rotation_matrix_from_directions(Eigen::Matrix<Scalar, 3, 1> v0,
  11. Eigen::Matrix<Scalar, 3, 1> v1,
  12. bool normalized)
  13. {
  14. Eigen::Matrix<Scalar, 3, 3> rotM;
  15. const double epsilon=0.00001;
  16. if (!normalized)
  17. {
  18. v0.normalize();
  19. v1.normalize();
  20. }
  21. Scalar dot=v0.dot(v1);
  22. ///control if there is no rotation
  23. if (dot>((double)1-epsilon))
  24. {
  25. rotM = Eigen::Matrix<Scalar, 3, 3>::Identity();
  26. return rotM;
  27. }
  28. ///find the axis of rotation
  29. Eigen::Matrix<Scalar, 3, 1> axis;
  30. axis=v0.cross(v1);
  31. axis.normalize();
  32. ///construct rotation matrix
  33. Scalar u=axis(0);
  34. Scalar v=axis(1);
  35. Scalar w=axis(2);
  36. Scalar phi=acos(dot);
  37. Scalar rcos = cos(phi);
  38. Scalar rsin = sin(phi);
  39. rotM(0,0) = rcos + u*u*(1-rcos);
  40. rotM(1,0) = w * rsin + v*u*(1-rcos);
  41. rotM(2,0) = -v * rsin + w*u*(1-rcos);
  42. rotM(0,1) = -w * rsin + u*v*(1-rcos);
  43. rotM(1,1) = rcos + v*v*(1-rcos);
  44. rotM(2,1) = u * rsin + w*v*(1-rcos);
  45. rotM(0,2) = v * rsin + u*w*(1-rcos);
  46. rotM(1,2) = -u * rsin + v*w*(1-rcos);
  47. rotM(2,2) = rcos + w*w*(1-rcos);
  48. return rotM;
  49. }
  50. #ifndef IGL_HEADER_ONLY
  51. // Explicit template specialization
  52. #endif