/**
 * Selection outline post process stage.
 */

#version 430

#pragma include "render_pipeline_base.inc.glsl"

uniform sampler2D ShadedScene;
uniform sampler2D SelectionMaskTex;

uniform float SelectionOutlineEnabled;
uniform vec4 SelectionOutlineColor;
uniform float SelectionOutlineWidth;   // pixels
uniform float SelectionFillAlpha;      // 0..1

out vec4 result;

float sample_mask(vec2 uv) {
    return textureLod(SelectionMaskTex, uv, 0).r;
}

void main() {
    vec2 uv = get_texcoord();
    vec3 scene_col = textureLod(ShadedScene, uv, 0).rgb;

    if (SelectionOutlineEnabled < 0.5) {
        result = vec4(scene_col, 1.0);
        return;
    }

    vec2 texel = vec2(max(1.0, SelectionOutlineWidth)) / SCREEN_SIZE;
    float center = sample_mask(uv);

    float max_nei = 0.0;
    max_nei = max(max_nei, sample_mask(uv + vec2( texel.x, 0.0)));
    max_nei = max(max_nei, sample_mask(uv + vec2(-texel.x, 0.0)));
    max_nei = max(max_nei, sample_mask(uv + vec2(0.0,  texel.y)));
    max_nei = max(max_nei, sample_mask(uv + vec2(0.0, -texel.y)));
    max_nei = max(max_nei, sample_mask(uv + vec2( texel.x,  texel.y)));
    max_nei = max(max_nei, sample_mask(uv + vec2( texel.x, -texel.y)));
    max_nei = max(max_nei, sample_mask(uv + vec2(-texel.x,  texel.y)));
    max_nei = max(max_nei, sample_mask(uv + vec2(-texel.x, -texel.y)));

    // Outer contour only.
    float edge = clamp(max_nei - center, 0.0, 1.0);
    float fill = center * SelectionFillAlpha;

    vec3 col = scene_col;
    if (fill > 0.0) {
        col = mix(col, SelectionOutlineColor.rgb, fill * SelectionOutlineColor.a);
    }
    if (edge > 0.0) {
        col = mix(col, SelectionOutlineColor.rgb, edge * SelectionOutlineColor.a);
    }

    result = vec4(col, 1.0);
}

