Tutorial 5 – Transparency
Now that we’ve got multiple polygons being drawn correctly we can start to experiment with some more effects, namely transparency.
Transparency allows certain polygons to be rendered through others; Think windows, gasses, lens flares etc.
Effects & Algorithms
Transparency is not as straightforward as you might first think (though it is very easy to implement so don’t worry about that!). The first thing that should be considered is how “see-through” an object is. In computer graphics this property is referred to as alpha. The higher the alpha value the more opaque an object is. To set this value we use glColor just as before, except this time we add a fourth value:
glColor4f(r, g, b, alpha);
The next thing to think about is how different objects interact with light. In real life there are transparent/translucent objects such as windows, bottles etc. These objects allow light to pass through them but remove certain wavelengths; e.g. A green bottle will filter out most wavelengths of light except for green, making objects behind the bottle appear to be green.
There are other objects that are translucent in a different way. Think of a flame. Look through a flame and any objects you see behind it will appear brighter than usual. This is because the flame, rather than removing light, adds it to any images passing through it.
To cater for these effects, OpenGL provides a mechanism to set the alpha blending algorithms used to create transparency:
glBlendFunc(source factor, destination factor);
The source and destination values choose how the colour from the object in the background is mixed with the colour of the translucent object. Below is an image to demonstrate how these algorithms can be used:
The circles on the left are rendered using the arguments (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), the ones on the right are rendered with (GL_SRC_ALPHA, GL_ONE).
Once you’ve set up the colour of a polygon and told OpenGL how to blend different fragments, all that’s left to do is turn on transparency:
And that’s all you need to do to let your OpenGL programs render transparency.
This is the one final caveat of transparency. In OpenGL, if you are using depth testing, you must render your objects from the back of the scene to the front, otherwise you will get some unwanted artifacts. In the sample code below, try switching the order in which the quad and the triangle are rendered and see what a difference it makes!
If you render your scene correctly however, these are the kind of effects that you should see: