Home > Articles > Programming > Graphic Programming

  • Print
  • + Share This
This chapter is from the book

Buffer Objects

Advanced

There are many operations in OpenGL where you send a large block of data to OpenGL, such as passing vertex array data for processing. Transferring that data may be as simple as copying from your system’s memory down to your graphics card. However, because OpenGL was designed as a client-server model, any time that OpenGL needs data, it will have to be transferred from the client’s memory. If that data doesn’t change, or if the client and server reside on different computers (distributed rendering), that data transfer may be slow, or redundant.

Buffer objects were added to OpenGL Version 1.5 to allow an application to explicitly specify which data it would like to be stored in the graphics server.

Many different types of buffer objects are used in the current versions of OpenGL:

  • Vertex data in arrays can be stored in server-side buffer objects starting with OpenGL Version 1.5. They are described in “Using Buffer Objects with Vertex-Array Data” on page 102 of this chapter.
  • Support for storing pixel data, such as texture maps or blocks of pixels, in buffer objects was added into OpenGL Version 2.1 It is described in “Using Buffer Objects with Pixel Rectangle Data” in Chapter 8.
  • Version 3.1 added uniform buffer objects for storing blocks of uniform-variable data for use with shaders.

You will find many other features in OpenGL that use the term “objects,” but not all apply to storing blocks of data. For example, texture objects (introduced in OpenGL Version 1.1) merely encapsulate various state settings associated with texture maps (See “Texture Objects” on page 437). Likewise, vertex-array objects, added in Version 3.0, encapsulate the state parameters associated with using vertex arrays. These types of objects allow you to alter numerous state settings with many fewer function calls. For maximum performance, you should try to use them whenever possible, once you’re comfortable with their operation.

Creating Buffer Objects

In OpenGL Version 3.0, any nonzero unsigned integer may used as a buffer object identifier. You may either arbitrarily select representative values or let OpenGL allocate and manage those identifiers for you. Why the difference? By having OpenGL allocate identifiers, you are guaranteed to avoid an already used buffer object identifier. This helps to eliminate the risk of modifying data unintentionally. In fact, OpenGL Version 3.1 requires that all object identifiers be generated, disallowing user-defined names.

To have OpenGL allocate buffer objects identifiers, call glGenBuffers().

You can also determine whether an identifier is a currently used buffer object identifier by calling glIsBuffer().

Making a Buffer Object Active

To make a buffer object active, it needs to be bound. Binding selects which buffer object future operations will affect, either for initializing data or using that buffer for rendering. That is, if you have more than one buffer object in your application, you’ll likely call glBindBuffer() multiple times: once to initialize the object and its data, and then subsequent times either to select that object for use in rendering or to update its data.

To disable use of buffer objects, call glBindBuffer() with zero as the buffer identifier. This switches OpenGL to the default mode of not using buffer objects.

Allocating and Initializing Buffer Objects with Data

Once you’ve bound a buffer object, you need to reserve space for storing your data. This is done by calling glBufferData().

glBufferData() first allocates memory in the OpenGL server for storing your data. If you request too much memory, a GL_OUT_OF_MEMORY error will be set. Once the storage has been reserved, and if the data parameter is not NULL, size units of storage (usually bytes) are copied from the client’s memory into the buffer object. However, if you need to dynamically load the data at some point after the buffer is created, pass NULL in for the data pointer. This will reserve the appropriate storage for your data, but leave it uninitialized.

The final parameter to glBufferData(), usage, is a performance hint to OpenGL. Based upon the value you specify for usage, OpenGL may be able to optimize the data for better performance, or it can choose to ignore the hint. There are three operations that can be done to buffer object data:

  1. Drawing—the client specifies data that is used for rendering.
  2. Reading—data values are read from an OpenGL buffer (such as the framebuffer) and used in the application in various computations not immediately related to rendering.
  3. Copying—data values are read from an OpenGL buffer and then used as data for rendering.

Additionally, depending upon how often you intend to update the data, there are various operational hints for describing how often the data will be read or used in rendering:

  • Stream mode—you specify the data once, and use it only a few times in drawing or other operations.
  • Static mode—you specify the data once, but use the values often.
  • Dynamic mode—you may update the data often and use the data values in the buffer object many times as well.

Possible values for usage are described in Table 2-6.

Table 2-6. Values for usage Parameter of glBufferData()

Parameter

Meaning

GL_STREAM_DRAW

Data is specified once and used at most a few times as the source of drawing and image specification commands.

GL_STREAM_READ

Data is copied once from an OpenGL buffer and is used at most a few times by the application as data values.

GL_STREAM_COPY

Data is copied once from an OpenGL buffer and is used at most a few times as the source for drawing or image specification commands.

