/*********************************************************************NVMH3****

******************************************************************************/

float4x4 worldViewProj : WorldViewProjection;
float4x4 Proj : Projection;

float3 campos : CAMERAPOS;

float3 TargetPosition = float3(0,0,0);
float  FocalRange = 0.0f;
float  MaxBlurFactor = 1.0f;
float  ImageWidth;
float  ImageHeight;
float  MaxSampleRadius;
int	   DebugMode = 1;

texture BlurTexture : BlurTexture;
sampler BlurTextureSampler = sampler_state 
{
    texture = <BlurTexture>;
    AddressU  = WRAP;        
    AddressV  = WRAP;
    AddressW  = WRAP;
    MIPFILTER = LINEAR;
    MINFILTER = LINEAR;
    MAGFILTER = LINEAR;
};

texture diffuseTexture : DiffuseTexture;
sampler DiffuseTextureSampler = sampler_state 
{
    texture = <diffuseTexture>;
    AddressU  = CLAMP;        
    AddressV  = CLAMP;
    AddressW  = CLAMP;
    MIPFILTER = LINEAR;
    MINFILTER = LINEAR;
    MAGFILTER = LINEAR;
};

texture depthTexture : Custom0;
sampler DepthTextureSampler = sampler_state 
{
    texture = <depthTexture>;
};


texture halfSampleTexture : Custom1;
sampler HalfTextureSampler = sampler_state 
{
    texture = <halfSampleTexture>;
    AddressU  = WRAP;        
    AddressV  = WRAP;
    AddressW  = WRAP;
    MIPFILTER = LINEAR;
    MINFILTER = LINEAR;
    MAGFILTER = LINEAR;
};

struct vertexInput {
    float4 position				: POSITION;
    float2 texCoordDiffuse		: TEXCOORD0;
};

struct vertexOutput {
    float4 hPosition		: POSITION;
    float2 texCoordDiffuse	: TEXCOORD0;
};


vertexOutput VS_Screen(vertexInput IN) 
{
    vertexOutput OUT;
    
    OUT.hPosition = mul( IN.position, Proj );
    
    OUT.texCoordDiffuse = IN.texCoordDiffuse;
    return OUT;
}


float4 PS_TexturedGuassian2Pass( vertexOutput IN): COLOR
{
	float3 sampled = tex2D( DiffuseTextureSampler, IN.texCoordDiffuse ).xyz;
	float3 blurred = tex2D( BlurTextureSampler, IN.texCoordDiffuse ).xyz;  		
	
	float4 cameraToPixel =  tex2D( DepthTextureSampler, IN.texCoordDiffuse );	
	float3 worldPos = -(cameraToPixel - campos);
	float3 targetToPixel = TargetPosition - worldPos;
	float3 cameraToTarget = campos - TargetPosition;
	float focalDist = length(cameraToTarget);
	
	float dist = length( cameraToPixel );
		
	// Blur factor based on the distance from focal plane
	float blur = saturate( (abs(dist - focalDist) * FocalRange) / (length(cameraToTarget)/2.0f) );
    blur = blur * MaxBlurFactor;    
    		
	float3 outColor = lerp( sampled, blurred, blur );
	//return float4( blur, blur, blur, 1 );
 	
	return float4( outColor, 1 );
}



technique gaussian2Pass
{
    pass p0 
    {		
		VertexShader = compile vs_2_0 VS_Screen();
		PixelShader  = compile ps_2_0 PS_TexturedGuassian2Pass();
		cullmode = none;
    }
}