precision mediump float;

uniform sampler2D u_Sampler;
varying vec2 v_TexCoord;
varying vec4 v_origPos;


// https://skytiger.wordpress.com/2010/12/01/packing-depth-into-color/
// another" http://stackoverflow.com/questions/6408851/draw-the-depth-value-in-opengl-using-shaders

vec4 packDepth24(in float depth)
{

    // Constants
    const vec3 scale  = vec3(1.0, 256.0, 65536.0);
    const vec2 ogb    = vec2(65536.0, 256.0) / 16777215.0;
    const float normal  = 256.0 / 255.0;

    // Avoid Precision Errors
    vec3 unit         = vec3 (depth, depth, depth);
    unit.gb             -= floor(unit.gb / ogb) * ogb;

    // Scale Up
    vec3 color        = unit * scale;

    // Use Fraction to emulate Modulo
    color               = fract(color);

    // Normalize Range
    color               *= normal;

    // Mask Noise
    color.rg            -= color.gb / 256.0;

    return vec4(color,1.0);
}

// (currently NOT USED)! 32b
vec4 packDepth(const in float depth)
{
    //const vec4 bitShift = vec4(256.0*256.0, 256.0, 1.0, 1.0);
    const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);

    const vec4 bitMask  = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);
    vec4 res = fract(depth * bitShift);
    res -= res.xxyz * bitMask;
    return res;
}

void main()
{
  vec4 color = texture2D(u_Sampler, v_TexCoord);

  // if pixel is transparent, throw it away
  if (color.w < 0.98) discard;

// http://stackoverflow.com/questions/10264949/glsl-gl-fragcoord-z-calculation-and-setting-gl-fragdepth
  float far=gl_DepthRange.far; float near=gl_DepthRange.near;

    float ndc_depth = v_origPos.z / v_origPos.w;

    float depth = (((far-near) * ndc_depth) + near + far) / 2.0;

      gl_FragColor = packDepth24(depth); // save depth into frag color RGBA - hack
}