Alpha Mapping
In most of our renderers, we've assumed that any fragment that arrives in the fragment shader needs a color. However, we also have the option of throwing out a fragment using GLSL's discard
command. Suppose we have a texture that has an alpha channel. We could look up a fragment's opacity in the texture and then discard any fragment whose opacity was below some threshold.
A texture that is used to throw out some fragments and retain others is called an alpha map or a mask. The underlying geometry to which an alpha map is applied is often a simple triangle or quadrilateral, while the fragments that survive the alpha test form an intricate shape that would be too costly to express through vertices.
Consider this snowflake, which is modeled with just four vertices and an alpha map:
The quadrilateral bearing the texture is rendered in the usual way. The fragment shader looks up the color in the texture and discards the fragment if the alpha value is less than 0.5:
uniform sampler2D alphamap;
in vec2 mixTexPosition;
out vec4 fragmentColor;
void main() {
vec4 alpha = texture(alphamap, mixTexPosition).a;
if (alpha < 0.5) {
discard;
} else {
fragmentColor = vec4(1.0);
}
}
uniform sampler2D alphamap; in vec2 mixTexPosition; out vec4 fragmentColor; void main() { vec4 alpha = texture(alphamap, mixTexPosition).a; if (alpha < 0.5) { discard; } else { fragmentColor = vec4(1.0); } }
By itself, the alpha test leaves a harsh edge at the interface between discarded and retained fragments. If we need a smoother transition, we can assign the alpha intensity to fragmentColor
instead of discarding. We'll also have to enable blending and deal with the issues that come with it. Namely, we'll need to render the scene in back to front order so that the semi-transparent fragments will properly mix with the surfaces behind them.
Alpha mapping is frequently used in particle systems, which are data structures that manage the properties of many small projectiles over time. So that many particles may be rendered quickly, each is rendered with simple geometry to which an alpha map is applied. The particles are often too small for the viewer to notice the ragged edges of the alpha test.