ExperimentsFable 5.2 Python art (30 images)

Painterly still life, an image drawn with Python code by Fable 5.2. Opens the full-size image in a new tab.
#!/usr/bin/env python3
"""21 Painterly still life.

A fruit bowl, a bottle and loose fruit on a table in soft window light.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Step 1: a small 3D scene made of distance formulas is ray-marched with soft
shadows (the "underpainting"). Step 2: the picture is repainted with
brush strokes that follow the forms, and the strokes get thick-paint relief.
Run: .venv/bin/python scripts/21-painterly-still-life.py
"""
import os, time, math
import numpy as np
from PIL import Image
from scipy import ndimage as ndi

W, H = 1600, 2000
RW, RH = 800, 1000            # the 3D scene is rendered at half size, then painted at full size
SEED = 21
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '21-painterly-still-life.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 norm(v):
    return v / (np.linalg.norm(v, axis=-1, keepdims=True) + 1e-9)


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


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


def wob(p, f, s=0.0):
    """Cheap smooth 3D pattern in -1..1 (sum of sines), used for skin colour variation."""
    x, y, z = p[:, 0] * f, p[:, 1] * f, p[:, 2] * f
    return (np.sin(x * 1.7 + 1.3 * np.sin(y * 1.1 + s) + s) + np.sin(y * 2.3 + 1.7 * np.sin(z * 1.3 + 2 * s))
            + np.sin(z * 1.9 + 1.1 * np.sin(x * 2.1 + 3 * s))) / 3.0


# ----------------------------------------------------------------------------
# Scene: distance formulas
# ----------------------------------------------------------------------------
TABLE, WALL, BOWL, ORANGE, APPLE_R, APPLE_G, PEAR, LEMON, GRAPE, BOTTLE, STEM, PLUM = range(12)
BOWL_C = np.array([0.15, 1.50, 0.0], F)
BOWL_R = 1.45
RIM_Y = 1.22
TABLE_Z = 2.75

ORANGES = [(-0.72, 1.32, 0.45, 0.49), (0.12, 1.98, -0.08, 0.46)]
APPLES_R = [(0.32, 1.40, 0.62, 0.52)]
APPLES_G = [(0.92, 1.50, -0.38, 0.50)]
PLUMS = [(0.42, 0.29, 1.95, 0.29), (0.98, 0.27, 2.2, 0.27)]

# grapes: a hanging bunch that spills over the rim of the bowl
grng = np.random.default_rng(5)
GRAPES = []
spine = np.array([[0.80, 1.50, 0.55], [1.24, 1.42, 0.95], [1.47, 1.0, 1.16], [1.5, 0.55, 1.25], [1.58, 0.17, 1.42]])
tries = 0
while len(GRAPES) < 46 and tries < 4000:
    tries += 1
    u = grng.random()
    k = u * (len(spine) - 1)
    i = min(int(k), len(spine) - 2)
    c = spine[i] + (spine[i + 1] - spine[i]) * (k - i)
    rad = 0.24 * math.sin(math.pi * (0.10 + 0.75 * u)) + 0.04
    c = c + grng.normal(0, 1, 3) * rad * 0.5
    r = grng.uniform(0.115, 0.145)
    c[1] = max(c[1], r + 0.005)
    if all(np.linalg.norm(c - g[:3]) > 0.82 * (r + g[3]) for g in GRAPES):
        GRAPES.append((c[0], c[1], c[2], r))
GRAPES = np.array(GRAPES, F)


def sd_sphere(p, c):
    return np.sqrt((p[:, 0] - c[0]) ** 2 + (p[:, 1] - c[1]) ** 2 + (p[:, 2] - c[2]) ** 2) - c[3]


def sd_apple(p, c):
    # a fat ring shape: gives the dimples at the top and the bottom of an apple
    x, y, z, r = c
    q = np.sqrt((p[:, 0] - x) ** 2 + (p[:, 2] - z) ** 2) - 0.2 * r
    return np.sqrt(q * q + ((p[:, 1] - y) * 1.08) ** 2) - 0.8 * r


