OpenGL Shading Language Tutorials

Tutorial 7: Color Key


If you ever programmed in DirectX you probably heard of color keys. Color keying is a very simple method: A certain color (people often used color #FF00FF) is declared transparent.

Example:

In this example you would just see the circle when it is rendered, the pink will be removed.

Solution:
In fragment shaders you can use 'discard' and the current fragment is ignored, the program would look like this:

 

Fragment Shader Source

uniform sampler2D myTexture;


#define epsilon 0.0001
void main (void)
{
vec4 value = texture2D(myTexture, vec2(gl_TexCoord[0]));
if (value[0] > 1.0-epsilon) && (value[2] > 1.0-epsilon)) discard; gl_FragColor = value; }
 

Vertex Shader Source

void main(void)
{
gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
 

Exercise:

Using colorkeying this way is very problematic. Aliasing effects would make some pink dots still visible. It is better to use an alpha channel for transparency. Implement a vertex and a fragment shader for color keying with alpha channel.


Result: Using Alpha Channel for transparency

Go to Tutorial 8


Author: Martin Christen, christen@clockworkcoders.com
(source code is included in Tutorial Version 0.2 and higher)

 

 

© 2003 by Martin Christen. All Rights Reserved.
christen@clockworkcoders.com