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(loop): choose a wrap transition that preserves motion

Soohong Kim91e9833a75c8
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index d6aa64b..6d2dc70 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -173,7 +173,10 @@ was 17). `video-loop` therefore:
*smallest* local minimum that is within 15 % of the deepest one — exact repeats dip
again at 2× and 3× the period, the half-period look-alike dips noticeably less;
3. only then picks the **start** with the best seam for that period (± 1 frame):
- `seam = D[i][i+L]` over the mean adjacent distance inside the cycle.
+ `seam = D[i+L-1][i]` over the mean adjacent distance inside the cycle.
+ Choose the ratio closest to 1 in log space, so a repeated pose at the wrap does
+ not win just because its distance is small. `next_frame_distance` retains the
+ distance to the frame after the cycle for diagnostics.
Windows come from the state profile (`STATE_PROFILES`). **Gait states take theirs in
seconds**, because a stride is a fact about the body, not about the clip length: walk
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index f0acc2e..391b829 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -186,17 +186,24 @@ def detect_cycle(D: np.ndarray, *, min_len: int, max_len: int, gait_floor: int |
guard = {"applied": False, "below_floor": period, "gait_floor": gait_floor, "why": "the doubled period repeats too much worse to be the same gait"}
profile_mean = float(np.mean([prof[L] for L in prof]))
periodicity = (profile_mean - prof[period]) / profile_mean if profile_mean > 0 else 0.0
+ # Score the last displayed frame -> first frame transition against an ordinary
+ # playback step. Minimising distance alone rewards a repeated pose (a stall).
+ # Log distance penalises steps that are too short or too long symmetrically.
best: dict[str, Any] | None = None
for L in (period - 1, period, period + 1):
if L < min_len or L > max_len:
continue
for i in range(0, n - L):
- seam = float(D[i, i + L])
+ seam = float(D[i + L - 1, i])
inner = float(adjacent[i : i + L - 1].mean())
ratio = seam / inner if inner > 0 else math.inf
- if best is None or ratio < best["ratio"]:
- best = {"start": i, "length": L, "seam": seam, "inner_mean_adjacent": inner, "ratio": ratio}
+ score = abs(math.log(ratio)) if ratio > 0 else math.inf
+ if best is None or score < best["wrap_score"]:
+ best = {"start": i, "length": L, "seam": seam, "inner_mean_adjacent": inner,
+ "ratio": ratio, "wrap_score": score,
+ "next_frame_distance": float(D[i, i + L]) if i + L < n else None}
assert best is not None
+ best.pop("wrap_score")
best["period_global"] = period
best["half_period_guard"] = guard
best["periodicity"] = round(periodicity, 4) # how far below the profile mean the period dips (0 = flat = no period)
diff --git a/tests/video/test_loop_sampling_and_wrap.py b/tests/video/test_loop_sampling_and_wrap.py
new file mode 100644
index 0000000..0b1ede2
--- /dev/null
+++ b/tests/video/test_loop_sampling_and_wrap.py
@@ -0,0 +1,75 @@
+"""Loop cuts preserve an ordinary playback step at the wrap."""
+
+from __future__ import annotations
+
+import math
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from sprite_gen._deps import np
+from sprite_gen.video import loop as loop_mod
+
+
+def _walker(tmp_path: Path, *, period: int, n: int, size=(64, 64)) -> list[Path]:
+ """A walker whose stride is `period` frames, with a near/far marker so the half
+ period is distinguishable — the same body in a 1 s, 2 s or 3 s clip."""
+ d = tmp_path / "keyed"
+ d.mkdir(parents=True, exist_ok=True)
+ files = []
+ for t in range(n):
+ im = Image.new("RGBA", size, (0, 0, 0, 0))
+ for y in range(10, 40):
+ for x in range(26, 38):
+ im.putpixel((x, y), (200, 60, 60, 255))
+ phase = 2 * math.pi * t / period
+ leg_x = 32 + round(10 * math.sin(phase))
+ for y in range(40, 58):
+ for x in range(leg_x - 3, leg_x + 3):
+ if 0 <= x < size[0]:
+ im.putpixel((x, y), (60, 60, 200, 255))
+ if math.sin(phase) >= 0:
+ im.putpixel((leg_x, 50), (255, 255, 0, 255))
+ f = d / f"f{t:03d}.png"
+ im.save(f)
+ files.append(f)
+ return files
+
+
+def test_the_cut_is_scored_on_the_step_that_plays_not_the_frame_after_it(tmp_path: Path) -> None:
+ """A non-integer period is where the two metrics disagree, and the wrap step is the
+ one a viewer sees: too small means the last frame repeats the first and the loop
+ freezes for a frame."""
+ files = _walker(tmp_path, period=12, n=96)
+ D = loop_mod.distance_matrix(files)
+ cycle = loop_mod.detect_cycle(D, min_len=4, max_len=40)
+ i, L = cycle["start"], cycle["length"]
+ adjacent = np.array([D[k, k + 1] for k in range(len(files) - 1)])
+ inner = float(adjacent[i : i + L - 1].mean())
+ # `seam`/`ratio` report D[i+L-1, i] — the transition from the last shown frame back
+ # to the first — not D[i, i+L].
+ assert cycle["seam"] == pytest.approx(float(D[i + L - 1, i]), rel=1e-9)
+ assert cycle["ratio"] == pytest.approx(cycle["seam"] / inner, rel=1e-9)
+ # and it is a real step of the cycle, never a stall
+ assert cycle["ratio"] > 0.5
+
+
+def test_a_stall_at_the_wrap_loses_to_an_ordinary_step() -> None:
+ """A non-integer period is exactly where the two metrics disagree.
+
+ Frames walk around a circle with a synthetic 24.5-frame period. L=25 puts the last shown frame half a step from the
+ first (wrap 0.50x: the loop freezes for a frame); L=24 plays an ordinary step.
+ """
+ period, n = 24.5, 60
+ angle = np.arange(n) * 2 * math.pi / period
+ points = np.stack([np.cos(angle), np.sin(angle)], axis=1)
+ D = np.linalg.norm(points[:, None, :] - points[None, :, :], axis=-1).astype(np.float32)
+ adjacent = float(np.mean([D[k, k + 1] for k in range(n - 1)]))
+ # the situation, stated: L=25 stalls, L=24 does not
+ assert D[24, 0] / adjacent == pytest.approx(0.50, abs=0.05)
+ assert D[23, 0] / adjacent == pytest.approx(1.49, abs=0.05)
+
+ cycle = loop_mod.detect_cycle(D, min_len=20, max_len=28)
+ assert cycle["length"] == 24
+ assert cycle["ratio"] > 0.75, "a cut that repeats its first frame at the wrap must lose"
diff --git a/tests/video/test_video_pipeline.py b/tests/video/test_video_pipeline.py
index 4eacc3b..7abdf7d 100644
--- a/tests/video/test_video_pipeline.py
+++ b/tests/video/test_video_pipeline.py
@@ -170,7 +170,13 @@ def test_detect_cycle_finds_the_full_period_not_the_half_or_1_5x(tmp_path: Path)
cycle = loop_mod.detect_cycle(D, min_len=4, max_len=40)
assert cycle["period_global"] == 12
assert cycle["length"] in (11, 12, 13)
- assert cycle["ratio"] < 1.0
+ # The cut closes exactly: the frame that would come next IS the frame it jumps back to.
+ assert cycle["next_frame_distance"] == pytest.approx(0.0, abs=1e-6)
+ # `ratio` scores the step that actually plays at the wrap, so it is a step of this
+ # cycle and not a number that shrinks toward zero. The fixture's leg is a rounded
+ # sine, which makes its own steps lumpy (1.50 1.20 0.32 0.32 1.20 1.50 ... x the mean),
+ # so the closest any cut can put the wrap to an average step here is ~1.2.
+ assert 0.9 < cycle["ratio"] < 1.6
def test_detect_cycle_refuses_empty_window() -> None: