#ifdef PROJECTED
#define tex2DLight tex2Dproj
#else 
#define tex2DLight tex2D
#endif

#define HQ_POSNORMAL

// Pixel data
sampler2D RenderTex;
sampler2D NormalTex;
sampler2D MaterialTex;

// Utility functions
#include "dcLineLine.HLSL"
#include "dcOutputPos.HLSL"
#include "dcCubeNormalize.HLSL"

sampler2D Shadow;
float3 ShadowPos;
float4x4 ShadowView;
float4x4 ShadowProj;

float4x4 ShadowMatrix;

// Pixel input
struct PS_INPUT{
#ifdef PROJECTED
	float4 Tex				: TEXCOORD0;
#else
	float2 Tex				: TEXCOORD0;
#endif

	float3 ViewDir			: TEXCOORD1;
};

// Pixel output
struct PS_OUTPUT{
	float4 Color			: COLOR;
};

// Functions
//static float OffsetSize = 512;
//static float InvOffsetSize = 1.0f / 512;

/*float ComputeShadow(float3 Pos){
	float4 LightProj = mul(float4(Pos, 1), ShadowMatrix);
	
	float3 Tex = abs(LightProj.xyz);
	
	float Result;
	if (Tex.x < 1 && Tex.y < 1 && Tex.z < 1){
		float Depth1 = LightProj.z;
		float Depth2 = tex2D(Shadow, LightProj.xy);
		
		Result = Depth1 > Depth2;
	}
	else Result = 0;
	
	return Result;
}*/

float ComputeShadow(float3 Pos){
	float4 LightProj = mul(float4(Pos, 1), ShadowMatrix);
	
	float3 Diff1 = Pos - ShadowPos;
	float Depth1Sq = dot(Diff1, Diff1);
	
	float4 Diff2 = tex2Dproj(Shadow, LightProj);
	float Depth2Sq = dot(Diff2.xyz, Diff2.xyz);
	
	// XY is masked by the bordercolor alpha channel
	// ZNear is masked by the sign of the dotproduct.
	// ZFar is currently not being masked.
	float Dot = clamp(dot(Diff1, Diff2.xyz), 0, 1);
	
	float Blend = Diff2.a * Dot;
	
	return (Depth1Sq > Depth2Sq) * Blend;
}

PS_OUTPUT main(const PS_INPUT Input){
	float4 NormalData = tex2DLight(NormalTex, Input.Tex);
		
	float3 Normal = UnpackNormal(NormalData.xyz);
	float3 Pos = UnpackPos(NormalData.w, Input.ViewDir);
		
	
	PS_OUTPUT Out;
	Out.Color.rgb = 0;
	Out.Color.a = ComputeShadow(Pos) * 0.6f;
	
	return Out;
}