#!/usr/bin/env python3
"""Generates the tileable textures of "Experience - Rob revisited" (games/alis/assets/revisited/).

Everything is procedural (spectral noise, cellular noise, strokes): no download, no model, no outside picture.
Run from anywhere:  python3 -I games/alis/tools/reborn/textures.py
Needs numpy and Pillow. Deterministic (fixed seeds).

Outputs (PNG, RGBA):
  ground_<name>.png  512x512, tileable, alpha = height (for height-blended splatting; kept in 64..255)
                     names: grass jungle mud sand rock snow
  props.png          2048x2048 atlas of 8x8 cells of 256 (see CELLS below; alpha = cut-out for foliage)
  detail.png         512x512 tileable detail normal map of the ground (rgb = normal x, z, y; a = height)
  noise.png          256x256 tileable noise: r,g = two fbm, b = cellular, a = fine fbm (clouds, water, detail)
"""
import math
import os
import sys

import numpy as np
from PIL import Image, ImageDraw, ImageFilter

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'assets', 'revisited')
N = 512


# ---- noise ------------------------------------------------------------------------------------------

def fbm(size, beta, seed, lo=1.0):
    """Tileable fractal noise by spectral synthesis: white noise filtered by f^-beta. Normalised 0..1."""
    rng = np.random.default_rng(seed)
    white = rng.standard_normal((size, size))
    f = np.fft.fft2(white)
    fy = np.fft.fftfreq(size)[:, None] * size
    fx = np.fft.fftfreq(size)[None, :] * size
    r = np.sqrt(fx * fx + fy * fy)
    r[0, 0] = 1.0
    filt = 1.0 / np.power(np.maximum(r, lo), beta)
    filt[0, 0] = 0.0
    out = np.real(np.fft.ifft2(f * filt))
    out -= out.min()
    out /= out.max() + 1e-9
    return out


def band(size, fmin, fmax, seed):
    """Tileable noise with frequencies between fmin and fmax cycles per tile."""
    rng = np.random.default_rng(seed)
    f = np.fft.fft2(rng.standard_normal((size, size)))
    fy = np.fft.fftfreq(size)[:, None] * size
    fx = np.fft.fftfreq(size)[None, :] * size
    r = np.sqrt(fx * fx + fy * fy)
    out = np.real(np.fft.ifft2(f * ((r >= fmin) & (r <= fmax))))
    out -= out.min()
    return out / (out.max() + 1e-9)


def cellular(size, count, seed):
    """Tileable Worley noise: (F1, F2) distances in pixels, and the id of the nearest point."""
    rng = np.random.default_rng(seed)
    pts = rng.random((count, 2)) * size
    yy, xx = np.mgrid[0:size, 0:size].astype(np.float32)
    f1 = np.full((size, size), 1e9, np.float32)
    f2 = np.full((size, size), 1e9, np.float32)
    ident = np.zeros((size, size), np.int32)
    for i, (px, py) in enumerate(pts):
        dx = np.abs(xx - px)
        dx = np.minimum(dx, size - dx)
        dy = np.abs(yy - py)
        dy = np.minimum(dy, size - dy)
        d = np.sqrt(dx * dx + dy * dy)
        closer = d < f1
        f2 = np.where(closer, f1, np.minimum(f2, d))
        ident = np.where(closer, i, ident)
        f1 = np.where(closer, d, f1)
    return f1, f2, ident


def lerp(a, b, t):
    t = t[..., None] if np.ndim(t) == 2 else t
    return a + (b - a) * t


def col(*rgb):
    return np.array(rgb, np.float32) / 255.0


def smooth(e0, e1, x):
    t = np.clip((x - e0) / (e1 - e0), 0.0, 1.0)
    return t * t * (3 - 2 * t)


def wrap_blur(img, radius):
    """Gaussian blur that keeps the tile seamless (blur a 3x3 tiling, keep the centre)."""
    h, w = img.shape[:2]
    big = np.tile(img, (3, 3, 1) if img.ndim == 3 else (3, 3))
    mode = 'RGB' if img.ndim == 3 else 'L'
    pim = Image.fromarray(np.clip(big * 255, 0, 255).astype(np.uint8), mode).filter(ImageFilter.GaussianBlur(radius))
    out = np.asarray(pim).astype(np.float32) / 255.0
    return out[h:2 * h, w:2 * w]


class Canvas:
    """A float RGBA canvas where shapes are drawn with wrap-around (seamless tiles)."""

    def __init__(self, size, rgb=None):
        self.size = size
        self.img = Image.new('RGBA', (size, size), (0, 0, 0, 0))

    def poly(self, points, fill, layer=None):
        s = self.size
        layer = layer or self.img
        d = ImageDraw.Draw(layer, 'RGBA')
        for ox in (-s, 0, s):
            for oy in (-s, 0, s):
                pts = [(x + ox, y + oy) for x, y in points]
                xs = [p[0] for p in pts]
                ys = [p[1] for p in pts]
                if max(xs) < 0 or min(xs) > s or max(ys) < 0 or min(ys) > s:
                    continue
                d.polygon(pts, fill=fill)

    def line(self, a, b, fill, width=1):
        s = self.size
        d = ImageDraw.Draw(self.img, 'RGBA')
        for ox in (-s, 0, s):
            for oy in (-s, 0, s):
                d.line([(a[0] + ox, a[1] + oy), (b[0] + ox, b[1] + oy)], fill=fill, width=width)

    def ellipse(self, cx, cy, rx, ry, fill):
        s = self.size
        d = ImageDraw.Draw(self.img, 'RGBA')
        for ox in (-s, 0, s):
            for oy in (-s, 0, s):
                d.ellipse([cx - rx + ox, cy - ry + oy, cx + rx + ox, cy + ry + oy], fill=fill)

    def array(self):
        return np.asarray(self.img).astype(np.float32) / 255.0


def over(base, layer):
    """Composites an RGBA float layer over an RGB float base."""
    a = layer[..., 3:4]
    return base * (1 - a) + layer[..., :3] * a


def leaf_points(cx, cy, length, width, angle, tip=0.0):
    """A leaf outline (pointed ellipse) around its base point."""
    pts = []
    ca, sa = math.cos(angle), math.sin(angle)
    for i in range(13):
        t = i / 12
        w = width * math.sin(math.pi * t) ** 0.8 * (1 - tip * t)
        pts.append((t * length, w))
    for i in range(12, -1, -1):
        t = i / 12
        w = width * math.sin(math.pi * t) ** 0.8 * (1 - tip * t)
        pts.append((t * length, -w))
    return [(cx + x * ca - y * sa, cy + x * sa + y * ca) for x, y in pts]


def save(name, rgb, alpha=None):
    rgb = np.clip(rgb, 0, 1)
    if alpha is None:
        alpha = np.ones(rgb.shape[:2], np.float32)
    a = np.clip(alpha, 0, 1)
    arr = np.concatenate([rgb, a[..., None]], axis=2)
    img = Image.fromarray((arr * 255 + 0.5).astype(np.uint8), 'RGBA')
    path = os.path.join(OUT, name)
    img.save(path, optimize=True)
    print(f'{name}: {os.path.getsize(path) // 1024} KB')


def height_alpha(h):
    """Height (0..1) stored as alpha 64..255 (never fully transparent: GD keeps the colour)."""
    return 0.25 + 0.75 * np.clip(h, 0, 1)


