Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(handed-check): a far sliver turned over no longer passes as the near item in a side view
Soohong Kima8de7abeaa6b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7f18037..32d4eb1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,8 +5,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased - A character with an item on one side has its left-facing views drawn, not mirrored- **Handedness, said once** (`sprite_gen/gen/handedness.py`): `--handed "<item>=<left|right> [part]"` names an item on one of the character's own sides ("the black smartwatch=left wrist"); the engine works out where that side is in each view — the picture's right or left in a front, back or diagonal view, near or far in a side or diagonal view (`placement`) — and says it in the prompts (`text`). `sprite-gen gen --direction <view> [--facing …] --handed …` adds the engine's still view sentence and, per item, which side it is on, where that is in the view, and that the sentence outranks an attached picture; with `--handed`, `--facing-fix mirror` is refused and `regen` never falls back to a mirror. `video-prompt --handed` and `video-set --handed` end the clip prompt with where the item stays, anchored to the first frame and named once where it shows; on the far side of a side view it is not named at all — the near arm "stays bare, exactly as in the image" — since a clip prompt that names a hidden item draws it on the near arm. [docs/video-pipeline.md](docs/video-pipeline.md#handedness--an-item-on-one-side).-- **Left-facing views drawn, not mirrored — opt-in**: `video-set --facing right,left` films every side and diagonal view both ways, each from its own still (`--base side@right=… --base side@left=…`); a turned view missing a still for one facing is refused, naming the `gen --direction … --facing …` call that draws it. Items are named `<view>-<facing>-<state>`, the table names the facing, each side still is inspected for its own facing, and gaits are aligned across all eight. Mirroring stays the default (drawing costs as much again); one facing keeps the item names and table as before.-- **New `sprite-gen handed-check`** checks a still or loop frame by frame: a colour-marked item (`--marker`, a saturated colour nothing else on the character has) must sit on its view's picture side of the body's centre, in one place only, showing in at least half the frames on a near side and, against a `--reference` front or back picture, no more than a sliver on the far side of a side view. `--strap --zone` adds the item's band seen without its marker (a bare strap on the other arm) within the rows it sits in. Specks of the marker's hue left on outlines by a clip's colour blocks are recorded, not judged. `--board` draws every frame with its verdict; exit 1 on a failure. Drawn test figures pass as they should look and fail turned over in every view (`tests/qa/test_handed_check.py`).+- **Left-facing views drawn, not mirrored — opt-in**: `video-set --facing right,left` films every side and diagonal view both ways, each from its own still (`--base side@right=… --base side@left=…`); a turned view missing a still for one facing is refused, naming the `gen --direction … --facing …` call that draws it. Items are named `<view>-<facing>-<state>`, the table names the facing, each side still is inspected for its own facing, and gaits are aligned across all eight. With `--handed`, a front or back walk's mid-step redraw is told the item's side as well. Mirroring stays the default (drawing costs as much again); one facing keeps the item names and table as before.+- **New `sprite-gen handed-check`** checks a still or loop frame by frame: a colour-marked item (`--marker`, a saturated colour nothing else on the character has) must sit on its view's picture side of the body's centre, in one place only, showing in at least half the frames on a near side and, against a `--reference` front or back picture, no more than a sliver on the far side of a side view and more than a sliver on its near side — a side view has no picture side, so a far sliver turned over to face the other way does not count as the near item shown. Without a reference both size rules are reported unchecked (`far_hidden`, `near_whole`). `--strap --zone` adds the item's band seen without its marker (a bare strap on the other arm) within the rows it sits in. Specks of the marker's hue left on outlines by a clip's colour blocks are recorded, not judged. `--board` draws every frame with its verdict; exit 1 on a failure. Drawn test figures pass as they should look and fail turned over in every view, a side view's far sliver against `--reference` (`tests/qa/test_handed_check.py`).- **Fix: a diagonal facing left was filmed heading right.** The diagonal walk and run sentences said "to the right" and "toward the upper right" whatever `--facing` was; they now take the facing ("heading diagonally toward the viewer and to the left"). `video-prompt` and `video-set` also cut a left-facing diagonal's loop with `--facing left` (it was always `right`), which mirrors the jump repair's hair box. Right-facing prompts are unchanged.## v2.21.0 - A clip made by a video MCP on your agent (ZCRE) becomes a loop: the prompt comes out, the mp4 goes indiff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex b5a69ed..b45840a 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -319,7 +319,9 @@ view — the item is not named at all: "The wrist in front of the body stays barimage, for the whole clip." A clip prompt that names a hidden item, and lists what the near arm mustnot wear, draws it on the near arm. A far arm that swings into view can still grow a bare band in anear-side view; holding the arms still (`--motion`) is the caller's choice, and `handed-check --strap`-finds it.+finds it. A front or back walk's mid-step redraw (`walk_start_prompt`, `video-prompt`'s `start_still`)+ends with the still's handedness sentences too: redrawn from the base alone, the model may put the item+on the other wrist.**Left-facing views, drawn.** `video-set --facing right,left` films every side and diagonal view bothways, each from its own still: `--base side@right=E.png --base side@left=W.png --base@@ -340,9 +342,14 @@ nothing else on the character has — a watch's screen — and checks every fram- every view: the item in at most one place (blobs within 2 % of the body height are one; one smallerthan a quarter of the largest is a speck — a clip's colour blocks tint outlines toward the item'shue — recorded and drawn, not judged);-- the near side of a side or diagonal view: the item shows in at least half the frames;+- the near side of a side or diagonal view: the item shows in at least half the frames — in a side view,+ against `--reference`, as more than a sliver (its largest blob larger than half the item seen whole):+ a side view has no picture side, so a far sliver turned over must not count as the near item shown;- the far side of a side view: no blob larger than half the item seen whole on `--reference` (a keyed- front or back picture); without one this rule is reported unchecked.+ front or back picture).++Without `--reference` neither side-view size rule is checked; the report says so (`far_hidden` /+`near_whole`: `checked: false`) and a near frame counts as shown by any blob.`--strap '#RRGGBB' --zone TOP,BOTTOM` adds the item's band seen without its marker: pixels of thatcolour in those rows of the body (fractions of its height), eroded so outlines drop out, wider and@@ -353,9 +360,10 @@ expected, red not) and bands boxed, for what pixels cannot judge: an unmarked itthe wrong hand. The exit code is 1 on a failure.A set that made its left-facing views by mirroring fails: a front view turned over puts the item on-the wrong side; a side view facing right (item hidden on the far arm) turned over hides it on the near-arm; a diagonal turned over moves it across the picture. `tests/qa/test_handed_check.py` draws each-view as it should look, passes it, and fails it turned over.+the wrong side; a side view facing right (item hidden on the far arm, or a sliver of it) turned over+hides it, or leaves the sliver, on the near arm — the sliver is caught against `--reference` only; a+diagonal turned over moves it across the picture. `tests/qa/test_handed_check.py` draws each view as it+should look, passes it, and fails it turned over.## 3. Frames — extract, key, check the edgesdiff --git a/sprite_gen/qa/handed.py b/sprite_gen/qa/handed.pyindex 485d21a..4f5f9f3 100644--- a/sprite_gen/qa/handed.py+++ b/sprite_gen/qa/handed.py@@ -13,7 +13,11 @@ each blob's centre is compared with the body's own centre (the mean x of its opa- the near side of a side or diagonal view: the item must show in at least half the frames;- the far side of a side view: the item is hidden or a sliver — no blob may be larger than half theitem seen whole, measured on `--reference` pictures of the same character (front or back, the item- in full view). Without a reference this one rule is not checked, and the report says so.+ in full view);+- the near side of a side view, against `--reference`: a frame shows the item only when it is more than+ that sliver. A side view has no picture side, so size is all that tells the near wrist from the far+ one: a far sliver turned over to face the other way must not count as the near item shown.+ Without a reference neither size rule is checked (`far_hidden` / `near_whole`), and the report says so.The screen colour cannot see the item's band without its marker — a watch's bare strap on the other arm.`--strap` names the band's colour (usually dark) and `--zone` the rows the item sits in (black is common:@@ -22,8 +26,9 @@ taller than an outline, is another place the item shows. Specks of the marker'sblocks leave on outlines are recorded and not judged.A picture turned over moves the item: a front view turned over puts it on the wrong side, a side view-facing right (the item on the far arm, hidden) turned over to face left hides it on the near arm. So a-set that made its left-hand views by mirroring fails here (`tests/qa/test_handed_check.py` proves it).+facing right (the item on the far arm, hidden or a sliver) turned over to face left hides it, or leaves only+that sliver, on the near arm. So a set that made its left-hand views by mirroring fails here — a side view's+sliver only against `--reference` (`tests/qa/test_handed_check.py` proves it).Pixels cannot judge everything — an unmarked item, an item drawn on the wrong hand where it stays hidden —so `--board` draws every frame with its blobs ringed (green as expected, red not) for a person to look at."""@@ -229,16 +234,24 @@ def check(frames: list[Image.Image], *, item: handed_mod.Handed, view: str, facirows.append({**m, "bad": bad})if bad:fails.append({"frame": i, "why": bad})- shown = sum(1 for r in rows if r["blobs"])+ # A side view has no picture side, so near and far differ only in size: on the near side a frame shows the+ # item when its largest blob is more than a sliver (the far side's own limit), or a far sliver turned over+ # would count as the near item shown.+ sized = view == "side" and expect["depth"] == "near" and full is not None+ shown = sum(1 for r in rows if r["blobs"] and (not sized or r["blobs"][0]["ratio"] > FAR_MAX * full))rules: dict[str, Any] = {}if expect["picture"]:rules["picture_side"] = expect["picture"]if expect["depth"] == "near":rules["near_shown"] = {"min": NEAR_SHOWN_MIN, "shown": shown, "frames": len(rows),"ok": shown >= NEAR_SHOWN_MIN * len(rows)}- if view == "side" and expect["depth"] == "far":- rules["far_hidden"] = ({"checked": False, "why": "no --reference: the item seen whole is unknown"} if full is None- else {"checked": True, "full_ratio": round(full, 6), "max": FAR_MAX})+ if view == "side":+ size = ({"checked": False, "why": "no --reference: the item seen whole is unknown"} if full is None+ else {"checked": True, "full_ratio": round(full, 6)})+ if expect["depth"] == "far":+ rules["far_hidden"] = {**size, **({"max": FAR_MAX} if full is not None else {})}+ else:+ rules["near_whole"] = {**size, **({"min": FAR_MAX} if full is not None else {})}ok = not fails and rules.get("near_shown", {}).get("ok", True)return {"kind": "sprite-gen-handed-check",@@ -325,7 +338,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--marker", required=True, help="#RRGGBB: a saturated colour of the item that nothing else on the character has")parser.add_argument("--strap", help="#RRGGBB: the item's band colour (a watch strap, usually dark); a band of it with no marker on it, away from the marker, counts as another place the item shows. Use with --zone")parser.add_argument("--zone", default="0,1", help="TOP,BOTTOM: the rows the item sits in, as fractions of the body's height from its top (default 0,1, the whole body); e.g. 0.5,0.9 for a wrist")- parser.add_argument("--reference", action="append", type=Path, default=[], help="a keyed front or back picture of the same character with the item in full view (repeatable): a side view's far item must stay smaller than half of it")+ parser.add_argument("--reference", action="append", type=Path, default=[], help="a keyed front or back picture of the same character with the item in full view (repeatable): in a side view the far item must stay smaller than half of it, and the near item counts as shown only when larger")parser.add_argument("--report", type=Path, help="write the report JSON here")parser.add_argument("--board", type=Path, help="write the review board PNG here")@@ -344,15 +357,17 @@ def run(**kwargs: object) -> int:atomic_write_text(Path(str(kwargs["report"])), json.dumps(report, ensure_ascii=False, indent=2) + "\n")summary = {k: report[k] for k in ("view", "facing", "expect", "frames", "frames_shown", "ok")}summary["fails"] = len(report["fails"])- if report["rules"].get("far_hidden", {}).get("checked") is False:- summary["unchecked"] = report["rules"]["far_hidden"]["why"]+ for rule in ("far_hidden", "near_whole"):+ if report["rules"].get(rule, {}).get("checked") is False:+ summary["unchecked"] = f"{rule}: {report['rules'][rule]['why']}"print(json.dumps(summary, ensure_ascii=False))if not report["ok"]:for f in report["fails"][:10]:print(f"handed-check: frame {f['frame']}: {'; '.join(f['why'])}", file=sys.stderr)if report["rules"].get("near_shown", {}).get("ok") is False:r = report["rules"]["near_shown"]- print(f"handed-check: on the near side the item shows in {r['shown']} of {r['frames']} frames", file=sys.stderr)+ whole = " more than a sliver" if report["rules"].get("near_whole", {}).get("checked") else ""+ print(f"handed-check: on the near side the item shows{whole} in {r['shown']} of {r['frames']} frames", file=sys.stderr)return 0 if report["ok"] else 1diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex a0ee573..f34f910 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -381,15 +381,19 @@ def starts_mid_step(state: str, direction: str) -> bool:return state == "walk" and direction in WALK_START_TEXT-def walk_start_prompt(direction: str, key: str | None = None) -> str:- """The redraw sentence for a walk's mid-step start still; with `key` (green / magenta) the background line."""+def walk_start_prompt(direction: str, key: str | None = None, handed: list[Handed] | None = None) -> str:+ """The redraw sentence for a walk's mid-step start still; with `key` (green / magenta) the background line,+ then with `handed` where each asymmetric item is in this view (`handedness.text`, the still's sentences)."""if direction not in WALK_START_TEXT:raise SystemExit(f"video: no mid-step start still for the {direction} view (only {', '.join(WALK_START_TEXT)})")- if key is None:- return WALK_START_TEXT[direction]- if key not in KEY_BACKGROUND_TEXT:- raise SystemExit(f"video: a mid-step start still is drawn on a green or magenta key, not {key!r}")- return f"{WALK_START_TEXT[direction]} {KEY_BACKGROUND_TEXT[key]}"+ text = WALK_START_TEXT[direction]+ if key is not None:+ if key not in KEY_BACKGROUND_TEXT:+ raise SystemExit(f"video: a mid-step start still is drawn on a green or magenta key, not {key!r}")+ text += f" {KEY_BACKGROUND_TEXT[key]}"+ if handed:+ text += " " + handed_mod.text(handed, direction)+ return textdef run_video_cli(image: Path, prompt: str, out: Path, report: Path, *, duration: int, resolution: str, log: Path, last_frame: Path | None = None) -> int:@@ -410,8 +414,10 @@ def run_redraw_cli(base: Path, prompt: str, out: Path, report: Path, *, log: Patdef walk_start_still(base: Path, direction: str, item_dir: Path, *, key: str, force: bool,- runner: Callable[..., int] = run_redraw_cli, provider: str | None = None) -> tuple[Path, dict[str, Any]]:- """The base still redrawn mid-step for a front or back walk (`WALK_START_TEXT`), on the base's own key.+ runner: Callable[..., int] = run_redraw_cli, provider: str | None = None,+ handed: list[Handed] | None = None) -> tuple[Path, dict[str, Any]]:+ """The base still redrawn mid-step for a front or back walk (`WALK_START_TEXT`), on the base's own key,+ told where each `handed` item is (a redraw from a reference alone can move it to the other side).Reused when the same prompt already drew it from the same base (unless `force`)."""with Image.open(base) as im:@@ -419,7 +425,7 @@ def walk_start_still(base: Path, direction: str, item_dir: Path, *, key: str, foif kind not in KEY_BACKGROUND_TEXT:raise SystemExit(f"the {direction} walk starts from a still redrawn mid-step on a green or magenta key, and this "f"base's corners are not one (key {key}); pass --walk-start as-given to film from the base itself")- prompt = walk_start_prompt(direction, kind)+ prompt = walk_start_prompt(direction, kind, handed)out, report = item_dir / "walk-start.png", item_dir / "walk-start.report.json"if out.is_file() and report.is_file() and not force:try:@@ -515,7 +521,7 @@ def run_item(facing_report = Noneif starts_mid_step(state, direction) and walk_start == "redraw":still, result["walk_start"] = walk_start_still(base, direction, item_dir, key=key, force=force,- runner=redraw_runner, provider=still_provider)+ runner=redraw_runner, provider=still_provider, handed=handed)if direction == "side":if prepare_side is not None:still, facing_report = prepare_side(base)diff --git a/sprite_gen/video/clip_prompt.py b/sprite_gen/video/clip_prompt.pyindex 276f022..c1dbdf5 100644--- a/sprite_gen/video/clip_prompt.py+++ b/sprite_gen/video/clip_prompt.py@@ -86,7 +86,7 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:if mid_step:record["start_still"] = {"why": "a front or back walk films from its still redrawn mid-step; from a standing still the clip model walks askew",- "prompt": batch_mod.walk_start_prompt(direction, key),+ "prompt": batch_mod.walk_start_prompt(direction, key, handed),"command": "sprite-gen gen --ref <still.png> --prompt-file <start-prompt.txt> --out <dir>/walk-start.png --report <dir>/walk-start.report.json",}return recorddiff --git a/tests/qa/test_handed_check.py b/tests/qa/test_handed_check.pyindex 6565bff..7a34e7f 100644--- a/tests/qa/test_handed_check.py+++ b/tests/qa/test_handed_check.py@@ -62,6 +62,7 @@ def test_each_view_drawn_as_its_handedness_says_passes(view, facing) -> None:report = check(loop(DRAWN[(view, facing)]), view, facing)assert report["ok"], report["fails"]assert report["expect"] == h.placement("left", view, facing)+ assert check(loop(DRAWN[(view, facing)]), view, facing, references=[figure("right")])["ok"]@pytest.mark.parametrize("view,facing,as_view,as_facing", [@@ -94,6 +95,26 @@ def test_the_wrong_wrist_in_a_side_view_needs_a_reference_to_be_caught() -> Noneassert sliver["ok"]+def test_a_far_sliver_turned_over_is_not_the_near_item_shown() -> None:+ """Facing right, the far wrist's watch may show as a sliver as the arm swings. Turned over to face left,+ that sliver is on the arm behind the body — the own right wrist, the wrong one — and the near wrist is+ bare. A side view has no picture side, so only size against a reference tells the two apart; without+ one the near side's size is reported unchecked, not passed as checked."""+ reference = [figure("right")]+ right = [figure("near", swing=s, screen=4) for s in (0, 2, 4, 6, 4, 2)]+ assert check(right, "side", "right", references=reference)["ok"]+ mirrored = [ImageOps.mirror(f) for f in right]+ caught = check(mirrored, "side", "left", references=reference)+ assert not caught["ok"] and caught["fails"] == []+ assert caught["rules"]["near_shown"] == {"min": 0.5, "shown": 0, "frames": 6, "ok": False}+ assert caught["rules"]["near_whole"]["checked"] is True and caught["frames_shown"] == 0+ unchecked = check(mirrored, "side", "left")+ assert unchecked["rules"]["near_whole"] == {"checked": False, "why": "no --reference: the item seen whole is unknown"}+ # the near watch drawn in full counts as shown against the same reference+ drawn = check(loop("near"), "side", "left", references=reference)+ assert drawn["ok"] and drawn["rules"]["near_shown"]["shown"] == 6++def test_the_item_in_two_places_fails_and_a_split_screen_is_one() -> None:both = figure("right")d = ImageDraw.Draw(both)diff --git a/tests/video/test_batch_handed.py b/tests/video/test_batch_handed.pyindex 88fdd5a..cb1ccb0 100644--- a/tests/video/test_batch_handed.py+++ b/tests/video/test_batch_handed.py@@ -5,6 +5,7 @@ import jsonfrom pathlib import Pathimport pytest+from PIL import Image, ImageDrawfrom sprite_gen.gen import handedness as hfrom sprite_gen.video import batch@@ -115,3 +116,25 @@ def test_cli_threads_both_facings_and_items(monkeypatch, tmp_path) -> None:"--handed", "the black smartwatch=left wrist"]) == 0assert seen[0]["facing"] == "right,left" and seen[0]["handed"] == WATCHassert set(seen[0]["bases"]) == {"side@right", "side@left"}+++def test_a_front_walk_redrawn_mid_step_is_told_where_the_item_is(tmp_path, offline) -> None:+ """The front and back walks film from the still redrawn mid-step; that redraw says the item's side too,+ so a redraw from the reference alone does not move it, and its clip prompt is anchored to that still."""+ redraws: list[str] = []++ def paint(base, prompt, out, report, *, log, provider=None):+ redraws.append(prompt)+ out.write_bytes(base.read_bytes())+ report.write_text(json.dumps({"prompt": prompt, "refs": [str(base)]}))+ return 0++ base = Image.new("RGB", (96, 128), (0, 255, 0))+ ImageDraw.Draw(base).rectangle((36, 20, 59, 109), fill=(120, 60, 40))+ base.save(tmp_path / "front.png")+ result = batch.run_set(bases={"front": tmp_path / "front.png"}, states=["walk"], root=tmp_path, character=None,+ duration=3, resolution="720p", key="green", concurrency=1, force=False, gap=0,+ video_runner=_video({}), redraw_runner=paint, align_cycles="off", handed=WATCH)+ assert result["ok"] == 1 and result["items"][0]["walk_start"]["redrawn"] is True+ assert redraws == [batch.walk_start_prompt("front", result["items"][0]["walk_start"]["key"], WATCH)]+ assert redraws[0].endswith(h.text(WATCH, "front")) and "at the right of the picture" in redraws[0]