varying vec2 v_texture;
#ifndef DISABLE_SHADOW_MAPPING
varying vec4 v_shadowCoords;
#endif
varying vec2 v_texPitch;

#ifdef VERTEX_SHADER
uniform mat4 u_mvpMatrix;
#ifndef DISABLE_SHADOW_MAPPING
uniform mat4 u_lightMatrix;
#endif

attribute vec4 a_vertex;
attribute vec2 a_texture;
attribute vec2 a_texture1;

void main()
{
    v_texture = a_texture1;
	v_texPitch = a_texture;
#ifndef DISABLE_SHADOW_MAPPING
	v_shadowCoords = u_lightMatrix * a_vertex;
#endif
	gl_Position = u_mvpMatrix * a_vertex;
}
#endif // VERTEX_SHADER

/****************************************
 *  FRAGMENT SHADER
 ****************************************/
#ifdef FRAGMENT_SHADER

#ifndef DISABLE_SHADOW_MAPPING
  #ifdef GLES
    #ifdef GL_EXT_shadow_samplers
      #define SHADOWSAMPLER sampler2DShadow
      #define SHADOW2DPROJ(a,b) shadow2DProjEXT(a,b)
    #else
      #define SHADOWSAMPLER sampler2D
      #define SHADOW2DPROJ(a,b) clamp((b.w * texture2DProj(a, b).x - b.z) * 1000000.0 + 1.0, 0.0, 1.0)
    #endif
  #else
    #define SHADOWSAMPLER sampler2DShadow
    #define SHADOW2DPROJ(a,b) shadow2DProj(a,b).r
  #endif
  uniform lowp SHADOWSAMPLER u_tex5;
#endif

uniform sampler2D		u_tex0;
uniform sampler2D		u_tex1;
uniform sampler2D		u_tex2;
uniform sampler2D		u_tex3;
uniform sampler2D		u_tex4;

void main()
{
#ifndef DISABLE_SHADOW_MAPPING
	float fLightDepth = SHADOW2DPROJ( u_tex5, v_shadowCoords );
	fLightDepth += 1.0;
	fLightDepth *= 0.5;
#endif

	vec4 pitchMap = texture2D(u_tex4, v_texPitch);

	vec4 vDiffuse;
	vDiffuse = texture2D(u_tex0, v_texture)  * pitchMap.r;
	vDiffuse += texture2D(u_tex1, v_texture) * pitchMap.g;
	vDiffuse += texture2D(u_tex2, v_texture) * pitchMap.b;
	vDiffuse += texture2D(u_tex3, v_texture) * 0.5 * pitchMap.a;
	vDiffuse.a = 1.0;
	
#ifndef DISABLE_SHADOW_MAPPING
	vDiffuse.rgb *= fLightDepth;
#endif

	gl_FragColor = vDiffuse;
}
#endif // FRAGMENT_SHADER
