
float4 sddx;
texture Texture0 : ZBackBuffer;
texture Texture1 : BlurBackBuffer;

sampler DepthMap = 
sampler_state
{
    Texture = <Texture0>;
    MinFilter = Linear;
	MagFilter = Linear;
	AddressU = Clamp;
	AddressV = Clamp;
};

sampler AmbientOcclusionMap = 
sampler_state
{
    Texture = <Texture1>;
    MinFilter = Linear;
	MagFilter = Linear;
	AddressU = Clamp;
	AddressV = Clamp;
};


//------------------------------------
struct vertexOutput {
    float4 HPosition : POSITION;
    float2 UV0	: TEXCOORD0;
};


float4 PS(vertexOutput In) : COLOR0
{    
	float color 	= tex2D(AmbientOcclusionMap, In.UV0).x;
	float depth 	= tex2D(DepthMap, In.UV0).x;
	float num = 1;

	int blurdist = 8;
		
	//for( int i = -blurdist/2; i <= blurdist/2; i+=1)
	for (int i = 0; i < blurdist; ++i)
	{
		float2 texCoord = In.UV0 + sddx.xy * 4.0 * float2(
													sin((3.141 / 4.0) * i),
													cos((3.141 / 4.0) * i)
												);
												
		//texCoord = In.UV0 + i * sddx.xy;
		
		float newsample = tex2D(AmbientOcclusionMap, texCoord).x;
		float newdepth = tex2D(DepthMap, texCoord).x;
		
		float depthDif = (newdepth - depth)*100.0f;
		float depthDifSqr = depthDif* depthDif;
				
		// Blur if samples are less than 10cm apart	and angle between their normals is less than about 10 deg
		//if(depthDifSqr > 10)
		{
			num += 1;//  ( blurdist/2 - abs(i-blurdist/2.0f));
			color += newsample;// *  ( blurdist/2 - abs(i-blurdist/2.0f));
		}
	}
	
	float4 outColor = color/num;
	outColor.a = 1.0f;
	return outColor;
}


technique Effect
{
    pass P0
    {
		ColorOp[0] = SelectArg1;
		ColorArg1[0] = Texture;
    	ColorOp[1] = SelectArg1;
		ColorArg1[1] = Texture;
		
		VertexShader = NULL;
		PixelShader  = compile ps_2_0 PS();	
	
		CullMode = None;
		ZEnable = true;
		ZFunc = ALWAYS;
		ZWriteEnable = false;
    }
}
