Cotton code
110 lines · 4.5 KB · PythonRaw
#!/usr/bin/env python3"""Write the generated caps and plaster into `apps/loom/Sources/CottonPaper/Media.xcassets`.    python3 scripts/gen-caps/export_caps.py <out-dir from make_caps.py>Each cap is cropped on its SOLID alpha (alpha > 200 — the soft contact shadowis not the cap) to a square with a 5 % pad, centred, and resized to 600 px, soevery enamel lands at the same size on the board whatever the generator didwith the frame. The plaster becomes a seamless 1024 px TILE (a 1024 squarefrom the middle of the picture, mirrored four ways and halved), written asJPEG at the imageset's 2x scale — so it tiles at 512pt and `PageGroundFill`needs no screen geometry to draw it. It is written as grey RELIEF (`relief`),never as a colour: the page's colour is the `ground_muted` token.    python3 scripts/gen-caps/export_caps.py --reliefre-derives the two committed tiles as relief in place.Needs Pillow (`python3 -m pip install pillow`)."""import pathlib, sysfrom PIL import ImageROOT = pathlib.Path(__file__).resolve().parents[2]CATALOGUE = ROOT / "apps/loom/Sources/CottonPaper/Media.xcassets"CAPS = ["cream", "red", "navy", "yellow", "green", "silver", "orange", "burgundy", "sky", "pink", "black", "teal", "empty"]def trimmed(path, size=600, pad=0.05):    im = Image.open(path).convert("RGBA")    solid = im.getchannel("A").point(lambda v: 255 if v > 200 else 0)    bb = solid.getbbox()    if bb is None:        raise SystemExit(f"{path}: nothing opaque in it")    side = max(bb[2] - bb[0], bb[3] - bb[1])    side = int(side * (1 + 2 * pad))    cx, cy = (bb[0] + bb[2]) // 2, (bb[1] + bb[3]) // 2    canvas = Image.new("RGBA", (side, side), (0, 0, 0, 0))    canvas.alpha_composite(im, (side // 2 - cx, side // 2 - cy))    return canvas.resize((size, size), Image.LANCZOS)def tile(plaster, size=1024):    im = Image.open(plaster).convert("RGB")    c = im.crop((0, (im.height - size) // 2, size, (im.height - size) // 2 + size))    m = Image.new("RGB", (size * 2, size * 2))    m.paste(c, (0, 0))    m.paste(c.transpose(Image.FLIP_LEFT_RIGHT), (size, 0))    m.paste(c.transpose(Image.FLIP_TOP_BOTTOM), (0, size))    m.paste(c.transpose(Image.ROTATE_180), (size, size))    return m.resize((size, size), Image.LANCZOS)# THE PLASTER CARRIES RELIEF, NOT COLOUR. The tile is grey, centred on 128,# and `PageGroundFill` lays it over the page's ground token with `.overlay`.# Overlay at 50 % grey leaves the colour under it exactly where it was, and it# is linear in the tile over a light ground, so the page's MEAN is the token's# hex to the unit. The colour of the page is then a palette decision# (`ground_muted`, `crates/cotton-core/src/design/palette.rs`) rather than a# property of a photograph. `RELIEF_STD` is the spread of the grey around 128:# overlay over a ground near 230 turns 10 of grey spread into about 2 of# luminance spread, which is the spread the colour plaster had.RELIEF_STD = 10.0def relief(image, std=RELIEF_STD):    """The tile as grey relief: luminance re-centred on 128 at `std` spread.    Idempotent, so the committed tiles can be re-derived from themselves    (`--relief`) when no generator output is to hand."""    from PIL import ImageStat    grey = image.convert("L")    stat = ImageStat.Stat(grey)    mean, spread = stat.mean[0], stat.stddev[0] or 1.0    # Written as RGB: a grey-colour-space JPEG is one more thing for the    # catalogue and the blend to interpret, and the bytes saved are few.    return grey.point(lambda v: max(0, min(255, int(round(128 + (v - mean) * std / spread))))).convert("RGB")def rewrite_relief():    """Re-derive the committed plaster tile as relief, in place."""    path = CATALOGUE / "home-plaster.imageset" / "home-plaster.jpg"    relief(Image.open(path)).save(path, quality=90, optimize=True)    print("wrote", path.relative_to(ROOT))def main():    if sys.argv[1:] == ["--relief"]:        rewrite_relief()        return    src = pathlib.Path(sys.argv[1])    for name in CAPS:        f = src / f"cap-{name}.png"        if not f.exists():            print("skip", name)            continue        dest = CATALOGUE / f"cap-{name}.imageset" / f"cap-{name}.png"        dest.parent.mkdir(parents=True, exist_ok=True)        trimmed(f).save(dest, optimize=True)        print("wrote", dest.relative_to(ROOT))    light = src / "plaster.png"    if light.exists():        d = CATALOGUE / "home-plaster.imageset"        relief(tile(light)).save(d / "home-plaster.jpg", quality=90, optimize=True)        print("wrote the plaster tile as relief")if __name__ == "__main__":    main()