
uniform vec4 colorMultiplier;
out vec4 colorResult;

#ifdef TEXTURE
layout (binding = 0) uniform sampler2D texture0;
in vec2 uvOut;
#endif

#ifdef COLOR
in vec4 vertexColor;
#endif

#ifdef HUE_SHIFT
in float hueShiftOut;
#endif

#ifdef NEEDS_SCREEN_SIZE
uniform vec2 screenSize;
#endif

#ifdef LIGHT_MAP
uniform sampler2D lightmap;
uniform vec4 lightmapUV;
in vec4 gl_FragCoord;
#endif

// https://gist.github.com/983/e170a24ae8eba2cd174f
// http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl
// https://stackoverflow.com/questions/15095909/from-rgb-to-hsv-in-opengl-glsl
// All components are in the range [0…1], including hue.
vec3 rgb2hsv(vec3 c)
{
	vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
	vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
	vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));

	float d = q.x - min(q.w, q.y);
	float e = 1.0e-10;
	return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}

// All components are in the range [0…1], including hue.
vec3 hsv2rgb(vec3 c)
{
	vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
	vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
	return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}

void main() {
	colorResult = vec4(1, 1, 1, 1);

#ifdef TEXTURE
	colorResult *= texture(texture0, uvOut);
#endif

#ifdef HUE_SHIFT
	vec3 hsv2 = rgb2hsv(colorResult.rgb);
	hsv2[0] += hueShiftOut / 360;
	colorResult = vec4(hsv2rgb(hsv2), colorResult.a);
#endif

#ifdef COLOR
	colorResult *= vertexColor;
#endif

	colorResult *= colorMultiplier;

#ifdef LIGHT_MAP
	vec4 lightmapSample = texture(lightmap, vec2(
		mix(lightmapUV.x, lightmapUV.z, gl_FragCoord.x / screenSize.x),
		mix(lightmapUV.y, lightmapUV.w, gl_FragCoord.y / screenSize.y)
	));

	colorResult *= vec4(lightmapSample.xyz, 1.0);
#endif
}
