by Richard S. Wright, Jr.
WHAT YOU'LL LEARN IN THIS CHAPTER:
How To | Functions You'll Use |
---|---|
Blend colors and objects together |
|
Use alpha testing to eliminate fragments |
|
Add depth cues with fog |
|
Render motion-blurred animation |
|
In the preceding chapter, you learned that there is more to making a ball appear red than just setting the drawing color to red. Material properties and lighting parameters can go a long way toward adding realism to your graphics, but modeling the real world has a few other challenges that we will address in this chapter. For starters, many effects are accomplished by means of blending colors together. Transparent objects such as stained glass windows or plastic bottles allow you to see through them, but the light from the objects behind them is blended with the color of the transparent object you are seeing through. This type of transparency is achieved in OpenGL by drawing the background objects first and then blending the foreground object in front with the colors that are already present in the color buffer. A good part of making this technique work requires that we now consider the fourth color component that until now we have been ignoring, alpha.
You have already learned that OpenGL rendering places color values in the color buffer under normal circumstances. You have 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. This is, of course, under normal circumstances. These rules suddenly no longer apply the moment you turn on OpenGL blending:
glEnable(GL_BLENDING);
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.
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).
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 6.1 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 6.1. OpenGL Blending Factors
Function | RGB Blend Factors | Alpha Blend Factor |
---|---|---|
(0,0,0) | 0 | |
(1,1,1) | 1 | |
(Rs,Gs,Bs) | As | |
(1,1,1) – (Rs,Gs,Bs) | 1 – As | |
(Rd,Gd,Bd) | Ad | |
(1,1,1) – (Rd,Gd,Bd) | 1 – Ad | |
(As,As,As) | As | |
(1,1,1) – (As,As,As) | 1 – As | |
(Ad,Ad,Ad) | Ad | |
(1,1,1) – (Ad,Ad,Ad) | 1 – Ad | |
(Rc,Gc,Bc) | Ac | |
(1,1,1) – (Rc,Gc,Bc) | 1 – Ac | |
(Ac,Ac,Ac) | Ac | |
| 1 – Ac | |
(f,f,f)[*] | 1 | |
[*] Where f = min(As, 1 – Ad). |
Remember that colors are represented by floating-point numbers, so adding them, subtracting them, and even multiplying them are all perfectly valid operations. Table 6.1 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.5 (0.0f, 0.0f, 1.0f, 0.5f), you would compute the final color as follows:
Cd = destination color = (1.0f, 0.0f, 0.0f, 0.0f)
Cs = source color = (0.0f, 0.0f, 1.0f, 0.5f)
S = source alpha = 0.5
D = one minus source alpha = 1.0 – 0.5 = 0.5
Now, the equation
Cf = (Cs * S) + (Cd * D)
evaluates to
Cf = (Blue * 0.5) + (Red * 0.5)
The final color is a scaled combination of the original red value with the incoming blue value. The higher the incoming alpha value, the more of the incoming color that 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 technique does require, however, that you draw the background object or objects first and then draw the transparent object blended over the top. The effect can be quite dramatic. For example, in the REFLECTION sample program, we will use transparency to achieve the illusion of a reflection in a mirrored surface. We begin with a rotating torus with a sphere revolving around it, similar to the view in the preceding chapter's Sphere World example. Beneath the torus and sphere, we will place a reflective tiled floor. The output from this program is shown in Figure 6.1, and the drawing code is shown in Listing 6.1.
Example 6.1. Rendering Function for the REFLECTION Program
/////////////////////////////////////////////////////////////////////// // Called to draw scene void RenderScene(void) { // Clear the window with current clearing color glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); // Move light under floor to light the "reflected" world glLightfv(GL_LIGHT0, GL_POSITION, fLightPosMirror); glPushMatrix(); glFrontFace(GL_CW); // geometry is mirrored, // swap orientation glScalef(1.0f, -1.0f, 1.0f); DrawWorld(); glFrontFace(GL_CCW); glPopMatrix(); // Draw the ground transparently over the reflection glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); DrawGround(); glDisable(GL_BLEND); glEnable(GL_LIGHTING); // Restore correct lighting and draw the world correctly glLightfv(GL_LIGHT0, GL_POSITION, fLightPos); DrawWorld(); glPopMatrix(); // Do the buffer Swap glutSwapBuffers(); }
The basic algorithm for this effect is to draw the scene upside down first. We use one function to draw the scene, DrawWorld()
, but to draw it upside down, we scale by –1 to invert the y-axis, reverse our polygon winding, and place the light down beneath us. After drawing the upside-down world, we draw the ground, but we use blending to create a transparent floor over the top of the inverted world. Finally, we turn off blending, put the light back overhead, and draw the world right side up.
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 6.2 and selected with the following function:
void glBlendEquation(GLenum mode);
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 6.1, 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 can be changed with this function:
void glBlendColor(GLclampf red, GLclampf green, Glclampf blue, GLclampf alpha);
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 give-away that a computer-generated 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 6.2 shows the output for the sample program SMOOTHER. In Figure 6.3, we have zoomed in on a line segment and some points to show the jagged edges.
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 (changing the blending equation is also not supported on all OpenGL implementations). 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 note, however, that GL_POLYGON_SMOOTH
is not supported on all OpenGL implementations. Listing 6.2 shows the code from the SMOOTHER program that responds to a pop-up menu that allows the user to switch between antialiased and non-antialiased rendering modes. When this program is run with antialiasing enabled, the points and lines appear smoother (fuzzier). In Figure 6.4, a zoomed-in section shows the same area as Figure 6.3, but now with the jagged edges somewhat reduced.
Example 6.2. 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(); }
Note especially here the calls to the glHint
function that was discussed in Chapter 2, “Using OpenGL.” 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
).
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 recent addition to OpenGL to address this shortcoming is multisampling. When this feature is supported (it is an OpenGL 1.3 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 bit field (GLUT_MULTISAMPLE
) that allows you to request this until you reach the operating system–specific chapters later. For example, to request a multisampled, full-color, double-buffered frame buffer 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:
or
The sample program MULTISAMPLE is simply the Sphere World sample from the preceding chapter with multisampling selected and enabled. Figure 6.5 shows the difference between two zoomed-in sections from each program. You can see that multisampling really helps smooth out the geometry's edges on the image to the right, lending to a much more pleasing appearance to the rendered output.
Another important note about multisampling is that when it is enabled, the point, line, and polygon smoothing features 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);
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:
When GL_SAMPLE_COVERAGE
is enabled, the glSampleCoverage
function allows you to specify a specific value that is ANDed (bitwise) with the fragment coverage value:
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.
Another easy-to-use special effect that OpenGL supports is fog. With fog, OpenGL blends a fog color that you specify with geometry after all other color computations have been completed. The amount of the fog color mixed with the geometry varies with the distance of the geometry from the camera origin. The result is a 3D scene that appears to contain fog. Fog can be useful for slowly obscuring objects as they “disappear” into the background fog, or a slight amount of fog will produce a hazy effect on distant objects, providing a powerful and realistic depth cue. Figure 6.6 shows output from the sample program FOGGED. As you can see, this is nothing more than the ubiquitous Sphere World example with fog turned on.
Listing 6.3 shows the few lines of code added to the SetupRC
function to produce this effect.
Example 6.3. Setting Up Fog for Our Sphere World
// Grayish background glClearColor(fLowLight[0], fLowLight[1], fLowLight[2], fLowLight[3]); // Setup Fog parameters glEnable(GL_FOG); // Turn Fog on glFogfv(GL_FOG_COLOR, fLowLight); // Set fog color to match background glFogf(GL_FOG_START, 5.0f); // How far away does the fog start glFogf(GL_FOG_END, 30.0f); // How far away does the fog stop glFogi(GL_FOG_MODE, GL_LINEAR); // Which fog equation do I use?
Turning fog on and off is as easy as using the following functions:
glEnable/glDisable(GL_FOG);
The means of changing fog parameters (how the fog behaves) is to use the glFog
function. There are several variations on glFog
:
void glFogi(GLenum pname, GLint param); void glFogf(GLenum pname, GLfloat param); void glFogiv(GLenum pname, GLint* params); void glFogfv(GLenum pname, GLfloat* params);
The first use of glFog
shown here is
glFogfv(GL_FOG_COLOR, fLowLight); // Set fog color to match background
When used with the GL_FOG_COLOR
parameter, this function expects a pointer to an array of floating-point values that specifies what color the fog should be. Here, we used the same color for the fog as the background clear color. If the fog color does not match the background (there is no strict requirement for this!), as objects become fogged, they will become a fog-colored silhouette against the background.
The next two lines allow us to specify how far away an object must be before fog is applied and how far away the object must be for the fog to be fully applied (object is fog color):
glFogf(GL_FOG_START, 5.0f); // How far away does the fog start glFogf(GL_FOG_END, 30.0f); // How far away does the fog stop
The parameter GL_FOG_START
specifies how far away from the eye fogging begins to take effect, and GL_FOG_END
is the distance from the eye where the fog color completely overpowers the color of the object. The transition from start to end is controlled by the fog equation, which we set to GL_LINEAR
here:
glFogi(GL_FOG_MODE, GL_LINEAR); // Which fog equation do I use?
The fog equation calculates a fog factor that varies from 0 to 1 as the distance of the fragment moves between the start and end distances. OpenGL supports three fog equations: GL_LINEAR
, GL_EXP
, and GL_EXP2
. These equations are shown in Table 6.3.
In these equations, c is the distance of the fragment from the eye point, end is the GL_FOG_END
distance, and start is the GL_FOG_START
distance. The value d is the fog density. Fog density is typically set with glFogf
:
glFogf(GL_FOG_DENSITY, 0.5f);
Figure 6.7 shows graphically how the fog equation and fog density parameters affect the transition from the original fragment color to the fog color. GL_LINEAR
is a straight linear progression, whereas the GL_EXP
and GL_EXP2
equations show two characteristic curves for their transitions. The fog density value has no effect with linear fog (GL_LINEAR
), but the other two curves you see here are generally pulled downward with increasing density values. These graphs, for example, show approximately a density value of 0.5.
The distance to a fragment from the eye point can be calculated in one of two ways. The first, GL_FRAGMENT_DEPTH
, uses the depth value of the fragment itself and can be turned on with glFog
, as shown here:
glFogi(GL_FOG_COORD_SRC, GL_FRAGMENT_DEPTH);
The second method interpolates the fog depth between vertices and is the default fog depth calculation method. This method can be a little faster but can result in a lower quality image. Like vertex-based lighting, the more geometry, the better the results will look. Once again, glFog
allows you to set this mode specifically:
glFogi(GL_FOG_COORD_SRC, GL_FOG_COORD);
In addition to the color, stencil, and depth buffers, OpenGL supports what is called the accumulation buffer. This buffer allows you to render to the color buffer, and then instead of displaying the results in the window, copy the contents of the color buffer to the accumulation buffer. Several supported copy operations allow you to repeatedly blend in different ways the color buffer contents with the accumulated contents in the accumulation buffer (thus its name!). When you have finished accumulating an image, you can then copy the accumulation buffer back to the color buffer and display the results with a buffer swap.
The behavior of the accumulation buffer is controlled by one function:
void glAccum(GLenumm op, GLfloat value);
The first parameter specifies which accumulation operation you want to use, and the second is a floating-point value that is used to scale the operation. Table 6.4 lists the accumulation operations supported.
Table 6.4. OpenGL Accumulation Operations
Operation | Description |
---|---|
Scales color buffer values by value and adds them to current contents of the accumulation buffer. | |
Scales color buffer values by value and replaces the current contents of the accumulation buffer. | |
Scales the color values from the accumulation buffer by value and then copies the values to the color buffer. | |
| Scales the color values in the accumulation buffer by value and stores the result in the accumulation buffer. |
| Scales the color values in the accumulation buffer by value and adds the result to the current accumulation buffer contents. |
Because of the large amount of memory that must be copied and processed for accumulation buffer operations, few real-time applications make use of this facility. For non–real-time rendering, OpenGL can produce some astonishing effects that you might not expect from a real-time API. For example, you can render a scene multiple times and move the point of view around by a fraction of a pixel each time. Accumulating these multiple rendering passes blurs the sharp edges and can produce an entire scene fully antialiased with a quality that surpasses anything that can be done with multisampling. You can also use this blurring effect to blur the background or foreground of an image and then render the object of focus clearly afterward, simulating some depth of field camera effects.
In our sample program MOTIONBLUR, we will demonstrate yet another use of the accumulation buffer to create what appears to be a motion blur effect. A moving sphere is drawn repeatedly in different positions. Each time it is drawn, it is accumulated to the accumulation buffer, with a smaller weight on subsequent passes. The result is a brighter red sphere with a trailing ghost-like image of itself following along behind. The output from this program is shown in Figure 6.8.
Listing 6.4 shows the DrawGeometry
function, which draws all the geometry of the scene. The RenderScene
function then repeatedly calls this function and accumulates the results into the accumulation buffer. When finished, the lines
glAccum(GL_RETURN, 1.0f); glutSwapBuffers();
copy the accumulation buffer back to the color buffer and perform the buffer swap.
Example 6.4. Using the Accumulation Buffer for Motion Blur
///////////////////////////////////////////////////////////// // Draw the ground and the revolving sphere void DrawGeometry(void) { // Clear the window with current clearing color glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); DrawGround(); // Place the moving sphere glColor3f(1.0f, 0.0f, 0.0f); glTranslatef(0.0f, 0.5f, -3.5f); glRotatef(-(yRot * 2.0f), 0.0f, 1.0f, 0.0f); glTranslatef(1.0f, 0.0f, 0.0f); glutSolidSphere(0.1f, 17, 9); glPopMatrix(); } /////////////////////////////////////////////////////////////////////// // Called to draw scene. The world is drawn multiple times with each // frame blended with the last. The current rotation is advanced each // time to create the illusion of motion blur. void RenderScene(void) { GLfloat fPass; GLfloat fPasses = 10.0f; // Set the current rotation back a few degrees yRot = 35.0f; for(fPass = 0.0f; fPass < fPasses; fPass += 1.0f) { yRot += .75f; //1.0f / (fPass+1.0f); // Draw sphere DrawGeometry(); // Accumulate to back buffer if(fPass == 0.0f) glAccum(GL_LOAD, 0.5f); else glAccum(GL_ACCUM, 0.5f * (1.0f / fPasses)); } // copy accumulation buffer to color buffer and // do the buffer Swap glAccum(GL_RETURN, 1.0f); glutSwapBuffers(); }
Finally, you must remember to ask for an accumulation buffer when you set up your OpenGL rendering context (see the OS-specific chapters for how to perform this task on your platform). GLUT also provides support for the accumulation buffer by passing the token GLUT_ACCUM
to the glutInitDisplayMode
function, as shown here:
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_ACCUM);
Blending is a powerful OpenGL feature that enables a myriad of special effects algorithms. Aside from direct support for blending, fog, and an accumulation buffer, OpenGL also supports some other means of tweaking color values and fragments as they are written to the color buffer.
After a final color is computed and is about to be written to the color buffer, OpenGL allows you to mask out one or more of the color channels with the glColorMask
function:
void glColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
The parameters are for the red, green, blue, and alpha channels, respectively. Passing GL_TRUE
allows writing of this channel, and GL_FALSE
prevents writing to this channel.
Many 2D graphics APIs allow binary logical operations to be performed between the source and destination colors. OpenGL also supports these types of 2D operations with the glLogicOp
function:
void glLogicOp(GLenum op);
The logical operation modes are listed in Table 6.5. The logical operation is not enabled by default and is controlled, as most states are, with glEnable
/glDisable
using the value GL_COLOR_LOGIG_OP
. For example, to turn on the logical operations, you use the following:
glEnable(GL_COLOR_LOGIC_OP);
Alpha testing allows you to tell OpenGL to discard fragments whose alpha value fails the alpha comparison test. Discarded fragments are not written to the color, depth, stencil, or accumulation buffers. This feature allows you to improve performance by dropping values that otherwise might be written to the buffers and to eliminate geometry from the depth buffer that may not be visible in the color buffer (because of very low alpha values). The alpha test value and comparison function are specified with the glAlphaFunc
function:
void glAlphaFunc(GLenum func, GLclampf ref);
The reference value is clamped to the range 0.0 to 1.0, and the comparison function may be specified by any of the constants in Table 6.6. You can turn alpha testing on and off with glEnable
/glDisable
using the constant GL_ALPHA_TEST
. The behavior of this function is similar to the glDepthFunc
function covered in Chapter 3.
Table 6.6. Alpha Test Comparison Functions
Constant | Comparison Function |
---|---|
| Never passes |
| Always passes |
| Passes if the fragment is less than the reference value |
| Passes if the fragment is less than or equal to the reference value |
| Passes if the fragment is equal to the reference value |
| Passes if the fragment is greater than or equal to the reference value |
| Passes if the fragment is greater than the reference value |
|
Dithering is a simple operation (in principle) that allows a display system with a small number of discrete colors to simulate displaying a much wider range of colors. For example, the color gray can be simulated by displaying a mix of white and black dots on the screen. More white than black dots make for a lighter gray, whereas more black dots make a darker gray. When your eye is far enough from the display, you cannot see the individual dots, and the blending effect creates the illusion of the color mix. This technique is useful for display systems that support only 8 or 16 bits of color information. Each OpenGL implementation is free to implement its own dithering algorithm, but the effect can be dramatically improved image quality on lower-end color systems. By default, dithering is turned on, and can be controlled with glEnable
/glDisable
and the constant GL_DITHER
:
glEnable(GL_DITHER); // Initially enabled
On higher-end display systems with greater color resolution, the implementation may not need dithering, and dithering may not be employed at a potentially considerable performance savings.
In this chapter, we took color beyond simple shading and lighting effects. You saw how to use blending to create transparent and reflective surfaces and create antialiased points, lines, and polygons with the blending and multisampling features of OpenGL. You also were introduced to the accumulation buffer and saw at least one common special effect that it is normally used for. Finally, you saw how OpenGL supports other color manipulation features such as color masks, bitwise color operations, and dithering, and how to use the alpha test to discard fragments altogether. Now we progress further in the next chapter from colors, shading, and blending to operations that incorporate real image data.
Included in the sample directory on the CD-ROM for this chapter, you'll find an update of the Sphere World example from Chapter 5. You can study the source code to see how we have incorporated many of the techniques from this chapter to add some additional depth queuing to the world with fog, partially transparent shadows on the ground, and fully antialiased rendering of all geometry.
glAccum | |
---|---|
Purpose: | Operates on the accumulation buffer to establish pixel values. |
Include File: |
|
Syntax: | |
void glAccum(GLenum op, GLfloat value); | |
Description: | This function operates on the accumulation buffer. Except for |
Parameters: | |
|
|
| |
Returns: | |
See Also: |
|
glBlendEquation | |
---|---|
Purpose: | Sets the blending equation to be used for color blending operations. |
Include File: |
|
Syntax: | |
void glBlendEquation(GLenum mode);
| |
Description: | When blending is enabled, the source and destination colors are combined. The |
Parameters: | |
|
|
Returns: | |
See Also: |
|
glBlendFunc | |
---|---|
Purpose: | Sets color blending function's source and destination factors. |
Include File: |
|
Syntax: | |
void glBlendFunc(GLenum sfactor, GLenum dfactor); | |
Description: | This function sets the source and destination blending factors for color blending. You must call |
Parameters: | |
| |
|
|
Returns: | |
See Also: |
|
glBlendFuncSeparate | |
---|---|
Purpose: | Allows separate blending factors to be applied to the RGB color and alpha value. |
Include File: |
|
Syntax: | |
void glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); | |
Description: | This function allows a separate weighting factor to be applied to the color (RGB) portion of a fragment and its alpha component. This applies to both source and destination color values. The list of valid blending factors is given in Table 6.1. |
Parameters: | |
| |
|
|
|
|
|
|
Returns: | |
See Also: |
|
glLogicOp | |
---|---|
Purpose: | Selects a logical operation to be performed on color writes. |
Include File: |
|
Syntax: | |
void glLogicOp(GLenum op);
| |
Description: | This function sets a bitwise logical operation to be performed between an incoming color value (source) and the existing (destination) color in the color buffer. By default, the logic operation is disabled and must be turned on with |
Parameters: | |
op |
|
Returns: | |
See Also: |
|