openglvaoindex-buffer

Draw cylinder lateral with glDrawElements, Index Buffer and enabled GL_CULL_FACE


I need this: What cylinder I need

And I HAVE TO use glDrawElements and this: glEnable(GL_CULL_FACE).

What I tried:

...

glm::vec3   CMyApp::GetCylinderUV(float u, float v)
{
    u *= 2* 3.1415f;
    float r = 1;

    return glm::vec3(r * cosf(u), 2 * v, r * sinf(u));
}

...

glEnable(GL_CULL_FACE);

...

Vertex vert[(N+1)*(M+1)];
for (int i=0; i<=N; ++i)
    for (int j=0; j<=M; ++j)
    {
        float u = i/(float)N;
        float v = j/(float)M;

        vert[i + j*(N + 1)].p = GetCylinderUV(u, v);
        vert[i + j*(N+1)].c = glm::normalize( vert[i + j*(N+1)].p );
    }

...

GLushort indices[3*2*(N)*(M)];
for (int i=0; i<N; ++i)
    for (int j=0; j<M; ++j)
    {
        //      (i,j+1)
        //        o-----o(i+1,j+1)
        //        |\    |           a = p(u_i, v_i)
        //        | \   |           b = p(u_{i+1}, v_i)
        //        |  \  |           c = p(u_i, v_{i+1})
        //        |   \ |           d = p(u_{i+1}, v_{i+1})
        //        |    \|
        //  (i,j) o-----o(i+1, j)
        indices[6*i + j*3*2*(N) + 0] = (i)      + (j)*  (N+1);
        indices[6*i + j*3*2*(N) + 1] = (i+1)    + (j)*  (N+1);
        indices[6*i + j*3*2*(N) + 2] = (i)      + (j+1)*(N+1);
        indices[6*i + j*3*2*(N) + 3] = (i+1)    + (j)*  (N+1);
        indices[6*i + j*3*2*(N) + 4] = (i+1)    + (j+1)*(N+1);
        indices[6*i + j*3*2*(N) + 5] = (i)      + (j+1)*(N+1);
    }

glDrawElements( GL_TRIANGLES,
                3*2*(N)*(M),
                GL_UNSIGNED_SHORT,
                0);

And the bad result: Bad cylinder

But it can be fix with delete glEnable(GL_CULL_FACE);, but I have to use that.


Solution

  • Finally I found the answer for my question: