Other Buffer Tricks
You learned from Chapter 2 that OpenGL does not render (draw) these primitives directly on the screen. Instead, rendering is done in a buffer, which is later swapped to the screen. We refer to these two buffers as the front (the screen) and back color buffers. By default, OpenGL commands are rendered into the back buffer, and when you call glutSwapBuffers (or your operating systemspecific buffer swap function), the front and back buffers are swapped so that you can see the rendering results. You can, however, render directly into the front buffer if you want. This capability can be useful for displaying a series of drawing commands so that you can see some object or shape actually being drawn. There are two ways to do this; both are discussed in the following section.
Using Buffer Targets
The first way to render directly into the front buffer is to just tell OpenGL that you want drawing to be done there. You do this by calling the following function:
void glDrawBuffer(Glenum mode);
Specifying GL_FRONT causes OpenGL to render to the front buffer, and GL_BACK moves rendering back to the back buffer. OpenGL implementations can support more than just a single front and back buffer for rendering, such as left and right buffers for stereo rendering, and auxiliary buffers. These other buffers are documented further in the reference section at the end of this chapter.
The second way to render to the front buffer is to simply not request double-buffered rendering when OpenGL is initialized. OpenGL is initialized differently on each OS platform, but with GLUT, we initialize our display mode for RGB color and double-buffered rendering with the following line of code:
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
To get single-buffered rendering, you simply omit the bit flag GLUT_DOUBLE, as shown here:
glutInitDisplayMode(GLUT_RGB);
When you do single-buffered rendering, it is important to call either glFlush or glFinish whenever you want to see the results actually drawn to screen. A buffer swap implicitly performs a flush of the pipeline and waits for rendering to complete before the swap actually occurs. We'll discuss the mechanics of this process in more detail in Chapter 11, "It's All About the Pipeline: Faster Geometry Throughput."
Listing 3.12 shows the drawing code for the sample program SINGLE. This example uses a single rendering buffer to draw a series of points spiraling out from the center of the window. The RenderScene() function is called repeatedly and uses static variables to cycle through a simple animation. The output of the SINGLE sample program is shown in Figure 3.35.
Figure 3.35 Output from the single-buffered rendering example.
Listing 3.12 Drawing Code for the SINGLE Sample
/////////////////////////////////////////////////////////// // Called to draw scene void RenderScene(void) { static GLdouble dRadius = 0.1; static GLdouble dAngle = 0.0; // Clear blue window glClearColor(0.0f, 0.0f, 1.0f, 0.0f); if(dAngle == 0.0) glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POINTS); glVertex2d(dRadius * cos(dAngle), dRadius * sin(dAngle)); glEnd(); dRadius *= 1.01; dAngle += 0.1; if(dAngle > 30.0) { dRadius = 0.1; dAngle = 0.0; } glFlush(); }
Manipulating the Depth Buffer
The color buffers are not the only buffers that OpenGL renders into. In the preceding chapter, we mentioned other buffer targets, including the depth buffer. However, the depth buffer is filled with depth values instead of color values. Requesting a depth buffer with GLUT is as simple as adding the GLUT_DEPTH bit flag when initializing the display mode:
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
You've already seen that enabling the use of the depth buffer for depth testing is as easy as calling the following:
glEnable(GL_DEPTH_TEST);
Even when depth testing is not enabled, if a depth buffer is created, OpenGL will write corresponding depth values for all color fragments that go into the color buffer. Sometimes, though, you may want to temporarily turn off writing values to the depth buffer as well as depth testing. You can do this with the function glDepthMask:
void glDepthMask(GLboolean mask);
Setting the mask to GL_FALSE disables writes to the depth buffer but does not disable depth testing from being performed using any values that have already been written to the depth buffer. Calling this function with GL_TRUE re-enables writing to the depth buffer, which is the default state. Masking color writes is also possible but a bit more involved, and will be discussed in Chapter 6.
Cutting It Out with Scissors
One way to improve rendering performance is to update only the portion of the screen that has changed. You may also need to restrict OpenGL rendering to a smaller rectangular region inside the window. OpenGL allows you to specify a scissor rectangle within your window where rendering can take place. By default, the scissor rectangle is the size of the window, and no scissor test takes place. You turn on the scissor test with the ubiquitous glEnable function:
glEnable(GL_SCISSOR_TEST);
You can, of course, turn off the scissor test again with the corresponding glDisable function call. The rectangle within the window where rendering is performed, called the scissor box, is specified in window coordinates (pixels) with the following function:
void glScissor(GLint x, GLint y, GLsizei width, GLsizei height);
The x and y parameters specify the lower-left corner of the scissor box, with width and height being the corresponding dimensions of the scissor box. Listing 3.13 shows the rendering code for the sample program SCISSOR. This program clears the color buffer three times, each time with a smaller scissor box specified before the clear. The result is a set of overlapping colored rectangles, as shown in Figure 3.36.
Listing 3.13 Using the Scissor Box to Render a Series of Rectangles
void RenderScene(void) { // Clear blue window glClearColor(0.0f, 0.0f, 1.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); // Now set scissor to smaller red sub region glClearColor(1.0f, 0.0f, 0.0f, 0.0f); glScissor(100, 100, 600, 400); glEnable(GL_SCISSOR_TEST); glClear(GL_COLOR_BUFFER_BIT); // Finally, an even smaller green rectangle glClearColor(0.0f, 1.0f, 0.0f, 0.0f); glScissor(200, 200, 400, 200); glClear(GL_COLOR_BUFFER_BIT); // Turn scissor back off for next render glDisable(GL_SCISSOR_TEST); glutSwapBuffers(); }
Figure 3.36 Shrinking scissor boxes.
Using the Stencil Buffer
Using the OpenGL scissor box is a great way to restrict rendering to a rectangle within the window. Frequently, however, we want to mask out an irregularly shaped area using a stencil pattern. In the real world, a stencil is a flat piece of cardboard or other material that has a pattern cut out of it. Painters use the stencil to apply paint to a surface using the pattern in the stencil. Figure 3.37 shows how this process works.
Figure 3.37 Using a stencil to paint a surface in the real world.
In the OpenGL world, we have the stencil buffer instead. The stencil buffer provides a similar capability but is far more powerful because we can create the stencil pattern ourselves with rendering commands. To use OpenGL stenciling, we must first request a stencil buffer using the platform-specific OpenGL setup procedures. When using GLUT, we request one when we initialize the display mode. For example, the following line of code sets up a double-buffered RGB color buffer with stencil:
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_STENCIL);
The stencil operation is relatively fast on modern hardware-accelerated OpenGL implementations, but it can also be turned on and off with glEnable/glDisable. For example, we turn on the stencil test with the following line of code:
glEnable(GL_STENCIL_TEST);
With the stencil test enabled, drawing occurs only at locations that pass the stencil test. You set up the stencil test that you want to use with this function:
void glStencilFunc(GLenum func, GLint ref, GLuint mask);
The stencil function that you want to use, func, can be any one of these values: GL_NEVER, GL_ALWAYS, GL_LESS, GL_LEQUAL, GL_EQUAL, GL_GEQUAL, GL_GREATER, and GL_NOTEQUAL. These values tell OpenGL how to compare the value already stored in the stencil buffer with the value you specify in ref. These values correspond to never or always passing, passing if the reference value is less than, less than or equal, greater than or equal, greater than, and not equal to the value already stored in the stencil buffer, respectively. In addition, you can specify a mask value that is bit-wise ANDed with both the reference value and the value from the stencil buffer before the comparison takes place.
Stencil Bits
You need to realize that the stencil buffer may be of limited precision. Stencil buffers are typically only between 1 and 8 bits deep. Each OpenGL implementation may have its own limits on the available bit depth of the stencil buffer, and each operating system or environment has its own methods of querying and setting this value. In GLUT, you just get the most stencil bits available, but for finer-grained control, you need to refer to the operating systemspecific chapters later in the book. Values passed to ref and mask that exceed the available bit depth of the stencil buffer are simply truncated, and only the maximum number of least significant bits is used.
Creating the Stencil Pattern
You now know how the stencil test is performed, but how are values put into the stencil buffer to begin with? First, we must make sure that the stencil buffer is cleared before we start any drawing operations. We do this in the same way that we clear the color and depth buffers with glClearusing the bit mask GL_STENCIL_BUFFER_BIT. For example, the following line of code clears the color, depth, and stencil buffers simultaneously:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
The value used in the clear operation is set previously with a call to
glClearStencil(GLint s);
When the stencil test is enabled, rendering commands are tested against the value in the stencil buffer using the glStencilFunc parameters we just discussed. Fragments (color values placed in the color buffer) are either written or discarded based on the outcome of that stencil test. The stencil buffer itself is also modified during this test, and what goes into the stencil buffer depends on how you've called the glStencilOp function:
void glStencilOp(GLenum fail, GLenum zfail, GLenum zpass);
These values tell OpenGL how to change the value of the stencil buffer if the stencil test fails (fail), and even if the stencil test passes, you can modify the stencil buffer if the depth test fails (zfail) or passes (zpass). The valid values for these arguments are GL_KEEP, GL_ZERO, GL_REPLACE, GL_INCR, GL_DECR, GL_INVERT, GL_INCR_WRAP, and GL_DECR_WRAP. These values correspond to keeping the current value, setting it to zero, replacing with the reference value (from glStencilFunc), incrementing or decrementing the value, inverting it, and incrementing/decrementing with wrap, respectively. Both GL_INCR and GL_DECR increment and decrement the stencil value but are clamped to the minimum and maximum value that can be represented in the stencil buffer for a given bit depth. GL_INCR_WRAP and likewise GL_DECR_WRAP simply wrap the values around when they exceed the upper and lower limits of a given bit representation.
In the sample program STENCIL, we create a spiral line pattern in the stencil buffer, but not in the color buffer. The bouncing rectangle from Chapter 2 comes back for a visit, but this time, the stencil test prevents drawing of the red rectangle anywhere the stencil buffer contains a 0x1 value. Listing 3.14 shows the relevant drawing code.
Listing 3.14 Rendering Code for the STENCIL Sample
void RenderScene(void) { GLdouble dRadius = 0.1; // Initial radius of spiral GLdouble dAngle; // Looping variable // Clear blue window glClearColor(0.0f, 0.0f, 1.0f, 0.0f); // Use 0 for clear stencil, enable stencil test glClearStencil(0.0f); glEnable(GL_STENCIL_TEST); // Clear color and stencil buffer glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // All drawing commands fail the stencil test, and are not // drawn, but increment the value in the stencil buffer. glStencilFunc(GL_NEVER, 0x0, 0x0); glStencilOp(GL_INCR, GL_INCR, GL_INCR); // Spiral pattern will create stencil pattern // Draw the spiral pattern with white lines. We // make the lines white to demonstrate that the // stencil function prevents them from being drawn glColor3f(1.0f, 1.0f, 1.0f); glBegin(GL_LINE_STRIP); for(dAngle = 0; dAngle < 400.0; dAngle += 0.1) { glVertex2d(dRadius * cos(dAngle), dRadius * sin(dAngle)); dRadius *= 1.002; } glEnd(); // Now, allow drawing, except where the stencil pattern is 0x1 // and do not make any further changes to the stencil buffer glStencilFunc(GL_NOTEQUAL, 0x1, 0x1); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // Now draw red bouncing square // (x and y) are modified by a timer function glColor3f(1.0f, 0.0f, 0.0f); glRectf(x, y, x + rsize, y - rsize); // All done, do the buffer swap glutSwapBuffers(); }
The following two lines cause all fragments to fail the stencil test. The values of ref and mask are irrelevant in this case and are not used.
glStencilFunc(GL_NEVER, 0x0, 0x0); glStencilOp(GL_INCR, GL_INCR, GL_INCR);
The arguments to glStencilOp, however, cause the value in the stencil buffer to be written (incremented actually), regardless of whether anything is seen on the screen. Following these lines, a white spiral line is drawn, and even though the color of the line is white so you can see it against the blue background, it is not drawn in the color buffer because it always fails the stencil test (GL_NEVER). You are essentially rendering only to the stencil buffer!
Next, we change the stencil operation with these lines:
glStencilFunc(GL_NOTEQUAL, 0x1, 0x1); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
Now, drawing will occur anywhere the stencil buffer is not equal (GL_NOTEQUAL) to 0x1, which is anywhere onscreen that the spiral line is not drawn. The subsequent call to glStencilOp is optional for this example, but it tells OpenGL to leave the stencil buffer alone for all future drawing operations. Although this sample is best seen in action, Figure 3.38shows an image of what the bounding red square looks like as it is "stenciled out."
Just like the depth buffer, you can also mask out writes to the stencil buffer by using the function glStencilMask:
void glStencilMake(GLboolean mask);
Setting the mask to false does not disable stencil test operations but does prevent any operation from writing values into the stencil buffer.
Figure 3.38 The bouncing red square with masking stencil pattern.