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 lays each cell a second time, on what the cells have in common

Soohong Kim5eac204468ae
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5d0459b..86ce963 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,8 +4,8 @@ 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.
+- **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. A part as thick as the body outlasts the wearing — ears as wide as the head — and a cell that has it elsewhere than the first cell does, laid on the first cell alone, lies ears on ears with its body tens of pixels off, so the read jumped there too. The cells are therefore laid twice: laid on the first cell, each is moved back by its lay and the cells are counted — per level and pixel, how many more of them are in that level there than are not, and none where no more are — and each cell is then laid on that count the same way; its lay less the first cell's own is the motion. The head and torso are at one place in every cell and count in full; ears up in some cells and flopped onto the face in others, or a leg forward and back, are at any one place in half of the cells or fewer and count nothing. A thick part that keeps one place in most of the cells is body to this read, which sees outlines only. **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)`; so is a strip with no part of the body at one place in more than half of its cells: `video-follow: no part of the body is at one place in more than half of the cells`. Reading the motion is two lays of every cell: on an Apple M1, one thread, 0.5 s for 24 cells of 210 × 240 px, 16 s for 24 cells of 630 × 720 px (11 s for one lay), and 110 s for 64 cells of 700 × 700 px around one disc 640 px across (58 s for one lay). [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. It also follows a chest on a bunny whose lop ears, more than half as thick as its body is wide, swing down and back up once a cycle: the record and the chest's moved pixels are the earless bunny's. Laid on the first cell alone, the body was read as dropping with the ears by up to 30 px in 8 of the 24 cells and as jumping back in the next, and the chest was refused (a move at gain 1 of 16.1 px, no more than gain 0.94). A strip whose cells share no place — a bar, and in each other cell a block at a different place along it — 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 9098058..77c00c9 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -1032,10 +1032,21 @@ sprite-gen video-follow --loop-dir set/front-walk/loop --region 136,164,60,50 [-
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
+ shallower levels. A part as thick as the body outlasts the wearing — ears as wide as the head —
+ and a cell that has it elsewhere than the first cell does, laid on the first cell alone, lies
+ ears on ears with its body tens of pixels off. So the cells are laid twice. Laid on the first
+ cell, each is moved back by its lay and the cells are counted: per level and pixel, how many
+ more of them are in that level there than are not (none, where no more are). The head and
+ torso are in every cell at one place and count the whole number of cells; what swings — ears
+ up in some cells and flopped onto the face in others, a leg forward and back — is at any one
+ place in half of the cells or fewer and counts nothing. Each cell is then laid on that count
+ as it was on the first cell, and its lay less the first cell's own is the motion. A thick part
+ that keeps one place in most of the cells is body to this read, which sees outlines only. 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
+ cell's body is refused, and so is a strip with no part of the body at one place in more than
+ half of its cells. 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`
diff --git a/sprite_gen/video/follow.py b/sprite_gen/video/follow.py
index 468adb6..ece0770 100644
--- a/sprite_gen/video/follow.py
+++ b/sprite_gen/video/follow.py
@@ -11,7 +11,10 @@ each cell's body lies from the first cell's. The silhouette is worn down from a
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
+is still in, and then laid again on what the cells so laid have in common: what more than half of
+them have at one place, so a part as thick as the body that is elsewhere in another cell (ears as
+wide as the head, up in one cell and on the face in the next) does not pull that cell onto itself.
+(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
@@ -102,23 +105,24 @@ def depth(solid: np.ndarray) -> int:
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():
+def _levels(solid: np.ndarray, worn: range) -> tuple[np.ndarray, int, int] | None:
+ """`solid` worn down by each of `worn`, as one number per pixel: how many of those levels the pixel is still
+ in. Each level lies inside the one before, so level i is where that number is over i. Cut to the box of the
+ first level, with that box's top and left; None when nothing is left of `solid` worn down by the first."""
+ level = wear(solid, worn[0])
+ if not level.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]
+ ys, xs = np.nonzero(level.any(axis=1))[0], np.nonzero(level.any(axis=0))[0]
+ level = level[ys[0]: ys[-1] + 1, xs[0]: xs[-1] + 1]
+ inside = level.astype(np.int32)
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])
+ inside += level
+ return inside, int(ys[0]), int(xs[0])
def _fft_length(n: int) -> int:
@@ -133,25 +137,54 @@ def _fft_length(n: int) -> int:
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
+def _overlay(onto: tuple[list[np.ndarray], int, int], levels: tuple[np.ndarray, int, int]) -> tuple[int, int]:
+ """The shift (dx, dy) of a cell from what it is laid on: where `onto` — per level a whole number at every
+ pixel, with its top and left — moved by it, lands on the cell's own levels most, the numbers that land on
+ the cell's pixels summed at every level and the levels summed."""
+ (a, ya, xa), (b, yb, xb) = onto, 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)
+ height, width = a[0].shape[0] + b.shape[0] - 1, a[0].shape[1] + b.shape[1] - 1
+ shape = (_fft_length(height), _fft_length(width))
+ # overlap[i, j]: what of `onto` lands 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((b > i).astype(np.float64), shape) * np.fft.rfft2(la[::-1, ::-1].astype(np.float64), shape)
+ for i, la in enumerate(a))
+ # Sums of whole numbers 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.rint(np.fft.irfft2(spectrum, shape)[:height, :width]).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 _common(levels: list[tuple[np.ndarray, int, int]], lays: list[tuple[int, int]],
+ count: int) -> tuple[list[np.ndarray], int, int] | None:
+ """What the cells' bodies have in common, each cell moved back by its lay: per level (`count` of them) and
+ pixel, how many more of the cells are in that level there than are not (none, where no more are), cut to
+ the box of what is left, with that box's top and left; None when no pixel is in more than half of the cells.
+
+ The head and torso are in every cell at one place and count the whole number of cells. What swings and is
+ thick enough to outlast the wearing — an ear as wide as the head, up in some cells and flopped onto the
+ face in others; a leg forward and back — is at any one place in half of the cells or fewer, and counts
+ nothing. A thick part that keeps one place in most of the cells counts as the body does: outlines alone
+ do not tell the two apart."""
+ tops = [top - dy for (_, top, _), (_, dy) in zip(levels, lays)]
+ lefts = [left - dx for (_, _, left), (dx, _) in zip(levels, lays)]
+ top, left = min(tops), min(lefts)
+ height = max(t + inside.shape[0] for t, (inside, _, _) in zip(tops, levels)) - top
+ width = max(l + inside.shape[1] for l, (inside, _, _) in zip(lefts, levels)) - left
+ cells_in = np.zeros((count, height, width), np.int32)
+ level = np.arange(count)[:, None, None]
+ for (inside, _, _), t, l in zip(levels, tops, lefts):
+ cells_in[:, t - top: t - top + inside.shape[0], l - left: l - left + inside.shape[1]] += inside > level
+ more = np.maximum(0, 2 * cells_in - len(levels))
+ # Each level lies inside the one before, in every cell: the first level's box holds them all.
+ ys, xs = np.nonzero(more[0].any(axis=1))[0], np.nonzero(more[0].any(axis=0))[0]
+ if not len(ys):
+ return None
+ return list(more[:, ys[0]: ys[-1] + 1, xs[0]: xs[-1] + 1]), top + int(ys[0]), left + int(xs[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.
@@ -163,7 +196,14 @@ def body_motion(cells: list[Image.Image]) -> tuple[np.ndarray, np.ndarray, int,
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."""
+ is shallower in one cell (an arm swung away from it) still counts at its shallower levels.
+
+ That lay answers to everything left in cell 0, and a part as thick as the body is left: where
+ ears as wide as the head stand up in cell 0 and flop onto the face in another cell, the cell
+ is laid ears on ears, the body tens of pixels off. So the cells are laid a second time, on what
+ they have in common as first laid (`_common`), and that lay, less cell 0's own, is the motion:
+ the ears are at one place in too few cells to count, and the cell lies head on head and torso
+ on torso."""
solids = []
for k, cell in enumerate(cells):
solid = np.asarray(cell.getchannel("A")) >= ALPHA_SOLID
@@ -175,16 +215,21 @@ def body_motion(cells: list[Image.Image]) -> tuple[np.ndarray, np.ndarray, int,
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 = [], []
+ levels = []
for k, solid in enumerate(solids):
- levels = _levels(solid, worn)
- if levels is None:
+ level = _levels(solid, worn)
+ if level 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]]
+ levels.append(level)
+ inside0, top0, left0 = levels[0]
+ lays = [_overlay(([inside0 > i for i in range(len(worn))], top0, left0), level) for level in levels]
+ common = _common(levels, lays, len(worn))
+ if common is None:
+ raise ValueError("no part of the body is at one place in more than half of the cells")
+ lays = [_overlay(common, level) for level in levels]
+ dx0, dy0 = lays[0]
+ return (np.asarray([dy - dy0 for _, dy in lays], float), np.asarray([dx - dx0 for dx, _ in lays], float),
+ height0, [worn[0], worn[-1]])
def follow_offsets(motion: np.ndarray, fps: float, *, freq: float, zeta: float, gain: float) -> np.ndarray:
diff --git a/tests/video/test_follow.py b/tests/video/test_follow.py
index 5f04c14..6e57cd5 100644
--- a/tests/video/test_follow.py
+++ b/tests/video/test_follow.py
@@ -136,6 +136,56 @@ def test_a_cell_with_no_core_is_refused(tmp_path):
assert 'follow' not in json.loads((loop_dir/'walk.strip.json').read_text())
+def bunny(k, ears, period=24):
+ """A front bunny, its head, torso and legs one column that bobs twice a cycle, with or without lop ears out
+ to both sides of its head: each more than half as thick as the column is wide and nearly as long, swinging
+ down and back up once a cycle."""
+ im = Image.new('RGBA', (210, 240))
+ d = ImageDraw.Draw(im)
+ bob = round(3*math.sin(4*math.pi*k/period))
+ d.rectangle((70, 30+bob, 140, 225+bob), fill=(250, 250, 250, 255)) # head, torso and legs
+ d.ellipse((85, 110+bob, 125, 150+bob), fill=(230, 90, 120, 255)) # the soft part
+ if ears:
+ droop = round(60*(1-math.cos(2*math.pi*k/period)))
+ d.rectangle((10, 32+bob+droop, 70, 72+bob+droop), fill=(235, 235, 240, 255))
+ d.rectangle((140, 32+bob+droop, 200, 72+bob+droop), fill=(235, 235, 240, 255))
+ return im
+
+
+def test_ears_as_thick_as_the_body_do_not_move_it(tmp_path):
+ # Ears this thick outlast the wearing, and a cell laid on cell 0 alone lies ears on ears: in the cells where
+ # the ears had swung less than their own thickness from where cell 0 has them the body was read as dropping
+ # with them, by up to 30 px, and as jumping back in the next cell. Laid again on what the cells have in
+ # common, the ears are at one place in too few cells to count.
+ chest = (105.0, 130.0, 24.0, 24.0) # the soft part, as bunny draws it in cell 0
+ bare = follow.follow_loop(strip_dir(tmp_path/'bare', lambda k: bunny(k, ears=False)), [chest], on_fold='lower')
+ eared = follow.follow_loop(strip_dir(tmp_path/'eared', lambda k: bunny(k, ears=True)), [chest], on_fold='lower')
+ assert bare['body_bob_px'] == [0.0, 6.0]
+ for key in ('body_bob_px', 'dx_px', 'dy_px', 'reach_px', 'gain', 'fold'):
+ assert eared[key] == bare[key], key
+ moved = [np.asarray(Image.open(p/'walk.strip.png').convert('RGBA')) for p in (tmp_path/'bare', tmp_path/'eared')]
+ source = [np.asarray(Image.open(p/follow.SOURCE).convert('RGBA')) for p in (tmp_path/'bare', tmp_path/'eared')]
+ 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_cells_with_no_body_in_common_are_refused(tmp_path):
+ # What the cells have in common is what more than half of them have at one place. A bar in cell 0 and a
+ # block at a different place along it in each other cell: no place is in more than two of the four.
+ def draw(k):
+ im = Image.new('RGBA', (160, 200))
+ box = (20, 80, 140, 120) if k == 0 else (20+40*(k-1), 80, 60+40*(k-1), 120)
+ ImageDraw.Draw(im).rectangle(box, fill=(20, 90, 180, 255))
+ return im
+ loop_dir = strip_dir(tmp_path/'apart', draw, n=4)
+ as_cut = (loop_dir/'walk.strip.png').read_bytes()
+ with pytest.raises(SystemExit, match=r'^video-follow: no part of the body is at one place in more than half of the cells$'):
+ follow.follow_loop(loop_dir, [(80.0, 100.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.