shader_type canvas_item;
uniform sampler2D screen_texture : hint_screen_texture, filter_nearest;
uniform vec2 grid_size = vec2(640.0, 360.0);
uniform float strength = 0.32;
uniform float damage = 0.0;
float bayer(vec2 p) {
    ivec2 q = ivec2(mod(p, 4.0));
    int i = q.x + q.y * 4;
    float b[16] = float[](0.0,8.0,2.0,10.0,12.0,4.0,14.0,6.0,3.0,11.0,1.0,9.0,15.0,7.0,13.0,5.0);
    return b[i] / 16.0 - 0.5;
}
void fragment() {
    vec2 uv = (floor(SCREEN_UV * grid_size) + 0.5) / grid_size;
    vec3 col = texture(screen_texture, uv).rgb;
    float d = bayer(floor(SCREEN_UV * grid_size));
    col = mix(col, floor(clamp(col + d / 90.0, 0.0, 1.0) * 31.0 + 0.5) / 31.0, strength);
    vec2 v = SCREEN_UV * (1.0 - SCREEN_UV.yx);
    float vignette = clamp(pow(v.x * v.y * 20.0, 0.20), 0.46, 1.0);
    col *= mix(1.0, vignette, 0.45);
    col = mix(col, vec3(0.4, 0.025, 0.018), damage * (1.0 - vignette));
    COLOR = vec4(col, 1.0);
}
