iPhone 3D Programming : Blending and Augmented Reality - Blending Caveats
An equally important caveat is that you should render your triangles in back-to-front order; the standard blending math simply doesn’t work if you try to draw the top layer before the layer beneath it. Let’s demonstrate why this is so. Suppose you’d like to depict a half-opaque red triangle on top of a half-opaque green triangle. Assuming the clear color is black, the history of a pixel in the framebuffer would look like this if you use back-to-front ordering:
Clear to Black. Result: (0, 0, 0).
Draw the half-opaque green triangle. Result: (0, 0.5, 0).
Draw the half-opaque red triangle. Result: (0.5, 0.25, 0).
So, the resulting pixel is a yellowish red; this is what you’d expect. If you try to draw the red triangle first, the result is different:
Clear to Black. Result: (0, 0, 0).
Draw the half-opaque red triangle. Result: (0.5, 0, 0).
Draw the half-opaque green triangle. Result: (0.25, 0.5, 0).
Now you have yellowish green. Order matters when you’re blending! Incidentally, there’s a way to adjust the blending equations so that you can draw in front-to-back order instead of back-to-front; we’ll show how in the next section.
Warning:
When blending is enabled, sort your draw calls from farthest to nearest, and disable depth testing.
Alpha Testing
OpenGL ES supports an alternative to blending called alpha testing. Rather than applying an equation at every pixel to determine the final color, alpha testing performs a simple comparison of the source alpha with a presupplied value. If the comparison fails, the framebuffer is left unchanged; otherwise, the source color is written out. Alpha testing is generally used less frequently than blending because it cannot be used for smooth anti-aliasing or fade-out effects. In some ways, alpha testing is similar to blending with one-bit alpha.
With alpha testing, there’s no back-to-front ordering requirement like there is with blending. It’s simple to enable and configure:
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_LESS, 1.0f);
The first parameter of glAlphaFunc is a comparison function, similar to the depth comparison function . The second parameter is the reference value used for comparison. Use alpha testing with caution: Apple’s documentation warns that it can adversely affect performance.