//----------------------------------------------------------------------------
// DirectX wants texture coordinates with components in [0,1].
//----------------------------------------------------------------------------
float3 MapToUnit (float3 kVector)
{
    // map [-1,1] to [0,1]
    return 0.5f*kVector + 0.5f;
}
//----------------------------------------------------------------------------
float3 MapFromUnit (float3 kVector)
{
    // map [0,1] to [-1,1]
    return 2.0f*kVector - 1.0f;
}
//----------------------------------------------------------------------------
void v_Fresnel
(
    in float3        kModelPosition  : POSITION,
    in float3        kModelNormal : NORMAL,
    out float4       kClipPosition : POSITION,
    out float3       kWorldNormal : TEXCOORD0,
    out float3       kEyeDirection : TEXCOORD1,
    uniform float4x4 WVPMatrix,
    uniform float4x4 WMatrix,
    uniform float3   CameraWorldPosition)
{
    // Transform the position from model space to clip space.
    kClipPosition = mul(float4(kModelPosition,1.0f),WVPMatrix);
    
    // Transform the position from model space to world space.
    float3 kWorldPosition = mul(float4(kModelPosition,1.0f),WMatrix).xyz;

    // Transform the normal from model space to world space.  In case the
    // model-to-world matrix has nonunit scales, the resulting vector must
    // be normalized.  Map the vector to [0,1]^3.
    kWorldNormal = MapToUnit(normalize(mul(kModelNormal,(float3x3)WMatrix)));

    // Calculate the eye direction.  Map the vector to [0,1]^3.
    kEyeDirection = MapToUnit(normalize(kWorldPosition-CameraWorldPosition));
}
//----------------------------------------------------------------------------
void p_Fresnel
(
    in float3  kWorldNormal : TEXCOORD0, 
    in float3  kEyeDirection : TEXCOORD1,
    out float4 kPixelColor : COLOR)
{
    //  Map the vectors to [-1,1]^3.
    kWorldNormal = MapFromUnit(kWorldNormal);
    kEyeDirection = MapFromUnit(kEyeDirection);
    
    // Calculate the Fresnel factor.
    float fFresnel = 1 + dot(kWorldNormal,kEyeDirection);
    fFresnel = fFresnel*fFresnel;

    // Set all color channels to the Fresnel factor.
    kPixelColor = fFresnel;
}
//----------------------------------------------------------------------------