def quantize(rgb, bits=6):
    """Drops the lowest bits: smaller PNG files, invisible once filtered and lit."""
    q = float(2 ** bits - 1)
    return np.round(np.clip(rgb, 0, 1) * q) / q


# ---- ground textures ------------------------------------------------------------------------------

def grass():
    """Seen from above: a dense mat of thin blades over darker soil and dead straw."""
    rng = np.random.default_rng(11)
    low = fbm(N, 1.8, 1)
    mid = fbm(N, 1.2, 2)
    base = lerp(col(30, 44, 18), col(54, 66, 26), low)
    base = lerp(base, col(70, 62, 34), smooth(0.6, 0.9, mid) * 0.6)
    img = Image.fromarray((np.clip(base, 0, 1) * 255).astype(np.uint8), 'RGB').convert('RGBA')
    big = Image.new('RGBA', (N * 3, N * 3))
    for ox in range(3):
        for oy in range(3):
            big.paste(img, (ox * N, oy * N))
    d = ImageDraw.Draw(big, 'RGBA')
    greens = [(70, 100, 34), (84, 116, 40), (98, 128, 46), (112, 136, 54), (60, 88, 30), (122, 130, 62), (132, 124, 70)]
    for layer in range(3):
        count = [9000, 14000, 12000][layer]
        for i in range(count):
            x, y = rng.random(2) * N
            ang = rng.random() * math.tau
            ln = (4 + rng.random() * 9) * (1.0 + 0.4 * layer)
            g = greens[rng.integers(len(greens))]
            light = (0.55 + 0.25 * layer + rng.random() * 0.3) * (0.75 + 0.35 * low[int(y) % N, int(x) % N])
            c = tuple(int(min(255, v * light)) for v in g)
            if layer == 0 and rng.random() < 0.35:
                c = (int(118 * light), int(104 * light), int(62 * light))     # dead straw underneath
            ex, ey = x + math.cos(ang) * ln, y + math.sin(ang) * ln
            w = 1 if rng.random() < 0.7 else 2
            for ox in (0, N, N * 2):
                for oy in (0, N, N * 2):
                    d.line([(x + ox, y + oy), (ex + ox, ey + oy)], fill=c + (255,), width=w)
    arr = np.asarray(big).astype(np.float32) / 255.0
    tile = arr[N:2 * N, N:2 * N].copy()
    rgb = tile[..., :3]
    # soften a touch, keep detail
    rgb = rgb * 0.75 + wrap_blur(rgb, 0.7) * 0.25
    rgb *= (0.85 + 0.3 * band(N, 2, 6, 4))[..., None]
    lum = rgb.mean(axis=2)
    h = np.clip((lum - lum.min()) / (lum.max() - lum.min() + 1e-6), 0, 1) * 0.7 + low * 0.3
    save('ground_grass.png', quantize(rgb), height_alpha(h))


def jungle():
    rng = np.random.default_rng(21)
    soil = fbm(N, 1.6, 22)
    rgb = lerp(col(34, 24, 14), col(62, 44, 26), soil)
    rgb *= (0.8 + 0.4 * fbm(N, 0.8, 23))[..., None]
    cv = Canvas(N)
    leafc = [(98, 62, 28), (122, 80, 34), (80, 52, 24), (140, 96, 44), (70, 72, 30), (96, 92, 40), (58, 70, 26), (150, 110, 52), (66, 40, 20)]
    for i in range(2600):
        x, y = rng.random(2) * N
        ln = 14 + rng.random() * 26
        w = ln * (0.22 + rng.random() * 0.16)
        ang = rng.random() * math.tau
        c = leafc[rng.integers(len(leafc))]
        sh = 0.7 + rng.random() * 0.5
        c = tuple(int(min(255, v * sh)) for v in c)
        cv.poly(leaf_points(x + 2, y + 2, ln, w, ang), (8, 5, 2, 110))
        cv.poly(leaf_points(x, y, ln, w, ang), c + (255,))
        ca, sa = math.cos(ang), math.sin(ang)
        mid = tuple(int(v * 0.7) for v in c) + (200,)
        cv.line((x, y), (x + ca * ln * 0.95, y + sa * ln * 0.95), mid, 1)
    for i in range(160):        # twigs
        x, y = rng.random(2) * N
        ang = rng.random() * math.tau
        ln = 20 + rng.random() * 50
        cv.line((x + 1, y + 1), (x + math.cos(ang) * ln + 1, y + math.sin(ang) * ln + 1), (10, 6, 3, 160), 3)
        cv.line((x, y), (x + math.cos(ang) * ln, y + math.sin(ang) * ln), (84, 60, 36, 255), 2)
    layer = cv.array()
    rgb = over(rgb, layer)
    moss = smooth(0.6, 0.8, fbm(N, 1.4, 24))
    rgb = lerp(rgb, col(46, 70, 26) * (0.7 + 0.5 * fbm(N, 0.4, 25))[..., None], moss * 0.75)
    h = layer[..., 3] * 0.5 + soil * 0.3 + moss * 0.2
    save('ground_jungle.png', quantize(rgb), height_alpha(h))


def mud():
    rng = np.random.default_rng(31)
    low = fbm(N, 1.7, 32)
    rgb = lerp(col(54, 40, 27), col(98, 76, 52), low)
    rgb *= (0.82 + 0.3 * fbm(N, 0.7, 33))[..., None]
    wet = smooth(0.48, 0.72, fbm(N, 2.0, 34))
    rgb = lerp(rgb, rgb * 0.5 + col(8, 8, 10), wet * 0.75)
    # footprint-like dents and ruts: soft dark blobs
    dents = smooth(0.62, 0.8, band(N, 8, 30, 38))
    rgb = lerp(rgb, rgb * 0.7, dents * 0.6)
    # small stones half sunk, same hues as the mud
    cv = Canvas(N)
    for i in range(260):
        x, y = rng.random(2) * N
        r = 2.0 + rng.random() * 4.5
        g = 62 + rng.random() * 36
        c = (int(g * 1.05), int(g * 0.95), int(g * 0.82))
        cv.ellipse(x + 1.2, y + 1.2, r, r * 0.8, (20, 14, 8, 140))
        cv.ellipse(x, y, r, r * 0.8, c + (255,))
        cv.ellipse(x - r * 0.3, y - r * 0.3, r * 0.35, r * 0.25, (min(255, c[0] + 18), min(255, c[1] + 16), min(255, c[2] + 12), 120))
    layer = cv.array()
    rgb = over(rgb, layer)
    # twigs and straw
    cv2 = Canvas(N)
    for i in range(140):
        x, y = rng.random(2) * N
        ang = rng.random() * math.tau
        ln = 8 + rng.random() * 26
        cv2.line((x, y), (x + math.cos(ang) * ln, y + math.sin(ang) * ln), (120, 96, 60, 200), 1)
    rgb = over(rgb, cv2.array())
    h = low * 0.5 + layer[..., 3] * 0.4 + (1 - wet) * 0.2 - dents * 0.2
    save('ground_mud.png', quantize(rgb), height_alpha(h))


