// Based on libretro shader https://github.com/libretro/common-shaders/blob/master/test/lab/misc/sharpness.cg
// Converted to obs effect file by Nibbles

uniform float4x4 ViewProj;
uniform texture2d image;

uniform float sharpness;
uniform float texture_width;
uniform float texture_height;

sampler_state def_sampler {
	Filter   = Linear;
	AddressU = Clamp;
	AddressV = Clamp;
};

struct VertInOut {
	float4 pos : POSITION;
	float2 uv  : TEXCOORD0;
};

struct VertOut {
	float4 pos : POSITION;
	float2 uv  : TEXCOORD0;
	float4 t1  : TEXCOORD1;
	float4 t2  : TEXCOORD2;
	float4 t3  : TEXCOORD3;
};

VertOut VSDefault(VertInOut vert_in)
{
	VertOut vert_out;
	vert_out.pos = mul(float4(vert_in.pos.xyz, 1.0), ViewProj);
	vert_out.uv  = vert_in.uv;

	float2 ps = float2(1.0/texture_width, 1.0/texture_height);
	float dx = ps.x;
	float dy = ps.y;

	vert_out.t1 = vert_in.uv.xxxy + float4( -dx, 0, dx,    -dy); //  A  B  C
	vert_out.t2 = vert_in.uv.xxxy + float4( -dx, 0, dx,      0); //  D  E  F
	vert_out.t3 = vert_in.uv.xxxy + float4( -dx, 0, dx,     dy); //  G  H  I
	return vert_out;
}

float4 PSDrawBare(VertOut vert_in) : TARGET
{
	float4 E  = image.Sample(def_sampler, vert_in.uv);

	float4 color = 8*E;
	float4 B = image.Sample(def_sampler, vert_in.t1.yw);
	float4 D = image.Sample(def_sampler, vert_in.t2.xw);
	float4 F = image.Sample(def_sampler, vert_in.t2.zw);
	float4 H = image.Sample(def_sampler, vert_in.t3.yw);
	color -= image.Sample(def_sampler, vert_in.t1.xw);
	color -= B;
	color -= image.Sample(def_sampler, vert_in.t1.zw);
	color -= D;
	color -= F;
	color -= image.Sample(def_sampler, vert_in.t3.xw);
	color -= H;
	color -= image.Sample(def_sampler, vert_in.t3.zw);

	color = ( (distance(E,F) != 0.0 && distance(E,D) != 0.0) || (distance(E,B) != 0.0 && distance(E,H) != 0.0) ) ? saturate(E + color * sharpness) : E;

	return color;
}

technique Draw
{
	pass
	{
		vertex_shader = VSDefault(vert_in);
		pixel_shader  = PSDrawBare(vert_in);
	}
}
