/**
 *
 * Diplomova prace
 * Stinove techniky na dnesnim hardware a jejich porovnani
 *
 * Michal Toth
 *
 * Fakulta informacnich technologii
 * Vysoke uceni technicke v Brne
 *
 * 2013/2014
 *
 */

/*
 * Materialovy shader pro aplikaci barvy, spekularni textury, emitovaci textury
 * a jednoduchy bump mapping (pouze na rovnou plochu)
 */

#version 420

in vec3 position;
in vec3 normal;
in vec2 tc;

uniform sampler2D texNormal;
uniform sampler2D texSpecular;
uniform sampler2D texEmit;
uniform sampler2D KaTex;

uniform bool useTexSpecular;
uniform bool useTexNormal;

uniform vec3 Ka;
uniform vec3 La;
uniform vec3 Ld;
uniform vec3 Ls;

uniform vec3 cameraPos;
uniform vec3 lightPos;

uniform mat4 mNorm;

uniform float shininess=32;

out vec4 fragColor;

void main() {
    vec3 col = Ka+texture(KaTex,tc).rgb;

    vec3 E = texture(texEmit,tc).rgb;

    vec3 N;
    if(useTexNormal){
	vec3 tn = (mNorm*vec4(texture(texNormal,tc).rgb*2.0-1.0,1)).rgb;
	N = normalize(normal+tn);
    }else{
	N = normalize(normal);
    }

    vec3 L = normalize(lightPos-position);

    vec3 A = La*col;
    vec3 D = Ld*max(dot(L,N),0)*col;

    vec3 S = vec3(0,0,0);
    if(shininess>0){
	vec3 V = normalize(cameraPos-position);
	vec3 R = reflect(-L,N);
	float spec = max(0,pow(dot(R,V),shininess));
	S = spec*Ls;
	if(useTexSpecular){
	    S*=texture(texSpecular,tc).rgb;
	}
    }

    fragColor = vec4(A+D+S+E,1);
}
