Home > Articles > Programming > Graphic Programming

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

Vertex Arrays

You may have noticed that OpenGL requires many function calls to render geometric primitives. Drawing a 20-sided polygon requires at least 22 function calls: one call to glBegin(), one call for each of the vertices, and a final call to glEnd(). In the two previous code examples, additional information (polygon boundary edge flags or surface normals) added function calls for each vertex. This can quickly double or triple the number of function calls required for one geometric object. For some systems, function calls have a great deal of overhead and can hinder performance.

An additional problem is the redundant processing of vertices that are shared between adjacent polygons. For example, the cube in Figure 2-14 has six faces and eight shared vertices. Unfortunately, if the standard method of describing this object is used, each vertex has to be specified three times: once for every face that uses it. Therefore, 24 vertices are processed, even though eight would be enough.

Figure 2-14

Figure 2-14 Six Sides, Eight Shared Vertices

OpenGL has vertex array routines that allow you to specify a lot of vertex-related data with just a few arrays and to access that data with equally few function calls. Using vertex array routines, all 20 vertices in a 20-sided polygon can be put into one array and called with one function. If each vertex also has a surface normal, all 20 surface normals can be put into another array and also called with one function.

Arranging data in vertex arrays may increase the performance of your application. Using vertex arrays reduces the number of function calls, which improves performance. Also, using vertex arrays may allow reuse of already processed shared vertices.

There are three steps to using vertex arrays to render geometry:

  1. Activate (enable) the appropriate arrays, with each storing a different type of data: vertex coordinates, surface normals, RGBA colors, secondary colors, color indices, fog coordinates, texture coordinates, polygon edge flags, or vertex attributes for use in a vertex shader.
  2. Put data into the array or arrays. The arrays are accessed by the addresses of (that is, pointers to) their memory locations. In the client-server model, this data is stored in the client’s address space, unless you choose to use buffer objects (see “Buffer Objects” on page 91), for which the arrays are stored in server memory.
  3. Draw geometry with the data. OpenGL obtains the data from all activated arrays by dereferencing the pointers. In the client-server model, the data is transferred to the server’s address space. There are three ways to do this:

    • Accessing individual array elements (randomly hopping around)
    • Creating a list of individual array elements (methodically hopping around)
    • Processing sequential array elements

    The dereferencing method you choose may depend on the type of problem you encounter. Version 1.4 added support for multiple array access from a single function call.

Interleaved vertex array data is another common method of organization. Instead of several different arrays, each maintaining a different type of data (color, surface normal, coordinate, and so on), you may have the different types of data mixed into a single array. (See “Interleaved Arrays” on page 88.)

Step 1: Enabling Arrays

The first step is to call glEnableClientState() with an enumerated parameter, which activates the chosen array. In theory, you may need to call this up to eight times to activate the eight available arrays. In practice, you’ll probably activate up to six arrays. For example, it is unlikely that you would activate both GL_COLOR_ARRAY and GL_INDEX_ARRAY, as your program’s display mode supports either RGBA mode or color-index mode, but probably not both simultaneously.

If you use lighting, you may want to define a surface normal for every vertex. (See “Normal Vectors” on page 68.) To use vertex arrays for that case, you activate both the surface normal and vertex coordinate arrays:

glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);

Suppose that you want to turn off lighting at some point and just draw the geometry using a single color. You want to call glDisable() to turn off lighting states (see Chapter 5). Now that lighting has been deactivated, you also want to stop changing the values of the surface normal state, which is wasted effort. To do this, you call

glDisableClientState(GL_NORMAL_ARRAY);

You might be asking yourself why the architects of OpenGL created these new (and long) command names, like gl*ClientState(), for example. Why can’t you just call glEnable() and glDisable()? One reason is that glEnable() and glDisable() can be stored in a display list, but the specification of vertex arrays cannot, because the data remains on the client’s side.

If multitexturing is enabled, enabling and disabling client arrays affects only the active texturing unit. See “Multitexturing” on page 467 for more details.

Step 2: Specifying Data for the Arrays

