Home > Articles > Programming > Graphic Programming

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

Buffer Objects


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()




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


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


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.


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


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


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


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


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


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 */
} 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()




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.


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.


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.


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),

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,
glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0));

glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices

glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE,
  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020