#!/usr/bin/env python3
"""30 Free choice: storm tower at sunset.

A thunderstorm cloud (cumulonimbus) stands over a calm sea in the last light of the day.
Fable 5.2 Python art experiment: every pixel comes from the code below.
The cloud is a true 3D volume. Its shape is a set of soft blobs (a tower with an
anvil top) that is broken up with 3D noise. For every pixel a ray walks through
the volume in small steps; at every step a second, short walk toward the sun
measures how much cloud is in the way. That gives the glowing sunlit edges and
the blue shadowed side. The sea is a mirror of the finished sky with ripples.
Run: .venv/bin/python scripts/30-free-choice-storm-tower.py
"""
import os, time, math
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage as ndi

W, H = 1600, 2000
HOR = 1380                      # horizon row
PXS = 0.00034                   # tangent per pixel (a shift lens: the horizon sits low, verticals stay vertical)
RS = 1                          # 1 = the volume is rendered at full size (2 = half size, four times faster)
SEED = 30
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '30-free-choice-storm-tower.png')
F = np.float32
rng = np.random.default_rng(SEED)


def smooth(a, b, x):
    t = np.clip((x - a) / (b - a + 1e-9), 0, 1)
    return t * t * (3 - 2 * t)


def vnoise(shape, cell, r):
    h, w = shape
    cy, cx = cell if isinstance(cell, tuple) else (cell, cell)
    g = r.random((int(h / cy) + 4, int(w / cx) + 4)).astype(F)
    z = ndi.zoom(g, (cy, cx), order=3 if min(cy, cx) >= 3 else 1)
    oy, ox = int(cy * 1.5), int(cx * 1.5)
    return z[oy:oy + h, ox:ox + w]


def fbm(shape, cell, octaves, r):
    cy, cx = cell if isinstance(cell, tuple) else (cell, cell)
    out = np.zeros(shape, F)
    amp, tot = 1.0, 0.0
    for _ in range(octaves):
        out += amp * vnoise(shape, (max(1.0, cy), max(1.0, cx)), r)
        tot += amp
        amp *= 0.5
        cy /= 2; cx /= 2
    return out / tot


def ramp(t, stops):
    pos = [p for p, _ in stops]
    cols = np.array([c for _, c in stops], F)
    return np.stack([np.interp(t, pos, cols[:, i]) for i in range(3)], -1).astype(F)


# ----------------------------------------------------------------------------
# 3D noise and the cloud volume
# ----------------------------------------------------------------------------
NL = 64
LAT = np.random.default_rng(1).random(NL * NL * NL).astype(F)


def noise3(p):
    """Smooth 3D noise in 0..1 (random lattice with smooth interpolation)."""
    pf = np.floor(p)
    f = p - pf
    f = f * f * (3 - 2 * f)
    i = pf.astype(np.int32) & (NL - 1)
    j = (i + 1) & (NL - 1)
    x0, y0, z0 = i[:, 0] * NL * NL, i[:, 1] * NL, i[:, 2]
    x1, y1, z1 = j[:, 0] * NL * NL, j[:, 1] * NL, j[:, 2]
    fx, fy, fz = f[:, 0], f[:, 1], f[:, 2]
    a = LAT[x0 + y0 + z0] * (1 - fz) + LAT[x0 + y0 + z1] * fz
    b = LAT[x0 + y1 + z0] * (1 - fz) + LAT[x0 + y1 + z1] * fz
    c = LAT[x1 + y0 + z0] * (1 - fz) + LAT[x1 + y0 + z1] * fz
    d = LAT[x1 + y1 + z0] * (1 - fz) + LAT[x1 + y1 + z1] * fz
    return (a * (1 - fy) + b * fy) * (1 - fx) + (c * (1 - fy) + d * fy) * fx


def fbm3(p, octaves):
    out = np.zeros(len(p), F)
    amp, tot = 1.0, 0.0
    for k in range(octaves):
        out += amp * noise3(p * F(2.0 ** k) + F(17.3 * k))
        tot += amp
        amp *= 0.5
    return out / tot


