/*
   Merge Dithering and Pseudo Transparency Shader v2.8 - Pass 2
   by Sp00kyFox, 2014

   Eliminating isolated detections.

*/

#pragma parameter VL_LO "MDAPT VL LO Thresh" 1.25 0.0 10.0 0.05
#pragma parameter VL_HI "MDAPT VL HI Thresh" 1.75 0.0 10.0 0.05
#pragma parameter CB_LO "MDAPT CB LO Thresh" 5.25 0.0 25.0 0.05
#pragma parameter CB_HI "MDAPT CB HI Thresh" 5.75 0.0 25.0 0.05

#ifdef PARAMETER_UNIFORM
	uniform float VL_LO, VL_HI, CB_LO, CB_HI;
#else
	#define VL_LO 1.25
	#define VL_HI 1.75
	#define CB_LO 5.25
	#define CB_HI 5.75
#endif

/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
   - FX11 compilers
*/

#define TEX(dx,dy) COMPAT_Sample(decal, texCoord+float2((dx),(dy))*t1)
#define and(x,y) min(x,y)
#define or(x,y)  max(x,y)

float2 sigmoid(float2 signal){
	return smoothstep(float2(VL_LO, CB_LO), float2(VL_HI, CB_HI), signal);
}

#include "../../../../compat_includes.inc"
uniform COMPAT_Texture2D(decal) : TEXUNIT0;
uniform float4x4 modelViewProj;

struct out_vertex
{
	float4 position : COMPAT_POS;
	float2 texCoord : TEXCOORD0;
	float2 t1       : TEXCOORD1;
};

out_vertex main_vertex(COMPAT_IN_VERTEX)
{
#ifdef HLSL_4
	float4 position = VIN.position;
	float2 texCoord = VIN.texCoord;
#endif
	out_vertex OUT;
	OUT.position = mul(modelViewProj, position);
	OUT.texCoord = texCoord;
	OUT.t1 = 1.0 / COMPAT_texture_size;
	
	return OUT;
}

/*    FRAGMENT SHADER    */
float4 mdapt_pass2(float2 texCoord, float2 t1, COMPAT_Texture2D(decal))
{
	/*
		NW  UUL U2 UUR NE
		ULL UL  U1 UR  URR
		L2  L1  C  R1  R2
		DLL DL  D1 DR  DRR	
		SW  DDL D2 DDR SE
	*/

	float2 C = TEX( 0, 0).xy;
	

	float2 hits = float2(0.0, 0.0);
	
	//phase 1
	float2 L1 = TEX(-1, 0).xy;
	float2 R1 = TEX( 1, 0).xy;
	float2 U1 = TEX( 0,-1).xy;
	float2 D1 = TEX( 0, 1).xy;

	//phase 2
	float2 L2 = and(TEX(-2, 0).xy, L1);
	float2 R2 = and(TEX( 2, 0).xy, R1);
	float2 U2 = and(TEX( 0,-2).xy, U1);
	float2 D2 = and(TEX( 0, 2).xy, D1);
	float2 UL = and(TEX(-1,-1).xy, or(L1, U1));
	float2 UR = and(TEX( 1,-1).xy, or(R1, U1));
	float2 DL = and(TEX(-1, 1).xy, or(L1, D1));
	float2 DR = and(TEX( 1, 1).xy, or(R1, D1));

	//phase 3
	float2 ULL = and(TEX(-2,-1).xy, or(L2, UL));
	float2 URR = and(TEX( 2,-1).xy, or(R2, UR));
	float2 DRR = and(TEX( 2, 1).xy, or(R2, DR));
	float2 DLL = and(TEX(-2, 1).xy, or(L2, DL));
	float2 UUL = and(TEX(-1,-2).xy, or(U2, UL));
	float2 UUR = and(TEX( 1,-2).xy, or(U2, UR));
	float2 DDR = and(TEX( 1, 2).xy, or(D2, DR));
	float2 DDL = and(TEX(-1, 2).xy, or(D2, DL));

	//phase 4
	hits += and(TEX(-2,-2).xy, or(UUL, ULL));
	hits += and(TEX( 2,-2).xy, or(UUR, URR));
	hits += and(TEX(-2, 2).xy, or(DDL, DLL));
	hits += and(TEX( 2, 2).xy, or(DDR, DRR));

	hits += (ULL + URR + DRR + DLL + L2 + R2) + float2(0.0, 1.0) * (C + U1 + U2 + D1 + D2 + L1 + R1 + UL + UR + DL + DR + UUL + UUR + DDR + DDL);


	return float4(C * sigmoid(hits), C);
}

float4 main_fragment(COMPAT_IN_FRAGMENT) : COMPAT_Output
{
	return mdapt_pass2(VOUT.texCoord, VOUT.t1, decal);
}
COMPAT_END