1
\$\begingroup\$

I am using an array buffer for colors data. If I want to load different colors for the current mesh in real time what is the correct way to do it. At the moment I am doing:

glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER, SIZE, colorsData, GL_STATIC_DRAW);
glEnableVertexAttribArray(shader->attrib("color"));
glVertexAttribPointer(shader->attrib("color"), 3, GL_FLOAT, GL_TRUE, 0, NULL);
glBindBuffer(GL_ARRAY_BUFFER, 0);

It works, but I am not sure if this is good and efficient way to do it. What happens to the previous data ? Does it write on top of it ?

Do I need to call :

glDeleteBuffers(1, colorBuffer);
glGenBuffers(1, colorBuffer);

before transfering the new data into the buffer ?

\$\endgroup\$
0
4
\$\begingroup\$

glBufferData() overwrites the previous data, and is generally what you should use to load new data into a GL buffer. Conceptually it is similar to overwriting data in an array.

glDeleteBuffers() and glGenBuffers() destroy and recreate a buffer. Conceptually they are similar to free() and malloc(). If you're just writing new data into the buffer, destroying it and recreating it is not only overkill, but will almost certainly bring a performance penalty.

But, above all, what is the problem you're experiencing?

\$\endgroup\$
0
1
\$\begingroup\$

You don't need to rebind the VAO or reset the vertex attributes. You can just overwrite the data in place:

glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER, SIZE, colorsData, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

When glDraw* is called the new data will be used.

I use GL_DYNAMIC_DRAW because you would change the data often whereas GL_STATIC_DRAW would indicate that you won't change it often. It really doesn't make a difference but allows the driver to optimize differently.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.