Pro OpenGL ES for iOS

(singke) #1

318 CHAPTER 10: OpenGL ES 2, Shaders, and...^


Now we’re ready to use our shaders, which turn out to be surprisingly straightforward.
First, glUseProgram() sets the current program, followed by the glUniform* functions
that pass the values from your app to the shaders on the card. The attributes are usually
supplied at the same time as the geometry, via the use of calls such as
glVertexAtttribPointer().
One additional note regarding this example is to be found in its setupGL() method. This
was briefly touched upon in Chapter 1 but now is a good time to take a little closer look
at how the data is actually passed to the GPU in an OpenGL ES 2 program. Vertex array
objects (VAOs), not to be confused with vertex buffer objects, represent a collection of
information that describes a specific state of your scene. As with other objects,
creating/using VAOs follows the same path: generate a unique ID, bind it, fill it up, and
then unbind it until needed. Many VAOs can be generated that haul about the pointers of
the geometry and attributes different aspects of your world. In the cube example,
consider Listing 10-7. After the VAO ID is generated and bound as the current VAO, a
vertex buffer object is created for the interleaved geometric data. Afterward, the VAO is
notified about how the VBO data is organized, and in this case, just the position and
normals are addressed.
Listing 10-7. Creating the Vertex Array Object

glGenVertexArraysOES (1, &_vertexArray);
glBindVertexArrayOES(_vertexArray);

glGenBuffers(1, &_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(gCubeVertexData), gCubeVertexData,
GL_STATIC_DRAW);

glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 24,
BUFFER_OFFSET(0));
glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 24,
BUFFER_OFFSET(12));

glBindVertexArrayOES(0);
When it comes time to draw, the VAO handle is set to be the current one, and the
normal glDrawArray() routine is called.

Earth at Night

Let’s start with our earth model and see how shaders can be used to make it more
interesting. You’re familiar with the image used for the earth’s surface, as shown in
Figure 10-2 (left), but you may have also seen a similar image of the earth at night, as
shown in Figure 10-2 (right). What would be neat is if we could show the night texture on
the dark side of the earth, instead of just a dark version of the regular texture map.
Free download pdf