// in which two textures get rendered on top of each other
uniform sampler2D baseMap;
uniform vec2 LightStrength;
uniform vec4 lights1;
varying vec2 Texcoord;


void main(void)
{
	float exposure = 0.0015;
	float decay = 0.98;
	float density = 0.1;
	float weight = 10.0;
    int NUM_SAMPLES = 20;
	
	//convert lightPos to screenPos if not already done so
	vec4 uv = Texcoord.xyxy;
	vec4 l1 = lights1;
	l1.y = 1 - l1.y;
	l1.w = 1 - l1.w;
	vec4 deltaTexCoord = uv - l1;
	float step = 1.0 / float(NUM_SAMPLES) * density;
	deltaTexCoord *= step;
	
	float illuminationDecay = 1.0;
	
	vec4 base = texture2D(baseMap, Texcoord);

	float shadows1 = 0.0;
	float shadows2 = 0.0;
	
	for(int i=0; i < NUM_SAMPLES; i++)
	{
		uv -= deltaTexCoord;
		float sample1 = dot(texture2D(baseMap, uv.xy), vec4(0.3, 0.59, 0.11, 1.0));
		float sample2 = dot(texture2D(baseMap, uv.zw), vec4(0.3, 0.59, 0.11, 1.0));
		sample1 = pow(sample1 + 0.1, 5.0);
		sample2 = pow(sample2 + 0.1, 5.0);
		float d = illuminationDecay * weight;
		sample1 *= d;
		sample2 *= d;
		shadows1 += sample1;
		shadows2 += sample2;
		illuminationDecay *= decay;
	}
	
	shadows1 *= exposure;
	shadows2 *= exposure;
	
	float walls = dot(vec3(0.3, 0.59, 0.11), base.xyz);
	walls = clamp(pow(walls + 0.8, 50.0), 0.0, 1.0);
	
	float att1 = pow(1.0 - clamp(length(l1.xy - Texcoord), 0.0, 1.0), 10.0) * LightStrength.x;
	float att2 = pow(1.0 - clamp(length(l1.zw - Texcoord), 0.0, 1.0), 10.0) * LightStrength.y;
	
	vec4 final = base + ((1.0 - shadows1) * att1 + (1.0 - shadows2) * att2) * vec4(0.5, 0.7, 0.9, 1.0);
	final.a = 1.0;
	gl_FragColor = final;
}