Hi there and sorry for being a noob in shader programming.
I am trying to create a glass shader, which is quite ambitious for my skill level - I know. Nevertheless, we are growing with our challenges.
Here is where I am stuck:
I wanted to write the backfaces of my glass vase to the depth buffer in the second pass. Then in the third pass I wanted to go through the frontfaces, calculate their distance to the camera and compare it to the depth buffer. The idea was to find out how thick my object is, which differs from pixel to pixel. If this worked, I could use the thickness as an input to calculate some kind of refraction with the grab pass, which is my first one.
I put together some lines of code - just for visualization of that thickness value. It seems to work … kind of … in scene view. But if I move the camera far away, my object is lighter. If I zoom in, it is getting darker. In game view the object is all white, no matter where the camera is. Does anyone has an explanation for this behavior?
Shader "Custom/Glas"
{
Properties
{
_Radius( "Radius", Float ) = 1
}
SubShader
{
Tags { "RenderType" = "Transparent" "Queue" = "Transparent" }
GrabPass{} //----------------------------- speichere die Pixel hinter dem Objekt
Pass //----------------------------------- schreibe die Backfaces in den Tiefenpuffer
{
Name "Backfaces-2-DepthBuffer"
Cull Front
ZWrite On
ColorMask 0
}
Pass //----------------------------------- berechne die Glasstärke
{
Name "Compute Depth"
ZWrite Off
Cull Back
Blend One Zero
CGPROGRAM
#pragma target 3.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f {
float4 pos : POSITION;
float4 screenPos : TEXCOORD0;
};
v2f vert (appdata_full v)
{
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.screenPos = ComputeScreenPos(o.pos);
return o;
}
uniform sampler2D _CameraDepthTexture;
uniform float _Radius;
half4 frag( v2f i ) : COLOR
{
float sceneZ = LinearEyeDepth( tex2Dproj( _CameraDepthTexture, UNITY_PROJ_COORD( i.screenPos ) ).r );
float partZ = i.screenPos.z;
float diff = abs( sceneZ - partZ ) / _Radius;
return half4( diff, diff, diff, 1 );
}
ENDCG
}
}
}