// Fragment Shader – file "minimal.frag"

#version 150 core

in vec2 ex_texcoord;
in vec3 ex_normal;
in vec3 ex_tangent;
in vec3 ex_bitangent;
in vec3 ex_eye;
in vec3 ex_lightdir;

out vec4 out_color;

uniform vec4 color_ambient;
uniform vec4 color_diffuse;
uniform vec4 color_specular;
uniform float shininess;
uniform sampler2D tex;
uniform sampler2D texNormal;

void main(void)
{
    vec4 final_color = color_ambient;
    //vec3 N = normalize(ex_normal);
    vec3 L = normalize(ex_lightdir);
    vec3 map_normal = normalize(texture2D(texNormal, ex_texcoord).xyz * 2.0 - 1.0);

    mat3 TBN = mat3(normalize(ex_tangent), normalize(ex_bitangent), normalize(ex_normal));
    vec3 N = normalize(TBN * map_normal);

    float lambertTerm = dot(N,L);

    if (lambertTerm > 0.0)
    {
        final_color += color_diffuse * lambertTerm;
        vec3 E = normalize(ex_eye);
        vec3 R = reflect(-L, N);
        float specular = pow(max(dot(R,E), 0.0), shininess);
        final_color += color_specular * specular;
    }

    vec4 texel = texture(tex, ex_texcoord);
    
    out_color = final_color * texel;
}
