///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2008 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// Created : 2005-12-21
// Updated : 2008-11-27
// Licence : This source is under MIT License
// File    : glm/gtx/quaternion.inl
///////////////////////////////////////////////////////////////////////////////////////////////////

#include <limits>

namespace glm{
namespace detail{

    template <typename valType> 
    inline tquat<valType>::tquat() : 
        x(0),
        y(0),
        z(0),
        w(1)
    {}

    template <typename valType> 
    inline tquat<valType>::tquat
	(
		valType const & s, 
		tvec3<valType> const & v
	) : 
        x(v.x),
        y(v.y),
        z(v.z),
        w(s)
    {}

    template <typename valType> 
    inline tquat<valType>::tquat
	(
		valType const & w, 
		valType const & x, 
		valType const & y, 
		valType const & z
	) :
        x(x),
        y(y),
        z(z),
        w(w)
    {}

    //////////////////////////////////////////////////////////////
    // tquat conversions

	template <typename valType> 
	inline tquat<valType>::tquat
	(
		valType const & pitch, 
		valType const & yaw, 
		valType const & roll
	)
	{
		tvec3<valType> eulerAngle(pitch * valType(0.5), yaw * valType(0.5), roll * valType(0.5));
		tvec3<valType> c = glm::cos(eulerAngle * valType(0.5));
		tvec3<valType> s = glm::sin(eulerAngle * valType(0.5));
		
		this->w = c.x * c.y * c.z + s.x * s.y * s.z;
		this->x = s.x * c.y * c.z - c.x * s.y * s.z;
		this->y = c.x * s.y * c.z + s.x * c.y * s.z;
		this->z = c.x * c.y * s.z - s.x * s.y * c.z;
	}

	template <typename valType> 
	inline tquat<valType>::tquat
	(
		tvec3<valType> const & eulerAngle
	)
	{
		tvec3<valType> c = glm::cos(eulerAngle * valType(0.5));
		tvec3<valType> s = glm::sin(eulerAngle * valType(0.5));
		
		this->w = c.x * c.y * c.z + s.x * s.y * s.z;
		this->x = s.x * c.y * c.z - c.x * s.y * s.z;
		this->y = c.x * s.y * c.z + s.x * c.y * s.z;
		this->z = c.x * c.y * s.z - s.x * s.y * c.z;		
	}

    template <typename T> 
    inline tquat<T>::tquat
	(
		tmat3x3<T> const & m
	)
    {
		*this = toQuat(m);
    }

    template <typename T> 
    inline tquat<T>::tquat
	(
		tmat4x4<T> const & m
	)
    {
		*this = toQuat(m);
    }

    //////////////////////////////////////////////////////////////
    // tquat<T> accesses

    template <typename valType> 
    inline valType& tquat<valType>::operator [] (int i)
    {
        return (&x)[i];
    }

    template <typename valType> 
    inline valType tquat<valType>::operator [] (int i) const
    {
        return (&x)[i];
    }

    //////////////////////////////////////////////////////////////
    // tquat<T> operators

    template <typename valType> 
    inline tquat<valType>& tquat<valType>::operator *=
	(
		valType const & s
	)
    {
        this->w *= s;
        this->x *= s;
        this->y *= s;
        this->z *= s;
        return *this;
    }

    template <typename valType> 
    inline tquat<valType>& tquat<valType>::operator /=
	(
		valType const & s
	)
    {
        this->w /= s;
        this->x /= s;
        this->y /= s;
        this->z /= s;
        return *this;
    }

    //////////////////////////////////////////////////////////////
    // tquat<T> external operators

	template <typename T>
	inline detail::tquat<T> operator- 
	(
		detail::tquat<T> const & q
	)
	{
		return detail::tquat<T>(-q.x, -q.y, -q.z, -q.w);
	}

	// Transformation
	template <typename T>
	inline detail::tvec3<T> operator* 
	(
		detail::tquat<T> const & q, 
		detail::tvec3<T> const & v
	)
	{
		detail::tvec3<T> uv, uuv;
		detail::tvec3<T> QuatVector(q.x, q.y, q.z);
		uv = glm::cross(QuatVector, v);
		uuv = glm::cross(QuatVector, uv);
		uv *= (T(2) * q.w); 
		uuv *= T(2); 

		return v + uv + uuv;
	}

	template <typename T>
	inline detail::tvec4<T> operator* 
	(
		detail::tquat<T> const & q, 
		detail::tvec4<T> const & v
	)
	{
		return detail::tvec4<T>(q * detail::tvec3<T>(v), v.w);
	}

	template <typename valType> 
	inline detail::tquat<valType> operator* 
	(
		detail::tquat<valType> const & q, 
		valType const & s
	)
	{
		return detail::tquat<valType>(
			q.w * s, q.x * s, q.y * s, q.z * s);
	}

