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

#ifdef VERT_SHADER
#include "geometry_vertex_io.glsl"

uniform float p_pulse;
uniform float p_shake;

void process() 
{
	float face_change = mod(p_beat*0.5 + 0.75, 4.0);
	
	vec4 pos = (modelMatrix)*in_Position;
	//pos.xy *=length(pos.xy)*0.2;
	pos.z += (sin(pos.x*0.1) * sin(pos.y*0.1 + p_beat)) * length(pos.xy)*(0.5);
	pos.xy *= mix(1.0, mod(face_change, 1.0), p_pulse);
	pos.x *= 1.3;
	
	pos.xy += camshake(p_beat*1.5) * p_shake;
	
	ex_Position = viewMatrix*pos;

	gl_Position = (projectionMatrix*viewMatrix)*pos; 
}


#define PROCESSING_FUNCTION process
#include "geometry_base_vertex.glsl"

#endif


#ifdef FRAG_SHADER
#include "geometry_base_fragment_io.glsl"
#line 34 1

#define FACECOUNT (4.0)

float bumps(float x) {
	x*=3.0;
	return sin(x*6.7) + sin(x*3.1) + sin(0.2 * x) + sin(log(sin(x*1.1)*2.0));
}

void main()
{
	float face_change = mod(p_beat*0.5 + 0.75, 4.0);
	float face_index = floor(face_change);

	vec2 uv = ex_UV.xy;// + vec2(sin(ex_UV.y*8.0 + p_time)*0.1, sin(ex_UV.x*8.0 + p_time)*0.1);
	uv.x *= (1.0/FACECOUNT);
	uv.x += (1.0/FACECOUNT) * face_index;
	
	//float glitch = pow(mod(face_change, 1.0) * noise(p_time.xxx) * 0.3, 2.0);
	float glitch = pow(mod(face_change, 1.0) * bumps(p_beat) * 0.3, 2.0);
	//uv.xy += vec2(glitch, 0.0) * pow(mod(p_time + ex_Position.y*0.1 + glitch*0.1, 1.0), 8.0) * 5.0;
	//uv.xy *= 1.0 - length(uv.xy - vec2(0.5, 0.5)) * mod(face_change, 1.0) * 0.2;
	uv.xy += vec2(sin(glitch + face_index + uv.y*3.0 + p_time)*glitch, sin(glitch*0.5)) *0.1 ;
	
	vec2 eps = vec2(0.004, 0.0);
	vec4 sampld = texture(tex, uv);
	vec4 sampl_left = texture(tex, uv - eps.xy);
	vec4 sampl_right = texture(tex, uv + eps.xy);
	vec4 sampl_up = texture(tex, uv + eps.yx);
	vec4 sampl_down = texture(tex, uv - eps.yx);
	
	vec3 col = sampld.rgb;
	
	mat2 taps = mat2(1.0, -1.0, 1.0, -1.0);
	col = (sampl_left * taps[0][0] + sampl_right * taps[0][1] +
		sampl_up * taps[1][0] + sampl_down * taps[1][1]).rgb;

	vec3 sobel =  pow(col.rgb * 5.0, vec3(4.0));
	col.rgb = sobel;
	col.rgb = vec3(dot(col.rgb, vec3(1.0, 1.0, 1.0)));
	float center_dist = length(ex_Position.xy);
	col.rgb *= hsv2rgb(vec3(0.6 + mod(face_change, 1.0)*0.1 + center_dist*0.002, 1.0, 1.0)).rgb;
	//col.rgb = sampld.rgb;

	
	if (sampld.a <= ALPHA_TEST_THRESHOLD) {
		discard;
	}
	
	out_Color = vec4(col, 1.0);
	
	out_Position = ex_Position.xyz;
	out_Normal.xyz = compressv3(ex_Normal.xyz);
	//out_Material = vec4(texture(emitMap, ex_UV.xy).r, 0.0, 0.0, 0.0);
	out_Material = vec4(sobel.r, 0.0, 0.0, 0.0);
}

#endif