// vert //

out vec3 geom_normal;
out mat3 TBN;
out vec4 object_color;

void main(void) {
	qgl_MaterialIndex = qgl_Material;
	qgl_FragTexture = qgl_Texture;
	gl_Position = qgl_ftransform();
	
	geom_normal = normalize(qgl_Normal * qgl_getNormalMatrix());
	TBN = qgl_getTangentMatrix() * mat3(qgl_Tangent, qgl_Bitangent, qgl_Normal);
	object_color = qgl_ObjectColor;
}


// frag //

in vec3 geom_normal;
in mat3 TBN;
in vec4 object_color;

uniform vec2 dt;
uniform float z_near;

const vec3 luma = vec3(0.299, 0.587, 0.114);
const float _pe = 2.4e-7;

void main(void) {
	vec2 tc = qgl_FragTexture.xy;

	vec4 diffuse = qgl_materialTexture(QGL_MAP_DIFFUSE, tc, vec4(0)) * object_color;
	diffuse.rgb *= qgl_material[qgl_MaterialIndex].color_diffuse.rgb;
	diffuse.a *= (1.f - qgl_material[qgl_MaterialIndex].transparency);

	vec3 normal, dn;
	dn = qgl_materialTexture(QGL_MAP_NORMAL, tc, -vec4(0.5, 0.5, 1., 0.)).xyz;
	//dn.y = -dn.y;
	float dn_sl = length(dn);
	dn = TBN * dn;
	dn *= dn_sl / (length(dn) + 1E-6);
	normal = normalize(geom_normal + dn);
	
	float metalness = dot(qgl_materialTexture(QGL_MAP_METALNESS, tc, vec4(0)).rgb, luma);
	metalness = clamp(metalness, 0, 1);
	
	float roughness = dot(qgl_materialTexture(QGL_MAP_ROUGHNESS, tc, vec4(0)).rgb, luma);
	roughness = clamp(roughness, 0.0001, 0.9999);
	
	float reflectivity = clamp(qgl_material[qgl_MaterialIndex].reflectivity, 0., 1.);

	vec4 emission = qgl_materialTexture(QGL_MAP_EMISSION, tc, vec4(0));
	emission *= qgl_material[qgl_MaterialIndex].color_emission;

	float height = dot(qgl_materialTexture(QGL_MAP_RELIEF, tc, vec4(0)).rgb, luma);
	
	float z = gl_FragCoord.z;
	z = z + z - 1;
	z = ((_pe - 2.) * z_near) / (z + _pe - 1.); // infinite depth

	qgl_FragData[0] = vec4(diffuse .rgba);
	qgl_FragData[1] = vec4(normal  .xyz, z);
	qgl_FragData[2] = vec4(metalness, roughness, reflectivity, 0);
	qgl_FragData[3] = vec4(emission.rgb, 0/*bn.x*/);
	//qgl_FragData[4] = vec4(speed.xy, bn.yz);

	//ivec2 itc = ivec2(gl_FragCoord.xy);
	//qgl_FragData[0].rgb = vec3(dot(n,vec3(0,0,1)));
	//qgl_FragData[0].rgb = diffuse.rgb * dot(n,vec3(0,0,1));
}
