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

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

float4x4 worldViewProj : WorldViewProjection;
float4x4 Proj : Projection;

float3 campos : CAMERAPOS;

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


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

texture depthTexture2 : Custom2;
sampler DepthTextureSampler2 = sampler_state 
{
    texture = <depthTexture2>;
};


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

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


float WorkingSaturate(float x)
{
    if (x<0)
        x = 0;
    else if (x>1)
        x = 1;
    return x;
}


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


//-----------------------------------
float4 PS_Textured( vertexOutput IN): COLOR
{
	float3 fullColor = float3(0.8f, 0.95f, 0.95f);
	float3  noColor = float3(0.1f, 0.4f, 0.4f);
	
	float3 sampled = tex2D( DiffuseTextureSampler, IN.texCoordDiffuse ).xyz; 
	
	float4 worldPosBack =  tex2D( DepthTextureSampler, IN.texCoordDiffuse );
	
	//return float4( normalize( worldPosBack.xyz), 1);
	
	float4 worldPosFront =  tex2D( DepthTextureSampler2, IN.texCoordDiffuse );
	//return float4( normalize(worldPosFront.xyz), 1);
	
	float lengthFrontToBack = length( worldPosBack.xyz - worldPosFront.xyz );
	float lengthCamToBack = length( worldPosBack.xyz - campos.xyz );
	
	float thickness = min( lengthCamToBack, lengthFrontToBack );
	
	//thickness =  lengthFrontToBack;
	
	thickness = thickness / 60.0f;
	//return float4( lengthFrontToBack, lengthFrontToBack, lengthFrontToBack, 1 );
	
	thickness = pow( thickness, 3.0 );
	thickness = clamp( thickness, 0.0f, 1.0f );
	
	//lengthFrontToBack = 1.0f - lengthFrontToBack;
	
	float3 outcolor;
	float bg = sampled.x + sampled.y + sampled.z;
	if( bg == 0.0f )
		outcolor = noColor;
	else
		outcolor = lerp( noColor, fullColor, thickness);
		
	
	return float4( outcolor, 1 );
	
	float3 mixColor = float3(1,1,1);
	
	float3 outColor = mixColor * lengthFrontToBack;
	
    return float4( outColor, 1 );
}



//-----------------------------------
technique basic
{
    pass p0 
    {		
		VertexShader = compile vs_2_0 VS_Screen();
		PixelShader  = compile ps_2_0 PS_Textured();
		cullmode = none;
    }
}
