#!/usr/bin/env python3
"""17 Truchet maze.

A grid of 20 x 25 square tiles. Each tile carries one of three simple designs:
two quarter-circle arcs (in one of two rotations) or a straight crossing. The
ends always meet in the middle of the tile edges, so the tiles join into long
ribbons. The script follows every ribbon through the grid (union-find) and
gives each complete ribbon one colour, which shows the hidden structure: small
rings, long wandering paths and a woven band where the crossings are.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/17-truchet-maze.py
"""
import os, time, math
import numpy as np
from PIL import Image
from scipy import ndimage as ndi

W, H = 1600, 2000
T = 80                        # tile size
C, R = W // T, H // T         # 20 columns, 25 rows
HW = 0.175                    # half width of a ribbon, in tiles
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '17-truchet-maze.png')
F32 = np.float32
rng = np.random.default_rng(1717)


def hexc(s):
    s = s.lstrip('#')
    return np.array([int(s[i:i + 2], 16) for i in (0, 2, 4)], F32) / 255.0


def smoothstep(a, b, x):
    t = np.clip((x - a) / (b - a), 0, 1)
    return t * t * (3 - 2 * t)


# ----------------------------------------------------------------------------
# 1. Choose the tiles. Two slow noise fields steer the choice, so the picture
#    has regions: rings, diagonal waves, and a woven band of crossings.
# ----------------------------------------------------------------------------
def field(sig):
    n = ndi.gaussian_filter(rng.standard_normal((R + 8, C + 8)), sig)[4:-4, 4:-4]
    return (n - n.mean()) / n.std()


rr, cc = np.mgrid[0:R, 0:C]
parity = (rr + cc) % 2
n_or, n_cr = field(2.7), field(3.0)
# Orientation: where the bias is strong the tiles follow the checkerboard (this
# makes rings) or oppose it (this makes long diagonal waves); elsewhere random.
p_ring = 1 / (1 + np.exp(-2.6 * n_or))
orient = np.where(rng.random((R, C)) < 0.72, np.where(rng.random((R, C)) < p_ring, parity, 1 - parity),
                  rng.integers(0, 2, (R, C)))
# Crossings: mostly inside a diagonal band.
band = np.exp(-((cc / C - 0.5) * 0.9 + (rr / R - 0.5) * 1.15 + 0.02) ** 2 / (2 * 0.16 ** 2))
p_cross = np.clip(0.06 + 0.62 * band + 0.10 * n_cr, 0, 0.9)
kind = np.where(rng.random((R, C)) < p_cross, 2, orient)       # 0, 1: arcs; 2: crossing

# ----------------------------------------------------------------------------
# 2. Follow the ribbons. Every tile edge has one port; a tile joins its four
#    ports in two pairs. Union-find gives every ribbon an identity.
# ----------------------------------------------------------------------------
NH = (R + 1) * C


def hid(r, c): return r * C + c                        # port on the top edge of tile (r, c)
def vid(r, c): return NH + r * (C + 1) + c             # port on the left edge of tile (r, c)


parent = np.arange(NH + R * (C + 1))


def find(a):
    while parent[a] != a:
        parent[a] = parent[parent[a]]
        a = parent[a]
    return a


def union(a, b):
    ra, rb = find(a), find(b)
    if ra != rb:
        parent[ra] = rb


for r in range(R):
    for c in range(C):
        N, S, Wp, E = hid(r, c), hid(r + 1, c), vid(r, c), vid(r, c + 1)
        k = kind[r, c]
        if k == 0: union(N, Wp); union(S, E)
        elif k == 1: union(N, E); union(S, Wp)
        else: union(N, S); union(Wp, E)
root = np.array([find(a) for a in range(parent.size)])
# Length of each ribbon = number of tile pieces it has.
length = np.zeros(parent.size, int)
for r in range(R):
    for c in range(C):
        length[root[hid(r, c)]] += 1                   # the piece that holds the N port
        k = kind[r, c]
        length[root[hid(r + 1, c)] if k != 2 else root[vid(r, c)]] += 1
# Does the ribbon leave the picture? (then it is not a closed loop)
open_path = np.zeros(parent.size, bool)
for c in range(C):
    open_path[root[hid(0, c)]] = True; open_path[root[hid(R, c)]] = True
for r in range(R):
    open_path[root[vid(r, 0)]] = True; open_path[root[vid(r, C)]] = True

# Colours: small closed rings are gold, the others take a colour from the palette.
PAL = ['#2aa79f', '#e2674a', '#f3ead3', '#4a7dc4', '#c9628c', '#7fb8c9']
WEI = [0.24, 0.22, 0.16, 0.18, 0.10, 0.10]
pcol = np.zeros((parent.size, 3), F32)
for a in np.unique(root):
    if length[a] <= 4 and not open_path[a]:
        pcol[a] = hexc('#f0b93a')
    else:
        pcol[a] = hexc(PAL[rng.choice(len(PAL), p=WEI)]) * rng.uniform(0.9, 1.06)
# The longest ribbon is always cream, so that it reads as the main thread.
longest = np.argmax(length)
pcol[longest] = hexc('#f6efdc')
print('ribbons: %d, longest %d pieces' % (len(np.unique(root)), length.max()))

