440 lines · 20.3 KB · PythonRaw
#!/usr/bin/env python3"""Paint the journal's diary (`journal.diary`) as wordless layers into theLoom package's catalogue, procedurally, so it is reproducible from the repo. python3 scripts/paint-diary.py [--out <directory>] [--icon <file.png>]The diary is a cloth-bound book lying open on the bedside table, its lefthalf folded back under it, so one page faces up inside the navy cloth withthe spine's round on its left, the page block's edges showing right andbelow, and the strap with its small brass lock lying out to the right. Thelayers, each a 3x PNG: diary-book the book: its shadow on the table, the cloth cover and spine, the page block, the page (cream, faintly ruled), the strap and the brass lock diary-ribbon-in the ribbon marker's short tail, peeping out under the page block by the spine (the page not starred) diary-ribbon-out the ribbon pulled out: down the page's spine side from the headband and over the foot onto the table (the page starred) diary-seal-great the mood pressed as a wax seal: gold diary-seal-good green diary-seal-okay blue-grey diary-seal-low indigo diary-seal-awful oxblood diary-seal-bare no mood: a plain unpressed disc of pale wax`--icon` paints the app's icon instead: the diary closed, its brass lockfastened, on the walnut bedside table under the lamp (1024 px, opaque).The page's place in `diary-book`, its rules and the ribbon's run are theface's knobs (`JournalDiaryFaceKnobs`); a repainted book owes new knobs.No word, figure or letter is on any layer."""from __future__ import annotationsimport jsonimport sysfrom pathlib import Pathimport numpy as npfrom PIL import Image, ImageDraw, ImageFilterROOT = Path(__file__).resolve().parent.parentCATALOGUE = ROOT / "apps/loom/Sources/CottonPaper/Media.xcassets"# The book's canvas, and its parts' places in it, in pixels (3 a point).W, H = 1260, 1700COVER = (40, 36, 1150, 1570)SPINE = 96 # the round of the spine, from the cover's left edgeBLOCK = (118, 58, 1130, 1550)PAGE = (120, 58, 1110, 1530)STRAP_Y = (770, 846)LOCK = (1168, 728, 1250, 888)RIBBON_X = (148, 184)CLOTH = "#1E2A47"PAPER = "#F3EAD5"RULE = "#9DAFC0"RIBBON = "#7E1420"LEATHER = "#3A2418"BRASS = "#B98A3E"# The page's faint rules, as shares of its height: the header's printed# double rule, then the writing's rules down to the foot.HEADER_RULE = 0.158RULE_TOP = 0.222RULE_STEP = 0.0475RULES = [round(RULE_TOP + i * RULE_STEP, 4) for i in range(16)]SEALS = { "great": "#B98A2C", "good": "#2F6332", "okay": "#5D7080", "low": "#2F3168", "awful": "#561419",}BARE = "#CFC7B5"def rng(seed: int) -> np.random.Generator: return np.random.default_rng(seed)def hexrgb(h: str) -> np.ndarray: h = h.lstrip("#") return np.array([int(h[i : i + 2], 16) for i in (0, 2, 4)], dtype=float)def blur_noise(r: np.random.Generator, shape: tuple[int, int], sigma: float) -> np.ndarray: """Smooth noise of about `sigma` pixels, unit spread.""" white = Image.fromarray(((r.standard_normal(shape) * 40) + 128).clip(0, 255).astype(np.uint8)) out = np.asarray(white.filter(ImageFilter.GaussianBlur(sigma)), dtype=float) return (out - out.mean()) / (out.std() + 1e-9)def mask(shape: tuple[int, int], draw) -> np.ndarray: """A soft-edged mask drawn by `draw(ImageDraw)` at 4x and brought down.""" big = Image.new("L", (shape[1] * 4, shape[0] * 4), 0) draw(ImageDraw.Draw(big), 4) return np.asarray(big.resize((shape[1], shape[0]), Image.LANCZOS), dtype=float) / 255def rrect(box, radius): def draw(d, s): d.rounded_rectangle([v * s for v in box], radius=radius * s, fill=255) return drawdef over(dst: np.ndarray, rgb: np.ndarray, alpha: np.ndarray) -> None: """Lay `rgb` at `alpha` over the premultiplied-free RGBA `dst`, in place.""" a = alpha[..., None] da = dst[..., 3:4] / 255 out_a = a + da * (1 - a) dst[..., :3] = np.where(out_a > 0, (rgb * a + dst[..., :3] * da * (1 - a)) / np.maximum(out_a, 1e-6), 0) dst[..., 3:4] = out_a * 255# MARK: The bookdef paint_book() -> np.ndarray: r = rng(21) yy, xx = np.mgrid[0:H, 0:W].astype(float) canvas = np.zeros((H, W, 4)) lamp = np.clip(1.08 - 0.22 * np.hypot((xx - W * 0.5) / W, (yy - H * 0.3) / H) * 2, 0.8, 1.1)[..., None] # its shadow on the table, soft, a little down and right of the lamp sx0, sy0, sx1, sy1 = COVER shadow = Image.new("L", (W, H), 0) ImageDraw.Draw(shadow).rounded_rectangle([sx0 + 16, sy0 + 30, sx1 + 30, sy1 + 30], radius=40, fill=200) ImageDraw.Draw(shadow).rounded_rectangle([sx1 - 20, STRAP_Y[0] + 14, LOCK[2] + 10, STRAP_Y[1] + 22], radius=20, fill=170) shadow = np.asarray(shadow.filter(ImageFilter.GaussianBlur(26)), dtype=float) / 255 over(canvas, np.zeros(3), shadow * 0.62) # the strap, lying out from under the back cover to the right, and its lock strap = mask((H, W), rrect((sx1 - 60, STRAP_Y[0], LOCK[0] + 30, STRAP_Y[1]), 10)) grain = 0.06 * blur_noise(r, (H, W), 1.2) + 0.05 * blur_noise(r, (H, W), 6) sv = (yy - STRAP_Y[0]) / (STRAP_Y[1] - STRAP_Y[0]) edge = 0.18 * (np.exp(-(sv / 0.08) ** 2) * -0.4 + np.exp(-((1 - sv) / 0.08) ** 2) * -1) leather = hexrgb(LEATHER)[None, None, :] * (1 + grain + edge)[..., None] # the stitching along it, a row of pale dashes each side stitch = np.zeros((H, W)) for y in (STRAP_Y[0] + 9, STRAP_Y[1] - 10): on = ((xx // 14) % 2 == 0) & (np.abs(yy - y) < 1.6) & (xx > sx1 - 10) & (xx < LOCK[0] - 6) stitch += on leather = leather * (1 - 0.0 * stitch[..., None]) + stitch[..., None] * (hexrgb("#8A6A4C")[None, None, :] - leather) * 0.8 over(canvas, leather * lamp, strap) paint_lock(canvas, xx, yy, closed=False) # the cover: navy book cloth, its weave, its edges darker and its corners worn x0, y0, x1, y1 = COVER cover = mask((H, W), rrect(COVER, 26)) weave = 0.05 * np.sin(xx * 2 * np.pi / 3.2) * np.sin(yy * 2 * np.pi / 3.2) + 0.04 * blur_noise(r, (H, W), 0.8) mottle = 0.05 * blur_noise(r, (H, W), 40) inset = np.minimum(np.minimum(xx - x0, x1 - xx), np.minimum(yy - y0, y1 - yy)) rim = -0.28 * np.exp(-np.clip(inset, 0, None) / 7) + 0.10 * np.exp(-((inset - 10) / 4) ** 2) corners = np.zeros((H, W)) for cx, cy in ((x1, y0), (x1, y1), (x0, y1), (x0, y0)): corners += 0.35 * np.exp(-(np.hypot(xx - cx, yy - cy) / 26) ** 2) # the spine's round on the left, lit on its crown u = np.clip((xx - x0) / SPINE, 0, 1) spine = np.where(xx < x0 + SPINE, 0.20 * np.sin(np.pi * u) - 0.25 * (1 - u) ** 3, 0) hinge = -0.30 * np.exp(-((xx - (x0 + SPINE)) / 4) ** 2) light = weave + mottle + rim + corners + spine + hinge cloth = hexrgb(CLOTH)[None, None, :] * (1 + light)[..., None] over(canvas, cloth * lamp, cover) # the headband's red and gold at the spine's top and foot for y in (y0 + 4, y1 - 14): band = mask((H, W), rrect((x0 + 18, y, x0 + SPINE - 4, y + 10), 5)) stripes = np.where((((xx // 5) % 2) == 0)[..., None], hexrgb("#8E2A22"), hexrgb("#C9A458")) over(canvas, stripes * lamp, band) # the page block's edges, right and below the page bx0, by0, bx1, by1 = BLOCK block = mask((H, W), rrect(BLOCK, 6)) leaves = 0.10 * np.sin(np.maximum(xx - PAGE[2], yy - PAGE[3]) * 2 * np.pi / 3.0) + 0.05 * blur_noise(r, (H, W), 1.0) shade = -0.18 * np.clip(np.maximum(xx - PAGE[2], yy - PAGE[3]) / 20, 0, 1) edges = hexrgb("#E6DCC3")[None, None, :] * (1 + leaves + shade)[..., None] over(canvas, edges * lamp, block) # the page: cream, its fibres, curving down into the spine on its left px0, py0, px1, py1 = PAGE page = mask((H, W), rrect(PAGE, 4)) fibres = 0.012 * blur_noise(r, (H, W), 0.7) + 0.006 * blur_noise(r, (H, W), 9) + 0.008 * blur_noise(r, (H, W), 80) gutter = -0.30 * np.exp(-np.clip(xx - px0, 0, None) / 34) - 0.06 * np.exp(-np.clip(xx - px0, 0, None) / 140) foot = -0.05 * np.exp(-np.clip(py1 - yy, 0, None) / 30) - 0.04 * np.exp(-np.clip(px1 - xx, 0, None) / 30) paper = hexrgb(PAPER)[None, None, :] * (1 + fibres + gutter + foot)[..., None] # the faint rules, the header's printed double, then the writing's ph = py1 - py0 ink = np.zeros((H, W)) inside = (xx > px0 + 70) & (xx < px1 - 46) for share, weight in [(HEADER_RULE, 1.0), (HEADER_RULE + 0.006, 0.6)] + [(s, 0.75) for s in RULES]: y = py0 + share * ph ink += weight * np.exp(-((yy - y) / 1.2) ** 2) * inside paper = paper * (1 - 0.32 * np.clip(ink, 0, 1)[..., None]) + hexrgb(RULE)[None, None, :] * 0.32 * np.clip(ink, 0, 1)[..., None] over(canvas, paper * lamp, page) return canvasdef paint_lock(canvas: np.ndarray, xx: np.ndarray, yy: np.ndarray, closed: bool) -> None: """The small brass lock at the strap's end: a rounded plate, bevelled, with its keyhole and two pins.""" lx0, ly0, lx1, ly1 = LOCK plate = mask(canvas.shape[:2], rrect(LOCK, 22)) cx, cy = (lx0 + lx1) / 2, (ly0 + ly1) / 2 inset = np.minimum(np.minimum(xx - lx0, lx1 - xx), np.minimum(yy - ly0, ly1 - yy)) bevel = np.clip(1 - inset / 12, 0, 1) lit = ((xx - cx) + (yy - cy)) < 0 light = np.where(lit, 0.35, -0.35) * bevel ** 1.5 sheen = 0.25 * np.exp(-(((xx - cx + 14) / 26) ** 2 + ((yy - cy + 30) / 50) ** 2)) brushed = 0.04 * np.sin(yy * 2 * np.pi / 2.5) brass = hexrgb(BRASS)[None, None, :] * (1 + light + sheen + brushed)[..., None] over(canvas, brass, plate) # the keyhole: a round and its slot below hole = mask(canvas.shape[:2], lambda d, s: ( d.ellipse([(cx - 11) * s, (cy - 16) * s, (cx + 11) * s, (cy + 6) * s], fill=255), d.polygon([((cx - 6) * s, cy * s), ((cx + 6) * s, cy * s), ((cx + 9) * s, (cy + 30) * s), ((cx - 9) * s, (cy + 30) * s)], fill=255), )) over(canvas, hexrgb("#1A120B"), hole * 0.92) for py in (ly0 + 16, ly1 - 16): pin = mask(canvas.shape[:2], lambda d, s, py=py: d.ellipse([(cx - 6) * s, (py - 6) * s, (cx + 6) * s, (py + 6) * s], fill=255)) over(canvas, hexrgb("#E2C27A"), pin * 0.9)# MARK: The ribbondef ribbon_path(points: list[tuple[float, float]], width: float, notch: bool) -> np.ndarray: """The satin ribbon along `points`, `width` wide, its end cut in a V.""" def draw(d, s): pts = [(x * s, y * s) for x, y in points] d.line(pts, fill=255, width=int(width * s), joint="curve") if notch: (x0, y0), (x1, y1) = points[-2], points[-1] dx, dy = x1 - x0, y1 - y0 n = (dx * dx + dy * dy) ** 0.5 ux, uy = dx / n, dy / n px, py = -uy * width / 2, ux * width / 2 # cut the V out of the end d.polygon([((x1 + px + ux) * s, (y1 + py + uy) * s), ((x1 - ux * width * 0.7) * s, (y1 - uy * width * 0.7) * s), ((x1 - px + ux) * s, (y1 - py + uy) * s), ((x1 + ux * 30) * s, (y1 + uy * 30) * s)], fill=0) return mask((H, W), draw)def paint_ribbon(out: bool) -> np.ndarray: r = rng(31 if out else 32) yy, xx = np.mgrid[0:H, 0:W].astype(float) canvas = np.zeros((H, W, 4)) mid = (RIBBON_X[0] + RIBBON_X[1]) / 2 width = RIBBON_X[1] - RIBBON_X[0] if out: # from the headband, down the page by the spine, over the foot onto the table pts = [(mid - 8, COVER[1] - 6), (mid, PAGE[1] + 40), (mid + 3, PAGE[1] + 700), (mid - 2, PAGE[3] - 10), (mid + 10, COVER[3] + 30), (mid + 40, H - 24)] else: # only its tail, out from under the page block by the spine pts = [(mid, BLOCK[3] - 30), (mid + 6, COVER[3] + 10), (mid + 22, COVER[3] + 70)] ribbon = ribbon_path(pts, width, notch=True) shadow = np.asarray(Image.fromarray((ribbon * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(5)), dtype=float) / 255 shadow = np.roll(np.roll(shadow, 6, axis=0), 4, axis=1) over(canvas, np.zeros(3), shadow * 0.45) # satin: a sheen running along it, a fine twill across sheen = 0.22 * np.sin((xx - mid) / width * np.pi * 1.6 + 0.6) + 0.05 * blur_noise(r, (H, W), 1.0) twill = 0.04 * np.sin((xx + yy) * 2 * np.pi / 4) satin = hexrgb(RIBBON)[None, None, :] * (1 + sheen + twill)[..., None] over(canvas, satin, ribbon) return canvas# MARK: The sealsSEAL = 360def paint_seal(colour: str, pressed: bool, seed: int) -> np.ndarray: """A wax seal from above as a lit height field: an irregular pool of wax, domed, and where pressed a sunk round with a raised rim and a raised eight-petalled flower in it.""" r = rng(seed) n = SEAL yy, xx = np.mgrid[0:n, 0:n].astype(float) c = n / 2 d = np.hypot(xx - c, yy - c) theta = np.arctan2(yy - c, xx - c) wobble = sum(r.normal(0, 4.5 / k) * np.cos(k * theta + r.random() * 6.28) for k in range(2, 9)) radius = 138 + wobble pool = np.clip((radius - d) / 2.0, 0, 1) height = np.clip(radius - d, 0, 22) / 22 height = height ** 0.6 * 1.0 if pressed: well = np.clip((104 - d) / 2.0, 0, 1) rim = np.exp(-((d - 108) / 5) ** 2) * 0.35 petals = 0.5 + 0.5 * np.cos(8 * theta) flower = np.clip((34 + 30 * petals - d) / 3.0, 0, 1) * 0.55 + np.clip((18 - d) / 2.5, 0, 1) * 0.25 ring = np.exp(-((d - 86) / 2.2) ** 2) * 0.3 height = height - 0.55 * well + rim + well * (flower + ring) else: height = height * 0.7 height = height + 0.006 * blur_noise(r, (n, n), 2.5) + 0.02 * blur_noise(r, (n, n), 14) * pool gy, gx = np.gradient(height * 30) normal = np.dstack([-gx, -gy, np.ones_like(gx)]) normal /= np.linalg.norm(normal, axis=2, keepdims=True) light = np.array([-0.5, -0.6, 0.62]) light /= np.linalg.norm(light) lambert = np.clip((normal * light).sum(axis=2), 0, 1) halfway = light + np.array([0, 0, 1.0]) halfway /= np.linalg.norm(halfway) spec = np.clip((normal * halfway).sum(axis=2), 0, 1) ** 40 * (0.55 if pressed else 0.35) base = hexrgb(colour) wax = base[None, None, :] * (0.5 + 0.62 * lambert)[..., None] + 255 * spec[..., None] canvas = np.zeros((n, n, 4)) shadow = np.asarray(Image.fromarray((pool * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(7)), dtype=float) / 255 shadow = np.roll(np.roll(shadow, 7, axis=0), 5, axis=1) over(canvas, np.zeros(3), shadow * 0.42) over(canvas, wax, pool) return canvas# MARK: The icondef paint_icon() -> np.ndarray: """The diary closed on the walnut bedside table under the lamp, its strap fastened with the brass lock, seen from above, a little turned.""" sys.path.insert(0, str(ROOT / "scripts")) import importlib.util spec = importlib.util.spec_from_file_location("grounds", ROOT / "scripts/paint-ground-tiles.py") grounds = importlib.util.module_from_spec(spec) spec.loader.exec_module(grounds) table = grounds.journal_bedside()[:1024, :1024] lamp = grounds.bedside_lamp() / 255 n = 1024 yy, xx = np.mgrid[0:n, 0:n].astype(float) pool = np.clip(1 - np.hypot(xx - n * 0.48, yy - n * 0.42) / (n * 0.75), 0, 1) ** 1.6 canvas = np.dstack([table * (0.62 + 0.55 * pool[..., None]), np.full((n, n), 255.0)]) del lamp # the closed book, drawn at its own canvas then turned and laid on bw, bh = 640, 820 book = np.zeros((bh + 200, bw + 260, 4)) r = rng(41) by, bx = np.mgrid[0 : book.shape[0], 0 : book.shape[1]].astype(float) x0, y0, x1, y1 = 100, 80, 100 + bw, 80 + bh shadow = Image.new("L", (book.shape[1], book.shape[0]), 0) ImageDraw.Draw(shadow).rounded_rectangle([x0 + 14, y0 + 26, x1 + 26, y1 + 30], radius=40, fill=210) shadow = np.asarray(shadow.filter(ImageFilter.GaussianBlur(24)), dtype=float) / 255 over(book, np.zeros(3), shadow * 0.7) # the page block's edge, showing on the right and below the front board block = mask(book.shape[:2], rrect((x0 + 30, y0 + 10, x1 + 6, y1 + 8), 8)) leaves = 0.10 * np.sin(np.maximum(bx - x1 + 14, by - y1 + 10) * 2 * np.pi / 3.0) over(book, hexrgb("#E2D6BA")[None, None, :] * (1 + leaves)[..., None], block) # the front board, navy cloth, the spine's round on the left cover = mask(book.shape[:2], rrect((x0, y0, x1 - 6, y1 - 4), 30)) weave = 0.05 * np.sin(bx * 2 * np.pi / 3.2) * np.sin(by * 2 * np.pi / 3.2) + 0.018 * blur_noise(r, book.shape[:2], 60) inset = np.minimum(np.minimum(bx - x0, x1 - 6 - bx), np.minimum(by - y0, y1 - 4 - by)) rim = -0.3 * np.exp(-np.clip(inset, 0, None) / 8) + 0.12 * np.exp(-((inset - 12) / 4) ** 2) u = np.clip((bx - x0) / 70, 0, 1) spine = np.where(bx < x0 + 70, 0.22 * np.sin(np.pi * u) - 0.25 * (1 - u) ** 3, 0) - 0.3 * np.exp(-((bx - x0 - 70) / 4) ** 2) corners = sum(0.4 * np.exp(-(np.hypot(bx - cx, by - cy) / 30) ** 2) for cx, cy in ((x1, y0), (x1, y1), (x0, y1), (x0, y0))) # a blind-stamped panel on the board, its frame pressed into the cloth panel = np.zeros(book.shape[:2]) px0, py0, px1, py1 = x0 + 140, y0 + 120, x1 - 80, y1 - 120 pin = np.minimum(np.minimum(bx - px0, px1 - bx), np.minimum(by - py0, py1 - by)) panel += -0.22 * np.exp(-(pin / 2.2) ** 2) + 0.10 * np.exp(-((pin + 4) / 2.0) ** 2) cloth = hexrgb(CLOTH)[None, None, :] * (1 + weave + rim + spine + corners + panel)[..., None] over(book, cloth, cover) # the ribbon's tail out at the foot by the spine tail = mask(book.shape[:2], lambda d, s: d.polygon([((x0 + 96) * s, (y1 - 10) * s), ((x0 + 128) * s, (y1 - 10) * s), ((x0 + 140) * s, (y1 + 70) * s), ((x0 + 122) * s, (y1 + 52) * s), ((x0 + 106) * s, (y1 + 74) * s)], fill=255)) over(book, hexrgb(RIBBON), tail) # the strap across the fore-edge, fastened by the lock on the board sy0, sy1 = (y0 + y1) / 2 - 40, (y0 + y1) / 2 + 40 strap = mask(book.shape[:2], rrect((x1 - 170, sy0, x1 + 20, sy1), 12)) grain = 0.06 * blur_noise(r, book.shape[:2], 1.2) over(book, hexrgb(LEATHER)[None, None, :] * (1 + grain)[..., None], strap) global LOCK keep = LOCK LOCK = (x1 - 230, (y0 + y1) / 2 - 90, x1 - 130, (y0 + y1) / 2 + 90) paint_lock(book, bx, by, closed=True) LOCK = keep turned = Image.fromarray(np.clip(book, 0, 255).astype(np.uint8), "RGBA").rotate(-8, resample=Image.BICUBIC, expand=True) turned = np.asarray(turned, dtype=float) oy = (n - turned.shape[0]) // 2 + 20 ox = (n - turned.shape[1]) // 2 + 30 region = canvas[max(oy, 0) : oy + turned.shape[0], max(ox, 0) : ox + turned.shape[1]] piece = turned[max(-oy, 0) : max(-oy, 0) + region.shape[0], max(-ox, 0) : max(-ox, 0) + region.shape[1]] lit = 0.8 + 0.35 * pool[max(oy, 0) : max(oy, 0) + region.shape[0], max(ox, 0) : max(ox, 0) + region.shape[1]] over(region, piece[..., :3] * lit[..., None], piece[..., 3] / 255) return canvas# MARK: Writingdef write(name: str, pixels: np.ndarray, out: Path) -> None: image = Image.fromarray(np.clip(pixels, 0, 255).astype(np.uint8), "RGBA") folder = out / f"{name}.imageset" folder.mkdir(parents=True, exist_ok=True) for old in folder.iterdir(): old.unlink() image.save(folder / f"{name}.png", optimize=True) contents = { "images": [ {"filename": f"{name}.png", "idiom": "universal", "scale": "3x"}, {"filename": f"{name}.png", "idiom": "mac", "scale": "2x"}, ], "info": {"author": "xcode", "version": 1}, "properties": {"preserves-vector-representation": False}, } (folder / "Contents.json").write_text(json.dumps(contents, indent=2) + "\n") print(f"{name}: {image.width} x {image.height}")def main() -> None: args = sys.argv[1:] out = CATALOGUE if "--out" in args: k = args.index("--out") out = Path(args[k + 1]) del args[k : k + 2] if "--icon" in args: k = args.index("--icon") Image.fromarray(np.clip(paint_icon(), 0, 255).astype(np.uint8), "RGBA").convert("RGB").save(args[k + 1]) print(f"icon: {args[k + 1]}") return write("diary-book", paint_book(), out) write("diary-ribbon-in", paint_ribbon(out=False), out) write("diary-ribbon-out", paint_ribbon(out=True), out) for i, (mood, colour) in enumerate(SEALS.items()): write(f"diary-seal-{mood}", paint_seal(colour, pressed=True, seed=50 + i), out) write("diary-seal-bare", paint_seal(BARE, pressed=False, seed=60), out) print("page", [round(v / d, 4) for v, d in zip(PAGE, (W, H, W, H))], "aspect", round(W / H, 4)) print("rules", RULES)if __name__ == "__main__": main()