c++ - 纯 C 语言中的 glRotatef

标签 c++ c opengl 3d glrotate

我在用纯 C 语言编写 glRotatef 的替代函数时遇到问题。我需要实现参数为:点列表、角度和旋转 vector 的函数。函数必须返回旋转后的点列表。我的函数如下所示:

void rotate(float * current, float a, float x, float y, float z)
{
    float sina = sinf(a);
    float cosa = cosf(a);
    float rotateMatrix[9] = //creating rotate matrix
    {
        x*x*(1-cosa) + cosa,    x*y*(1-cosa) - z*sina,  x*z*(1-cosa) + y*sina,
        y*x*(1-cosa) + z*sina,  y*y*(1-cosa) + cosa,    y*z*(1-cosa) - x*sina,
        z*x*(1-cosa) - y*sina,  z*y*(1-cosa) + x*sina,  z*z*(1-cosa) + cosa
    };
    float *resultVertexList = current; //temporary help
    int i;
    for(i=0;current[i] != 0;i++) //multiplying CURRENT_MATRIX * ROTATE_MATRIX
    {
        int currentVertex = (i/3) * 3;
        int rotateColumn = i%3;
        resultVertexList[i] =
        current[currentVertex] * rotateMatrix[rotateColumn] +
        current[currentVertex+1] * rotateMatrix[rotateColumn+3] +
        current[currentVertex+2] * rotateMatrix[rotateColumn+6];
    }
    current = resultVertexList;
}

我这样调用它:rotate(current, M_PI/10, 0, 1, 0);

之后,我获取当前点列表并使用 openGL 简单地绘制它们。为了进行测试,我尝试旋转代表立方体的点列表。它会旋转,但每调用一次rotate函数,它就会收缩。我不知道为什么。查看一些屏幕截图:

  1. without any rotating, front side of cube

  2. when I rotate it shrinks

多次调用rotate函数后,它缩小到一个点。

我做错了什么?

最佳答案

这行代码:

float *resultVertexList = current; //temporary help

不复制您的顶点列表。您只是将指针复制到列表,因此在此之后您将有两个指向同一个列表的指针。因此,下面的循环使用已经旋转的 x/y 坐标来计算新的 y/z 坐标,这显然是错误的。

我还想知道您的终止条件:

current[i] != 0

这并没有错,但它会阻止您拥有任何坐标为零的顶点。相反,我建议使用一个附加参数来显式传递顶点计数。

我还会旋转每个顶点而不是每个坐标,这更自然且更容易理解:

void rotate(float * current, int vertexCount, float a, float x, float y, float z)
{
    float sina = sinf(a);
    float cosa = cosf(a);
    float rotateMatrix[9] =
    {
        x*x*(1 - cosa) + cosa, x*y*(1 - cosa) - z*sina, x*z*(1 - cosa) + y*sina,
        y*x*(1 - cosa) + z*sina, y*y*(1 - cosa) + cosa, y*z*(1 - cosa) - x*sina,
        z*x*(1 - cosa) - y*sina, z*y*(1 - cosa) + x*sina, z*z*(1 - cosa) + cosa
    };

    int i;
    for (i = 0; i < vertexCount; ++i)
    {
        float* vertex = current + i * 3;

        float x = rotateMatrix[0] * vertex[0] + rotateMatrix[1] * vertex[1] + rotateMatrix[2] * vertex[2];
        float y = rotateMatrix[3] * vertex[0] + rotateMatrix[4] * vertex[1] + rotateMatrix[5] * vertex[2];
        float z = rotateMatrix[6] * vertex[0] + rotateMatrix[7] * vertex[1] + rotateMatrix[8] * vertex[2];

        vertex[0] = x;
        vertex[1] = y;
        vertex[2] = z;
    }
}

关于c++ - 纯 C 语言中的 glRotatef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27768072/

相关文章:

c++ - 如何枚举 vfs c 或 c++ 目录中的所有文件?

java - JMenus导致JOGL GLCanvas Canvas 闪烁

android - 适用于 Android 的 ffmpeg : neon build has text relocations

c++ - 矩阵类运算符重载、析构问题

c++ - 按下了什么键?键盘 Hook

client - 为什么我无法读取服务器文件中的多个字符串?

c - 找到数组中最常用的字符?

opengl - 如何可视化生成的 RNA 二级结构

c++ - C/C++ 矩阵乘法顺序

c++ - 编译 Eliza 聊天机器人 C++ 时出现问题 LNK2019