8
votes

I want to make transparency on my 32bit bitmap texture using GLSL. My fragment shader looks like this:

#version 120
uniform sampler2D myTexture;
varying vec2 TexCoord;

void main(void)
{
    if(texture2D(myTexture, TexCoord).a != 1.0f)
    {
        discard;
    }
    gl_FragColor = texture2D(myTexture, TexCoord);
}

But that makes transparent only the pixels where alpha is equal 0 and I want to maintain the fade from the texture. For example in this picture the first image is the texture, the second is the texture mask and the third is the desired result:

Example

The texture and the texture mask are in one 32bit bitmap.

Does anyone know, how to achieve this using GLSL?

1
I know, but that's the immediate mode only and it's really inaccurate, I want to do it with shaders. The blending also makes some annoying transparent border around the mask.ProXicT
Blending does work well with shaders and modern OpengGL.dari

1 Answers

10
votes

You need to enable GL_BLEND, and the alpha output of your fragment shader will be used to blend the fragment output with the framebuffer.

glEnable(GL_BLEND);
glBlendFunc(..., ...);

glDraw????(...);

// You don't have to do it here, but GL_BLEND will remain enabled
// until you disable it again.
glDisable(GL_BLEND);

If you use premultiplied alpha,

glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

If you use non-premultiplied alpha,

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

The fragment shader can't do the blending because it doesn't have access to the framebuffer.