Search code examples
c++openglattributessharedvbo

Should I use the same VBO for passing different vertex attributes? Or should I use 2?


I know the glVertexAttribPointer will use the values from the VBO that was bound when it was called. But can you buffer twice onto the same object? Would it replace what was in? Or can you clear a buffer? I don't know if this approach is correct:

glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO); // shared VBO

glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(posLoc);
glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 3*sizeof(GLfloat),(GLvoid*)0);


glBufferData(GL_ARRAY_BUFFER,  sizeof(colours),  colours, GL_STATIC_DRAW);
glEnableVertexAttribArray(colLoc);
glVertexAttribPointer(colLoc, 4, GL_FLOAT, GL_FALSE, 4*sizeof(GLfloat),(GLvoid*)0);

glBindBuffer(GL_ARRAY_VERTEX, 0);
glBindVertexArray(0);

Or if I should be using 2 VBOs for buffering the data. What would happen if you call the glBufferData function twice to the same bound vertex array object? This is the other way I would think of for doing this:

glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO1); // VBO for vertices

glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(posLoc);
glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 3*sizeof(GLfloat),(GLvoid*)0);

glBindBuffer(GL_ARRAY_BUFFER, VBO2); // VBO for colours

glBufferData(GL_ARRAY_BUFFER,  sizeof(colours),  colours, GL_STATIC_DRAW);
glEnableVertexAttribArray(colLoc);
glVertexAttribPointer(colLoc, 4, GL_FLOAT, GL_FALSE, 4*sizeof(GLfloat),(GLvoid*)0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

Solution

  • The top example won't work as the second glBufferData call will overwrite all of the buffer space in the second one. To properly do that, you have to use the stride and pointer arguments properly, so that the data is interleaved. It's easier (and cleaner imo) to just have multiple VBO's, each storing a separate set of data.