Wireframe without Z-Fighting

Sometimes, for debugging purposes, or maybe for some effects, we would like to render a model, together with the wireframe on top of it.

A simple way to to this is to first render the model normally, and then render it using RenderState.FillMode set to FillMode.Wireframe. Now if we draw it like this, the wireframe would still be colored the same way as the model. To fix this, we need to use a separate effect for drawing the wireframe, which would draw it using a single color.

If we do this, we get the following:

Z Fight

The problem is clearly visible, especially when the camera is moving. Because the object and the wireframe are drawn in the exact same position, Z-Fighting occurs.

One way to fix this, the one used in this sample, is to set the DepthBias to a non-zero value. The DepthBias is used to modify the depth of a rendered polygon. A positive value will make the depth larger, thus moving the polygon further from the camera. A negative will move the polygon close to the camera.

By using a negative depth bias, the wireframe will appear close to the camera, so no more Z-Fighting will occur.

using DepthBias

However, care must be taken with the DepthBias, and it must be kept at a low value. A high value would bring polygons that should be occluded closer to the camera, and risk making them visible, as seen in the next picture.

Depth Bias too large

In the downloadable sample, you can see a Game Component that uses a BasicEffect to draw the wireframe of a model. Before drawing, we set the DepthBias to a value, and before exiting the function, we reset it to the default value of 0.0f, so other drawing code is not affected.

When running the sample, the DepthBias for wireframe rendering is set to -0.000001f. Use the buttons indicated on the screen to adjust the DepthBias, and see how different values affect the rendering.

The sample can be downloaded here.

  • Pingback: Catalin Zima - XNA and HLSL blog » Welcome!

  • Mahdi Khodadadi Fard

    Thanks Catalin, That is great and useful sample.

  • Kenshin

    Hi Catalin,

    thank’s for the great tutorial.
    I am trying to solve a z-fight problem experienced rendering a simple axis system on a a simple scene (a box with reversed normal).

    I render each axe using a simple line primitive: graphics.DrawUserPrimitives(PrimitiveType.LineList, zaxis, 0, 1);

    Changing DepthBias do not seem to affect my axis system, but the wireframe of the stage i correctly rendered using your solution.

    Please, can you give me an hand to solve this problem?

    Kenshin

  • Xavier

    Hello Kenshin,
    I’ve the same problem… and the only solution I’ve found is to use the
    DepthBias.
    But instead to set the DepthBias = -0.000001f to the LineList, I’ve setted
    DepthBias = 0.000001f for all the other meshes…
    I jope ths helps.

  • http://ozlael.egloos.com ozlael

    thank for good post.
    I’ll link to my blog.
    god bless you 🙂