Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

fix: preserve cutout colors in game atlas packs

Soohong Kim76f45debc35a
diff --git a/docs/game-pack.md b/docs/game-pack.md
index bc947dc..46fe7cc 100644
--- a/docs/game-pack.md
+++ b/docs/game-pack.md
@@ -73,7 +73,7 @@ The `display` object requires exactly one positive integer dimension:
* `height`: Canvas height in pixels; width preserves aspect ratio to the nearest whole pixel.
* `body_height`: Character body height in pixels. Scales using source metadata `body_h`. When `body_h` is absent, provide `source_body_height` on the asset entry root.
-Frame alpha is not auto-trimmed. Resampling defaults to `nearest` when source metadata contains `frame_variant=pixel`, and `lanczos` otherwise. For plain pixel-art PNGs lacking metadata, set `"resample": "nearest"`.
+Frame alpha is not auto-trimmed. Accepted request `resample` values remain `nearest` and `lanczos`, defaulting to `nearest` when source metadata contains `frame_variant=pixel`, and `lanczos` otherwise. `nearest` uses Pillow nearest-neighbour directly, preserving pixel-art samples. The `lanczos` request mode now delegates to the engine's shared `sprite_gen.util.resample.resize_cell`, the same cutout scaler used by video-loop, extract, slice-sheet, and scene. It scales coverage separately from colour (LANCZOS coverage and Hamming colour), avoiding the colour ringing of plain RGBA LANCZOS (refer to the Cells item in [video-pipeline.md](video-pipeline.md)). For plain pixel-art PNGs lacking metadata, set `"resample": "nearest"`.
### Playback overrides and defaults
@@ -84,7 +84,7 @@ Source policies and row anchors are preserved by the asset adapter. Optional ent
* `hold_last`: Hold final frame on completion (defaults to `false`).
* `end_frame`: Zero-based output playback termination index (defaults to final frame; validated within frame count).
* `blend`: `"normal"` (default) or `"add"`.
-* `direction`: Direction override code or `null` (defaults to `null`).
+* `direction`: Direction override code or `null` (defaults to `null`). Allowed only if the entry resolves to one animation; the user can select one source `state` to override one animation. An entry expanding multiple states or directions must reject any `direction` field, including `null`, before publishing output.
* `events`: Array of `{"frame": <int>, "name": "<string>"}` triggers where `frame` is a zero-based playback position validated within frame count (defaults to `[]`).
## Packing and layout
diff --git a/sprite_gen/compose/game_pack.py b/sprite_gen/compose/game_pack.py
index 58273ad..cedfaf6 100644
--- a/sprite_gen/compose/game_pack.py
+++ b/sprite_gen/compose/game_pack.py
@@ -14,6 +14,7 @@ import tempfile
from PIL import Image
from sprite_gen.spec.assets import finite, load_asset_states
+from sprite_gen.util.resample import resize_cell
MAX_PAGE_SIZE = 4096
MAX_BYTES = 50_000_000
@@ -76,7 +77,7 @@ def _display(sequence, entry):
sampling = entry.get("resample", "nearest" if sequence.metadata.get("frame_variant") == "pixel" else "lanczos")
if sampling not in ("nearest", "lanczos"):
raise ValueError("resample must be nearest or lanczos")
- return size, anchor, Image.Resampling.NEAREST if sampling == "nearest" else Image.Resampling.LANCZOS
+ return size, anchor, sampling
def _prepare(request, base, page_size):
@@ -96,6 +97,8 @@ def _prepare(request, base, page_size):
if not isinstance(entry.get("source"), str) or not entry["source"]:
raise ValueError("each asset requires a source path")
sequences = load_asset_states(base / entry["source"], state=entry.get("state"), fps=entry.get("fps"), anchor=entry.get("anchor"))
+ if len(sequences) > 1 and "direction" in entry:
+ raise ValueError("direction override requires one animation; select a source state")
for state, sequence in sequences.items():
key = asset_id if state is None else f"{asset_id}/{_name(state)}"
size, anchor, sampling = _display(sequence, entry)
@@ -107,7 +110,8 @@ def _prepare(request, base, page_size):
for index, image in enumerate(sequence.frames):
name = f"{key}/{index:06d}"
animation["frames"].append(name)
- frames.append((name, image.resize(size, sampling), anchor))
+ cell = image.resize(size, Image.Resampling.NEAREST) if sampling == "nearest" else resize_cell(image, size)
+ frames.append((name, cell, anchor))
animations[key] = animation
sources.update(sequence.source_files)
return dict(sorted(animations.items())), sorted(frames, key=lambda f: f[0]), sources
diff --git a/tests/compose/test_game_pack.py b/tests/compose/test_game_pack.py
index 18be4b7..bd508da 100644
--- a/tests/compose/test_game_pack.py
+++ b/tests/compose/test_game_pack.py
@@ -7,7 +7,9 @@ import sys
import pytest
from PIL import Image
+from keyed_figure import colour_outside, figure
from sprite_gen.compose import game_pack
+from sprite_gen.util.resample import resize_cell
def write_json(path, data):
@@ -43,6 +45,37 @@ def pixels(out, result, animation):
return found
[email protected]("scale,resample", [(0.16, None), (0.5, "lanczos"), (0.75, None)])
+def test_scaled_cutout_carries_no_colour_its_source_did_not_have(tmp_path, scale, resample):
+ src = figure()
+ src.save(tmp_path / "hero.png")
+ entry = {"id": "hero", "source": "hero.png", "display": {"height": round(src.height * scale)}}
+ if resample is not None:
+ entry["resample"] = resample
+ result = game_pack.pack(request(tmp_path, [entry]), tmp_path / "out")
+ (cell,) = pixels(tmp_path / "out", result, "hero")
+ assert colour_outside(src, cell) == 0
+ assert cell.tobytes() == resize_cell(src, cell.size).tobytes()
+ assert colour_outside(src, src.resize(cell.size, Image.Resampling.LANCZOS)) > 100
+
+
[email protected]("pixel_metadata", [False, True])
+def test_pixel_resampling_keeps_nearest_samples(tmp_path, pixel_metadata):
+ src = figure()
+ src.save(tmp_path / "hero.png")
+ entry = {"id": "hero", "source": "hero.png", "display": {"height": 90}}
+ if pixel_metadata:
+ write_json(tmp_path / "hero.json", {
+ "frames": 1, "w": src.width, "h": src.height, "delay_ms": 100, "frame_variant": "pixel",
+ })
+ entry["source"] = "hero.json"
+ else:
+ entry["resample"] = "nearest"
+ result = game_pack.pack(request(tmp_path, [entry]), tmp_path / "out")
+ (cell,) = pixels(tmp_path / "out", result, "hero")
+ assert cell.tobytes() == src.resize(cell.size, Image.Resampling.NEAREST).tobytes()
+
+
def test_mixed_export_preserves_timing_order_policy_pivot_and_pixel_colors(tmp_path):
strip(tmp_path)
Image.new("RGBA", (4, 6), (61, 29, 243, 127)).save(tmp_path / "pixel.png")
@@ -105,6 +138,17 @@ def test_direction_sheet_uses_declared_row_positions_and_lengths(tmp_path):
expected = [Image.new("RGBA", (1, 1), c).getpixel((0, 0)) for c in colors[code]]
assert [f.getpixel((1, 1)) for f in pixels(out, result, f"walk/{code}")] == expected
+ for direction in ("E", None):
+ entry = {"id": "walk", "source": "set.json", "display": {"body_height": 3}, "direction": direction}
+ overridden = request(tmp_path, [entry])
+ with pytest.raises(ValueError, match="direction.*state"):
+ game_pack.pack(overridden, tmp_path / "ambiguous")
+ assert not (tmp_path / "ambiguous").exists()
+ entry["state"] = "N"
+ selected = game_pack.pack(request(tmp_path, [entry]), tmp_path / f"selected-{direction}")
+ assert list(selected["animations"]) == ["walk/N"]
+ assert selected["animations"]["walk/N"]["direction"] == direction
+
def test_runtime_atlas_repeated_rectangles_and_variable_durations(tmp_path):
strip(tmp_path)