#include "../DeathScreen.hls"
#include "../MipLevels.hls"
#include "../FogOfWar/FogOfWar_PS.hls"
#include "../Transition/Transition.hls"

// Diffuse map
sampler DIFFUSE_MAP :           register (s0);
sampler GLOSS_MAP : register(s2);
#if EMISSIVE
// Funky emissive map which contains diffuse/emissive slider and team color mask
sampler EMISSIVE_MAP :          register (s1);
#endif
sampler ENVIRONMENT_MAP : register (s3);

float3 FakeLightDir;
float4   vCamera;
float4 SpecularColorAndPower;

float4 LightPosition; // xyz light position
float4 SpecInfo; // x= min y= max z = multiplier w = Lambert Bias
float4 RimColor; // xyz = color of the rim lighting| w = contribution
float RimWidth; // the width of the rim lighitng
float3 DiffuseLight = (0.15, 0.05, 0.0);

// Shadow map
sampler	SHADOW_MAP	:			register (s5);

#ifdef MOD2X_COLORMAP
sampler COLORMAP    : register (s8);
#endif
#ifdef FOG_PIXELSHADER_BLEND
sampler FOGLIGHTING : register(s9);
#endif

// Highlight the character when selected
float4 kGrassFade : register(c23);

// Ambient color
float4  AMBIENT_COLOR  :        register(c21);

// Self illumination value
float3 SELF_ILLUMINATION : register(c24);

float4 DEPTH_SCALE_OFFSET : register(c25);

float4 CAMERA_POSITION : register(c26);

float4 OUTLINE_MOD : register(c27);

#include "../ShadowMap/pcf1.hls"

struct FRAGMENT
{
    float4  m_Color0 : COLOR0;
#ifdef MRT_SUPPORTED
    float4  m_Color1 : COLOR1;
#endif
};


