// Genetic object shader

#version 330

#pragma vertex_shader

in vec4 vertex;
in vec3 normal;
in vec4 tangent;
in vec2 texCoord;


#ifdef SKINNED
in vec4  weights;
in ivec4 indices;
uniform mat4 boneMatrices[84];
#endif

uniform mat4  transform;
uniform mat4  modelMatrix;

out vec2 texcoord;
out vec3 worldNormal;
out vec3 worldPos;
out vec3 worldTangent;
out vec3 worldBinormal;

void main() {
	vec4 pos = vertex;
	vec3 norm = normal;
	vec3 tang = tangent.xyz;
	
	#ifdef SKINNED
	vec4 weight = weights;
	ivec4 index = indices;
	vec3 blendPos = vec3(0.0);
	vec3 blendNorm = vec3(0.0);
	vec3 blendTang = vec3(0.0);
	for(int i=0; i<SKINNED; ++i) {
		blendPos  += (boneMatrices[index.x] * vertex).xyz * weight.x;
		blendNorm += mat3(boneMatrices[index.x]) * normal * weight.x;
		blendTang += mat3(boneMatrices[index.x]) * tangent.xyz * weight.x;
		weight = weight.yzwx;
		index = index.yzwx;
	}
	pos.xyz = blendPos;
	norm = blendNorm;
	tang = blendTang;
	#endif

	gl_Position = transform * pos;
	texcoord = texCoord;
	worldNormal = mat3(modelMatrix) * norm;
	worldTangent = mat3(modelMatrix) * tang;
	worldBinormal = cross(worldNormal, worldTangent) * tangent.w;
	worldPos = (modelMatrix * pos).xyz;
}


#pragma fragment_shader

in vec2 texcoord;
in vec3 worldNormal;
in vec3 worldTangent;
in vec3 worldBinormal;
in vec3 worldPos;

layout(location=0) out vec4 buf0;
layout(location=1) out vec4 buf1;

uniform sampler2D diffuseMap;
uniform sampler2D normalMap;
uniform vec4 highlight;


void main() {
	vec4 diff = texture(diffuseMap, texcoord.st);
	vec4 norm = texture(normalMap, texcoord.st); 

	#ifdef THRESHOLD
	if(diff.a < THRESHOLD) discard;
	diff.rgb *= 1.3;
	#endif

	// Highlight colourise
	diff.rgb = mix(diff.rgb, highlight.rgb, highlight.a);

	// Normal map
	vec3 n = norm.xyz * 2.0 - 1.0;
	mat3 tbn = mat3(normalize(worldTangent), normalize(worldBinormal), normalize(worldNormal));
	vec3 normal = tbn * n;

	// Lighting
	float l = dot(normal, normalize(vec3(1.0,1.0,1.0)));
	float s = (l+1.0)/1.3 * 0.2 + 0.1;
	diff.rgb *= max(l, s);


	buf0 = diff;
	buf1 = vec4(normal * 0.5 + 0.5, 0.0);

}

