//
// Copyright (C) ANSYS, Inc. and its subsidiaries.  All Rights Reserved.
//
// Encoding/decoding functions for value packing in render targets.
//
// Author: jprihan
//


// Packs gl_FragCoord.z depth value [0,1) as RGBA8.
// Note that with this encoding encode(1.0) == encode(0.0)
// so either check 0.0 < depth < 1.0, or pre-multiply value by
// 0.9999991 before encoding, and post-multiply the decoded 
// depth by 1.0 / 0.9999991
//! HLSL ref: http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/

// p_value should be in the range [0,1)
vec4 EncodeFragDepthAsRGBA8( float p_value )
{
    vec4 enc = vec4( 1.0f, 255.0f, 65025.0f, 16581375.0f ) * p_value;
    float oo255 = 1.0f / 255.0f;
    enc = fract(enc);
    enc -= enc.yzww * vec4( oo255, oo255, oo255, 0.0f );
    return enc;
}

// decodes depth from RBGA to the range [0,1)
float DecodeFragDepthFromRGBA8( vec4 p_rgba )
{
    return dot( p_rgba, vec4(1.0, 1/255.0, 1/65025.0, 1/16581375.0) );
}

