/*

Deferred render targets:

0:
 r, g, b: diffuse color
 a:
1:
 r, g, b: normal vector components (mapped to [0..1])
 a: specular scale
2:

*/
#version 120


uniform sampler2D tex_diffuse;
uniform sampler2D tex_normal;
uniform sampler2D tex_param;

uniform float refract_ofs;
varying vec2 pos;

varying vec3 lnor, ltan, ltan2;

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

void main(){
    vec4 diffuse = texture2D(tex_diffuse, gl_TexCoord[0].xy);
    vec4 param = texture2D(tex_param, gl_TexCoord[0].xy);

    if(diffuse.a < 0.4)
        discard;

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

    // swizzling because we're using DXT5 for normal maps, shuffling the
    // components when compressing to use the less-compressed alpha channel:
    // RGB -> xGBR
    // (could we put something into the unused x channel with the right tools?)
    vec3 ns = texture2D(tex_normal, gl_TexCoord[0].xy).wyz;
    vec3 localNormal = normalize(wrangleNormal(ns).xyz);
    localNormal = matrix * localNormal;

	gl_FragData[0] = vec4(pow(diffuse.xyz, vec3(2.2,2.2,2.2)), param.b);
	gl_FragData[1] = vec4(localNormal * 0.5 + vec3(0.5, 0.5, 0.5), 0.0);
}
