//
// Copyright (C) ANSYS, Inc. and its subsidiaries.  All Rights Reserved.
//
// Author: mgcosta
//

#pragma include("lib/TemplateShader.frag.glsl")

// included for float -> rgba depth conversion
#pragma include("lib/EncodingUtils.glsl")

in vec2 var_TexCoord;
noperspective in float var_ResultInRange;
noperspective in float var_ScaleInRange;

uniform bool encodeDepthAsRGBA;
uniform sampler2D colorMap;
uniform vec4 resultsOutOfRangeColor;

bvec4 fCullMask( in float p_inRange )
{
    return ( p_inRange < 1.0 ) ? bvec4( false ) : bvec4( true );
}

vec4 fCullColor( in vec4 p_correctColor, in vec4 p_wrongColor, in bvec4 p_mask )
{
    vec4 color = mix( p_wrongColor, p_correctColor, p_mask );

    if ( color.a < 0.1 )
        discard;

    return color;
}

#if defined( SYMBOLPLOT_POINT_MODE )
#   define SYMBOLPLOT_POINT_MODE_CUSTOM_SHAPE
#   define SYMBOLPLOT_POINT_MODE_CIRCLE
#endif

vec4 HandleFragmentColor(in vec4 baseColor)
{
    if ( var_ScaleInRange < 1.0 )
        discard;

    vec4 fragColor = baseColor;

    vec4 texColor = texture( colorMap, var_TexCoord );

#if defined( SYMBOLPLOT_NO_LIGHTING )

// TODO: Add antialiasing to point shapes
#if defined( SYMBOLPLOT_POINT_MODE_CUSTOM_SHAPE )
    vec2 p = gl_PointCoord * 2.0 - vec2( 1.0 );

#if defined( SYMBOLPLOT_POINT_MODE_RING ) || defined( SYMBOLPLOT_POINT_MODE_ROSE ) || defined( SYMBOLPLOT_POINT_MODE_SPIRAL ) || defined( SYMBOLPLOT_POINT_MODE_STAR )
    float r = sqrt( dot( p, p ) );
#endif

#if defined( SYMBOLPLOT_POINT_MODE_ROSE ) || defined( SYMBOLPLOT_POINT_MODE_SPIRAL ) || defined( SYMBOLPLOT_POINT_MODE_STAR )
    float theta = atan( p.y, p.x );
#endif

#if defined( SYMBOLPLOT_POINT_MODE_CIRCLE )
    if ( dot( p, p ) > 0.75 ) // circle
#endif

#if defined( SYMBOLPLOT_POINT_MODE_RING )
    if ( dot( p, p ) > r || dot( p, p ) < r * 0.75 ) // outer ring
#endif

#if defined( SYMBOLPLOT_POINT_MODE_ROSE )
    if ( dot( p, p ) > cos( theta * 5.0 ) ) // polar rose
#endif

#if defined( SYMBOLPLOT_POINT_MODE_SPIRAL )
    if ( dot( p, p ) > 5.0 / cos( theta - 20.0 * r ) ) // spiral
#endif

#if defined( SYMBOLPLOT_POINT_MODE_STAR )
    if ( dot( p, p ) > 0.5 * exp( cos( theta * 5.0 ) * 0.75 ) ) // rounded star
#endif
        discard;
    else
#endif

    fragColor = fCullColor( texColor, resultsOutOfRangeColor, fCullMask( var_ResultInRange ) );
#else
    fragColor *= fCullColor( texColor, resultsOutOfRangeColor, fCullMask( var_ResultInRange ) );
#endif

    // we need to evaluate the above code to ensure we respect
    // any fragment discards that might occur
    if (encodeDepthAsRGBA == true)
    {
        // encode frag coord [0..1] depth as RGBA
        // strictly speaking we need gl_FragCoord.z < 1
        // as 1.0 will be encoded as vec4(0,0,0,0), which decodes
        // to 0.0, but we can handle that when decoding later
        fragColor = EncodeFragDepthAsRGBA8( gl_FragCoord.z );
    }

    return fragColor;
}

