#version 430

layout(binding=0) uniform sampler2D tex;
layout(binding=1) uniform sampler2D texNorm;

in vec4 posG;
in vec3 normalG;
in vec2 uvG;
in vec3 tangentG;
in vec3 colorG;

layout(location = 0) out vec4 frag;
layout(location = 1) out vec4 frag2;

// layout(location = 0) out uvec4 uex_colour;
// layout(location = 1) out vec4 ex_colour;

uniform float g_time;

uniform float g_uvOfsX = 0.0;

void main() {

  vec3 normal = normalG;
  vec2 uv = uvG;
  vec3 tangent = tangentG;
  vec3 color = colorG;

 // color.rgb = vec3(1.0);

  vec4 diffuse = vec4(0.0);
  vec2 myUv;

  myUv = uv*5.0;
  myUv.y = fract((myUv.y+0.5)*2.0)*0.5+0.5;
  myUv.y *= -1.0;
  myUv.x += g_uvOfsX;

  vec4 texv = texture2D(tex, myUv.xy*1.0);
  diffuse += 1.0*texv*texv*100.0+0.0*vec4(1.0);

  myUv = uv*3.0;
  myUv.y = fract((myUv.y+0.5)*2.0)*0.5+0.5;
  myUv.y *= -1.0;
  myUv.x += g_uvOfsX;
  texv = texture2D(tex, myUv.xy*1.0);
  diffuse += 1.0*texv*texv*100.0+0.0*vec4(1.0);

  diffuse.a = 1.0;


 // diffuse.r = pow(diffuse.r, 2.5);
 // diffuse.g = pow(diffuse.g, 1.10);
 // diffuse.b = pow(diffuse.b, 0.70);

  vec3 lightPos = vec3(0.0*cos(g_time*2.0), 0.0, 5.0);
  vec3 surfPos = vec3(0.0f, 0.0f, 0.0f);
  vec3 lightDir = lightPos-surfPos;

  float lightDist = sqrt(dot(lightDir, lightDir));

  vec3 myNormal = normal;
  vec3 biTangent = cross(myNormal, tangent);

//  float bumpX = 0.0*(texture2D(tex, myUv.xy+vec2(1.0/512.0, 0.0)).g-texture2D(tex, myUv.xy+vec2(-1.0/512.0, 0.0)).g);
//  float bumpY = 0.0*(texture2D(tex, myUv.xy+vec2(0.0, 1.0/512.0)).g-texture2D(tex, myUv.xy+vec2(0.0, -1.0/512.0)).g);


  vec4 normFromTex = texture2D(texNorm, myUv);
  float bumpStrength = 0.1;
  float bumpX = -(normFromTex.x-0.5)*bumpStrength;
  float bumpY = -(normFromTex.y-0.5)*bumpStrength;

//  bumpX = 0.0;
//  bumpY = 0.0;

  myNormal += tangent*bumpX + biTangent*bumpY;


  float normalLen = sqrt(dot(myNormal, myNormal));

  float d = dot(lightDir, myNormal)/(lightDist*normalLen);
  d = clamp(d, 0.0, 1.0);

  //d = d*0.35+pow(d, 128.0f);
  //frag = vec4(d, d, d, d);

 // frag = (diffuse+0.4)*d*0.35 + pow(d, 128.0f)+0.03;

  float specPow = 80.0;

  frag = diffuse*(d*0.0+0.015)*0.5 + 0.0*pow(d, specPow);

  vec4 c = frag;


//  c.r = pow(c.r, 0.85);
//  c.g = pow(c.g, 0.55);
//  c.b = pow(c.b, 0.45);

  c.r = pow(c.r, 1.0);
  c.g = pow(c.g, 1.0);
  c.b = pow(c.b, 1.0);

  c.a = diffuse.a*1.0;

 // c.a = 1.0;

  // c.rgb = vec3((posG.z/posG.w-0.9)*10.0);
  //c.rgb = vec3(gl_FragDepth*10000.0);
  // c.rgb = vec3((gl_FragCoord.z*gl_FragCoord.w-0.0)*10.0);

  float depthi = 1.0-(gl_FragCoord.z*gl_FragCoord.w-0.0)*2.0;

  frag = vec4(c.r, c.g, c.b, c.a);
  frag.a = 1.0;

//  frag.rgb = pow(frag.rgb, vec3(0.5));

 // frag.r = 1.0;

  frag2 = frag;
  frag2 = vec4(frag.rgb, 1.0);
  frag2.r += 0.15;
 // frag2.rgb = vec3(depthi*depthi);

}

