Question

I understand that by setting the depth function in OpenGL ES one can control how overlapping geometries are rendered in a 3D scene. I use gl.depthFunc(gl.LEQUAL) (webgl) in my code.

However when two sets of polygons are coincident and are of different color, the resulting surface turns out to be an arbitrary mixed pattern of the two colors (which changes as the camera location changes, hence leads to flickering). Take a look at this image:

enter image description here

How can I fix this? I have tried different depthFunc values, but none of them solves this problem. I would like the coincident polygons to have single color, it doesn't matter which one.

Was it helpful?

Solution

This is called z-fighting, and is related to two objects being rendered at the same depth, but rounding errors (and depth buffer precision) occasionally popping one in front of the other. One solution available to you is to use the glPolygonOffset function:

http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPolygonOffset.xml

You can see an example of it in use at the bottom of this page:

http://www.glprogramming.com/red/chapter06.html

OTHER TIPS

What you experience is called Z fighting and unfortunately there's not definitive solution against it. What happens is, that due to the limited precision of the depth buffer, rounding errors occur and either one of the primitives "win" the depth test operation. Changing the depth function will just toggle the colours in the fighting pattern, but not remove it.

One method to get rid of the Z fighting is using polygon offset http://www.opengl.org/wiki/Basics_Of_Polygon_Offset

Unfortunately polygon offset introduces its own share of problems.

Try changing your z-near to be farther from zero in your call to gluPerspective:

void gluPerspective(
    GLdouble    fovy,
    GLdouble    aspect,
    GLdouble    zNear,
    GLdouble    zFar);

From this website: http://www.opengl.org/resources/faq/technical/depthbuffer.htm

Depth buffering seems to work, but polygons seem to bleed through polygons that are in front of them. What's going on?

You may have configured your zNear and zFar clipping planes in a way that severely limits your depth buffer precision. Generally, this is caused by a zNear clipping plane value that's too close to 0.0. As the zNear clipping plane is set increasingly closer to 0.0, the effective precision of the depth buffer decreases dramatically. Moving the zFar clipping plane further away from the eye always has a negative impact on depth buffer precision, but it's not one as dramatic as moving the zNear clipping plane.

Try messing with glPolygonOffset(factor, units). This page might help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top