ExperimentsFable 5.2 Python art (30 images)

Winter aurora forest, an image drawn with Python code by Fable 5.2. Opens the full-size image in a new tab.
#!/usr/bin/env python3
"""01 Winter aurora forest.

Snowy pines at night, a green aurora, and one warm lamp post.
Fable 5.2 Python art experiment: every pixel comes from the code below
(numpy noise fields, vector shapes, then a brush-stroke repaint).
Run: .venv/bin/python scripts/01-winter-aurora-forest.py
"""
import os, sys, time, math
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage as ndi

# ----------------------------------------------------------------------------
# Shared helper code (copied into every script so that each script runs alone)
# ----------------------------------------------------------------------------
W, H = 1600, 2000
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
F32 = np.float32


def hexc(s):
    s = s.lstrip('#')
    return np.array([int(s[i:i + 2], 16) for i in (0, 2, 4)], F32) / 255.0


def c8(c):
    return tuple(int(max(0, min(255, round(float(v) * 255)))) for v in c)


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


def mix(a, b, t):
    return a + (b - a) * t


def ramp(t, stops):
    """Colour gradient. stops = [(position, '#hex'), ...]; t is an array."""
    pos = [p for p, _ in stops]
    cols = np.array([hexc(c) if isinstance(c, str) else c for _, c in stops])
    return np.stack([np.interp(t, pos, cols[:, i]) for i in range(3)], -1).astype(F32)


def vnoise(shape, cell, rng):
    """Smooth value noise in 0..1: a random grid, enlarged with cubic interpolation."""
    h, w = shape
    cy, cx = (cell, cell) if np.isscalar(cell) else cell
    cy, cx = max(1.0, float(cy)), max(1.0, float(cx))
    gh, gw = int(h / cy) + 4, int(w / cx) + 4
    g = rng.random((gh, gw)).astype(F32)
    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)
    z = z[oy:oy + h, ox:ox + w]
    if z.shape != (h, w):
        z = np.pad(z, ((0, h - z.shape[0]), (0, w - z.shape[1])), mode='edge')
    return z


def fbm(shape, cell, octaves, rng, gain=0.5, lac=2.0):
    """Fractal noise in about 0..1 (sum of value noise octaves)."""
    cy, cx = (cell, cell) if np.isscalar(cell) else cell
    out = np.zeros(shape, F32)
    amp, tot = 1.0, 0.0
    for _ in range(octaves):
        out += amp * vnoise(shape, (cy, cx), rng)
        tot += amp
        amp *= gain
        cy /= lac
        cx /= lac
    return out / tot


