uniform sampler2D s_tex0; 

uniform float exposure;
uniform float daytime;
uniform float dayfactor;

uniform vec4 u_blendcolor;

varying vec2 v_texcoord;

const float MIDDLE_GREY = 0.72;
const float FUDGE = 0.001;
const float L_WHITE = 1.5;
const float PI = 3.14159265358979323846264;

// from: http://www.koders.com/noncode/fidB134383CDA66ACFDDE1E2BB70579CB362DC28D24.aspx
/** Tone mapping function 
@note Only affects rgb, not a
@param inColour The HDR colour
@param lum The scene lumninence 
@returns Tone mapped colour
*/
vec4 toneMap(in vec4 inColour, in float lum)
{
	// From Reinhard et al
	// "Photographic Tone Reproduction for Digital Images"
	
	// Initial luminence scaling (equation 2)
    inColour.rgb *= MIDDLE_GREY / (FUDGE + lum);

	// Control white out (equation 4 nom)
    inColour.rgb *= (1.0 + inColour.rgb / L_WHITE);

	// Final mapping (equation 4 denom)
	inColour.rgb /= (1.0 + inColour.rgb);
	
	return inColour;

}

vec4 tint(in vec4 color)
{
	// time parameter is 24h compressed into 0..1 around midnight
	// 0.0  -> 00:00
	// 0.25 -> 06:00
	// 0.5  -> 12:00
	// 0.75 -> 18:00
	// a 15 hour day goes from 05:30 (.229166667) to 20:30 (.854166667)

	// tint according to time of the day
	vec4 skycolor;
	// skycolor.r = sin((daytime-2.3)*2.0*PI)*0.3+0.3; //max(0.0, sin((daytime-0.14)*1.2*PI))*0.3;
	// skycolor.g = max(0.0, sin((daytime-0.2292)*1.6*PI))*0.61;
	// skycolor.b = max(0.0, sin((daytime-0.2292)*2.0*PI)/2.0+0.1);
	skycolor.rgb *= color.rgb;

	color.rgb = (1.-dayfactor) * color.rgb + dayfactor * skycolor.rgb;

	// then we tonemap
	color = toneMap(color, exposure);
	return color;
}

void main()
{	
	vec4 color = texture2D(s_tex0, v_texcoord) * u_blendcolor;

	gl_FragColor = tint(color);
} 
