0.00
60.0 fps

Cloudy day

A sky full of clouds with a full 30 s daylight cycle.

Log in to post a comment.

precision highp float;
precision highp int;

const int VIEW_STEPS = 50;
const int LIGHT_STEPS = 5;
const float CLOUD_COVERAGE = 0.60; // 0.35 scattered, 0.70 mostly cloudy
const float CLOUD_DENSITY = 1.22;
const float DAY_LENGTH = 30.0;    // Seconds per full day/night cycle
const float SUN_BLOOM = 1.0;     // 0.0 disables bloom
const float TAU = 6.28318530718;
const vec2 WIND = vec2(0.105, 0.035); // XZ world units per second

const float CLOUD_BASE = 1.48;
const float CLOUD_TOP = 4.06;
const float FAR_DISTANCE = 66.0;

float saturate(float x)
{
    return clamp(x, 0.0, 1.0);
}

// Four lattice corners at a time. Unsigned arithmetic keeps the hash
// coherent across negative coordinates as the cloud field moves.
vec4 hash4(uvec4 n)
{
    n = (n ^ (n >> 16u)) * 0x7feb352du;
    n = (n ^ (n >> 15u)) * 0x846ca68bu;
    n = n ^ (n >> 16u);
    return vec4(n >> 8u) * (1.0 / 16777216.0);
}

float noise3(vec3 p)
{
    ivec3 cell = ivec3(floor(p));
    vec3 f = fract(p);
    f = f * f * (3.0 - 2.0 * f);

    uint seed = uint(cell.x) * 1597334677u
              + uint(cell.y) * 3812015801u
              + uint(cell.z) * 2798796415u;
    uvec4 xy = uvec4(0u, 1597334677u, 3812015801u,
                     1597334677u + 3812015801u);
    vec4 taps = mix(hash4(seed + xy), hash4(seed + xy + 2798796415u), f.z);
    return mix(mix(taps.x, taps.y, f.x), mix(taps.z, taps.w, f.x), f.y);
}

float cloudDensity(vec3 p, bool detail)
{
    float h = (p.y - CLOUD_BASE) / (CLOUD_TOP - CLOUD_BASE);
    if (h <= 0.0 || h >= 1.0) return 0.0;

    // The weather field controls both the location and height of cloud banks.
    vec3 weatherPos = vec3(p.x * 0.245, 14.37, p.z * 0.245);
    float weather = 0.72 * noise3(weatherPos)
                  + 0.28 * noise3(weatherPos * 2.09 + 19.1);
    float top = mix(0.44, 1.0, smoothstep(0.26, 0.79, weather));
    float profile = smoothstep(0.0, 0.14, h)
                  * (1.0 - smoothstep(top - 0.27, top, h));
    if (profile <= 0.0) return 0.0;

    // Broad, rounded lobes carry finer erosion only where there is cloud.
    vec3 q = p * vec3(0.83, 1.02, 0.83) + vec3(7.7, 34.1, 13.6);
    q.xz += vec2(0.26, 0.09) * h;
    float billows = 0.67 * noise3(q)
                  + 0.24 * noise3(q * 2.06 + 8.3)
                  + 0.09 * noise3(q * 4.17 - 11.9);
    float threshold = 0.54 + (0.54 - CLOUD_COVERAGE) * 0.74
                    - (weather - 0.5) * 0.71;
    float shape = billows - threshold - (1.0 - profile) * 0.26;
    if (shape <= 0.0) return 0.0;

    if (detail)
    {
        float erosion = 0.64 * noise3(q * 8.21 + 12.4)
                      + 0.36 * noise3(q * 16.43 - 24.8);
        shape -= 0.145 * erosion * (1.0 - smoothstep(0.12, 0.33, shape));
    }

    return CLOUD_DENSITY * profile * smoothstep(0.0, 0.37, shape);
}

// Atmosphere distances are in km. The cloud layer uses the same units.
const float EARTH_RADIUS = 6371.0;
const float ATMOSPHERE_RADIUS = 6451.0;
const vec3 PLANET_ORIGIN = vec3(0.0, EARTH_RADIUS, 0.0);
const vec3 RAYLEIGH_BETA = vec3(0.005802, 0.013558, 0.033100);
const float MIE_BETA = 0.0062;
const float MIE_EXTINCTION = 0.0069;
const vec3 OZONE_BETA = vec3(0.000650, 0.001881, 0.000085);
const vec3 SOLAR_RADIANCE = vec3(15.8, 15.2, 14.3);
const float CLOUD_EXTINCTION = 2.65;
const float SHAFT_STRENGTH = 0.92;
const int NEAR_AIR_STEPS = 12;
const int FAR_AIR_STEPS = 15;
const int SOLAR_AIR_STEPS = 9;

