简体   繁体   中英

Draw cylinder in shader based opengl

I'm looking for a good way to draw cylinder on opengl, i tried to draw multiple circles

for (GLuint m = 0; m <= segments; ++m) {
    for (GLuint n = 0; n <= segments; ++n) {
        GLfloat const t = 2 * M_PI * (float) n / (float) segments;
        //position
        points[num++] = x + sin(t) * r;
        points[num++] = .0005 * m;
        points[num++] = y + cos(t) * r;
        //color
        points[num++] = 1;
        points[num++] = 1;
        points[num++] = 1;
        //texture
        points[num++] = sin(t) * 0.5 + 0.5;
        points[num++] = cos(t) * 0.5 + 0.5;
    }
}

and on display function

GLuint pointer = 0;
for (GLuint i = 0; i <= segments; ++i) {
 glDrawArrays(GL_TRIANGLE_FAN, pointer, segments + 1);
 pointer += segments + 1;
}

I'm asking if there is a direct way to draw this cylinder

drawing many discs one on top of the other is too slow (unless you really want to draw the cylinder as slices of discs)

You should just draw the sides of the cylinder. For example a quad mesh would be

// for (GLuint m = 0; m <= segments; ++m)
float const bottom = .0005f * 0.f;
float const top    = .0005f * (segments-1.f);
for(GLuint n = 0; n <= segments; ++n)
{
    GLfloat const t0 = 2 * M_PI * (float)n / (float)segments;
    GLfloat const t1 = 2 * M_PI * (float)(n+1) / (float)segments;
    //quad vertex 0
    points[num++] = x + sin(t0) * r;
    points[num++] = bottom;
    points[num++] = y + cos(t0) * r;
    //quad vertex 1
    points[num++] = x + sin(t1) * r;
    points[num++] = bottom;
    points[num++] = y + cos(t1) * r;
    //quad vertex 2
    points[num++] = x + sin(t1) * r;
    points[num++] = top;
    points[num++] = y + cos(t1) * r;
    //quad vertex 3
    points[num++] = x + sin(t0) * r;
    points[num++] = top;
    points[num++] = y + cos(t0) * r;
}

You can add 2 disks (the bases) to close the cylinder.

You can reduce fetching vertices form memory using a vertex+index buffer. In new versions of OGL you can eliminate vertex memory read by indexing the mesh using gl_VertexID

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