def sand():
    yy, xx = np.mgrid[0:N, 0:N].astype(np.float32) / N
    warp = fbm(N, 2.2, 41)
    ripple = 0.5 + 0.5 * np.sin(math.tau * (9 * yy + 2 * xx + warp * 2.2))
    low = fbm(N, 1.8, 42)
    grain = fbm(N, 0.0, 43)
    rgb = lerp(col(176, 150, 108), col(214, 192, 150), low)
    rgb *= (0.88 + 0.2 * ripple)[..., None]
    rgb *= (0.86 + 0.28 * grain)[..., None]
    rng = np.random.default_rng(44)
    dark = rng.random((N, N)) < 0.03
    rgb = np.where(dark[..., None], rgb * 0.6, rgb)
    cv = Canvas(N)
    for i in range(120):
        x, y = rng.random(2) * N
        r = 1.5 + rng.random() * 3
        c = [(120, 110, 100), (200, 190, 180), (150, 120, 96)][rng.integers(3)]
        cv.ellipse(x + 1, y + 1, r, r * 0.8, (40, 30, 20, 120))
        cv.ellipse(x, y, r, r * 0.8, c + (255,))
    layer = cv.array()
    rgb = over(rgb, layer)
    h = ripple * 0.5 + low * 0.3 + layer[..., 3] * 0.2
    save('ground_sand.png', quantize(rgb), height_alpha(h))


def rock(name='ground_rock.png', size=N, seed=51, cell=None):
    yy, xx = np.mgrid[0:size, 0:size].astype(np.float32) / size
    n1 = fbm(size, 2.0, seed)
    n2 = fbm(size, 1.3, seed + 1)
    n3 = fbm(size, 0.6, seed + 2)
    ridge = 1 - np.abs(band(size, 3, 24, seed + 3) * 2 - 1)
    strata = 0.5 + 0.5 * np.sin(math.tau * (5 * yy + n1 * 1.6))
    n4 = fbm(size, 0.3, seed + 8)
    v = 0.32 * n1 + 0.33 * n2 + 0.2 * n3 + 0.05 * strata + 0.1 * n4
    rgb = lerp(col(78, 74, 70), col(150, 144, 136), v)
    rgb = lerp(rgb, col(120, 108, 92), smooth(0.4, 0.8, fbm(size, 1.5, seed + 4)) * 0.4)
    f1, f2, _ = cellular(size, 40 if size >= 512 else 14, seed + 5)
    crack = (1 - smooth(0.0, 1.6, f2 - f1)) * smooth(0.45, 0.7, n2) * 0.7
    crack = np.maximum(crack, smooth(0.97, 0.995, ridge) * 0.5)
    rgb = lerp(rgb, rgb * 0.45, crack)
    # light edge of the crack (relief)
    sh = np.roll(np.roll(crack, 1, 0), 1, 1)
    rgb = rgb * (1 + 0.25 * np.clip(sh - crack, 0, 1))[..., None]
    lich = smooth(0.72, 0.82, fbm(size, 1.0, seed + 6)) * smooth(0.4, 0.7, n3)
    rgb = lerp(rgb, col(140, 150, 90) * (0.7 + 0.5 * n3)[..., None], lich * 0.6)
    rgb *= (0.9 + 0.2 * fbm(size, 0.0, seed + 7))[..., None]
    h = v - crack * 0.5
    if cell is not None:
        return rgb, h
    save(name, quantize(rgb), height_alpha(h))


def snow():
    low = fbm(N, 2.0, 61)
    mid = fbm(N, 1.4, 62)
    yy, xx = np.mgrid[0:N, 0:N].astype(np.float32) / N
    drift = 0.5 + 0.5 * np.sin(math.tau * (3 * xx + 5 * yy + low * 1.5))
    v = low * 0.55 + mid * 0.37 + drift * 0.08
    rgb = lerp(col(180, 196, 216), col(246, 248, 252), smooth(0.15, 0.85, v))
    rng = np.random.default_rng(63)
    sparkle = rng.random((N, N)) > 0.996
    rgb = np.where(sparkle[..., None], 1.0, rgb)
    rgb *= (0.96 + 0.06 * fbm(N, 0.2, 64))[..., None]
    save('ground_snow.png', quantize(rgb, 7), height_alpha(v))


# ---- props atlas ----------------------------------------------------------------------------------

C = 256
CELLS = ['bark', 'palm', 'leaves', 'frond', 'needles', 'berry', 'stone', 'metal',
         'planks', 'fabric', 'thatch', 'fur', 'skin', 'blades', 'bone', 'plain',
         'bark_jungle', 'big_leaves', 'fern', 'reeds', 'tuft', 'liana', 'hull', 'char',
         'basalt', 'rope', 'pattern', 'leather', 'hair', 'feathers', 'scales', 'chitin',
         'screen', 'moss', 'leaves_small', 'flowers', 'rust']
GRID = 8


def cell_bark():
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32) / C
    n = fbm(C, 1.4, 101)
    # fibres: noise stretched along y (generate on a squeezed grid by sampling)
    fib = band(C, 6, 40, 102)
    fib = np.repeat(fib[::8, :], 8, axis=0)   # long vertical structures
    fib = wrap_blur(fib, 3)
    ridges = 0.5 + 0.5 * np.sin(math.tau * (12 * xx + n * 1.8))
    v = 0.45 * ridges + 0.35 * fib + 0.2 * n
    rgb = lerp(col(46, 34, 24), col(118, 96, 74), v)
    rgb = lerp(rgb, rgb * 0.4, smooth(0.15, 0.0, ridges))
    moss = smooth(0.62, 0.8, fbm(C, 1.6, 103))
    rgb = lerp(rgb, col(60, 80, 34), moss * 0.6)
    return rgb, np.ones((C, C))


def cell_palm():
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32) / C
    n = fbm(C, 1.2, 111)
    rings = (yy * 8 + n * 0.25) % 1.0
    ring = smooth(0.75, 0.95, rings)
    fib = band(C, 10, 60, 112)
    rgb = lerp(col(92, 74, 52), col(150, 128, 96), 0.6 * fib + 0.4 * n)
    rgb = lerp(rgb, rgb * 0.45, ring)
    rgb *= (0.85 + 0.25 * (1 - rings))[..., None]
    return rgb, np.ones((C, C))


def foliage_cell(seed, count, shape, colours, berries=False):
    rng = np.random.default_rng(seed)
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    for i in range(count):
        x, y = rng.random(2) * C
        c = colours[rng.integers(len(colours))]
        sh = 0.7 + rng.random() * 0.5
        c = tuple(int(min(255, v * sh)) for v in c)
        rr = math.hypot(x - C / 2, y - C / 2) / (C / 2)
        if rr > 0.95 or rng.random() < rr ** 2.2:
            continue
        if shape == 'broad':
            ln = 22 + rng.random() * 18
            ang = rng.random() * math.tau
            pts = leaf_points(x, y, ln, ln * 0.3, ang)
            # keep the leaves inside the cell (alpha cut-outs never cross the cell edge)
            if any(p[0] < 2 or p[0] > C - 2 or p[1] < 2 or p[1] > C - 2 for p in pts):
                continue
            d.polygon(pts, fill=c + (255,))
            ca, sa = math.cos(ang), math.sin(ang)
            d.line([(x, y), (x + ca * ln * 0.9, y + sa * ln * 0.9)], fill=tuple(int(v * 0.75) for v in c) + (255,), width=1)
        else:
            ln = 8 + rng.random() * 8
            ang = rng.random() * math.tau
            pts = leaf_points(x, y, ln, ln * 0.35, ang)
            if any(p[0] < 2 or p[0] > C - 2 or p[1] < 2 or p[1] > C - 2 for p in pts):
                continue
            d.polygon(pts, fill=c + (255,))
    if berries:
        for i in range(70):
            x, y = 12 + rng.random(2) * (C - 24)
            if math.hypot(x - C / 2, y - C / 2) > C * 0.38:
                continue
            r = 3 + rng.random() * 2.5
            d.ellipse([x - r, y - r, x + r, y + r], fill=(40, 16, 60, 255))
            d.ellipse([x - r * 0.75, y - r * 0.75, x + r * 0.6, y + r * 0.6], fill=(90, 30, 120, 255))
            d.ellipse([x - r * 0.5, y - r * 0.6, x - r * 0.1, y - r * 0.2], fill=(220, 190, 240, 255))
    a = np.asarray(img).astype(np.float32) / 255.0
    # darker deep inside the cluster: fake self-shadowing
    shade = 0.75 + 0.35 * fbm(C, 1.5, seed + 1)
    return a[..., :3] * shade[..., None], a[..., 3]