There is a straightforward way by which a single command specifies a single array in the client space. There are eight different routines for specifying arrays—one routine for each kind of array. There is also a command that can specify several client-space arrays at once, all originating from a single interleaved array.

To access the other seven arrays, there are seven similar routines:

The main difference among the routines is whether size and type are unique or must be specified. For example, a surface normal always has three components, so it is redundant to specify its size. An edge flag is always a single Boolean, so neither size nor type needs to be mentioned. Table 2-4 displays legal values for size and data types.

Table 2-4. Vertex Array Sizes (Values per Vertex) and Data Types

Command

Sizes

Values for type Argument

glVertexPointer

2, 3, 4

GL_SHORT, GL_INT, GL_FLOAT, GL_DOUBLE

glColorPointer

3, 4

GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT, GL_FLOAT, GL_DOUBLE

glSecondaryColorPointer

3

GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT, GL_FLOAT, GL_DOUBLE

glIndexPointer

1

GL_UNSIGNED_BYTE, GL_SHORT, GL_INT, GL_FLOAT, GL_DOUBLE

glNormalPointer

3

GL_BYTE, GL_SHORT, GL_INT, GL_FLOAT, GL_DOUBLE

glFogCoordPointer

1

GL_FLOAT, GL_DOUBLE

glTexCoordPointer

1, 2, 3, 4

GL_SHORT, GL_INT, GL_FLOAT, GL_DOUBLE

glEdgeFlagPointer

1

no type argument (type of data must be GLboolean)

For OpenGL implementations that support multitexturing, specifying a texture coordinate array with glTexCoordPointer() only affects the currently active texture unit. See “Multitexturing” on page 467 for more information.

Example 2-9 uses vertex arrays for both RGBA colors and vertex coordinates. RGB floating-point values and their corresponding (x, y) integer coordinates are loaded into the GL_COLOR_ARRAY and GL_VERTEX_ARRAY.

Example 2-9. Enabling and Loading Vertex Arrays: varray.c

static GLint vertices[] = {25, 25,
                          100, 325,
                          175, 25,
                          175, 325,
                          250, 25,
                          325, 325};
static GLfloat colors[] = {1.0, 0.2, 0.2,
                          0.2, 0.2, 1.0,
                          0.8, 1.0, 0.2,
                          0.75, 0.75, 0.75,
                          0.35, 0.35, 0.35,
                          0.5, 0.5, 0.5};

glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);

glColorPointer(3, GL_FLOAT, 0, colors);
glVertexPointer(2, GL_INT, 0, vertices);

Stride

The stride parameter for the gl*Pointer() routines tells OpenGL how to access the data you provide in your pointer arrays. Its value should be the number of bytes between the starts of two successive pointer elements, or zero, which is a special case. For example, suppose you stored both your vertex’s RGB and (x, y, z) coordinates in a single array, such as the following:

static GLfloat intertwined[] =
      {1.0, 0.2, 1.0, 100.0, 100.0, 0.0,
       1.0, 0.2, 0.2,   0.0, 200.0, 0.0,
       1.0, 1.0, 0.2, 100.0, 300.0, 0.0,
       0.2, 1.0, 0.2, 200.0, 300.0, 0.0,
       0.2, 1.0, 1.0, 300.0, 200.0, 0.0,
       0.2, 0.2, 1.0, 200.0, 100.0, 0.0};

To reference only the color values in the intertwined array, the following call starts from the beginning of the array (which could also be passed as &intertwined[0]) and jumps ahead 6 * sizeof(GLfloat) bytes, which is the size of both the color and vertex coordinate values. This jump is enough to get to the beginning of the data for the next vertex:

glColorPointer(3, GL_FLOAT, 6*sizeof(GLfloat), &intertwined[0]);

For the vertex coordinate pointer, you need to start from further in the array, at the fourth element of intertwined (remember that C programmers start counting at zero):

glVertexPointer(3, GL_FLOAT, 6*sizeof(GLfloat), &intertwined[3]);

If your data is stored similar to the intertwined array above, you may find the approach described in “Interleaved Arrays” on page 88 more convenient for storing your data.

With a stride of zero, each type of vertex array (RGB color, color index, vertex coordinate, and so on) must be tightly packed. The data in the array must be homogeneous; that is, the data must be all RGB color values, all vertex coordinates, or all some other data similar in some fashion.

Step 3: Dereferencing and Rendering

Until the contents of the vertex arrays are dereferenced, the arrays remain on the client side, and their contents are easily changed. In Step 3, contents of the arrays are obtained, sent to the server, and then sent down the graphics processing pipeline for rendering.

You can obtain data from a single array element (indexed location), from an ordered list of array elements (which may be limited to a subset of the entire vertex array data), or from a sequence of array elements.

Dereferencing a Single Array Element

glArrayElement() is usually called between glBegin() and glEnd(). (If called outside, glArrayElement() sets the current state for all enabled arrays, except for vertex, which has no current state.) In Example 2-10, a triangle is drawn using the third, fourth, and sixth vertices from enabled vertex arrays. (Again, remember that C programmers begin counting array locations with zero.)

Example 2-10. Using glArrayElement() to Define Colors and Vertices

glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glColorPointer(3, GL_FLOAT, 0, colors);
glVertexPointer(2, GL_INT, 0, vertices);

glBegin(GL_TRIANGLES);
glArrayElement(2);
glArrayElement(3);
glArrayElement(5);
glEnd();

When executed, the latter five lines of code have the same effect as

glBegin(GL_TRIANGLES);
glColor3fv(colors + (2 * 3));
glVertex2iv(vertices + (2 * 2));
glColor3fv(colors + (3 * 3));
glVertex2iv(vertices + (3 * 2));
glColor3fv(colors + (5 * 3));
glVertex2iv(vertices + (5 * 2));
glEnd();

Since glArrayElement() is only a single function call per vertex, it may reduce the number of function calls, which increases overall performance.

Be warned that if the contents of the array are changed between glBegin() and glEnd(), there is no guarantee that you will receive original data or changed data for your requested element. To be safe, don’t change the contents of any array element that might be accessed until the primitive is completed.

Dereferencing a List of Array Elements

glArrayElement() is good for randomly “hopping around” your data arrays. Similar routines, glDrawElements(), glMultiDrawElements(), and glDrawRangeElements(), are good for hopping around your data arrays in a more orderly manner.

The effect of glDrawElements() is almost the same as this command sequence:

glBegin(mode);
for (i = 0; i < count; i++)
   glArrayElement(indices[i]);
glEnd();

glDrawElements() additionally checks to make sure mode, count, and type are valid. Also, unlike the preceding sequence, executing glDrawElements() leaves several states indeterminate. After execution of glDrawElements(), current RGB color, secondary color, color index, normal coordinates, fog coordinates, texture coordinates, and edge flag are indeterminate if the corresponding array has been enabled.

With glDrawElements(), the vertices for each face of the cube can be placed in an array of indices. Example 2-11 shows two ways to use glDrawElements() to render the cube. Figure 2-15 shows the numbering of the vertices used in Example 2-11.

Figure 2-15

Figure 2-15 Cube with Numbered Vertices

Example 2-11. Using glDrawElements() to Dereference Several Array Elements

static GLubyte frontIndices[] = {4, 5, 6, 7};
static GLubyte rightIndices[] = {1, 2, 6, 5};
static GLubyte bottomIndices[] = {0, 1, 5, 4};
static GLubyte backIndices[] = {0, 3, 2, 1};
static GLubyte leftIndices[] = {0, 4, 7, 3};
static GLubyte topIndices[] = {2, 3, 7, 6};

glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, frontIndices);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, rightIndices);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, bottomIndices);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, backIndices);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, leftIndices);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, topIndices);

With several primitive types (such as GL_QUADS, GL_TRIANGLES, and GL_LINES), you may be able to compact several lists of indices together into a single array. Since the GL_QUADS primitive interprets each group of four vertices as a single polygon, you may compact all the indices used in Example 2-11 into a single array, as shown in Example 2-12:

