如何频繁更新顶点缓冲区数据(每帧)opengl

问题描述:

我在屏幕上显示了一个简单的二维三角形,我想每帧更新颜色缓冲区数据,所以三角形的颜色不断变化,但我不知道如何有效地更新数据.

I have a simple 2d triangle displayed on the screen, I want to update the color buffer data every frame, so the color of the triangle changes constantly, but im not sure how to update the data efficiently.

这是颜色缓冲区的代码:

this is the code for the color buffer:

GLfloat colourVert[] = {
        0.0f, 1.0f, 0.0f,
        1.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 1.0f
    };



GLuint colourBuffer;
glGenBuffers(1, &colourBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colourBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(colourVert), colourVert, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);

我需要在这些行中添加一些东西还是需要修改着色器,有人可以解释一下吗,谢谢您的帮助.

Do I need to add something in these lines or do I need to modify the shaders, can someone explain please, thanks for any help.

你绝对不应该每帧都生成一个新的缓冲区.只需重用已有的.也可以只设置一次属性指针,因为它们存储在 VAO 中.实际需要的仅有两行是 glBindBufferglBufferData(或者更好地使用 glBufferSubData,因为这将重用分配的内存而不是分配新的内存段).

You should definitely not generate a new buffer every frame. Just reuse the already existing one. Also setting up attribute pointers can also be done just once since they are stored in the VAO. The only two lines actually necessary are glBindBuffer and glBufferData (or even better use glBufferSubData since this will reuse the allocated memory instead of allocating a new memory segment).

请注意,此答案仅适用于 OpenGL 3.3 Core(及更新版本)和 OpenGL-ES 3.0(及更新版本).对于不支持/不需要 VAO 的 OpenGL 版本,可能还必须在每一帧中进行属性设置.

Note, that this answer only applies to OpenGL 3.3 Core (and newer) and OpenGL-ES 3.0 (and newer). For OpenGL versions that don't support/require VAOs, the attribute setup might also have to happen in every frame.