#version 430

layout(binding=0) uniform sampler2D texColor;
layout(binding=1) uniform sampler2D texDepthNorm;
layout(binding=2) uniform sampler2D texPos;

in vec4 posG;
in vec4 posW;
in vec4 posInst;
in float ageG;

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

layout(binding=0, offset=0) uniform atomic_uint ac;

layout(binding=0, r32ui) uniform uimage2D headPointers;
layout(binding=1, r32ui) uniform uimage2D nextPointers;
layout(binding=2, rgba16f) uniform image2D pixelListColors;
layout(binding=3, rgba32f) uniform image2D pixelListDepthNorm;

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

uniform float g_time;

uniform float g_uvOfsX = 0.0;
uniform float g_uvScale = 1.0;

uniform float g_texBrightness = 1.0;

#define PI 3.1415926

vec2 latlong(vec3 v) {
  v = normalize(v);
  float theta = acos(v.z); // +z is up
  float phi = atan(v.y, v.x) + PI;
  return vec2(phi, theta)*vec2(.1591549, .6366198);
}


uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
uniform mat4 modelViewInvMatrix;

uniform mat4 projectionInvMatrix;

uniform mat4 viewMatrix;


vec4 rotateXY(vec4 p, float a) {
  vec4 r = p;
  r.x = cos(a)*p.x - sin(a)*p.y;
  r.y = sin(a)*p.x + cos(a)*p.y;
  return r;
}

vec3 rotateXY3(vec3 p, float a) {
  return rotateXY(vec4(p, 0.0), a).xyz;
}


// google glsl rand gave this, thanks and credit flies to
// http://stackoverflow.com/questions/4200224/random-noise-functions-for-glsl
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

uniform float g_windowWidth=1280.0;
uniform float g_windowHeight=720.0;

uniform float zNear = 0.1;
uniform float zFar = 1000.0;
// convert from 0.0 to 1.0 depth sample ds to linear depth
float linearDepth(float ds) {
    ds = 2.0*ds-1.0;
    float zLinear = 2.0*zNear*zFar/(zFar+zNear-ds*(zFar-zNear));
    return zLinear;
}


void main() {

  vec3 mposInst = posInst.xyz;
  vec3 lightCen = mposInst.xyz*1.0;

  vec2 scrUV = vec2(gl_FragCoord.x/g_windowWidth, gl_FragCoord.y/g_windowHeight);

  vec3 surfPos = texture2D(texPos, scrUV).rgb;
  vec3 surfLight = surfPos.rgb-lightCen;
  float dd = dot(surfLight,surfLight);

  if (dd > 0.250) {
      discard;
  }

  vec3 surfDepthNorm = texture2D(texDepthNorm, scrUV).rgb;
  vec3 surfNorm = vec3(surfDepthNorm.gb, sqrt(1.0-dot(surfDepthNorm.gb, surfDepthNorm.gb)));
  surfNorm = normalize(surfNorm);
  surfNorm = (viewMatrix * vec4(surfNorm, 0.0)).xyz;

  float dots = dot(-surfNorm, surfLight)/sqrt(dd);
  dots = clamp(dots, 0.0, 1.0);

  dots = pow(dots, 8.0);

  float br = 0.1*clamp(ageG, 0.0, 1.0);

  frag.rgb = vec3(br/(dd*dd*200.0+2.0))*dots;

//  frag.rgb = surfNorm;
//  frag.rgb = surfPos*0.01;

  frag.a = 1.0;
  frag2 = vec4(frag.r*100.0, 0.0, 0.0, 1.0);
}

