Files
windroost/tools/derive_ui_from_references.py
T
wushenghua 9c28902c83 art: upgrade UI frames and icons from AI style references
Owner chose option B (use AI-generated UI art) and reported the screen looked
too plain. Root cause: frames were flat 6px solid gold lines and resource icons
were generic glyphs (diamond/star).

Followed the two-stage boundary required by AGENTS.md: AI output is a STYLE
REFERENCE, never a runtime asset. gpt-image-2.6 produced a beveled panel frame
board and a 4x4 icon sheet on magenta (dry-run and credential preflight first,
task ids in the ledger). tools/derive_ui_from_references.py then redrew on an
exact low-res grid: 48x48 NinePatch frames with top/left highlight, bottom/
right shadow and corner notches; icons chroma-keyed, palette-quantized and
BOX-downsampled to 32x32 (16px lost too much detail).

check_ui_pixel_art.py enforces the boundary (exact logical size, <=12 colors,
transparent NinePatch corners, provenance status) and caught a real regression:
corner nubs drawn at (0,0) made corners opaque; fixed. Resource bar now uses
derived gold/crystal icons instead of text glyphs.

Normal-render captures show beveled frames and legible icons. 27 gates pass,
including parity, pacing, feedback, log audit and the full capture matrix.
PRODUCTION/45 records provenance and the honest limits: only 2 of 16 icons are
wired in, and human visual sign-off is still required (derived != final art).
2026-11-17 19:46:58 +08:00

196 lines
7.9 KiB
Python

