/*
--------------------------------------------------------------------------------
This source file is part of SkyX.
Visit http://www.paradise-studios.net/products/skyx/

Copyright (C) 2009-2012 Xavier Verguín González <xavyiy@gmail.com>

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
--------------------------------------------------------------------------------
*/

// --------------------- SkyX moon material ------------------------
// ----------------------- GLSL Fragment ---------------------------

// IN
varying vec4 vUVYLength;
// UNIFORM
uniform vec3      uMoonPhase;
uniform vec3      uMoonHalo1;
uniform vec3      uMoonHalo2;
uniform float     uMoonHaloFlip;
uniform sampler2D uMoon;
uniform sampler2D uMoonHalo;

void main(void)
{
	// Output color
    gl_FragColor = texture2D(uMoon, vUVYLength.xy);
	
	// Moon phase + halo
	float radius = abs(uMoonPhase.x);
	vec2 center = vec2(uMoonPhase.y, 0.5);
	float dist = length(vUVYLength.xy - center);
	float att = clamp((radius-dist+0.015)*40.0, 0.0, 1.0);
	
	float UVYLength_x = vUVYLength.x; // GLSL warns about varying assignments
	if (uMoonHaloFlip > 0.5)
	{
		UVYLength_x = 1.0-vUVYLength.x;
	}
	
	vec2 haloUV = vec2(UVYLength_x/4.0, vUVYLength.y/2.0);
	vec2 halo1UV = vec2(uMoonHalo1.x + haloUV.x, uMoonHalo1.y + haloUV.y);
	vec2 halo2UV = vec2(uMoonHalo2.x + haloUV.x, uMoonHalo2.y + haloUV.y);
	
	float haloIntensity = texture2D(uMoonHalo, halo1UV).w*uMoonHalo1.z + texture2D(uMoonHalo, halo2UV).w*uMoonHalo2.z;
	
	haloIntensity = pow(haloIntensity, uMoonPhase.z);
	
	if (uMoonPhase.x > 0.0)
	{
		gl_FragColor.rgb *= 0.16 + (1.0-0.16)*(1.0-att);
		gl_FragColor.rgb += clamp(haloIntensity-gl_FragColor.r, 0.0, 1.0)*(1.0-(1.0-att)*gl_FragColor.a);
	}
	else
	{
		gl_FragColor.rgb *= 0.16 + (1.0-0.16)*att;
		gl_FragColor.rgb += clamp(haloIntensity-gl_FragColor.r, 0.0, 1.0)*(1.0-att*gl_FragColor.a);
	}	

	gl_FragColor.rgb += (1.0-gl_FragColor.a)*1.4*(1.0-pow(gl_FragColor.a,2.0*haloIntensity)); // Anti-alias at moon edges hack
	gl_FragColor.rgb = clamp(gl_FragColor.rgb, 0.0, 1.0);
	
	gl_FragColor.a = max(gl_FragColor.a, haloIntensity);
	
	// Transparency at horizon
    gl_FragColor.w *= clamp((vUVYLength.z/vUVYLength.w)*10.0, 0.0, 1.0);
}