noobsaibot
noobsaibot

Reputation: 377

opengl indexed drawing issue

i'm trying to render a sphere with opengl (3.0). the algorithm below computes the vertices and the according indices. all in all it works quite well, however, there seem to be a glitch in the matrix, cause i get an ugly cone inside the sphere.

enter image description here

vertices.resize(rings * segments * 3);
colors.resize(rings * segments * 3);
indices.resize(6 * rings * segments);

auto v = vertices.begin();
auto c = colors.begin();
auto i = indices.begin();

auto dTheta = M_PI / (f32)rings;
auto dPhi   = 2 * M_PI / (f32)segments;

for ( u32 ring = 0; ring < rings; ++ring ) {
    auto r0 = radius * sinf(ring * dTheta);
    auto y0 = radius * cosf(ring * dTheta);
    for ( u32 segment = 0; segment < segments; ++segment ) {
        auto x0 = r0 * sinf(segment * dPhi);
        auto z0 = r0 * cosf(segment * dPhi);

        *v++ = x0;  *c++ = color.r;
        *v++ = y0;  *c++ = color.g;
        *v++ = z0;  *c++ = color.b;

        if (ring < rings) {
            *i++ = ( (ring  ) * segments ) + segment;
            *i++ = ( (ring+1) * segments ) + segment;
            *i++ = ( (ring+1) * segments ) + segment + 1;
            *i++ = ( (ring+1) * segments ) + segment + 1;
            *i++ = ( (ring  ) * segments ) + segment + 1;
            *i++ = ( (ring  ) * segments ) + segment;
        }
    }
}

any idea what i'm missing?

Upvotes: 0

Views: 175

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474366

*i++ = ( (ring+1) * segments ) + segment + 1;
*i++ = ( (ring+1) * segments ) + segment + 1;
*i++ = ( (ring  ) * segments ) + segment + 1;

What index do you compute if segment is equal to segments - 1? Yes, you get an index from the next segment.

And if there is no next segment? Then you get an index outside of your list of points.

Your segment increment needs to wrap around to 0:

*i++ = ( (ring+1) * segments ) + (segment + 1) % segments;
*i++ = ( (ring+1) * segments ) + (segment + 1) % segments;
*i++ = ( (ring  ) * segments ) + (segment + 1) % segments;

Also, consider what happens if ring is equal to rings - 1. Same problem, but you need a different solution. Your if statement is wrong. It should be:

if((ring + 1) < rings)

Upvotes: 3

Related Questions