/*
====================================================================================================

    Copyright (C) 2020 RRe36

    All Rights Reserved unless otherwise explicitly stated.


    By downloading this you have agreed to the license and terms of use.
    These can be found inside the included license-file
    or here: https://rre36.com/copyright-license

    Violating these terms may be penalized with actions according to the Digital Millennium
    Copyright Act (DMCA), the Information Society Directive and/or similar laws
    depending on your country.

====================================================================================================
*/

vec3 getSky(vec3 viewDir) {
    vec3 v      = -viewDir;
    vec3 hvt    = normalize(-upvecView+v);
    vec3 hvb    = normalize(upvecView+v);
    vec3 sv     = normalize(sunvecView+v);
    vec3 mv     = normalize(moonvecView+v);

    float horTop    = dot(hvt, v);
    float horBottom = dot(hvb, v);
    float sun   = 1.0-dot(sv, v);
    float hor   = linStep(1.0-max(horTop, horBottom), 0.0, 0.2958);

    float horizon   = pow6(hor);
    float zenith    = 1.0-linStep(1.0-horTop, 0.0, 0.2958);
        zenith      = exp(-zenith*1.5) * 0.8 + 0.2;

    float vDotS     = dot(viewDir, sunvecView);

    float sunscatter = mieHG(vDotS, 0.78)*rcp(pi)*(1.0-daytime.w);

    float sunHint   = saturate(mieHG(vDotS, 0.2)*rcp(0.2)*1.35);
        horizon     = mix(horizon, horizon*sunHint, sqr(daytime.x + daytime.z)*0.8);

    float ld        = linStep(1.0 - horTop, 0.25, 0.2958);
        ld          = cube(ld) * 0.96 * sunHint;

    vec3 sunColor   = lightColor[0] * 0.2;

    vec3 ldcol      = mix(skyColorMat[1], sunColor * skyColorMat[1] * 0.9 + sunColor * sunscatter, sstep(sunvec.y, -0.1, 0.01));
        ldcol       = mix(ldcol * 0.5, skyColorMat[0] * 0.5, sqrt(linStep(horBottom, 0.76, 1.0)) * 0.8);

    //float rayleighPhase = rayleighPhase(vDotS) * pi4;

    vec3 sky    = skyColorMat[0] * zenith;
        sky     = mix(sky, ldcol, ld);
        sky     = mix(sky, skyColorMat[1] * 1.2, horizon);
        sky    += sunColor * sunscatter * 1.35;
        //sky     = hor > 0.99 ? vec3(horizon) : vec3( 0.0);

    return sky;
}