def cell_frond():
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    rng = np.random.default_rng(121)
    cx = C / 2
    # leaflets both sides of a central rachis, from bottom (v = 1) to top (v = 0)
    for i in range(46):
        t = i / 45
        y = C - 6 - t * (C - 14)
        ln = (C * 0.47) * math.sin(math.pi * (0.12 + 0.88 * t)) ** 0.7
        for side in (-1, 1):
            ang = side * (0.35 + 0.25 * t)
            ex = cx + side * ln * math.cos(ang - side * 0.0)
            ey = y - ln * 0.45
            g = (50 + int(rng.random() * 40), 96 + int(rng.random() * 40), 30 + int(rng.random() * 20))
            pts = [(cx, y + 2), (cx + side * ln * 0.5, y - ln * 0.18 - 3), (ex, ey), (cx + side * ln * 0.5, y - ln * 0.18 + 2), (cx, y + 5)]
            d.polygon(pts, fill=g + (255,))
            d.line([(cx, y + 3), (ex, ey)], fill=(int(g[0] * 1.3), int(g[1] * 1.2), g[2], 255), width=1)
    d.line([(cx, C - 2), (cx, 6)], fill=(120, 110, 60, 255), width=4)
    a = np.asarray(img).astype(np.float32) / 255.0
    return a[..., :3], a[..., 3]


def cell_needles():
    """A conifer branch spray: a twig from the bottom centre (the trunk side) to the top, side twigs, needles."""
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    rng = np.random.default_rng(131)

    def twig(x0, y0, ang, ln, depth):
        steps = int(ln / 4) + 1
        x, y = x0, y0
        for k in range(steps):
            t = k / max(1, steps - 1)
            nx = x + math.cos(ang) * 4
            ny = y + math.sin(ang) * 4
            d.line([(x, y), (nx, ny)], fill=(64, 46, 30, 255), width=max(1, 3 - depth))
            # needles on both sides, shorter toward the tip
            nl = (9 - depth * 2) * (1 - 0.5 * t) + 2
            for side in (-1, 1):
                for j in range(2):
                    a2 = ang + side * (0.9 + rng.normal() * 0.2)
                    g = (24 + int(rng.random() * 30), 56 + int(rng.random() * 42), 30 + int(rng.random() * 24))
                    px = x + (nx - x) * j / 2
                    py = y + (ny - y) * j / 2
                    ex = px + math.cos(a2) * nl
                    ey = py + math.sin(a2) * nl
                    if 2 < ex < C - 2 and 2 < ey < C - 2:
                        d.line([(px, py), (ex, ey)], fill=g + (255,), width=2)
            if depth < 2 and k > 1 and k % 3 == 0:
                for side in (-1, 1):
                    twig(x, y, ang + side * (0.7 + rng.random() * 0.3), ln * (0.45 - 0.1 * depth) * (1 - t * 0.6), depth + 1)
            x, y = nx, ny
            ang += rng.normal() * 0.05
            if not (4 < x < C - 4 and 4 < y < C - 4):
                break

    twig(C / 2, C - 6, -math.pi / 2, C * 0.9, 0)
    a = np.asarray(img).astype(np.float32) / 255.0
    return a[..., :3] * (0.8 + 0.3 * fbm(C, 1.3, 132))[..., None], a[..., 3]


def cell_stone():
    rgb, h = rock(size=C, seed=141, cell=True)
    return rgb, np.ones((C, C))


def cell_metal():
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32) / C
    n = fbm(C, 1.5, 151)
    rgb = lerp(col(150, 156, 160), col(196, 200, 204), n)
    seam = ((xx * 2) % 1.0 < 0.012) | ((yy * 4) % 1.0 < 0.012)
    rgb = np.where(seam[..., None], rgb * 0.45, rgb)
    rgb = np.where(np.roll(seam, 2, 0)[..., None] & ~seam[..., None], rgb * 1.15, rgb)
    rng = np.random.default_rng(152)
    img = Image.fromarray((np.clip(rgb, 0, 1) * 255).astype(np.uint8), 'RGB')
    d = ImageDraw.Draw(img)
    for gx in range(2):
        for gy in range(4):
            for k in range(6):
                for (px, py) in ((gx * 128 + 8 + k * 21, gy * 64 + 7), (gx * 128 + 8 + k * 21, gy * 64 + 57)):
                    d.ellipse([px - 2, py - 2, px + 2, py + 2], fill=(110, 112, 116))
                    d.point((px - 1, py - 1), fill=(230, 232, 236))
    for i in range(60):   # scratches
        x, y = rng.random(2) * C
        ang = rng.normal() * 0.4
        ln = 6 + rng.random() * 30
        d.line([(x, y), (x + math.cos(ang) * ln, y + math.sin(ang) * ln)], fill=(186, 190, 194), width=1)
    rgb = np.asarray(img).astype(np.float32) / 255.0
    grime = smooth(0.55, 0.9, fbm(C, 1.8, 153))
    rgb = lerp(rgb, rgb * col(150, 130, 110), grime * 0.6)
    return rgb, np.ones((C, C))


def cell_planks():
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32) / C
    rng = np.random.default_rng(161)
    plank = np.floor(xx * 5).astype(int)
    tint = rng.random(5)[plank]
    n = fbm(C, 1.3, 162)
    grain = 0.5 + 0.5 * np.sin(math.tau * (xx * 60 + n * 3 + tint * 7))
    rgb = lerp(col(92, 64, 40), col(150, 112, 74), 0.5 * grain + 0.3 * tint + 0.2 * n)
    gap = ((xx * 5) % 1.0) < 0.03
    rgb = np.where(gap[..., None], rgb * 0.3, rgb)
    knots_f1, _, _ = cellular(C, 7, 163)
    rgb = lerp(rgb, rgb * 0.5, smooth(5, 1, knots_f1))
    rgb *= (0.8 + 0.3 * fbm(C, 1.8, 164))[..., None]
    return rgb, np.ones((C, C))


def cell_fabric():
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32)
    weave = 0.5 + 0.25 * np.sin(xx * math.pi / 2) * np.sign(np.sin(yy * math.pi / 4)) + 0.25 * np.sin(yy * math.pi / 2)
    n = fbm(C, 1.6, 171)
    rgb = lerp(col(150, 140, 120), col(206, 196, 174), 0.6 * weave + 0.4 * n)
    stain = smooth(0.6, 0.85, fbm(C, 1.9, 172))
    rgb = lerp(rgb, rgb * col(140, 120, 90), stain * 0.6)
    return rgb, np.ones((C, C))


