2
\$\begingroup\$

I've just readed a chapter of Unity iOS Essential by Robert Wiebe.

It shows a solution for handling z-figthing problem occuring while rendering a street on a plane with the same y offset.

Basically it modified Normal-Diffuse shader provided by Unity, specifing the (texture?) offset in -1, -1.

Here's basically what the shader looks like:

Shader "Custom/ModifiedNormalDiffuse" {
    Properties {
        _Color ("Main Color", Color) = (1,1,1,1)
        _MainTex ("Base (RGB)", 2D) = "white" {}
    }
    SubShader {
        Offset -1,-1   //THIS IS THE ADDED LINE
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Lambert

        sampler2D _MainTex;
        fixed4 _Color;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            half4 c = tex2D (_MainTex, IN.uv_MainTex) *_Color;
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    } 
    FallBack "Diffuse"
}

Ok. That's simple and it works. The author says about it:

...we could use a copy of the shader that draw the road at an Offset of -1, -1 so that whenever the two textures are drawn, the road is always drawn last.

I don't know CG nor GLSL, but I've a little bit of experience with HLSL. Anyway I can't figure out what exactly is going on.

Could anyone explain me what exactly Offset directly does, and how is solves z-fighting problems?

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

It appears to be a slightly misleading book. Offset does not change drawing order or even the 3D position of pixels. It simply adds some numbers to the Z value (the one that's going to the Z tests and Z-buffer) of a pixel (hence the term "offset"), making it appear above or below other triangles. This is generally used to prioritize visibility of triangles with (nearly) coincident surface planes.

To find out, what exactly is it that the parameters change, refer to the Unity ShaderLab documentation.

As for Z-fighting... in this case, offset would shift the odds of having more visible pixels towards your road plane.

\$\endgroup\$
2
  • \$\begingroup\$ +1: Thanks for the explanation. Indeed of the slightly wrong author's explanation, is this the right method to resolve z-fighting, right? \$\endgroup\$
    – Heisenbug
    Sep 11, 2012 at 10:43
  • \$\begingroup\$ It is one of such methods, yes. There are other, slightly less practical ones available, but I don't think they're worth mentioning in this particular case. \$\endgroup\$
    – snake5
    Sep 11, 2012 at 10:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .