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