1
\$\begingroup\$

Rather than have two separate shaders in my OpenGL code (one for when a texture is bound, one for when none is bound) I usually go for one shader program which handles both. This is my usual fragment shader:

#version 330

uniform bool textured;
uniform sampler2D sampler;

in vec4 fColor;
in vec2 tCoord;

out vec4 final_color;

void main()
{
    vec4 texel = vec4(1.0, 1.0, 1.0, 1.0);
    if (textured)
        texel = texture(sampler, tCoord);
    final_color = fColor * texel;
}

In a modern OpenGL profile, this compiled but did not output anything but black pixels (alternatively in LWJGL legacy profile, it outputted regular colors if textured == false and textured if textured == true). I don't see any reason that this wouldn't work, but what is a method which would work for both textured and untextured fragments?

EDIT:

\$\endgroup\$
1
\$\begingroup\$

If you don't bind a texture to the slot, the result of sampling is basically undefined (though it's often vec4(0)).

To fix your issue, create a white 1x1 texture and assign it to sampler when you're using this shader without a texture.

\$\endgroup\$
  • \$\begingroup\$ Even though I only reference it if textured == true? \$\endgroup\$ – Zach Goethel Dec 26 '15 at 22:39
  • \$\begingroup\$ @ZachGoethel Ah, missed that, sorry. In that case, there could easily be a bug in the textured uniform setting code. But there could also be undefined behavior (shader compiles to mix(texel, texture(..), textured), texture returns NaN). Either way, the approach I described works without the branch and extra parameter. \$\endgroup\$ – snake5 Dec 26 '15 at 22:47
  • \$\begingroup\$ But do you have recommended changes? To set textured I use glUniform1i([location getter], 0 or 1). \$\endgroup\$ – Zach Goethel Dec 26 '15 at 22:51
  • \$\begingroup\$ @ZachGoethel There's nothing to change there. But have you actually checked that the code runs, and at the right time (after glUseProgram, before the draw call)? P.S. stackoverflow.com/a/21030831/1648140 \$\endgroup\$ – snake5 Dec 26 '15 at 22:56
  • \$\begingroup\$ I'm adding links to my main.cpp and shader.hpp, but I won't be able to add more until tomorrow afternoon. \$\endgroup\$ – Zach Goethel Dec 26 '15 at 23:00

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.