#ifdef GL_ES
precision mediump float;
#endif

uniform sampler2D u_texture;
uniform sampler2D u_fogTexture;
uniform vec2 u_resolution;


/**
 * PLAY AROUND WITH THESE
 */

const float unseenBrightness = 0.1;
const float unseenSaturation = 0.0;
const float previouslySeenBrightness = 0.45;
const float previouslySeenSaturation = 0.0;

const float sampleDistance = 3.5; // how many fog texture pixels to blur
const int sampleCount = 30; // more means less noise, more power needed

/**
 * OK STOP PLAYING AROUND
 */


varying vec2 v_texCoord;
varying vec4 v_color;


/**
 * Converts a color to greyscale.*
 *
 * Level 0 is full greyscale, level 1 is full color
 */
vec4 greyscale(in vec4 color, in float level) {
	float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));

	return mix(color, vec4(gray, gray, gray, color.a), level);
}

/**
 * Adjusts the brightness of a color
 */
vec4 brightness(in vec4 color, in float level) {
	return vec4(color.r*level, color.g*level, color.b*level, color.a);
}

/**
 * Sampling for gaussian blur
 */
float sampleGaussian(in sampler2D sampleTexture, in float dist, in float blurSizeH, in float blurSizeV) {
	float sum = 0.0;
	float divideBy = (dist*2.0+1.0)*(dist*2.0+1.0)*2.0;

	for (float x = -dist; x <= dist; x++) {
		for (float y = -dist; y <= dist; y++) {
			sum += texture2D(u_fogTexture, vec2(v_texCoord.x+x*blurSizeH, v_texCoord.y+y*blurSizeV)).r / divideBy;
			sum += texture2D(u_fogTexture, vec2(v_texCoord.x+x*blurSizeH, v_texCoord.y+y*blurSizeV)).g / divideBy;
		}
	}

	return sum / divideBy;
}

/*
float rand0;

void seed(vec2 v){
	rand0=fract(v.x*v.y);
}

float rand(){
	rand0=fract(9645.1344*rand0+6923.8639);
	return abs(clamp(rand0, 0.0, 1.0));
}

*/
/*
// http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/
float rand(in vec2 co) {
	float a = 12.9898;
	float b = 78.233;
	float c = 43758.5453;
	float dt= dot(co,vec2(a,b));
	float sn= mod(dt,3.14);
	return fract(sin(sn) * c);
}
*/
/*
float rand(vec2 n) {
	return 0.5 + 0.5 *
		fract(sin(dot(n.xy, vec2(12.9898, 78.233)))* 43758.5453);
}
*/



/*
//
// Description : Array and textureless GLSL 2D simplex noise function.
//      Author : Ian McEwan, Ashima Arts.
//  Maintainer : ijm
//     Lastmod : 20110822 (ijm)
//     License : Copyright (C) 2011 Ashima Arts. All rights reserved.
//               Distributed under the MIT License. See LICENSE file.
//               https://github.com/ashima/webgl-noise
//

vec3 mod289(vec3 x) {
  return x - floor(x * (1.0 / 289.0)) * 289.0;
}

vec2 mod289(vec2 x) {
  return x - floor(x * (1.0 / 289.0)) * 289.0;
}

vec3 permute(vec3 x) {
  return mod289(((x*34.0)+1.0)*x);
}

float snoise(vec2 v)
  {
  const vec4 C = vec4(0.211324865405187,  // (3.0-sqrt(3.0))/6.0
                      0.366025403784439,  // 0.5*(sqrt(3.0)-1.0)
                     -0.577350269189626,  // -1.0 + 2.0 * C.x
                      0.024390243902439); // 1.0 / 41.0
// First corner
  vec2 i  = floor(v + dot(v, C.yy) );
  vec2 x0 = v -   i + dot(i, C.xx);

// Other corners
  vec2 i1;
  //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0
  //i1.y = 1.0 - i1.x;
  i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
  // x0 = x0 - 0.0 + 0.0 * C.xx ;
  // x1 = x0 - i1 + 1.0 * C.xx ;
  // x2 = x0 - 1.0 + 2.0 * C.xx ;
  vec4 x12 = x0.xyxy + C.xxzz;
  x12.xy -= i1;

// Permutations
  i = mod289(i); // Avoid truncation effects in permutation
  vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 ))
		+ i.x + vec3(0.0, i1.x, 1.0 ));

  vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0);
  m = m*m ;
  m = m*m ;

// Gradients: 41 points uniformly over a line, mapped onto a diamond.
// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)

  vec3 x = 2.0 * fract(p * C.www) - 1.0;
  vec3 h = abs(x) - 0.5;
  vec3 ox = floor(x + 0.5);
  vec3 a0 = x - ox;

// Normalise gradients implicitly by scaling m
// Approximation of: m *= inversesqrt( a0*a0 + h*h );
  m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h );

// Compute final noise value at P
  vec3 g;
  g.x  = a0.x  * x0.x  + h.x  * x0.y;
  g.yz = a0.yz * x12.xz + h.yz * x12.yw;
  return 130.0 * dot(m, g);
}
*/

