Still having trouble with the whole getting world pos from depth in a shader. Ive taken the code from Lighting.cginc and put it in my shader but just cant get the right results. In the video below you will see the red area is meant to show a world position but it moves around and distorts as the camera moves, the shader is below, can any of the expert Shader authors out there give me a clue as to how I can get this working?
Edit: It says in the docs it that _CameraToWorld is a built in matrix but I need to add it to the shader code, is this wrong? Also should I be manually be setting anything such as the camera matrix, none of the unity post effects do so so I assume not.
Shader "ShowPos Effect Shader"
{
Properties
{
_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader
{
Pass
{
ZTest Always Cull Off ZWrite Off
Fog { Mode off }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
uniform float4 _MainTex_TexelSize;
struct appdata
{
float4 vertex : POSITION;
float3 texcoord : TEXCOORD0;
};
struct v2f
{
float4 pos : SV_POSITION;
float4 uv : TEXCOORD0;
float3 ray : TEXCOORD1;
};
v2f vert (appdata v)
{
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = ComputeScreenPos (o.pos);
o.ray = mul (UNITY_MATRIX_MV, v.vertex).xyz * float3(-1,-1,1);
// v.texcoord is equal to 0 when we are drawing 3D light shapes and
// contains a ray pointing from the camera to one of near plane's
// corners in camera space when we are drawing a full screen quad.
o.ray = lerp(o.ray, v.texcoord, v.texcoord.z != 0);
return o;
}
sampler2D _CameraDepthTexture;
float4x4 _CameraToWorld;
float4 frag (v2f i) : COLOR
{
i.ray = i.ray * (_ProjectionParams.z / i.ray.z);
float2 uv = i.uv.xy / i.uv.w;
float depth = tex2D(_CameraDepthTexture, uv).r;
depth = Linear01Depth(depth);
float4 vpos = float4(i.ray * depth, 1);
float3 wpos = mul(_CameraToWorld, vpos).xyz;
return float4(normalize(wpos), 1);
}
ENDCG
}
}
Fallback off
}