uniform sampler2D Texture0;
uniform sampler2D Background;
uniform mat4 ViewMatrixInverse;
uniform vec3 Lamp0Pos;
uniform float SpecExpon;
uniform vec4 DiffuseColor;
uniform float Ks;

varying vec2 texCoord;

vec4 lit(float NdotL, float NdotH, float m) {

  float ambient = 1.0;
  float diffuse = max(NdotL, 0.0);
  float specular = step(0.0, NdotL) * max(NdotH * m, 0.0);

  return vec4(ambient, diffuse, specular, 1.0);
}


vec3 phong_shading(vec3 Nn, vec3 Ln, vec3 Vn)
   {
   float fNDotL           = dot( Vn, Ln );
   return vec3(fNDotL,fNDotL,fNDotL);//*DiffuseColor.xyz;
   vec3  fvReflection     = normalize( ( ( 2.0 * Vn ) * fNDotL ) - Ln ); 
   float fRDotV           = max( 0.0, dot( fvReflection, Vn ) );   
   vec4  fvTotalDiffuse   = DiffuseColor * fNDotL * DiffuseColor; 
   float  fvTotalSpecular  = ( pow( fRDotV, SpecExpon ) ) * Ks;
   return  ( fvTotalDiffuse.xyz + vec3(fvTotalSpecular) );
   }

void main(void)
   {
//   gl_FragColor = texture2D( Texture0, texCoord );
// return;
      
   vec4 n = vec4(0,0,0,0);
   float c = 0.0;
   vec2 uv = texCoord;
   vec4 v = texture2D(Texture0, uv);
   if (v.x==0.0)
      {
      discard;
      }
   //float mult = -v.w;
   float mult = 1.0/0.07;
   for (float x = -2.0; x < 2.0; x+=0.33)
      for (float y = -2.0; y < 2.0; y+=0.33)
         {
         vec4 v2 = texture2D(Texture0, uv+vec2(x*0.1/mult, y*0.1/mult));//, 0.01, 0.01);
         //if ( abs(v.w-v2.w)+abs(x)/10.0+abs(y)/10.0 <= 1.0)
            {
            n+=v2;
            c+=1.0;
            }
         }
         
   n = n/c;
   float h = n.w;
   n.w = 0.0;
   n.z = -n.z;
   n = normalize(n);
   float relh = length(n.xz);

   float val = pow(dot(n.xyz, normalize(vec3(0.-0,03,-1.0))),1.1);
   gl_FragColor = DiffuseColor * val;
   return;
   
/*   vec4 refraction = texture2D(Background, uv+normalize(n.yz)*h/100.0);
   gl_FragColor = refraction;
   return;*/
   
   vec3 LampEyeSpace = (vec4(Lamp0Pos,1) * ViewMatrixInverse).xyz;
   vec3 LightNormalized = normalize(LampEyeSpace);
   
   // hack: using untransformed light
   //gl_FragColor = n;
   //return;

   gl_FragColor = vec4
      (
      phong_shading(n.xyz, normalize(vec3(0,-0.3,-1)), n.xyz),
      1
      );
   }
   