rotation_matrix_from_directions.cpp 2.3 KB

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