"""
Grains 1/4 inch square over the whole wall, each by chance bare, gray ink wash,
or flat India ink. Then, three hundred million times, a chance grain takes the
state of one of its four neighbors, chosen by chance. Draw the grains as they
are at the end.

Run:  python3 champion.py   ->  renders-champion/render-1.png  (2500 x 2500)
"""

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

# ---------------------------------------------------------------- the wall
GRAIN_INCH = 0.25          # the instruction's 1/4 inch square grain
WALL_INCH = 125.0          # the wall: 125 in square, 10 ft 5 in on a side
N = int(round(WALL_INCH / GRAIN_INCH))   # 500 grains on a side, 250,000 grains
STEPS = 300_000_000        # three hundred million exchanges
SIZE = 2500                # the drawing, square
PX = SIZE // N             # 5 px to the grain
SEED = 20261119

BARE, WASH, INK = 0, 1, 2

# ------------------------------------------------------------- the states
rng = np.random.default_rng(SEED)
state = rng.integers(0, 3, size=(N, N), dtype=np.uint8)   # each by chance

# ------------------------------------------------------- the three hundred
# million exchanges. Grains are drawn one at a time, in batches of BATCH out
# of 250,000, so each batch is a 0.1 % slice of the wall taken at once.
DR = np.array([-1, 1, 0, 0], dtype=np.int64)
DC = np.array([0, 0, -1, 1], dtype=np.int64)
BATCH = 250

done = 0
while done < STEPS:
    b = min(BATCH, STEPS - done)
    done += b
    r = rng.integers(0, N, size=b)
    c = rng.integers(0, N, size=b)
    d = rng.integers(0, 4, size=b)
    sr = r + DR[d]
    sc = c + DC[d]
    # a grain on an edge has only two or three neighbors: draw again until the
    # neighbor chosen is one that exists on the wall
    bad = (sr < 0) | (sr >= N) | (sc < 0) | (sc >= N)
    while bad.any():
        k = np.flatnonzero(bad)
        d[k] = rng.integers(0, 4, size=k.size)
        sr[k] = r[k] + DR[d[k]]
        sc[k] = c[k] + DC[d[k]]
        bad[k] = (sr[k] < 0) | (sr[k] >= N) | (sc[k] < 0) | (sc[k] >= N)
    state[r, c] = state[sr, sc]

# ------------------------------------------------------------- the drawing
# bare plaster, a gray wash of the same ink, and flat India ink
TONE = np.array([239.0, 143.0, 23.0])      # value of each state
JITTER = np.array([2.2, 5.0, 2.0])         # how much one square differs from
                                           # the next: the wash varies most
# bare plaster runs warm, the wash is near neutral, the ink runs cool
TINT = np.array([[1.006, 1.000, 0.982],
                 [0.997, 1.000, 1.003],
                 [0.985, 0.995, 1.012]])

paint = rng.standard_normal((N, N))
value = TONE[state] + paint * JITTER[state]

big = np.repeat(np.repeat(state, PX, axis=0), PX, axis=1)
grains = np.repeat(np.repeat(value, PX, axis=0), PX, axis=1)

# the surface: a slow unevenness across the plaster, and its tooth
slow = gaussian_filter(rng.standard_normal((SIZE, SIZE)), 70.0)
slow /= np.abs(slow).max() + 1e-12
tooth = gaussian_filter(rng.standard_normal((SIZE, SIZE)), 0.6) * 3.2
img = grains * (1.0 + 0.030 * slow) + tooth

rgb = np.clip(img[..., None] * TINT[big], 0, 255).astype(np.uint8)

out = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                   "renders-champion", "render-1.png")
os.makedirs(os.path.dirname(out), exist_ok=True)
Image.fromarray(rgb).save(out)
print("wrote", out, "grains", N, "x", N, "steps", STEPS)
