/*=============================================================================
	DOFAndBloomBlendPixelShader.usf: Pixel shader for blending the blurred depth of field and bloom colors with the scene color.
	Copyright © 2006 Epic Games, Inc. All Rights Reserved.
=============================================================================*/

#include "Common.usf"
#include "DepthOfFieldCommon.usf"

sampler2D BlurredImage;

// scene material parameters

float4 SceneShadowsAndDesaturation;  // RGB = SceneShadows, A = (1-SceneDesaturation)
float4 SceneInverseHighLights;       // RGB = 1 / SceneHighLights
float4 SceneMidTones;                // RGB = SceneMidTones
float4 SceneScaledLuminanceWeights;  // RGB = LuminanceWeights * SceneDesaturation

static float3 SceneShadows      = SceneShadowsAndDesaturation.rgb;
static float  SceneDesaturation = SceneShadowsAndDesaturation.a;

// gamma correction parameters

float4 GammaColorScaleAndInverse;
float4 GammaOverlayColor;

static float3 GammaColorScale = GammaColorScaleAndInverse.rgb; 
static float  GammaInverse    = GammaColorScaleAndInverse.a;

void Main(
	in float2 UV : TEXCOORD0,
	in float2 SceneUV : TEXCOORD1,
	out float4 OutColor : COLOR0
	)
{
    // DOF and bloom effect

	float SceneDepth = CalcSceneDepth(SceneUV);

	half3 FocusedSceneColor = CalcSceneColor(SceneUV);
	half  FocusedWeight = saturate(1 - CalcUnfocusedPercent(SceneDepth));

	half3 UnfocusedSceneColor = tex2D(BlurredImage,UV).rgb;
	half  UnfocusedWeight = tex2D(BlurredImage,UV).a;

//	half  WeightSum = max(FocusedWeight + UnfocusedWeight, 0.001);
    half  WeightSum = FocusedWeight + UnfocusedWeight;

	//nse vbunny--
	#if SUPPORTS_FP_FILTERING
		half3 DOFResult = (FocusedSceneColor * FocusedWeight + UnfocusedSceneColor) / WeightSum;
	#else
		half3 DOFResult = (FocusedSceneColor * FocusedWeight + UnfocusedSceneColor * 4) / WeightSum;
	#endif
	//--nse vbunny
	
    // Material effect

    half3 Color = pow(saturate(DOFResult - SceneShadows) * SceneInverseHighLights.rgb, SceneMidTones.rgb);
    half3 ScaledLuminance = dot(Color.rgb, SceneScaledLuminanceWeights.rgb);

    half3 MaterialResult = GammaOverlayColor.rgb + Color * SceneDesaturation + ScaledLuminance;

	// Gamma correction (note that for some reason HLSL generates better code when we add a color to the
    // MaterialResult, so I changed the code so that we add GammaOverlayColor / GammaColorScale to the
    // MaterialResult as opposed to adding GammaOverlayColor to the LinearColor.

	half3 LinearColor = MaterialResult.rgb * GammaColorScale.rgb;
	
	// RETURN_COLOR not needed unless writing to SceneColor
	//OutColor = RETURN_COLOR( float4(pow(saturate(LinearColor), GammaInverse), 0.f) );
	OutColor = float4(pow(saturate(LinearColor), GammaInverse), 0.f);
}
