#!/usr/bin/env python3
"""load -- 2026-11-03

Carries out one wall-drawing instruction:

    Black ink. On the upper half of the wall lay a dozen short loose strokes at
    chance places, each with a chance load, some barely wet, some flooding. Each
    drips as far as its load carries, the wettest to the floor. A drip that
    crosses a lower stroke blooms into it.

Run from inside this directory:  python3 champion.py
Writes renders-champion/render-1.png, square, 2500 px.
"""

import math
import os

import numpy as np
from scipy import ndimage
from PIL import Image

S = 2500
SEED = int(os.environ.get("LOAD_SEED", "5"))
OUT = os.path.join("renders-champion", "render-1.png")

N_STROKES = 12          # "a dozen"
UPPER = 0.5             # "the upper half of the wall"

rng = np.random.default_rng(SEED)

ink = np.zeros((S, S), np.float32)
scratch = np.zeros((S, S), np.float32)
_dirty = None


# ----------------------------------------------------------------- texture

def fbm(shape, base, octaves, gain=0.5, rg=None):
    rg = rg if rg is not None else rng
    out = np.zeros(shape, np.float32)
    amp, tot, res = 1.0, 0.0, base
    for _ in range(octaves):
        g = rg.random((res + 2, res + 2)).astype(np.float32)
        z = ndimage.zoom(g, (shape[0] / res, shape[1] / res), order=3)
        z = z[: shape[0], : shape[1]]
        if z.shape != tuple(shape):
            z = np.pad(z, ((0, shape[0] - z.shape[0]), (0, shape[1] - z.shape[1])),
                       mode="edge")
        out += amp * z
        tot += amp
        amp *= gain
        res *= 2
    out /= tot
    out -= out.min()
    out /= max(float(out.max()), 1e-6)
    return out


TOOTH = fbm((S, S), 48, 6, 0.56)          # plaster tooth: granulates the ink
MOTTLE = fbm((S, S), 6, 4, 0.5)           # faint unevenness of the wall itself


def noise1d(n, smooth, rg=None, seedless=False):
    rg = rg if rg is not None else rng
    v = rg.normal(0.0, 1.0, max(n, 4)).astype(np.float32)
    v = ndimage.gaussian_filter1d(v, smooth, mode="nearest")
    m = float(np.max(np.abs(v)))
    return v / (m + 1e-6)


# --------------------------------------------------------------- stamping
# Each mark (one stroke, one drip, one bloom) is built in `scratch` with a
# max-blend so a dense polyline does not accumulate against itself, then added
# into `ink`.  Ink therefore piles up between marks but not within one.

def layer_begin():
    global _dirty
    _dirty = None


def _touch(xa, xb, ya, yb):
    global _dirty
    if _dirty is None:
        _dirty = [xa, xb, ya, yb]
    else:
        _dirty[0] = min(_dirty[0], xa)
        _dirty[1] = max(_dirty[1], xb)
        _dirty[2] = min(_dirty[2], ya)
        _dirty[3] = max(_dirty[3], yb)


def seg(x0, y0, x1, y1, r0, r1, amount, soft=1.7, tex=0.0):
    pad = max(r0, r1) + soft + 1.0
    xa = max(0, int(math.floor(min(x0, x1) - pad)))
    xb = min(S, int(math.ceil(max(x0, x1) + pad)) + 1)
    ya = max(0, int(math.floor(min(y0, y1) - pad)))
    yb = min(S, int(math.ceil(max(y0, y1) + pad)) + 1)
    if xa >= xb or ya >= yb:
        return
    X = np.arange(xa, xb, dtype=np.float32)[None, :]
    Y = np.arange(ya, yb, dtype=np.float32)[:, None]
    dx, dy = x1 - x0, y1 - y0
    L2 = dx * dx + dy * dy
    if L2 < 1e-9:
        t = np.zeros((yb - ya, xb - xa), np.float32)
        d = np.sqrt((X - x0) ** 2 + (Y - y0) ** 2)
    else:
        t = np.clip(((X - x0) * dx + (Y - y0) * dy) / L2, 0.0, 1.0)
        d = np.sqrt((X - (x0 + t * dx)) ** 2 + (Y - (y0 + t * dy)) ** 2)
    r = r0 + t * (r1 - r0)
    a = np.clip(0.5 + (r - d) / soft, 0.0, 1.0) * amount
    if tex > 0.0:
        a *= (1.0 - tex) + 2.0 * tex * TOOTH[ya:yb, xa:xb]
    np.maximum(scratch[ya:yb, xa:xb], a, out=scratch[ya:yb, xa:xb])
    _touch(xa, xb, ya, yb)


