Check for invalid Sampler

Is there I can check to see if a sampler is with a valid range for example if I pass “-1” in as a parameter for a sampler would there be a way to check if its -1 and instead default to a color?

GLuint diffuse = glGetUniformLocation(program, "SamplerDiffuse");

//Unable to find texture

glUniform1i(diffuse, -1);//use default color instead

Fragment Shader:

uniform sampler2D SamplerDiffuse;

void main(){
 if(int(SamplerDiffuse) == -1){//obviously this line doesn't work this is what I basically want to do
    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
 }
 else{
    gl_FragColor = texture2D(SamplerDiffuse, gl_TexCoord[0].xy);
 }
}

If you cannot compare a sampler type variable to say “-1” (because the GLSLspec says you cannot), why don’t you use another boolean type or integer type uniform to indicate if the sampler is set correctly?

Bind the sampler uniform to a valid texture unit, but don’t bind a texture to that unit. Then use

if( textureSize( SamplerDiffuse, 0).x > 0)
   // sample texture
else
   // use default color

to check if there is a texture. At least on Nvidia cards, it will return 0 if no texture is attached. You’ll need at least GLSL 1.30 to use textureSize(). I’ve been using this with good results for a while.

I’m not sure if this will always work on all hardware, as the GLSL spec doesn’t specify what should happen if a texture is not bound. According to the OpenGL spec 2.20.4, texture size query, “If the computed texture image level is outside the range [levelbase, levelmax], the results are undefined.” may also apply to an unbound texture unit.

I’m think that rendering is supposed to fail if you have not bound a valid texture to the texture unit a sampler is associated with.

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.