uniform sampler2D materialtex;
uniform sampler2D normaltex;
uniform sampler2D colortex;

varying vec3 normal;
varying vec3 tangent;
varying vec3 binormal;
varying vec4 color;

vec3 nnormal;

void main()
{
//	gl_FragColor=vec4(0,1,0,0);
//	return;

	vec3 tnormal=texture2D(normaltex, gl_TexCoord[0].st).xyz;
	tnormal=(tnormal-vec3(0.5, 0.5, 0.5))*2.0;
	nnormal=normalize(tangent*tnormal.x + binormal*tnormal.y + normal*tnormal.z);

	// overlay vertex color (selection, mask)
//	outcolor+=color;

	vec2 lightmap_coords=nnormal.xy*0.495+vec2(0.5, 0.5);
	lightmap_coords.y*=-1.0;

	vec4 shade=texture2D(materialtex, lightmap_coords);
	
	vec4 texcolor=texture2D(colortex, gl_TexCoord[0].st);

	gl_FragColor=mix(texcolor, shade, color.w)*color;
	gl_FragColor.w=1.0;

/*	vec4 multfactor=shade*2.0;
	vec4 screenfactor=multfactor-vec4(1,1,1,1);
	multfactor=min(multfactor, vec4(1,1,1,1));
	screenfactor=max(screenfactor, vec4(0,0,0,0));
	
	color=vec4(1,1,1,1)-(vec4(1,1,1,1)-color)*(vec4(1,1,1,1)-screenfactor);
	
	gl_FragColor=color*multfactor;
*/
}

