Multitexture with GLSL

From OpenGL.org
Jump to: navigation, search

Many users want to have some form of multitexturing. They may want texture #1 and texture #2 to be multiplied together, or added together, or blended together based on some kind of factor like an alpha value.
This shows GLSL code for doing blending between 2 texture based on a alpha value.
Why would you use GLSL if it requires a GL 2.0 minimum?
1. Because GL 2.0 has been available for a few years now
2. Most everyone has a GL 2.0 capable video card in their system (Geforce FX and up, Radeon 9500 and up)
3. The fixed function pipeline is eliminated from GPU for a long time now. It is better to just use shaders and to write modern code.

If Texture0 is your 1st texture.
If Texture1 is your 2nd texture.
If Texture2 is your alpha mask source.
The GLSL code for the FS would look like this

  uniform sampler2D Texture0;
  uniform sampler2D Texture1;
  uniform sampler2D Texture2;   //Mask
  varying vec2 TexCoord0;
  //-------------------
  void main()
  {  
     vec4 texel0, texel1, texel2, resultColor;
     //-------------------
     texel0 = texture2D(Texture0, TexCoord0);
     texel1 = texture2D(Texture1, TexCoord0);
     texel2 = texture2D(Texture2, TexCoord0);
     //-------------------
     resultColor = mix(texel0, texel1, texel2.a);
     gl_FragColor = resultColor;
  }


If Texture0 is your 1st texture. This is also the source of the alpha mask.
If Texture1 is your 2nd texture.

  uniform sampler2D Texture0;
  uniform sampler2D Texture1;
  varying vec2 TexCoord0;
  //-------------------
  void main()
  {  
     vec4 texel0, texel1, resultColor;
     //-------------------
     texel0 = texture2D(Texture0, TexCoord0);
     texel1 = texture2D(Texture1, TexCoord0);
     //-------------------
     resultColor = mix(texel0, texel1, texel0.a);
     gl_FragColor = resultColor;
  }