Search code examples
openglglsl

timing for update of uniforms in opengl


For the simple vertex shader below to render a triangle, when is it safe to update the uniform mvpMatrix from the CPU (using glUniformMatrix4fv)? Is it safe to assume that after a draw call, e.g. glDrawArrays that the uniform can be updated for the next draw? Or are there sync mechanisms to ensure that the update is not taking place mid way through the vertex shader applying the MVP matrix.

#version 330
layout (location=0) in vec3 vert
uniform mat4 mvpMatrix;

void main(void)
{
    gl_Position = mvpMatrix * vec4(vert, 1.0);
}

Solution

  • OpenGL is defined as a synchronous API. This means that everything (largely) happens "as-if" every command is executed fully and completely by the time the function call returns. As such, you can change uniforms (or any other state) as you wish without affecting any prior rendering commands.

    Now, that doesn't make it a good idea. But how bad of an idea it is depends on the kind of state in question. Changing uniform state is extremely cheap (especially compared to other state), and implementations of OpenGL kind of expect you to do so between rendering calls, so they're optimized for that circumstance. Changing the contents of storage (like the data stored in a buffer object used to provide uniform data), is going to be much more painful. So if you're using UBOs, its better to write your data to an unused piece of a buffer than to overwrite the part of a buffer being used by a prior rendering command.