#include "../ColorPalette.hls"
#include "../DeathScreen.hls"
#include "../MipLevels.hls"
#include "../FogOfWar/FogOfWar_PS.hls"
#include "SoftParticle.hls"
#include "ColorRemap.hls"
#include "AlphaErode.hls"

sampler TEXTURE                 : register(s0);
sampler PARTICLE_COLOR_TEXTURE  : register(s1);

#ifdef  MULTIPASS
sampler TEXTUREMULT             : register(s3);
#endif

#ifdef MASKED
sampler NAVMESH_MASK_TEXTURE    : register(s4);
#endif

#if defined(COLORPALETTE_COLORBLIND)
   float4 APPLY_TEAM_COLOR_CORRECTION : register(c11);
#endif



struct PS_IN
{
    float4  color0      : TEXCOORD0;    // N.B. colors can be > 1 (e.g. mod2x), so use a full interpolator and not COLOR0 which saturates on ps_2_0
    float4  uv0_uv1     : TEXCOORD1;
#ifdef MASKED
    float4  uvFOW_uvMap : TEXCOORD2;    
#else
    float2  uvFOW       : TEXCOORD2;
#endif
#ifdef ALPHA_EROSION
    float   erosion     : TEXCOORD3;
#endif
#ifdef SOFT_PARTICLES
    float4  projPosition: TEXCOORD4;    // clipspace POSITION semantic isn't supplied to pixel shader, need an explicit interpolator
#endif
};

void main( in PS_IN input, out float4 out_color0:COLOR0 )
{
    float2 uv0 = input.uv0_uv1.xy;
    float2 uv1 = input.uv0_uv1.zw;
    
    float4 texel = tex2D(TEXTURE, uv0);
    
#ifdef PALETTIZE_TEXTURES
    // remap textures according to palettization settings
    texel.rgb = ColorizeMainTexture(texel).rgb;
#endif

#ifdef  MULTIPASS
    texel = texel * tex2D(TEXTUREMULT, uv1);
#endif  

#ifndef ALPHA_EROSION
    // apply p-rgba colorizing texture (if not using alpha erosion which uses same sampler)
    float4 particle_color_texel = tex2D(PARTICLE_COLOR_TEXTURE, uv1);
    texel *= particle_color_texel;
#endif

    out_color0 = input.color0 * texel;

#ifdef COLORPALETTE_COLORBLIND
    if (APPLY_TEAM_COLOR_CORRECTION.r != 0.0f)
    {       
        ApplyColorCorrectionColorblind(out_color0);
    }
#endif

#ifndef DISABLE_FOW
#ifdef MASKED
    float4 fowFactors = GetFogOfWarFactors(input.uvFOW_uvMap.xy);
#else
    float4 fowFactors = GetFogOfWarFactors(input.uvFOW);
#endif
    
    // Apply FOW to final result
    // NOTE:  This ignores the FowOverlay texture tint and assumes the FoW is black
    out_color0.rgb *= fowFactors.a;
#endif // DISABLE_FOW

#ifdef ALPHA_EROSION
    out_color0.a *= CalcAlphaErosion(input.erosion, uv0);
#endif

    //**
    // soft particles
#ifdef SOFT_PARTICLES
    out_color0 = CalcSoftParticleColor(input.projPosition,out_color0);
#endif
    
    //**
    // Finalize output color
    out_color0.rgb = ApplyMipColorsVisualization(out_color0.rgb, uv0);
    
#ifdef MASKED
    float4 mask = tex2D(NAVMESH_MASK_TEXTURE, input.uvFOW_uvMap.zw);   
    out_color0.a = min(mask.r, out_color0.a);
#endif
}
