michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #ifndef GFX_QUATERNION_H michael@0: #define GFX_QUATERNION_H michael@0: michael@0: #include "mozilla/gfx/BasePoint4D.h" michael@0: #include "gfx3DMatrix.h" michael@0: #include "nsAlgorithm.h" michael@0: #include michael@0: michael@0: struct gfxQuaternion : public mozilla::gfx::BasePoint4D { michael@0: typedef mozilla::gfx::BasePoint4D Super; michael@0: michael@0: gfxQuaternion() : Super() {} michael@0: gfxQuaternion(gfxFloat aX, gfxFloat aY, gfxFloat aZ, gfxFloat aW) : Super(aX, aY, aZ, aW) {} michael@0: michael@0: gfxQuaternion(const gfx3DMatrix& aMatrix) { michael@0: w = 0.5 * sqrt(std::max(1 + aMatrix[0][0] + aMatrix[1][1] + aMatrix[2][2], 0.0f)); michael@0: x = 0.5 * sqrt(std::max(1 + aMatrix[0][0] - aMatrix[1][1] - aMatrix[2][2], 0.0f)); michael@0: y = 0.5 * sqrt(std::max(1 - aMatrix[0][0] + aMatrix[1][1] - aMatrix[2][2], 0.0f)); michael@0: z = 0.5 * sqrt(std::max(1 - aMatrix[0][0] - aMatrix[1][1] + aMatrix[2][2], 0.0f)); michael@0: michael@0: if(aMatrix[2][1] > aMatrix[1][2]) michael@0: x = -x; michael@0: if(aMatrix[0][2] > aMatrix[2][0]) michael@0: y = -y; michael@0: if(aMatrix[1][0] > aMatrix[0][1]) michael@0: z = -z; michael@0: } michael@0: michael@0: gfxQuaternion Slerp(const gfxQuaternion &aOther, gfxFloat aCoeff) { michael@0: gfxFloat dot = mozilla::clamped(DotProduct(aOther), -1.0, 1.0); michael@0: if (dot == 1.0) { michael@0: return *this; michael@0: } michael@0: michael@0: gfxFloat theta = acos(dot); michael@0: gfxFloat rsintheta = 1/sqrt(1 - dot*dot); michael@0: gfxFloat rightWeight = sin(aCoeff*theta)*rsintheta; michael@0: michael@0: gfxQuaternion left = *this; michael@0: gfxQuaternion right = aOther; michael@0: michael@0: left *= cos(aCoeff*theta) - dot*rightWeight; michael@0: right *= rightWeight; michael@0: michael@0: return left + right; michael@0: } michael@0: michael@0: gfx3DMatrix ToMatrix() { michael@0: gfx3DMatrix temp; michael@0: michael@0: temp[0][0] = 1 - 2 * (y * y + z * z); michael@0: temp[0][1] = 2 * (x * y + w * z); michael@0: temp[0][2] = 2 * (x * z - w * y); michael@0: temp[1][0] = 2 * (x * y - w * z); michael@0: temp[1][1] = 1 - 2 * (x * x + z * z); michael@0: temp[1][2] = 2 * (y * z + w * x); michael@0: temp[2][0] = 2 * (x * z + w * y); michael@0: temp[2][1] = 2 * (y * z - w * x); michael@0: temp[2][2] = 1 - 2 * (x * x + y * y); michael@0: michael@0: return temp; michael@0: } michael@0: michael@0: }; michael@0: michael@0: #endif /* GFX_QUATERNION_H */