1 // Copyright (C) 2006-2009 Mathias Froehlich - Mathias.Froehlich@web.de
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.
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.
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.
29 #ifndef NO_OPENSCENEGRAPH_INTERFACE
39 /// Default constructor. Does not initialize at all.
40 /// If you need them zero initialized, SGQuat::zeros()
43 /// Initialize with nans in the debug build, that will guarantee to have
44 /// a fast uninitialized default constructor in the release but shows up
45 /// uninitialized values in the debug build very fast ...
47 for (unsigned i = 0; i < 4; ++i)
48 data()[i] = SGLimits<T>::quiet_NaN();
51 /// Constructor. Initialize by the given values
52 SGQuat(T _x, T _y, T _z, T _w)
53 { x() = _x; y() = _y; z() = _z; w() = _w; }
54 /// Constructor. Initialize by the content of a plain array,
55 /// make sure it has at least 4 elements
56 explicit SGQuat(const T* d)
57 { data()[0] = d[0]; data()[1] = d[1]; data()[2] = d[2]; data()[3] = d[3]; }
58 #ifndef NO_OPENSCENEGRAPH_INTERFACE
59 explicit SGQuat(const osg::Quat& d)
60 { data()[0] = d[0]; data()[1] = d[1]; data()[2] = d[2]; data()[3] = d[3]; }
63 /// Return a unit quaternion
64 static SGQuat unit(void)
65 { return fromRealImag(1, SGVec3<T>(0, 0, 0)); }
67 /// Return a quaternion from euler angles
68 static SGQuat fromEulerRad(T z, T y, T x)
71 T zd2 = T(0.5)*z; T yd2 = T(0.5)*y; T xd2 = T(0.5)*x;
72 T Szd2 = sin(zd2); T Syd2 = sin(yd2); T Sxd2 = sin(xd2);
73 T Czd2 = cos(zd2); T Cyd2 = cos(yd2); T Cxd2 = cos(xd2);
74 T Cxd2Czd2 = Cxd2*Czd2; T Cxd2Szd2 = Cxd2*Szd2;
75 T Sxd2Szd2 = Sxd2*Szd2; T Sxd2Czd2 = Sxd2*Czd2;
76 q.w() = Cxd2Czd2*Cyd2 + Sxd2Szd2*Syd2;
77 q.x() = Sxd2Czd2*Cyd2 - Cxd2Szd2*Syd2;
78 q.y() = Cxd2Czd2*Syd2 + Sxd2Szd2*Cyd2;
79 q.z() = Cxd2Szd2*Cyd2 - Sxd2Czd2*Syd2;
83 /// Return a quaternion from euler angles in degrees
84 static SGQuat fromEulerDeg(T z, T y, T x)
86 return fromEulerRad(SGMisc<T>::deg2rad(z), SGMisc<T>::deg2rad(y),
87 SGMisc<T>::deg2rad(x));
90 /// Return a quaternion from euler angles
91 static SGQuat fromYawPitchRoll(T y, T p, T r)
92 { return fromEulerRad(y, p, r); }
94 /// Return a quaternion from euler angles
95 static SGQuat fromYawPitchRollDeg(T y, T p, T r)
96 { return fromEulerDeg(y, p, r); }
98 /// Return a quaternion from euler angles
99 static SGQuat fromHeadAttBank(T h, T a, T b)
100 { return fromEulerRad(h, a, b); }
102 /// Return a quaternion from euler angles
103 static SGQuat fromHeadAttBankDeg(T h, T a, T b)
104 { return fromEulerDeg(h, a, b); }
106 /// Return a quaternion rotation from the earth centered to the
107 /// simulation usual horizontal local frame from given
108 /// longitude and latitude.
109 /// The horizontal local frame used in simulations is the frame with x-axis
110 /// pointing north, the y-axis pointing eastwards and the z axis
111 /// pointing downwards.
112 static SGQuat fromLonLatRad(T lon, T lat)
116 T yd2 = T(-0.25)*SGMisc<T>::pi() - T(0.5)*lat;
127 /// Like the above provided for convenience
128 static SGQuat fromLonLatDeg(T lon, T lat)
129 { return fromLonLatRad(SGMisc<T>::deg2rad(lon), SGMisc<T>::deg2rad(lat)); }
130 /// Like the above provided for convenience
131 static SGQuat fromLonLat(const SGGeod& geod)
132 { return fromLonLatRad(geod.getLongitudeRad(), geod.getLatitudeRad()); }
135 /// Create a quaternion from the angle axis representation
136 static SGQuat fromAngleAxis(T angle, const SGVec3<T>& axis)
138 T angle2 = T(0.5)*angle;
139 return fromRealImag(cos(angle2), T(sin(angle2))*axis);
142 /// Create a quaternion from the angle axis representation
143 static SGQuat fromAngleAxisDeg(T angle, const SGVec3<T>& axis)
144 { return fromAngleAxis(SGMisc<T>::deg2rad(angle), axis); }
146 /// Create a quaternion from the angle axis representation where the angle
147 /// is stored in the axis' length
148 static SGQuat fromAngleAxis(const SGVec3<T>& axis)
150 T nAxis = norm(axis);
151 if (nAxis <= SGLimits<T>::min())
152 return SGQuat::unit();
153 T angle2 = T(0.5)*nAxis;
154 return fromRealImag(cos(angle2), T(sin(angle2)/nAxis)*axis);
157 /// Return a quaternion that rotates the from vector onto the to vector.
158 static SGQuat fromRotateTo(const SGVec3<T>& from, const SGVec3<T>& to)
160 T nfrom = norm(from);
162 if (nfrom <= SGLimits<T>::min() || nto <= SGLimits<T>::min())
163 return SGQuat::unit();
165 return SGQuat::fromRotateToNorm((1/nfrom)*from, (1/nto)*to);
168 /// Return a quaternion that rotates v1 onto the i1-th unit vector
169 /// and v2 into a plane that is spanned by the i2-th and i1-th unit vector.
170 static SGQuat fromRotateTo(const SGVec3<T>& v1, unsigned i1,
171 const SGVec3<T>& v2, unsigned i2)
175 if (nrmv1 <= SGLimits<T>::min() || nrmv2 <= SGLimits<T>::min())
176 return SGQuat::unit();
178 SGVec3<T> nv1 = (1/nrmv1)*v1;
179 SGVec3<T> nv2 = (1/nrmv2)*v2;
180 T dv1v2 = dot(nv1, nv2);
181 if (fabs(fabs(dv1v2)-1) <= SGLimits<T>::epsilon())
182 return SGQuat::unit();
184 // The target vector for the first rotation
185 SGVec3<T> nto1 = SGVec3<T>::zeros();
186 SGVec3<T> nto2 = SGVec3<T>::zeros();
190 // The first rotation can be done with the usual routine.
191 SGQuat q = SGQuat::fromRotateToNorm(nv1, nto1);
193 // The rotation axis for the second rotation is the
194 // target for the first one, so the rotation axis is nto1
195 // We need to get the angle.
197 // Make nv2 exactly orthogonal to nv1.
198 nv2 = normalize(nv2 - dv1v2*nv1);
200 SGVec3<T> tnv2 = q.transform(nv2);
201 T cosang = dot(nto2, tnv2);
202 T cos05ang = T(0.5)+T(0.5)*cosang;
205 cos05ang = sqrt(cos05ang);
206 T sig = dot(nto1, cross(nto2, tnv2));
207 T sin05ang = T(0.5)-T(0.5)*cosang;
210 sin05ang = copysign(sqrt(sin05ang), sig);
211 q *= SGQuat::fromRealImag(cos05ang, sin05ang*nto1);
217 // Return a quaternion which rotates the vector given by v
218 // to the vector -v. Other directions are *not* preserved.
219 static SGQuat fromChangeSign(const SGVec3<T>& v)
221 // The vector from points to the oposite direction than to.
222 // Find a vector perpendicular to the vector to.
223 T absv1 = fabs(v(0));
224 T absv2 = fabs(v(1));
225 T absv3 = fabs(v(2));
228 if (absv2 < absv1 && absv3 < absv1) {
230 axis = (1/sqrt(1+quot*quot))*SGVec3<T>(quot, -1, 0);
231 } else if (absv1 < absv2 && absv3 < absv2) {
233 axis = (1/sqrt(1+quot*quot))*SGVec3<T>(0, quot, -1);
234 } else if (absv1 < absv3 && absv2 < absv3) {
236 axis = (1/sqrt(1+quot*quot))*SGVec3<T>(-1, 0, quot);
238 // The all zero case.
239 return SGQuat::unit();
242 return SGQuat::fromRealImag(0, axis);
245 /// Return a quaternion from real and imaginary part
246 static SGQuat fromRealImag(T r, const SGVec3<T>& i)
256 /// Return an all zero vector
257 static SGQuat zeros(void)
258 { return SGQuat(0, 0, 0, 0); }
260 /// write the euler angles into the references
261 void getEulerRad(T& zRad, T& yRad, T& xRad) const
268 T num = 2*(y()*z() + w()*x());
269 T den = sqrQW - sqrQX - sqrQY + sqrQZ;
270 if (fabs(den) <= SGLimits<T>::min() &&
271 fabs(num) <= SGLimits<T>::min())
274 xRad = atan2(num, den);
276 T tmp = 2*(x()*z() - w()*y());
278 yRad = T(0.5)*SGMisc<T>::pi();
280 yRad = -T(0.5)*SGMisc<T>::pi();
284 num = 2*(x()*y() + w()*z());
285 den = sqrQW + sqrQX - sqrQY - sqrQZ;
286 if (fabs(den) <= SGLimits<T>::min() &&
287 fabs(num) <= SGLimits<T>::min())
290 T psi = atan2(num, den);
292 psi += 2*SGMisc<T>::pi();
297 /// write the euler angles in degrees into the references
298 void getEulerDeg(T& zDeg, T& yDeg, T& xDeg) const
300 getEulerRad(zDeg, yDeg, xDeg);
301 zDeg = SGMisc<T>::rad2deg(zDeg);
302 yDeg = SGMisc<T>::rad2deg(yDeg);
303 xDeg = SGMisc<T>::rad2deg(xDeg);
306 /// write the angle axis representation into the references
307 void getAngleAxis(T& angle, SGVec3<T>& axis) const
310 if (nrm <= SGLimits<T>::min()) {
312 axis = SGVec3<T>(0, 0, 0);
315 angle = acos(SGMisc<T>::max(-1, SGMisc<T>::min(1, rNrm*w())));
317 if (fabs(sAng) <= SGLimits<T>::min())
318 axis = SGVec3<T>(1, 0, 0);
320 axis = (rNrm/sAng)*imag(*this);
325 /// write the angle axis representation into the references
326 void getAngleAxis(SGVec3<T>& axis) const
329 getAngleAxis(angle, axis);
333 /// Access by index, the index is unchecked
334 const T& operator()(unsigned i) const
335 { return data()[i]; }
336 /// Access by index, the index is unchecked
337 T& operator()(unsigned i)
338 { return data()[i]; }
340 /// Access raw data by index, the index is unchecked
341 const T& operator[](unsigned i) const
342 { return data()[i]; }
343 /// Access raw data by index, the index is unchecked
344 T& operator[](unsigned i)
345 { return data()[i]; }
347 /// Access the x component
348 const T& x(void) const
349 { return data()[0]; }
350 /// Access the x component
352 { return data()[0]; }
353 /// Access the y component
354 const T& y(void) const
355 { return data()[1]; }
356 /// Access the y component
358 { return data()[1]; }
359 /// Access the z component
360 const T& z(void) const
361 { return data()[2]; }
362 /// Access the z component
364 { return data()[2]; }
365 /// Access the w component
366 const T& w(void) const
367 { return data()[3]; }
368 /// Access the w component
370 { return data()[3]; }
372 /// Get the data pointer
373 const T (&data(void) const)[4]
375 /// Get the data pointer
379 #ifndef NO_OPENSCENEGRAPH_INTERFACE
380 osg::Quat osg() const
381 { return osg::Quat(data()[0], data()[1], data()[2], data()[3]); }
385 SGQuat& operator+=(const SGQuat& v)
386 { data()[0]+=v(0);data()[1]+=v(1);data()[2]+=v(2);data()[3]+=v(3);return *this; }
387 /// Inplace subtraction
388 SGQuat& operator-=(const SGQuat& v)
389 { data()[0]-=v(0);data()[1]-=v(1);data()[2]-=v(2);data()[3]-=v(3);return *this; }
390 /// Inplace scalar multiplication
392 SGQuat& operator*=(S s)
393 { data()[0] *= s; data()[1] *= s; data()[2] *= s; data()[3] *= s; return *this; }
394 /// Inplace scalar multiplication by 1/s
396 SGQuat& operator/=(S s)
397 { return operator*=(1/T(s)); }
398 /// Inplace quaternion multiplication
399 SGQuat& operator*=(const SGQuat& v);
401 /// Transform a vector from the current coordinate frame to a coordinate
402 /// frame rotated with the quaternion
403 SGVec3<T> transform(const SGVec3<T>& v) const
405 T r = 2/dot(*this, *this);
406 SGVec3<T> qimag = imag(*this);
408 return (r*qr*qr - 1)*v + (r*dot(qimag, v))*qimag - (r*qr)*cross(qimag, v);
410 /// Transform a vector from the coordinate frame rotated with the quaternion
411 /// to the current coordinate frame
412 SGVec3<T> backTransform(const SGVec3<T>& v) const
414 T r = 2/dot(*this, *this);
415 SGVec3<T> qimag = imag(*this);
417 return (r*qr*qr - 1)*v + (r*dot(qimag, v))*qimag + (r*qr)*cross(qimag, v);
420 /// Rotate a given vector with the quaternion
421 SGVec3<T> rotate(const SGVec3<T>& v) const
422 { return backTransform(v); }
423 /// Rotate a given vector with the inverse quaternion
424 SGVec3<T> rotateBack(const SGVec3<T>& v) const
425 { return transform(v); }
427 /// Return the time derivative of the quaternion given the angular velocity
429 derivative(const SGVec3<T>& angVel) const
433 deriv.w() = T(0.5)*(-x()*angVel(0) - y()*angVel(1) - z()*angVel(2));
434 deriv.x() = T(0.5)*( w()*angVel(0) - z()*angVel(1) + y()*angVel(2));
435 deriv.y() = T(0.5)*( z()*angVel(0) + w()*angVel(1) - x()*angVel(2));
436 deriv.z() = T(0.5)*(-y()*angVel(0) + x()*angVel(1) + w()*angVel(2));
443 // Private because it assumes normalized inputs.
445 fromRotateToSmaller90Deg(T cosang,
446 const SGVec3<T>& from, const SGVec3<T>& to)
448 // In this function we assume that the angle required to rotate from
449 // the vector from to the vector to is <= 90 deg.
450 // That is done so because of possible instabilities when we rotate more
453 // Note that the next comment does actually cover a *more* *general* case
454 // than we need in this function. That shows that this formula is even
455 // valid for rotations up to 180deg.
457 // Because of the signs in the axis, it is sufficient to care for angles
458 // in the interval [-pi,pi]. That means that 0.5*angle is in the interval
459 // [-pi/2,pi/2]. But in that range the cosine is allways >= 0.
460 // So we do not need to care for egative roots in the following equation:
461 T cos05ang = sqrt(T(0.5)+T(0.5)*cosang);
464 // Now our assumption of angles <= 90 deg comes in play.
465 // For that reason, we know that cos05ang is not zero.
466 // It is even more, we can see from the above formula that
467 // sqrt(0.5) < cos05ang.
470 // Compute the rotation axis, that is
471 // sin(angle)*normalized rotation axis
472 SGVec3<T> axis = cross(to, from);
474 // We need sin(0.5*angle)*normalized rotation axis.
475 // So rescale with sin(0.5*x)/sin(x).
476 // To do that we use the equation:
477 // sin(x) = 2*sin(0.5*x)*cos(0.5*x)
478 return SGQuat::fromRealImag( cos05ang, (1/(2*cos05ang))*axis);
481 // Private because it assumes normalized inputs.
483 fromRotateToNorm(const SGVec3<T>& from, const SGVec3<T>& to)
485 // To avoid instabilities with roundoff, we distinguish between rotations
486 // with more then 90deg and rotations with less than 90deg.
488 // Compute the cosine of the angle.
489 T cosang = dot(from, to);
491 // For the small ones do direct computation
492 if (T(-0.5) < cosang)
493 return SGQuat::fromRotateToSmaller90Deg(cosang, from, to);
495 // For larger rotations. first rotate from to -from.
496 // Past that we will have a smaller angle again.
497 SGQuat q1 = SGQuat::fromChangeSign(from);
498 SGQuat q2 = SGQuat::fromRotateToSmaller90Deg(-cosang, -from, to);
505 /// Unary +, do nothing ...
509 operator+(const SGQuat<T>& v)
512 /// Unary -, do nearly nothing
516 operator-(const SGQuat<T>& v)
517 { return SGQuat<T>(-v(0), -v(1), -v(2), -v(3)); }
523 operator+(const SGQuat<T>& v1, const SGQuat<T>& v2)
524 { return SGQuat<T>(v1(0)+v2(0), v1(1)+v2(1), v1(2)+v2(2), v1(3)+v2(3)); }
530 operator-(const SGQuat<T>& v1, const SGQuat<T>& v2)
531 { return SGQuat<T>(v1(0)-v2(0), v1(1)-v2(1), v1(2)-v2(2), v1(3)-v2(3)); }
533 /// Scalar multiplication
534 template<typename S, typename T>
537 operator*(S s, const SGQuat<T>& v)
538 { return SGQuat<T>(s*v(0), s*v(1), s*v(2), s*v(3)); }
540 /// Scalar multiplication
541 template<typename S, typename T>
544 operator*(const SGQuat<T>& v, S s)
545 { return SGQuat<T>(s*v(0), s*v(1), s*v(2), s*v(3)); }
547 /// Quaterion multiplication
551 operator*(const SGQuat<T>& v1, const SGQuat<T>& v2)
554 v.x() = v1.w()*v2.x() + v1.x()*v2.w() + v1.y()*v2.z() - v1.z()*v2.y();
555 v.y() = v1.w()*v2.y() - v1.x()*v2.z() + v1.y()*v2.w() + v1.z()*v2.x();
556 v.z() = v1.w()*v2.z() + v1.x()*v2.y() - v1.y()*v2.x() + v1.z()*v2.w();
557 v.w() = v1.w()*v2.w() - v1.x()*v2.x() - v1.y()*v2.y() - v1.z()*v2.z();
561 /// Now define the inplace multiplication
565 SGQuat<T>::operator*=(const SGQuat& v)
566 { (*this) = (*this)*v; return *this; }
568 /// The conjugate of the quaternion, this is also the
569 /// inverse for normalized quaternions
573 conj(const SGQuat<T>& v)
574 { return SGQuat<T>(-v(0), -v(1), -v(2), v(3)); }
576 /// The conjugate of the quaternion, this is also the
577 /// inverse for normalized quaternions
581 inverse(const SGQuat<T>& v)
582 { return (1/dot(v, v))*SGQuat<T>(-v(0), -v(1), -v(2), v(3)); }
584 /// The imagniary part of the quaternion
588 real(const SGQuat<T>& v)
591 /// The imagniary part of the quaternion
595 imag(const SGQuat<T>& v)
596 { return SGVec3<T>(v.x(), v.y(), v.z()); }
598 /// Scalar dot product
602 dot(const SGQuat<T>& v1, const SGQuat<T>& v2)
603 { return v1(0)*v2(0) + v1(1)*v2(1) + v1(2)*v2(2) + v1(3)*v2(3); }
605 /// The euclidean norm of the vector, that is what most people call length
609 norm(const SGQuat<T>& v)
610 { return sqrt(dot(v, v)); }
612 /// The euclidean norm of the vector, that is what most people call length
616 length(const SGQuat<T>& v)
617 { return sqrt(dot(v, v)); }
619 /// The 1-norm of the vector, this one is the fastest length function we
620 /// can implement on modern cpu's
624 norm1(const SGQuat<T>& v)
625 { return fabs(v(0)) + fabs(v(1)) + fabs(v(2)) + fabs(v(3)); }
627 /// The euclidean norm of the vector, that is what most people call length
631 normalize(const SGQuat<T>& q)
632 { return (1/norm(q))*q; }
634 /// Return true if exactly the same
638 operator==(const SGQuat<T>& v1, const SGQuat<T>& v2)
639 { return v1(0)==v2(0) && v1(1)==v2(1) && v1(2)==v2(2) && v1(3)==v2(3); }
641 /// Return true if not exactly the same
645 operator!=(const SGQuat<T>& v1, const SGQuat<T>& v2)
646 { return ! (v1 == v2); }
648 /// Return true if equal to the relative tolerance tol
649 /// Note that this is not the same than comparing quaternions to represent
650 /// the same rotation
654 equivalent(const SGQuat<T>& v1, const SGQuat<T>& v2, T tol)
655 { return norm1(v1 - v2) < tol*(norm1(v1) + norm1(v2)); }
657 /// Return true if about equal to roundoff of the underlying type
658 /// Note that this is not the same than comparing quaternions to represent
659 /// the same rotation
663 equivalent(const SGQuat<T>& v1, const SGQuat<T>& v2)
664 { return equivalent(v1, v2, 100*SGLimits<T>::epsilon()); }
670 isNaN(const SGQuat<T>& v)
672 return SGMisc<T>::isNaN(v(0)) || SGMisc<T>::isNaN(v(1))
673 || SGMisc<T>::isNaN(v(2)) || SGMisc<T>::isNaN(v(3));
677 /// quaternion interpolation for t in [0,1] interpolate between src (=0)
682 interpolate(T t, const SGQuat<T>& src, const SGQuat<T>& dst)
684 T cosPhi = dot(src, dst);
685 // need to take the shorter way ...
686 int signCosPhi = SGMisc<T>::sign(cosPhi);
687 // cosPhi must be corrected for that sign
688 cosPhi = fabs(cosPhi);
690 // first opportunity to fail - make sure acos will succeed later -
695 // now the half angle between the orientations
698 // need the scales now, if the angle is very small, do linear interpolation
699 // to avoid instabilities
701 if (fabs(o) <= SGLimits<T>::epsilon()) {
705 // note that we can give a positive lower bound for sin(o) here
708 scale0 = sin((1 - t)*o)*so;
709 scale1 = sin(t*o)*so;
712 return scale0*src + signCosPhi*scale1*dst;
715 /// Output to an ostream
716 template<typename char_type, typename traits_type, typename T>
718 std::basic_ostream<char_type, traits_type>&
719 operator<<(std::basic_ostream<char_type, traits_type>& s, const SGQuat<T>& v)
720 { return s << "[ " << v(0) << ", " << v(1) << ", " << v(2) << ", " << v(3) << " ]"; }
724 toQuatf(const SGQuatd& v)
725 { return SGQuatf((float)v(0), (float)v(1), (float)v(2), (float)v(3)); }
729 toQuatd(const SGQuatf& v)
730 { return SGQuatd(v(0), v(1), v(2), v(3)); }
732 #ifndef NO_OPENSCENEGRAPH_INTERFACE
735 toSG(const osg::Quat& q)
736 { return SGQuatd(q[0], q[1], q[2], q[3]); }
740 toOsg(const SGQuatd& q)
741 { return osg::Quat(q[0], q[1], q[2], q[3]); }