def cell_thatch():
    img = Image.new('RGB', (C, C), (70, 56, 30))
    d = ImageDraw.Draw(img)
    rng = np.random.default_rng(181)
    for i in range(2600):
        x = rng.random() * C
        y = rng.random() * C
        ln = 20 + rng.random() * 40
        ang = math.pi / 2 + rng.normal() * 0.12
        c = (int(150 + rng.random() * 70), int(120 + rng.random() * 60), int(60 + rng.random() * 40))
        for oy in (-C, 0, C):
            d.line([(x, y + oy), (x + math.cos(ang) * ln, y + math.sin(ang) * ln + oy)], fill=c, width=1)
    rgb = np.asarray(img).astype(np.float32) / 255.0
    yy = np.mgrid[0:C, 0:C][0] / C
    rgb *= (0.93 + 0.07 * ((yy * 4) % 1.0))[..., None]    # layered rows
    return rgb * (0.8 + 0.3 * fbm(C, 1.5, 182))[..., None], np.ones((C, C))


def cell_fur():
    img = Image.new('RGB', (C, C), (90, 90, 90))
    d = ImageDraw.Draw(img)
    rng = np.random.default_rng(191)
    for i in range(9000):
        x, y = rng.random(2) * C
        ln = 4 + rng.random() * 9
        ang = math.pi / 2 + rng.normal() * 0.35
        v = int(110 + rng.random() * 120)
        for ox in (-C, 0, C):
            for oy in (-C, 0, C):
                d.line([(x + ox, y + oy), (x + ox + math.cos(ang) * ln, y + oy + math.sin(ang) * ln)], fill=(v, v, v), width=1)
    rgb = np.asarray(img).astype(np.float32) / 255.0
    return rgb * (0.75 + 0.35 * fbm(C, 1.6, 192))[..., None], np.ones((C, C))


def cell_skin():
    n = fbm(C, 1.4, 201)
    f1, f2, _ = cellular(C, 300, 202)
    scale = smooth(0.0, 3.0, f2 - f1)
    v = 0.6 + 0.25 * n + 0.15 * scale
    rgb = np.repeat(v[..., None], 3, axis=2) * col(230, 230, 230)
    return rgb, np.ones((C, C))


def cell_blades():
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    rng = np.random.default_rng(211)
    for i in range(170):
        x0 = C / 2 + rng.normal() * C * 0.17
        if x0 < 8 or x0 > C - 8:
            continue
        edge = abs(x0 - C / 2) / (C / 2)
        h = C * (0.35 + rng.random() * 0.6) * (1 - 0.55 * edge)
        lean = (x0 - C / 2) * 0.35 + rng.normal() * 18
        w = 2.5 + rng.random() * 2.5
        g = (int(60 + rng.random() * 50), int(96 + rng.random() * 50), int(28 + rng.random() * 26))
        tipc = (min(255, g[0] + 60), min(255, g[1] + 40), g[2] + 10)
        pts_l, pts_r = [], []
        for k in range(9):
            t = k / 8
            x = x0 + lean * t * t
            y = C - 1 - h * t
            ww = w * (1 - t)
            pts_l.append((x - ww, y))
            pts_r.append((x + ww, y))
        x_end = min(C - 3, max(3, x0 + lean))
        if x_end != x0 + lean:
            continue
        d.polygon(pts_l + pts_r[::-1], fill=g + (255,))
        d.line([pts_l[5], (x0 + lean, C - 1 - h)], fill=tipc + (255,), width=1)
    a = np.asarray(img).astype(np.float32) / 255.0
    yy = np.mgrid[0:C, 0:C][0] / C
    return a[..., :3] * (0.45 + 0.65 * (1 - yy))[..., None], a[..., 3]


def cell_bone():
    n = fbm(C, 1.5, 221)
    f1, f2, _ = cellular(C, 500, 222)
    pores = smooth(1.5, 0.0, f1)
    rgb = lerp(col(196, 184, 156), col(232, 224, 200), n)
    rgb = lerp(rgb, rgb * 0.7, pores * 0.5)
    return rgb, np.ones((C, C))


def cell_plain():
    n = fbm(C, 1.8, 231)
    v = 0.86 + 0.14 * n
    return np.repeat(v[..., None], 3, axis=2), np.ones((C, C))


# ---- wave 2 cells ---------------------------------------------------------------------------------

def rgba_of(img):
    a = np.asarray(img).astype(np.float32) / 255.0
    return a[..., :3], a[..., 3]


def cell_bark_jungle():
    """Smooth pale bark of the giant jungle trees: long shallow fissures, lichen blotches, green moss in the cracks."""
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32) / C
    n = fbm(C, 1.5, 501)
    fis = band(C, 4, 18, 502)
    fis = np.repeat(fis[::16, :], 16, axis=0)
    fis = wrap_blur(fis, 4)
    v = 0.55 + 0.25 * n + 0.2 * fis
    rgb = lerp(col(70, 66, 54), col(150, 142, 120), v)
    crack = smooth(0.18, 0.05, np.abs(fis - 0.5)) * 0.0 + smooth(0.62, 0.8, fis) * 0.5
    rgb = lerp(rgb, rgb * 0.55, crack)
    lich = smooth(0.66, 0.74, fbm(C, 1.1, 503))
    rgb = lerp(rgb, col(176, 180, 150), lich * 0.55)
    moss = smooth(0.55, 0.75, fbm(C, 1.7, 504)) * (0.4 + 0.6 * crack)
    rgb = lerp(rgb, col(48, 78, 28), moss * 0.7)
    return rgb * (0.85 + 0.2 * fbm(C, 0.3, 505))[..., None], np.ones((C, C))


def cell_big_leaves():
    """Three or four large broad leaves (understory, banana-like), from the bottom centre outwards: veins, a glossy rim."""
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    rng = np.random.default_rng(511)
    for k, ang in enumerate([-2.35, -0.8, -1.95, -1.2, -1.57]):
        ln = C * (0.62 + rng.random() * 0.1)
        w = ln * (0.2 + rng.random() * 0.05)
        bx, by = C / 2, C - 4
        pts = leaf_points(bx, by, ln, w, ang, 0.2)
        pts = [(min(C - 2, max(2, x)), min(C - 2, max(2, y))) for x, y in pts]
        g = [(40, 92, 30), (52, 104, 34), (34, 80, 26), (62, 112, 40), (46, 98, 36)][k]
        d.polygon(pts, fill=g + (255,))
        ca, sa = math.cos(ang), math.sin(ang)
        for j in range(1, 14):
            t = j / 14
            px, py = bx + ca * ln * t, by + sa * ln * t
            ww = w * math.sin(math.pi * t) ** 0.8 * 0.7
            for side in (-1, 1):
                ex = px + (-sa * side) * ww + ca * ww * 0.35
                ey = py + (ca * side) * ww + sa * ww * 0.35
                d.line([(px, py), (min(C - 2, max(2, ex)), min(C - 2, max(2, ey)))], fill=(int(g[0] * 0.75), int(g[1] * 0.8), int(g[2] * 0.7), 255), width=1)
        d.line([(bx, by), (bx + ca * ln * 0.95, by + sa * ln * 0.95)], fill=(150, 170, 90, 255), width=3)
    rgb, a = rgba_of(img)
    shade = 0.75 + 0.4 * fbm(C, 1.2, 512)
    return rgb * shade[..., None], a


