0

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

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);
}

我的错误在哪里?

4

1 回答 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;
}

在您的代码中对我来说似乎有问题的一件事是您没有对轴进行标准化。

于 2013-11-15T14:10:39.460 回答