

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

uniform sampler2D tex;

uniform vec4 time_s;
uniform vec4 glitch;

in vec2 texcoord_nm;

float sat( float t ) {
	return clamp( t, 0.0f, 1.0f );
}

vec2 sat( vec2 t ) {
	return clamp( t, 0.0f, 1.0f );
}

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

//note: /\ t=[0;0.5;1], y=[0;1;0]
float linterp( float t ) {
	return sat( 1 - abs( 2*t - 1 ) );
}

vec3 spectrum_offset( float t ) {
	vec3 ret;
	float lo = step(t,0.5f);
	float hi = 1.0f-lo;
	float w = linterp( remap( t, 1.0f/6.0f, 5.0f/6.0f ) );
	float neg_w = 1.0f-w;
	ret = vec3(lo,1.0f,hi) * vec3(neg_w, w, neg_w);
	return pow( ret, vec3(1.0f/2.2f) );
}

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

//note: [-1;1]
float srand( vec2 n ) {
	return rand(n) * 2 - 1;
}

float trunc( float x, float num_levels )
{
	return floor(x*num_levels) / num_levels;
}
vec2 trunc( vec2 x, float num_levels )
{
	return floor(x*num_levels) / num_levels;
}

void main()
{
	float time = mod(time_s.x,32); // + modelmat[0].x + modelmat[0].z;

	float gnm = sat(glitch.x);
	float rnd0 = rand( trunc( vec2(time), 6.0f ) );
	float r0 = sat((1.0f-gnm)*0.7f + rnd0);
	float rnd1 = rand( vec2(trunc( texcoord_nm.x, 10*r0 ), time) ); //horz
	//float r1 = 1.0f - sat( (1.0f-gnm)*0.5f + rnd1 );
	float r1 = 0.5f - 0.5f * gnm + rnd1;
	r1 = 1.0f - max( 0, ((r1<1.0f) ? r1 : 0.9999999f) ); //note: weird ass bug on old drivers
	float rnd2 = rand( vec2(trunc( texcoord_nm.y, 40*r1 ), time) ); //vert
	float r2 = sat( rnd2 );

	float rnd3 = rand( vec2(trunc( texcoord_nm.y, 10*r0 ), time) );
	float r3 = (1-sat(rnd3+0.8f)) - 0.1f;

// outcol0 = vec4( vec3( abs(r2) ), 1 );
// return;

	vec2 uv = texcoord_nm;

	float pxrnd = rand( uv + time );

	float ofs = 0.05f * r2 * glitch.x * ( rnd0 > 0.5f ? 1.0f : -1.0f );
	ofs += 0.5f * pxrnd * ofs;

	uv.y += 0.1f * r3 * glitch.x;

// outcol0 = vec4( vec3( uv.xy,0 ), 1 );
// return;

	vec4 sum = vec4(0.0f);
	vec3 wsum = vec3(0.0f);
	for( int i=0; i<10; ++i )
	{
		float t = float(i) / 10.0f;
		uv.x = sat( uv.x + ofs * t );
		vec4 samplecol = texture( tex, uv );
		vec3 s = spectrum_offset( t );
		samplecol.rgb = samplecol.rgb * s;
		sum += samplecol;
		wsum += s;
	}
	sum.rgb /= wsum;
	sum.a /= 10.0f;

	outcol0.a = sum.a;
	outcol0.rgb = sum.rgb; // * outcol0.a;
}
