
// ------- UNIFORMS (SHADER CONSTS) -------
uniform sampler2D	hu_sSceneTexture0;
uniform sampler2D	hu_sDepthTexture0;
uniform vec4		hu_vCameraNearFar;

uniform vec4		u_vAlphaDistanceFunction;
uniform vec4		u_vAlphaDistanceFunctionOutline;
uniform vec4		u_vOutlineColor;

// ------- INTERPOLATORS (SHADER INPUTS) -------
varying vec2		v_vTex0UV;
varying vec2		v_vUV0;
varying vec2		v_vUV1;
varying vec2		v_vUV2;
varying vec2		v_vUV3;

// ------- FUNCTIONS ------- 

float GetDist(sampler2D sDepth, vec2 vCoords)
{
	float fDepth = texture2D(sDepth, vCoords).x;
	// linear depth = (2.0 * n) / (f + n - z * (f - n));
	float fLinearDepth = (2.0*hu_vCameraNearFar.x)/(hu_vCameraNearFar.w - fDepth*hu_vCameraNearFar.z);
	return fLinearDepth*hu_vCameraNearFar.z;
}

vec4 Blend(vec4 f1, vec4 f2)
{
	//float a = a1 + a2 - a1*a2;
	//f = (f1*a1 + f2*a2*(1.0 - a1))/a; // = (f1*a1 + f2*a2 - f2*a1*a2)/a;
	
	vec4 f;
	float a = f1.a + f2.a - f1.a*f2.a;
	f = vec4((f1.rgb*f1.a + f2.rgb*(f2.a*(1.0 - f1.a)))/a, a);
	//f = vec4((f1.rgb*f1.a + f2.rgb*f2.a - f2.rgb*(f1.a*f2.a))/a, a);
	return f;
}

void main(void)
{
	vec4 f = texture2D(hu_sSceneTexture0, v_vTex0UV);

	if (f.b < 0.99)
	{
		float fDist = GetDist(hu_sDepthTexture0, v_vTex0UV);

		bool b = f.a <= texture2D(hu_sSceneTexture0, v_vUV0).a && f.a <= texture2D(hu_sSceneTexture0, v_vUV1).a && 
			f.a <= texture2D(hu_sSceneTexture0, v_vUV2).a && f.a <= texture2D(hu_sSceneTexture0, v_vUV3).a;

// 		f.a = GetGrowingValue(u_vAlphaDistanceFunction, fDist);
// 		if ( !b)
// 		{	// outline
// 			vec3 c = lerp(f.rgb, u_vOutlineColor.rgb, f.a);
// 			float a = GetGrowingValue(u_vAlphaDistanceFunctionOutline, fDist);
// 			float t = a*u_vOutlineColor.a;
// 			f = vec4(c, t);
// 			//vec4 v = Blend(f, vec4(u_vOutlineColor.rgb, t));
// 			//f = v;
// 		}
		
		if (b)
		{	// inside
			f.a = GetGrowingValue(u_vAlphaDistanceFunction, fDist);
		}
		else
		{	// outline
			f.rgb = u_vOutlineColor.rgb;
			float a = GetGrowingValue(u_vAlphaDistanceFunctionOutline, fDist);			
			f.a = a*u_vOutlineColor.a;
		}
	}
	else
	{
		f.a = 0.0;
	}

	gl_FragColor = f;
}
