# How to calculate 2D viewport coordinates in a shader?

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 :

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

## 1 Answer

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.

• 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. Commented Jun 11, 2016 at 17:26
• 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. Commented Jun 11, 2016 at 18:37
• 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);" Commented Jun 11, 2016 at 19:22
• It worked. Thanks! Could you edit your question so I can accept it as solution. Commented Jun 11, 2016 at 20:16
• Ok, glad I could help. Btw, cool effect. Commented Jun 12, 2016 at 5:00