	template <typename valType> 
	inline detail::tquat<valType> operator* 
	(
		valType const & s,
		detail::tquat<valType> const & q
	)
	{
		return q * s;
	}

	template <typename valType> 
	inline detail::tquat<valType> operator/ 
	(
		detail::tquat<valType> const & q, 
		valType const & s
	)
	{
		return detail::tquat<valType>(
			q.w / s, q.x / s, q.y / s, q.z / s);
	}

}//namespace detail

namespace gtx{
namespace quaternion{

	////////////////////////////////////////////////////////
    template <typename T> 
	inline T length
	(
		detail::tquat<T> const & q
	)
    {
		return static_cast<T>(glm::sqrt(dot(q, q)));
    }

    template <typename T> 
    inline detail::tquat<T> normalize
	(
		detail::tquat<T> const & q
	)
    {
        T len = static_cast<T>(length(q));
        if(len <= 0) // Problem
            return detail::tquat<T>(1, 0, 0, 0);
        T oneOverLen = 1 / len;
        return detail::tquat<T>(q.w * oneOverLen, q.x * oneOverLen, q.y * oneOverLen, q.z * oneOverLen);
    }

    template <typename T> 
    inline T dot
	(
		detail::tquat<T> const & q1, 
		detail::tquat<T> const & q2
	)
    {
        return q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w;
    }

    template <typename T> 
    inline detail::tquat<T> cross
	(
		detail::tquat<T> const & q1, 
		detail::tquat<T> const & q2
	)
    {
        return detail::tquat<T>(
            q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z,
	        q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y,
	        q1.w * q2.y + q1.y * q2.w + q1.z * q2.x - q1.x * q2.z,
	        q1.w * q2.z + q1.z * q2.w + q1.x * q2.y - q1.y * q2.x);
    }

    template <typename valType> 
    inline detail::tvec3<valType> cross
	(
		detail::tvec3<valType> const & v, 
		detail::tquat<valType> const & q
	)
    {
		return rotate(inverse(q), v);		
    }

	template <typename valType> 
    inline detail::tvec3<valType> cross
	(
		detail::tquat<valType> const & q, 
		detail::tvec3<valType> const & v
	)
    {
		return rotate(q, v);
    }

    template <typename T>
    inline detail::tquat<T> mix
	(
		detail::tquat<T> const & x, 
		detail::tquat<T> const & y, 
		T a
	)
    {
        if(a <= T(0)) return x;
        if(a >= T(1)) return y;

        float fCos = dot(x, y);
        detail::tquat<T> y2(y); //BUG!!! tquat<T> y2;
        if(fCos < T(0))
        {
            y2 = -y;
            fCos = -fCos;
        }

        //if(fCos > 1.0f) // problem
        float k0, k1;
        if(fCos > T(0.9999))
        {
            k0 = T(1) - a;
            k1 = T(0) + a; //BUG!!! 1.0f + a;
        }
        else
        {
            T fSin = sqrt(T(1) - fCos * fCos);
            T fAngle = atan(fSin, fCos);
            T fOneOverSin = T(1) / fSin;
            k0 = sin((T(1) - a) * fAngle) * fOneOverSin;
            k1 = sin((T(0) + a) * fAngle) * fOneOverSin;
        }

        return detail::tquat<T>(
            k0 * x.w + k1 * y2.w,
            k0 * x.x + k1 * y2.x,
            k0 * x.y + k1 * y2.y,
            k0 * x.z + k1 * y2.z);
    }

    template <typename T> 
    inline detail::tquat<T> squad
	(
		detail::tquat<T> const & q1, 
		detail::tquat<T> const & q2, 
		detail::tquat<T> const & s1, 
		detail::tquat<T> const & s2, 
		T const h)
    {
        return mix(mix(q1, q2, h), mix(s1, s2, h), T(2) * h (T(1) - h));
    }

    template <typename T> 
    inline detail::tquat<T> intermediate
	(
		detail::tquat<T> const & prev, 
		detail::tquat<T> const & curr, 
		detail::tquat<T> const & next
	)
    {
        detail::tquat<T> invQuat = inverse(curr);
        return ext((log(next + invQuat) + log(prev + invQuat)) / T(-4)) * curr;
    }

    template <typename T> 
    inline detail::tquat<T> exp
	(
		detail::tquat<T> const & q, 
		T const exponent
	)
    {
        detail::tvec3<T> u(q.x, q.y, q.z);
        float a = length(u);
        detail::tvec3<T> v(u / a);
        return detail::tquat<T>(cos(a), sin(a) * v);
    }

