//Settings//
#include "/lib/settings.glsl"

//Varyings//
varying vec2 texCoord;

//Fragment Shader///////////////////////////////////////////////////////////////////////////////////
#ifdef FSH

    //Uniforms//
    #ifdef CAS
    uniform float viewWidth, viewHeight;
    #endif

    uniform sampler2D colortex1;

    //Common Functions//

    ////////////////////////////////////////////////////////////////////////
    //////////////////////////////////CAS//////////////////////////////////
    ////////////////////////////By Septonious/////////////////////////////

    #ifdef CAS
        void ContrastAdaptiveSharpening(out vec4 outColor){

            vec2 uvcas=gl_FragCoord.xy / vec2(viewWidth, viewHeight);

            vec4 originalColor=textureLod(colortex1, uvcas,0.0);

            float maxGreen=originalColor.g;
            float minGreen=originalColor.g;

            vec4  uvoff              =vec4(1.0, 0.0, 1.0, -1.0) / vec4(vec2(viewWidth, viewWidth), vec2(viewHeight, viewHeight));
            vec4  modifiedColor      =vec4(0.0);
            vec4  newColor           =textureLod(colortex1, uvcas + uvoff.yw,0.0);
                  maxGreen           =max(maxGreen, newColor.g);
                  minGreen           =min(minGreen, newColor.g);
                  modifiedColor      =newColor;
                  newColor           =textureLod(colortex1, uvcas + uvoff.xy,0.0);
                  maxGreen           =max(maxGreen, newColor.g);
                  minGreen           =min(minGreen, newColor.g);
                  modifiedColor     +=newColor;
                  newColor           =textureLod(colortex1, uvcas + uvoff.yz,0.0);
                  maxGreen           =max(maxGreen, newColor.g);
                  minGreen           =min(minGreen, newColor.g);
                  modifiedColor     +=newColor;
                  newColor           =textureLod(colortex1, uvcas - uvoff.xy,0.0);
                  maxGreen           =max(maxGreen, newColor.g);
                  minGreen           =min(minGreen, newColor.g);
                  modifiedColor     +=newColor;
            float adaptiveSharpening =0.0;
                  maxGreen           =max(0.0, maxGreen);

            adaptiveSharpening=minGreen / maxGreen;

            adaptiveSharpening =sqrt(max(0.0, adaptiveSharpening));
            adaptiveSharpening*=mix(-0.125, -0.2, 0.5);
            outColor           =(originalColor + modifiedColor * adaptiveSharpening) / (1.0 + 4.0 * adaptiveSharpening);
        }
    #endif

        //Program//
    void main(){
        vec4 color = textureLod(colortex1, texCoord, 0.0);

        #ifdef CAS
            ContrastAdaptiveSharpening(color);
        #endif

        /*DRAWBUFFERS:1*/
        gl_FragData[0] = vec4(color);

    }

#endif

//Vertex Shader/////////////////////////////////////////////////////////////////////////////////////
#ifdef VSH

//Program//
void main(){
    texCoord=gl_MultiTexCoord0.xy;

    gl_Position=ftransform();
}

#endif