/*=============================================================================
	Fog.hlsl: Scene fogging pixel shaders.
	Copyright 2004 Epic Games, Inc. All Rights Reserved.

	Revision history:
		* Created by Andrew Scheidecker.
=============================================================================*/

sampler		SceneTexture;

static const float FLT_EPSILON = 0.001f;

float4 linePlaneIntersection(float3 RelativeB,float4 RelativeZ)
{
	return RelativeZ / (abs(RelativeB.z) <= FLT_EPSILON ? FLT_EPSILON : RelativeB.z);
}

float   FogMinDist;
float   FogLength;
float   FogDensity;
float4  FogColor;

float4 fogScene(
	float2 UV : TEXCOORD0,
	float4 ScreenVector : TEXCOORD1,
	float4 MinHeightRelativeZ : TEXCOORD2,
	float4 MaxHeightRelativeZ : TEXCOORD3) : COLOR0
{
    float4  SceneTexel = tex2D(SceneTexture,UV);
    float3 	SceneColor = SceneTexel.rgb;
	float 	SceneDepth = SceneTexel.a;

    float3	WorldPosition = ScreenVector * clamp(SceneDepth,1,65500);

	float	Distance = length(WorldPosition);
    float   fogamount = (Distance-FogMinDist)/FogLength;
    
    //get a parabolic falloff, gentler initial derivative
    fogamount = clamp(FogDensity*fogamount*fogamount,0.0,1.0);
    
    SceneColor = SceneColor*(1.0-fogamount) + fogamount*FogColor.rgb;
    
	return float4(SceneColor,SceneDepth);
}

struct vertexShaderOutput
{
	float4	Position : POSITION;
	float2	TexCoord : TEXCOORD0;
	float4	ScreenVector : TEXCOORD1;
	float4	MinHeightRelativeZ : TEXCOORD2;
	float4	MaxHeightRelativeZ : TEXCOORD3;
	float4	Dummy : TEXCOORD4;
};

float4	FogMinHeight;
float4	FogMaxHeight;

float4		ScreenPositionScaleBias;
float4x4	ScreenToWorld;
float3		CameraPosition;

vertexShaderOutput vertexShader(float4 Position : POSITION,float2 TexCoord : TEXCOORD0)
{
	vertexShaderOutput Result;
	Result.Position = Position;
	Result.TexCoord = TexCoord;
	Result.ScreenVector = mul(ScreenToWorld,float4((TexCoord - ScreenPositionScaleBias.wz) / ScreenPositionScaleBias.xy,1,0));
	Result.Dummy = mul(ScreenToWorld,float4((TexCoord - ScreenPositionScaleBias.wz) / ScreenPositionScaleBias.xy,1,1));
	Result.MinHeightRelativeZ = FogMinHeight - CameraPosition.z;
	Result.MaxHeightRelativeZ = FogMaxHeight - CameraPosition.z;
	return Result;
}
