#!/usr/bin/env python3
"""
Black pencil. From a hundred chance points on the edges, 4 inch lines straight in.
Each end splits into two lines 6 to 9 tenths as long, turned 15 to 45 degrees, one
each way. A line that would cross or come within 1/16 inch of another stops and
splits no more.

Run from inside this folder:   python3 champion.py
Writes:                        renders-champion/render-1.png   (2500 x 2500)

Everything the instruction fixes is fixed here. The choices it leaves open are
collected in CHOICES below and explained in champion-statement.md.
"""

import math
import os

import numpy as np
from PIL import Image

# ---------------------------------------------------------------------------
# What the instruction fixes
# ---------------------------------------------------------------------------
N_POINTS = 100          # "a hundred chance points on the edges"
FIRST_LEN = 4.0         # "4 inch lines straight in"
SHRINK = (0.6, 0.9)     # "6 to 9 tenths as long"
TURN = (15.0, 45.0)     # "turned 15 to 45 degrees, one each way"
CLEAR = 1.0 / 16.0      # "come within 1/16 inch of another"

# ---------------------------------------------------------------------------
# CHOICES - what the instruction leaves open (see champion-statement.md)
# ---------------------------------------------------------------------------
SHEET = 40.0            # the square sheet, in inches
PIXELS = 2500           # the render, square
SEED = 32               # which draw of the hundred chance points is kept
MIN_LEN = CLEAR         # a line shorter than the drawing's own tolerance is not drawn
LINE_MM = 0.9           # the pencil's mark, soft and black
CELL = 0.25             # spatial-hash cell, inches; an implementation detail only

PPI = PIXELS / SHEET


# ===========================================================================
# 1. The drawing, as geometry
# ===========================================================================

