layout(location = 0, index = 0) out vec4 outcol0;

uniform sampler2D tex0;
uniform vec4 sharpen;
uniform vec4 texelsize;
uniform vec4 time_s;

in vec2 texcoord0_nm;

//remaps interval [a;b] to [0;1]
float remap( float t, float a, float b ) {
	return clamp( (t - a) / (b - a), 0, 1 );
}


//note: [0;1]
vec3 nrand3( vec2 n ) {
	return fract(sin(dot(n.xy, vec2(12.9898, 78.233)))* vec3(43758.5453, 28001.8384, 50849.4141) );
}

void main()
{
	vec4 ctr = texture( tex0, texcoord0_nm );

	const vec3 rcp3 = vec3(0.333333);

	float s0 = dot( ctr.rgb, rcp3 );
	
	float s1 = dot( texture( tex0, texcoord0_nm + vec2( 1,0)*texelsize.zw ).rgb, rcp3 );
	float s2 = dot( texture( tex0, texcoord0_nm + vec2(-1,0)*texelsize.zw ).rgb, rcp3 );
	float s3 = dot( texture( tex0, texcoord0_nm + vec2(0, 1)*texelsize.zw ).rgb, rcp3 );
	float s4 = dot( texture( tex0, texcoord0_nm + vec2(0,-1)*texelsize.zw ).rgb, rcp3 );

	float s5 = dot( texture( tex0, texcoord0_nm + vec2( 1, 1)*texelsize.zw ).rgb, rcp3 );
	float s6 = dot( texture( tex0, texcoord0_nm + vec2(-1,-1)*texelsize.zw ).rgb, rcp3 );
	float s7 = dot( texture( tex0, texcoord0_nm + vec2(-1, 1)*texelsize.zw ).rgb, rcp3 );
	float s8 = dot( texture( tex0, texcoord0_nm + vec2( 1,-1)*texelsize.zw ).rgb, rcp3 );

	float hz = abs( s2 - s1 );
	float vt = abs( s3 - s4 );
	float d1 = abs( s5 - s6 );
	float d2 = abs( s7 - s8 );
	
	//float its = hz + vt + 0.5*(d1+d2);
	float its = 2.5*min(max(hz,vt), max(d1,d2));

	float out_edge = 5.0 * sharpen.x * remap( its, sharpen.y, sharpen.z );

	outcol0 = vec4( max( vec3(out_edge) / (1-ctr.rgb), ctr.rgb ), ctr.a );
	outcol0.rgb = mix( clamp(outcol0.rgb,0,1), vec3(out_edge), sharpen.w );

	outcol0.rgb += nrand3( texcoord0_nm + fract(time_s.x+0.59318) ) / 255.0;
}
