Search code examples
openglgraphicsshader

OpenGL multiple Sampler2D (array) examples?


I find it surprisingly frustrating that it is so difficult to find examples of sampler2d arrays such as

uniform sampler2D myTextureSampler[5];

How would one store the uniform location of this?:

gl.GetUniformLocation(program, "myTextureSampler")

Would one simply use:

gl.GetUniformLocation(program, "myTextureSampler[0]")
gl.GetUniformLocation(program2, "myTextureSampler[2]")

How would one go about using multiple textures like this:

gl.BindTexture(gl.TEXTURE_2D, 1)
gl.BindTexture(gl.TEXTURE_2D, 2)

etc..

gl.ActiveTexture(gl.TEXTURE0)
gl.ActiveTexture(gl.TEXTURE1)

etc..

Note: this code is not pure c++ opengl. Just looking for the basic concept on how it would be done.

A simple example of passing, getting uniform location for a sampler2d array would be great. Does anyone have experience with this stuff?


Solution

  • I presume it's the same as all other shader array accesses and that:

    glGetUniformLocation(program, "myTextureSampler[0]");
    

    will work.

    To use multiple textures you should set the slot which you want to put your texture in to active first:

    glActiveTexture(GL_TEXTURE0);
    

    and then you can bind your texture:

    glBindTexture(GL_TEXTURE_2D, texture.handle);
    

    The second parameter is the handle you got from glGenTextures().

    Then you match the sampler2D with the appropriate texture by calling:

    glUniform1i(location, 0);
    

    The first parameter is the location you got back from calling glGetUniformLocation(). The second parameter is the active texture slot (GL_TEXTURE0 in this case).