#!/usr/bin/env python3
"""Spell a word in capital letters as an IFS system for fractint.ifs.

    make_word.py WORD            print the block
    make_word.py WORD --write    put it in fractint.ifs (next to this script):
                                 replaces a block of the same name, else appends
    make_word.py WORD --render out.png   also draw the attractor (needs PIL)

Every letter is a few straight strokes (parallelograms), a letter box about
6 x 10 with strokes 1.2 thick, letters 1.8 apart. The attractor is the union of
its own strokes, so each IFS row maps the whole word's bounding box [0,W]x[0,H]
onto ONE stroke: with P the image of the origin, u the image of the x edge and
v the image of the y edge, a=u.x/W, b=v.x/H, c=u.y/W, d=v.y/H, e,f=P. The
probability of a row is its stroke's area over the total area (3 decimals, the
last row takes the rounding so the sum is exactly 1).

Stroke rules (see the 'lars' entry): vertical stems turn the word 90 degrees
along the stroke, bars keep it upright, diagonals run the word ALONG the stroke
(never across it); strokes only touch edge to edge, never overlap (checked, a
warning goes to stderr). Only straight strokes exist, so C G J O Q S U D are
blocky with cut corners.
"""
import re
import sys
import os
import random

T = 1.2      # stroke thickness
DW = 1.4     # horizontal width of a diagonal stroke
H = 10.0     # letter height
GAP = 1.8    # between letters
W6 = 6.0     # default letter width


class Letter:
    """Strokes as (P, u, v) in the letter's own box, x from 0 to width."""

    def __init__(self, width):
        self.width = width
        self.s = []

    def hbar(self, x0, x1, y0, y1):
        self.s.append(((x0, y0), (x1 - x0, 0), (0, y1 - y0)))

    def vbar(self, x0, x1, y0, y1):
        self.s.append(((x1, y0), (0, y1 - y0), (-(x1 - x0), 0)))

    def diag(self, bl, tl, y0, y1, w=DW):
        """Bottom edge from x=bl at y0, top edge from x=tl at y1, both w wide."""
        self.s.append(((bl + w, y0), (tl - bl, y1 - y0), (-w, 0)))