def blur(a, s):
    """Gaussian blur for 2D or 3D (h, w, c) arrays; large radii use a small copy."""
    if s <= 0:
        return a
    if s > 10:
        k = int(s // 5)
        h, w = a.shape[:2]
        ph, pw = (-h) % k, (-w) % k
        pad = ((0, ph), (0, pw)) + (((0, 0),) if a.ndim == 3 else ())
        b = np.pad(a, pad, mode='edge')
        hh, ww = b.shape[0] // k, b.shape[1] // k
        if a.ndim == 3:
            b = b.reshape(hh, k, ww, k, -1).mean((1, 3))
            b = ndi.gaussian_filter(b, (s / k, s / k, 0), mode='nearest')
            b = ndi.zoom(b, (k, k, 1), order=1)
        else:
            b = b.reshape(hh, k, ww, k).mean((1, 3))
            b = ndi.gaussian_filter(b, s / k, mode='nearest')
            b = ndi.zoom(b, (k, k), order=1)
        return b[:h, :w].astype(F32)
    sig = (s, s, 0) if a.ndim == 3 else s
    return ndi.gaussian_filter(a, sig, mode='nearest').astype(F32)


def bloom(a, thresh=0.7, sigmas=(6, 20, 60), gains=(0.35, 0.3, 0.25)):
    """Soft glow around bright areas."""
    lum = a.max(-1)
    hi = a * smooth(thresh, thresh + 0.25, lum)[..., None]
    out = a.copy()
    for s, g in zip(sigmas, gains):
        out += g * blur(hi, s)
    return out


def glow(cx, cy, r, power=2.0):
    """Radial falloff field, 1 at the centre."""
    yy, xx = np.mgrid[0:H, 0:W].astype(F32)
    d2 = ((xx - cx) ** 2 + (yy - cy) ** 2) / (r * r)
    return 1.0 / (1.0 + d2) ** power


def comp(base, rgb, a):
    """Alpha composite. rgb may be one colour or an image; a is an (h, w) mask."""
    return base * (1 - a[..., None]) + np.asarray(rgb, F32) * a[..., None]


class Layer:
    """Vector drawing layer (PIL) drawn at 2x size, then averaged down for smooth edges."""

    def __init__(self, ss=2):
        self.ss = ss
        self.im = Image.new('RGBA', (W * ss, H * ss), (0, 0, 0, 0))
        self.d = ImageDraw.Draw(self.im)

    def _p(self, pts):
        s = self.ss
        return [(float(x) * s, float(y) * s) for x, y in pts]

    def poly(self, pts, col, a=1.0):
        self.d.polygon(self._p(pts), fill=c8(col) + (int(a * 255),))

    def line(self, pts, col, width=1.0, a=1.0):
        wd = max(1, int(round(width * self.ss)))
        self.d.line(self._p(pts), fill=c8(col) + (int(a * 255),), width=wd, joint='curve')

    def dot(self, x, y, rx, col, a=1.0, ry=None):
        s = self.ss
        ry = rx if ry is None else ry
        self.d.ellipse([(x - rx) * s, (y - ry) * s, (x + rx) * s, (y + ry) * s],
                       fill=c8(col) + (int(a * 255),))

    def arrays(self):
        im = self.im.convert('RGBa').reduce(self.ss)       # premultiplied alpha
        a = np.asarray(im).astype(F32) / 255.0
        return a[..., :3], a[..., 3]

    def onto(self, base, opacity=1.0, soften=0.0):
        rgb, a = self.arrays()
        if soften > 0:
            rgb, a = blur(rgb, soften), blur(a, soften)
        return base * (1 - a[..., None] * opacity) + rgb * opacity


def painterly(ref, rng, sizes=(44, 22, 11, 6), thresh=(0, 0.06, 0.05, 0.04), ss=2,
              jitter=0.035, length=5, base_angle=None, edge_follow=1.0, relief=0.3,
              density=1.0, tol=0.22, underblur=30, keep=None):
    """Repaint an image with oriented brush strokes, coarse to fine.

    Strokes follow the edges of the picture (structure tensor) and a flow field
    elsewhere. Finer strokes are added only where the canvas still differs from
    the reference. A separate height map of the strokes gives the paint relief.
    keep: optional (h, w) probability mask that limits where fine strokes go.
    """
    h, w = ref.shape[:2]
    lum = ref @ np.array([0.3, 0.59, 0.11], F32)
    l2 = ndi.gaussian_filter(lum, 2.0)
    gx, gy = ndi.sobel(l2, axis=1), ndi.sobel(l2, axis=0)
    jxx, jyy, jxy = blur(gx * gx, 6), blur(gy * gy, 6), blur(gx * gy, 6)
    theta = 0.5 * np.arctan2(2 * jxy, jxx - jyy) + np.pi / 2
    coh = np.sqrt((jxx - jyy) ** 2 + 4 * jxy ** 2)
    cw = smooth(0.0004, 0.01, coh) * edge_follow
    if base_angle is None:
        base_angle = fbm((h, w), 320, 3, rng) * np.pi * 3
    base_angle = np.broadcast_to(np.asarray(base_angle, F32), (h, w))
    c2 = cw * np.cos(2 * theta) + (1 - cw) * np.cos(2 * base_angle)
    s2 = cw * np.sin(2 * theta) + (1 - cw) * np.sin(2 * base_angle)
    ang = 0.5 * np.arctan2(s2, c2)
    dxf, dyf = np.cos(ang).astype(F32), np.sin(ang).astype(F32)

    start = np.clip(blur(ref, underblur), 0, 1)
    canvas = Image.fromarray((start * 255).astype(np.uint8)).resize((w * ss, h * ss), Image.BILINEAR)
    hmap = Image.new('L', (w * ss, h * ss), 128)
    dr, hd = ImageDraw.Draw(canvas), ImageDraw.Draw(hmap)

    for li, s in enumerate(sizes):
        sp = max(2.0, s * 0.45 / density)
        ny, nx = int(h / sp) + 1, int(w / sp) + 1
        gy_, gx_ = np.mgrid[0:ny, 0:nx].astype(F32)
        px = (gx_ + rng.random((ny, nx))).ravel() * sp
        py = (gy_ + rng.random((ny, nx))).ravel() * sp
        ok = (px < w - 1) & (py < h - 1)
        px, py = px[ok], py[ok]
        xi, yi = px.astype(int), py.astype(int)
        sel = np.ones(len(px), bool)
        if thresh[li] > 0:
            cur = np.asarray(canvas.reduce(ss)).astype(F32) / 255.0
            diff = blur(np.abs(cur - ref).sum(-1), s * 0.5)
            sel &= diff[yi, xi] > thresh[li]
        if keep is not None and li >= 1:
            sel &= rng.random(len(px)) < keep[yi, xi]
        px, py, xi, yi = px[sel], py[sel], xi[sel], yi[sel]
        n = len(px)
        if n == 0:
            continue
        col0 = ref[yi, xi]
        K = int(length)
        step = s * 0.6
        pts = np.zeros((n, 2 * K + 1, 2), F32)
        pts[:, K, 0], pts[:, K, 1] = px, py
        for sgn in (1, -1):
            x, y = px.copy(), py.copy()
            ddx, ddy = dxf[yi, xi] * sgn, dyf[yi, xi] * sgn
            alive = np.ones(n, bool)
            for k in range(1, K + 1):
                ix = np.clip(x.astype(int), 0, w - 1)
                iy = np.clip(y.astype(int), 0, h - 1)
                ndx, ndy = dxf[iy, ix], dyf[iy, ix]
                flip = np.where(ndx * ddx + ndy * ddy < 0, -1.0, 1.0)
                ddx, ddy = ndx * flip, ndy * flip
                nx_, ny_ = x + ddx * step, y + ddy * step
                jx = np.clip(nx_.astype(int), 0, w - 1)
                jy = np.clip(ny_.astype(int), 0, h - 1)
                alive &= np.abs(ref[jy, jx] - col0).sum(-1) < tol
                x = np.where(alive, nx_, x)
                y = np.where(alive, ny_, y)
                pts[:, K + sgn * k, 0], pts[:, K + sgn * k, 1] = x, y
        colj = col0 * (1 + jitter * rng.standard_normal((n, 1))) + 0.4 * jitter * rng.standard_normal((n, 3))
        cols = (np.clip(colj, 0, 1) * 255).astype(np.uint8)
        order = rng.permutation(n)
        P = (pts[order] * ss).reshape(n, -1).tolist()
        Cc = cols[order].tolist()
        G = rng.integers(40, 216, n).tolist()
        Bo = (rng.standard_normal((n, 3)) * s * ss * 0.28).tolist()
        Bl = (1 + 0.07 * rng.standard_normal((n, 3))).tolist()
        wd = max(1, int(s * ss))
        r = wd / 2.0
        for i in range(n):
            p = P[i]
            c = tuple(Cc[i])
            dr.line(p, fill=c, width=wd, joint='curve')
            hd.line(p, fill=G[i], width=wd, joint='curve')
            for ex, ey in ((p[0], p[1]), (p[-2], p[-1])):
                box = [ex - r, ey - r, ex + r, ey + r]
                dr.ellipse(box, fill=c)
                hd.ellipse(box, fill=G[i])
            if s >= 9:        # bristle streaks inside the larger strokes
                vx, vy = p[-2] - p[0], p[-1] - p[1]
                vl = math.hypot(vx, vy) + 1e-6
                ox_, oy_ = -vy / vl, vx / vl
                for b in range(3):
                    o = Bo[i][b]
                    q = [v + (o * ox_ if j % 2 == 0 else o * oy_) for j, v in enumerate(p)]
                    cb = tuple(int(max(0, min(255, v * Bl[i][b]))) for v in c)
                    dr.line(q, fill=cb, width=max(1, wd // 5), joint='curve')
                    hd.line(q, fill=int(max(0, min(255, G[i] + 40 * (Bl[i][b] - 1) * 14))), width=max(1, wd // 5))
    out = np.asarray(canvas.reduce(ss)).astype(F32) / 255.0
    if relief > 0:
        hm = ndi.gaussian_filter(np.asarray(hmap.reduce(ss)).astype(F32), 0.8)
        sh = np.clip((-ndi.sobel(hm, axis=1) * 0.5 - ndi.sobel(hm, axis=0) * 0.85) / 255.0, -1, 1)
        out = out * (1 + relief * sh[..., None])
    return out


def finish(a, name, rng, vignette=0.22, grain=0.012, weave=0.018):
    """Vignette, canvas weave, grain, then save to ../images/<name>.png."""
    yy, xx = np.mgrid[0:H, 0:W].astype(F32)
    r = np.sqrt(((xx / W - 0.5) * 1.15) ** 2 + (yy / H - 0.5) ** 2)
    a = a * (1 - vignette * smooth(0.3, 0.8, r))[..., None]
    if weave > 0:
        wv = (np.sin(xx * 2.1) * np.sin(yy * 2.1)) * 0.5 + (vnoise((H, W), 2.5, rng) - 0.5)
        a = a * (1 + weave * wv)[..., None]
    if grain > 0:
        a = a + grain * rng.standard_normal((H, W, 1)).astype(F32)
    out = os.path.join(HERE, '..', 'images', name + '.png')
    os.makedirs(os.path.dirname(out), exist_ok=True)
    Image.fromarray((np.clip(a, 0, 1) * 255 + 0.5).astype(np.uint8)).save(out)
    print(f'saved {os.path.normpath(out)}  ({time.time() - T0:.1f} s)')

# ----------------------------------------------------------------------------
# The picture
# ----------------------------------------------------------------------------
SEED = 101
rng = np.random.default_rng(SEED)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)

LX, LY = 610.0, 1585.0          # lamp post foot
LAMP_H = 470.0
HEADY = LY - LAMP_H             # centre of the lantern
WARM = hexc('#ffb257')

# ---- sky ---------------------------------------------------------------
sky = ramp(yy / H, [(0.0, '#03061a'), (0.3, '#071530'), (0.55, '#0c2a45'), (0.7, '#12404d')])

# stars
st = np.zeros((H, W), F32)
n = 2600
sx, sy = rng.integers(0, W, n), rng.integers(0, 1350, n)
st[sy, sx] = rng.random(n) ** 6 * 3.0 + 0.15
stars = blur(st, 0.8) * 4 + blur(st, 2.5) * 6

# aurora: curtains of vertical rays that hang from wavy base lines
aur = np.zeros((H, W, 3), F32)
ray1d = lambda cell: vnoise((1, 6000), (1, cell), rng)[0]
for (y0, amp, lam, ph, slant, Lr, gain) in [
        (1010, 150, 520, 0.6, -0.20, 520, 1.00),
        (700, 120, 700, 2.4, -0.12, 430, 0.75),
        (1150, 60, 380, 4.0, -0.25, 300, 0.45)]:
    xw = xx[0]
    yb = y0 + amp * np.sin(xw / lam + ph) + 70 * np.sin(xw / (lam * 0.37) + ph * 2.1) \
        + 80 * (vnoise((1, W), (1, 300), rng)[0] - 0.5) - 0.18 * (xw - W / 2) \
        + 90 * (vnoise((1, W), (1, 22), rng)[0] - 0.5) + 60 * (vnoise((1, W), (1, 70), rng)[0] - 0.5)
    up = yb[None, :] - yy                                  # height above the base line
    u = xx + slant * up + 2000
    rays = np.interp(u, np.arange(6000), ray1d(9)) * 0.55 + np.interp(u, np.arange(6000), ray1d(34)) * 0.45
    rays = smooth(0.25, 0.85, rays) ** 1.3
    broad = np.interp(u, np.arange(6000), ray1d(260))
    env = np.where(up > 0, np.exp(-np.maximum(up, 0) / Lr), np.exp(np.minimum(up, 0) / 26.0))
    inten = env * (0.25 + 0.95 * rays) * smooth(0.2, 0.75, broad) * gain
    t = np.clip(up / (Lr * 1.7), 0, 1)
    col = ramp(t, [(0.0, '#aaff9a'), (0.15, '#35ee6e'), (0.45, '#10c07a'), (0.75, '#2a6cbc'), (1.0, '#6c3cb4')])
    aur += col * inten[..., None]
aur = aur + blur(aur, 26) * 0.9 + blur(aur, 90) * 0.5
am = aur.max(-1, keepdims=True) + 1e-6
aur = aur * ((1 - np.exp(-am * 0.9)) / am) * 0.86        # soft limit, keeps the hue
sky = sky + aur
img = sky

# ---- ground -------------------------------------------------------------
gline = 1335 + 26 * (vnoise((1, W), (1, 420), rng)[0] - 0.5) + 0.03 * (xx[0] - 800)
tg = np.clip((yy - gline[None, :]) / (H - 1335), 0, 1)
base_n = fbm((H, W), (64, 300), 4, rng)
rows = np.clip((tg ** 0.55) * (H - 1), 0, H - 1).astype(int)
drift = np.take_along_axis(base_n, rows, 0)
dsl = ndi.sobel(ndi.gaussian_filter(drift, 3), axis=0)
dsl = np.clip(dsl / (np.abs(dsl).max() + 1e-6) * 4, -1, 1)
dslx = ndi.sobel(ndi.gaussian_filter(drift, 3), axis=1)
dslx = np.clip(dslx / (np.abs(dslx).max() + 1e-6) * 4, -1, 1)
ground = ramp(tg, [(0, '#1b3559'), (0.35, '#24426e'), (1, '#1c3562')])
ground *= (1 + 0.3 * dsl)[..., None]
ground += np.array([0.02, 0.10, 0.07], F32) * (1 - tg[..., None]) ** 2      # aurora light on far snow

# mid-ground and foreground trees: (x, foot y, height)
TREES = [(330, 1470, 560), (455, 1432, 380), (880, 1452, 640), (1015, 1425, 400),
         (745, 1418, 300), (1180, 1440, 470), (215, 1445, 430)]
BIG = [(1385, 1985, 1640), (60, 1900, 1180)]

# shadows that the trees cast away from the lamp
sh = Layer()
for (tx, ty, th) in TREES + BIG:
    dx, dy = tx - LX, (ty - LY) * 3.0
    dl = math.hypot(dx, dy) + 1e-6
    ux, uy = dx / dl, dy / dl / 3.0
    ln = 900
    wb = th * 0.05
    px_, py_ = -uy * 3, ux / 3
    nrm = math.hypot(px_, py_)
    px_, py_ = px_ / nrm, py_ / nrm * 0.33
    sh.poly([(tx - px_ * wb, ty - py_ * wb), (tx + px_ * wb, ty + py_ * wb),
             (tx + ux * ln + px_ * wb * 7, ty + uy * ln + py_ * wb * 7),
             (tx + ux * ln - px_ * wb * 7, ty + uy * ln - py_ * wb * 7)], (1, 1, 1))
_, shadow = sh.arrays()
shadow = blur(shadow, 9)

pool_d2 = ((xx - LX) / 430) ** 2 + ((yy - LY) / 150) ** 2
pool = 1.0 / (1 + pool_d2) ** 1.5
tolamp_x = np.clip((LX - xx) / 300, -1, 1)
lampshade = 1 + 0.4 * (dsl * np.sign(yy - LY) * -1) + 0.35 * dslx * tolamp_x
spark = (vnoise((H, W), 2.2, rng) > 0.82) * 0.25
ground += (WARM * 1.25) * (pool * (1 - 0.8 * shadow) * np.clip(lampshade, 0.3, 1.9) * (1 + spark))[..., None]
gmask = smooth(-2, 2, yy - gline[None, :])
img = comp(img, ground, gmask)

# footprints that lead to the lamp
fp = Layer()
for i, t in enumerate(np.linspace(0, 1, 34)):
    px_ = mix(1010, LX + 30, t) + 110 * math.sin(t * 3.1) * (1 - t)
    py_ = mix(2010, LY + 22, t ** 0.8)
    sc = mix(1.0, 0.36, t)
    side = (1 if i % 2 else -1) * 17 * sc
    fp.dot(px_ + side, py_, 24 * sc, hexc('#0f1f3e'), 0.9, ry=10 * sc)
    fp.dot(px_ + side + 3 * sc, py_ + 8 * sc, 20 * sc, hexc('#e9a868') * (0.25 + 0.75 * t), 0.5 * t ** 1.5 + 0.08, ry=3 * sc)
img = fp.onto(img, soften=1.2)

# ---- distant tree lines -------------------------------------------------
far = Layer()
for (cnt, hmin, hmax, colr, yo) in [(170, 26, 80, '#0b1c30', -4), (90, 60, 170, '#071424', 4)]:
    for _ in range(cnt):
        x = rng.uniform(-30, W + 30)
        hgt = rng.uniform(hmin, hmax) * (1.25 if (x < 250 or x > 1250) else 1.0)
        yb = np.interp(x, xx[0], gline) + yo + rng.uniform(-3, 5)
        wd = hgt * rng.uniform(0.16, 0.24)
        pts = [(x, yb - hgt)]
        for k in range(1, 7):
            f = k / 6
            pts.append((x + wd * f * rng.uniform(0.8, 1.1), yb - hgt * (1 - f) + rng.uniform(0, 5)))
            pts.append((x + wd * f * 0.55, yb - hgt * (1 - f) - 3))
        for k in range(6, 0, -1):
            f = k / 6
            pts.append((x - wd * f * 0.55, yb - hgt * (1 - f) - 3))
            pts.append((x - wd * f * rng.uniform(0.8, 1.1), yb - hgt * (1 - f) + rng.uniform(0, 5)))
        far.poly(pts, hexc(colr) * rng.uniform(0.8, 1.2))
img = far.onto(img)


# ---- pines built from needle strokes and snow strokes -------------------------
def pine(L, x0, yb, hgt, haze=0.0):
    wbase = hgt * 0.215
    L.line([(x0, yb + 3), (x0, yb - hgt * 0.2)], hexc('#0b0907'), max(3, hgt * 0.022))
    tiers = int(10 + hgt / 70)
    for ti in range(tiers, 0, -1):
        t = ti / tiers
        y = yb - hgt * 0.06 - hgt * 0.94 * (1 - t)
        wv = wbase * (t ** 0.8) * (0.72 + 0.3 * rng.random()) + 3
        nb = int(7 + wv / 5)
        for _ in range(nb):
            u = rng.uniform(-1, 1)
            u = math.copysign(abs(u) ** 0.7, u)
            tipx = x0 + u * wv
            tipy = y + abs(u) * wv * 0.42 + rng.uniform(-4, 6)
            rx, ry = x0 + u * wv * 0.1, y - wv * 0.16
            bw = max(2.5, hgt * 0.013) * rng.uniform(0.7, 1.4)
            dist = math.hypot(tipx - LX, (tipy - HEADY))
            facing = 1.0 if (LX - x0) * u > 0 else 0.12
            if abs(x0 - LX) < 1:
                facing = 0.5
            lit = facing * (abs(u) ** 0.6) / (1 + (dist / 420) ** 2)
            dark = mix(hexc('#040c0c'), hexc('#0f2a26'), rng.random() * 0.8)
            dark = dark + WARM * lit * 0.14
            dark = mix(dark, hexc('#0d2136'), haze)
            midx, midy = (rx + tipx) / 2, (ry + tipy) / 2 - wv * 0.03
            L.line([(rx, ry), (midx, midy), (tipx, tipy)], dark, bw)
            # sprays of needles under the branch
            for _k in range(2):
                f = rng.uniform(0.35, 1.0)
                bx, by = mix(rx, tipx, f), mix(ry, tipy, f)
                L.line([(bx, by), (bx + u * wv * 0.08, by + bw * rng.uniform(1.5, 3.2))], dark * 0.9, bw * 0.6)
            # snow on top of the branch
            if rng.random() < 0.85:
                f0, f1 = rng.uniform(0.15, 0.45), rng.uniform(0.7, 1.0)
                sx0, sy0 = mix(rx, tipx, f0), mix(ry, tipy, f0) - bw * 0.55
                sx1, sy1 = mix(rx, tipx, f1), mix(ry, tipy, f1) - bw * 0.55
                snow = mix(hexc('#3a5b90'), hexc('#a5c3e6'), rng.random() ** 1.3)
                snow = snow + np.array([0.0, 0.07, 0.04], F32)             # aurora tint
                snow = mix(snow, hexc('#ffd9a0'), min(1.0, lit * 2.2)) + WARM * lit * 0.5
                snow = mix(snow, hexc('#1a3352'), haze)
                L.line([(sx0, sy0), ((sx0 + sx1) / 2, (sy0 + sy1) / 2 - bw * 0.2), (sx1, sy1)], snow, bw * 0.95)
                if rng.random() < 0.3:
                    L.dot(sx1, sy1, bw * 1.1, snow * 1.05, ry=bw * 0.7)
    # snow skirt at the foot
    L.dot(x0, yb + 2, hgt * 0.12, hexc('#2a4874'), 0.9, ry=hgt * 0.012 + 3)


mid = Layer()
for (tx, ty, th) in sorted(TREES, key=lambda t: t[1]):
    pine(mid, tx, ty, th, haze=0.22)
img = mid.onto(img)

# ---- the lamp post ------------------------------------------------------
lp = Layer()
iron = hexc('#0a0a0d')
lp.poly([(LX - 9, LY + 4), (LX + 9, LY + 4), (LX + 5, HEADY + 62), (LX - 5, HEADY + 62)], iron)
lp.poly([(LX - 17, LY + 6), (LX + 17, LY + 6), (LX + 10, LY - 26), (LX - 10, LY - 26)], iron)
lp.dot(LX, LY - 150, 9, iron, ry=5)
lp.dot(LX, HEADY + 66, 12, iron, ry=6)
lp.line([(LX - 30, HEADY + 96), (LX + 30, HEADY + 96)], iron, 4)            # ladder bar
# lantern glass
lp.poly([(LX - 21, HEADY + 52), (LX + 21, HEADY + 52), (LX + 33, HEADY - 38), (LX - 33, HEADY - 38)], hexc('#ffc060'))
lp.poly([(LX - 12, HEADY + 44), (LX + 12, HEADY + 44), (LX + 19, HEADY - 30), (LX - 19, HEADY - 30)], hexc('#fff3c4'))
for sx_ in (-1, 0, 1):                                                       # frame bars
    lp.line([(LX + sx_ * 21, HEADY + 52), (LX + sx_ * 33, HEADY - 38)], iron, 3.2)
lp.poly([(LX - 24, HEADY + 50), (LX + 24, HEADY + 50), (LX + 18, HEADY + 62), (LX - 18, HEADY + 62)], iron)
lp.poly([(LX - 44, HEADY - 36), (LX + 44, HEADY - 36), (LX + 9, HEADY - 78), (LX - 9, HEADY - 78)], iron)   # roof
lp.dot(LX, HEADY - 86, 6, iron, ry=9)
lp.poly([(LX - 44, HEADY - 38), (LX + 44, HEADY - 38), (LX + 30, HEADY - 58), (LX + 8, HEADY - 82),
         (LX - 8, HEADY - 82), (LX - 30, HEADY - 58)], hexc('#9db7d6'))                                    # snow cap
lp.poly([(LX - 40, HEADY - 38), (LX + 40, HEADY - 38), (LX + 24, HEADY - 50), (LX - 24, HEADY - 50)], hexc('#ffd9a0'))
lp.dot(LX, LY + 6, 44, hexc('#ffe6bd'), 0.9, ry=9)                          # snow heap at the foot
img = lp.onto(img)

# ---- foreground pines ---------------------------------------------------
fg = Layer()
for (tx, ty, th) in BIG:
    pine(fg, tx, ty, th, haze=0.0)
img = fg.onto(img)

# ---- repaint everything with brush strokes -------------------------------------
under = img.copy()
flow = np.where(yy < gline[None, :], np.pi / 2 + 0.25 * (fbm((H, W), 300, 2, rng) - 0.5) * 4,
                0.5 * (fbm((H, W), 260, 2, rng) - 0.5) * 2)
paint = painterly(np.clip(under, 0, 1), rng, sizes=(46, 24, 12, 6, 3.5), thresh=(0, 0.07, 0.055, 0.045, 0.05),
                  base_angle=flow, relief=0.3, jitter=0.05, length=5)
img = paint

# ---- light added on top of the paint ------------------------------------
halo = glow(LX, HEADY + 5, 24, 1.8)[..., None] * hexc('#fff0c8') * 0.55 \
    + glow(LX, HEADY, 150, 1.5)[..., None] * WARM * 0.30 \
    + glow(LX, HEADY, 520, 1.3)[..., None] * WARM * 0.13
img = img + halo
img += stars[..., None] * 0.8 * (1 - gmask[..., None]) * (1 - np.clip(aur.max(-1) * 1.5, 0, 0.8))[..., None]

# falling snow, warm where the lamp lights it
fl = np.zeros((H, W), F32)
n = 700
fxs, fys = rng.integers(0, W, n), rng.integers(0, H, n)
fl[fys, fxs] = rng.random(n) ** 2 + 0.2
flk = blur(fl, 1.3) * 10
fl2 = np.zeros((H, W), F32)
n = 130
fl2[rng.integers(0, H, n), rng.integers(0, W, n)] = rng.random(n) + 0.5
flk2 = blur(fl2, 3.6) * 38
near_lamp = glow(LX, HEADY, 330, 1.2)
fcol = mix(hexc('#9fc0e6'), hexc('#ffd596'), np.clip(near_lamp * 2.2, 0, 1)[..., None])
img += fcol * ((flk * 0.42 + flk2 * 0.22) * (0.38 + 2.6 * near_lamp))[..., None]

img = bloom(img, 0.8, (5, 18), (0.25, 0.2))
img = np.clip(img, 0, 1) ** 0.94
finish(img, '01-winter-aurora-forest', rng, vignette=0.3)