OpenGl旋转自定义实现 [英] OpenGl rotate custom implementation

查看:203
本文介绍了OpenGl旋转自定义实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对Opengl glRotatef(angle,x,y,z)函数的自定义实现进行编码. 我编写了旋转矩阵,但是当我尝试使用它时,其效果与原始函数不同.这是我的代码;

I'm trying to code my custom implementation of Opengl glRotatef(angle,x,y,z) function. I wrote the rotation matrix, but when I try to use it, the effect is not the same as the original function. Here is my code;

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

我的错误在哪里?

推荐答案

有一个库

There is a library glm, that does exactly the same thing as old openGL functions. You can compare your implementation with implementation in glm and figure it out :)

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

在我的代码中对我来说似乎不对的一件事是,您没有对轴进行归一化.

The one thing that seems wrong to me in your code is that you don't normalize the axis.

这篇关于OpenGl旋转自定义实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