0

I tried to implement something in glsl to do texture splatting, but the for loop is acting weird and gives different results for code that does exactly the same.

Code 1:

for(int i = 0; i < 5; ++i) {
 if(i == 1) {
  float fade = texture2D(alphaTextures[i], texCoord.st).r;
  vec4 texCol = texture2D(textures[i], texCoord.ba);
  texColor = mix(texColor, texCol, fade);
 }
}

Code 2:

for(int i = 0; i < 6; ++i) {
 if(i == 1) {
  float fade = texture2D(alphaTextures[i], texCoord.st).r;
  vec4 texCol = texture2D(textures[i], texCoord.ba);
  texColor = mix(texColor, texCol, fade);
 }
}

The if statement is just for testing purposes so that it should give the same result. The only difference is the loop condition. I really have no idea why only Code 1 gives the correct result. Here are two pictures:

Code1

Code2

The result should be like in picture 1.

2 Answers2

1

According to this answer, you can't iterate over a sampler array. The index alphaTextures[i] is invalid, you can only use alphaTextures[1].

This changes in GLSL 4.00+ (OpenGL 4.0+), where you can have a variable index, but it cannot be from a shader input/derived value.

Community
  • 1
  • 1
chronospoon
  • 510
  • 6
  • 14
0

One reason could be that Graphic processors don't like branched texture fetches.

Try this instead:

 for(int i = 0; i < 6; ++i) {
    float fade = texture2D(alphaTextures[i], texCoord.st).r;
    vec4 texCol = texture2D(textures[i], texCoord.ba);

    if(i == 1) {
       texColor = mix(texColor, texCol, fade);
    }
 }

(disclaimer) i am only guessing and this error is really weird.

Quonux
  • 2,975
  • 1
  • 24
  • 32