#include "inc/uniforms.glsl"
#include "inc/utils.glsl"
#line 3

uniform mat4 shadowTransform;

#ifdef VERTEX
#line 9
layout(location=0) in vec4 in_Position;
layout(location=1) in vec4 in_Color;
// normal
layout(location=3) in vec2 in_UV;
out vec4 ex_Color;
out vec2 ex_UV;

void main()
{
	ex_Color = in_Color;
	ex_UV = in_UV;
	gl_Position = in_Position;
}

#endif

#ifdef FRAGMENT

in vec4 ex_Color;
in vec2 ex_UV;

layout(location=0) out vec4 out_Color;

uniform sampler2D shadowbuffer;
uniform sampler2D logo;

uniform float p_fullbright;

#include "inc/buffers.glsl"
#include "inc/shadows.glsl"
#line 34

vec3 getViewpos() {
	return texture(positionbuffer, ex_UV).xyz;
}

uniform float debugKey;
uniform float p_brite_mult;

#define COLOR_LUT_SIZE (32.0)

void main()
{
	float depth = texture(depthbuffer, ex_UV).x;
	vec3 viewpos = getViewpos();
	
	vec4 albedo = texture(albedobuffer, ex_UV);
	vec4 col = albedo;
	
	vec4 material = texture(materialbuffer, ex_UV);
	float specularExponent = unscaleSpecular(material.g);
	float specularMultiplier = material.b;
	
	col.r += lights.spot[0].intensity.r;
	
	// the normal components are stored in range [0, 1]
	vec3 normal = normalize(decompressv3(texture(normalbuffer, ex_UV).rgb));
	
	col.rgb = albedo.rgb;
	
	vec4 worldpos = (inverseViewMatrix*vec4(viewpos, 1.0)).xyzw;
	vec4 lightview = shadowTransform * worldpos; // light position in lamp view space
	vec3 lightclip = lightViewToClip(lightview);
	
	vec3 point_to_lamp = normalize(worldpos.xyz - lights.spot[0].pos);

	vec3 lamplight = accumulate_light(scenecam, worldpos, lightclip, normal, specularExponent, specularMultiplier, 0.0);
	
	if (p_fullbright == 0.0) {
		vec3 illum = vec3(0.0) + lamplight;
		col.rgb *= illum;	// show the diffuse color
	}
	
	// Use emit buffer as mixing ratio.
	col.rgb = mix(col.rgb, albedo.rgb, material.r);
	
		col.rgb *= p_brite_mult;
		
	if (debugKey == 0.0f) { 
		vec3 coord = col.rbg;
		vec3 scale = vec3((COLOR_LUT_SIZE - 1.0f) / COLOR_LUT_SIZE);
		vec3 offset = vec3(1.0 / (2.0 * COLOR_LUT_SIZE));
		col.rgb = texture(colorLUT, coord * scale + offset).rgb;
	}
	
	float morenoise = (1.0-length(col.rgb))*5.0;
	col.rgb *= 1.0 + 0.05*noise(vec3(ex_UV.x, ex_UV.y, p_time)) * morenoise;
	
	out_Color = col; 
} 

#endif