struct Light
{
    vec3 sun;
    vec3 cloudBaseSun;
    vec3 cloudTopSun;
    vec3 ambient;
    vec3 windOffset;
};

struct Volume
{
    vec3 radiance;
    vec3 transmittance;
    float cloudVisibility;
};

float phaseHG(float mu, float g)
{
    return (1.0 - g * g) * pow(max(1.0 + g * g - 2.0 * g * mu, 0.001), -1.5);
}

float atmosphereExit(vec3 p, vec3 ray)
{
    float b = dot(p, ray);
    float c = dot(p, p) - ATMOSPHERE_RADIUS * ATMOSPHERE_RADIUS;
    return -b + sqrt(max(b * b - c, 0.0));
}

float groundHit(vec3 p, vec3 ray)
{
    float b = dot(p, ray);
    float c = max(dot(p, p) - EARTH_RADIUS * EARTH_RADIUS, 0.0);
    float discriminant = b * b - c;
    if (b >= 0.0 || discriminant <= 0.0) return -1.0;

    // Stable form of the near intersection for cameras close to the surface.
    return c / (-b + sqrt(discriminant));
}

vec3 airDensity(vec3 p)
{
    float altitude = max(length(p) - EARTH_RADIUS, 0.0);
    return vec3(exp(-altitude / 8.0), exp(-altitude / 1.2),
                max(1.0 - abs(altitude - 25.0) / 15.0, 0.0));
}

vec3 airExtinction(vec3 density)
{
    return RAYLEIGH_BETA * density.x + MIE_EXTINCTION * density.y
         + OZONE_BETA * density.z;
}

vec3 sunlightThroughAir(vec3 radialPoint, vec3 sun)
{
    if (groundHit(radialPoint, sun) >= 0.0) return vec3(0.0);

    float distanceToSpace = atmosphereExit(radialPoint, sun);
    vec3 column = vec3(0.0);
    float previous = 0.0;
    for (int i = 1; i <= SOLAR_AIR_STEPS; ++i)
    {
        float u = float(i) / float(SOLAR_AIR_STEPS);
        float next = distanceToSpace * u * u;
        float mid = 0.5 * (previous + next);
        column += airDensity(radialPoint + sun * mid) * (next - previous);
        previous = next;
    }
    return exp(-airExtinction(column));
}

Light daylightAt(float time)
{
    // Start in early morning with the sun in the default camera view.
    float angle = TAU * fract(time / DAY_LENGTH + 0.092);
    vec3 sun = normalize(vec3(-0.85 * cos(angle), 0.98 * sin(angle), 1.0));
    vec3 lowerSun = sunlightThroughAir(PLANET_ORIGIN + vec3(0.0, CLOUD_BASE, 0.0), sun);
    vec3 upperSun = sunlightThroughAir(PLANET_ORIGIN + vec3(0.0, CLOUD_TOP, 0.0), sun);
    float day = smoothstep(-0.10, 0.30, sun.y);
    float twilight = smoothstep(-0.22, -0.025, sun.y)
                   * (1.0 - smoothstep(0.04, 0.34, sun.y));
    // Diffuse sky fill approximates light from the rest of the hemisphere.
    vec3 ambient = mix(vec3(0.010, 0.019, 0.043), vec3(0.23, 0.36, 0.62), day)
                 + twilight * vec3(0.085, 0.036, 0.028);
    vec3 wind = vec3(WIND.x, 0.0, WIND.y) * time;
    return Light(sun, lowerSun, upperSun, ambient, wind);
}

float cloudSunDepth(vec3 worldPos, Light light)
{
    if (light.sun.y <= 0.0 || worldPos.y >= CLOUD_TOP) return 0.0;
    float entry = max(0.0, (CLOUD_BASE - worldPos.y) / light.sun.y);
    float exitDistance = min((CLOUD_TOP - worldPos.y) / light.sun.y, entry + 19.0);
    vec3 start = worldPos + light.sun * entry - light.windOffset;
    float opticalDepth = 0.0;
    float previous = entry;
    for (int i = 1; i <= LIGHT_STEPS; ++i)
    {
        float u = float(i) / float(LIGHT_STEPS);
        float next = mix(entry, exitDistance, u * u);
        float mid = 0.5 * (previous + next) - entry;
        float density = cloudDensity(start + light.sun * mid, false);
        opticalDepth += CLOUD_EXTINCTION * density * (next - previous);
        previous = next;
        if (opticalDepth > 9.0) break;
    }
    return opticalDepth;
}

