]> git.mxchange.org Git - simgear.git/blob - simgear/math/SGQuat.hxx
c4bf5cc789d1cfeb4b046ee24caa14e858c95183
[simgear.git] / simgear / math / SGQuat.hxx
1 #ifndef SGQuat_H
2 #define SGQuat_H
3
4 /// 3D Vector Class
5 template<typename T>
6 class SGQuat {
7 public:
8   typedef T value_type;
9
10   /// Default constructor. Does not initialize at all.
11   /// If you need them zero initialized, SGQuat::zeros()
12   SGQuat(void)
13   {
14     /// Initialize with nans in the debug build, that will guarantee to have
15     /// a fast uninitialized default constructor in the release but shows up
16     /// uninitialized values in the debug build very fast ...
17 #ifndef NDEBUG
18     for (unsigned i = 0; i < 4; ++i)
19       _data[i] = SGLimits<T>::quiet_NaN();
20 #endif
21   }
22   /// Constructor. Initialize by the given values
23   SGQuat(T _x, T _y, T _z, T _w)
24   { x() = _x; y() = _y; z() = _z; w() = _w; }
25   /// Constructor. Initialize by the content of a plain array,
26   /// make sure it has at least 4 elements
27   explicit SGQuat(const T* d)
28   { _data[0] = d[0]; _data[1] = d[1]; _data[2] = d[2]; _data[3] = d[3]; }
29
30   /// Return a unit quaternion
31   static SGQuat unit(void)
32   { return fromRealImag(1, SGVec3<T>(0)); }
33
34   /// Return a quaternion from euler angles
35   static SGQuat fromEulerRad(T z, T y, T x)
36   {
37     SGQuat q;
38     T zd2 = T(0.5)*z; T yd2 = T(0.5)*y; T xd2 = T(0.5)*x;
39     T Szd2 = sin(zd2); T Syd2 = sin(yd2); T Sxd2 = sin(xd2);
40     T Czd2 = cos(zd2); T Cyd2 = cos(yd2); T Cxd2 = cos(xd2);
41     T Cxd2Czd2 = Cxd2*Czd2; T Cxd2Szd2 = Cxd2*Szd2;
42     T Sxd2Szd2 = Sxd2*Szd2; T Sxd2Czd2 = Sxd2*Czd2;
43     q.w() = Cxd2Czd2*Cyd2 + Sxd2Szd2*Syd2;
44     q.x() = Sxd2Czd2*Cyd2 - Cxd2Szd2*Syd2;
45     q.y() = Cxd2Czd2*Syd2 + Sxd2Szd2*Cyd2;
46     q.z() = Cxd2Szd2*Cyd2 - Sxd2Czd2*Syd2;
47     return q;
48   }
49
50   /// Return a quaternion from euler angles in degrees
51   static SGQuat fromEulerDeg(T z, T y, T x)
52   {
53     return fromEulerRad(SGMisc<T>::deg2rad(z), SGMisc<T>::deg2rad(y),
54                         SGMisc<T>::deg2rad(x));
55   }
56
57   /// Return a quaternion from euler angles
58   static SGQuat fromYawPitchRoll(T y, T p, T r)
59   { return fromEulerRad(y, p, r); }
60
61   /// Return a quaternion from euler angles
62   static SGQuat fromYawPitchRollDeg(T y, T p, T r)
63   { return fromEulerDeg(y, p, r); }
64
65   /// Return a quaternion from euler angles
66   static SGQuat fromHeadAttBank(T h, T a, T b)
67   { return fromEulerRad(h, a, b); }
68
69   /// Return a quaternion from euler angles
70   static SGQuat fromHeadAttBankDeg(T h, T a, T b)
71   { return fromEulerDeg(h, a, b); }
72
73   /// Return a quaternion rotation the the horizontal local frame from given
74   /// longitude and latitude
75   static SGQuat fromLonLatRad(T lon, T lat)
76   {
77     SGQuat q;
78     T zd2 = T(0.5)*lon;
79     T yd2 = T(-0.25)*SGMisc<value_type>::pi() - T(0.5)*lat;
80     T Szd2 = sin(zd2);
81     T Syd2 = sin(yd2);
82     T Czd2 = cos(zd2);
83     T Cyd2 = cos(yd2);
84     q.w() = Czd2*Cyd2;
85     q.x() = -Szd2*Syd2;
86     q.y() = Czd2*Syd2;
87     q.z() = Szd2*Cyd2;
88     return q;
89   }
90
91   /// Return a quaternion rotation the the horizontal local frame from given
92   /// longitude and latitude
93   static SGQuat fromLonLatDeg(T lon, T lat)
94   { return fromLonLatRad(SGMisc<T>::deg2rad(lon), SGMisc<T>::deg2rad(lat)); }
95
96   /// Create a quaternion from the angle axis representation
97   static SGQuat fromAngleAxis(T angle, const SGVec3<T>& axis)
98   {
99     T angle2 = 0.5*angle;
100     return fromRealImag(cos(angle2), T(sin(angle2))*axis);
101   }
102
103   /// Create a quaternion from the angle axis representation
104   static SGQuat fromAngleAxisDeg(T angle, const SGVec3<T>& axis)
105   { return fromAngleAxis(SGMisc<T>::deg2rad(angle), axis); }
106
107   /// Create a quaternion from the angle axis representation where the angle
108   /// is stored in the axis' length
109   static SGQuat fromAngleAxis(const SGVec3<T>& axis)
110   {
111     T nAxis = norm(axis);
112     if (nAxis <= SGLimits<T>::min())
113       return SGQuat(1, 0, 0, 0);
114     T angle2 = 0.5*nAxis;
115     return fromRealImag(cos(angle2), T(sin(angle2)/nAxis)*axis);
116   }
117
118   /// Return a quaternion from real and imaginary part
119   static SGQuat fromRealImag(T r, const SGVec3<T>& i)
120   {
121     SGQuat q;
122     q.w() = r;
123     q.x() = i(0);
124     q.y() = i(1);
125     q.z() = i(2);
126     return q;
127   }
128
129   /// Return an all zero vector
130   static SGQuat zeros(void)
131   { return SGQuat(0, 0, 0, 0); }
132
133   /// write the euler angles into the references
134   void getEulerRad(T& zRad, T& yRad, T& xRad) const
135   {
136     value_type sqrQW = w()*w();
137     value_type sqrQX = x()*x();
138     value_type sqrQY = y()*y();
139     value_type sqrQZ = z()*z();
140
141     value_type num = 2*(y()*z() + w()*x());
142     value_type den = sqrQW - sqrQX - sqrQY + sqrQZ;
143     if (fabs(den) < SGLimits<value_type>::min() &&
144         fabs(num) < SGLimits<value_type>::min())
145       xRad = 0;
146     else
147       xRad = atan2(num, den);
148     
149     value_type tmp = 2*(x()*z() - w()*y());
150     if (tmp < -1)
151       yRad = 0.5*SGMisc<value_type>::pi();
152     else if (1 < tmp)
153       yRad = -0.5*SGMisc<value_type>::pi();
154     else
155       yRad = -asin(tmp);
156    
157     num = 2*(x()*y() + w()*z()); 
158     den = sqrQW + sqrQX - sqrQY - sqrQZ;
159     if (fabs(den) < SGLimits<value_type>::min() &&
160         fabs(num) < SGLimits<value_type>::min())
161       zRad = 0;
162     else {
163       value_type psi = atan2(num, den);
164       if (psi < 0)
165         psi += 2*SGMisc<value_type>::pi();
166       zRad = psi;
167     }
168   }
169
170   /// write the euler angles in degrees into the references
171   void getEulerDeg(T& zDeg, T& yDeg, T& xDeg) const
172   {
173     getEulerRad(zDeg, yDeg, xDeg);
174     zDeg = SGMisc<T>::rad2deg(zDeg);
175     yDeg = SGMisc<T>::rad2deg(yDeg);
176     xDeg = SGMisc<T>::rad2deg(xDeg);
177   }
178
179   /// write the angle axis representation into the references
180   void getAngleAxis(T& angle, SGVec3<T>& axis) const
181   {
182     T nrm = norm(*this);
183     if (nrm < SGLimits<T>::min()) {
184       angle = 0;
185       axis = SGVec3<T>(0, 0, 0);
186     } else {
187       T rNrm = 1/nrm;
188       angle = acos(SGMisc<T>::max(-1, SGMisc<T>::min(1, rNrm*w())));
189       T sAng = sin(angle);
190       if (fabs(sAng) < SGLimits<T>::min())
191         axis = SGVec3<T>(1, 0, 0);
192       else 
193         axis = (rNrm/sAng)*imag(*this);
194       angle *= 2;
195     }
196   }
197
198   /// write the angle axis representation into the references
199   void getAngleAxis(SGVec3<T>& axis) const
200   {
201     T angle;
202     getAngleAxis(angle, axis);
203     axis *= angle;
204   }
205
206   /// Access by index, the index is unchecked
207   const T& operator()(unsigned i) const
208   { return _data[i]; }
209   /// Access by index, the index is unchecked
210   T& operator()(unsigned i)
211   { return _data[i]; }
212
213   /// Access raw data by index, the index is unchecked
214   const T& operator[](unsigned i) const
215   { return _data[i]; }
216   /// Access raw data by index, the index is unchecked
217   T& operator[](unsigned i)
218   { return _data[i]; }
219
220   /// Access the x component
221   const T& x(void) const
222   { return _data[0]; }
223   /// Access the x component
224   T& x(void)
225   { return _data[0]; }
226   /// Access the y component
227   const T& y(void) const
228   { return _data[1]; }
229   /// Access the y component
230   T& y(void)
231   { return _data[1]; }
232   /// Access the z component
233   const T& z(void) const
234   { return _data[2]; }
235   /// Access the z component
236   T& z(void)
237   { return _data[2]; }
238   /// Access the w component
239   const T& w(void) const
240   { return _data[3]; }
241   /// Access the w component
242   T& w(void)
243   { return _data[3]; }
244
245   /// Get the data pointer, usefull for interfacing with plib's sg*Vec
246   const T* data(void) const
247   { return _data; }
248   /// Get the data pointer, usefull for interfacing with plib's sg*Vec
249   T* data(void)
250   { return _data; }
251
252   /// Readonly interface function to ssg's sgQuat/sgdQuat
253   const T (&sg(void) const)[4]
254   { return _data; }
255   /// Interface function to ssg's sgQuat/sgdQuat
256   T (&sg(void))[4]
257   { return _data; }
258
259   /// Inplace addition
260   SGQuat& operator+=(const SGQuat& v)
261   { _data[0]+=v(0);_data[1]+=v(1);_data[2]+=v(2);_data[3]+=v(3);return *this; }
262   /// Inplace subtraction
263   SGQuat& operator-=(const SGQuat& v)
264   { _data[0]-=v(0);_data[1]-=v(1);_data[2]-=v(2);_data[3]-=v(3);return *this; }
265   /// Inplace scalar multiplication
266   template<typename S>
267   SGQuat& operator*=(S s)
268   { _data[0] *= s; _data[1] *= s; _data[2] *= s; _data[3] *= s; return *this; }
269   /// Inplace scalar multiplication by 1/s
270   template<typename S>
271   SGQuat& operator/=(S s)
272   { return operator*=(1/T(s)); }
273   /// Inplace quaternion multiplication
274   SGQuat& operator*=(const SGQuat& v);
275
276   /// Transform a vector from the current coordinate frame to a coordinate
277   /// frame rotated with the quaternion
278   SGVec3<T> transform(const SGVec3<T>& v) const
279   {
280     value_type r = 2/dot(*this, *this);
281     SGVec3<T> qimag = imag(*this);
282     value_type qr = real(*this);
283     return (r*qr*qr - 1)*v + (r*dot(qimag, v))*qimag - (r*qr)*cross(qimag, v);
284   }
285   /// Transform a vector from the coordinate frame rotated with the quaternion
286   /// to the current coordinate frame
287   SGVec3<T> backTransform(const SGVec3<T>& v) const
288   {
289     value_type r = 2/dot(*this, *this);
290     SGVec3<T> qimag = imag(*this);
291     value_type qr = real(*this);
292     return (r*qr*qr - 1)*v + (r*dot(qimag, v))*qimag + (r*qr)*cross(qimag, v);
293   }
294
295   /// Rotate a given vector with the quaternion
296   SGVec3<T> rotate(const SGVec3<T>& v) const
297   { return backTransform(v); }
298   /// Rotate a given vector with the inverse quaternion
299   SGVec3<T> rotateBack(const SGVec3<T>& v) const
300   { return transform(v); }
301
302   /// Return the time derivative of the quaternion given the angular velocity
303   SGQuat
304   derivative(const SGVec3<T>& angVel)
305   {
306     SGQuat deriv;
307
308     deriv.w() = 0.5*(-x()*angVel(0) - y()*angVel(1) - z()*angVel(2));
309     deriv.x() = 0.5*( w()*angVel(0) - z()*angVel(1) + y()*angVel(2));
310     deriv.y() = 0.5*( z()*angVel(0) + w()*angVel(1) - x()*angVel(2));
311     deriv.z() = 0.5*(-y()*angVel(0) + x()*angVel(1) + w()*angVel(2));
312     
313     return deriv;
314   }
315
316 private:
317   /// The actual data
318   T _data[4];
319 };
320
321 /// Unary +, do nothing ...
322 template<typename T>
323 inline
324 const SGQuat<T>&
325 operator+(const SGQuat<T>& v)
326 { return v; }
327
328 /// Unary -, do nearly nothing
329 template<typename T>
330 inline
331 SGQuat<T>
332 operator-(const SGQuat<T>& v)
333 { return SGQuat<T>(-v(0), -v(1), -v(2), -v(3)); }
334
335 /// Binary +
336 template<typename T>
337 inline
338 SGQuat<T>
339 operator+(const SGQuat<T>& v1, const SGQuat<T>& v2)
340 { return SGQuat<T>(v1(0)+v2(0), v1(1)+v2(1), v1(2)+v2(2), v1(3)+v2(3)); }
341
342 /// Binary -
343 template<typename T>
344 inline
345 SGQuat<T>
346 operator-(const SGQuat<T>& v1, const SGQuat<T>& v2)
347 { return SGQuat<T>(v1(0)-v2(0), v1(1)-v2(1), v1(2)-v2(2), v1(3)-v2(3)); }
348
349 /// Scalar multiplication
350 template<typename S, typename T>
351 inline
352 SGQuat<T>
353 operator*(S s, const SGQuat<T>& v)
354 { return SGQuat<T>(s*v(0), s*v(1), s*v(2), s*v(3)); }
355
356 /// Scalar multiplication
357 template<typename S, typename T>
358 inline
359 SGQuat<T>
360 operator*(const SGQuat<T>& v, S s)
361 { return SGQuat<T>(s*v(0), s*v(1), s*v(2), s*v(3)); }
362
363 /// Quaterion multiplication
364 template<typename T>
365 inline
366 SGQuat<T>
367 operator*(const SGQuat<T>& v1, const SGQuat<T>& v2)
368 {
369   SGQuat<T> v;
370   v.x() = v1.w()*v2.x() + v1.x()*v2.w() + v1.y()*v2.z() - v1.z()*v2.y();
371   v.y() = v1.w()*v2.y() - v1.x()*v2.z() + v1.y()*v2.w() + v1.z()*v2.x();
372   v.z() = v1.w()*v2.z() + v1.x()*v2.y() - v1.y()*v2.x() + v1.z()*v2.w();
373   v.w() = v1.w()*v2.w() - v1.x()*v2.x() - v1.y()*v2.y() - v1.z()*v2.z();
374   return v;
375 }
376
377 /// Now define the inplace multiplication
378 template<typename T>
379 inline
380 SGQuat<T>&
381 SGQuat<T>::operator*=(const SGQuat& v)
382 { (*this) = (*this)*v; return *this; }
383
384 /// The conjugate of the quaternion, this is also the
385 /// inverse for normalized quaternions
386 template<typename T>
387 inline
388 SGQuat<T>
389 conj(const SGQuat<T>& v)
390 { return SGQuat<T>(-v(0), -v(1), -v(2), v(3)); }
391
392 /// The conjugate of the quaternion, this is also the
393 /// inverse for normalized quaternions
394 template<typename T>
395 inline
396 SGQuat<T>
397 inverse(const SGQuat<T>& v)
398 { return (1/dot(v, v))*SGQuat<T>(-v(0), -v(1), -v(2), v(3)); }
399
400 /// The imagniary part of the quaternion
401 template<typename T>
402 inline
403 T
404 real(const SGQuat<T>& v)
405 { return v.w(); }
406
407 /// The imagniary part of the quaternion
408 template<typename T>
409 inline
410 SGVec3<T>
411 imag(const SGQuat<T>& v)
412 { return SGVec3<T>(v.x(), v.y(), v.z()); }
413
414 /// Scalar dot product
415 template<typename T>
416 inline
417 T
418 dot(const SGQuat<T>& v1, const SGQuat<T>& v2)
419 { return v1(0)*v2(0) + v1(1)*v2(1) + v1(2)*v2(2) + v1(3)*v2(3); }
420
421 /// The euclidean norm of the vector, that is what most people call length
422 template<typename T>
423 inline
424 T
425 norm(const SGQuat<T>& v)
426 { return sqrt(dot(v, v)); }
427
428 /// The euclidean norm of the vector, that is what most people call length
429 template<typename T>
430 inline
431 T
432 length(const SGQuat<T>& v)
433 { return sqrt(dot(v, v)); }
434
435 /// The 1-norm of the vector, this one is the fastest length function we
436 /// can implement on modern cpu's
437 template<typename T>
438 inline
439 T
440 norm1(const SGQuat<T>& v)
441 { return fabs(v(0)) + fabs(v(1)) + fabs(v(2)) + fabs(v(3)); }
442
443 /// The euclidean norm of the vector, that is what most people call length
444 template<typename T>
445 inline
446 SGQuat<T>
447 normalize(const SGQuat<T>& q)
448 { return (1/norm(q))*q; }
449
450 /// Return true if exactly the same
451 template<typename T>
452 inline
453 bool
454 operator==(const SGQuat<T>& v1, const SGQuat<T>& v2)
455 { return v1(0)==v2(0) && v1(1)==v2(1) && v1(2)==v2(2) && v1(3)==v2(3); }
456
457 /// Return true if not exactly the same
458 template<typename T>
459 inline
460 bool
461 operator!=(const SGQuat<T>& v1, const SGQuat<T>& v2)
462 { return ! (v1 == v2); }
463
464 /// Return true if equal to the relative tolerance tol
465 /// Note that this is not the same than comparing quaternions to represent
466 /// the same rotation
467 template<typename T>
468 inline
469 bool
470 equivalent(const SGQuat<T>& v1, const SGQuat<T>& v2, T tol)
471 { return norm1(v1 - v2) < tol*(norm1(v1) + norm1(v2)); }
472
473 /// Return true if about equal to roundoff of the underlying type
474 /// Note that this is not the same than comparing quaternions to represent
475 /// the same rotation
476 template<typename T>
477 inline
478 bool
479 equivalent(const SGQuat<T>& v1, const SGQuat<T>& v2)
480 { return equivalent(v1, v2, 100*SGLimits<T>::epsilon()); }
481
482 #ifndef NDEBUG
483 template<typename T>
484 inline
485 bool
486 isNaN(const SGQuat<T>& v)
487 {
488   return SGMisc<T>::isNaN(v(0)) || SGMisc<T>::isNaN(v(1))
489     || SGMisc<T>::isNaN(v(2)) || SGMisc<T>::isNaN(v(3));
490 }
491 #endif
492
493 /// quaternion interpolation for t in [0,1] interpolate between src (=0)
494 /// and dst (=1)
495 template<typename T>
496 inline
497 SGQuat<T>
498 interpolate(T t, const SGQuat<T>& src, const SGQuat<T>& dst)
499 {
500   T cosPhi = dot(src, dst);
501   // need to take the shorter way ...
502   int signCosPhi = SGMisc<T>::sign(cosPhi);
503   // cosPhi must be corrected for that sign
504   cosPhi = fabs(cosPhi);
505
506   // first opportunity to fail - make sure acos will succeed later -
507   // result is correct
508   if (1 <= cosPhi)
509     return dst;
510
511   // now the half angle between the orientations
512   T o = acos(cosPhi);
513
514   // need the scales now, if the angle is very small, do linear interpolation
515   // to avoid instabilities
516   T scale0, scale1;
517   if (fabs(o) < SGLimits<T>::epsilon()) {
518     scale0 = 1 - t;
519     scale1 = t;
520   } else {
521     // note that we can give a positive lower bound for sin(o) here
522     T sino = sin(o);
523     T so = 1/sino;
524     scale0 = sin((1 - t)*o)*so;
525     scale1 = sin(t*o)*so;
526   }
527
528   return scale0*src + signCosPhi*scale1*dst;
529 }
530
531 /// Output to an ostream
532 template<typename char_type, typename traits_type, typename T>
533 inline
534 std::basic_ostream<char_type, traits_type>&
535 operator<<(std::basic_ostream<char_type, traits_type>& s, const SGQuat<T>& v)
536 { return s << "[ " << v(0) << ", " << v(1) << ", " << v(2) << ", " << v(3) << " ]"; }
537
538 /// Two classes doing actually the same on different types
539 typedef SGQuat<float> SGQuatf;
540 typedef SGQuat<double> SGQuatd;
541
542 inline
543 SGQuatf
544 toQuatf(const SGQuatd& v)
545 { return SGQuatf((float)v(0), (float)v(1), (float)v(2), (float)v(3)); }
546
547 inline
548 SGQuatd
549 toQuatd(const SGQuatf& v)
550 { return SGQuatd(v(0), v(1), v(2), v(3)); }
551
552 #endif