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(video): video-follow reads the body's motion off the body, not off whatever is at its top

Soohong Kim50b29f7a6083
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fcfbb49..5d0459b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,9 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
## Unreleased
+- **Output change: `video-follow` reads the body's motion off the body, not off whatever is at its top.** The motion was the top row of the silhouette and the middle of the band under it, so whatever came to the top was the body: a tail tip rising over the head, a flopping ear, a ponytail, a sword or a rod held up. Where such a part took the top in some cells and not in others, the read jumped by the part's whole swing from one cell to the next; where it held the top, the bob was the part's own swing. The follow-through then answered the tail, the ears or the weapon, the region was carried off its part, and large parts were refused. Now each cell is laid where its silhouette, worn down by every whole number of pixels from a quarter to half of the first cell's depth, overlaps the first cell's, worn alike, most: the overlaps of every level summed, counted in whole pixels (the FFT's rounding is gone, so the same strip reads the same on every machine), a tie going to the smaller move. What swings on the body and is thinner than it is worn away, the deepest of the body counts most, and a torso that is shallower in one cell (an arm swung away from it) still counts. **Every follow-through moves differently, the strips whose top is the head included — no strip is written byte for byte as before**: the head nods and leads the torso, and the read is now the torso's. The record gains `body_worn_px`, the first and last level the silhouette was worn down to. A cell with nothing in it a quarter as deep as the first cell's body is refused: `video-follow: cell <k> has no body as deep as a quarter of cell 0's (<px> px)`. Reading the motion takes 1–2 s on strips of 18–48 cells and 12 s on 64 cells of 640 px around one deep blob. [docs/video-pipeline.md](docs/video-pipeline.md#6-follow-through--video-follow).
+- **`tests/video/test_follow.py`** follows a chest on a walker with a thin tail whose tip swings over the head, and on one holding a sword up and swinging it over the head: the record (bob, `dx_px`, `dy_px`, reach, gain, fold) and the chest's moved pixels are the bare walker's. Before this, the chest was refused on both: the read made the move at gain 1 20.8 and 17.5 px, so the chest could take no more than gain 0.52 and 0.61, where on the bare walker it moves at 2.5. A strip with a cell no deeper than a line is refused untouched.
+
- **Fix: `video-follow` replaces the loop's files only once all of them are written.** The strip, the GIF and the WebP were written over the loop's before the record was, so a run that failed on the record — `follow.follow_loop` given numpy numbers, an int64 of which has no JSON form (`TypeError`) — or on an animation's check left a moved strip beside a record that did not say so. Now the strip, GIF, WebP and record are written and checked in a scratch directory beside the loop (`.follow.*`), each under its own name, and moved over the loop's files after the record is written; a run that fails on the way leaves all four as they were (the strip as cut is still kept as `follow.source.png`, as on a refusal). `follow_loop` reads its regions, `gain`, `freq` and `zeta` as the floats the command line gives, so numpy numbers, or plain ints, write the strip and record that the same numbers as floats write, byte for byte (a caller that passed plain ints finds them recorded as floats, `80.0` where it was `80`). `loop.verify_animation` closes the file it checks. The command's output, its strip, GIF, WebP and record, and `--help` are as before, byte for byte. [docs/video-pipeline.md](docs/video-pipeline.md#6-follow-through--video-follow).
- **`tests/video/test_follow.py`** moves a chest and a smaller head region given as int64, int32, float32, float64 and plain int coordinates, as the rows of an int64 array, and with a float32 `gain`: each writes the strip, GIF, WebP and record the float coordinates write, byte for byte (before this the int64 run failed on the record with the strip already moved). A run made to fail on its record or on its WebP's check, on a loop as cut and on one already followed, leaves the strip, GIF, WebP and record as they were, and nothing beside them but `follow.source.png`.
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 79812d8..9098058 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -1021,8 +1021,21 @@ sprite-gen video-follow --loop-dir set/front-walk/loop --region 136,164,60,50 [-
(`cx,cy,rx,ry`; repeatable). It is carried with the body's bob from cell to cell. Somebody has
to say where it is — the engine does not find it: look at the first cell (or ask a vision model
for the four numbers once per direction; a mirrored direction takes the mirror's region).
-- **The motion** is the body's own: the crown's row (up and down) and the middle of the head
- (side to side), read off the cells. The part is a damped mass on the body — its offset x from
+- **The motion** is the body's own: how far each cell's body lies from the first cell's, up and
+ down and side to side. The silhouette (alpha ≥ 128) is worn down: worn by r, a pixel stays when
+ the square of side 2·r + 1 around it is all body. Its depth is the most the first cell can be
+ worn down by and still keep a pixel, plus one; worn by a quarter of that, what swings on the
+ body and is thinner than it (a tail, a ponytail, an ear, a sword or a rod held up, the legs and
+ arms) is gone and the head and torso are left. Each cell is laid where its silhouette, worn by
+ every whole number of pixels from a quarter to half of that depth, overlaps the first cell's,
+ worn alike, most — the overlaps of every level counted in whole pixels and summed, a tie going
+ to the smaller move. A pixel counts once for each level it is still in, so the deepest of the
+ body counts most and a part that comes and goes cannot outweigh it, while a torso that is
+ shallower in one cell (an arm swung away from it, long hair lifted off it) still counts at its
+ shallower levels. The top of the body was read before: whatever came to the top was the
+ motion, and a tail tip, a flopping ear or a sword raised over the head made it jump by the
+ part's whole swing from one cell to the next. A cell with nothing in it a quarter as deep as the first
+ cell's body is refused. The part is a damped mass on the body — its offset x from
where the body carries it answers x'' + 2ζωx' + ω²x = −body'' — solved in the loop's periodic
steady state per harmonic of the cycle (the first six), so it lags the bob and settles, with no
kick at a foot strike, and the last frame leads into the first. `--freq` (2.4 Hz) and `--zeta`
@@ -1045,12 +1058,13 @@ sprite-gen video-follow --loop-dir set/front-walk/loop --region 136,164,60,50 [-
region and the largest gain that would not fold it). Where regions of different gains overlap,
the larger move wins; the move there is nowhere steeper than either region's own, so nothing
folds. A strip whose regions all take one gain — one region, or regions that fold alike, or
- none that folds — is written as before this was per region, byte for byte, and its `gain` is
+ none that folds — is written as one gain for the strip writes it, byte for byte, and its `gain` is
then the `--gain` that gives this strip by itself. The default stays `refuse`, with the same
- output and the same message as 2.24.0; a strip that does not fold is the same under either.
+ message as 2.24.0; a strip that does not fold is the same under either.
- **What it writes**: the strip, GIF and WebP over the loop's own (both animations re-opened and
checked as `video-loop` checks them), and `follow` in `<name>.strip.json` (the regions, the
- settings, the body's bob, `dx_px`/`dy_px` per cell, `reach_px`; `gain` is the gain used and
+ settings, the body's height in the first cell `body_px`, the first and last level it was worn
+ down to `body_worn_px`, the body's bob `body_bob_px` (side to side, up and down), `dx_px`/`dy_px` per cell, `reach_px`; `gain` is the gain used and
`gain_requested` the one asked for, and `fold` says whether it was lowered, the move asked for,
the move at gain 1, and per region its smaller radius, how near the used move is to folding it
(`ratio`, under 1) and the gain at which it folds). Where the regions took gains of their own,
diff --git a/sprite_gen/video/follow.py b/sprite_gen/video/follow.py
index 2345a85..468adb6 100644
--- a/sprite_gen/video/follow.py
+++ b/sprite_gen/video/follow.py
@@ -6,9 +6,14 @@ a pouch on a strap) mostly moves with the body as one piece, even when the promp
bounce: at sprite size it reads as rigid. This puts that follow-through back after the loop is
cut.
-Each frame of the strip is a cell of one cycle. The body's motion is read off the cells: the
-row of the crown (up and down) and the middle of the head (side to side). A part hung on the
-body is a damped mass: its offset x from where the body carries it answers the body's own
+Each frame of the strip is a cell of one cycle. The body's motion is read off the cells: how far
+each cell's body lies from the first cell's. The silhouette is worn down from a quarter to half
+of its depth in the first cell, so what swings on the body — a tail, a ponytail, an ear, a sword
+or a rod held up, the legs and arms — is worn away and the head and torso are left; each cell is
+laid where it overlaps the first cell most, worn alike, a pixel counting once for every level it
+is still in. (Read off the top of the body instead, the motion was whatever came to the top: a
+tail tip or a raised sword made it jump by the part's whole swing from one cell to the next.) A part
+hung on the body is a damped mass: its offset x from where the body carries it answers the body's own
acceleration, x'' + 2·ζ·ω·x' + ω²·x = −body''. The loop repeats, so the answer is the periodic
steady state, solved per harmonic of the cycle: no start-up, no kick at a foot strike, and the
last frame leads into the first. `--gain` scales that physical answer and nothing else; it is
@@ -57,7 +62,7 @@ GAIN_STEP = 0.01 # a lowered gain is a whole number of these, so the report's `
ON_FOLD_MODES = ("refuse", "lower")
HARMONICS = 6 # of the cycle, for the body's motion: a step's shape, not its noise
ALPHA_SOLID = 128
-HEAD_SHARE = 0.07 # of the body's height under the crown: where the head's middle is read
+WORN_FROM, WORN_TO = 0.25, 0.5 # of the body's depth in the first cell: the levels its silhouette is worn down to
SOURCE = loop_mod.FOLLOW_SOURCE
@@ -71,23 +76,115 @@ def parse_region(text: str) -> tuple[float, float, float, float]:
return cx, cy, rx, ry
-def body_motion(cells: list[Image.Image]) -> tuple[np.ndarray, np.ndarray, int]:
- """Per cell: the crown's row and the head's middle column; and the body's height in cell 0."""
- rows, cols = [], []
- height0 = 0
+def _run_depth(solid: np.ndarray, axis: int) -> np.ndarray:
+ """Per solid pixel, how far along `axis` the nearest clear pixel is (1 beside one; past the cell's edge is clear)."""
+ m = np.moveaxis(solid, axis, -1)
+ n = m.shape[-1]
+ at = np.broadcast_to(np.arange(n), m.shape)
+ before = np.maximum.accumulate(np.where(m, -1, at), axis=-1)
+ after = np.minimum.accumulate(np.where(m, n, at)[..., ::-1], axis=-1)[..., ::-1]
+ return np.moveaxis(np.where(m, np.minimum(at - before, after - at), 0), -1, axis)
+
+
+def wear(solid: np.ndarray, r: int) -> np.ndarray:
+ """`solid` worn down by r: the pixels whose square of side 2·r + 1 around them is solid."""
+ return _run_depth(_run_depth(solid, 1) > r, 0) > r
+
+
+def depth(solid: np.ndarray) -> int:
+ """How deep the body is at its deepest: the most it is worn down by and still has a pixel, plus one."""
+ lo, hi = 0, (min(solid.shape) + 1) // 2 # worn by lo something is left; worn by hi nothing is
+ if not solid.any():
+ return 0
+ while hi - lo > 1:
+ mid = (lo + hi) // 2
+ lo, hi = (mid, hi) if wear(solid, mid).any() else (lo, mid)
+ return lo + 1
+
+
+def _levels(solid: np.ndarray, worn: range) -> tuple[list[np.ndarray], int, int] | None:
+ """`solid` worn down by each of `worn`, cut to the box of the first (each lies inside the one before),
+ and that box's top and left; None when nothing is left of it worn down by the first."""
+ first = wear(solid, worn[0])
+ if not first.any():
+ return None
+ ys, xs = np.nonzero(first.any(axis=1))[0], np.nonzero(first.any(axis=0))[0]
+ level = first[ys[0]: ys[-1] + 1, xs[0]: xs[-1] + 1]
+ levels = [level]
+ for _ in worn[1:]:
+ # Worn down by one more pixel: a square of side 2·r + 3 is one of side 2·r + 1 grown by one each way.
+ across = np.pad(level, 1)
+ level = across[1:-1, :-2] & across[1:-1, 1:-1] & across[1:-1, 2:]
+ down = np.pad(level, 1)
+ level = down[:-2, 1:-1] & down[1:-1, 1:-1] & down[2:, 1:-1]
+ levels.append(level)
+ return levels, int(ys[0]), int(xs[0])
+
+
+def _fft_length(n: int) -> int:
+ """The first length from n on with no prime factor over 5: an FFT of it is fast."""
+ while True:
+ m = n
+ for p in (2, 3, 5):
+ while m % p == 0:
+ m //= p
+ if m == 1:
+ return n
+ n += 1
+
+
+def _overlay(levels0: tuple[list[np.ndarray], int, int], levels: tuple[list[np.ndarray], int, int]) -> tuple[int, int]:
+ """The shift (dx, dy) of a cell from cell 0: where cell 0's levels, moved by it, land on the cell's own most,
+ the pixels that land counted at every level and summed."""
+ (a, ya, xa), (b, yb, xb) = levels0, levels
+ # Long enough that no move wraps round (a.h + b.h - 1 each way, and so on), and fast.
+ shape = (_fft_length(a[0].shape[0] + b[0].shape[0] - 1), _fft_length(a[0].shape[1] + b[0].shape[1] - 1))
+ # overlap[i, j]: how many pixels of each of cell 0's levels land on the cell's same level moved by
+ # (j - (a.w - 1), i - (a.h - 1)), summed over the levels, for every move that meets.
+ spectrum = sum(np.fft.rfft2(lb.astype(np.float64), shape) * np.fft.rfft2(la[::-1, ::-1].astype(np.float64), shape)
+ for la, lb in zip(a, b))
+ # Counts of pixels are whole numbers: rounded, the FFT's own rounding (not the same on every machine) is
+ # gone, so a tie is a tie on every machine, and it goes to the move nearest none.
+ overlap = np.fft.irfft2(spectrum, shape)[: a[0].shape[0] + b[0].shape[0] - 1, : a[0].shape[1] + b[0].shape[1] - 1]
+ overlap = np.rint(overlap).astype(np.int64)
+ shifts = [(int(j) - (a[0].shape[1] - 1) + xb - xa, int(i) - (a[0].shape[0] - 1) + yb - ya)
+ for i, j in np.argwhere(overlap == overlap.max())]
+ return min(shifts, key=lambda s: (s[0] ** 2 + s[1] ** 2, s[1], s[0]))
+
+
+def body_motion(cells: list[Image.Image]) -> tuple[np.ndarray, np.ndarray, int, list[int]]:
+ """Per cell: how far its body lies from cell 0's, down and across (px); the body's height in cell 0,
+ and the first and last level its silhouette is worn down to.
+
+ The top of the body is whatever comes to the top — a tail tip, a ponytail, an ear, a sword held
+ up — and read there the motion jumps from cell to cell. What swings on the body is thinner than
+ the body it swings on: worn down by a quarter of the body's depth it is gone, and what is left
+ is the head and torso. Each cell is laid where its silhouette, worn down by every whole number
+ of pixels from a quarter to half of that depth, overlaps cell 0's, worn alike, most, the
+ overlaps of every level summed: a pixel counts once for each level it is still in, so the
+ deepest of the body counts most and nothing that comes and goes outweighs it, and a torso that
+ is shallower in one cell (an arm swung away from it) still counts at its shallower levels."""
+ solids = []
for k, cell in enumerate(cells):
solid = np.asarray(cell.getchannel("A")) >= ALPHA_SOLID
- ys = np.nonzero(solid.any(axis=1))[0]
- if not len(ys):
+ if not solid.any():
raise ValueError(f"cell {k} has no solid body")
- top, bottom = int(ys[0]), int(ys[-1])
- if k == 0:
- height0 = bottom - top
- band = solid[top: top + max(8, round(HEAD_SHARE * (bottom - top)))]
- xs = np.nonzero(band.any(axis=0))[0]
- rows.append(top)
- cols.append((xs[0] + xs[-1]) / 2)
- return np.asarray(rows, float), np.asarray(cols, float), height0
+ solids.append(solid)
+ ys = np.nonzero(solids[0].any(axis=1))[0]
+ height0 = int(ys[-1] - ys[0])
+ deepest = depth(solids[0])
+ first = int(WORN_FROM * deepest)
+ worn = range(first, max(first + 1, int(WORN_TO * deepest)))
+ levels0 = _levels(solids[0], worn)
+ rows, cols = [], []
+ for k, solid in enumerate(solids):
+ levels = _levels(solid, worn)
+ if levels is None:
+ raise ValueError(f"cell {k} has no body as deep as a quarter of cell 0's ({worn[0]} px)")
+ dx, dy = _overlay(levels0, levels)
+ rows.append(dy)
+ cols.append(dx)
+ return np.asarray(rows, float), np.asarray(cols, float), height0, [worn[0], worn[-1]]
def follow_offsets(motion: np.ndarray, fps: float, *, freq: float, zeta: float, gain: float) -> np.ndarray:
@@ -211,7 +308,7 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]
cells = [strip.crop((k * w, 0, (k + 1) * w, h)) for k in range(n)]
fps = 1000.0 / float(meta["delay_ms"])
try:
- rows, cols, height0 = body_motion(cells)
+ rows, cols, height0, worn = body_motion(cells)
except ValueError as exc:
raise SystemExit(f"video-follow: {exc}") from exc
dy = follow_offsets(rows, fps, freq=freq, zeta=zeta, gain=gain)
@@ -272,7 +369,7 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]
loop_mod.write_webp(out, staged[webp_path], delay_ms=delay_ms, workdir=stage / ".webp-frames")
record = {
"regions": [list(r) for r in regions], "gain": gain, "freq_hz": freq, "zeta": zeta, "harmonics": HARMONICS,
- "source": SOURCE, "body_px": height0,
+ "source": SOURCE, "body_px": height0, "body_worn_px": worn,
"body_bob_px": [round(float(np.ptp(cols)), 2), round(float(np.ptp(rows)), 2)],
"dx_px": np.round(dx, 2).tolist(), "dy_px": np.round(dy, 2).tolist(),
"reach_px": round(reach, 2),
diff --git a/tests/video/test_follow.py b/tests/video/test_follow.py
index 520966b..5f04c14 100644
--- a/tests/video/test_follow.py
+++ b/tests/video/test_follow.py
@@ -74,6 +74,68 @@ def test_the_region_moves_with_the_bob_and_nothing_else_does(loop_dir):
assert (loop_dir/follow.SOURCE).exists()
+def with_top(k, kind, period=24):
+ """The walker with something thin swinging over its head: a tail from the hip whose tip rises above
+ the crown for part of the cycle, or a sword held up and swung over the head from side to side."""
+ im = walker(k, period)
+ d = ImageDraw.Draw(im)
+ bob = round(3*math.sin(4*math.pi*k/period))
+ phase = 2*math.pi*k/period
+ if kind == 'tail':
+ d.line((108, 100+bob, 125+25*math.cos(phase), 12+14*math.sin(phase)), fill=(120, 70, 30, 255), width=3)
+ else:
+ d.line((102, 40+bob, 80+45*math.sin(phase), 4+6*(1-math.cos(phase))), fill=(200, 200, 220, 255), width=4)
+ return im
+
+
+def strip_dir(path, draw, n=24):
+ """A loop directory holding one cycle of `draw(k)` as a strip, as video-loop leaves one."""
+ cells = [draw(k) for k in range(n)]
+ w, h = cells[0].size
+ strip = Image.new('RGBA', (w*n, h))
+ for k, c in enumerate(cells):
+ strip.paste(c, (k*w, 0))
+ path.mkdir()
+ strip.save(path/'walk.strip.png')
+ (path/'walk.strip.json').write_text(json.dumps({'kind': 'periodic', 'frames': n, 'w': w, 'h': h, 'delay_ms': 1000/24}))
+ return path
+
+
[email protected]('kind', ['tail', 'sword'])
+def test_what_swings_over_the_head_does_not_move_the_body(tmp_path, kind):
+ # The motion was read off the top of the body, so whatever came to the top was the body: a tail tip
+ # rising over the head made the read jump across the cell, a sword held up made the body follow its tip.
+ chest = (80.0, 83.0, 22.0, 17.0) # the soft part, as walker draws it in cell 0
+ bare = follow.follow_loop(strip_dir(tmp_path/'bare', walker), [chest], on_fold='lower')
+ topped = follow.follow_loop(strip_dir(tmp_path/kind, lambda k: with_top(k, kind)), [chest], on_fold='lower')
+ # The head and torso bob 3 px up and down twice a cycle and do not move across.
+ assert bare['body_bob_px'] == [0.0, 6.0]
+ for key in ('body_bob_px', 'dx_px', 'dy_px', 'reach_px', 'gain', 'fold'):
+ assert topped[key] == bare[key], key
+ # The chest moves alike under both: what the follow-through changed in the chest is the same pixels.
+ moved = [np.asarray(Image.open(p/'walk.strip.png').convert('RGBA')) for p in (tmp_path/'bare', tmp_path/kind)]
+ source = [np.asarray(Image.open(p/follow.SOURCE).convert('RGBA')) for p in (tmp_path/'bare', tmp_path/kind)]
+ changed = [(m != s).any(axis=-1) for m, s in zip(moved, source)]
+ assert changed[0].any() and np.array_equal(changed[0], changed[1])
+ assert np.array_equal(moved[0][changed[0]], moved[1][changed[1]])
+
+
+def test_a_cell_with_no_core_is_refused(tmp_path):
+ # A cell whose body is nowhere a quarter as deep as cell 0's has nothing to lay on cell 0's.
+ def draw(k):
+ if k != 5:
+ return walker(k)
+ im = Image.new('RGBA', (160, 200))
+ ImageDraw.Draw(im).line((80, 20, 80, 190), fill=(20, 90, 180, 255), width=5)
+ return im
+ loop_dir = strip_dir(tmp_path/'thin', draw)
+ as_cut = (loop_dir/'walk.strip.png').read_bytes()
+ with pytest.raises(SystemExit, match=r"^video-follow: cell 5 has no body as deep as a quarter of cell 0's \(\d+ px\)$"):
+ follow.follow_loop(loop_dir, [(80.0, 83.0, 22.0, 17.0)])
+ assert (loop_dir/'walk.strip.png').read_bytes() == as_cut
+ assert 'follow' not in json.loads((loop_dir/'walk.strip.json').read_text())
+
+
def test_the_part_lags_and_settles_without_a_kick():
# One cycle of a smooth bob: the answer is as smooth (no frame-to-frame jump far beyond the rest)
# and closes on itself, since it is the loop's steady state.
@@ -295,8 +357,8 @@ def test_regions_that_take_one_gain_are_written_as_one_gain(loop_dir):
rec = json.loads((loop_dir/'walk.strip.json').read_text())['follow']
assert rec['fold']['lowered'] is True and follow.GAIN_MEASURED <= rec['gain'] < follow.GAIN_DEFAULT
assert [sorted(e) for e in rec['fold']['regions']] == [['gain_limit', 'radius_px', 'ratio']]*2
- assert sorted(rec) == ['body_bob_px', 'body_px', 'dx_px', 'dy_px', 'fold', 'freq_hz', 'gain', 'gain_requested', 'gif',
- 'harmonics', 'on_fold', 'reach_px', 'regions', 'source', 'webp', 'zeta']
+ assert sorted(rec) == ['body_bob_px', 'body_px', 'body_worn_px', 'dx_px', 'dy_px', 'fold', 'freq_hz', 'gain', 'gain_requested',
+ 'gif', 'harmonics', 'on_fold', 'reach_px', 'regions', 'source', 'webp', 'zeta']
assert sorted(rec['fold']) == ['lowered', 'ratio', 'reach_per_gain_px', 'reach_requested_px', 'regions']
lowered = (loop_dir/'walk.strip.png').read_bytes()
follow.follow_loop(loop_dir, [a, b], gain=result['gain'])