uniform sampler2D tex;
uniform sampler2D lightFromLeft;
uniform sampler2D lightFromTop;
uniform sampler2D lightFromRight;
uniform sampler2D lightFromBottom;
uniform sampler2D bump;
uniform vec2 lightSize;
uniform float screenHeight;

varying float vflipped;
varying float vstrength;

void main(void) {
    vec4 bumpLookup = texture2D(bump, floor(gl_TexCoord[0].st) / 1024.0);
    float leftM = max(bumpLookup.y - 0.3, 0.0) * 2.0 * bumpLookup.z * vstrength;
    float rightM = max(0.7 - bumpLookup.y, 0.0) * 2.0 * bumpLookup.z * vstrength;
    float topM = max(bumpLookup.x - 0.3, 0.0) * 2.0 * bumpLookup.z * vstrength;
    float bottomM = max(0.7 - bumpLookup.x, 0.0) * 2.0 * bumpLookup.z * vstrength;
	
	vec4 lightTop = texture2D(lightFromTop, vec2(gl_FragCoord.x, screenHeight - gl_FragCoord.y) / lightSize / 4.0);
	lightTop = vec4(lightTop.x * topM, lightTop.y * topM, lightTop.z * topM, 0);
	
	vec4 lightBottom = texture2D(lightFromBottom, vec2(gl_FragCoord.x, screenHeight - gl_FragCoord.y) / lightSize / 4.0);
	lightBottom = vec4(lightBottom.x * bottomM, lightBottom.y * bottomM, lightBottom.z * bottomM, 0);
	
    vec4 lightLeft = texture2D(lightFromLeft, vec2(gl_FragCoord.x, screenHeight - gl_FragCoord.y) / lightSize / 4.0);
	vec4 lightRight = texture2D(lightFromRight, vec2(gl_FragCoord.x, screenHeight - gl_FragCoord.y) / lightSize / 4.0);
	
	if (vflipped > 0.9) {
	    lightLeft = vec4(lightLeft.x * rightM, lightLeft.y * rightM, lightLeft.z * rightM, 0);
	    lightRight = vec4(lightRight.x * leftM, lightRight.y * leftM, lightRight.z * leftM, 0);
	} else {
	    lightLeft = vec4(lightLeft.x * leftM, lightLeft.y * leftM, lightLeft.z * leftM, 0);
	    lightRight = vec4(lightRight.x * rightM, lightRight.y * rightM, lightRight.z * rightM, 0);
	}
	
	gl_FragColor = texture2D(tex, floor(gl_TexCoord[0].st) / 1024.0) * gl_Color + lightLeft + lightRight + lightTop + lightBottom;
}
