Skip to content

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

test: define pixel and video effect contracts

Soohong Kim58bcf5f7b019
diff --git a/tests/gen/test_pixel_effect.py b/tests/gen/test_pixel_effect.py
new file mode 100644
index 0000000..c857c5d
--- /dev/null
+++ b/tests/gen/test_pixel_effect.py
@@ -0,0 +1,59 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Effect grids have a lifetime and a centre, not a character's feet and fixed height."""
+import argparse
+import json
+
+import pytest
+from PIL import Image
+
+from sprite_gen.gen import pixel_draw as draw
+
+
+def request(*args):
+ parser = argparse.ArgumentParser()
+ draw.add_arguments(parser)
+ return draw.resolve_request(parser.parse_args(["--subject", "a spark", "--out-dir", "unused", *args]))
+
+
+def test_only_effects_accept_two_to_eight_frames():
+ names = ",".join(f"f{i}" for i in range(8))
+ assert len(request("--kind", "effect", "--frames", names).frames) == 8
+ assert len(request("--kind", "effect").frames) >= 2
+ for kind in ("sprite", "icon", "tile"):
+ with pytest.raises(SystemExit, match="at most 4"):
+ request("--kind", kind, "--frames", names)
+ for names in ("only", ",".join(f"f{i}" for i in range(9))):
+ with pytest.raises(SystemExit, match="2.*8"):
+ request("--kind", "effect", "--frames", names)
+ with pytest.raises(SystemExit, match="walk-cycle"):
+ request("--kind", "effect", "--walk-cycle")
+ prompt = draw.generation_prompt(request("--kind", "effect"))
+ assert "center" in prompt and "empty" in prompt and "brightness" in prompt
+ assert "same proportions" not in prompt and "floor" not in prompt
+
+
+def grid_text():
+ rows = lambda points: "\n".join("".join("a" if (x, y) in points else "." for x in range(8)) for y in range(8))
+ return "PALETTE\n. transparent\na #FF6600\n" + "\n".join(
+ f"FRAME {name}\n{rows(points)}" for name, points in [
+ ("birth", {(4, 4)}), ("peak", {(2, 2), (4, 4), (6, 6)}), ("gone", set())]) + "\nEND\n"
+
+
+def test_effect_grid_keeps_sparks_changed_extent_and_empty_end(tmp_path):
+ grid = tmp_path / "effect.txt"
+ grid.write_text(grid_text())
+ out = tmp_path / "out"
+ assert draw.main(["--grid", str(grid), "--kind", "effect", "--out-dir", str(out)]) == 0
+ report = json.loads((out / "report.json").read_text())
+ assert report["status"] == "ok"
+ meta = json.loads((out / report["files"]["metadata"]).read_text())
+ assert meta["loop"] is False and meta["hold_last"] is False
+ assert meta["anchor"] == [4, 4] and meta["frames"] == 3
+ strip = Image.open(out / report["files"]["strip"]).convert("RGBA")
+ assert strip.size == (24, 8)
+ assert strip.getpixel((8 + 2, 2)) == (255, 102, 0, 255)
+ assert strip.crop((16, 0, 24, 8)).getchannel("A").getbbox() is None
+ with Image.open(out / report["files"]["gif"]) as gif:
+ assert "loop" not in gif.info
+ with pytest.raises(SystemExit, match="G3"):
+ draw.main(["--grid", str(grid), "--kind", "sprite", "--out-dir", str(tmp_path / "sprite")])
diff --git a/tests/video/test_effect.py b/tests/video/test_effect.py
new file mode 100644
index 0000000..5053631
--- /dev/null
+++ b/tests/video/test_effect.py
@@ -0,0 +1,58 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Black-backed emissions keep their energy, isolated sparks and empty endpoints."""
+from PIL import Image
+import pytest
+
+from sprite_gen._deps import np
+from sprite_gen.video import frames, batch, clip_prompt
+
+
+def test_brightness_alpha_reconstructs_dark_and_saturated_emission(tmp_path):
+ src = tmp_path / "raw.png"
+ rgb = np.zeros((16, 16, 3), dtype=np.uint8)
+ rgb[0, 0] = (255, 0, 0) # an intentional isolated edge spark
+ rgb[7, 7] = (3, 3, 3) # dark smoke cannot be discarded by a threshold
+ rgb[8, 8] = (65, 25, 5) # soft glow: no double multiplication by alpha
+ Image.fromarray(rgb).save(src)
+ report = frames.key_frames([src], tmp_path / "keyed", alpha_mode="brightness")
+ rgba = np.array(Image.open(tmp_path / "keyed" / src.name)).astype(float)
+ emitted = rgba[:, :, :3] * rgba[:, :, 3:] / 255
+ assert np.max(abs(emitted - rgb)) <= .5
+ assert rgba[7, 7, 3] == 3 and rgba[0, 0, 3] == 255
+ assert not rgba[1, 1].any()
+ # An additive preview on a bright surface must never acquire a dark halo.
+ for background in (0, 220, 255):
+ composed = np.minimum(background + emitted, 255)
+ assert np.min(composed) >= background
+ assert report["blend"] == "add" and report["edge_policy"] == "off"
+ assert report["specks"]["dropped"] == 0
+
+
+def test_brightness_run_skips_chroma_cleanup(tmp_path, monkeypatch):
+ src = tmp_path / "f0001.png"
+ Image.new("RGB", (8, 8), (0, 0, 0)).save(src)
+ clip = tmp_path / "clip.mp4"
+ clip.write_bytes(b"synthetic")
+ monkeypatch.setattr(frames, "probe", lambda _: {"stream_index": 0, "fps": 24})
+ monkeypatch.setattr(frames, "extract", lambda *a: [src])
+ def forbidden(*a, **k):
+ pytest.fail("brightness alpha must not call chroma cleanup")
+ for name in ("cutout", "drop_specks", "decide_spill", "edge_contact"):
+ monkeypatch.setattr(frames, name, forbidden)
+ report = frames.run_frames(clip, tmp_path / "out", key="auto", allow_edge_contact=False,
+ report_path=None, alpha_mode="brightness")
+ assert report["alpha_zero_pct_min"] == 100
+ assert report["alpha_mode"] == "brightness" and report["blend"] == "add"
+
+
+def test_effect_prompt_uses_black_end_and_lifetime_only():
+ prompt = batch.build_prompt("front", "effect", "A burst of fire")
+ assert "black" in prompt and "disappear" in prompt
+ assert "no effects" not in prompt and "chroma" not in prompt
+ assert "no effects" in batch.build_prompt("front", "attack", None)
+ assert batch.pins_last_frame("effect", "front")
+ plan = clip_prompt.plan_prompt(direction="front", state="effect")
+ assert plan["last_frame"] == "black" and plan["cycle"] == "lifetime"
+ assert "--alpha-mode brightness" in plan["commands"]["frames"]
+ with pytest.raises(SystemExit, match="end.frame"):
+ clip_prompt.plan_prompt(direction="front", state="effect", last_frame=False, unpinned=True)