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

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

uniform sampler2D image;

vec3 bgf(vec3 dir) {
    vec3 col = vec3(0);
    col += 0.5*max(vec3(0), vec3(0.11,0.06,0.06)*smoothstep(0.3,0.5,dot(dir, normalize(vec3(0,0,-1)))));
    col += 0.2*max(vec3(0), vec3(0.13,0.31,0.31)*smoothstep(0.5,0.9,dot(dir, normalize(vec3(1,-1,-1)))));
    return col;
}

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;
    vec3 refray = reflect(eyeray, norm);
    float specular = pow(max(0,dot(refray, -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));
    color+=bgf(refray);
    color+=max(0,smoothstep(-0.05,-0.06,vpos.y)-smoothstep(-0.07,-0.08,vpos.y)+smoothstep(-0.1,-2.0,vpos.y))*vec3(1,0.2,0.1)*1;
    fragColor = vec4(color*(1+nTime*2), 1);
}