# soft blobs: centre x, y, z and radii x, y, z (kilometres)
BLOBS = np.array([
    (4.0, 2.6, 40.0, 5.0, 2.2, 5.0), (3.6, 4.6, 40.0, 4.2, 2.8, 4.2), (4.6, 6.8, 40.6, 3.8, 2.8, 3.8),
    (4.0, 8.9, 40.0, 3.5, 2.7, 3.5), (4.6, 10.8, 40.0, 4.4, 2.1, 4.4),
    (6.0, 12.3, 41.0, 10.5, 1.25, 8.0), (10.0, 12.6, 42.0, 8.5, 1.0, 6.5), (0.5, 12.0, 41.0, 5.0, 0.9, 5.0),
    (0.2, 3.3, 38.2, 2.8, 2.2, 2.8), (-2.2, 2.5, 39.0, 2.4, 1.6, 2.4), (8.0, 4.1, 38.5, 2.8, 2.4, 2.8),
    (0.9, 6.3, 38.8, 2.4, 2.2, 2.4), (7.4, 7.6, 39.4, 2.4, 2.1, 2.4), (-4.4, 2.0, 41.0, 2.7, 1.2, 2.7),
    (10.6, 2.7, 41.0, 3.2, 1.7, 3.2), (1.6, 9.2, 39.0, 2.0, 1.8, 2.0), (6.6, 10.0, 39.2, 2.0, 1.7, 2.0),
    (-7.5, 1.9, 44.0, 3.0, 0.9, 3.0), (13.5, 2.2, 43.0, 3.2, 1.1, 3.2),
], F)


def macro(p):
    """How deep a point lies inside the union of blobs (above 0 = inside)."""
    acc = np.zeros(len(p), F)
    for b in BLOBS:
        q = np.sqrt(((p[:, 0] - b[0]) / b[3]) ** 2 + ((p[:, 1] - b[1]) / b[4]) ** 2 + ((p[:, 2] - b[2]) / b[5]) ** 2)
        acc += np.exp(np.minimum((1 - q) * 7.0, 30))
    return np.log(acc + 1e-12) / 7.0


def density(p, fine=True):
    m = macro(p)
    rho = np.zeros(len(p), F)
    near = m > -0.42
    if near.any():
        pn = p[near]
        n1 = fbm3(pn * F(0.42), 3 if fine else 2)
        shape = m[near] + 0.62 * (n1 - 0.56)
        if fine:
            n2 = fbm3(pn * F(2.1) + F(5.0), 4)
            shape = shape + 0.24 * (n2 - 0.5)
        # flat base, slightly ragged
        base = smooth(1.30, 1.85, pn[:, 1] + 0.5 * (n1 - 0.5))
        rho[near] = np.clip(shape * 6.5, 0, 1) * base
    return rho


SUN = np.array([-0.93, 0.115, 0.20], F)
SUN /= np.linalg.norm(SUN)
LSTEPS = np.array([0.10, 0.22, 0.42, 0.75, 1.25, 2.0, 3.2], F)
LDS = np.diff(np.r_[0, LSTEPS]).astype(F)
SIGMA = 5.0
FLASH = np.array([7.6, 3.6, 41.5], F)          # a flicker of lightning inside the cloud