def dot(x, y, r, amount, soft=1.7, tex=0.0):
    seg(x, y, x, y, r, r, amount, soft, tex)


def blob(cx, cy, rad, amount, rough=0.22, soft=2.0, tex=0.0):
    """A disc with a wandering edge -- how a wet stain actually stops."""
    h = [(float(rng.integers(2, 4)), float(rng.uniform(0, 6.283)),
          1.0 + float(rng.random())),
         (float(rng.integers(4, 7)), float(rng.uniform(0, 6.283)),
          0.55 * float(rng.random())),
         (float(rng.integers(7, 11)), float(rng.uniform(0, 6.283)),
          0.22 * float(rng.random()))]
    wsum = sum(w for _, _, w in h) + 1e-6
    # a small stain cannot crenellate: its edge is only a few pixels long
    rough = rough * min(1.0, rad / 26.0)
    pad = rad * (1.0 + rough) + soft + 2.0
    xa = max(0, int(cx - pad))
    xb = min(S, int(cx + pad) + 1)
    ya = max(0, int(cy - pad))
    yb = min(S, int(cy + pad) + 1)
    if xa >= xb or ya >= yb:
        return
    X = np.arange(xa, xb, dtype=np.float32)[None, :] - cx
    Y = np.arange(ya, yb, dtype=np.float32)[:, None] - cy
    ang = np.arctan2(Y, X)
    m = np.zeros_like(ang)
    for k, p, w in h:
        m += (w / wsum) * np.sin(k * ang + p)
    m = rad * (1.0 + rough * m)
    d = np.sqrt(X * X + Y * Y)
    a = np.clip(0.5 + (m - d) / soft, 0.0, 1.0) * amount
    if tex > 0.0:
        a *= (1.0 - tex) + 2.0 * tex * TOOTH[ya:yb, xa:xb]
    np.maximum(scratch[ya:yb, xa:xb], a, out=scratch[ya:yb, xa:xb])
    _touch(xa, xb, ya, yb)


def layer_commit(scale=1.0):
    if _dirty is None:
        return
    xa, xb, ya, yb = _dirty
    sl = (slice(ya, yb), slice(xa, xb))
    if scale == 1.0:
        ink[sl] += scratch[sl]
    else:
        ink[sl] += scratch[sl] * scale
    scratch[sl] = 0.0
    layer_begin()


# ----------------------------------------------------------------- strokes
# A stroke is a short loose brush mark: a gently bent path, a bristle bundle
# whose hairs separate when the brush is nearly dry and merge when it floods.

class Stroke:
    __slots__ = ("P", "R", "load", "tan", "idx")


