

// wether the eye is located in the origin (true)
// or at (0,0, +infinity) (false)
uniform bool eyeAtOrigin;
uniform sampler2D colMap;
uniform sampler2D norMap;
uniform sampler2D transpMap;
uniform float scaleTex;
uniform int tecCoordGen;
uniform float tex_tran_x;
uniform float tex_tran_y;
uniform float minTransp;

uniform bool drawOnlyNormal;
uniform bool drawOnlyDepth;



varying vec3 normal; // fragment normal in eye space.
varying vec3 position; // fragment position in eye space.
varying vec3 nor;
varying vec3 vertex;
vec2 tc;
varying vec4 v_position;

vec3 packFloatToVec3i(const float value)
{
   const vec3 bitSh = vec3( 256.0 * 256.0, 256.0, 1.0);
   const vec3 bitMsk = vec3( 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);
   vec3 res = fract(value * bitSh);
   res -= res.xxy * bitMsk;
   return res;
}



vec4 lightSource( vec3 N, vec3 V, gl_LightSourceParameters light )
{
	vec3  H;
	float d = length( light.position.xyz - V );
	vec3  L = normalize( light.position.xyz - V );

	if(eyeAtOrigin)
	H = normalize( L + vec3( 0.0, 0.0, 1.0 ) );
	else	
	H = normalize( L );

	float NdotL = max( 0.0, dot( N,L ) );
	float NdotH = max( 0.0, dot( N,H ) );

	float Idiff = NdotL;
	float Ispec = pow( NdotH, gl_FrontMaterial.shininess );


	// 'real' shading
	return 
		gl_FrontMaterial.ambient  * light.ambient +
		gl_FrontMaterial.diffuse  * light.diffuse  * Idiff +
		gl_FrontMaterial.specular * light.specular * Ispec;
}

vec4 getTexture(sampler2D tex)
{
		vec4 col;
		vec2 sc=vec2(scaleTex);
		vec2 tran=vec2(tex_tran_x,tex_tran_y) ;
		if(tecCoordGen==1)
		{
			
	   		col =  texture2D(tex,(vertex.xz+ tran)*sc)*(nor.y*nor.y);
	    	col += texture2D(tex,(vertex.xy+ tran)*sc)*(nor.z*nor.z);
	   	 	col += texture2D(tex,(vertex.yz+ tran)*sc)*(nor.x*nor.x);


		}
		else
			col = texture2D(tex,(gl_TexCoord[0].xy+ tran) * sc );

		return col;
}

vec3 getNormal()
{
	//vec3 np = ( getTexture(norMap).xyz-vec3(.5));
	//return normal; //+ vec4(gl_NormalMatrix*vec3(np),0);
	vec3 N = normalize( normal + getTexture(norMap).xyz-vec3(0.5) );
	return N;
}

float getTransp()
{
	vec3 t = getTexture(transpMap).xyz;
	float rez = (t.x+t.y+t.z)/3.0;
	return rez;
}
//
// computes light of all light sources and the scene.
//
vec4 lighting( void )
{

	//vec3 N = normalize( normal + getTexture(norMap).xyz-vec3(0.5) );
	vec3 N = getNormal();
	return
		gl_FrontMaterial.emission +
		gl_FrontMaterial.ambient * gl_LightModel.ambient +
		(lightSource( N, position, gl_LightSource[0] )+
		lightSource( N, position, gl_LightSource[1] ) )
			* getTexture(colMap);
}





void main( void )
{

		tc=gl_TexCoord[0].xy;
		if(getTransp()<minTransp)
			discard;
		else
		{
			if(drawOnlyNormal==true)
				gl_FragColor = vec4(getNormal(),1);
			if(drawOnlyDepth==true)
				gl_FragColor=vec4(packFloatToVec3i(length(v_position)/500.0),1);				
		
			if(drawOnlyNormal!=true && drawOnlyDepth!=true)
			gl_FragColor = lighting()*gl_Color;
		
		}

}
