uniform mat4 invBasis;
uniform mat4 modelViewProj;
uniform mat4 equatorialToHorizon;
uniform vec4 fog;
uniform vec4 fogDistance;
uniform vec4 up;

void main()
{
    vec4 horizonCoords = (equatorialToHorizon * gl_Vertex);
    gl_Position = (modelViewProj * horizonCoords);

    gl_TexCoord[0] = gl_MultiTexCoord0;

    float magnitude = gl_MultiTexCoord0.x;

    // At scotopic levels when stars are visible, the varying effect of scattering by
    // wavelength usually isn't visible. So it's not modeled to gain back a little performance.

    // Convert magnitude to luminance
    float luminance = pow(100.0, (-magnitude / 5.0));

    float r2 = luminance / (pow(luminance, 2.0/3.0) + 0.02); // The .02 term controls the overall star brightness.
    vec4 luminanceRGB = vec4(r2, r2, r2, 1);

    vec4 starColor = gl_Color * luminanceRGB;

	// Add fog
    vec4 fogColor;
    fogColor.xyz = fog.xyz;
    fogColor.w = 1.0;
    float fogDensity = fog.w;
    float volumeDistance = fogDistance.x;

	vec3 starPos = gl_Position.xyz;
	float cosTheta = max(1.0E-10, dot(normalize(starPos), up.xyz));
    float fFogDistance = volumeDistance / cosTheta;
    float f = exp(-(fogDensity * fFogDistance));

    vec4 finalColor = mix(fogColor, starColor, clamp(f, 0.0, 1.0));

    gl_TexCoord[0].z = 0.0;
    gl_FrontColor = finalColor;
}
