Files
windroost/tools/pixel_sprite_pack.py
T

186 lines
7.7 KiB
Python

#!/usr/bin/env python3
"""Turn independent magenta-backed sources into an exact runtime atlas.
The default path is deliberately simple: key the background, crop the complete
subject, and resize it once into the runtime cell. Optional ``--pixelize`` is
available only when a source is not already pixel art; it is never required for
an image that was generated in the project's pixel style.
"""
from __future__ import annotations
import argparse
import json
import math
from pathlib import Path
from PIL import Image
def parse_size(value: str) -> tuple[int, int]:
try:
w, h = (int(part) for part in value.lower().split("x", 1))
except Exception as exc:
raise argparse.ArgumentTypeError("size must be WIDTHxHEIGHT") from exc
if w <= 0 or h <= 0:
raise argparse.ArgumentTypeError("size must be positive")
return w, h
def parse_rgb(value: str) -> tuple[int, int, int]:
try:
values = tuple(int(part) for part in value.split(","))
except Exception as exc:
raise argparse.ArgumentTypeError("color must be R,G,B") from exc
if len(values) != 3 or any(channel < 0 or channel > 255 for channel in values):
raise argparse.ArgumentTypeError("color must be R,G,B")
return values
def key_image(image: Image.Image, key: tuple[int, int, int], hard: float, soft: float) -> Image.Image:
"""Create an alpha mask from a noisy magenta backing colour."""
kr, kg, kb = key
out = image.convert("RGBA")
pixels = []
for r, g, b, _ in out.getdata():
distance = math.sqrt((r - kr) ** 2 + (g - kg) ** 2 + (b - kb) ** 2)
if distance <= hard:
alpha = 0
elif distance >= soft:
alpha = 255
else:
alpha = round((distance - hard) / (soft - hard) * 255)
# Remove only visible magenta spill from the transition band.
if alpha and min(r, b) - g > 18:
excess = min(r, b) - g
spill = 1.0 - alpha / 255.0
r = max(0, round(r - excess * spill))
b = max(0, round(b - excess * spill))
pixels.append((r, g, b, alpha))
out.putdata(pixels)
return out
def quantize_with_alpha(image: Image.Image, colors: int) -> Image.Image:
image = image.convert("RGBA")
alpha = image.getchannel("A")
rgb = Image.new("RGB", image.size, (0, 0, 0))
rgb.paste(image.convert("RGB"), mask=alpha)
rgb = rgb.quantize(colors=colors, dither=Image.Dither.NONE).convert("RGB")
rgb.putalpha(alpha)
return rgb
def prepare(source: Path, cell_size: tuple[int, int], pixel_step: int, fit: float,
key: tuple[int, int, int], hard: float, soft: float, colors: int,
pixelize: bool, resample: Image.Resampling, resample_name: str) -> tuple[Image.Image, dict]:
image = key_image(Image.open(source), key, hard, soft)
bbox = image.getchannel("A").getbbox()
if bbox is None:
raise ValueError(f"{source} became empty after magenta key")
art = image.crop(bbox)
cell_w, cell_h = cell_size
max_w = max(1, round(cell_w * fit))
max_h = max(1, round(cell_h * fit))
if pixelize:
logical_w = max(1, cell_w // pixel_step)
logical_h = max(1, cell_h // pixel_step)
max_w = max(1, round(logical_w * fit))
max_h = max(1, round(logical_h * fit))
mode = "optional_pixelize"
else:
logical_w = logical_h = None
mode = "direct_crop"
scale = min(max_w / art.width, max_h / art.height)
target_size = (max(1, round(art.width * scale)), max(1, round(art.height * scale)))
resized = art.resize(target_size, resample)
if pixelize:
resized = quantize_with_alpha(resized, colors)
large_size = (resized.width * pixel_step, resized.height * pixel_step)
large = resized.resize(large_size, Image.Resampling.NEAREST)
else:
large = resized
cell = Image.new("RGB", cell_size, key)
x = (cell_w - large.width) // 2
y = (cell_h - large.height) // 2
cell.paste(large, (x, y), large)
return cell, {
"source": str(source),
"source_size": list(image.size),
"source_alpha_bbox": list(bbox),
"processing_mode": mode,
"logical_canvas": [logical_w, logical_h] if pixelize else None,
"pixel_step": pixel_step if pixelize else None,
"resample": resample_name,
"pre_upscale_size": list(resized.size),
"runtime_size": list(large.size),
"cell_offset": [x, y],
"palette_colors": colors,
}
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--inputs", required=True, help="comma-separated source PNG paths")
parser.add_argument("--names", required=True, help="comma-separated stable cell names")
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--cols", required=True, type=int)
parser.add_argument("--cell-size", required=True, type=parse_size)
parser.add_argument("--pixel-step", type=int, default=3, help="only used with --pixelize")
parser.add_argument("--fit", type=float, default=0.82)
parser.add_argument("--colors", type=int, default=32, help="only used with --pixelize")
parser.add_argument("--pixelize", action="store_true", help="optional conversion for non-pixel sources")
parser.add_argument("--resample", choices=("nearest", "lanczos"), default="nearest")
parser.add_argument("--key", type=parse_rgb, default=(255, 0, 255))
parser.add_argument("--hard", type=float, default=70)
parser.add_argument("--soft", type=float, default=135)
args = parser.parse_args()
inputs = [Path(item) for item in args.inputs.split(",") if item]
names = [item for item in args.names.split(",") if item]
if len(inputs) != len(names):
parser.error("inputs and names must contain the same number of items")
if args.cols <= 0 or len(inputs) % args.cols:
parser.error("the number of inputs must be divisible by --cols")
if args.pixel_step <= 0 or not 0 < args.fit <= 1:
parser.error("pixel-step must be positive and fit must be between 0 and 1")
if args.colors < 2 or args.colors > 256:
parser.error("colors must be between 2 and 256")
resample = Image.Resampling.NEAREST if args.resample == "nearest" else Image.Resampling.LANCZOS
cell_w, cell_h = args.cell_size
rows = len(inputs) // args.cols
atlas = Image.new("RGB", (args.cols * cell_w, rows * cell_h), args.key)
entries = []
for index, (source, name) in enumerate(zip(inputs, names)):
cell, entry = prepare(source, args.cell_size, args.pixel_step, args.fit, args.key, args.hard, args.soft, args.colors, args.pixelize, resample, args.resample)
row, col = divmod(index, args.cols)
atlas.paste(cell, (col * cell_w, row * cell_h))
entry.update({"name": name, "atlas_rect": [col * cell_w, row * cell_h, cell_w, cell_h]})
entries.append(entry)
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",
"rows": rows,
"cols": args.cols,
"cell_size": [cell_w, cell_h],
"atlas_size": list(atlas.size),
"background": list(args.key),
"key_hard_distance": args.hard,
"key_soft_distance": args.soft,
"fit": args.fit,
"processing_mode": "optional_pixelize" if args.pixelize else "direct_crop",
"resample": args.resample,
"entries": entries,
}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps({"output": str(args.output), "manifest": str(manifest), "atlas_size": list(atlas.size)}))
return 0
if __name__ == "__main__":
raise SystemExit(main())