Skip to content

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

Merge origin/main (v3.10.0, 2837fd8) into plan/qipao-recut-cell-record-1029: the air retime's cells beside the strip's record of its cells

Soohong Kim95dfb99590da
diff --cc CHANGELOG.md
index b20191b,60bb7bf..1dbd132
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -2,66 -2,28 +2,88 @@@
All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.
+## Unreleased
+
- **Upgrading from 3.8.0: `video-loop` writes `cell_record` into every strip record `<name>.strip.json`, and `video-sway` gains options that shape a `--region-mask` region alongside `--read-on-cut`. Strips, frames and records keep their bytes by default, but `video-sway --read-on-cut` reads cuts by that record alone and refuses cuts made without it.** New options `--region-over` and `--region-shear` shape the region mask and its rim; both are off by default, and when not given, strips, frames, and records remain byte for byte what they were. With `--region-crease` the wear wears the crease in as before; laid over the figure the region reaches down to the crease again in every cell, changing those runs' output. Runs with `--region-over` and runs with `--region-membrane` draw differently than before this change; the four new membrane options are off by default and byte for byte as before when not given. New options `--region-over-solid`, `--region-rim-round`, `--region-membrane` and `--read-on-cut` are off by default; when not given, strips, frames, and records remain byte for byte what they were. Runs with `--read-on` alone behave as before, except that its no-match message now names `--read-on-cut`. The refusal for `--region-over` or `--region-shear` given without `--region-mask` keeps refusing the same runs, and its message now names the new options too: "--region-over, --region-over-solid, --region-rim-round, --region-shear and --region-membrane shape a region mask; they need --region-mask" (it was "--region-over and --region-shear shape a region mask; they need --region-mask").
++**Upgrading from 3.10.0: `video-loop` writes `cell_record` into every strip record `<name>.strip.json`, and `video-sway` gains options that shape a `--region-mask` region alongside `--read-on-cut`. Strips, frames and records keep their bytes by default, but `video-sway --read-on-cut` reads cuts by that record alone and refuses cuts made without it.** New options `--region-over` and `--region-shear` shape the region mask and its rim; both are off by default, and when not given, strips, frames, and records remain byte for byte what they were. With `--region-crease` the wear wears the crease in as before; laid over the figure the region reaches down to the crease again in every cell, changing those runs' output. Runs with `--region-over` and runs with `--region-membrane` draw differently than before this change; the four new membrane options are off by default and byte for byte as before when not given. New options `--region-over-solid`, `--region-rim-round`, `--region-membrane` and `--read-on-cut` are off by default; when not given, strips, frames, and records remain byte for byte what they were. Runs with `--read-on` alone behave as before, except that its no-match message now names `--read-on-cut`. The refusal for `--region-over` or `--region-shear` given without `--region-mask` keeps refusing the same runs, and its message now names the new options too: "--region-over, --region-over-solid, --region-rim-round, --region-shear and --region-membrane shape a region mask; they need --region-mask" (it was "--region-over and --region-shear shape a region mask; they need --region-mask").
+
+- **New: laying a region over the figure and widening the rim for shear (`--region-over`, `--region-shear`).** `--region-over` lays the region over the figure under it instead of pinning its lower edge, freeing held pixels under the edge (solid or not), moving the band within reach, drawing the layer over the band by alpha, drawing the air by the move, and showing the figure under its lower edge at the move where it lifts. Its soft edge moves with the region (except under the lower edge where touching a solid pixel outside keeps it in the band), its solid outline against air goes with the layer, and `--hold-mask` leaves pixels the region mask does not cover out of the layer and band while pixels it covers move with the region. `--region-shear S` widens the rim across and down so a move one way rises across the rim the other way by at most S px per px (`shear_floor`), preventing tears along the sides. With either option, the ledger records move steps between neighbouring pixels, still strips left standing, and tip outline shapes, and `--region-over` records `lifted_px`. Both require `--region-mask`, are off by default, and leave strips, frames, and records byte for byte what they were when not given. See [video-pipeline](docs/video-pipeline.md) section 6.
+- **Changed: wearing the crease row in like every other edge of the mask and reaching down to the crease only when laying a region over the figure (`--region-crease`, `--region-over`).** Removed: the step that filled each crease column back down to the crease row after the mask was worn in (`crease_kept` is gone). Now `--region-crease` ends the mask on the crease before the wear and the wear (`--region-shrink`) wears the whole mask in, the crease row too, like every other edge. So the record's `mask.box` ends `--region-shrink` rows above the crease row (2 rows at the default), as it did before `crease_kept`. New, under `--region-over` only: in every cell the region reaches down to the crease again (`crease_reach`): the crease's rows (its columns and rows on the cell the mask was drawn on; a column between two crease columns takes the nearer one's row, the left one's on a tie) are carried into the cell by the mask's carry there (the column rounded to the nearest, half to even; the row rounded down), and in each crease column where the region holds a pixel, the cell's solid pixels from the region's lowest pixel down to the crease's row join the region. The crease is the picture's own edge, so the layer reaches it in every cell while the wear still wears the mask in everywhere else. Without `--region-over` nothing reaches back down: the worn mask is the region.
+- **New: solid under-edges, round rims, figure membranes, and recut strip pairing (`--region-over-solid`, `--region-rim-round`, `--region-membrane`, `--read-on-cut`).** `--region-over-solid` frees only solid pixels (alpha 128 or more) under the lower edge into the band while keeping softer pixels as anchors, and carries the region's soft edge with it under the lower edge. `--region-rim-round` holds the rim round beside the region across the wider of its two widths (`max(Lx, Ly)`), preventing steep downward steps below corners where the lower edge runs lower. `--region-membrane N` moves the figure under the lower edge within N + 1 px as a membrane by solving 4-neighbour figure means in passes instead of conjugate gradients (from a cos² start, at most 1200 passes, leaving no piece out) so the figure stretches rather than slides, drawing membrane pixels by their move and reporting membrane-specific fold refusals. `--read-on-cut STRIP` pairs regions read on another cut of the same clip by matching source frame numbers and applying a whole-pixel shift across crops on unaligned and aligned loops alike. The shift is taken on the frame as filmed, less where each cut's body or motion anchor moved that frame. Each cut is now read by its record of its cells alone: `cell_record` in the strip's record (`<name>.strip.json`), which `video-loop` now writes, bound to the strip by `cell_record.strip_sha256` (the sha256 of the strip PNG), with one entry per cell: `source_frame`, `anchor_move_px` (where the anchor moved that frame before the crop, whole px across and down), `scale` (`size_hold` and `gait_fallback`: the factor each step that holds a clip's frames to one size scaled that frame by, 1 where it did not hold them) and `as_filmed` (true where the cell's pixels at the end of the cut are its pixels anchored before any repair, the receipt `source_projection.before_repair_pixels_sha256` in the cut's report, and no step held the clip's frames to one size). On a loop aligned from its cut it reads the cut's own record, which `video-cycle-align` now keeps beside the cut's frames as filmed (`cycle.source/<name>.strip.json`) and which must be bound to the strip the alignment's origin names (`cycle_align.origin.strip_sha256`). It refuses, no-match, saying which and naming the field: a cut with no `cell_record` (any cut made before this release), a record bound to another strip, a record that does not give its cells as `video-loop` writes them (a field missing or not of its kind, in any cell), a loop aligned from its cut with no kept record, a paired cell a hold scaled or not cut as filmed, and two paired cells that are not the same pixels where they overlap at the shift (a record changed to call a cell as filmed is held to the cell's pixels). The report beside a cut is no longer looked for or read. All four options are off by default and leave strips, frames, and records byte for byte what they were when not given. See [video-pipeline](docs/video-pipeline.md) section 6.
+- **New: the membrane's own keys (`--region-membrane-unpin`, `--region-clear-alpha`, `--region-floor-beside`, `--region-own-outline`).** `--region-membrane-unpin` makes what the membrane moves no anchor of the rim either, so the region's move does not fall to none at its first rows under its lower edge. `--region-clear-alpha A` (a whole number from 1 to 127) reads a pixel under alpha A as clear by the sets the region moves and holds and by the membrane's figure while the cell's bytes stay its own, so a speck of dust beside the figure holds nothing. `--region-floor-beside N` sets the lower edge beside the region's columns to the lowest pixel of its columns within N px of that side, not that of its nearest column alone. `--region-own-outline G` grows the region G 4-neighbour steps over the cell's solid pixels within G 4-neighbour steps of a clear pixel before the sets (never under its lower edge's line and never over pixels `--hold-mask` leaves out), moving the outline its carried mask leaves out with the region. All four require `--region-mask`, shape nothing without `--region-membrane` (leaving the same bytes and record, naming none of them), are off by default, and leave strips, frames, and records byte for byte what they were when not given. See [video-pipeline](docs/video-pipeline.md) section 6.
- - **Output change: `cell_record` in strip records, `source_projection` for motion anchors, and kept cut strip records.** `video-loop` now writes `cell_record` into every strip record it writes (the fields above). The strip PNG, the GIF, the WebP and the frames of `cycle/` keep their bytes; the strip record gains this one key. A cut's report gains `source_projection` (`recipe`, `wrap_dx_px`, `before_repair_pixels_sha256`) at `--anchor motion` and `--anchor motion-auto` too, with `recipe` `motion-anchor-correction-v1` there; it was written only at `--anchor none` and `body` before (unchanged there). `cell_record` is written in the strip record only, not in the report's copy of it. `video-cycle-align`'s first alignment of a loop now also writes `cycle.source/<name>.strip.json`, the loop's strip record as cut, byte for byte, before it rewrites `<name>.strip.json`; later alignments leave it as it is, and a new cut with `video-loop` removes it with `cycle.source/`. The aligned strip's record does not carry `cell_record` (it is the record of another strip). The pair policy `RECUT_POLICY` is now `same-clip/source-frame/whole-px-shift/2`. At `--out-fps` (3.8.0: cells each made at a time of their own, more cells than the cut has frames), the report's `held_fill.out_fps` gains `shows` (per cell, the frame of the cut it is, or null where it was made), and `cell_record` still holds one entry per cell: `source_frame` is the frame the cell is, and for a cell made between two frames the cut's frame at or before its time (the frame the seam reads it as), with that frame's `anchor_move_px` and `scale`. `as_filmed` is true only where the cell's pixels are that frame's pixels anchored before any repair, so a cell that repeats a frame unchanged is as filmed, and a cell made between two frames is not, and `video-sway --read-on-cut` does not pair it.
++- **Output change: `cell_record` in strip records, `source_projection` for motion anchors, and kept cut strip records.** `video-loop` now writes `cell_record` into every strip record it writes (the fields above). The strip PNG, the GIF, the WebP and the frames of `cycle/` keep their bytes; the strip record gains this one key. A cut's report gains `source_projection` (`recipe`, `wrap_dx_px`, `before_repair_pixels_sha256`) at `--anchor motion` and `--anchor motion-auto` too, with `recipe` `motion-anchor-correction-v1` there; it was written only at `--anchor none` and `body` before (unchanged there). `cell_record` is written in the strip record only, not in the report's copy of it. `video-cycle-align`'s first alignment of a loop now also writes `cycle.source/<name>.strip.json`, the loop's strip record as cut, byte for byte, before it rewrites `<name>.strip.json`; later alignments leave it as it is, and a new cut with `video-loop` removes it with `cycle.source/`. The aligned strip's record does not carry `cell_record` (it is the record of another strip). The pair policy `RECUT_POLICY` is now `same-clip/source-frame/whole-px-shift/2`. At `--out-fps` (3.8.0: cells each made at a time of their own, more cells than the cut has frames), and at `--out-fps` with the air retimed, the report's `held_fill.out_fps` gains `shows` (per cell, the frame of the cut it is, or null where it was made), and `cell_record` now reads a retimed cut the same way as a cut at `--out-fps`: `source_frame` is the frame the cell is, and for a cell made between two frames the cut's frame at or before its time (the frame the seam reads it as), with that frame's `anchor_move_px` and `scale`. `as_filmed` is true only where the cell's pixels are that frame's pixels anchored before any repair, so a cell that repeats a frame unchanged is as filmed, and a cell made between two frames, a cell moved onto the parabola or along, and every cell of a cut the retime laid on a larger canvas are not as filmed, and `video-sway --read-on-cut` does not pair them. The cells before the take-off that the retime neither moved nor laid on a larger canvas stay as filmed.
+- Python callers: `sway_loop`, `sway_frames`, `read_request` and `read_ask` accept `region_over` (bool; default False) and `region_shear` (float; None: off). New in `sprite_gen.video.sway`: `shear_floor`, `layer_sets`, `lay_over`, `cover_depth`, `still_strip`, `tip_shape` and `move_steps`; constants `OVER_POLICY`, `TIP_COLS`, `TIP_AIR`, `TIP_RING`, `TIP_OFF` and `TIP_SEARCH`; `RegionMask` gains `over`, `shear`, `hold` and `edges()`; `Masked` gains `sheared`, `left_out` and `left_out_in(k)`; `rim_bands` gains `floor` (None: as before).
+- Python callers: `sway_loop`, `sway_frames`, `read_request` and `read_ask` accept `region_over_solid` (bool; default False), `region_rim_round` (bool; default False) and `region_membrane` (int; None: off); `sway_loop` and `read_request` accept `read_on_cut` (Path; None: off, refused by `sway_frames`). New in `sprite_gen.video.sway`: `membrane_sets`, `membrane_move(free, figure, own, outline, move, reach)`, `recut_pair`, `recut_ask` and `read_cut`; new in `sprite_gen.video.loop`: `ramp_offset`; new in `sprite_gen.video.motion_anchor`: `laid_at`; constants `OVER_SOLID_POLICY`, `MEMBRANE_POLICY`, `RECUT_POLICY`, `RECUT_DRIFT` and `RIM_ROUND_POLICY`; `RegionMask` gains `over_solid`, `membrane` and `rim_round`; `Request` gains `read_on_cut`; `layer_sets(..., solid_only=False)` gains `solid_only` and returns the new set `below`; `read_on_relation(..., cut=False)` gains `cut`; and `transported_motion(..., paired=None)` gains `paired`. New in `sprite_gen.video.sway`: `cell_record(record, strip_sha256)` (the record of a strip's cells, a ValueError naming what it does not give), `recut_same(pair, cut_cell, cell, read_on)` (refuses two paired cells that are not the same pixels at the shift) and `aligned_from(loop_dir, meta_path, meta)` (the cut's record an alignment kept, or None); `recut_pair(meta, cut, read_on, *, strip_sha256, kept=None)` takes this loop's strip sha256 and the kept record; `read_cut` returns the strip picture under `strip`; `Request` gains `aligned_from`; new in `sprite_gen.video.loop`: constants `CELL_RECORD`, `CELL_SCALE_STEPS` and `MOTION_RECIPE`.
+- **Tests**: new file `tests/video/test_sway_region_over.py` covers these cases on synthetic figures (the region test's body and its striped part over the torso's right side and past it over the air, with a dark crease under it on the torso; an arm block beside the part's lower left; a dark outline row under the part where it hangs over the air). Each case first reads what a sway writes with the new options (its cells, its record), so on a release without them the same input fails on what comes out:
+ - without the new options nothing of them is read or written (cells and record as before, from Python with them passed off);
+ - with `--region-crease` the wear wears the crease in with the rest (the worn mask's lowest row on the torso 2 rows over the crease, its box ending there), nothing under the crease moves, and laid over the figure the region reaches down to the crease again in every cell (its lowest pixel on the crease's row in each crease column);
+ - laid over the figure under it, the lower edge moves as much as the part above it does (at gain 2.5 and 1.25), while without `--region-over` the crease pins it;
+ - the layer draws the band where it lands, no read of the move taken there, and keeps its bytes elsewhere; the move draws the air (reads are taken there); a read in the air that takes the held figure beside it (the torso's soft side past the band) is walked back, in the air alone and never on the band (4, 9 and 6 reads in three cells, none in the others); nothing outside the region, its soft edge, the air and the band changes; the layer covers no deeper than the band; nothing folds;
+ - where the part lifts it shows the figure under it: each pixel there is read at its whole move, none read short, its alpha the source's read there; read wholly on opaque pixels it stays opaque and shows the torso and the crease, not the stripes; beside the torso's soft side one column of the part's, within 2 px of that side, is as soft as its read of that side and the air past it (in 7 of the 12 lifting cells); in the rows the part leaves, its column over the torso's soft side shows thinner than that side in exactly the cells where the part moves toward the torso;
+ - its outline against the air goes with it and leaves the air behind, and its outline against the figure (the crease) keeps its bytes;
+ - two new cases for `--hold-mask` with `--region-over`: the pixels it names that the region mask covers (a piece in the arm's colour inside the part) are the region's, no anchors, and move with the part (one PNG carried and a folder per cell); the pixels it names that the region mask does not cover keep their bytes in every cell, and on a band (`--band auto` with the same `--hold-mask`) every pixel it names keeps its bytes while the part moves round them;
+ - where the part lifts off a piece in the arm's colour right under its lower edge, left out with `--hold-mask`, the part's reads that would take the piece are read from their other pixels (10 in every lifting cell), none of them lifted and all opaque: no hole opens and the piece keeps its bytes;
+ - `--region-shear` 0.5 and 0.25 widen the rim to the least it asks, so the drawn move's step across the rim stays within the bound, and less than without it;
+ - the still strip is read from the region to its side (beside the arm, the px the mask left short; over the air, 0);
+ - the tip is read on the side over the air; a tip moved whole is 0 px off its own shape, its shift found;
+ - `move_steps` reads the most step both ways where both pixels are shown;
+ - `--frames` gives the strip's cells and the same record;
+ - each refusal leaves the loop as it was.
+ `tests/video/test_sway_region.py`'s crease case now reads the worn mask's box ending 2 rows over the crease row. `tests/video/test_follow_inspect.py` now names `--region-over` and `--region-shear` among the arguments `video-sway` takes and `video-sway-inspect` does not.
+- **Tests**: updates to `tests/video/test_sway_region_over.py` and new file `tests/video/test_sway_read_on_recut.py` cover these cases on synthetic figures (the region tests' body with a striped part over the torso's right side and past it over the air; the read-on runner):
+ - over-solid: only solid pixels under the lower edge are free and drawn over; the not-opaque rest stays, an anchor, with bytes kept; the soft edge under the lower edge beside the torso goes with the part, while sliding over without the flag it belongs to the figure;
+ - the membrane at reach 3 and 6: under the lower edge within reach + 1 px, never the outline over the band; each pixel's move is the mean of its figure 4-neighbours' to within less than `MEMBRANE_STEP` (what one more pass would move it), and the record names `step_px` and `passes_most`; the seam step down from the part's last row is at most half of the one sliding over; drawn by the move, never laid over;
+ - the membrane never moves a piece left out (stops at its sides); without the membrane the layer is as it was;
+ - a membrane too short for the move is refused by its name, writing nothing;
+ - below the corner of a part whose lower edge falls from its left side, with `--region-rim-round` the move rises down by at most pi/2 of its size over the rim's wider width, and more than that without the flag;
+ - the refusals list gains each new option's refusal;
+ - without the membrane the four new options shape nothing (the same bytes and record);
+ - the four new options' refusals (each without `--region-mask`, and the values `--region-clear-alpha` 0 and 128, `--region-floor-beside` -1, `--region-own-outline` -2) leave the loop as it was;
+ - two defect shapes, each red on the engine before this change: a part laid over the figure with a few pixels not opaque (alpha 60 and 30) a few rows under its lower edge over the air and a near-clear speck (alpha 3), with `--region-over-solid`, `--region-membrane 6` and `--region-shear 0.35`: with `--region-membrane-unpin` and `--region-clear-alpha 8` the lower edge over the air moves with the part (lag 0.25 px or under), without them it stays short of the move (0.5 px or more), and under the clear alpha the speck is neither held nor the membrane's; and a part whose outline over the air takes one or two pixels past its mask in a row that changes from cell to cell, with `--band-up 0.4` and `--region-membrane 6`: with `--region-own-outline 2` those pixels are the region's and the side moves by each row's share of the move (lag 0.25 px or under), without it they are anchors and the side bends at a row that changes from cell to cell (0.5 px or more);
+ - `--region-floor-beside`: beside a region whose lower edge falls 1 px a column, the lower edge past each side is that of its lowest column within N of that side (directly on `layer_sets`);
+ - the frames path gives the strip's cells with `--region-membrane 6`;
+ - in new file `tests/video/test_sway_read_on_recut.py`, a cut again at the same frame with a wider crop moves the regions and the mask by the crop's shift and gives the sway on the regions drawn there by hand;
+ - a cut again at another start moves the mask onto the cell that is that frame, pixel for pixel, with every pixel outside it kept;
+ - a cell elsewhere in either cut that its record calls scaled or not as filmed leaves the pair as it is;
+ - a loop aligned from the cut again carries the pair through the alignment; the alignment keeps the cut's strip record byte for byte beside its frames (`cycle.source/<name>.strip.json`), bound to the strip its origin names, and a second alignment keeps it as it was; the aligned strip's record holds no `cell_record`;
+ - on a loop aligned from its cut, these are refused, each saying which: a kept record that is gone, a kept record that holds no `cell_record`, a kept record bound to another strip, a paired cell its kept record calls not as filmed, and the read cut's cell drawn between the frames either side with its record changed to call it as filmed;
+ - two cuts at `--anchor body` whose ramps move frame 4 by nothing in the first and by -6 px in the second pair that frame where each ramp moved it: shift (0, 0), no drift, the moved mask is the patch where the second cut drew that frame, pixel for pixel; the crops alone set it 6 px apart;
+ - two cuts at `--anchor body` whose ramps move no frame (both `wrap_dx_px` 0) pair by their crops alone, as before, the mask landing on the patch there;
+ - two cuts at `--anchor motion` (head and torso regions on each cut's first frame) pair the frame where each correction laid it: the shift is the crops' less where the first correction laid that frame plus where the second laid it, not the crops' alone, and the mask lands on the patch there; each cell's `anchor_move_px` is the correction's place and every cell is as filmed; the report's `source_projection` names the motion recipe;
+ - `video-loop` records each cell of its strip in the strip's record bound to its PNG: the source frame, the body ramp's move, no hold's scale, as filmed; the record is written beside the strip and not into the report, whose receipt holds one digest per frame;
+ - a cell the jump repair gave way (a filmed ghost, no RIFE) is recorded not as filmed, every other cell as filmed;
+ - refusals: a frame this loop does not hold, a record with no clip it is cut from, and without `--read-on-cut` the relation's refusal as ever, each leaving the loop as it was;
+ - a record of its cells not there or not as `video-loop` writes it is refused naming the field, on either cut: none, not an object, bound to another strip or none, no cells or one too few, a cell's entry, its `source_frame`, `anchor_move_px`, `scale`, and `as_filmed` missing or not of its kind (float, text, boolean, zero, NaN);
+ - a paired cell its record calls scaled by the size hold or the gait fallback, or not as filmed, is refused saying which, on either cut;
+ - a cell an interpolator made, on either cut, is refused whatever its record says: as `video-loop` records it (not as filmed), and with its record changed to call it as filmed (its pixels are not the other cut's at the shift);
+ - a loop aligned from its cut (`video-cycle-align`) named by `--read-on-cut`, and a cut of another clip, are refused, and what the key is refused for leaves the loop as it was;
+ - the walk away from the camera of the gait fallback tests, cut by `video-loop` with and without the size hold: the record gives the factor the size hold scaled each cell by, equal to the report's `size_hold.cut_frames`, and calls none of the held cells as filmed;
+ - the same walk cut twice by `video-loop` as a walk with the size hold on for one cut, for the other, and for both is refused, leaving the loop as it was, the record of the held cell naming its factor;
+ - the same walk held in one cut with every trace of the hold and walk taken out of the report and strip record (the report's `size_hold`, the report's `state`, the report's strip's `state`, the strip record's `state`) is refused by the record of its cells; with the record's factors and `as_filmed` taken out too, refused naming the field; with the strip record's `cell_record` taken out, refused as a record with none; with the record changed to call every cell as filmed, refused by its pixels on either cut;
+ - the command line reads the relation `recut`.
+ `tests/video/test_follow_inspect.py` now names `--region-over-solid`, `--region-membrane`, `--read-on-cut`, `--region-rim-round`, `--region-membrane-unpin`, `--region-clear-alpha`, `--region-floor-beside` and `--region-own-outline` among the arguments `video-sway` takes and `video-sway-inspect` does not.
+
+ ## v3.10.0 - Root motion on single-play cuts, their air retimed on a given gravity, length and speed (--air-retime), and a caller-named single play (--cycle once --start --length)
+
+ **Upgrading from 3.9.0: a cut played once with a body (`video-loop --cycle once`, `once-return`, `one-shot`, and so `video-set`'s single-play states) gains `root_motion` in its report and strip metadata: each cell's root, what it stands on, and its airs. Its cells and every other key keep their bytes and values. The air is drawn again only when asked (`--air-retime`).**
+
+ - **New: root motion on every cut played once.** `root_motion` gives each cell's root (the subject's mass centre, as `inspect-motion`'s `centroid_px`, in cell px), the floor's row (`ground_y`), the runs of cells on the ground or in a contact the caller names (`--contact hand=12:20`, frames of the clip), and each air: its take-off and landing cells, the seconds between them, its apex and the cell it peaks in. With `--meters-per-px M` it adds each root in metres from the first cell's (`root_m`) and each apex in metres. A game reads `root` to place each cell and moves the body on its own physics. `video-loop` prints each air in one line (`air 0.42 s, apex 0.21 m`) and `video-set` puts `loop.air` on each item.
+ - **New: `video-loop --air-retime gravity=G,air=T,speed=V`** (and `video-set --air-retime`). Each air with its take-off and landing in the cut is given `T` seconds, `G` m/s² and `V` m/s along, any of them, each the clip's own where not given; `G` and `V` need `--meters-per-px`. The air's cells are spread evenly over its new seconds, each the clip's pose at the same share of its air, made with RIFE between two frames where it falls between them (the held-cell fill's frames, judged the same way), and moved whole onto the parabola from the take-off's root to the landing's; the landing and the cells after it move along with it, so a planted foot stays planted. The take-off, the landing and the cells on the ground before it are the frames as filmed. The strip metadata's `air_retime` records each air's seconds and apex before and after, the gravity and speed used, how far along it moved, the cells made and the poses over cells. With no RIFE and a frame to make, the air is cut as filmed and a warning names the motion and the install line. A loop, or a cut with no such air, is cut as filmed and says why. A retimed cut is not restored from its source frames (`video-loop-repair`).
+ - **New: `video-loop --cycle once --start S --length L`** plays exactly those frames once (`terminal.kind: given`): a move cut out of a longer motion that settles on no pose, such as a vault in a run. Before, a single-play cut refused `--start` and `--length`.
+ - Python callers: `sprite_gen.video.root_motion` (`parse_retime`, `parse_contacts`, `clip_floor`, `root`, `touching`, `reading`, `read`, `sidecar`, `said`, `apex`, `retime`, `public`); `held_fill.at_times` (a cell at each given time, taken out of `upsample`); `qa.motion.centroid` and `qa.motion.contact_spans` (were `_contact_spans`); `nonloop.on_floor`, `nonloop.GROUND_PX`, `nonloop.given_ending`; `loop.run_loop(..., air_retime=, meters_per_px=, contacts=)`; `batch.run_set(..., air_retime=, meters_per_px=)`.
+ - **Docs**: [video-pipeline.md](docs/video-pipeline.md) section 4, "Root motion" (the keys, how a game reads `root`, the mass centre and not a body part, `--cycle once --start --length`, the air retimed, what it takes from sprite-gen); `SKILL.md` (tell the user each air's seconds and apex).
+ - **Tests**: `tests/video/test_root_motion.py` with `tests/video/jump_inputs.py` (a synthetic jump whose mass centre flies a parabola under a known gravity: the root read within half a pixel, the air's cells, seconds and apex, the ground and a named hand contact; the air doubled peaks at g T²/8 with twice its cells, every cell on the parabola, none shown again, the take-off and the ground before it byte for byte, the landing moved along whole, and through real RIFE (`real_rife`) every between made and judged; the air alone keeps the clip's gravity; no RIFE cut as filmed with the motion named; the six cuts `tests/video/test_held_fill.py` pins keep their pictures as decoded (`tests/picture_digest.py`) and every metadata value but the new key, the keyed clip's file sha read against the run's own files; the refusals; `video-set` hands the handle on).
+
+ ## v3.9.0 - Provider address environment variables, subscription logins off, and the capabilities verb
+
+ **Upgrading from 3.8.0: nothing changes unless you set one of the new variables. Each provider's calls can go to another address (`SPRITE_GEN_OPENAI_BASE_URL`, `SPRITE_GEN_XAI_BASE_URL`, `SPRITE_GEN_ANTHROPIC_BASE_URL`, `SPRITE_GEN_ELEVENLABS_BASE_URL`), `SPRITE_GEN_LOGINS=off` runs every call on its API key, and the new verb `sprite-gen capabilities` prints every verb and argument as one JSON line. Unset, every request goes where it went with the same bytes, and every output keeps its bytes except `sprite-gen --help`, which lists the new verb.**
+
+ - **New: provider addresses.** Each of the four providers sprite-gen calls over HTTP has a variable that replaces its documented address (the API root with its version path, `https://api.openai.com/v1`, `https://api.x.ai/v1`, `https://api.anthropic.com/v1`, `https://api.elevenlabs.io/v1`). It is read when each request is made, not at import, so a value set or changed after the engine is imported is followed. Unset, empty or blank is the documented address. It moves every direct call: OpenAI images, edits and vision checks; Grok images, edits and vision checks, the video facing check, the video requests, polls and `video-resume`; Anthropic messages and Message Batches; ElevenLabs sound. A value that is not an `http://` or `https://` address with no query or fragment stops the call naming the variable.
+ - **New: a URL a provider hands back is fetched through the same address.** With `SPRITE_GEN_XAI_BASE_URL` set, the finished clip is downloaded as `GET <value>/sprite-gen/fetch?url=<the clip's URL, percent-encoded>`, first without a token and once more with the bearer token after a 401 or 403, as before. With `SPRITE_GEN_ANTHROPIC_BASE_URL` set, a batch's results file comes the same way with the API key. A relay that forwards the provider's API forwards these too. Unset, the URL is fetched where it points.
+ - **New: `SPRITE_GEN_LOGINS=off`.** No subscription login is read: the grok login file (and `GROK_HOME`) is not looked at and `XAI_API_KEY` is used, `claude auth status` is not run and `ANTHROPIC_API_KEY` is used, and codex is not usable (`codex login status` is not run; a default codex asks or runs what you chose for a codex that cannot run, naming the variable, and `--provider codex` stops). Each key keeps its rule: set but empty is refused, and a missing key stops the call naming the key and the variable. Unset or empty is `on`, the order as before; any other value is refused.
+ - **New: `sprite-gen capabilities`.** One JSON line: every verb (domain, description, old names, sub-verbs) and every argument as the CLI's parser holds it (spellings, type, how many values, default, required, choices, groups of which one is given), the providers each verb may call and whether it may be billed (`video-resume` calls xAI and buys nothing), and the provider and login variables. It is read off the parser, so a verb or flag added to the CLI is listed with nothing else written. At this release it is 42,227 bytes, where every `--help` together is 158,857.
+ - Python callers: new module `sprite_gen.gen.address` (`PROVIDERS`, `base`, `url`, `fetched`, `FETCH_PATH`), `sprite_gen.gen.base.LOGINS_ENV`, `LOGINS_OFF` and `logins_on`, new module `sprite_gen.workflow.capabilities` (`document`, `PROVIDER_CALLS`, `NO_PURCHASE`). Removed: the module constants `xai.API_BASE`, `openai_provider.API_BASE`, `anthropic_api.API_BASE` and `sprite_gen.audio.provider.BASE`, which kept a provider's address where a variable could not move it; `video` no longer copies the xAI address at import.
+ - **Tests**: `tests/gen/test_provider_address.py` (every call site against a local relay, the address unset, empty and blank, a value changed after import, the relay given the request's bytes, the clip and results file fetched through it, refused values, no module but the registry naming an address and none reading it at import), `tests/gen/test_logins_off.py` (each route on and off, the empty key refusal kept, codex's question and refusals, the access check), `tests/workflow/test_capabilities.py` (the document against the parser and every verb's printed options, a verb or flag added is listed, the providers, the size against every `--help`).
+
## v3.8.0 - Held cells found and filled with in-betweens by default, and a cut given above its clip's frame rate (--out-fps)
**Upgrading from 3.7.0: `video-loop` (and so `video-set`) now finds neighbour cells of a cut that show the same picture and, by default, makes them again with RIFE's frames between. A cut with no such cell comes out byte for byte as before. A cut with them comes out with its held cells made, its length, beat, first and last cells and wrap unchanged. `--fill-held off` cuts as before. Every cut's report and strip metadata gain `held_fill`.**
diff --cc docs/video-pipeline.md
index fdf7861,d87a9ed..a1c38ca
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@@ -727,82 -796,8 +802,85 @@@ place of the body, and a stretched loo
names the strip they were read on — its file's sha256, as cut, before any follow-through (64
lowercase hexadecimal digits; anything else is refused before anything is read):
-- **`no-match`**, refused: neither — another clip, another cut, a strip nothing here was cut or
- aligned from. Locate the regions again on this strip.
+- **`recut`**: the regions were read on another cut of this loop's own source clip, given by
+ `--read-on-cut STRIP`. It pairs the cuts when both records name the same source in `source_cut`
+ (its `source`) and this loop's cut holds the source frame of the cut's cell 0, at its cell j.
+ The report `video-loop` wrote beside a cut is no longer looked for or read for `--read-on-cut`,
+ and need not be beside the strip. Each cut is now read by its record of its cells alone.
+ `video-loop` writes it in the strip's record (`<name>.strip.json`, not the report) under
+ `cell_record`, bound to the strip by `cell_record.strip_sha256`, the sha256 of the strip PNG it
+ describes. `cell_record.cells` holds one entry per cell of the strip, in order: `source_frame`,
+ the source frame the cell is (a whole number); `anchor_move_px`, where the cut's anchor moved
+ that frame before the crop, across and down, in whole px (nothing (`[0, 0]`) at `--anchor none`,
+ round(`wrap_dx_px` x k / L) across at `--anchor body` for frame k of a cut L frames long, and the
+ left and top of `padding_ltrb` plus that frame's entry of `shifts_xy` at `--anchor motion` and
+ `--anchor motion-auto`); `scale`, the factor each step that holds a clip's frames to one size
+ scaled the frame by about its feet before the cut, `size_hold` (the size hold) and `gait_fallback`
+ (the gait fallback), 1 where the step did not hold the clip's frames; and `as_filmed`, true where
+ the cell is that frame as filmed but for its anchor's move. Its pixels at the end of the cut are
+ its pixels anchored, before any repair (the receipt `video-loop` writes in its report,
+ `source_projection.before_repair_pixels_sha256`), and no step held the clip's frames to one size.
+ A cell the jump repair, the seam bridge, the overlapped wrap or the wrap blend made again, gave
+ way or redrew is not as filmed by its pixels; no list of those steps is read. In a cut at
+ `--out-fps` (cells each made at a time of their own, more cells than the cut has frames),
- `cell_record` still holds one entry per cell, and each cell's `source_frame` is the frame the
- cell is, and for a cell made between two frames the cut's frame at or before its time (the frame
- the seam reads it as), with that frame's `anchor_move_px` and `scale`. `as_filmed` is true only
- where the cell's pixels are that frame's pixels anchored before any repair, so a cell that
- repeats a frame unchanged is as filmed, and a cell made between two frames is not, and
- `video-sway --read-on-cut` does not pair it. `video-loop` now
++ `cell_record` still holds one entry per cell, and now reads a retimed cut the same way as a cut
++ at `--out-fps`: each cell's `source_frame` is the frame the cell is, and for a cell made between
++ two frames the cut's frame at or before its time (the frame the seam reads it as), with that
++ frame's `anchor_move_px` and `scale`. `as_filmed` is true only where the cell's pixels are that
++ frame's pixels anchored before any repair, so a cell that repeats a frame unchanged is as filmed,
++ and a cell made between two frames, a cell moved onto the parabola or along, and every cell of a
++ cut the retime laid on a larger canvas are not as filmed, and `video-sway --read-on-cut` does not
++ pair them. The cells before the take-off that the retime neither moved nor laid on a larger canvas
++ stay as filmed. `video-loop` now
+ writes that receipt (`source_projection`) in the report of every cut but `--anchor feet` and a
+ lifetime cut, so also at `--anchor motion` and `motion-auto` (`recipe`
+ `motion-anchor-correction-v1` there). On a loop aligned from its cut (`cycle_align`), the aligned
+ strip is another strip, so `video-cycle-align` does not carry `cell_record` over to it. Its first
+ alignment keeps the cut's own strip record, byte for byte, beside the cut's frames as filmed
+ (`cycle.source/<name>.strip.json`), and later alignments keep it. There the cut's record is read
+ from that file, bound to the strip the alignment's origin names
+ (`cycle_align.origin.strip_sha256`); the regions sit on the aligned cell that is cut cell j and
+ are carried as `transported` carries them. On an unaligned loop they are read on cell j and
+ carried from there. The regions' centres, a `--region-mask` PNG, and a single `--hold-mask` PNG
+ are moved pixel for pixel onto cell j by the whole pixel shift the two crops and cell sizes set
+ that frame apart, each crop taken on the frame as filmed: its `source_rect` less the cell's
+ `anchor_move_px`. A pixel may lie at most `RECUT_DRIFT` (1.0 px) off that shift anywhere in the
+ cell. The pair's policy is now `same-clip/source-frame/whole-px-shift/2`. Then the two cells are
+ compared: the cut's cell 0 laid on this loop's cell j at the shift must be the same pixels (RGBA)
+ wherever they overlap. A record changed to call a cell the frame as filmed is held to that
+ frame's pixels this way. Before crops are read, the run is refused no-match and the loop left as
+ it was, saying which and naming the field: a cut with no `cell_record` (a cut `video-loop` made
+ before it wrote one: every cut made by 3.5.0 or before), on the cut `--read-on-cut` names or on
+ this loop's ("it holds no record of them (cell_record), as a cut video-loop made before it wrote
+ one does"); a record of another strip (`cell_record.strip_sha256` is not the strip's sha256); a
+ record that does not give its cells as `video-loop` writes it, naming the field, for instance
+ `cell_record.cells[2].source_frame` (`cell_record` not an object, `cells` not one entry per cell of
+ the strip, a cell's entry not an object, `source_frame` not a whole number, `anchor_move_px` not
+ two whole px, a `scale` factor missing or not a positive number, `as_filmed` not true or false);
+ a loop aligned from its cut whose cut's record is not kept beside its frames as filmed
+ (`cycle.source/<name>.strip.json`); a record that names no clip it is cut from (`source_cut`),
+ two cuts of different clips, or a source frame this loop's cut does not hold. Every cell's entry
+ is read this way, not only the cell paired. Refusal no-match also occurs if either cell paired was
+ scaled by a hold (its `scale.size_hold` or `scale.gait_fallback` not 1: no whole px shift undoes a
+ scale), or is not as filmed (`as_filmed` false). Only the two cells paired are read for this; a
+ cell elsewhere in either cut that a hold scaled or a repair made leaves the pair as it is.
+ Refusal no-match also occurs if the two cells are not the same pixels where they overlap at the
+ shift, saying how many of how many px differ, or if the strip `--read-on-cut` names is a loop
+ aligned from its cut (`cycle_align`), whose cells are not the cut's frames in order. A run is
+ refused uncertain if a cut records no crop, if crops, scales and anchors set a pixel more than 1 px
+ off one whole shift, or if an aligned loop holds no cell for cut cell j. `STRIP` is that cut's
+ strip PNG, whose bytes must have the sha256 `--read-on` names, with its record beside it as
+ `video-loop` writes one using the same file name ending `.json` instead of `.png`, refusing with
+ "--read-on-cut names the strip --read-on names by its sha256; it needs --read-on" when `--read-on`
+ is not given and "wants the strip's PNG and its record beside it" when either file is missing.
+ Masks are moved by the shift alone with no polygon grown and no scaling, while a mask pixel that
+ would leave the cell refuses the run, and a folder of masks (one per cell) is refused under
+ `--read-on-cut` with "regions read on another cut (--read-on-cut) are drawn on its cell 0 alone:
+ give one PNG". `video-sway` takes `--read-on-cut` on `--loop-dir` only, and `video-sway-inspect`
+ does not take it.
+- **`no-match`**, refused: neither — another clip, another cut no record pairs with this one
+ (`--read-on-cut` names the cut that one does), a strip nothing here was cut or aligned from.
+ Locate the regions again on this strip.
#### A least area each move leaves — `--stretch-floor D`
diff --cc sprite_gen/video/held_fill.py
index 3d23399,5880d7e..446b643
--- a/sprite_gen/video/held_fill.py
+++ b/sprite_gen/video/held_fill.py
@@@ -281,14 -283,13 +283,14 @@@ def times(n: int, fps: float, out_fps:
return [k * (n - 1) / (count - 1) for k in range(count)]
- def upsample(frames: list[Image.Image], interpolate: rife_mod.Interpolate, *, ring: bool, fps: float, out_fps: float,
- reads: bool | None = None) -> tuple[list[Image.Image], dict[str, Any]]:
- """`frames` given at `out_fps` (`times`): a cell on a frame's time is that frame, one between two frames showing
- one picture is that picture, any other is made between the two at its own time (`_made`, within half a cell of
- it), and one no frame made is taken for is the nearer frame and named (`shown_again`). `shows`: the frame each cell
- is, None where it was made."""
+ def at_times(frames: list[Image.Image], interpolate: rife_mod.Interpolate, at: Sequence[float], *, ring: bool,
+ spacing: float | Sequence[float], reads: bool | None = None) -> tuple[list[Image.Image], dict[str, Any]]:
+ """`frames` at the times `at`, in frames of the cut: a cell on a frame's time is that frame, one between two frames
+ showing one picture is that picture, any other is made between the two at its own time (`_made`, within half its
+ `spacing` of it: frames a cell, one for all or one each), and one no frame made is taken for is the nearer frame and
- named (`shown_again`). The record: how many were made, the cells shown again, and how each was (`frames`)."""
++ named (`shown_again`). The record: how many were made, the cells shown again, how each was (`frames`), and the
++ frame each cell is, None where it was made (`shows`)."""
n = len(frames)
- at = times(n, fps, out_fps, ring=ring)
same = same_steps(frames + ([frames[0]] if ring else []))
if reads is None:
reads = bool(ghost_screen(frames)["reads"])
@@@ -306,24 -304,28 +307,32 @@@
a = math.floor(tau)
if same[a]:
out.append(frames[a])
+ shows.append(a)
continue
t = tau - a
- frame, how = _made(interpolate, frames[a], frames[(a + 1) % n], t, (t - spacing / 2, t + spacing / 2), reads=reads)
+ half = (spacing if isinstance(spacing, (int, float)) else spacing[k]) / 2
+ frame, how = _made(interpolate, frames[a], frames[(a + 1) % n], t, (t - half, t + half), reads=reads)
if frame is None:
out.append(frames[near % n])
+ shows.append(near % n)
shown_again.append(k)
made.append({"cell": k, "between": [a, (a + 1) % n], "taken": near % n, **how})
continue
out.append(frame)
+ shows.append(None)
made.append({"cell": k, "between": [a, (a + 1) % n], **how})
- return out, {"asked": out_fps, "fps": fps, "applied": True, "cells": len(out), "times": [round(x, 4) for x in at],
- "made": sum(1 for m in made if "taken" not in m), "shown_again": shown_again, "frames": made,
- return out, {"made": sum(1 for m in made if "taken" not in m), "shown_again": shown_again, "frames": made}
++ return out, {"made": sum(1 for m in made if "taken" not in m), "shown_again": shown_again, "frames": made,
+ "shows": shows}
+ def upsample(frames: list[Image.Image], interpolate: rife_mod.Interpolate, *, ring: bool, fps: float, out_fps: float,
+ reads: bool | None = None) -> tuple[list[Image.Image], dict[str, Any]]:
+ """`frames` given at `out_fps` (`times`), each cell at its own time (`at_times`, within half a cell of it)."""
+ at = times(len(frames), fps, out_fps, ring=ring)
+ out, made = at_times(frames, interpolate, at, ring=ring, spacing=fps / out_fps, reads=reads)
+ return out, {"asked": out_fps, "fps": fps, "applied": True, "cells": len(out), "times": [round(x, 4) for x in at], **made}
+
+
def public(record: dict[str, Any]) -> dict[str, Any]:
"""The record as the strip metadata carries it: the reading as delivered (`cells`, `poses`, `held_runs`), before
(each run `filled` or why not, with its faults), the cells made and left, and the rate asked — not each try."""
diff --cc sprite_gen/video/loop.py
index 159cdcf,4d2de95..db390f1
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@@ -2181,37 -2193,6 +2216,38 @@@ def _refuse_overlap(frames_dir: Path, f
refuse_overlap({"--frames-dir": frames_dir, **{f"{f.name} in --frames-dir": f for f in files}}, outputs, verb="video-loop")
+def _cell_record(strip_bytes: bytes, cells: list[Image.Image], *, start: int, length: int, samples: list[int],
+ anchored: list[str], wrap_dx: int, motion: dict[str, Any] | None,
+ scales: dict[str, list[float]], upsampled: dict[str, Any] | None = None) -> dict[str, Any]:
+ """The strip's record of its cells (`CELL_RECORD`), bound to the strip by its PNG's sha256: for each cell, the frame of
+ the cut it shows at the end of the cut (`cells`, frame `samples[c]` of a cut `length` frames long from clip frame
- `start`; at --out-fps, `upsampled`, the frame cell `samples[c]` is, and one made between two frames reads as the
- frame at or before its time, as the seam reads it), the source frame it is, where the anchor moved that frame before
- the crop (the body anchor's ramp, `ramp_offset` of `wrap_dx`; the motion correction's place, `motion_anchor.laid_at`;
- nothing at --anchor none or feet),
++ `start`; at --out-fps or with its air retimed, `upsampled`, the frame cell `samples[c]` is, and one made between two
++ frames reads as the frame at or before its time, as the seam reads it), the source frame it is, where the anchor
++ moved that frame before the crop (the body anchor's ramp, `ramp_offset` of `wrap_dx`; the motion correction's place,
++ `motion_anchor.laid_at`; nothing at --anchor none or feet),
+ the factor each step that held the clip's frames to one size scaled it by (`scales`, per clip frame; 1 where none did),
+ and whether it is that frame as filmed but for the anchor's move: its pixels are its pixels anchored, before any
+ repair (`anchored`, the cut's receipt), and no step held the clip's frames. What made a cell otherwise — a repair, a
- blend at the wrap, a hold, a frame between at --out-fps — is not listed: the cell's pixels say it."""
++ blend at the wrap, a hold, a frame between at --out-fps or in a retimed air, the air retime's move — is not listed:
++ the cell's pixels say it."""
+ def moved(k: int) -> list[int]:
+ if motion is not None:
+ return list(motion_anchor.laid_at(motion, k))
+ return [ramp_offset(wrap_dx, k, length), 0]
+
+ def frame(c: int) -> int:
+ if upsampled is None:
+ return c
+ shown = upsampled["shows"][c]
+ return shown if shown is not None else min(length - 1, math.floor(upsampled["times"][c]))
+
+ return {"strip_sha256": evidence_mod.digest(strip_bytes), "cells": [
+ {"source_frame": start + k, "anchor_move_px": moved(k),
+ "scale": {step: scales[step][start + k] if step in scales else 1.0 for step in CELL_SCALE_STEPS},
+ "as_filmed": not scales and evidence_mod.digest(cell.tobytes()) == anchored[k]}
+ for k, cell in ((frame(c), cell) for c, cell in zip(samples, cells))]}
+
+
def run_loop(frames_dir: Path, out_dir: Path, **options: Any) -> dict[str, Any]:
"""Cut the loop (`_cut_loop`, which takes the options). The frames a size hold or the gait fallback scales back
are written in folders of the run's own (`_Scratch`), removed however the run ends."""
@@@ -2837,7 -2831,39 +2896,39 @@@ def _cut_loop
"of it is named a ghost, here or in video-cycle-align, so look at cycle/ (docs/loop-repair.md)", file=sys.stderr)
held_record = report_base["held_fill"]
upsampled = None
- if out_fps is not None:
+ # A cut played once carries its root motion (docs/video-pipeline.md, "Root motion"), read against the clip's floor.
+ floor = root_motion_mod.clip_floor(files) if cycle["kind"] in root_motion_mod.KINDS else None
+ retimed = None
+ if asked_air is not None:
+ if cycle["kind"] not in root_motion_mod.KINDS:
+ report_base["air_retime"] = {"asked": asked_air, "applied": False,
+ "why": f"a {cycle['kind']} cut: the air of a cut played once is retimed"}
+ else:
+ # The air given its own length, gravity and speed: its cells made again between the clip's frames at the
+ # cut's rate (held_fill.at_times), each moved onto the parabola, the landing on along.
+ try:
+ frames, report_base["air_retime"], retimed = _air_retime(
+ frames, interpolate, fps=fps, rate=out_fps or fps, floor=floor, times=[i + k for k in range(L)],
+ declared=declared, asked=asked_air, meters_per_px=meters_per_px, facing=facing)
+ except (ValueError, rife_mod.RifeUnavailable) as exc:
+ error = (f"video-loop: {exc}; --air-retime makes the frames between the clip's — fix RIFE, or cut it "
+ "without --air-retime (docs/video-pipeline.md, \"Root motion\")")
+ refuse(target, out_dir, name, {**report_base, "status": "failed", "error": error, "cycle": cycle})
+ raise SystemExit(error) from exc
+ for line in _air_lines(name, report_base["air_retime"]):
+ print(f"video-loop: warning: {name}: {line}", file=sys.stderr)
+ if retimed is not None:
+ upsampled = retimed["times"]
+ report_base["seam_measurement"] = "rendered-cells"
+ as_filmed = {} # the cells are each made at a time of their own: read as they play
+ cycle_seconds = len(frames) / (out_fps or fps)
+ n_out = min(len(frames), max(n_asked, round(cycle_seconds * gif_fps)))
+ if out_fps is not None:
+ record = report_base["air_retime"]
+ held_record["out_fps"] = {"asked": out_fps, "fps": fps, "applied": True, "cells": len(frames),
+ "times": [round(x, 4) for x in upsampled], "made": record["made"],
- "shown_again": record["shown_again"]}
++ "shown_again": record["shown_again"], "shows": retimed["shows"]}
+ if out_fps is not None and retimed is None:
# A rate above the clip's: every cell at its own time, made between the frames beside it (held_fill.upsample).
try:
frames, held_record["out_fps"] = _upsample(frames, interpolate, ring=ring, fps=fps, out_fps=out_fps)
@@@ -2941,12 -2983,7 +3048,12 @@@
n_out = min(n_out, int(strip_meta["frames"]))
strip_path = out_dir / f"{name}.strip.png"
strip.save(strip_path)
- atomic_write_text(out_dir / f"{name}.strip.json", json.dumps(strip_meta, indent=2) + "\n")
+ cell_record = _cell_record(strip_path.read_bytes(), [frames[k] for k in strip_meta["sample_indices"]], start=i,
+ length=L, samples=strip_meta["sample_indices"], anchored=anchored, wrap_dx=wrap_dx,
+ motion=motion, scales=clip_scales,
- upsampled=held_record["out_fps"] if upsampled is not None else None)
++ upsampled=None if upsampled is None else retimed if retimed is not None else held_record["out_fps"])
+ # The record of its cells is the strip's own: written beside it, not into the report.
+ atomic_write_text(out_dir / f"{name}.strip.json", json.dumps({**strip_meta, CELL_RECORD: cell_record}, indent=2) + "\n")
# resampled GIF/WebP frames: same crop as the strip, n_out evenly across the cycle
single_play = cycle["kind"] in nonloop.KINDS
diff --cc sprite_gen/video/root_motion.py
index 0000000,5de31de..b93e978
mode 000000,100644..100644
--- a/sprite_gen/video/root_motion.py
+++ b/sprite_gen/video/root_motion.py
@@@ -1,0 -1,340 +1,341 @@@
+ # SPDX-License-Identifier: Apache-2.0
+ """Root motion: where the body is in each cell of a cut played once, what it stands on and its air (`read`,
+ `sidecar`); and the air given a length, a gravity and a speed of its own (`retime`). docs/video-pipeline.md, "Root
+ motion".
+
+ The root is the subject's mass centre: the mean of its pixels (alpha over 0), the point inspect-motion reads as a
+ frame's `centroid_px` (`qa.motion.centroid`). No body part is named. In the air it is the point that falls on a parabola
+ under gravity whatever the arms and legs do, so it is the point a game moves: a cell is drawn with its root on the
+ body's place. A frame stands on the ground where its lowest body row is within nonloop.GROUND_PX of the clip's floor,
+ the lowest row any frame of the clip reaches (`nonloop.on_floor`, the rule the strip's standing height reads). A
+ contact the floor does not show, a hand on a wall the clip does not draw, is named by the caller over frames of the clip
+ in inspect-motion's spans (`--contact hand=12:20`, `qa.motion.contact_spans`). The air is each run of frames touching
+ nothing: its take-off is the frame before it, its landing the frame after, its seconds those between the two, and its
+ apex how far the root rises over the take-off's.
+
+ `retime` gives each air with a take-off and a landing a length (`air`, seconds), a gravity (`gravity`) and a speed
+ along (`speed`), each the clip's own where not given. The cut is made again at its rate: the frames up to the take-off
+ and from the landing at the clip's pace, the air's cells spread evenly over it, each showing the clip's pose at the same
+ share of the clip's air, made between the two frames it falls between where it falls between them (held_fill.at_times,
+ the cells the 3.8.0 fill makes). Each air cell is then moved whole, by whole pixels, until its root stands on the
+ parabola from the take-off's root to the landing's; the landing and every cell after it is moved along by as much
+ further as the air now carries the body, so a planted foot stays planted. The take-off and the landing are the frames
+ as filmed, and so is every cell up to the take-off.
+ """
+
+ from __future__ import annotations
+
+ import math
+ from collections.abc import Sequence
+ from pathlib import Path
+ from typing import Any
+
+ from PIL import Image
+
+ from sprite_gen._deps import np
+ from sprite_gen.qa import motion as qa_motion
+ from sprite_gen.video import held_fill as held_fill_mod
+ from sprite_gen.video import nonloop
+ from sprite_gen.video import rife as rife_mod
+
+ KINDS = ("once", "once-return", "one-shot") # the cuts played once that carry a body (not an effect's lifetime)
+ RETIME_KEYS = ("gravity", "air", "speed")
+ GROUND = "ground"
+ SNAP = held_fill_mod.SNAP # a time within this of a frame is that frame
+
+
+ def parse_retime(text: str) -> dict[str, float]:
+ """`gravity=G,air=T,speed=V`, any of them, each once: metres a second squared, seconds, metres a second along."""
+ out: dict[str, float] = {}
+ for part in text.split(","):
+ key, eq, value = (s.strip() for s in part.partition("="))
+ if not eq or key not in RETIME_KEYS or key in out:
+ raise ValueError(f"--air-retime {text!r}: KEY=VALUE pairs of {', '.join(RETIME_KEYS)}, each once "
+ "(gravity=9.81,air=0.6,speed=4)")
+ try:
+ number = float(value)
+ except ValueError:
+ raise ValueError(f"--air-retime {key}={value}: not a number") from None
+ if not math.isfinite(number) or number < 0 or (number == 0 and key != "speed"):
+ raise ValueError(f"--air-retime {key}={value}: " + ("0 or more" if key == "speed" else "more than 0"))
+ out[key] = number
+ return out
+
+
+ def parse_contacts(values: Sequence[str], frames: int) -> list[tuple[str, list[list[int]]]]:
+ """`NAME=SPANS` (`hand=12:20`): a contact the floor does not show, over zero-based frames of the clip, in
+ inspect-motion's spans (`qa.motion.contact_spans`). `ground` is the floor's own."""
+ out: list[tuple[str, list[list[int]]]] = []
+ for value in values:
+ name, eq, spans = (s.strip() for s in value.partition("="))
+ if not eq or not name or name == GROUND or any(name == n for n, _ in out):
+ raise ValueError(f"--contact {value!r}: NAME=SPANS, a name of its own (not {GROUND!r}) and the clip's frames "
+ "it touches through, e.g. hand=12:20")
+ try:
+ out.append((name, qa_motion.contact_spans(spans, frames)))
+ except ValueError as exc:
+ raise ValueError(f"--contact {value!r}: {exc} (the clip has {frames} frames, numbered from 0)") from None
+ return out
+
+
+ def clip_floor(files: Sequence[Path]) -> int | None:
+ """The clip's floor: the lowest body row any of its frames reaches (`nonloop.body_box`), as filmed."""
+ bottoms = [box[3] for f in files if (box := nonloop.body_box(Image.open(f).convert("RGBA"))) is not None]
+ return max(bottoms) if bottoms else None
+
+
+ def root(frame: Image.Image) -> list[float] | None:
+ """A frame's root: its subject's mass centre, [x, y] px (`qa.motion.centroid`)."""
+ return qa_motion.centroid(np.asarray(frame.getchannel("A")) > 0)
+
+
+ def touching(frames: Sequence[Image.Image], *, floor: int | None, times: Sequence[float],
+ declared: Sequence[tuple[str, list[list[int]]]] = ()) -> list[list[str]]:
+ """What each frame touches: the ground where its body stands on the floor, and each declared contact whose span
+ holds its time (in frames of the clip)."""
+ out = []
+ for frame, t in zip(frames, times):
+ box = nonloop.body_box(frame)
+ on = [GROUND] if floor is not None and box is not None and nonloop.on_floor(box, floor) else []
+ on += [name for name, spans in declared if any(a - SNAP <= t <= b + SNAP for a, b in spans)]
+ out.append(on)
+ return out
+
+
+ def reading(frames: Sequence[Image.Image], *, floor: int | None, times: Sequence[float],
+ declared: Sequence[tuple[str, list[list[int]]]] = ()) -> tuple[list[list[float] | None], list[list[str]]]:
+ """Each frame's root and what it touches (`root`, `touching`)."""
+ return [root(f) for f in frames], touching(frames, floor=floor, times=times, declared=declared)
+
+
+ def _runs(flags: Sequence[bool]) -> list[list[int]]:
+ """Each run of true flags: [first, last]."""
+ found: list[list[int]] = []
+ for k, flag in enumerate(flags):
+ if flag and found and found[-1][1] == k - 1:
+ found[-1][1] = k
+ elif flag:
+ found.append([k, k])
+ return found
+
+
+ def read(roots: Sequence[list[float] | None], touch: Sequence[list[str]], seconds: Sequence[float]) -> dict[str, Any]:
+ """The contacts (each name's runs of frames) and the air (each run of frames touching nothing: its take-off and
+ landing frames, the seconds between them, and its apex, how far the root rises over the take-off's, px up)."""
+ n = len(touch)
+ names = list(dict.fromkeys(name for on in touch for name in on))
+ contacts = [{"by": name, "cells": run} for name in names for run in _runs([name in on for on in touch])]
+ air = []
+ for first, last in _runs([not on for on in touch]):
+ takeoff = first - 1 if first > 0 else None
+ landing = last + 1 if last < n - 1 else None
+ span: dict[str, Any] = {"cells": [first, last], "takeoff": takeoff, "landing": landing,
+ "seconds": round(seconds[landing] - seconds[takeoff], 4) if None not in (takeoff, landing) else None}
+ ys = [(roots[k][1], k) for k in range(first, last + 1) if roots[k] is not None]
+ if takeoff is not None and roots[takeoff] is not None and ys:
+ top, at = min(ys)
+ span.update(apex_px=round(roots[takeoff][1] - top, 2), apex_cell=at)
+ air.append(span)
+ return {"contacts": sorted(contacts, key=lambda c: (c["cells"][0], c["by"])), "air": air}
+
+
+ def sidecar(frames: Sequence[Image.Image], *, rect: Sequence[int] | None, size: tuple[int, int], floor: int | None,
+ seconds: Sequence[float], touch: Sequence[list[str]], meters_per_px: float | None) -> dict[str, Any]:
+ """The strip's `root_motion`: each cell's root in cell px from the cell's top-left (draw the cell with that point on
+ the body's place), the floor's row, the contacts and the air in cells; with `meters_per_px` (of the frames as cut)
+ the roots in metres from the first cell's, up positive, and each apex in metres. `frames` are the cells' frames as
+ cut, `rect` the source rectangle the strip crops them to, `size` a cell's (w, h)."""
+ if rect is None:
+ return {"why": "the cells are each moved to a foot line of their own (--anchor feet): no one rectangle maps a frame to its cell"}
+ left, top, right, bottom = rect
+ sx, sy = size[0] / (right - left), size[1] / (bottom - top)
+ at = [root(f) for f in frames]
+ measured = read(at, touch, seconds)
+ for span in measured["air"]:
+ if "apex_px" in span:
+ span["apex_px"] = round(span["apex_px"] * sy, 2)
+ out: dict[str, Any] = {
+ "point": "mass-centre",
+ "root": [None if r is None else [round((r[0] - left) * sx, 2), round((r[1] - top) * sy, 2)] for r in at],
+ "ground_y": None if floor is None else round((floor - top) * sy, 2),
+ **measured,
+ }
+ if meters_per_px is not None:
+ per_cell = meters_per_px / sy
+ out["meters_per_px"] = round(per_cell, 8)
+ first = next((r for r in out["root"] if r is not None), None)
+ out["root_m"] = [None if r is None or first is None else
+ [round((r[0] - first[0]) * per_cell, 4), round((first[1] - r[1]) * per_cell, 4)] for r in out["root"]]
+ for span in out["air"]:
+ if "apex_px" in span:
+ span["apex_m"] = round(span["apex_px"] * per_cell, 4)
+ return out
+
+
+ def said(record: dict[str, Any]) -> list[str]:
+ """Each air of a cut as a person is told it: its seconds and its apex."""
+ lines = []
+ for span in record.get("air", []):
+ if span.get("seconds") is None:
+ lines.append(f"cells {span['cells'][0]}-{span['cells'][1]} in the air, no "
+ f"{'take-off' if span['takeoff'] is None else 'landing'} in the cut")
+ continue
+ apex = f"{span['apex_m']:.2f} m" if "apex_m" in span else f"{span['apex_px']:g} px"
+ lines.append(f"air {span['seconds']:.2f} s, apex {apex} (cells {span['cells'][0]}-{span['cells'][1]})")
+ return lines
+
+
+ def _gravity(ys: Sequence[float], a: int, b: int, fps: float) -> float | None:
+ """The clip's own gravity over an air from frame `a` to `b` (px a second squared, down): the least squares fit of
+ the root's rise over the line from take-off to landing to g·t·(T - t)/2. None where the root is unread."""
+ T = (b - a) / fps
+ num = den = 0.0
+ for k in range(a + 1, b):
+ t = (k - a) / fps
+ s = t * (T - t) / 2
+ num += (ys[a] + (ys[b] - ys[a]) * t / T - ys[k]) * s
+ den += s * s
+ return num / den if den > 0 else None
+
+
+ def apex(rise: float, gravity: float, seconds: float) -> float:
+ """The highest a root rises over its take-off's on the parabola that ends `rise` px higher after `seconds` under
+ `gravity` (px a second squared): g·T²/8 where it lands at its own height."""
+ t = min(seconds, max(0.0, seconds / 2 + rise / (gravity * seconds)))
+ return rise * t / seconds + gravity * t * (seconds - t) / 2
+
+
+ def _pieces(L: int, spans: Sequence[dict[str, Any]], *, fps: float, rate: float,
+ airs: Sequence[float]) -> list[tuple[float, float, int, int | None]]:
+ """The cut as pieces (from frame, to frame, cells, which air or None): the ground at the clip's pace, each air in
+ as many cells as its new seconds hold at `rate`."""
+ pieces: list[tuple[float, float, int, int | None]] = []
+ at = 0
+ for which, span in enumerate(spans):
+ a, b = span["takeoff"], span["landing"]
+ if a > at:
+ pieces.append((at, a, max(1, round((a - at) * rate / fps)), None))
+ pieces.append((a, b, max(1, round(airs[which] * rate)), which))
+ at = b
+ if L - 1 > at:
+ pieces.append((at, L - 1, max(1, round((L - 1 - at) * rate / fps)), None))
+ return pieces
+
+
+ def retime(frames: list[Image.Image], interpolate: rife_mod.Interpolate, *, fps: float, rate: float, floor: int | None,
+ times: Sequence[float], declared: Sequence[tuple[str, list[list[int]]]], asked: dict[str, float],
+ meters_per_px: float | None, facing: str = "right") -> tuple[list[Image.Image], dict[str, Any], dict[str, Any] | None]:
+ """The cut with each air that has a take-off and a landing retimed (see the module), at `rate` cells a second.
+ `times` are the frames' times in frames of the clip (for the declared contacts). Returns the frames, the record, and
+ what the cut's reading needs where it was retimed (None where not): each cell's time in frames of the cut (`times`),
- what each cell touches (`touch`), and the canvas the cells were moved on (`offset`, where the frames' (0, 0) is)."""
++ the frame each cell is, None where it was made (`shows`, held_fill.at_times'), what each cell touches (`touch`), and
++ the canvas the cells were moved on (`offset`, where the frames' (0, 0) is)."""
+ L = len(frames)
+ roots, touch = reading(frames, floor=floor, times=times, declared=declared)
+ before = read(roots, touch, [k / fps for k in range(L)])
+ record: dict[str, Any] = {"asked": dict(asked), "applied": False, "before": before["air"]}
+ if meters_per_px is not None:
+ record["meters_per_px"] = meters_per_px
+ spans = [s for s in before["air"] if s["seconds"] is not None]
+ if not spans:
+ record["why"] = ("no air in the cut" if not before["air"] else
+ "no air with both its take-off and its landing in the cut")
+ return frames, record, None
+ if any(roots[s["takeoff"]] is None or roots[s["landing"]] is None for s in spans):
+ record["why"] = "a take-off or a landing frame shows no body"
+ return frames, record, None
+ plans = []
+ for span in spans:
+ a, b = span["takeoff"], span["landing"]
+ T0 = (b - a) / fps
+ ys = [r[1] if r is not None else math.nan for r in roots]
+ g0 = _gravity(ys, a, b, fps)
+ g = asked["gravity"] / meters_per_px if "gravity" in asked else g0
+ if g is None or not g > 0:
+ record["why"] = (f"the clip's own air (frames {a}-{b}) does not rise over the line from its take-off to its "
+ "landing (no gravity to read): give gravity=")
+ return frames, record, None
+ along = roots[b][0] - roots[a][0]
+ sign = (1 if along > 0 else -1) if abs(along) >= 1 else (1 if facing == "right" else -1)
+ speed = asked["speed"] / meters_per_px if "speed" in asked else abs(along) / T0
+ T1 = asked.get("air", T0)
+ plans.append({"a": a, "b": b, "T0": T0, "g0": g0, "g": g, "speed": speed, "sign": sign, "T1": T1})
+ pieces = _pieces(L, spans, fps=fps, rate=rate, airs=[p["T1"] for p in plans])
+ at, spacing, piece_of = [0.0], [1.0], [None]
+ for start, end, cells, which in pieces:
+ for j in range(1, cells + 1):
+ at.append(start + (end - start) * j / cells)
+ spacing.append((end - start) / cells)
+ piece_of.append((which, j, cells))
+ made_frames, made = held_fill_mod.at_times(frames, interpolate, at, ring=False, spacing=spacing)
+ # Each cell moved: none up to the first take-off; an air cell onto its parabola; from a landing on, along.
+ moves: list[tuple[int, int]] = []
+ along_px = 0
+ for k, of in enumerate(piece_of):
+ which = None if of is None else of[0]
+ if which is not None and of[1] == 1:
+ plans[which].update(moved_from=along_px, cells=of[2], seconds=of[2] / rate, first_cell=k - 1)
+ if which is None or of[1] == of[2]:
+ if which is not None:
+ # the landing: as far along as the air carried the body from its take-off
+ p = plans[which]
+ xa = roots[p["a"]][0] + p["moved_from"]
+ along_px = round(xa + p["sign"] * p["speed"] * p["seconds"] - roots[p["b"]][0])
+ p["moved_px"] = along_px - p["moved_from"]
+ moves.append((along_px, 0))
+ continue
+ p = plans[which]
+ T, t, w = p["seconds"], of[1] / rate, of[1] / of[2]
+ xa, ya = roots[p["a"]][0] + p["moved_from"], roots[p["a"]][1]
+ x = xa + p["sign"] * p["speed"] * T * w
+ y = ya + (roots[p["b"]][1] - ya) * w - p["g"] * t * (T - t) / 2
+ here = root(made_frames[k])
+ moves.append((0, 0) if here is None else (round(x - here[0]), round(y - here[1])))
+ boxes = [nonloop.body_box(f) for f in made_frames]
+ W, H = frames[0].size
+ lo_x = min([0] + [b[0] + m[0] for b, m in zip(boxes, moves) if b is not None])
+ lo_y = min([0] + [b[1] + m[1] for b, m in zip(boxes, moves) if b is not None])
+ hi_x = max([W] + [b[2] + m[0] for b, m in zip(boxes, moves) if b is not None])
+ hi_y = max([H] + [b[3] + m[1] for b, m in zip(boxes, moves) if b is not None])
+ offset, size = (-lo_x, -lo_y), (hi_x - lo_x, hi_y - lo_y)
+ out = []
+ for f, (dx, dy) in zip(made_frames, moves):
+ if (dx, dy) == (0, 0) and offset == (0, 0) and size == (W, H):
+ out.append(f)
+ continue
+ canvas = Image.new("RGBA", size, (0, 0, 0, 0))
+ canvas.paste(f, (offset[0] + dx, offset[1] + dy))
+ out.append(canvas)
+ cell_touch = []
+ for k, of in enumerate(piece_of):
+ if of is not None and of[0] is not None and of[1] < of[2]:
+ cell_touch.append([])
+ else:
+ cell_touch.append(touch[min(L - 1, round(at[k]))])
+ airs = []
+ for span, p in zip(spans, plans):
+ rise = roots[p["a"]][1] - roots[p["b"]][1]
+ row = {"cells": [p["first_cell"] + 1, p["first_cell"] + p["cells"] - 1],
+ "takeoff": p["first_cell"], "landing": p["first_cell"] + p["cells"],
+ "frames": [p["a"], p["b"]], "seconds_before": round(p["T0"], 4), "seconds": round(p["seconds"], 4),
+ "apex_before_px": span.get("apex_px"), "apex_px": round(apex(rise, p["g"], p["seconds"]), 2),
+ "gravity_px": round(p["g"], 2), "speed_px": round(p["speed"], 2), "moved_along_px": p["moved_px"]}
+ if p["g0"] is not None:
+ row["gravity_before_px"] = round(p["g0"], 2)
+ if meters_per_px is not None:
+ row.update(apex_m=round(row["apex_px"] * meters_per_px, 4), gravity=round(p["g"] * meters_per_px, 4),
+ speed=round(p["speed"] * meters_per_px, 4))
+ if "air" in asked and abs(p["seconds"] - asked["air"]) > 1e-9:
+ row["asked_seconds"] = asked["air"]
+ airs.append(row)
+ same = held_fill_mod.same_steps(out)
+ record.update(applied=True, rate=rate, air=airs, made=made["made"], shown_again=made["shown_again"],
+ canvas_offset=list(offset), **held_fill_mod.reading(same))
+ record["frames"] = made["frames"]
- return out, record, {"times": at, "touch": cell_touch, "offset": offset}
++ return out, record, {"times": at, "shows": made["shows"], "touch": cell_touch, "offset": offset}
+
+
+ def public(record: dict[str, Any]) -> dict[str, Any]:
+ """The retime as the strip metadata carries it: what was asked, each air before and after, the cells made and the
+ cells shown again, the poses over the cells — not how each frame was made."""
+ return {k: v for k, v in record.items() if k != "frames"}
diff --cc tests/video/test_root_motion.py
index 0000000,e94e78a..206f90f
mode 000000,100644..100644
--- a/tests/video/test_root_motion.py
+++ b/tests/video/test_root_motion.py
@@@ -1,0 -1,297 +1,336 @@@
+ # SPDX-License-Identifier: Apache-2.0
+ """Root motion (sprite_gen/video/root_motion.py, docs/video-pipeline.md "Root motion"): a cut played once carries
+ where its body is in each cell (the mass centre), what each cell touches and its air, in the strip sidecar; with
+ `--air-retime` the air is given a length, a gravity and a speed of its own, its cells made between the clip's frames
+ (held_fill.at_times), the take-off and the landing as filmed and the contacts where they were. Without the handle the
-cut is the same pictures as before (tests/picture_digest.py) and its sidecar only grows a key.
++cut is the same pictures as before (tests/picture_digest.py) and its sidecar only grows a key (and the record of its
++cells, `cell_record`, as every cut's).
+
+ The jump is synthetic (tests/video/jump_inputs.py), its mass centre on a parabola under a known gravity; the
+ interpolator is the stand-in that draws it again at the time asked for (`Between`)."""
+
+ from __future__ import annotations
+
+ import hashlib
+ import json
++import math
+ from pathlib import Path
+
+ import pytest
+ from PIL import Image
+
+ from sprite_gen.video import evidence
+ from sprite_gen.video import held_fill
+ from sprite_gen.video import loop as loop_mod
+ from sprite_gen.video import nonloop
+ from sprite_gen.video import root_motion as rm
++from sprite_gen.video import sway
+ from tests.video import jump_inputs as J
+ from tests.video.held_fill_inputs import Between
+ from tests.video.test_held_fill import UNHELD, _no_rife, _pictures
+
+
+ def _run(tmp_path: Path, frames: list[Image.Image], name: str = "j", **kw) -> dict:
+ keyed = J.save(frames, tmp_path / f"{name}-keyed")
+ return loop_mod.run_loop(keyed, tmp_path / f"{name}-out", fps=J.FPS, min_len=None, max_len=None, n_out=None,
+ seam_max=loop_mod.SEAM_RATIO_MAX, name=name, report_path=None, **kw)
+
+
+ def _meta(rep: dict) -> dict:
+ return json.loads(Path(rep["strip"]["path"]).with_suffix("").with_suffix(".strip.json").read_text())
+
+
+ def _cells(rep: dict) -> list[Image.Image]:
+ meta = _meta(rep)
+ strip = Image.open(rep["strip"]["path"]).convert("RGBA")
+ return [strip.crop((k * meta["w"], 0, (k + 1) * meta["w"], meta["h"])) for k in range(meta["frames"])]
+
+
+ def _read(frames: list[Image.Image], declared=()) -> dict:
+ floor = max(nonloop.body_box(f)[3] for f in frames)
+ roots = [rm.root(f) for f in frames]
+ touch = rm.touching(frames, floor=floor, times=range(len(frames)), declared=declared)
+ return {"roots": roots, "touch": touch, **rm.read(roots, touch, [k / J.FPS for k in range(len(frames))])}
+
+
+ def test_the_root_of_a_body_flying_under_gravity_is_read_on_its_parabola():
+ frames = J.jump()
+ got = _read(frames)
+ height = max(b[3] - b[1] for b in map(nonloop.body_box, frames))
+ worst = max(max(abs(got["roots"][k][0] - J.path(k - J.TAKEOFF)[0]), abs(got["roots"][k][1] - J.path(k - J.TAKEOFF)[1]))
+ for k in range(J.TAKEOFF, J.LANDING + 1))
+ assert worst <= 0.5 and worst / height < 0.05 # a whole pixel's placing, under half a pixel
+ (air,) = got["air"]
+ assert air["cells"] == [J.TAKEOFF + 1, J.LANDING - 1]
+ assert (air["takeoff"], air["landing"]) == (J.TAKEOFF, J.LANDING)
+ assert air["seconds"] == pytest.approx(J.AIR, abs=1e-4)
+ assert air["apex_px"] == pytest.approx(J.APEX, abs=1.0)
+ assert got["contacts"] == [{"by": "ground", "cells": [0, J.TAKEOFF]}, {"by": "ground", "cells": [J.LANDING, J.FRAMES - 1]}]
+
+
+ def test_a_contact_the_floor_does_not_show_is_named_over_the_clip_s_frames():
+ frames = J.jump()
+ declared = rm.parse_contacts(["hand=6:8"], len(frames))
+ got = _read(frames, declared)
+ assert {"by": "hand", "cells": [6, 8]} in got["contacts"]
+ (air,) = got["air"]
+ assert (air["takeoff"], air["cells"], air["landing"]) == (8, [9, 14], J.LANDING)
+ with pytest.raises(ValueError, match="ground"):
+ rm.parse_contacts(["ground=1:2"], 10)
+ with pytest.raises(ValueError, match="numbered from 0"):
+ rm.parse_contacts(["hand=4:40"], 10)
+
+
+ def test_the_retime_keys_are_read_and_a_wrong_one_is_refused():
+ assert rm.parse_retime("gravity=9.81,air=0.6,speed=4") == {"gravity": 9.81, "air": 0.6, "speed": 4.0}
+ assert rm.parse_retime("air=1.2") == {"air": 1.2}
+ for bad in ("air", "air=0", "lift=2", "air=1,air=2", "gravity=-1", "speed=x"):
+ with pytest.raises(ValueError):
+ rm.parse_retime(bad)
+
+
+ def _retimed(**asked):
+ frames = J.jump()
+ between = Between(J.draw, range(J.FRAMES))
+ floor = max(nonloop.body_box(f)[3] for f in frames)
+ out, record, plan = rm.retime(frames, between, fps=J.FPS, rate=J.FPS, floor=floor, times=range(J.FRAMES), declared=(),
+ asked=asked, meters_per_px=J.METERS_PER_PX)
+ return frames, out, record, plan, between
+
+
+ def test_the_air_twice_as_long_rises_g_t2_over_8_its_cells_made_between_and_the_contacts_kept():
+ frames, out, record, plan, between = _retimed(gravity=9.81, air=2 * J.AIR)
+ assert record["applied"]
+ (air,) = record["air"]
+ cells = round(2 * J.AIR * J.FPS)
+ assert len(out) == J.FRAMES + cells - (J.LANDING - J.TAKEOFF) # the air holds twice the cells
+ assert air["seconds"] == pytest.approx(2 * J.AIR, abs=1e-4) and air["gravity"] == pytest.approx(9.81, abs=1e-3)
+ T = 2 * J.AIR
+ assert air["apex_px"] == pytest.approx(J.GRAVITY * T * T / 8, abs=0.01)
+ # read on the cells delivered: the air spans the new cells, rises g·t²/8 and lands where the parabola does
+ ox, oy = plan["offset"]
+ roots = [rm.root(f) for f in out]
+ measured = rm.read(roots, plan["touch"], [k / J.FPS for k in range(len(out))])
+ (got,) = measured["air"]
+ assert got["cells"] == [J.TAKEOFF + 1, J.TAKEOFF + cells - 1] and got["seconds"] == pytest.approx(T, abs=1e-4)
+ assert got["apex_px"] == pytest.approx(J.GRAVITY * T * T / 8, abs=1.0)
+ # every air cell on the parabola, within a whole pixel's placing
+ xa, ya = roots[J.TAKEOFF]
+ for j in range(1, cells):
+ t = j / J.FPS
+ x = xa + 2 * (J.X_LANDING - J.X_TAKEOFF) * j / cells # the clip's own speed, for twice as long
+ y = ya - J.GRAVITY * t * (T - t) / 2
+ assert abs(roots[J.TAKEOFF + j][0] - x) <= 0.5 and abs(roots[J.TAKEOFF + j][1] - y) <= 0.5
+ # the poses: the clip's at the same share of its air, every other one made between two frames
+ assert record["made"] == cells // 2 and record["shown_again"] == []
+ assert sorted({round(c[2], 4) for c in between.calls}) == [0.5]
+ # no picture shown twice in the air
+ same = held_fill.same_steps(out)
+ assert not any(same[J.TAKEOFF:J.TAKEOFF + cells])
+ # the take-off, the cells before it and the landing block are the frames as filmed, moved whole
+ moved = air["moved_along_px"]
+ assert moved == 2 * (J.X_LANDING - J.X_TAKEOFF) - (J.X_LANDING - J.X_TAKEOFF)
+ for k in range(J.TAKEOFF + 1):
+ assert out[k].crop((ox, oy, ox + J.W, oy + J.H)).tobytes() == frames[k].tobytes()
+ for k in range(J.LANDING, J.FRAMES):
+ o = J.TAKEOFF + cells + (k - J.LANDING)
+ assert out[o].crop((ox + moved, oy, ox + moved + J.W, oy + J.H)).tobytes() == frames[k].tobytes()
+ # the ground cells stand on the floor, moved, and the air cells touch nothing
+ floor = J.FLOOR + 1 + oy
+ for k, f in enumerate(out):
+ on = nonloop.on_floor(nonloop.body_box(f), floor)
+ assert on == (not J.TAKEOFF < k < J.TAKEOFF + cells), k
+
+
+ def test_the_air_given_only_a_length_keeps_the_clip_s_own_gravity_and_speed():
+ frames, out, record, plan, _ = _retimed(air=J.AIR)
+ (air,) = record["air"]
+ assert air["gravity_before_px"] == pytest.approx(J.GRAVITY, rel=0.02)
+ assert air["seconds"] == pytest.approx(J.AIR, abs=1e-4) and air["moved_along_px"] == 0
+ assert record["made"] == 0 # every cell a frame: nothing to make, no RIFE asked for
+
+
+ def test_a_cut_with_no_air_is_not_retimed_and_says_why():
+ frames = [J.draw(0)] * 2 + J.jump()[:J.TAKEOFF + 1]
+ floor = max(nonloop.body_box(f)[3] for f in frames)
+ out, record, plan = rm.retime(frames, None, fps=J.FPS, rate=J.FPS, floor=floor, times=range(len(frames)),
+ declared=(), asked={"air": 1.0}, meters_per_px=None)
+ assert out is frames and plan is None and record["applied"] is False and record["why"] == "no air in the cut"
+
+
+ def test_video_loop_carries_the_root_motion_of_a_jump_and_retimes_its_air(tmp_path):
+ rep = _run(tmp_path, J.jump(), "plain", state="jump", cycle_mode="once")
+ meta = _meta(rep)
+ root = meta["root_motion"]
+ assert len(root["root"]) == meta["frames"]
+ start = meta["source_cut"]["start"]
+ (air,) = root["air"]
+ assert (air["takeoff"], air["landing"]) == (J.TAKEOFF - start, J.LANDING - start)
+ assert air["seconds"] == pytest.approx(J.AIR, abs=1e-3)
+ assert air["apex_px"] == pytest.approx(J.APEX * meta["scale"], abs=1.0)
+ assert "air_retime" not in meta and rep["root_motion"]["air"] == root["air"]
+ between = Between(J.draw, range(J.FRAMES))
+ rep = _run(tmp_path, J.jump(), "long", state="jump", cycle_mode="once", air_retime=f"gravity=9.81,air={2 * J.AIR}",
+ meters_per_px=J.METERS_PER_PX, interpolate=between)
+ meta = _meta(rep)
+ record = meta["air_retime"]
+ assert record["applied"] and record["made"] == 10 and meta["frames"] == rep["cycle"]["length"] + 10
+ (air,) = meta["root_motion"]["air"]
+ T = 2 * J.AIR
+ assert air["seconds"] == pytest.approx(T, abs=1e-3)
+ assert air["apex_m"] == pytest.approx(9.81 * T * T / 8, rel=0.03)
+ assert "times" in meta["source_cut"] and "out_fps" not in meta
+ # no picture shown twice in the air: the held runs left are the end pose the cut holds
+ first, last = air["cells"]
+ assert all(r["start"] > last or r["start"] + r["length"] <= first for r in meta["held_fill"]["held_runs"])
+ assert record["poses"] == meta["held_fill"]["poses"] and record["cells"] == meta["frames"]
+
+
+ @pytest.mark.real_rife
+ @pytest.mark.timeout(900) # 10 calls of the binary at about 210 x 250, each judged: seconds on a GPU, minutes on a CPU's Vulkan driver
+ def test_real_rife_makes_the_air_twice_as_long_with_no_frame_shown_again(tmp_path):
+ """The same jump through rife-ncnn-vulkan located as a cut locates it: every between made and judged, none shown
+ again, the air on its parabola."""
+ rep = _run(tmp_path, J.jump(), "real", state="jump", cycle_mode="once", air_retime=f"air={2 * J.AIR}",
+ meters_per_px=J.METERS_PER_PX)
+ meta = _meta(rep)
+ record = meta["air_retime"]
+ assert record["applied"] and record["made"] == 10 and record["shown_again"] == []
+ (air,) = meta["root_motion"]["air"]
+ T = 2 * J.AIR
+ assert air["seconds"] == pytest.approx(T, abs=1e-3)
+ assert air["apex_m"] == pytest.approx(9.81 * T * T / 8, rel=0.03)
+ first, last = air["cells"]
+ assert all(r["start"] > last or r["start"] + r["length"] <= first for r in meta["held_fill"]["held_runs"])
+
+
+ def test_no_rife_leaves_the_air_as_filmed_and_says_which_motion(tmp_path, monkeypatch, capsys):
+ _no_rife(monkeypatch, tmp_path)
+ rep = _run(tmp_path, J.jump(), "leap", state="jump", cycle_mode="once", air_retime=f"air={2 * J.AIR}")
+ err = capsys.readouterr().err
+ meta = _meta(rep)
+ assert meta["air_retime"]["applied"] is False and meta["air_retime"]["why"] == "RIFE is not installed"
+ assert "leap" in err and "was not retimed" in err and "rife install" in err
+ assert meta["frames"] == rep["cycle"]["length"] # as filmed
+ assert meta["root_motion"]["air"][0]["seconds"] == pytest.approx(J.AIR, abs=1e-3)
+
+
++def test_a_retimed_cut_records_each_cell_as_the_frame_it_is_and_a_cell_made_or_moved_as_not_filmed(tmp_path):
++ """The strip's record of its cells (`cell_record`, video-sway --read-on-cut) of the jump with its air half as long
++ again, on the clip's own canvas: a cell held_fill.at_times takes as a frame (`shows`) is that frame, one made between
++ two frames reads as the frame before its time; the cells up to the take-off are their frames as filmed, and no air
++ cell (made, or moved onto the parabola) nor any from the landing on (moved along) is, so --read-on-cut does not
++ pair it."""
++ between = Between(J.draw, range(J.FRAMES))
++ rep = _run(tmp_path, J.jump(), "long", state="jump", cycle_mode="once", air_retime=f"air={1.5 * J.AIR}",
++ interpolate=between)
++ meta = _meta(rep)
++ record = meta["air_retime"]
++ (air,) = record["air"]
++ assert record["applied"] and record["canvas_offset"] == [0, 0] and air["moved_along_px"] != 0
++ assert {im.size for im in (Image.open(p) for p in (Path(rep["out_dir"]) / "cycle").glob("frame-*.png"))} == {(J.W, J.H)}
++ sha = hashlib.sha256(Path(rep["strip"]["path"]).read_bytes()).hexdigest()
++ cells, times = sway.cell_record(meta, sha), meta["source_cut"]["times"]
++ assert len(cells) == meta["frames"] == len(times)
++ made = [c for c, t in enumerate(times) if abs(t - round(t)) > held_fill.SNAP]
++ assert len(made) == record["made"] == 10 and all(air["takeoff"] < c < air["landing"] for c in made)
++ for c, (cell, t) in enumerate(zip(cells, times)):
++ assert cell["source_frame"] == (math.floor(t) if c in made else round(t)), c
++ assert cell["as_filmed"] is (c <= air["takeoff"]), c
++ # Read on a cut of the same clip from frame 6: the retimed cut's first cell of frame 6 is made between 6 and 7.
++ read = _run(tmp_path, J.jump(), "from6", state="jump", cycle_mode="once", start=6, length=10)
++ first = [c["source_frame"] for c in cells].index(6)
++ assert first in made
++ with pytest.raises(SystemExit, match=rf"cell {first} is not that frame as filmed: video-loop did not cut it as filmed "
++ rf"\(cell_record\.cells\[{first}\]\.as_filmed\)"):
++ sway.recut_pair(meta, _meta(read), hashlib.sha256(Path(read["strip"]["path"]).read_bytes()).hexdigest(),
++ strip_sha256=sha)
++
++
+ def test_gravity_or_speed_without_metres_per_pixel_is_refused(tmp_path):
+ with pytest.raises(SystemExit, match="--meters-per-px"):
+ _run(tmp_path, J.jump(), "g", state="jump", cycle_mode="once", air_retime="gravity=9.81")
+ with pytest.raises(SystemExit, match="--contact"):
+ _run(tmp_path, J.jump(), "c", state="jump", cycle_mode="once", contacts=["hand=3:99"])
+
+
+ # The base engine's sidecars of the six inputs the held-cell tests pin (559d498, v3.8.0), every key: without the handle
-# the cut keeps every one of them, value for value, and a cut played once grows `root_motion`. The keyed clip's
++# the cut keeps every one of them, value for value, a cut played once grows `root_motion`, and every cut the record of
++# its cells (`cell_record`, bound to its strip by the PNG file's sha, so read against this run's strip). The keyed clip's
+ # identity (`source_cut.source.sha256`) is the sha of the input PNG files, other bytes on Linux than on macOS (its
+ # zlib): it is read against this run's own files, and pinned without.
+ SIDECARS = {
+ "hop-one-shot": "b546c1762af5aee76faa7ff83752a50b2accbc2de4b5daf3fd610a8d3eef914e",
+ "swing-once-return": "991343cce794a6f90c30b606f461ed6eeaf8d804e0ecadac3f51ab631b0fb813",
+ "swing-pinned": "88ecedeca1ff148799ac226b946c5c7d60d4a73dee347e2c6b4c33ca98eeeec3",
+ "topple-once": "78f0c731c7f6c72ea27fa15890652899d45ad8efd1e55ba8a66907b2d447f84e",
+ "walk-auto": "edf29b6fde312a55e0e4813ca1571511d855b603a78c12b75a9d5121f9e9448d",
+ "walk-fixed": "b9d991735bd05268e04ffae9c2660a21271075f5c0a0c281b2d0e7fbbe4c84de",
+ }
+
+
+ @pytest.mark.parametrize("case", sorted(UNHELD))
+ def test_without_the_handle_the_cut_is_the_same_pictures_as_before_and_its_sidecar_only_grows(case, tmp_path, monkeypatch):
+ _no_rife(monkeypatch, tmp_path)
+ frames, kw, pinned = UNHELD[case]
+ keyed = J.save(frames(), tmp_path / f"{case}-keyed")
+ rep = loop_mod.run_loop(keyed, tmp_path / f"{case}-out", fps=24.0, min_len=None, max_len=None, n_out=None,
+ seam_max=loop_mod.SEAM_RATIO_MAX, name=case, report_path=None, **kw)
+ assert _pictures(Path(rep["out_dir"]), case) == pinned
+ meta = _meta(rep)
+ grown = meta.pop("root_motion", None)
++ cells = meta.pop(loop_mod.CELL_RECORD)
++ assert cells["strip_sha256"] == hashlib.sha256(Path(rep["strip"]["path"]).read_bytes()).hexdigest()
++ assert len(cells["cells"]) == meta["frames"]
+ source = meta["source_cut"]["source"]
+ assert source.pop("sha256") == evidence.source_identity(sorted(keyed.glob("*.png")), 24.0)["sha256"]
+ assert hashlib.sha256(json.dumps(meta, sort_keys=True).encode()).hexdigest() == SIDECARS[case]
+ assert (grown is not None) == (meta["kind"] in rm.KINDS)
+ if grown is not None:
+ assert len(grown["root"]) == meta["frames"] and grown["point"] == "mass-centre"
+
+
+ def test_video_loop_and_video_set_take_the_switches():
+ from tests.conftest import help_options
+
+ loop = help_options("-m", "sprite_gen.cli", "video-loop")
+ assert {"--air-retime", "--meters-per-px", "--contact"} <= loop
+ assert {"--air-retime", "--meters-per-px"} <= help_options("-m", "sprite_gen.cli", "video-set")
+
+
+ def test_video_set_hands_the_switches_to_each_cut_and_says_each_air(monkeypatch, tmp_path):
+ from sprite_gen.video import batch
+
+ seen: list[dict] = []
+ monkeypatch.setattr(batch.frames_mod, "run_frames", lambda clip, out, **kw: {
+ "fps": 24, "frames": 10, "alpha_zero_pct_min": 50, "alpha_zero_pct_max": 60, "keyed_dir": str(out)})
+
+ def run_loop(*a, **kw):
+ seen.append(kw)
+ return {"cycle": {"length": 10, "period_global": None, "ratio": 0.0, "kind": "once"}, "resampled_seam_ratio": None,
+ "n_out": 10, "gif": {"file": "loop.gif"}, "webp": {"file": "loop.webp"}, "strip": {"path": "strip.png"},
+ "held_fill": {"cells": 10, "poses": 10, "held_runs": [], "made": [],
+ "before": {"cells": 10, "poses": 10, "held_runs": []}},
+ "root_motion": {"air": [{"cells": [3, 6], "takeoff": 2, "landing": 7, "seconds": 0.2083, "apex_px": 31.5,
+ "apex_m": 0.42}]},
+ "air_retime": {"applied": False, "why": "RIFE is not installed", "before": []}}
+
+ def video(image, prompt, out, report, **kw):
+ out.write_bytes(b"test-video")
+ report.write_text(json.dumps({"prompt": prompt}))
+ return 0
+
+ monkeypatch.setattr(batch.loop_mod, "run_loop", run_loop)
+ monkeypatch.setattr(batch, "_staggered_start", lambda gap: None)
+ still = tmp_path / "side.png"
+ Image.new("RGBA", (64, 64), (200, 80, 30, 255)).save(still)
+ result = batch.run_set(bases={"side": still}, states=["jump"], root=tmp_path / "set", character=None, duration=3,
+ resolution="720p", key="green", concurrency=1, force=False, gap=0, video_runner=video,
+ align_cycles="off", air_retime="gravity=9.81,air=0.6,speed=4", meters_per_px=0.005)
+ assert [(kw["air_retime"], kw["meters_per_px"]) for kw in seen] == [("gravity=9.81,air=0.6,speed=4", 0.005)]
+ assert result["items"][0]["loop"]["air"] == ["air 0.21 s, apex 0.42 m (cells 3-6)"]
+ assert any("air not retimed" in w for w in result["warnings"])
+ with pytest.raises(SystemExit, match="--meters-per-px"):
+ batch.run_set(bases={"side": still}, states=["jump"], root=tmp_path / "set2", character=None, duration=3,
+ resolution="720p", key="green", concurrency=1, force=False, gap=0, video_runner=video,
+ align_cycles="off", air_retime="speed=4")