def sd_pear(p):
    a = sd_sphere(p, (-0.3, 1.52, -0.55, 0.52))
    b = sd_sphere(p, (-0.36, 2.2, -0.6, 0.27))
    k = 0.45
    h = np.clip(0.5 + 0.5 * (b - a) / k, 0, 1)
    return b + (a - b) * h - k * h * (1 - h)


LEM_C = np.array([-1.25, 0.31, 1.62], F)
LEM_A = 0.5


def sd_lemon(p):
    ca, sa = math.cos(LEM_A), math.sin(LEM_A)
    x = (p[:, 0] - LEM_C[0]) * ca + (p[:, 2] - LEM_C[2]) * sa
    z = -(p[:, 0] - LEM_C[0]) * sa + (p[:, 2] - LEM_C[2]) * ca
    y = p[:, 1] - LEM_C[1]
    body = (np.sqrt((x / 0.46) ** 2 + (y / 0.31) ** 2 + (z / 0.31) ** 2) - 1) * 0.31
    tip = np.sqrt((np.abs(x) - 0.44) ** 2 + y * y + z * z) - 0.075
    k = 0.12
    h = np.clip(0.5 + 0.5 * (tip - body) / k, 0, 1)
    return tip + (body - tip) * h - k * h * (1 - h)


BOT = (-1.78, -1.05)


def sd_bottle(p):
    r = np.sqrt((p[:, 0] - BOT[0]) ** 2 + (p[:, 2] - BOT[1]) ** 2)
    y = p[:, 1]
    rad = 0.43 - 0.29 * smooth(1.85, 2.45, y) + 0.035 * smooth(3.3, 3.34, y) * (1 - smooth(3.42, 3.46, y))
    d = np.maximum(r - rad, y - 3.5)
    return d * 0.8


def sd_capsule(p, a, b, r):
    a = np.asarray(a, F); b = np.asarray(b, F)
    pa = p - a
    ba = b - a
    h = np.clip((pa @ ba) / (ba @ ba), 0, 1)
    return np.linalg.norm(pa - h[:, None] * ba, axis=1) - r


def sdf(p, want_id=False):
    x, y, z = p[:, 0], p[:, 1], p[:, 2]
    d = np.maximum(y, z - TABLE_Z)
    ids = np.zeros(len(p), np.int8) if want_id else None

    def add(dn, i):
        nonlocal d, ids
        if want_id:
            ids = np.where(dn < d, np.int8(i), ids)
        d = np.minimum(d, dn)

    add(z + 3.6, WALL)
    q = np.sqrt((x - BOWL_C[0]) ** 2 + (y - BOWL_C[1]) ** 2 + (z - BOWL_C[2]) ** 2)
    shell = np.maximum(np.abs(q - BOWL_R) - 0.045, y - RIM_Y)
    foot = np.maximum(np.sqrt((x - BOWL_C[0]) ** 2 + z * z) - 0.62, y - 0.14)
    add(np.minimum(shell, foot), BOWL)
    for c in ORANGES:
        add(sd_sphere(p, c), ORANGE)
    for c in APPLES_R:
        add(sd_apple(p, c), APPLE_R)
    for c in APPLES_G:
        add(sd_apple(p, c), APPLE_G)
    for c in PLUMS:
        add(sd_sphere(p, c), PLUM)
    add(sd_pear(p), PEAR)
    add(sd_lemon(p), LEMON)
    # grapes: only evaluate near the bunch
    near = (x > 0.35) & (z > 0.1) & (y < 2.1)
    if near.any():
        pn = p[near]
        dg = np.full(len(pn), 9.0, F)
        for g in GRAPES:
            dg = np.minimum(dg, sd_sphere(pn, g))
        full = np.full(len(p), 0.25, F)
        full[near] = dg
        add(full, GRAPE)
    add(sd_bottle(p), BOTTLE)
    st = sd_capsule(p, (0.32, 1.78, 0.62), (0.40, 2.02, 0.66), 0.022)
    st = np.minimum(st, sd_capsule(p, (0.92, 1.87, -0.38), (0.86, 2.1, -0.4), 0.022))
    st = np.minimum(st, sd_capsule(p, (-0.36, 2.44, -0.6), (-0.27, 2.68, -0.62), 0.024))
    st = np.minimum(st, sd_capsule(p, (0.82, 1.52, 0.57), (0.6, 1.66, 0.4), 0.03))
    add(st, STEM)
    return (d, ids) if want_id else d