Example 2-12. Compacting Several glDrawElements() Calls into One

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

glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, allIndices);

For other primitive types, compacting indices from several arrays into a single array renders a different result. In Example 2-13, two calls to glDrawElements() with the primitive GL_LINE_STRIP render two line strips. You cannot simply combine these two arrays and use a single call to glDrawElements() without concatenating the lines into a single strip that would connect vertices #6 and #7. (Note that vertex #1 is being used in both line strips just to show that this is legal.)

Example 2-13. Two glDrawElements() Calls That Render Two Line Strips

static GLubyte oneIndices[] = {0, 1, 2, 3, 4, 5, 6};
static GLubyte twoIndices[] = {7, 1, 8, 9, 10, 11};

glDrawElements(GL_LINE_STRIP, 7, GL_UNSIGNED_BYTE, oneIndices);
glDrawElements(GL_LINE_STRIP, 6, GL_UNSIGNED_BYTE, twoIndices);

The routine glMultiDrawElements() was introduced in OpenGL Version 1.4 to enable combining the effects of several glDrawElements() calls into a single call.

The effect of glMultiDrawElements() is the same as

for (i = 0; i < primcount; i++) {
   if (count[i] > 0)
      glDrawElements(mode, count[i], type, indices[i]);
}

The calls to glDrawElements() in Example 2-13 can be combined into a single call of glMultiDrawElements(), as shown in Example 2-14:

Example 2-14. Use of glMultiDrawElements(): mvarray.c

static GLubyte oneIndices[] = {0, 1, 2, 3, 4, 5, 6};
static GLubyte twoIndices[] = {7, 1, 8, 9, 10, 11};
static GLsizei count[] = {7, 6};
static GLvoid * indices[2] = {oneIndices, twoIndices};

glMultiDrawElements(GL_LINE_STRIP, count, GL_UNSIGNED_BYTE,
                     indices, 2);

Like glDrawElements() or glMultiDrawElements(), glDrawRangeElements() is also good for hopping around data arrays and rendering their contents. glDrawRangeElements() also introduces the added restriction of a range of legal values for its indices, which may increase program performance. For optimal performance, some OpenGL implementations may be able to prefetch (obtain prior to rendering) a limited amount of vertex array data. glDrawRangeElements() allows you to specify the range of vertices to be prefetched.

It is a mistake for vertices in the array indices to reference outside the range [start, end]. However, OpenGL implementations are not required to find or report this mistake. Therefore, illegal index values may or may not generate an OpenGL error condition, and it is entirely up to the implementation to decide what to do.

You can use glGetIntegerv() with GL_MAX_ELEMENTS_VERTICES and GL_MAX_ELEMENTS_INDICES to find out, respectively, the recommended maximum number of vertices to be prefetched and the maximum number of indices (indicating the number of vertices to be rendered) to be referenced. If end – start + 1 is greater than the recommended maximum of prefetched vertices, or if count is greater than the recommended maximum of indices, glDrawRangeElements() should still render correctly, but performance may be reduced.

Not all vertices in the range [start, end] have to be referenced. However, on some implementations, if you specify a sparsely used range, you may unnecessarily process many vertices that go unused.

With glArrayElement(), glDrawElements(), glMultiDrawElements(), and glDrawRangeElements(), it is possible that your OpenGL implementation caches recently processed (meaning transformed, lit) vertices, allowing your application to “reuse” them by not sending them down the transformation pipeline additional times. Take the aforementioned cube, for example, which has six faces (polygons) but only eight vertices. Each vertex is used by exactly three faces. Without gl*Elements(), rendering all six faces would require processing 24 vertices, even though 16 vertices are redundant. Your implementation of OpenGL may be able to minimize redundancy and process as few as eight vertices. (Reuse of vertices may be limited to all vertices within a single glDrawElements() or glDrawRangeElements() call, a single index array for glMultiDrawElements(), or, for glArrayElement(), within one glBegin()/glEnd() pair.)

Dereferencing a Sequence of Array Elements

