How to texture a "perfect cube" drawn with triangles?

I'm trying to map a texture on a cube which is basicly a triangle strip with 8 vertices and 14 indicies:

static const GLfloat vertices[8] =
{
    -1.f,-1.f,-1.f,
    -1.f,-1.f, 1.f,
    -1.f, 1.f,-1.f,
    -1.f, 1.f, 1.f,
     1.f,-1.f,-1.f,
     1.f,-1.f, 1.f,
     1.f, 1.f,-1.f,
     1.f, 1.f, 1.f
};

static const GLubyte indices[14] =
{
    2, 0, 6, 4, 5, 0, 1, 2, 3, 6, 7, 5, 3, 1
};

As you can see it starts drawing the back with 4 indices 2, 0, 6, 4 , then the bottom with 3 indices 5, 0, 1 and then starting off with triangles only 1, 2, 3 is a triangle on the left, 3, 6, 7 is a triangle on the top, and so on...

I'm a bit lost how to map a texture on this cube. This is my texture (you get the idea):

立方体纹理

I manage to get the back textured and somehow can add something to the front, but the other 4 faces are totally messed up and I'm a bit confused how the shader deals with the triangles regarding to the texture coordinates.

The best I could achieve is this:

我的奴才立方体

You can clearly see the triangles on the sides. And these are my texture coordinates:

static const GLfloat texCoords[] = {
    0.5, 0.5,
    1.0, 0.5,
    0.5, 1.0,
    1.0, 1.0,
    0.5, 0.5,
    0.5, 1.0,
    1.0, 0.5,
    1.0, 1.0,
    // ... ?
};

But whenever I try to add more coordinates it's totally creating something different I can not explain really why. Any idea how to improve this?


The mental obstacle you're running into is assuming that your cube has only 8 vertices. Yes, there are only 8 corer positions. But each face adjacent to that corner shows a different part of the image and hence has a different texture coordinate at that corner.

Vertices are tuples of

  • position
  • texture coordinate
  • any other attribute you can come up
  • As soon as one of that attribute changes you're dealing with an entirely different vertex. Which means for you, that you're dealing with 8 corner positions, but 3 different vertices at each corner, because there are meeting faces with different texture coordinates at that corner. So you actually need 24 vertices that make up 6 different faces which share no vertices at all.

    To make things easier for you as a beginner, don't put vertex positions and texture coordinates into different arrays. Instead write it like this:

    struct vertex_pos3_tex2 {
         float x,y,z;
         float s,t;
    } cube_vertices[24] =
    {
        /* 24 vertices of position and texture coordinate */
    };
    
    链接地址: http://www.djcxy.com/p/37182.html

    上一篇: 快速体积表示,修改和多边形化

    下一篇: 如何纹理用三角形绘制的“完美立方体”?