const vertexShader = `
    #include <clipping_planes_pars_vertex>
    varying vec2 vUv;
    void main() {
        vec3 transformed = vec3( position );
        vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );
        #include <clipping_planes_vertex>
        vUv = uv;
        gl_Position = projectionMatrix * mvPosition;
    }
`;

const fragmentShader = `
    #include <clipping_planes_pars_fragment>
    uniform vec3 iResolution;
    uniform sampler2D tDiffuse;
    varying vec2 vUv;
    uniform float fSharpness;
    uniform float fBrightness;
    uniform float fContrast;
    float sharpness = fSharpness / 100.0;
    float brightness = fBrightness / 255.0;
    float contrast = fContrast / 100.0;
    vec3 texsample(const int x, const int y, in vec2 fragCoord) {
        vec2 uv = fragCoord.xy ;
        uv = (uv + vec2(x, y)) / iResolution.xy;
        return texture2D(tDiffuse, uv).xyz;
    }

    vec3 texfilter(in vec2 fragCoord) {
        vec3 sum = texsample(-1, -1, fragCoord) * 0. + texsample(-1, 0, fragCoord) * -1. * sharpness + texsample(-1, 1, fragCoord) * 0. + texsample(0, -1, fragCoord) * -1. * sharpness + texsample(0, 0, fragCoord) * (4. * sharpness + 1.) + texsample(0, 1, fragCoord) * -1. * sharpness + texsample(1, -1, fragCoord) * 0. + texsample(1, 0, fragCoord) * -1. * sharpness + texsample(1, 1, fragCoord) * 0.;

        return sum;
    }

    void mainImage(out vec4 fragColor, in vec2 fragCoord) {
        vec2 fc = fragCoord.xy;
        vec3 col = texfilter(fc);
        vec3 colB = col.rgb + vec3(brightness);
        vec3 colC = (colB - vec3(0.5)) * contrast + vec3(0.5);
        fragColor = vec4(colC, 1);
    }
    void main() {
        #include <clipping_planes_fragment>
        mainImage(gl_FragColor, vUv * iResolution.xy);
    }
`;

var shaderUniformsManager = {
  Sharpness: 0.0,
  Brightness: 0.0,
  Contrast: 100.0,
};

//通过texture生成shaderMaterial
function ShaderMaterialHelper(texture, clippingPlanes) {
  const cubeShader = {
    uniforms: {
      iResolution: {
        value: new THREE.Vector3(512, 256, 1),
      },
      tDiffuse: {
        type: "t",
        value: texture,
      },
      fSharpness: { type: "f", value: shaderUniformsManager.Sharpness },
      fBrightness: { type: "f", value: shaderUniformsManager.Brightness },
      fContrast: { type: "f", value: shaderUniformsManager.Contrast },
    },
    vertexShader: vertexShader,
    fragmentShader: fragmentShader,
  };
  cubeMaterial = new THREE.ShaderMaterial({
    uniforms: cubeShader.uniforms,
    vertexShader: cubeShader.vertexShader,
    fragmentShader: cubeShader.fragmentShader,
    side: THREE.FrontSide,
    clippingPlanes: clippingPlanes,
    clipping: true,
  });
  return cubeMaterial;
}
