Shader "Unlit/Caustic"
{
	Properties
	{
		_MainTex("Texture", 2D) = "white" {}
		_Caustics1_ST("Caustics 1 ST", Vector) = (1,1,0,0)
		_Caustics2_ST("Caustics 2 ST", Vector) = (1,1,0,0)

		// Speed X, Speed Y
		_Caustics1_Speed("Caustics 1 Speed", Vector) = (1, 1, 0 ,0)
		_Caustics2_Speed("Caustics 2 Speed", Vector) = (1, 1, 0 ,0)
		_SplitRGB("SplitRGB",Range(0,1)) = 0
	}
	SubShader
	{
		Tags {"Queue" = "Transparent+100"}
		Pass
		{
			Blend One OneMinusSrcAlpha
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
			};

			struct v2f
			{
				float4 vertex : SV_POSITION;
				float4 screenPos : TEXCOORD1;
				float3 ray : TEXCOORD2;
			};

			sampler2D		_MainTex;
			float4			_MainTex_ST;
			sampler2D_float _CameraDepthTexture;

			float4			_Caustics1_ST;
			float4			_Caustics2_ST;
			float4			_Caustics1_Speed;
			float4			_Caustics2_Speed;
			float			_SplitRGB;
			fixed3 GetCausticColor(float2 uv)
			{
				fixed s = _SplitRGB;
				fixed r = tex2D(_MainTex, uv + fixed2(+s, +s)).r;
				fixed g = tex2D(_MainTex, uv + fixed2(+s, -s)).g;
				fixed b = tex2D(_MainTex, uv + fixed2(-s, -s)).b;
				return fixed3(r, g, b);
			}
			v2f vert(appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.screenPos = ComputeScreenPos(o.vertex);
				o.ray = UnityObjectToViewPos(v.vertex) * float3(-1,-1,1);
				return o;
			}

			fixed4 frag(v2f i) : SV_Target
			{

				//深度重建视空间坐标
				float2 screenuv = i.screenPos.xy / i.screenPos.w;
				//<Test
				//float linear01Depth;
				//float3 viewNormal;
				//float4 cdn = tex2D(_CameraDepthNormalsTexture, screenuv);
				//DecodeDepthNormal(cdn, linear01Depth, viewNormal);
				//return float4(cdn.rgb,1);// float4(viewNormal, 1);
				//Test>
				float depth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, screenuv);
				float viewDepth = Linear01Depth(depth) * _ProjectionParams.z;
				float3 viewPos = i.ray * viewDepth / i.ray.z;
				//转化到世界空间坐标
				float4 worldPos = mul(unity_CameraToWorld, float4(viewPos, 1.0));
				//转化为物体空间坐标
				float3 objectPos = mul(unity_WorldToObject, worldPos);
				//剔除掉在立方体外面的内容
				clip(float3(0.5, 0.5, 0.5) - abs(objectPos));
				//使用物体空间坐标的xz坐标作为采样uv
				float2 uv = objectPos.xz * _MainTex_ST.xy + 0.5;
				//fixed4 col = tex2D(_MainTex, uv + _Time.y * 0.01) + tex2D(_MainTex, uv - _Time.y * 0.01);

				fixed2 uv1 = uv * _Caustics1_ST.xy + _Caustics1_ST.zw;
				uv1 += _Caustics1_Speed.xy * _Time.y;
				fixed2 uv2 = uv * _Caustics2_ST.xy + _Caustics2_ST.zw;
				uv2 += _Caustics2_Speed.xy * _Time.y;
				float3 col = min(GetCausticColor(uv1), GetCausticColor(uv2));
				return float4(col*4, col.r);

				//fixed4 col = min(tex2D(_MainTex, uv) , tex2D(_MainTex, uv * 1.2 + float2(cos(_Time.y * 0.2), sin(_Time.y * 0.2))));
				//col.a = col.r;
				//col.rgb *= 8;
				//return col;
			}
			ENDCG
		}
	}
}
