#!/usr/bin/env python3
"""White crayon on a black wall.

    Stop one grain 1/16 inch wide at a chance point. Then fifty thousand more,
    each set loose at a chance empty spot and moved by unseen chance steps; it
    stops for good on its third step beside a stopped grain, and only there is
    drawn.

The wall is a square of 1/16 inch cells, 36 inches on a side. One grain is
stopped at a chance cell. Each of the fifty thousand that follow starts at a
chance empty cell and takes unseen chance steps (one cell, up/down/left/right,
uniform); a step that would carry it into a stopped grain or off the wall is
not taken. Every step that leaves it beside a stopped grain (sharing a side) is
counted, and on the third such step it stops for good and is drawn there. The
wandering leaves no mark.

The walk is simulated exactly. Where a grain is far from every stopped grain it
cannot touch one for a while, so many steps are drawn at once from the exact
distribution of that many steps (the sum of m chance steps, sampled in the
diagonal coordinates x+y and x-y, which are independent +-1 walks). The wall's
edge rule -- a step off the wall is not taken -- is reproduced exactly by
walking on a torus twice the wall's width in which the wall and its mirror
images tile the plane, and folding the result back onto the wall.

Run from this directory:  python3 champion.py   (about three minutes)
"""

import os
import time
import numpy as np
from scipy.ndimage import gaussian_filter
from PIL import Image

GRAIN_INCH = 1.0 / 16.0        # one grain is 1/16 inch wide
WALL_INCH = 36.0               # the wall is three feet square
G = int(round(WALL_INCH / GRAIN_INCH))   # 576 grains across
N = 50001                      # one grain, then fifty thousand more
SEED = 11
SIDE = 2500
OUT = os.path.join("renders-champion", "render-1.png")


def grow(G, N, seed, verbose=True):
    """Carry out the instruction; return the cells where grains stopped."""
    T = 2 * G                                   # the wall unfolded: wall + mirrors
    occ = bytearray(T * T)
    kmax = 1
    while (T >> (kmax + 1)) >= 5:
        kmax += 1
    mip = [None]; msz = [0]                     # block pyramid: is any grain near?
    for k in range(1, kmax + 1):
        g = (T + (1 << k) - 1) >> k
        mip.append(bytearray(g * g)); msz.append(g)
    Tm1 = T - 1

    def place(x, y):                            # a wall cell and its three mirrors
        for yy in (y, Tm1 - y):
            for xx in (x, Tm1 - x):
                occ[yy * T + xx] = 1
                for k in range(1, kmax + 1):
                    g = msz[k]; mip[k][(yy >> k) * g + (xx >> k)] = 1

    rng = np.random.default_rng(seed)
    POOL = 1 << 17
    dirs = rng.integers(0, 4, size=POOL).tolist(); di = POOL
    brt = rng.integers(0, G, size=POOL).tolist(); bi = POOL
    bpool = [None] * 40; bidx = [0] * 40

    # one grain stopped at a chance point
    sx = int(rng.integers(0, G)); sy = int(rng.integers(0, G))
    place(sx, sy)
    xs = [sx]; ys = [sy]

    t0 = time.time()
    for n in range(N - 1):
        while True:                             # set loose at a chance empty spot
            if bi + 2 > POOL:
                brt = rng.integers(0, G, size=POOL).tolist(); bi = 0
            x = brt[bi]; y = brt[bi + 1]; bi += 2
            if not occ[y * T + x]:
                break
        contacts = 0
        k = 1
        while True:
            # largest block size whose 3x3 ring holds no grain: nothing can be
            # touched for at least that many steps, so that many are taken at once
            while True:
                g = msz[k]; mk = mip[k]
                bx = x >> k; by = y >> k
                xl = bx - 1 if bx else g - 1
                xr = bx + 1 if bx + 1 < g else 0
                yu = (by - 1 if by else g - 1) * g
                yd = (by + 1 if by + 1 < g else 0) * g
                yc = by * g
                if (mk[yc+bx] or mk[yc+xl] or mk[yc+xr] or mk[yu+bx] or mk[yu+xl]
                        or mk[yu+xr] or mk[yd+bx] or mk[yd+xl] or mk[yd+xr]):
                    k -= 1
                    if k == 0:
                        break
                    continue
                if k == kmax:
                    break
                k2 = k + 1
                g = msz[k2]; mk = mip[k2]
                bx = x >> k2; by = y >> k2
                xl = bx - 1 if bx else g - 1
                xr = bx + 1 if bx + 1 < g else 0
                yu = (by - 1 if by else g - 1) * g
                yd = (by + 1 if by + 1 < g else 0) * g
                yc = by * g
                if (mk[yc+bx] or mk[yc+xl] or mk[yc+xr] or mk[yu+bx] or mk[yu+xl]
                        or mk[yu+xr] or mk[yd+bx] or mk[yd+xl] or mk[yd+xr]):
                    break
                k = k2
            if k:                               # m unseen steps in one draw
                j = k - 1
                m = 1 << j
                p = bpool[j]; i = bidx[j]
                if p is None or i + 2 > len(p):
                    p = rng.binomial(m, 0.5, size=8192).tolist(); bpool[j] = p; i = 0
                bidx[j] = i + 2
                du = 2 * p[i] - m               # x+y after m steps
                dv = 2 * p[i+1] - m             # x-y after m steps
                x = (x + ((du + dv) >> 1)) % T
                y = (y + ((du - dv) >> 1)) % T
                continue
            k = 1
            # one unseen chance step
            if di >= POOL:
                dirs = rng.integers(0, 4, size=POOL).tolist(); di = 0
            d = dirs[di]; di += 1
            if d == 0:
                nx = x + 1 if x + 1 < T else 0; ny = y
            elif d == 1:
                nx = x - 1 if x else Tm1; ny = y
            elif d == 2:
                nx = x; ny = y + 1 if y + 1 < T else 0
            else:
                nx = x; ny = y - 1 if y else Tm1
            if not occ[ny * T + nx]:            # a taken space is not entered
                x = nx; y = ny
            xl = x - 1 if x else Tm1
            xr = x + 1 if x + 1 < T else 0
            yu = (y - 1 if y else Tm1) * T
            yd = (y + 1 if y + 1 < T else 0) * T
            yc = y * T
            if occ[yc + xl] or occ[yc + xr] or occ[yu + x] or occ[yd + x]:
                contacts += 1                   # a step beside a stopped grain
                if contacts == 3:
                    break                       # the third one: it stops for good
        bxp = x if x < G else Tm1 - x           # fold back onto the wall
        byp = y if y < G else Tm1 - y
        place(bxp, byp)
        xs.append(bxp); ys.append(byp)
        if verbose and (n + 1) % 5000 == 0:
            print(f"  {n+1:6d} grains  {time.time()-t0:6.1f}s", flush=True)
    pts = np.empty((len(xs), 2), dtype=np.int32)
    pts[:, 0] = xs; pts[:, 1] = ys
    return pts


