#include "common.sh"


sampler   normTex : register(s1);


struct VsInput
{
  float2 xz        : POSITION0;
  float  y         : POSITION1;
  float  foam      : TEXCOORD1;
};

struct VsOutput
{
  float4 pos       : POSITION;
  float4 fog       : COLOR0;
  float3 tc        : TEXCOORD0; // foam in Z
  float3 eyeVec    : TEXCOORD1;
};


float4 tcOfs : register(c16);


VsOutput vsh(VsInput I)
{
  VsOutput O;

  float4 pos=float4(I.xz.x, I.y, I.xz.y, 1);

  O.pos=mul(globtm, pos);

  O.tc.xy=pos.xz*tcOfs.xy+tcOfs.w;
  O.tc.z=I.foam;

  O.fog=vs_calc_fog_color(pos.xyz);
  O.eyeVec=pos.xyz-view_pos.xyz;

  return O;
}


float4 psh(VsOutput I) : COLOR
{
  float3 res;

  float4 norm=tex2D(normTex, I.tc.xy);
  norm.xyz=norm.xyz*2-1;
  norm.xyz=normalize(norm.xyz);
  float ao=norm.w;

  float3 eyeVec=normalize(I.eyeVec);

  float3 ldir=normalize(-eyeVec+float3(0, 1, 0));

  res=saturate(dot(sun_dir.xyz, ldir))*0.15*(sunL.rgb+calc_sky_light(float3(0, 1, 0)));

  float fk=I.tc.z;
  float foam=lerp(fk, 1, fk*fk*0.7);

  // light
  float3 light=calc_simple_light(norm.xyz, ao);

  float3 foamColor=light*1.5;

  // sky reflection
  float3 vdir=reflect(eyeVec, norm.xyz);

  float3 refl=calc_sky_sun_color(vdir);

  float c=dot(norm.xyz, vdir);
  c=smoothstep(0, 1-0.7, c);

  refl*=float3(0.8, 0.9, 1.0)*0.8;

  // result
  res=lerp(res, refl, lerp(c, 1, 0.5));

  res=lerp(res, foamColor, foam);

  // fog
  res=lerp(res, I.fog.rgb, I.fog.a);

  return pack_color(res, 1);
}