def march(ro, rd, tmax=30.0, steps=110):
    n = len(rd)
    t = np.zeros(n, F)
    act = np.arange(n)
    for _ in range(steps):
        p = ro + rd[act] * t[act, None]
        d = sdf(p)
        t[act] += d * 0.95
        done = (d < 0.0015) | (t[act] > tmax)
        act = act[~done]
        if len(act) == 0:
            break
    return t


def normal_at(p):
    e = 0.003
    k = np.array([[1, -1, -1], [-1, -1, 1], [-1, 1, -1], [1, 1, 1]], F)
    n = np.zeros_like(p)
    for kk in k:
        n += kk[None, :] * sdf(p + kk[None, :] * e)[:, None]
    return norm(n)


def soft_shadow(p, n, L, k=7.0, steps=48):
    N = len(p)
    res = np.ones(N, F)
    t = np.full(N, 0.03, F)
    ro = p + n * 0.012
    act = np.arange(N)
    for _ in range(steps):
        d = sdf(ro[act] + L[None, :] * t[act, None])
        res[act] = np.minimum(res[act], k * d / t[act])
        t[act] += np.clip(d, 0.015, 0.35)
        done = (res[act] < 0.002) | (t[act] > 9.0)
        act = act[~done]
        if len(act) == 0:
            break
    return np.clip(res, 0, 1)


