in vec3 normal;
in vec2 uv;
in vec3 frag_position;
in float mat;
out vec4 fragColor;

uniform vec2 iResolution;
uniform vec3 eye;
uniform float fTime;
uniform int instanceX;
uniform int instanceZ;

uniform sampler2D image;

void main() {
    fragColor = vec4(uv, 1.0, 1.0);
    fragColor = vec4(normal, 1.0);
    fragColor = vec4(0.41, 0.69, 0.17, 1.0);
    //fragColor = texture(image, uv);

    vec4 map = texture(image, uv*2.0+instanceX*0.4+instanceZ*0.3);
    vec3 albedo = map.x*vec3(0.5, 0.5, 0.5);
    if (mat > 1.5) albedo=vec3(0.1,0.1,0.0);
    float radius = 143.0;
    vec3 lightpos = vec3(sin(fTime), -4, cos(fTime))*4.1;
    vec3 position = frag_position.xyz;
    vec3 norm = normal;
    if (mat < 1.5) norm += map.y;
    norm = normalize(norm);
    vec3 lightray = normalize(position-lightpos);
    vec3 eyevector = position-eye;
    float eyedistance = length(eyevector);
    vec3 eyeray = eyevector / eyedistance;
    float falloff = 1 / pow(distance(position, lightpos),2.0);
    float fres = mix(pow(1.0-dot(eyeray, -normal), 4.0), 1.0, 0.01);

    float diffuse = max(0, dot(norm, normalize(lightpos-position)));
    float rough = 1.0/map.z;
    if (mat > 1.5) rough = 1.0;
    if (mat < 0.5) rough = 999.0;
    float specular = pow(max(0,dot(reflect(eyeray, norm), -lightray)),rough)/rough;
    vec3 color = mix(diffuse*albedo,specular+vec3(0.1,0.2,0.3),vec3(fres));
    color = mix(color, vec3(0,0,0), 1-1/(1+eyedistance*eyedistance*1e-3));
    fragColor = vec4(color, 1);
}
