Game Development Reference
In-Depth Information
Figure 7-14. Rendering a rectangle as two triangles with six vertices (left), and rendering it with four vertices (right)
Instead of duplicating vertex v1 and v2 with vertex v4 and v6, we define these vertices only
once. We still render two triangles in this case, but we tell OpenGL ES explicitly which vertices
to use for each triangle (that is, use v1, v2, and v3 for the first triangle and v3, v4, and v1 for
the second one)—which vertices to use for each triangle are defined via indices in our vertices
array. The first vertex in our array has index 0, the second vertex has index 1, and so on. For the
preceding rectangle, we'd have a list of indices like this:
short[] indices = { 0, 1, 2,
2, 3, 0 };
Incidentally, OpenGL ES wants us to specify the indices as shorts (which is not entirely correct;
we could also use bytes). However, as with the vertex data, we can't just pass a short array to
OpenGL ES. It wants a direct ShortBuffer . We already know how to handle that:
ByteBuffer byteBuffer = ByteBuffer.allocate(indices.length * 2);
byteBuffer.order(ByteOrder.nativeOrder());
ShortBuffer shortBuffer = byteBuffer.asShortBuffer();
shortBuffer.put(indices);
shortBuffer.flip();
A short needs 2 bytes of memory, so we allocate indices.length × 2 bytes for our ShortBuffer .
We set the order to native again and get a ShortBuffer view so that we can handle the
underlying ByteBuffer more easily. All that's left is to put our indices into the ShortBuffer and
flip it so the limit and position are set correctly.
If we wanted to draw Bob as a rectangle with two indexed triangles, we could define our vertices
like this:
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * VERTEX_SIZE);
byteBuffer.order(ByteOrder.nativeOrder());
vertices = byteBuffer.asFloatBuffer();
vertices.put( new float [] { 100.0f, 100.0f, 0.0f, 1.0f,
228.0f, 100.0f, 1.0f, 1.0f,
228.0f, 229.0f, 1.0f, 0.0f,
100.0f, 228.0f, 0.0f, 0.0f });
vertices.flip();
The order of the vertices is exactly the same as in the right part of Figure 7-14 We tell OpenGL
ES that we have positions and texture coordinates for our vertices and where it can find these
Search WWH ::




Custom Search