def make_stroke(cx, cy, load):
    st = Stroke()
    ang = math.radians(float(rng.normal(0.0, 19.0)))
    ang = max(-0.70, min(0.70, ang))
    size = 0.68 + 0.95 * float(rng.random()) ** 1.25     # no two brushfuls alike
    length = (0.055 + 0.105 * float(rng.random())) * S * (0.84 + 0.30 * load) * size
    ux, uy = math.cos(ang), math.sin(ang)
    vx, vy = -uy, ux
    bend = float(rng.normal(0.0, 0.085)) * length
    n = 150
    t = np.linspace(0.0, 1.0, n, dtype=np.float32)
    wob = noise1d(n, 16.0) * (0.022 * length)
    off = bend * np.sin(np.pi * t) + wob
    px = cx + (t - 0.5) * length * ux + off * vx
    py = cy + (t - 0.5) * length * uy + off * vy
    # the brush lands, presses, and is dragged off: a blunt entry, a long tail
    a = 0.14 + 0.30 * float(rng.random())
    b = 0.55 + 1.35 * float(rng.random())
    if rng.random() < 0.5:
        a, b = b, a
    prof = (t ** a) * ((1.0 - t) ** b)
    prof = prof / max(float(prof.max()), 1e-6)
    press = 0.72 + 0.52 * (0.5 + 0.5 * noise1d(n, 6.0))
    rbase = (0.0042 + 0.0118 * load ** 0.85) * S * (0.55 + 0.55 * size)
    rr = rbase * (0.26 + 0.74 * prof) * press * (1.0 + 0.26 * noise1d(n, 5.0))
    st.P = np.stack([px, py], axis=1).astype(np.float32)
    st.R = np.maximum(rr, 1.2).astype(np.float32)
    st.load = load
    tg = np.gradient(st.P, axis=0)
    tg /= (np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6)
    st.tan = tg.astype(np.float32)
    return st


def draw_stroke(st):
    load = st.load
    P, R = st.P, st.R
    n = len(P)
    t = np.linspace(0.0, 1.0, n, dtype=np.float32)
    dry = (1.0 - load) ** 1.15
    amount = 0.26 + 2.30 * load ** 0.78
    nb = 7 + int(round(9.0 * dry))                   # a dry brush shows its hairs
    frac = 0.16 + 0.70 * load                        # hair thickness / stroke
    nx = -st.tan[:, 1]
    ny = st.tan[:, 0]
    edge = np.clip(np.minimum(t, 1.0 - t) / 0.15, 0.0, 1.0)
    layer_begin()
    for k in range(nb):
        u0 = (-1.0 + 2.0 * (k + 0.5) / nb) * (1.0 - frac)
        splay = noise1d(n, 13.0) * (0.26 + 0.20 * dry)
        u = u0 + splay
        g = 0.5 + 0.5 * noise1d(n, 4.5 + 9.0 * float(rng.random()))
        keep = np.clip(1.0 - dry * (1.35 - 1.10 * g), 0.0, 1.0)
        keep *= np.clip(edge * 1.25 + (g - 0.5) * 0.9, 0.0, 1.0)
        hair_a = amount * (0.60 + 0.52 * float(rng.random()))
        hr = np.maximum(R * frac * (0.78 + 0.34 * float(rng.random()))
                        * (1.0 + 0.3 * noise1d(n, 13.0)), 0.85)
        hx = P[:, 0] + u * R * nx
        hy = P[:, 1] + u * R * ny
        for i in range(n - 1):
            a = hair_a * 0.5 * (keep[i] + keep[i + 1])
            if a <= 0.02:
                continue
            seg(hx[i], hy[i], hx[i + 1], hy[i + 1], hr[i], hr[i + 1], a,
                soft=1.6, tex=0.18 + 0.40 * dry)
    # where a loaded brush dumps ink, and where the wet mark sags under it
    for _ in range(int(round(load * 2.6))):
        i = int(rng.integers(int(0.22 * n), int(0.78 * n)))
        rb = R[i] * (0.55 + 0.40 * float(rng.random()))
        blob(float(P[i, 0]), float(P[i, 1]) + R[i] * 0.30, rb,
             amount * 1.00, rough=0.30, soft=R[i] * 0.35, tex=0.10)
    if load > 0.28:
        sagamt = amount * (0.30 + 0.70 * load)
        sagn = np.clip(0.5 + 0.75 * noise1d(n, 9.0), 0.0, 1.0) ** 1.6
        for i in range(0, n - 2, 2):
            j = i + 2
            if sagn[i] < 0.06:
                continue
            dy0 = R[i] * (0.30 + 0.60 * load) * sagn[i]
            dy1 = R[j] * (0.30 + 0.60 * load) * sagn[j]
            seg(P[i, 0], P[i, 1] + dy0, P[j, 0], P[j, 1] + dy1,
                R[i] * 0.38 * (0.5 + sagn[i]), R[j] * 0.38 * (0.5 + sagn[j]),
                sagamt * (0.45 + 0.55 * sagn[i]), tex=0.12)
    layer_commit()


