#version 460 core

in vec4 kolorGeomToFrag;
in vec3 polozenie_scena_geom;
in vec3 normalna_scena_geom;
in vec2 wspTekstur_geom;

uniform vec3 PolozenieKamery = vec3(0,0,1);
uniform sampler2D ProbnikTeksturySfery;
uniform samplerCube ProbnikTeksturySkybox;

out vec4 FragColor;

vec4 reflection(vec3 I, vec3 N)
{
	vec3 R = reflect(I, N);
	vec4 environmentColor = texture(ProbnikTeksturySkybox, R);
	return environmentColor;
}

vec4 refraction(vec3 I, vec3 N)
{
	// dyspersja/rozszczepienie chromatyczne
	const vec3 etaRatio = vec3(1.1, 1.7, 1.4);
	vec3 TRed   = refract(I, N, etaRatio.r);
	vec3 TGreen = refract(I, N, etaRatio.g);
	vec3 TBlue  = refract(I, N, etaRatio.b);

	vec4 environmentColor;
	environmentColor.r = texture(ProbnikTeksturySkybox, TRed).r;
    environmentColor.g = texture(ProbnikTeksturySkybox, TGreen).g;
    environmentColor.b = texture(ProbnikTeksturySkybox, TBlue).b;
	environmentColor.a = 1.0;

	return environmentColor;
}


vec4 fresnel(vec3 I, vec3 N, vec4 reflectedColor, vec4 refractedColor)
{
	float bias = 0.2;
	float scale = 3;
	float power = 1.3;
	
	float reflectionFactor = clamp(bias + scale * pow(1.0 + dot(I, N), power), 0, 1);

	vec4 finalColor = mix(refractedColor, reflectedColor, reflectionFactor);
    return finalColor;
}

vec4 CieniowanieFresnela(vec4 argkolor)
{
	vec3 I = normalize(polozenie_scena_geom - PolozenieKamery);
	vec3 N = normalize(normalna_scena_geom);
	vec4 reflectedColor = reflection(I, N);
	vec4 refractedColor = refraction(I, N);

	return fresnel(I, N, reflectedColor, refractedColor);
}

void main()
{
	FragColor = CieniowanieFresnela(FragColor);
}