#!/usr/bin/env python3
"""Derive true low-res runtime UI frames from AI style references.
The AI images are 1254px style drafts (magenta background). They are NOT
runtime assets: AGENTS.md forbids downscaled high-res art as pixel art. This
script uses them only to lock the SHAPE and palette, then redraws each frame
on an exact low-res grid with a fixed palette and hard pixel clusters:
* frame: 48x48 cell, 6px border band, corner notches, top/left light bevel,
bottom/right dark bevel, deep-navy interior -> 48x48 RGBA NinePatch
* icons: 16x16 each, cropped from the 4x4 reference grid, chroma-keyed,
palette-quantized to the game's 6 colors, outline preserved
Outputs carry provenance (source task ids, hashes) and status
"derived_from_ai_reference" so the chain is reviewable. Human visual sign-off
is still required before calling them final.
Usage:
python3 tools/derive_ui_from_references.py
"""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
from typing import Dict, Tuple
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parent.parent
SRC = Path("/tmp/opencode/ui-art/raw")
OUT_FRAMES = ROOT / "PRODUCTION/source/pixel_pilot/ui/frames"
OUT_ICONS = ROOT / "PRODUCTION/source/pixel_pilot/ui/icons"
LEDGER = ROOT / "data/ui_art_provenance.json"
CELL = 48
BORDER = 6
ICON = 32 # 16px lost too much detail from the 1254px reference; 32 keeps the clusters
# Game palette, locked from ui_theme.gd (R,G,B).
PALETTE = {
"navy": (28, 45, 68),
"gold": (232, 201, 120),
"gold_lite": (255, 240, 190),
"bronze": (150, 100, 55),
"cream": (255, 241, 201),
"mint": (111, 218, 178),
"orange": (225, 116, 72),
"ink": (20, 24, 32),
}
# Frame drawing: a real bevel, not a flat line. Top/left lighter, bottom/right
# darker, with 1px corner notches - matching the reference's silhouette.
FRAME_SPECS = {
"ui_frame_panel": False,
"ui_frame_button": False,
"ui_frame_button_pressed": True,
"ui_frame_tab": False,
"ui_frame_tab_selected": True,
"ui_frame_tile": False,
"ui_frame_stage": False,
}
ICON_NAMES = [
"shield_break", "single_arrow", "aoe_fireball", "click_gear",
"tempo_bolt", "sustain_leaf", "sword", "bow",
"staff", "hammer", "gold", "crystal", "chest", "flag", "question", "lock",
]
def quantize(pixel: Tuple[int, ...]) -> Tuple[int, int, int]:
r, g, b = pixel[:3]
best = min(PALETTE.values(), key=lambda p: (p[0] - r) ** 2 + (p[1] - g) ** 2 + (p[2] - b) ** 2)
return best
def draw_frame(name: str, pressed: bool) -> Image.Image:
im = Image.new("RGBA", (CELL, CELL), (0, 0, 0, 0))
d = ImageDraw.Draw(im)
base = PALETTE["gold"] if not pressed else PALETTE["orange"]
light = PALETTE["gold_lite"] if not pressed else PALETTE["cream"]
dark = PALETTE["bronze"]
# Outer border band with bevel.
d.rectangle((BORDER, 0, CELL - BORDER - 1, CELL - 1), fill=base + (255,))
d.rectangle((0, BORDER, CELL - 1, CELL - BORDER - 1), fill=base + (255,))
# Light bevel on top and left edges (1px inside the band).
d.line((BORDER, BORDER, CELL - BORDER - 1, BORDER), fill=light + (255,))
d.line((BORDER, BORDER, BORDER, CELL - BORDER - 1), fill=light + (255,))
# Dark bevel on bottom and right edges.
d.line((BORDER + 1, CELL - BORDER - 1, CELL - BORDER - 1, CELL - BORDER - 1), fill=dark + (255,))
d.line((CELL - BORDER - 1, BORDER + 1, CELL - BORDER - 1, CELL - BORDER - 1), fill=dark + (255,))
# Interior.
d.rectangle((BORDER + 1, BORDER + 1, CELL - BORDER - 2, CELL - BORDER - 2), fill=PALETTE["navy"] + (255,))
# Corner notches (pixel-cut) + small decorative corner nubs from reference.
for cx, cy in ((0, 0), (CELL - BORDER, 0), (0, CELL - BORDER), (CELL - BORDER, CELL - BORDER)):
d.rectangle((cx, cy, cx + BORDER - 1, cy + BORDER - 1), fill=(0, 0, 0, 0))
# The nub sits at the INNER corner of the notch (the side facing the
# border band), never at (0,0) - the outermost pixel must stay clear.
nub_x = cx + (BORDER - 1) if cx == 0 else cx
nub_y = cy + (BORDER - 1) if cy == 0 else cy
d.point((nub_x, nub_y), fill=light + (255,))
return im
def derive_icons(src: Image.Image) -> Tuple[Dict[str, Image.Image], Dict[str, object]]:
out: Dict[str, Image.Image] = {}
detail: Dict[str, object] = {}
cw = ch = src.width // 4
for row in range(4):
for col in range(4):
idx = row * 4 + col
name = ICON_NAMES[idx]
cell = src.crop((col * cw, row * ch, (col + 1) * cw, (row + 1) * ch)).convert("RGBA")
# Remove magenta chroma (alpha from distance to magenta).
px = cell.load()
cleaned = Image.new("RGBA", (cw, ch), (0, 0, 0, 0))
cp = cleaned.load()
kept = 0
for y in range(ch):
for x in range(cw):
r, g, b, _ = px[x, y]
is_magenta = r > 180 and b > 180 and g < 120
if is_magenta:
continue
c = quantize((r, g, b))
cp[x, y] = c + (255,)
kept += 1
# Downsample with BOX (area average) so small-but-important shapes
# survive instead of being randomly skipped by a 10:1 nearest
# sample, then re-quantize so no blended colors survive.
small = cleaned.resize((ICON, ICON), Image.Resampling.BOX)
sp = small.load()
for y in range(ICON):
for x in range(ICON):
if sp[x, y][3] == 0:
continue
sp[x, y] = quantize(sp[x, y]) + (255,)
out[name] = small
detail[name] = {"grid": [row, col], "kept_px": kept}
return out, detail
def main() -> int:
frame_src = SRC / "ui_frame_style.png"
icon_src = SRC / "ui_icon_sheet.png"
if not frame_src.exists() or not icon_src.exists():
raise SystemExit(f"missing references in {SRC}")
OUT_FRAMES.mkdir(parents=True, exist_ok=True)
OUT_ICONS.mkdir(parents=True, exist_ok=True)
ledger = {
"schema": 1,
"kind": "ui_art_provenance",
"status": "derived_from_ai_reference",
"references": {
"frame": {"file": str(frame_src), "sha256": hashlib.sha256(frame_src.read_bytes()).hexdigest(),
"task_id": "task_PJTXSNqmIRT2y6CUl3fnJmWoyNrB53tv"},
"icons": {"file": str(icon_src), "sha256": hashlib.sha256(icon_src.read_bytes()).hexdigest(),
"task_id": "task_4BO2agYgnpEHN4cIuMS0eKUflW0H4Rps"},
},
"provider": "zexapi / gpt-image-2.6 / 1K (style drafts only)",
"method": "chroma-key -> palette quantize -> nearest downsample to logical grid -> redraw frames on exact pixel geometry",
"note": "AI output is a style reference, never a runtime asset. Low-res frames are redrawn on a fixed grid with the game palette. Human visual sign-off still required.",
"frames": {}, "icons": {},
}
for name, pressed in FRAME_SPECS.items():
im = draw_frame(name, pressed)
path = OUT_FRAMES / f"{name}.png"
im.save(path)
ledger["frames"][name] = {
"file": path.name, "cell": [CELL, CELL], "patch_margin": BORDER,
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
}
print(f"frame {name}")
icons, detail = derive_icons(Image.open(icon_src))
for name, im in icons.items():
path = OUT_ICONS / f"icon_{name}.png"
im.save(path)
ledger["icons"][name] = {
"file": path.name, "cell": [ICON, ICON],
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
**detail[name],
}
print(f"icon {name}")
LEDGER.write_text(json.dumps(ledger, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"wrote {LEDGER}")
return 0
if __name__ == "__main__":
raise SystemExit(main())