While glArrayElement(), glDrawElements(), and glDrawRangeElements() “hop around” your data arrays, glDrawArrays() plows straight through them.

The effect of glDrawArrays() is almost the same as this command sequence:

glBegin (mode);
for (i = 0; i < count; i++)
   glArrayElement(first + i);
glEnd();

As is the case with glDrawElements(), glDrawArrays() also performs error checking on its parameter values and leaves the current RGB color, secondary color, color index, normal coordinates, fog coordinates, texture coordinates, and edge flag with indeterminate values if the corresponding array has been enabled.

Try This

try_this.jpg

Change the icosahedron drawing routine in Example 2-19 on page 115 to use vertex arrays.

Similar to glMultiDrawElements(), the routine glMultiDrawArrays() was introduced in OpenGL Version 1.4 to combine several glDrawArrays() calls into a single call.

The effect of glMultiDrawArrays() is the same as

for (i = 0; i < primcount; i++) {
   if (count[i] > 0)
      glDrawArrays(mode, first[i], count[i]);
}

Restarting Primitives

As you start working with larger sets of vertex data, you are likely to find that you need to make numerous calls to the OpenGL drawing routines, usually rendering the same type of primitive (such as GL_TRIANGLE_STRIP, for example) that you used in the previous drawing call. Of course, you can use the glMultiDraw*() routines, but they require the overhead of maintaining the arrays for the starting index and length of each primitive.

OpenGL Version 3.1 added the ability to restart primitives within the same drawing call by specifying a special value, the primitive restart index, which is specially processed by OpenGL. When the primitive restart index is encountered in a draw call, a new rendering primitive of the same type is started with the vertex following the index. The primitive restart index is specified by the glPrimitiveRestartIndex() routine.

Primitive restarting is controlled by calling glEnable() or glDisable() and specifying GL_PRIMITIVE_RESTART, as demonstrated in Example 2-15.

Example 2-15. Using glPrimitiveRestartIndex() to Render Multiple Triangle Strips: primrestart.c.

#define BUFFER_OFFSET(offset) ((GLvoid *) NULL + offset)

#define XStart      -0.8
#define XEnd         0.8
#define YStart      -0.8
#define YEnd         0.8

#define NumXPoints          11
#define NumYPoints          11
#define NumPoints           (NumXPoints * NumYPoints)
#define NumPointsPerStrip   (2*NumXPoints)
#define NumStrips           (NumYPoints-1)
#define RestartIndex        0xffff

void
init()
{
    GLuint    vbo, ebo;
    GLfloat   *vertices;
    GLushort  *indices;

    /* Set up vertex data */
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, 2*NumPoints*sizeof(GLfloat),
        NULL, GL_STATIC_DRAW);
    vertices = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);

    if (vertices == NULL) {
        fprintf(stderr, "Unable to map vertex buffer\n");
        exit(EXIT_FAILURE);
    }
    else {
        int       i, j;
        GLfloat  dx = (XEnd - XStart) / (NumXPoints - 1);
        GLfloat  dy = (YEnd - YStart) / (NumYPoints - 1);
        GLfloat  *tmp = vertices;
        int n = 0;

        for (j = 0; j < NumYPoints; ++j) {
            GLfloat y = YStart + j*dy;

            for (i = 0; i < NumXPoints; ++i) {
                GLfloat x = XStart + i*dx;
                *tmp++ = x;
                *tmp++ = y;
            }
        }

        glUnmapBuffer(GL_ARRAY_BUFFER);
        glVertexPointer(2, GL_FLOAT, 0, BUFFER_OFFSET(0));
        glEnableClientState(GL_VERTEX_ARRAY);
    }

    /* Set up index data */
    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);

    /* We allocate an extra restart index because it simplifies
    **   the element-array loop logic */
    glBufferData( GL_ELEMENT_ARRAY_BUFFER,
        NumStrips*(NumPointsPerStrip+1)*sizeof(GLushort),
        NULL, GL_STATIC_DRAW );
    indices = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER,
        GL_WRITE_ONLY);

    if (indices == NULL) {
        fprintf(stderr, "Unable to map index buffer\n");
        exit(EXIT_FAILURE);
    }
    else {
        int       i, j;
        GLushort  *index = indices;
        for (j = 0; j < NumStrips; ++j) {
            GLushort  bottomRow = j*NumYPoints;
            GLushort  topRow = bottomRow + NumYPoints;

            for (i = 0; i < NumXPoints; ++i) {
                *index++ = topRow + i;
                *index++ = bottomRow + i;
            }
            *index++ = RestartIndex;
        }

        glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
    }

    glPrimitiveRestartIndex(RestartIndex);
    glEnable(GL_PRIMITIVE_RESTART);
}

