OpenGL 3.3 multitexture: GL_TEXTURE1 and following are always black (Only GL_TEXTURE0 works fine)

Tobias Schwandt picture Tobias Schwandt · Mar 13, 2013 · Viewed 7k times · Source

Every texture after GL_TEXTURE0 (texture on slot 0) is black.

Fragment shader (sample code to check different textures by changing weights):

#version 330

uniform sampler2D g_ColorTex;
uniform sampler2D g_DepthTex;
uniform sampler2D g_DofNearBlurTex;
uniform sampler2D g_DofDownBlurTex;

in vec4 g_VertexPosition;
in vec2 g_ScreenCoords;

layout (location = 0) out vec4  FragColor;

void main() 
{
    // Changing weights to check textures
    FragColor  = 1.00001f * vec4(texture(g_ColorTex      , g_ScreenCoords).rgb, 1.0f);
    FragColor += 0.00001f * vec4(texture(g_DepthTex      , g_ScreenCoords).rgb, 1.0f);
    FragColor += 0.00001f * vec4(texture(g_DofNearBlurTex, g_ScreenCoords).rgb, 1.0f);
    FragColor += 0.00001f * vec4(texture(g_DofDownBlurTex, g_ScreenCoords).rgb, 1.0f);
}

I upload textures like that (excerpt!):

::glUseProgram(ShaderHandle);

unsigned int TextureIndex;


TextureIndex = ::glGetUniformLocation(ShaderHandle, "g_ColorTex");

::glUniform1i(TextureIndex, 0);

::glActiveTexture(GL_TEXTURE0);

::glBindTexture(GL_TEXTURE_2D, TextureHandle);

::glBindSampler(GL_TEXTURE0, SamplerHandle);


TextureIndex = ::glGetUniformLocation(ShaderHandle, "g_DepthTex");

::glUniform1i(TextureIndex, 1);

::glActiveTexture(GL_TEXTURE1);

::glBindTexture(GL_TEXTURE_2D, TextureHandle);

::glBindSampler(GL_TEXTURE1, SamplerHandle);


TextureIndex = ::glGetUniformLocation(ShaderHandle, "g_DofNearBlurTex");

::glUniform1i(TextureIndex, 2);

::glActiveTexture(GL_TEXTURE2);

::glBindTexture(GL_TEXTURE_2D, TextureHandle);

::glBindSampler(GL_TEXTURE2, SamplerHandle);


TextureIndex = ::glGetUniformLocation(ShaderHandle, "g_DofDownBlurTex");

::glUniform1i(TextureIndex, 3);

::glActiveTexture(GL_TEXTURE3);

::glBindTexture(GL_TEXTURE_2D, TextureHandle);

::glBindSampler(GL_TEXTURE3, SamplerHandle);

//...

::glDrawElements(GL_TRIANGLES, Mesh->m_Indices.size() * 3, GL_UNSIGNED_INT, 0);

I tried to change texture slots and upload different textures, but I always get a black screen until I use textures on GL_TEXTURE0.

Answer

Nicol Bolas picture Nicol Bolas · Mar 14, 2013
::glBindSampler(GL_TEXTURE0, SamplerHandle);

That's wrong. glBindSampler takes the texture image unit index, not an enum. That should be 0, not GL_TEXTURE0.

The best way to handle this is as follows:

glUniform1i(TextureIndex, index);
glActiveTexture(GL_TEXTURE0 + index);
glBindTexture(GL_TEXTURE_2D, TextureHandle);
glBindSampler(index, SamplerHandle);