]> git.mxchange.org Git - simgear.git/blob - simgear/math/SGQuat.hxx
Boolean uniforms are now updatable by properties
[simgear.git] / simgear / math / SGQuat.hxx
1 // Copyright (C) 2006-2009  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 /// Quaternion Class
30 template<typename T>
31 class SGQuat {
32 public:
33   typedef T value_type;
34
35   /// Default constructor. Does not initialize at all.
36   /// If you need them zero initialized, SGQuat::zeros()
37   SGQuat(void)
38   {
39     /// Initialize with nans in the debug build, that will guarantee to have
40     /// a fast uninitialized default constructor in the release but shows up
41     /// uninitialized values in the debug build very fast ...
42 #ifndef NDEBUG
43     for (unsigned i = 0; i < 4; ++i)
44       data()[i] = SGLimits<T>::quiet_NaN();
45 #endif
46   }
47   /// Constructor. Initialize by the given values
48   SGQuat(T _x, T _y, T _z, T _w)
49   { x() = _x; y() = _y; z() = _z; w() = _w; }
50   /// Constructor. Initialize by the content of a plain array,
51   /// make sure it has at least 4 elements
52   explicit SGQuat(const T* d)
53   { data()[0] = d[0]; data()[1] = d[1]; data()[2] = d[2]; data()[3] = d[3]; }
54
55   /// Return a unit quaternion
56   static SGQuat unit(void)
57   { return fromRealImag(1, SGVec3<T>(0, 0, 0)); }
58
59   /// Return a quaternion from euler angles
60   static SGQuat fromEulerRad(T z, T y, T x)
61   {
62     SGQuat q;
63     T zd2 = T(0.5)*z; T yd2 = T(0.5)*y; T xd2 = T(0.5)*x;
64     T Szd2 = sin(zd2); T Syd2 = sin(yd2); T Sxd2 = sin(xd2);
65     T Czd2 = cos(zd2); T Cyd2 = cos(yd2); T Cxd2 = cos(xd2);
66     T Cxd2Czd2 = Cxd2*Czd2; T Cxd2Szd2 = Cxd2*Szd2;
67     T Sxd2Szd2 = Sxd2*Szd2; T Sxd2Czd2 = Sxd2*Czd2;
68     q.w() = Cxd2Czd2*Cyd2 + Sxd2Szd2*Syd2;
69     q.x() = Sxd2Czd2*Cyd2 - Cxd2Szd2*Syd2;
70     q.y() = Cxd2Czd2*Syd2 + Sxd2Szd2*Cyd2;
71     q.z() = Cxd2Szd2*Cyd2 - Sxd2Czd2*Syd2;
72     return q;
73   }
74
75   /// Return a quaternion from euler angles in degrees
76   static SGQuat fromEulerDeg(T z, T y, T x)
77   {
78     return fromEulerRad(SGMisc<T>::deg2rad(z), SGMisc<T>::deg2rad(y),
79                         SGMisc<T>::deg2rad(x));
80   }
81
82   /// Return a quaternion from euler angles
83   static SGQuat fromYawPitchRoll(T y, T p, T r)
84   { return fromEulerRad(y, p, r); }
85
86   /// Return a quaternion from euler angles
87   static SGQuat fromYawPitchRollDeg(T y, T p, T r)
88   { return fromEulerDeg(y, p, r); }
89
90   /// Return a quaternion from euler angles
91   static SGQuat fromHeadAttBank(T h, T a, T b)
92   { return fromEulerRad(h, a, b); }
93
94   /// Return a quaternion from euler angles
95   static SGQuat fromHeadAttBankDeg(T h, T a, T b)
96   { return fromEulerDeg(h, a, b); }
97
98   /// Return a quaternion rotation from the earth centered to the
99   /// simulation usual horizontal local frame from given
100   /// longitude and latitude.
101   /// The horizontal local frame used in simulations is the frame with x-axis
102   /// pointing north, the y-axis pointing eastwards and the z axis
103   /// pointing downwards.
104   static SGQuat fromLonLatRad(T lon, T lat)
105   {
106     SGQuat q;
107     T zd2 = T(0.5)*lon;
108     T yd2 = T(-0.25)*SGMisc<T>::pi() - T(0.5)*lat;
109     T Szd2 = sin(zd2);
110     T Syd2 = sin(yd2);
111     T Czd2 = cos(zd2);
112     T Cyd2 = cos(yd2);
113     q.w() = Czd2*Cyd2;
114     q.x() = -Szd2*Syd2;
115     q.y() = Czd2*Syd2;
116     q.z() = Szd2*Cyd2;
117     return q;
118   }
119   /// Like the above provided for convenience
120   static SGQuat fromLonLatDeg(T lon, T lat)
121   { return fromLonLatRad(SGMisc<T>::deg2rad(lon), SGMisc<T>::deg2rad(lat)); }
122   /// Like the above provided for convenience
123   static SGQuat fromLonLat(const SGGeod& geod)
124   { return fromLonLatRad(geod.getLongitudeRad(), geod.getLatitudeRad()); }
125
126
127   /// Create a quaternion from the angle axis representation
128   static SGQuat fromAngleAxis(T angle, const SGVec3<T>& axis)
129   {
130     T angle2 = T(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::unit();
145     T angle2 = T(0.5)*nAxis;
146     return fromRealImag(cos(angle2), T(sin(angle2)/nAxis)*axis);
147   }
148
149   /// Create a normalized quaternion just from the imaginary part.
150   /// The imaginary part should point into that axis direction that results in
151   /// a quaternion with a positive real part.
152   /// This is the smallest numerically stable representation of an orientation
153   /// in space. See getPositiveRealImag()
154   static SGQuat fromPositiveRealImag(const SGVec3<T>& imag)
155   {
156     T r = sqrt(SGMisc<T>::max(T(0), T(1) - dot(imag, imag)));
157     return fromRealImag(r, imag);
158   }
159
160   /// Return a quaternion that rotates the from vector onto the to vector.
161   static SGQuat fromRotateTo(const SGVec3<T>& from, const SGVec3<T>& to)
162   {
163     T nfrom = norm(from);
164     T nto = norm(to);
165     if (nfrom <= SGLimits<T>::min() || nto <= SGLimits<T>::min())
166       return SGQuat::unit();
167
168     return SGQuat::fromRotateToNorm((1/nfrom)*from, (1/nto)*to);
169   }
170
171   /// Return a quaternion that rotates v1 onto the i1-th unit vector
172   /// and v2 into a plane that is spanned by the i2-th and i1-th unit vector.
173   static SGQuat fromRotateTo(const SGVec3<T>& v1, unsigned i1,
174                              const SGVec3<T>& v2, unsigned i2)
175   {
176     T nrmv1 = norm(v1);
177     T nrmv2 = norm(v2);
178     if (nrmv1 <= SGLimits<T>::min() || nrmv2 <= SGLimits<T>::min())
179       return SGQuat::unit();
180
181     SGVec3<T> nv1 = (1/nrmv1)*v1;
182     SGVec3<T> nv2 = (1/nrmv2)*v2;
183     T dv1v2 = dot(nv1, nv2);
184     if (fabs(fabs(dv1v2)-1) <= SGLimits<T>::epsilon())
185       return SGQuat::unit();
186
187     // The target vector for the first rotation
188     SGVec3<T> nto1 = SGVec3<T>::zeros();
189     SGVec3<T> nto2 = SGVec3<T>::zeros();
190     nto1[i1] = 1;
191     nto2[i2] = 1;
192
193     // The first rotation can be done with the usual routine.
194     SGQuat q = SGQuat::fromRotateToNorm(nv1, nto1);
195
196     // The rotation axis for the second rotation is the
197     // target for the first one, so the rotation axis is nto1
198     // We need to get the angle.
199
200     // Make nv2 exactly orthogonal to nv1.
201     nv2 = normalize(nv2 - dv1v2*nv1);
202
203     SGVec3<T> tnv2 = q.transform(nv2);
204     T cosang = dot(nto2, tnv2);
205     T cos05ang = T(0.5)+T(0.5)*cosang;
206     if (cos05ang <= 0)
207       cosang = 0;
208     cos05ang = sqrt(cos05ang);
209     T sig = dot(nto1, cross(nto2, tnv2));
210     T sin05ang = T(0.5)-T(0.5)*cosang;
211     if (sin05ang <= 0)
212       sin05ang = 0;
213     sin05ang = copysign(sqrt(sin05ang), sig);
214     q *= SGQuat::fromRealImag(cos05ang, sin05ang*nto1);
215
216     return q;
217   }
218
219
220   // Return a quaternion which rotates the vector given by v
221   // to the vector -v. Other directions are *not* preserved.
222   static SGQuat fromChangeSign(const SGVec3<T>& v)
223   {
224     // The vector from points to the oposite direction than to.
225     // Find a vector perpendicular to the vector to.
226     T absv1 = fabs(v(0));
227     T absv2 = fabs(v(1));
228     T absv3 = fabs(v(2));
229
230     SGVec3<T> axis;
231     if (absv2 < absv1 && absv3 < absv1) {
232       T quot = v(1)/v(0);
233       axis = (1/sqrt(1+quot*quot))*SGVec3<T>(quot, -1, 0);
234     } else if (absv1 < absv2 && absv3 < absv2) {
235       T quot = v(2)/v(1);
236       axis = (1/sqrt(1+quot*quot))*SGVec3<T>(0, quot, -1);
237     } else if (absv1 < absv3 && absv2 < absv3) {
238       T quot = v(0)/v(2);
239       axis = (1/sqrt(1+quot*quot))*SGVec3<T>(-1, 0, quot);
240     } else {
241       // The all zero case.
242       return SGQuat::unit();
243     }
244
245     return SGQuat::fromRealImag(0, axis);
246   }
247
248   /// Return a quaternion from real and imaginary part
249   static SGQuat fromRealImag(T r, const SGVec3<T>& i)
250   {
251     SGQuat q;
252     q.w() = r;
253     q.x() = i.x();
254     q.y() = i.y();
255     q.z() = i.z();
256     return q;
257   }
258
259   /// Return an all zero vector
260   static SGQuat zeros(void)
261   { return SGQuat(0, 0, 0, 0); }
262
263   /// write the euler angles into the references
264   void getEulerRad(T& zRad, T& yRad, T& xRad) const
265   {
266     T sqrQW = w()*w();
267     T sqrQX = x()*x();
268     T sqrQY = y()*y();
269     T sqrQZ = z()*z();
270
271     T num = 2*(y()*z() + w()*x());
272     T den = sqrQW - sqrQX - sqrQY + sqrQZ;
273     if (fabs(den) <= SGLimits<T>::min() &&
274         fabs(num) <= SGLimits<T>::min())
275       xRad = 0;
276     else
277       xRad = atan2(num, den);
278
279     T tmp = 2*(x()*z() - w()*y());
280     if (tmp <= -1)
281       yRad = T(0.5)*SGMisc<T>::pi();
282     else if (1 <= tmp)
283       yRad = -T(0.5)*SGMisc<T>::pi();
284     else
285       yRad = -asin(tmp);
286
287     num = 2*(x()*y() + w()*z());
288     den = sqrQW + sqrQX - sqrQY - sqrQZ;
289     if (fabs(den) <= SGLimits<T>::min() &&
290         fabs(num) <= SGLimits<T>::min())
291       zRad = 0;
292     else {
293       T psi = atan2(num, den);
294       if (psi < 0)
295         psi += 2*SGMisc<T>::pi();
296       zRad = psi;
297     }
298   }
299
300   /// write the euler angles in degrees into the references
301   void getEulerDeg(T& zDeg, T& yDeg, T& xDeg) const
302   {
303     getEulerRad(zDeg, yDeg, xDeg);
304     zDeg = SGMisc<T>::rad2deg(zDeg);
305     yDeg = SGMisc<T>::rad2deg(yDeg);
306     xDeg = SGMisc<T>::rad2deg(xDeg);
307   }
308
309   /// write the angle axis representation into the references
310   void getAngleAxis(T& angle, SGVec3<T>& axis) const
311   {
312     T nrm = norm(*this);
313     if (nrm <= SGLimits<T>::min()) {
314       angle = 0;
315       axis = SGVec3<T>(0, 0, 0);
316     } else {
317       T rNrm = 1/nrm;
318       angle = acos(SGMisc<T>::max(-1, SGMisc<T>::min(1, rNrm*w())));
319       T sAng = sin(angle);
320       if (fabs(sAng) <= SGLimits<T>::min())
321         axis = SGVec3<T>(1, 0, 0);
322       else
323         axis = (rNrm/sAng)*imag(*this);
324       angle *= 2;
325     }
326   }
327
328   /// write the angle axis representation into the references
329   void getAngleAxis(SGVec3<T>& axis) const
330   {
331     T angle;
332     getAngleAxis(angle, axis);
333     axis *= angle;
334   }
335
336   /// Get the imaginary part of the quaternion.
337   /// The imaginary part should point into that axis direction that results in
338   /// a quaternion with a positive real part.
339   /// This is the smallest numerically stable representation of an orientation
340   /// in space. See fromPositiveRealImag()
341   SGVec3<T> getPositiveRealImag() const
342   {
343     if (real(*this) < T(0))
344       return (T(-1)/norm(*this))*imag(*this);
345     else
346       return (T(1)/norm(*this))*imag(*this);
347   }
348
349   /// Access by index, the index is unchecked
350   const T& operator()(unsigned i) const
351   { return data()[i]; }
352   /// Access by index, the index is unchecked
353   T& operator()(unsigned i)
354   { return data()[i]; }
355
356   /// Access raw data by index, the index is unchecked
357   const T& operator[](unsigned i) const
358   { return data()[i]; }
359   /// Access raw data by index, the index is unchecked
360   T& operator[](unsigned i)
361   { return data()[i]; }
362
363   /// Access the x component
364   const T& x(void) const
365   { return data()[0]; }
366   /// Access the x component
367   T& x(void)
368   { return data()[0]; }
369   /// Access the y component
370   const T& y(void) const
371   { return data()[1]; }
372   /// Access the y component
373   T& y(void)
374   { return data()[1]; }
375   /// Access the z component
376   const T& z(void) const
377   { return data()[2]; }
378   /// Access the z component
379   T& z(void)
380   { return data()[2]; }
381   /// Access the w component
382   const T& w(void) const
383   { return data()[3]; }
384   /// Access the w component
385   T& w(void)
386   { return data()[3]; }
387
388   /// Get the data pointer
389   const T (&data(void) const)[4]
390   { return _data; }
391   /// Get the data pointer
392   T (&data(void))[4]
393   { return _data; }
394
395   /// Inplace addition
396   SGQuat& operator+=(const SGQuat& v)
397   { data()[0]+=v(0);data()[1]+=v(1);data()[2]+=v(2);data()[3]+=v(3);return *this; }
398   /// Inplace subtraction
399   SGQuat& operator-=(const SGQuat& v)
400   { data()[0]-=v(0);data()[1]-=v(1);data()[2]-=v(2);data()[3]-=v(3);return *this; }
401   /// Inplace scalar multiplication
402   template<typename S>
403   SGQuat& operator*=(S s)
404   { data()[0] *= s; data()[1] *= s; data()[2] *= s; data()[3] *= s; return *this; }
405   /// Inplace scalar multiplication by 1/s
406   template<typename S>
407   SGQuat& operator/=(S s)
408   { return operator*=(1/T(s)); }
409   /// Inplace quaternion multiplication
410   SGQuat& operator*=(const SGQuat& v);
411
412   /// Transform a vector from the current coordinate frame to a coordinate
413   /// frame rotated with the quaternion
414   SGVec3<T> transform(const SGVec3<T>& v) const
415   {
416     T r = 2/dot(*this, *this);
417     SGVec3<T> qimag = imag(*this);
418     T qr = real(*this);
419     return (r*qr*qr - 1)*v + (r*dot(qimag, v))*qimag - (r*qr)*cross(qimag, v);
420   }
421   /// Transform a vector from the coordinate frame rotated with the quaternion
422   /// to the current coordinate frame
423   SGVec3<T> backTransform(const SGVec3<T>& v) const
424   {
425     T r = 2/dot(*this, *this);
426     SGVec3<T> qimag = imag(*this);
427     T qr = real(*this);
428     return (r*qr*qr - 1)*v + (r*dot(qimag, v))*qimag + (r*qr)*cross(qimag, v);
429   }
430
431   /// Rotate a given vector with the quaternion
432   SGVec3<T> rotate(const SGVec3<T>& v) const
433   { return backTransform(v); }
434   /// Rotate a given vector with the inverse quaternion
435   SGVec3<T> rotateBack(const SGVec3<T>& v) const
436   { return transform(v); }
437
438   /// Return the time derivative of the quaternion given the angular velocity
439   SGQuat
440   derivative(const SGVec3<T>& angVel) const
441   {
442     SGQuat deriv;
443
444     deriv.w() = T(0.5)*(-x()*angVel(0) - y()*angVel(1) - z()*angVel(2));
445     deriv.x() = T(0.5)*( w()*angVel(0) - z()*angVel(1) + y()*angVel(2));
446     deriv.y() = T(0.5)*( z()*angVel(0) + w()*angVel(1) - x()*angVel(2));
447     deriv.z() = T(0.5)*(-y()*angVel(0) + x()*angVel(1) + w()*angVel(2));
448
449     return deriv;
450   }
451
452   /// Return the angular velocity w that makes q0 translate to q1 using
453   /// an explicit euler step with stepsize h.
454   /// That is, look for an w where
455   /// q1 = normalize(q0 + h*q0.derivative(w))
456   static SGVec3<T>
457   forwardDifferenceVelocity(const SGQuat& q0, const SGQuat& q1, const T& h)
458   {
459     // Let D_q0*w = q0.derivative(w), D_q0 the above 4x3 matrix.
460     // Then D_q0^t*D_q0 = 0.25*Id and D_q0*q0 = 0.
461     // Let lambda be a nonzero normailzation factor, then
462     //  q1 = normalize(q0 + h*q0.derivative(w))
463     // can be rewritten
464     //  lambda*q1 = q0 + h*D_q0*w.
465     // Multiply left by the transpose D_q0^t and reorder gives
466     //  4*lambda/h*D_q0^t*q1 = w.
467     // Now compute lambda by substitution of w into the original
468     // equation
469     //  lambda*q1 = q0 + 4*lambda*D_q0*D_q0^t*q1,
470     // multiply by q1^t from the left
471     //  lambda*<q1,q1> = <q0,q1> + 4*lambda*<D_q0^t*q1,D_q0^t*q1>
472     // and solving for lambda gives
473     //  lambda = <q0,q1>/(1 - 4*<D_q0^t*q1,D_q0^t*q1>).
474
475     // The transpose of the derivative matrix
476     // the 0.5 factor is handled below
477     // also note that the initializer uses x, y, z, w instead of w, x, y, z
478     SGQuat d0(q0.w(), q0.z(), -q0.y(), -q0.x());
479     SGQuat d1(-q0.z(), q0.w(), q0.x(), -q0.y());
480     SGQuat d2(q0.y(), -q0.x(), q0.w(), -q0.z());
481     // 2*D_q0^t*q1
482     SGVec3<T> Dq(dot(d0, q1), dot(d1, q1), dot(d2, q1));
483     // Like above, but take into account that Dq = 2*D_q0^t*q1
484     T lambda = dot(q0, q1)/(T(1) - dot(Dq, Dq));
485     return (2*lambda/h)*Dq;
486   }
487
488 private:
489
490   // Private because it assumes normalized inputs.
491   static SGQuat
492   fromRotateToSmaller90Deg(T cosang,
493                            const SGVec3<T>& from, const SGVec3<T>& to)
494   {
495     // In this function we assume that the angle required to rotate from
496     // the vector from to the vector to is <= 90 deg.
497     // That is done so because of possible instabilities when we rotate more
498     // then 90deg.
499
500     // Note that the next comment does actually cover a *more* *general* case
501     // than we need in this function. That shows that this formula is even
502     // valid for rotations up to 180deg.
503
504     // Because of the signs in the axis, it is sufficient to care for angles
505     // in the interval [-pi,pi]. That means that 0.5*angle is in the interval
506     // [-pi/2,pi/2]. But in that range the cosine is allways >= 0.
507     // So we do not need to care for egative roots in the following equation:
508     T cos05ang = sqrt(T(0.5)+T(0.5)*cosang);
509
510
511     // Now our assumption of angles <= 90 deg comes in play.
512     // For that reason, we know that cos05ang is not zero.
513     // It is even more, we can see from the above formula that
514     // sqrt(0.5) < cos05ang.
515
516
517     // Compute the rotation axis, that is
518     // sin(angle)*normalized rotation axis
519     SGVec3<T> axis = cross(to, from);
520
521     // We need sin(0.5*angle)*normalized rotation axis.
522     // So rescale with sin(0.5*x)/sin(x).
523     // To do that we use the equation:
524     // sin(x) = 2*sin(0.5*x)*cos(0.5*x)
525     return SGQuat::fromRealImag( cos05ang, (1/(2*cos05ang))*axis);
526   }
527
528   // Private because it assumes normalized inputs.
529   static SGQuat
530   fromRotateToNorm(const SGVec3<T>& from, const SGVec3<T>& to)
531   {
532     // To avoid instabilities with roundoff, we distinguish between rotations
533     // with more then 90deg and rotations with less than 90deg.
534
535     // Compute the cosine of the angle.
536     T cosang = dot(from, to);
537
538     // For the small ones do direct computation
539     if (T(-0.5) < cosang)
540       return SGQuat::fromRotateToSmaller90Deg(cosang, from, to);
541
542     // For larger rotations. first rotate from to -from.
543     // Past that we will have a smaller angle again.
544     SGQuat q1 = SGQuat::fromChangeSign(from);
545     SGQuat q2 = SGQuat::fromRotateToSmaller90Deg(-cosang, -from, to);
546     return q1*q2;
547   }
548
549   T _data[4];
550 };
551
552 /// Unary +, do nothing ...
553 template<typename T>
554 inline
555 const SGQuat<T>&
556 operator+(const SGQuat<T>& v)
557 { return v; }
558
559 /// Unary -, do nearly nothing
560 template<typename T>
561 inline
562 SGQuat<T>
563 operator-(const SGQuat<T>& v)
564 { return SGQuat<T>(-v(0), -v(1), -v(2), -v(3)); }
565
566 /// Binary +
567 template<typename T>
568 inline
569 SGQuat<T>
570 operator+(const SGQuat<T>& v1, const SGQuat<T>& v2)
571 { return SGQuat<T>(v1(0)+v2(0), v1(1)+v2(1), v1(2)+v2(2), v1(3)+v2(3)); }
572
573 /// Binary -
574 template<typename T>
575 inline
576 SGQuat<T>
577 operator-(const SGQuat<T>& v1, const SGQuat<T>& v2)
578 { return SGQuat<T>(v1(0)-v2(0), v1(1)-v2(1), v1(2)-v2(2), v1(3)-v2(3)); }
579
580 /// Scalar multiplication
581 template<typename S, typename T>
582 inline
583 SGQuat<T>
584 operator*(S s, const SGQuat<T>& v)
585 { return SGQuat<T>(s*v(0), s*v(1), s*v(2), s*v(3)); }
586
587 /// Scalar multiplication
588 template<typename S, typename T>
589 inline
590 SGQuat<T>
591 operator*(const SGQuat<T>& v, S s)
592 { return SGQuat<T>(s*v(0), s*v(1), s*v(2), s*v(3)); }
593
594 /// Quaterion multiplication
595 template<typename T>
596 inline
597 SGQuat<T>
598 operator*(const SGQuat<T>& v1, const SGQuat<T>& v2)
599 {
600   SGQuat<T> v;
601   v.x() = v1.w()*v2.x() + v1.x()*v2.w() + v1.y()*v2.z() - v1.z()*v2.y();
602   v.y() = v1.w()*v2.y() - v1.x()*v2.z() + v1.y()*v2.w() + v1.z()*v2.x();
603   v.z() = v1.w()*v2.z() + v1.x()*v2.y() - v1.y()*v2.x() + v1.z()*v2.w();
604   v.w() = v1.w()*v2.w() - v1.x()*v2.x() - v1.y()*v2.y() - v1.z()*v2.z();
605   return v;
606 }
607
608 /// Now define the inplace multiplication
609 template<typename T>
610 inline
611 SGQuat<T>&
612 SGQuat<T>::operator*=(const SGQuat& v)
613 { (*this) = (*this)*v; return *this; }
614
615 /// The conjugate of the quaternion, this is also the
616 /// inverse for normalized quaternions
617 template<typename T>
618 inline
619 SGQuat<T>
620 conj(const SGQuat<T>& v)
621 { return SGQuat<T>(-v(0), -v(1), -v(2), v(3)); }
622
623 /// The conjugate of the quaternion, this is also the
624 /// inverse for normalized quaternions
625 template<typename T>
626 inline
627 SGQuat<T>
628 inverse(const SGQuat<T>& v)
629 { return (1/dot(v, v))*SGQuat<T>(-v(0), -v(1), -v(2), v(3)); }
630
631 /// The imagniary part of the quaternion
632 template<typename T>
633 inline
634 T
635 real(const SGQuat<T>& v)
636 { return v.w(); }
637
638 /// The imagniary part of the quaternion
639 template<typename T>
640 inline
641 SGVec3<T>
642 imag(const SGQuat<T>& v)
643 { return SGVec3<T>(v.x(), v.y(), v.z()); }
644
645 /// Scalar dot product
646 template<typename T>
647 inline
648 T
649 dot(const SGQuat<T>& v1, const SGQuat<T>& v2)
650 { return v1(0)*v2(0) + v1(1)*v2(1) + v1(2)*v2(2) + v1(3)*v2(3); }
651
652 /// The euclidean norm of the vector, that is what most people call length
653 template<typename T>
654 inline
655 T
656 norm(const SGQuat<T>& v)
657 { return sqrt(dot(v, v)); }
658
659 /// The euclidean norm of the vector, that is what most people call length
660 template<typename T>
661 inline
662 T
663 length(const SGQuat<T>& v)
664 { return sqrt(dot(v, v)); }
665
666 /// The 1-norm of the vector, this one is the fastest length function we
667 /// can implement on modern cpu's
668 template<typename T>
669 inline
670 T
671 norm1(const SGQuat<T>& v)
672 { return fabs(v(0)) + fabs(v(1)) + fabs(v(2)) + fabs(v(3)); }
673
674 /// The euclidean norm of the vector, that is what most people call length
675 template<typename T>
676 inline
677 SGQuat<T>
678 normalize(const SGQuat<T>& q)
679 { return (1/norm(q))*q; }
680
681 /// Return true if exactly the same
682 template<typename T>
683 inline
684 bool
685 operator==(const SGQuat<T>& v1, const SGQuat<T>& v2)
686 { return v1(0)==v2(0) && v1(1)==v2(1) && v1(2)==v2(2) && v1(3)==v2(3); }
687
688 /// Return true if not exactly the same
689 template<typename T>
690 inline
691 bool
692 operator!=(const SGQuat<T>& v1, const SGQuat<T>& v2)
693 { return ! (v1 == v2); }
694
695 /// Return true if equal to the relative tolerance tol
696 /// Note that this is not the same than comparing quaternions to represent
697 /// the same rotation
698 template<typename T>
699 inline
700 bool
701 equivalent(const SGQuat<T>& v1, const SGQuat<T>& v2, T tol)
702 { return norm1(v1 - v2) < tol*(norm1(v1) + norm1(v2)); }
703
704 /// Return true if about equal to roundoff of the underlying type
705 /// Note that this is not the same than comparing quaternions to represent
706 /// the same rotation
707 template<typename T>
708 inline
709 bool
710 equivalent(const SGQuat<T>& v1, const SGQuat<T>& v2)
711 { return equivalent(v1, v2, 100*SGLimits<T>::epsilon()); }
712
713 #ifndef NDEBUG
714 template<typename T>
715 inline
716 bool
717 isNaN(const SGQuat<T>& v)
718 {
719   return SGMisc<T>::isNaN(v(0)) || SGMisc<T>::isNaN(v(1))
720     || SGMisc<T>::isNaN(v(2)) || SGMisc<T>::isNaN(v(3));
721 }
722 #endif
723
724 /// quaternion interpolation for t in [0,1] interpolate between src (=0)
725 /// and dst (=1)
726 template<typename T>
727 inline
728 SGQuat<T>
729 interpolate(T t, const SGQuat<T>& src, const SGQuat<T>& dst)
730 {
731   T cosPhi = dot(src, dst);
732   // need to take the shorter way ...
733   int signCosPhi = SGMisc<T>::sign(cosPhi);
734   // cosPhi must be corrected for that sign
735   cosPhi = fabs(cosPhi);
736
737   // first opportunity to fail - make sure acos will succeed later -
738   // result is correct
739   if (1 <= cosPhi)
740     return dst;
741
742   // now the half angle between the orientations
743   T o = acos(cosPhi);
744
745   // need the scales now, if the angle is very small, do linear interpolation
746   // to avoid instabilities
747   T scale0, scale1;
748   if (fabs(o) <= SGLimits<T>::epsilon()) {
749     scale0 = 1 - t;
750     scale1 = t;
751   } else {
752     // note that we can give a positive lower bound for sin(o) here
753     T sino = sin(o);
754     T so = 1/sino;
755     scale0 = sin((1 - t)*o)*so;
756     scale1 = sin(t*o)*so;
757   }
758
759   return scale0*src + signCosPhi*scale1*dst;
760 }
761
762 /// Output to an ostream
763 template<typename char_type, typename traits_type, typename T>
764 inline
765 std::basic_ostream<char_type, traits_type>&
766 operator<<(std::basic_ostream<char_type, traits_type>& s, const SGQuat<T>& v)
767 { return s << "[ " << v(0) << ", " << v(1) << ", " << v(2) << ", " << v(3) << " ]"; }
768
769 inline
770 SGQuatf
771 toQuatf(const SGQuatd& v)
772 { return SGQuatf((float)v(0), (float)v(1), (float)v(2), (float)v(3)); }
773
774 inline
775 SGQuatd
776 toQuatd(const SGQuatf& v)
777 { return SGQuatd(v(0), v(1), v(2), v(3)); }
778
779 #endif