# ------------------------------------------------------------------- drips

def drip_points(x0, y0, reach, step=3.0):
    n = max(3, int(reach / step) + 1)
    s = np.arange(n, dtype=np.float32) * (reach / (n - 1))
    drift = np.cumsum(noise1d(n, 26.0))
    drift = drift / (float(np.max(np.abs(drift))) + 1e-6)
    amp = 0.018 * reach + 2.6
    jitter = noise1d(n, 2.2) * 0.55
    x = x0 + drift * amp + jitter
    y = y0 + s
    return x.astype(np.float32), y.astype(np.float32), s


def width_along(s, reach, w0, wthread, crossings):
    ld = 0.055 * reach + 9.0
    w = wthread + (w0 - wthread) * np.exp(-s / ld)
    w = w * (1.0 + 0.17 * noise1d(len(s), 19.0))
    for sc in crossings:
        w = w * np.where(s > sc, 1.11, 1.0)
    # the running front slows and fattens
    w = w * (1.0 + 0.30 * np.clip((s - 0.86 * reach) / (0.14 * reach + 1.0), 0.0, 1.0))
    return np.maximum(w, 0.8)


def inside_strokes(X, Y, strokes, skip):
    """First index at which the drip enters each stroke it crosses."""
    hits = []
    Q = np.stack([X, Y], axis=1)
    for si, st in enumerate(strokes):
        if si in skip:
            continue
        dx = st.P[None, :, 0] - Q[:, None, 0]
        dy = st.P[None, :, 1] - Q[:, None, 1]
        d = np.sqrt(dx * dx + dy * dy)
        pen = d - st.R[None, :] * 1.02
        best = np.argmin(pen, axis=1)
        mind = pen[np.arange(len(Q)), best]
        w = np.nonzero(mind < 0.0)[0]
        if len(w):
            i = int(w[0])
            hits.append((i, si, int(best[i])))
    hits.sort()
    return hits


blooms = []          # (x, y, stroke index, path index, delivered load)
drip_count = [0]


def draw_drip(x0, y0, reach, w0, load, strokes, skip, depth=0):
    if reach < 4.0 or depth > 2:
        return
    drip_count[0] += 1
    X, Y, s = drip_points(x0, y0, reach)
    keep = Y < S + 40.0
    X, Y, s = X[keep], Y[keep], s[keep]
    if len(X) < 3:
        return
    hits = inside_strokes(X, Y, strokes, skip)
    crossings = [float(s[i]) for i, _, _ in hits]
    wthread = 1.25 + 3.1 * load
    w = width_along(s, reach, max(w0, wthread + 0.4), wthread, crossings)
    amount = 0.75 + 1.85 * load ** 0.75
    amt = amount * (0.72 + 0.42 * np.exp(-s / (0.09 * reach + 12.0)))
    layer_begin()
    for i in range(len(X) - 1):
        seg(X[i], Y[i], X[i + 1], Y[i + 1], w[i], w[i + 1],
            float(0.5 * (amt[i] + amt[i + 1])), soft=1.6, tex=0.13)
    # the bead the drip stops in, where it does not reach the floor
    if Y[-1] < S - 6.0 and rng.random() < 0.78:
        rb = w[-1] * (1.55 + 1.15 * float(rng.random())) + 0.8
        for k, f in enumerate((1.0, 0.86, 0.6, 0.32)):
            dot(float(X[-1]), float(Y[-1]) + rb * 0.42 * k, rb * f,
                amount * 1.06, tex=0.08)
    layer_commit()

    for i, si, pj in hits:
        delivered = load * (0.34 + 0.66 * (1.0 - s[i] / reach))
        delivered = float(min(1.0, max(0.0, delivered)))
        blooms.append((float(X[i]), float(Y[i]), si, pj, delivered))
        st = strokes[si]
        if delivered > 0.26 and depth < 2:
            R = float(st.R[pj])
            bx = float(X[i]) + float(rng.normal(0.0, R * 0.5))
            by = float(st.P[pj, 1]) + R * (0.95 + 0.3 * float(rng.random()))
            sub = delivered * (0.30 + 0.28 * float(rng.random())) * (S - by)
            draw_drip(bx, by, sub, R * 0.45, delivered * 0.8,
                      strokes, skip | {si}, depth + 1)


