简体   繁体   中英

GL_TRIANGLES instead of GL_QUADS

I want to modify the code for generating 3D sphere, so it uses triangles for drawing instead of quads. The problem is, as usual, that I get some error -- "vector iterator not incrementable". What's wrong with it?

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;

    }
}

Looks like your triangle-generator-version of the loop does (sectors-1) times (rings-1) iterations, each one increasing i six times, but you have resized the vector i iterates through to just (rings * sectors * 4) , which was enough to the quad-generator-version of the loop.


Assuming the triangle version was ok, this adjust shall fix it:

indices.resize(rings * sectors * 6)

This kind of oversight generally arises when you code without drinking enough coffee. Or too much of it (graph showing the hyperbola boundaries when your code will actually fail, (mapping rings and sectors numbers to x and y) due to the fact that you are allocating more space then needed for the iterations).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM