Saturday, May 8, 2010

GLSL MultiTexture CheckList

Most of the tutorials about glsl cover the GPU side of things and generally leave out the host (CPU) side of the code to your imagination.. well not exactly .. but they assume you get it right. Turns out.. its' not that straightforward afterall.. or atleast not for me. So Here is a check list you need to see for getting multi texturing (multiple uniform variables in Fragment shader) to work.

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex0id); // general texture bind call we all know and love.
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, tex1id);

glUseProgram(program); //program is the shader program you create using glCreateProgram() call.
GLint h0 = glGetUniformLocation(program, "tex0");
GLint h1 = glGetUnifromLocation(program, "tex1");
glUnifrom1i(h0, 0); //first texture sampler
glUniform1i(h1, 1); //second texture sampler.
The code for Fragment Shader corresponding to the above cpu code is as follows
uniform sampler2D tex0;
uniform sampler2D tex1;
void main()
{
gl_FragColor = texture2D(tex0, gl_TexCoord[0].st) + texture2D(tex1, gl_TexCoord[0].st);
}
So Now the check list:
  • Use glActiveTexture for each texture unit
  • Use 0, 1, .. texture unit index while assigning values to uniform values.
  • Call glUseProgram() before trying to set uniform values.
  • Bind texture with texture id for each glActiveTexture.
I know this might look silly but iv'e seen a lot of people asking for this particular problem.. and sadly.. I struggled to get this right too... and this is a post to make sure i dont' ever have to go through that pain again...

3 comments:

  1. but how do we give texture coordinates while multitexturing in GLSL ..do we need to provide texture coordinates more than one time...??

    ReplyDelete
  2. Exactly what I needed, thank you!

    ReplyDelete
  3. Thank you!
    I was feeling like an idiot for missing these sadly enough not so hard steps..

    ReplyDelete