#include "common.sh"


struct VsOutput
{
  float4 pos  : POSITION;
  float2 tc   : TEXCOORD0;
  float3 wvec : TEXCOORD1;
};


float4 texsz : register(c16);
float4 viewx : register(c17);
float4 viewy : register(c18);
float4 viewz : register(c19);


VsOutput vsh(float2 pos: POSITION)
{
  VsOutput O;
  O.pos=float4(pos, 1, 1);
  O.tc=pos.xy*texsz.xy+texsz.zw;
  O.wvec=pos.x*viewx.xyz+pos.y*viewy.xyz+viewz.xyz;
  return O;
}


float3 viewPos    : register(c16);
float4 ps_options : register(c17);

sampler aperTex : register(s0);


float4 psh(VsOutput I) : COLOR
{
  UNPACK_GBUF(I.tc.xy)

  float4 light=tex2D(light_tex, I.tc.xy);
  unpack_color(light.rgb);
  light*=2;

  light=lerp(light, 1, glow*(1-water));

  float3 eyeVecNorm=normalize(I.wvec);
  float3 eyeVec=I.wvec*depth;
  float3 pos=eyeVec+viewPos;

  float4 aper=tex2D(aperTex, pos.xz*(1.0/HMAP_SIZE)+0.5/HMAP_SIZE)*2-1;
  aper.y=sqrt(1-dot(aper.xz, aper.xz));
  //aper.xyz=normalize(aper.xyz);

  float3 res;

  // res=color;
  //res=norm*0.5+0.5;
  //res=aper.y*0.5+0.5;
  //res=1-aper.w;
  //res=depth*256;
  //res=depth*4;
  // res=light.rgb;
  res=light.rgb*color;

  if (water>0)
  {
    // reflection
    float3 ldir=normalize(-eyeVecNorm+float3(0, 1, 0));
    float3 wres=saturate(dot(sun_dir.xyz, ldir))*0.15*(sunL.rgb+calc_sky_color(float3(0, 1, 0)));

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

    float3 refl=calc_sky_sun_color(vdir);

    float c=dot(aper.xyz, vdir);
    c=smoothstep(aper.w, 1-(1-aper.w)*0.7, c);

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

    // water shading
    float3 foamColor=light.rgb*2;

    wres=lerp(wres, refl, lerp(c, 1, 0.5));

    // blend water
    float w=1-water;
    float w2=w*w, w4=w2*w2, w8=w4*w4;
    float w32=w8*w8; w32*=w32;
    res=lerp(res*lerp(1, 0.5, 1-w32), wres, 1-float3(w4, w2, w));

    res=lerp(res, foamColor, gloss*(1-w32));
  }

  // fog
  float3 fogColor=calc_sky_color(eyeVecNorm)*planet_k;

  float3 v=eyeVec;
  v.y*=0.5;

  float t=saturate(dot(v, v)/(fog_range*fog_range));
  t=(2-t)*t;
  t=t*t;
  float fogFactor=t*ps_options.x;

  res=lerp(res, fogColor, fogFactor);

  return pack_color(res, 1);
}