void
display()
{
    int  i, start;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glColor3f(1, 1, 1);
    glDrawElements(GL_TRIANGLE_STRIP,
        NumStrips*(NumPointsPerStrip + 1),
        GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));

    glutSwapBuffers();
}

Instanced Drawing

Advanced

OpenGL Version 3.1 (specifically, GLSL version 1.40) added support for instanced drawing, which provides an additional value—gl_InstanceID, called the instance ID, and accessible only in a vertex shader—that is monotonically incremented for each group of primitives specified.

glDrawArraysInstanced() operates similarly to glMultiDrawArrays(), except that the starting index and vertex count (as specified by first and count, respectively) are the same for each call to glDrawArrays().

glDrawArraysInstanced() has the same effect as this call sequence (except that your application cannot manually update gl_InstanceID):

for (i = 0; i < primcount; i++) {
   gl_InstanceID = i;
   glDrawArrays(mode, first, count);
}
gl_InstanceID = 0;

Likewise, glDrawElementsInstanced() performs the same operation, but allows random-access to the data in the vertex array:

The implementation of glDrawElementsInstanced() is shown here:

for (i = 0; i < primcount; i++) {
   gl_InstanceID = i;
   glDrawElements(mode, count, type, indicies);
}
gl_InstanceID = 0;

Interleaved Arrays

Advanced

Earlier in this chapter (see “Stride” on page 76), the special case of interleaved arrays was examined. In that section, the array intertwined, which interleaves RGB color and 3D vertex coordinates, was accessed by calls to glColorPointer() and glVertexPointer(). Careful use of stride helped properly specify the arrays:

static GLfloat intertwined[] =
      {1.0, 0.2, 1.0, 100.0, 100.0, 0.0,
       1.0, 0.2, 0.2, 0.0, 200.0, 0.0,
       1.0, 1.0, 0.2, 100.0, 300.0, 0.0,
       0.2, 1.0, 0.2, 200.0, 300.0, 0.0,
       0.2, 1.0, 1.0, 300.0, 200.0, 0.0,
       0.2, 0.2, 1.0, 200.0, 100.0, 0.0};

There is also a behemoth routine, glInterleavedArrays(), that can specify several vertex arrays at once. glInterleavedArrays() also enables and disables the appropriate arrays (so it combines “Step 1: Enabling Arrays” on page 72 and “Step 2: Specifying Data for the Arrays” on page 73). The array intertwined exactly fits one of the 14 data-interleaving configurations supported by glInterleavedArrays(). Therefore, to specify the contents of the array intertwined into the RGB color and vertex arrays and enable both arrays, call

glInterleavedArrays(GL_C3F_V3F, 0, intertwined);

This call to glInterleavedArrays() enables GL_COLOR_ARRAY and GL_VERTEX_ARRAY. It disables GL_SECONDARY_COLOR_ARRAY, GL_INDEX_ARRAY, GL_NORMAL_ARRAY, GL_FOG_COORD_ARRAY, GL_TEXTURE_COORD_ARRAY, and GL_EDGE_FLAG_ARRAY.

This call also has the same effect as calling glColorPointer() and glVertexPointer() to specify the values for six vertices in each array. Now you are ready for Step 3: calling glArrayElement(), glDrawElements(), glDrawRangeElements(), or glDrawArrays() to dereference array elements.

Note that glInterleavedArrays() does not support edge flags.

