
// pass this color from your material color as a uniform later on...
uniform vec4 matColor;

varying vec3 vVertex;
varying vec3 vNormal;

uniform samplerCube envCubeMap;
uniform sampler2D diffMap;

uniform float textureScale;
uniform float fMixEnvDiff;

vec3 ReflectVector(vec3 vNormal, vec3 vViewVec)
{
	return vViewVec - 2.0 * vNormal*dot(vNormal, vViewVec);
}

vec2 tGetAutomaticTexCoords(vec3 pos, vec3 normal)
{
      float dotX = dot(normal,vec3(1.0,0.0,0.0));
      float dotY = dot(normal,vec3(0.0,1.0,0.0));
      float dotZ = dot(normal,vec3(0.0,0.0,1.0));
      float adotX = abs(dotX);
      float adotY = abs(dotY);
      float adotZ = abs(dotZ);
      
      vec3 npos = pos - vec3(0,0,0);
      vec2 texCoordOut = npos.xy;
      if(dotZ > 0.0)
      {
            texCoordOut = npos.xy;
      }
      else
      {
            texCoordOut = vec2(npos.x,-npos.y);
      }
      if(adotX > adotY)
      {
            if(adotX > adotZ)
            {
                  if(dotX > 0.0)
                  {
                        texCoordOut = npos.yz;
                  }
                  else
                  {
                        texCoordOut = vec2(-npos.y,npos.z);
                  }
            }
      }
      else if(adotY > adotZ)
      {
            if(dotY > 0.0)
            {
                  texCoordOut = vec2(-npos.x, npos.z);
            }
            else
            {
                  texCoordOut = vec2(npos.x,npos.z);
            }
      }
      return texCoordOut;
}

void main()
{
	vec2 localTexCoord = tGetAutomaticTexCoords(vVertex.xyz, vNormal.xyz);

	vec3 lightDir = vec3(0.934935,0.340287,0.0);	// "light" fixed from the right, 20 degrees slightly up
	vec3 normal = normalize(gl_NormalMatrix * vNormal);

	vec3 viewDir = vec3(0.0,0.0,1.0); // will not work well in perspective, should be EyePos-gl_Vertex in worldspace
	vec3 reflVec = ReflectVector(normal, viewDir);
	vec4 reflColor = textureCube(envCubeMap, reflVec);
	vec4 diffColor = texture2D(diffMap, localTexCoord.xy * textureScale);

	// extend from -1.1 to 0,1 to have full range even in non lit area
	float cpdot = dot(normal,lightDir)*0.5 + 0.5;
	
	vec4 finalColor = vec4(0);

	vec4 materialColor = mix(matColor, diffColor, fMixEnvDiff);

	finalColor.rgb = reflColor.rgb*materialColor.rgb;	// just modulating with reflection here, we should mix with a factor

	gl_FragColor = vec4(finalColor.rgb, 1.0);
}