void integrateVolume(inout Volume volume, vec3 extinction, vec3 source, float stepLength)
{
    // The analytic solution for a segment with constant coefficients.
    vec3 opticalDepth = extinction * stepLength;
    vec3 stepT = exp(-opticalDepth);
    vec3 integral = mix(vec3(stepLength), (1.0 - stepT) / max(extinction, vec3(1e-8)),
                        step(vec3(0.0002), opticalDepth));
    volume.radiance += volume.transmittance * source * integral;
    volume.transmittance *= stepT;
}

void marchAir(inout Volume volume, vec3 eye, vec3 ray, Light light,
              vec3 rayleighPhase, float miePhase, vec2 range, bool cloudShadows)
{
    if (range.y <= range.x || volume.transmittance.r < 0.002) return;
    int sampleCount = cloudShadows ? NEAR_AIR_STEPS : FAR_AIR_STEPS;
    float previous = range.x;
    for (int i = 1; i <= FAR_AIR_STEPS; ++i)
    {
        if (i > sampleCount) break;
        float u = float(i) / float(sampleCount);
        float next = mix(range.x, range.y, u * (0.20 + 0.80 * u));
        float mid = 0.5 * (previous + next);
        vec3 p = eye + ray * mid;
        vec3 radialPoint = p + PLANET_ORIGIN;
        vec3 density = airDensity(radialPoint);
        vec3 irradiance = SOLAR_RADIANCE * sunlightThroughAir(radialPoint, light.sun);
        if (cloudShadows && mid < 48.0 && p.y < CLOUD_TOP && light.sun.y > 0.035)
        {
            // A cloud's shadow reduces the sunlight scattered by air below it.
            float shadow = exp(-cloudSunDepth(p, light));
            float weight = SHAFT_STRENGTH * smoothstep(0.035, 0.12, light.sun.y)
                         * (1.0 - smoothstep(28.0, 48.0, mid));
            irradiance *= mix(1.0, shadow, weight);
        }
        vec3 source = irradiance * (rayleighPhase * density.x + miePhase * density.y);
        integrateVolume(volume, airExtinction(density), source, next - previous);
        previous = next;
    }
}

void marchClouds(inout Volume volume, vec3 eye, vec3 ray, Light light,
                 vec3 rayleighPhase, float miePhase, vec2 range, float jitter)
{
    float mu = dot(ray, light.sun);
    float cloudPhase = 0.51 * phaseHG(mu, 0.62) + 0.17 * phaseHG(mu, -0.24);
    float shadowWeight = smoothstep(0.0, 0.06, light.sun.y);
    float previous = range.x;

    for (int i = 1; i <= VIEW_STEPS; ++i)
    {
        float u = float(i) / float(VIEW_STEPS);
        float next = mix(range.x, range.y, u * (0.62 + 0.38 * u));
        float stepLength = next - previous;
        float mid = mix(previous, next, jitter);
        previous = next;

        vec3 p = eye + ray * mid;
        float cloud = cloudDensity(p - light.windOffset, true)
                    * (1.0 - smoothstep(43.0, FAR_DISTANCE, mid));
        float cloudSigma = CLOUD_EXTINCTION * cloud;
        float height = saturate((p.y - CLOUD_BASE) / (CLOUD_TOP - CLOUD_BASE));
        vec3 sunThroughAir = mix(light.cloudBaseSun, light.cloudTopSun, height);
        vec3 air = airDensity(p + PLANET_ORIGIN);

        float cloudDepth = 0.0;
        if (cloud > 0.0001 && shadowWeight > 0.0)
            cloudDepth = cloudSunDepth(p, light) * shadowWeight;
        float direct = exp(-cloudDepth);
        // Broader, less attenuated lobes approximate multiple scattering.
        float bounce = 0.31 * exp(-0.21 * cloudDepth) + 0.085 * exp(-0.064 * cloudDepth);
        vec3 cloudLight = light.ambient * mix(0.68, 1.52, height)
                        + 2.65 * sunThroughAir * (cloudPhase * direct + bounce);
        vec3 source = cloudSigma * cloudLight;
        source += SOLAR_RADIANCE * sunThroughAir * direct
                * (rayleighPhase * air.x + miePhase * air.y);

        integrateVolume(volume, airExtinction(air) + cloudSigma, source, stepLength);
        volume.cloudVisibility *= exp(-cloudSigma * stepLength);
        if (volume.transmittance.r < 0.002) break;
    }
}

