开始学习OpenGL ES。绘制四边形

时间:2013-11-28 12:04:27

标签: android opengl-es

我尝试用开放式GL ES 1.0绘制四边形。 但我有一个例外,它说我试图绘制比我更多的顶点。

渲染器代码:

package com.example.MyGLTest;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

public class OpenGLRenderer implements GLSurfaceView.Renderer{

    FloatBuffer plaineVerticesBuffer;
    FloatBuffer plaineIndicesBuffer;

    private float[] plaineVertices = {
            -1, -1, 0, //bottom left corner
            -1,  1, 0, //top left corner
            1,  1, 0,  //top right corner
            1, -1, 0   // bottom right rocner
    };
    private float plaine_indices[] = {
            0,1,2, // first triangle (bottom left - top left - top right)
            0,2,3 // second triangle (bottom left - top right - bottom right);
    };

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {


        ByteBuffer bb = ByteBuffer.allocateDirect(plaineVertices.length * 4);
        bb.order(ByteOrder.nativeOrder());
        plaineVerticesBuffer = bb.asFloatBuffer();
        plaineVerticesBuffer.put(plaineVertices);

        ByteBuffer bb1  = ByteBuffer.allocateDirect(plaine_indices.length * 4);
        bb1.order(ByteOrder.nativeOrder());
        plaineIndicesBuffer = bb1.asFloatBuffer();
        plaineIndicesBuffer.put(plaine_indices);
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {

    }

    @Override
    public void onDrawFrame(GL10 gl) {
        //GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        gl.glColor4f(0.0f, 1.0f, 0.0f, 0.5f);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

        gl.glVertexPointer(4,GL10.GL_FLOAT,0, plaineVerticesBuffer);
        gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, 6 ,GL10.GL_FLOAT, plaineIndicesBuffer);
    }
}

logcat错误:

java.lang.ArrayIndexOutOfBoundsException: remaining() < count < needed
        at com.google.android.gles_jni.GLImpl.glDrawElements(Native Method)
        at com.example.MyGLTest.OpenGLRenderer.onDrawFrame(OpenGLRenderer.java:60)
        at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1531)
        at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1248)

任何人都可以解释我为什么会收到此错误吗?

1 个答案:

答案 0 :(得分:0)

您正在追踪一个包含2个三角形的条带,并且您正在传递6个顶点。您应该绘制GL_TRIANGLES或修复索引。