OpenGL ES depth buffer android, can't get to work

Viewed 11296

I'm unable to get the depth buffer working correctly on Android OpenGL ES 2.0. Regardless of what I do, the objects are always render in the order provided and completely ignore the depth buffer.

From what I've read, the default setup should have a depth buffer, but I've nonetheless tried every function I could think of to get it working:

//setup
setEGLContextClientVersion(2);
setEGLConfigChooser( true );

GLES20.glEnable( GLES20.GL_DEPTH_TEST );
GLES20.glDepthFunc( GLES20.GL_LEQUAL );
GLES20.glDepthMask( true );

//render
GLES20.glClearColor(0.8f, 0.5f, 0.8f, 1.0f);
GLES20.glClearDepthf(1.0f);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

I am placing objects at 0.5, 0.0, -0.5 in the z-axis. I can verify that this works since if I use a perspective view it will correctly alter the sizes of the objects (distant ones smaller) -- my vertex shader does nothing but apply the view matrix. If I'm correct I can't alter the depth in the fragment shader at all in ES, so that can't be wrong.

I'm stumped. I really have no idea what else I could check. Every search I do (in the web, or here) gives answers that don't seem to solve the problem (though it indicates people have had the problem for other reasons). Most examples in ES 2.0 don't actually have enough objects to test the depth buffer, so I can't be positive the sample code is correct either.


To comment: My "setup" section is called just after a call to "super" inside my derived GLSurfaceView, prior to setting the renderer. The "render" part is called first inside my renderes "onDrawFrame".

5 Answers

In my case, neither setEGLConfigChooser, glDepthFunc nor glDepthMask is needed (they may be optional). To enabling depth buffer feature, just adding glEnable(GL_DEPTH_TEST) in onSurfaceCreated should be sufficient. The cause of problem was in the other place.

The critical solution for me was to change this line in onDrawFrame:

glClear(GL_COLOR_BUFFER_BIT);

to

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

The outline is like below (in Kotlin):

override fun onSurfaceCreated(gl10: GL10, eglConfig: EGLConfig) {
    glEnable(GL_DEPTH_TEST)

    // Do something
}

override fun onDrawFrame(gl10: GL10) {
    glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)

    // Do something
}
Related