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

#ifdef VERT_SHADER

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 FRAG_SHADER

in vec4 ex_Color;
in vec2 ex_UV;

layout(location=0) out vec4 out_Color;

uniform sampler2D colorbuffer;

uniform float p_glow;
uniform float p_mirror_x;
uniform float p_black;
uniform float p_desaturate;


uniform float p_bloom_amount;
uniform float p_bloom_treshold;
	

#include "fxaa.glsl"
#line 37

vec3 colorGrading(vec3 col) {
	float black_level = 0.02;
	col = max(vec3(0.0), col);	// get rid of negative components
	
	// raise black level
	col *= 1.0-black_level;
	col += vec3(black_level);
	
	vec3 hsv = rgb2hsv(col);
	col.rgb = hsv2rgb(vec3(hsv.r, min(1.0, max(0.0, hsv.g - p_desaturate)), hsv.b));
	
	return col;
}

void main()
{
	vec2 resolution = textureSize(colorbuffer, 0);
	
	vec2 uv = ex_UV;
	
	if (p_mirror_x > 0.0) {
		if (p_mirror_x < 0.5) {
			uv.x -= 0.5 - p_mirror_x;
		}
	
		if (uv.x > p_mirror_x) {
			//uv.x = 1.0 - uv.x;
			uv.x = p_mirror_x - (uv.x - p_mirror_x);
		}
	}
	
	//vec4 col = applyFXAA(uv * resolution.xy, colorbuffer, resolution.xy);
	

	vec4 col = vec4(.0);
	for(float i = fract(99*p_time+length(sin(uv*1000)*10000.0)); i<20.0; i+=0.3) {
		vec2 pos = vec2(cos(i*i),sin(i*i))/resolution.xy*i*2.0;
		float l = length(pos);
		col += max(vec4(.0),p_bloom_amount*(vec4(1.0)-exp(-p_bloom_treshold*vec4(texture(colorbuffer, uv+pos).xyz,.1))))*exp(-l*l)*0.3;
	}
	
	col.rgb = colorGrading(col.rgb);
	
	col += applyFXAA(uv * resolution.xy, colorbuffer, resolution.xy);
	
	
	col.rgb *= 1.0-p_black;
	out_Color = col; 
} 

#endif