Search code examples
c++openglgraphicsglut

How to do texture mapping for cylinder created by GL_TRIANGLE_STRIP in OpenGL and how to taper a cylinder


I am currently trying to create a model of squidward from spongebob squarepant's house.

I have created a cyllinder out of GL_TRIANGLE_STRIPs as I am not allowed to use any predefined OpenGL models to create the shapes.

I am trying to do texture mapping for each triangle on the cylinder but the texture comes out stretched and not as it is supposed to be.

Here is my code for the cylinder

glPushMatrix();
    glTranslated(xPos, yPos, TABLETOP_Z - cubeLen);
    glScaled(cubeLen / 2, cubeLen / 2, 1.0);
        
    glBegin(GL_TRIANGLE_STRIP);
        glTexCoord3f(xPos, yPos, TABLETOP_Z);
        glTexCoord3f(xPos, yPos, TABLETOP_Z);

        for (int i = 0; i <= 32; i++) {
            double x_next = 1.0 * cos((i + 1) * 2.0 * PI/ (32 - 2.0));
            double y_next = 1.0 * sin((i + 1) * 2.0 * PI / (32 - 2.0));

            if (i % 2 == 0) {
                glTexCoord3f(x_next, y_next, TABLETOP_Z + cubeLen);
                glVertex3f(x_next, y_next, TABLETOP_Z + cubeLen);

            } else {
                glTexCoord3f(x_next, y_next, TABLETOP_Z);
                glVertex3f(x_next, y_next, TABLETOP_Z);
            }
        }

    glEnd();
    glPopMatrix();

And here is what the texture is supposed to look like: enter image description here

And here is what it looks like on the cylinder enter image description here


Solution

  • The texture coordinates are 2-dimenional and have to be in range [0.0, 1.0]:

    glBegin(GL_TRIANGLE_STRIP);
    for (int i = 0; i <= 32; i++) {
        double x_next = 1.0 * cos((i + 1) * 2.0 * PI/ (32 - 2.0));
        double y_next = 1.0 * sin((i + 1) * 2.0 * PI / (32 - 2.0));
    
        if (i % 2 == 0) {
            glTexCoord3f((float)i / 32.0f, 1.0f);
            glVertex3f(x_next, y_next, TABLETOP_Z + cubeLen);
    
        } else {
            glTexCoord3f((float)i / 32.0f, 0.0f);
            glVertex3f(x_next, y_next, TABLETOP_Z);
        }
    }
    glEnd();
    

    See How do opengl texture coordinates work?