/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
   - FX11 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.

*/

#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 //

// 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))

#include "../../compat_includes.inc"
uniform COMPAT_Texture2D(decal) : TEXUNIT0;
uniform float4x4 modelViewProj;

struct out_vertex
{
	float4 position : COMPAT_POS;
	float2 texCoord : TEXCOORD0;
#ifndef HLSL_4
	float4 Color    : COLOR;
#endif
};

out_vertex main_vertex(COMPAT_IN_VERTEX)
{
	out_vertex OUT;
#ifdef HLSL_4
	float4 position = VIN.position;
	float2 texCoord = VIN.texCoord;
#else
	OUT.Color = color;
#endif
	OUT.position = mul(modelViewProj, position);
	OUT.texCoord = texCoord;
	
	return OUT;
}

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

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

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

    weight = delta*(1-r);

    return color+weight;
}

/*    FRAGMENT SHADER    */
float4 bevel(float2 texture_size, float2 texCoord, COMPAT_Texture2D(decal))
{
    float2 position = frac(texCoord*texture_size);

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

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

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

float4 main_fragment(COMPAT_IN_FRAGMENT) : COMPAT_Output
{
	return bevel(COMPAT_texture_size, VOUT.texCoord, decal);
}
COMPAT_END