import { Scene } from "../base/Scene";
import { TextureLayer } from "../base/TextureLayer";


const LineArtShader = /*glsl*/ `

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

const float w1 = 0.147761;
const float w2 = 0.118318; 
const float w3 = 0.0947416; 


vec4 GaussianBlur(in sampler2D image, in vec2 texCoord, in vec2 pixelSize) {
  vec4 C00 = texture2D(image, texCoord + vec2(-pixelSize.x, -pixelSize.y)) * w3 ;
  vec4 C01 = texture2D(image, texCoord + vec2(0.0, -pixelSize.y)) * w2;
  vec4 C02 = texture2D(image, texCoord + vec2(pixelSize.x, -pixelSize.y)) * w3 ;

  vec4 C10 = texture2D(image, texCoord + vec2(-pixelSize.x, 0.0)) * w2;
  vec4 C11 = texture2D(image, texCoord + vec2(0.0, 0.0)) * w1;
  vec4 C12 = texture2D(image, texCoord + vec2(pixelSize.x, 0.0)) * w2;

  vec4 C20 = texture2D(image, texCoord + vec2(-pixelSize.x, pixelSize.y)) * w3;
  vec4 C21 = texture2D(image, texCoord + vec2(0.0, pixelSize.y)) * w2;
  vec4 C22 = texture2D(image, texCoord + vec2(pixelSize.x, pixelSize.y)) * w3;

  return 
    C00 + C01 + C02 +
    C10 + C11 + C12 +
    C20 + C21 + C22 ;
}

void main() {

  vec4 color = GaussianBlur(u_image, v_texCoord, u_texSize);
  //vec4 color = texture2D(u_image, v_texCoord);
  //if(u_scale > 100. ) {
    if(color.a >= 0.4) {
        gl_FragColor = vec4(0.15, 0.15, 0.15, 1);
    }else{
        gl_FragColor = vec4(0, 0, 0, 0);
    }
  //}else{
  //    gl_FragColor = vec4(.15, 0.15, 0.15, color.a);
  //}

}


`;


export class LineArtLayer extends TextureLayer {

  constructor(
    scene: Scene,
    image: HTMLImageElement | HTMLCanvasElement,
    width: number,
    height: number,
  ) {
    const gl = scene.gl;

    // Create a texture.
    let texture = gl.createTexture()!;
    gl.bindTexture(gl.TEXTURE_2D, texture);

    // Set the parameters so we can render any size image.
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

    //gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);

    //Upload the image into the texture.
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, gl.ALPHA, gl.UNSIGNED_BYTE, image);
    //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

    super(scene, texture, image.width, image.height, width, height, LineArtShader)

  }
}