Search code examples
opengltransparencyblending

OpenGL: Transparent texture issue


I have troubles with Texture transparency in OpenGL. As you can see in the picture below, it doesn't quite work. It's worth noting, that the black is actually the ClearColor, I use to clear the screen.

enter image description here

I use the following code to implement blending:

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

Here's my fragment shader:

#version 330 core

in vec2 tex_coords;

out vec4 color;

uniform vec4 spritecolor;
uniform sampler2D image;

void main(void)
{
    color = spritecolor * texture(image, tex_coords);
}

Here is a screenshot of the scene in wireframe mode, in case it helps with the drawn vertices:

Scene in Wireframe mode

If anything else is needed, feel free to ask, I'll add it.


Solution

  • You have to do a Transparency Sorting

    If a scene is drawn, usually the depth test (glDepthFunc) is set to GL_LESS. This causes fragments to be drawn only when they are in front of the scene so far drawn.

    To draw transparents correctly, you have to draw the opaque objects first. The transparent objects have to be drawn after, sorted by the reverse distance to the camera position.To draw transparents correctly, you have to draw the opaque objects first. The transparent objects have to be drawn after, sorted by the reverse distance to the camera position.
    Draw the transparent object first, which has the largest distance to the camera position and draw the transparent object last, which has the lowest distance to the camera position.

    See also the answers to the following questions: