Files
sloop-fm1/tools/gen_icons.py
T
2026-10-04 11:08:49 -04:00

92 lines
3.8 KiB
Python

#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
# Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments
"""Turn the icon atlas into a C header (run by tools/build.py).
gen_icons.py OUT.h [ASSETS_DIR] (default ASSETS_DIR: assets)
Input
icons.json {"cell": 12, "cols": 16, "names": ["generic", "attack", ...]}
names[i] is the cell i of the atlas, row-major; each becomes ICON_<NAME>.
icons.png the atlas, cell x cell pixels per icon, cols cells per row. Any mode:
ink = brightness (or alpha, if the PNG has transparency), quantised to
2 bits: 0 = background, 1 / 2 / 3 = a third / two thirds / full ink.
Output: per icon cell*cell 2-bit pixels, row-major, 4 pixels per byte, first pixel in the
high bits (12 x 12 -> 36 B), plus the enum ICON_<NAME> and FELUCCA_ICONS_N (the number of
drawn icons; 0 when the PNG, the JSON or Pillow is missing, so the firmware builds without).
"""
import json
import re
import sys
from pathlib import Path
ASSETS = Path(__file__).resolve().parents[1] / "assets"
def load(assets):
"""-> (cell, names, [cells of 2-bit pixels] or None, note)"""
try:
meta = json.loads((assets / "icons.json").read_text())
cell, names = int(meta["cell"]), [str(n) for n in meta["names"]]
cols = int(meta.get("cols", 16))
except (OSError, ValueError, KeyError) as e:
return 12, [], None, f"no icons.json ({e.__class__.__name__})"
try:
from PIL import Image
img = Image.open(assets / "icons.png")
except ImportError:
return cell, names, None, "no Pillow"
except OSError:
return cell, names, None, "no icons.png"
if img.mode in ("RGBA", "LA", "PA") or (img.mode == "P" and "transparency" in img.info):
rgba = img.convert("RGBA")
lum, alpha = rgba.convert("L"), rgba.getchannel("A")
ink = lambda x, y: lum.getpixel((x, y)) * alpha.getpixel((x, y)) // 255 # noqa: E731
else:
lum = img.convert("L")
ink = lambda x, y: lum.getpixel((x, y)) # noqa: E731
cells = []
for i in range(len(names)):
ox, oy = (i % cols) * cell, (i // cols) * cell
px = []
for y in range(cell):
for x in range(cell):
inside = ox + x < img.width and oy + y < img.height
px.append((ink(ox + x, oy + y) + 42) // 85 if inside else 0) # 0..255 -> 0..3
cells.append(px)
return cell, names, cells, f"{img.width}x{img.height} {img.mode}"
def main(out, assets=ASSETS):
cell, names, cells, note = load(Path(assets))
lines = ["/* generated by tools/gen_icons.py from assets/icons.png + icons.json */",
"#pragma once", "#include <stdint.h>", f"#define ICON_CELL {cell}"]
ids = []
for n in names:
ident = "ICON_" + re.sub(r"[^A-Z0-9]", "_", n.upper())
if ident in ids:
raise SystemExit(f"gen_icons: duplicate icon name {n!r}")
ids.append(ident)
if ids:
lines.append("enum {")
lines += [f" {ident}," for ident in ids]
lines.append(" ICON_COUNT\n};")
n = len(cells) if cells else 0
lines.append(f"#define FELUCCA_ICONS_N {n}")
if n:
bpi = (cell * cell + 3) // 4
lines.append(f"#define ICON_BYTES {bpi}")
lines.append(f"static const uint8_t ICON_DATA[{n}][{bpi}] = {{")
for name, px in zip(names, cells):
px = px + [0] * (-len(px) % 4)
b = [(px[i] << 6) | (px[i + 1] << 4) | (px[i + 2] << 2) | px[i + 3] for i in range(0, len(px), 4)]
lines.append(" {" + ", ".join(f"0x{v:02x}" for v in b) + f"}}, /* {name} */")
lines.append("};")
Path(out).write_text("\n".join(lines) + "\n")
print(f"icons: {n} of {len(names)} ({note}), {n * ((cell * cell + 3) // 4)} B")
if __name__ == "__main__":
main(*sys.argv[1:])