/* Scanline shader by Michael Pavone with additional filtering
 * based on 'sharp-bilinear' by Themaister (license: Public domain)
 * This is an integer prescale filter that should be combined
 * with bilinear hardware filtering (GL_BILINEAR filter or some such) to achieve
 * a smooth scaling result with minimum blur. This is good for pixel graphics
 * that are scaled by non-integer factors. */

uniform sampler2D textures[2];
uniform int need_swap;

varying mediump vec2 texcoord;
varying mediump vec4 texsize;
varying mediump vec4 prescale;
varying mediump float scanline_out;

void main()
{
	/* Figure out where in the texel to sample to get correct pre-scaled bilinear.
	 * Uses the hardware bilinear interpolator to avoid having to sample 4 times manually.*/
	mediump vec2 texel = texcoord * texsize.xy;
	mediump vec2 region_range = 0.5 - 0.5 * prescale.zw;
	mediump vec2 center_dist = fract(texel) - 0.5;
	mediump vec2 f = (center_dist - clamp(center_dist, -region_range, region_range)) * prescale.xy + 0.5;
	mediump vec4 color = texture2D(textures[0], (floor(texel) + f) * texsize.zw);

	color = mix(
		color * color,
		color,
		sin(scanline_out) * 0.5 + 0.5
	);
	color = vec4(pow(color.rgb, vec3(2.2/3.0)) * 2.0, 1.0);

	if (need_swap != 0) {
		gl_FragColor = color.bgra;
	} else {
		gl_FragColor = color;
	}
}