    template <typename T> 
    inline detail::tquat<T> log
	(
		detail::tquat<T> const & q
	)
    {
        if((q.x == T(0)) && (q.y == T(0)) && (q.z == T(0)))
        {
            if(q.w > T(0))
                return detail::tquat<T>(log(q.w), T(0), T(0), T(0));
            else if(q.w < T(0))
                return detail::tquat<T>(log(-q.w), T(3.1415926535897932384626433832795), T(0),T(0));
            else
                return detail::tquat<T>(std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity());
        } 
        else 
        {
            T Vec3Len = sqrt(q.x * q.x + q.y * q.y + q.z * q.z);
            T QuatLen = sqrt(Vec3Len * Vec3Len + q.w * q.w);
            T t = atan(Vec3Len, T(q.w)) / Vec3Len;
            return detail::tquat<T>(t * q.x, t * q.y, t * q.z, log(QuatLen));
        }
    }

    template <typename T> 
    inline detail::tquat<T> pow
	(
		detail::tquat<T> const & x, 
		const T y
	)
    {
        if(abs(x.w) > T(0.9999))
            return x;
        float Angle = acos(y);
        float NewAngle = Angle * y;
        float Div = sin(NewAngle) / sin(Angle);
        return detail::tquat<T>(
            cos(NewAngle),
            x.x * Div,
            x.y * Div,
            x.z * Div);
    }

	//template <typename T> 
	//inline detail::tquat<T> sqrt
	//(
	//	detail::tquat<T> const & q
	//)
	//{
	//	T q0 = T(1) - dot(q, q);
	//	return T(2) * (T(1) + q0) * q;
	//}

    template <typename T> 
    inline detail::tquat<T> conjugate
	(
		detail::tquat<T> const & q
	)
    {
        return detail::tquat<T>(q.w, -q.x, -q.y, -q.z);
    }

    template <typename T> 
    inline detail::tquat<T> inverse
	(
		detail::tquat<T> const & q
	)
    {
        return conjugate(q) / length(q);
    }

    template <typename T> 
    inline detail::tquat<T> rotate
	(
		detail::tquat<T> const & q, 
		T angle, 
		T x, T y, T z
	)
    {
        // Axis of rotation must be normalised
        T len = length(detail::tvec3<T>(x, y, z));
        if(abs(len - T(1)) > T(0.001))
        {
            T oneOverLen = T(1) / len;
            x *= oneOverLen;
            y *= oneOverLen;
            z *= oneOverLen;
        }

        angle = radians(angle);
        T fSin = sin(angle * T(0.5));

        return cross(q, detail::tquat<T>(cos(angle * T(0.5)), x * fSin, y * fSin, z * fSin));
    }

    template <typename T> 
    inline detail::tquat<T> rotate
	(
		detail::tquat<T> const & q, 
		T angle, 
		detail::tvec3<T> const & v
	)
    {
		return rotate(q, angle, v.x, v.y, v.z);
	}

    template <typename T> 
    inline detail::tvec3<T> rotate
	(
		detail::tquat<T> const & q, 
		detail::tvec3<T> const & v
	)
    {
		return q * v;
    }

    template <typename T> 
    inline detail::tvec4<T> rotate
	(
		detail::tquat<T> const & q, 
		detail::tvec4<T> const & v
	)
    {
        return q * v;
    }

    template <typename T> 
    inline T angle
	(
		detail::tquat<T> const & x
	)
    {
        return cos(x.w) * T(2);
    }

    template <typename T> 
    inline detail::tvec3<T> axis
	(
		detail::tquat<T> const & x
	)
    {
        T tmp1 = T(1) - x.w * x.w;
        if(tmp1 <= T(0))
            return detail::tvec3<T>(0, 0, 1);
        T tmp2 = T(1) / sqrt(tmp1);
        return detail::tvec3<T>(x.x * tmp2, x.y * tmp2, x.z * tmp2);
    }

    template <typename T> 
    inline detail::tmat3x3<T> toMat3
	(
		detail::tquat<T> const & q
	)
    {
        detail::tmat3x3<T> Result(1);
        Result[0][0] = 1 - 2 * q.y * q.y - 2 * q.z * q.z;
        Result[0][1] = 2 * q.x * q.y + 2 * q.w * q.z;
        Result[0][2] = 2 * q.x * q.z - 2 * q.w * q.y;

        Result[1][0] = 2 * q.x * q.y - 2 * q.w * q.z;
        Result[1][1] = 1 - 2 * q.x * q.x - 2 * q.z * q.z;
        Result[1][2] = 2 * q.y * q.z + 2 * q.w * q.x;

        Result[2][0] = 2 * q.x * q.z + 2 * q.w * q.y;
        Result[2][1] = 2 * q.y * q.z - 2 * q.w * q.x;
        Result[2][2] = 1 - 2 * q.x * q.x - 2 * q.y * q.y;
        return Result;
    }