GL_STATIC_DRAW

Data is specified once and used many times as the source of drawing or image specification commands.

GL_STATIC_READ

Data is copied once from an OpenGL buffer and is used many times by the application as data values.

GL_STATIC_COPY

Data is copied once from an OpenGL buffer and is used many times as the source for drawing or image specification commands.

GL_DYNAMIC_DRAW

Data is specified many times and used many times as the source of drawing and image specification commands.

GL_DYNAMIC_READ

Data is copied many times from an OpenGL buffer and is used many times by the application as data values.

GL_DYNAMIC_COPY

Data is copied many times from an OpenGL buffer and is used many times as the source for drawing or image specification commands.

Updating Data Values in Buffer Objects

There are two methods for updating data stored in a buffer object. The first method assumes that you have data of the same type prepared in a buffer in your application. glBufferSubData() will replace some subset of the data in the bound buffer object with the data you provide.

The second method allows you more control over which data values are updated in the buffer. glMapBuffer() and glMapBufferRange() return a pointer to the buffer object memory, into which you can write new values (or simply read the data, depending on your choice of memory access permissions), just as if you were assigning values to an array. When you’ve completed updating the values in the buffer, you call glUnmapBuffer() to signify that you’ve completed updating the data.

glMapBuffer() provides access to the entire set of data contained in the buffer object. This approach is useful if you need to modify much of the data in buffer, but may be inefficient if you have a large buffer and need to update only a small portion of the values.

When you’ve completed accessing the storage, you can unmap the buffer by calling glUnmapBuffer().

As a simple example of how you might selectively update elements of your data, we’ll use glMapBuffer() to obtain a pointer to the data in a buffer object containing three-dimensional positional coordinates, and then update only the z-coordinates.

GLfloat* data;

data = (GLfloat*) glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE);

if (data != (GLfloat*) NULL) {
    for( i = 0; i < 8; ++i )
        data[3*i+2] *= 2.0;  /* Modify Z values */
    glUnmapBuffer(GL_ARRAY_BUFFER);
} else {
    /* Handle not being able to update data */
}

If you need to update only a relatively small number of values in the buffer (as compared to its total size), or small contiguous ranges of values in a very large buffer object, it may be more efficient to use glMapBufferRange(). It allows you to map only the range of data values you need.

Using glMapBufferRange(), you can specify optional hints by setting additional bits within access. These flags describe how the OpenGL server needs to preserve data that was originally in the buffer before you mapped it. The hints are meant to aid the OpenGL implementation in determining which data values it needs to retain, or for how long, to keep any internal copies of the data correct and consistent.

As described in Table 2-7, specifying GL_MAP_FLUSH_EXPLICIT_BIT in the access flags when mapping a buffer region with glMapBufferRange() requires ranges modified within the mapped buffer to be indicated to the OpenGL by a call to glFlushMappedBufferRange().

Table 2-7. Values for the access Parameter of glMapBufferRange()

Parameter

Meaning

GL_MAP_INVALIDATE_RANGE_BIT

Specify that the previous values in the mapped range may be discarded, but preserve the other values within the buffer. Data within this range are undefined unless explicitly written. No OpenGL error is generated if later OpenGL calls access undefined data, and the results of such calls are undefined (but may cause application or system errors). This flag may not be used in conjunction with the GL_READ_BIT.

GL_MAP_INVALIDATE_BUFFER_BIT

Specify that the previous values of the entire buffer may be discarded, and all values with the buffer are undefined unless explicitly written. No OpenGL error is generated if later OpenGL calls access undefined data, and the results of such calls are undefined (but may cause application or system errors). This flag may not be used in conjunction with the GL_READ_BIT.

GL_MAP_FLUSH_EXPLICIT_BIT

Indicate that discrete ranges of the mapped region may be updated, that the application will signal when modifications to a range should be considered completed by calling glFlushMappedBufferRange(). No OpenGL error is generated if a range of the mapped buffer is updated but not flushed, however, the values are undefined until flushed.

Using this option will require any modified ranges to be explicitly flushed to the OpenGL server—glUnmapBuffer() will not automatically flush the buffer’s data.

GL_MAP_UNSYNCHRONIZED_BIT

Specify that OpenGL should not attempt to synchronize pending operations on a buffer (e.g., updating data with a call to glBufferData(), or the application is trying to use the data in the buffer for rendering) until the call to glMapBufferRange() has completed. No OpenGL errors are generated for the pending operations that access or modify the mapped region, but the results of those operations is undefined.

Copying Data Between Buffer Objects

