#version 150

vec4 compress(vec4 in_color, float threshold, float ratio) {
  vec4 diff = in_color - vec4(threshold);
  diff = clamp(diff, 0.0, 100.0);
  return in_color - (diff * (1.0 - 1.0 / ratio));
}

uniform sampler2D source[];
uniform vec4 sourceSize[];

in Vertex {
  vec2 texCoord[9];
};

out vec4 fragColor;

void main() {
  vec3 c00 = texture2D(source[0], texCoord[1]).xyz;
  vec3 c01 = texture2D(source[0], texCoord[8]).xyz;
  vec3 c02 = texture2D(source[0], texCoord[7]).xyz;
  vec3 c10 = texture2D(source[0], texCoord[2]).xyz;
  vec3 c11 = texture2D(source[0], texCoord[0]).xyz;
  vec3 c12 = texture2D(source[0], texCoord[6]).xyz;
  vec3 c20 = texture2D(source[0], texCoord[3]).xyz;
  vec3 c21 = texture2D(source[0], texCoord[4]).xyz;
  vec3 c22 = texture2D(source[0], texCoord[5]).xyz;

  vec2 tex = texCoord[0].xy;
  vec2 texsize = sourceSize[0].xy;

  vec3 first = mix(c00, c20, fract(tex.x * texsize.x + 0.5));
  vec3 second = mix(c02, c22, fract(tex.x * texsize.x + 0.5));

  vec3 mid_horiz = mix(c01, c21, fract(tex.x * texsize.x + 0.5));
  vec3 mid_vert = mix(c10, c12, fract(tex.y * texsize.y + 0.5));

  vec3 res = mix(first, second, fract(tex.y * texsize.y + 0.5));
  vec4 final = vec4(0.26 * (res + mid_horiz + mid_vert) + 3.5 * abs(res - mix(mid_horiz, mid_vert, 0.5)), 1.0);
  fragColor = compress(final, 0.8, 5.0);
}