def render_scene():
    cam = np.array([0.6, 2.35, 9.2], F)
    tgt = np.array([-0.08, 1.50, 0.0], F)
    fw = norm(tgt - cam)
    rt = norm(np.cross(fw, np.array([0, 1, 0], F)))
    up = np.cross(rt, fw)
    yy, xx = np.mgrid[0:RH, 0:RW].astype(F)
    tanh = 0.246
    u = (xx + 0.5 - RW / 2) / (RW / 2) * tanh
    v = -(yy + 0.5 - RH / 2) / (RW / 2) * tanh
    rd = norm(fw[None, :] + u.reshape(-1, 1) * rt[None, :] + v.reshape(-1, 1) * up[None, :]).astype(F)
    t = march(cam, rd)
    p = cam + rd * t[:, None]
    d, ids = sdf(p, True)
    n = normal_at(p)
    print('  march done %.1fs' % (time.time() - T0))

    L = norm(np.array([-0.86, 0.50, 0.24], F))           # light comes from a window on the left
    sh = soft_shadow(p, n, L)
    # the window: a soft bright rectangle with glazing bars, projected along the light direction
    a = norm(np.cross(L, np.array([0, 1, 0], F)))
    b = np.cross(a, L)
    wu = p @ a
    wv = p @ b
    win = smooth(-3.3, -1.9, wu) * (1 - smooth(1.9, 3.3, wu)) * smooth(-1.5, -0.6, wv) * (1 - smooth(2.6, 3.9, wv))
    bars = 1 - 0.55 * np.exp(-((wu - 0.9) / 0.14) ** 2) - 0.45 * np.exp(-((wv - 2.25) / 0.12) ** 2)
    onwall = ids == WALL
    # on the wall the window shows as a slanted patch of light with the shadow of the glazing bars
    sx = p[:, 0] - 0.55 * (p[:, 1] - 3.0)
    patch = smooth(-4.6, -3.9, sx) * (1 - smooth(-0.9, 0.5, sx)) * smooth(1.2, 1.9, p[:, 1] + 0.25 * p[:, 0]) \
        * (1 - smooth(5.2, 6.4, p[:, 1] + 0.25 * p[:, 0]))
    wbars = 1 - 0.6 * np.exp(-((sx + 2.55) / 0.09) ** 2) - 0.5 * np.exp(-((p[:, 1] + 0.25 * p[:, 0] - 3.9) / 0.08) ** 2)
    win = np.where(onwall, patch * wbars * 2.6, win)
    # ambient occlusion: how open is the space above the surface
    ao = np.ones(len(p), F)
    for i, hh in enumerate((0.06, 0.15, 0.32, 0.6)):
        ao -= (hh - sdf(p + n * hh)) * (0.9 / (i + 1.0)) / hh * 0.28
    ao = np.clip(ao, 0.15, 1)
    print('  light done %.1fs' % (time.time() - T0))

    ndl = np.clip(n @ L, 0, 1)
    wrap = np.clip((n @ L + 0.35) / 1.35, 0, 1)
    V = -rd
    Hh = norm(L[None, :] + V)
    ndh = np.clip(np.sum(n * Hh, 1), 0, 1)
    fres = (1 - np.clip(np.sum(n * V, 1), 0, 1)) ** 3

    alb = np.zeros((len(p), 3), F)
    spec = np.zeros(len(p), F)
    gloss = np.full(len(p), 30.0, F)
    sss = np.zeros(len(p), F)

    def col(*c):
        return np.array(c, F)

    m = ids == TABLE
    pm = p[m]
    top = n[m][:, 1] > 0.5
    grain = 0.5 + 0.5 * np.sin(pm[:, 2] * 9 + 3 * np.sin(pm[:, 0] * 0.8) + 2.0 * wob(pm, 1.3))
    wood = col(0.23, 0.125, 0.065)[None, :] * (0.75 + 0.5 * grain[:, None]) * (1 + 0.2 * wob(pm, 0.6, 2.0)[:, None])
    wood = np.where(top[:, None], wood, wood * 0.55)
    # linen cloth that lies under the bowl and hangs over the front edge
    cx = pm[:, 0] + 0.35 * np.sin(pm[:, 2] * 0.9 + 1.0) + 0.1 * np.sin(pm[:, 2] * 2.7)
    edge_l = -0.95 + 0.5 * (pm[:, 2] - 1.0) * -0.25
    cloth = smooth(edge_l - 0.02, edge_l + 0.02, cx) * (1 - smooth(3.05, 3.09, cx + 0.25 * pm[:, 2]))
    cloth *= np.where(top, smooth(-1.9, -1.86, pm[:, 2] + 0.2 * np.sin(pm[:, 0] * 1.4)), 1.0)
    hem = -1.15 + 0.1 * np.sin(pm[:, 0] * 2.1) - 0.35 * smooth(1.5, 3.2, pm[:, 0])
    cloth *= np.where(top, 1.0, smooth(hem - 0.02, hem + 0.02, pm[:, 1]))
    fold = np.sin(pm[:, 0] * 3.1 + 1.6 * np.sin(pm[:, 2] * 0.8 + pm[:, 1] * 0.6) + 0.8) * 0.5 \
        + 0.5 * np.sin(pm[:, 0] * 7.3 - pm[:, 2] * 2.2 + 0.5 * pm[:, 1])
    fold_top = np.sin(pm[:, 0] * 2.2 - pm[:, 2] * 3.0 + 1.5 * np.sin(pm[:, 0] * 1.3)) * 0.5 + 0.3 * np.sin(pm[:, 2] * 6 + pm[:, 0] * 4)
    fold = np.where(top, fold_top * 0.8, fold)
    linen = col(0.80, 0.76, 0.66)[None, :] * (0.80 + 0.2 * fold[:, None])
    alb[m] = wood * (1 - cloth[:, None]) + linen * cloth[:, None]
    spec[m] = 0.10 * (1 - cloth)
    # folds change how much light the cloth catches
    foldlight = np.ones(len(p), F)
    foldlight[m] = np.clip(1 + cloth * 0.95 * fold, 0.1, 2)
    cloth_full = np.zeros(len(p), F)
    cloth_full[m] = cloth

    m = ids == WALL
    pm = p[m]
    alb[m] = col(0.40, 0.35, 0.24)[None, :] * (1 + 0.16 * wob(pm, 0.45, 1.0)[:, None] + 0.08 * wob(pm, 1.7, 4.0)[:, None])

    m = ids == BOWL
    pm = p[m]
    ang = np.arctan2(pm[:, 2] - BOWL_C[2], pm[:, 0] - BOWL_C[0])
    yb = pm[:, 1]
    band = smooth(1.02, 1.05, yb) * (1 - smooth(1.14, 1.17, yb))
    band2 = smooth(0.33, 0.35, yb) * (1 - smooth(0.4, 0.42, yb))
    motif = smooth(0.25, 0.4, np.abs(np.sin(ang * 9))) * smooth(0.52, 0.56, yb) * (1 - smooth(0.92, 0.96, yb))
    motif *= smooth(0.12, 0.2, np.abs(np.sin(ang * 9) * 0.5 - (yb - 0.74) * 2.2)) < 0.5
    blue = np.clip(band + band2 + 0.9 * motif, 0, 1)
    alb[m] = col(0.86, 0.85, 0.80)[None, :] * (1 - blue[:, None]) + col(0.10, 0.22, 0.50)[None, :] * blue[:, None]
    spec[m] = 0.55
    gloss[m] = 90

    m = ids == ORANGE
    pm = p[m]
    alb[m] = col(0.93, 0.44, 0.05)[None, :] * (1 + 0.10 * wob(pm, 3.0)[:, None]) * (1 + 0.05 * wob(pm, 40.0)[:, None])
    spec[m] = 0.18; gloss[m] = 25; sss[m] = 0.25

    m = ids == APPLE_R
    pm = p[m]
    k = smooth(-0.25, 0.5, wob(pm, 2.4, 1.0) + 0.5 * wob(pm * np.array([6, 0.6, 6], F), 1.0) + (pm[:, 1] - 1.45) * 1.2)
    alb[m] = col(0.62, 0.05, 0.05)[None, :] * (1 - k[:, None]) + col(0.82, 0.55, 0.12)[None, :] * k[:, None]
    spec[m] = 0.45; gloss[m] = 60; sss[m] = 0.1

    m = ids == APPLE_G
    pm = p[m]
    k = smooth(-0.4, 0.6, wob(pm, 2.0, 3.0))
    alb[m] = col(0.42, 0.56, 0.10)[None, :] * (1 - k[:, None]) + col(0.68, 0.70, 0.18)[None, :] * k[:, None]
    spec[m] = 0.4; gloss[m] = 55; sss[m] = 0.1

    m = ids == PEAR
    pm = p[m]
    k = smooth(-0.3, 0.6, wob(pm, 1.8, 5.0) + (pm[:, 0] + 0.3) * 0.8)
    alb[m] = col(0.74, 0.66, 0.16)[None, :] * (1 - k[:, None]) + col(0.72, 0.36, 0.12)[None, :] * k[:, None]
    alb[m] *= (1 - 0.12 * (wob(pm, 30.0) > 0.55))[:, None]
    spec[m] = 0.2; gloss[m] = 30; sss[m] = 0.15

    m = ids == LEMON
    pm = p[m]
    alb[m] = col(0.95, 0.78, 0.08)[None, :] * (1 + 0.07 * wob(pm, 5.0)[:, None])
    spec[m] = 0.2; gloss[m] = 25; sss[m] = 0.25

    m = ids == GRAPE
    pm = p[m]
    # every grape gets its own tint; find the nearest grape
    dd = np.stack([sd_sphere(pm, g) for g in GRAPES], 1)
    gi = dd.argmin(1)
    tint = np.random.default_rng(9).random(len(GRAPES)).astype(F)[gi]
    base = col(0.07, 0.015, 0.10)[None, :] * (1 - tint[:, None]) + col(0.17, 0.025, 0.09)[None, :] * tint[:, None]
    bloomk = 0.13 * (0.5 + 0.5 * wob(pm, 9.0))                   # the pale waxy film on grapes
    alb[m] = base * (1 - bloomk[:, None]) + col(0.50, 0.52, 0.66)[None, :] * bloomk[:, None]
    spec[m] = 0.7; gloss[m] = 90; sss[m] = 0.2

    m = ids == PLUM
    pm = p[m]
    bloomk = 0.3 * (0.5 + 0.5 * wob(pm, 6.0, 2.0))
    alb[m] = col(0.085, 0.03, 0.13)[None, :] * (1 - bloomk[:, None]) + col(0.30, 0.34, 0.52)[None, :] * bloomk[:, None]
    spec[m] = 0.4; gloss[m] = 45; sss[m] = 0.2

    m = ids == BOTTLE
    pm = p[m]
    alb[m] = col(0.012, 0.035, 0.018)[None, :]
    lab = smooth(0.75, 0.78, pm[:, 1]) * (1 - smooth(1.5, 1.53, pm[:, 1])) * (pm[:, 2] > BOT[1] + 0.1)
    lab = lab * (1 - 0.45 * (np.abs(pm[:, 1] - 1.125) > 0.3) * (np.abs(pm[:, 1] - 1.125) < 0.33))
    alb[m] = alb[m] * (1 - lab[:, None]) + col(0.62, 0.52, 0.34)[None, :] * lab[:, None] * (1 + 0.08 * wob(pm, 8.0)[:, None])
    spec[m] = 0.9 * (1 - 0.8 * lab); gloss[m] = 140

    m = ids == STEM
    alb[m] = col(0.16, 0.10, 0.05)[None, :]

    sun = np.array([1.0, 0.92, 0.78], F) * 2.9
    sky = np.array([0.30, 0.37, 0.50], F) * 0.17
    bounce = np.array([0.42, 0.26, 0.13], F) * 0.20
    direct = (ndl * (1 - sss) + wrap * sss) * np.minimum(sh + sss * 0.25, 1) * win * foldlight
    light = direct[:, None] * sun[None, :] \
        + ((0.55 + 0.45 * n[:, 1]) * ao)[:, None] * sky[None, :] \
        + (np.clip(0.5 - 0.5 * n[:, 1], 0, 1) * ao)[:, None] * bounce[None, :] \
        + (np.clip(n[:, 0] * 0.8 + 0.2, 0, 1) * ao * 0.10)[:, None] * np.array([0.5, 0.42, 0.34], F)[None, :]
    c = alb * light
    # translucent fruit: a little light shines through at grazing edges
    c += alb * (sss * fres * win * 0.9)[:, None] * sun[None, :] * 0.5
    # highlights: the window seen in shiny skins
    c += (spec * ndh ** gloss * sh * win)[:, None] * sun[None, :] * 0.8
    c += (spec * fres * 0.25 * ao)[:, None] * sky[None, :]
    # the glass bottle: a long window reflection and a hint of light passing through
    mb = ids == BOTTLE
    refl = np.exp(-((n[mb] @ norm(np.array([-0.62, 0.0, 0.78], F)) - 0.97) / 0.03) ** 2) * (0.55 + 0.45 * wob(p[mb], 2.0))
    refl = refl * smooth(0.2, 0.5, p[mb, 1]) * (1 - 0.6 * smooth(1.8, 2.4, p[mb, 1]))
    c[mb] += refl[:, None] * np.array([0.8, 0.85, 0.7], F)[None, :] * 0.45
    c[mb] += (np.clip(n[mb, 0], 0, 1) ** 3 * 0.22)[:, None] * np.array([0.15, 0.5, 0.2], F)[None, :]

    img = c.reshape(RH, RW, 3)
    return img, ids.reshape(RH, RW), cloth_full.reshape(RH, RW)


