rotation_matrix_from_directions.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Daniele Panozzo <[email protected]>, Olga Diamanti <[email protected]>
  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. #include <iostream>
  11. template <typename Scalar>
  12. IGL_INLINE Eigen::Matrix<Scalar, 3, 3> igl::rotation_matrix_from_directions(
  13. const Eigen::Matrix<Scalar, 3, 1> v0,
  14. const Eigen::Matrix<Scalar, 3, 1> v1)
  15. {
  16. Eigen::Matrix<Scalar, 3, 3> rotM;
  17. const double epsilon=1e-8;
  18. Scalar dot=v0.normalized().dot(v1.normalized());
  19. ///control if there is no rotation
  20. if ((v0-v1).norm()<epsilon)
  21. {
  22. rotM = Eigen::Matrix<Scalar, 3, 3>::Identity();
  23. return rotM;
  24. }
  25. if ((v0+v1).norm()<epsilon)
  26. {
  27. rotM = -Eigen::Matrix<Scalar, 3, 3>::Identity();
  28. rotM(0,0) = 1.;
  29. #ifdef IGL_ROTATION_MATRIX_FROM_DIRECTIONS_DEBUG
  30. std::cerr<<"igl::rotation_matrix_from_directions: rotating around x axis by 180o"<<std::endl;
  31. #endif
  32. return rotM;
  33. }
  34. ///find the axis of rotation
  35. Eigen::Matrix<Scalar, 3, 1> axis;
  36. axis=v0.cross(v1);
  37. axis.normalize();
  38. ///construct rotation matrix
  39. Scalar u=axis(0);
  40. Scalar v=axis(1);
  41. Scalar w=axis(2);
  42. Scalar phi=acos(dot);
  43. Scalar rcos = cos(phi);
  44. Scalar rsin = sin(phi);
  45. rotM(0,0) = rcos + u*u*(1-rcos);
  46. rotM(1,0) = w * rsin + v*u*(1-rcos);
  47. rotM(2,0) = -v * rsin + w*u*(1-rcos);
  48. rotM(0,1) = -w * rsin + u*v*(1-rcos);
  49. rotM(1,1) = rcos + v*v*(1-rcos);
  50. rotM(2,1) = u * rsin + w*v*(1-rcos);
  51. rotM(0,2) = v * rsin + u*w*(1-rcos);
  52. rotM(1,2) = -u * rsin + v*w*(1-rcos);
  53. rotM(2,2) = rcos + w*w*(1-rcos);
  54. return rotM;
  55. }
  56. #ifdef IGL_STATIC_LIBRARY
  57. // Explicit template instantiation
  58. 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>);
  59. #endif