#version 120
uniform sampler2D   tex_reflect;
uniform sampler2D   tex_warp;

uniform vec3    light_vec;

uniform vec2    res_r;
uniform vec2    texc_scale;

uniform float   time;
uniform vec3    fov_modifier;

varying vec4    pos;
varying vec3    ltan2, ltan, lnor;

/**
 * Decodes signed normals from their unsigned storage format.
 */
vec3 wrangleNormal(in vec3 sample){
    return sample * 2.0 - vec3(1.0, 1.0, 1.0);
}

void main(){
    vec2 tc = gl_FragCoord.xy * res_r; // base tex coord to warp

    //vec2 time_fac = vec2(sin(time), cos(time));
    vec2 time_fac = vec2(sin(time*0.5)*0.15,time);

    vec3 ns = wrangleNormal(texture2D(tex_warp, gl_TexCoord[0].xy*texc_scale*vec2(1.0, 2.0)+time_fac).wyz)
                + wrangleNormal(texture2D(tex_warp, gl_TexCoord[0].xy*texc_scale*vec2(1.0, 2.0)-time_fac).wyz) * 0.4
                + wrangleNormal(texture2D(tex_warp, gl_TexCoord[0].xy*texc_scale*vec2(9.0, 23.0)-time_fac*2.0).wyz)* 0.1
                + wrangleNormal(texture2D(tex_warp, gl_TexCoord[0].xy*texc_scale*vec2(0.5, 0.1)+time_fac*2.0).wyz)* 0.2;
/*
    KOKEILE EFEKTINÄ! (sämplää vaikka jotain esigeneroitua bittikarttaa)
    vec3 ns = wrangleNormal(texture2D(tex_warp, gl_TexCoord[0].xy*texc_scale*5.0+time_fac).wyz)
                * wrangleNormal(texture2D(tex_warp, gl_TexCoord[0].xy*texc_scale*14.0-time_fac*2.3).wyz)* 1.4
                / wrangleNormal(texture2D(tex_warp, gl_TexCoord[0].xy*texc_scale*202.0+time_fac*1.4).wyz) * 0.3;
*/
//    ns *= vec3(1.0, 1.0, 1.0);

    mat3 matrix = mat3(ltan2, ltan, lnor);

    vec3 normal = normalize(matrix * ns);
    vec3 eye_vec = vec3(tc * 2.0 - vec2(1,1), -1.0) * fov_modifier;

    vec4 ts = texture2D(tex_reflect, tc - normal.yx * vec2(0.04, 0.04)+ vec2(0.04, 0.0));
    float transparency = (dot(normalize(pos.xyz), normal) + dot(normalize(pos.xyz), lnor)) * 0.5;
    transparency *= transparency;

    vec3 R = reflect(normal, -light_vec);
    vec3 V = normalize(eye_vec);
    gl_FragColor = vec4(ts.rgb, mix(1.0, 0.1, transparency))
        + vec4(1.4, 1.0, 0.7, 0.70) * pow(max(0.0, dot(R,V)), 80.0);
}