# ----------------------------------------------------------------------------
# Brush engine
# ----------------------------------------------------------------------------
def make_sprite(length, width, ang, r):
    S = int(length + 6) | 1
    yy, xx = np.mgrid[0:S, 0:S].astype(F) - S // 2
    ca, sa = math.cos(ang), math.sin(ang)
    u = xx * ca + yy * sa
    v = -xx * sa + yy * ca
    un = u / (length / 2)
    vn = v / (width / 2)
    nb = max(4, int(width * 1.2))
    bn = ndi.gaussian_filter1d(r.random(nb + 8).astype(F), 1.0)
    bn = (bn - bn.min()) / (bn.max() - bn.min() + 1e-6)
    bi = np.clip(((vn * 0.5 + 0.5) * nb + 4).astype(int), 0, nb + 7)
    bristle = bn[bi]
    endk = 1 - smooth(0.55, 1.0, np.abs(un) + 0.25 * (bristle - 0.5))
    a = endk * (1 - smooth(0.7, 1.0, np.abs(vn)))
    dry = smooth(0.1, 1.0, un) * smooth(0.45, 0.8, bristle)
    a = a * (1 - 0.75 * dry)
    hgt = a * (0.55 + 0.45 * bristle) + 0.35 * a * smooth(0.5, 0.9, np.abs(vn))
    return a.astype(F), hgt.astype(F)