def build(ch):
    t, h = T, H
    if ch == 'A':
        L = Letter(8.0)
        dx = 4.0 - DW
        L.diag(0, dx, 0, h)
        L.diag(8.0 - DW, 8.0 - DW - dx, 0, h)
        mid = h * 0.38   # crossbar between the legs at the width they have there
        x0 = DW + dx * 0.38
        L.hbar(x0, 8.0 - x0, mid - t / 2, mid + t / 2)
    elif ch == 'B':
        L = Letter(W6)
        L.vbar(0, t, 0, h)
        for y0, y1 in ((8.8, h), (4.4, 5.6), (0, t)):
            L.hbar(t, W6 - t, y0, y1)
        L.vbar(W6 - t, W6, 5.6, 8.8)
        L.vbar(W6 - t, W6, t, 4.4)
    elif ch == 'C':
        L = Letter(W6)
        L.vbar(0, t, t, 8.8)
        L.hbar(t, W6, 8.8, h)
        L.hbar(t, W6, 0, t)
        L.vbar(W6 - t, W6, 6.8, 8.8)
        L.vbar(W6 - t, W6, t, 3.2)
    elif ch == 'D':
        L = Letter(W6)
        L.vbar(0, t, 0, h)
        L.hbar(t, W6 - t, 8.8, h)
        L.hbar(t, W6 - t, 0, t)
        L.vbar(W6 - t, W6, t, 8.8)
    elif ch == 'E':
        L = Letter(W6)
        L.vbar(0, t, 0, h)
        for y0, y1 in ((8.8, h), (4.4, 5.6), (0, t)):
            L.hbar(t, W6, y0, y1)
    elif ch == 'F':
        L = Letter(W6)
        L.vbar(0, t, 0, h)
        L.hbar(t, W6, 8.8, h)
        L.hbar(t, W6 - 0.6, 4.4, 5.6)
    elif ch == 'G':
        L = Letter(W6)
        L.vbar(0, t, t, 8.8)
        L.hbar(t, W6, 8.8, h)
        L.hbar(t, W6, 0, t)
        L.vbar(W6 - t, W6, 6.8, 8.8)
        L.vbar(W6 - t, W6, t, 5.2)
        L.hbar(W6 / 2, W6 - t, 4.0, 5.2)
    elif ch == 'H':
        L = Letter(W6)
        L.vbar(0, t, 0, h)
        L.vbar(W6 - t, W6, 0, h)
        L.hbar(t, W6 - t, 4.4, 5.6)
    elif ch == 'I':
        L = Letter(4.0)
        L.hbar(0, 4.0, 8.8, h)
        L.hbar(0, 4.0, 0, t)
        L.vbar(1.4, 2.6, t, 8.8)
    elif ch == 'J':
        L = Letter(W6)
        L.vbar(W6 - t, W6, t, h)
        L.hbar(t, W6 - t, 0, t)
        L.vbar(0, t, t, 3.2)
    elif ch == 'K':
        L = Letter(6.4)
        L.vbar(0, t, 0, h)
        L.diag(t, 6.4 - DW, 5.0, h)
        L.diag(6.4 - DW, t, 0, 5.0)
    elif ch == 'L':
        L = Letter(W6)
        L.vbar(0, t, 0, h)
        L.hbar(t, W6, 0, t)
    elif ch == 'M':
        L = Letter(8.0)
        L.vbar(0, t, 0, h)
        L.vbar(8.0 - t, 8.0, 0, h)
        L.diag(4.0 - DW, t, 3.0, h)
        L.diag(4.0, 8.0 - t - DW, 3.0, h)
    elif ch == 'N':
        L = Letter(W6)
        L.vbar(0, t, 0, h)
        L.vbar(W6 - t, W6, 0, h)
        L.diag(W6 - t - DW, t, 0, h)
    elif ch == 'O':
        L = Letter(W6)
        L.vbar(0, t, t, 8.8)
        L.vbar(W6 - t, W6, t, 8.8)
        L.hbar(t, W6 - t, 8.8, h)
        L.hbar(t, W6 - t, 0, t)
    elif ch == 'P':
        L = Letter(W6)
        L.vbar(0, t, 0, h)
        L.hbar(t, W6 - t, 8.8, h)
        L.hbar(t, W6 - t, 4.4, 5.6)
        L.vbar(W6 - t, W6, 5.6, 8.8)
    elif ch == 'Q':
        L = Letter(W6)
        L.vbar(0, t, t, 8.8)
        L.vbar(W6 - t, W6, t, 8.8)
        L.hbar(t, W6 - t, 8.8, h)
        L.hbar(t, W6 - t, 0, t)
        L.diag(1.8, W6 - t - DW, t, 3.6, w=DW - 0.2)   # tail inside the bowl
    elif ch == 'R':
        L = Letter(W6)
        L.vbar(0, t, 0, h)
        L.hbar(t, W6 - t, 8.8, h)
        L.hbar(t, W6 - t, 4.4, 5.6)
        L.vbar(W6 - t, W6, 5.6, 8.8)
        L.diag(W6 - DW, 2.2, 0, 4.4)
    elif ch == 'S':
        L = Letter(W6)
        L.hbar(t, W6, 8.8, h)
        L.vbar(0, t, 4.4, h)
        L.hbar(t, W6 - t, 4.4, 5.6)
        L.vbar(W6 - t, W6, 0, 5.6)
        L.hbar(0, W6 - t, 0, t)
    elif ch == 'T':
        L = Letter(W6)
        L.hbar(0, W6, 8.8, h)
        L.vbar(W6 / 2 - t / 2, W6 / 2 + t / 2, 0, 8.8)
    elif ch == 'U':
        L = Letter(W6)
        L.vbar(0, t, t, h)
        L.vbar(W6 - t, W6, t, h)
        L.hbar(t, W6 - t, 0, t)
    elif ch == 'V':
        L = Letter(7.0)
        c = 3.5
        L.diag(c - DW, 0, 0, h)
        L.diag(c, 7.0 - DW, 0, h)
    elif ch == 'W':
        L = Letter(10.0)
        L.diag(2.5 - DW, 0, 0, h)
        L.diag(2.5, 5.0 - DW, 0, h)
        L.diag(7.5 - DW, 5.0, 0, h)
        L.diag(7.5, 10.0 - DW, 0, h)
    elif ch == 'X':
        L = Letter(7.0)
        c = 3.5
        L.diag(c - DW, 0, 5.0, h)        # upper arms meet at the middle
        L.diag(c, 7.0 - DW, 5.0, h)
        L.diag(0, c - DW, 0, 5.0)        # lower arms
        L.diag(7.0 - DW, c, 0, 5.0)
    elif ch == 'Y':
        L = Letter(7.0)
        c = 3.5
        L.diag(c - DW, 0, 5.0, h)
        L.diag(c, 7.0 - DW, 5.0, h)
        L.vbar(c - DW / 2, c + DW / 2, 0, 5.0)
    elif ch == 'Z':
        L = Letter(W6)
        L.hbar(0, W6, 8.8, h)
        L.hbar(0, W6, 0, t)
        L.diag(0, W6 - DW, t, 8.8)
    else:
        raise SystemExit("make_word.py: only the letters A-Z, got %r" % ch)
    return L


