#include "ShaderConstants.fxh"
#include "util.fxh"

struct PS_Input
{
	float4 position : SV_Position;

#ifndef BYPASS_PIXEL_SHADER
	lpfloat4 color : COLOR;
	snorm float2 uv0 : TEXCOORD_0_FB_MSAA;
	snorm float2 uv1 : TEXCOORD_1_FB_MSAA;
#endif

#ifdef FOG
	float4 fogColor : FOG_COLOR;
#endif
};

struct PS_Output
{
	float4 color : SV_Target;
};

ROOT_SIGNATURE


#define Fused_TONEMAP
#define saturation 1.333
#define exposure 1.075
#define brightness 0.750
#define gamma 1.900
#define contrast 1.97


float filmic_curve(float x) {

float A = 0.22;
float B = 0.5;
float C = 0.15 * brightness;
float D = 0.4 * gamma;
float E = 0.01 * contrast;
float F = 0.2;

return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;
}

float3 Fusedmapping(float3 clr) {
float W = 1.0 / exposure;

#ifdef Fused_TONEMAP

float Luma = dot(clr, float3(0.0, 0.3, 0.3));
float3 Chroma = clr - Luma;
clr = (Chroma * saturation) + Luma;
  clr = float3(filmic_curve(clr.r), filmic_curve(clr.g), filmic_curve(clr.b)) / filmic_curve(W);
#endif
return clr;
}


void main(in PS_Input PSInput, out PS_Output PSOutput)
{
#ifdef BYPASS_PIXEL_SHADER
    PSOutput.color = float4(0.0f, 0.0f, 0.0f, 0.0f);
    return;
#else

float torchlightaffects = (1.0 - PSInput.uv1.x);


float3 Fused_LIGHT = float3(0.700,0.500,0.300);


#if USE_TEXEL_AA
	float4 diffuse = texture2D_AA(TEXTURE_0, TextureSampler0, PSInput.uv0 );
#else
	float4 diffuse = TEXTURE_0.Sample(TextureSampler0, PSInput.uv0);
#endif

#ifdef SEASONS_FAR
	diffuse.a = 1.0f;
#endif

#if USE_ALPHA_TEST
	#ifdef ALPHA_TO_COVERAGE
		#define ALPHA_THRESHOLD 0.05
	#else
		#define ALPHA_THRESHOLD 0.5
	#endif
	if(diffuse.a < ALPHA_THRESHOLD)
		discard;
#endif

#if defined(BLEND)
	diffuse.a *= PSInput.color.a;
#endif

#if !defined(ALWAYS_LIT)
	diffuse = diffuse * TEXTURE_1.Sample(TextureSampler1, PSInput.uv1);
#endif

#ifndef SEASONS
	#if !USE_ALPHA_TEST && !defined(BLEND)
		diffuse.a = PSInput.color.a;
	#endif

	diffuse.rgb *= PSInput.color.rgb;
#else
	float2 uv = PSInput.color.xy;
	diffuse.rgb *= lerp(1.0f, TEXTURE_2.Sample(TextureSampler2, uv).rgb*2.0f, PSInput.color.b);
	diffuse.rgb *= PSInput.color.aaa;
	diffuse.a = 1.0f;
#endif

#ifdef FOG
	float weather = smoothstep(0.8,1.0,FOG_CONTROL.y);
#else
	float weather = 1.0;
#endif

diffuse.rgb = Fusedmapping(diffuse.rgb);
diffuse.rgb += Fused_LIGHT.rgb*max(0.0,PSInput.uv1.x-0.5f);

PSOutput.color = diffuse;

#ifdef VR_MODE
	PSOutput.color = max(PSOutput.color, 1 / 255.0f);
#endif

#endif
}
