// Copyright (C) Kimmo Lahtinen - All Rights Reserved

/*

OLD SGX GPUS:

Swizzling components of vectors declared with low precision is expensive and should be avoide.

Many built-in functions use medium-precision inputs and outputs. If your app provides low-precision 
floating-point values as parameters or assigns the results to a low-precision floating-point variable, 
the shader may have to include additional instructions to convert the values. These additional instructions 
are also added when swizzling the vector results of a computation.

For best results, limit your use of low-precision variables to color values.

Note: It may not seem obvious, but any calculation on the texture coordinates counts as a 
dependent texture read. For example, packing multiple sets of texture coordinates into a single 
varying parameter and using a swizzle command to extract the coordinates still causes a dependent texture read.

NEW GPUS:

Medium- and low-precision floating-point shader values are computed identically, 
as 16-bit floating point values. This is a change from the PowerVR SGX hardware, which used 10-bit 
fixed-point format for low-precision values. If your shaders use low-precision floating point 
variables and you also support the PowerVR SGX hardware, you must test your shaders on both GPUs.

*/

varying lowp vec4 frag_color;
varying highp vec2 frag_uv_diffuse;
varying mediump vec2 frag_uv_ground;
varying mediump vec2 frag_ground_add_mul;

uniform sampler2D uni_texture_diffuse;

void main(void) 
{
	// TODO: could disable some features on shitty devices? maybe try sampling ground color
	// in vertex shader?

	vec4 tex_color_diffuse = texture2D(uni_texture_diffuse, frag_uv_diffuse);

	// Sample ground color texture
	vec3 tex_color_ground = sample_level_lightmap(frag_uv_ground);
	vec3 tex_color_ground_premult = tex_color_ground * tex_color_diffuse.a; // Premultiply ground texture color (premult alpha)

	// Mix texture color with ground color
	vec3 final_color = mix(tex_color_diffuse.rgb, tex_color_ground_premult, frag_ground_add_mul.y);

#ifdef MEGASPRITE_BETTER_COLOR_FLASHES
	// Some color kludging: overbright with add + clamping to 1.0 for damage red flash or shielded blue etc.
	final_color = min(final_color + frag_ground_add_mul.x * tex_color_diffuse.a, 1.0);
#endif	
//	frag_color = vec4(1, 0, 0, 1);
	// DEBUG: highlight grass show sprites
//	final_color.rgb *= 0.01; final_color.rgb += tex_color_diffuse.rgb;

	gl_FragColor = vec4(final_color, tex_color_diffuse.a) * frag_color;
//	gl_FragColor.a = 1.0;
}
