/**
 * Copyright (C) 2014 Stellar Jockeys.
 * All Rights Reserved.
 *
 * NOTICE: All information contained herein is, and remains the property of
 * Stellar Jockeys and its suppliers, if any.  The intellectual and technical
 * concepts contained herein are proprietary to Stellar Jockeys and its suppliers.
 * Dissemination of this information or reproduction of this material is
 * strictly forbidden unless prior written permission is obtained from
 * Stellar Jockeys.
 *
 * @file occluded.frag
 * @date 07/03/2014
 */
#version 120
uniform sampler2D uDepth;
uniform sampler2D uMaterial;
uniform float uDepthConversion;
uniform vec2 uTapDelta;
varying vec2 vPosition;
varying vec2 vTextureCoord;
varying float vOccludedPriority;
varying vec4 vOccludedColor;

//#include <conversions.glsl>
//#include <constants.glsl>
//#include <fragmaterial.glsl>
//#include <fragnormal.glsl>

const float OCCLUDED_PRIORITY_TOLERANCE = 1.0 / 255.0;
const float OCCLUDED_RIM_SHADING_RANGE = 1.0 - OCCLUDED_RIM_SHADING_MIN;

void main()
{
    float depth = texture2D(uDepth, vTextureCoord).r;
    gl_FragDepth = AdjustedDepth(gl_FragCoord.z, depth, uDepthConversion);

    vec2 tapDelta = uTapDelta;
    float mirrored = clamp(floor(dFdx(vTextureCoord.x)), -1.0, 0.0) * 2.0 + 1.0;
    tapDelta.x *= mirrored;

    vec3 normal = DeriveNormal(vTextureCoord, depth, tapDelta, PPD_SRC, uDepth);

    float priority = texture2D(uMaterial, vPosition).b + OCCLUDED_PRIORITY_TOLERANCE;
    float showOcclusion = (step(vOccludedPriority, priority) * -1.0) + 1.0;
    showOcclusion *= ceil(depth - OCCLUDED_DEPTH_THRESHOLD);

    float rimLighting = (pow(normal.z, OCCLUDED_RIM_SHADING_POWER) * -1.0) + 1.0;
    rimLighting = (rimLighting * OCCLUDED_RIM_SHADING_RANGE) + OCCLUDED_RIM_SHADING_MIN;
    float rimAlpha = mix(rimLighting, 1.0, OCCLUDED_RIM_SHADING_FALLOFF_OPACITY) * showOcclusion;

    /*
     * Multiplying the rim lighting with the color helps create dark areas when over bright areas.
     *
     * Using the rim lighting in the alpha helps make it look more ghosted.
     */
    gl_FragColor = vOccludedColor * vec4(rimLighting, rimLighting, rimLighting, rimAlpha);
}
