## Using Indices to Add Another Triangle

Let us conclude the examples by inheriting from the AbstractRenderer class and creating another triangle simply by adding another point and using indices. Conceptually, you'll define the four points as (-1,-1, 1,-1, 0,1, 1,1). And you will ask OpenGL to draw these as (0,1,2 0,2,3). Listing 10-13 shows the code to do this. (Notice that we changed the dimensions of the triangle.)

Listing 10-13. The SimpleTriangleRenderer2 Class //filename: SimpleTriangleRenderer2.java public class SimpleTriangleRenderer2 extends AbstractRenderer {

private final static int VERTS = 4; private FloatBuffer mFVertexBuffer; private ShortBuffer mIndexBuffer;

public SimpleTriangleRenderer2(Context context) {

ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4);

vbb.order(ByteOrder.nativeOrder());

mFVertexBuffer = vbb.asFloatBuffer();

ByteBuffer ibb = ByteBuffer.allocateDirect(6 * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer();

-1.0f, -1.0f, 0, // (x1,y1,zl) 1.0f, -1.0f, 0, 0.0f, 1.0f, 0, 1.0f, 1.0f, 0

for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) {

mFVertexBuffer.put(coords[i*3+j]);

mIndexBuffer.put(myIndecesArray[i]);

mFVertexBuffer.position(0); mIndexBuffer.position(0);

protected void draw(GL10 gl) {

gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glDrawElements(GLl0.GL_TRIANGLES, 6, GLl0.GL_UNSIGNED_SHORT, mIndexBuffer);

Once the SimpleTriangleRenderer2 class is in place, you can change the code in the OpenGLTestHarnessActivity to invoke this renderer instead of the SimpleTriangleRenderer:

mTestHarness = new OpenGLTestHarness(this); mTestHarness.setRenderer(new SimpleTriangleRenderer2(this));

The changed portion is highlighted. After you change this code, you can run the OpenGLTestHarnessActivity again to see the two triangles drawn out (see Figure 10-6).

Figure 10-6. Two triangles with four points

Altering this code to allow for animation is quite simple. Update the guardedRun() method in the OpenGLDrawingThread.java class so the while loop won't wait to redraw as long as the width and height are valid. This will allow continuous redraw()s even when there is no resize(). Once a draw method is called multiple times, you can use the matrix methods to rotate, scale, and move. At that point, the ideas are similar to the ones we presented in Chapter 6.

0 0