/**
 * Fast pseudorandom. Needs a vec2 for seed
 */
float rand(vec2 co) {
	float a = 12.9898;
	float b = 78.233;
	float c = 43758.5453;
	float dt= dot(co.xy ,vec2(a,b));
	float sn= mod(dt,3.14);
	return fract(sin(sn) * c);
}



//https://github.com/ashima/webgl-noise/wiki

/**
 * Sampling for monte carlo blur
 */
float sampleMonteCarlo(in sampler2D sampleTexture, in float dist, in float blurSizeH, in float blurSizeV, in int iter) {
	float sum = 0.0;

	float x = 0.0;
	float y = 0.0;

	vec2 sd = v_texCoord;

	float fiter = float(iter);
	float chunk = 0.0;


	for (int i = 0; i < iter; i++) {
		chunk = float(i) / fiter;

		sd.x += chunk/blurSizeH;
		x = (rand(sd)*dist*2.0)-dist;
		sd.y += chunk/blurSizeV;
		y = (rand(sd)*dist*2.0)-dist;

		sum += texture2D(u_fogTexture, vec2(v_texCoord.x+x*blurSizeH, v_texCoord.y+y*blurSizeV)).r;
		sum += texture2D(u_fogTexture, vec2(v_texCoord.x+x*blurSizeH, v_texCoord.y+y*blurSizeV)).g;
	}

	return sum / float(iter*2);
}

void main() {
	float blurSizeH = 1.0/u_resolution.x; // one horizontal pixel in the fog map
	float blurSizeV = 1.0/u_resolution.y; // one vertical pixel in the fog map


	// blurry sampling from the seen / visible textures

	//float sum = sampleGaussian(u_fogTexture, sampleDistance, blurSizeH, blurSizeV);
	float sum = sampleMonteCarlo(u_fogTexture, sampleDistance, blurSizeH, blurSizeV, sampleCount);


	// color adjustments

	vec2 texCoord = vec2(gl_FragCoord.x / u_resolution.x, gl_FragCoord.y / u_resolution.y);
	vec4 color = texture2D(u_texture, texCoord);

	float brightnessLevel;
	float grayscaleLevel;

	// previously or currently seen
	if (sum >= 0.5) {
		brightnessLevel = mix(previouslySeenBrightness, 1.0, sum*2.0 - 1.0);
		grayscaleLevel = mix(previouslySeenSaturation, 1.0, sum*2.0 - 1.0);
	// never seen
	} else {
		brightnessLevel = mix(unseenBrightness, previouslySeenBrightness, sum*2.0);
		grayscaleLevel = mix(unseenSaturation, previouslySeenSaturation, sum*2.0);
	}

	color = greyscale(color, 1.0-grayscaleLevel);
	color = brightness(color, brightnessLevel);

	gl_FragColor = color;
}
