Blending

Blending produces the effect of transparency by combining the color of a transparent object with the color of whatever is behind it. In OpenGL documentation, these colors are referred to as the source and destination colors (the reason for the term destination will be seen later).

Many different formulas for combining the two colors can be used. The formula is defined by the glBlendFunc() function. The most common blending formula is:

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

This means that if a transparent object with color (R1, G1, B1) and alpha A1 is in front of another object with color (R2, G2, B2), the final, blended color is computed by:

R = A1 * R1 + (1-A1) * R2
G = A1 * G1 + (1-A1) * G2
B = A1 * B1 + (1-A1) * B2

For example, if the alpha is 0.25 (25% opaque):

R = 0.25 * R1 + 0.75 * R2
G = 0.25 * G1 + 0.75 * G2
B = 0.25 * B1 + 0.75 * B2

The combination of A1 and (1-A1) guarantees that the resulting color will be in the range 0 to 1 (assuming the input colors are in that range, which OpenGL takes care of).

[Note: some researchers suggest, for good mathematical reasons, that we should use a different formula, with the alpha already multiplied into the source color. But in typical OpenGL programming we don't do this - we still do it the wrong way.]

Using blending

Using blending for transparency involves the following steps:

Enable blending
glEnable(GL_BLEND);
 
Set the blending function
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 
Assign an alpha < 1
glColor4f(1.0, 0.0, 0.0, 0.5);
or
GLfloat red[4] = { 1, 0, 0, 0.5 };
glMaterialfv(GL_FRONT, GL_DIFFUSE, red);

Example: transparent.c





next