#pragma parameter BEVEL_LEVEL "Bevel Level" 0.2 0.0 0.5 0.01
#ifdef PARAMETER_UNIFORM
uniform float BEVEL_LEVEL;
#else
#define BEVEL_LEVEL 0.2
#endif
// END PARAMETERS //


/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
*/

/*
   Hyllian's Bevel Shader
  
   Copyright (C) 2011-2014 Hyllian/Jararaca - sergiogdb@gmail.com

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version 2
   of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/


// Constants used with gamma correction.
#define InputGamma             2.4
#define OutputGamma            2.2

#define GAMMA_IN(color)     pow(color, float3(InputGamma, InputGamma, InputGamma))
#define GAMMA_OUT(color)    pow(color, float3(1.0 / OutputGamma, 1.0 / OutputGamma, 1.0 / OutputGamma))


float3 bevel(float2 pos, float3 color)
{
    float3 weight;

    float r = sqrt(dot(pos, 1.0));

    float3 delta = lerp(float3(BEVEL_LEVEL), float3(1.0-BEVEL_LEVEL), color);

    weight = delta*(1-r);

    return color+weight;
}


struct input
{
    float2 video_size;
    float2 texture_size;
    float2 output_size;
    float frame_count;
    float frame_direction;
    float frame_rotation;
};


struct out_vertex {
    float4 position : POSITION;
    float4 color    : COLOR;
    float2 texCoord : TEXCOORD0;
};


/*    VERTEX_SHADER    */
out_vertex main_vertex
(
    float4 position : POSITION,
    float4 color    : COLOR,
    float2 texCoord : TEXCOORD0,

    uniform float4x4 modelViewProj,
    uniform input IN
)
{
    out_vertex OUT;

    OUT.position = mul(modelViewProj, position);
    OUT.color    = color;
    OUT.texCoord = texCoord;

    return OUT;
}


/*    FRAGMENT SHADER    */
float4 main_fragment(in out_vertex VAR, uniform sampler2D decal : TEXUNIT0, uniform input IN) : COLOR
{
    float2 position = frac(VAR.texCoord*IN.texture_size);

    float3 color = GAMMA_IN(tex2D(decal, VAR.texCoord).rgb);

    color = saturate(bevel(position, color));

    return float4(GAMMA_OUT(color), 1.0);
}