def render_cloud():
    w, h = W // RS, HOR // RS
    yy, xx = np.mgrid[0:h, 0:w].astype(F)
    dx = ((xx + 0.5) * RS - W / 2) * PXS
    dy = (HOR - (yy + 0.5) * RS) * PXS
    rd = np.stack([dx.ravel(), dy.ravel(), np.ones(w * h, F)], 1)
    rd /= np.linalg.norm(rd, axis=1, keepdims=True)
    N = len(rd)
    Cout = np.zeros((N, 3), F)
    Tout = np.ones(N, F)
    jrng = np.random.default_rng(2)
    nsteps = 150
    chunk = 120000
    for c0 in range(0, N, chunk):
        d = rd[c0:c0 + chunk]
        n = len(d)
        t0 = 31.5 / d[:, 2]
        t1 = np.minimum(52.0 / d[:, 2], 14.6 / np.maximum(d[:, 1], 1e-4))
        dt = np.maximum(t1 - t0, 0) / nsteps
        T = np.ones(n, F)
        C = np.zeros((n, 3), F)
        act = np.nonzero(dt > 1e-4)[0]
        jit = jrng.random(n).astype(F)
        for s in range(nsteps):
            if len(act) == 0:
                break
            t = t0[act] + (s + jit[act]) * dt[act]
            p = d[act] * t[:, None]
            rho = density(p)
            hit = rho > 0.004
            if hit.any():
                ph = p[hit]; rh = rho[hit]; ai = act[hit]
                tau = np.zeros(len(ph), F)
                for ls, lds in zip(LSTEPS, LDS):
                    tau += density(ph + SUN[None, :] * ls, fine=False) * lds
                ts = 0.80 * np.exp(-SIGMA * 0.75 * tau) + 0.20 * np.exp(-SIGMA * 0.20 * tau)
                cosang = d[ai] @ SUN
                phase = 0.55 * (1 - 0.55 ** 2) / (1 + 0.55 ** 2 - 2 * 0.55 * cosang) ** 1.5 + 0.45 * 1.0
                hk = smooth(1.5, 12.5, ph[:, 1])[:, None]
                sunc = np.array([1.00, 0.30, 0.10], F)[None, :] * (1 - hk) + np.array([1.00, 0.57, 0.25], F)[None, :] * hk
                amb_up = np.array([0.13, 0.19, 0.40], F) * 0.40
                amb_w = np.array([0.50, 0.22, 0.22], F) * 0.10
                occ = np.exp(-2.2 * np.clip(rh, 0, 1)) * (0.45 + 0.55 * smooth(1.5, 13, ph[:, 1]))
                S = sunc * (ts * phase * 3.6)[:, None] + (amb_up[None, :] * (0.55 + 0.9 * occ[:, None]) + amb_w[None, :])
                dl = np.linalg.norm(ph - FLASH[None, :], axis=1)
                S += (1.3 / (dl * dl + 0.5) * np.exp(-dl * 0.55))[:, None] * np.array([0.62, 0.62, 1.0], F)
                a = 1 - np.exp(-SIGMA * rh * dt[ai])
                C[ai] += (T[ai] * a)[:, None] * S
                T[ai] *= 1 - a
            if s % 8 == 7:
                act = act[T[act] > 0.012]
        Cout[c0:c0 + n] = C
        Tout[c0:c0 + n] = T
        print('  volume rows %d / %d  %.1fs' % (min(N, c0 + chunk) // w, h, time.time() - T0))
    C = Cout.reshape(h, w, 3); T = Tout.reshape(h, w)
    if RS == 1:
        return C, T
    Cb = np.stack([ndi.zoom(C[..., i], RS, order=3) for i in range(3)], -1)
    Tb = np.clip(ndi.zoom(T, RS, order=3), 0, 1)
    # restore a little crispness after enlarging
    Cb = np.clip(Cb + 0.6 * (Cb - ndi.gaussian_filter(Cb, (1.6, 1.6, 0))), 0, None)
    return Cb.astype(F), Tb.astype(F)


def main():
    yy, xx = np.mgrid[0:H, 0:W].astype(F)
    # ------------------------------------------------------------ sky (above the horizon)
    el = np.clip((HOR - yy) / HOR, 0, 1)
    sky = ramp(el, [(0.0, (0.80, 0.34, 0.16)), (0.05, (0.66, 0.28, 0.22)), (0.14, (0.38, 0.22, 0.34)), (0.30, (0.14, 0.15, 0.36)),
                    (0.55, (0.045, 0.08, 0.24)), (1.0, (0.010, 0.020, 0.085))])
    # afterglow where the sun has just set, off the left edge
    dg = np.hypot((xx + 260) / 1500.0, (yy - HOR - 10) / 520.0)
    sky += (np.exp(-dg * dg * 1.6) * 0.62)[..., None] * np.array([1.0, 0.46, 0.10], F)
    sky += (np.exp(-dg * 3.2) * 0.55)[..., None] * np.array([1.0, 0.74, 0.34], F)
    right = smooth(700, 1600, xx)[..., None] * np.exp(-el * 9)[..., None]
    sky = sky * (1 - 0.45 * right) + np.array([0.34, 0.28, 0.46], F) * 0.45 * right
    # stars and a thin moon
    srng = np.random.default_rng(5)
    ns = 1500
    sx = srng.integers(0, W, ns); sy = (srng.random(ns) ** 1.7 * HOR * 0.62).astype(int)
    sb = srng.random(ns) ** 3
    st = np.zeros((H, W), F)
    st[sy, sx] = 0.12 + sb * 1.4
    st = st + ndi.gaussian_filter(st, 1.2) * 2.5
    sky += (st * smooth(0.30, 0.62, el))[..., None] * np.array([0.9, 0.95, 1.0], F)
    mx, my, mr = 300.0, 250.0, 34.0
    md = np.hypot(xx - mx, yy - my)
    crescent = smooth(mr + 1, mr - 1, md) * smooth(mr * 0.93 - 1, mr * 0.93 + 1, np.hypot(xx - mx - 15, yy - my - 7))
    sky += crescent[..., None] * np.array([1.5, 1.42, 1.2], F) + (np.exp(-md / 70.0) * 0.05)[..., None] * np.array([0.8, 0.85, 1.0], F)
    sky += (smooth(mr + 1, mr - 1, md) * 0.035)[..., None]
    # high feathery clouds that still catch the sun
    crng = np.random.default_rng(6)
    ci = fbm((H, W), (50, 520), 5, crng)
    ci2 = fbm((H, W), (14, 130), 4, crng)
    cirrus = smooth(0.50, 0.78, ci * 0.7 + ci2 * 0.3) * np.exp(-((el - 0.50) / 0.20) ** 2) * smooth(1150, 100, xx) * 0.55
    sky = sky * (1 - cirrus[..., None]) + np.array([0.95, 0.40, 0.34], F) * cirrus[..., None] * 0.75
    # low bank of far clouds on the horizon: dark tops, glowing undersides
    bank = fbm((H, W), (30, 300), 5, crng)
    bank2 = fbm((H, W), (10, 80), 4, crng)
    bk = smooth(0.52, 0.66, bank * 0.72 + bank2 * 0.28 + 0.30 * np.exp(-((el - 0.030) / 0.028) ** 2) - 0.17) * smooth(0.11, 0.06, el)
    under = np.clip(ndi.sobel(ndi.gaussian_filter(bk, 3), 0) * 3.0, 0, 1)
    bcol = np.array([0.10, 0.065, 0.15], F)[None, None, :] * (1 - smooth(900, 0, xx)[..., None] * 0.2) + under[..., None] * np.array([1.0, 0.42, 0.12], F) * smooth(1500, 200, xx)[..., None]
    sky = sky * (1 - 0.94 * bk[..., None]) + bcol * 0.94 * bk[..., None]
    print('sky %.1fs' % (time.time() - T0))

    # ------------------------------------------------------------ the storm cloud
    C, T = render_cloud()
    img = sky.copy()
    # a curtain of rain below the cloud base
    rn = fbm((H, W), (300, 26), 3, crng)
    xs_sh = xx + (HOR - yy) * 0.22
    rain = smooth(860, 1060, xs_sh) * smooth(1460, 1240, xs_sh) * smooth(1170, 1260, yy) * (0.30 + 0.75 * rn) * 0.62
    rain = np.clip(rain, 0, 0.85) * (yy < HOR)
    img = img * (1 - rain[..., None]) + np.array([0.06, 0.05, 0.12], F) * rain[..., None]
    img[:HOR] = img[:HOR] * T[..., None] + C
    # a single fork of lightning in the rain
    bolt = Image.new('L', (W, H), 0)
    bd = ImageDraw.Draw(bolt)
    brng = np.random.default_rng(13)

    def fork(x, y, y_end, wid, drift):
        pts = [(x, y)]
        while y < y_end:
            step = brng.uniform(9, 24)
            x += brng.normal(drift, 0.75) * step * 0.55
            y += step
            pts.append((x, min(y, y_end)))
            if wid > 1.5 and brng.random() < 0.07:
                fork(x, y, min(y_end, y + brng.uniform(30, 90)), wid * 0.45, drift + brng.choice([-1, 1]) * 0.8)
        bd.line(pts, fill=255, width=max(1, int(round(wid))), joint='curve')

    fork(1168.0, 1196.0, float(HOR), 2.0, -0.12)
    bm = np.asarray(bolt, F) / 255.0
    bcore = ndi.gaussian_filter(bm, 0.7)
    bglow = ndi.gaussian_filter(bm, 5) * 2.2 + ndi.gaussian_filter(bm, 24) * 5.0 + ndi.gaussian_filter(bm, 90) * 9.0
    img += bcore[..., None] * np.array([3.0, 3.0, 3.4], F) + (bglow * (yy < HOR + 4))[..., None] * np.array([0.55, 0.50, 1.0], F) * 0.5

    # ------------------------------------------------------------ a small sailing boat on the horizon
    boat = Image.new('L', (W * 2, H * 2), 0)
    d2 = ImageDraw.Draw(boat)
    bx, by = 430.0, HOR + 1.0

    def P2(pts):
        return [((bx + px) * 2, (by + py) * 2) for px, py in pts]

    d2.polygon(P2([(-30, -9), (30, -9), (22, 0), (-24, 0)]), fill=255)
    d2.polygon(P2([(1, -76), (1, -13), (28, -13)]), fill=255)
    d2.polygon(P2([(-3, -68), (-3, -13), (-23, -13)]), fill=255)
    d2.line(P2([(-1, -80), (-1, -9)]), fill=255, width=3)
    boatm = np.asarray(boat.resize((W, H), Image.BOX), F) / 255.0
    img = img * (1 - boatm[..., None]) + np.array([0.035, 0.03, 0.06], F) * boatm[..., None]
    # birds
    birds = Image.new('L', (W * 2, H * 2), 0)
    d3 = ImageDraw.Draw(birds)
    for (qx, qy, sc) in ((610, 1120, 1.0), (665, 1150, 0.8), (560, 1165, 0.7), (720, 1105, 0.6), (780, 1140, 0.5)):
        for sgn in (-1, 1):
            pts = [((qx + sgn * 17 * sc * tt) * 2, (qy - 8 * sc * math.sin(tt * 2.6) + 4 * sc * tt) * 2) for tt in np.linspace(0, 1, 8)]
            d3.line(pts, fill=255, width=int(max(2, 4 * sc)))
    birdm = np.asarray(birds.resize((W, H), Image.BOX), F) / 255.0
    img = img * (1 - 0.9 * birdm[..., None]) + np.array([0.04, 0.03, 0.07], F) * 0.9 * birdm[..., None]

    # ------------------------------------------------------------ the sea: a rippled mirror
    wrng = np.random.default_rng(9)
    depth = np.clip((yy - HOR) / (H - HOR), 0, 1)
    rip1 = fbm((H, W), (3, 90), 3, wrng) - 0.5
    rip2 = fbm((H, W), (7, 240), 3, wrng) - 0.5
    persp = 0.25 + 3.2 * depth
    ysrc = HOR - (yy - HOR) * 1.0 - 2 + (rip1 * 26 + rip2 * 40) * persp * depth ** 0.5
    xsrc = xx + (rip2 * 30) * depth
    ysrc = np.clip(ysrc, 0, HOR - 1)
    refl = np.stack([ndi.map_coordinates(img[..., i], [ysrc, np.clip(xsrc, 0, W - 1)], order=1) for i in range(3)], -1)
    refl = refl * (0.60 - 0.16 * depth[..., None]) * np.array([0.90, 0.96, 1.06], F) + np.array([0.004, 0.012, 0.022], F)
    # dark ripple lines and a few light glints
    lines = smooth(0.12, 0.30, rip1 * (0.4 + 2.0 * depth))
    refl *= (1 - 0.30 * lines * smooth(0.02, 0.3, depth))[..., None]
    glint = smooth(0.20, 0.34, -rip1) * np.exp(-((xx - 150) / 620.0) ** 2) * smooth(0.0, 0.25, depth) * 0.20
    refl += glint[..., None] * np.array([1.0, 0.55, 0.25], F)
    sea = smooth(HOR - 0.5, HOR + 0.5, yy)[..., None]
    img = img * (1 - sea) + refl * sea
    # thin bright line where sea meets sky on the left
    hl = np.exp(-((yy - HOR) / 1.4) ** 2) * np.exp(-((xx + 100) / 700.0) ** 2) * 0.5
    img += hl[..., None] * np.array([1.0, 0.7, 0.4], F)

    # ------------------------------------------------------------ finish
    hi = np.clip(img - 1.0, 0, 5)
    img = img + 0.22 * ndi.gaussian_filter(hi, (8, 8, 0)) + 0.14 * ndi.gaussian_filter(hi, (40, 40, 0))
    x = img * 0.86
    img = (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)       # film-like tone curve
    img = np.clip(img, 0, 1) ** (1 / 2.2)
    g = img.mean(-1, keepdims=True)
    img = np.clip(g + (img - g) * 1.12, 0, 1)
    vig = 1 - 0.26 * smooth(0.5, 1.2, np.hypot((xx - W * 0.5) / W, (yy - H * 0.52) / H) * 1.7)
    img *= vig[..., None]
    img += (rng.random((H, W, 1)).astype(F) - 0.5) * 0.014
    Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)).save(OUT)
    print('saved %s  %.1fs' % (os.path.abspath(OUT), time.time() - T0))


if __name__ == '__main__':
    main()
