问题
I'm currently using glDrawElements to render using multiple VBOs (vertex, color, texture, and index). I've found that very few vertices are shared, so I'd like to switch to glDrawArrays, and a single interleaved VBO.
I've been unable to find a clear example of 1) creating an interleaved VBO and adding a quad or tri to it (vert, color, texture), and 2) doing whatever is needed to draw it using glDrawArrays. What is the code for these two steps?
回答1:
Off the top of my head:
//init
glBindBuffer(GL_ARRAY_BUFFER, new_array);
GLfloat data[] = {
0.f, 0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 100.f, 0.f, 1.f,
0.f, 100.f, 100.f, 1.f, 1.f,
0.f, 100.f, 100.f, 1.f, 1.f,
0.f, 100.f, 0.f, 1.f, 0.f,
0.f, 0.f, 0.f, 0.f, 0.f,
};
glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);
// draw
glBindBuffer(GL_ARRAY_BUFFER, new_array);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 5*sizeof(GLfloat), NULL);
glClientActiveTexture(GL_TEXTURE0);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 5*sizeof(GLfloat), ((char*)NULL)+3*sizeof(GLfloat) );
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
There is nothing particularly magic in this code. Just watch how:
- The data from the
data
array gets loaded: as is, all contiguous - the stride for the various attributes is set to 5*sizeof(GLfloat), as this is what is in data: 3 floats for position and 2 for texcoord. Side note, you usually want this to be a power of 2, unlike here.
- the offset is computed from the start of the array. so since we store vertex first, the offset for vertex is 0. texcoord is stored after 3 floats of position data, so its offset is 3*sizeof(GLfloat).
I did not include color in there for a reason: they typically are stored as UNORMs, which makes for a messier initialization code. You need to store both GLfloat and GLubyte in the same memory chunk. At that point, structs can help if you want to do it in code, but it largely depends on where your data is ultimately coming from.
来源:https://stackoverflow.com/questions/5906742/drawing-interleaved-vbo-with-gldrawarrays