OpenGL顶点阵列球体C的问题

时间:2013-04-10 19:23:49

标签: c++ opengl

这是问题的一张照片:

enter image description here

这是线框:

wireframe

正如您从上面的图片中看到的,我有一些奇怪的图形问题,我不知道如何修复,我认为代码有些不对,尽管其他人没有遇到代码问题。

代码:

    unsigned int rings = 12, sectors = 24;

    float const R = 1./(float)(rings-1);
    float const S = 1./(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 y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

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

            *v++ = x * getR();
            *v++ = y * getR();
            *v++ = z * getR();

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

    indices.resize(rings * sectors * 4);
    std:vector<GLushort>::iterator i = indices.begin();
    for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
            *i++ = r * sectors + s;
            *i++ = r * sectors + (s+1);
            *i++ = (r+1) * sectors + (s+1);
            *i++ = (r+1) * sectors + s;
    }

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glVertexPointer(3, GL_FLOAT, 0, vertices.data());
    glNormalPointer(GL_FLOAT, 0, normals.data());
    glTexCoordPointer(2, GL_FLOAT, 0, texcoords.data());
    glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, indices.data());

代码取自(Creating a 3D sphere in Opengl using Visual C++

1 个答案:

答案 0 :(得分:4)

索引将以顶点之外的索引结束。 索引中的最后四个值将是:

*i++ = 11 * 24 + 23 = 287;
*i++ = 11 * 24 + (23 + 1) = 288;
*i++ = (11 + 1) * 24 + (23 + 1) = 312;
*i++ = (11 + 1) * 24 + 23 = 311;

但顶点只包含288个顶点。我认为为什么它适用于其他人是glDrawElements可能在某些实现中包装索引。