Cube with Indices

I decided to turn my square into a cube. I figured I would only need 8 vertices, since a cube has that many corners, and I would just use 36 indices.

float vertices[] = 
    {
        // positions      // texture coords

        //front
        0.2f, 0.2f, 0.0f, 1.0f, 1.0f,    // top right
        0.2f, -0.2f, 0.0f, 1.0f, 0.0f,   // bottom right
        -0.2f, -0.2f, 0.0f, 0.0f, 0.0f,  // bottom left
        -0.2f, 0.2f, 0.0f, 0.0f, 1.0f,   // top left 

        //back
        0.2f, 0.2f, -0.4f, 1.0f, 1.0f,   // top right
        0.2f, -0.2f, -0.4f, 1.0f, 0.0f,  // bottom right
        -0.2f, -0.2f, -0.4f, 0.0f, 0.0f, // bottom left
        -0.2f, 0.2f, -0.4f, 0.0f, 1.0f,  // top left 
    };

    unsigned int indices[] = 
    {
       // front
       0, 1, 3, 
       1, 2, 3,  
       // back
       4, 5, 7,
       5, 6, 7,
       // right
       0, 1, 4,
       1, 4, 5,
       // left
       2, 3, 7,
       2, 6, 7,
       // top
       0, 3, 4,
       3, 4, 7,
       // bottom
       1, 2, 5,
       2, 5, 6
    };

However, this only drew the front and back textures correctly, the other 4 faces were drawn but not mapped the right way. I found a tutorial on how to do it correctly and it involved having 24 vertices, which I have now implemented to get the desired result.

My question is why do I have to specify 4 for each face, when they are sharing the same 8, 3 times each?

They aren’t. There are only 8 positions, but there are more than 8 distinct combinations of position and texture coordinates. Vertices can only be shared if they share all attributes, not just position.

If you’re mapping the entirety of a texture to all 6 faces, you can set the wrap mode to GL_REPEAT (the initial value) and assign texture coordinates based upon a net, which only requires 14 distinct vertices, e.g.:

static const GLuint indices[] = {
     0, 1, 5,  5, 1, 6,
     1, 2, 6,  6, 2, 7,
     2, 3, 7,  7, 3, 8,
     3, 4, 8,  8, 4, 9,
    10,11, 0,  0,11, 1,
     5, 6,12, 12, 6,13
};

static const GLfloat vertices[] = {
    -1,-1,-1, 0, 0,
     1,-1,-1, 1, 0,
     1, 1,-1, 2, 0,
    -1, 1,-1, 3, 0,
    -1,-1,-1, 4, 0,
    
    -1,-1, 1, 0, 1,
     1,-1, 1, 1, 1,
     1, 1, 1, 2, 1,
    -1, 1, 1, 3, 1,
    -1,-1, 1, 4, 1,
    
    -1, 1,-1, 0,-1,
     1, 1,-1, 1,-1,
    
    -1, 1, 1, 0, 2,
     1, 1, 1, 1, 2
};
1 Like

If each vertex only has one tex_coord and three textures meet in one vertex. You won’t be able to make it all fit properly.

1 Like