///////////////////////////////////////////////////////////////////////////////////////
///
///
///
///////////////////////////////////////////////////////////////////////////////////////
FRAGMENT
    main
    (
    #if defined(FOG_PIXELSHADER_BLEND)
        float4  uv1 :           TEXCOORD0, 
    #else
        float2  uv1 :           TEXCOORD0, 
    #endif
        float4  Pos1 :          TEXCOORD1,
        float4  in_texcoord4 :  TEXCOORD2,
#ifndef DISABLE_SHADOWS
        float3  uvSM :          TEXCOORD3, 
#endif
#if  SEPARATE_ALPHA_UV
        float2  alphaUV:        TEXCOORD4,
#endif
        float3 inWorldNormal : TEXCOORD5,
        float4  sunColor :      COLOR0,
        float4  envColor :      COLOR1
    )
{

#if 0    
    // Incident sun light
#ifndef USE_LIGHT_GRID
        float4 incidentSunLight = sunColor;

    #ifndef DISABLE_SHADOWS
        // Modulate the incident sun light by the shadow
        int shadowSamples = 1;
        
        float shadowMask = saturate(SampleShadowMap(SHADOW_MAP, uvSM)+0.4f);
        incidentSunLight *= shadowMask;
    #endif

        // Sum the incident sun light with contributions from environmental and ambient
        float4 incidentLight = incidentSunLight + envColor * 4 + AMBIENT_COLOR;
#else
    float4 incidentLight = envColor;
#endif

#if EMISSIVE
    // Read emissive texture which contains emissive/diffuse factor
    float4 texelEmissive = tex2D(EMISSIVE_MAP, uv1.xy);
    float emissiveFactor = texelEmissive.g;                 /// Amount of color which is emissive
    float diffuseFactor = saturate(1.f - emissiveFactor);   /// Amount of color which is diffuse
#else
    float emissiveFactor = 1.0f;
    float diffuseFactor = 0.0f;
#endif

#if defined(FULLBRIGHT) //handle the fullbright debug visualization.
    float4 lighting = 1.0f;
#elif defined(USE_LIGHT_GRID)
    //lighting
    #if defined(SHOW_LIGHTING)
        float lightScale = 1.0f;
    #else
        float lightScale = 4.0f * sunColor.b;
    #endif
    float4 lighting = saturate(diffuseFactor * incidentLight * lightScale + emissiveFactor + sunColor.a*float4(SELF_ILLUMINATION, 0.f));
#else
    float4 lighting = saturate(diffuseFactor * incidentLight + emissiveFactor + float4(SELF_ILLUMINATION, 0.f));
#endif

#else
    float4 lighting = 1.0f;
#endif // no lighting

    // Read the diffuse texture
    float4 texelDiffuse = tex2D(DIFFUSE_MAP, uv1.xy);

#if SEPARATE_ALPHA_UV
    texelDiffuse.a = tex2D(DIFFUSE_MAP, alphaUV).a;
#endif

    // Compute albedo color using a combination of diffuse and emissive values
    float4 albedoColor = texelDiffuse * lighting;

    float3 eyeRay = normalize( vCamera.xyz - Pos1);
    float3 lightRay = normalize(vCamera.xyz - Pos1 + LightPosition.xyz);

    float3 worldNormal = inWorldNormal;
    worldNormal = normalize(worldNormal);

    //Rim Lighting Test2 BEGIN**********************************
    //float rim = 1 - max(dot(eyeRay, worldNormal), 0.0);
    //rim = smoothstep(0.6, 1.0, rim);
    //float4 rimLighting = RimColor * float4(rim, rim, rim,1.0);
    //rimLighting *= rimLighting.w;
    //Rim Lighting Test2 END******************************************

    float lambert = saturate(max(dot(lightRay,worldNormal),0.0f) + SpecInfo.w);
    float3 halfDir = normalize(lightRay + eyeRay);
    float specAngle = max(dot(halfDir, worldNormal), 0.0);

    //float specMask = tex2D(GLOSS_MAP, uv1.xy);
    float specMask = tex2D(GLOSS_MAP, uv1.xy).r;
    //rimLighting *= saturate(specMask + 0.5f);
    float destructionMask = saturate(specMask - RimColor.w);
    float specular = pow(specAngle, lerp(SpecInfo.x, SpecInfo.y, 1 - destructionMask));
    float3 specularColor = specular * SpecInfo.z;

    //ENVIRONMENT MAP TEST BEGIN*****************************
    float3 r = 2.0f * dot(eyeRay, worldNormal) * worldNormal - eyeRay;
    float m = 2.0f * sqrt( pow( r.x, 2.0f ) + pow( r.y, 2.0f ) + pow( r.z + 1.0f, 2.0f ) );
    float2 vN = r.xy / m + 0.5f;
    float3 EnvMap = tex2D( ENVIRONMENT_MAP, vN ).rgb;

    //ENVIRONMENT MAP TEST END*******************************
#if DESTRUCTION_MASK
    albedoColor = lerp(albedoColor,float4(specMask,specMask,specMask,1),destructionMask);
    EnvMap = lerp(EnvMap, albedoColor,destructionMask);
#endif
    //float3 colorLinear = albedoColor;
    //adding this line below is saying there are toom many instructions... comment out the line below that.
    //float3 colorLinear = lerp(lambert * albedoColor + (specularColor * EnvMap), rimLighting, rimLighting);
    //float3 colorLinear = albedoColor * specularColor + albedoColor;
    float3 colorLinear = lambert * albedoColor + ((EnvMap * specular) * SpecInfo.z);
    //float4 colorLinear = float4 (destructionMask,destructionMask,destructionMask, 1.0f);
    //float4 colorLinear = float4 (specular,specular,specular, 1.0f);
    //float4 colorLinear = float4 (specularColor.x,specularColor.y,specularColor.z, 1.0f);
    //float3 colorLinear = EnvMap;


    float4 finalColor = float4(colorLinear.xyz, texelDiffuse.a);// setting up final color to use the gloabal alpahas
    finalColor = ApplyTransition(finalColor, lighting.rgb, uv1.xy);
    finalColor.a *= kGrassFade.a;

#if 0//!defined(DISABLE_FOW) && !defined(FULLBRIGHT)
    float4 fowFactors = GetFogOfWarFactors(in_texcoord4.xy);
    finalColor.rgb = lerp(fowFactors.rgb, finalColor.rgb, fowFactors.a);
#endif

//Note: if texture transition is enabled then too many instructions are used if combined with height fog.
//So fog is disabled during texture transitions.
#if defined(FOG_PIXELSHADER_BLEND) && !defined(FULLBRIGHT)
    //modify the fog color based on the fog of war...
    float4 fogColor = tex2D(FOGLIGHTING, in_texcoord4.xy);
    #ifndef DISABLE_FOW
        fogColor = lerp(fowFactors, fogColor, fowFactors.a);
    #endif
    float fogOpacity = envColor.a;
    #ifdef MOD2X_COLORMAP
        float colorMapOpacity = tex2D(COLORMAP, uv1.zw).a;
        fogOpacity = saturate( fogOpacity*colorMapOpacity*2.0f );
    #endif

    finalColor.rgb = lerp( finalColor, fogColor, fogOpacity );


#endif
    
    float3 delta = CAMERA_POSITION.xyz - Pos1.xyz;
    float dist = DEPTH_SCALE_OFFSET.x * (length(delta) + DEPTH_SCALE_OFFSET.y); 
    float4 out_color1 = float4(dist*OUTLINE_MOD.x, OUTLINE_MOD.x, 0.f, 1.f);
    
    //  This has the effect of thinning and lightening the outline as the fog gets more opaque.
    //However the outline never completely disappears, which is desirable in order to make 
    //characters easier to see even in foggy conditions.
    //  In this way the outline can be affected by the fog (it looks terrible otherwise) but 
    //without effecting the outline pass or drastically effecting performance.
#if defined(FOG_PIXELSHADER_BLEND) && !defined(FULLBRIGHT)
    out_color1.xy = lerp(out_color1.xy, 4.0f, fogOpacity);
#endif

    // Return fragment
    FRAGMENT fragment;
    fragment.m_Color0 = finalColor;
#ifdef MRT_SUPPORTED
    fragment.m_Color1 = out_color1;
#endif
    
    //Editor / Debugging features.
    #if defined(SHOW_LIGHTING)
        #if defined(USE_LIGHT_GRID)
            fragment.m_Color0.rgb = lighting;
        #else
            fragment.m_Color0.rgb = lighting*0.25f;
        #endif
    #elif defined(GRAYSCALE)
        float3 LUMINANCE_CONVERSION = float3(0.299f, 0.587f, 0.114f);
        fragment.m_Color0.rgb = dot( fragment.m_Color0.rgb, LUMINANCE_CONVERSION );
    #endif

    fragment.m_Color0.rgb = ApplyMipColorsVisualization(fragment.m_Color0.rgb, uv1.xy);
    return fragment;
}
