[[vertex]]

uniform mat4 mvp;

in vec4 pos;
in vec2 uvs;
out vec2 uv;

void main()
{
    uv = uvs;
    gl_Position = mvp * vec4(pos.xyz, 1.0);
}

[[fragment]]

#include "include/blur.glsl"
#include "include/blend.glsl"
#include "include/blend-stroke.glsl"
#include "include/color.glsl"

uniform sampler2D tex;
uniform sampler2D tex_stroke;
uniform sampler2D tex_mask;
uniform mediump float alpha;
uniform int blend_mode;
uniform mediump vec2 resolution;
uniform bool lock;
uniform bool mask;
uniform bool use_fragcoord;

uniform bool use_dual;
uniform sampler2D tex_dual;
uniform mediump float dual_alpha;
uniform int dual_blend_mode;

uniform bool use_pattern;
uniform 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;
out mediump vec4 frag;

void main()
{
    mediump vec2 uv_base = use_fragcoord ? (gl_FragCoord.st / resolution) : uv;
    mediump vec4 base = texture(tex, uv_base);
    mediump vec4 stroke = texture(tex_stroke, uv);
    
    if (stroke.a == 0.0)
    {
        frag = base;
        return;
    }

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

    if (use_dual)
    {
        mediump vec4 dual = texture(tex_dual, uv);
        stroke.a = clamp(blend_stroke(stroke.a, dual.a, dual_alpha, dual_blend_mode), 0.0, 1.0);
    }

    stroke.a = mask ? stroke.a * blur(tex_mask, uv).r : stroke.a;
    if (!lock && base.a == 0.0)
    {
        frag = stroke * vec4(1.0, 1.0, 1.0, alpha);
        return;
    }

    mediump vec4 blended = blend(base, stroke, blend_mode);
    frag = vec4(blended.rgb, (lock ? base.a : blended.a) * alpha);
}
