float4 AmbientColor : register(c1);
sampler2D BaseMap : register(s0);
sampler2D NormalMap : register(s1);
float4 PSLightColor[4] : register(c2);
sampler2D ShadowMap : register(s6);
float4 Toggles : register(c7);
float4 TESR_TerrainData : register(c8);
sampler2D TESR_Noise : register(s10) < string ResourceName = "Effects\TerrainNoise_n.dds"; > = sampler_state { ADDRESSU = WRAP; ADDRESSV = WRAP; MAGFILTER = LINEAR; MINFILTER = MINDEF; MIPFILTER = MIPDEF; };
sampler2D TESR_samplerNormalMap : register(s1) = sampler_state { MAGFILTER = LINEAR; MINFILTER = MINDEF; MIPFILTER = LINEAR; };
//
//
// Registers:
//
//   Name         Reg   Size
//   ------------ ----- ----
//   AmbientColor const_1       1
//   PSLightColor[0] const_2        1
//   Toggles      const_7       1
//   BaseMap      texture_0       1
//   NormalMap    texture_1       1
//   ShadowMap    texture_6       1
//


// Structures:

struct VS_OUTPUT {
    float2 BaseUV : TEXCOORD0;
    float3 texcoord_1 : TEXCOORD1_centroid;
    float texcoord_7 : TEXCOORD7_centroid;
    float4 color_1 : COLOR1;
};

struct PS_OUTPUT {
    float4 color_0 : COLOR0;
};

// Code:

PS_OUTPUT main(VS_OUTPUT IN) {
    PS_OUTPUT OUT;

#define	expand(v)		(((v) - 0.5) / 0.5)
#define	compress(v)		(((v) * 0.5) + 0.5)
#define	shade(n, l)		max(dot(n, l), 0)
#define	shades(n, l)		saturate(dot(n, l))
                                                 
    float3 q0;
    float3 q1;
    float3 q2;
    float3 q3;
    float4 r0;
    float3 r1;
    float4 r2;  
                                                                           
        
    r2.xyzw = tex2D(NormalMap, IN.BaseUV.xy);
    r0.xyzw = tex2D(BaseMap, IN.BaseUV.xy); 
  
    
    float3 noisec = (tex2D(ShadowMap, IN.BaseUV.xy * TESR_TerrainData.x).xyz * 2 + tex2D(ShadowMap, IN.BaseUV.xy * (TESR_TerrainData.x / 10)).xyz) * 0.3333;
    r1.x   = saturate(0.50 + 1.25 * (smoothstep(1.0, 0.0, pow(noisec.x, 0.5))));
    r1.xyz = lerp(r1.x, 1, pow(length(r0.rgb) / length(1), 2));
              
    float3 noisen = expand(tex2D(TESR_Noise, IN.BaseUV.xy * TESR_TerrainData.y).xyz);
    r2.xyz = (r2.xyz + float3(noisen.xy * TESR_TerrainData.z, 0));
      
    q0.xyz = (shades(normalize(expand(r2.xyz)), IN.texcoord_1.xyz) * PSLightColor[0].rgb) + AmbientColor.rgb;
    q1.xyz = r0.xyz * max(q0.xyz, 0);
    q2.xyz = q1.xyz * r1.x;
    q3.xyz = (Toggles.y <= 0.0 ? q2.xyz : ((IN.color_1.a * (IN.color_1.rgb - (r1.x * q1.xyz))) + q2.xyz));
    OUT.color_0.a = r0.w * AmbientColor.a;
    OUT.color_0.rgb = q3.xyz;     
    
    return OUT;
};                