// 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 texture2d target;
uniform float4 color = {1.0, 1.0, 1.0, 1.0};

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;
	float4 col : COLOR;
	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;
	vert_out.col = color;

	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 colorx = 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);
	colorx -= image.Sample(def_sampler, vert_in.t1.xw);
	colorx -= B;
	colorx -= image.Sample(def_sampler, vert_in.t1.zw);
	colorx -= D;
	colorx -= F;
	colorx -= image.Sample(def_sampler, vert_in.t3.xw);
	colorx -= H;
	colorx -= image.Sample(def_sampler, vert_in.t3.zw);

	colorx = ((E!=F && E!=D) || (E!=B && E!=H)) ? saturate(E + colorx*sharpness) : E;

	return colorx;
}

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