2013-11-15 39 views
0

我试图编写我自定义的Opengl glRotatef(angle,x,y,z)函数的实现。 我写了旋转矩阵,但是当我尝试使用它时,效果与原始函数不一样。这是我的代码;OpenGl旋转自定义实现

void mglRotate(float angle, float x, float y, float z) 
{ 
    float angle_rad = angle * (PI/180.0f); 

    float c = cos(angle_rad); 
    float s = sin(angle_rad); 
    float t = 1 - c; 

    float m[16] = { 
      c+x*x*t,y*x*t+z*s,z*x*t-y*s,0, 
      x*y*t-z*s,c+y*y*t,z*y*t+x*s,0, 
      x*z*t+y*s,y*z*t-x*s,z*z*t+c,0, 
      0,0,0,1 
    }; 

    glMultMatrixf(m); 
} 

我的错误在哪里?

+1

这个问题似乎是题外话题,因为它是关于线性代数的。 –

回答

3

有一个库glm,它和老的openGL函数完全一样。您可以在GLM与执行比较的实施和看着办吧:)

template <typename T> 
GLM_FUNC_QUALIFIER detail::tmat4x4<T> rotate 
(
    detail::tmat4x4<T> const & m, 
    T const & angle, 
    detail::tvec3<T> const & v 
) 
{ 
    T a = radians(angle); 
    T c = cos(a); 
    T s = sin(a); 

    detail::tvec3<T> axis = normalize(v); 

    detail::tvec3<T> temp = (T(1) - c) * axis; 

    detail::tmat4x4<T> Rotate(detail::tmat4x4<T>::null); 
    Rotate[0][0] = c + temp[0] * axis[0]; 
    Rotate[0][1] = 0 + temp[0] * axis[1] + s * axis[2]; 
    Rotate[0][2] = 0 + temp[0] * axis[2] - s * axis[1]; 

    Rotate[1][0] = 0 + temp[1] * axis[0] - s * axis[2]; 
    Rotate[1][1] = c + temp[1] * axis[1]; 
    Rotate[1][2] = 0 + temp[1] * axis[2] + s * axis[0]; 

    Rotate[2][0] = 0 + temp[2] * axis[0] + s * axis[1]; 
    Rotate[2][1] = 0 + temp[2] * axis[1] - s * axis[0]; 
    Rotate[2][2] = c + temp[2] * axis[2]; 

    detail::tmat4x4<T> Result(detail::tmat4x4<T>::null); 
    Result[0] = m[0] * Rotate[0][0] + m[1] * Rotate[0][1] + m[2] * Rotate[0][2]; 
    Result[1] = m[0] * Rotate[1][0] + m[1] * Rotate[1][1] + m[2] * Rotate[1][2]; 
    Result[2] = m[0] * Rotate[2][0] + m[1] * Rotate[2][1] + m[2] * Rotate[2][2]; 
    Result[3] = m[3]; 
    return Result; 
} 

有一两件事似乎是错误的我在你的代码,你不正常化的轴。

+0

我已经规范了轴,现在一切正常! – user1071138