97 lines
3.4 KiB
Python
97 lines
3.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Pack already-processed transparent frames without resizing them."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import re
|
|
from pathlib import Path
|
|
|
|
from PIL import Image
|
|
|
|
|
|
def parse_size(value: str) -> tuple[int, int]:
|
|
w, h = (int(part) for part in value.lower().split("x", 1))
|
|
if w <= 0 or h <= 0:
|
|
raise argparse.ArgumentTypeError("size must be positive")
|
|
return w, h
|
|
|
|
|
|
def frame_key(path: Path) -> int:
|
|
match = re.search(r"(\d+)(?:\.[^.]+)?$", path.stem)
|
|
return int(match.group(1)) if match else 0
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--states-json", required=True, type=Path, help="state -> {dir,fps,loop}")
|
|
parser.add_argument("--output", required=True, type=Path)
|
|
parser.add_argument("--cell-size", type=parse_size, default=(384, 384))
|
|
parser.add_argument("--cols", type=int, default=4)
|
|
args = parser.parse_args()
|
|
|
|
spec = json.loads(args.states_json.read_text(encoding="utf-8"))
|
|
if not isinstance(spec, dict) or not spec:
|
|
parser.error("states-json must be a non-empty object")
|
|
cell_w, cell_h = args.cell_size
|
|
if args.cols <= 0:
|
|
parser.error("cols must be positive")
|
|
|
|
state_frames: dict[str, list[Path]] = {}
|
|
for state, config in spec.items():
|
|
directory = Path(config["dir"])
|
|
frames = sorted(directory.glob("frame-*.png"), key=frame_key)
|
|
if not frames:
|
|
parser.error(f"state {state} has no frame-*.png files: {directory}")
|
|
for frame in frames:
|
|
with Image.open(frame) as image:
|
|
if image.size != (cell_w, cell_h):
|
|
parser.error(f"{frame} is {image.size}, expected {(cell_w, cell_h)}")
|
|
state_frames[state] = frames
|
|
|
|
total = sum(len(frames) for frames in state_frames.values())
|
|
rows = (total + args.cols - 1) // args.cols
|
|
atlas = Image.new("RGBA", (args.cols * cell_w, rows * cell_h), (0, 0, 0, 0))
|
|
entries: dict[str, dict] = {}
|
|
index = 0
|
|
for state, config in spec.items():
|
|
rects = []
|
|
for frame_index, frame in enumerate(state_frames[state]):
|
|
row, col = divmod(index, args.cols)
|
|
with Image.open(frame) as image:
|
|
atlas.alpha_composite(image.convert("RGBA"), (col * cell_w, row * cell_h))
|
|
rects.append({
|
|
"frame": frame_index,
|
|
"rect": [col * cell_w, row * cell_h, cell_w, cell_h],
|
|
"source": str(frame),
|
|
"duration_ms": round(1000 / float(config.get("fps", 8))),
|
|
})
|
|
index += 1
|
|
entries[state] = {
|
|
"frames": len(rects),
|
|
"fps": config.get("fps", 8),
|
|
"loop": bool(config.get("loop", False)),
|
|
"frame_layout": rects,
|
|
}
|
|
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
atlas.save(args.output, "PNG")
|
|
manifest = args.output.with_suffix(".manifest.json")
|
|
manifest.write_text(json.dumps({
|
|
"schema": 1,
|
|
"status": "pilot",
|
|
"processing": "exact_paste_no_resize",
|
|
"cell_size": [cell_w, cell_h],
|
|
"cols": args.cols,
|
|
"rows": rows,
|
|
"atlas_size": list(atlas.size),
|
|
"states": entries,
|
|
}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
print(json.dumps({"output": str(args.output), "manifest": str(manifest), "frames": total}))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|