1
$\begingroup$

To use a texture in an OpenGL shader, I have to write the Texture Unit to be used into a uniform variable:

source.c:

// Write 0 to uniform variable
GLuint texSampler = glGetUniformLocation(program, "texSampler");
glUniform1i(texSampler, 0);

shader.glsl

uniform sampler2D texSampler;

void SomeFunction(vec2 coord)
{
    vec4 data = texture(texSampler, coord);
    // do something
}

Why can't I just select the texture unit directly into the shader source, like this?

shader.glsl

void SomeFunction(vec2 coord)
{
    vec4 data = texture(0, coord);
    // do something
}

What is the architecturial reason, that I have to use a uniform variable to pass the texture unit into the shader?

$\endgroup$

1 Answer 1

3
$\begingroup$

Why can't I just select the texture unit directly into the shader source

You can:

layout(binding = 0) uniform sampler2D texSampler;

void SomeFunction(vec2 coord)
{
    vec4 data = texture(texSampler, coord);
    // do something
}

Binding indices of course must be constant expressions.

As for why you can't just use a number directly... how would GLSL know what kind of texture you're talking about? GLSL samplers are typed, in accord with the kind of texture being accessed. This is important, as it also changes what parameters texture takes. If you're accessing a 1D texture, texture takes a single float as a texture coordinate. If you're accessing a cubemap, it takes a vec3. Etc.

This is important for many reasons. One of them being that the logic for doing the fetch is often part of the shader itself. A shadow sampler might do the conditional logic within the shader. That wouldn't be possible if the GLSL didn't specify that it was doing a comparison test.

Note that even bindless textures, where you pass an integer that represents a texture object to the shader, still requires that you convert the integer handle for the texture into a specific sampler type.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.