Search code examples
openglglslvertex-shader

Vertex attribute bindings from multiple VAOs in one shader


Suppose I have a vertex shader with the following vertex attributes:

layout(location = 0) in vec4 foo1;
layout(location = 1) in vec4 bar1;
layout(location = 2) in vec4 foo2;
layout(location = 3) in vec4 bar2;

And two VAOs which were initialized like this:

glBindVertexArray(vao1);
...
glVertexAttribPointer(0, ...);
glVertexAttribPointer(1, ...);

glBindVertexArray(vao2);
...
glVertexAttribPointer(2, ...);
glVertexAttribPointer(3, ...);

Then, if I bind them successively:

glBindVertexArray(vao1);
glBindVertexArray(vao2);
glDrawArrays(...);

what data will I get from foo1 and bar1 vertex attributes? Can I expect their values to be taken from buffer pointed by vao1, or will their state be undefined?


Solution

  • OpenGL objects are not like macros (except for display lists, which actually are like macros). They store state. When you bind a new object to the same target as a previous object, all of the governed state is taken up by the new object; the old one is unbound from that binding point.

    Each VAO contains state for all of the available vertex attributes. The attributes default to being disabled. As such, if you only enable attributes 2 and 3 in a VAO, then when you bind that VAO, only attributes 2 and 3 will be enabled.