def cell_fern():
    """A fern frond: a rachis from the bottom centre to the top, pinnae both sides, each with lobes."""
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    rng = np.random.default_rng(521)
    cx = C / 2
    for i in range(26):
        t = i / 25
        y = C - 6 - t * (C - 16)
        ln = C * 0.46 * math.sin(math.pi * (0.1 + 0.9 * t)) ** 0.9 * (1 - 0.15 * t)
        for side in (-1, 1):
            g = (int(30 + rng.random() * 30), int(70 + rng.random() * 40), int(20 + rng.random() * 18))
            ang = math.atan2(-0.35, side)
            pts = leaf_points(cx, y, ln, max(1.8, ln * 0.075), ang, 0.4)
            pts = [(min(C - 2, max(2, px)), min(C - 2, max(2, py))) for px, py in pts]
            d.polygon(pts, fill=g + (255,))
            d.line([(cx, y), (cx + side * ln * 0.9, y - ln * 0.27)], fill=(int(g[0] * 0.7), int(g[1] * 0.75), g[2], 255), width=1)
    d.line([(cx, C - 2), (cx, 10)], fill=(90, 96, 44, 255), width=3)
    rgb, a = rgba_of(img)
    return rgb * (0.8 + 0.3 * fbm(C, 1.4, 522))[..., None], a


def cell_reeds():
    """Tall reeds / cattails: thin blades from the bottom edge to the top, a few brown seed heads."""
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    rng = np.random.default_rng(531)
    for i in range(70):
        x0 = 10 + rng.random() * (C - 20)
        h = C * (0.55 + rng.random() * 0.43)
        lean = rng.normal() * 22
        w = 1.5 + rng.random() * 2.5
        g = (int(80 + rng.random() * 60), int(100 + rng.random() * 50), int(40 + rng.random() * 26))
        pl, pr = [], []
        for k in range(10):
            t = k / 9
            x = min(C - 3, max(3, x0 + lean * t * t))
            y = C - 1 - h * t
            ww = w * (1 - t * 0.9)
            pl.append((x - ww, y))
            pr.append((x + ww, y))
        d.polygon(pl + pr[::-1], fill=g + (255,))
    for i in range(7):
        x = 20 + rng.random() * (C - 40)
        top = C * (0.05 + rng.random() * 0.25)
        d.line([(x, C - 1), (x, top)], fill=(110, 120, 60, 255), width=2)
        d.rounded_rectangle([x - 4, top + 6, x + 4, top + 34], radius=4, fill=(92, 58, 32, 255))
    rgb, a = rgba_of(img)
    yy = np.mgrid[0:C, 0:C][0] / C
    return rgb * (0.55 + 0.55 * (1 - yy))[..., None], a


def cell_tuft():
    """A realistic grass tuft: hundreds of thin blades, greens with dry straw, darker at the base."""
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    rng = np.random.default_rng(541)
    for i in range(420):
        x0 = C / 2 + rng.normal() * C * 0.2
        if x0 < 6 or x0 > C - 6:
            continue
        edge = abs(x0 - C / 2) / (C / 2)
        h = C * (0.3 + rng.random() * 0.68) * (1 - 0.5 * edge)
        lean = (x0 - C / 2) * 0.5 + rng.normal() * 16
        w = 1.0 + rng.random() * 1.6
        dry = rng.random() < 0.18
        g = (int(150 + rng.random() * 40), int(140 + rng.random() * 30), int(80 + rng.random() * 30)) if dry else \
            (int(56 + rng.random() * 50), int(90 + rng.random() * 50), int(26 + rng.random() * 24))
        pl, pr = [], []
        ok = True
        for k in range(9):
            t = k / 8
            x = x0 + lean * t * t
            y = C - 1 - h * t
            if x < 3 or x > C - 3:
                ok = False
                break
            ww = w * (1 - t)
            pl.append((x - ww, y))
            pr.append((x + ww, y))
        if ok:
            d.polygon(pl + pr[::-1], fill=g + (255,))
    rgb, a = rgba_of(img)
    yy = np.mgrid[0:C, 0:C][0] / C
    return rgb * (0.4 + 0.7 * (1 - yy) ** 0.7)[..., None], a


def cell_liana():
    """A hanging vine: a twisting stem down the middle, heart-shaped leaves both sides."""
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    rng = np.random.default_rng(551)
    pts = [(C / 2 + 14 * math.sin(y / 30.0), y) for y in range(0, C + 1, 4)]
    d.line(pts, fill=(78, 62, 34, 255), width=4)
    for i in range(26):
        y = rng.random() * (C - 20) + 10
        x = C / 2 + 14 * math.sin(y / 30.0)
        side = -1 if i % 2 else 1
        r = 10 + rng.random() * 10
        cx, cy = x + side * r * 0.9, y + r * 0.2
        g = (int(40 + rng.random() * 30), int(86 + rng.random() * 46), int(26 + rng.random() * 20))
        d.ellipse([cx - r, cy - r * 0.7, cx + r, cy + r * 0.7], fill=g + (255,))
        d.polygon([(cx - r * 0.6, cy + r * 0.3), (cx + r * 0.6, cy + r * 0.3), (cx, cy + r * 1.2)], fill=g + (255,))
        d.line([(x, y), (cx, cy + r * 0.8)], fill=(int(g[0] * 1.3), int(g[1] * 1.15), g[2], 255), width=1)
    rgb, a = rgba_of(img)
    return rgb * (0.8 + 0.3 * fbm(C, 1.3, 552))[..., None], a


def cell_hull():
    """Spacecraft hull: off-white panels, rivet lines, an orange band, stencils, rain streaks and soot."""
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32) / C
    n = fbm(C, 1.5, 561)
    rgb = lerp(col(176, 178, 172), col(222, 222, 214), n)
    img = Image.fromarray((np.clip(rgb, 0, 1) * 255).astype(np.uint8), 'RGB')
    d = ImageDraw.Draw(img)
    rng = np.random.default_rng(562)
    for gx in (0, 96, 176):
        d.line([(gx, 0), (gx, C)], fill=(92, 92, 90), width=2)
    for gy in (0, 70, 150, 210):
        d.line([(0, gy), (C, gy)], fill=(92, 92, 90), width=2)
    for gy in (0, 70, 150, 210):
        for k in range(0, C, 12):
            d.point((k + 3, gy + 5), fill=(120, 120, 118))
    d.rectangle([0, 112, C, 134], fill=(196, 92, 36))
    d.rectangle([0, 112, C, 114], fill=(120, 60, 26))
    for k in range(5):
        x, y = 18 + k * 40, 170
        d.rectangle([x, y, x + 6, y + 18], fill=(40, 40, 42))
        d.rectangle([x + 10, y, x + 24, y + 4], fill=(40, 40, 42))
    d.rectangle([110, 20, 160, 52], fill=(60, 62, 66))
    d.rectangle([113, 23, 157, 49], fill=(28, 34, 40))
    rgb = np.asarray(img).astype(np.float32) / 255.0
    streak = band(C, 4, 30, 563)
    streak = np.repeat(streak[::32, :], 32, axis=0)
    streak = wrap_blur(streak, 3)
    rgb = lerp(rgb, rgb * col(150, 136, 116), smooth(0.55, 0.85, streak) * 0.6)
    soot = smooth(0.55, 0.85, fbm(C, 1.8, 564))
    rgb = lerp(rgb, rgb * 0.35, soot * 0.55)
    return rgb, np.ones((C, C))


