0
\$\begingroup\$

In Unity, I use the following shader to calculate 2D viewport coordinates :

Shader "Foo"
{
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            struct vertInput {
                float4 pos : POSITION;
            }; 

            struct vertOutput {
                float4 pos : SV_POSITION;
                float4 uv : TEXCOORD0;
            };

            vertOutput vert (vertInput input)
            {
                vertOutput o;
                o.pos = mul(UNITY_MATRIX_MVP, input.pos);
                o.uv = mul(UNITY_MATRIX_MVP, input.pos);
                return o;
            }

            fixed4 frag (vertOutput output) : SV_Target
            {   
                float2 viewport = output.uv.xy / output.uv.z;
                return float4(sin(viewport.x*10.0), sin(viewport.y*10.0), 0.0, 1.0);
            }
            ENDCG
        }
    }
}

At first, it seems to work great. Here is results :

enter image description here

However if I move camera very close to the surface, the following unexpected glitch occurs :

enter image description here

\$\endgroup\$
1
\$\begingroup\$

When the distance to the camera is really small, you can end up dealing with very small numbers which create floating point rounding errors in your calculations. If you change

o.uv = mul(UNITY_MATRIX_MVP, input.pos);

to

o.uv = mul(UNITY_MATRIX_MV, input.pos);

then the projection portion of the matrix will no longer be included in your calculations (for the uv component at least), which has the effect of making the distance to the camera irrelevant and removing that warping.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ The issue i'm referring are not the tiny dots that you see in far away (which are indeed related to AA). It is the fact that the rendering should looks like first image. instead, the rendering distort itself progressively to the point it looks like 2nd image. \$\endgroup\$ – tigrou Jun 11 '16 at 17:26
  • \$\begingroup\$ I have put a video here : drive.google.com/file/d/0B0hZ6ptq8VzqWUVrMzcweDFHR00/… Please note i'm only zooming on the quad. At some point it get distorted while expect it to stay like before or totally disappear. \$\endgroup\$ – tigrou Jun 11 '16 at 18:37
  • \$\begingroup\$ Ok, you then you need to take the projection portion of the matrix out of the uv calculation: "o.uv = mul(UNITY_MATRIX_MV, input.pos);" \$\endgroup\$ – Tealr Jun 11 '16 at 19:22
  • \$\begingroup\$ It worked. Thanks! Could you edit your question so I can accept it as solution. \$\endgroup\$ – tigrou Jun 11 '16 at 20:16
  • \$\begingroup\$ Ok, glad I could help. Btw, cool effect. \$\endgroup\$ – Tealr Jun 12 '16 at 5:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.