Search code examples
glslfragment-shader

Access GLSL vec4 components by ivec4 indices


In GLSL I can do

vec4 data = vec4(1.0, 2.0, 3.0, 4.0);
gl_FragColor = data.xxyy;

But can I somehow do?

vec4 data = vec4(1.0, 2.0, 3.0, 4.0);
ivec4 indices = ivec4(0, 0, 1, 1);
gl_FragColor = data[indices];

Solution

  • No you cannot. Actually you want to Swizzle something like data.indices.

    You have to construct a vec4:

    gl_FragColor = 
        vec4(data[indices[0]], data[indices[1]], data[indices[2]], data[indices[3]]);
    

    Alternatively you can use matrix multiplication:

    indices = mat4(vec4(1,1,0,0), vec4(0,0,1,1), vec4(0,0,0,0), vec4(0,0,0,0));
    gl_FragColor = indices * data;