OpenGL顶点阵列球体杂散顶点

时间:2013-04-18 18:45:29

标签: c++ opengl

我一直在尝试使用各种代码片段在线编写opengl中的球体,但在运行代码之后会出现一个杂散的顶点,而且我不确定我的代码错过了哪个:

enter image description here

CODE:

    float Lats = 1/(float)(longitude-1);
    float Longs = 1/(float)(latitude-1);

    int r,s;

    vector<GLfloat> vertices;
    vector<GLfloat> normals;
    vector<GLfloat> texcoords;
    vector<GLushort> indices;

    for(r = 0; r < longitude; r++)
    {
        for(s = 0; s < latitude; s++)
        {
            float const x = cos(2*M_PI * s * Longs) * sin( M_PI * r * Lats );
            float const y = sin( -M_PI_2 + M_PI * r * Lats );
            float const z = sin(2*M_PI * s * Longs) * sin( M_PI * r * Lats );

            vertices.push_back(x * getR());
            vertices.push_back(y * getR());
            vertices.push_back(z * getR());

            normals.push_back(x);
            normals.push_back(y);
            normals.push_back(z);

            texcoords.push_back(s*Lats);
            texcoords.push_back(r*Longs);
        }
    }

    for(r = 0; r < longitude; r++) 
    {
        for(s = 0; s < latitude; s++)
        {
            indices.push_back(r * latitude + s);
            indices.push_back(r * latitude + (s+1));
            indices.push_back((r+1) * latitude + (s+1));
            indices.push_back((r+1) * latitude + s);
        }
    }

谁能看到我哪里出错?

1 个答案:

答案 0 :(得分:1)

你正在计算,

float Lats = 1/(float)(longitude-1);
float Longs = 1/(float)(latitude-1);

球体的北极导致除数为0.

<强>更新

再次查看您的代码后,我认为问题可能会更加微妙。

你假设

2*M_PI/* double */ * (latitude - 1)/*int*/  * 1/(float)(latitude - 1)/*float*/ == 2*M_PI

由于浮点问题可能不正确。这适用于sin()&amp;中的所有其他表达式。 COS()

可能你正在处理精度损失。

由于它是确定性的,你甚至可以在最后手动修复它。这仍然适用。

有趣的是,你的前脸,背面颜色编码清楚地表明了问题,顶部有一个“结”