cgmath/euler.rs
1// Copyright 2016 The CGMath Developers. For a full listing of the authors,
2// refer to the Cargo.toml file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use num_traits::cast;
17#[cfg(feature = "rand")]
18use rand::{
19 distributions::{Distribution, Standard},
20 Rng,
21};
22
23use structure::*;
24
25use angle::Rad;
26use approx;
27#[cfg(feature = "mint")]
28use mint;
29use num::BaseFloat;
30use quaternion::Quaternion;
31
32/// A set of [Euler angles] representing a rotation in three-dimensional space.
33///
34/// This type is marked as `#[repr(C)]`.
35///
36/// The axis rotation sequence is XYZ. That is, the rotation is first around
37/// the X axis, then the Y axis, and lastly the Z axis (using intrinsic
38/// rotations). Since all three rotation axes are used, the angles are
39/// Tait–Bryan angles rather than proper Euler angles.
40///
41/// # Ranges
42///
43/// - x: [-pi, pi]
44/// - y: [-pi/2, pi/2]
45/// - z: [-pi, pi]
46///
47/// # Defining rotations using Euler angles
48///
49/// Note that while [Euler angles] are intuitive to define, they are prone to
50/// [gimbal lock] and are challenging to interpolate between. Instead we
51/// recommend that you convert them to a more robust representation, such as a
52/// quaternion or a rotation matrix. To this end, `From<Euler<A>>` conversions
53/// are provided for the following types:
54///
55/// - [`Basis3`](struct.Basis3.html)
56/// - [`Matrix3`](struct.Matrix3.html)
57/// - [`Matrix4`](struct.Matrix4.html)
58/// - [`Quaternion`](struct.Quaternion.html)
59///
60/// For example, to define a quaternion that applies the following:
61///
62/// 1. a 90° rotation around the _x_ axis
63/// 2. a 45° rotation around the _y_ axis
64/// 3. a 15° rotation around the _z_ axis
65///
66/// you can use the following code:
67///
68/// ```
69/// use cgmath::{Deg, Euler, Quaternion};
70///
71/// let rotation = Quaternion::from(Euler {
72/// x: Deg(90.0),
73/// y: Deg(45.0),
74/// z: Deg(15.0),
75/// });
76/// ```
77///
78/// [Euler angles]: https://en.wikipedia.org/wiki/Euler_angles
79/// [gimbal lock]: https://en.wikipedia.org/wiki/Gimbal_lock#Gimbal_lock_in_applied_mathematics
80/// [convert]: #defining-rotations-using-euler-angles
81#[repr(C)]
82#[derive(Copy, Clone, Debug, PartialEq, Eq)]
83#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
84pub struct Euler<A> {
85 /// The angle to apply around the _x_ axis. Also known at the _pitch_.
86 pub x: A,
87 /// The angle to apply around the _y_ axis. Also known at the _yaw_.
88 pub y: A,
89 /// The angle to apply around the _z_ axis. Also known at the _roll_.
90 pub z: A,
91}
92
93impl<A> Euler<A> {
94 /// Construct a set of euler angles.
95 ///
96 /// # Arguments
97 ///
98 /// * `x` - The angle to apply around the _x_ axis. Also known at the _pitch_.
99 /// * `y` - The angle to apply around the _y_ axis. Also known at the _yaw_.
100 /// * `z` - The angle to apply around the _z_ axis. Also known at the _roll_.
101 pub const fn new(x: A, y: A, z: A) -> Euler<A> {
102 Euler { x: x, y: y, z: z }
103 }
104}
105
106impl<S: BaseFloat> From<Quaternion<S>> for Euler<Rad<S>> {
107 fn from(src: Quaternion<S>) -> Euler<Rad<S>> {
108 let sig: S = cast(0.499).unwrap();
109 let two: S = cast(2).unwrap();
110 let one: S = cast(1).unwrap();
111
112 let (qw, qx, qy, qz) = (src.s, src.v.x, src.v.y, src.v.z);
113 let (sqw, sqx, sqy, sqz) = (qw * qw, qx * qx, qy * qy, qz * qz);
114
115 let unit = sqx + sqz + sqy + sqw;
116 let test = qx * qz + qy * qw;
117
118 // We set x to zero and z to the value, but the other way would work too.
119 if test > sig * unit {
120 // x + z = 2 * atan(x / w)
121 Euler {
122 x: Rad::zero(),
123 y: Rad::turn_div_4(),
124 z: Rad::atan2(qx, qw) * two,
125 }
126 } else if test < -sig * unit {
127 // x - z = 2 * atan(x / w)
128 Euler {
129 x: Rad::zero(),
130 y: -Rad::turn_div_4(),
131 z: -Rad::atan2(qx, qw) * two,
132 }
133 } else {
134 // Using the quat-to-matrix equation from either
135 // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm
136 // or equation 15 on page 7 of
137 // http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf
138 // to fill in the equations on page A-2 of the NASA document gives the below.
139 Euler {
140 x: Rad::atan2(two * (-qy * qz + qx * qw), one - two * (sqx + sqy)),
141 y: Rad::asin(two * (qx * qz + qy * qw)),
142 z: Rad::atan2(two * (-qx * qy + qz * qw), one - two * (sqy + sqz)),
143 }
144 }
145 }
146}
147
148impl<A: Angle> approx::AbsDiffEq for Euler<A> {
149 type Epsilon = A::Epsilon;
150
151 #[inline]
152 fn default_epsilon() -> A::Epsilon {
153 A::default_epsilon()
154 }
155
156 #[inline]
157 fn abs_diff_eq(&self, other: &Self, epsilon: A::Epsilon) -> bool {
158 A::abs_diff_eq(&self.x, &other.x, epsilon)
159 && A::abs_diff_eq(&self.y, &other.y, epsilon)
160 && A::abs_diff_eq(&self.z, &other.z, epsilon)
161 }
162}
163
164impl<A: Angle> approx::RelativeEq for Euler<A> {
165 #[inline]
166 fn default_max_relative() -> A::Epsilon {
167 A::default_max_relative()
168 }
169
170 #[inline]
171 fn relative_eq(&self, other: &Self, epsilon: A::Epsilon, max_relative: A::Epsilon) -> bool {
172 A::relative_eq(&self.x, &other.x, epsilon, max_relative)
173 && A::relative_eq(&self.y, &other.y, epsilon, max_relative)
174 && A::relative_eq(&self.z, &other.z, epsilon, max_relative)
175 }
176}
177
178impl<A: Angle> approx::UlpsEq for Euler<A> {
179 #[inline]
180 fn default_max_ulps() -> u32 {
181 A::default_max_ulps()
182 }
183
184 #[inline]
185 fn ulps_eq(&self, other: &Self, epsilon: A::Epsilon, max_ulps: u32) -> bool {
186 A::ulps_eq(&self.x, &other.x, epsilon, max_ulps)
187 && A::ulps_eq(&self.y, &other.y, epsilon, max_ulps)
188 && A::ulps_eq(&self.z, &other.z, epsilon, max_ulps)
189 }
190}
191
192#[cfg(feature = "rand")]
193impl<A> Distribution<Euler<A>> for Standard
194where
195 Standard: Distribution<A>,
196 A: Angle,
197{
198 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Euler<A> {
199 Euler {
200 x: rng.gen(),
201 y: rng.gen(),
202 z: rng.gen(),
203 }
204 }
205}
206
207#[cfg(feature = "mint")]
208type MintEuler<S> = mint::EulerAngles<S, mint::IntraXYZ>;
209
210#[cfg(feature = "mint")]
211impl<S, A: Angle + From<S>> From<MintEuler<S>> for Euler<A> {
212 fn from(mint: MintEuler<S>) -> Self {
213 Euler {
214 x: mint.a.into(),
215 y: mint.b.into(),
216 z: mint.c.into(),
217 }
218 }
219}
220
221#[cfg(feature = "mint")]
222impl<S: Clone, A: Angle + Into<S>> Into<MintEuler<S>> for Euler<A> {
223 fn into(self) -> MintEuler<S> {
224 MintEuler::from([self.x.into(), self.y.into(), self.z.into()])
225 }
226}