def paint(under, r, layers, detail=None, flow=None):
    """Repaint `under` (h, w, 3) with brush strokes. Returns the picture and a paint height map."""
    h, w = under.shape[:2]
    M = 80
    canvas = np.zeros((h + 2 * M, w + 2 * M, 3), F)
    canvas[M:-M, M:-M] = ndi.gaussian_filter(under, (30, 30, 0)) * 0.9
    hmap = np.zeros((h + 2 * M, w + 2 * M), F)
    lum = under @ np.array([0.3, 0.5, 0.2], F)
    ls = ndi.gaussian_filter(lum, 5)
    gx = ndi.sobel(ls, 1)
    gy = ndi.sobel(ls, 0)
    # structure tensor: smooth the edge direction over a neighbourhood
    jxx = ndi.gaussian_filter(gx * gx, 10)
    jyy = ndi.gaussian_filter(gy * gy, 10)
    jxy = ndi.gaussian_filter(gx * gy, 10)
    theta = 0.5 * np.arctan2(2 * jxy, jxx - jyy) + math.pi / 2     # along the edge
    cohere = np.sqrt((jxx - jyy) ** 2 + 4 * jxy ** 2)
    cohere = smooth(0.0, np.percentile(cohere, 80), cohere)
    if flow is None:
        flow = (fbm((h, w), 260, 3, r) - 0.5) * 5.0
    theta = np.where(cohere > 0.12, theta, flow)
    NA = 24
    for li, (length, width, count, opac, sig) in enumerate(layers):
        ref = ndi.gaussian_filter(under, (sig, sig, 0))
        sprites = [[make_sprite(length * s, width * s, math.pi * k / NA, r) for k in range(NA)] for s in (0.8, 1.0, 1.25)]
        if li == 0:
            n = count
            xs = r.uniform(0, w, n)
            ys = r.uniform(0, h, n)
        else:
            err = np.abs(canvas[M:-M, M:-M] - under).sum(-1)
            err = ndi.gaussian_filter(err, width * 0.6) + 0.004
            if detail is not None:
                err = err * ((0.5, 0.5, 0.4, 0.2, 0.06, 0.03)[li] + detail)
            pr = (err ** 1.5).ravel().astype(np.float64)
            pr /= pr.sum()
            idx = r.choice(h * w, size=count, p=pr)
            ys, xs = np.divmod(idx, w)
            xs = xs + r.uniform(-0.5, 0.5, count)
            ys = ys + r.uniform(-0.5, 0.5, count)
            n = count
        xi = np.clip(xs.astype(int), 0, w - 1)
        yi = np.clip(ys.astype(int), 0, h - 1)
        jit = 0.035 if li < 2 else 0.06
        cols = ref[yi, xi] * (1 + r.normal(0, jit, (n, 1))) + r.normal(0, jit * 0.25, (n, 3))
        cols = np.clip(cols, 0, 1.2).astype(F)
        angs = theta[yi, xi] + r.normal(0, 0.22, n)
        ak = np.round(angs / (math.pi / NA)).astype(int) % NA
        sk = r.integers(0, 3, n)
        for i in range(n):
            a, hg = sprites[sk[i]][ak[i]]
            S = a.shape[0]
            y0 = int(ys[i]) + M - S // 2
            x0 = int(xs[i]) + M - S // 2
            if y0 < 0 or x0 < 0 or y0 + S > h + 2 * M or x0 + S > w + 2 * M:
                continue
            ao = a * opac
            cv = canvas[y0:y0 + S, x0:x0 + S]
            cv += (cols[i] - cv) * ao[..., None]
            hv = hmap[y0:y0 + S, x0:x0 + S]
            hv += (hg * (0.6 + 0.4 * width / layers[0][1]) + 0.15 * hv - hv) * ao
        print('  layer %d (%d strokes) %.1fs' % (li, n, time.time() - T0))
    return canvas[M:-M, M:-M], hmap[M:-M, M:-M]


