precision highp float;
uniform sampler2D u_image;
uniform float u_scale;
uniform vec2 u_texSize;
varying vec2 v_texCoord;


vec4 CubicHermite(vec4 A, vec4 B, vec4 C, vec4 D, float t) {
  float t2 = t * t;
  float t3 = t * t * t;
  vec4 a = -A / 2.0 + (3.0 * B) / 2.0 - (3.0 * C) / 2.0 + D / 2.0;
  vec4 b = A - (5.0 * B) / 2.0 + 2.0 * C - D / 2.0;
  vec4 c = -A / 2.0 + C / 2.0;
  vec4 d = B;

  return a * t3 + b * t2 + c * t + d;
}

vec4 BicubicHermite(sampler2D image, vec2 texCoord, vec2 pixelSize) {

  vec2 textureSize = 1. / pixelSize;
  vec2 f = fract(texCoord * textureSize + .5);
  vec2 uv = (floor(texCoord * textureSize - .5) + .5) / textureSize;

  vec4 C00 = texture2D(image, uv + vec2(-pixelSize.x, -pixelSize.y));
  vec4 C10 = texture2D(image, uv + vec2(0.0, -pixelSize.y));
  vec4 C20 = texture2D(image, uv + vec2(pixelSize.x, -pixelSize.y));
  vec4 C30 = texture2D(image, uv + vec2(2.0 * pixelSize.x, -pixelSize.y));

  vec4 C01 = texture2D(image, uv + vec2(-pixelSize.x, 0.0));
  vec4 C11 = texture2D(image, uv + vec2(0.0, 0.0));
  vec4 C21 = texture2D(image, uv + vec2(pixelSize.x, 0.0));
  vec4 C31 = texture2D(image, uv + vec2(2.0 * pixelSize.x, 0.0));

  vec4 C02 = texture2D(image, uv + vec2(-pixelSize.x, pixelSize.y));
  vec4 C12 = texture2D(image, uv + vec2(0.0, pixelSize.y));
  vec4 C22 = texture2D(image, uv + vec2(pixelSize.x, pixelSize.y));
  vec4 C32 = texture2D(image, uv + vec2(2.0 * pixelSize.x, pixelSize.y));

  vec4 C03 = texture2D(image, uv + vec2(-pixelSize.x, 2.0 * pixelSize.y));
  vec4 C13 = texture2D(image, uv + vec2(0.0, 2.0 * pixelSize.y));
  vec4 C23 = texture2D(image, uv + vec2(pixelSize.x, 2.0 * pixelSize.y));
  vec4 C33 = texture2D(image, uv + vec2(2.0 * pixelSize.x, 2.0 * pixelSize.y));

  vec4 CP0X = CubicHermite(C00, C10, C20, C30, f.x);
  vec4 CP1X = CubicHermite(C01, C11, C21, C31, f.x);
  vec4 CP2X = CubicHermite(C02, C12, C22, C32, f.x);
  vec4 CP3X = CubicHermite(C03, C13, C23, C33, f.x);

  return CubicHermite(CP0X, CP1X, CP2X, CP3X, f.y);

}

void main() {
  gl_FragColor = BicubicHermite(u_image, v_texCoord, u_texSize);
}
