2

If I have a mesh (such as a cube with 6 faces, each consisting individually of 4 vertices, totaling 24 vertices) and I want to apply a different texture to each face, how would I do this? Currently I draw the entire mesh (all 6 faces of a cube) at once using glDrawElements(), supplying all of the indices into one buffer. I cannot see a way to apply a texture to a subset of the indices when drawing. Would I have to split up the indices, drawing each face one-by-one, rebinding textures between each face, or is there a more eloquent solution?

genpfault
  • 51,148
  • 11
  • 85
  • 139
shpen
  • 53
  • 5

2 Answers2

8

Yes, you will have to render each face differently (split it up accordingly and bind the texture for each face). It's not elegant and it's not pretty, but it's fairly simple if you have your indices in their own element buffer (a GL buffer, not a ShortBuffer or something like that). You can just specify the offset into the buffer using glDrawElements and the number of triangles to draw for each face. Then it goes something like this (pseudocode):

static class IndexRange
{
    public int offset
    public int numIndices
}

// ... later, down the hall and to the left ...

int faceTextures[] = {tex0, tex1, tex2, ...}
IndexRange faceIndices[] = {face0, face1, face2, ...}

// setup buffers and all that jazz

for (index = 0; index < numFaces; ++index)
{
    IndexRange face = faceIndices[index]
    int texture = faceTextures[index]

    glBindTexture(GL_TEXTURE_2D, texture)
    glDrawElements(GL_TRIANGLES, face.numIndices, GL_UNSIGNED_SHORT, face.offset)
}

If you're using a ShortBuffer or something like that, I'm not entirely sure how you'd go about doing that, but I imagine you could probably slice it as needed and get the necessary buffers for each differently-textured face. Either way, the process remains relatively the same: split up the mesh and for each face, bind the texture and draw only those indices corresponding to that face.

  • That's the way to go. One way to go using Java's buffers is to modify the buffers during draw time. However, I usually use VBOs in order to easily set the offset for the vertices and I skip using regular vertex arrays since almost every Android phone supports VBOs nowadays. – Wroclai Jul 23 '11 at 10:48
0

You have to use few texture units. Check the documentation of function glClientActiveTexture() in the specification. Also see this question.

UPDATE: You might also consider using libgdx, a very nice OpenGL ES wrapper (and more).

Community
  • 1
  • 1
kar
  • 741
  • 6
  • 16
  • 1
    I really don't get the impression that this answer addresses the question. `glClientActiveTexture` doesn't really have that much to do with this from what I can see, and you haven't explained the relevance of the question you've linked. Telling him/her to just use a "very nice ... wrapper" also doesn't explain why the asker ought to use the wrapper or how it addresses the question. –  Jul 22 '11 at 21:19