# ------------------------------------------------------------------ blooms
# "Blooms into it": the arriving ink opens into the wet mark, wicks along it
# both ways, and fingers out of it.

def draw_bloom(bx, by, st, pj, delivered):
    """The arriving ink opens into the wet mark, runs along inside it, and
    fingers out of its edge."""
    R = float(st.R[pj])
    P = st.P
    n = len(P)
    seglen = np.linalg.norm(np.diff(P, axis=0), axis=1)
    arc = np.concatenate([[0.0], np.cumsum(seglen)]).astype(np.float32)
    A = 0.80 + 1.45 * delivered
    Lf = R * (1.9 + 6.2 * delivered)

    # --- the stain spreading into the mark, following its curve
    layer_begin()
    for sgn in (-1, 1):
        i = pj
        while 0 <= i + sgn < n:
            j = i + sgn
            d = abs(float(arc[j]) - float(arc[pj]))
            if d > Lf:
                break
            f = d / Lf
            rr = R * (1.30 - 0.70 * f) * (1.0 + 0.10 * math.sin(d * 0.11))
            a = A * (0.92 * (1.0 - f) ** 1.6 + 0.07)
            seg(float(P[i, 0]), float(P[i, 1]) + R * 0.18 * f,
                float(P[j, 0]), float(P[j, 1]) + R * 0.18 * f,
                max(rr, 1.2), max(rr, 1.2), a, soft=R * 0.40, tex=0.18)
            i = j
    # --- the stain itself: wet ink creeping out of the mark, spread along it
    #     and sagging below it, built as a chain of ragged lobes
    stain = []
    Rh = R * (1.28 + 1.30 * delivered)
    span = Lf * 0.72
    i = pj
    lobes = [(bx, by, Rh)]
    step = max(1.0, Rh * 0.34)                 # one lobe every third of a width
    for sgn in (-1, 1):
        nxt = step
        i = pj
        while 0 <= i + sgn < n:
            j = i + sgn
            d = abs(float(arc[j]) - float(arc[pj]))
            if d > span:
                break
            if d >= nxt:
                nxt += step
                f = d / max(span, 1e-6)
                rr = Rh * (1.0 - 0.72 * f) * (0.80 + 0.4 * float(rng.random()))
                if rr > R * 0.45:
                    lobes.append((float(P[j, 0]) + float(rng.normal(0, R * 0.2)),
                                  float(P[j, 1]) + R * 0.25 * f
                                  + float(rng.normal(0, R * 0.2)), rr))
            i = j
    lobes.append((bx + float(rng.normal(0, R * 0.3)), by + Rh * 0.55,
                  Rh * (0.55 + 0.35 * float(rng.random()))))
    layer_begin()
    for (lx, ly, lr) in lobes:
        blob(lx, ly, lr, A * 0.150, rough=0.38, soft=max(lr * 0.24, 2.5),
             tex=0.32)
        stain.append((lx, ly, lr))
    for (lx, ly, lr) in lobes:
        blob(lx, ly, lr * 0.58, A * 0.36, rough=0.36, soft=max(lr * 0.16, 2.0),
             tex=0.26)
    layer_commit()

    # --- the dark heart where the drip landed
    layer_begin()
    Rc = R * (0.80 + 1.15 * delivered)
    blob(bx, by, Rc, A * 0.98, rough=0.18, soft=R * 0.55, tex=0.14)
    layer_commit()

    # --- capillary fringing at the edge of the stain
    layer_begin()
    nf = 18 + int(round(40.0 * delivered))
    for _ in range(nf):
        lx, ly, lr = stain[int(rng.integers(0, len(stain)))]
        th = float(rng.uniform(0.0, 2.0 * math.pi))
        if rng.random() < 0.35:
            th = math.pi * 0.5 + float(rng.normal(0.0, 0.8))
        cx = lx + math.cos(th) * lr * 0.88
        cy = ly + math.sin(th) * lr * 0.88
        L = lr * (0.07 + 0.42 * float(rng.random()) ** 2.0)
        m = max(2, int(L / 3.0))
        tr = 0.9 + 1.3 * float(rng.random())
        wig = noise1d(m, 1.6) * 0.45
        aa = A * (0.30 + 0.40 * float(rng.random()))
        for k in range(m):
            th2 = th + wig[k]
            nxp = cx + math.cos(th2) * (L / m)
            nyp = cy + math.sin(th2) * (L / m)
            f = k / m
            seg(cx, cy, nxp, nyp, max(tr * (1.0 - 0.5 * f), 0.7),
                max(tr * (1.0 - 0.5 * (k + 1) / m), 0.7),
                aa * (1.0 - 0.6 * f), soft=1.5, tex=0.34)
            cx, cy = nxp, nyp
    # granules settling in the stain
    for _ in range(int(12 + 40 * delivered)):
        lx, ly, lr = stain[int(rng.integers(0, len(stain)))]
        th = float(rng.uniform(0.0, 2.0 * math.pi))
        rr = lr * float(rng.random()) ** 0.5
        dot(lx + math.cos(th) * rr, ly + math.sin(th) * rr,
            0.8 + 2.4 * float(rng.random()), A * 0.26, soft=2.2, tex=0.4)
    layer_commit()