def draw_the_lines():
    """Carry out the instruction. Returns arrays of segment endpoints, in inches."""
    rng = np.random.default_rng(SEED)

    cap = 400_000
    AX = np.empty(cap); AY = np.empty(cap)
    BX = np.empty(cap); BY = np.empty(cap)
    n = 0

    grid = {}
    inv = 1.0 / CELL

    def register(i):
        i0 = int(math.floor(min(AX[i], BX[i]) * inv)); i1 = int(math.floor(max(AX[i], BX[i]) * inv))
        j0 = int(math.floor(min(AY[i], BY[i]) * inv)); j1 = int(math.floor(max(AY[i], BY[i]) * inv))
        for a in range(i0, i1 + 1):
            for b in range(j0, j1 + 1):
                grid.setdefault((a, b), []).append(i)

    def nearby(px, py, qx, qy):
        pad = CLEAR + 1e-9
        i0 = int(math.floor((min(px, qx) - pad) * inv)); i1 = int(math.floor((max(px, qx) + pad) * inv))
        j0 = int(math.floor((min(py, qy) - pad) * inv)); j1 = int(math.floor((max(py, qy) + pad) * inv))
        out = []
        for a in range(i0, i1 + 1):
            for b in range(j0, j1 + 1):
                lst = grid.get((a, b))
                if lst:
                    out.extend(lst)
        if not out:
            return np.empty(0, dtype=np.int64)
        return np.unique(np.asarray(out, dtype=np.int64))

    def stop_inside(px, py, dx, dy, L):
        """How far the line may run before it would leave the sheet."""
        t = L
        for o, d in ((px, dx), (py, dy)):
            if d > 1e-12:
                t = min(t, (SHEET - o) / d)
            elif d < -1e-12:
                t = min(t, (0.0 - o) / d)
        return max(min(t, L), 0.0)

    def stop_clear(px, py, dx, dy, L, idx):
        """How far the line may run before it crosses, or comes within 1/16 inch of,
        any line already drawn.  Exact: the line enters the capsule of radius 1/16
        around each drawn segment over a single interval of t, so the earliest entry
        over all of them is where this line stops."""
        if idx.size == 0:
            return L
        ax = AX[idx]; ay = AY[idx]; bx = BX[idx]; by = BY[idx]
        best = L
        c = CLEAR

        # the two round caps of each capsule
        for ex, ey in ((ax, ay), (bx, by)):
            fx = px - ex; fy = py - ey
            b_ = dx * fx + dy * fy
            q = fx * fx + fy * fy - c * c
            disc = b_ * b_ - q
            m = disc >= 0.0
            if m.any():
                sq = np.sqrt(disc[m])
                t1 = -b_[m] - sq
                t2 = -b_[m] + sq
                t1 = np.where(t1 < 0.0, np.where(t2 >= 0.0, 0.0, np.inf), t1)
                v = t1.min()
                if v < best:
                    best = v

        # the straight flank of each capsule
        ex = bx - ax; ey = by - ay
        seglen = np.sqrt(ex * ex + ey * ey)
        ok = seglen > 1e-12
        if ok.any():
            mm = seglen[ok]
            ux = ex[ok] / mm; uy = ey[ok] / mm
            wx = -uy; wy = ux
            gx = px - ax[ok]; gy = py - ay[ok]
            s0 = ux * gx + uy * gy; sd = ux * dx + uy * dy
            n0 = wx * gx + wy * gy; nd = wx * dx + wy * dy
            lo = np.zeros(mm.shape); hi = np.full(mm.shape, L)
            with np.errstate(divide="ignore", invalid="ignore"):
                ta = (0.0 - s0) / sd; tb = (mm - s0) / sd
                tc = (-c - n0) / nd; td = (c - n0) / nd
            pos = sd > 1e-12; neg = sd < -1e-12
            lo = np.where(pos, np.maximum(lo, ta), lo); hi = np.where(pos, np.minimum(hi, tb), hi)
            lo = np.where(neg, np.maximum(lo, tb), lo); hi = np.where(neg, np.minimum(hi, ta), hi)
            bad = (~(pos | neg)) & ((s0 < 0.0) | (s0 > mm))
            pos2 = nd > 1e-12; neg2 = nd < -1e-12
            lo = np.where(pos2, np.maximum(lo, tc), lo); hi = np.where(pos2, np.minimum(hi, td), hi)
            lo = np.where(neg2, np.maximum(lo, td), lo); hi = np.where(neg2, np.minimum(hi, tc), hi)
            bad |= (~(pos2 | neg2)) & (np.abs(n0) > c)
            good = (~bad) & (lo <= hi)
            if good.any():
                v = lo[good].min()
                if v < best:
                    best = v
        return max(best, 0.0)

    # the hundred chance points, and the 4 inch lines straight in from them
    perim = rng.random(N_POINTS) * (4.0 * SHEET)
    waiting = []
    for p in perim:
        if p < SHEET:
            start = (p, 0.0, 0.0, 1.0)
        elif p < 2 * SHEET:
            start = (SHEET, p - SHEET, -1.0, 0.0)
        elif p < 3 * SHEET:
            start = (3 * SHEET - p, SHEET, 0.0, -1.0)
        else:
            start = (0.0, 4 * SHEET - p, 1.0, 0.0)
        waiting.append((*start, FIRST_LEN))

    # all hundred lines first, then all their splits, then all of those
    while waiting and n < cap - 4:
        nxt = []
        for k in rng.permutation(len(waiting)):
            px, py, dx, dy, want = waiting[k]
            reach = stop_inside(px, py, dx, dy, want)
            idx = nearby(px, py, px + dx * reach, py + dy * reach)
            if idx.size:
                # lines that meet this one at its own branch point touch there by
                # construction - its parent and its sibling - and are not "another"
                tol = 1e-7
                at_start = ((np.abs(AX[idx] - px) < tol) & (np.abs(AY[idx] - py) < tol)) | \
                           ((np.abs(BX[idx] - px) < tol) & (np.abs(BY[idx] - py) < tol))
                idx = idx[~at_start]
            got = stop_clear(px, py, dx, dy, reach, idx)
            if got <= 1e-6:
                continue                      # nowhere to go; no mark

            i = n
            AX[i] = px; AY[i] = py
            BX[i] = px + dx * got; BY[i] = py + dy * got
            n += 1
            register(i)

            if got < want - 1e-9:
                continue                      # it stopped, so it splits no more
            if got < MIN_LEN:
                continue

            base = math.atan2(dy, dx)
            for sign in (1.0, -1.0):          # one each way
                ang = base + sign * math.radians(rng.uniform(*TURN))
                ln = got * rng.uniform(*SHRINK)
                if ln >= MIN_LEN:
                    nxt.append((BX[i], BY[i], math.cos(ang), math.sin(ang), ln))
        waiting = nxt

    return AX[:n], AY[:n], BX[:n], BY[:n]


# ===========================================================================
# 2. The drawing, in black pencil on paper
# ===========================================================================

def wobble(rng, n, scale):
    m = max(2, int(n / scale) + 2)
    base = rng.standard_normal(m)
    x = np.linspace(0, m - 1, n)
    i = np.floor(x).astype(int); f = x - i
    return base[i] * (1 - f) + base[np.minimum(i + 1, m - 1)] * f


