Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix: preserve character scale across non-pixel sprite rows
huajuan404daf91ff256dd
diff --git a/docs/pixel-unfake.md b/docs/pixel-unfake.mdindex 4fa180b..d19ec60 100644--- a/docs/pixel-unfake.md+++ b/docs/pixel-unfake.md@@ -26,6 +26,14 @@ Optional `fit` object (opt-in; absent means legacy behavior). For pixel-art targ`prepare_sprite_run.py` exposes these as `--fit-resample`, `--fit-align-x`, `--fit-align-y`, and `--fit-ground-frames` / `--no-fit-ground-frames`, plus the `pixel_unfake` family below as `--fit-pixel-unfake`, `--fit-logical-height`, `--fit-palette-size`, `--fit-detail-bias`, `--fit-outline {on,off,STRENGTH}`, `--fit-pitch-hint`. CLI flags override the same keys in `--request` JSON; either way the merged result is recorded in the run's `sprite-request.json` `fit` object (SSoT).+With `fit.pixel_unfake: false`, extracted poses in each state row share one shrink+ratio, chosen to fit the widest and tallest poses inside the cell's safe area.+A raised or extended weapon therefore does not shrink only that pose's body.+This preserves scale already present in the generated row; it does not repair+size drift drawn by the image model. Alignment still follows `align_x`/`align_y`,+and separate state rows can have different shrink ratios. The pixel-unfake path+and standalone `fit_to_cell` calls keep their existing behavior.+## `pixel_unfake` modeFor true pixel-unfake output (game-ready chunky pixel art with intact 1px outlines), use the `pixel_unfake` mode instead of `resample` — it removes ALL non-integer resampling:diff --git a/sprite_gen/frames/extract.py b/sprite_gen/frames/extract.pyindex 48a2494..3d68ee7 100644--- a/sprite_gen/frames/extract.py+++ b/sprite_gen/frames/extract.py@@ -1267,6 +1267,8 @@ def fit_to_cell(safe_margin_x: int,safe_margin_y: int,fit: dict[str, Any] | None = None,+ *,+ scale: float | None = None,) -> Image.Image:# `fit` comes from sprite-request.json ("fit" object):# resample: "lanczos" (default) | "nearest" | "kcentroid" — kcentroid is the@@ -1293,7 +1295,8 @@ def fit_to_cell(sprite = image.crop(bbox)max_width = max(1, cell_width - safe_margin_x * 2)max_height = max(1, cell_height - safe_margin_y * 2)- scale = min(max_width / sprite.width, max_height / sprite.height, 1.0)+ if scale is None:+ scale = min(max_width / sprite.width, max_height / sprite.height, 1.0)if scale != 1.0:new_size = (max(1, round(sprite.width * scale)), max(1, round(sprite.height * scale)))if resample_name == "kcentroid":@@ -2566,21 +2569,37 @@ def extract_component_images(strip: Image.Image, frame_count: int) -> list[Imagereturn [component_group_image(strip, group) for group in groups]+def fit_row_to_cells(images: list[Image.Image], cell_width: int, cell_height: int,+ safe_margin_x: int, safe_margin_y: int,+ fit: dict[str, Any] | None = None) -> list[Image.Image]:+ # The prop's reach changes a pose's bounds, not the character's physical size.+ # One scale for the complete row fits even its widest/tallest pose.+ bounds = [bbox for image in images if (bbox := image.getbbox()) is not None]+ scale = 1.0+ if bounds:+ max_width = max(bbox[2] - bbox[0] for bbox in bounds)+ max_height = max(bbox[3] - bbox[1] for bbox in bounds)+ scale = min(max(1, cell_width - 2 * safe_margin_x) / max_width,+ max(1, cell_height - 2 * safe_margin_y) / max_height, 1.0)+ return [fit_to_cell(image, cell_width, cell_height, safe_margin_x, safe_margin_y,+ fit, scale=scale) for image in images]++def extract_component_frames(strip: Image.Image, frame_count: int, cell_width: int, cell_height: int, safe_margin_x: int, safe_margin_y: int, fit: dict[str, Any] | None = None) -> list[Image.Image] | None:images = extract_component_images(strip, frame_count)if images is None:return None- return [fit_to_cell(image, cell_width, cell_height, safe_margin_x, safe_margin_y, fit) for image in images]+ return fit_row_to_cells(images, cell_width, cell_height, safe_margin_x, safe_margin_y, fit)def extract_slot_frames(strip: Image.Image, frame_count: int, cell_width: int, cell_height: int, safe_margin_x: int, safe_margin_y: int, fit: dict[str, Any] | None = None) -> list[Image.Image]:slot_width = strip.width / frame_count- frames = []+ images = []for index in range(frame_count):left = round(index * slot_width)right = round((index + 1) * slot_width)- frames.append(fit_to_cell(strip.crop((left, 0, right, strip.height)), cell_width, cell_height, safe_margin_x, safe_margin_y, fit))- return frames+ images.append(strip.crop((left, 0, right, strip.height)))+ return fit_row_to_cells(images, cell_width, cell_height, safe_margin_x, safe_margin_y, fit)def chroma_adjacent_count(image: Image.Image, chroma_key: tuple[int, int, int], threshold: float) -> int:diff --git a/tests/frames/test_row_scale.py b/tests/frames/test_row_scale.pynew file mode 100644index 0000000..0b06790--- /dev/null+++ b/tests/frames/test_row_scale.py@@ -0,0 +1,68 @@+# SPDX-License-Identifier: Apache-2.0+"""Weapon motion must not change the size of an unchanged body in an image row."""+import json++import pytest+from PIL import Image, ImageDraw+from conftest import run_script+from sprite_gen.frames import extract+++def attack_strip():+ strip = Image.new('RGBA', (720, 240))+ for i in range(3):+ pose = Image.new('RGBA', (240, 240))+ draw = ImageDraw.Draw(pose)+ draw.rectangle((20, 90, 79, 209), fill=(220, 30, 30, 255))+ if i == 1: # lift a weapon above the unchanged body+ draw.rectangle((40, 10, 49, 89), fill=(30, 30, 220, 255))+ if i == 2: # extend that weapon to the right+ draw.rectangle((80, 100, 204, 109), fill=(30, 30, 220, 255))+ strip.alpha_composite(pose, (i * 240, 0))+ return strip+++def red_body_size(frame):+ mask = Image.new('L', frame.size)+ mask.putdata([255 if r > 180 and g < 80 and b < 80 and a > 128 else 0+ for r, g, b, a in frame.get_flattened_data()])+ box = mask.getbbox()+ assert box is not None+ return box[2]-box[0], box[3]-box[1]++[email protected]('route', ['components', 'slots'])[email protected]('resample', ['nearest', 'lanczos', 'kcentroid'])[email protected]('cell', [(128, 128), (192, 128), (128, 192)])+def test_weapon_pose_changes_preserve_body_scale(route, resample, cell):+ fn = extract.extract_component_frames if route == 'components' else extract.extract_slot_frames+ frames = fn(attack_strip(), 3, *cell, 12, 12,+ {'align_x': 'bbox-center', 'resample': resample})+ assert frames is not None and len(frames) == 3+ bodies = [red_body_size(frame) for frame in frames]+ for axis in (0, 1):+ assert max(size[axis] for size in bodies)-min(size[axis] for size in bodies) <= 1+ for frame in frames:+ assert frame.size == cell and frame.mode == 'RGBA'+ x0, y0, x1, y1 = frame.getbbox()+ assert x0 >= 12 and y0 >= 12 and x1 <= cell[0]-12 and y1 <= cell[1]-12+++def test_cli_extract_preserves_body_scale(tmp_path):+ prepared = run_script('prepare_sprite_run.py', '--out-dir', str(tmp_path),+ '--character-id', 'weapon-scale', '--cell-size', '128',+ '--safe-margin', '12', '--no-fit-pixel-unfake',+ '--fit-align-x', 'bbox-center', '--fit-resample', 'nearest',+ '--chroma-key', '#00FF00', '--request-json', json.dumps({+ 'states': {'attack': {'frames': 3, 'fps': 8, 'loop': False}}}))+ assert prepared.returncode == 0, prepared.stdout + prepared.stderr+ attack_strip().save(tmp_path / 'raw/attack.png')+ extracted = run_script('extract_sprite_row_frames.py', '--run-dir', str(tmp_path))+ assert extracted.returncode == 0, extracted.stdout + extracted.stderr+ manifest = json.loads((tmp_path / 'frames/frames-manifest.json').read_text())+ row = manifest['rows'][0]+ assert manifest['ok'] and row['method'] == 'components'+ sizes = [red_body_size(Image.open(tmp_path / path).convert('RGBA')) for path in row['files']]+ assert len(sizes) == 3+ for axis in (0, 1):+ assert max(size[axis] for size in sizes) - min(size[axis] for size in sizes) <= 1