Using an offset with VBOs in OpenGL

hidayat picture hidayat · Feb 24, 2012 · Viewed 12.4k times · Source

What I want to do is to render a mesh multiple times with the same vbo but with different offset. Example:

//Load VBO
glGenBuffers(2, &bufferObjects[0]);
glBindBuffer(GL_ARRAY_BUFFER, bufferObjects[VERTEX_DATA]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*size(vertices)*3, &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferObjects[INDEX_DATA]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int)*size(indices), &indices[0], GL_STATIC_DRAW);

//Render VBO
glBindBuffer(GL_ARRAY_BUFFER, bufferObjects[VERTEX_DATA]);
glVertexPointer(3, GL_FLOAT, 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferObjects[INDEX_DATA]);
glDrawElements(renderFlag, nrIndices, GL_UNSIGNED_INT, 0);

If I draw the hole mesh at the same time there is no problem, but is it possible to draw the same mesh with a different start index, like this:

glDrawElements(renderFlag, 20, GL_UNSIGNED_INT, "WHAT TO WRITE HERE"?);

Answer

Nicol Bolas picture Nicol Bolas · Feb 24, 2012

What do you mean by "start index"? You could mean one of two things:

Start at a different position in the buffer object

Well, just do that. glDrawElements takes an offset into the buffer object for where it starts to pull indices from. So add a value to that.

glDrawElements(renderFlag, 20, GL_UNSIGNED_INT, (void*)(ixStart * sizeof(GLuint)));

Offset the indices you fetch from the buffer

This means that you want to draw the same range of indices, but you want to apply an offset to those index values themselves. So if your index buffer looks like this: (1, 4, 2, 0, 5, ...), and you apply an offset of 20, then it will fetch these indices: (21, 24, 22, 20, 25, ...).

This is done with glDrawElementsBaseVertex. It looks something like this:

glDrawElementsBaseVertex(renderFlag, 20, GL_UNSIGNED_INT, 0, offset);