vec3 displayColor(vec3 linearColor)
{
    vec3 color = max(vec3(0.0), linearColor * 0.96);
    color = color * (1.0 + 0.15 * color) / (1.0 + color);
    return pow(clamp(color, 0.0, 1.0), vec3(1.0 / 2.2));
}

void mainImage(out vec4 fragColor, in vec2 fragCoord)
{
    vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    vec2 look = vec2(0.0, 0.43);
    // zw retains the initial click, so the view stays put on release.
    if (any(notEqual(iMouse.zw, vec2(0.0))))
    {
        vec2 mouse = clamp(iMouse.xy / iResolution.xy, 0.0, 1.0);
        look = vec2((mouse.x - 0.5) * 6.2831853, mix(-0.16, 1.43, mouse.y));
    }

    vec3 forward = vec3(sin(look.x) * cos(look.y), sin(look.y),
                        cos(look.x) * cos(look.y));
    vec3 right = normalize(cross(vec3(0.0, 1.0, 0.0), forward));
    vec3 up = cross(forward, right);
    vec3 ray = normalize(1.92 * forward + uv.x * right + uv.y * up);

    vec3 eye = vec3(0.0, 0.32, 0.0);
    vec3 radialEye = eye + PLANET_ORIGIN;
    Light light = daylightAt(iTime);
    float mu = clamp(dot(ray, light.sun), -1.0, 1.0);
    vec3 rayleighPhase = RAYLEIGH_BETA * (0.0596831 * (1.0 + mu * mu));
    float miePhase = MIE_BETA * (0.07957747 * phaseHG(mu, 0.76));

    float groundDistance = groundHit(radialEye, ray);
    float finish = atmosphereExit(radialEye, ray);
    if (groundDistance >= 0.0) finish = min(finish, groundDistance);

    float cloudEntry = (CLOUD_BASE - eye.y) / max(ray.y, 0.00001);
    float cloudExit = min((CLOUD_TOP - eye.y) / max(ray.y, 0.00001),
                          min(finish, FAR_DISTANCE));
    bool crossesClouds = cloudEntry < cloudExit;
    float nearEnd = crossesClouds ? cloudEntry : min(finish, 25.0);
    Volume volume = Volume(vec3(0.0), vec3(1.0), 1.0);
    marchAir(volume, eye, ray, light, rayleighPhase, miePhase,
             vec2(0.0, nearEnd), true);
    if (crossesClouds)
    {
        vec2 pixel = floor(fragCoord);
        float jitter = 0.13 + 0.74 * fract(52.9829189
                     * fract(dot(pixel, vec2(0.06711056, 0.00583715))));
        marchClouds(volume, eye, ray, light, rayleighPhase, miePhase,
                    vec2(cloudEntry, cloudExit), jitter);
        nearEnd = cloudExit;
    }
    marchAir(volume, eye, ray, light, rayleighPhase, miePhase,
             vec2(nearEnd, finish), false);

    // The disk is attenuated by the same view-ray extinction as the sky.
    vec3 sunDelta = ray - light.sun;
    float sunDistance = dot(sunDelta, sunDelta);
    float sunRadius2 = 0.000159;
    float aa = max(fwidth(sunDistance) * 0.65, 0.000001);
    float disk = 1.0 - smoothstep(sunRadius2 - aa, sunRadius2 + aa, sunDistance);
    float night = 1.0 - smoothstep(-0.21, -0.075, light.sun.y);
    vec3 background = vec3(0.003, 0.008, 0.023) * night;
    if (groundDistance >= 0.0)
        background = vec3(0.12, 0.16, 0.18) * max(light.sun.y, 0.0)
                   + vec3(0.003, 0.006, 0.012);
    else
        background += 2.1 * SOLAR_RADIANCE * disk;

    float glow = 1.55 * exp(-sunDistance / 0.00085)
               + 0.31 * exp(-sunDistance / 0.010);
    vec3 bloom = SUN_BLOOM * glow * sqrt(volume.cloudVisibility)
               * sunlightThroughAir(radialEye, light.sun);
    vec3 color = volume.radiance + volume.transmittance * background + bloom;
    fragColor = vec4(displayColor(color), 1.0);
}