Skip to content

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

fix: cut single-play clips at the first stable terminal pose

Soohong Kimeb1d33e23005
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index 963dfa3..aea2b94 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -1264,8 +1264,11 @@ def run_loop(
if steps is not None:
cycle = _counted(cycle, steps, window=window, D=D, trajectory=trajectory, frames=source_frames, moved=moved, detect=detect)
elif cycle_mode == "once":
- nonloop.validate_body([Image.open(f).convert("RGBA") for f in files])
- cycle = nonloop.select_cut(D, masses, fps=fps)
+ source_frames = [Image.open(f).convert("RGBA") for f in files]
+ boxes = [nonloop.body_box(frame) for frame in source_frames]
+ cycle = nonloop.select_cut(D, masses, fps=fps,
+ ending=partial(nonloop.hold_ending, boxes=boxes, state=state))
+ nonloop.validate_body(source_frames[cycle["start"]:cycle["end_frame"] + 1])
elif cycle_mode == "fixed":
if start is None or length is None:
raise SystemExit("video-loop: --cycle fixed needs --start and --length")
diff --git a/sprite_gen/video/nonloop.py b/sprite_gen/video/nonloop.py
index 5739f70..40f40fb 100644
--- a/sprite_gen/video/nonloop.py
+++ b/sprite_gen/video/nonloop.py
@@ -8,33 +8,104 @@ from typing import Any, Callable
from sprite_gen._deps import np
KINDS = ("once", "lifetime")
-MOTION_TEXT = {'death': 'collapses directly onto the ground, settles into a completely prone position, and remains lying entirely motionless for the final 0.4 seconds without shifting, rising, or returning to the starting posture.', 'fall': 'drops briefly downward in place, impacts and settles onto the ground, and holds that grounded resting position completely motionless for the final 0.4 seconds without bouncing, recovering, or returning to the start.', 'land': 'descends vertically a short distance, absorbs ground impact by compressing into a low crouch, and holds that crouched posture completely motionless for the final 0.4 seconds without standing up or returning to the start.', 'cast': 'raises a casting implement or the forward body into an active casting pose and holds that gesture completely motionless for the final 0.4 seconds, displaying no glowing lights, bursts, or particle effects.', 'hurt_hold': 'recoils backward from an impact once and immediately holds the recoiled posture completely motionless for the final 0.4 seconds without relaxing, recovering, or returning to the start.', 'transform': 'changes into a final form through a single completed morph and holds that new form completely motionless for the final 0.4 seconds without shifting, reverting, or returning to the starting form.'}
+MOTION_TEXT = {'death': 'collapses directly onto the ground, settles into a completely prone position, and remains '
+ 'lying entirely motionless for the final 0.4 seconds without shifting, rising, or returning '
+ 'to the starting posture.',
+ 'fall': 'drops briefly downward in place, impacts and settles onto the ground, and holds that grounded '
+ 'resting position completely motionless for the final 0.4 seconds without bouncing, '
+ 'recovering, or returning to the start.',
+ 'land': 'descends vertically a short distance, absorbs ground impact by compressing into a low crouch, '
+ 'and holds that crouched posture completely motionless for the final 0.4 seconds without '
+ 'standing up or returning to the start.',
+ 'cast': 'raises a casting implement or the forward body into an active casting pose and holds that '
+ 'gesture completely motionless for the final 0.4 seconds, displaying no glowing lights, '
+ 'bursts, or particle effects.',
+ 'hurt_hold': 'recoils backward from an impact once and immediately holds the recoiled posture '
+ 'completely motionless for the final 0.4 seconds without relaxing, recovering, or '
+ 'returning to the start.',
+ 'transform': 'changes into a final form through a single completed morph and holds that new form '
+ 'completely motionless for the final 0.4 seconds without shifting, reverting, or '
+ 'returning to the starting form.'}
STATES = frozenset(MOTION_TEXT)
COMMON_TEXT = 'Each action is executed exactly once without looping or returning to the initial state, holding the final pose completely motionless for the final 0.4 seconds, keeping the full body and any props entirely inside the frame under a fixed camera against a flat pure chroma background with no shadows, particles, visual effects, or smears, while preserving the original art style and permitting changes to character design and proportions solely for the transform action.'
-ANATOMY_TEXT = {'quadruped': 'Preserve quadruped anatomical structure without requiring an upright or standing stance, allowing natural weight transfer, crouching, and full ground collapse during death or falls without requiring all four limbs to touch the ground on every frame.', 'legless': 'Preserve continuous limbless anatomy without forcing an upright orientation, allowing undulating, coiled, or fully flattened ground configurations during death or falls without introducing limbs.'}
+ANATOMY_TEXT = {'quadruped': 'Preserve quadruped anatomical structure without requiring an upright or standing stance, '
+ 'allowing natural weight transfer, crouching, and full ground collapse during death or '
+ 'falls without requiring all four limbs to touch the ground on every frame.',
+ 'legless': 'Preserve continuous limbless anatomy without forcing an upright orientation, allowing '
+ 'undulating, coiled, or fully flattened ground configurations during death or falls without '
+ 'introducing limbs.'}
CYCLIC_STATES = frozenset({"idle", "walk", "run", "talk", "blink", "breathe"})
STABLE_SECONDS = 0.2
STABLE_MAX = 0.025 # distance / visible subject mass, independent of canvas padding
+POSE_SHAPE_TOLERANCE = 0.05
+POSE_FLOOR_TOLERANCE = 0.02
+GROUND_HEIGHT_MAX = 0.8
+GROUND_STATES = frozenset({"death", "fall"})
-def hold_ending(D: np.ndarray, masses: np.ndarray, fps: float) -> tuple[int, int, dict[str, Any]]:
- """Require a visible, stable final window, including slow drift against its endpoint."""
+def hold_ending(D: np.ndarray, masses: np.ndarray, fps: float, *,
+ boxes: list[tuple[int, int, int, int] | None] | None = None,
+ state: str | None = None) -> tuple[int, int, dict[str, Any]]:
+ """End at the first settled terminal pose, discarding subsequent motion."""
n = len(D)
count = max(4, math.ceil(fps * STABLE_SECONDS))
- if n <= count + 1 or float(masses.min()) <= 0:
- raise ValueError("once needs a visible subject and a stable final window")
- scale = float(np.median(masses[-count:]))
- tail = D[-count:, -count:] / scale
- diameter = float(tail.max())
- if diameter > STABLE_MAX:
- raise ValueError(f"once has no stable end pose: final {count} frames move {diameter:.4f} of the subject (limit {STABLE_MAX})")
- departure = D[0] / max(float(masses[0]), scale)
- active = np.flatnonzero(departure > STABLE_MAX * 2)
- if not len(active) or int(active[0]) >= n - count:
+ if n <= count + 1 or float(masses[0]) <= 0:
+ raise ValueError("once needs a visible subject and a stable end window")
+ if not np.any(D[0] / max(float(masses[0]), float(np.median(masses))) > STABLE_MAX * 2):
raise ValueError("once has no performed action before its stable end pose")
- start = max(0, int(active[0]) - 1)
- return start, n - 1, {"kind": "hold", "frames": count, "start": n - count,
- "diameter": diameter, "max": STABLE_MAX, "normalization": "subject-mass"}
+ reason = "no window meets the stability limit"
+ for end in range(count + 1, n):
+ first = end - count + 1
+ if float(masses[first:end + 1].min()) <= 0:
+ continue
+ scale = float(np.median(masses[first:end + 1]))
+ diameter = float(D[first:end + 1, first:end + 1].max()) / scale
+ if diameter > STABLE_MAX:
+ continue
+ departure = D[0] / max(float(masses[0]), scale)
+ active = np.flatnonzero(departure[:first] > STABLE_MAX * 2)
+ if not len(active):
+ continue
+ pose = None
+ if boxes is not None:
+ try:
+ pose = terminal_pose(boxes[:end + 1], count=count, state=state)
+ except ValueError as exc:
+ reason = str(exc)
+ continue
+ elif float(np.median(departure[first:end + 1])) <= STABLE_MAX * 2:
+ continue
+ start = max(0, int(active[0]) - 1)
+ return start, end, {"kind": "hold", "frames": count, "start": first,
+ "diameter": diameter, "max": STABLE_MAX, "normalization": "subject-mass",
+ **({"pose": pose} if pose is not None else {})}
+ raise ValueError(f"once has no stable end pose: {reason} ({count} frames, limit {STABLE_MAX})")
+
+
+def terminal_pose(boxes: list[tuple[int, int, int, int] | None], *, count: int,
+ state: str | None) -> dict[str, Any]:
+ """Compare body geometry, independent of color noise and horizontal drift."""
+ first = boxes[0]
+ tail = boxes[-count:]
+ if first is None or any(b is None for b in tail):
+ raise ValueError("once needs a visible end pose")
+ height = first[3] - first[1]
+ width = first[2] - first[0]
+ last_height = float(np.median([b[3] - b[1] for b in tail]))
+ last_width = float(np.median([b[2] - b[0] for b in tail]))
+ height_ratio = last_height / height
+ aspect_ratio = (last_width / last_height) / (width / height)
+ floor_shift = abs(float(np.median([b[3] for b in tail])) - first[3]) / height
+ if (abs(height_ratio - 1) <= POSE_SHAPE_TOLERANCE
+ and abs(aspect_ratio - 1) <= POSE_SHAPE_TOLERANCE
+ and floor_shift <= POSE_FLOOR_TOLERANCE):
+ raise ValueError("once ends in the starting pose: body height, aspect and floor position have returned")
+ if state in GROUND_STATES and height_ratio > GROUND_HEIGHT_MAX:
+ raise ValueError(f"once: {state} needs a lowered ground pose; end/start body height {height_ratio:.3f} exceeds {GROUND_HEIGHT_MAX}")
+ return {"profile": "ground" if state in GROUND_STATES else "changed",
+ "height_ratio": height_ratio, "aspect_ratio": aspect_ratio, "floor_shift": floor_shift,
+ "shape_tolerance": POSE_SHAPE_TOLERANCE, "floor_tolerance": POSE_FLOOR_TOLERANCE,
+ **({"height_max": GROUND_HEIGHT_MAX} if state in GROUND_STATES else {})}
Ending = Callable[[np.ndarray, np.ndarray, float], tuple[int, int, dict[str, Any]]]
@@ -67,11 +138,14 @@ def metadata(cycle: dict[str, Any], indices: list[int]) -> dict[str, Any]:
"name": "motion_peak"}]}
+def body_box(frame: Any) -> tuple[int, int, int, int] | None:
+ return frame.getchannel("A").point(lambda a: 255 if a >= 8 else 0).getbbox()
+
+
def validate_body(frames: list[Any]) -> None:
- """A terminal pose may change shape, but no keyed body may leave its source canvas."""
+ """No retained body may leave its source canvas."""
for k, frame in enumerate(frames):
- alpha = frame.getchannel("A").point(lambda a: 255 if a >= 8 else 0)
- box = alpha.getbbox()
+ box = body_box(frame)
if box is None:
raise ValueError(f"once: subject is empty at frame {k}")
if box[0] == 0 or box[1] == 0 or box[2] == frame.width or box[3] == frame.height: