in vec2 uv;
in vec2 uvn;

out vec4 C;

uniform int tex_render;
uniform int tex_prev;
uniform int tex;
uniform float blocks_glitch_amt;
uniform float feedback_glitch_amt;

float rand(vec3 p3)
{
    p3  = fract(p3 * 222.1031);
    p3 += dot(p3, p3.zyx + 31.33);
    return fract((p3.x + p3.y) * p3.z);
}
float rand(vec2 p)
{
    vec3 p3  = fract(vec3(p.xyx) * .1031);
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.x + p3.y) * p3.z);
}
vec3 rand(float p)
{
    vec3 p3 = fract(vec3(p) * vec3(.1031, .1030, .0973));
    p3 += dot(p3, p3.yzx+33.33);
    return fract((p3.xxy+p3.yzz)*p3.zyx);
}

#include noise.glsl

float Bayer2(vec2 a) {
    a = floor(a);
    return fract(a.x / 2. + a.y * a.y * .75);
}

#define Bayer4(a)   (Bayer2 (.5 *(a)) * .25 + Bayer2(a))
#define Bayer8(a)   (Bayer4 (.5 *(a)) * .25 + Bayer2(a))
#define Bayer16(a)  (Bayer8 (.5 *(a)) * .25 + Bayer2(a))
#define Bayer32(a)  (Bayer16(.5 *(a)) * .25 + Bayer2(a))
#define Bayer64(a)  (Bayer32(.5 *(a)) * .25 + Bayer2(a))

void main() {
    vec2 u = uvn;

    C = max(texture(textures[tex_render], u),0.);


//    uniform float blocks_glitch_amt;
//    uniform float feedback_glitch_amt;
    if(true){
        vec2 md = vec2(0.1,0.1);
        vec2 muv = u;
        vec2 fluv = floor(muv/md)*md;
        muv = fract(muv/md)*md;
        
        float jigg_amt = 0.005 * blocks_glitch_amt;

        vec2 jiggle = jigg_amt * valueNoise(hash12(fluv)*100.0 + T*10.0, 1.0).xy;
        jiggle = jiggle - 0.5*jigg_amt;
        vec2 prev_jiggle = jigg_amt * valueNoise(hash12(fluv)*100.0 + T*10.0 - 0.04, 1.0).xy;
        prev_jiggle = prev_jiggle - 0.5*jigg_amt;
        
//        ;
//        muv += 0.2 * sin(vec2(rand(fluv),rand(fluv + 124.5))*T+fract(sin(fluv*124.421)*124.532));
        muv += jiggle;
        muv += fluv;

        vec2 jigg_deriv = (jiggle - prev_jiggle)/0.04;
        float bay = Bayer8(U.xy);
        
        u += bay * jigg_deriv;

        C -= C;
        u = muv;
        float its = 3 * 5;
        for(int ch = 0; ch < 3; ch++){
            for (float i = 0.; i < its; i++){
                C[ch] += max(texture(textures[tex_render], u + jigg_deriv*float(ch + 1.)*0.4), 0.)[ch];
            }
        }
        C /= its/1;

    }
    if(true){
        float glitch_feedback_amt = 0.998 * feedback_glitch_amt;
        vec4 prev_frame = texture(textures[tex_prev], u);
//        vec4 curr_frame = texture(textures[tex_render], u);
        vec4 curr_frame = C;
        C = mix(curr_frame,prev_frame, glitch_feedback_amt*(luma(curr_frame.rgb)));
    }

//    C = sqrt(C);
//    C = 1.-C;
//    C = FXAA(textures[tex_render], u);
//    C=pow(
//        C,
//        vec4(.4545)
//    );

    C.w = 1.0;
}
