#version 410
#pragma include "filter_common.glsl"

// (C) 2020 David Lettier
// lettier.com
vec3 dilation(int size, float separation, float minThreshold, float maxThreshold, int shapeType, sampler2D colorTexture) {
    vec2 tex_size = textureSize(colorTexture, 0).xy;
    vec2 fragCoord = gl_FragCoord.xy;

    vec4 fragColor = texture(colorTexture, fragCoord / tex_size);

    // if (size <= 0) { return; }

    float  mx = 0.0;
    vec4  cmx = fragColor;

    for (int i = -size; i <= size; ++i) {
        for (int j = -size; j <= size; ++j) {

            bool condition = false;
            if (shapeType == 0) {
                // For a rectangular shape.
                condition = false;
            } else if (shapeType == 1) {
                // For a diamond shape;
                condition = !(abs(i) <= size - abs(j));
            } else if (shapeType == 2) {
                // For a circular shape.
                condition = !(distance(vec2(i, j), vec2(0, 0)) <= size);
            }
            if (condition) { continue; }

            vec4 c =
                texture
                ( colorTexture
                ,   ( gl_FragCoord.xy
                    + (vec2(i, j) * separation)
                    )
                    / tex_size
                );

            float mxt = dot(c.rgb, vec3(0.3, 0.59, 0.11));

            if (mxt > mx) {
                mx = mxt;
                cmx = c;
            }
        }
    }

    fragColor.rgb =
        mix
            ( fragColor.rgb
            , cmx.rgb
            , smoothstep(minThreshold, maxThreshold, mx)
            );

    return fragColor.rgb;
}



void main() {
//    vec4 mainColor = texture(p3d_Texture0, uv);
//    p3d_FragColor = vec4(vec3(0.0), mainColor.a);

    p3d_FragColor = vec4(vec3(0.0), 1.0);

    // Original color
    vec3 originalColor = texture(p3d_Texture0, uv).rgb;
    if (originalWeight > 0.0) {
        p3d_FragColor.rgb += originalColor * originalWeight;
    }

    // Bloom
    if (bloomRadius > 0 && bloomWeight > 0) {
        vec3 bloomColor = texture(p3d_Texture2, uv).rgb;
        p3d_FragColor.rgb += bloomColor * bloomWeight;
    }

//    // Dilation
//    if (dilationSize > 0.0 && dilationWeight > 0.0 && dilationSeparation > 0.0) {
//        p3d_FragColor.rgb += dilationWeight * dilation(
//            int(dilationSize),
//            dilationSeparation,
//            dilationMinThreshold,
//            dilationMaxThreshold,
//            int(dilationShapeType),
//            p3d_Texture0
//        );
//    } else {
//        p3d_FragColor.rgb += originalColor * dilationWeight;
//    }

}