def draw(pts, G, out, side=SIDE, q=8, seed=11):
    """White crayon on a black wall: one waxy dab per stopped grain."""
    rng = np.random.default_rng(seed)
    H = G * q
    n = len(pts)
    r = q + 4; c = (r - 1) / 2.0
    gy, gx = np.mgrid[0:r, 0:r].astype(np.float32)
    NK = 8; kers = []
    for _ in range(NK):                         # a few dab shapes, no two alike
        rad = 0.86 * (1.0 + 0.14 * (rng.random() - 0.5))
        ex = 2.4 + 1.4 * rng.random()
        ax = 1.0 + 0.14 * (rng.random() - 0.5)
        u = (gx - c) / (q / 2.0) / ax
        v = (gy - c) / (q / 2.0) * ax
        d = (np.abs(u) ** ex + np.abs(v) ** ex) ** (1.0 / ex)
        t = np.clip((rad - d) / 0.32 + 1.0, 0.0, 1.0)
        kers.append((t * t * (3 - 2 * t)).ravel())
    P = H + 2 * r
    wax = np.zeros(P * P, dtype=np.float32)
    off = ((np.arange(r) + r)[:, None] * P + (np.arange(r) + r)[None, :]).ravel()
    jx = rng.integers(-1, 2, size=n); jy = rng.integers(-1, 2, size=n)
    press = (0.88 + 0.44 * rng.random(n)).astype(np.float32)
    kid = rng.integers(0, NK, size=n)
    base = (pts[:, 1] * q - 2 + jy).astype(np.int64) * P + \
           (pts[:, 0] * q - 2 + jx).astype(np.int64)
    for i in range(NK):
        sel = kid == i
        np.add.at(wax, (base[sel][:, None] + off[None, :]).ravel(),
                  (press[sel][:, None] * kers[i][None, :]).ravel())
    wax = wax.reshape(P, P)[r:r + H, r:r + H]
    tooth = gaussian_filter(rng.random((H, H)).astype(np.float32), 0.14 * q)
    tooth -= tooth.mean(); tooth /= (tooth.std() + 1e-9)
    tooth = np.clip(0.70 + 0.44 * tooth, 0.10, 1.3)     # wax catches on the tooth
    streak = gaussian_filter(rng.random((H, H)).astype(np.float32), (0.6 * q, 5.0 * q))
    streak -= streak.mean(); streak /= (streak.std() + 1e-9)
    tooth *= np.clip(1.0 + 0.09 * streak, 0.7, 1.3)
    cov = np.clip(wax, 0.0, 1.6) * tooth
    cov = gaussian_filter(cov, 0.13 * q)
    cov += gaussian_filter(cov, 0.9 * q) * 0.07 + gaussian_filter(cov, 3.2 * q) * 0.026
    cov = np.clip(cov, 0.0, 1.0)
    mot = gaussian_filter(rng.random((H, H)).astype(np.float32), 1.1 * q)
    mot -= mot.mean(); mot /= (mot.std() + 1e-9)
    grit = gaussian_filter(rng.random((H, H)).astype(np.float32), 0.06 * q)
    grit -= grit.mean(); grit /= (grit.std() + 1e-9)
    wall = np.clip(8.5 + 1.6 * mot + 1.6 * grit, 2.0, 22.0)    # the black wall
    chalk = np.array([253.0, 251.0, 246.0], dtype=np.float32)
    wallc = np.stack([wall, wall, wall * 1.06], axis=-1)
    img = wallc + (chalk[None, None, :] - wallc) * cov[..., None]
    im = Image.fromarray(np.clip(img, 0, 255).astype(np.uint8), "RGB")
    if im.size[0] != side:
        im = im.resize((side, side), Image.LANCZOS)
    os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
    im.save(out)
    return im


def main():
    t0 = time.time()
    pts = grow(G, N, SEED)
    print(f"  {len(pts)} grains stopped on a {WALL_INCH:g}in wall "
          f"({G}x{G} grains, {len(pts)/float(G*G):.1%} of it covered) "
          f"in {time.time()-t0:.0f}s", flush=True)
    draw(pts, G, OUT)
    print(f"  wrote {OUT} ({SIDE}x{SIDE}) in {time.time()-t0:.0f}s total", flush=True)


if __name__ == "__main__":
    main()
