#version 430 core

uniform vec2 detailParams; // uv-scale, intensity

uniform sampler2D alphamap;
uniform sampler2D diffusemap;
uniform sampler2D normalmap;
uniform sampler2D details_diffuse;
uniform sampler2D details_normal;

in vec3 normal;
in vec4 tangent;
in vec2 uv;
in vec3 world_uvw;

layout (location = 0) out vec4 gb_diffuse;
layout (location = 2) out vec4 gb_normal;   // normal xyz, ?

void main()
{
#if 1
	float alpha = texture(alphamap, uv).r;
	if ( alpha < (10.0/255.0) ) discard;

	vec3 t = normalize(tangent.xyz);
	vec3 n = normalize(normal);
	//vec3 b = normalize( cross(n, t) * tangent.w );
	vec3 b = normalize( cross(n, t) );
	
	vec3 bn = texture(normalmap, uv).xyz*2.0 - vec3(1.0);

	vec3 diff = texture(diffusemap, uv).rgb;

	vec2 uv2 = world_uvw.xz * detailParams.x;
	diff *= vec3(1.0) - texture(details_diffuse, uv2).xyz * alpha * 0.5 * detailParams.y;
	bn += (texture(details_normal, uv2).xyz*2.0 - vec3(1.0)) * alpha * 0.5 * detailParams.y;

	gb_diffuse.rgb = diff;
	gb_diffuse.a = alpha*0.75;

	mat3 mr = mat3(t, b, n);
	n = normalize(mr*bn);
	gb_normal.rgb = n;
	gb_normal.a = alpha;
#else
	float alpha = texture(alphamap, uv).r;
	if ( alpha < (10.0/255.0) ) discard;

	vec3 diff = texture(diffusemap, uv).rgb;

	vec2 uv2 = world_uvw.xz * detailParams.x;
	diff *= vec3(1.0) - texture(details_diffuse, uv2).xyz * alpha * 0.5 * detailParams.y;

	gb_diffuse.rgb = diff;
	gb_diffuse.a = alpha*0.75;
#endif
}
