Question:
I have an array of sampler2D that looks like so:uniform sampler2D u_Textures[2];
. I want to be able to render more textures(in this case 2) in the same drawcall. In my fragment shader, if I set the color output value to somethiung like red, it does show me 2 red squares witch leads me to belive I did something wrong when binding the textures.
My code:Answer:
You cannot use a fragment shader input variable to index an array of texture samplers. You have to use asampler2DArray
(GL_TEXTURE_2D_ARRAY
) instead of an array of sampler2D
(GL_TEXTURE_2D
).int index = int(v_texIndex); vec4 texColor = texture(u_Textures[index], v_TexCoord);
is undefined behavior because
v_texIndex
is a fragment shader input variable and therefore not a dynamically uniform expression. See GLSL 4.60 Specification – 4.1.7. Opaque Types[…] Texture-combined sampler types are opaque types, […]. When aggregated into arrays within a shader, they can only be indexed with a dynamically uniform integral expression, otherwise results are undefined.
Example using
sampler2DArray
:texture
is overloaded for all sampler types. The texture coordinates and texture layer need not to dynamically uniform, but the index into a sampler array has to be dynamically uniform.If you have better answer, please add a comment about this, thank you!