The mechanics of glInterleavedArrays() are intricate and require reference to Example 2-16 and Table 2-5. In that example and table, you’ll see et, ec, and en, which are the Boolean values for the enabled or disabled texture coordinate, color, and normal arrays; and you’ll see st, sc, and sv, which are the sizes (numbers of components) for the texture coordinate, color, and vertex arrays. tc is the data type for RGBA color, which is the only array that can have nonfloating-point interleaved values. pc, pn, and pv are the calculated strides for jumping into individual color, normal, and vertex values; and s is the stride (if one is not specified by the user) to jump from one array element to the next.

The effect of glInterleavedArrays() is the same as calling the command sequence in Example 2-16 with many values defined in Table 2-5. All pointer arithmetic is performed in units of sizeof(GLubyte).

Example 2-16. Effect of glInterleavedArrays(format, stride, pointer)

int str;
/*  set et, ec, en, st, sc, sv, tc, pc, pn, pv, and s
 *  as a function of Table 2-5 and the value of format
 */

str = stride;
if (str == 0)
   str = s;

glDisableClientState(GL_EDGE_FLAG_ARRAY);
glDisableClientState(GL_INDEX_ARRAY);
glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
glDisableClientState(GL_FOG_COORD_ARRAY);

if (et) {
   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
   glTexCoordPointer(st, GL_FLOAT, str, pointer);
}
else
   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
if (ec) {
   glEnableClientState(GL_COLOR_ARRAY);
   glColorPointer(sc, tc, str, pointer+pc);
}
else
   glDisableClientState(GL_COLOR_ARRAY);

if (en) {
   glEnableClientState(GL_NORMAL_ARRAY);
   glNormalPointer(GL_FLOAT, str, pointer+pn);
}
else
   glDisableClientState(GL_NORMAL_ARRAY);

glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(sv, GL_FLOAT, str, pointer+pv);

In Table 2-5, T and F are True and False. f is sizeof(GLfloat). c is 4 times sizeof(GLubyte), rounded up to the nearest multiple of f.

Table 2-5. Variables That Direct glInterleavedArrays()

Format

et

ec

en

st

sc

sv

tc

pc

pn

pv

s

GL_V2F

F

F

F

2

0

2f

GL_V3F

F

F

F

3

0

3f

GL_C4UB_V2F

F

T

F

4

2

GL_UNSIGNED_BYTE

0

c

c+2f

GL_C4UB_V3F

F

T

F

4

3

GL_UNSIGNED_BYTE

0

c

c+3f

GL_C3F_V3F

F

T

F

3

3

GL_FLOAT

0

3f

6f

GL_N3F_V3F

F

F

T

3

0

3f

6f

GL_C4F_N3F_V3F

F

T

T

4

3

GL_FLOAT

0

4f

7f

10f

GL_T2F_V3F

T

F

F

2

3

2f

5f

GL_T4F_V4F

T

F

F

4

4

4f

8f

GL_T2F_C4UB_V3F

T

T

F

2

4

3

GL_UNSIGNED_BYTE

2f

c+2f

c+5f

GL_T2F_C3F_V3F

T

T

F

2

3

3

GL_FLOAT

2f

5f

8f

GL_T2F_N3F_V3F

T

F

T

2

3

2f

5f

8f

GL_T2F_C4F_N3F_V3F

T

T

T

2

4

3

GL_FLOAT

2f

6f

9f

12f

GL_T4F_C4F_N3F_V4F

T

T

T

4

4

4

GL_FLOAT

4f

8f

11f

15f

Start by learning the simpler formats, GL_V2F, GL_V3F, and GL_C3F_V3F. If you use any of the formats with C4UB, you may have to use a struct data type or do some delicate type casting and pointer math to pack four unsigned bytes into a single 32-bit word.

For some OpenGL implementations, use of interleaved arrays may increase application performance. With an interleaved array, the exact layout of your data is known. You know your data is tightly packed and may be accessed in one chunk. If interleaved arrays are not used, the stride and size information has to be examined to detect whether data is tightly packed.

  • + Share This
  • 🔖 Save To Your Account