def relief(img, hmap, r, strength=1.0):
    hs = ndi.gaussian_filter(hmap, 0.8)
    gx = ndi.sobel(hs, 1)
    gy = ndi.sobel(hs, 0)
    shade = np.clip(-(gx * -0.7 + gy * -0.7) * 0.22 * strength, -0.22, 0.30)
    h, w = hmap.shape
    yy, xx = np.mgrid[0:h, 0:w].astype(F)
    weave = 0.5 * np.sin(xx * 1.9) * np.sin(yy * 1.9) + (r.random((h, w)).astype(F) - 0.5)
    out = img * (1 + shade[..., None]) + np.clip(shade, 0, 1)[..., None] * 0.05
    return out * (1 + 0.018 * weave[..., None])


def main():
    img, ids, cloth = render_scene()
    # tone: gentle shoulder so the bright cloth and highlights do not clip
    img = 1 - np.exp(-img * 1.35)
    img = np.clip(img, 0, 1) ** (1 / 2.2)
    img = img * img * (3 - 2 * img) * 0.55 + img * 0.45          # more contrast
    g = img.mean(-1, keepdims=True)
    img = np.clip(g + (img - g) * 1.22, 0, 1)                    # richer colour
    # warm dark glaze, like an old varnished oil painting
    img = img * np.array([1.02, 1.0, 0.93], F)
    under = np.stack([ndi.zoom(img[..., i], 2, order=3) for i in range(3)], -1).astype(F)
    under = np.clip(under, 0, 1)
    obj = (ids != WALL) & (ids != TABLE)
    detail = ndi.zoom(ndi.gaussian_filter(obj.astype(F), 4) + 0.5 * cloth, 2, order=1)
    print('scene %.1fs' % (time.time() - T0))
    layers = [  # length, width, count, opacity, colour blur
        (190, 78, 2200, 0.95, 16),
        (120, 46, 5000, 0.93, 9),
        (70, 27, 11000, 0.92, 5),
        (40, 15, 22000, 0.9, 2.5),
        (22, 8.5, 30000, 0.9, 1.3),
        (12, 4.5, 22000, 0.85, 0.7),
    ]
    canvas, hmap = paint(under, rng, layers, detail=detail)
    out = relief(canvas, hmap, rng)
    yy, xx = np.mgrid[0:H, 0:W].astype(F)
    vig = 1 - 0.30 * smooth(0.55, 1.25, np.hypot((xx - W * 0.47) / W, (yy - H * 0.55) / H) * 1.6)
    out = np.clip(out * vig[..., None], 0, 1)
    Image.fromarray((out * 255 + 0.5).astype(np.uint8)).save(OUT)
    print('saved %s  %.1fs' % (os.path.abspath(OUT), time.time() - T0))


if __name__ == '__main__':
    main()