# -------------------------------------------------------------- the drawing

def place_strokes():
    """A dozen chance places in the upper half, no two on top of each other."""
    pts = []
    tries = 0
    xlo, xhi = 0.085 * S, 0.915 * S
    ylo, yhi = 0.055 * S, 0.455 * S
    minsep = 0.128 * S
    while len(pts) < N_STROKES and tries < 60000:
        tries += 1
        x = float(rng.uniform(xlo, xhi))
        y = float(rng.uniform(ylo, yhi))
        if all((x - a) ** 2 + (y - b) ** 2 > minsep ** 2 for a, b in pts):
            pts.append((x, y))
        elif tries > 20000:
            minsep *= 0.995
    return pts


def chance_loads(n):
    """Chance loads spread across the range: some barely wet, some flooding."""
    q = (np.arange(n) + 0.5) / n
    q = q + rng.uniform(-0.5 / n, 0.5 / n, n)
    loads = np.clip(q, 0.002, 0.998)
    # U-ish shaping so the set really does hold both extremes
    loads = 0.5 + 0.5 * np.sign(loads - 0.5) * np.abs(2.0 * loads - 1.0) ** 0.78
    loads = np.clip(loads, 0.028, 1.0)
    loads = np.sort(loads)
    loads[-1] = 1.0                  # the wettest, which reaches the floor
    rng.shuffle(loads)
    return loads.astype(np.float32)


