Blending
You already learned that OpenGL rendering places color values in the color buffer under normal circumstances. You also learned that depth values for each fragment are also placed in the depth buffer. When depth testing is turned off (disabled), new color values simply overwrite any other values already present in the color buffer. When depth testing is turned on (enabled), new color fragments replace an existing fragment only if they are deemed closer to the near clipping plane than the values already there. Under normal circumstances then, any drawing operation is either discarded entirely, or just completely overwrites any old color values, depending on the result of the depth test. This obliteration of the underlying color values no longer happens the moment you turn on OpenGL blending:
glEnable(GL_BLEND);
When blending is enabled, the incoming color is combined with the color value already present in the color buffer. How these colors are combined leads to a great many and varied special effects.
Combining Colors
First, we must introduce a more official terminology for the color values coming in and already in the color buffer. The color value already stored in the color buffer is called the destination color, and this color value contains the three individual red, green, and blue components, and optionally a stored alpha value as well. A color value that is coming in as a result of more rendering commands that may or may not interact with the destination color is called the source color. The source color also contains either three or four color components (red, green, blue, and optionally alpha). Note that anytime you omit an alpha value, OpenGL assumes it is 1.0.
How the source and destination colors are combined when blending is enabled is controlled by the blending equation. By default, the blending equation looks like this:
- Cf = (Cs * S) + (Cd * D)
Here, Cf is the final computed color, Cs is the source color, Cd is the destination color, and S and D are the source and destination blending factors. These blending factors are set with the following function:
glBlendFunc(GLenum S, GLenum D);
As you can see, S and D are enumerants and not physical values that you specify directly. Table 3.3 lists the possible values for the blending function. The subscripts stand for source, destination, and color (for blend color, to be discussed shortly). R, G, B, and A stand for Red, Green, Blue, and Alpha, respectively.
Table 3.3. OpenGL Blending Factors
Function |
RGB Blend Factors |
Alpha Blend Factor |
GL_ZERO |
(0,0,0) |
0 |
GL_ONE |
(1,1,1) |
1 |
GL_SRC_COLOR |
(Rs,Gs,Bs) |
As |
GL_ONE_MINUS_SRC_COLOR |
(1,1,1) – (Rs,Gs,Bs) |
1 – As |
GL_DST_COLOR |
(Rd,Gd,Bd) |
Ad |
GL_ONE_MINUS_DST_COLOR |
(1,1,1) – (Rd,Gd,Bd) |
1 – Ad |
GL_SRC_ALPHA |
(As,As,As) |
As |
GL_ONE_MINUS_SRC_ALPHA |
(1,1,1) – (As,As,As) |
1 – As |
GL_DST_ALPHA |
(Ad,Ad,Ad) |
Ad |
GL_ONE_MINUS_DST_ALPHA |
(1,1,1) – (Ad,Ad,Ad) |
1 – Ad |
GL_CONSTANT_COLOR |
(Rc,Gc,Bc) |
Ac |
GL_ONE_MINUS_CONSTANT_COLOR |
(1,1,1) – (Rc,Gc,Bc) |
1 – Ac |
GL_CONSTANT_ALPHA |
(Ac,Ac,Ac) |
Ac |
GL_ONE_MINUS_CONSTANT_ALPHA |
(1,1,1) – (Ac,Ac,Ac) |
1 – Ac |
GL_SRC_ALPHA_SATURATE |
(f,f,f)* |
1 |
Remember that colors are represented by floating-point numbers, so adding them, subtracting them, and even multiplying them are all perfectly valid operations. Table 3.3 may seem a bit bewildering, so let's look at a common blending function combination:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
This function tells OpenGL to take the source (incoming) color and multiply the color (the RGB values) by the alpha value. Add this to the result of multiplying the destination color by one minus the alpha value from the source. Say, for example, that you have the color Red (1.0f, 0.0f, 0.0f, 0.0f) already in the color buffer. This is the destination color, or Cd. If something is drawn over this with the color blue and an alpha of 0.6 (0.0f, 0.0f, 1.0f, 0.6f), you would compute the final color as shown here:
Cd = destination color = (1.0f, 0.0f, 0.0f, 0.0f)
Cs = source color = (0.0f, 0.0f, 1.0f, 0.6f)
S = source alpha = 0.6
D = one minus source alpha = 1.0 – 0.6 = 0.4
Now, the equation
- Cf = (Cs * S) + (Cd * D)
evaluates to
- Cf = (Blue * 0.6) + (Red * 0.4)
The final color is a scaled combination of the original red value and the incoming blue value. The higher the incoming alpha value, the more of the incoming color is added and the less of the original color is retained.
This blending function is often used to achieve the effect of drawing a transparent object in front of some other opaque object. This particular technique does require, however, that you draw the background object or objects first and then draw the transparent object blended over the top.
For example, in the Blending sample program, we use transparency to achieve the illusion of a partially transparent red rectangle that we can move about on a white background. Also in the window are a red, blue, green, and black rectangle. Using the cursor keys, you can move the transparent rectangle around and over the other colors. The output of this program is shown in Figure 3.26.
Figure 3.26 The movable red rectangle blending with the background colors.
This example is based on the Move example program from Chapter 2. In this case, however, the background is white, and we also draw the four other colored blocks in fixed locations. The red transparent block is drawn with blending turned on, and a red color that has an alpha set to 0.5.
GLfloat vRed[] = { 1.0f, 0.0f, 0.0f, 0.5f }; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); shaderManager.UseStockShader(GLT_SHADER_IDENTITY, vRed); squareBatch.Draw(); glDisable(GL_BLEND);
It is interesting to note that the white simply dilutes the red color, the black darkens it, and blending red with red is simply...just still red.
Changing the Blending Equation
The blending equation we showed you earlier,
- Cf = (Cs * S) + (Cd * D)
is the default blending equation. You can actually choose from five different blending equations, each given in Table 3.4 and selected with the following function:
void glBlendEquation(GLenum mode);
Table 3.4. Available Blend Equation Modes
Mode |
Function |
GL_FUNC_ADD (default) |
Cf = (Cs * S) + (Cd * D) |
GL_FUNC_SUBTRACT |
Cf = (Cs * S) – (Cd * D) |
GL_FUNC_REVERSE_SUBTRACT |
Cf = (Cd * D) – (Cs * S) |
GL_MIN |
Cf = min(Cs, Cd) |
GL_MAX |
Cf = max(Cs, Cd) |
In addition to glBlendFunc, you have even more flexibility with this function:
void glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
Whereas glBlendFunc specifies the blend functions for source and destination RGBA values, glBlendFuncSeparate allows you to specify blending functions for the RGB and alpha components separately.
Finally, as shown in Table 3.4, the GL_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_ALPHA, and GL_ONE_MINUS_CONSTANT_ALPHA values all allow a constant blending color to be introduced to the blending equation. This constant blending color is initially black (0.0f, 0.0f, 0.0f, 0.0f), but it can be changed with this function:
void glBlendColor(GLclampf red, GLclampf green, Glclampf blue, GLclampf alpha);
Antialiasing
Another use for OpenGL's blending capabilities is antialiasing. Under most circumstances, individual rendered fragments are mapped to individual pixels on a computer screen. These pixels are square (or squarish), and usually you can spot the division between two colors quite clearly. These jaggies, as they are often called, catch the eye's attention and can destroy the illusion that the image is natural. These jaggies are a dead giveaway that the image is computer generated! For many rendering tasks, it is desirable to achieve as much realism as possible, particularly in games, simulations, or artistic endeavors. Figure 3.27 shows the output for the sample program Smoother. In Figure 3.28, we zoomed in on a line segment and some points to show the jagged edges.
Figure 3.27 Output from the program Smoother.
Figure 3.28 A closer look at some jaggies.
To get rid of the jagged edges between primitives, OpenGL uses blending to blend the color of the fragment with the destination color of the pixel and its surrounding pixels. In essence, pixel colors are smeared slightly to neighboring pixels along the edges of any primitives.
Turning on antialiasing is simple. First, you must enable blending and set the blending function to be the same as you used in the preceding section for transparency:
glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
You also need to make sure the blend equation is set to GL_ADD, but because this is the default and most common blending equation, we don't show it here. After blending is enabled and the proper blending function and equation are selected, you can choose to antialias points, lines, and/or polygons (any solid primitive) by calling glEnable:
glEnable(GL_POINT_SMOOTH); // Smooth out points glEnable(GL_LINE_SMOOTH); // Smooth out lines glEnable(GL_POLYGON_SMOOTH); // Smooth out polygon edges
You should use GL_POLYGON_SMOOTH with care. You might expect to smooth out edges on solid geometry, but there are other tedious rules to making this work. For example, geometry that overlaps requires a different blending mode, and you may need to sort your scene from front to back. We won't go into the details because this method of solid object antialiasing has fallen out of common use and has largely been replaced by a superior route to smoothing edges on 3D geometry called multisampling. This feature is discussed in the next section. Without multisampling, you can still get this overlapping geometry problem with antialiased lines that overlap. For wireframe rendering, for example, you can usually get away with just disabling depth testing to avoid the depth artifacts at the line intersections.
Listing 3.3 shows the code from the Smoother program that responds to a pop-up menu that allows the user to switch between antialiased and nonantialiased rendering modes. When this program is run with antialiasing enabled, the points and lines appear smoother (fuzzier). In Figure 3.29, a zoomed-in section shows the same area as Figure 3.27, but now with the jagged edges smoothed out.
Listing 3.3. Switching Between Antialiased and Normal Rendering
/////////////////////////////////////////////////////////////////////// // Reset flags as appropriate in response to menu selections void ProcessMenu(int value) { switch(value) { case 1: // Turn on antialiasing, and give hint to do the best // job possible. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glEnable(GL_POLYGON_SMOOTH); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); break; case 2: // Turn off blending and all smoothing glDisable(GL_BLEND); glDisable(GL_LINE_SMOOTH); glDisable(GL_POINT_SMOOTH); glDisable(GL_POLYGON_SMOOTH); break; default: break; } // Trigger a redraw glutPostRedisplay(); }
Figure 3.29 No more jaggies!
Note especially here the calls to the glHint function discussed in Chapter 2. There are many algorithms and approaches to achieve antialiased primitives. Any specific OpenGL implementation may choose any one of those approaches, and perhaps even support two! You can ask OpenGL, if it does support multiple antialiasing algorithms, to choose one that is very fast (GL_FASTEST) or the one with the most accuracy in appearance (GL_NICEST).
Multisampling
One of the biggest advantages to antialiasing is that it smoothes out the edges of primitives and can lend a more natural and realistic appearance to renderings. Point and line smoothing is widely supported, but unfortunately polygon smoothing is not available on all platforms. Even when GL_POLYGON_SMOOTH is available, it is not as convenient a means of having your whole scene antialiased as you might think. Because it is based on the blending operation, you would need to sort all your primitives from front to back! Yuck.
A more modern addition to OpenGL to address this shortcoming is multisampling. When this feature is supported (it is an OpenGL 1.3 or later feature), an additional buffer is added to the framebuffer that includes the color, depth, and stencil values. All primitives are sampled multiple times per pixel, and the results are stored in this buffer. These samples are resolved to a single value each time the pixel is updated, so from the programmer's standpoint, it appears automatic and happens "behind the scenes." Naturally, this extra memory and processing that must take place are not without their performance penalties, and some implementations may not support multisampling for multiple rendering contexts.
To get multisampling, you must first obtain a rendering context that has support for a multisampled framebuffer. This varies from platform to platform, but GLUT exposes a bitfield (GLUT_MULTISAMPLE) that allows you to request this until you reach the operating system-specific chapters in Part III. For example, to request a multisampled, full-color, double-buffered framebuffer with depth, you would call
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_MULTISAMPLE);
You can turn multisampling on and off using the glEnable/glDisable combination and the GL_MULTISAMPLE token:
glEnable(GL_MULTISAMPLE);
or
glDisable(GL_MULTISAMPLE);
Another important note about multisampling is that when it is enabled, the point, line, and polygon smoothing features via antialiasing are ignored if enabled. This means you cannot use point and line smoothing at the same time as multisampling. On a given OpenGL implementation, points and lines may look better with smoothing turned on instead of multisampling. To accommodate this, you might turn off multisampling before drawing points and lines and then turn on multisampling for other solid geometry. The following pseudocode shows a rough outline of how to do this:
glDisable(GL_MULTISAMPLE); glEnable(GL_POINT_SMOOTH); // Draw some smooth points // ... glDisable(GL_POINT_SMOOTH); glEnable(GL_MULTISAMPLE);
Of course if you do not have a multisampled buffer to begin with, OpenGL behaves as if GL_MULTISAMPLE were disabled.
The multisample buffers use the RGB values of fragments by default and do not include the alpha component of the colors. You can change this by calling glEnable with one of the following three values:
- GL_SAMPLE_ALPHA_TO_COVERAGE—Use the alpha value.
- GL_SAMPLE_ALPHA_TO_ONE—Set alpha to 1 and use it.
- GL_SAMPLE_COVERAGE—Use the value set with glSampleCoverage.
When GL_SAMPLE_COVERAGE is enabled, the glSampleCoverage function allows you to specify a value that is ANDed (bitwise) with the fragment coverage value:
void glSampleCoverage(GLclampf value, GLboolean invert);
This fine-tuning of how the multisample operation works is not strictly specified by the specification, and the exact results may vary from implementation to implementation.