[[vertex]]

uniform mat4 mvp;

in vec4 pos;
in vec2 uvs;
in vec2 uvs2;
out vec2 uv;
out vec2 uv_2;
out float q;

void main()
{
    uv = uvs;
    uv_2 = uvs2;
    q = pos.w;
    gl_Position = mvp * vec4(pos.xy, 0.0, 1.0);
}

[[fragment]]

#include "include/ext-fb-fetch.glsl"
#include "include/rand.glsl"
#include "include/color.glsl"
#include "include/blend-stroke.glsl"

uniform mediump sampler2D tex;
uniform mediump sampler2D tex_bg;
uniform mediump sampler2D tex_mix;
uniform mediump vec4 col;
uniform mediump vec2 resolution;
uniform mediump float alpha;
uniform mediump float opacity;
uniform mediump float noise;
uniform mediump float mix_alpha;
uniform mediump float wet;

uniform bool use_pattern;
uniform mediump sampler2D tex_pattern;
uniform mediump vec2 pattern_scale;
uniform mediump float pattern_bright;
uniform mediump float pattern_contr;
uniform mediump float pattern_depth;
uniform mediump vec2 pattern_offset;
uniform bool pattern_invert;
uniform int patt_blend_mode;

in mediump vec2 uv;
in mediump vec2 uv_2;
in mediump float q;
#if defined(GL_EXT_shader_framebuffer_fetch)
    inout mediump vec4 frag;
#else
    out mediump vec4 frag;
#endif

void main()
{
    mediump vec2 uv2 = gl_FragCoord.st / resolution;
    mediump float brush_alpha = ( 1.0 - texture(tex, uv/q).r ) * alpha;
    mediump vec4 fg = vec4(col.rgb, brush_alpha);

    // early discard
    if (fg.a == 0.0)
        discard;

    if (use_pattern)
    {
        mediump vec2 rscale = resolution / vec2(512.0);
        mediump float patt = texture(tex_pattern, uv2 * (1.0 / pattern_scale) * rscale + pattern_offset).r;
        if (pattern_invert)
            patt = 1.0 - patt;
        patt = patt * pattern_depth + (1.0 - pattern_depth);
        if (pattern_bright != 0.5)
            patt = brightness1(patt, 1.0 - pattern_bright);
        if (pattern_contr != 0.5)
            patt = contrast1(patt, pattern_contr);
        fg.a = blend_stroke(fg.a, patt, pattern_depth, patt_blend_mode);
    }

#if defined(GL_EXT_shader_framebuffer_fetch)
    mediump vec4 bg = frag;
#elif defined(GL_ARM_shader_framebuffer_fetch)
    mediump vec4 bg = gl_LastFragColorARM;
#else
    mediump vec4 bg = texture(tex_bg, uv2);
#endif

    fg.a *= 1.0-rand(uv2+uv)*noise;

    // no need to go further
    if (fg.a <= 0.0)
        discard;

    if (mix_alpha > 0.0)
    {
        mediump vec2 uv_mix = uv_2 / q;
        if (uv_mix.x < 0.0 || uv_mix.x > 1.0 || uv_mix.y < 0.0 || uv_mix.y > 1.0) discard;
        mediump vec4 mbg = texture(tex_mix, uv_mix);
        fg.rgb = mix(fg.rgb, mbg.rgb, mix_alpha * mbg.a);
    }

    mediump float contribution = max(0.0, opacity - bg.a) * fg.a;
    mediump float alpha_tot = bg.a + contribution;
    mediump vec3 rgb = mix(bg.rgb, fg.rgb, clamp(fg.a / alpha_tot, 0.0, 1.0));
    mediump vec4 frag_wet = vec4(rgb, max(bg.a, fg.a * 1.2));
    mediump vec4 frag_dry = vec4(rgb, alpha_tot);
    frag = mix(frag_dry, frag_wet, wet);
}

