#include "inc/uniforms.glsl"
#include "inc/utils.glsl"
#line 3

#ifdef VERTEX

layout(location = 0) in vec4 in_Position;
layout(location = 1) in vec4 in_Color;
// normal
layout(location = 3) in vec2 in_UV;
out vec4 ex_Color;
out vec2 ex_UV;

void main()
{
	ex_Color = in_Color;
	ex_UV = in_UV;
	gl_Position = in_Position;
}

#endif

#ifdef FRAGMENT

in vec4 ex_Color;
in vec2 ex_UV;

layout(location = 0) out vec4 out_Color;

uniform sampler2D colorbuffer;
uniform sampler2D buffew;

uniform float p_scanlines;
uniform float p_jpeg;
#define USE_SCANLINES

void main()
{
	vec3 result = vec3(.0);
	
	if (p_jpeg == 0.0) {
		result = texture(colorbuffer, ex_UV).rgb;
	} else {
		
		vec2 resolution = textureSize(buffew, 0);
		vec2 local = vec2(ivec2(gl_FragCoord.xy) % 8);
		vec2 base = gl_FragCoord.xy - local;
		
		float x = local.x, y = local.y;
		for (float u = .0; u < 8.0; u += 1.0) {
			float cos_u = cos((2.0*x + 1.0)*u*3.141592 / 16.0);
			if (u < .5) cos_u *= 1.0 / sqrt(2.0);
			for (float v = .0; v < 8.0; v += 1.0) {
				float cos_v = cos((2.0 * y + 1.0)*v*3.141592 / 16.0);
				if (v < .5) cos_v *= 1.0 / sqrt(2.0);
				if (u+v<1.0+16.0*(.5+.5*p_jpeg))
					result += (texture(buffew, (base + vec2(u, v)) / resolution).xyz)*cos_u*cos_v;
			}
		}
		result *= .25;
	}

#ifdef USE_SCANLINES
	result.rgb *= mix(1.0, mod(gl_FragCoord.y, 2), p_scanlines);
	result.rgb *= 1.0 + p_scanlines*0.5;
#endif

	out_Color = vec4(result, 1.0);// vec4((result + vec3(128.0)) / 256.0, 1.0);
}

#endif