Cotton code
611 lines · 25.2 KB · PythonRaw
#!/usr/bin/env python3"""Paint the podcast's transistor radio, layer by layer, into the Loompackage's catalogue.    python3 scripts/paint-radio.py [--out <directory>] [--sheet <png>]The show's radio (`podcast.radio`, CottonFaces' `Cotton/RadioFace.swift`)is a late-fifties portrait transistor radio standing bare on the podcasts'formica counter (12 Nov 2026): a two-tone case, glossy cherry red overcream, parted by a chrome strip; a chrome-bezelled dial window in the red,behind whose glass the show's artwork stands as the tuning card on a creamdial card; a chrome nameplate and a pilot jewel above it; two ivory keysand a chrome button in the cream, and below them a perforated chromespeaker grille between two knurled red knobs.Every layer is painted here as a height field lit from the upper left(the counter's window), the plastics glossy, the chrome reflecting a skyover a dark horizon, each at its place in one 1086 x 1448 cabinet box(`RadioFaceKnobs`, which these rectangles must match). No word, numeral,tick, scale or arrow is on any of them: the face draws those live.    radio-cabinet           the case, its dial window cut out    radio-shadow            its cast shadow, larger than the box    radio-glass-lit         the dial card behind the glass, lit warm (playing)    radio-glass-dim         the same card, unlit (at rest, paused)    radio-glass-sheen       the glass over card, artwork and print: its                            reflection and the bezel's shade on it    radio-plate             the blank chrome nameplate the count is typed on    radio-knob              one knurled red knob, drawn twice (VOL, TUNE)    radio-knob-pointer      its ivory pointer alone, upright, turned live    radio-key-left          the raised left key (back fifteen seconds)    radio-key-pressed-left  its pressed state, registered to it    radio-key-right         the raised right key (on fifteen seconds)    radio-key-pressed-right its pressed state    radio-button-in         the round chrome button pushed in (playing)    radio-button-out        the button out (at rest, paused)    radio-lamp-off          the pilot jewel, dark    radio-lamp-on           the pilot jewel, lit    radio-needle            the red needle, moved live along the scaleEach is a PNG declared 3x (2x on the Mac), as the radio's earlier layerswere. `--sheet` also writes the layers composited as the face lays them,at rest, for looking at. `--icon <png>` writes the app's icon from thesame layers: the radio playing, its dial lit, standing on the formicacounter by the window with the counter's ribbed chrome edge across thefoot, 1024 px square, for `scripts/import-app-icons.py`."""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"BOX = (1086, 1448)# The places, in the box's pixels (x, y, width, height): RadioFaceKnobs.SHADOW = (-80, -80, 1246, 1608)WINDOW = (130, 150, 826, 490)PLATE = (468, 50, 150, 62)LAMP = (125, 25, 130, 130)KEY_BACK = (170, 770, 160, 112)KEY_ON = (756, 770, 160, 112)BUTTON = (480, 766, 126, 126)VOLUME = (90, 1040, 190, 190)TUNE = (806, 1040, 190, 190)NEEDLE = (12, 96)GRILLE = (320, 960, 446, 400)STRIP = (690, 714)  # the chrome strip's top and footLIGHT = np.array([-0.45, -0.55, 0.70])LIGHT = LIGHT / np.linalg.norm(LIGHT)HALF = LIGHT + np.array([0.0, 0.0, 1.0])HALF = HALF / np.linalg.norm(HALF)RED = np.array([196, 40, 38], dtype=float)CREAM = np.array([238, 228, 205], dtype=float)IVORY = np.array([247, 240, 222], dtype=float)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 grid(w: int, h: int) -> tuple[np.ndarray, np.ndarray]:    yy, xx = np.mgrid[0:h, 0:w].astype(float)    return xx + 0.5, yy + 0.5def rrect(xx, yy, x, y, w, h, r) -> np.ndarray:    """Signed distance to a rounded rectangle: negative inside."""    cx, cy = x + w / 2, y + h / 2    qx = np.abs(xx - cx) - (w / 2 - r)    qy = np.abs(yy - cy) - (h / 2 - r)    outside = np.hypot(np.maximum(qx, 0), np.maximum(qy, 0))    return outside + np.minimum(np.maximum(qx, qy), 0) - rdef circle(xx, yy, cx, cy, r) -> np.ndarray:    return np.hypot(xx - cx, yy - cy) - rdef cover(sdf: np.ndarray) -> np.ndarray:    """Anti-aliased coverage of a shape from its distance."""    return np.clip(0.5 - sdf, 0, 1)def bevel(sdf: np.ndarray, width: float, height: float) -> np.ndarray:    """A rounded edge rising `height` over `width` from the outline inward."""    t = np.clip(-sdf / width, 0, 1)    return height * np.sin(t * np.pi / 2)def periodic_noise(r: np.random.Generator, shape, scale: float) -> np.ndarray:    h, w = shape    white = r.standard_normal((h, w))    fy = np.fft.fftfreq(h)[:, None]    fx = np.fft.fftfreq(w)[None, :]    gain = np.exp(-2 * (np.pi ** 2) * ((fx * scale) ** 2 + (fy * scale) ** 2))    out = np.real(np.fft.ifft2(np.fft.fft2(white) * gain))    return (out - out.mean()) / (out.std() + 1e-9)def normals(height: np.ndarray) -> np.ndarray:    gy, gx = np.gradient(height)    n = np.stack([-gx, -gy, np.ones_like(height)], -1)    return n / np.linalg.norm(n, axis=-1, keepdims=True)def plastic(n: np.ndarray, albedo: np.ndarray, gloss: float, shininess: float, ambient: float = 0.42) -> np.ndarray:    """Glossy moulded plastic: lambert under the window's light, a soft    sheen over it and a sharp specular glint."""    diffuse = np.clip(np.einsum("...k,k->...", n, LIGHT), 0, 1)    spec = np.clip(np.einsum("...k,k->...", n, HALF), 0, 1) ** shininess    sheen = np.clip(np.einsum("...k,k->...", n, HALF), 0, 1) ** (shininess / 8)    lit = albedo * (ambient + 0.66 * diffuse)[..., None]    return lit + 255 * (gloss * spec + 0.08 * gloss * sheen)[..., None]def chrome(n: np.ndarray, brushed: np.ndarray | None = None) -> np.ndarray:    """Polished chrome: the reflected sky, a dark horizon band and the    pale counter below, keyed off the reflection's rise, and the window's    glint where the reflection meets the light."""    view = np.array([0.0, 0.0, 1.0])    d = np.einsum("...k,k->...", n, view)    refl = 2 * d[..., None] * n - view    rise = -refl[..., 1]  # +1 the sky above, -1 the counter below    sky = np.interp(rise, [-1, -0.55, -0.3, -0.12, 0.15, 1], [140, 200, 80, 150, 215, 250])    tint = np.stack([sky * 0.97, sky * 0.99, sky * 1.03], -1)    # the counter's mint caught low in the chrome    low = np.clip((-rise - 0.1) / 0.6, 0, 1)[..., None]    tint = tint * (1 - 0.25 * low) + hexrgb("#BFD9C9") * 0.25 * low    glint = np.clip(np.einsum("...k,k->...", refl, LIGHT), 0, 1) ** 60    out = tint + 255 * 0.9 * glint[..., None]    if brushed is not None:        out = out * (1 + 0.05 * brushed)[..., None]    return outdef rgba(rgb: np.ndarray, alpha: np.ndarray) -> np.ndarray:    return np.concatenate([np.clip(rgb, 0, 255), np.clip(alpha, 0, 1)[..., None] * 255], -1)def over(base: np.ndarray, top: np.ndarray) -> np.ndarray:    """`top` over `base`, both RGBA 0..255, unpremultiplied."""    ta = top[..., 3:4] / 255    ba = base[..., 3:4] / 255    a = ta + ba * (1 - ta)    rgb = (top[..., :3] * ta + base[..., :3] * ba * (1 - ta)) / np.maximum(a, 1e-6)    return np.concatenate([rgb, a * 255], -1)# MARK: the cabinetdef cabinet() -> np.ndarray:    w, h = BOX    xx, yy = grid(w, h)    r = np.random.default_rng(21)    case = rrect(xx, yy, 20, 20, w - 40, h - 40, 92)    height = bevel(case, 46, 46)    # the chrome strip, a raised half-round bead across the case    top, foot = STRIP    mid, half = (top + foot) / 2, (foot - top) / 2    strip = np.clip(1 - ((yy - mid) / half) ** 2, 0, 1)    in_strip = (np.abs(yy - mid) < half) & (case < -2)    height = height + np.where(in_strip, 7 * np.sqrt(strip), 0)    # the dial window's chrome bezel: a raised ring, its inside cut out    wx, wy, ww, wh = WINDOW    outer = rrect(xx, yy, wx - 20, wy - 20, ww + 40, wh + 40, 30)    inner = rrect(xx, yy, wx, wy, ww, wh, 14)    ring = (outer < 0) & (inner >= 0)    t = np.clip((-outer) / 20, 0, 1)    height = height + np.where(ring, 10 * np.sin(np.pi * t) + 2, 0)    # the nameplate's seat: a shallow recess    px, py, pw, ph = PLATE    seat = rrect(xx, yy, px - 6, py - 6, pw + 12, ph + 12, 14)    height = height - np.where(seat < 0, bevel(seat, 4, 3), 0)    # the pilot jewel's chrome ring    lx, ly, lw, lh = LAMP    lc = (lx + lw / 2, ly + lh / 2)    jewel_ring = circle(xx, yy, *lc, 40)    ring_t = np.clip(-jewel_ring / 12, 0, 1)    lamp_ring = (jewel_ring < 0) & (jewel_ring > -12)    height = height + np.where(lamp_ring, 6 * np.sin(np.pi * ring_t), 0)    # the keys' and the button's wells, sunk into the cream    wells = []    for kx, ky, kw, kh in (KEY_BACK, KEY_ON):        wells.append(rrect(xx, yy, kx - 4, ky - 4, kw + 8, kh + 8, 18))    bx, by, bw, bh = BUTTON    wells.append(circle(xx, yy, bx + bw / 2, by + bh / 2, bw / 2 + 4))    well = np.minimum.reduce(wells)    height = height - np.where(well < 0, bevel(well, 6, 8), 0)    # the grille: a raised chrome plate, perforated    gx, gy, gw, gh = GRILLE    plate = rrect(xx, yy, gx, gy, gw, gh, 38)    height = height + np.where(plate < 0, bevel(plate, 10, 9), 0)    # whole holes only, the grid centred on the plate with a margin round it    pitch, hole_r, margin = 30, 8.5, 26    cols = int((gw - 2 * margin) // pitch) + 1    rows = int((gh - 2 * margin) // pitch) + 1    x0 = gx + (gw - (cols - 1) * pitch) / 2    y0 = gy + (gh - (rows - 1) * pitch) / 2    ci = np.clip(np.round((xx - x0) / pitch), 0, cols - 1)    ri = np.clip(np.round((yy - y0) / pitch), 0, rows - 1)    hole = np.hypot(xx - (x0 + ci * pitch), yy - (y0 + ri * pitch)) - hole_r    height = height - np.where(hole < 0, bevel(hole, 2.5, 7), 0)    # the knobs' seats: a faint chrome-rimmed boss under each knob    for kx, ky, kw, kh in (VOLUME, TUNE):        boss = circle(xx, yy, kx + kw / 2, ky + kh / 2, kw / 2 - 2)        height = height + np.where(boss < 0, bevel(boss, 6, 3), 0)    smooth = normals(height)    # the moulding's faint orange peel on the plastic alone; the chrome is polished    n = normals(height + 0.3 * periodic_noise(r, (h, w), 26))    red_zone = yy < mid    albedo = np.where(red_zone[..., None], RED, CREAM)    albedo = albedo * (1 + 0.012 * periodic_noise(r, (h, w), 40))[..., None]    out = plastic(n, albedo, gloss=0.55, shininess=90)    # a long soft window reflection across the red's gloss, upper left    streak = np.exp(-(((xx * 0.55 + yy) - 330) / 70) ** 2) * np.clip(1 - xx / 700, 0, 1)    out = out + 255 * 0.10 * (streak * red_zone)[..., None]    brushed = periodic_noise(r, (h, w), 0.8) * 0.5 + periodic_noise(r, (h, w), 6) * 0.5    metal = in_strip | ring | lamp_ring | (plate < 0)    out = np.where(metal[..., None], chrome(smooth, 0.3 * brushed), out)    # the wells' floors in shade, the holes dark with the speaker cloth    out = np.where((well < -6)[..., None], out * 0.86, out)    cloth = hexrgb("#2B2622") * (1 + 0.25 * periodic_noise(r, (h, w), 1.2))[..., None]    deep = np.clip(-hole / 3, 0, 1)[..., None]    out = np.where((hole < 0)[..., None], out * (1 - deep) + cloth * deep, out)    # the nameplate's seat darkened a little, the plate itself laid over it    out = np.where((seat < 0)[..., None], out * 0.9, out)    alpha = cover(case) * (1 - cover(inner))    return rgba(out, alpha)def shadow() -> np.ndarray:    sx, sy, sw, sh = SHADOW    xx, yy = grid(sw, sh)    case = rrect(xx + sx, yy + sy, 20 + 22, 20 + 34, BOX[0] - 40, BOX[1] - 40, 92)    a = cover(case)    img = Image.fromarray((a * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(26))    a = np.asarray(img).astype(float) / 255 * 0.42    contact = Image.fromarray((cover(rrect(xx + sx, yy + sy, 26, 30, BOX[0] - 52, BOX[1] - 46, 92)) * 255).astype(np.uint8))    contact = np.asarray(contact.filter(ImageFilter.GaussianBlur(8))).astype(float) / 255 * 0.35    a = np.clip(a + contact, 0, 0.7)    return rgba(np.zeros((sh, sw, 3)) + hexrgb("#24322C"), a)# MARK: the dial windowdef glass(lit: bool) -> np.ndarray:    _, _, w, h = WINDOW    xx, yy = grid(w, h)    r = np.random.default_rng(31)    card = hexrgb("#F2E2BC") if lit else hexrgb("#CFC6B2")    fibre = 0.012 * periodic_noise(r, (h, w), 1.5) + 0.008 * periodic_noise(r, (h, w), 30)    out = card * (1 + fibre)[..., None]    if lit:        # the dial lamp behind the card, warm at the middle, amber at the rim        d = np.hypot((xx - w * 0.55) / (w * 0.75), (yy - h * 0.5) / (h * 0.85))        glow = np.clip(1 - d, 0, 1) ** 1.3        amber = hexrgb("#E9B865")        out = out * (1 - 0.35 * (1 - glow))[..., None] + amber * (0.35 * (1 - glow))[..., None]        out = out + 255 * 0.06 * glow[..., None]    else:        out = out * (0.92 - 0.06 * np.hypot((xx - w / 2) / w, (yy - h / 2) / h))[..., None]    # the printed rule framing the card, an inch in from the bezel    frame = rrect(xx, yy, 14, 14, w - 28, h - 28, 8)    line = np.clip(1.4 - np.abs(frame), 0, 1)    ink = hexrgb("#7A4A26") if lit else hexrgb("#6E5A44")    out = out * (1 - 0.55 * line)[..., None] + ink * (0.55 * line)[..., None]    return rgba(out, np.ones((h, w)))def glass_sheen() -> np.ndarray:    _, _, w, h = WINDOW    xx, yy = grid(w, h)    # the bezel's shade along the top and the left, where the glass sits under it    edge = np.minimum(xx, yy)    shade = np.exp(-edge / 16) * 0.38    # the sky's reflection, a soft diagonal band from the upper left    band = np.exp(-(((xx * 0.6 + yy) - h * 0.35) / (h * 0.22)) ** 2) * np.clip(1.15 - xx / w, 0, 1)    thin = np.exp(-(((xx * 0.6 + yy) - h * 0.72) / (h * 0.05)) ** 2) * np.clip(1 - xx / w, 0, 1)    white = 0.20 * band + 0.10 * thin    a = shade + white    rgb = (hexrgb("#1F1A16")[None, None, :] * shade[..., None] + 255 * white[..., None]) / np.maximum(a, 1e-6)[..., None]    return rgba(rgb, a)# MARK: the parts laid over the cabinetdef plate() -> np.ndarray:    _, _, w, h = PLATE    xx, yy = grid(w, h)    r = np.random.default_rng(41)    shape = rrect(xx, yy, 1, 1, w - 2, h - 2, 9)    height = bevel(shape, 7, 6)    brushed = periodic_noise(r, (h, w), 0.6)    brushed = np.repeat(brushed[:, :1], w, 1) * 0.6 + brushed * 0.2    out = chrome(normals(height), brushed)    return rgba(out, cover(shape))def lamp(on: bool) -> np.ndarray:    _, _, w, h = LAMP    xx, yy = grid(w, h)    cx, cy, radius = w / 2, h / 2, 28    d = np.hypot(xx - cx, yy - cy)    jewel = d - radius    # a faceted dome: eight facets round a flat table    angle = np.arctan2(yy - cy, xx - cx)    facet = np.cos(8 * angle) * 0.5 + 0.5    dome = np.sqrt(np.clip(1 - (d / radius) ** 2, 0, 1)) * 16 + facet * np.clip(d / radius, 0, 1) * 2.5    n = normals(dome)    base = hexrgb("#E4441E") if on else hexrgb("#5B0F0C")    out = plastic(n, base, gloss=0.9, shininess=180, ambient=0.75 if on else 0.4)    if on:        core = np.clip(1 - d / radius, 0, 1) ** 0.8        out = out + np.array([255, 190, 90])[None, None, :] * (0.55 * core)[..., None]        halo = np.exp(-((d - radius) / 22) ** 2) * (d > radius) * 0.55        halo_rgb = np.array([255, 120, 50], dtype=float)        a = np.maximum(cover(jewel), halo)        rgb = np.where((jewel < 0)[..., None], out, halo_rgb)        return rgba(rgb, a)    return rgba(out, cover(jewel))def needle() -> np.ndarray:    w, h = NEEDLE    xx, yy = grid(w, h)    shape = rrect(xx, yy, 3, 0, w - 6, h, 3)    across = np.clip(1 - np.abs(xx - w / 2) / (w / 2 - 3), 0, 1)    rgb = hexrgb("#C9241B") * (0.7 + 0.45 * across)[..., None]    return rgba(rgb, cover(shape))def knob() -> np.ndarray:    _, _, w, h = VOLUME    xx, yy = grid(w, h)    cx, cy, radius = w / 2, h / 2, 80    d = np.hypot(xx - cx, yy - cy)    angle = np.arctan2(yy - cy, xx - cx)    body = d - radius    # the knurled skirt, a chrome rim, and the dished red face    knurl = (np.cos(72 * angle) * 0.5 + 0.5) * np.clip((d - radius * 0.78) / (radius * 0.22), 0, 1)    height = bevel(body, 14, 20) + 2.2 * knurl    rim = (d > radius * 0.62) & (d < radius * 0.70)    height = height + np.where(rim, 3, 0) - np.where(d < radius * 0.62, 2.5 * (1 - (d / (radius * 0.62)) ** 2), 0)    n = normals(height)    out = plastic(n, RED * 0.95, gloss=0.6, shininess=110)    out = np.where(rim[..., None], chrome(n), out)    # its shadow on the cream, down and right    sh = Image.fromarray((cover(np.hypot(xx - cx - 7, yy - cy - 9) - radius) * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(6))    sh_a = np.asarray(sh).astype(float) / 255 * 0.45    layer = rgba(out, cover(body))    shadow_layer = rgba(np.zeros((h, w, 3)) + hexrgb("#3A2A20"), sh_a)    return over(shadow_layer, layer)def knob_pointer() -> np.ndarray:    _, _, w, h = VOLUME    xx, yy = grid(w, h)    cx, cy = w / 2, h / 2    # an ivory inlay from inside the rim to near the skirt, upright    shape = rrect(xx, yy, cx - 4, cy - 76, 8, 30, 4)    across = np.clip(1 - np.abs(xx - cx) / 4, 0, 1)    rgb = IVORY * (0.82 + 0.2 * across)[..., None]    return rgba(rgb, cover(shape))def key(pressed: bool) -> np.ndarray:    _, _, w, h = KEY_BACK    xx, yy = grid(w, h)    sink = 3 if pressed else 0    shape = rrect(xx, yy, 8, 8 + sink, w - 16, h - 16 - sink, 14)    # a gently domed ivory top, its front edge rounded    dome = bevel(shape, 16, 12) + 4 * np.clip(1 - ((yy - h / 2) / (h / 2)) ** 2, 0, 1)    n = normals(dome)    out = plastic(n, IVORY * (0.93 if pressed else 1), gloss=0.35, shininess=60)    drop = 3 if pressed else 8    sh = Image.fromarray((cover(rrect(xx, yy, 8 + drop * 0.6, 8 + drop, w - 16, h - 16, 14)) * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(4))    sh_a = np.asarray(sh).astype(float) / 255 * 0.40    return over(rgba(np.zeros((h, w, 3)) + hexrgb("#3A2A20"), sh_a), rgba(out, cover(shape)))def button(pushed: bool) -> np.ndarray:    _, _, w, h = BUTTON    xx, yy = grid(w, h)    cx, cy = w / 2, h / 2    radius = 50 if pushed else 54    d = np.hypot(xx - cx, yy - cy)    body = d - radius    dome = np.sqrt(np.clip(1 - (d / radius) ** 2, 0, 1)) * (8 if pushed else 22) + bevel(body, 6, 4)    n = normals(dome)    out = chrome(n) * (0.86 if pushed else 1)    drop = 2 if pushed else 8    sh = Image.fromarray((cover(np.hypot(xx - cx - drop * 0.6, yy - cy - drop) - radius) * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(4))    sh_a = np.asarray(sh).astype(float) / 255 * 0.42    return over(rgba(np.zeros((h, w, 3)) + hexrgb("#3A2A20"), sh_a), rgba(out, cover(body)))LAYERS = {    "radio-cabinet": cabinet,    "radio-shadow": shadow,    "radio-glass-lit": lambda: glass(True),    "radio-glass-dim": lambda: glass(False),    "radio-glass-sheen": glass_sheen,    "radio-plate": plate,    "radio-knob": knob,    "radio-knob-pointer": knob_pointer,    "radio-key-left": lambda: key(False),    "radio-key-pressed-left": lambda: key(True),    "radio-key-right": lambda: key(False),    "radio-key-pressed-right": lambda: key(True),    "radio-button-in": lambda: button(True),    "radio-button-out": lambda: button(False),    "radio-lamp-off": lambda: lamp(False),    "radio-lamp-on": lambda: lamp(True),    "radio-needle": needle,}def write(name: str, pixels: np.ndarray, out: Path) -> Image.Image:    image = Image.fromarray(np.clip(pixels, 0, 255).astype(np.uint8))    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")    return imagedef sheet(layers: dict[str, Image.Image], path: Path, ground: Path | None) -> None:    """The layers as the face lays them, at rest, on the counter."""    pad = 120    canvas = Image.new("RGBA", (BOX[0] + 2 * pad, BOX[1] + 2 * pad), (205, 225, 210, 255))    if ground is not None and ground.exists():        tile = Image.open(ground).convert("RGBA")        for x in range(0, canvas.width, tile.width):            for y in range(0, canvas.height, tile.height):                canvas.paste(tile, (x, y))    def lay(name, rect):        x, y = rect[0], rect[1]        canvas.alpha_composite(layers[name], (x + pad, y + pad))    lay("radio-shadow", SHADOW)    lay("radio-glass-dim", WINDOW)    lay("radio-glass-sheen", WINDOW)    lay("radio-cabinet", (0, 0))    lay("radio-plate", PLATE)    lay("radio-lamp-off", LAMP)    lay("radio-knob", VOLUME)    lay("radio-knob-pointer", VOLUME)    lay("radio-knob", TUNE)    lay("radio-knob-pointer", TUNE)    lay("radio-key-left", KEY_BACK)    lay("radio-key-right", KEY_ON)    lay("radio-button-out", BUTTON)    canvas.convert("RGB").save(path)def icon(layers: dict[str, Image.Image], path: Path) -> None:    side = 1024    tile = Image.open(CATALOGUE / "podcasts-formica.imageset/podcasts-formica.jpg").convert("RGB")    # the formica nearer than on the phone: its boomerangs read at icon size    tile = tile.resize((int(tile.width * 1.6), int(tile.height * 1.6)), Image.LANCZOS)    canvas = Image.new("RGBA", (side, side))    for x in range(0, side, tile.width):        for y in range(0, side, tile.height):            canvas.paste(tile, (x, y))    xx, yy = grid(side, side)    # the window's daylight from the upper left, the room darker toward the foot    light = 1 + 0.16 * np.clip(1 - np.hypot(xx, yy) / (side * 1.1), 0, 1) ** 1.5 - 0.10 * (yy / side) ** 2    pixels = np.asarray(canvas).astype(float)    pixels[..., :3] *= light[..., None]    canvas = Image.fromarray(np.clip(pixels, 0, 255).astype(np.uint8))    # the radio, playing: its layers composited at full size, then scaled    pad = 120    radio = Image.new("RGBA", (BOX[0] + 2 * pad, BOX[1] + 2 * pad), (0, 0, 0, 0))    def lay(name, rect):        radio.alpha_composite(layers[name], (rect[0] + pad, rect[1] + pad))    lay("radio-shadow", SHADOW)    lay("radio-glass-lit", WINDOW)    # the scale's ticks and the needle, as the face prints them, wordless    wx, wy, ww, wh = WINDOW    scale = Image.new("RGBA", (ww, wh), (0, 0, 0, 0))    draw = ImageDraw.Draw(scale)    left, right, base = 160 - wx, 926 - wx, 548 - wy    draw.line([(left, base), (right, base)], fill=(61, 33, 15, 255), width=3)    for k in range(61):        x = left + (right - left) * k / 60        draw.line([(x, base), (x, base - (18 if k % 5 == 0 else 10))], fill=(61, 33, 15, 255), width=3)    # a tuning card of sound: concentric arcs, the broadcast's    cx, cy = ww // 2, (178 - wy) + 145    draw.rounded_rectangle([cx - 145, cy - 145, cx + 145, cy + 145], radius=6, fill=(28, 52, 78, 255))    for r, c in ((40, (243, 170, 92)), (75, (232, 120, 72)), (110, (196, 52, 44))):        draw.arc([cx - 80 - r, cy - r, cx - 80 + r, cy + r], -55, 55, fill=c + (255,), width=14)    draw.ellipse([cx - 98, cy - 18, cx - 62, cy + 18], fill=(243, 170, 92, 255))    radio.alpha_composite(scale, (wx + pad, wy + pad))    lay("radio-needle", (int(160 + 0.38 * 766 - NEEDLE[0] / 2), 500))    lay("radio-glass-sheen", WINDOW)    lay("radio-cabinet", (0, 0))    lay("radio-plate", PLATE)    lay("radio-lamp-on", LAMP)    for rect in (VOLUME, TUNE):        lay("radio-knob", rect)        lay("radio-knob-pointer", rect)    lay("radio-key-left", KEY_BACK)    lay("radio-key-right", KEY_ON)    lay("radio-button-in", BUTTON)    height = 820    width = int(radio.width * height / radio.height)    radio = radio.resize((width, height), Image.LANCZOS)    canvas.alpha_composite(radio, ((side - width) // 2, 40))    # the counter's ribbed chrome edge across the foot    top = 902    band = np.zeros((side - top, side, 3))    yb = np.arange(side - top, dtype=float)[:, None]    ribs = 0.5 + 0.5 * np.cos(2 * np.pi * yb / 14)    sky = np.interp(yb / (side - top), [0, 0.12, 0.5, 0.8, 1], [250, 205, 120, 175, 90])    band[...] = (sky * (0.82 + 0.18 * ribs))[..., None] * np.array([0.97, 0.99, 1.03])    edge = Image.fromarray(np.clip(band, 0, 255).astype(np.uint8)).convert("RGBA")    shade = Image.new("RGBA", (side, 10), (30, 40, 36, 90))    canvas.alpha_composite(shade, (0, top - 6))    canvas.alpha_composite(edge, (0, top))    canvas.convert("RGB").save(path)def main() -> None:    args = sys.argv[1:]    out = CATALOGUE    sheet_path = None    if "--out" in args:        k = args.index("--out")        out = Path(args[k + 1])        del args[k : k + 2]    icon_path = None    if "--icon" in args:        k = args.index("--icon")        icon_path = Path(args[k + 1])        del args[k : k + 2]    if "--sheet" in args:        k = args.index("--sheet")        sheet_path = Path(args[k + 1])        del args[k : k + 2]    layers = {name: write(name, paint(), out) for name, paint in LAYERS.items()}    for name, image in layers.items():        print(f"{name}: {image.width} x {image.height}")    if sheet_path is not None:        sheet(layers, sheet_path, CATALOGUE / "podcasts-formica.imageset/podcasts-formica.jpg")    if icon_path is not None:        icon(layers, icon_path)if __name__ == "__main__":    main()