Search code examples
glsl

Layout specifiers for uniforms


In the vertex shader we can specify two OUT uniforms.

layout(location = 0) out float v_transparency;
layout(location = 1) out vec2  v_texcoord;

In the Fragment shader we can receive them like this.

layout(location = 0) in float v_transparency;
layout(location = 1) in vec2  v_texcoord;

The same can also be done without specifying the layout , Is there any advantage in specifying the layouts ?


Solution

  • If you link shader objects together into programs containing multiple shader stages, then the interfaces between the two programs must exactly match. That is, for every input in one stage, there must be a corresponding output in the next, and vice-versa. Otherwise, a linker error occurs.

    If you use separate programs however, this is not necessary. It is possible for a shader stage output to not be listed among the next shader stage's inputs. Inputs not filled by an output have unspecified values (and therefore this is only useful if you don't read from it); outputs not received by an input are ignored.

    However, this rule only applies to interface variables declared with layout(location = #) qualifiers. For variables that match via name (as well as input/output interface blocks), every input must go to an output and vice-versa.

    Also, for interface variables with location qualifiers, the types do not have to exactly match. If the output and input types are different vector sizes (or scalar) of the same basic type (vec2 and vec3, uvec4 and uint, but not uvec3 and ivec2), so long as the input has fewer components than the output, the match will still work. So the output can be a vec4 while the input is a vec2; the input will only get the first 2 values.

    Note that this is also a function of separate programs, not just the use of location qualifiers.