Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(pixel-draw): an answer that writes its block more than once is read from the last block that reads whole
Soohong Kim10bbda71014b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 449b243..b6013ed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased- **New: `background-tile --axis xy` makes one tile seamless in both directions and measures both joins.** It quilts along x, then along y with a cyclic seam: the second seam's two ends, which meet across the x wrap, may differ by one step at most, so the second quilt cannot break the first one's join. The report measures the finished tile on both axes (`axes.x`, `axes.y`, each with its join, quilt seam, `status` and reasons); the top-level `status` is `needs-review` when either axis is, and each reason names its axis. Two separate one-axis runs had no such rule, and the second run's report measured only its own axis. `inspect_tile_xy(image)` measures both joins of any tile ([asset-tools](docs/asset-tools.md#both-axes-a-ground-tile)).+- **Fix: a `pixel-draw` answer that writes its block more than once is read from the last block that reads whole.** An answer sometimes writes a first try — the palette and `END` with no frame — then "Corrected:" and the whole block (seen 2026-10-15 on a 16 px icon); G1 read the first block, found the frame missing and drew the candidate again. Now every block is read and the last one that reads whole is the answer (when none does, the last whose rows the row repair can fix), recorded in G1's `recovered` as `block_many` with which block was read. An answer of one block is read as before.+- **Tests** — `tests/gen/test_pixel_grid.py` (several blocks read from the last whole one, or the last with rows to repair; one block as before) and an answer of two blocks drawn once in `tests/gen/test_pixel_draw.py`.- **New: alpha haze cleanup for transparent sheets (`frames.alpha_floor.clear_haze`).** Pixels at or above a floor, and faint pixels within a few pixels of them (an object's anti-aliased edge), are kept byte for byte; every other faint pixel becomes fully transparent. The report measures the haze share before and after and counts the solid and edge pixels that changed (`0`). Used by `ui-kit` (on by default) and `slice-sheet --alpha-floor N` (off by default; writes `<prefix>alpha-cleanup.json`). `slice-sheet --chroma-key none` cuts a sheet that is already transparent on its own alpha ([sheet-slicing](docs/sheet-slicing.md#transparent-sheets)).- **New verb: `ui-kit` splits a game UI kit sheet into nine-slice elements.** `gen --layout-guide ui-kit` attaches a fixed square layout (panel, button, pressed button, card frame, HP and XP bar frames, timer badge) and asks for each element in its box. `ui-kit --sheet uikit.png --out-dir ui/` clears the haze, assigns parts to boxes by centroid, and writes each element's PNG and `ui-kit.json` (or `--report PATH`, which must end in `.json`; each element's `file` is its PNG's path from the report's directory, so a report written outside `--out-dir` still finds its elements): its rectangle, its stretch (`xy`, `x` for the bars, `none` for the badge), nine-slice insets measured so that every corner ornament and end cap lies in a fixed slice, and the content padding (a bar frame's track, a panel's text area). An ornament in the middle of an edge, an empty box or a stray part is reported or refused ([ui-kit](docs/ui-kit.md)). `--layout-guide` alone is still the one-slot figure guide.- **New: `game-pack` request and manifest version 2 with `images`, `tiles` and `ui`.** Single images (props) are atlas frames with an anchor and an optional footprint (`"base"` measures where the image meets the ground); tiles are their own PNG and WebP files with their stored and on-screen sizes; `ui.kit` reads a `ui-kit` report into nine-slice entries (frame, size, stretch, insets, padding) and `ui.icons` adds fixed icons. Every number is in pixels of the stored image. A version 1 request is packed byte for byte as before, and a version 1 request naming the new sections is refused ([game-pack](docs/game-pack.md#version-2-images-tiles-and-ui)).diff --git a/docs/pixel-draw.md b/docs/pixel-draw.mdindex 868d0b5..cd50bde 100644--- a/docs/pixel-draw.md+++ b/docs/pixel-draw.md@@ -161,7 +161,7 @@ past the safe area has not been measured yet.| Gate | Checks | On failure ||---|---|---|-| G1 parse | One block; palette lines `<key> #RRGGBB` (`.` is transparent and nothing else); the frames asked for, each exactly N rows of N palette keys | Row issues → row repair (two rounds), then one redraw; anything else → one redraw. Recovered by code and recorded: a single frame written without its `FRAME` line or under another name, frames in another order, the fence tagged otherwise, no `END` line |+| G1 parse | One block; palette lines `<key> #RRGGBB` (`.` is transparent and nothing else); the frames asked for, each exactly N rows of N palette keys | Row issues → row repair (two rounds), then one redraw; anything else → one redraw. Recovered by code and recorded: a single frame written without its `FRAME` line or under another name, frames in another order, the fence tagged otherwise, no `END` line; an answer that writes its block more than once — a first try, then "Corrected:" and the block again — is read from the last block that reads whole (when none does, the last whose rows can be repaired), `block_many` saying which || G2 palette | Opaque colours used ≤ the limit; a fixed palette's colours only | fails || G3 alpha | Each frame's background by the judgment `gen` reads a generated raw by (`alpha_verdict`, [gen.md](gen.md#transparent-output--strategy-per-provider)): `real-alpha` is at least 5 % of the pixels and half the one-pixel border alpha 0, `no-alpha` none. Sprite/icon: `real-alpha`, something drawn, four transparent corners. Tile: `no-alpha` | fails || G4 tile seam | Each tile frame's join along x and along y, by the measure `background-tile` reports (`inspect_tile`, [asset-tools.md](asset-tools.md#repeating-tiles)): the wrap edge against the tile's own neighbours | warns where it says `needs-review`, with its reasons — a local measure, never proof that the tile repeats cleanly; look at `tiled-3x3.png` |diff --git a/sprite_gen/gen/pixel_grid.py b/sprite_gen/gen/pixel_grid.pyindex b9dd52e..b803180 100644--- a/sprite_gen/gen/pixel_grid.py+++ b/sprite_gen/gen/pixel_grid.py@@ -16,7 +16,8 @@ Parsing is strict and says what it found (`Issue`):are what the row repair asks for, one row at a time, and `splice` puts the answers in;- recovered issues are code-recoverable and recorded, never silent: the fence tagged otherwise ormissing, a fence never closed, a single frame written without its `FRAME` line or under another- name, frames in another order, no `END` line.+ name, frames in another order, no `END` line, an answer that wrote its block more than once (the+ last block that reads whole is read).`png_bytes` writes a frame as a PNG whose bytes depend only on its pixels — stored deflateblocks, no compressor in the loop — so the same grid gives the same file on any machine and any@@ -57,8 +58,8 @@ STRUCTURAL = frozenset({"frame_duplicate", "row_count_over", "stray_line",})ROW_CODES = frozenset({"row_width", "unknown_symbol", "row_missing"})-RECOVERED = frozenset({"block_tag", "block_unclosed", "frame_header_missing", "frame_renamed", "frame_order",- "no_end"})+RECOVERED = frozenset({"block_tag", "block_unclosed", "block_many", "frame_header_missing", "frame_renamed",+ "frame_order", "no_end"})_PALETTE_LINE = re.compile(r"^(\S)\s+(transparent|#[0-9A-Fa-f]{6})$")_ROW_ANSWER = re.compile(r"^\s*`?\s*ROW\s+(\S+)\s+(\d+)\s*:\s*(.*?)\s*`?\s*$", re.M)@@ -365,23 +366,21 @@ def _json_row(row: object) -> list[str]:return [_json_token(v) for v in row] if isinstance(row, list) else []-def parse_answer(text: str, fmt: str, width: int, height: int, frames: Sequence[str]) -> tuple[Grid | None, list[Issue]]:- """Read a model's answer. Returns the grid (None when nothing could be read) and every issue."""- issues: list[Issue] = []- if fmt == "chargrid":- body, found = _fenced(text, "pixels")- elif fmt == "json":- body, found = _fenced(text, "json")- if body is None:- start, end = text.find("{"), text.rfind("}")- body, found = (text[start:end + 1], "block_tag") if 0 <= start < end else (None, None)- else:- raise ValueError(f"unknown format {fmt!r}")- if body is None:- issues.append(Issue("no_block", None, None, f"no ```{'pixels' if fmt == 'chargrid' else 'json'} block"))- return None, issues- if found:- issues.append(Issue(found))+def _blocks(text: str, tag: str) -> list[tuple[str, str | None]]:+ """Every ```<tag> block of an answer, in order, and how each was found: as asked (None), or never+ closed before the next block or the end of the answer (`block_unclosed`)."""+ openers = list(re.finditer(r"```" + re.escape(tag) + r"[ \t]*\r?\n", text))+ out: list[tuple[str, str | None]] = []+ for number, opener in enumerate(openers):+ end = openers[number + 1].start() if number + 1 < len(openers) else len(text)+ close = text.find("```", opener.end(), end)+ out.append((text[opener.end():close], None) if close >= 0 else (text[opener.end():end], "block_unclosed"))+ return out+++def _read_body(body: str, found: str | None, fmt: str, width: int, height: int,+ frames: Sequence[str]) -> tuple[Grid | None, list[Issue]]:+ issues = [Issue(found)] if found else []parse = _parse_chargrid_body if fmt == "chargrid" else _parse_json_bodygrid = parse(body, width, height, frames, issues)if grid is not None and not structural(issues):@@ -389,6 +388,38 @@ def parse_answer(text: str, fmt: str, width: int, height: int, frames: Sequence[return grid, issues+def _last_whole(blocks: list[tuple[str, str | None]], fmt: str, width: int, height: int,+ frames: Sequence[str]) -> tuple[Grid | None, list[Issue]]:+ """An answer that wrote its block more than once — a first try, then "Corrected:" and the block+ again: the last block that reads whole is the answer; when none does, the last whose rows the+ row repair can fix; when none can, the last. Which one was read is recorded (`block_many`)."""+ read = [_read_body(body, found, fmt, width, height, frames) for body, found in blocks]+ numbers = range(len(read) - 1, -1, -1)+ chosen = next((n for n in numbers if read[n][0] is not None and not structural(read[n][1])+ and not row_issues(read[n][1])), None)+ if chosen is None:+ chosen = next((n for n in numbers if read[n][0] is not None and not structural(read[n][1])), len(read) - 1)+ grid, issues = read[chosen]+ return grid, [Issue("block_many", None, None, f"{len(read)} blocks, read block {chosen + 1}"), *issues]+++def parse_answer(text: str, fmt: str, width: int, height: int, frames: Sequence[str]) -> tuple[Grid | None, list[Issue]]:+ """Read a model's answer. Returns the grid (None when nothing could be read) and every issue."""+ if fmt not in FORMATS:+ raise ValueError(f"unknown format {fmt!r}")+ tag = "pixels" if fmt == "chargrid" else "json"+ blocks = _blocks(text, tag)+ if len(blocks) > 1:+ return _last_whole(blocks, fmt, width, height, frames)+ body, found = _fenced(text, tag)+ if body is None and fmt == "json":+ start, end = text.find("{"), text.rfind("}")+ body, found = (text[start:end + 1], "block_tag") if 0 <= start < end else (None, None)+ if body is None:+ return None, [Issue("no_block", None, None, f"no ```{tag} block")]+ return _read_body(body, found, fmt, width, height, frames)++def read_grid_text(text: str) -> tuple[Grid | None, list[Issue]]:"""Read a `grid.txt` (the character grid with or without its fence); the frames and the canvassize are what it holds — the commonest row length is the width, the commonest row count thediff --git a/tests/gen/test_pixel_draw.py b/tests/gen/test_pixel_draw.pyindex ed0a5df..ae17765 100644--- a/tests/gen/test_pixel_draw.py+++ b/tests/gen/test_pixel_draw.py@@ -266,6 +266,19 @@ def test_a_candidate_is_drawn_twice_at_most(tmp_path, claude):assert asked(fake) == ["c1-gen1", "c1-gen2"]+def test_an_answer_that_writes_its_block_again_is_read_from_the_last_whole_block(tmp_path, claude):+ """A block, then 'Corrected:' and the block again (seen on the subscription, 2026-10-15): the last+ block that reads whole is the answer - recorded, not drawn again."""+ half = SPRITE16[:SPRITE16.index("FRAME sprite")] + "END\n```"+ fake = claude({"c1-gen1": reply(half + "\n\nWait, the frame belongs inside the block. Corrected:\n\n" + SPRITE16)})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a knight", "--size", "16", "--candidates", "1") == 0+ assert asked(fake) == ["c1-gen1"]+ (candidate,) = report_of(out)["candidates"]+ assert candidate["status"] == "passed" and candidate["redraws"] == []+ assert candidate["G1"] == {"ok": True, "issues": [], "recovered": [{"code": "block_many", "detail": "2 blocks, read block 2"}]}++def test_a_refusal_is_reported_as_it_came(tmp_path, claude):fake = claude({"c1-gen1": reply("", stop="refusal", details={"type": "refusal", "category": "cyber", "explanation": "x"})})out = tmp_path / "run"diff --git a/tests/gen/test_pixel_grid.py b/tests/gen/test_pixel_grid.pyindex 4c214e4..1b71711 100644--- a/tests/gen/test_pixel_grid.py+++ b/tests/gen/test_pixel_grid.py@@ -250,3 +250,41 @@ def test_palette_rules(tmp_path):for bad in ("free:0", "free:63", "free:x", "#12345", "#aabbcc,#AABBCC", str(tmp_path / "missing.hex")):with pytest.raises(ValueError):pg.palette_rule(bad)+++# ----------------------------------------------------------------------------- several blocks in one answer++def test_several_blocks_read_the_last_one_that_reads_whole():+ """An answer that writes a block, then 'Corrected:' and the block again: the last block that reads+ whole is the answer, recorded. Seen 2026-10-15 on a 16 px icon - a first block of the palette alone+ and END, then the whole block."""+ half = _block(". transparent\na #112233", {})+ whole = _block(". transparent\na #112233", {"icon": ROWS8})+ text = "Here:\n" + half + "\nWait, the frame belongs inside the block. Corrected:\n\n" + whole+ grid, issues = pg.parse_answer(text, "chargrid", 8, 8, ("icon",))+ assert grid.frames["icon"] == [list(row) for row in ROWS8]+ assert [i.to_dict() for i in issues] == [{"code": "block_many", "detail": "2 blocks, read block 2"}]+ assert pg.recovered(issues) == issues+++def test_a_whole_block_before_a_broken_one_is_the_one_read():+ whole = _block(". transparent\na #112233", {"icon": ROWS8})+ cut = "```pixels\nPALETTE\n. transparent\na #112233\nFRAME icon\n........\n.aaa"+ grid, issues = pg.parse_answer(whole + "\nLet me redo it:\n" + cut, "chargrid", 8, 8, ("icon",))+ assert codes(issues) == ["block_many"] and issues[0].detail == "2 blocks, read block 1"+ assert grid.frames["icon"] == [list(row) for row in ROWS8]+++def test_of_several_broken_blocks_the_last_with_rows_to_repair_is_read():+ first = _block(". transparent\nEND_PALETTE_PLACEHOLDER", {"icon": ROWS8})+ second = _block(". transparent\na #112233", {"icon": ROWS8[:7] + [".aaaaaaa."]})+ grid, issues = pg.parse_answer(first + second, "chargrid", 8, 8, ("icon",))+ assert codes(issues) == ["block_many", "row_width"] and grid is not None+ assert [(i.code, i.row) for i in pg.row_issues(issues)] == [("row_width", 8)]+++def test_one_block_reads_as_it_always_did():+ whole = _block(". transparent\na #112233", {"icon": ROWS8})+ assert pg.parse_answer(whole, "chargrid", 8, 8, ("icon",))[1] == []+ assert pg.parse_answer("text then " + whole + " and a note", "chargrid", 8, 8, ("icon",))[1] == []+