def main():
    places = place_strokes()
    loads = chance_loads(len(places))
    order = np.argsort([p[1] for p in places])     # top of the wall downward
    strokes = []
    for k in order:
        strokes.append(make_stroke(places[k][0], places[k][1], float(loads[k])))

    for st in strokes:
        draw_stroke(st)

    for si, st in enumerate(strokes):
        load = st.load
        n = len(st.P)
        weight = (st.R ** 2) * (st.P[:, 1] - st.P[:, 1].min() + 6.0)
        weight[: int(0.08 * n)] = 0.0
        weight[int(0.92 * n):] = 0.0
        weight = weight / weight.sum()
        ndrip = 1 + int(round(2.3 * load ** 1.4))
        used = []
        for d in range(ndrip):
            for _ in range(24):
                i = int(rng.choice(n, p=weight))
                if all(abs(i - j) > 0.11 * n for j in used):
                    break
            used.append(i)
            R = float(st.R[i])
            x0 = float(st.P[i, 0]) + float(rng.normal(0.0, R * 0.22))
            y0 = float(st.P[i, 1]) + R * (0.75 + 0.3 * float(rng.random()))
            avail = S - y0
            if d == 0:
                u = load ** 1.45
                reach = (0.006 * S) * (1.0 - u) + avail * 1.05 * u
            else:
                u = load ** 1.45
                base = (0.006 * S) * (1.0 - u) + avail * 1.05 * u
                reach = base * float(rng.uniform(0.07, 0.42))
            w0 = R * (0.30 + 0.26 * load)
            draw_drip(x0, y0, float(reach), w0, load, strokes, {si})

    for bx, by, si, pj, delivered in blooms:
        draw_bloom(bx, by, strokes[si], pj, delivered)

    low = max(float((st.P[:, 1] + st.R * 1.9).max()) for st in strokes)
    floor_hits = sum(1 for st in strokes if st.load ** 1.45 * 1.05 >= 1.0)
    print(f"seed {SEED}: {len(strokes)} strokes, {drip_count[0]} drips, "
          f"{len(blooms)} blooms, lowest stroke ink y={low / S:.3f}, "
          f"to-the-floor={floor_hits}")
    print("loads:", " ".join(f"{s.load:.2f}" for s in strokes))

    # ---------------------------------------------------------- developing
    D = np.clip(ink, 0.0, 2.6)
    # ink granulates into the tooth of the wall, more where it is thin
    D = D * (0.90 + 0.20 * TOOTH) * (1.0 + 0.30 * (1.0 - TOOTH) * np.exp(-1.6 * D))
    # ink pools at the edge of every wet area while it dries
    Dn = np.clip(D, 0.0, 1.0)
    G = ndimage.gaussian_filter(Dn, 6.5)
    D += 0.55 * np.clip(Dn - G, 0.0, None)
    G2 = ndimage.gaussian_filter(Dn, 22.0)
    D += 0.18 * np.clip(Dn - G2, 0.0, None)

    alpha = 1.0 - np.exp(-1.80 * np.clip(D, 0.0, None))
    alpha = np.clip(alpha, 0.0, 1.0)

    wall = np.empty((S, S, 3), np.float32)
    base = np.array([250.0, 248.0, 244.0], np.float32)
    shade = (0.985 + 0.030 * MOTTLE)[:, :, None]
    grain = (0.996 + 0.009 * TOOTH)[:, :, None]
    wall[:] = base[None, None, :] * shade * grain
    black = np.array([13.0, 12.0, 11.0], np.float32)
    a3 = alpha[:, :, None]
    img = wall * (1.0 - a3) + black[None, None, :] * a3
    out = np.clip(img + rng.normal(0.0, 0.5, img.shape), 0, 255).astype(np.uint8)

    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    Image.fromarray(out).save(OUT)
    print("wrote", OUT, out.shape)


if __name__ == "__main__":
    main()
