我正在尝试在 opengl es 中显示一个三角形,并且我已经多次阅读本教程,但我无法弄清楚为什么会发生这种情况。它显示背景但不显示三角形,我仔细查看了代码,但找不到任何错误。
这是我的主要活动:
public class MainActivity extends Activity {
GLSurfaceView ourSurface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ourSurface = new GLSurfaceView(this);
ourSurface.setRenderer(new GLRenderer());
setContentView(ourSurface);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
ourSurface.onPause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
ourSurface.onResume();
}
}
这是我的渲染器:
public class GLRenderer implements Renderer{
private GLTriangle tri;
public GLRenderer(){
tri = new GLTriangle();
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig eglConfig) {
// TODO Auto-generated method stub
gl.glDisable(GL10.GL_DITHER);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(.8f, 0f, .2f, 1f);
gl.glClearDepthf(1f);
}
@Override
public void onDrawFrame(GL10 gl) {
// TODO Auto-generated method stub
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, 0, 0, -10, 0, 0, 0, 0, 2, 0);
tri.draw(gl);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
// TODO Auto-generated method stub
gl.glViewport(0, 0, width, height);
float ratio = (float)width/height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1f, 1, 25);
}
}
这是我的三角形:
public class GLTriangle {
private float vertices[] = {
0f,1f,
1f,-1f,
-1f,-1f
};
private FloatBuffer vertBuff;
private short pIndex[]= {0,1,2};
private ShortBuffer pBuff;
public GLTriangle(){
ByteBuffer bBuff = ByteBuffer.allocateDirect(vertices.length * 4);
bBuff.order(ByteOrder.nativeOrder());
vertBuff = bBuff.asFloatBuffer();
vertBuff.put(vertices);
vertBuff.position(0);
ByteBuffer pbBuff = ByteBuffer.allocateDirect(pIndex.length * 2);
bBuff.order(ByteOrder.nativeOrder());
pBuff = pbBuff.asShortBuffer();
pBuff.put(pIndex);
pBuff.position(0);
}
public void draw(GL10 gl){
gl.glFrontFace(GL10.GL_CW);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertBuff);
gl.glDrawElements(GL10.GL_TRIANGLES, pIndex.length, GL10.GL_UNSIGNED_SHORT, pBuff);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
}