# ----------------------------------------------------------------------------
# 3. Draw. For every pixel: distance to the centre line of the two pieces in its tile.
# ----------------------------------------------------------------------------
yy, xx = np.mgrid[0:H, 0:W].astype(F32)
tx = np.minimum((xx / T).astype(int), C - 1); ty = np.minimum((yy / T).astype(int), R - 1)
u = xx / T - tx + 0.5 / T; v = yy / T - ty + 0.5 / T
k = kind[ty, tx]

dA = np.select([k == 0, k == 1], [np.abs(np.hypot(u, v) - 0.5), np.abs(np.hypot(1 - u, v) - 0.5)], np.abs(u - 0.5))
dB = np.select([k == 0, k == 1], [np.abs(np.hypot(1 - u, 1 - v) - 0.5), np.abs(np.hypot(u, 1 - v) - 0.5)], np.abs(v - 0.5))
# Piece A always holds the N port; piece B holds S (arcs) or W (crossing).
idA = root[hid(ty, tx)]
idB = np.where(k == 2, root[vid(ty, tx)], root[hid(ty + 1, tx)])
# In a crossing, which piece is on top alternates like a real weave.
a_over = (k != 2) | (((tx + ty) % 2) == 0)

# Background: deep navy with a soft woven texture and a vignette.
tex = ndi.gaussian_filter(rng.standard_normal((H, W)).astype(F32), (0.6, 3)) + ndi.gaussian_filter(
    rng.standard_normal((H, W)).astype(F32), (3, 0.6))
tex /= tex.std()
vig = 1 - 0.35 * (((xx - W / 2) / (W * 0.72)) ** 2 + ((yy - H / 2) / (H * 0.72)) ** 2)
bg = hexc('#111827')[None, None, :] * (1.0 + 0.10 * tex[..., None]) * vig[..., None]
# Small studs on the tile corners.
cu = np.abs(xx / T - np.round(xx / T)) * T; cv = np.abs(yy / T - np.round(yy / T)) * T
stud_d = np.hypot(cu, cv)
stud = 1 - smoothstep(3.6, 5.0, stud_d)
bg = bg * (1 - stud[..., None]) + hexc('#8f7a45') * stud[..., None] * (0.75 + 0.25 * (1 - stud_d / 6))[..., None]


def ribbon(d, pid):
    """Colour and coverage of a ribbon piece, from the distance d to its centre line."""
    s = np.clip(d / HW, 0, 1.2)
    cover = 1 - smoothstep(HW - 0.9 / T, HW + 0.9 / T, d)
    base = pcol[pid]
    # Rounded cord: light in the middle, darker at the sides, with a dark outline
    # and two fine inlaid lines.
    round_ = 0.62 + 0.42 * np.sqrt(np.clip(1 - s * s, 0, 1))
    inlay = 1 - 0.30 * (1 - smoothstep(0.02, 0.05, np.abs(s - 0.60)))
    outline = smoothstep(0.80, 0.93, s)
    col = base * (round_ * inlay)[..., None]
    col = col * (1 - outline[..., None]) + base * 0.22 * outline[..., None]
    # a little sheen along the middle
    col += (np.clip(1 - s / 0.28, 0, 1) ** 2 * 0.10)[..., None]
    return col, cover


colA, covA = ribbon(dA, idA)
colB, covB = ribbon(dB, idB)

# Drop shadow of all ribbons on the background.
allcov = np.maximum(covA, covB)
sh = ndi.shift(ndi.gaussian_filter(allcov, 6), (8, 5), order=1, mode='nearest')
img = bg * (1 - 0.62 * sh[..., None])

# Under-piece first, then the over-piece; the over-piece shades the one below near its edges.
under_col = np.where(a_over[..., None], colB, colA); under_cov = np.where(a_over, covB, covA)
over_col = np.where(a_over[..., None], colA, colB); over_cov = np.where(a_over, covA, covB)
over_d = np.where(a_over, dA, dB)
contact = 1 - 0.78 * (1 - smoothstep(HW - 0.01, HW + 0.17, over_d)) * (k == 2)
under_col = under_col * contact[..., None]
img = img * (1 - under_cov[..., None]) + under_col * under_cov[..., None]
img = img * (1 - over_cov[..., None]) + over_col * over_cov[..., None]

# Finish: soft light from the upper left, faint fabric texture on the ribbons, grain.
light = 1.08 - 0.22 * (xx / W * 0.5 + yy / H * 0.5)
img *= light[..., None]
img *= (1 + 0.035 * tex * allcov)[..., None]
glow = np.stack([ndi.gaussian_filter(img[..., c], 22) for c in range(3)], -1)
img = img + 0.10 * glow
img = np.clip(img, 0, 1) ** 0.95

# Mat and frame line: the weave is seen through a window, with a soft inner shadow.
e = np.minimum(np.minimum(xx, W - 1 - xx), np.minimum(yy, H - 1 - yy))
MAT = 40.0
img *= (0.62 + 0.38 * smoothstep(MAT, MAT + 34, e))[..., None]
mat = 1 - smoothstep(MAT - 0.7, MAT + 0.7, e)
mat_col = hexc('#0d1220')[None, None, :] * (1.0 + 0.10 * tex[..., None])
img = img * (1 - mat[..., None]) + mat_col * mat[..., None]
line = 1 - smoothstep(1.2, 2.4, np.abs(e - (MAT - 9)))
img = img * (1 - line[..., None]) + hexc('#b99a52') * line[..., None]
img += rng.standard_normal((H, W, 1)).astype(F32) * 0.006
Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)).save(OUT)
print('saved', os.path.normpath(OUT), '%.1fs' % (time.time() - T0))
