Galaxis Codebase  1.0.0
Team Galaxis software stack for the Carolo Cup 2023 - ROS2 based software
math.hpp
Go to the documentation of this file.
1 #ifndef GALAXIS_MATH_HPP
2 #define GALAXIS_MATH_HPP
3 #include <cmath>
4 
5 namespace galaxis {
6 
7  namespace math {
8  // Copied from: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
9 
10  struct Quaternion {
11  double w = 0;
12  double x = 0;
13  double y = 0;
14  double z = 0;
15  };
16 
17  struct EulerAngles {
18  double roll = 0;
19  double pitch = 0;
20  double yaw = 0;
21  };
22 
23  Quaternion euler_angles_to_quaternion(EulerAngles const& e) { // yaw (Z), pitch (Y), roll (X)
24 
25  // Abbreviations for the various angular functions
26  double cy = cos(e.yaw * 0.5);
27  double sy = sin(e.yaw * 0.5);
28  double cp = cos(e.pitch * 0.5);
29  double sp = sin(e.pitch * 0.5);
30  double cr = cos(e.roll * 0.5);
31  double sr = sin(e.roll * 0.5);
32 
33  Quaternion q;
34  q.w = cr * cp * cy + sr * sp * sy;
35  q.x = sr * cp * cy - cr * sp * sy;
36  q.y = cr * sp * cy + sr * cp * sy;
37  q.z = cr * cp * sy - sr * sp * cy;
38 
39  return q;
40  }
41 
43  EulerAngles angles;
44 
45  // roll (x-axis rotation)
46  double sinr_cosp = 2 * (q.w * q.x + q.y * q.z);
47  double cosr_cosp = 1 - 2 * (q.x * q.x + q.y * q.y);
48  angles.roll = std::atan2(sinr_cosp, cosr_cosp);
49 
50  // pitch (y-axis rotation)
51  double sinp = 2 * (q.w * q.y - q.z * q.x);
52  if (std::abs(sinp) >= 1)
53  angles.pitch = std::copysign(M_PI / 2, sinp); // use 90 degrees if out of range
54  else
55  angles.pitch = std::asin(sinp);
56 
57  // yaw (z-axis rotation)
58  double siny_cosp = 2 * (q.w * q.z + q.x * q.y);
59  double cosy_cosp = 1 - 2 * (q.y * q.y + q.z * q.z);
60  angles.yaw = std::atan2(siny_cosp, cosy_cosp);
61 
62  return angles;
63  }
64 
65  } // namespace math
66 
67 } // namespace galaxis
68 
69 #endif
galaxis::math::Quaternion::w
double w
Definition: math.hpp:11
galaxis::math::quaternion_to_euler
EulerAngles quaternion_to_euler(Quaternion const &q)
Definition: math.hpp:42
galaxis::math::euler_angles_to_quaternion
Quaternion euler_angles_to_quaternion(EulerAngles const &e)
Definition: math.hpp:23
galaxis::math::EulerAngles::pitch
double pitch
Definition: math.hpp:19
galaxis::math::EulerAngles::yaw
double yaw
Definition: math.hpp:20
galaxis::math::Quaternion::x
double x
Definition: math.hpp:12
galaxis::math::Quaternion::y
double y
Definition: math.hpp:13
galaxis
Definition: MapClasses.hpp:10
galaxis::math::EulerAngles
Definition: math.hpp:17
galaxis::math::Quaternion
Definition: math.hpp:10
galaxis::math::Quaternion::z
double z
Definition: math.hpp:14
galaxis::math::EulerAngles::roll
double roll
Definition: math.hpp:18