#!/usr/bin/env python3
"""06 Autumn forest path.

A path into low sun: tree trunks in three depth bands, about 40,000 leaf
dabs coloured by how close they are to the light, long trunk shadows,
dappled ground, falling leaves, then a brush-stroke repaint.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/06-autumn-forest-path.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 = 606
rng = np.random.default_rng(SEED)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)

VPX, HZ = 830.0, 1070.0             # where the path ends
SUNX, SUNY = 850.0, 860.0
LEAF = [(0, '#2a0a0c'), (0.22, '#8a1512'), (0.45, '#cf3e16'), (0.68, '#f28f1e'), (0.86, '#ffc83c'), (1, '#fff0a0')]

tg = np.clip((yy - HZ) / (H - HZ), 0, 1)
cxp = lambda t: VPX + 105 * np.sin(t * 2.7) * t
hwp = lambda t: 9 + 500 * t ** 1.12
sunl = glow(SUNX, SUNY, 330, 1.25)

# ---- backdrop: the light at the end of the path ---------------------------------
r = np.sqrt(((xx - SUNX) / 1.0) ** 2 + ((yy - SUNY) / 1.25) ** 2) / 1100
bg = ramp(np.clip(r, 0, 1), [(0, '#fff2bc'), (0.08, '#ffd978'), (0.3, '#f09a30'), (0.55, '#b9541a'), (0.8, '#5e2410'), (1, '#27100a')])
bg *= (0.85 + 0.3 * fbm((H, W), 90, 4, rng))[..., None]
img = bg

# ---- trunks ------------------------------------------------------------------------
TRUNKS = []
for i in range(34):
    t = rng.uniform(0.02, 1.0) ** 1.25
    side = -1 if i % 2 else 1
    off = hwp(t) + (14 + 560 * rng.random() ** 1.3) * (0.25 + t)
    TRUNKS.append([float(cxp(t) + side * off), t, rng.uniform(0.8, 1.25), rng.uniform(-0.05, 0.05)])
TRUNKS += [[95.0, 1.12, 1.5, 0.03], [1525.0, 1.06, 1.25, -0.04], [455.0, 0.5, 1.2, 0.02], [1180.0, 0.42, 1.1, -0.03]]
TRUNKS = [tr for tr in TRUNKS if -120 < tr[0] < W + 120]
TRUNKS.sort(key=lambda tr: tr[1])

# ---- ground --------------------------------------------------------------------------
pathm = smooth(1.08, 0.86, np.abs(xx - cxp(tg)) / hwp(tg))
gzv = 1.0 / (tg + 0.035)
gxv = (xx - VPX) * gzv / 60.0
TEXG = ndi.gaussian_filter(rng.random((256, 256)).astype(F32), 3, mode='wrap')
TEXG = (TEXG - TEXG.min()) / (TEXG.max() - TEXG.min())
dap = ndi.map_coordinates(TEXG, np.stack([(gzv * 26) % 256, (gxv * 5.5) % 256]), order=1, mode='grid-wrap')
dapple = smooth(0.4, 0.62, dap)
shl = Layer()
for (x, t, wsc, lean) in TRUNKS:
    yb = HZ + (H - HZ) * t
    wd = (16 + 105 * t) * wsc
    dx, dy = x - VPX, (yb - HZ) + 40
    dl = math.hypot(dx, dy)
    ux, uy = dx / dl, dy / dl
    L_ = 1600
    shl.poly([(x - wd * 0.5, yb), (x + wd * 0.5, yb), (x + ux * L_ + wd * 2.2, yb + uy * L_), (x + ux * L_ - wd * 2.2, yb + uy * L_)], (1, 1, 1))
_, shadow = shl.arrays()
shadow = blur(shadow, 7) * smooth(0.0, 0.08, tg)
light = (0.42 + 0.78 * dapple) * (1 - 0.62 * shadow)
light *= 0.75 + 1.1 * np.exp(-np.abs(xx - cxp(tg)) / (260 + 500 * tg)) * (1 - 0.45 * tg)
earth = ramp(tg, [(0, '#f6c46e'), (0.3, '#d99746'), (1, '#9c6230')])
litter = ramp(tg, [(0, '#e59a3a'), (0.3, '#b9561c'), (1, '#6e2a10')])
ground = mix(litter, earth, pathm[..., None]) * light[..., None]
ground = mix(ground, ground * np.array([0.78, 0.62, 1.1], F32) + hexc('#2a0f22') * 0.25, (shadow * 0.6)[..., None])   # cool violet in the shadows
ground += sunl[..., None] * hexc('#ffd27a') * 0.45
img = comp(img, ground, smooth(-2, 2, yy - HZ))

# leaves that lie on the ground
gl = Layer()
n = 15000
t_ = rng.random(n) ** 0.75
ys = HZ + (H - HZ) * t_ + rng.uniform(-3, 3, n)
xs = rng.uniform(-20, W + 20, n)
keep = rng.random(n) > 0.55 * (np.abs(xs - cxp(t_)) < hwp(t_) * 0.8)
for i in np.argsort(ys):
    if not keep[i]:
        continue
    x, y, t = xs[i], ys[i], t_[i]
    li = float(light[int(np.clip(y, 0, H - 1)), int(np.clip(x, 0, W - 1))])
    c = ramp(np.array([np.clip(rng.uniform(0.15, 0.75) + 0.28 * (li - 0.6), 0, 1)]), LEAF)[0] * (0.55 + 0.6 * li)
    sz = (2.5 + 17 * t) * rng.uniform(0.6, 1.3)
    gl.dot(x, y, sz, c, 0.92, ry=sz * rng.uniform(0.3, 0.55))
img = gl.onto(img)


# ---- trees and leaves, far to near -------------------------------------------------------
def trunk(L, x, t, wsc, lean):
    yb = HZ + (H - HZ) * t
    wd = (16 + 105 * t) * wsc
    hazef = np.clip(1 - t, 0, 1) ** 1.6 * 0.82
    dark = mix(hexc('#1c110b'), hexc('#c8742a'), hazef)
    topx = x + lean * (yb + 100)
    L.poly([(x - wd * 0.62, yb + 4), (x - wd * 0.47, yb - wd * 1.2), (topx - wd * 0.33, -60),
            (topx + wd * 0.33, -60), (x + wd * 0.47, yb - wd * 1.2), (x + wd * 0.62, yb + 4)], dark)
    sgn = 1 if x < SUNX else -1                          # the side that faces the light
    rimc = mix(hexc('#ff9d2e'), hexc('#ffe9a0'), hazef)
    for k in range(2):
        f = 0.47 - 0.04 * k
        L.poly([(x + sgn * wd * f, yb - wd * 1.2), (topx + sgn * wd * (f - 0.14), -60),
                (topx + sgn * wd * (f - 0.14 - 0.03), -60), (x + sgn * wd * (f - 0.04), yb - wd * 1.2)], rimc, 0.6 - 0.3 * k)
    for _ in range(int(4 + 10 * t)):                    # bark strokes
        bx = rng.uniform(-0.38, 0.38)
        y0 = rng.uniform(-40, yb - 20)
        ln = rng.uniform(40, 220) * (0.4 + t)
        fx = lambda yv: x + (topx - x) * (yb - yv) / (yb + 60) + bx * wd
        L.line([(fx(y0), y0), (fx(y0 + ln) + rng.uniform(-3, 3), y0 + ln)], dark * rng.uniform(0.45, 0.8), max(1.2, wd * 0.05), 0.8)
    for _ in range(rng.integers(2, 5)):                 # branches
        y0 = rng.uniform(0.05, 0.7) * yb
        bx0 = x + (topx - x) * (yb - y0) / (yb + 60)
        sd = rng.choice([-1, 1])
        ln = rng.uniform(140, 420) * (0.35 + 0.9 * t)
        pts = [(bx0, y0)]
        a = rng.uniform(0.5, 1.1)
        for s_ in range(1, 5):
            pts.append((bx0 + sd * ln * s_ / 4 * math.cos(a), y0 - ln * s_ / 4 * math.sin(a) + 10 * s_ * s_ * 0.3))
        for s_ in range(4):
            L.line(pts[s_:s_ + 2], dark, max(1.5, wd * 0.2 * (1 - s_ / 4.5)))


def leaves(L, n_cl, per, sd, smin, smax, ylo, yhi, darken, hole):
    for _ in range(n_cl):
        cx_, cy_ = rng.uniform(-60, W + 60), rng.uniform(ylo, yhi)
        if hole > 0 and ((cx_ - SUNX) / (hole * 0.8)) ** 2 + ((cy_ - SUNY - 60) / (hole * 1.25)) ** 2 < 1:
            continue
        px = rng.normal(cx_, sd, per)
        py = rng.normal(cy_, sd * 0.7, per)
        for x, y in zip(px, py):
            d = math.hypot(x - SUNX, y - SUNY)
            lit = 1.0 / (1 + (d / 420.0) ** 2)
            v = np.clip(0.18 + 0.85 * lit + rng.normal(0, 0.16) - darken * (0.55 if rng.random() > 0.22 else -0.1), 0, 1)
            c = ramp(np.array([v]), LEAF)[0]
            sz = rng.uniform(smin, smax)
            a = rng.uniform(0, np.pi)
            L.line([(x - math.cos(a) * sz * 0.5, y - math.sin(a) * sz * 0.5), (x + math.cos(a) * sz * 0.5, y + math.sin(a) * sz * 0.5)],
                   c, sz * rng.uniform(0.55, 0.85), 0.95)


bands = [(0.0, 0.22), (0.22, 0.55), (0.55, 2.0)]
LEAFSET = [(170, 70, 55, 5, 10, 250, 1050, 0.0, 150), (120, 80, 85, 9, 18, -40, 930, 0.45, 250), (46, 110, 120, 16, 34, -80, 560, 0.75, 420)]
for (lo, hi), ls in zip(bands, LEAFSET):
    L = Layer()
    for (x, t, wsc, lean) in TRUNKS:
        if lo <= t < hi:
            trunk(L, x, t, wsc, lean)
    leaves(L, *ls)
    img = L.onto(img)
    if hi < 0.6:                                         # warm haze between the depth bands
        img = img + sunl[..., None] * hexc('#ffc864') * 0.14

# ---- light shafts --------------------------------------------------------------------------
ang = np.arctan2(yy - SUNY, xx - SUNX)
rr = np.hypot(xx - SUNX, yy - SUNY)
n1 = vnoise((1, 4096), (1, 26), rng)[0] * 0.6 + vnoise((1, 4096), (1, 7), rng)[0] * 0.4
shaft = np.interp((ang + np.pi) / (2 * np.pi) * 4095, np.arange(4096), n1)
shaft = smooth(0.5, 0.78, shaft) * np.exp(-rr / 850.0) * smooth(30, 160, rr)
img = img * (1 + 0.5 * shaft[..., None]) + shaft[..., None] * hexc('#ffb84a') * 0.12

# ---- falling leaves ----------------------------------------------------------------------
fl = Layer()
for _ in range(75):
    x, y = rng.uniform(40, W - 40), rng.uniform(120, 1850)
    sz = rng.uniform(9, 30) * (0.6 + 0.6 * y / H)
    a = rng.uniform(0, 2 * np.pi)
    squash = rng.uniform(0.3, 0.75)
    ca, sa = math.cos(a), math.sin(a)
    pts = []
    for th in np.linspace(0, 2 * np.pi, 14, endpoint=False):
        lx = math.cos(th) * sz * (1 + 0.25 * math.cos(th))
        ly = math.sin(th) * sz * squash * (1 - 0.35 * math.cos(th))
        pts.append((x + lx * ca - ly * sa, y + lx * sa + ly * ca))
    d = math.hypot(x - SUNX, y - SUNY)
    v = np.clip(0.45 + 0.5 / (1 + (d / 500) ** 2) + rng.normal(0, 0.15), 0.2, 1)
    c = ramp(np.array([v]), LEAF)[0]
    fl.poly(pts, c)
    fl.line([(x - ca * sz * 1.1, y - sa * sz * 1.1), (x + ca * sz * 1.2, y + sa * sz * 1.2)], c * 0.6, max(1.0, sz * 0.08))
img = fl.onto(img)

# ---- brush pass and glow -------------------------------------------------------------------
ref = np.clip(img, 0, 1)
flow = np.where(yy < HZ, np.arctan2(yy - SUNY, xx - SUNX) + 0.6 * (fbm((H, W), 200, 2, rng) - 0.5) * 3, 0.3 * (fbm((H, W), 200, 2, rng) - 0.5))
painted = painterly(ref, rng, sizes=(36, 18, 10, 5), thresh=(0, 0.07, 0.06, 0.05), base_angle=flow, relief=0.3, jitter=0.05, length=4)
img = mix(painted, ref, 0.1)
img += glow(SUNX, SUNY, 50, 1.6)[..., None] * hexc('#fff3c4') * 0.4
img += glow(SUNX, SUNY, 300, 1.4)[..., None] * hexc('#ffc864') * 0.1
img = bloom(img, 0.82, (8, 36), (0.16, 0.16))
img = np.clip(img, 0, 1) ** 1.05
finish(img, '06-autumn-forest-path', rng, vignette=0.3)