def word_strokes(word):
    strokes, x = [], 0.0
    for i, ch in enumerate(word):
        L = build(ch)
        for P, u, v in L.s:
            strokes.append(((P[0] + x, P[1]), u, v))
        x += L.width + (GAP if i < len(word) - 1 else 0)
    return strokes, x


def corners(s):
    P, u, v = s
    return [P, (P[0] + u[0], P[1] + u[1]), (P[0] + u[0] + v[0], P[1] + u[1] + v[1]), (P[0] + v[0], P[1] + v[1])]


def inside(pt, poly):
    sgn = None
    for i in range(4):
        a, b = poly[i], poly[(i + 1) % 4]
        cr = (b[0] - a[0]) * (pt[1] - a[1]) - (b[1] - a[1]) * (pt[0] - a[0])
        if abs(cr) < 1e-9:
            continue
        if sgn is None:
            sgn = cr > 0
        elif sgn != (cr > 0):
            return False
    return True


def overlaps(strokes):
    """Pairs of strokes sharing area, found by sampling (touching is fine)."""
    polys = [corners(s) for s in strokes]
    # P, u, v have det > 0 for all, so corners are counter-clockwise or all clockwise: inside() copes with both
    bad = []
    for i in range(len(polys)):
        for j in range(i + 1, len(polys)):
            P, u, v = strokes[i]
            n = 0
            for a in range(1, 8):
                for b in range(1, 8):
                    pt = (P[0] + u[0] * a / 8 + v[0] * b / 8, P[1] + u[1] * a / 8 + v[1] * b / 8)
                    if inside(pt, polys[j]):
                        n += 1
            if n > 2:
                bad.append((i, j, n))
    return bad


def block(word):
    strokes, W = word_strokes(word)
    for i, j, n in overlaps(strokes):
        print("warning: strokes %d and %d overlap (%d of 49 samples)" % (i + 1, j + 1, n), file=sys.stderr)
    rows, tot = [], 0.0
    for P, u, v in strokes:
        area = abs(u[0] * v[1] - u[1] * v[0])
        tot += area
        rows.append([u[0] / W, v[0] / H, u[1] / W, v[1] / H, P[0], P[1], area])
    ps = [round(r[6] / tot, 3) for r in rows]
    ps[-1] = round(ps[-1] + 1 - sum(ps), 3)
    if min(ps) <= 0:
        print("warning: a stroke's probability rounds to %s" % min(ps), file=sys.stderr)
    out = ["%s { ; by Lars" % word.lower()]
    for r, p in zip(rows, ps):
        out.append("  " + " ".join(("%.4f" % x).rstrip('0').rstrip('.') if x else "0" for x in r[:6]) + " %.3f" % p)
    out.append("}")
    return "\n".join(out) + "\n", rows, ps, W


def render(rows, ps, W, path, n=400000, size=900):
    from PIL import Image
    img = Image.new("L", (size, int(size * H / W) + 1), 255)
    px = img.load()
    x = y = 0.0
    cum = []
    s = 0
    for p in ps:
        s += p
        cum.append(s)
    for k in range(n):
        r = random.random()
        for i, c in enumerate(cum):
            if r <= c or i == len(cum) - 1:
                break
        a, b, c_, d, e, f, _ = rows[i]
        x, y = a * x + b * y + e, c_ * x + d * y + f
        if k > 20:
            X, Y = int(x / W * (size - 1)), int((1 - y / H) * (img.size[1] - 1))
            if 0 <= X < img.size[0] and 0 <= Y < img.size[1]:
                px[X, Y] = 0
    img.save(path)


def main():
    args = sys.argv[1:]
    if not args or not args[0].isalpha():
        raise SystemExit(__doc__)
    word = args[0].upper()
    text, rows, ps, W = block(word)
    if "--render" in args:
        render(rows, ps, W, args[args.index("--render") + 1])
    if "--write" not in args:
        print(text, end="")
        return
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fractint.ifs")
    src = open(path).read()
    pat = re.compile(r'^%s \{.*?\n\}\n' % re.escape(word.lower()), re.S | re.M)
    if pat.search(src):
        src = pat.sub(lambda m: text, src, count=1)
    else:
        src = src.rstrip("\n") + "\n\n" + text
    open(path, "w").write(src)
    print("wrote %s (%d rows) to %s" % (word.lower(), len(rows), path))


if __name__ == "__main__":
    main()