def field(rng, h, w, scale):
    mh = max(2, int(h / scale) + 2); mw = max(2, int(w / scale) + 2)
    base = rng.standard_normal((mh, mw))
    yy = np.linspace(0, mh - 1, h); xx = np.linspace(0, mw - 1, w)
    iy = np.floor(yy).astype(int); fy = (yy - iy)[:, None]
    ix = np.floor(xx).astype(int); fx = (xx - ix)[None, :]
    iy1 = np.minimum(iy + 1, mh - 1); ix1 = np.minimum(ix + 1, mw - 1)
    a = base[np.ix_(iy, ix)]; b = base[np.ix_(iy, ix1)]
    c = base[np.ix_(iy1, ix)]; d = base[np.ix_(iy1, ix1)]
    return ((a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy).astype(np.float32)


def render(AX, AY, BX, BY):
    rng = np.random.default_rng(SEED * 7919 + 13)
    px = PIXELS
    sigma = max(0.46, (LINE_MM / 25.4) * PPI / 2.6)
    graphite = np.zeros(px * px, dtype=np.float32)

    K = 2 if sigma < 1.0 else 3
    offs = [(dx, dy) for dy in range(-K, K + 1) for dx in range(-K, K + 1)]
    odx = np.array([o[0] for o in offs], dtype=np.float32)[None, :]
    ody = np.array([o[1] for o in offs], dtype=np.float32)[None, :]
    oix = odx.astype(np.int32); oiy = ody.astype(np.int32)

    passes = 3
    for i in range(len(AX)):
        x0, y0 = AX[i] * PPI, AY[i] * PPI
        x1, y1 = BX[i] * PPI, BY[i] * PPI
        L = math.hypot(x1 - x0, y1 - y0)
        if L < 0.3:
            continue
        nsamp = max(2, int(L / 0.4) + 1)
        t = np.linspace(0.0, 1.0, nsamp).astype(np.float32)
        ux, uy = (x1 - x0) / L, (y1 - y0) / L
        nx, ny = -uy, ux

        pressure = 0.66 + 0.66 * rng.random() ** 1.3                 # stroke to stroke
        ends = 0.66 + 0.34 * np.clip(np.minimum(t, 1.0 - t) * L / 2.2, 0.0, 1.0)
        tooth = 1.0 + 0.42 * wobble(rng, nsamp, 6.0) + 0.20 * wobble(rng, nsamp, 1.6)
        w_along = (pressure * ends * np.clip(tooth, 0.22, 2.0)).astype(np.float32)

        for _ in range(passes):
            lat = (0.34 * sigma) * wobble(rng, nsamp, 30.0) + rng.normal(0.0, 0.22 * sigma)
            jit = rng.normal(0.0, 0.16, nsamp)
            cx = x0 + ux * (t * L + jit) + nx * lat
            cy = y0 + uy * (t * L + jit) + ny * lat
            ix = np.floor(cx).astype(np.int32); iy = np.floor(cy).astype(np.int32)
            fx = (cx - ix).astype(np.float32)[:, None]
            fy = (cy - iy).astype(np.float32)[:, None]
            w = np.exp(-((odx - fx) ** 2 + (ody - fy) ** 2) / (2.0 * sigma * sigma))
            w *= (w_along[:, None] / passes)
            gx = ix[:, None] + oix; gy = iy[:, None] + oiy
            ok = (gx >= 0) & (gx < px) & (gy >= 0) & (gy < px)
            flat = (gy * px + gx)[ok].astype(np.int64)
            graphite += np.bincount(flat, weights=w[ok].astype(np.float64),
                                    minlength=px * px).astype(np.float32)

    graphite = graphite.reshape(px, px)

    # the paper's tooth decides how much graphite it takes
    tooth = 0.5 * field(rng, px, px, 2.2) + 0.5 * field(rng, px, px, 9.0)
    graphite *= np.clip(1.0 + 0.62 * tooth, 0.18, 2.1)

    ink = np.clip(1.0 - np.exp(-1.42 * graphite), 0.0, 1.0)[..., None]

    grain = 0.5 * field(rng, px, px, 1.6) + 0.5 * field(rng, px, px, 18.0)
    paper = np.empty((px, px, 3), dtype=np.float32)
    paper[..., 0] = 0.972; paper[..., 1] = 0.966; paper[..., 2] = 0.951
    paper += (grain * 0.012)[..., None]

    black = np.empty((px, px, 3), dtype=np.float32)
    black[..., 0] = 0.152; black[..., 1] = 0.149; black[..., 2] = 0.158
    black += (0.34 * np.exp(-1.8 * graphite))[..., None]          # graphite greys out thin

    return np.clip(paper * (1.0 - ink) + black * ink, 0.0, 1.0)


# ===========================================================================

def main():
    AX, AY, BX, BY = draw_the_lines()
    lengths = np.hypot(BX - AX, BY - AY)
    print(f"{len(AX)} lines, {lengths.sum():.0f} inches of pencil on a "
          f"{SHEET:.0f} inch square")
    img = render(AX, AY, BX, BY)
    here = os.path.dirname(os.path.abspath(__file__))
    out = os.path.join(here, "renders-champion", "render-1.png")
    os.makedirs(os.path.dirname(out), exist_ok=True)
    Image.fromarray((img * 255.0 + 0.5).astype(np.uint8)).save(out)
    print("wrote", out)


if __name__ == "__main__":
    main()
