#version 330 core

in vec2 texCoord;
in vec3 N;
in vec3 P;
in vec4 ShadowCoord;

out vec4 color; 

uniform vec3 light;
uniform vec3 shadowLightDir;
uniform sampler2D color_texture;
uniform sampler2D shadowmap;

float getFactor(vec3 suv){
	float xOffset = 1.0/1024.0;
    float yOffset = 1.0/1024.0;
	
	vec2 suvBig = suv.xy * 1024;
	
	vec2 delta = suvBig - round(suvBig);
	

    float factor = 0.0;
	
	float x = 1/81.0;
	
	for (int y = -4 ; y <= 4 ; y++) {
        for (int x = -4 ; x <= 4 ; x++) {
            vec2 Offsets = vec2(x * xOffset, y * yOffset);
            vec3 UVC = vec3(suv.xy + Offsets, suv.z);
			if ( texture( shadowmap, UVC.xy).r  <  UVC.z - 0.0001){
				factor += 0.4;
			} else {
				factor += 1.0;
			}
        }
    }

    return factor*x;
}

float getPFactor(vec3 suv){

	float bias = 0.001;
	
	vec2 suvBig = suv.xy * 1024;
	
	vec2 delta = suvBig - round(suvBig);
	
	if (delta.x == 0) {
		delta.x = bias;
	}
	if (delta.y == 0) {
		delta.y = bias;
	}
	
	//vec2 uvNew = round(suvBig)/1024.0;
	
	vec2 offset = vec2(sign(delta.x), sign(delta.y));
	
	
	
	vec2 offsetDiv = offset/1024.0;
	float o1;
	float o2;
	float o3;
	float o4;
	if ( texture( shadowmap, suv.xy).r  <  suv.z - bias){
		o1 = 0.4;
	} else {
		o1 = 1.0;
	}
	if ( texture( shadowmap, suv.xy+vec2(offsetDiv.x, 0)).r  <  suv.z - bias){
		o2 = 0.4;
	} else {
		o2 = 1.0;
	}
	if ( texture( shadowmap, suv.xy+vec2(0, offsetDiv.y)).r  <  suv.z - bias){
		o3 = 0.4;
	} else {
		o3 = 1.0;
	}
	if ( texture( shadowmap, suv.xy+offsetDiv).r  <  suv.z - bias){
		o4 = 0.4;
	} else {
		o4 = 1.0;
	}
	
	return (o4 * abs(delta.x) * abs(delta.y)) + (o3 * (1 - abs(delta.x)) * abs(delta.y)) + (o2 * abs(delta.x) * (1 - abs(delta.y))) + (o1 * (1 - abs(delta.x)) * (1 - abs(delta.y)));

}

void main(){

	float bias = 0.0001;

	vec3 suv = ShadowCoord.xyz*0.5 + vec3(0.5, 0.5, 0.5);

	//float visibility = 1.5;
	//if ( texture( shadowmap, suv.xy).r  <  suv.z - bias){
	//	visibility = 0.4;
	//}
	
	float visibility = getFactor(suv);
	
	//visibility = texture(shadowmap, suv);
    
    vec3 textureColor = texture(color_texture, texCoord).rgb;
    vec3 normal = normalize(N);

    vec3 lightDirection = normalize(shadowLightDir);

    float attenuation = 1;

    float diffuse = max(0.0, dot(normal,lightDirection));
	
    color = vec4(((diffuse*(attenuation*0.7)+0.3f)*textureColor*visibility), 1.0);
	
	//color = vec4(visibility, visibility, visibility, 1);
	
	//float b = texture( shadowmap, texCoord ).r;
	
	//color = vec4(b, b, b, 1);
}