GL_TRIANGLES而不是GL_QUADS

时间:2014-04-29 22:22:17

标签: c++ opengl

我想修改生成3D球体的代码,因此它使用三角形来绘制而不是四边形。像往常一样,问题是我得到了一些错误 - “矢量迭代器不可递增”。怎么了?

SolidSphere(float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1.0f / (float)(rings-1);
    float const S = 1.0f / (float)(sectors-1);
    int r, s;

    vertices.resize(rings * sectors * 3);
    normals.resize(rings * sectors * 3);
    texcoords.resize(rings * sectors * 2);
    std::vector<GLfloat>::iterator v = vertices.begin();
    std::vector<GLfloat>::iterator n = normals.begin();
    std::vector<GLfloat>::iterator t = texcoords.begin();
    for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
            float const x = sinf(M_PI * r * R) * cosf(2 * M_PI * s * S);
            float const y = sinf(-M_PI_2 + M_PI * r * R );                
            float const z = sinf(2.0f * M_PI * s * S) * sinf( M_PI * r * R );

            *t++ = s*S;
            *t++ = r*R;

            *v++ = x * radius;
            *v++ = y * radius;
            *v++ = z * radius;

            *n++ = x;
            *n++ = y;
            *n++ = z;
    }

    indices.resize(rings * sectors * 4);
    std::vector<GLushort>::iterator i = indices.begin();
    for(r = 0; r < rings-1; r++) for(s = 0; s < sectors-1; s++) {
        /* triangles -- not working!
        *i++ = r * sectors + s;
        *i++ = (r + 1) * sectors + (s + 1);
        *i++ = r * sectors + (s + 1);

        *i++ = r * sectors + s;
        *i++ = (r + 1) * sectors + s;
        *i++ = (r + 1) * sectors + (s + 1); */

        /* quads */
        *i++ = r * sectors + s;
        *i++ = r * sectors + (s+1);
        *i++ = (r+1) * sectors + (s+1);
        *i++ = (r+1) * sectors + s;

    }
}

1 个答案:

答案 0 :(得分:1)

看起来你的三角形生成器版本的循环执行(sectors-1)(rings-1)次迭代,每次迭代增加i六次,但你已经调整了向量i的大小迭代到(rings * sectors * 4),这对于循环的四生成器版本来说已经足够了。


假设三角形版本没问题,这个调整将解决它:

indices.resize(rings * sectors * 6)

当你在没有喝足够咖啡的情况下进行编码时,通常会出现这种疏忽。 Or too much of it(图表显示代码实际失败时的双曲线边界,(将环和扇区数映射到x和y),因为您正在为迭代分配更多空间)。