Skip to content

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

feat(assets,scene): bind measurements to decoded bytes and selected sequences; stage scene output

Soohong Kimbad3431661f0
diff --git a/sprite_gen/background/__init__.py b/sprite_gen/background/__init__.py
new file mode 100644
index 0000000..43b77ec
--- /dev/null
+++ b/sprite_gen/background/__init__.py
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Standalone background asset preparation and inspection."""
diff --git a/sprite_gen/background/tile.py b/sprite_gen/background/tile.py
new file mode 100644
index 0000000..9b2268a
--- /dev/null
+++ b/sprite_gen/background/tile.py
@@ -0,0 +1,325 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Periodic background crops, joined with a hard minimum-error RGBA quilt.
+
+The source must contain ``period + overlap`` pixels along the selected axis;
+``1 <= overlap < period``. A bounded search chooses a crop. Its trailing
+overlap B replaces part of the leading overlap A along a connected seam.
+Every output pixel is copied intact from A or B, including its original alpha.
+There is no resampling, blur, compositing, or colour interpolation.
+
+Reports describe local pixel differences, not semantic continuity of a painting.
+Inspect repeated tiles visually even when the numerical checks pass.
+"""
+
+from __future__ import annotations
+
+import argparse
+import io
+import json
+from numbers import Integral
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+from sprite_gen._deps import np
+from sprite_gen.spec.runio import acquire_run_dir_lock, atomic_write_set, release_run_dir_lock
+
+
+MAX_CANDIDATES = 32
+_ASSESSMENT = (
+ "Local pixel discontinuity checks only; review repeated tiles visually for "
+ "cut silhouettes, repeated landmarks, and painting continuity."
+)
+
+
+def _pixels(image: Image.Image, axis: str) -> Any:
+ if axis not in ("x", "y"):
+ raise ValueError("axis must be x or y")
+ if not isinstance(image, Image.Image):
+ raise TypeError("image must be a PIL image")
+ if min(image.size) < 1:
+ raise ValueError("image dimensions must be positive")
+ pixels = np.asarray(image.convert("RGBA"))
+ return pixels if axis == "x" else pixels.transpose(1, 0, 2)
+
+
+def _differences(a: Any, b: Any) -> tuple[Any, Any]:
+ """Visible RGB on both black and white, plus independent alpha (0..255)."""
+ a = a.astype(np.float32)
+ b = b.astype(np.float32)
+ alpha_delta = a[..., 3] - b[..., 3]
+ black_delta = a[..., :3] * (a[..., 3:] / 255) - b[..., :3] * (b[..., 3:] / 255)
+ white_delta = black_delta - alpha_delta[..., None]
+ color = np.maximum(np.abs(black_delta), np.abs(white_delta)).mean(axis=-1)
+ return color, np.abs(alpha_delta)
+
+
+def _stats(values: Any) -> dict[str, float]:
+ if not values.size:
+ return {"mean": 0.0, "p95": 0.0, "max": 0.0}
+ return {"mean": float(values.mean()), "p95": float(np.percentile(values, 95)),
+ "max": float(values.max())}
+
+
+def _alpha_stats(values: Any) -> dict[str, float]:
+ return {**_stats(values),
+ "mismatch_fraction": float(np.count_nonzero(values) / values.size) if values.size else 0.0}
+
+
+def _limits(interior: dict[str, float]) -> dict[str, float]:
+ return {key: max(floor, 2 * interior[key])
+ for key, floor in (("mean", 3.0), ("p95", 8.0), ("max", 16.0))}
+
+
+def _exceeds(measured: dict[str, float], limits: dict[str, float]) -> bool:
+ return any(measured[key] > limit for key, limit in limits.items())
+
+
+def _ratio(edge: float, interior: float) -> float | None:
+ # JSON has no infinity. Null explicitly means a nonzero edge over a zero
+ # baseline; the absolute metrics and thresholds still determine the verdict.
+ return edge / interior if interior else (0.0 if edge == 0 else None)
+
+
+def inspect_tile(image: Image.Image, axis: str = "x") -> dict[str, Any]:
+ """Measure the actual wrap edge against ordinary interior neighbours.
+
+ RGB is compared as displayed over both black and white, so invisible RGB
+ cannot inflate a score and transparent silhouettes cannot disappear from it.
+ All differences are in 8-bit channel units. ``pass`` is a local heuristic,
+ never a guarantee of seamless artwork. An axis of length one lacks evidence.
+ """
+ pixels = _pixels(image, axis)
+ edge_color, edge_alpha = _differences(pixels[:, -1], pixels[:, 0])
+ inner_color, inner_alpha = _differences(pixels[:, :-1], pixels[:, 1:])
+ color, alpha = _stats(edge_color), _alpha_stats(edge_alpha)
+ interior_color, interior_alpha = _stats(inner_color), _alpha_stats(inner_alpha)
+ color_limits, alpha_limits = _limits(interior_color), _limits(interior_alpha)
+ reasons = []
+ if pixels.shape[1] < 2:
+ reasons.append("No interior neighbours along the tiling axis to establish a baseline.")
+ if _exceeds(color, color_limits):
+ reasons.append("Wrap edge color difference exceeds interior variation.")
+ if _exceeds(alpha, alpha_limits):
+ reasons.append("Wrap seam alpha mismatch exceeds interior variation.")
+ return {
+ "schema_version": 1, "axis": axis, "size": list(image.size),
+ "period": int(pixels.shape[1]),
+ "status": "needs-review" if reasons else "pass",
+ "requires_visual_review": True, "assessment": _ASSESSMENT,
+ "review_reasons": reasons,
+ "color_metric": "mean per-channel absolute difference, worst of black/white composites (0..255)",
+ "edge_color_difference": color,
+ "interior_color_difference": interior_color,
+ "edge_to_interior_color_ratio": _ratio(color["mean"], interior_color["mean"]),
+ "seam_alpha_mismatch": alpha,
+ "interior_alpha_difference": interior_alpha,
+ "edge_to_interior_alpha_ratio": _ratio(alpha["mean"], interior_alpha["mean"]),
+ "thresholds": {"color": color_limits, "alpha": alpha_limits},
+ }
+
+
+def _minimum_seam(error: Any) -> tuple[Any, float]:
+ """Minimum accumulated error, with neighbouring rows moving at most one px.
+
+ ``cut`` is the LAST B pixel, not the first A pixel. In particular cut=0
+ must copy B at x=0: the wrap then joins adjacent source pixels P-1 and P.
+ Reserve the overlap's final column for A when overlap > 1. A one-column
+ overlap necessarily copies B there and switches to A at the next column.
+ """
+ height, overlap = error.shape
+ width = max(1, overlap - 1)
+ costs = error[0, :width].astype(np.float64)
+ steps = np.zeros((height, width), dtype=np.int8)
+ for row in range(1, height):
+ left = np.concatenate(([np.inf], costs[:-1]))
+ right = np.concatenate((costs[1:], [np.inf]))
+ steps[row, (left < costs) & (left <= right)] = -1
+ steps[row, (right < costs) & (right < left)] = 1
+ costs = np.minimum(costs, np.minimum(left, right)) + error[row, :width]
+ seam = np.empty(height, dtype=np.int32)
+ seam[-1] = int(np.argmin(costs))
+ score = float(costs[seam[-1]] / height)
+ for row in range(height - 1, 0, -1):
+ seam[row - 1] = seam[row] + steps[row, seam[row]]
+ return seam, score
+
+
+def _crop_box(start: int, length: int, cross: int, axis: str) -> list[int]:
+ return [start, 0, start + length, cross] if axis == "x" else [0, start, cross, start + length]
+
+
+def make_tile(
+ image: Image.Image, period: int, *, axis: str = "x", overlap: int = 32,
+) -> tuple[Image.Image, dict[str, Any]]:
+ """Return an RGBA tile and JSON-safe report, leaving ``image`` untouched.
+
+ The tile is ``period`` pixels along ``axis`` with the other dimension
+ unchanged. At most MAX_CANDIDATES evenly spaced crop starts are evaluated,
+ including both endpoints. The seam search is exact within each candidate,
+ but the bounded crop search does not claim a global optimum.
+ """
+ for name, value in (("period", period), ("overlap", overlap)):
+ if isinstance(value, bool) or not isinstance(value, Integral):
+ raise TypeError(f"{name} must be an integer")
+ period, overlap = int(period), int(overlap)
+ if period < 2 or not 1 <= overlap < period:
+ raise ValueError("geometry requires period >= 2 and 1 <= overlap < period")
+ pixels = _pixels(image, axis)
+ height, length, _ = pixels.shape
+ slack = length - period - overlap
+ if slack < 0:
+ raise ValueError(
+ f"source has {length} pixels along {axis}; period + overlap requires {period + overlap}"
+ )
+ starts = np.unique(np.linspace(0, slack, min(MAX_CANDIDATES, slack + 1)).round().astype(int))
+ best_score = float("inf")
+ best_start = 0
+ best_seam = None
+ for start in starts:
+ a = pixels[:, start:start + overlap].astype(np.float32)
+ b = pixels[:, start + period:start + period + overlap].astype(np.float32)
+ # Premultiplied RGB removes hidden RGB from the energy; alpha remains an
+ # independent equally weighted channel. Selection still copies raw RGBA.
+ a[..., :3] *= a[..., 3:] / 255
+ b[..., :3] *= b[..., 3:] / 255
+ seam, score = _minimum_seam(np.square(a - b).mean(axis=-1))
+ if score < best_score:
+ best_score, best_start, best_seam = score, int(start), seam
+ assert best_seam is not None
+ crop = pixels[:, best_start:best_start + period + overlap]
+ result = crop[:, :period].copy()
+ use_b = np.arange(overlap)[None, :] <= best_seam[:, None]
+ result[:, :overlap] = np.where(use_b[..., None], crop[:, period:], crop[:, :overlap])
+ tile = Image.fromarray(result if axis == "x" else result.transpose(1, 0, 2))
+ report = inspect_tile(tile, axis)
+
+ # The wrap is now a natural source adjacency. It can pass while the new
+ # internal cut is bad, so inspect that cut separately against SOURCE detail.
+ # Include vertical mask transitions as well as each row's horizontal cut.
+ rows = np.arange(height)
+ seam_color, seam_alpha = _differences(result[rows, best_seam], result[rows, best_seam + 1])
+ reference_color, reference_alpha = _differences(crop[:, :-1], crop[:, 1:])
+ turn_rows = np.flatnonzero(np.diff(best_seam))
+ if turn_rows.size:
+ turn_cols = np.maximum(best_seam[turn_rows], best_seam[turn_rows + 1])
+ turn_color, turn_alpha = _differences(result[turn_rows, turn_cols], result[turn_rows + 1, turn_cols])
+ seam_color = np.concatenate((seam_color, turn_color))
+ seam_alpha = np.concatenate((seam_alpha, turn_alpha))
+ vertical_color, vertical_alpha = _differences(crop[:-1], crop[1:])
+ reference_color = np.concatenate((reference_color.ravel(), vertical_color.ravel()))
+ reference_alpha = np.concatenate((reference_alpha.ravel(), vertical_alpha.ravel()))
+ quilt_color, quilt_alpha = _stats(seam_color), _alpha_stats(seam_alpha)
+ reference_color_stats, reference_alpha_stats = _stats(reference_color), _alpha_stats(reference_alpha)
+ quilt_color_limits, quilt_alpha_limits = _limits(reference_color_stats), _limits(reference_alpha_stats)
+ if _exceeds(quilt_color, quilt_color_limits):
+ report["review_reasons"].append("Internal quilt color difference exceeds source interior variation.")
+ if _exceeds(quilt_alpha, quilt_alpha_limits):
+ report["review_reasons"].append("Internal quilt alpha mismatch exceeds source interior variation.")
+ report.update({
+ "status": "needs-review" if report["review_reasons"] else "pass",
+ "method": "crop-overlap-minimum-error-quilt",
+ "source_size": list(image.size),
+ "source_crop": _crop_box(best_start, period + overlap, height, axis),
+ "core_crop": _crop_box(best_start, period, height, axis),
+ "overlap": overlap,
+ "search": {"evaluated_candidates": int(starts.size), "candidate_limit": MAX_CANDIDATES,
+ "available_crops": slack + 1, "strategy": "evenly-spaced including endpoints"},
+ "quilt_seam": {
+ "positions": best_seam.tolist(), "position_meaning": "last tail/B pixel per cross-axis row",
+ "mean_squared_error": best_score,
+ "color_difference": quilt_color, "alpha_mismatch": quilt_alpha,
+ "source_interior_color_difference": reference_color_stats,
+ "source_interior_alpha_difference": reference_alpha_stats,
+ "thresholds": {"color": quilt_color_limits, "alpha": quilt_alpha_limits},
+ },
+ })
+ return tile, report
+
+
+def _same_file(a: Path, b: Path) -> bool:
+ return a == b or (a.exists() and b.exists() and a.samefile(b))
+
+
+def _validate_paths(source: Path, out: Path, report: Path) -> None:
+ if out.suffix.lower() != ".png" or report.suffix.lower() != ".json":
+ raise ValueError("--out must be a PNG path and --report must be a JSON path")
+ if not source.is_file():
+ raise ValueError(f"source is not a file: {source}")
+ for target in (out, report):
+ if _same_file(source, target):
+ raise ValueError(f"refusing to overwrite source: {target}")
+ if target.exists() and not target.is_file():
+ raise ValueError(f"output is not a regular file: {target}")
+ for parent in target.parents:
+ if parent.exists() and not parent.is_dir():
+ raise ValueError(f"output parent is not a directory: {parent}")
+ if _same_file(out, report):
+ raise ValueError("PNG output and JSON report must be different files")
+ if out in report.parents or report in out.parents:
+ raise ValueError("an output file cannot be another output's parent directory")
+
+
+def _publish(
+ *, source: Path, out: Path, period: int, axis: str = "x", overlap: int = 32,
+ report: Path | None = None,
+) -> int:
+ source = Path(source).expanduser().resolve()
+ out = Path(out).expanduser().resolve()
+ report_path = Path(report).expanduser().resolve() if report is not None else out.with_suffix(".report.json")
+ _validate_paths(source, out, report_path)
+ with Image.open(source) as image:
+ if image.format != "PNG" or getattr(image, "n_frames", 1) != 1:
+ raise ValueError("--source must be a single-frame PNG")
+ tile, metrics = make_tile(image, period, axis=axis, overlap=overlap)
+ metrics.update({"source": str(source), "output": str(out)})
+ png = io.BytesIO()
+ tile.save(png, format="PNG")
+ payloads = {out: png.getvalue(), report_path: json.dumps(metrics, indent=2, allow_nan=False) + "\n"}
+ # Validate and encode everything before any filesystem mutation. Lock each
+ # destination directory (stable ordering), since reports may live elsewhere.
+ # The locks are task-scoped: whatever this call acquired is released when it
+ # returns or fails, including after a partial acquisition, so an API caller
+ # never keeps a writer lock until the process exits.
+ _validate_paths(source, out, report_path)
+ locked = []
+ try:
+ for directory in sorted({out.parent, report_path.parent}):
+ directory.mkdir(parents=True, exist_ok=True)
+ acquire_run_dir_lock(directory, "background-tile")
+ locked.append(directory)
+ _validate_paths(source, out, report_path)
+ atomic_write_set(payloads)
+ finally:
+ for directory in reversed(locked):
+ release_run_dir_lock(directory)
+ print(f"background-tile: {metrics['status']} — {out} (report: {report_path})")
+ return 0
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--source", required=True, type=Path, help="independent single-frame PNG")
+ parser.add_argument("--out", required=True, type=Path, help="output PNG; cannot overwrite the source")
+ parser.add_argument("--period", required=True, type=int, help="tile length in pixels along --axis")
+ parser.add_argument("--axis", choices=("x", "y"), default="x")
+ parser.add_argument("--overlap", type=int, default=32,
+ help="1 <= overlap < period; source must contain period + overlap pixels")
+ parser.add_argument("--report", type=Path, help="JSON report (default: <out-stem>.report.json)")
+
+
+def run(**kwargs: Any) -> int:
+ try:
+ return _publish(**kwargs)
+ except (OSError, ValueError, TypeError) as exc:
+ raise SystemExit(f"background-tile: {exc}") from exc
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ add_arguments(parser)
+ return run(**vars(parser.parse_args(argv)))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/effects/shadow.py b/sprite_gen/effects/shadow.py
new file mode 100644
index 0000000..eb8ab75
--- /dev/null
+++ b/sprite_gen/effects/shadow.py
@@ -0,0 +1,254 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Project an asset's alpha silhouette into a shadow about its stationary foot."""
+
+from __future__ import annotations
+
+import argparse
+import io
+import json
+import math
+from numbers import Integral, Real
+from pathlib import Path
+
+from PIL import Image, ImageFilter
+
+from sprite_gen.spec.runio import (
+ acquire_run_dir_lock,
+ atomic_write_set,
+ release_run_dir_lock,
+)
+
+
+_MAX_FRAME_PIXELS = 16_777_216
+_MAX_SEQUENCE_PIXELS = 67_108_864
+_MAX_DIMENSION = 65_536
+
+
+def _number(value, name: str, low: float, high: float) -> float:
+ if isinstance(value, bool) or not isinstance(value, Real):
+ raise ValueError(f"{name} must be a finite number in [{low}, {high}]")
+ try:
+ result = float(value)
+ except OverflowError as exc:
+ raise ValueError(f"{name} is too large") from exc
+ if not math.isfinite(result) or not low <= result <= high:
+ raise ValueError(f"{name} must be a finite number in [{low}, {high}]")
+ return result
+
+
+def _anchor(value) -> tuple[float, float]:
+ if not isinstance(value, (tuple, list)) or len(value) != 2:
+ raise ValueError("anchor must contain two pixel coordinates")
+ return (_number(value[0], "anchor x", -1_000_000, 1_000_000),
+ _number(value[1], "anchor y", -1_000_000, 1_000_000))
+
+
+def _rgb(value) -> tuple[int, int, int]:
+ if not isinstance(value, (tuple, list)) or len(value) != 3:
+ raise ValueError("color must contain three RGB integers in [0, 255]")
+ if any(isinstance(v, bool) or not isinstance(v, Integral) or not 0 <= v <= 255
+ for v in value):
+ raise ValueError("color must contain three RGB integers in [0, 255]")
+ return tuple(int(v) for v in value)
+
+
+def _parameters(squash, shear, opacity, blur, color):
+ return (_number(squash, "squash", 0.001, 1),
+ _number(shear, "shear", -16, 16),
+ _number(opacity, "opacity", 0, 1),
+ _number(blur, "blur", 0, 128), _rgb(color))
+
+
+def _check_size(size, *, limit=_MAX_FRAME_PIXELS):
+ width, height = size
+ if (width <= 0 or height <= 0 or max(width, height) > _MAX_DIMENSION
+ or width * height > limit):
+ raise ValueError(f"shadow canvas {width}x{height} exceeds the supported size "
+ f"(positive dimensions <= {_MAX_DIMENSION}, <= {limit} pixels)")
+
+
+def _geometry(size, anchor, squash, shear, blur):
+ _check_size(size)
+ width, height = size
+ ax, ay = anchor
+ # Forward map: x' = x + shear*(y-ay), y' = ay + squash*(y-ay).
+ # Including the anchor keeps even an external pivot representable. Bounds
+ # come from the full image rectangle, never a changing per-frame alpha bbox.
+ # Bicubic interpolation can touch two transparent source pixels past an
+ # edge; their projected support must fit even at the maximum shear.
+ xs = [x + shear * (y - ay) for x in (-2, width + 2)
+ for y in (-2, height + 2)] + [ax]
+ ys = [ay + squash * (y - ay) for y in (-2, height + 2)] + [ay]
+ # Pillow's Gaussian approximation has finite support. Four radii plus
+ # interpolation clearance leave a transparent border even at opaque edges.
+ padding = math.ceil(4 * blur) + 3
+ left, top = math.floor(min(xs)) - padding, math.floor(min(ys)) - padding
+ right, bottom = math.ceil(max(xs)) + padding, math.ceil(max(ys)) + padding
+ output_size = (right - left, bottom - top)
+ _check_size(output_size)
+ return output_size, (ax - left, ay - top), (left, top)
+
+
+def project_shadow(
+ image: Image.Image,
+ anchor: tuple[float, float],
+ *,
+ squash: float = 0.25,
+ shear: float = 0.8,
+ opacity: float = 0.4,
+ blur: float = 3,
+ color: tuple[int, int, int] = (20, 15, 30),
+) -> tuple[Image.Image, tuple[float, float]]:
+ """Return an RGBA shadow and its foot anchor, both in canvas pixel units.
+
+ Place the returned anchor at the sprite's world anchor. The affine map
+ fixes that point exactly; positive shear sends pixels above it to the left.
+ Canvas bounds include the entire projection and blur, including for an
+ off-center anchor. Neither source pixels nor image metadata are modified.
+
+ ``squash`` is in [0.001, 1], ``shear`` in [-16, 16], ``opacity`` in [0, 1],
+ and ``blur`` is a radius in [0, 128] pixels. RGB components are bytes.
+ """
+ if not isinstance(image, Image.Image):
+ raise ValueError("image must be a PIL Image")
+ anchor = _anchor(anchor)
+ squash, shear, opacity, blur, color = _parameters(squash, shear, opacity, blur, color)
+ size, shadow_anchor, (left, top) = _geometry(image.size, anchor, squash, shear, blur)
+ _, ay = anchor
+ # Pillow expects the inverse map, in edge-based pixel coordinates.
+ # A transparent source border avoids Pillow's interpolation edge clamping:
+ # an opaque silhouette touching the source edge then behaves exactly as it
+ # would on a larger transparent source canvas.
+ source_alpha = Image.new("L", (image.width + 4, image.height + 4))
+ source_alpha.paste(image.convert("RGBA").getchannel("A"), (2, 2))
+ alpha = source_alpha.transform(
+ size, Image.Transform.AFFINE,
+ (1, -shear / squash, left - shear * (top - ay) / squash + 2,
+ 0, 1 / squash, ay + (top - ay) / squash + 2),
+ resample=Image.Resampling.BICUBIC, fillcolor=0,
+ )
+ if blur:
+ alpha = alpha.filter(ImageFilter.GaussianBlur(blur))
+ # Applying opacity last ensures monotonicity, including blurred edges.
+ alpha = alpha.point([round(value * opacity) for value in range(256)])
+ shadow = Image.new("RGBA", size, (*color, 0))
+ shadow.putalpha(alpha)
+ return shadow, shadow_anchor
+
+
+def _parse_color(value: str) -> tuple[int, int, int]:
+ try:
+ if value.startswith("#") and len(value) == 7:
+ return _rgb(tuple(int(value[i:i + 2], 16) for i in (1, 3, 5)))
+ return _rgb(tuple(int(part.strip()) for part in value.split(",")))
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError("color must be R,G,B or #RRGGBB") from exc
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--source", required=True, type=Path, help="asset PNG or manifest")
+ parser.add_argument("--out-dir", required=True, type=Path)
+ parser.add_argument("--state", help="animation state for an atlas")
+ parser.add_argument("--fps", type=float, help="explicit source frame rate")
+ parser.add_argument("--anchor-x", type=float, help="source foot x in pixels; supply both axes")
+ parser.add_argument("--anchor-y", type=float, help="source foot y in pixels; supply both axes")
+ parser.add_argument("--squash", type=float, default=0.25, help="vertical scale [0.001, 1]")
+ parser.add_argument("--shear", type=float, default=0.8, help="shear [-16, 16]; positive falls left")
+ parser.add_argument("--opacity", type=float, default=0.4, help="alpha multiplier [0, 1]")
+ parser.add_argument("--blur", type=float, default=3, help="blur radius [0, 128] pixels")
+ parser.add_argument("--color", type=_parse_color, default=(20, 15, 30), help="R,G,B or #RRGGBB")
+
+
+def _png_bytes(image: Image.Image) -> bytes:
+ buffer = io.BytesIO()
+ image.save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+def _validate_targets(targets, sources):
+ protected = {Path(path).resolve() for path in sources}
+ for target in targets:
+ if target.resolve() in protected:
+ raise ValueError(f"shadow output would overwrite source: {target}")
+ if target.is_symlink() or (target.exists() and not target.is_file()):
+ raise ValueError(f"shadow output must be a regular file: {target}")
+
+
+def run(
+ *, source: Path, out_dir: Path, state: str | None = None, fps: float | None = None,
+ anchor_x: float | None = None, anchor_y: float | None = None,
+ squash: float = 0.25, shear: float = 0.8, opacity: float = 0.4,
+ blur: float = 3, color: tuple[int, int, int] = (20, 15, 30),
+) -> int:
+ """Publish frame PNGs, ``shadow.png`` strip and ``shadow.asset.json`` descriptor."""
+ squash, shear, opacity, blur, color = _parameters(squash, shear, opacity, blur, color)
+ if (anchor_x is None) != (anchor_y is None):
+ raise ValueError("anchor-x and anchor-y must be supplied together")
+ anchor = None if anchor_x is None else _anchor((anchor_x, anchor_y))
+ if fps is not None:
+ fps = _number(fps, "fps", 0.001, 1000)
+ source, out_dir = Path(source).resolve(), Path(out_dir).resolve()
+ # The shared adapter alone owns source formats and timing interpretation.
+ # Lazy import also keeps the pure image operation independent of file IO.
+ from sprite_gen.spec.assets import load_asset
+
+ asset = load_asset(source, state=state, fps=fps, anchor=anchor)
+ if not asset.frames or len(asset.frames) != len(asset.durations):
+ raise ValueError("asset must have one duration for every frame")
+ durations = [_number(value, "frame duration", 1e-9, 86_400)
+ for value in asset.durations]
+ if any(frame.size != asset.frames[0].size for frame in asset.frames):
+ raise ValueError("asset frames must share a uniform canvas")
+ anchor = _anchor(asset.anchor)
+ size, output_anchor, _ = _geometry(asset.frames[0].size, anchor, squash, shear, blur)
+ strip_size = (size[0] * len(asset.frames), size[1])
+ _check_size(strip_size, limit=_MAX_SEQUENCE_PIXELS)
+ protected = (source, *asset.source_files)
+ targets = [out_dir / f"frame-{i:03d}.png" for i in range(len(asset.frames))]
+ sheet_path, descriptor_path = out_dir / "shadow.png", out_dir / "shadow.asset.json"
+ _validate_targets([*targets, sheet_path, descriptor_path], protected)
+ if out_dir.exists() and not out_dir.is_dir():
+ raise ValueError(f"out-dir must be a directory: {out_dir}")
+
+ # All rendering, encoding and validation precede directory/lock creation.
+ # No failed projection can leave a partially published frame sequence.
+ sheet = Image.new("RGBA", strip_size)
+ payloads = {}
+ for index, (frame, target) in enumerate(zip(asset.frames, targets)):
+ rendered, _ = project_shadow(
+ frame, anchor, squash=squash, shear=shear, opacity=opacity, blur=blur, color=color)
+ sheet.paste(rendered, (index * size[0], 0))
+ payloads[target] = _png_bytes(rendered)
+ payloads[sheet_path] = _png_bytes(sheet)
+ descriptor = {
+ "kind": "sprite-gen-asset", "version": 1,
+ "frames": [{"file": target.name, "duration": duration}
+ for target, duration in zip(targets, durations)],
+ "anchor": list(output_anchor),
+ }
+ payloads[descriptor_path] = json.dumps(descriptor, indent=2, allow_nan=False) + "\n"
+ out_dir.mkdir(parents=True, exist_ok=True)
+ acquire_run_dir_lock(out_dir, "shadow")
+ try:
+ # A concurrent writer may have changed the destination while rendering.
+ _validate_targets(payloads, protected)
+ atomic_write_set(payloads)
+ finally:
+ release_run_dir_lock(out_dir)
+ print(json.dumps({"ok": True, "manifest": str(descriptor_path), "sheet": str(sheet_path),
+ "frames": len(targets), "anchor": list(output_anchor)}))
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ add_arguments(parser)
+ args = parser.parse_args(argv)
+ try:
+ return run(**vars(args))
+ except (ValueError, OSError) as exc:
+ parser.error(str(exc))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/qa/motion.py b/sprite_gen/qa/motion.py
new file mode 100644
index 0000000..70210df
--- /dev/null
+++ b/sprite_gen/qa/motion.py
@@ -0,0 +1,471 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Inspect motion without editing frames or inferring travel from a silhouette.
+
+Manual measurement example::
+
+ python -m sprite_gen.qa.motion --source walk.json --contacts 0:4,8:12 \
+ --foot-box 8,25,34,12 --facing right --out motion.json
+
+Contacts are zero-based inclusive stance spans (or consecutive frame indices).
+The caller asserts that the SAME foot is planted throughout each span. foot_box
+is a fixed source-pixel x,y,width,height ROI enclosing only that foot throughout
+its sweep. It must exclude the other foot and body. Facing is an annotation,
+never a request to flip, reverse, or apply a speed. Confidence measures agreement
+with these manual assumptions; pixels alone cannot establish ground contact.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import math
+from numbers import Integral
+from pathlib import Path
+import sys
+from typing import TYPE_CHECKING
+
+from sprite_gen._deps import np
+from PIL import Image
+
+from sprite_gen.spec.assets import sequence_identity
+from sprite_gen.spec.runio import acquire_run_dir_lock, atomic_write_set, release_run_dir_lock
+
+if TYPE_CHECKING:
+ from sprite_gen.spec.assets import FrameSequence
+
+
+NEAR_SILHOUETTE_IOU = 0.98
+
+
+def _number(value, name):
+ if isinstance(value, bool):
+ raise ValueError(f"{name} must be finite")
+ try:
+ value = float(value)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{name} must be finite") from exc
+ if not math.isfinite(value):
+ raise ValueError(f"{name} must be finite")
+ return value
+
+
+def _contact_spans(contacts, count):
+ if contacts is None:
+ return []
+ if isinstance(contacts, str):
+ entries = []
+ for token in contacts.split(","):
+ parts = token.split(":")
+ if len(parts) not in (1, 2) or not all(p.strip().isdigit() for p in parts):
+ raise ValueError("contacts must be indices or inclusive spans, e.g. 0:4,8:12")
+ values = tuple(int(p) for p in parts)
+ entries.append(values[0] if len(values) == 1 else values)
+ else:
+ try:
+ entries = list(contacts)
+ except TypeError as exc:
+ raise ValueError("contacts must be indices or inclusive spans") from exc
+ if not entries:
+ raise ValueError("contacts cannot be empty")
+ spans = []
+ previous_was_index = False
+ for entry in entries:
+ is_index = isinstance(entry, Integral) and not isinstance(entry, bool)
+ if is_index:
+ start = end = int(entry)
+ else:
+ if not isinstance(entry, (list, tuple)) or len(entry) != 2:
+ raise ValueError("contacts must contain integer indices or (start, end) spans")
+ start, end = entry
+ if any(not isinstance(v, Integral) or isinstance(v, bool) for v in entry):
+ raise ValueError("contact indices must be integers")
+ start, end = int(start), int(end)
+ if not 0 <= start <= end < count:
+ raise ValueError("contact span is reversed or outside the frame sequence")
+ if spans and start <= spans[-1][1]:
+ raise ValueError("contacts must be ordered and cannot overlap or repeat")
+ if is_index and previous_was_index and spans and start == spans[-1][1] + 1:
+ spans[-1][1] = end
+ else:
+ spans.append([start, end])
+ previous_was_index = is_index
+ return spans
+
+
+def _foot_roi(foot_box, size):
+ if foot_box is None:
+ return None
+ if isinstance(foot_box, str):
+ parts = foot_box.split(",")
+ try:
+ foot_box = tuple(int(p) for p in parts)
+ except ValueError as exc:
+ raise ValueError("foot_box must be integer x,y,width,height") from exc
+ if not isinstance(foot_box, (list, tuple)) or len(foot_box) != 4:
+ raise ValueError("foot_box must be integer x,y,width,height")
+ if any(not isinstance(v, Integral) or isinstance(v, bool) for v in foot_box):
+ raise ValueError("foot_box must be integer x,y,width,height")
+ x, y, width, height = map(int, foot_box)
+ if min(x, y) < 0 or min(width, height) <= 0 or x + width > size[0] or y + height > size[1]:
+ raise ValueError("foot_box must fit inside the frame canvas with positive dimensions")
+ return x, y, width, height
+
+
+def _bbox(mask):
+ ys, xs = np.nonzero(mask)
+ if not len(xs):
+ return None
+ return [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]
+
+
+def _components(mask):
+ """Count 8-connected shapes only up to two; no selection of a 'best' blob."""
+ remaining = set(zip(*np.nonzero(mask)))
+ count = 0
+ while remaining:
+ count += 1
+ if count == 2:
+ return count
+ stack = [remaining.pop()]
+ while stack:
+ y, x = stack.pop()
+ for dy in (-1, 0, 1):
+ for dx in (-1, 0, 1):
+ neighbor = y + dy, x + dx
+ if neighbor in remaining:
+ remaining.remove(neighbor)
+ stack.append(neighbor)
+ return count
+
+
+def _foot_sample(mask, box, index, start):
+ x, y, width, height = box
+ region = mask[y:y + height, x:x + width]
+ bbox = _bbox(region)
+ sample = {"frame": index, "time_seconds": start, "bbox": None, "x": None, "y": None}
+ reasons = []
+ if bbox is None:
+ return sample, ["foot ROI is empty in a contact frame"]
+ left, top, right, bottom = bbox
+ if _components(region) > 1:
+ reasons.append("multiple disconnected shapes in foot ROI")
+ # Two legs can be connected above their soles: connectivity alone is not
+ # evidence for one foot. This band is only an ambiguity veto, never a tracker.
+ band = region[max(top, bottom - 2):bottom].any(axis=0)
+ lobes = np.count_nonzero(band & ~np.r_[False, band[:-1]])
+ if lobes > 1:
+ reasons.append("multiple contact lobes in foot ROI")
+ if left == 0 or right == width:
+ reasons.append("foot touches horizontal ROI boundary; tracking may be clipped")
+ ys, xs = np.nonzero(region)
+ sample.update(
+ bbox=[left + x, top + y, right + x, bottom + y],
+ x=float(xs.mean() + x + 0.5), y=float(ys.mean() + y + 0.5),
+ area=int(region.sum()),
+ )
+ return sample, reasons
+
+
+def _stance_candidate(masks, starts, durations, span, box):
+ first, last = span
+ candidate = {
+ "frames": span, "status": "needs-review", "confidence": 0.0,
+ "evidence": "manual contacts and foot ROI", "reasons": [], "samples": [],
+ "duration_seconds": sum(durations[first:last + 1]),
+ "measurement_elapsed_seconds": None,
+ "foot_velocity_px_per_second": None, "stride_px_per_second": None,
+ }
+ reasons = candidate["reasons"]
+ for index in range(first, last + 1):
+ sample, defects = _foot_sample(masks[index], box, index, starts[index])
+ candidate["samples"].append(sample)
+ reasons.extend(defects)
+ samples = candidate["samples"]
+ if any(sample["bbox"] is None for sample in samples):
+ candidate["reasons"] = list(dict.fromkeys(reasons))
+ return candidate
+ if max(s["bbox"][3] for s in samples) - min(s["bbox"][3] for s in samples) > 1:
+ reasons.append("foot baseline moves vertically; contact may be airborne")
+ if max(s["y"] for s in samples) - min(s["y"] for s in samples) > 1:
+ reasons.append("foot centroid moves vertically; stance is uncertain")
+ areas = [s["area"] for s in samples]
+ if max(areas) > min(areas) * 1.25:
+ reasons.append("foot silhouette area changes; tracking identity is uncertain")
+ for axis in (0, 1):
+ extents = [s["bbox"][axis + 2] - s["bbox"][axis] for s in samples]
+ if max(extents) - min(extents) > max(1, min(extents) * 0.25):
+ reasons.append("foot silhouette dimensions change; tracking identity is uncertain")
+ break
+
+ # Identical held observations carry time, but do not become extra regression
+ # votes. Their first timestamps survive; the next movement retains EVERY
+ # intervening duration. The final pose's hold is not a displacement interval.
+ observations = []
+ for sample in samples:
+ if not observations or any(sample[key] != observations[-1][key] for key in ("x", "y", "bbox", "area")):
+ observations.append(sample)
+ candidate["pose_onset_frames"] = [s["frame"] for s in observations]
+ if len(observations) < 3:
+ reasons.append("need at least three distinct tracked poses for a stance measurement")
+ if len(observations) >= 2:
+ times = np.array([s["time_seconds"] for s in observations])
+ xs = np.array([s["x"] for s in observations])
+ elapsed = float(times[-1] - times[0])
+ candidate["measurement_elapsed_seconds"] = elapsed
+ velocity = _number(float(xs[-1] - xs[0]) / elapsed, "foot velocity")
+ candidate["measured_velocity_candidate_px_per_second"] = velocity
+ deltas = np.diff(xs)
+ if (deltas > 0.25).any() and (deltas < -0.25).any():
+ reasons.append("horizontal reversal")
+ if abs(float(xs[-1] - xs[0])) < 1:
+ reasons.append("insufficient net horizontal displacement")
+ residuals = xs - (xs[0] + velocity * (times - times[0]))
+ rmse = float(np.sqrt(np.mean(residuals ** 2)))
+ candidate["fit_rmse_px"] = rmse
+ if rmse > max(0.5, float(np.ptp(xs)) * 0.1):
+ reasons.append("foot velocity is inconsistent across the declared stance")
+ if not reasons:
+ candidate.update(
+ status="verified", confidence=0.9,
+ foot_velocity_px_per_second=velocity, stride_px_per_second=abs(velocity),
+ )
+ candidate["reasons"] = list(dict.fromkeys(reasons))
+ return candidate
+
+
+def analyze_motion(sequence: FrameSequence, *, contacts=None, foot_box=None, facing=None) -> dict:
+ """Return JSON-ready evidence, preserving sequence images and all frame time.
+
+ ``contacts`` accepts ``"0:4,8:12"``, ``[(0, 4), (8, 12)]``, or an ordered
+ iterable of indices (consecutive indices become one span). Spans never bridge
+ the loop boundary. ``foot_box`` accepts a 4-tuple or ``"x,y,w,h"`` in pixels.
+ Anchor coordinates follow FrameSequence's source-pixel contract. Positive
+ foot velocity means right in image coordinates. Stride is its magnitude,
+ conditional on the manually asserted stationary-ground contact, not a claim
+ about travel direction. A report without verified contact returns null speed.
+ ``sequence`` records which sequence was measured (source, atlas state, fps
+ override, frame count, size, anchor, effective durations) so a consumer can
+ refuse to apply the stride to any other selection of the same files.
+ """
+ frames, raw_durations = tuple(sequence.frames), tuple(sequence.durations)
+ if not frames or len(frames) != len(raw_durations):
+ raise ValueError("motion analysis needs one duration per frame and at least one frame")
+ if any(not isinstance(frame, Image.Image) for frame in frames):
+ raise ValueError("sequence frames must be PIL images")
+ width, height = frames[0].size
+ if min(width, height) <= 0 or any(frame.size != (width, height) for frame in frames):
+ raise ValueError("sequence frames must share a nonempty canvas")
+ durations = [_number(value, "duration") for value in raw_durations]
+ if any(value <= 0 for value in durations):
+ raise ValueError("frame durations must be positive")
+ if len(sequence.anchor) != 2:
+ raise ValueError("anchor requires x,y in source pixels")
+ anchor = [_number(v, "anchor") for v in sequence.anchor]
+ if facing not in (None, "left", "right"):
+ raise ValueError("facing must be left or right")
+ spans = _contact_spans(contacts, len(frames))
+ box = _foot_roi(foot_box, (width, height))
+ starts = []
+ elapsed = 0.0
+ for duration in durations:
+ starts.append(elapsed)
+ next_time = elapsed + duration
+ if not math.isfinite(next_time) or next_time <= elapsed:
+ raise ValueError("frame timing exceeds finite timestamp precision")
+ elapsed = next_time
+
+ masks, rows = [], []
+ seen_frames, seen_masks = set(), set()
+ unique_masks = []
+ exact = exact_silhouette = near_silhouette = adjacent_exact = 0
+ changed = silhouette_changed = 0
+ silhouette_change = 0.0
+ sides = {name: [] for name in ("left", "top", "right", "bottom")}
+ previous_pixels = None
+ previous_hash = None
+ for index, frame in enumerate(frames):
+ pixels = np.asarray(frame.convert("RGBA"))
+ mask = pixels[:, :, 3] > 0
+ image_hash = hashlib.sha256(pixels.tobytes()).digest()
+ mask_hash = hashlib.sha256(mask.tobytes()).digest()
+ exact += image_hash in seen_frames
+ adjacent_exact += image_hash == previous_hash
+ seen_frames.add(image_hash)
+ previous_hash = image_hash
+ if mask_hash in seen_masks:
+ exact_silhouette += 1
+ else:
+ for earlier in unique_masks:
+ union = np.count_nonzero(mask | earlier)
+ if union and np.count_nonzero(mask & earlier) / union >= NEAR_SILHOUETTE_IOU:
+ near_silhouette += 1
+ break
+ unique_masks.append(mask)
+ seen_masks.add(mask_hash)
+ if previous_pixels is not None:
+ changed += bool(np.any(np.any(pixels != previous_pixels, axis=2) & (mask | masks[-1])))
+ union = np.count_nonzero(mask | masks[-1])
+ difference = np.count_nonzero(mask ^ masks[-1])
+ silhouette_changed += bool(difference > 0)
+ silhouette_change += difference / union if union else 0.0
+ previous_pixels = pixels
+ masks.append(mask)
+ bbox = _bbox(mask)
+ edge_sides = []
+ if bbox:
+ for side, touches in zip(sides, (bbox[0] == 0, bbox[1] == 0, bbox[2] == width, bbox[3] == height)):
+ if touches:
+ sides[side].append(index)
+ edge_sides.append(side)
+ ys, xs = np.nonzero(mask)
+ rows.append({
+ "frame": index, "time_seconds": starts[index], "duration_seconds": durations[index],
+ "bbox": bbox, "anchor_px": anchor.copy(),
+ "bbox_from_anchor": [v - anchor[i % 2] for i, v in enumerate(bbox)] if bbox else None,
+ "centroid_px": [float(xs.mean() + 0.5), float(ys.mean() + 0.5)] if bbox else None,
+ "opaque_pixels": int(mask.sum()), "edge_sides": edge_sides,
+ })
+ bboxes = [row["bbox"] for row in rows if row["bbox"] is not None]
+ bounds = {
+ "union": [min(b[0] for b in bboxes), min(b[1] for b in bboxes),
+ max(b[2] for b in bboxes), max(b[3] for b in bboxes)] if bboxes else None,
+ "width_range": [min(b[2] - b[0] for b in bboxes), max(b[2] - b[0] for b in bboxes)] if bboxes else None,
+ "height_range": [min(b[3] - b[1] for b in bboxes), max(b[3] - b[1] for b in bboxes)] if bboxes else None,
+ "bottom_range": [min(b[3] for b in bboxes), max(b[3] for b in bboxes)] if bboxes else None,
+ }
+ warnings = []
+ candidates = [_stance_candidate(masks, starts, durations, span, box) for span in spans] if box else []
+ status = "needs-review" if changed else "unknown"
+ velocity = stride = None
+ confidence = 0.0
+ if not spans or box is None:
+ warnings.append("Ground contact is unknown: provide both manual contacts and a single-foot ROI; silhouette bottoms do not identify a planted foot.")
+ if candidates:
+ verified = [c for c in candidates if c["status"] == "verified"]
+ if len(verified) != len(candidates):
+ warnings.append("At least one declared stance failed contact checks; no aggregate stride is verified.")
+ status = "needs-review"
+ else:
+ velocities = [c["foot_velocity_px_per_second"] for c in verified]
+ if min(velocities) * max(velocities) <= 0:
+ warnings.append("Declared stance spans disagree on foot motion sign.")
+ status = "needs-review"
+ elif max(map(abs, velocities)) > min(map(abs, velocities)) * 1.25:
+ warnings.append("Declared stance spans disagree on speed by more than 25 percent.")
+ status = "needs-review"
+ else:
+ measured_time = sum(c["measurement_elapsed_seconds"] for c in verified)
+ velocity = sum(c["foot_velocity_px_per_second"] * c["measurement_elapsed_seconds"] for c in verified) / measured_time
+ stride, confidence, status = abs(velocity), 0.9, "verified"
+ if facing and (velocity > 0) == (facing == "right"):
+ warnings.append("Measured foot motion points toward the stated facing; review the annotations. Measurement sign is unchanged.")
+ edges = sorted({index for indices in sides.values() for index in indices})
+ if edges:
+ warnings.append("Visible pixels touch the canvas edge; clipping is possible.")
+ if len(bboxes) < len(frames):
+ warnings.append("The sequence contains empty silhouettes.")
+ if exact or exact_silhouette or near_silhouette:
+ warnings.append("Repeated poses retain all source frame durations; no frames were removed.")
+ return {
+ "kind": "sprite-gen-motion-report", "version": 1, "status": status,
+ "frame_count": len(frames), "duration_seconds": elapsed, "size": [width, height],
+ "anchor_px": anchor, "facing": facing, "contacts": spans, "foot_box": list(box) if box else None,
+ "duplicate_frames": {"exact": exact, "adjacent_exact": adjacent_exact,
+ "exact_silhouette": exact_silhouette, "near_silhouette": near_silhouette},
+ "motion": {"present": bool(changed), "changed_transitions": changed,
+ "silhouette_changed_transitions": silhouette_changed,
+ "silhouette_change_per_second": _number(float(silhouette_change) / elapsed, "motion rate")},
+ "frames": rows, "bbox_stats": bounds, "edge_contact": {"frames": edges, "sides": sides},
+ "contact_candidates": candidates, "confidence": confidence,
+ "sequence": sequence_identity(sequence),
+ "source_fingerprints": sequence.fingerprints(), "stride_verified": status == "verified",
+ "foot_velocity_px_per_second": velocity, "stride_px_per_second": stride,
+ "warnings": warnings,
+ "method": {
+ "silhouette": "alpha > 0 in source canvas coordinates; bbox right/bottom are exclusive",
+ "near_silhouette_iou": NEAR_SILHOUETTE_IOU,
+ "duplicates": "Counts frames matching an earlier frame; near excludes exact silhouette matches. No time or frames are removed.",
+ "motion": "Adjacent visible pixel changes; silhouette XOR/union summed over full duration. No loop-seam assumption.",
+ "contact": "User-declared same-foot stance spans plus isolated ROI alpha centroid; no automatic contact or facing inference.",
+ "timing": "Cumulative frame-start seconds; repeated tracked poses use their first onset with all intervening durations retained. Final hold is included in duration but has no displacement endpoint.",
+ "velocity": "Endpoint horizontal displacement / pose-onset elapsed seconds; positive = image right. Stride is absolute velocity under manual ground-contact assumptions.",
+ "confidence": "0.9 = at least 3 distinct poses, stable baseline/shape, monotonic near-linear motion and consistent spans. Heuristic conditional confidence, not a calibrated contact probability.",
+ "sequence": "Identity of the analysed sequence: source, atlas state, fps override, frame count, size, anchor and effective per-frame durations. A consumer applying the stride must match all of it and source_fingerprints; another state or frame rate of the same files is a different sequence.",
+ },
+ }
+
+
+def add_arguments(parser):
+ """Register inspect-motion arguments on the parent's CLI subparser."""
+ parser.add_argument("--source", required=True, type=Path)
+ parser.add_argument("--state", help="Atlas state, required when the source has several")
+ parser.add_argument("--fps", type=float, help="Explicit frame-rate override")
+ parser.add_argument("--anchor-x", type=float, help="Anchor x in source pixels; supply with --anchor-y")
+ parser.add_argument("--anchor-y", type=float, help="Anchor y in source pixels; supply with --anchor-x")
+ parser.add_argument("--contacts", help="Manual same-foot stance: zero-based inclusive spans, e.g. 0:4,8:12")
+ parser.add_argument("--foot-box", help="Fixed x,y,width,height pixel ROI isolating one foot throughout each stance")
+ parser.add_argument("--facing", choices=("left", "right"), help="Annotation only; never flips frames or measurement sign")
+ parser.add_argument("--out", type=Path, help="Optional JSON report; otherwise stdout only")
+
+
+def _output_path(out, source, sequence):
+ path = Path(out).expanduser().resolve()
+ protected = {Path(source).expanduser().resolve(), *(Path(p).resolve() for p in sequence.source_files)}
+ if path in protected or (path.exists() and any(p.exists() and path.samefile(p) for p in protected)):
+ raise ValueError("motion report must not overwrite an asset source file")
+ if path.name == ".sprite-gen.lock" or path.name.endswith(".sg-rwlock"):
+ raise ValueError("motion report must not overwrite an output lock")
+ if path.exists() and not path.is_file():
+ raise ValueError("motion report output must be a file")
+ for ancestor in path.parents:
+ if ancestor.exists() and not ancestor.is_dir():
+ raise ValueError("motion report parent must be a directory")
+ return path
+
+
+def run(**kwargs) -> int:
+ """Analyze once; return 0 for a valid report (including unknown), 2 on error."""
+ from sprite_gen.spec.assets import load_asset
+
+ parser = argparse.ArgumentParser(add_help=False)
+ add_arguments(parser)
+ allowed = {action.dest: action.default for action in parser._actions}
+ unexpected = kwargs.keys() - allowed.keys()
+ if unexpected:
+ raise TypeError(f"unexpected keyword arguments: {', '.join(sorted(unexpected))}")
+ args = argparse.Namespace(**(allowed | kwargs))
+ try:
+ if args.source is None:
+ raise ValueError("source is required")
+ if (args.anchor_x is None) != (args.anchor_y is None):
+ raise ValueError("anchor-x and anchor-y must be supplied together")
+ anchor = None if args.anchor_x is None else (args.anchor_x, args.anchor_y)
+ sequence = load_asset(Path(args.source), state=args.state, fps=args.fps, anchor=anchor)
+ report = analyze_motion(sequence, contacts=args.contacts, foot_box=args.foot_box, facing=args.facing)
+ report["source_files"] = [str(p) for p in sequence.source_files]
+ report["source"] = str(Path(args.source).expanduser().resolve())
+ payload = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + "\n"
+ if args.out is not None:
+ output = _output_path(args.out, args.source, sequence)
+ output.parent.mkdir(parents=True, exist_ok=True)
+ acquire_run_dir_lock(output.parent, "inspect-motion")
+ try:
+ atomic_write_set({output: payload})
+ finally:
+ release_run_dir_lock(output.parent)
+ print(payload, end="")
+ return 0
+ except (OSError, ValueError) as exc:
+ print(f"inspect-motion: {exc}", file=sys.stderr)
+ return 2
+
+
+def main(argv=None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ add_arguments(parser)
+ return run(**vars(parser.parse_args(argv)))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/scene/__init__.py b/sprite_gen/scene/__init__.py
new file mode 100644
index 0000000..1a530d4
--- /dev/null
+++ b/sprite_gen/scene/__init__.py
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Optional scene consumers of existing assets and deterministic processing tools."""
diff --git a/sprite_gen/scene/inspect_scene.py b/sprite_gen/scene/inspect_scene.py
new file mode 100644
index 0000000..1203ccf
--- /dev/null
+++ b/sprite_gen/scene/inspect_scene.py
@@ -0,0 +1,156 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Measure rendered evidence; numeric checks do not certify artistic completeness."""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+from sprite_gen._deps import np
+
+from sprite_gen.scene.model import Scene, load_scene
+from sprite_gen.spec.runio import LOCK_FILENAME, RWLOCK_SUFFIX, acquire_run_dir_lock, atomic_write_set, release_run_dir_lock
+
+
+# The wrap of a loop may be no worse than twice the largest ordinary transition
+# (with a one-level floor), mirroring the tile inspector's edge-to-interior rule.
+SEAM_SLACK = 2.0
+SEAM_FLOOR = 1.0
+PHASE_CLOSURE_LIMIT = 1.0
+
+
+def _mae(a, b) -> float:
+ return float(np.abs(a - b).mean())
+
+
+def inspect_scene(scene: Scene, *, renderer=None, frame_dir=None):
+ from sprite_gen.scene.render import Renderer
+ renderer = renderer or Renderer(scene)
+ first = previous = None
+ green, magenta = 0, 0
+ clipped = {layer.id: {"top_frames": 0, "bottom_frames": 0, "side_frames": 0, "offscreen_frames": 0,
+ "empty_frames": 0, "minimum_top_y": None} for layer in scene.layers}
+ adjacent = []
+ for i in range(scene.frame_count):
+ image, placements = renderer.frame(i/scene.fps, geometry=True)
+ if frame_dir is not None:
+ image.save(Path(frame_dir) / f"frame-{i:05d}.png")
+ pixels = np.asarray(image).astype(np.int16)
+ if first is None:
+ first = pixels.copy()
+ r, g, b, a = [pixels[..., j] for j in range(4)]
+ green += int(((a > 0) & (g >= 100) & (r <= .35*g) & (b <= .35*g)).sum())
+ magenta += int(((a > 0) & (r >= 100) & (b >= .8*r) & (g <= .35*np.maximum(r,b))).sum())
+ if previous is not None:
+ adjacent.append(_mae(pixels, previous))
+ previous = pixels
+ by_layer = {}
+ for entry in placements:
+ by_layer.setdefault(entry["id"], []).append(entry)
+ for name, stat in clipped.items():
+ boxes = [e for e in by_layer.get(name, []) if e["bbox"] is not None]
+ if not boxes:
+ stat["empty_frames"] += 1
+ continue
+ visible = [e for e in boxes if e["visible"]]
+ if not visible:
+ stat["offscreen_frames"] += 1
+ else:
+ stat["top_frames"] += int(any(e["bbox"][1] < 0 for e in visible))
+ stat["bottom_frames"] += int(any(e["bbox"][3] > scene.height for e in visible))
+ stat["side_frames"] += int(any((e["bbox"][0] < 0 or e["bbox"][2] > scene.width) and not e["repeat_x"] for e in visible))
+ y = min(e["bbox"][1] for e in boxes)
+ stat["minimum_top_y"] = y if stat["minimum_top_y"] is None else min(y, stat["minimum_top_y"])
+ # The seam a viewer sees is the last rendered frame followed by the first.
+ # Phase closure (the scene state at t=duration equals t=0) is a separate
+ # fact: it holds for any periodic scene, including one whose asset jumps
+ # at its own wrap, so it cannot stand in for the seam.
+ seam = _mae(previous, first)
+ adjacent_max = max(adjacent) if adjacent else 0.0
+ seam_limit = max(SEAM_FLOOR, SEAM_SLACK * adjacent_max)
+ closure = _mae(np.asarray(renderer.frame(scene.duration)).astype(np.int16), first)
+ loop = {"seam_mae": seam, "adjacent_mae_mean": float(np.mean(adjacent)) if adjacent else 0.0,
+ "adjacent_mae_max": adjacent_max, "seam_limit": seam_limit, "seam_pass": seam <= seam_limit,
+ "phase_closure_mae": closure, "phase_closure_pass": closure <= PHASE_CLOSURE_LIMIT}
+ loop["pass"] = loop["seam_pass"] and loop["phase_closure_pass"]
+ sources = {}
+ tiles = {}
+ for name, seq in scene.assets.items():
+ contacts = []
+ for frame in seq.frames:
+ a = np.asarray(frame)[..., 3] > 128
+ contacts.append({"top": int(a[0].sum()), "bottom": int(a[-1].sum()), "left": int(a[:,0].sum()), "right": int(a[:,-1].sum())})
+ sources[name] = {"edge_contact": contacts, "completeness": "unverified", "note": "Edge contact is a diagnostic; missing artwork inside a source needs visual review."}
+ from sprite_gen.background.tile import inspect_tile
+ for layer in scene.layers:
+ if layer.repeat_x:
+ tiles[layer.id] = inspect_tile(layer.sequence.frames[0].crop((0,0,int(layer.period),layer.sequence.size[1])), axis="x")
+ warnings = []
+ if green or magenta:
+ warnings.append("key-like colours detected; compare to source subject colours before treating as residue")
+ if not loop["phase_closure_pass"]:
+ warnings.append("end-to-start scene differs; review motion/scroll periods for an intended loop")
+ if not loop["seam_pass"]:
+ warnings.append("the last frame to first frame step is larger than ordinary transitions; review the loop wrap")
+ if any(s["top_frames"] or s["bottom_frames"] for s in clipped.values()):
+ warnings.append("some source content crosses the viewport top or bottom; inspect layer bounds")
+ offscreen = [name for name, s in clipped.items() if s["offscreen_frames"]]
+ if offscreen:
+ warnings.append(f"layers entirely outside the viewport in some frames: {', '.join(offscreen)}")
+ return {"kind": "sprite-gen-scene-inspection", "version": 1, "frames": scene.frame_count,
+ "source_fingerprints": scene.source_fingerprints, "status": "needs-review" if warnings else "measured",
+ "loop": loop, "key_like_pixels": {"green": green, "magenta": magenta}, "clipping": clipped,
+ "sources": sources, "tile_joins": tiles, "warnings": warnings, "visual_review_required": True}
+
+
+def output_path(out, scene: Scene) -> Path:
+ """Resolve the report path and refuse scene inputs, their aliases and reserved lock names."""
+ path = Path(out).expanduser().resolve()
+ if path.name == LOCK_FILENAME or path.name.endswith(RWLOCK_SUFFIX):
+ raise ValueError("inspection output must not use a reserved lock name")
+ protected = [Path(p) for p in scene.source_fingerprints]
+ if path in protected or (path.exists() and any(p.exists() and path.samefile(p) for p in protected)):
+ raise ValueError("inspection output cannot overwrite scene inputs")
+ if path.exists() and not path.is_file():
+ raise ValueError("inspection output must be a file")
+ for ancestor in path.parents:
+ if ancestor.exists() and not ancestor.is_dir():
+ raise ValueError("inspection output parent must be a directory")
+ return path
+
+
+def add_arguments(parser):
+ parser.add_argument("--spec", type=Path, required=True)
+ parser.add_argument("--out", type=Path)
+ parser.add_argument("--require-loop", action="store_true")
+
+
+def run(spec, out=None, require_loop=False):
+ try:
+ scene = load_scene(spec)
+ if out is not None:
+ output_path(out, scene)
+ report = inspect_scene(scene)
+ payload = json.dumps(report, indent=2) + "\n"
+ if out is not None:
+ target = output_path(out, scene)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ acquire_run_dir_lock(target.parent, "scene-inspect")
+ try:
+ atomic_write_set({target: payload})
+ finally:
+ release_run_dir_lock(target.parent)
+ print(payload, end="")
+ return int(require_loop and not report["loop"]["pass"])
+ except (ValueError, OSError, KeyError, TypeError) as exc:
+ raise SystemExit(f"scene-inspect: {exc}") from exc
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ add_arguments(parser)
+ return run(**vars(parser.parse_args()))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/scene/model.py b/sprite_gen/scene/model.py
new file mode 100644
index 0000000..72fa64e
--- /dev/null
+++ b/sprite_gen/scene/model.py
@@ -0,0 +1,201 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Scene layout and time belong here; source frames belong to asset metadata."""
+from __future__ import annotations
+
+from dataclasses import dataclass
+import hashlib
+import json
+from pathlib import Path
+
+from sprite_gen.spec.assets import FrameSequence, finite, load_asset, same_identity
+
+
+def fields(data, allowed, where):
+ if not isinstance(data, dict):
+ raise ValueError(f"{where} must be an object")
+ extra = set(data) - set(allowed)
+ if extra:
+ raise ValueError(f"unknown {where} fields: {', '.join(sorted(extra))}")
+
+
+def pair(value, where):
+ if not isinstance(value, (list, tuple)) or len(value) != 2:
+ raise ValueError(f"{where} must be [x, y]")
+ return tuple(finite(v, where) for v in value)
+
+
+def boolean(value, where):
+ if not isinstance(value, bool):
+ raise ValueError(f"{where} must be boolean")
+ return value
+
+
+def read_json(path: Path) -> tuple[object, str]:
+ """Parse a JSON file from one read and return the document with the SHA-256 of those bytes."""
+ data = Path(path).read_bytes()
+ return json.loads(data.decode("utf-8")), hashlib.sha256(data).hexdigest()
+
+
+@dataclass
+class Layer:
+ id: str
+ asset: str
+ sequence: FrameSequence
+ at: tuple
+ velocity: tuple
+ scale: float
+ # Integer pixel size the frames are actually rasterised at. Its ratio to the
+ # source size, not the requested `scale`, is the scale motion is applied with.
+ raster_size: tuple
+ opacity: float
+ z: float
+ parallax: float
+ repeat_x: bool
+ period: float
+ shadow: bool
+ playback_rate: float
+ loop: bool
+ offset: float
+ plane: str | None
+
+
+@dataclass
+class Scene:
+ path: Path
+ spec: dict
+ width: int
+ height: int
+ fps: float
+ duration: float
+ background: tuple
+ camera_at: tuple
+ camera_velocity: tuple
+ light: dict
+ layers: list[Layer]
+ assets: dict[str, FrameSequence]
+ source_fingerprints: dict
+
+ @property
+ def frame_count(self):
+ return round(self.fps * self.duration)
+
+
+def bound_stride(measurement, sequence: FrameSequence) -> float:
+ """Return the verified stride of ``measurement`` if it measured exactly ``sequence``.
+
+ The report must be verified, hash the same bytes the sequence was decoded
+ from, and name the same selection: source, atlas state, frame-rate override,
+ frame count, size, anchor and per-frame durations. A walk report cannot
+ drive the idle state of the same atlas, and a report taken at another frame
+ rate cannot drive the sequence at its native timing.
+ """
+ if not isinstance(measurement, dict) or measurement.get("kind") != "sprite-gen-motion-report":
+ raise ValueError("stride report must be a sprite-gen-motion-report")
+ if measurement.get("stride_verified") is not True:
+ raise ValueError("stride measurement is unverified; provide reliable contact evidence")
+ if measurement.get("source_fingerprints") != sequence.fingerprints():
+ raise ValueError("stride measurement is stale or belongs to another asset")
+ if "sequence" not in measurement:
+ raise ValueError("stride report lacks its sequence identity; measure again with the current motion tool")
+ if not same_identity(measurement["sequence"], sequence):
+ raise ValueError("stride measurement belongs to another state, frame rate or anchor of this asset")
+ return finite(measurement.get("stride_px_per_second"), "measured stride", positive=True)
+
+
+def load_scene(path: Path) -> Scene:
+ path = Path(path).expanduser().resolve()
+ data, digest = read_json(path)
+ fields(data, {"kind", "version", "canvas", "fps", "duration", "camera", "light", "planes", "assets", "layers"}, "scene")
+ if data.get("kind") != "sprite-gen-scene" or data.get("version") != 1:
+ raise ValueError("scene requires kind sprite-gen-scene and version 1")
+ canvas = data.get("canvas", {})
+ fields(canvas, {"width", "height", "background"}, "canvas")
+ dims = [finite(canvas.get(k), f"canvas {k}", positive=True) for k in ("width", "height")]
+ if any(v != int(v) or v > 8192 for v in dims) or dims[0]*dims[1] > 16_777_216:
+ raise ValueError("scene canvas must use integer dimensions up to 8192 and 16 megapixels")
+ background = canvas.get("background", [0, 0, 0, 255])
+ if not isinstance(background, list) or len(background) not in (3, 4) or any(isinstance(v, bool) or not isinstance(v, int) or not 0 <= v <= 255 for v in background):
+ raise ValueError("canvas background must be RGB or RGBA bytes")
+ if len(background) == 3:
+ background = background + [255]
+ fps = finite(data.get("fps", 24), "fps", positive=True)
+ duration = finite(data.get("duration"), "duration", positive=True)
+ if fps > 120 or not 1 <= round(duration*fps) <= 10_000 or abs(duration*fps-round(duration*fps)) > 1e-6:
+ raise ValueError("duration * fps must be an integer from 1 to 10000; fps <= 120")
+ camera = data.get("camera", {})
+ fields(camera, {"at", "velocity"}, "camera")
+ camera_at = pair(camera.get("at", [0, 0]), "camera at")
+ camera_velocity = pair(camera.get("velocity", [0, 0]), "camera velocity")
+ light = data.get("light", {})
+ fields(light, {"squash", "shear", "opacity", "blur", "color"}, "light")
+ planes = data.get("planes", {})
+ if not isinstance(planes, dict):
+ raise ValueError("planes must be an object")
+ for name, plane in planes.items():
+ fields(plane, {"velocity"}, f"plane {name}")
+ pair(plane.get("velocity", [0, 0]), "plane velocity")
+ assets, fingerprints = {}, {str(path): digest}
+ if not isinstance(data.get("assets"), dict) or not data["assets"]:
+ raise ValueError("scene assets must be a nonempty object")
+ for name, reference in data["assets"].items():
+ if isinstance(reference, str):
+ reference = {"source": reference}
+ fields(reference, {"source", "state"}, f"asset {name}")
+ if not isinstance(reference.get("source"), str):
+ raise ValueError(f"asset {name} requires a source path")
+ asset = load_asset(path.parent / reference["source"], state=reference.get("state"))
+ assets[name] = asset
+ fingerprints.update(asset.fingerprints())
+ entries = data.get("layers")
+ if not isinstance(entries, list) or not entries:
+ raise ValueError("scene layers must be a nonempty list")
+ layers, names = [], set()
+ for entry in entries:
+ fields(entry, {"id", "asset", "at", "velocity", "scale", "opacity", "z", "parallax", "repeat_x", "period", "shadow", "playback_rate", "loop", "offset", "plane", "stride"}, "layer")
+ name = entry.get("id")
+ if not isinstance(name, str) or not name or not all(c.isalnum() or c in "-_" for c in name) or name in names:
+ raise ValueError("layer id must be unique and contain only letters, digits, dash or underscore")
+ names.add(name)
+ asset_name = entry.get("asset")
+ if asset_name not in assets:
+ raise ValueError(f"unknown asset for layer {name}: {asset_name}")
+ seq = assets[asset_name]
+ scale = finite(entry.get("scale", 1), "layer scale", positive=True)
+ raster_size = tuple(round(v*scale) for v in seq.size)
+ if min(raster_size) < 1 or max(raster_size) > 16384 or raster_size[0]*raster_size[1] > 16_777_216:
+ raise ValueError("scaled layer dimensions must be between 1 and 16384 and at most 16 megapixels")
+ opacity = finite(entry.get("opacity", 1), "layer opacity")
+ if not 0 <= opacity <= 1:
+ raise ValueError("layer opacity must be 0..1")
+ plane = entry.get("plane")
+ if plane is not None and plane not in planes:
+ raise ValueError(f"unknown plane: {plane}")
+ plane_v = pair(planes[plane].get("velocity", [0, 0]), "plane velocity") if plane is not None else (0, 0)
+ velocity = pair(entry.get("velocity", [0, 0]), "layer velocity")
+ rate = finite(entry.get("playback_rate", 1), "playback_rate", positive=True)
+ if "stride" in entry:
+ if "velocity" in entry:
+ raise ValueError("choose layer velocity or measured stride, not both")
+ stride = entry["stride"]
+ fields(stride, {"report", "direction"}, "stride")
+ if stride.get("direction") not in ("left", "right") or not isinstance(stride.get("report"), str):
+ raise ValueError("stride requires a report and explicit left/right direction")
+ rp = (path.parent / stride["report"]).resolve()
+ measurement, report_digest = read_json(rp)
+ speed = bound_stride(measurement, seq)
+ # Source px per source second, scaled to rendered px per scene second:
+ # the raster scale actually used for this layer times the playback rate.
+ raster_scale = raster_size[0] / seq.size[0]
+ velocity = (speed*raster_scale*rate*(-1 if stride["direction"] == "left" else 1), 0)
+ fingerprints[str(rp)] = report_digest
+ velocity = tuple(a+b for a, b in zip(plane_v, velocity))
+ period = finite(entry.get("period", seq.size[0]), "repeat period", positive=True)
+ if period > seq.size[0] or int(period) != period or round(period*scale) < 1:
+ raise ValueError("repeat period must be an integer within the source width")
+ layer = Layer(name, asset_name, seq, pair(entry.get("at", [0, 0]), "layer at"), velocity, scale, raster_size, opacity,
+ finite(entry.get("z", 0), "layer z"), finite(entry.get("parallax", 1), "parallax"),
+ boolean(entry.get("repeat_x", False), "repeat_x"), period, boolean(entry.get("shadow", False), "shadow"),
+ rate, boolean(entry.get("loop", seq.metadata.get("loop", True)), "loop"), finite(entry.get("offset", 0), "offset"), plane)
+ layers.append(layer)
+ return Scene(path, data, int(dims[0]), int(dims[1]), fps, duration, tuple(background), camera_at, camera_velocity,
+ light, sorted(layers, key=lambda layer: layer.z), assets, fingerprints)
diff --git a/sprite_gen/scene/render.py b/sprite_gen/scene/render.py
new file mode 100644
index 0000000..e80f27b
--- /dev/null
+++ b/sprite_gen/scene/render.py
@@ -0,0 +1,331 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Deterministic asset placement. No generation calls or sprite source writes.
+
+Every prerequisite (formats, codec constraints, GIF settings, ffmpeg, output
+directory) is checked before anything is created; frames and encodes are staged
+in a private temporary directory and published as one atomic set. A failure
+leaves no partial output behind and is never retried automatically.
+"""
+from __future__ import annotations
+
+import argparse
+import contextlib
+import hashlib
+from io import BytesIO
+import json
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+
+from PIL import Image
+
+from sprite_gen.scene.model import Scene, load_scene
+from sprite_gen.spec.assets import finite
+from sprite_gen.spec.runio import LOCK_FILENAME, acquire_run_dir_lock, atomic_write_set, release_run_dir_lock
+
+
+FORMATS = ("png", "mp4", "gif")
+# GIF defaults: the scene's own frame rate, a full 256-colour palette and no
+# downscale unless the canvas is wider than 640 px. Nothing is reduced silently.
+GIF_MAX_WIDTH_DEFAULT = 640
+GIF_COLORS_DEFAULT = 256
+GIF_DITHER_CHOICES = ("none", "bayer", "floyd_steinberg", "sierra2_4a")
+GIF_DITHER_DEFAULT = "none"
+GIF_MAX_BYTES_DEFAULT = 8_000_000
+
+
+def png_bytes(image):
+ out = BytesIO()
+ image.save(out, format="PNG")
+ return out.getvalue()
+
+
+def composite(target, source, x, y):
+ x, y = round(x), round(y)
+ left, top = max(0, x), max(0, y)
+ right, bottom = min(target.width, x+source.width), min(target.height, y+source.height)
+ if left < right and top < bottom:
+ target.alpha_composite(source.crop((left-x, top-y, right-x, bottom-y)), (left, top))
+
+
+class Renderer:
+ def __init__(self, scene: Scene):
+ self.scene = scene
+ self.prepared = {}
+ # Import only when scene/shadow is used; ordinary sprite commands need no scene setup.
+ from sprite_gen.effects.shadow import project_shadow
+ for layer in scene.layers:
+ seq = layer.sequence
+ size = tuple(layer.raster_size)
+ anchor = tuple(a*new/old for a, new, old in zip(seq.anchor, size, seq.size))
+ frames = {}
+ for source in seq.frames:
+ image = source.resize(size, Image.Resampling.LANCZOS)
+ if layer.repeat_x:
+ image = image.crop((0, 0, round(layer.period*layer.scale), size[1]))
+ if layer.opacity != 1:
+ image.putalpha(image.getchannel("A").point(lambda a: round(a*layer.opacity)))
+ shadow = project_shadow(image, anchor, **scene.light) if layer.shadow else None
+ frames[id(source)] = (image, anchor, shadow, image.getchannel("A").getbbox())
+ self.prepared[layer.id] = frames
+
+ def frame(self, time: float, *, only=None, geometry=False):
+ """Composite the scene at ``time``; with ``geometry`` also return every placement.
+
+ Placements carry the unclipped bounding box of each placed copy in canvas
+ coordinates (``None`` for a fully transparent source frame) and whether
+ any of it lies inside the viewport, so a layer that is entirely off
+ screen is reported rather than silently dropped.
+ """
+ scene = self.scene
+ frame = Image.new("RGBA", (scene.width, scene.height), (0, 0, 0, 0) if only else scene.background)
+ placements = []
+ for layer in scene.layers:
+ if only and layer.id != only:
+ continue
+ source = layer.sequence.frame_at(time*layer.playback_rate+layer.offset, loop=layer.loop)
+ image, anchor, shadow, bbox = self.prepared[layer.id][id(source)]
+ point = [layer.at[i] + layer.velocity[i]*time - (scene.camera_at[i]+scene.camera_velocity[i]*time)*layer.parallax for i in range(2)]
+ left, top = point[0]-anchor[0], point[1]-anchor[1]
+ offsets = [0]
+ if layer.repeat_x:
+ period = image.width
+ left %= period
+ offsets = range(-period, scene.width+period, period)
+ for dx in offsets:
+ if shadow:
+ sh, sh_anchor = shadow
+ composite(frame, sh, left+dx+anchor[0]-sh_anchor[0], top+anchor[1]-sh_anchor[1])
+ composite(frame, image, left+dx, top)
+ if geometry:
+ entry = {"id": layer.id, "repeat_x": layer.repeat_x, "bbox": None, "visible": False}
+ if bbox:
+ box = [left+dx+bbox[0], top+bbox[1], left+dx+bbox[2], top+bbox[3]]
+ entry["bbox"] = box
+ entry["visible"] = box[2] > 0 and box[0] < scene.width and box[3] > 0 and box[1] < scene.height
+ placements.append(entry)
+ return (frame, placements) if geometry else frame
+
+
+def _ffmpeg_binary():
+ binary = shutil.which("ffmpeg")
+ if not binary:
+ raise ValueError("ffmpeg is required for scene video export")
+ return binary
+
+
+def _ffmpeg(args):
+ process = subprocess.run([_ffmpeg_binary(), "-hide_banner", "-loglevel", "error", "-y", *args], capture_output=True, text=True)
+ if process.returncode:
+ raise ValueError(f"ffmpeg failed: {process.stderr[-3000:]}")
+
+
+def _bounded_integer(value, name, low, high):
+ number = finite(value, name)
+ if number != int(number) or not low <= number <= high:
+ raise ValueError(f"{name} must be an integer from {low} to {high}")
+ return int(number)
+
+
+def parse_formats(formats):
+ chosen = {f.strip() for f in formats.split(",")} if isinstance(formats, str) else set(formats)
+ if not chosen or chosen - set(FORMATS):
+ raise ValueError("formats must be a comma-separated selection of png,mp4,gif")
+ return chosen
+
+
+def gif_settings(scene: Scene, *, gif_width=None, gif_fps=None, gif_colors=GIF_COLORS_DEFAULT,
+ gif_dither=GIF_DITHER_DEFAULT, gif_max_bytes=GIF_MAX_BYTES_DEFAULT):
+ """Validate the explicit GIF choices. Every value is used as given; none is lowered later."""
+ if scene.background[3] != 255:
+ raise ValueError("scene GIF preview needs opaque background; export transparent layers as PNG")
+ width = min(GIF_MAX_WIDTH_DEFAULT, scene.width) if gif_width is None else _bounded_integer(gif_width, "gif_width", 1, scene.width)
+ fps = scene.fps if gif_fps is None else finite(gif_fps, "gif_fps", positive=True)
+ if fps > scene.fps:
+ raise ValueError("gif_fps cannot exceed the scene fps; frames are never invented")
+ colors = _bounded_integer(gif_colors, "gif_colors", 2, 256)
+ if gif_dither not in GIF_DITHER_CHOICES:
+ raise ValueError(f"gif_dither must be one of {', '.join(GIF_DITHER_CHOICES)}")
+ max_bytes = None if gif_max_bytes is None else int(finite(gif_max_bytes, "gif_max_bytes", positive=True))
+ return {"width": width, "fps": fps, "colors": colors, "dither": gif_dither, "max_bytes": max_bytes}
+
+
+def encoding_settings(scene: Scene, formats: set, **gif) -> dict:
+ """Everything the encoders need, checked before any output path exists."""
+ settings = {}
+ if "mp4" in formats:
+ if scene.width % 2 or scene.height % 2 or scene.background[3] != 255:
+ raise ValueError("MP4 requires even canvas dimensions and an opaque background")
+ settings["mp4"] = {"codec": "libx264", "crf": 18, "preset": "fast", "pix_fmt": "yuv420p"}
+ if "gif" in formats:
+ settings["gif"] = gif_settings(scene, **gif)
+ if settings:
+ settings["ffmpeg"] = _ffmpeg_binary()
+ return settings
+
+
+def encode_frames(work: Path, scene: Scene, formats: set, settings: dict):
+ """Encode staged frames once each, before publishing anything. No automatic retries."""
+ outputs, report = {}, {}
+ pattern = str(work / "frame-%05d.png")
+ if "mp4" in formats:
+ mp4 = settings["mp4"]
+ dest = work / "scene.mp4"
+ _ffmpeg(["-framerate", str(scene.fps), "-i", pattern, "-frames:v", str(scene.frame_count), "-c:v", mp4["codec"],
+ "-preset", mp4["preset"], "-crf", str(mp4["crf"]), "-pix_fmt", mp4["pix_fmt"], "-movflags", "+faststart", "-an", str(dest)])
+ outputs["scene.mp4"] = dest.read_bytes()
+ report["mp4"] = {**mp4, "fps": scene.fps, "bytes": len(outputs["scene.mp4"])}
+ if "gif" in formats:
+ gif = settings["gif"]
+ filters = []
+ if gif["fps"] != scene.fps:
+ filters.append(f"fps={gif['fps']}")
+ if gif["width"] != scene.width:
+ filters.append(f"scale={gif['width']}:-1:flags=lanczos")
+ chain = ",".join(filters)
+ pal, dest = work / "palette.png", work / "scene.gif"
+ # The background is opaque, so the whole palette is spent on colours.
+ palettegen = f"palettegen=max_colors={gif['colors']}:reserve_transparent=0"
+ paletteuse = f"paletteuse=dither={gif['dither']}"
+ _ffmpeg(["-framerate", str(scene.fps), "-i", pattern, "-vf", f"{chain},{palettegen}" if chain else palettegen, "-frames:v", "1", str(pal)])
+ _ffmpeg(["-framerate", str(scene.fps), "-i", pattern, "-i", str(pal), "-lavfi",
+ f"{chain}[x];[x][1:v]{paletteuse}" if chain else f"[0:v][1:v]{paletteuse}", "-loop", "0", str(dest)])
+ data = dest.read_bytes()
+ with Image.open(dest) as encoded:
+ frames, size = getattr(encoded, "n_frames", 1), encoded.size
+ report["gif"] = {"width": size[0], "height": size[1], "fps": gif["fps"], "colors": gif["colors"], "dither": gif["dither"],
+ "frames": frames, "bytes": len(data), "max_bytes": gif["max_bytes"]}
+ if gif["max_bytes"] is not None and len(data) > gif["max_bytes"]:
+ raise ValueError(f"scene.gif is {len(data)} bytes, over the {gif['max_bytes']} byte budget; "
+ "lower gif_width, gif_fps or gif_colors, or raise gif_max_bytes (quality is never reduced automatically)")
+ outputs["scene.gif"] = data
+ return outputs, report
+
+
+def _validate_output(output: Path, scene: Scene):
+ # A scene output directory is dedicated; never overwrite source assets or scene specs.
+ if any(p == output or output in p.parents for p in map(Path, scene.source_fingerprints)):
+ raise ValueError("output directory contains scene inputs; choose a separate output directory")
+ if output.exists() and not output.is_dir():
+ raise ValueError("scene output must be a directory")
+ if output.exists() and any(p.name != LOCK_FILENAME for p in output.iterdir()):
+ raise ValueError("scene output directory must be empty; choose a new render directory")
+
+
+def render_scene(spec, out_dir, *, formats="mp4,gif", gif_max_bytes=GIF_MAX_BYTES_DEFAULT, gif_width=None, gif_fps=None,
+ gif_colors=GIF_COLORS_DEFAULT, gif_dither=GIF_DITHER_DEFAULT, export_layers=False):
+ scene = load_scene(spec)
+ formats = parse_formats(formats)
+ renderer = Renderer(scene)
+ settings = encoding_settings(scene, formats, gif_width=gif_width, gif_fps=gif_fps, gif_colors=gif_colors,
+ gif_dither=gif_dither, gif_max_bytes=gif_max_bytes)
+ output = Path(out_dir).expanduser().resolve()
+ _validate_output(output, scene)
+ created = not output.exists()
+ output.mkdir(parents=True, exist_ok=True)
+ try:
+ acquire_run_dir_lock(output, "scene-render")
+ if any(p.name != LOCK_FILENAME for p in output.iterdir()):
+ raise ValueError("scene output directory became nonempty before the writer lock")
+ return _render_locked(scene, renderer, output, formats, settings, export_layers)
+ except BaseException:
+ release_run_dir_lock(output)
+ if created:
+ # Only the directory this call created, and only while it is still empty:
+ # a partially published set stays in place and is reported as a failure.
+ with contextlib.suppress(OSError):
+ output.rmdir()
+ raise
+ finally:
+ release_run_dir_lock(output)
+
+
+def _render_locked(scene, renderer, output, formats, settings, export_layers):
+ from sprite_gen.scene.inspect_scene import inspect_scene
+ with tempfile.TemporaryDirectory(prefix="sprite-gen-scene-") as tmp:
+ work = Path(tmp)
+ check = inspect_scene(scene, renderer=renderer, frame_dir=work)
+ payloads = {}
+ for index in sorted(set([0, scene.frame_count//3, 2*scene.frame_count//3, scene.frame_count-1])):
+ payloads[output / f"check-{index:05d}.png"] = (work / f"frame-{index:05d}.png").read_bytes()
+ if "png" in formats:
+ for p in sorted(work.glob("frame-*.png")):
+ payloads[output / "frames" / p.name] = p.read_bytes()
+ encoded, encoding = encode_frames(work, scene, formats, settings)
+ payloads.update({output / name: data for name, data in encoded.items()})
+ if export_layers:
+ # Frame-zero layer plates plus original references and motion in placement.json.
+ # Moving sprites are kept as source references; PNG plates alone are not animation export.
+ for layer in scene.layers:
+ payloads[output / "layers" / f"{layer.id}.png"] = png_bytes(renderer.frame(0, only=layer.id))
+ placement = {"kind": "sprite-gen-scene-placement", "version": 1, "source_spec": str(scene.path),
+ "source_fingerprints": scene.source_fingerprints, "canvas": [scene.width, scene.height],
+ "fps": scene.fps, "duration": scene.duration, "camera": scene.spec.get("camera", {}), "light": scene.light,
+ "assets": {k: {"source": a.metadata["source"], "state": a.metadata.get("state")} for k, a in scene.assets.items()},
+ "layers": [{"id": l.id, "asset": l.asset, "at": l.at, "velocity": l.velocity, "scale": l.scale,
+ "raster_size": list(l.raster_size), "opacity": l.opacity, "z": l.z, "parallax": l.parallax,
+ "repeat_x": l.repeat_x, "period": l.period, "shadow": l.shadow, "playback_rate": l.playback_rate,
+ "loop": l.loop, "offset": l.offset, "plane": l.plane} for l in scene.layers],
+ "layer_plate_time": 0 if export_layers else None, "portable": False,
+ "note": "Placement metadata references source files; copy referenced assets when moving this output."}
+ report = {"kind": "sprite-gen-scene-render", "version": 1, "source_spec": str(scene.path),
+ "source_fingerprints": scene.source_fingerprints, "frames": scene.frame_count,
+ "files": [str(p.relative_to(output)) for p in payloads] + ["placement.json", "scene.report.json"],
+ "encoding": encoding, "inspection": check}
+ payloads[output / "placement.json"] = json.dumps(placement, indent=2)+"\n"
+ payloads[output / "scene.report.json"] = json.dumps(report, indent=2)+"\n"
+ # The fingerprints are the bytes that were decoded; an input replaced since
+ # then is detected here, before any success report is published.
+ if any(hashlib.sha256(Path(p).read_bytes()).hexdigest() != digest for p, digest in scene.source_fingerprints.items()):
+ raise ValueError("scene inputs changed during render; output not published")
+ # The output directory was verified empty under the lock; its subdirectories
+ # are created only now, after every encode succeeded, and removed again
+ # if they are still empty when publication fails.
+ directories = sorted({p.parent for p in payloads} - {output})
+ created = []
+ try:
+ for directory in directories:
+ directory.mkdir()
+ created.append(directory)
+ atomic_write_set(payloads)
+ except BaseException:
+ for directory in reversed(created):
+ with contextlib.suppress(OSError):
+ directory.rmdir()
+ raise
+ return report
+
+
+def add_arguments(parser):
+ parser.add_argument("--spec", type=Path, required=True)
+ parser.add_argument("--out-dir", type=Path, required=True)
+ parser.add_argument("--formats", default="mp4,gif", help="comma-separated selection of png,mp4,gif")
+ parser.add_argument("--gif-max-bytes", type=int, default=GIF_MAX_BYTES_DEFAULT,
+ help="fail (do not degrade) when the GIF is larger than this many bytes")
+ parser.add_argument("--gif-width", type=int, help="GIF width in pixels; default min(640, canvas width), never wider than the canvas")
+ parser.add_argument("--gif-fps", type=float, help="GIF frame rate; default the scene fps, never higher")
+ parser.add_argument("--gif-colors", type=int, default=GIF_COLORS_DEFAULT, help="palette size 2..256; default 256")
+ parser.add_argument("--gif-dither", choices=GIF_DITHER_CHOICES, default=GIF_DITHER_DEFAULT,
+ help="paletteuse dithering; default none keeps flat pixel-art colours exact")
+ parser.add_argument("--export-layers", action="store_true")
+
+
+def run(**kwargs):
+ try:
+ report = render_scene(**kwargs)
+ except (ValueError, OSError, KeyError, TypeError) as exc:
+ raise SystemExit(f"scene-render: {exc}") from exc
+ print(json.dumps({"frames": report["frames"], "files": report["files"], "encoding": report["encoding"],
+ "inspection_status": report["inspection"]["status"]}, indent=2))
+ return 0
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ add_arguments(parser)
+ return run(**vars(parser.parse_args()))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/spec/assets.py b/sprite_gen/spec/assets.py
new file mode 100644
index 0000000..4386976
--- /dev/null
+++ b/sprite_gen/spec/assets.py
@@ -0,0 +1,285 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Read-only adapters for external frames, loop strips and runtime atlases.
+
+The returned sequence is an in-memory snapshot, never another editable asset store.
+Durations are seconds; the anchor is in source pixels, defaulting to bottom centre.
+
+Every source file is read from disk exactly once. Frames are decoded and
+descriptors parsed from those bytes, and ``fingerprints()`` hashes the very same
+bytes, so a file replaced on disk after loading can neither change the frames of
+an existing sequence nor make its fingerprints agree with the new file.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import hashlib
+from io import BytesIO
+import json
+import math
+from pathlib import Path
+
+from PIL import Image
+
+
+def finite(value, name: str, *, positive=False) -> float:
+ if isinstance(value, bool):
+ raise ValueError(f"{name} must be a finite number")
+ try:
+ result = float(value)
+ except (ValueError, TypeError, OverflowError) as exc:
+ raise ValueError(f"{name} must be a finite number") from exc
+ if not math.isfinite(result) or (positive and result <= 0):
+ raise ValueError(f"{name} must be {'positive and ' if positive else ''}finite")
+ return result
+
+
+def sequence_identity(sequence) -> dict:
+ """The facts a measurement of ``sequence`` is bound to.
+
+ A consumer that applies a report (for example a scene stride) must find the
+ same source, atlas state, frame-rate override, frame count, canvas size,
+ anchor and per-frame durations in the sequence it selected, in addition to
+ matching ``fingerprints()``. Two states of one atlas share files and hashes
+ but not this identity; so do one sequence loaded at two frame rates.
+ """
+ metadata = getattr(sequence, "metadata", None) or {}
+ size = sequence.frames[0].size
+ return {
+ "source": metadata.get("source"),
+ "state": metadata.get("state"),
+ "fps_override": metadata.get("fps_override"),
+ "frame_count": len(sequence.frames),
+ "size": [int(size[0]), int(size[1])],
+ "anchor_px": [float(v) for v in sequence.anchor],
+ "durations_seconds": [float(v) for v in sequence.durations],
+ }
+
+
+def same_identity(reported, sequence) -> bool:
+ """True when ``reported`` (a JSON round trip of ``sequence_identity``) names ``sequence``.
+
+ The effective per-frame durations are compared, not how they were specified:
+ a frame-rate override that reproduces the native timing measured the same
+ motion. ``fps_override`` stays in the record for readers.
+ """
+ if not isinstance(reported, dict):
+ return False
+ expected = sequence_identity(sequence)
+ if set(reported) != set(expected):
+ return False
+ for key in ("source", "state", "frame_count", "size"):
+ if reported[key] != expected[key]:
+ return False
+ for key in ("anchor_px", "durations_seconds"):
+ a, b = reported[key], expected[key]
+ if not isinstance(a, list) or len(a) != len(b) or not all(_close(x, y) for x, y in zip(a, b)):
+ return False
+ return True
+
+
+def _close(a, b) -> bool:
+ try:
+ return math.isclose(float(a), float(b), rel_tol=1e-9, abs_tol=1e-12)
+ except (TypeError, ValueError):
+ return False
+
+
+@dataclass(frozen=True)
+class FrameSequence:
+ """An in-memory frame sequence: ``frames, durations, anchor, source_files, metadata``.
+
+ ``anchor`` defaults to the bottom centre of the frame canvas. A sequence
+ built from files also carries, keyword-only, the SHA-256 of the bytes each
+ source file contributed (``source_digests``, one per ``source_files`` entry);
+ a manually constructed sequence that names source files without those
+ digests is refused, so nothing unverifiable can pose as file-backed.
+ """
+ frames: tuple[Image.Image, ...]
+ durations: tuple[float, ...]
+ anchor: tuple[float, float] | None = None
+ source_files: tuple[Path, ...] = ()
+ metadata: dict = field(default_factory=dict)
+ source_digests: tuple[str, ...] = field(default=(), kw_only=True)
+
+ def __post_init__(self):
+ if not self.frames or len(self.frames) != len(self.durations):
+ raise ValueError("asset needs one positive duration per frame")
+ if any(f.size != self.frames[0].size for f in self.frames):
+ raise ValueError("asset frames must share a canvas size")
+ for d in self.durations:
+ finite(d, "frame duration", positive=True)
+ if self.anchor is None:
+ object.__setattr__(self, "anchor", (self.frames[0].width / 2, self.frames[0].height))
+ if not isinstance(self.anchor, (tuple, list)) or len(self.anchor) != 2:
+ raise ValueError("asset anchor needs [x, y]")
+ object.__setattr__(self, "anchor", tuple(finite(v, "anchor") for v in self.anchor))
+ if len(self.source_files) != len(self.source_digests):
+ raise ValueError("each source file needs the SHA-256 of the bytes decoded from it")
+
+ @property
+ def size(self):
+ return self.frames[0].size
+
+ @property
+ def duration(self):
+ return sum(self.durations)
+
+ def frame_at(self, t: float, loop=True):
+ t = finite(t, "frame time")
+ if loop:
+ t %= self.duration
+ elif t >= self.duration:
+ return self.frames[-1]
+ t = max(0, t)
+ end = 0.0
+ for frame, duration in zip(self.frames, self.durations):
+ end += duration
+ if t < end - 1e-10:
+ return frame
+ return self.frames[-1]
+
+ def fingerprints(self):
+ """SHA-256 of the exact bytes this sequence was decoded from, keyed by resolved path.
+
+ The digests were taken from the bytes read at load time, never from a
+ later read of the files, so they describe these frames and nothing else.
+ """
+ return {str(path): digest for path, digest in zip(self.source_files, self.source_digests)}
+
+ def identity(self) -> dict:
+ return sequence_identity(self)
+
+
+def _read_bytes(path: Path) -> bytes:
+ """The single place a source file is read; every decode and hash uses its result."""
+ return Path(path).read_bytes()
+
+
+# One decoded source image (a frame, a loop strip or an atlas sheet) may hold at
+# most this many pixels: 256 MB of RGBA, below Pillow's decompression-bomb
+# warning, so a hostile header is refused before any pixel data is decoded.
+MAX_SOURCE_PIXELS = 67_108_864
+
+
+def _decode_image(data: bytes) -> Image.Image:
+ with Image.open(BytesIO(data)) as image:
+ if getattr(image, "n_frames", 1) != 1:
+ raise ValueError("animated image input requires an explicit frame descriptor")
+ width, height = image.size
+ if width < 1 or height < 1 or width * height > MAX_SOURCE_PIXELS:
+ raise ValueError(f"source image {width}x{height} exceeds the supported {MAX_SOURCE_PIXELS} pixels")
+ return image.convert("RGBA")
+
+
+class _Snapshot:
+ """Bytes of every file touched by one load, each read once, with their digests."""
+
+ def __init__(self):
+ self.digests: dict[Path, str] = {}
+ self._bytes: dict[Path, bytes] = {}
+
+ def read(self, path: Path) -> bytes:
+ if path not in self._bytes:
+ data = _read_bytes(path)
+ self._bytes[path] = data
+ self.digests[path] = hashlib.sha256(data).hexdigest()
+ return self._bytes[path]
+
+ def image(self, path: Path) -> Image.Image:
+ return _decode_image(self.read(path))
+
+ def json(self, path: Path):
+ return json.loads(self.read(path).decode("utf-8"))
+
+
+def _choose(rows, state):
+ if not isinstance(rows, dict) or not rows:
+ raise ValueError("asset has no animation states")
+ if state is None:
+ if len(rows) != 1:
+ raise ValueError("--state is required for a multi-state atlas")
+ state = next(iter(rows))
+ if state not in rows:
+ raise ValueError(f"unknown asset state: {state}")
+ return state
+
+
+def _integer(value, name):
+ number = finite(value, name, positive=True)
+ if number != int(number):
+ raise ValueError(f"{name} must be an integer")
+ return int(number)
+
+
+def load_asset(source: Path, *, state=None, fps=None, anchor=None) -> FrameSequence:
+ source = Path(source).expanduser().resolve()
+ snapshot = _Snapshot()
+ meta = {"source": str(source)}
+ declared_anchor = None
+ if source.suffix.lower() != ".json":
+ if state is not None:
+ raise ValueError("--state is only valid for atlas input")
+ frames = [snapshot.image(source)]
+ durations = [1.0]
+ else:
+ data = snapshot.json(source)
+ if not isinstance(data, dict):
+ raise ValueError("asset descriptor must be an object")
+ declared_anchor = data.get("anchor")
+ if data.get("kind") == "sprite-gen-asset":
+ if data.get("version") != 1 or state is not None:
+ raise ValueError("external asset requires version 1 and no --state")
+ entries = data.get("frames")
+ if not isinstance(entries, list) or not entries:
+ raise ValueError("asset frames must be a nonempty ordered list")
+ frames, durations = [], []
+ for entry in entries:
+ if not isinstance(entry, dict) or not isinstance(entry.get("file"), str):
+ raise ValueError("each asset frame requires file and duration")
+ frames.append(snapshot.image((source.parent / entry["file"]).resolve()))
+ durations.append(finite(entry.get("duration"), "frame duration", positive=True))
+ elif "frame_layout" in data:
+ layout = data["frame_layout"]
+ state = _choose(layout.get("rows"), state)
+ sheet = snapshot.image((source.parent / data["sprite_sheet_alpha"]).resolve())
+ frames = []
+ for rect in layout["rows"][state]:
+ x, y = finite(rect["x"], "rect x"), finite(rect["y"], "rect y")
+ w, h = _integer(rect["w"], "rect width"), _integer(rect["h"], "rect height")
+ if int(x) != x or int(y) != y or min(x, y) < 0 or x+w > sheet.width or y+h > sheet.height:
+ raise ValueError("atlas frame rectangle outside sheet")
+ frames.append(sheet.crop((int(x), int(y), int(x)+w, int(y)+h)))
+ anim = data["animation"]["rows"][state]
+ if "durations_ms" in anim:
+ durations = [finite(v, "duration_ms", positive=True) / 1000 for v in anim["durations_ms"]]
+ else:
+ durations = [1 / finite(anim.get("fps"), "atlas fps", positive=True)] * len(frames)
+ meta.update(state=state, loop=bool(anim.get("loop", True)))
+ elif all(k in data for k in ("frames", "w", "h", "delay_ms")):
+ if state is not None:
+ raise ValueError("--state is only valid for atlas input")
+ sheet = snapshot.image(source.with_suffix(".png"))
+ n, w, h = (_integer(data[k], k) for k in ("frames", "w", "h"))
+ if sheet.size != (n * w, h):
+ raise ValueError("loop strip size disagrees with its sidecar")
+ frames = [sheet.crop((i*w, 0, (i+1)*w, h)) for i in range(n)]
+ durations = [finite(data["delay_ms"], "delay_ms", positive=True)/1000] * n
+ meta["loop"] = True
+ else:
+ raise ValueError("unsupported asset descriptor; use sprite-gen-asset, loop strip sidecar or atlas manifest")
+ if not frames:
+ raise ValueError("asset requires at least one frame")
+ if fps is not None:
+ durations = [1 / finite(fps, "fps", positive=True)] * len(frames)
+ meta["fps_override"] = float(fps)
+ point = anchor if anchor is not None else declared_anchor
+ if point is None:
+ point = (frames[0].width / 2, frames[0].height)
+ meta["anchor_source"] = "bottom-center default"
+ else:
+ if not isinstance(point, (tuple, list)) or len(point) != 2:
+ raise ValueError("anchor must be [x, y]")
+ point = tuple(finite(v, "anchor") for v in point)
+ meta["anchor_source"] = "explicit override" if anchor is not None else "asset metadata"
+ return FrameSequence(tuple(frames), tuple(durations), tuple(point), tuple(snapshot.digests), meta,
+ source_digests=tuple(snapshot.digests.values()))
diff --git a/tests/background/test_tile.py b/tests/background/test_tile.py
new file mode 100644
index 0000000..9d4b03d
--- /dev/null
+++ b/tests/background/test_tile.py
@@ -0,0 +1,158 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Synthetic pixel oracles for periodic cropping and RGBA quilting."""
+
+import json
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from sprite_gen.background.tile import inspect_tile, make_tile
+
+
+def pattern(period=16, height=13, repeats=4):
+ y, x = np.indices((height, period))
+ angle = 2 * np.pi * x / period
+ pixels = np.stack((90 + 60 * np.sin(angle) + y,
+ 120 + 40 * np.cos(angle) + y * 2,
+ 80 + 30 * np.sin(angle + y / 3),
+ np.full_like(x, 255)), axis=-1).astype(np.uint8)
+ return Image.fromarray(np.tile(pixels, (1, repeats, 1)))
+
+
+def test_periodic_pattern_keeps_exact_detail_and_does_not_mutate_input():
+ source = pattern()
+ before = source.tobytes()
+ tile, report = make_tile(source, 16, overlap=5)
+ left, top, right, bottom = report["source_crop"]
+ assert (right - left, bottom - top) == (21, 13)
+ assert tile.size == (16, 13)
+ assert tile.mode == "RGBA"
+ assert tile.tobytes() == source.crop((left, top, left + 16, bottom)).tobytes()
+ assert source.tobytes() == before
+ assert report["status"] == "pass"
+ assert report["requires_visual_review"] is True
+ assert report["search"]["evaluated_candidates"] <= report["search"]["candidate_limit"]
+ json.dumps(report, allow_nan=False)
+
+
+def test_minimum_error_seam_follows_a_connected_curved_match():
+ pixels = np.full((7, 15, 4), (20, 40, 60, 255), dtype=np.uint8)
+ pixels[:, 10:, :3] = 200
+ expected = [0, 1, 2, 3, 2, 1, 0]
+ for row, col in enumerate(expected):
+ pixels[row, 10 + col, :3] = (20, 40, 60)
+ _, report = make_tile(Image.fromarray(pixels), 10, overlap=5)
+ assert report["quilt_seam"]["positions"] == expected
+ assert report["quilt_seam"]["mean_squared_error"] == 0
+
+
+def test_bounded_search_includes_last_available_crop():
+ pixels = np.random.default_rng(12).integers(0, 256, (11, 100, 4), dtype=np.uint8)
+ pixels[..., 3] = 255
+ pixels[:, 96:100] = pixels[:, 84:88]
+ _, report = make_tile(Image.fromarray(pixels), 12, overlap=4)
+ assert report["source_crop"] == [84, 0, 100, 11]
+ assert report["search"]["evaluated_candidates"] <= 32
+ assert report["quilt_seam"]["mean_squared_error"] == 0
+
+
[email protected]("overlap", [1, 2, 4, 7])
+def test_alpha_silhouettes_copy_whole_pixels_and_select_tail_at_zero(overlap):
+ period = 8
+ y, x = np.indices((9, period + overlap))
+ alpha = np.where(y > (x * 3) % 7, 255, np.where(y == (x * 3) % 7, 97, 0))
+ pixels = np.stack((x * 11, y * 21, (x + y) * 7, alpha), axis=-1).astype(np.uint8)
+ source = Image.fromarray(pixels)
+ tiled, report = make_tile(source, period, overlap=overlap)
+ result = np.asarray(tiled)
+ assert np.array_equal(result[:, 0], pixels[:, period])
+ assert np.array_equal(result[:, overlap:], pixels[:, overlap:period])
+ seam = np.asarray(report["quilt_seam"]["positions"])
+ assert np.all(np.abs(np.diff(seam)) <= 1)
+ for row, cut in enumerate(seam):
+ assert np.array_equal(result[row, :cut + 1], pixels[row, period:period + cut + 1])
+ assert np.array_equal(result[row, cut + 1:], pixels[row, cut + 1:period])
+ if overlap > 1:
+ assert np.array_equal(result[:, overlap - 1], pixels[:, overlap - 1])
+ assert set(np.unique(result[..., 3])) <= {0, 97, 255}
+ assert source.tobytes() == pixels.tobytes()
+
+
+def test_y_axis_is_transposed_x_quilting_with_real_crop_coordinates():
+ source = pattern(period=9, height=7, repeats=3)
+ x_tile, x_report = make_tile(source, 9, overlap=3)
+ vertical = source.transpose(Image.Transpose.TRANSPOSE)
+ y_tile, y_report = make_tile(vertical, 9, axis="y", overlap=3)
+ assert y_tile.tobytes() == x_tile.transpose(Image.Transpose.TRANSPOSE).tobytes()
+ l, t, r, b = x_report["source_crop"]
+ assert y_report["source_crop"] == [t, l, b, r]
+ assert y_report["axis"] == "y"
+ assert y_report["edge_color_difference"] == x_report["edge_color_difference"]
+ assert inspect_tile(y_tile, "y")["edge_color_difference"] == x_report["edge_color_difference"]
+
+
[email protected]("period,overlap,axis", [
+ (0, 2, "x"), (1, 1, "x"), (5, 0, "x"), (5, -1, "x"),
+ (5, 5, "x"), (5, 6, "x"), (19, 2, "x"), (9, 2, "y"),
+ (5, 2, "z"), (5.5, 2, "x"), (True, 2, "x"), (5, 1.5, "x"),
+])
+def test_impossible_geometry_is_rejected(period, overlap, axis):
+ with pytest.raises((ValueError, TypeError)):
+ make_tile(Image.new("RGBA", (20, 10)), period, overlap=overlap, axis=axis)
+
+
+def test_smallest_quilt_and_single_scanline_are_supported():
+ source = Image.new("RGBA", (3, 1), (11, 22, 33, 97))
+ tiled, report = make_tile(source, 2, overlap=1)
+ assert tiled.size == (2, 1)
+ assert tiled.tobytes() == source.crop((0, 0, 2, 1)).tobytes()
+ assert report["quilt_seam"]["positions"] == [0]
+ json.dumps(report, allow_nan=False)
+
+
+def test_inspection_measures_real_color_edge_against_interior():
+ ramp = np.zeros((40, 64, 4), dtype=np.uint8)
+ ramp[..., :3] = np.arange(64, dtype=np.uint8)[None, :, None] * 3
+ ramp[..., 3] = 255
+ report = inspect_tile(Image.fromarray(ramp))
+ assert report["edge_color_difference"]["mean"] == pytest.approx(189)
+ assert report["interior_color_difference"]["mean"] == pytest.approx(3)
+ assert report["edge_to_interior_color_ratio"] == pytest.approx(63)
+ assert report["status"] == "needs-review"
+ assert report["review_reasons"]
+
+
+def test_inspection_ignores_invisible_rgb_but_detects_alpha_break():
+ pixels = np.zeros((20, 40, 4), dtype=np.uint8)
+ pixels[:, 0, :3] = 255
+ hidden = inspect_tile(Image.fromarray(pixels))
+ assert hidden["edge_color_difference"]["max"] == 0
+ assert hidden["seam_alpha_mismatch"]["max"] == 0
+ pixels[:, -1, 3] = 255
+ broken = inspect_tile(Image.fromarray(pixels))
+ assert broken["seam_alpha_mismatch"]["mean"] == 255
+ assert broken["status"] == "needs-review"
+ assert any("alpha" in reason for reason in broken["review_reasons"])
+
+
+def test_low_error_wrap_does_not_hide_bad_internal_quilt_cut():
+ pixels = np.zeros((20, 40, 4), dtype=np.uint8)
+ pixels[..., 3] = 255
+ pixels[..., :3] = np.arange(40, dtype=np.uint8)[None, :, None] * 6
+ tiled, report = make_tile(Image.fromarray(pixels), 32, overlap=8)
+ assert report["edge_color_difference"]["mean"] == pytest.approx(6)
+ assert report["quilt_seam"]["color_difference"]["mean"] > 150
+ assert report["status"] == "needs-review"
+ assert any("quilt" in reason for reason in report["review_reasons"])
+ assert inspect_tile(tiled)["edge_color_difference"] == report["edge_color_difference"]
+
+
+def test_inspection_handles_one_pixel_and_rejects_empty_or_bad_axis():
+ report = inspect_tile(Image.new("RGBA", (1, 1)))
+ assert report["status"] == "needs-review"
+ json.dumps(report, allow_nan=False)
+ for image, axis in [(Image.new("RGBA", (0, 3)), "x"),
+ (Image.new("RGBA", (2, 2)), "diagonal")]:
+ with pytest.raises(ValueError):
+ inspect_tile(image, axis)
diff --git a/tests/background/test_tile_cli.py b/tests/background/test_tile_cli.py
new file mode 100644
index 0000000..4e690f2
--- /dev/null
+++ b/tests/background/test_tile_cli.py
@@ -0,0 +1,194 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The standalone entrypoint publishes external PNGs through canonical run IO."""
+
+import argparse
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+from PIL import Image
+
+from sprite_gen.background import tile
+from sprite_gen.spec import runio
+
+
+def invoke(source, out, *extra):
+ return subprocess.run(
+ [sys.executable, "-m", "sprite_gen.background.tile", "--source", str(source),
+ "--out", str(out), "--period", "8", "--overlap", "3", *map(str, extra)],
+ capture_output=True, text=True, timeout=20,
+ )
+
+
+def source(tmp_path):
+ path = tmp_path / "external.png"
+ Image.new("RGBA", (24, 13), (32, 71, 117, 97)).save(path)
+ return path
+
+
+def test_module_publishes_png_and_report_without_sprite_run(source, tmp_path):
+ before = source.read_bytes()
+ out, report = tmp_path / "output" / "tile.png", tmp_path / "reports" / "tile.json"
+ proc = invoke(source, out, "--report", report)
+ assert proc.returncode == 0, proc.stderr
+ assert "pass" in proc.stdout
+ with Image.open(out) as image:
+ assert image.format == "PNG"
+ assert image.mode == "RGBA"
+ assert image.size == (8, 13)
+ assert image.getpixel((0, 0)) == (32, 71, 117, 97)
+ metrics = json.loads(report.read_text())
+ assert metrics["source"] == str(source)
+ assert metrics["output"] == str(out)
+ assert metrics["status"] == "pass"
+ assert source.read_bytes() == before
+ assert not list(tmp_path.rglob("sprite-request.json"))
+ assert not list(tmp_path.rglob("*.tmp"))
+ assert not list(tmp_path.rglob(runio.LOCK_FILENAME))
+
+
+def test_registration_arguments_use_the_same_run_function(source, tmp_path):
+ parser = argparse.ArgumentParser()
+ tile.add_arguments(parser)
+ args = parser.parse_args(["--source", str(source), "--out", str(tmp_path / "out.png"),
+ "--period", "8", "--overlap", "3", "--axis", "y"])
+ try:
+ assert tile.run(**vars(args)) == 0
+ finally:
+ runio.release_run_dir_lock(tmp_path)
+ report = json.loads((tmp_path / "out.report.json").read_text())
+ assert report["size"] == [24, 8]
+ assert report["axis"] == "y"
+
+
[email protected]("alias", ["direct", "symlink", "hardlink", "report-hardlink"])
+def test_source_overwrite_and_aliases_are_refused(source, tmp_path, alias):
+ before = source.read_bytes()
+ out = tmp_path / "new" / "tile.png"
+ report = tmp_path / "new" / "report.json"
+ if alias == "direct":
+ out = source
+ elif alias in ("symlink", "hardlink"):
+ out = tmp_path / "alias.png"
+ if alias == "symlink":
+ out.symlink_to(source)
+ else:
+ os.link(source, out)
+ else:
+ report = tmp_path / "alias.json"
+ os.link(source, report)
+ proc = invoke(source, out, "--report", report)
+ assert proc.returncode != 0
+ assert "overwrite source" in proc.stderr
+ assert source.read_bytes() == before
+ assert not (tmp_path / "new").exists()
+ assert not list(tmp_path.rglob(runio.LOCK_FILENAME))
+
+
[email protected]("failure", ["geometry", "bad-axis", "bad-overlap", "not-png", "animation",
+ "out-format", "report-format", "nested-paths", "parent-file"])
+def test_invalid_inputs_do_not_create_output_dirs_or_locks(source, tmp_path, failure):
+ out = tmp_path / "new" / "out.png"
+ report = tmp_path / "new" / "out.json"
+ extra = []
+ if failure == "geometry":
+ extra = ["--period", "40"]
+ elif failure == "bad-axis":
+ extra = ["--axis", "z"]
+ elif failure == "bad-overlap":
+ extra = ["--overlap", "0"]
+ elif failure == "not-png":
+ Image.new("RGB", (24, 13)).save(source, format="JPEG")
+ elif failure == "animation":
+ Image.new("RGBA", (24, 13), "red").save(
+ source, save_all=True, append_images=[Image.new("RGBA", (24, 13), "blue")], duration=50)
+ elif failure == "out-format":
+ out = out.with_suffix(".jpg")
+ elif failure == "report-format":
+ report = report.with_suffix(".txt")
+ elif failure == "nested-paths":
+ report = out / "report.json"
+ elif failure == "parent-file":
+ report = source / "report.json"
+ before = source.read_bytes()
+ proc = invoke(source, out, "--report", report, *extra)
+ assert proc.returncode != 0
+ assert source.read_bytes() == before
+ assert not (tmp_path / "new").exists()
+ assert not list(tmp_path.rglob(runio.LOCK_FILENAME))
+
+
+def test_report_may_not_alias_output(source, tmp_path):
+ out, report = tmp_path / "out.png", tmp_path / "report.json"
+ out.write_bytes(b"original output")
+ os.link(out, report)
+ proc = invoke(source, out, "--report", report)
+ assert proc.returncode != 0
+ assert "different files" in proc.stderr
+ assert out.read_bytes() == report.read_bytes() == b"original output"
+
+
+def test_active_writer_lock_is_not_retried_or_overwritten(source, tmp_path):
+ output = tmp_path / "output"
+ output.mkdir()
+ lock = output / runio.LOCK_FILENAME
+ lock.write_text(json.dumps({"pid": os.getpid(), "owner": "synthetic-test-writer"}))
+ before = lock.read_bytes()
+ proc = invoke(source, output / "tile.png")
+ assert proc.returncode != 0
+ assert "locked by synthetic-test-writer" in proc.stderr
+ assert lock.read_bytes() == before
+ assert not (output / "tile.png").exists()
+ assert not (output / "tile.report.json").exists()
+
+
+def test_canonical_publication_stages_complete_set_and_surfaces_failure(source, tmp_path, monkeypatch):
+ out, report = tmp_path / "tile.png", tmp_path / "tile.json"
+ out.write_bytes(b"previous PNG")
+ report.write_text("previous report")
+ called = []
+
+ def fail_second_staging_file(*args, **kwargs):
+ called.append(kwargs["prefix"])
+ if len(called) == 2:
+ raise OSError("synthetic staging failure")
+ return original_mkstemp(*args, **kwargs)
+
+ original_mkstemp = runio.tempfile.mkstemp
+ monkeypatch.setattr(runio.tempfile, "mkstemp", fail_second_staging_file)
+ try:
+ with pytest.raises(SystemExit, match="synthetic staging failure"):
+ tile.run(source=source, out=out, report=report, period=8, overlap=3)
+ finally:
+ runio.release_run_dir_lock(tmp_path)
+ assert len(called) == 2
+ assert out.read_bytes() == b"previous PNG"
+ assert report.read_text() == "previous report"
+ assert not list(tmp_path.glob("*.tmp"))
+
+
+def test_in_process_run_releases_every_lock_it_acquired_on_success(source, tmp_path):
+ out, report = tmp_path / "png" / "tile.png", tmp_path / "json" / "tile.json"
+ assert tile.run(source=source, out=out, report=report, period=8, overlap=3) == 0
+ for directory in (out.parent, report.parent):
+ assert not (directory / runio.LOCK_FILENAME).exists()
+ assert (directory / runio.LOCK_FILENAME).resolve() not in runio._HELD_LOCKS
+ assert tile.run(source=source, out=out, report=report, period=8, overlap=3) == 0
+
+
+def test_partial_lock_acquisition_is_undone_when_the_second_directory_is_held(source, tmp_path):
+ out, report = tmp_path / "a" / "tile.png", tmp_path / "b" / "tile.json"
+ report.parent.mkdir()
+ foreign = report.parent / runio.LOCK_FILENAME
+ foreign.write_text(json.dumps({"pid": os.getpid(), "owner": "synthetic-other-writer"}))
+ before = foreign.read_bytes()
+ with pytest.raises(SystemExit, match="locked by synthetic-other-writer"):
+ tile.run(source=source, out=out, report=report, period=8, overlap=3)
+ assert not (out.parent / runio.LOCK_FILENAME).exists()
+ assert (out.parent / runio.LOCK_FILENAME).resolve() not in runio._HELD_LOCKS
+ assert foreign.read_bytes() == before
+ assert not out.exists() and not report.exists()
diff --git a/tests/effects/test_shadow.py b/tests/effects/test_shadow.py
new file mode 100644
index 0000000..1bec4e8
--- /dev/null
+++ b/tests/effects/test_shadow.py
@@ -0,0 +1,397 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Synthetic geometry and publication checks for projected silhouette shadows."""
+
+import argparse
+import json
+import math
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import numpy as np
+import pytest
+from PIL import Image, ImageDraw
+
+from sprite_gen.effects.shadow import project_shadow
+from sprite_gen.effects import shadow
+from sprite_gen.spec.assets import load_asset
+from sprite_gen.spec import runio
+
+
+def _silhouette(size=(32, 48)):
+ image = Image.new("RGBA", size)
+ draw = ImageDraw.Draw(image)
+ draw.rectangle((0, 0, size[0] - 1, size[1] - 1), fill=(220, 40, 170, 180))
+ draw.rectangle((7, 8, 20, 37), fill=(30, 240, 20, 255))
+ return image
+
+
+def _center_of_alpha(image):
+ alpha = np.asarray(image.getchannel("A"), dtype=float)
+ ys, xs = np.indices(alpha.shape)
+ return ((alpha * (xs + 0.5)).sum() / alpha.sum(),
+ (alpha * (ys + 0.5)).sum() / alpha.sum())
+
+
+def _in_world(image, anchor, size=(1024, 1024)):
+ world = Image.new("RGBA", size)
+ offset = (round(size[0] / 2 - anchor[0]), round(size[1] / 2 - anchor[1]))
+ assert offset[0] >= 0 and offset[1] >= 0
+ assert offset[0] + image.width <= size[0]
+ assert offset[1] + image.height <= size[1]
+ world.paste(image, offset)
+ return np.asarray(world.getchannel("A"))
+
+
[email protected]("shear", [-2.0, 0.0, 2.0])
+def test_foot_anchor_is_a_stationary_point(shear):
+ image = Image.new("RGBA", (40, 40))
+ ImageDraw.Draw(image).rectangle((17, 27, 23, 33), fill=(255, 255, 255, 255))
+ anchor = (20.5, 30.5)
+ shadow, shadow_anchor = project_shadow(
+ image, anchor, squash=0.5, shear=shear, opacity=1, blur=0)
+ center = _center_of_alpha(shadow)
+ assert center[0] - shadow_anchor[0] == pytest.approx(0, abs=0.6)
+ assert center[1] - shadow_anchor[1] == pytest.approx(0, abs=0.6)
+
+
[email protected]("shear", [-1.0, 1.0])
+def test_positive_shear_falls_left_and_negative_falls_right(shear):
+ image = Image.new("RGBA", (40, 40))
+ ImageDraw.Draw(image).rectangle((17, 7, 22, 12), fill="white")
+ shadow, anchor = project_shadow(
+ image, (20, 40), squash=0.5, shear=shear, opacity=1, blur=0)
+ center = _center_of_alpha(shadow)
+ assert center[0] - anchor[0] == pytest.approx(-30 * shear, abs=0.7)
+ assert center[1] - anchor[1] == pytest.approx(-15, abs=0.7)
+
+
[email protected]("anchor", [(0, 0), (0, 48), (32, 48), (7.5, 31.5)])
[email protected]("shear", [-2.0, 2.0])
[email protected]("blur", [0, 3, 9])
+def test_canvas_does_not_crop_even_at_offcenter_anchors(anchor, shear, blur):
+ source = _silhouette()
+ shadow, shadow_anchor = project_shadow(
+ source, anchor, squash=0.5, shear=shear, opacity=1, blur=blur)
+ # Extra source transparency cannot reveal pixels missing from the original
+ # projection. This catches both clipped shear and truncated blur tails.
+ padded = Image.new("RGBA", (source.width + 160, source.height + 160))
+ padded.paste(source, (80, 80))
+ reference, reference_anchor = project_shadow(
+ padded, (anchor[0] + 80, anchor[1] + 80),
+ squash=0.5, shear=shear, opacity=1, blur=blur)
+ assert np.array_equal(_in_world(shadow, shadow_anchor),
+ _in_world(reference, reference_anchor))
+ bounds = shadow.getchannel("A").getbbox()
+ assert bounds is not None
+ assert 0 < bounds[0] < bounds[2] < shadow.width
+ assert 0 < bounds[1] < bounds[3] < shadow.height
+
+
+def test_identity_projection_keeps_alpha_and_applies_only_requested_color():
+ source = _silhouette()
+ shadow, anchor = project_shadow(
+ source, (16, 48), squash=1, shear=0, opacity=1, blur=0, color=(1, 2, 3))
+ x, y = int(anchor[0] - 16), int(anchor[1] - 48)
+ crop = shadow.crop((x, y, x + source.width, y + source.height))
+ assert crop.getchannel("A").tobytes() == source.getchannel("A").tobytes()
+ assert np.all(np.asarray(crop)[:, :, :3] == (1, 2, 3))
+
+
+def test_opacity_is_monotonic_and_does_not_change_geometry():
+ source = _silhouette()
+ outputs = [project_shadow(source, (16, 48), opacity=value)
+ for value in [0, 0.2, 0.4, 0.8, 1]]
+ assert len({(image.size, anchor) for image, anchor in outputs}) == 1
+ alphas = [np.asarray(image.getchannel("A")) for image, _ in outputs]
+ assert not alphas[0].any()
+ for low, high in zip(alphas, alphas[1:]):
+ assert np.all(low <= high)
+ assert low.sum() < high.sum()
+
+
[email protected]("mode", ["RGBA", "RGB", "L", "P"])
+def test_source_is_unchanged_and_output_is_rgba(mode):
+ source = _silhouette().convert(mode)
+ original = source.tobytes(), source.mode, source.size, source.getpalette()
+ shadow, _ = project_shadow(source, (16, 48))
+ assert shadow.mode == "RGBA"
+ assert (source.tobytes(), source.mode, source.size, source.getpalette()) == original
+
+
+def test_empty_silhouette_stays_transparent():
+ shadow, anchor = project_shadow(Image.new("RGBA", (20, 30)), (10, 30))
+ assert shadow.getchannel("A").getbbox() is None
+ assert all(math.isfinite(value) for value in anchor)
+
+
[email protected]("name,value", [
+ ("squash", 0), ("squash", -1), ("squash", 2), ("squash", 1e-100),
+ ("shear", 10000), ("shear", -10000),
+ ("opacity", -0.1), ("opacity", 1.1),
+ ("blur", -1), ("blur", 10000),
+ *[(name, value) for name in ["squash", "shear", "opacity", "blur"]
+ for value in [float("nan"), float("inf"), float("-inf"), True, "bad"]],
+ ("color", (1, 2)), ("color", (-1, 2, 3)), ("color", (1, 2, 256)),
+ ("color", (1, 2, 3.5)), ("color", (1, 2, float("nan"))),
+ ("color", (True, 2, 3)), ("color", "red"), ("color", None),
+])
+def test_invalid_parameters_are_rejected(name, value):
+ with pytest.raises(ValueError):
+ project_shadow(_silhouette(), (16, 48), **{name: value})
+
+
[email protected]("anchor", [None, (1,), (1, 2, 3), (float("nan"), 2),
+ (1, float("inf")), (True, 2), (1e12, 2)])
+def test_invalid_anchor_is_rejected(anchor):
+ with pytest.raises(ValueError):
+ project_shadow(_silhouette(), anchor)
+
+
+def test_zero_sized_image_is_rejected():
+ with pytest.raises(ValueError):
+ project_shadow(Image.new("RGBA", (0, 10)), (0, 10))
+
+
+def _asset_files(tmp_path):
+ images = [_silhouette(), Image.new("RGBA", (32, 48))]
+ ImageDraw.Draw(images[1]).ellipse((12, 22, 31, 47), fill=(255, 140, 30, 255))
+ entries = []
+ for index, (image, duration) in enumerate(zip(images, (0.07, 0.23))):
+ path = tmp_path / f"source-{index}.png"
+ image.save(path)
+ entries.append({"file": path.name, "duration": duration})
+ source = tmp_path / "source.asset.json"
+ source.write_text(json.dumps({"kind": "sprite-gen-asset", "version": 1,
+ "frames": entries, "anchor": [7.5, 47]}))
+ return source
+
+
+def test_run_publishes_loadable_sequence_strip_timing_anchor_and_preserves_source(tmp_path):
+ source = _asset_files(tmp_path)
+ original = load_asset(source)
+ fingerprints = original.fingerprints()
+ out_dir = tmp_path / "shadows"
+ assert shadow.run(source=source, out_dir=out_dir) == 0
+ generated = load_asset(out_dir / "shadow.asset.json")
+ assert generated.durations == original.durations
+ assert generated.duration == pytest.approx(0.3)
+ assert len(generated.frames) == 2
+ assert len({frame.size for frame in generated.frames}) == 1
+ for index, frame in enumerate(original.frames):
+ expected, anchor = project_shadow(frame, original.anchor)
+ assert generated.frames[index].tobytes() == expected.tobytes()
+ assert generated.anchor == anchor
+ assert generated.frame_at(0.08).tobytes() == generated.frames[1].tobytes()
+ with Image.open(out_dir / "shadow.png") as sheet:
+ width, height = generated.size
+ assert sheet.mode == "RGBA"
+ assert sheet.size == (width * 2, height)
+ for index, frame in enumerate(generated.frames):
+ assert sheet.crop((index * width, 0, (index + 1) * width, height)).tobytes() == frame.tobytes()
+ assert original.fingerprints() == fingerprints
+ assert not (out_dir / runio.LOCK_FILENAME).exists()
+
+
[email protected]("source_kind", ["png", "descriptor", "loop", "atlas"])
+def test_run_uses_shared_loader_for_all_source_types(tmp_path, source_kind):
+ source = _asset_files(tmp_path)
+ state = None
+ if source_kind == "png":
+ source = tmp_path / "source-0.png"
+ elif source_kind in ("loop", "atlas"):
+ sheet = Image.new("RGBA", (64, 48))
+ for index in range(2):
+ with Image.open(tmp_path / f"source-{index}.png") as frame:
+ sheet.paste(frame, (index * 32, 0))
+ if source_kind == "loop":
+ sheet.save(tmp_path / "motion.strip.png")
+ source = tmp_path / "motion.strip.json"
+ data = {"frames": 2, "w": 32, "h": 48, "delay_ms": 150}
+ else:
+ sheet.save(tmp_path / "atlas.png")
+ source = tmp_path / "atlas.json"
+ state = "walk"
+ data = {
+ "sprite_sheet_alpha": "atlas.png",
+ "frame_layout": {"rows": {"walk": [
+ {"x": index * 32, "y": 0, "w": 32, "h": 48} for index in range(2)]}},
+ "animation": {"rows": {"walk": {"durations_ms": [70, 230], "loop": True}}},
+ }
+ source.write_text(json.dumps(data))
+ original = load_asset(source, state=state)
+ fingerprints = original.fingerprints()
+ out_dir = tmp_path / "shadows"
+ assert shadow.run(source=source, out_dir=out_dir, state=state) == 0
+ result = load_asset(out_dir / "shadow.asset.json")
+ assert result.durations == original.durations
+ assert len(result.frames) == len(original.frames)
+ assert original.fingerprints() == fingerprints
+
+
+def test_run_honors_fps_and_anchor_overrides(tmp_path):
+ source = _asset_files(tmp_path)
+ out_dir = tmp_path / "shadows"
+ shadow.run(source=source, out_dir=out_dir, fps=20, anchor_x=0, anchor_y=40)
+ result = load_asset(out_dir / "shadow.asset.json")
+ assert result.durations == (0.05, 0.05)
+ _, expected_anchor = project_shadow(load_asset(source).frames[0], (0, 40))
+ assert result.anchor == expected_anchor
+
+
[email protected]("kwargs", [
+ {"opacity": float("nan")}, {"squash": 0}, {"shear": float("inf")},
+ {"blur": -1}, {"color": (300, 0, 0)},
+ {"anchor_x": 12}, {"anchor_y": 32}, {"anchor_x": 0, "anchor_y": float("nan")},
+ {"fps": 0}, {"fps": -1}, {"fps": float("nan")}, {"fps": float("inf")},
+])
+def test_invalid_cli_values_do_not_create_output(tmp_path, kwargs):
+ source = tmp_path / "source.png"
+ _silhouette().save(source)
+ before = source.read_bytes()
+ out_dir = tmp_path / "shadows"
+ with pytest.raises(ValueError):
+ shadow.run(source=source, out_dir=out_dir, **kwargs)
+ assert not out_dir.exists()
+ assert source.read_bytes() == before
+
+
+def test_malformed_source_does_not_create_output(tmp_path):
+ source = tmp_path / "source.asset.json"
+ source.write_text('{"kind":"sprite-gen-asset","version":1,"frames":[]}')
+ out_dir = tmp_path / "shadows"
+ with pytest.raises(ValueError):
+ shadow.run(source=source, out_dir=out_dir)
+ assert not out_dir.exists()
+
+
+def test_huge_projection_is_rejected_before_output_creation(tmp_path):
+ source = _asset_files(tmp_path)
+ out_dir = tmp_path / "shadows"
+ with pytest.raises(ValueError, match="canvas"):
+ shadow.run(source=source, out_dir=out_dir, anchor_x=1_000_000, anchor_y=1_000_000)
+ assert not out_dir.exists()
+
+
[email protected]("filename", ["frame-000.png", "shadow.png", "shadow.asset.json"])
+def test_outputs_cannot_overwrite_input_files(tmp_path, filename):
+ if filename.endswith("json"):
+ original = _asset_files(tmp_path)
+ source = tmp_path / filename
+ source.write_bytes(original.read_bytes())
+ else:
+ source = tmp_path / filename
+ _silhouette().save(source)
+ before = {path: path.read_bytes() for path in tmp_path.iterdir()}
+ with pytest.raises(ValueError, match="overwrite source"):
+ shadow.run(source=source, out_dir=tmp_path)
+ assert {path: path.read_bytes() for path in tmp_path.iterdir()} == before
+
+
+def test_output_cannot_overwrite_a_frame_referenced_by_descriptor(tmp_path):
+ source = _asset_files(tmp_path)
+ data = json.loads(source.read_text())
+ referenced_frame = tmp_path / "frame-000.png"
+ referenced_frame.write_bytes((tmp_path / "source-0.png").read_bytes())
+ data["frames"][0]["file"] = referenced_frame.name
+ source.write_text(json.dumps(data))
+ before = referenced_frame.read_bytes()
+ with pytest.raises(ValueError, match="overwrite source"):
+ shadow.run(source=source, out_dir=tmp_path)
+ assert referenced_frame.read_bytes() == before
+ assert not (tmp_path / runio.LOCK_FILENAME).exists()
+
+
+def test_render_failure_leaves_no_output_and_is_not_retried(tmp_path, monkeypatch):
+ source = _asset_files(tmp_path)
+ out_dir = tmp_path / "shadows"
+ calls = []
+
+ def fail_encode(image):
+ calls.append(image)
+ raise OSError("synthetic encoder failure")
+
+ monkeypatch.setattr(shadow, "_png_bytes", fail_encode)
+ with pytest.raises(OSError, match="synthetic encoder failure"):
+ shadow.run(source=source, out_dir=out_dir)
+ assert len(calls) == 1
+ assert not out_dir.exists()
+
+
+def test_staging_failure_preserves_existing_outputs_and_releases_lock(tmp_path, monkeypatch):
+ source = _asset_files(tmp_path)
+ out_dir = tmp_path / "shadows"
+ shadow.run(source=source, out_dir=out_dir)
+ before = {path.name: path.read_bytes() for path in out_dir.iterdir()}
+ fsync = runio.os.fsync
+ calls = []
+
+ def fail_second_staged_file(fd):
+ calls.append(fd)
+ if len(calls) == 2:
+ raise OSError("synthetic disk failure")
+ fsync(fd)
+
+ monkeypatch.setattr(runio.os, "fsync", fail_second_staged_file)
+ with pytest.raises(OSError, match="synthetic disk failure"):
+ shadow.run(source=source, out_dir=out_dir, shear=-1)
+ assert len(calls) == 2
+ assert {path.name: path.read_bytes() for path in out_dir.iterdir()} == before
+ assert not (out_dir / runio.LOCK_FILENAME).exists()
+
+
+def test_live_writer_lock_is_respected_without_publishing(tmp_path):
+ source = _asset_files(tmp_path)
+ out_dir = tmp_path / "shadows"
+ out_dir.mkdir()
+ lock = out_dir / runio.LOCK_FILENAME
+ lock.write_text(json.dumps({"owner": "synthetic-other-writer", "pid": os.getpid()}))
+ before = lock.read_bytes()
+ with pytest.raises(SystemExit, match="locked by synthetic-other-writer"):
+ shadow.run(source=source, out_dir=out_dir)
+ assert list(out_dir.iterdir()) == [lock]
+ assert lock.read_bytes() == before
+
+
[email protected]("target_kind", ["symlink", "directory"])
+def test_invalid_target_is_rejected_without_mutating_destination(tmp_path, target_kind):
+ source = _asset_files(tmp_path)
+ out_dir = tmp_path / "shadows"
+ out_dir.mkdir()
+ target = out_dir / "shadow.png"
+ if target_kind == "symlink":
+ target.symlink_to(tmp_path / "unrelated.png")
+ else:
+ target.mkdir()
+ with pytest.raises(ValueError, match="regular file"):
+ shadow.run(source=source, out_dir=out_dir)
+ assert list(out_dir.iterdir()) == [target]
+
+
+def test_parser_registers_specified_names_and_color_formats():
+ parser = argparse.ArgumentParser()
+ shadow.add_arguments(parser)
+ args = parser.parse_args(["--source", "source.png", "--out-dir", "result", "--color", "#140f1e"])
+ assert args.source == Path("source.png")
+ assert args.out_dir == Path("result")
+ assert args.color == (20, 15, 30)
+ assert parser.parse_args(["--source", "s", "--out-dir", "o", "--color", "2,3,4"]).color == (2, 3, 4)
+ with pytest.raises(SystemExit):
+ parser.parse_args(["--source", "s", "--out-dir", "o", "--color", "256,0,0"])
+
+
+def test_module_cli_executes_the_real_publication_path(tmp_path):
+ source = _asset_files(tmp_path)
+ out_dir = tmp_path / "shadows"
+ result = subprocess.run(
+ [sys.executable, "-m", "sprite_gen.effects.shadow", "--source", str(source),
+ "--out-dir", str(out_dir), "--shear", "-0.8", "--color", "10,20,30"],
+ capture_output=True, text=True, check=False,
+ )
+ assert result.returncode == 0, result.stderr
+ report = json.loads(result.stdout)
+ assert report["ok"] is True
+ assert report["frames"] == 2
+ assert load_asset(Path(report["manifest"])).durations == (0.07, 0.23)
+ assert not (out_dir / runio.LOCK_FILENAME).exists()
diff --git a/tests/qa/test_motion.py b/tests/qa/test_motion.py
new file mode 100644
index 0000000..c40c64a
--- /dev/null
+++ b/tests/qa/test_motion.py
@@ -0,0 +1,397 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Synthetic motion measurements; no provider assets or real run directories."""
+
+from __future__ import annotations
+
+import json
+import hashlib
+import os
+import subprocess
+import sys
+from types import SimpleNamespace
+
+import pytest
+from PIL import Image, ImageDraw
+
+from sprite_gen.qa.motion import analyze_motion
+from sprite_gen.qa import motion
+
+
+def sequence(xs=(24, 22, 20, 18, 16), *, durations=None, ys=None, two_feet=False):
+ frames = []
+ for index, x in enumerate(xs):
+ frame = Image.new("RGBA", (48, 40))
+ draw = ImageDraw.Draw(frame)
+ draw.rectangle((15, 5, 30, 20), fill="white")
+ y = 30 if ys is None else ys[index]
+ draw.rectangle((x, y, x + 3, y + 2), fill="white")
+ if two_feet:
+ draw.rectangle((36, y, 39, y + 2), fill="white")
+ frames.append(frame)
+ return SimpleNamespace(
+ frames=tuple(frames), durations=tuple(durations or [0.1] * len(frames)),
+ anchor=(24.0, 40.0), source_files=(), metadata={}, fingerprints=lambda: {},
+ )
+
+
+FOOT_BOX = (8, 25, 34, 12)
+
+
+def test_manual_stance_measures_signed_velocity_without_facing_inference():
+ report = analyze_motion(sequence(), contacts="0:4", foot_box=FOOT_BOX)
+ assert report["status"] == "verified"
+ assert report["stride_verified"] is True
+ assert report["source_fingerprints"] == {}
+ assert report["foot_velocity_px_per_second"] == pytest.approx(-20)
+ assert report["stride_px_per_second"] == pytest.approx(20)
+ assert report["confidence"] >= 0.8
+ assert report["duration_seconds"] == pytest.approx(0.5)
+ assert report["facing"] is None
+ assert report["contact_candidates"][0]["measurement_elapsed_seconds"] == pytest.approx(0.4)
+
+
[email protected]("xs, expected", [((16, 18, 20, 22, 24), 20), ((24, 22, 20, 18, 16), -20)])
+def test_facing_never_flips_velocity_or_reverses_frames(xs, expected):
+ seq = sequence(xs)
+ before = tuple(frame.tobytes() for frame in seq.frames)
+ for facing in (None, "left", "right"):
+ report = analyze_motion(seq, contacts=range(5), foot_box=FOOT_BOX, facing=facing)
+ assert report["foot_velocity_px_per_second"] == pytest.approx(expected)
+ assert report["stride_px_per_second"] == pytest.approx(abs(expected))
+ assert report["facing"] == facing
+ assert tuple(frame.tobytes() for frame in seq.frames) == before
+
+
+def test_split_duplicate_holds_preserve_duration_and_stance_speed():
+ original = sequence(durations=[0.2] * 5)
+ repeated = sequence(
+ (24, 24, 22, 22, 20, 20, 18, 18, 16, 16), durations=[0.07, 0.13] * 5,
+ )
+ a = analyze_motion(original, contacts="0:4", foot_box=FOOT_BOX)
+ b = analyze_motion(repeated, contacts="0:9", foot_box=FOOT_BOX)
+ assert b["duration_seconds"] == pytest.approx(a["duration_seconds"])
+ assert b["stride_px_per_second"] == pytest.approx(a["stride_px_per_second"])
+ assert b["foot_velocity_px_per_second"] == pytest.approx(-10)
+ assert b["duplicate_frames"]["exact"] == 5
+ assert b["duplicate_frames"]["exact_silhouette"] == 5
+ assert len(b["frames"]) == 10
+ assert b["frames"][-1]["duration_seconds"] == pytest.approx(0.13)
+ assert b["contact_candidates"][0]["measurement_elapsed_seconds"] == pytest.approx(0.8)
+
+
+def test_added_hold_time_reduces_speed_instead_of_being_dropped():
+ original = analyze_motion(sequence(), contacts="0:4", foot_box=FOOT_BOX)
+ repeated = analyze_motion(
+ sequence((24, 24, 22, 22, 20, 20, 18, 18, 16, 16)),
+ contacts="0:9", foot_box=FOOT_BOX,
+ )
+ assert repeated["duration_seconds"] == pytest.approx(original["duration_seconds"] * 2)
+ assert repeated["stride_px_per_second"] == pytest.approx(original["stride_px_per_second"] / 2)
+
+
+def test_nonuniform_frame_durations_determine_speed():
+ seq = sequence((24, 23, 20, 18, 16), durations=[0.05, 0.15, 0.1, 0.1, 0.4])
+ report = analyze_motion(seq, contacts=[(0, 4)], foot_box=FOOT_BOX)
+ assert report["foot_velocity_px_per_second"] == pytest.approx(-20)
+ assert report["duration_seconds"] == pytest.approx(0.8)
+
+
[email protected]("kwargs", [{}, {"contacts": "0:4"}, {"foot_box": FOOT_BOX}])
+def test_unannotated_motion_cannot_claim_stride(kwargs):
+ report = analyze_motion(sequence(), **kwargs)
+ assert report["motion"]["present"] is True
+ assert report["status"] == "needs-review"
+ assert report["stride_px_per_second"] is None
+ assert report["foot_velocity_px_per_second"] is None
+ assert report["warnings"]
+
+
+def test_two_feet_in_roi_cannot_claim_stance_speed():
+ report = analyze_motion(sequence(two_feet=True), contacts="0:4", foot_box=FOOT_BOX)
+ assert report["status"] == "needs-review"
+ assert report["stride_px_per_second"] is None
+ assert any("multiple" in reason for reason in report["contact_candidates"][0]["reasons"])
+
+
+def test_connected_legs_still_have_ambiguous_contact_lobes():
+ seq = sequence(two_feet=True)
+ for frame in seq.frames:
+ ImageDraw.Draw(frame).rectangle((16, 28, 39, 30), fill="white")
+ report = analyze_motion(seq, contacts="0:4", foot_box=FOOT_BOX)
+ assert report["stride_px_per_second"] is None
+ assert any("multiple" in reason for reason in report["contact_candidates"][0]["reasons"])
+
+
[email protected]("ys", [(23, 21, 19, 21, 23), (30, 28, 26, 28, 30)])
+def test_airborne_or_vertically_moving_foot_stays_unknown(ys):
+ report = analyze_motion(sequence(ys=ys), contacts="0:4", foot_box=FOOT_BOX)
+ assert report["status"] == "needs-review"
+ assert report["stride_px_per_second"] is None
+ assert report["foot_velocity_px_per_second"] is None
+
+
+def test_stance_reversal_is_rejected():
+ report = analyze_motion(sequence((24, 22, 20, 22, 24)), contacts="0:4", foot_box=FOOT_BOX)
+ assert report["stride_px_per_second"] is None
+ assert "horizontal reversal" in report["contact_candidates"][0]["reasons"]
+
+
+def test_contact_spans_do_not_bridge_swing_and_conflicting_signs_stay_unknown():
+ seq = sequence((24, 22, 20, 34, 16, 18, 20))
+ report = analyze_motion(seq, contacts="0:2,4:6", foot_box=FOOT_BOX)
+ assert len(report["contact_candidates"]) == 2
+ assert all(item["status"] == "verified" for item in report["contact_candidates"])
+ assert report["stride_px_per_second"] is None
+ assert report["status"] == "needs-review"
+
+
+def test_static_empty_and_single_frame_are_unknown_and_json_safe():
+ for seq in (sequence((20, 20, 20)), sequence((20,)), sequence((20, 20))):
+ report = analyze_motion(seq)
+ assert report["status"] == "unknown"
+ assert report["stride_px_per_second"] is None
+ json.dumps(report, allow_nan=False)
+ blank = sequence((20,))
+ blank.frames = (Image.new("RGBA", (48, 40)),)
+ report = analyze_motion(blank)
+ assert report["frames"][0]["bbox"] is None
+ assert report["bbox_stats"]["union"] is None
+
+
+def test_silhouette_repeats_near_poses_edges_and_anchor_stats():
+ frame = Image.new("RGBA", (48, 40))
+ ImageDraw.Draw(frame).rectangle((0, 0, 20, 30), fill="white")
+ recolored = frame.copy()
+ ImageDraw.Draw(recolored).rectangle((0, 0, 20, 30), fill="red")
+ near = recolored.copy()
+ near.putpixel((20, 30), (0, 0, 0, 0))
+ seq = sequence((20,) * 4)
+ seq.frames = (frame, recolored, near, frame.copy())
+ report = analyze_motion(seq)
+ assert report["duplicate_frames"]["exact"] == 1
+ assert report["duplicate_frames"]["exact_silhouette"] == 2
+ assert report["duplicate_frames"]["near_silhouette"] == 1
+ assert report["edge_contact"]["frames"] == [0, 1, 2, 3]
+ assert report["edge_contact"]["sides"]["left"] == [0, 1, 2, 3]
+ assert report["frames"][0]["anchor_px"] == [24.0, 40.0]
+ assert report["frames"][0]["bbox_from_anchor"] == [-24.0, -40.0, -3.0, -9.0]
+
+
[email protected]("kwargs", [
+ {"contacts": "4:0"}, {"contacts": "0:8"}, {"contacts": "0:2,2:4"},
+ {"contacts": [0, 0, 1]}, {"contacts": ""}, {"contacts": "-1:2"},
+ {"contacts": [0, 2.5]}, {"foot_box": (0, 0, 0, 10)},
+ {"foot_box": (0, 0, 49, 10)}, {"foot_box": (0, 0, 10.5, 10)},
+ {"facing": "up"},
+])
+def test_invalid_annotations_fail_before_analysis(kwargs):
+ with pytest.raises(ValueError):
+ analyze_motion(sequence(), **kwargs)
+
+
[email protected]("durations", [(0.1,), (0.1, 0, 0.1, 0.1, 0.1), (float("nan"),) * 5])
+def test_invalid_timing_is_rejected(durations):
+ seq = sequence()
+ seq.durations = durations
+ with pytest.raises(ValueError):
+ analyze_motion(seq)
+
+
+def test_timing_that_overflows_derived_speed_is_rejected():
+ seq = sequence(durations=[1e-320] * 5)
+ with pytest.raises(ValueError, match="finite"):
+ analyze_motion(seq, contacts="0:4", foot_box=FOOT_BOX)
+ with pytest.raises(ValueError, match="finite"):
+ analyze_motion(seq)
+
+
+def descriptor(tmp_path):
+ """Exercise the real shared adapter with a declared external sequence."""
+ entries = []
+ for index, frame in enumerate(sequence().frames):
+ path = tmp_path / f"foot-{index}.png"
+ frame.save(path)
+ entries.append({"file": path.name, "duration": 0.1})
+ path = tmp_path / "walk.json"
+ path.write_text(json.dumps({"kind": "sprite-gen-asset", "version": 1, "frames": entries}))
+ return path
+
+
+def file_bytes(directory):
+ return {str(p.relative_to(directory)): p.read_bytes() for p in directory.rglob("*") if p.is_file()}
+
+
+def test_run_real_adapter_stdout_is_read_only_and_fingerprints_match(tmp_path, capsys):
+ source = descriptor(tmp_path)
+ before = file_bytes(tmp_path)
+ assert motion.run(source=source, contacts="0:4", foot_box="8,25,34,12", anchor_x=12, anchor_y=38) == 0
+ report = json.loads(capsys.readouterr().out)
+ assert report["stride_verified"] is True
+ assert report["stride_px_per_second"] == pytest.approx(20)
+ assert report["anchor_px"] == [12, 38]
+ assert report["source_fingerprints"] == {
+ str(tmp_path / name): hashlib.sha256(contents).hexdigest() for name, contents in before.items()
+ }
+ assert file_bytes(tmp_path) == before
+
+
+def test_module_entrypoint_publishes_report_and_preserves_sources(tmp_path):
+ source = descriptor(tmp_path)
+ before = file_bytes(tmp_path)
+ output = tmp_path / "reports" / "motion.json"
+ result = subprocess.run(
+ [sys.executable, "-m", "sprite_gen.qa.motion", "--source", str(source),
+ "--contacts", "0:4", "--foot-box", "8,25,34,12", "--fps", "5",
+ "--facing", "right", "--out", str(output)],
+ capture_output=True, text=True, check=False,
+ )
+ assert result.returncode == 0, result.stderr
+ report = json.loads(output.read_text())
+ assert report == json.loads(result.stdout)
+ assert report["stride_px_per_second"] == pytest.approx(10)
+ assert report["duration_seconds"] == pytest.approx(1)
+ assert not (output.parent / ".sprite-gen.lock").exists()
+ for name, contents in before.items():
+ assert (tmp_path / name).read_bytes() == contents
+
+
[email protected]("target", ["walk.json", "foot-0.png", "symlink.json", "hardlink.json"])
+def test_output_cannot_overwrite_any_source_or_alias(tmp_path, capsys, target):
+ source = descriptor(tmp_path)
+ output = tmp_path / target
+ if target == "symlink.json":
+ output.symlink_to(source)
+ if target == "hardlink.json":
+ os.link(source, output)
+ before = file_bytes(tmp_path)
+ assert motion.run(source=source, out=output) == 2
+ assert "must not overwrite" in capsys.readouterr().err
+ assert file_bytes(tmp_path) == before
+
+
[email protected]("kwargs", [
+ {"contacts": "0:999"}, {"foot_box": "8,25,99,12"}, {"anchor_x": 2},
+ {"fps": 0}, {"facing": "north"},
+])
+def test_invalid_cli_input_creates_no_output_or_locks(tmp_path, capsys, kwargs):
+ source = descriptor(tmp_path)
+ before = file_bytes(tmp_path)
+ output = tmp_path / "new" / "report.json"
+ assert motion.run(source=source, out=output, **kwargs) == 2
+ assert capsys.readouterr().err
+ assert file_bytes(tmp_path) == before
+ assert not output.parent.exists()
+
+
+def test_publication_uses_output_lock_then_atomic_write_once(tmp_path, monkeypatch, capsys):
+ source = descriptor(tmp_path)
+ output = tmp_path / "reports" / "motion.json"
+ calls = []
+ real_write = motion.atomic_write_set
+
+ def lock(directory, owner):
+ assert directory == output.parent
+ calls.append(("lock", owner))
+
+ def write(payloads):
+ assert calls == [("lock", "inspect-motion")]
+ assert list(payloads) == [output]
+ calls.append(("write",))
+ real_write(payloads)
+
+ monkeypatch.setattr(motion, "acquire_run_dir_lock", lock)
+ monkeypatch.setattr(motion, "atomic_write_set", write)
+ assert motion.run(source=source, out=output) == 0
+ assert len(calls) == 2
+ assert json.loads(output.read_text()) == json.loads(capsys.readouterr().out)
+
+
+def test_live_output_lock_fails_without_retry_or_report(tmp_path):
+ source = descriptor(tmp_path)
+ output = tmp_path / "report.json"
+ (tmp_path / ".sprite-gen.lock").write_text(json.dumps({"owner": "synthetic-writer", "pid": os.getpid()}))
+ before = file_bytes(tmp_path)
+ with pytest.raises(SystemExit, match="locked by synthetic-writer"):
+ motion.run(source=source, out=output)
+ assert file_bytes(tmp_path) == before
+
+
+def test_atomic_publish_failure_keeps_existing_report_and_does_not_retry(tmp_path, monkeypatch, capsys):
+ source = descriptor(tmp_path)
+ output = tmp_path / "report.json"
+ output.write_text("existing report")
+ calls = []
+
+ def fail_once(payloads):
+ calls.append(payloads)
+ raise OSError("synthetic disk failure")
+
+ monkeypatch.setattr(motion, "atomic_write_set", fail_once)
+ assert motion.run(source=source, out=output) == 2
+ assert len(calls) == 1
+ assert output.read_text() == "existing report"
+ assert "synthetic disk failure" in capsys.readouterr().err
+
+
+def test_consistent_separate_stances_can_measure_without_bridging_swing():
+ seq = sequence((24, 22, 20, 32, 24, 22, 20))
+ report = analyze_motion(seq, contacts=[0, 1, 2, 4, 5, 6], foot_box=FOOT_BOX)
+ assert report["contacts"] == [[0, 2], [4, 6]]
+ assert report["stride_verified"] is True
+ assert report["foot_velocity_px_per_second"] == pytest.approx(-20)
+
+
+def test_invalid_stance_is_not_silently_dropped_from_aggregate():
+ seq = sequence((24, 22, 20, 32, 24, 24, 24))
+ report = analyze_motion(seq, contacts="0:2,4:6", foot_box=FOOT_BOX)
+ assert report["contact_candidates"][0]["status"] == "verified"
+ assert report["contact_candidates"][1]["status"] == "needs-review"
+ assert report["stride_verified"] is False
+ assert report["stride_px_per_second"] is None
+
+
+def test_foot_roi_clipping_and_speed_changes_are_not_verified():
+ clipped = analyze_motion(sequence(), contacts="0:4", foot_box=(16, 25, 12, 12))
+ assert clipped["stride_verified"] is False
+ inconsistent = analyze_motion(sequence((26, 25, 24, 23, 16)), contacts="0:4", foot_box=FOOT_BOX)
+ assert inconsistent["stride_verified"] is False
+ assert "foot velocity is inconsistent" in " ".join(inconsistent["contact_candidates"][0]["reasons"])
+
+
+def test_report_names_the_measured_sequence_so_consumers_can_refuse_other_selections(tmp_path):
+ from sprite_gen.spec.assets import load_asset, same_identity, sequence_identity
+
+ sheet = Image.new("RGBA", (48 * 5, 40))
+ for index, frame in enumerate(sequence().frames):
+ sheet.paste(frame, (48 * index, 0))
+ sheet.save(tmp_path / "atlas.png")
+ rects = [{"x": 48 * i, "y": 0, "w": 48, "h": 40} for i in range(5)]
+ (tmp_path / "atlas.json").write_text(json.dumps({
+ "sprite_sheet_alpha": "atlas.png",
+ "frame_layout": {"rows": {"walk": rects, "idle": [rects[0]] * 5}},
+ "animation": {"rows": {s: {"durations_ms": [100] * 5, "loop": True} for s in ("walk", "idle")}},
+ }))
+ walk = load_asset(tmp_path / "atlas.json", state="walk")
+ report = json.loads(json.dumps(analyze_motion(walk, contacts="0:4", foot_box=FOOT_BOX)))
+ assert report["sequence"] == sequence_identity(walk)
+ assert report["sequence"]["state"] == "walk" and report["sequence"]["durations_seconds"] == [0.1] * 5
+ assert same_identity(report["sequence"], walk)
+ assert not same_identity(report["sequence"], load_asset(tmp_path / "atlas.json", state="idle"))
+ assert not same_identity(report["sequence"], load_asset(tmp_path / "atlas.json", state="walk", fps=5))
+ assert report["source_fingerprints"] == walk.fingerprints()
+ assert "sequence" in report["method"]
+ in_memory = analyze_motion(sequence(), contacts="0:4", foot_box=FOOT_BOX)
+ assert in_memory["sequence"] == {"source": None, "state": None, "fps_override": None, "frame_count": 5,
+ "size": [48, 40], "anchor_px": [24.0, 40.0], "durations_seconds": [0.1] * 5}
+
+
+def test_in_process_publication_releases_the_output_lock(tmp_path, capsys):
+ from sprite_gen.spec import runio
+
+ source = descriptor(tmp_path)
+ output = tmp_path / "reports" / "motion.json"
+ assert motion.run(source=source, out=output) == 0
+ assert not (output.parent / runio.LOCK_FILENAME).exists()
+ assert (output.parent / runio.LOCK_FILENAME).resolve() not in runio._HELD_LOCKS
+ assert motion.run(source=source, out=output) == 0
+ assert json.loads(output.read_text())["kind"] == "sprite-gen-motion-report"
diff --git a/tests/scene/test_inspect_scene.py b/tests/scene/test_inspect_scene.py
new file mode 100644
index 0000000..6f45114
--- /dev/null
+++ b/tests/scene/test_inspect_scene.py
@@ -0,0 +1,224 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Scene inspection: the seam a viewer sees, phase closure, visibility and guarded report publication."""
+
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+from PIL import Image, ImageDraw
+
+from sprite_gen.scene import inspect_scene as module
+from sprite_gen.scene.inspect_scene import inspect_scene, output_path, run
+from sprite_gen.scene.model import load_scene
+from sprite_gen.spec import runio
+
+
+def frames_asset(tmp_path, name, images, duration=0.1):
+ entries = []
+ for index, image in enumerate(images):
+ file = f"{name}-{index}.png"
+ image.save(tmp_path / file)
+ entries.append({"file": file, "duration": duration})
+ path = tmp_path / f"{name}.json"
+ path.write_text(json.dumps({"kind": "sprite-gen-asset", "version": 1, "frames": entries}))
+ return path
+
+
+def write_scene(tmp_path, assets, layers, *, width=16, height=16, fps=10, duration=1.0, background=(0, 0, 0), name="scene.json"):
+ spec = {"kind": "sprite-gen-scene", "version": 1, "canvas": {"width": width, "height": height, "background": list(background)},
+ "fps": fps, "duration": duration, "assets": assets, "layers": layers}
+ path = tmp_path / name
+ path.write_text(json.dumps(spec))
+ return path
+
+
+def ramp_scene(tmp_path):
+ frames_asset(tmp_path, "ramp", [Image.new("RGBA", (16, 16), (i * 25, i * 25, i * 25, 255)) for i in range(10)])
+ return write_scene(tmp_path, {"ramp": "ramp.json"}, [{"id": "ramp", "asset": "ramp", "at": [8, 16]}])
+
+
+def bob_frames(xs=(4, 6, 8, 6)):
+ images = []
+ for x in xs:
+ image = Image.new("RGBA", (16, 16))
+ ImageDraw.Draw(image).rectangle((x, 4, x + 3, 11), fill=(220, 220, 220, 255))
+ images.append(image)
+ return images
+
+
+def test_ramp_wrap_pop_fails_the_seam_even_though_the_phase_closes(tmp_path):
+ report = inspect_scene(load_scene(ramp_scene(tmp_path)))
+ loop = report["loop"]
+ assert loop["adjacent_mae_mean"] == pytest.approx(18.75) and loop["adjacent_mae_max"] == pytest.approx(18.75)
+ assert loop["seam_mae"] == pytest.approx(168.75)
+ assert loop["seam_limit"] == pytest.approx(37.5)
+ assert loop["phase_closure_mae"] == 0 and loop["phase_closure_pass"] is True
+ assert loop["seam_pass"] is False and loop["pass"] is False
+ assert report["status"] == "needs-review"
+ assert any("loop wrap" in warning for warning in report["warnings"])
+
+
+def test_periodic_cycle_passes_seam_and_phase_closure(tmp_path):
+ frames_asset(tmp_path, "bob", bob_frames())
+ spec = write_scene(tmp_path, {"bob": "bob.json"}, [{"id": "bob", "asset": "bob", "at": [8, 16]}], duration=0.4)
+ loop = inspect_scene(load_scene(spec))["loop"]
+ assert loop["adjacent_mae_max"] > 0
+ assert loop["seam_mae"] == pytest.approx(loop["adjacent_mae_max"])
+ assert loop["phase_closure_mae"] == 0
+ assert loop["pass"] is True
+
+
+def test_moving_sprite_that_does_not_return_fails_phase_closure_not_the_seam(tmp_path):
+ frames_asset(tmp_path, "bob", bob_frames())
+ spec = write_scene(tmp_path, {"bob": "bob.json"}, [{"id": "bob", "asset": "bob", "at": [2, 16], "velocity": [10, 0]}], duration=0.4)
+ report = inspect_scene(load_scene(spec))
+ assert report["loop"]["phase_closure_pass"] is False and report["loop"]["pass"] is False
+ assert any("end-to-start" in warning for warning in report["warnings"])
+
+
[email protected]("velocity, closes", [([16, 0], True), ([10, 0], False)])
+def test_scrolling_background_closes_only_when_it_travels_whole_periods(tmp_path, velocity, closes):
+ strip = Image.new("RGBA", (16, 4))
+ for x in range(16):
+ ImageDraw.Draw(strip).line((x, 0, x, 3), fill=(x * 16, 40, 200 - x * 12, 255))
+ strip.save(tmp_path / "strip.png")
+ spec = write_scene(tmp_path, {"strip": "strip.png"}, [{"id": "ground", "asset": "strip", "at": [0, 16], "repeat_x": True, "velocity": velocity}])
+ report = inspect_scene(load_scene(spec))
+ # 16 px/s over one second is exactly one period: the wrap is an ordinary
+ # one-frame scroll step. 10 px/s leaves a 6 px jump at the wrap, which both
+ # the phase closure and the seam report.
+ assert report["loop"]["phase_closure_pass"] is closes
+ assert report["loop"]["seam_pass"] is closes
+ assert report["loop"]["pass"] is closes
+ assert report["tile_joins"]["ground"]["axis"] == "x" and report["tile_joins"]["ground"]["period"] == 16
+ assert report["clipping"]["ground"]["side_frames"] == 0 and report["clipping"]["ground"]["offscreen_frames"] == 0
+
+
+def test_static_scene_is_a_trivial_loop(tmp_path):
+ frames_asset(tmp_path, "still", bob_frames((4,)))
+ report = inspect_scene(load_scene(write_scene(tmp_path, {"still": "still.json"}, [{"id": "s", "asset": "still", "at": [8, 16]}])))
+ assert report["loop"] == {"seam_mae": 0.0, "adjacent_mae_mean": 0.0, "adjacent_mae_max": 0.0, "seam_limit": 1.0, "seam_pass": True,
+ "phase_closure_mae": 0.0, "phase_closure_pass": True, "pass": True}
+ assert report["status"] == "measured" and report["warnings"] == []
+ assert report["visual_review_required"] is True
+
+
+def test_offscreen_partially_clipped_and_empty_frames_are_reported_separately(tmp_path):
+ frames_asset(tmp_path, "box", bob_frames((6,)))
+ blank = Image.new("RGBA", (16, 16))
+ frames_asset(tmp_path, "blink", [bob_frames((6,))[0], blank, blank])
+ spec = write_scene(tmp_path, {"box": "box.json", "blink": "blink.json"}, [
+ {"id": "gone", "asset": "box", "at": [8, -50]},
+ {"id": "cut", "asset": "box", "at": [8, 8]},
+ {"id": "blink", "asset": "blink", "at": [8, 16]},
+ ], duration=0.3)
+ report = inspect_scene(load_scene(spec))
+ assert report["clipping"]["gone"] == {"top_frames": 0, "bottom_frames": 0, "side_frames": 0, "offscreen_frames": 3,
+ "empty_frames": 0, "minimum_top_y": -62.0}
+ assert report["clipping"]["cut"]["top_frames"] == 3 and report["clipping"]["cut"]["offscreen_frames"] == 0
+ assert report["clipping"]["cut"]["minimum_top_y"] == -4.0
+ assert report["clipping"]["blink"]["empty_frames"] == 2 and report["clipping"]["blink"]["offscreen_frames"] == 0
+ assert report["status"] == "needs-review"
+ assert any(warning.endswith("gone") for warning in report["warnings"])
+ assert any("viewport top or bottom" in warning for warning in report["warnings"])
+
+
+def test_key_like_colours_are_counted_and_flagged(tmp_path):
+ frames_asset(tmp_path, "green", [Image.new("RGBA", (4, 4), (0, 255, 0, 255))])
+ report = inspect_scene(load_scene(write_scene(tmp_path, {"green": "green.json"}, [{"id": "g", "asset": "green", "at": [8, 16]}], duration=0.1)))
+ assert report["key_like_pixels"] == {"green": 16, "magenta": 0}
+ assert any("key-like" in warning for warning in report["warnings"])
+ assert report["sources"]["green"]["edge_contact"][0] == {"top": 4, "bottom": 4, "left": 4, "right": 4}
+
+
+def test_run_publishes_the_report_under_the_writer_lock_and_releases_it(tmp_path, monkeypatch, capsys):
+ spec = ramp_scene(tmp_path)
+ out = tmp_path / "reports" / "inspection.json"
+ calls = []
+ real_acquire, real_write, real_release = module.acquire_run_dir_lock, module.atomic_write_set, module.release_run_dir_lock
+
+ def acquire(directory, owner):
+ calls.append(("lock", owner))
+ return real_acquire(directory, owner)
+
+ def write(payloads):
+ assert calls == [("lock", "scene-inspect")] and list(payloads) == [out]
+ assert (out.parent / runio.LOCK_FILENAME).exists()
+ calls.append(("write",))
+ real_write(payloads)
+
+ def release(directory):
+ calls.append(("release",))
+ real_release(directory)
+
+ monkeypatch.setattr(module, "acquire_run_dir_lock", acquire)
+ monkeypatch.setattr(module, "atomic_write_set", write)
+ monkeypatch.setattr(module, "release_run_dir_lock", release)
+ assert run(spec, out=out, require_loop=True) == 1
+ assert calls == [("lock", "scene-inspect"), ("write",), ("release",)]
+ assert json.loads(out.read_text()) == json.loads(capsys.readouterr().out)
+ assert not (out.parent / runio.LOCK_FILENAME).exists()
+ calls.clear()
+ assert run(spec, out=out) == 0
+ assert calls == [("lock", "scene-inspect"), ("write",), ("release",)]
+
+
[email protected]("target", [".sprite-gen.lock", "reports/.sprite-gen.lock", ".out.sg-rwlock", "scene.json", "ramp-3.png",
+ "spec-symlink.json", "asset-hardlink.png", "a-directory", "ramp-0.png/report.json"])
+def test_run_refuses_reserved_names_scene_inputs_and_their_aliases(tmp_path, capsys, target):
+ spec = ramp_scene(tmp_path)
+ out = tmp_path / target
+ if target == "spec-symlink.json":
+ out.symlink_to(spec)
+ elif target == "asset-hardlink.png":
+ os.link(tmp_path / "ramp-1.png", out)
+ elif target == "a-directory":
+ out.mkdir()
+ before = {p: p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()}
+ with pytest.raises(SystemExit, match="scene-inspect: inspection output"):
+ run(spec, out=out)
+ assert capsys.readouterr().out == ""
+ assert {p: p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} == before
+ assert not list(tmp_path.rglob(runio.LOCK_FILENAME))
+
+
+def test_output_path_is_resolved_and_checked_before_rendering(tmp_path):
+ scene = load_scene(ramp_scene(tmp_path))
+ assert output_path(tmp_path / "reports" / "x.json", scene) == (tmp_path / "reports" / "x.json").resolve()
+ with pytest.raises(ValueError, match="reserved lock name"):
+ output_path(tmp_path / runio.LOCK_FILENAME, scene)
+
+
+def test_run_respects_another_writers_live_lock_without_publishing(tmp_path, capsys):
+ spec = ramp_scene(tmp_path)
+ reports = tmp_path / "reports"
+ reports.mkdir()
+ lock = reports / runio.LOCK_FILENAME
+ lock.write_text(json.dumps({"owner": "synthetic-other-writer", "pid": os.getpid()}))
+ before = lock.read_bytes()
+ with pytest.raises(SystemExit, match="locked by synthetic-other-writer"):
+ run(spec, out=reports / "inspection.json")
+ assert capsys.readouterr().out == ""
+ assert list(reports.iterdir()) == [lock] and lock.read_bytes() == before
+
+
+def test_stdout_only_run_never_locks_or_writes(tmp_path, capsys):
+ spec = ramp_scene(tmp_path)
+ before = sorted(p.name for p in tmp_path.iterdir())
+ assert run(spec) == 0
+ assert json.loads(capsys.readouterr().out)["loop"]["pass"] is False
+ assert sorted(p.name for p in tmp_path.iterdir()) == before
+
+
+def test_module_entrypoint_reports_and_signals_a_failed_loop(tmp_path):
+ spec = ramp_scene(tmp_path)
+ out = tmp_path / "inspection.json"
+ result = subprocess.run([sys.executable, "-m", "sprite_gen.scene.inspect_scene", "--spec", str(spec), "--out", str(out), "--require-loop"],
+ capture_output=True, text=True, check=False)
+ assert result.returncode == 1, result.stderr
+ report = json.loads(result.stdout)
+ assert report == json.loads(out.read_text())
+ assert report["kind"] == "sprite-gen-scene-inspection" and report["loop"]["seam_pass"] is False
+ assert not (tmp_path / runio.LOCK_FILENAME).exists()
diff --git a/tests/scene/test_model.py b/tests/scene/test_model.py
new file mode 100644
index 0000000..5056e45
--- /dev/null
+++ b/tests/scene/test_model.py
@@ -0,0 +1,206 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Scene specs: timing, placement defaults, planes and stride binding to the measured sequence."""
+
+import hashlib
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image, ImageDraw
+
+from sprite_gen.qa.motion import analyze_motion
+from sprite_gen.scene import model
+from sprite_gen.scene.model import bound_stride, load_scene
+from sprite_gen.spec.assets import load_asset
+
+
+FOOT_BOX = (8, 25, 34, 12)
+
+
+def sha(path):
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
+
+
+def atlas(tmp_path):
+ sheet = Image.new("RGBA", (48 * 5, 40))
+ for index, x in enumerate((24, 22, 20, 18, 16)):
+ draw = ImageDraw.Draw(sheet)
+ draw.rectangle((48 * index + 15, 5, 48 * index + 30, 20), fill="white")
+ draw.rectangle((48 * index + x, 30, 48 * index + x + 3, 32), fill="white")
+ sheet.save(tmp_path / "atlas.png")
+ rects = [{"x": 48 * i, "y": 0, "w": 48, "h": 40} for i in range(5)]
+ path = tmp_path / "atlas.json"
+ path.write_text(json.dumps({
+ "sprite_sheet_alpha": "atlas.png",
+ "frame_layout": {"rows": {"walk": rects, "idle": [rects[0]] * 5}},
+ "animation": {"rows": {s: {"fps": 10, "durations_ms": [100] * 5, "loop": True} for s in ("walk", "idle")}},
+ }))
+ return path
+
+
+def motion_report(tmp_path, name="walk.motion.json", **load):
+ report = analyze_motion(load_asset(tmp_path / "atlas.json", **load), contacts="0:4", foot_box=FOOT_BOX)
+ assert report["stride_verified"] is True
+ path = tmp_path / name
+ path.write_text(json.dumps(report))
+ return path
+
+
+def scene(tmp_path, layers=None, **overrides):
+ spec = {"kind": "sprite-gen-scene", "version": 1, "canvas": {"width": 48, "height": 40, "background": [0, 0, 0]},
+ "fps": 10, "duration": 0.5, "assets": {"walk": {"source": "atlas.json", "state": "walk"}},
+ "layers": layers if layers is not None else [{"id": "hero", "asset": "walk", "at": [24, 40]}]}
+ spec.update(overrides)
+ path = tmp_path / "scene.json"
+ path.write_text(json.dumps(spec))
+ return path
+
+
+def test_layers_carry_defaults_raster_size_and_z_order(tmp_path):
+ atlas(tmp_path)
+ loaded = load_scene(scene(tmp_path, layers=[
+ {"id": "front", "asset": "walk", "at": [10, 40], "z": 5},
+ {"id": "back", "asset": "walk", "at": [20, 40], "z": -1, "scale": 0.33, "opacity": 0.5, "loop": False},
+ ], assets={"walk": {"source": "atlas.json", "state": "walk"}}))
+ assert [layer.id for layer in loaded.layers] == ["back", "front"]
+ front, back = loaded.layers[1], loaded.layers[0]
+ assert front.velocity == (0, 0) and front.scale == 1 and front.raster_size == (48, 40)
+ assert front.opacity == 1 and front.loop is True and front.plane is None and front.playback_rate == 1
+ assert back.raster_size == (16, 13)
+ assert back.opacity == 0.5 and back.loop is False
+ assert loaded.frame_count == 5 and loaded.background == (0, 0, 0, 255)
+ assert loaded.spec["canvas"]["background"] == [0, 0, 0]
+ assert loaded.source_fingerprints == {str(p.resolve()): sha(p) for p in (tmp_path / "scene.json", tmp_path / "atlas.json", tmp_path / "atlas.png")}
+
+
+def test_plane_velocity_adds_to_layer_velocity(tmp_path):
+ atlas(tmp_path)
+ loaded = load_scene(scene(tmp_path, planes={"ground": {"velocity": [-30, 0]}},
+ layers=[{"id": "hero", "asset": "walk", "at": [24, 40], "velocity": [5, 2], "plane": "ground"}]))
+ assert loaded.layers[0].velocity == (-25, 2)
+ with pytest.raises(ValueError, match="unknown plane"):
+ load_scene(scene(tmp_path, layers=[{"id": "hero", "asset": "walk", "at": [24, 40], "plane": "sky"}]))
+
+
+def test_stride_applies_actual_raster_scale_playback_rate_and_explicit_direction(tmp_path):
+ atlas(tmp_path)
+ report = motion_report(tmp_path, state="walk")
+ speed = json.loads(report.read_text())["stride_px_per_second"]
+ assert speed == pytest.approx(20)
+ loaded = load_scene(scene(tmp_path, layers=[{"id": "hero", "asset": "walk", "at": [24, 40], "scale": 0.33,
+ "playback_rate": 2, "stride": {"report": "walk.motion.json", "direction": "left"}}]))
+ layer = loaded.layers[0]
+ assert layer.raster_size == (16, 13)
+ assert layer.velocity == (pytest.approx(-20 * (16 / 48) * 2), 0)
+ assert layer.velocity[0] != pytest.approx(-20 * 0.33 * 2)
+ assert loaded.source_fingerprints[str(report.resolve())] == sha(report)
+ right = load_scene(scene(tmp_path, layers=[{"id": "hero", "asset": "walk", "at": [24, 40],
+ "stride": {"report": "walk.motion.json", "direction": "right"}}]))
+ assert right.layers[0].velocity == (pytest.approx(20), 0)
+
+
[email protected]("case, message", [
+ ("other-state", "another state, frame rate or anchor"),
+ ("fps-override", "another state, frame rate or anchor"),
+ ("anchor-override", "another state, frame rate or anchor"),
+ ("unverified", "unverified"),
+ ("stale-bytes", "stale or belongs to another asset"),
+ ("no-identity", "lacks its sequence identity"),
+ ("not-a-report", "sprite-gen-motion-report"),
+])
+def test_stride_rejects_reports_of_any_other_selection_of_the_same_files(tmp_path, case, message):
+ atlas(tmp_path)
+ if case == "other-state":
+ report = motion_report(tmp_path, state="walk")
+ spec = scene(tmp_path, assets={"walk": {"source": "atlas.json", "state": "idle"}},
+ layers=[{"id": "hero", "asset": "walk", "at": [24, 40], "stride": {"report": report.name, "direction": "right"}}])
+ else:
+ load = {"state": "walk"}
+ if case == "fps-override":
+ load["fps"] = 5
+ if case == "anchor-override":
+ load["anchor"] = (24, 39)
+ report = motion_report(tmp_path, **load)
+ data = json.loads(report.read_text())
+ if case == "unverified":
+ data["stride_verified"] = False
+ if case == "no-identity":
+ del data["sequence"]
+ if case == "not-a-report":
+ data["kind"] = "sprite-gen-scene-inspection"
+ report.write_text(json.dumps(data))
+ if case == "stale-bytes":
+ with Image.open(tmp_path / "atlas.png") as sheet:
+ sheet.convert("RGBA").save(tmp_path / "atlas.png", optimize=True)
+ assert sha(tmp_path / "atlas.png") != data["source_fingerprints"][str((tmp_path / "atlas.png").resolve())]
+ spec = scene(tmp_path, layers=[{"id": "hero", "asset": "walk", "at": [24, 40], "stride": {"report": report.name, "direction": "right"}}])
+ with pytest.raises(ValueError, match=message):
+ load_scene(spec)
+
+
+def test_stride_report_and_velocity_are_exclusive_and_direction_is_required(tmp_path):
+ atlas(tmp_path)
+ report = motion_report(tmp_path, state="walk")
+ with pytest.raises(ValueError, match="not both"):
+ load_scene(scene(tmp_path, layers=[{"id": "hero", "asset": "walk", "velocity": [1, 0], "stride": {"report": report.name, "direction": "right"}}]))
+ with pytest.raises(ValueError, match="explicit left/right"):
+ load_scene(scene(tmp_path, layers=[{"id": "hero", "asset": "walk", "stride": {"report": report.name}}]))
+ with pytest.raises(ValueError, match="explicit left/right"):
+ load_scene(scene(tmp_path, layers=[{"id": "hero", "asset": "walk", "stride": {"report": report.name, "direction": "up"}}]))
+ with pytest.raises(ValueError, match="unknown stride fields"):
+ load_scene(scene(tmp_path, layers=[{"id": "hero", "asset": "walk", "stride": {"report": report.name, "direction": "right", "flip": True}}]))
+
+
+def test_bound_stride_is_the_single_gate_for_measured_speed(tmp_path):
+ atlas(tmp_path)
+ walk = load_asset(tmp_path / "atlas.json", state="walk")
+ report = json.loads(json.dumps(analyze_motion(walk, contacts="0:4", foot_box=FOOT_BOX)))
+ assert bound_stride(report, walk) == pytest.approx(20)
+ with pytest.raises(ValueError):
+ bound_stride(report, load_asset(tmp_path / "atlas.json", state="idle"))
+ with pytest.raises(ValueError):
+ bound_stride({**report, "stride_px_per_second": 0}, walk)
+
+
+def test_scene_and_report_identity_are_the_parsed_bytes(tmp_path, monkeypatch):
+ atlas(tmp_path)
+ report = motion_report(tmp_path, state="walk")
+ spec = scene(tmp_path, layers=[{"id": "hero", "asset": "walk", "at": [24, 40], "stride": {"report": report.name, "direction": "right"}}])
+ original_hashes = {str(p.resolve()): sha(p) for p in (spec, report)}
+ original = model.read_json
+
+ def read_then_rewrite(path):
+ document, digest = original(path)
+ Path(path).write_text(json.dumps(document, indent=4))
+ return document, digest
+
+ monkeypatch.setattr(model, "read_json", read_then_rewrite)
+ loaded = load_scene(spec)
+ for path, digest in original_hashes.items():
+ assert loaded.source_fingerprints[path] == digest
+ assert sha(path) != digest
+ assert loaded.layers[0].velocity == (pytest.approx(20), 0)
+
+
[email protected]("overrides, message", [
+ ({"kind": "scene"}, "kind sprite-gen-scene"),
+ ({"extra": 1}, "unknown scene fields"),
+ ({"duration": 0.55}, "integer"),
+ ({"duration": 1e-10}, "integer"),
+ ({"fps": 200, "duration": 1}, "fps <= 120"),
+ ({"canvas": {"width": 48.5, "height": 40}}, "integer dimensions"),
+ ({"canvas": {"width": 48, "height": 40, "background": [0, 0, 300]}}, "RGB or RGBA"),
+ ({"assets": {}}, "nonempty"),
+ ({"layers": []}, "nonempty"),
+ ({"layers": [{"id": "hero", "asset": "walk"}, {"id": "hero", "asset": "walk"}]}, "unique"),
+ ({"layers": [{"id": "hero", "asset": "ghost"}]}, "unknown asset"),
+ ({"layers": [{"id": "hero", "asset": "walk", "opacity": 1.5}]}, "0..1"),
+ ({"layers": [{"id": "hero", "asset": "walk", "repeat_x": True, "period": 49}]}, "within the source width"),
+ ({"layers": [{"id": "hero", "asset": "walk", "repeat_x": "yes"}]}, "boolean"),
+ ({"layers": [{"id": "hero", "asset": "walk", "scale": 0}]}, "positive"),
+ ({"light": {"angle": 3}}, "unknown light fields"),
+])
+def test_invalid_scene_specs_are_rejected(tmp_path, overrides, message):
+ atlas(tmp_path)
+ with pytest.raises(ValueError, match=message):
+ load_scene(scene(tmp_path, **overrides))
diff --git a/tests/scene/test_render.py b/tests/scene/test_render.py
new file mode 100644
index 0000000..8da98cc
--- /dev/null
+++ b/tests/scene/test_render.py
@@ -0,0 +1,320 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Deterministic placement, staged publication and explicit encoding of scene renders."""
+
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+import pytest
+from PIL import Image, ImageDraw
+
+from sprite_gen.scene import render
+from sprite_gen.scene.model import load_scene
+from sprite_gen.scene.render import Renderer, render_scene
+from sprite_gen.spec import assets, runio
+
+
+HAS_FFMPEG = shutil.which("ffmpeg") is not None
+RED, GREEN, BLUE, BLACK = (200, 30, 30, 255), (30, 200, 30, 255), (30, 30, 200, 255), (0, 0, 0, 255)
+
+
+def square(path, color=RED, size=(4, 4)):
+ Image.new("RGBA", size, color).save(path)
+ return path
+
+
+def write_scene(tmp_path, layers, *, width=16, height=12, fps=10, duration=0.5, background=(0, 0, 0), **extra):
+ assets_block = extra.pop("assets", None) or {"red": "red.png"}
+ if "red.png" in json.dumps(assets_block) and not (tmp_path / "red.png").exists():
+ square(tmp_path / "red.png")
+ spec = {"kind": "sprite-gen-scene", "version": 1, "canvas": {"width": width, "height": height, "background": list(background)},
+ "fps": fps, "duration": duration, "assets": assets_block, "layers": layers, **extra}
+ path = tmp_path / "scene.json"
+ path.write_text(json.dumps(spec))
+ return path
+
+
+def snapshot(directory):
+ return {str(p.relative_to(directory)): p.read_bytes() for p in Path(directory).rglob("*") if p.is_file()}
+
+
+def test_anchor_velocity_camera_parallax_and_z_order_place_pixels(tmp_path):
+ square(tmp_path / "green.png", GREEN, (2, 2))
+ spec = write_scene(tmp_path, [
+ {"id": "front", "asset": "green", "at": [8, 12], "z": 1},
+ {"id": "hero", "asset": "red", "at": [8, 12], "velocity": [10, 0], "parallax": 0.5},
+ ], assets={"red": "red.png", "green": "green.png"}, camera={"at": [2, 0], "velocity": [4, 0]})
+ renderer = Renderer(load_scene(spec))
+ frame0 = renderer.frame(0)
+ # Bottom-centre anchor: a 4x4 red square at (8, 12) covers x 6..9, y 8..11; camera at 2 with parallax .5 shifts it left by 1.
+ assert frame0.getpixel((5, 8)) == RED and frame0.getpixel((8, 11)) == RED and frame0.getpixel((9, 8)) == BLACK
+ # The green 2x2 layer (parallax 1, so the camera shifts it by 2) sits above the red one.
+ assert frame0.getpixel((5, 10)) == GREEN and frame0.getpixel((6, 11)) == GREEN and frame0.getpixel((7, 10)) == RED
+ frame = renderer.frame(0.3)
+ # 10 px/s minus half the 4 px/s camera velocity: +2.4 px after 0.3 s, rounded to 2.
+ assert frame.getpixel((7, 8)) == RED and frame.getpixel((10, 8)) == RED and frame.getpixel((11, 8)) == BLACK
+ plate = renderer.frame(0, only="hero")
+ assert plate.getpixel((0, 0)) == (0, 0, 0, 0) and plate.getpixel((7, 10)) == RED
+
+
+def test_repeat_x_tiles_the_period_across_the_canvas_and_wraps_offsets(tmp_path):
+ strip = Image.new("RGBA", (6, 3))
+ ImageDraw.Draw(strip).rectangle((0, 0, 1, 2), fill=BLUE)
+ strip.save(tmp_path / "strip.png")
+ spec = write_scene(tmp_path, [{"id": "ground", "asset": "strip", "at": [0, 12], "repeat_x": True, "period": 3, "velocity": [1, 0]}],
+ assets={"strip": "strip.png"}, duration=1)
+ renderer = Renderer(load_scene(spec))
+ row = [renderer.frame(0).getpixel((x, 10)) for x in range(16)]
+ assert row == [BLUE, BLUE, BLACK] * 5 + [BLUE]
+ row = [renderer.frame(0.9).getpixel((x, 10)) for x in range(16)]
+ # 0.9 px of travel rounds each copy one pixel to the right; the copy from the left wraps in.
+ assert row == [BLACK, BLUE, BLUE] * 5 + [BLACK]
+ frame, geometry = renderer.frame(0, geometry=True)
+ assert all(entry["repeat_x"] for entry in geometry) and any(entry["visible"] for entry in geometry)
+
+
+def test_geometry_reports_offscreen_copies_unclipped_and_empty_frames(tmp_path):
+ empty = tmp_path / "blank.png"
+ Image.new("RGBA", (4, 4)).save(empty)
+ spec = write_scene(tmp_path, [
+ {"id": "gone", "asset": "red", "at": [8, -100]},
+ {"id": "cut", "asset": "red", "at": [8, 2]},
+ {"id": "blank", "asset": "blank", "at": [8, 8]},
+ ], assets={"red": "red.png", "blank": "blank.png"})
+ _, geometry = Renderer(load_scene(spec)).frame(0, geometry=True)
+ by_id = {entry["id"]: entry for entry in geometry}
+ assert by_id["gone"] == {"id": "gone", "repeat_x": False, "bbox": [6, -104, 10, -100], "visible": False}
+ assert by_id["cut"] == {"id": "cut", "repeat_x": False, "bbox": [6, -2, 10, 2], "visible": True}
+ assert by_id["blank"] == {"id": "blank", "repeat_x": False, "bbox": None, "visible": False}
+
+
+def test_png_render_publishes_the_reported_set_atomically_and_leaves_inputs_alone(tmp_path):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12], "scale": 0.5}], fps=4, duration=1)
+ before = snapshot(tmp_path)
+ out = tmp_path / "out"
+ report = render_scene(spec, out, formats="png")
+ published = snapshot(out)
+ assert sorted(published) == sorted(report["files"])
+ assert set(report["files"]) == {"check-00000.png", "check-00001.png", "check-00002.png", "check-00003.png",
+ *(f"frames/frame-{i:05d}.png" for i in range(4)), "placement.json", "scene.report.json"}
+ assert json.loads(published["scene.report.json"]) == report
+ placement = json.loads(published["placement.json"])
+ assert placement["layers"][0]["raster_size"] == [2, 2] and placement["layers"][0]["scale"] == 0.5
+ assert placement["source_fingerprints"] == report["source_fingerprints"] == {
+ str(p.resolve()): hashlib.sha256(p.read_bytes()).hexdigest() for p in (spec, tmp_path / "red.png")}
+ assert report["encoding"] == {} and report["inspection"]["status"] == "measured"
+ with Image.open(out / "frames" / "frame-00000.png") as frame:
+ assert frame.size == (16, 12) and frame.getpixel((7, 10)) == RED and frame.getpixel((6, 10)) == BLACK
+ assert snapshot(tmp_path) == {**before, **{f"out/{k}": v for k, v in published.items()}}
+ assert not (out / runio.LOCK_FILENAME).exists()
+
+
+def test_export_layers_publishes_frame_zero_plates_and_records_it(tmp_path):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}])
+ out = tmp_path / "out"
+ report = render_scene(spec, out, formats="png", export_layers=True)
+ assert "layers/hero.png" in report["files"]
+ with Image.open(out / "layers" / "hero.png") as plate:
+ assert plate.getpixel((0, 0)) == (0, 0, 0, 0) and plate.getpixel((7, 10)) == RED
+ assert json.loads((out / "placement.json").read_text())["layer_plate_time"] == 0
+
+
[email protected]("formats, kwargs, message", [
+ ("png,mp4", {}, "even canvas dimensions"),
+ ("gif", {"gif_fps": 20}, "cannot exceed the scene fps"),
+ ("gif", {"gif_width": 40}, "gif_width"),
+ ("gif", {"gif_width": 0}, "gif_width"),
+ ("gif", {"gif_colors": 1}, "gif_colors"),
+ ("gif", {"gif_colors": 257}, "gif_colors"),
+ ("gif", {"gif_dither": "random"}, "gif_dither"),
+ ("gif", {"gif_max_bytes": 0}, "gif_max_bytes"),
+ ("webm", {}, "formats"),
+ ("", {}, "formats"),
+])
+def test_prerequisites_fail_before_any_output_exists_and_the_corrected_call_succeeds(tmp_path, formats, kwargs, message):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}], width=15)
+ out = tmp_path / "out"
+ before = snapshot(tmp_path)
+ with pytest.raises(ValueError, match=message):
+ render_scene(spec, out, formats=formats, **kwargs)
+ assert not out.exists()
+ assert snapshot(tmp_path) == before
+ assert render_scene(spec, out, formats="png")["frames"] == 5
+
+
[email protected]("formats", ["mp4", "gif", "png,gif"])
+def test_missing_ffmpeg_is_reported_before_any_directory_is_created(tmp_path, monkeypatch, formats):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}])
+ monkeypatch.setattr(render.shutil, "which", lambda name: None)
+ with pytest.raises(ValueError, match="ffmpeg is required"):
+ render_scene(spec, tmp_path / "out", formats=formats)
+ assert not (tmp_path / "out").exists()
+
+
+def test_transparent_background_cannot_encode_video_but_renders_png(tmp_path):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}], background=(0, 0, 0, 0))
+ for formats, message in (("mp4", "opaque"), ("gif", "opaque")):
+ with pytest.raises(ValueError, match=message):
+ render_scene(spec, tmp_path / "out", formats=formats)
+ assert not (tmp_path / "out").exists()
+ render_scene(spec, tmp_path / "out", formats="png")
+ with Image.open(tmp_path / "out" / "check-00000.png") as frame:
+ assert frame.getpixel((0, 0)) == (0, 0, 0, 0)
+
+
+def test_encoder_failure_leaves_no_output_no_lock_and_is_not_retried(tmp_path, monkeypatch):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}])
+ calls = []
+
+ def fail(args):
+ calls.append(args)
+ raise ValueError("ffmpeg failed: synthetic encoder failure")
+
+ monkeypatch.setattr(render, "_ffmpeg", fail)
+ monkeypatch.setattr(render.shutil, "which", lambda name: "/synthetic/ffmpeg")
+ out = tmp_path / "renders" / "out"
+ with pytest.raises(ValueError, match="synthetic encoder failure"):
+ render_scene(spec, out, formats="png,mp4")
+ assert len(calls) == 1
+ assert not out.exists()
+ assert (tmp_path / "renders").is_dir()
+ assert not list(tmp_path.rglob(runio.LOCK_FILENAME))
+ monkeypatch.undo()
+ assert render_scene(spec, out, formats="png")["frames"] == 5
+
+
+def test_staging_failure_keeps_a_preexisting_output_directory_empty_without_subdirectories(tmp_path, monkeypatch):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}])
+ out = tmp_path / "out"
+ out.mkdir()
+ fsync = runio.os.fsync
+ calls = []
+
+ def fail_third_staged_file(fd):
+ calls.append(fd)
+ if len(calls) == 3:
+ raise OSError("synthetic disk failure")
+ fsync(fd)
+
+ monkeypatch.setattr(runio.os, "fsync", fail_third_staged_file)
+ with pytest.raises(OSError, match="synthetic disk failure"):
+ render_scene(spec, out, formats="png", export_layers=True)
+ assert len(calls) == 3
+ assert out.is_dir() and list(out.iterdir()) == []
+ monkeypatch.undo()
+ assert "layers/hero.png" in render_scene(spec, out, formats="png", export_layers=True)["files"]
+
+
+def test_input_replaced_after_decoding_is_detected_and_nothing_is_published(tmp_path, monkeypatch):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [2, 4]}], width=4, height=4, fps=1, duration=1)
+ original = assets._read_bytes
+
+ def read_then_replace(path):
+ data = original(path)
+ if Path(path).name == "red.png":
+ square(Path(path), BLUE)
+ return data
+
+ monkeypatch.setattr(assets, "_read_bytes", read_then_replace)
+ out = tmp_path / "out"
+ with pytest.raises(ValueError, match="inputs changed during render"):
+ render_scene(spec, out, formats="png")
+ assert not out.exists()
+ monkeypatch.undo()
+ report = render_scene(spec, out, formats="png")
+ assert report["source_fingerprints"][str((tmp_path / "red.png").resolve())] == hashlib.sha256((tmp_path / "red.png").read_bytes()).hexdigest()
+ with Image.open(out / "check-00000.png") as frame:
+ assert frame.getpixel((2, 2)) == BLUE
+
+
[email protected]("problem", ["inputs-inside", "nonempty", "live-lock", "file"])
+def test_output_directory_rules_are_enforced_without_touching_the_destination(tmp_path, problem):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}])
+ out, message, expected = tmp_path / "out", "", ValueError
+ if problem == "inputs-inside":
+ out, message = tmp_path, "contains scene inputs"
+ elif problem == "nonempty":
+ out.mkdir()
+ (out / "previous.txt").write_text("keep me")
+ message = "must be empty"
+ elif problem == "live-lock":
+ out.mkdir()
+ (out / runio.LOCK_FILENAME).write_text(json.dumps({"owner": "synthetic-other-writer", "pid": os.getpid()}))
+ message, expected = "locked by synthetic-other-writer", SystemExit
+ else:
+ out.write_text("a file")
+ message = "must be a directory"
+ before = snapshot(tmp_path)
+ with pytest.raises(expected, match=message):
+ render_scene(spec, out, formats="png")
+ assert snapshot(tmp_path) == before
+
+
[email protected](not HAS_FFMPEG, reason="ffmpeg not installed")
+def test_gif_and_mp4_use_explicit_settings_with_source_fps_and_full_palette_by_default(tmp_path):
+ frames = []
+ for i in range(6):
+ image = Image.new("RGBA", (24, 20))
+ ImageDraw.Draw(image).rectangle((4 + i, 4, 10 + i, 16), fill=RED)
+ image.save(tmp_path / f"f{i}.png")
+ frames.append({"file": f"f{i}.png", "duration": 0.1})
+ (tmp_path / "walk.json").write_text(json.dumps({"kind": "sprite-gen-asset", "version": 1, "frames": frames}))
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "walk", "at": [32, 36]}], assets={"walk": "walk.json"},
+ width=64, height=40, fps=10, duration=0.6, background=(30, 60, 90))
+ report = render_scene(spec, tmp_path / "default", formats="gif,mp4")
+ assert report["encoding"]["gif"] == {"width": 64, "height": 40, "fps": 10.0, "colors": 256, "dither": "none", "frames": 6,
+ "bytes": (tmp_path / "default" / "scene.gif").stat().st_size, "max_bytes": 8_000_000}
+ assert report["encoding"]["mp4"]["codec"] == "libx264" and (tmp_path / "default" / "scene.mp4").stat().st_size == report["encoding"]["mp4"]["bytes"]
+ with Image.open(tmp_path / "default" / "scene.gif") as gif:
+ assert gif.n_frames == 6 and gif.size == (64, 40)
+ assert gif.info["duration"] == 100 and gif.info.get("loop") == 0
+ explicit = render_scene(spec, tmp_path / "explicit", formats="gif", gif_width=32, gif_fps=5, gif_colors=16, gif_dither="bayer")
+ assert explicit["encoding"]["gif"]["width"] == 32 and explicit["encoding"]["gif"]["height"] == 20
+ assert explicit["encoding"]["gif"]["frames"] == 3 and explicit["encoding"]["gif"]["colors"] == 16
+ assert explicit["encoding"]["gif"]["dither"] == "bayer"
+ with Image.open(tmp_path / "explicit" / "scene.gif") as gif:
+ assert gif.n_frames == 3 and gif.size == (32, 20) and gif.info["duration"] == 200
+
+
[email protected](not HAS_FFMPEG, reason="ffmpeg not installed")
+def test_gif_over_budget_fails_by_name_without_degrading_or_publishing(tmp_path, monkeypatch):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}], background=(30, 60, 90))
+ calls = []
+ original = render._ffmpeg
+ monkeypatch.setattr(render, "_ffmpeg", lambda args: calls.append(args) or original(args))
+ with pytest.raises(ValueError, match=r"over the 100 byte budget.*never reduced automatically"):
+ render_scene(spec, tmp_path / "out", formats="gif", gif_max_bytes=100)
+ assert len(calls) == 2
+ assert not (tmp_path / "out").exists()
+
+
+def test_parser_exposes_the_gif_controls_with_documented_defaults():
+ parser = argparse.ArgumentParser()
+ render.add_arguments(parser)
+ args = parser.parse_args(["--spec", "s.json", "--out-dir", "o"])
+ assert (args.formats, args.gif_max_bytes, args.gif_width, args.gif_fps, args.gif_colors, args.gif_dither, args.export_layers) == \
+ ("mp4,gif", 8_000_000, None, None, 256, "none", False)
+ args = parser.parse_args(["--spec", "s.json", "--out-dir", "o", "--gif-width", "320", "--gif-fps", "12", "--gif-colors", "64", "--gif-dither", "sierra2_4a"])
+ assert (args.gif_width, args.gif_fps, args.gif_colors, args.gif_dither) == (320, 12.0, 64, "sierra2_4a")
+ with pytest.raises(SystemExit):
+ parser.parse_args(["--spec", "s.json", "--out-dir", "o", "--gif-dither", "random"])
+ assert render.GIF_MAX_WIDTH_DEFAULT == 640
+
+
+def test_module_entrypoint_renders_and_reports_failures_by_name(tmp_path):
+ spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}], width=15)
+ out = tmp_path / "out"
+ result = subprocess.run([sys.executable, "-m", "sprite_gen.scene.render", "--spec", str(spec), "--out-dir", str(out), "--formats", "png"],
+ capture_output=True, text=True, check=False)
+ assert result.returncode == 0, result.stderr
+ summary = json.loads(result.stdout)
+ assert summary["frames"] == 5 and summary["inspection_status"] == "measured" and "placement.json" in summary["files"]
+ failed = subprocess.run([sys.executable, "-m", "sprite_gen.scene.render", "--spec", str(spec), "--out-dir", str(tmp_path / "video"), "--formats", "mp4"],
+ capture_output=True, text=True, check=False)
+ assert failed.returncode != 0 and "scene-render: MP4 requires even canvas dimensions" in failed.stderr
+ assert not (tmp_path / "video").exists()
diff --git a/tests/spec/test_assets.py b/tests/spec/test_assets.py
new file mode 100644
index 0000000..2b4dc2b
--- /dev/null
+++ b/tests/spec/test_assets.py
@@ -0,0 +1,318 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The shared read-only adapter: real writer formats, one-read snapshots, bound fingerprints."""
+
+import hashlib
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image, ImageDraw
+
+from conftest import run_script
+from sprite_gen.spec import assets
+from sprite_gen.spec.assets import FrameSequence, load_asset, same_identity, sequence_identity
+from sprite_gen.video.loop import build_strip
+
+
+def sha(path):
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
+
+
+def walk_frames(xs=(24, 22, 20, 18, 16)):
+ frames = []
+ for x in xs:
+ frame = Image.new("RGBA", (48, 40))
+ draw = ImageDraw.Draw(frame)
+ draw.rectangle((15, 5, 30, 20), fill="white")
+ draw.rectangle((x, 30, x + 3, y := 32), fill=(200, 40, 40, 255))
+ frames.append(frame)
+ return frames
+
+
+def descriptor(tmp_path, *, anchor=None, durations=(0.1, 0.1, 0.1, 0.1, 0.1), files=None):
+ entries = []
+ for index, (frame, duration) in enumerate(zip(walk_frames(), durations)):
+ name = f"foot-{index}.png" if files is None else files[index]
+ path = tmp_path / name
+ if not path.exists():
+ frame.save(path)
+ entries.append({"file": name, "duration": duration})
+ data = {"kind": "sprite-gen-asset", "version": 1, "frames": entries}
+ if anchor is not None:
+ data["anchor"] = anchor
+ path = tmp_path / "walk.json"
+ path.write_text(json.dumps(data))
+ return path
+
+
+def atlas(tmp_path, states=("walk", "idle")):
+ frames = walk_frames()
+ sheet = Image.new("RGBA", (48 * 5, 40))
+ for index, frame in enumerate(frames):
+ sheet.paste(frame, (48 * index, 0))
+ sheet.save(tmp_path / "atlas.png")
+ rects = [{"x": 48 * i, "y": 0, "w": 48, "h": 40} for i in range(5)]
+ rows = {"walk": rects, "idle": [rects[0]] * 3}
+ path = tmp_path / "atlas.json"
+ path.write_text(json.dumps({
+ "sprite_sheet_alpha": "atlas.png", "game_input": "atlas.png",
+ "frame_layout": {"rows": {s: rows[s] for s in states}},
+ "animation": {"rows": {s: {"fps": 10, "durations_ms": [100] * len(rows[s]), "loop": True} for s in states}},
+ }))
+ return path
+
+
+def test_png_single_frame_defaults_to_one_second_and_bottom_centre(tmp_path):
+ source = tmp_path / "still.png"
+ walk_frames()[0].save(source)
+ seq = load_asset(source)
+ assert len(seq.frames) == 1 and seq.frames[0].mode == "RGBA"
+ assert seq.durations == (1.0,)
+ assert seq.anchor == (24.0, 40)
+ assert seq.metadata == {"source": str(source.resolve()), "anchor_source": "bottom-center default"}
+ assert seq.fingerprints() == {str(source.resolve()): sha(source)}
+ with pytest.raises(ValueError, match="state"):
+ load_asset(source, state="walk")
+
+
+def test_descriptor_reads_ordered_frames_durations_anchor_and_every_file_hash(tmp_path):
+ source = descriptor(tmp_path, anchor=[12, 38], durations=(0.05, 0.15, 0.1, 0.1, 0.4))
+ seq = load_asset(source)
+ assert seq.durations == (0.05, 0.15, 0.1, 0.1, 0.4)
+ assert seq.duration == pytest.approx(0.8)
+ assert seq.anchor == (12.0, 38.0)
+ assert seq.metadata["anchor_source"] == "asset metadata"
+ expected = walk_frames()
+ for frame, original in zip(seq.frames, expected):
+ assert frame.tobytes() == original.tobytes()
+ assert seq.fingerprints() == {str((tmp_path / name).resolve()): sha(tmp_path / name)
+ for name in ["walk.json", *(f"foot-{i}.png" for i in range(5))]}
+ assert load_asset(source, anchor=(1, 2)).metadata["anchor_source"] == "explicit override"
+ with pytest.raises(ValueError, match="state"):
+ load_asset(source, state="walk")
+
+
+def test_descriptor_referencing_one_file_twice_reads_it_once(tmp_path, monkeypatch):
+ source = descriptor(tmp_path, files=["a.png", "a.png", "b.png", "b.png", "b.png"])
+ reads = []
+ original = assets._read_bytes
+
+ def counting_read(path):
+ reads.append(Path(path).name)
+ return original(path)
+
+ monkeypatch.setattr(assets, "_read_bytes", counting_read)
+ seq = load_asset(source)
+ assert len(seq.frames) == 5
+ assert sorted(reads) == ["a.png", "b.png", "walk.json"]
+ assert set(seq.fingerprints()) == {str((tmp_path / n).resolve()) for n in ("walk.json", "a.png", "b.png")}
+
+
+def test_real_loop_strip_writer_output_is_read_back_cell_by_cell(tmp_path):
+ frames = walk_frames()
+ strip, meta = build_strip(frames, cycle_seconds=0.5)
+ strip.save(tmp_path / "walk.strip.png")
+ (tmp_path / "walk.strip.json").write_text(json.dumps(meta))
+ seq = load_asset(tmp_path / "walk.strip.json")
+ assert seq.size == (meta["w"], meta["h"])
+ assert len(seq.frames) == meta["frames"]
+ assert seq.durations == (meta["delay_ms"] / 1000,) * meta["frames"]
+ assert seq.duration == pytest.approx(0.5)
+ assert seq.metadata["loop"] is True
+ assert seq.anchor == (meta["w"] / 2, meta["h"])
+ for index, frame in enumerate(seq.frames):
+ assert frame.tobytes() == strip.crop((index * meta["w"], 0, (index + 1) * meta["w"], meta["h"])).tobytes()
+ assert set(seq.fingerprints()) == {str((tmp_path / n).resolve()) for n in ("walk.strip.json", "walk.strip.png")}
+ with pytest.raises(ValueError, match="state"):
+ load_asset(tmp_path / "walk.strip.json", state="walk")
+ strip.crop((0, 0, strip.width - 1, strip.height)).save(tmp_path / "walk.strip.png")
+ with pytest.raises(ValueError, match="disagrees"):
+ load_asset(tmp_path / "walk.strip.json")
+
+
+def test_real_runtime_atlas_writer_output_keeps_rects_and_timing(fixture_run_dir):
+ for script in ("extract_sprite_row_frames.py", "compose_sprite_atlas.py"):
+ proc = run_script(script, "--run-dir", str(fixture_run_dir))
+ assert proc.returncode == 0, proc.stdout + proc.stderr
+ manifest_path = fixture_run_dir / "manifest.json"
+ manifest = json.loads(manifest_path.read_text())
+ with pytest.raises(ValueError, match="--state is required"):
+ load_asset(manifest_path)
+ with pytest.raises(ValueError, match="unknown asset state"):
+ load_asset(manifest_path, state="fly")
+ with Image.open(fixture_run_dir / manifest["sprite_sheet_alpha"]) as sheet:
+ sheet = sheet.convert("RGBA")
+ for state, rects in manifest["frame_layout"]["rows"].items():
+ seq = load_asset(manifest_path, state=state)
+ timing = manifest["animation"]["rows"][state]
+ assert len(seq.frames) == len(rects)
+ assert seq.durations == tuple(ms / 1000 for ms in timing["durations_ms"])
+ assert seq.metadata["state"] == state
+ assert seq.metadata["loop"] is bool(timing["loop"])
+ for frame, rect in zip(seq.frames, rects):
+ assert frame.size == (rect["w"], rect["h"])
+ assert frame.tobytes() == sheet.crop((rect["x"], rect["y"], rect["x"] + rect["w"], rect["y"] + rect["h"])).tobytes()
+ assert seq.fingerprints() == {str(manifest_path.resolve()): sha(manifest_path),
+ str((fixture_run_dir / manifest["sprite_sheet_alpha"]).resolve()): sha(fixture_run_dir / manifest["sprite_sheet_alpha"])}
+
+
+def test_fps_override_replaces_timing_and_is_part_of_identity(tmp_path):
+ source = atlas(tmp_path)
+ native = load_asset(source, state="walk")
+ faster = load_asset(source, state="walk", fps=5)
+ assert native.durations == (0.1,) * 5
+ assert faster.durations == (0.2,) * 5
+ assert faster.metadata["fps_override"] == 5.0
+ assert "fps_override" not in native.metadata
+ assert native.fingerprints() == faster.fingerprints()
+ assert sequence_identity(native) != sequence_identity(faster)
+
+
+def test_identity_separates_states_rates_and_anchors_of_one_file_set(tmp_path):
+ source = atlas(tmp_path)
+ walk = load_asset(source, state="walk")
+ idle = load_asset(source, state="idle")
+ assert walk.fingerprints() == idle.fingerprints()
+ identity = json.loads(json.dumps(walk.identity()))
+ assert identity == {"source": str(source.resolve()), "state": "walk", "fps_override": None, "frame_count": 5,
+ "size": [48, 40], "anchor_px": [24.0, 40.0], "durations_seconds": [0.1] * 5}
+ assert same_identity(identity, walk)
+ assert not same_identity(identity, idle)
+ assert not same_identity(identity, load_asset(source, state="walk", fps=10.0001))
+ assert same_identity(identity, load_asset(source, state="walk", fps=10))
+ assert not same_identity(identity, load_asset(source, state="walk", anchor=(24, 39)))
+ assert not same_identity({**identity, "durations_seconds": [0.1] * 4 + [0.2]}, walk)
+ assert not same_identity({k: v for k, v in identity.items() if k != "state"}, walk)
+ assert not same_identity(None, walk)
+
+
+def test_fingerprints_describe_the_decoded_bytes_not_the_file_now_on_disk(tmp_path):
+ source = tmp_path / "swap.png"
+ Image.new("RGBA", (4, 4), "red").save(source)
+ red_hash = sha(source)
+ loaded = load_asset(source)
+ Image.new("RGBA", (4, 4), "blue").save(source)
+ assert loaded.frames[0].getpixel((0, 0)) == (255, 0, 0, 255)
+ assert loaded.fingerprints() == {str(source.resolve()): red_hash}
+ assert loaded.fingerprints() != load_asset(source).fingerprints()
+ assert load_asset(source).fingerprints() == {str(source.resolve()): sha(source)}
+
+
+def test_replacement_between_read_and_decode_cannot_separate_pixels_from_hash(tmp_path, monkeypatch):
+ source = tmp_path / "race.png"
+ Image.new("RGBA", (4, 4), "red").save(source)
+ red_hash = sha(source)
+ original = assets._read_bytes
+
+ def read_then_replace(path):
+ data = original(path)
+ Image.new("RGBA", (4, 4), "blue").save(path)
+ return data
+
+ monkeypatch.setattr(assets, "_read_bytes", read_then_replace)
+ loaded = load_asset(source)
+ assert loaded.frames[0].getpixel((0, 0)) == (255, 0, 0, 255)
+ assert loaded.fingerprints() == {str(source.resolve()): red_hash}
+ assert sha(source) != red_hash
+
+
+def test_descriptor_identity_is_the_parsed_bytes(tmp_path, monkeypatch):
+ source = descriptor(tmp_path)
+ original_hash = sha(source)
+ original = assets._read_bytes
+
+ def read_then_edit(path):
+ data = original(path)
+ if Path(path).name == "walk.json":
+ edited = json.loads(data)
+ edited["frames"] = edited["frames"][:2]
+ Path(path).write_text(json.dumps(edited))
+ return data
+
+ monkeypatch.setattr(assets, "_read_bytes", read_then_edit)
+ loaded = load_asset(source)
+ assert len(loaded.frames) == 5
+ assert loaded.fingerprints()[str(source.resolve())] == original_hash
+ assert sha(source) != original_hash
+
+
+def test_animated_and_oversized_images_are_refused_before_decoding(tmp_path, monkeypatch):
+ animated = tmp_path / "animated.png"
+ Image.new("RGBA", (4, 4), "red").save(animated, save_all=True, append_images=[Image.new("RGBA", (4, 4), "blue")], duration=50)
+ with pytest.raises(ValueError, match="animated"):
+ load_asset(animated)
+ monkeypatch.setattr(assets, "MAX_SOURCE_PIXELS", 15)
+ still = tmp_path / "still.png"
+ Image.new("RGBA", (4, 4)).save(still)
+ with pytest.raises(ValueError, match="exceeds the supported"):
+ load_asset(still)
+ monkeypatch.setattr(assets, "MAX_SOURCE_PIXELS", 16)
+ assert load_asset(still).size == (4, 4)
+
+
+def test_frame_at_wraps_when_looping_and_holds_the_last_frame_otherwise(tmp_path):
+ seq = load_asset(descriptor(tmp_path, durations=(0.1, 0.2, 0.3, 0.1, 0.3)))
+ starts = [0, 0.1, 0.3, 0.6, 0.7]
+ for index, start in enumerate(starts):
+ assert seq.frame_at(start) is seq.frames[index]
+ assert seq.frame_at(start + 0.05) is seq.frames[index]
+ assert seq.frame_at(1.0) is seq.frames[0]
+ assert seq.frame_at(1.15) is seq.frames[1]
+ assert seq.frame_at(-0.05) is seq.frames[4]
+ assert seq.frame_at(1.0, loop=False) is seq.frames[4]
+ assert seq.frame_at(-1, loop=False) is seq.frames[0]
+ with pytest.raises(ValueError):
+ seq.frame_at(float("nan"))
+
+
[email protected]("mutate, message", [
+ (lambda d: [1, 2], "must be an object"),
+ (lambda d: {**d, "frames": []}, "nonempty"),
+ (lambda d: {**d, "frames": [{"file": "foot-0.png"}]}, "duration"),
+ (lambda d: {**d, "frames": [{"file": "foot-0.png", "duration": 0}]}, "duration"),
+ (lambda d: {**d, "frames": [{"duration": 0.1}]}, "file and duration"),
+ (lambda d: {**d, "version": 2}, "version 1"),
+ (lambda d: {"kind": "something-else"}, "unsupported asset descriptor"),
+ (lambda d: {**d, "anchor": [1]}, "anchor"),
+])
+def test_invalid_descriptors_are_rejected(tmp_path, mutate, message):
+ source = descriptor(tmp_path)
+ source.write_text(json.dumps(mutate(json.loads(source.read_text()))))
+ with pytest.raises(ValueError, match=message):
+ load_asset(source)
+
+
[email protected]("mutate, message", [
+ (lambda d: d["frame_layout"]["rows"]["walk"].append({"x": 48 * 5, "y": 0, "w": 48, "h": 40}), "outside sheet"),
+ (lambda d: d["frame_layout"]["rows"]["walk"].append({"x": 0, "y": 0, "w": 48.5, "h": 40}), "integer"),
+ (lambda d: d["frame_layout"]["rows"]["walk"].__setitem__(0, {"x": 0.5, "y": 0, "w": 48, "h": 40}), "outside sheet"),
+ (lambda d: d["animation"]["rows"]["walk"].update({"durations_ms": [0] * 5}), "duration_ms"),
+ (lambda d: d["frame_layout"].update({"rows": {}}), "no animation states"),
+])
+def test_invalid_atlas_manifests_are_rejected(tmp_path, mutate, message):
+ source = atlas(tmp_path, states=("walk",))
+ data = json.loads(source.read_text())
+ mutate(data)
+ source.write_text(json.dumps(data))
+ with pytest.raises(ValueError, match=message):
+ load_asset(source)
+
+
+def test_frame_sequence_positional_contract_defaults_anchor_and_keeps_digests_keyword_only(tmp_path):
+ frame = Image.new("RGBA", (6, 4))
+ bare = FrameSequence((frame,), (1.0,))
+ assert bare.anchor == (3.0, 4.0)
+ assert bare.source_files == () and bare.metadata == {} and bare.source_digests == ()
+ assert bare.fingerprints() == {}
+ assert bare.identity() == {"source": None, "state": None, "fps_override": None, "frame_count": 1,
+ "size": [6, 4], "anchor_px": [3.0, 4.0], "durations_seconds": [1.0]}
+ positional = FrameSequence((frame,), (0.5,), [1, 2], (), {"source": "memory"})
+ assert positional.anchor == (1.0, 2.0) and positional.metadata == {"source": "memory"}
+ with pytest.raises(ValueError, match="SHA-256"):
+ FrameSequence((frame,), (1.0,), None, (tmp_path / "x.png",), {})
+ with pytest.raises(TypeError):
+ FrameSequence((frame,), (1.0,), None, (tmp_path / "x.png",), {}, ("digest",))
+ with pytest.raises(ValueError, match="anchor"):
+ FrameSequence((frame,), (1.0,), (1, float("nan")))
+ backed = FrameSequence((frame,), (1.0,), None, (tmp_path / "x.png",), {}, source_digests=("abc",))
+ assert backed.fingerprints() == {str(tmp_path / "x.png"): "abc"}