Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(pixel-draw): G8 takes the image path's safe-area judgment instead of its own - safe_area_fit, lifted out of the pixel snap unchanged, warns a frame past the physical cap and notes one past the safe area as info; a pixel on the canvas edge no longer fails a candidate, the floor-row warning stays, and the prompt gives the safe area as a target for the body's size
Soohong Kim47bf14ff21a5
diff --git a/sprite_gen/frames/extract.py b/sprite_gen/frames/extract.pyindex 48a2494..67186f6 100644--- a/sprite_gen/frames/extract.py+++ b/sprite_gen/frames/extract.py@@ -1194,6 +1194,24 @@ def cell_geometry(cell: dict[str, Any]) -> tuple[int, int, int, int]:return width, height, safe_margin_x, safe_margin_y+def safe_area_fit(sizes: list[tuple[int, int]], cell_width: int, cell_height: int, safe_margin_x: int,+ safe_margin_y: int, scale: int = 1) -> dict[str, Any]:+ """셀에 들어갈 프레임 크기(논리 픽셀 `(w, h)`, `scale` = 논리 1칸의 셀 픽셀 수)의 안전영역 판정.++ 물리캡 = 가로는 칸 너비, 세로는 칸 높이에서 바닥 여백 하나를 뺀 것(바닥 줄에 선 프레임이 가진+ 줄들). 넘으면 `over` — 경고, 리롤 후보. 안전영역(사방 여백 안)은 넘었지만 물리캡 이내면 `soft` —+ 여백 침범, 리롤 대상 아님, 정보성 알림만 (maintainer 확정 2026-07-14). 실패는 없다.+ `over`/`soft` 는 `sizes` 의 인덱스. 판정은 여기 하나다 — 픽셀 스냅(아래 `_snap_strip`)과+ `pixel-draw` 의 G8(`sprite_gen/gen/pixel_gates.py`)이 같이 부른다."""+ cap_w = max(1, cell_width // scale)+ cap_h = max(1, (cell_height - safe_margin_y) // scale)+ safe_w = max(1, (cell_width - safe_margin_x * 2) // scale)+ safe_h = max(1, (cell_height - safe_margin_y * 2) // scale)+ over = [i for i, (w, h) in enumerate(sizes) if w > cap_w or h > cap_h]+ soft = [i for i, (w, h) in enumerate(sizes) if (w > safe_w or h > safe_h) and w <= cap_w and h <= cap_h]+ return {"cap": [cap_w, cap_h], "safe": [safe_w, safe_h], "over": over, "soft": soft}++# align_x "alpha-centroid" 는 perfectpixel-studio internal/sprite/extract.go 이식# (github.com/gykim80/perfectpixel-studio, MIT). bbox 중심 정렬은 팔/무기가 뻗은# 프레임에서 면적이 큰 몸통을 반대로 밀어 재생 시 좌우 지터를 만들고, 알파 가중@@ -3375,27 +3393,23 @@ def _run_locked(args: argparse.Namespace, run_dir: Path):# 제거된 결정이 플래그 하나로 되살아나는 회귀 경로였다 (회귀 2026-07-17:# 높이 통일 시도가 이 플래그로 재발) — 선언되어 있으면 요란하게 거부한다.# 물리 한계(셀에서 바닥 마진만 지킴)만 캡으로 강제하고, 캡에 걸리면 관측- # 가능하게 경고한다.+ # 가능하게 경고한다. 캡과 안전영역의 판정은 `safe_area_fit` 하나다.if fit_config.get("conform") is not None:raise SystemExit("fit.conform was removed (maintainer 2026-07-14/17): native logical size is ""the only behavior — squashing to logical_height merges cells and eats ""detail. Remove the key from sprite-request.json.")- cap_w = max(1, cell_width // pp_scale)- cap_h = max(1, (cell_height - safe_margin_y) // pp_scale)- over = [f"{i}:{s.width}x{s.height}" for i, s in enumerate(snapped)- if s.width > cap_w or s.height > cap_h]+ fit = safe_area_fit([(s.width, s.height) for s in snapped], cell_width, cell_height,+ safe_margin_x, safe_margin_y, pp_scale)+ (cap_w, cap_h), (safe_w, safe_h) = fit["cap"], fit["safe"]+ over = [f"{i}:{snapped[i].width}x{snapped[i].height}" for i in fit["over"]]if over:all_warnings.append(f"{tag}: native logical exceeds the physical cap "f"{cap_w}x{cap_h} — capped frames (reroll candidates): {', '.join(over)}")# 안전영역(사방 여백 준수 상한)은 넘었지만 물리캡 이내 = 여백 침범.# 리롤 대상 아님 — 정보성 알림만 (maintainer 확정 2026-07-14).- safe_w = max(1, (cell_width - safe_margin_x * 2) // pp_scale)- safe_h = max(1, (cell_height - safe_margin_y * 2) // pp_scale)- soft = [f"{i}:{s.width}x{s.height}" for i, s in enumerate(snapped)- if (s.width > safe_w or s.height > safe_h)- and s.width <= cap_w and s.height <= cap_h]+ soft = [f"{i}:{snapped[i].width}x{snapped[i].height}" for i in fit["soft"]]if soft:all_warnings.append(f"{tag}: frames exceed the safe area {safe_w}x{safe_h} but fit "diff --git a/sprite_gen/gen/pixel_draw.py b/sprite_gen/gen/pixel_draw.pyindex fbc5de9..2399311 100644--- a/sprite_gen/gen/pixel_draw.py+++ b/sprite_gen/gen/pixel_draw.py@@ -15,10 +15,12 @@ One run, `--candidates` K answers to the same request:2. G1 parse. Row issues are repaired one row at a time (`ROW <frame> <n>: …`, two rounds at most);an answer still broken, or broken beyond its rows, is drawn once more. A candidate is drawn atmost twice in all.-3. G2 palette, G3 alpha, G6 frames and G8 safe area (a pixel on the canvas edge) fail a candidate;- G4 tile seam, G5 stray pixels, the walk cycle's leg alternation and G8's body and floor checks- warn. The prompt gives a sprite or icon the engine's safe area (`safe_area_lines`) in rows and- columns.+3. G2 palette, G3 alpha and G6 frames fail a candidate; G4 tile seam, G5 stray pixels, the walk+ cycle's leg alternation and G8 safe area (a frame past the physical cap, a sprite off the floor+ row) warn, and G8 notes a frame past the safe area within the cap in an info line — the image+ path's judgment (`frames.extract.safe_area_fit`). The prompt gives a sprite or icon the engine's+ safe area (`safe_area_lines`) in rows and columns, as a target for the body's size that a pose+ may go past.4. G7: of two or more candidates that passed, one vision call (effort low) picks, or a persondoes (`--pick human`). One that passed alone is the pick.@@ -236,8 +238,8 @@ def _format_spec(request: PixelRequest) -> str:def safe_area_lines(request: PixelRequest) -> list[str]:"""The engine's safe area of a sprite or icon (`pixel_gates.safe_area`, G8), in rows and columns- counted from 1: the body inside it, only a thin detail in the margin, the canvas edge clear, and a- sprite's feet on its bottom row."""+ counted from 1: a target for the body's average size that a pose may go past, as far as the canvas+ edge, and a sprite's feet on its bottom row."""size = request.sizearea = safe_area(size, size)margin, inner, floor = area["margin"][0], area["size"][0], area["floor_row"] + 1@@ -246,21 +248,17 @@ def safe_area_lines(request: PixelRequest) -> list[str]:lines = [f"Safe area: at {size}x{size} there is no margin; {'the subject' if sprite else 'the icon'} may use ""the whole canvas, with the four corner pixels transparent."]else:- first, last, reach = margin + 1, size - margin, margin - 1- edge = f"outermost rows and columns (rows 1 and {size}, columns 1 and {size})"- if reach:- past = (f"Only a thin detail (a weapon tip, a strand of hair, an effect) may reach into the margin, at "- f"most {reach} pixel{'s' if reach > 1 else ''} past the safe area; the {edge} stay transparent.")- else:- past = f"The {edge} are the margin and stay transparent: at this size nothing reaches past the safe area."+ first, last = margin + 1, size - marginbody = "the subject's body" if sprite else "the icon"- lines = [f"Safe area: keep a {margin}-pixel margin on every side and draw {body} inside the central "- f"{inner}x{inner} pixels: rows {first}-{last} and columns {first}-{last}, counting rows and columns "- f"from 1. {past}"]+ lines = [f"Safe area: draw {body} about the size of the central {inner}x{inner} pixels - rows {first}-{last} "+ f"and columns {first}-{last}, counting rows and columns from 1 - inside a {margin}-pixel margin on "+ "every side. That is a target for its average size, not a wall: when a pose or a detail needs the "+ "room (a raised weapon, a long blade, an effect, a wide stance), it may reach past the safe area into "+ "the margin, up to the canvas edge. Keep the four corner pixels transparent."]if sprite:every = " in every frame" if len(request.frames) > 1 else ""- lines.append(f"Floor: row {floor}, the bottom row of the safe area, is the ground. The feet (or the lowest point "- f"the subject rests on) stand on row {floor}{every}, and nothing of the body goes below it.")+ lines.append(f"Floor: row {floor}, the bottom row of the safe area, is the ground: the feet (or the lowest point "+ f"the subject rests on) stand on row {floor}{every}.")return lines@@ -357,7 +355,8 @@ def _kept(request: PixelRequest) -> str:if request.kind == "tile" or area["margin"][0] == 0:return ""inner = area["size"][0]- return f", the body kept inside the central {inner}x{inner} with a {area['margin'][0]}-pixel margin"+ return (f", the body about the size of the central {inner}x{inner}, inside a {area['margin'][0]}-pixel margin a "+ "pose may reach into")def pick_prompt(request: PixelRequest, labels: list[str]) -> str:@@ -607,6 +606,7 @@ class Candidate:g1: dict[str, Any] | None = Nonegates: dict[str, Any] | None = Nonewarnings: list[str] = field(default_factory=list)+ info: list[str] = field(default_factory=list)grid: Grid | None = Nonefiles: dict[str, Any] = field(default_factory=dict)@@ -617,7 +617,7 @@ class Candidate:def to_dict(self) -> dict[str, Any]:return {"id": self.id, "status": self.status, "reason": self.reason, "effort": self.effort,"generations": self.generations, "redraws": self.redraws, "repairs": self.repairs, "G1": self.g1,- "gates": self.gates, "warnings": self.warnings, "files": self.files}+ "gates": self.gates, "warnings": self.warnings, "info": self.info, "files": self.files}def _g1(issues: list[Issue]) -> dict[str, Any]:@@ -682,7 +682,7 @@ class Run:candidate.effort, candidate.grid = effort, gridpixels = {name: frame_pixels(grid, name) for name in request.frames}candidate.gates = evaluate(pixels, kind=request.kind, rule=request.palette, walk_cycle=request.walk_cycle)- candidate.warnings = candidate.gates["warnings"]+ candidate.warnings, candidate.info = candidate.gates["warnings"], candidate.gates["info"]if candidate.gates["ok"]:return candidate.end("passed")return candidate.end("failed", "failed " + ", ".join(candidate.gates["failed"]))@@ -981,7 +981,7 @@ def _run_grid(args: argparse.Namespace) -> int:"grid_source": str(Path(args.grid).expanduser().resolve()), "model": None,"request": {"kind": kind, "frames": list(frames), "walk_cycle": bool(args.walk_cycle),"palette": rule.to_dict()},- "G1": _g1(issues), "gates": None, "warnings": [], "files": {}, "calls": [],+ "G1": _g1(issues), "gates": None, "warnings": [], "info": [], "files": {}, "calls": [],"cost_usd": 0.0}if grid is None or not report["G1"]["ok"]:path = _write_report(out_dir, report)@@ -989,8 +989,8 @@ def _run_grid(args: argparse.Namespace) -> int:pixels = {name: frame_pixels(grid, name) for name in frames}gates = evaluate(pixels, kind=kind, rule=rule, walk_cycle=bool(args.walk_cycle))files = write_files(out_dir, grid, frames, kind, rule, _colors_used(pixels))- report.update(status="ok" if gates["ok"] else "failed", gates=gates, warnings=gates["warnings"], files=files,- request={**report["request"], "size": [grid.width, grid.height]})+ report.update(status="ok" if gates["ok"] else "failed", gates=gates, warnings=gates["warnings"], info=gates["info"],+ files=files, request={**report["request"], "size": [grid.width, grid.height]})path = _write_report(out_dir, report)if not gates["ok"]:raise _refuse(f"{args.grid} fails {', '.join(gates['failed'])}; files and report in {out_dir} ({path.name})")@@ -1032,7 +1032,7 @@ def _run(args: argparse.Namespace, *, sleep: Callable[[float], None] = time.sleerun = Run(request, out_dir, calls, batch_wait=batch_wait, note=note)report: dict[str, Any] = {"kind": REPORT_KIND, "status": None, "out_dir": str(out_dir), "source": "model","model": api.MODEL, "request": request.to_dict(), "chosen": None, "files": {},- "pick": None, "candidates": [], "warnings": []}+ "pick": None, "candidates": [], "warnings": [], "info": []}try:candidates = run.candidates()except Unfinished as unfinished:@@ -1066,7 +1066,7 @@ def _run(args: argparse.Namespace, *, sleep: Callable[[float], None] = time.sleefor k, v in chosen.files.items()}for name in _flat(top):shutil.copyfile(source / name, out_dir / name)- report.update(chosen=chosen.id, files=top, warnings=chosen.warnings)+ report.update(chosen=chosen.id, files=top, warnings=chosen.warnings, info=chosen.info)if pick.get("error"):report["status"] = "pick_failed"path = _finish(report, calls, started)diff --git a/sprite_gen/gen/pixel_gates.py b/sprite_gen/gen/pixel_gates.pyindex 1a815d3..c606002 100644--- a/sprite_gen/gen/pixel_gates.py+++ b/sprite_gen/gen/pixel_gates.py@@ -11,19 +11,23 @@- G5 stray pixels (warning): opaque pixels of a sprite or icon with no opaque 4-neighbour.- G6 frames: every frame stands on the same bottom row, heights differ by at most one pixel andno two frames are the same. A sprite's or icon's rows and heights are measured inside its safe- area: a staff raised or a spark into the margin in one frame is not a taller figure (G8 judges+ area: a staff raised or a spark into the margin in one frame is not a taller figure (G8 notesthe margin). A walk cycle (contact, passing, contact, passing) also warns whenits two contact frames differ by less than 40% of the mean contact↔passing difference: the legsbarely change sides.- G8 safe area, on a sprite or icon: the engine's safe area (`safe_area`, the margin `prepare`- keeps around every cell). A pixel on the canvas's outermost row or column fails — the margin- is room for a weapon tip, a strand of hair or an effect, never the canvas edge. It warns when- the body box — the rows and columns holding at least a quarter as many opaque pixels as the- fullest one, so a thin tip drops out of it — reaches more than a pixel past the safe area, and- when a sprite's body box does not end on the floor row, the safe area's own bottom row, where- `prepare`'s fit grounds a frame. Below 11 px the margin is 0 and there is no edge to keep.--A failed gate fails the candidate; a warning is reported and passes.+ keeps around every cell), a target for the body's average size and not a wall. G8 never fails.+ Its judgment is the one the image path makes when it snaps a sprite to pixels,+ `frames.extract.safe_area_fit`, called on each frame's opaque box: past the physical cap (the+ canvas's width, its height less the margin under the floor row) warns, a reroll candidate; past+ the safe area but within the cap is an info line; nothing fails. G8 also warns when a sprite's+ body box — the rows and columns holding at least a quarter as many opaque pixels as the fullest+ one, so a thin tip drops out of it — does not end on the floor row, the safe area's own bottom+ row, where `prepare`'s fit grounds a frame. Below 11 px the margin is 0: the safe area and the+ cap are the canvas.++A failed gate fails the candidate; a warning is reported and passes; an info line is reported and+asks for nothing."""from __future__ import annotations@@ -36,7 +40,6 @@ BORDER_TRANSPARENT_MIN = 0.5HEIGHT_SPREAD_MAX = 1WALK_CONTACT_RATIO_MIN = 0.4BODY_LINE_SHARE = 0.25-SAFE_OVERFLOW_MAX = 1Frame = Sequence[Sequence[Pixel]]@@ -176,65 +179,67 @@ def _body_lines(counts: list[int]) -> list[int]:return [i for i, n in enumerate(counts) if n and n >= BODY_LINE_SHARE * fullest]-def _frame_safe(frame: Frame, area: dict[str, Any]) -> dict[str, Any]:+def _frame_boxes(frame: Frame) -> dict[str, Any]:+ """The opaque box of a frame and its size, and its body box."""height, width = len(frame), len(frame[0])- mx, my = area["margin"]- left, top, right, bottom = area["box"]rows = [sum(1 for p in row if _opaque(p)) for row in frame]columns = [sum(1 for y in range(height) if _opaque(frame[y][x])) for x in range(width)]- edge = {(x, y) for y in range(height) for x in range(width) if _opaque(frame[y][x])- and ((mx and x in (0, width - 1)) or (my and y in (0, height - 1)))}if not any(rows):- return {"edge_pixels": 0, "bbox": None, "body_box": None, "overflow": None}+ return {"bbox": None, "size": [0, 0], "body_box": None}used_rows = [y for y, n in enumerate(rows) if n]used_columns = [x for x, n in enumerate(columns) if n]body_rows, body_columns = _body_lines(rows), _body_lines(columns)- body = [body_columns[0], body_rows[0], body_columns[-1], body_rows[-1]]return {- "edge_pixels": len(edge),"bbox": [used_columns[0], used_rows[0], used_columns[-1], used_rows[-1]],- "body_box": body,- "overflow": {"left": max(0, left - body[0]), "top": max(0, top - body[1]),- "right": max(0, body[2] - right), "bottom": max(0, body[3] - bottom)},+ "size": [used_columns[-1] - used_columns[0] + 1, used_rows[-1] - used_rows[0] + 1],+ "body_box": [body_columns[0], body_rows[0], body_columns[-1], body_rows[-1]],}def g8_safe_area(frames: dict[str, Frame], kind: str, area: dict[str, Any]) -> dict[str, Any]:- per = {name: _frame_safe(frame, area) for name, frame in frames.items()}- edge = sum(m["edge_pixels"] for m in per.values())- body_overflow = {}- for name, m in per.items():- sides = {side: px for side, px in (m["overflow"] or {}).items() if px > SAFE_OVERFLOW_MAX}- if sides:- body_overflow[name] = sides+ # Imported here, as `prepare` above: the judgment is the image path's, made in one place.+ from sprite_gen.frames.extract import safe_area_fit++ names = list(frames)+ per = {name: _frame_boxes(frames[name]) for name in names}+ first = frames[names[0]]+ mx, my = area["margin"]+ fit = safe_area_fit([tuple(per[name]["size"]) for name in names], len(first[0]), len(first), mx, my)floor = area["floor_row"] if kind == "sprite" else Noneoff_floor = {name: m["body_box"][3] - floor for name, m in per.items()if floor is not None and m["body_box"] and m["body_box"][3] != floor}- return {"ok": edge == 0, "margin": area["margin"], "safe_area": area["size"], "safe_box": area["box"],- "floor_row": floor, "edge_pixels": edge, "overflow_max": SAFE_OVERFLOW_MAX,- "body_overflow": body_overflow, "off_floor": off_floor, "frames": per}---def _g8_warnings(g8: dict[str, Any]) -> list[str]:- lines = []- if g8["body_overflow"]:- (width, height), (mx, my) = g8["safe_area"], g8["margin"]- where = "; ".join(f"{name}: " + ", ".join(f"{px} px {side}" for side, px in sides.items())- for name, sides in g8["body_overflow"].items())- margin = f"{mx}" if mx == my else f"{mx}x{my}"- lines.append(f"G8 the body reaches past the {width}x{height} safe area by more than {SAFE_OVERFLOW_MAX} px "- f"({where}) — only a thin detail may go into the {margin} px margin")+ return {"warn": bool(fit["over"] or off_floor), "margin": area["margin"], "safe_area": fit["safe"],+ "physical_cap": fit["cap"], "safe_box": area["box"], "floor_row": floor,+ "over_cap": [names[i] for i in fit["over"]], "past_safe_area": [names[i] for i in fit["soft"]],+ "off_floor": off_floor, "frames": per}+++def _g8_lines(g8: dict[str, Any]) -> tuple[list[str], list[str]]:+ """G8's warnings (a reroll candidate) and its info lines (nothing is asked), in the image path's words."""+ def sizes(names: list[str]) -> str:+ return ", ".join(f"{name}:{g8['frames'][name]['size'][0]}x{g8['frames'][name]['size'][1]}" for name in names)++ warnings, info = [], []+ if g8["over_cap"]:+ width, height = g8["physical_cap"]+ warnings.append(f"G8: frames exceed the physical cap {width}x{height} (reroll candidates): {sizes(g8['over_cap'])}")if g8["off_floor"]:where = ", ".join(f"{name} {abs(d)} px {'below' if d > 0 else 'above'} it" for name, d in g8["off_floor"].items())- lines.append(f"G8 the feet are not on the floor row (the safe area's bottom row): {where}")- return lines+ warnings.append(f"G8 the feet are not on the floor row (the safe area's bottom row): {where}")+ if g8["past_safe_area"]:+ width, height = g8["safe_area"]+ info.append(f"G8: frames exceed the safe area {width}x{height} but fit within the margin zone (informational, "+ f"no action): {sizes(g8['past_safe_area'])}")+ return warnings, infodef evaluate(frames: dict[str, Frame], *, kind: str, rule: PaletteRule, walk_cycle: bool) -> dict[str, Any]:- """Every gate of one candidate. `ok` is G2, G3, G6 and G8 together; `warnings` say what G4, G5,- the walk check and G8 found, one line each."""+ """Every gate of one candidate. `ok` is G2, G3 and G6 together; `warnings` say what G4, G5, the+ walk check and G8 found that may want a redraw, `info` what G8 found that asks for nothing, one+ line each."""gates: dict[str, Any] = {"G2": g2_palette(frames, rule), "G3": g3_alpha(frames, kind)}warnings: list[str] = []+ info: list[str] = []first = next(iter(frames.values()))area = None if kind == "tile" else safe_area(len(first[0]), len(first))if kind == "tile":@@ -255,6 +260,7 @@ def evaluate(frames: dict[str, Frame], *, kind: str, rule: PaletteRule, walk_cycf"{WALK_CONTACT_RATIO_MIN:.0%}) — touch up the legs")if area is not None:gates["G8"] = g8_safe_area(frames, kind, area)- warnings += _g8_warnings(gates["G8"])- failed = [name for name in ("G2", "G3", "G6", "G8") if name in gates and not gates[name]["ok"]]- return {"ok": not failed, "failed": failed, "warnings": warnings, **gates}+ g8_warnings, info = _g8_lines(gates["G8"])+ warnings += g8_warnings+ failed = [name for name in ("G2", "G3", "G6") if name in gates and not gates[name]["ok"]]+ return {"ok": not failed, "failed": failed, "warnings": warnings, "info": info, **gates}