    template <typename T> 
    inline detail::tmat4x4<T> toMat4
	(
		detail::tquat<T> const & q
	)
    {
        return detail::tmat4x4<T>(toMat3(q));
    }

    template <typename T> 
    inline detail::tquat<T> toQuat
	(
		detail::tmat3x3<T> const & m
	)
    {
        T fourXSquaredMinus1 = m[0][0] - m[1][1] - m[2][2];
        T fourYSquaredMinus1 = m[1][1] - m[0][0] - m[2][2];
        T fourZSquaredMinus1 = m[2][2] - m[0][0] - m[1][1];
        T fourWSquaredMinus1 = m[0][0] + m[1][1] + m[2][2];
        
        int biggestIndex = 0;
        T fourBiggestSquaredMinus1 = fourWSquaredMinus1;
        if(fourXSquaredMinus1 > fourBiggestSquaredMinus1)
        {
            fourBiggestSquaredMinus1 = fourXSquaredMinus1;
            biggestIndex = 1;
        }
        if(fourYSquaredMinus1 > fourBiggestSquaredMinus1)
        {
            fourBiggestSquaredMinus1 = fourYSquaredMinus1;
            biggestIndex = 2;
        }
        if(fourZSquaredMinus1 > fourBiggestSquaredMinus1)
        {
            fourBiggestSquaredMinus1 = fourZSquaredMinus1;
            biggestIndex = 3;
        }

        T biggestVal = sqrt(fourBiggestSquaredMinus1 + T(1)) * T(0.5);
        T mult = T(0.25) / biggestVal;

        detail::tquat<T> Result;
        switch(biggestIndex)
        {
        case 0:
            Result.w = biggestVal; 
            Result.x = (m[1][2] - m[2][1]) * mult;
            Result.y = (m[2][0] - m[0][2]) * mult;
            Result.z = (m[0][1] - m[1][0]) * mult;
            break;
        case 1:
            Result.w = (m[1][2] - m[2][1]) * mult;
            Result.x = biggestVal;
            Result.y = (m[0][1] + m[1][0]) * mult;
            Result.z = (m[2][1] + m[1][2]) * mult;
            break;
        case 2:
            Result.w = (m[2][0] - m[0][2]) * mult;
            Result.x = (m[0][1] + m[1][0]) * mult;
            Result.y = biggestVal;
            Result.z = (m[1][2] + m[2][1]) * mult;
            break;
        case 3:
            Result.w = (m[0][1] - m[1][0]) * mult;
            Result.x = (m[2][0] + m[0][2]) * mult;
            Result.y = (m[1][2] + m[2][1]) * mult;
            Result.z = biggestVal;
            break;
        }
        return Result;
    }

    template <typename T> 
    inline detail::tquat<T> toQuat
	(
		detail::tmat4x4<T> const & m4
	)
    {
		return toQuat(detail::tmat3x3<T>(m4));
    }

    template <typename valType> 
    inline detail::tquat<valType> angleAxis
	(
		valType const & angle, 
		valType const & x, 
		valType const & y, 
		valType const & z
	)
    {
        return angleAxis(angle, detail::tvec3<valType>(x, y, z));
    }

    template <typename valType> 
    inline detail::tquat<valType> angleAxis
	(
		valType const & angle, 
		detail::tvec3<valType> const & v
	)
    {
        detail::tquat<valType> result;
        detail::tvec3<valType> v_normalized = glm::normalize(v);

		valType a = glm::radians(angle);
        valType s = glm::sin(a * valType(0.5));

        result.w = glm::cos(a * valType(0.5));
        result.x = v.x * s;
        result.y = v.y * s;
        result.z = v.z * s;
        return result;
    }

    template <typename T> 
	inline T extractRealComponent
	(
		detail::tquat<T> const & q
	)
    {
        T w = T(1.0) - q.x * q.x - q.y * q.y - q.z * q.z;
        if(w < T(0))
            return T(0);
        else
            return -sqrt(w);
    }

	template <typename T> 
	inline T roll
	(
		detail::tquat<T> const & q
	)
	{
		return tan2(T(2) * (q.x * q.y + q.w * q.z), q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z);
	}

	template <typename valType> 
	inline valType pitch
	(
		detail::tquat<valType> const & q
	)
	{
		return atan2(valType(2) * (q.y * q.z + q.w * q.x), q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z);
	}

	template <typename valType> 
	inline valType yaw
	(
		detail::tquat<valType> const & q
	)
	{
		return asin(valType(-2) * (q.x * q.z - q.w * q.y));
	}

    template <typename valType> 
    inline detail::tvec3<valType> eularAngles
	(
		detail::tquat<valType> const & x
	)
    {
        return detail::tvec3<valType>(pitch(x), yaw(x), roll(x));
    }

}//namespace quaternion
}//namespace gtx
}//namespace glm