def cell_char():
    """Charred wood: black, cracked in blocks (alligator char), grey ash on the ridges."""
    f1, f2, _ = cellular(C, 90, 571)
    edge = smooth(0.0, 2.5, f2 - f1)
    n = fbm(C, 1.4, 572)
    v = 0.08 + 0.12 * n + 0.1 * edge
    rgb = np.repeat(v[..., None], 3, axis=2) * col(255, 236, 220)
    ash = smooth(0.62, 0.8, fbm(C, 1.1, 573)) * edge
    rgb = lerp(rgb, col(130, 126, 120), ash * 0.6)
    return rgb, np.ones((C, C))


def cell_basalt():
    """Dark basalt: blue-grey, fine vesicles, faint horizontal joints."""
    n = fbm(C, 1.6, 581)
    f1, f2, _ = cellular(C, 700, 582)
    ves = smooth(1.8, 0.4, f1) * smooth(0.45, 0.75, fbm(C, 1.0, 583))
    v = 0.6 + 0.3 * n
    rgb = lerp(col(34, 36, 40), col(84, 86, 92), v)
    rgb = lerp(rgb, rgb * 0.4, ves * 0.7)
    yy = np.mgrid[0:C, 0:C][0] / C
    joint = smooth(0.985, 1.0, 0.5 + 0.5 * np.sin(math.tau * (yy * 3 + n * 0.3)))
    rgb = lerp(rgb, rgb * 0.45, joint)
    salt = smooth(0.75, 0.86, fbm(C, 1.3, 584))
    rgb = lerp(rgb, col(150, 150, 140), salt * 0.25)
    return rgb, np.ones((C, C))


def cell_rope():
    """Twisted fibre rope along u: diagonal strands."""
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32) / C
    twist = 0.5 + 0.5 * np.sin(math.tau * (xx * 6 + yy * 3))
    fib = band(C, 20, 90, 591)
    v = 0.4 + 0.45 * twist + 0.15 * fib
    rgb = lerp(col(90, 70, 40), col(186, 160, 110), v)
    rgb = lerp(rgb, rgb * 0.45, smooth(0.15, 0.0, twist))
    return rgb, np.ones((C, C))


