//
//  Object3d.vsh
//  PlayMate
//
//  Created by David McKibbin on 7/5/12.
//  Copyright (c) 2012 Firaxis Games. All rights reserved.
//

#ifdef GL_ES
precision highp   int;		// built-in defaults
precision highp   float;
precision lowp    sampler2D;
precision lowp    samplerCube;
#endif

uniform mat4 RenderMatrix;
uniform mat3 NormalMatrix;

uniform vec3 LightVector;
uniform vec3 LightAmbient;
uniform vec3 LightDiffuse;

uniform float FogLevel;
uniform float FogDepth;

attribute vec4 a_Position;
attribute vec3 a_Normal;
attribute vec4 a_Color;	// team color
attribute vec2 a_TexUV0;
attribute vec2 a_TexUV1;

varying vec4  v_Color;
varying vec3  v_Light;
varying vec2  v_TexUV;
varying float v_FogDist;

float FogFactor()
{
	if (FogLevel <= 0.0)  return 0.0;	// no fog

	if (gl_Position.w <= 0.0)  return 0.0;	// behind camera

	float fogDist = gl_Position.z / gl_Position.w;

	if (fogDist <= 0.0)  return 0.0;	// behind 2*NearClip

	fogDist = pow( fogDist, FogLevel );	// make linear depth

	fogDist = (fogDist + FogDepth - 1.0) / FogDepth;

	fogDist = clamp( fogDist, 0.0, 1.0 );	// zero before FogDepth

	return fogDist;
}

void main()
{
    gl_Position = RenderMatrix * a_Position;

	v_FogDist = FogFactor();

	v_TexUV = a_TexUV1;
	v_TexUV = a_TexUV0;

	v_Color = a_Color;	// default & preserve alpha

	v_Color.rgb = v_Color.a * v_Color.rgb;	// pre-mul alpha

	v_Light = vec3(1,1,1);

	if (a_Normal.x==0.0 && a_Normal.y==0.0 && a_Normal.z==0.0)  return;

    vec3 eyeNormal = normalize( NormalMatrix * a_Normal );

    float nDotVP = max( 0.0, dot( eyeNormal, normalize(LightVector) ) );

	v_Light = LightAmbient + nDotVP * LightDiffuse;
}
