import Filter from "../Filter";
import { defaultVert } from "../defaultVerts";

const blurFrag = [
    "precision mediump float;",
    "varying vec2 vTextureCoord;",
    "uniform sampler2D uSampler;",
    "const float resolution=1024.0;",
    "uniform float radius;",//radius可为1.4
    "uniform vec2 dir;",//若为x模糊，可传入（1.0,0.0）  y模糊  （0.0,1.0）

    "void main() {",
    //this will be our RGBA sum
    "vec4 sum = vec4(0.0);",

    //our original texcoord for this fragment
    "vec2 tc = vTextureCoord;",

    //the amount to blur, i.e. how far off center to sample from 
    //1.0 -> blur by one pixel
    //2.0 -> blur by two pixels, etc.
    "float blur = radius/resolution;",

    //the direction of our blur
    //(1.0, 0.0) -> x-axis blur
    //(0.0, 1.0) -> y-axis blur
    "float hstep = dir.x;",
    "float vstep = dir.y;",


    //apply blurring, using a 9-tap filter with predefined gaussian weights

    "sum += texture2D(uSampler, vec2(tc.x - 4.0*blur*hstep, tc.y - 4.0*blur*vstep)) * 0.0162162162;",
    "sum += texture2D(uSampler, vec2(tc.x - 3.0*blur*hstep, tc.y - 3.0*blur*vstep)) * 0.0540540541;",
    "sum += texture2D(uSampler, vec2(tc.x - 2.0*blur*hstep, tc.y - 2.0*blur*vstep)) * 0.1216216216;",
    "sum += texture2D(uSampler, vec2(tc.x - 1.0*blur*hstep, tc.y - 1.0*blur*vstep)) * 0.1945945946;",

    "sum += texture2D(uSampler, vec2(tc.x, tc.y)) * 0.2270270270;",

    "sum += texture2D(uSampler, vec2(tc.x + 1.0*blur*hstep, tc.y + 1.0*blur*vstep)) * 0.1945945946;",
    "sum += texture2D(uSampler, vec2(tc.x + 2.0*blur*hstep, tc.y + 2.0*blur*vstep)) * 0.1216216216;",
    "sum += texture2D(uSampler, vec2(tc.x + 3.0*blur*hstep, tc.y + 3.0*blur*vstep)) * 0.0540540541;",
    "sum += texture2D(uSampler, vec2(tc.x + 4.0*blur*hstep, tc.y + 4.0*blur*vstep)) * 0.0162162162;",

    "vec4 cc= texture2D(uSampler,vTextureCoord );",

    //discard alpha for our simple demo, multiply by vertex color and return
    "gl_FragColor =vec4(sum.rgb, cc.a);",
    "}"
].join("\n")

//简单新能高点的模糊滤镜
export default class BlurFilterNew extends Filter {
    private _blur: number;
    get blur() {
        return this._blur;
    }
    /**
     * 系数0到1
     */
    set blur(value) {
        if (this._blur === value) return;
        if (value > 1) value = 1;
        if (value < 0) value = 0;
        this._blur = value
        this.uniforms.radius = value * 10;
    }
    /**
     * 
     * @param blur 模糊系数 0到1
     */
    constructor(blur: number = 0.5) {
        super(defaultVert, blurFrag);
        this.blur = blur;
        //先固定吧
        this.uniforms.dir = [1.0, 1.0];
    }
}