def cell_pattern():
    """Hand-woven cloth with bands of geometric motifs (zigzags, diamonds): Haldi and Ouvi garments, stall awnings."""
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32)
    weave = 0.82 + 0.1 * np.sin(xx * math.pi / 2) * np.sign(np.sin(yy * math.pi / 2))
    n = fbm(C, 1.5, 601)
    base = col(214, 200, 170)
    rgb = np.ones((C, C, 3), np.float32) * base
    band_id = (yy // 32).astype(int) % 4
    zig = (np.abs(((xx + yy * 0.0) % 32) - 16) + (yy % 32)) % 32 < 6
    diam = (np.abs((xx % 32) - 16) + np.abs((yy % 32) - 16)) < 9
    dots = ((xx % 16) < 4) & ((yy % 16) < 4)
    colours = [col(150, 52, 34), col(40, 74, 92), col(206, 150, 50), col(60, 46, 36)]
    for k in range(4):
        m = (band_id == k) & ([zig, diam, dots, zig][k])
        rgb = np.where(m[..., None], colours[k], rgb)
    stripes = (yy % 32) < 3
    rgb = np.where(stripes[..., None], col(70, 40, 30), rgb)
    rgb *= (weave * (0.85 + 0.25 * n))[..., None]
    return rgb, np.ones((C, C))


def cell_leather():
    n = fbm(C, 1.4, 611)
    f1, f2, _ = cellular(C, 260, 612)
    crease = smooth(1.2, 0.0, f2 - f1)
    v = 0.6 + 0.3 * n - 0.25 * crease
    rgb = lerp(col(70, 44, 26), col(150, 104, 66), v)
    scuff = smooth(0.7, 0.85, fbm(C, 1.0, 613))
    rgb = lerp(rgb, col(170, 140, 110), scuff * 0.3)
    return rgb, np.ones((C, C))


def cell_hair():
    """Hair strands, vertical, the lower edge ragged (alpha): grey, tinted by the mesh colour."""
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    rng = np.random.default_rng(621)
    for i in range(1800):
        x = rng.random() * C
        ln = C * (0.6 + rng.random() * 0.4)
        v = int(120 + rng.random() * 120)
        sway = rng.normal() * 8
        pts = [(min(C - 1, max(0, x + sway * (y / C) ** 2)), y) for y in np.linspace(0, ln, 8)]
        d.line(pts, fill=(v, v, v, 255), width=1 if rng.random() < 0.7 else 2)
    rgb, a = rgba_of(img)
    a = np.clip(wrap_blur(a, 0.6) * 1.6, 0, 1)
    rgb = np.where(a[..., None] > 0.05, rgb, 0.6)
    return rgb, a


def cell_feathers():
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32)
    row = (yy // 24).astype(int)
    off = (row % 2) * 16
    fx = ((xx + off) % 32) - 16
    fy = (yy % 24)
    shape = (fx / 15.0) ** 2 + ((fy - 4) / 22.0) ** 2
    edge = smooth(0.7, 1.0, shape)
    barb = 0.5 + 0.5 * np.sin(fx * 1.4 + fy * 0.3)
    v = 0.75 - 0.35 * edge + 0.12 * barb
    rgb = np.repeat(v[..., None], 3, axis=2) * (0.85 + 0.25 * fbm(C, 1.2, 631))[..., None]
    return rgb, np.ones((C, C))


def cell_scales():
    """Reptile hide: large raised scutes in rows (the croc's back), smaller scales between."""
    f1, f2, ident = cellular(C, 120, 641)
    scute = smooth(0.0, 4.0, f2 - f1)
    n = fbm(C, 1.4, 642)
    f1b, f2b, _ = cellular(C, 900, 643)
    small = smooth(0.0, 1.8, f2b - f1b)
    v = 0.4 + 0.35 * scute * (0.6 + 0.4 * small) + 0.2 * n
    rgb = np.repeat(v[..., None], 3, axis=2)
    return rgb, np.ones((C, C))


def cell_chitin():
    """Glossy plated shell: overlapping bands, darker seams, pale highlights."""
    yy, xx = np.mgrid[0:C, 0:C].astype(np.float32) / C
    n = fbm(C, 1.5, 651)
    bands = (yy * 6 + n * 0.3) % 1.0
    v = 0.45 + 0.4 * smooth(0.0, 0.8, bands) - 0.35 * smooth(0.9, 1.0, bands)
    f1, f2, _ = cellular(C, 400, 652)
    pits = smooth(1.2, 0.0, f1) * 0.25
    v = v - pits + 0.1 * fbm(C, 0.3, 653)
    rgb = np.repeat(v[..., None], 3, axis=2)
    return rgb, np.ones((C, C))


def cell_screen():
    """A terminal screen: dark glass, a frame, lines of glowing text and a small diagram."""
    img = Image.new('RGB', (C, C), (8, 16, 18))
    d = ImageDraw.Draw(img)
    rng = np.random.default_rng(661)
    d.rectangle([0, 0, C - 1, C - 1], outline=(50, 54, 58), width=10)
    y = 22
    while y < C - 70:
        x = 20
        while x < C - 30:
            w = int(6 + rng.random() * 26)
            if x + w > C - 20:
                break
            b = int(140 + rng.random() * 110)
            d.rectangle([x, y, x + w, y + 5], fill=(int(b * 0.35), b, int(b * 0.8)))
            x += w + 6
        y += 12
    d.rectangle([20, C - 62, C - 20, C - 20], outline=(80, 220, 190), width=2)
    pts = [(24 + k * 8, C - 40 - 14 * math.sin(k * 0.6)) for k in range(26)]
    d.line(pts, fill=(140, 255, 210), width=2)
    rgb = np.asarray(img).astype(np.float32) / 255.0
    yy = np.mgrid[0:C, 0:C][0]
    rgb *= (0.85 + 0.15 * (yy % 3 == 0))[..., None]
    return rgb, np.ones((C, C))


def cell_moss():
    n = fbm(C, 1.2, 671)
    f1, f2, _ = cellular(C, 500, 672)
    clump = smooth(2.5, 0.0, f1)
    v = 0.45 + 0.35 * n + 0.25 * clump
    rgb = lerp(col(30, 52, 18), col(110, 140, 50), v)
    return rgb, np.ones((C, C))


def cell_leaves_small():
    return foliage_cell(681, 2200, 'small', [(30, 70, 26), (44, 88, 34), (26, 62, 24), (56, 96, 40), (70, 100, 36)])


def cell_flowers():
    """A meadow patch card: thin stems and small flowers (white, yellow, violet), bottom anchored."""
    img = Image.new('RGBA', (C, C), (0, 0, 0, 0))
    d = ImageDraw.Draw(img, 'RGBA')
    rng = np.random.default_rng(691)
    for i in range(60):
        x = 12 + rng.random() * (C - 24)
        top = C * (0.25 + rng.random() * 0.55)
        lean = rng.normal() * 10
        d.line([(x, C - 1), (x + lean, top)], fill=(70, 110, 40, 255), width=2)
        c = [(236, 236, 220), (240, 200, 60), (150, 110, 200), (230, 120, 90)][rng.integers(4)]
        r = 4 + rng.random() * 5
        for k in range(5):
            a = k / 5 * math.tau
            px, py = x + lean + math.cos(a) * r * 0.8, top + math.sin(a) * r * 0.8
            d.ellipse([px - r * 0.55, py - r * 0.55, px + r * 0.55, py + r * 0.55], fill=c + (255,))
        d.ellipse([x + lean - 2, top - 2, x + lean + 2, top + 2], fill=(200, 150, 40, 255))
    rgb, a = rgba_of(img)
    return rgb, a


def cell_rust():
    n = fbm(C, 1.6, 701)
    pits = smooth(0.6, 0.85, fbm(C, 0.6, 702))
    v = 0.5 + 0.4 * n
    rgb = lerp(col(70, 36, 20), col(170, 90, 46), v)
    rgb = lerp(rgb, col(110, 104, 96), smooth(0.65, 0.85, fbm(C, 1.9, 703)) * 0.5)
    rgb = lerp(rgb, rgb * 0.5, pits * 0.5)
    return rgb, np.ones((C, C))


def detail():
    """The ground's detail normal map (tileable, 512): pebbles, clumps and fine grain."""
    s = 512
    h = fbm(s, 1.6, 801) * 0.45 + fbm(s, 0.9, 802) * 0.25
    f1, f2, _ = cellular(s, 260, 803)
    peb = np.clip(1.0 - f1 / 11.0, 0, 1) ** 1.5 * smooth(0.35, 0.7, fbm(s, 1.2, 804))
    h = h + peb * 0.5
    h = (h - h.min()) / (h.max() - h.min())
    k = 6.0
    gx = (np.roll(h, -1, 1) - np.roll(h, 1, 1)) * k
    gz = (np.roll(h, -1, 0) - np.roll(h, 1, 0)) * k
    ln = np.sqrt(gx * gx + gz * gz + 1.0)
    nx, nz, ny = -gx / ln, -gz / ln, 1.0 / ln
    arr = np.stack([nx * 0.5 + 0.5, nz * 0.5 + 0.5, ny], axis=2)
    save('detail.png', arr, height_alpha(h))


def props():
    makers = {
        'bark': cell_bark, 'palm': cell_palm,
        'leaves': lambda: foliage_cell(301, 900, 'broad', [(46, 92, 30), (60, 110, 36), (38, 78, 26), (80, 120, 40), (54, 96, 44)]),
        'frond': cell_frond, 'needles': cell_needles,
        'berry': lambda: foliage_cell(302, 2600, 'small', [(40, 84, 30), (54, 100, 36), (34, 70, 26), (66, 104, 40)], berries=True),
        'stone': cell_stone, 'metal': cell_metal, 'planks': cell_planks, 'fabric': cell_fabric, 'thatch': cell_thatch,
        'fur': cell_fur, 'skin': cell_skin, 'blades': cell_blades, 'bone': cell_bone, 'plain': cell_plain,
        'bark_jungle': cell_bark_jungle, 'big_leaves': cell_big_leaves, 'fern': cell_fern, 'reeds': cell_reeds,
        'tuft': cell_tuft, 'liana': cell_liana, 'hull': cell_hull, 'char': cell_char, 'basalt': cell_basalt,
        'rope': cell_rope, 'pattern': cell_pattern, 'leather': cell_leather, 'hair': cell_hair, 'feathers': cell_feathers,
        'scales': cell_scales, 'chitin': cell_chitin, 'screen': cell_screen, 'moss': cell_moss,
        'leaves_small': cell_leaves_small, 'flowers': cell_flowers, 'rust': cell_rust,
    }
    atlas = np.zeros((C * GRID, C * GRID, 3), np.float32) + 0.5
    alpha = np.ones((C * GRID, C * GRID), np.float32)
    for i, name in enumerate(CELLS):
        rgb, a = makers[name]()
        x, y = (i % GRID) * C, (i // GRID) * C
        # foliage: colour bleeds into the transparent pixels (filtering never shows black fringes)
        if a.min() < 0.99:
            mask = (a > 0.5).astype(np.float32)
            blur = wrap_blur(rgb * mask[..., None], 4)
            wsum = wrap_blur(np.repeat(mask[..., None], 3, axis=2), 4)
            fill = blur / np.maximum(wsum, 1e-3)
            rgb = np.where(mask[..., None] > 0, rgb, fill)
        atlas[y:y + C, x:x + C] = rgb
        alpha[y:y + C, x:x + C] = a
        print(f'  cell {i} {name}')
    save('props.png', quantize(atlas), alpha)


def noise():
    s = 256
    r = fbm(s, 1.8, 401)
    g = fbm(s, 1.4, 402)
    f1, f2, _ = cellular(s, 40, 403)
    b = np.clip(f1 / 28.0, 0, 1)
    a = fbm(s, 0.9, 404)
    arr = np.stack([r, g, b], axis=2)
    save('noise.png', arr, height_alpha(a))


def main():
    os.makedirs(OUT, exist_ok=True)
    only = sys.argv[1:]
    jobs = {'grass': grass, 'jungle': jungle, 'mud': mud, 'sand': sand, 'rock': rock, 'snow': snow, 'props': props, 'noise': noise,
            'detail': detail}
    for k, f in jobs.items():
        if not only or k in only:
            f()


if __name__ == '__main__':
    main()
