#version 150 //GL 3.2

#include <hostdefs>
#line 4

uniform sampler2D tex_diff;

/*
R: diffuse
	0 = ⟨discard⟩
	1 =                `color_diff_a`
	2 = ⟨diff tex⟩   * `color_diff_a`
	3 = ⟨vert color⟩ * `color_diff_a`

G: specular
	0 = ⟨discard⟩
	1 =                  `color_spec_bl.rgb`
	2 = ⟨diff tex⟩.rgb * `color_spec_bl.rgb`

B: shininess + diffuse/specular blending ratio source
	0    = ⟨discard⟩
	else = shininess=⟨value⟩/65535, ratio=`color_spec_bl.w`

A: emissive source
	0 = ⟨discard⟩
	1 = `color_emiss`, and discard normal
*/
uniform ivec4 config;
uniform vec4 color_diff_a;
uniform vec4 color_spec_bl;
uniform vec3 color_emiss;



in vec3 norm;
in vec2 texc;
in vec4 vcol;

out vec4 frag_diff_a ;
out vec4 frag_spec   ;
out vec4 frag_shin_bl;
out vec4 frag_emiss  ;
out vec4 frag_normal ;

void main()
{
	//Diffuse + alpha
	vec4 diff_tex_value = vec4(0.0); //Initialize to placate compiler
	switch (config.x)
	{
		case 0: frag_diff_a = vec4(0.0); break;
		case 1: frag_diff_a = color_diff_a; break;
		case 2:
		{
			#if GBUF_TEXAA == 1

				diff_tex_value = texture2D( tex_diff, texc );
				frag_diff_a = diff_tex_value;

			#else

				//Supersample the texture lookup; useful because we want to antialias this; even if
				//	nearest, want to have smooth edges.

				vec2 dCdx = (1.0/GBUF_TEXAA) * dFdx(texc);
				vec2 dCdy = (1.0/GBUF_TEXAA) * dFdy(texc);
				vec2 coord = texc - (float(GBUF_TEXAA-1)/float(2*GBUF_TEXAA)) * ( dCdx + dCdy );

				diff_tex_value = vec4(0.0);
				for ( int j=0; j<GBUF_TEXAA; ++j )
				for ( int i=0; i<GBUF_TEXAA; ++i )
				{
					diff_tex_value += texture2D( tex_diff, coord + float(i)*dCdx + float(j)*dCdy );
				}
				diff_tex_value *= 1.0/(GBUF_TEXAA*GBUF_TEXAA);

				frag_diff_a = diff_tex_value;

			#endif

			frag_diff_a *= color_diff_a;

			break;
		}
		default: /*case 3:*/ frag_diff_a = vcol * color_diff_a; break;
	}

	//Specular
	switch (config.y)
	{
		case 0 :             frag_spec = vec4(0.0); break;
		case 1 :             frag_spec = vec4( color_spec_bl.rgb                     , 1.0 ); break;
		default: /*case 2:*/ frag_spec = vec4( color_spec_bl.rgb * diff_tex_value.rgb, 1.0 ); break;
	}

	//Shininess + diffuse/specular blending ratio
	if ( config.z != 0 )
	{
		float shin = float(config.z) * (1.0/65535.0);
		frag_shin_bl = vec4( shin,color_spec_bl.w,0.0, 1.0 );
	}
	else frag_shin_bl = vec4(0.0);

	//Normal and emissive
	frag_normal = vec4( norm, 1.0 );
	if ( config.w == 0 ) frag_emiss = vec4(0.0);
	else
	{
		frag_normal = vec4(0.0); //Don't want to cover up normal from non-emissive geometry below
		frag_emiss = vec4( color_emiss, 1.0 );
	}
}