On some occasions, you may need to copy data from one buffer object to another. In versions of OpenGL prior to Version 3.1, this would be a two-step process:

  1. Copy the data from the buffer object into memory in your application. You would do this either by mapping the buffer and copying it into a local memory buffer, or by calling glGetBufferSubData() to copy the data from the server.
  2. Update the data in another buffer object by binding to the new object and then sending the new data using glBufferData() (or glBufferSubData() if you’re replacing only a subset). Alternatively, you could map the buffer, and then copy the data from a local memory buffer into the mapped buffer.

In OpenGL Version 3.1, the glCopyBufferSubData() command copies data without forcing it to make a temporary stop in your application’s memory.

Cleaning Up Buffer Objects

When you’re finished with a buffer object, you can release its resources and make its identifier available by calling glDeleteBuffers(). Any bindings to currently bound objects that are deleted are reset to zero.

Using Buffer Objects with Vertex-Array Data

To store your vertex-array data in buffer objects, you will need to add a few steps to your application.

  1. (Optional) Generate buffer object identifiers.
  2. Bind a buffer object, specifying that it will be used for either storing vertex data or indices.
  3. Request storage for your data, and optionally initialize those data elements.
  4. Specify offsets relative to the start of the buffer object to initialize the vertex-array functions, such as glVertexPointer().
  5. Bind the appropriate buffer object to be utilized in rendering.
  6. Render using an appropriate vertex-array rendering function, such as glDrawArrays() or glDrawElements().

If you need to initialize multiple buffer objects, you will repeat steps 2 through 4 for each buffer object.

Both “formats” of vertex-array data are available for use in buffer objects. As described in “Step 2: Specifying Data for the Arrays,” vertex, color, lighting normal, or any other type of associated vertex data can be stored in a buffer object. Additionally, interleaved vertex array data, as described in “Interleaved Arrays,” can also be stored in a buffer object. In either case, you would create a single buffer object to hold all of the data to be used as vertex arrays.

As compared to specifying a memory address in the client’s memory where OpenGL should access the vertex-array data, you specify the offset in machine units (usually bytes) to the data in the buffer. To help illustrate computing the offset, and to frustrate the purists in the audience, we’ll use the following macro to simplify expressing the offset:

#define BUFFER_OFFSET(bytes)  ((GLubyte*) NULL + (bytes))

For example, if you had floating-point color and position data for each vertex, perhaps represented as the following array

GLfloat vertexData[][6] = {
    { R0, G0, B0, X0, Y0, Z0 },
    { R1, G1, B1, X1, Y1, Z1 },
    ...
    { Rn, Gn, Bn, Xn, Yn, Zn }
};

that were used to initialize the buffer object, you could specify the data as two separate vertex array calls, one for colors and one for vertices:

glColorPointer(3, GL_FLOAT, 6*sizeof(GLfloat),BUFFER_OFFSET(0));
glVertexPointer(3, GL_FLOAT, 6*sizeof(GLfloat),
                BUFFER_OFFSET(3*sizeof(GLfloat));
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);

Conversely, since the data in vertexData matches a format for an interleaved vertex array, you could use glInterleavedArrays() for specifying the vertex-array data:

glInterleavedArrays(GL_C3F_V3F, 0, BUFFER_OFFSET(0));

Putting this all together, Example 2-17 demonstrates how buffer objects of vertex data might be used. The example creates two buffer objects, one containing vertex data and the other containing index data.

Example 2-17. Using Buffer Objects with Vertex Data

#define VERTICES     0
#define INDICES      1
#define NUM_BUFFERS  2
GLuint  buffers[NUM_BUFFERS];

GLfloat vertices[][3] = {
    { -1.0, -1.0, -1.0 },
    {  1.0, -1.0, -1.0 },
    {  1.0,  1.0, -1.0 },
    { -1.0,  1.0, -1.0 },
    { -1.0, -1.0,  1.0 },
    {  1.0, -1.0,  1.0 },
    {  1.0,  1.0,  1.0 },
    { -1.0,  1.0,  1.0 }
};

GLubyte indices[][4] = {
    { 0, 1, 2, 3 },
    { 4, 7, 6, 5 },
    { 0, 4, 5, 1 },
    { 3, 2, 6, 7 },
    { 0, 3, 7, 4 },
    { 1, 5, 6, 2 }
};

glGenBuffers(NUM_BUFFERS, buffers);

glBindBuffer(GL_ARRAY_BUFFER, buffers[VERTICES]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
             GL_STATIC_DRAW);
glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0));
glEnableClientState(GL_VERTEX_ARRAY);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[INDICES]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices
             GL_STATIC_DRAW);

glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE,
               BUFFER_OFFSET(0));
  • + Share This
  • 🔖 Save To Your Account