Skip to content

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

feat(video-sway): --region-mask moves a region's own pixels and holds every visible pixel round it — the mask carried round where the cell before had it, then round the lay, never by the lay alone; the weight sin² of the distance to the held pixels over a rim read off the move; off, the sway is 32cff00's byte for byte

Soohong Kim1fac0336988c
diff --git a/sprite_gen/video/sway.py b/sprite_gen/video/sway.py
index 9264ba3..0020fa7 100644
--- a/sprite_gen/video/sway.py
+++ b/sprite_gen/video/sway.py
@@ -124,6 +124,22 @@ whichever is less (`read_share`; read between neighbours, 1 − HOLD_SLOPE·√2
read from the others, or walked back further. The record holds the mask, the carry of each piece in every cell and a
ledger per cell (`hold_ledger`): what was kept, what was read short, and the pixels whose read takes the source
backwards, read off the move each read took.
+
+`--region-mask` gives the region as a mask instead of the ellipse's weight (off by default, and off nothing of it is read
+or written): a PNG drawn on the cell the regions were read on, or a folder of one PNG per cell. Its lower edge may be moved
+to the crease under it (`--region-crease`, `crease_of`) and it is worn in by `--region-shrink` px (SHRINK_DEFAULT), so a
+mask drawn a little large holds what is outside it; then it is carried into every cell by its own pixels (`carry_region`):
+round where the cell before had them first and round the lay second, the lesser difference of the two that settle, and
+where neither does, where the cell before had them, the record saying which and why — never the lay alone. In every cell
+each visible pixel outside the mask and its soft edge keeps its bytes, and the clear pixels within the move's reach and
+REGION_AIR px of it are the air it moves into. The weight is sin² of the distance to the nearest held pixel over a rim, an
+ellipse of Lx across and Ly down (`rim_bands`: the fold rule's least band each way for the largest move that way, times
+`--region-rim`, widened together until (π/2)·hypot(dx/Lx, dy/Ly) is at most RIM_SLOPE in every cell), so the move leaves a
+pixel at least 1 − RIM_SLOPE of its area and its read stays clear of the held pixels; with `--band-up`, the lesser of that
+and the upper yield's. The ellipses still say each region's gain and where `--band-up`'s shape sits. A read whose four
+pixels take a held one is read from the others, and walked back only where they are half its weight, which the rim keeps
+from happening. The record holds the mask, its carry in every cell and a ledger per cell (`region_ledger`). Not with
+`--band`, a region's flat share, `--stretch-floor` nor `--hold-mask`.
"""
from __future__ import annotations
@@ -205,6 +221,16 @@ HOLD_MARGIN = 1 # px (8-neighbour steps): a read stops short of the kept pixels
HOLD_SLOPE = 0.5 # of a px: how much more of its move a read takes a px further any way (across, down or both), at most
HOLD_ROUND = 1 # px each way the share of a read is taken at its least over, then averaged over (0: as found)
HOLD_STEPS = 16 # a read whose four pixels still take a kept one walks back a 1/HOLD_STEPS of its move at a time
+# A region given as a mask (`--region-mask`): its own pixels carried, every visible pixel outside it held, the weight falling
+# to 0 toward the held pixels over a rim inside it (sin², read off the move), the upper yield (`--band-up`) the lesser.
+REGION_POLICY = "own-pixels-mask/held-outside/rim-sin2/1"
+RIM_SLOPE = 0.9 # the rim is widened until a move takes at most this much of a pixel's area along the way it moves
+RIM_DEFAULT = 1.0 # times the fold rule's least band, across and down, the rim starts at (`--region-rim`)
+SHRINK_DEFAULT = 2 # px (4-neighbour steps) a region mask is worn in by (`--region-shrink`): a mask drawn a little large holds nothing outside
+REGION_SOFT = 2 # px (4-neighbour steps) from the region a pixel not opaque moves with it, unless it is beside another solid one
+REGION_AIR = 2 # px past the move's reach (8-neighbour steps) round the region of clear pixels it may move into
+CREASE_UP, CREASE_DOWN = 5, 3 # rows above and below a region's lowest pixel its lower edge is looked for (`--region-crease`)
+CREASE_SPAN = 2 # columns either way the crease's rows are taken the median over
def parse_region(text: str) -> tuple[float, ...]:
@@ -980,6 +1006,7 @@ class Ask:
breath: Breath | None = None # the breath the part follows; None: the body's motion, answered by the damped mass
band: Band | None = None # each region moved as one mass over a band (`--band`); None: the weight falls from the centre
hold: Hold | None = None # pixels a band moves round and leaves as they are (`--hold-mask`); None: none
+ mask: RegionMask | None = None # the region as a mask, held round (`--region-mask`); None: the ellipse's weight
@property
def across(self) -> float:
@@ -995,11 +1022,14 @@ def read_ask(regions: list[tuple[float, ...]], *, gain: float | None = None, fre
zeta: float | None = None, on_fold: str = "refuse", read_on: str | None = None,
stretch_floor: float | None = None, breathe: Path | None = None, lag: float | None = None,
gain_across: float | None = None, band: float | str | None = None, band_margin: float | str | None = None,
- band_up: tuple[float, float | str] | str | None = None, hold_mask: Path | None = None, verb: str = VERB) -> Ask:
+ band_up: tuple[float, float | str] | str | None = None, hold_mask: Path | None = None,
+ region_mask: Path | None = None, region_rim: float | None = None, region_shrink: int | None = None,
+ region_crease: bool = False, verb: str = VERB) -> Ask:
"""A sway's ask, read and checked. A number left out (None) is its default: the damped mass's gain, freq and zeta,
or, on the breath (`breathe`), the breath's gain and lag. `band` (px or AUTO; None: off) moves each region as one
mass, `band_margin` and `band_up` shaping it, and `hold_mask` (a PNG or a folder of them; None: off) holds pixels
- the band moves round."""
+ the band moves round. `region_mask` (a PNG or a folder of them; None: off) gives the region as a mask instead,
+ `region_rim`, `region_shrink`, `region_crease` and `band_up` shaping it."""
# The numbers go into the record, which is JSON, and into the cells' arithmetic: a numpy number from a
# caller (an int64 has no JSON form) is read as the float the command line gives, so every caller of the
# same numbers writes the same strip and record.
@@ -1035,6 +1065,13 @@ def read_ask(regions: list[tuple[float, ...]], *, gain: float | None = None, fre
if not 0 <= stretch_floor < 1: # a NaN is neither
raise SystemExit(f"{verb}: --stretch-floor is the least area a moved pixel keeps, at least 0 and under 1; got {stretch_floor:g}")
breath = None if breathe is None else read_breath(breathe, lag, verb=verb)
+ if region_mask is not None:
+ masked = _read_region_mask(regions, region_mask, region_rim, region_shrink, region_crease, band, band_margin, band_up,
+ stretch_floor, hold_mask, verb)
+ return Ask(regions, gain, freq, zeta, on_fold, None if read_on is None else str(read_on), stretch_floor, gain_across,
+ breath, mask=masked)
+ if region_rim is not None or region_shrink is not None or region_crease:
+ raise SystemExit(f"{verb}: --region-rim, --region-shrink and --region-crease shape a region mask; they need --region-mask")
shaped = _read_band(regions, band, band_margin, band_up, stretch_floor, verb)
if hold_mask is not None and shaped is None:
raise SystemExit(f"{verb}: --hold-mask keeps pixels as they are while a band moves its regions round them; it needs --band")
@@ -1064,6 +1101,44 @@ def _read_band(regions: list[tuple[float, ...]], band: float | str | None, margi
raise SystemExit(f"{verb}: {exc}") from exc
+def _read_region_mask(regions: list[tuple[float, ...]], path: Path, rim: float | None, shrink: int | None, crease: bool,
+ band: float | str | None, margin: float | str | None, up: tuple[float, float | str] | str | None,
+ stretch_floor: float | None, hold_mask: Path | None, verb: str) -> RegionMask:
+ """The region mask asked (`--region-mask`, `--region-rim`, `--region-shrink`, `--region-crease`, `--band-up`), checked
+ as the command line checks it, and its PNGs read."""
+ if band is not None:
+ raise SystemExit(f"{verb}: --region-mask moves the region's own pixels and holds every visible pixel round it, the weight "
+ "falling over a rim inside it; --band moves an ellipse over a band outside it: give one of them")
+ if margin is not None:
+ raise SystemExit(f"{verb}: --band-margin shapes a band; with --region-mask the rim is read off the move (--region-rim)")
+ flat = [region for region in regions if len(region) > 4]
+ if flat:
+ raise SystemExit(f"{verb}: --region-mask gives the region as a mask, and a region's fifth number (flat, {flat[0][4]:g} on "
+ f"--region {','.join(f'{v:g}' for v in flat[0])}) shapes the ellipse's weight: give the region as "
+ "cx,cy,rx,ry with --region-mask")
+ if stretch_floor is not None:
+ raise SystemExit(f"{verb}: --stretch-floor reads the weight that falls from a region's centre; with --region-mask the rim "
+ "is widened with the move")
+ if hold_mask is not None:
+ raise SystemExit(f"{verb}: --region-mask holds every visible pixel outside the region already; --hold-mask is a band's")
+ rim = RIM_DEFAULT if rim is None else float(rim)
+ if not rim >= 1 or not math.isfinite(rim): # a NaN is not
+ raise SystemExit(f"{verb}: --region-rim is how many times the fold rule's least band the rim starts at, 1 or more; got {rim:g}")
+ asked = SHRINK_DEFAULT if shrink is None else shrink
+ try:
+ shrink = int(asked) if not isinstance(asked, bool) and float(asked) == int(asked) else -1
+ except (TypeError, ValueError, OverflowError): # a NaN, an infinity, not a number
+ shrink = -1
+ if shrink < 0:
+ raise SystemExit(f"{verb}: --region-shrink is the px the mask is worn in by, a whole number, 0 or more; got {asked!r}")
+ try:
+ shaped = None if up is None else parse_band_up(up if isinstance(up, str) else ",".join(str(v) for v in up))
+ except argparse.ArgumentTypeError as exc:
+ raise SystemExit(f"{verb}: {exc}") from exc
+ masks, digests, per_cell = _read_masks(path, "--region-mask", verb)
+ return RegionMask(masks, digests, per_cell, rim, shrink, bool(crease), shaped)
+
+
@dataclass(frozen=True, eq=False)
class Request:
"""A sway asked of a loop directory, read and checked; nothing is written by reading it."""
@@ -1089,7 +1164,8 @@ def read_request(loop_dir: Path, regions: list[tuple[float, ...]], *, gain: floa
read_on: str | None = None, stretch_floor: float | None = None, breathe: Path | None = None,
lag: float | None = None, gain_across: float | None = None, band: float | str | None = None,
band_margin: float | str | None = None, band_up: tuple[float, float | str] | str | None = None,
- hold_mask: Path | None = None) -> Request:
+ hold_mask: Path | None = None, region_mask: Path | None = None, region_rim: float | None = None,
+ region_shrink: int | None = None, region_crease: bool = False) -> Request:
loop_dir = loop_dir.expanduser().resolve()
metas = sorted(loop_dir.glob("*.strip.json"))
if len(metas) != 1:
@@ -1102,7 +1178,8 @@ def read_request(loop_dir: Path, regions: list[tuple[float, ...]], *, gain: floa
raise SystemExit(f"{verb}: a one-shot plays once; the follow-through is a loop's steady state")
ask = read_ask(regions, gain=gain, freq=freq, zeta=zeta, on_fold=on_fold, read_on=read_on, stretch_floor=stretch_floor,
breathe=breathe, lag=lag, gain_across=gain_across, band=band, band_margin=band_margin, band_up=band_up,
- hold_mask=hold_mask, verb=verb)
+ hold_mask=hold_mask, region_mask=region_mask, region_rim=region_rim, region_shrink=region_shrink,
+ region_crease=region_crease, verb=verb)
return Request(loop_dir, name, meta_path, meta_bytes, meta, ask)
@@ -1138,6 +1215,7 @@ class Answer:
reference: dict[str, Any] | None = None # the frame the regions were read on, when not cell 0 (`--reference`)
band: Banded | None = None # what the band comes to (`--band`); None: the weight falls from the centre
hold: Held | None = None # what the hold mask comes to (`--hold-mask`); None: none
+ mask: Masked | None = None # what the region mask comes to (`--region-mask`); None: the ellipse's weight
def carry(self, k: int) -> tuple[float, float]:
"""How far cell k's body lies from cell 0's, across and down: every region's ellipse is carried by it. Carried
@@ -1152,6 +1230,10 @@ class Answer:
return [(group, (mx[k], my[k])) for group, (mx, my) in self.groups]
def moved(self, k: int) -> Image.Image:
+ if self.mask is not None:
+ if all(dx == 0 and dy == 0 for _, (dx, dy) in self.moves_in(k)):
+ return self.cells[k].copy()
+ return (self.mask.drawn[k] if k in self.mask.drawn else self.masked_cell(k)[0]).copy()
if self.band is None:
return move_regions(self.cells[k], self.moves_in(k), self.carry(k))
if all(dx == 0 and dy == 0 for _, (dx, dy) in self.moves_in(k)):
@@ -1191,6 +1273,50 @@ class Answer:
offsets = [(mx[k], my[k]) for mx, my in self.moves.values()]
return _largest_move(group_weights, offsets), weights
+ def mask_field(self, k: int, xx: np.ndarray, yy: np.ndarray) -> tuple[tuple[np.ndarray, np.ndarray, np.ndarray] | None, dict[str, np.ndarray]]:
+ """Under a region mask, cell k's move per pixel (`move_field`'s: covered, across, down; None where nothing moves)
+ and what it moves and holds there (`region_sets`: the region, its soft edge, the air it may move into, the held
+ pixels). Over the region, its soft edge and the air the weight is the rim's, sin² of the distance to the nearest
+ held pixel (`rim_distance`, over `Masked.rim`), and with `--band-up` the lesser of that and each region's upper
+ yield, the ellipse carried by its own pixels as a band carries it (`Masked.up`); 0 elsewhere."""
+ assert self.mask is not None
+ masked = self.mask
+ alpha = np.asarray(self.cells[k].getchannel("A"))
+ region = masked.region_in(k, alpha >= ALPHA_SOLID)
+ soft, held, air = region_sets(region, alpha, masked.air)
+ across, down = masked.rim[:2]
+ rim = np.where(region | soft | air, np.sin(0.5 * math.pi * rim_distance(held, across, down)) ** 2, 0.0)
+ # The groups as `solve_cells` makes them: one per gain a region moves by, in the order of `moves`.
+ groups = [[i for i, (rg, hold) in enumerate(zip(self.gains, self.held)) if rg == g and not hold] for g in self.moves]
+ if masked.up is None:
+ group_weights = [rim if members else np.zeros(rim.shape) for members in groups]
+ else:
+ yields = [band_weight(xx, yy, (region_[0] + carried["px"][0], region_[1] + carried["px"][1]), *shape)
+ for region_, shape, carried in zip(self.ask.regions, masked.up.shapes, masked.up.carried[k])]
+ group_weights = [np.minimum(rim, np.max([yields[i] for i in members], axis=0)) if members else np.zeros(rim.shape)
+ for members in groups]
+ offsets = [(mx[k], my[k]) for mx, my in self.moves.values()]
+ return _largest_move(group_weights, offsets), {"region": region, "soft": soft, "air": air, "held": held}
+
+ def masked_cell(self, k: int) -> tuple[Image.Image, dict[str, Any]]:
+ """Under a region mask, cell k drawn by its move (`mask_field`) as a hold draws it (`draw_held`), every read its
+ whole move and no held pixel read; what it moved and held, the move, and how each pixel was read. Kept in
+ `Masked.drawn`."""
+ assert self.mask is not None
+ cell = self.cells[k]
+ w, h = cell.size
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
+ field, sets = self.mask_field(k, xx, yy)
+ if field is None or all(dx == 0 and dy == 0 for _, (dx, dy) in self.moves_in(k)):
+ still = np.zeros((h, w))
+ field, drawn = None, cell.copy()
+ read = {"share": np.ones((h, w)), "readers": still > 0, "renormalised": still > 0, "walked": still > 0,
+ "read_x": still, "read_y": still}
+ else:
+ drawn, read = draw_held(cell, field, sets["held"], np.zeros((h, w), bool), short=False)
+ self.mask.drawn.setdefault(k, drawn)
+ return drawn, {**sets, "field": field, **read}
+
def record(self, source: str = SOURCE) -> dict[str, Any]:
"""The sway as the strip's meta records it, `source` the strip as cut kept beside it (`video-sway` adds its
animations' checks); a frames folder's records it alike, the folder its source."""
@@ -1213,17 +1339,20 @@ class Answer:
"reach_requested_px": round(self.reach_requested, 2), "reach_per_gain_px": round(self.reach_per_gain, 3),
# Where the regions took gains of their own, each says the gain it moved by and whether it
# was held still (gain 0); where they all took one, the strip's `gain` is every region's.
- "regions": [{"radius_px": radius, "ratio": round(ratio, 3),
- "gain_limit": None if (limit := gain_limit(self.reach_per_gain, radius)) is None else round(limit, 3)}
+ # A region mask's rim is read off the move (`rim_bands`): the fold rule reads no radius, and no gain folds it.
+ "regions": [{"radius_px": radius if math.isfinite(radius) else None, "ratio": round(ratio, 3),
+ "gain_limit": None if not math.isfinite(radius) or (limit := gain_limit(self.reach_per_gain, radius)) is None
+ else round(limit, 3)}
| ({} if len(set(self.gains)) == 1 else {"gain": g, "held": hold})
for radius, ratio, g, hold in zip(self.radii, self.ratios, self.gains, self.held)],
},
} | ({} if self.read_on is None else {"read_on": self.read_on}) | ({} if self.stretch is None else {"stretch": self.stretch}) \
- | ({} if self.read_on is None and self.stretch is None and self.band is None else
- {"carry_basis": dict(CARRY_BASIS if self.band is None else CARRY_BASIS_BAND)}) \
+ | ({} if self.read_on is None and self.stretch is None and self.band is None and self.mask is None else
+ {"carry_basis": dict(CARRY_BASIS if self.band is None and self.mask is None else CARRY_BASIS_BAND)}) \
| ({} if self.reference is None else {"reference": self.reference}) \
| ({} if self.band is None else {"band": self.band_record()}) \
- | ({} if self.hold is None else {"hold": self.hold_record()})
+ | ({} if self.hold is None else {"hold": self.hold_record()}) \
+ | ({} if self.mask is None else {"region_mask": self.mask_record()})
def band_record(self) -> dict[str, Any]:
"""The band as the record holds it (`--band`): what was asked, the reach it was read off, its px and the margin's,
@@ -1231,18 +1360,7 @@ class Answer:
what, the cells carried by the lay and why, and the ledger."""
assert self.band is not None
band = self.band
- carried = _carried_record
- return {
- "policy": BAND_POLICY, "asked": band.asked.asked(), "reach_px": round(band.reach, 4),
- "band_px": band.band, "margin_px": band.margin,
- "regions": [{"flat_px": [round(v, 4) for v in flat], "band_px": [round(v, 4) for v in bands],
- "steepest": {"per_gain": round(per_gain, 4), "cell": k, "ratio": round(g * per_gain, 3)}}
- for (flat, bands), (per_gain, k), g in zip(band.shapes, band.steepest, self.gains)],
- "carry": {"search_px": CARRY_SEARCH, "cells": [[carried(entry) for entry in cell] for cell in band.carried]},
- "lay": [{"cell": k, "region": i, "why": entry["why"]} for k, cell in enumerate(band.carried)
- for i, entry in enumerate(cell) if entry["from"] == "lay"],
- "ledger": band.ledger,
- }
+ return {"policy": BAND_POLICY, "asked": band.asked.asked(), **_shaped_record(band, self.gains), "ledger": band.ledger}
def hold_record(self) -> dict[str, Any]:
"""The hold mask as the record holds it (`--hold-mask`): what was asked, how its pieces are grown, kept round and
@@ -1261,10 +1379,49 @@ class Answer:
"ledger": hold.ledger,
}
+ def mask_record(self) -> dict[str, Any]:
+ """The region mask as the record holds it (`--region-mask`): what was asked; how far round the region its soft edge
+ and the air reach, and the rim (`rim_bands`); the mask on the cell it was drawn on, worn in, with the solid pixels
+ it was carried by, and the crease where asked (`crease_of`); where it is carried in every cell and from what, and
+ the cells that kept the carry of the cell before and why (None and none where a mask is given for each cell); the
+ upper yield's bands and carry (`--band-up`; None without it); and the ledger (`region_ledger`)."""
+ assert self.mask is not None
+ masked = self.mask
+ across, down, slope, least = masked.rim
+ one = None if masked.asked.per_cell else masked.worn[0]
+ return {
+ "policy": REGION_POLICY, "asked": masked.asked.asked(), "soft_px": REGION_SOFT, "air_px": masked.air,
+ "rim": {"across_px": across, "down_px": down, "least_px": list(least), "slope": slope, "slope_bound": RIM_SLOPE},
+ "mask": None if one is None else {"px": int(one.sum()), "box": _box(one), "carried_by_px": masked.matched},
+ "crease": masked.creases,
+ "carry": None if masked.carried is None else {"search_px": CARRY_SEARCH,
+ "cells": [_carried_record(entry) for entry in masked.carried]},
+ "kept": [{"cell": k, "why": entry["why"]} for k, entry in enumerate(masked.carried or []) if entry["from"] == "before"],
+ "up": None if masked.up is None else _shaped_record(masked.up, self.gains),
+ "ledger": masked.ledger,
+ }
+
+
+def _shaped_record(band: Banded, gains: list[float]) -> dict[str, Any]:
+ """A band's shape as the record holds it (`--band`, and `--band-up` under a region mask): the reach it was read off,
+ its px and the margin's, each region's flat radii and bands (across, above, below) and the steepest its weight falls,
+ where each region is carried in every cell and from what, and the cells carried by the lay and why."""
+ return {
+ "reach_px": round(band.reach, 4), "band_px": band.band, "margin_px": band.margin,
+ "regions": [{"flat_px": [round(v, 4) for v in flat], "band_px": [round(v, 4) for v in bands],
+ "steepest": {"per_gain": round(per_gain, 4), "cell": k, "ratio": round(g * per_gain, 3)}}
+ for (flat, bands), (per_gain, k), g in zip(band.shapes, band.steepest, gains)],
+ "carry": {"search_px": CARRY_SEARCH, "cells": [[_carried_record(entry) for entry in cell] for cell in band.carried]},
+ "lay": [{"cell": k, "region": i, "why": entry["why"]} for k, cell in enumerate(band.carried)
+ for i, entry in enumerate(cell) if entry["from"] == "lay"],
+ }
+
def _carried_record(entry: dict[str, Any]) -> dict[str, Any]:
- """A carry (`carry_mask`'s entry) as the record holds it."""
+ """A carry (`carry_mask`'s or `carry_region`'s entry) as the record holds it."""
out = {"px": [round(v, 4) + 0.0 for v in entry["px"]], "from": entry["from"]}
+ if "guess" in entry:
+ out["guess"] = entry["guess"]
if "why" in entry:
out["why"] = entry["why"]
if "least" in entry:
@@ -1365,13 +1522,18 @@ def solve_cells(ask: Ask, cells: list[Image.Image], frame_ms: float | None, *, v
reach = reach_at(gain)
shaped = None
- if ask.band is None:
- radii, sized, larger = [region_radius(region) for region in regions], "a region of radius", "give the region larger radii"
- else:
+ up = None if ask.mask is None else ask.mask.up # a region mask's upper yield: shaped as a band's, its band and margin auto
+ if ask.band is not None or up is not None:
# The reach first, at the gain asked: the band and the margin are read off it, and the fold rule reads each
# region by its narrowest band.
- shaped = band_shapes(ask.band, regions, reach)
- radii, sized, larger = [min(bands) for _, bands in shaped[2]], "a region's band of", "give a wider --band"
+ shaped = band_shapes(ask.band if ask.band is not None else Band(AUTO, AUTO, up), regions, reach)
+ radii, sized = [min(bands) for _, bands in shaped[2]], "a region's band of"
+ larger = "give a wider --band" if ask.band is not None else "give --band-up a wider band"
+ elif ask.mask is not None:
+ # A region mask's rim is read off the move at the gain it moves by (`rim_bands`): the fold rule reads no radius.
+ radii, sized, larger = [math.inf] * len(regions), "", ""
+ else:
+ radii, sized, larger = [region_radius(region) for region in regions], "a region of radius", "give the region larger radii"
smallest = min(radii)
requested, reach_requested = gain, reach
# The offset is the gain times the answer at gain 1, so one move decides every gain.
@@ -1416,7 +1578,9 @@ def solve_cells(ask: Ask, cells: list[Image.Image], frame_ms: float | None, *, v
answer = answer_at(gains, held)
if shaped is None:
- return answer
+ if ask.mask is None:
+ return answer
+ return _masked(answer, None, (whole_across, whole_down), None if reference is None else reference[0], verb)
# Under a band the regions are carried by their own pixels, whatever the gain; and where the flat ellipse and the
# outer one differ in shape (above the centre under --band-up) the band is narrower across its ring than its px,
# so the weight falls steeper than the fold rule reads. A pixel moved by the gain times u (the move at gain 1)
@@ -1427,16 +1591,21 @@ def solve_cells(ask: Ask, cells: list[Image.Image], frame_ms: float | None, *, v
if any(over):
i = over.index(True)
per_gain, k = steepest[i]
- why = (f"--band's weight falls steeper than its {shaped[0]:g} px where the band is narrower across its ring (cell {k}: "
+ flag, wider = (("--band", "a wider --band" + (" or --band-up" if ask.band.up else "")) if ask.band is not None
+ else ("--band-up", "--band-up a wider band"))
+ why = (f"{flag}'s weight falls steeper than its {shaped[0]:g} px where the band is narrower across its ring (cell {k}: "
f"at --gain {gains[i]:g} a pixel keeps {1 - gains[i] * per_gain:.3f} of its area)")
if on_fold == "refuse":
- raise SystemExit(f"{verb}: {why}; lower --gain or give a wider --band" + (" or --band-up" if ask.band.up else ""))
+ raise SystemExit(f"{verb}: {why}; lower --gain or give {wider}")
lowered = [steepest_gain(g, per_gain) if fold else g for g, fold, (per_gain, _) in zip(gains, over, steepest)]
held = [hold or (fold and g < GAIN_MEASURED) for g, hold, fold in zip(lowered, held, over)]
if all(held):
- raise SystemExit(f"{verb}: {why}, and --on-fold lower would have to go under --gain {GAIN_MEASURED:g}; give a wider "
- "--band" + (" or --band-up" if ask.band.up else ""))
+ raise SystemExit(f"{verb}: {why}, and --on-fold lower would have to go under --gain {GAIN_MEASURED:g}; give {wider}")
answer = answer_at([0.0 if hold else g for g, hold in zip(lowered, held)], held)
+ if ask.mask is not None:
+ # The upper yield's shape and carry, as a band's: its ledger is the region mask's (`region_ledger`).
+ up_band = Banded(Band(AUTO, AUTO, up), reach_requested, shaped[0], shaped[1], shaped[2], carried, steepest)
+ return _masked(answer, up_band, (whole_across, whole_down), None if reference is None else reference[0], verb)
banded = _banded(answer, shaped, reach_requested, carried, steepest, verb)
return banded if ask.hold is None else _held(banded, None if reference is None else reference[0], verb)
@@ -1586,13 +1755,21 @@ def band_notes(record: dict[str, Any], verb: str = VERB, at: str = f"{loop_mod.S
whys = "; ".join(f"cell {e['cell']}: {e['why']}" for e in entries)
notes.append(f"{verb}: warning: --band carries {name} by the body's lay in {len(entries)} cells, its own pixels not "
f"found surely ({whys}) — {at}.lay")
- ledger, n = band["ledger"], len(band["ledger"]["jacobian_min"])
said = {"band_on_regions_px": "the band lies over solid pixels of the regions",
"pressed_px": f"moved pixels are left under {PRESSED:g} of their area",
"stretched_px": f"moved pixels are left over {STRETCHED:g} of their area",
"outside_moved_px": f"solid pixels outside every region move {MOVED_PX:g} px or more"}
+ return notes + _ledger_notes(band["ledger"], said, "--band", verb, at)
+
+
+def _ledger_notes(ledger: dict[str, Any], said: dict[str, str], flag: str, verb: str, at: str) -> list[str]:
+ """A warning line for each count of `ledger` that `said` names and that is not 0 in some cell: in how many cells, up
+ to how many pixels and in which cell (and for the pressed and the stretched, the least or the most area there and
+ where), and where in the record (`at`)."""
+ notes = []
for key, what in said.items():
counts = ledger[key]
+ n = len(counts)
cells = [k for k, count in enumerate(counts) if count]
if not cells:
continue
@@ -1601,7 +1778,7 @@ def band_notes(record: dict[str, Any], verb: str = VERB, at: str = f"{loop_mod.S
if key in ("pressed_px", "stretched_px"):
spot = ledger["area_least" if key == "pressed_px" else "area_most"][top]
extra = f", {'least' if key == 'pressed_px' else 'most'} {spot[0]:g} at {spot[1]},{spot[2]}"
- notes.append(f"{verb}: warning: --band: {what} in {len(cells)} of {n} cells, up to {ledger[key + '_max']} px (cell "
+ notes.append(f"{verb}: warning: {flag}: {what} in {len(cells)} of {n} cells, up to {ledger[key + '_max']} px (cell "
f"{top}{extra}) — {at}.ledger.{key}")
return notes
@@ -1630,10 +1807,16 @@ def _mask_of(image: Image.Image) -> np.ndarray:
def read_hold(path: Path, verb: str = VERB) -> Hold:
"""A hold mask (`--hold-mask`) read: a PNG, or a folder of PNGs, one per cell, in name order. A single mask that holds
no pixel is refused; a cell of a folder may hold none."""
+ return Hold(*_read_masks(path, "--hold-mask", verb))
+
+
+def _read_masks(path: Path, flag: str, verb: str) -> tuple[list[np.ndarray], list[str], bool]:
+ """A mask's PNG, or a folder of PNGs, one per cell, in name order, read for `flag` (`_mask_of`): the masks, the sha256
+ of each file's bytes, and whether it is a folder. Masks that hold no pixel between them are refused."""
path = Path(path).expanduser()
files = sorted(path.glob("*.png")) if path.is_dir() else [path]
if not files:
- raise SystemExit(f"{verb}: --hold-mask {path}: a folder of masks with no PNG in it")
+ raise SystemExit(f"{verb}: {flag} {path}: a folder of masks with no PNG in it")
masks, digests = [], []
for file in files:
try:
@@ -1641,12 +1824,12 @@ def read_hold(path: Path, verb: str = VERB) -> Hold:
with Image.open(io.BytesIO(data)) as image:
masks.append(_mask_of(image))
except (OSError, ValueError) as exc:
- raise SystemExit(f"{verb}: --hold-mask {file}: not read ({exc})") from exc
+ raise SystemExit(f"{verb}: {flag} {file}: not read ({exc})") from exc
digests.append(hashlib.sha256(data).hexdigest())
if not any(mask.any() for mask in masks):
- raise SystemExit(f"{verb}: --hold-mask {path}: holds no pixel (alpha {ALPHA_SOLID} or more, or that light where it has "
+ raise SystemExit(f"{verb}: {flag} {path}: holds no pixel (alpha {ALPHA_SOLID} or more, or that light where it has "
"no alpha)")
- return Hold(masks, digests, path.is_dir())
+ return masks, digests, path.is_dir()
def _grow4(mask: np.ndarray, steps: int) -> np.ndarray:
@@ -1831,15 +2014,16 @@ def read_share(free: np.ndarray, size: np.ndarray) -> np.ndarray:
def draw_held(cell: Image.Image, field: tuple[np.ndarray, np.ndarray, np.ndarray], held: np.ndarray,
- air: np.ndarray) -> tuple[Image.Image, dict[str, np.ndarray]]:
+ air: np.ndarray, short: bool = True) -> tuple[Image.Image, dict[str, np.ndarray]]:
"""`cell` moved by `field` (`_draw`'s: covered, across, down) round what a hold keeps (`hold_sets`: the held pixels and
the air beside them). The field is as it is; the held pixels and the air keep their bytes; every other pixel is read
as `_draw` reads it, but only as far back along its move as `read_share` lets it, which stops short of every kept
- pixel. A read whose four pixels still take one it may not (a solid pixel a kept one, a clear pixel a held one) is read
- from the others where they are half its weight or more (`renormalised`), else walked back a 1/HOLD_STEPS of its move
- at a time until they are (`walked`). Where every read takes its whole move and no kept pixel the cell is `_draw`'s,
- byte for byte. Also returns, per pixel, the share of its move each read took (`share`), the pixels read (`readers`)
- and the move each read took (`read_x`, `read_y`; 0 on what is kept and on what does not move)."""
+ pixel (with `short` false, its whole move: a region mask's rim keeps its reads clear of the held pixels). A read whose
+ four pixels still take one it may not (a solid pixel a kept one, a clear pixel a held one) is read from the others
+ where they are half its weight or more (`renormalised`), else walked back a 1/HOLD_STEPS of its move at a time until
+ they are (`walked`). Where every read takes its whole move and no kept pixel the cell is `_draw`'s, byte for byte.
+ Also returns, per pixel, the share of its move each read took (`share`), the pixels read (`readers`) and the move each
+ read took (`read_x`, `read_y`; 0 on what is kept and on what does not move)."""
src = np.asarray(cell.convert("RGBA"), dtype=np.float32)
h, w = src.shape[:2]
yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
@@ -1851,7 +2035,7 @@ def draw_held(cell: Image.Image, field: tuple[np.ndarray, np.ndarray, np.ndarray
solid = src[..., 3] >= ALPHA_SOLID
readers = inside & ~kept & (size > 0)
share = np.ones((h, w))
- if readers.any():
+ if short and readers.any():
y, x = divmod(int(np.argmax(np.where(readers, size, -1))), w)
way = (float(move_x[y, x] / size[y, x]), float(move_y[y, x] / size[y, x]))
share = np.where(readers, read_share(free_back(kept, way, float(size[y, x]) / HOLD_SLOPE + 1), size), 1.0)
@@ -1997,19 +2181,353 @@ def hold_notes(record: dict[str, Any], verb: str = VERB, at: str = f"{loop_mod.S
whys = "; ".join(f"cell {e['cell']}: {e['why']}" for e in entries)
notes.append(f"{verb}: warning: --hold-mask carries its piece {i} by the body's lay in {len(entries)} cells, its own "
f"pixels not found surely ({whys}) — {at}.lay")
- ledger, n = hold["ledger"], len(hold["ledger"]["held_px"])
said = {"renormalised_px": "reads took a kept pixel and were read from the others",
"walked_px": "reads took a kept pixel and were walked back further",
"read_folded_px": "reads take the source backwards (0 or less of its area)"}
- for key, what in said.items():
- counts = ledger[key]
- cells = [k for k, count in enumerate(counts) if count]
- if not cells:
+ return notes + _ledger_notes(hold["ledger"], said, "--hold-mask", verb, at)
+
+
+@dataclass(frozen=True, eq=False)
+class RegionMask:
+ """A region given as a mask (`--region-mask`): one PNG drawn on the cell the regions were read on, or a folder of PNGs,
+ one per cell in name order, read as a hold mask is (`_mask_of`), and the sha256 of each file's bytes; how many times
+ the fold rule's least band the rim starts at (`--region-rim`), the px the mask is worn in by (`--region-shrink`),
+ whether its lower edge is moved to the crease under it (`--region-crease`), and the upper yield (`--band-up`'s flat
+ share and band; None: none)."""
+
+ masks: list[np.ndarray]
+ sha256: list[str]
+ per_cell: bool
+ rim: float = RIM_DEFAULT
+ shrink: int = SHRINK_DEFAULT
+ crease: bool = False
+ up: tuple[float, float | str] | None = None
+
+ def asked(self) -> dict[str, Any]:
+ return {"per_cell": self.per_cell, "sha256": self.sha256 if self.per_cell else self.sha256[0], "rim": self.rim,
+ "shrink_px": self.shrink, "crease": self.crease,
+ "up": None if self.up is None else {"flat": self.up[0], "band": self.up[1]}}
+
+
+@dataclass(frozen=True, eq=False)
+class Masked:
+ """What a region mask comes to on the cells (`--region-mask`): the mask — one, drawn on the cell the regions were read
+ on, which lies `base_shift` from cell 0, or one per cell — trimmed to its crease where asked and worn in (`worn`), each
+ one's crease (`creases`; None where not asked), how many solid pixels the one mask was carried by (`matched`), its
+ carry in every cell (`carried`, as `carry_region` carries it; None where a mask is given for each cell), how far round
+ the region the air it may move into reaches (`air`, 8-neighbour steps), the rim (`rim_bands`: across and down, its
+ slope at the steepest cell and the least bands it started at), the upper yield shaped and carried as a band's (`up`,
+ `--band-up`; None: none), and the ledger (`region_ledger`). Each cell is drawn once (`drawn`)."""
+
+ asked: RegionMask
+ worn: list[np.ndarray]
+ creases: list[dict[str, Any]] | None
+ base_shift: tuple[float, float]
+ matched: int
+ carried: list[dict[str, Any]] | None
+ air: int
+ rim: tuple[int, int, float, tuple[int, int]]
+ up: Banded | None = None
+ ledger: dict[str, Any] | None = None
+ drawn: dict[int, Image.Image] = dataclasses.field(default_factory=dict)
+
+ def region_in(self, k: int, solid: np.ndarray) -> np.ndarray:
+ """The region's pixels in cell k (`solid`: the cell's solid pixels): the mask given for it, or the one mask carried
+ there (`_carried`), where the cell is solid."""
+ if self.asked.per_cell:
+ return self.worn[k] & solid
+ px = self.carried[k]["px"]
+ return _carried(self.worn[0], (px[0] - self.base_shift[0], px[1] - self.base_shift[1])) & solid
+
+
+def _shrink4(mask: np.ndarray, steps: int) -> np.ndarray:
+ """`mask` worn in by `steps` 4-neighbour steps: a pixel stays where it and its 4 neighbours are all in it (past the
+ cell's edge none is)."""
+ out = mask.copy()
+ for _ in range(steps):
+ p = np.pad(out, 1)
+ out = p[1:-1, 1:-1] & p[:-2, 1:-1] & p[2:, 1:-1] & p[1:-1, :-2] & p[1:-1, 2:]
+ return out
+
+
+def _carried(mask: np.ndarray, shift: tuple[float, float]) -> np.ndarray:
+ """`mask` moved by `shift` (across, down), read bilinear as `_sample` reads a cell: the pixels it covers half or more of."""
+ h, w = mask.shape
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float64)
+ return _bilinear(mask.astype(np.float64), xx - shift[0], yy - shift[1]) >= 0.5
+
+
+def crease_of(cell: Image.Image, mask: np.ndarray) -> tuple[np.ndarray, dict[str, Any]]:
+ """`mask` ending at the crease under it (`--region-crease`): in each column of its solid pixels in `cell` whose lowest
+ has a solid pixel under it (the part lies on more of the figure there), the darkest solid pixel (by luma) from
+ CREASE_UP rows above that lowest one to CREASE_DOWN rows below it, the rows then the median over CREASE_SPAN columns
+ either way, rounded down; the mask is cut under that row and filled down to it with the column's solid pixels. A column
+ whose lowest pixel has a clear one under it (the part's free edge, over the air) is left as it is. Also the record of
+ it: each column's row, and how many columns were left free."""
+ rgba = np.asarray(cell.convert("RGBA"))
+ solid = rgba[..., 3] >= ALPHA_SOLID
+ luma = rgba[..., :3].astype(np.float64) @ np.array([0.299, 0.587, 0.114])
+ on = mask & solid
+ h = mask.shape[0]
+ darkest: dict[int, int] = {}
+ free = 0
+ for x in (int(x) for x in np.nonzero(on.any(axis=0))[0]):
+ lowest = int(np.nonzero(on[:, x])[0].max())
+ if lowest + 1 >= h or not solid[lowest + 1, x]:
+ free += 1
continue
- top = max(range(n), key=lambda k: counts[k])
- notes.append(f"{verb}: warning: --hold-mask: {what} in {len(cells)} of {n} cells, up to {ledger[key + '_max']} px (cell "
- f"{top}) — {at}.ledger.{key}")
- return notes
+ window = [y for y in range(lowest - CREASE_UP, lowest + CREASE_DOWN + 1) if 0 <= y < h and solid[y, x]]
+ darkest[x] = min(window, key=lambda y: luma[y, x])
+ rows = {x: int(np.floor(np.median([darkest[q] for q in range(x - CREASE_SPAN, x + CREASE_SPAN + 1) if q in darkest])))
+ for x in darkest}
+ out = mask.copy()
+ for x, y in rows.items():
+ lowest = int(np.nonzero(on[:, x])[0].max())
+ out[y + 1:, x] = False
+ out[lowest + 1:y + 1, x] |= solid[lowest + 1:y + 1, x]
+ return out, {"rows": {str(x): y for x, y in sorted(rows.items())}, "free_columns": free}
+
+
+def carry_region(whole: np.ndarray, cells: list[Image.Image], mask: np.ndarray, base_shift: tuple[float, float],
+ lays: list[tuple[float, float]], base_index: int | None) -> list[dict[str, Any]]:
+ """Per cell, where a region mask's pixels — those of `whole` (`_whole_premultiplied` of the cell it was drawn on, which
+ lies `base_shift` from cell 0) under `mask` — are (`carry_match`), in the loop's order from `base_index` (from cell 0
+ where the cell it was drawn on is none of them): looked for round where the cell before had them first and round the
+ cell's lay second, the lesser difference of the two that settle (where the cell before had them, on a tie); where
+ neither settles, where the cell before had them, saying why. A part moves little from one cell to the next, and the
+ lay can lie far off it where the outline changes; never the lay alone."""
+ n = len(cells)
+ order = list(range(n)) if base_index is None else [(base_index + i) % n for i in range(1, n)]
+ entries: dict[int, dict[str, Any]] = {}
+ if base_index is not None:
+ entries[base_index] = {"px": [float(base_shift[0]), float(base_shift[1])], "from": "base"}
+ before_cell, before = base_index, (0.0, 0.0) # the cell before and its carry from the cell the mask was drawn on
+ for k in order:
+ cell = _whole_premultiplied(cells[k])
+ lay = (float(lays[k][0]) - base_shift[0], float(lays[k][1]) - base_shift[1])
+ named = "where the frame it was drawn on had it" if before_cell is None else f"where cell {before_cell} had it"
+ tries = [("before", named, carry_match(whole, cell, mask, before, around=named))]
+ if (round(lay[0]), round(lay[1])) != (round(before[0]), round(before[1])): # else the same search
+ tries.append(("lay", "the lay", carry_match(whole, cell, mask, lay)))
+ settled = [(guess, found) for guess, _, found in tries if found.shift is not None]
+ if settled:
+ guess, found = min(settled, key=lambda t: t[1].least) # the first on a tie
+ before = found.shift
+ entries[k] = {"px": [base_shift[0] + before[0], base_shift[1] + before[1]], "from": "pixels", "guess": guess,
+ "least": found.least, "curvature": None if found.curvature is None else list(found.curvature)}
+ else:
+ found = tries[0][2]
+ entries[k] = {"px": [base_shift[0] + before[0], base_shift[1] + before[1]], "from": "before",
+ "why": "; ".join(f"round {name}: {miss.why}" for _, name, miss in tries),
+ "least": found.least, "curvature": None if found.curvature is None else list(found.curvature)}
+ before_cell = k
+ return [entries[k] for k in range(n)]
+
+
+def rim_bands(across: np.ndarray, down: np.ndarray, scale: float) -> tuple[int, int, float, tuple[int, int]]:
+ """A region mask's rim for a move (`across`, `down`: px per cell): it starts at the fold rule's least band for the
+ largest move each way, ceil(most × π / 2) + 1, times `scale` and rounded up, and both are widened a px at a time until
+ (π/2)·hypot(dx/Lx, dy/Ly) is at most RIM_SLOPE in every cell. sin²(π/2·d) rises at most π/2 a unit of d, and d (the
+ distance in rim units, `rim_distance`) at most 1/Lx a px across and 1/Ly down, so a move takes at most that much of a
+ pixel's area along its way and goes less far than the held pixels lie. The rim across and down, that slope at its
+ steepest cell, and the least bands it started at."""
+
+ def least(most: float) -> int:
+ return math.ceil((math.ceil(most * math.pi / 2) + 1) * scale)
+
+ started = (least(float(np.max(np.abs(across)))), least(float(np.max(np.abs(down)))))
+ lx, ly = started
+
+ def steepest() -> float:
+ return float(np.max(0.5 * math.pi * np.hypot(across / lx, down / ly)))
+
+ while steepest() > RIM_SLOPE:
+ lx, ly = lx + 1, ly + 1
+ return lx, ly, round(steepest(), 4), started
+
+
+def rim_distance(held: np.ndarray, across: int, down: int) -> np.ndarray:
+ """Per pixel, how far the nearest held pixel is in rim units, an ellipse `across` px wide each way and `down` px high —
+ d = the least of hypot((x − qx)/across, (y − qy)/down) over the held pixels q — and 1 where none is nearer: the least
+ along each row, then down each column, which is exact (past the cell's edge none is held)."""
+ h, w = held.shape
+ row = np.full((h, w), np.inf)
+ p = np.pad(held, ((0, 0), (across, across)))
+ for ox in range(-across, across + 1):
+ row = np.where(p[:, across + ox:across + ox + w], np.minimum(row, (ox / across) ** 2), row)
+ q = np.pad(row, ((down, down), (0, 0)), constant_values=np.inf)
+ both = np.full((h, w), np.inf)
+ for oy in range(-down, down + 1):
+ both = np.minimum(both, q[down + oy:down + oy + h] + (oy / down) ** 2)
+ return np.sqrt(np.minimum(both, 1.0))
+
+
+def region_sets(region: np.ndarray, alpha: np.ndarray, air: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """What a region mask moves and holds in a cell (`alpha`: the cell's alpha): the region's soft edge — the pixels not
+ opaque (alpha over 0, under ALPHA_SOLID) within REGION_SOFT 4-neighbour steps of it and not beside another solid
+ pixel — which moves with it; the held pixels, every other one not clear; and the clear pixels within `air`
+ 8-neighbour steps of it, the air it may move into."""
+ solid = alpha >= ALPHA_SOLID
+ soft = (alpha > 0) & ~solid & _grow4(region, REGION_SOFT) & ~region & ~_grow4(solid & ~region, 1)
+ return soft, (alpha > 0) & ~region & ~soft, (alpha == 0) & _grow8(region, air)
+
+
+def _masked(answer: Answer, up: Banded | None, whole: tuple[np.ndarray, np.ndarray], reference: Image.Image | None,
+ verb: str) -> Answer:
+ """`answer` with its region given as a mask (`--region-mask`): one mask, drawn on the cell the regions were read on
+ (`_band_base`), trimmed to its crease where asked (`crease_of`), worn in by `--region-shrink` px (`_shrink4`) and
+ carried into every cell by the solid pixels of the mask as trimmed (`carry_region`); or a mask for each cell, trimmed
+ and worn in on its own cell. The rim is read off the move the fold rule reads (`whole`, at gain 1) at the gain the
+ regions move by (`rim_bands`); `up` is the upper yield (`--band-up`; None: none); and the ledger of every cell
+ (`region_ledger`). Refused where the masks leave nothing to move, and where the move folds the picture all the same."""
+ mask, cells = answer.ask.mask, answer.cells
+ assert mask is not None
+ w, h = cells[0].size
+ for given in mask.masks:
+ if given.shape != (h, w):
+ raise SystemExit(f"{verb}: --region-mask is {given.shape[1]}x{given.shape[0]}, the cells are {w}x{h}: a mask is "
+ "drawn on a cell, pixel for pixel")
+ if mask.per_cell and len(mask.masks) != len(cells):
+ raise SystemExit(f"{verb}: --region-mask holds {len(mask.masks)} masks and there are {len(cells)} cells: a folder gives "
+ "one mask per cell, in name order")
+
+ def shaped(given: np.ndarray, cell: Image.Image) -> tuple[np.ndarray, np.ndarray, dict[str, Any] | None]:
+ trimmed, crease = crease_of(cell, given) if mask.crease else (given, None)
+ return trimmed, _shrink4(trimmed, mask.shrink), crease
+
+ if mask.per_cell:
+ made = [shaped(given, cell) for given, cell in zip(mask.masks, cells)]
+ base_shift, matched, carried = (0.0, 0.0), 0, None
+ else:
+ base, base_shift, base_index, lays = _band_base(answer, reference)
+ made = [shaped(mask.masks[0], base)]
+ by = made[0][0] & (np.asarray(base.getchannel("A")) >= ALPHA_SOLID)
+ if not by.any():
+ raise SystemExit(f"{verb}: --region-mask holds no solid pixel of the cell it was drawn on: nothing of the region to "
+ "carry")
+ matched = int(by.sum())
+ carried = carry_region(_whole_premultiplied(base), cells, by, base_shift, lays, base_index)
+ worn = [one for _, one, _ in made]
+ if not any(one.any() for one in worn):
+ raise SystemExit(f"{verb}: --region-shrink {mask.shrink} wears the region mask away: no pixel of it is left to move")
+ rim = rim_bands(answer.gain * whole[0], answer.gain * whole[1], mask.rim)
+ masked = Masked(mask, worn, None if not mask.crease else [crease for _, _, crease in made],
+ (float(base_shift[0]), float(base_shift[1])), matched, carried, math.ceil(answer.reach) + REGION_AIR, rim, up)
+ answer = dataclasses.replace(answer, mask=masked)
+ ledger = region_ledger(answer)
+ if min(ledger["jacobian_min"]) <= 0:
+ k = int(np.argmin(ledger["jacobian_min"]))
+ raise SystemExit(f"{verb}: --region-mask's rim ({rim[0]} px across, {rim[1]} down) keeps a move of {answer.reach:.1f} px "
+ f"taking at most {RIM_SLOPE:g} of a pixel's area, and cell {k}'s move folds the picture all the same (a "
+ f"pixel takes {ledger['jacobian_min'][k]:g} of its area); this is the engine's fault — nothing was written")
+ return dataclasses.replace(answer, mask=dataclasses.replace(masked, ledger=ledger))
+
+
+def region_ledger(answer: Answer) -> dict[str, Any]:
+ """Per cell, what a region mask moved and held and how its move went (`--region-mask`), each count a list over the
+ cells with its largest beside it:
+ - `region_px`, `soft_px`, `air_px`, `held_px`: the region's pixels, its soft edge, the clear pixels it may move into and
+ the visible pixels held (`region_sets`); `held_changed_px`: held pixels the drawn cell does not keep byte for byte;
+ - `move_most`: the most a pixel of the region moves, and where (px, x, y; None where none moves), and `move_most_max`;
+ - `pressed_px`, `stretched_px`: pixels of the drawn cell, solid, moved and not held, left with under PRESSED or over
+ STRETCHED of their area, the box they lie in, and the least and the most area with where it is (`area_least`,
+ `area_most`), as `band_ledger` counts them; `folded_px`: those whose move takes 0 or less of the source's area
+ (`jacobian`: the picture folds), and `jacobian_min`, the least area any of them takes — every read takes its whole
+ move, so the move and the read are one field;
+ - `read_held_weight`: the most weight a read's four pixels put on held pixels, and where (weight, x, y; None where no
+ read takes one), and `read_held_half_px`: reads that put half or more on them;
+ - `renormalised_px`, `walked_px`: reads that took a held pixel and were read from the others, and those walked back
+ (`draw_held`), which the rim keeps at 0."""
+ assert answer.mask is not None
+ w, h = answer.cells[0].size
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
+ inner = np.zeros((h, w), bool)
+ inner[1:-1, 1:-1] = True
+ keys = ("region_px", "soft_px", "air_px", "held_px", "held_changed_px", "move_most", "pressed_px", "pressed_box",
+ "area_least", "stretched_px", "stretched_box", "area_most", "folded_px", "jacobian_min", "read_held_weight",
+ "read_held_half_px", "renormalised_px", "walked_px")
+ ledger: dict[str, list[Any]] = {key: [] for key in keys}
+ for k, cell in enumerate(answer.cells):
+ drawn, read = answer.masked_cell(k)
+ region, held, field = read["region"], read["held"], read["field"]
+ for key in ("region", "soft", "air", "held"):
+ ledger[f"{key}_px"].append(int(read[key].sum()))
+ source, out = np.asarray(cell.convert("RGBA")), np.asarray(drawn.convert("RGBA"))
+ ledger["held_changed_px"].append(int((held & np.any(source != out, axis=-1)).sum()))
+ ledger["renormalised_px"].append(int(read["renormalised"].sum()))
+ ledger["walked_px"].append(int(read["walked"].sum()))
+ if field is None:
+ for key, empty in (("move_most", None), ("pressed_px", 0), ("pressed_box", None), ("area_least", None),
+ ("stretched_px", 0), ("stretched_box", None), ("area_most", None), ("folded_px", 0),
+ ("jacobian_min", 1.0), ("read_held_weight", None), ("read_held_half_px", 0)):
+ ledger[key].append(empty)
+ continue
+ inside, move_x, move_y = field
+ size = np.hypot(move_x, move_y)
+ if region.any():
+ y, x = divmod(int(np.argmax(np.where(region, size, -1.0))), w)
+ ledger["move_most"].append([round(float(size[y, x]), 4), x, y])
+ else:
+ ledger["move_most"].append(None)
+ taken = np.ones((h, w))
+ taken[1:-1, 1:-1] = jacobian(move_x, move_y)
+ moved = inner & inside & ~held & (out[..., 3] >= ALPHA_SOLID)
+ counted = moved & (taken > 0)
+ area = 1 / np.where(taken > 0, taken, 1.0) # each pixel's area: 1 over the source's it takes
+ pressed, stretched = counted & (area < PRESSED), counted & (area > STRETCHED)
+ for key, where in (("pressed", pressed), ("stretched", stretched)):
+ ledger[f"{key}_px"].append(int(where.sum()))
+ ledger[f"{key}_box"].append(_box(where))
+ for key, pick, empty in (("area_least", np.argmin, np.inf), ("area_most", np.argmax, -np.inf)):
+ if counted.any():
+ y, x = divmod(int(pick(np.where(counted, area, empty))), w)
+ ledger[key].append([round(float(area[y, x]), 4), x, y])
+ else:
+ ledger[key].append(None)
+ ledger["folded_px"].append(int((moved & (taken <= 0)).sum()))
+ ledger["jacobian_min"].append(round(float(taken[moved].min()), 4) if moved.any() else 1.0)
+ # The weight a read puts on held pixels, as `_sample` reads them: the rim keeps it under a half.
+ on_held = np.where(read["readers"], _bilinear(held.astype(np.float64), xx - move_x, yy - move_y), 0.0)
+ if (on_held > 0).any():
+ y, x = divmod(int(np.argmax(on_held)), w)
+ ledger["read_held_weight"].append([round(float(on_held[y, x]), 4), x, y])
+ else:
+ ledger["read_held_weight"].append(None)
+ ledger["read_held_half_px"].append(int((on_held >= 0.5).sum()))
+ out: dict[str, Any] = {}
+ for key in keys:
+ out[key] = ledger[key]
+ if key.endswith("_px"):
+ out[f"{key}_max"] = max(ledger[key], default=0)
+ out["move_most_max"] = max((most[0] for most in ledger["move_most"] if most is not None), default=0.0)
+ return out
+
+
+def region_notes(record: dict[str, Any], verb: str = VERB, at: str = f"{loop_mod.SWAY_RECORD}.region_mask") -> list[str]:
+ """What to say of a region mask's record (`--region-mask`), a line each, as warnings: the cells it kept the carry of
+ the cell before in and why, the cells `--band-up` carried a region's ellipse by the lay in and why, and every count of
+ the ledger that is not 0 in some cell — in how many cells, up to how many pixels and in which cell, and where in the
+ record (`at`)."""
+ masked, notes = record["region_mask"], []
+ if masked["kept"]:
+ whys = "; ".join(f"cell {e['cell']}: {e['why']}" for e in masked["kept"])
+ notes.append(f"{verb}: warning: --region-mask keeps the carry of the cell before in {len(masked['kept'])} cells, its own "
+ f"pixels found surely neither round where that cell had them nor round the lay ({whys}) — {at}.kept")
+ by_region: dict[int, list[dict[str, Any]]] = {}
+ for entry in [] if masked["up"] is None else masked["up"]["lay"]:
+ by_region.setdefault(entry["region"], []).append(entry)
+ for i, entries in sorted(by_region.items()):
+ name = "--region " + ",".join(f"{v:g}" for v in record["regions"][i])
+ whys = "; ".join(f"cell {e['cell']}: {e['why']}" for e in entries)
+ notes.append(f"{verb}: warning: --band-up carries {name} by the body's lay in {len(entries)} cells, its own pixels not "
+ f"found surely ({whys}) — {at}.up.lay")
+ said = {"held_changed_px": "held pixels do not keep their bytes (the engine's fault)",
+ "pressed_px": f"moved pixels are left under {PRESSED:g} of their area",
+ "stretched_px": f"moved pixels are left over {STRETCHED:g} of their area",
+ "read_held_half_px": "reads put half their weight or more on held pixels",
+ "renormalised_px": "reads took a held pixel and were read from the others",
+ "walked_px": "reads took a held pixel and were walked back"}
+ return notes + _ledger_notes(masked["ledger"], said, "--region-mask", verb, at)
def _keep_floor(ask: Ask, radii: list[float], gains: list[float], held: list[bool],
@@ -2048,10 +2566,12 @@ def sway_loop(loop_dir: Path, regions: list[tuple[float, ...]], *, gain: float |
breathe: Path | None = None, lag: float | None = None, gain_across: float | None = None,
band: float | str | None = None, band_margin: float | str | None = None,
band_up: tuple[float, float | str] | str | None = None, hold_mask: Path | None = None,
- verb: str = VERB) -> dict[str, Any]:
+ region_mask: Path | None = None, region_rim: float | None = None, region_shrink: int | None = None,
+ region_crease: bool = False, verb: str = VERB) -> dict[str, Any]:
request = read_request(loop_dir, regions, gain=gain, freq=freq, zeta=zeta, on_fold=on_fold, read_on=read_on,
stretch_floor=stretch_floor, breathe=breathe, lag=lag, gain_across=gain_across, band=band,
- band_margin=band_margin, band_up=band_up, hold_mask=hold_mask, verb=verb)
+ band_margin=band_margin, band_up=band_up, hold_mask=hold_mask, region_mask=region_mask,
+ region_rim=region_rim, region_shrink=region_shrink, region_crease=region_crease, verb=verb)
loop_dir, name, meta_path, meta = request.loop_dir, request.name, request.meta_path, request.meta
strip_path = request.strip_path
source = request.source_path
@@ -2104,7 +2624,8 @@ def sway_frames(frames: Path, out: Path, regions: list[tuple[float, ...]], *, fp
stretch_floor: float | None = None, breathe: Path | None = None, lag: float | None = None,
gain_across: float | None = None, reference: Path | None = None, band: float | str | None = None,
band_margin: float | str | None = None, band_up: tuple[float, float | str] | str | None = None,
- hold_mask: Path | None = None, verb: str = VERB) -> dict[str, Any]:
+ hold_mask: Path | None = None, region_mask: Path | None = None, region_rim: float | None = None,
+ region_shrink: int | None = None, region_crease: bool = False, verb: str = VERB) -> dict[str, Any]:
"""The sway of a folder of a cycle's frames — a loop's `cycle/`, or what `sprite-gen breathe` wrote from it — at their
own size and count, past the strip's caps on cells and width: the same frames under the same names, the regions
(in frame pixels) moved, and `sway.json` beside them, written whole into a new folder (`frames.folder`); the frames
@@ -2117,7 +2638,8 @@ def sway_frames(frames: Path, out: Path, regions: list[tuple[float, ...]], *, fp
from there, as they are on the loop's own cells."""
ask = read_ask(regions, gain=gain, freq=freq, zeta=zeta, on_fold=on_fold, read_on=read_on, stretch_floor=stretch_floor,
breathe=breathe, lag=lag, gain_across=gain_across, band=band, band_margin=band_margin, band_up=band_up,
- hold_mask=hold_mask, verb=verb)
+ hold_mask=hold_mask, region_mask=region_mask, region_rim=region_rim, region_shrink=region_shrink,
+ region_crease=region_crease, verb=verb)
if ask.read_on is not None:
raise SystemExit(f"{verb}: --read-on names the strip as cut that the regions were read on; frames are read as they are")
if ask.breath is not None and fps is not None:
@@ -2231,7 +2753,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--band-up", type=parse_band_up, default=None, metavar=f"FLAT[,PX|{AUTO}]",
help="with --band: above the centre the flat part stops FLAT (over 0, at most 1) of the region's height over "
f"it and the weight falls over PX from there ({AUTO}, the default: the band, or to {HANG_PAST:g} px over the "
- "region's top where that is further): the upper part gives, the rest moves whole. Default: above as below")
+ "region's top where that is further): the upper part gives, the rest moves whole. Default: above as below. "
+ "With --region-mask: that upper yield, the band and margin auto, and the rim's weight the lesser")
parser.add_argument("--hold-mask", type=Path, default=None, metavar="MASK.png|DIR",
help="with --band: pixels the band moves round and leaves as they are (an arm hanging over the part, a dress "
"below it), a PNG drawn on the cell the regions were read on (alpha, or light where it has none, "
@@ -2239,6 +2762,27 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
f"{HOLD_GROW} px; or a folder of one PNG per cell in name order, held as given. The pixels not opaque round "
"it and the air beside it are kept too, and a read headed into them stops short, its share of the move "
f"rising by {HOLD_SLOPE:g} a px from them. Off by default")
+ parser.add_argument("--region-mask", type=Path, default=None, metavar="MASK.png|DIR",
+ help="the region as a mask instead of the ellipse's weight: a PNG drawn on the cell the regions were read on "
+ f"(alpha, or light where it has none, {ALPHA_SOLID} or more), carried into every cell by its own pixels "
+ "(round where the cell before had them, then round the lay; where neither settles, where the cell before "
+ "had them, named in the record and a warning), or a folder of one PNG per cell in name order. Every "
+ f"visible pixel outside it and its soft edge keeps its bytes; it moves into the air within the move's reach "
+ f"and {REGION_AIR} px; the weight falls to 0 toward the held pixels over a rim (sin², the fold rule's least "
+ f"band across and down widened until a move takes at most {RIM_SLOPE:g} of a pixel's area), and with "
+ "--band-up the lesser of that and its upper yield. The ellipses still say each region's gain. Off by "
+ "default. Not with --band, a region's flat share, --stretch-floor nor --hold-mask")
+ parser.add_argument("--region-rim", type=float, default=None, metavar="SCALE",
+ help=f"with --region-mask: the rim starts at SCALE (1 or more) times the fold rule's least band (default "
+ f"{RIM_DEFAULT:g}; 1.5 a wider, gentler rim, a smaller part moving whole)")
+ parser.add_argument("--region-shrink", type=int, default=None, metavar="PX",
+ help=f"with --region-mask: wear the mask in by PX px (4-neighbour steps) before it moves, so a mask drawn a "
+ f"little large holds what is outside the part (default {SHRINK_DEFAULT}; 0: as given)")
+ parser.add_argument("--region-crease", action="store_true",
+ help=f"with --region-mask: before it is worn in, end the mask at the crease under it — in each column whose "
+ f"lowest pixel lies on more of the figure, the darkest solid pixel {CREASE_UP} px above to {CREASE_DOWN} "
+ f"below it, the median over {2 * CREASE_SPAN + 1} columns; a column over the air is left as it is. Off by "
+ "default")
parser.add_argument("--board", type=Path, help="write a before/after picture at the frames where the part sits lowest and highest")
@@ -2278,7 +2822,9 @@ def run(**kwargs: object) -> int:
"on_fold": str(kwargs.get("on_fold") or "refuse"), "read_on": kwargs.get("read_on"),
"stretch_floor": kwargs.get("stretch_floor"), "breathe": kwargs.get("breathe"), "lag": kwargs.get("lag"),
"gain_across": kwargs.get("gain_across"), "band": kwargs.get("band"), "band_margin": kwargs.get("band_margin"),
- "band_up": kwargs.get("band_up"), "hold_mask": kwargs.get("hold_mask")}
+ "band_up": kwargs.get("band_up"), "hold_mask": kwargs.get("hold_mask"), "region_mask": kwargs.get("region_mask"),
+ "region_rim": kwargs.get("region_rim"), "region_shrink": kwargs.get("region_shrink"),
+ "region_crease": bool(kwargs.get("region_crease"))}
if kwargs.get("frames") is not None:
if kwargs.get("out") is None:
raise SystemExit(f"{verb}: --frames needs --out, a new folder for the swayed frames")
@@ -2300,6 +2846,9 @@ def run(**kwargs: object) -> int:
if "hold" in result:
for note in hold_notes(result, verb, f"{FRAMES_RECORD} hold" if where == "out" else f"{loop_mod.SWAY_RECORD}.hold"):
print(note, file=sys.stderr)
+ if "region_mask" in result:
+ for note in region_notes(result, verb, f"{FRAMES_RECORD} region_mask" if where == "out" else f"{loop_mod.SWAY_RECORD}.region_mask"):
+ print(note, file=sys.stderr)
print(json.dumps({k: result[k] for k in (where, "regions", "gain", "gain_requested", "on_fold", "body_bob_px", "reach_px")}
| ({"region_gains": [entry["gain"] for entry in fold["regions"]]} if own else {})
| ({"drive": result["drive"]["kind"]} if "drive" in result else {})
@@ -2310,6 +2859,11 @@ def run(**kwargs: object) -> int:
| ({"hold": {"pieces": len(result["hold"]["pieces"]),
"lay_cells": sorted({entry["cell"] for entry in result["hold"]["lay"]}),
"read_folded_px_max": result["hold"]["ledger"]["read_folded_px_max"]}} if "hold" in result else {})
+ | ({"region_mask": {"kept_cells": [entry["cell"] for entry in result["region_mask"]["kept"]],
+ "rim_px": [result["region_mask"]["rim"]["across_px"], result["region_mask"]["rim"]["down_px"]],
+ "move_most_px": result["region_mask"]["ledger"]["move_most_max"],
+ "walked_px_max": result["region_mask"]["ledger"]["walked_px_max"]}}
+ if "region_mask" in result else {})
| ({"board": result["board"]} if "board" in result else {}), ensure_ascii=False, indent=2))
return 0
diff --git a/tests/video/test_follow_inspect.py b/tests/video/test_follow_inspect.py
index 5fa2ae5..0effb4f 100644
--- a/tests/video/test_follow_inspect.py
+++ b/tests/video/test_follow_inspect.py
@@ -454,8 +454,10 @@ def test_the_command_takes_what_video_follow_takes(tmp_path, capsys):
add_arguments(parsers[1])
followed, inspected = vars(parsers[0].parse_args(asked)), vars(parsers[1].parse_args([*asked, '--out-dir', str(out)]))
# video-sway's own: its board, the frames path beside the loop directory, the band (`--band`), whose carry by the
- # region's own pixels the inspection does not read, and the pixels a band leaves as they are (`--hold-mask`)
- own = {'board', 'frames', 'out', 'fps', 'reference', 'band', 'band_margin', 'band_up', 'hold_mask'}
+ # region's own pixels the inspection does not read, the pixels a band leaves as they are (`--hold-mask`), and the
+ # region given as a mask (`--region-mask`)
+ own = {'board', 'frames', 'out', 'fps', 'reference', 'band', 'band_margin', 'band_up', 'hold_mask', 'region_mask',
+ 'region_rim', 'region_shrink', 'region_crease'}
assert set(inspected)-set(followed) == {'out_dir', 'scale', 'columns'} and set(followed)-set(inspected) == own
assert {key: inspected[key] for key in followed if key not in own} == {key: value for key, value in followed.items() if key not in own}
capsys.readouterr()
diff --git a/tests/video/test_sway_region.py b/tests/video/test_sway_region.py
new file mode 100644
index 0000000..389b89b
--- /dev/null
+++ b/tests/video/test_sway_region.py
@@ -0,0 +1,584 @@
+"""`video-sway --region-mask`: the region given as a mask, every visible pixel outside it held.
+
+A mask drawn on the cell the regions were read on is the region instead of the ellipse's weight. It is carried into every
+cell by its own pixels — round where the cell before had them first, round the lay second, and where neither settles it
+keeps the cell before's carry and says so — and there every visible pixel outside it and its soft edge keeps its bytes,
+at any gain, while it moves into the air beside it. Its weight falls to 0 toward the held pixels over a rim read off the
+move (sin² of the distance in an ellipse Lx across and Ly down, widened until the move takes at most RIM_SLOPE of a
+pixel's area), so the picture does not fold and no read leans half on a held pixel; `--band-up` yields above. A mask
+drawn a little large is worn in (`--region-shrink`), and its lower edge may be moved to the crease under it
+(`--region-crease`) before it is worn in. Synthetic figures only: a body whose striped part, round above and cut straight
+below, lies over its torso's right side and past it, over the air, soft against the air, a dark crease under it on the
+torso; the band test's part on cloth with no pattern; the read-on test's runner, cut and turned.
+
+Each case first reads what a sway writes with the mask (its cells, whether it refuses, what it says), so on a release
+without the mask the same input fails on what comes out; the record and the ledger are read after.
+"""
+import hashlib
+import io
+import json
+import math
+import shutil
+
+import numpy as np
+import pytest
+from PIL import Image
+from sprite_gen import cli
+from sprite_gen.video import sway
+
+from tests.video.test_follow_inspect import CHEST, HEAD, LEG, N, TORSO, W, H, covered, strip_dir, sway as body_sway
+from tests.video.test_follow_read_on import aligned, cells_of as cut_cells, chest as cut_chest, meta_of, origin, origin_once # noqa: F401 (fixtures)
+from tests.video.test_sway_band import ramp, slide, sliding, whole_move
+
+POLICY = 'own-pixels-mask/held-outside/rim-sin2/1'
+PART = (71.0, 76.0, 21.0, 22.0) # the part in cell 0: round above its centre, straight down its sides below
+BOTTOM = 92 # its last row in cell 0; under it on the torso (x 35 to 85), a dark crease
+STRIPES = [(230, 90, 120), (250, 170, 90), (200, 60, 150)]
+CREASE = (25, 15, 40)
+SOFT = 90 # the alpha of the soft edges against the air: the part's own, and the torso's right side
+GAINS = (2.5, 1.25, 6.0) # the default, its half, and more than twice it
+SEARCH = 9
+FILES = [f'frame-{k:03d}.png' for k in range(N)]
+
+
+def text(region):
+ return ','.join(f'{v:g}' for v in region)
+
+
+def still(k):
+ return 0, 0
+
+
+def out_of_part(xx, yy):
+ """How far out of the part a place is, as the part lies in cell 0: in its ellipse's radii above the centre, in its
+ width below it; 1 on its edge."""
+ dx, dy = (xx-PART[0])/PART[2], (yy-PART[1])/PART[3]
+ return np.where(dy < 0, np.hypot(dx, dy), np.abs(dx))
+
+
+def part_figure(k, n=N, slide=still, lift=still):
+ """A body: a head and a torso that sway as one (and `lift(k)` further), legs to the ground, the torso's right side soft
+ against the air. On it, a further `slide(k)` whole pixels from where the torso carries it, a part striped across both
+ ways, over the torso's right side and past it, soft where it meets the air; under it on the torso, a dark crease."""
+ sx, sy = body_sway(k, n)
+ lx, ly = lift(k)
+ sx, sy = sx+lx, sy+ly
+ ex, ey = slide(k)
+ yy, xx = np.mgrid[0:H, 0:W]
+ a = np.zeros((H, W, 4), np.uint8)
+ a[(xx >= 45+sx) & (xx <= 75+sx) & (yy >= 20+sy) & (yy <= 45+sy)] = HEAD
+ a[(xx >= 35+sx) & (xx <= 85+sx) & (yy >= 46+sy) & (yy <= 110+sy)] = TORSO
+ a[(xx == 86+sx) & (yy >= 46+sy) & (yy <= 110+sy)] = (*TORSO[:3], SOFT)
+ for x0 in (44, 70):
+ a[(xx >= x0+sx) & (xx <= x0+6+sx) & (yy >= 111+sy) & (yy <= 150)] = LEG
+ px, py = xx-sx-ex, yy-sy-ey # where each pixel lies on the part, as in cell 0
+ r = out_of_part(px, py)
+ part = (r <= 1) & (py <= BOTTOM)
+ stripes = np.array([(*c, 255) for c in STRIPES], np.uint8)
+ a[part] = stripes[((px+2*py)//3 % 3)[part]]
+ a[(py == BOTTOM+1) & (r <= 1) & (a[..., 3] == 255)] = (*CREASE, 255) # on the torso only
+ a[(r > 1) & (r <= 1.06) & (py <= BOTTOM) & (a[..., 3] == 0)] = (*STRIPES[0], SOFT)
+ return Image.fromarray(a, 'RGBA')
+
+
+def part_at(k, slide=still):
+ """The part's opaque pixels in cell k."""
+ sx, sy = body_sway(k)
+ ex, ey = slide(k)
+ yy, xx = np.mgrid[0:H, 0:W]
+ return (out_of_part(xx-sx-ex, yy-sy-ey) <= 1) & (yy-sy-ey <= BOTTOM)
+
+
+def ours(k, slide=still):
+ """The part's pixels in cell k: its opaque ones, and its soft edge against the air."""
+ sx, sy = body_sway(k)
+ ex, ey = slide(k)
+ yy, xx = np.mgrid[0:H, 0:W]
+ r = out_of_part(xx-sx-ex, yy-sy-ey)
+ return part_at(k, slide) | ((r > 1) & (r <= 1.06) & (yy-sy-ey <= BOTTOM) & (xx > 86+sx))
+
+
+def mask_png(path, mask):
+ """A region mask drawn on cell 0: opaque white over `mask`, clear elsewhere."""
+ Image.fromarray(np.where(mask[..., None], 255, 0).astype(np.uint8).repeat(4, axis=2), 'RGBA').save(path)
+ return path
+
+
+def answer_of(loop_dir, regions, **kw):
+ """What `video-sway` asked the same way comes to on the loop (`sway.solve`), with nothing written."""
+ request = sway.read_request(loop_dir, regions, **kw)
+ strip = request.source_path if request.source_path.exists() else request.strip_path
+ data = strip.read_bytes()
+ return sway.solve(request, Image.open(io.BytesIO(data)).convert('RGBA'), strip_name=strip.name,
+ strip_sha256=hashlib.sha256(data).hexdigest())
+
+
+def cells_of(loop_dir):
+ strip = np.asarray(Image.open(loop_dir/'walk.strip.png').convert('RGBA'))
+ return [np.ascontiguousarray(strip[:, k*W:(k+1)*W]) for k in range(strip.shape[1]//W)]
+
+
+def grow4(mask, px):
+ for _ in range(px):
+ p = np.pad(mask, 1)
+ mask = p[1:-1, 1:-1] | p[:-2, 1:-1] | p[2:, 1:-1] | p[1:-1, :-2] | p[1:-1, 2:]
+ return mask
+
+
+def shrink4(mask, px):
+ for _ in range(px):
+ p = np.pad(mask, 1)
+ mask = p[1:-1, 1:-1] & p[:-2, 1:-1] & p[2:, 1:-1] & p[1:-1, :-2] & p[1:-1, 2:]
+ return mask
+
+
+def chebyshev_within(mask, px):
+ """The pixels `px` 8-neighbour steps or fewer from `mask`."""
+ for _ in range(px):
+ p = np.pad(mask, 1)
+ mask = np.logical_or.reduce([p[dy:dy+H, dx:dx+W] for dy in range(3) for dx in range(3)])
+ return mask
+
+
+def distance_by_offsets(held, lx, ly):
+ """The distance to the nearest held pixel in rim units, Lx across and Ly down, 1 past it: every offset inside the
+ ellipse tried in turn, apart from the engine's rows-then-columns."""
+ d = np.ones(held.shape)
+ p = np.pad(held, ((ly, ly), (lx, lx)))
+ for oy in range(-ly, ly+1):
+ for ox in range(-lx, lx+1):
+ r = math.hypot(ox/lx, oy/ly)
+ if r < 1:
+ d = np.where(p[ly+oy:ly+oy+H, lx+ox:lx+ox+W] & (r < d), r, d)
+ return d
+
+
+def rim_for(dx, dy, scale=1.0):
+ """The rim the move asks: the fold rule's least band each way times `scale`, widened until the slope is 0.9 or less."""
+ least = [math.ceil((math.ceil(float(np.max(np.abs(v)))*math.pi/2)+1)*scale) for v in (dx, dy)]
+ lx, ly = least
+ while float(np.max(0.5*math.pi*np.hypot(dx/lx, dy/ly))) > 0.9:
+ lx, ly = lx+1, ly+1
+ return lx, ly, least
+
+
+def weights(answer, k):
+ """Per pixel of cell k, the share of the cell's offset it moves by, and what the mask moves and holds there."""
+ yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
+ field, sets = answer.mask_field(k, xx, yy)
+ offset = math.hypot(answer.dx[k], answer.dy[k])
+ return (np.hypot(field[1], field[2])/offset if offset else np.zeros((H, W))), sets
+
+
+def held_kept(cells, source, slid=still, lift=still):
+ """Every visible pixel outside the part and its soft edge keeps its bytes in every cell."""
+ for k in range(N):
+ outside = (source[k][..., 3] > 0) & ~np.roll(ours(k, slid), lift(k)[1], axis=0)
+ assert np.array_equal(cells[k][outside], source[k][outside]), k
+
+
+# ---------------------------------------------------------------- off, nothing of it
+
+def test_without_a_region_mask_the_sway_is_as_ever(tmp_path):
+ for name, kw, args in (('plain', {}, []), ('band', {'band': 'auto'}, ['--band', 'auto'])):
+ by_cli, by_api = strip_dir(tmp_path/f'{name}-cli', part_figure), strip_dir(tmp_path/f'{name}-api', part_figure)
+ assert cli.main(['video-sway', '--loop-dir', str(by_cli), '--region', text(PART), *args]) == 0
+ sway.sway_loop(by_api, [PART], region_mask=None, region_rim=None, region_shrink=None, region_crease=False, **kw)
+ assert (by_cli/'walk.strip.png').read_bytes() == (by_api/'walk.strip.png').read_bytes(), name
+ record = json.loads((by_cli/'walk.strip.json').read_text())['follow']
+ assert 'region_mask' not in record and all(entry['radius_px'] is not None for entry in record['fold']['regions'])
+
+
+# ---------------------------------------------------------------- what is held, what moves
+
+def test_every_visible_pixel_outside_the_part_keeps_its_bytes_at_any_gain(tmp_path):
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ source = cells_of(strip_dir(tmp_path/'source', part_figure))
+ for gain in GAINS:
+ plain_dir, masked_dir = strip_dir(tmp_path/f'plain-{gain}', part_figure), strip_dir(tmp_path/f'masked-{gain}', part_figure)
+ sway.sway_loop(plain_dir, [PART], gain=gain, on_fold='lower')
+ record = sway.sway_loop(masked_dir, [PART], gain=gain, on_fold='lower', region_mask=mask)
+ plain, masked = cells_of(plain_dir), cells_of(masked_dir)
+ held_kept(masked, source)
+ plain_outside = moved = 0
+ for k in range(N):
+ outside = (source[k][..., 3] > 0) & ~ours(k)
+ plain_outside += int(np.any(plain[k][outside] != source[k][outside], axis=-1).sum())
+ moved += int(np.any(masked[k] != source[k], axis=-1).sum())
+ assert plain_outside > 0 and moved > 0, gain # the ellipse's weight moves the crease under the part; the mask does not
+ ledger = record['region_mask']['ledger']
+ assert ledger['held_changed_px_max'] == 0 and min(ledger['held_px']) > 0 and record['gain'] == gain
+
+
+def test_inside_its_rim_the_part_moves_whole_and_it_moves_into_the_air_and_no_further(tmp_path):
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ loop_dir = strip_dir(tmp_path/'loop', part_figure)
+ record = sway.sway_loop(loop_dir, [PART], region_mask=mask, region_shrink=0)
+ source, moved = cells_of(strip_dir(tmp_path/'source', part_figure)), cells_of(loop_dir)
+ answer = answer_of(strip_dir(tmp_path/'again', part_figure), [PART], region_mask=mask, region_shrink=0)
+ lx, ly = record['region_mask']['rim']['across_px'], record['region_mask']['rim']['down_px']
+ air = math.ceil(answer.reach) + 2
+ into_air = whole = 0
+ for k in range(N):
+ clear = source[k][..., 3] == 0
+ # Past the move's reach and 2 px of the part, the air stays as it was; nearer, the part moves into it.
+ far = clear & ~chebyshev_within(part_at(k), air)
+ assert np.array_equal(moved[k][far], source[k][far]), k
+ into_air += int((clear & (moved[k][..., 3] > 0)).sum())
+ # Where no held pixel lies within the rim and two px more, a pixel of the part is the cell moved by the cell's
+ # offset itself.
+ _, sets = weights(answer, k)
+ core = part_at(k) & (distance_by_offsets(sets['held'], lx+2, ly+2) >= 1)
+ assert np.array_equal(moved[k][core], whole_move(answer.cells[k], answer.dx[k], answer.dy[k])[core]), k
+ whole += int(core.sum()) if math.hypot(answer.dx[k], answer.dy[k]) > 0 else 0
+ assert into_air > 0 and whole > 0
+ assert record['region_mask']['air_px'] == air and record['region_mask']['soft_px'] == 2
+
+
+def test_the_parts_soft_edge_moves_with_it_and_a_soft_pixel_beside_the_torso_is_held(tmp_path):
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ loop_dir = strip_dir(tmp_path/'loop', part_figure)
+ sway.sway_loop(loop_dir, [PART], region_mask=mask, region_shrink=0)
+ source, moved = cells_of(strip_dir(tmp_path/'source', part_figure)), cells_of(loop_dir)
+ near = edge_moved = 0
+ for k in range(N):
+ solid, part = source[k][..., 3] >= 128, part_at(k)
+ # The torso's soft side is held where a solid pixel of the torso lies beside it, however near the part.
+ beside = (source[k][..., 3] == SOFT) & ~part & grow4(solid & ~part, 1)
+ assert beside.any() and np.array_equal(moved[k][beside], source[k][beside]), k
+ near += int((beside & grow4(part, 2)).sum())
+ edge = (source[k][..., 3] == SOFT) & ours(k) & ~part
+ edge_moved += int(np.any(moved[k][edge] != source[k][edge], axis=-1).sum())
+ assert near > 0 and edge_moved > 0
+
+
+# ---------------------------------------------------------------- carried by its own pixels
+
+def test_the_mask_is_carried_round_where_the_cell_before_had_it_first_and_the_record_says_so(tmp_path):
+ for name, slid in (('slide', slide), ('ramp', ramp)): # the ramp lies 12 px from the lay, past the search
+ figure = lambda k, n=N, s=slid: part_figure(k, n, slide=s)
+ mask = mask_png(tmp_path/f'{name}.png', part_at(0, slid))
+ loop_dir = strip_dir(tmp_path/name, figure)
+ sway.sway_loop(loop_dir, [PART], region_mask=mask)
+ held_kept(cells_of(loop_dir), cells_of(strip_dir(tmp_path/f'{name}-source', figure)), slid)
+ masked = json.loads((loop_dir/'walk.strip.json').read_text())['follow']['region_mask']
+ assert masked['kept'] == [] and masked['carry']['search_px'] == SEARCH
+ cells = masked['carry']['cells']
+ assert cells[0] == {'px': [0.0, 0.0], 'from': 'base'}
+ for k in range(1, N):
+ (sx, sy), (ex, ey) = body_sway(k), slid(k)
+ entry = cells[k]
+ assert entry['from'] == 'pixels' and abs(entry['px'][0]-(sx+ex)) < 0.1 and abs(entry['px'][1]-(sy+ey)) < 0.1, (name, k)
+ assert entry['curvature'][0] > 0 and entry['curvature'][1] > 0, (name, k)
+ if abs(ey) >= 10: # past the search from the lay
+ assert entry['guess'] == 'before', (name, k)
+
+
+def test_a_part_whose_body_jumps_past_the_search_is_found_round_the_lay(tmp_path):
+ lift = lambda k: (0, 12) if k == 5 else (0, 0)
+ figure = lambda k, n=N: part_figure(k, n, lift=lift)
+ loop_dir = strip_dir(tmp_path/'loop', figure)
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ sway.sway_loop(loop_dir, [PART], gain=1.0, region_mask=mask)
+ held_kept(cells_of(loop_dir), cells_of(strip_dir(tmp_path/'source', figure)), lift=lift)
+ masked = json.loads((loop_dir/'walk.strip.json').read_text())['follow']['region_mask']
+ assert masked['kept'] == []
+ for k in (5, 6): # 12 px from where the cell before had it: found round its own lay
+ sx, sy = body_sway(k)
+ entry = masked['carry']['cells'][k]
+ assert entry['from'] == 'pixels' and entry['guess'] == 'lay', (k, entry)
+ assert abs(entry['px'][0]-sx) < 0.1 and abs(entry['px'][1]-(sy+lift(k)[1])) < 0.1, (k, entry)
+
+
+def test_where_neither_guess_settles_the_carry_of_the_cell_before_is_kept_never_the_lay(tmp_path, capsys):
+ figure = sliding(lambda k: (0, 0), part=TORSO) # cloth with no pattern
+ loop_dir = strip_dir(tmp_path/'loop', figure)
+ patch = (60.0, 72.0, 14.0, 12.0)
+ mask = mask_png(tmp_path/'mask.png', covered(patch) & (np.asarray(figure(0))[..., 3] >= 128))
+ as_cut = cells_of(loop_dir)
+ assert cli.main(['video-sway', '--loop-dir', str(loop_dir), '--region', text(CHEST), '--region-mask', str(mask)]) == 0
+ out = capsys.readouterr()
+ moved = cells_of(loop_dir)
+ for k in range(N): # the mask stays where cell 0 had it, and nothing past it changes
+ assert np.array_equal(moved[k][~covered(patch)], as_cut[k][~covered(patch)]), k
+ masked = json.loads((loop_dir/'walk.strip.json').read_text())['follow']['region_mask']
+ cells, kept = masked['carry']['cells'], masked['kept']
+ assert [entry['cell'] for entry in kept] == list(range(1, N))
+ for k in range(1, N):
+ assert cells[k]['from'] == 'before' and cells[k]['px'] == [0.0, 0.0] and 'guess' not in cells[k], k
+ before = f"round where cell {k-1} had it: the least is on the search's edge, {SEARCH} px from where cell {k-1} had it"
+ assert cells[k]['why'].startswith(before) and kept[k-1] == {'cell': k, 'why': cells[k]['why']}, k
+ whys = '; '.join(f"cell {e['cell']}: {e['why']}" for e in kept)
+ assert (f"--region-mask keeps the carry of the cell before in {N-1} cells, its own pixels found surely neither round where "
+ f"that cell had them nor round the lay ({whys}) — follow.region_mask.kept") in out.err
+ assert json.loads(out.out)['region_mask']['kept_cells'] == list(range(1, N))
+
+
+# ---------------------------------------------------------------- the rim
+
[email protected]('gain', [2.5, 6.0])
+def test_the_rim_is_read_off_the_move_and_the_weight_is_sin2_of_the_distance_to_the_held_pixels(tmp_path, gain):
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ loop_dir = strip_dir(tmp_path/'loop', part_figure)
+ record = sway.sway_loop(loop_dir, [PART], gain=gain, region_mask=mask)
+ held_kept(cells_of(loop_dir), cells_of(strip_dir(tmp_path/'source', part_figure)))
+ answer = answer_of(strip_dir(tmp_path/'again', part_figure), [PART], gain=gain, region_mask=mask)
+ lx, ly, least = rim_for(answer.dx, answer.dy)
+ rim = record['region_mask']['rim']
+ assert (rim['across_px'], rim['down_px'], rim['least_px']) == (lx, ly, least) and rim['slope'] <= 0.9 == rim['slope_bound']
+ assert record['fold']['regions'] == [{'radius_px': None, 'ratio': 0.0, 'gain_limit': None}] and not record['fold']['lowered']
+ yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
+ for k in range(0, N, 3):
+ (inside, move_x, move_y), sets = answer.mask_field(k, xx, yy)
+ moving = sets['region'] | sets['soft'] | sets['air']
+ weight = np.where(moving, np.sin(0.5*math.pi*distance_by_offsets(sets['held'], lx, ly))**2, 0.0)
+ assert np.allclose(move_x, answer.dx[k]*weight, rtol=0, atol=1e-9) and np.allclose(move_y, answer.dy[k]*weight, rtol=0, atol=1e-9), k
+ assert not inside[sets['held']].any()
+ ledger = record['region_mask']['ledger']
+ assert ledger['folded_px_max'] == 0 and min(ledger['jacobian_min']) > 0
+ assert ledger['walked_px_max'] == 0 and ledger['read_held_half_px_max'] == 0
+ assert max(spot[0] for spot in ledger['read_held_weight'] if spot is not None) < 0.5
+ assert ledger['renormalised_px_max'] > 0 # reads that touch a held pixel are read from the others
+
+
+def test_a_wider_rim_moves_less_of_the_part_whole(tmp_path):
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ narrow_dir, wide_dir = strip_dir(tmp_path/'narrow', part_figure), strip_dir(tmp_path/'wide', part_figure)
+ narrow = sway.sway_loop(narrow_dir, [PART], region_mask=mask)
+ wide = sway.sway_loop(wide_dir, [PART], region_mask=mask, region_rim=1.5)
+ held_kept(cells_of(wide_dir), cells_of(strip_dir(tmp_path/'source', part_figure)))
+ assert any(not np.array_equal(a, b) for a, b in zip(cells_of(narrow_dir), cells_of(wide_dir)))
+ narrow_answer = answer_of(strip_dir(tmp_path/'a', part_figure), [PART], region_mask=mask)
+ wide_answer = answer_of(strip_dir(tmp_path/'b', part_figure), [PART], region_mask=mask, region_rim=1.5)
+ lx, ly, least = rim_for(wide_answer.dx, wide_answer.dy, 1.5)
+ rim, was = wide['region_mask']['rim'], narrow['region_mask']['rim']
+ assert (rim['across_px'], rim['down_px'], rim['least_px']) == (lx, ly, least) and wide['region_mask']['asked']['rim'] == 1.5
+ assert rim['across_px'] >= was['across_px'] and rim['down_px'] >= was['down_px'] and rim != was
+ whole_narrow = whole_wide = 0
+ for k in range(N):
+ a, sets = weights(narrow_answer, k)
+ b, _ = weights(wide_answer, k)
+ assert np.all(b <= a + 1e-12), k # nearer the held pixels in rim units, everywhere
+ whole_narrow += int((sets['region'] & (a >= 1 - 1e-12)).sum())
+ whole_wide += int((sets['region'] & (b >= 1 - 1e-12)).sum())
+ assert whole_wide < whole_narrow
+
+
+def test_band_up_yields_above_the_centre(tmp_path):
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ loop_dir = strip_dir(tmp_path/'up', part_figure)
+ record = sway.sway_loop(loop_dir, [PART], on_fold='lower', region_mask=mask, band_up=(0.2, 'auto'))
+ held_kept(cells_of(loop_dir), cells_of(strip_dir(tmp_path/'source', part_figure)))
+ answer = answer_of(strip_dir(tmp_path/'again', part_figure), [PART], on_fold='lower', region_mask=mask, band_up=(0.2, 'auto'))
+ up = answer.mask.up
+ lx, ly = record['region_mask']['rim']['across_px'], record['region_mask']['rim']['down_px']
+ yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
+ binds = 0
+ for k in range(N):
+ (_, move_x, move_y), sets = answer.mask_field(k, xx, yy)
+ carried = up.carried[k][0]['px']
+ yielded = sway.band_weight(xx, yy, (PART[0]+carried[0], PART[1]+carried[1]), *up.shapes[0])
+ rim = np.where(sets['region'] | sets['soft'] | sets['air'],
+ np.sin(0.5*math.pi*distance_by_offsets(sets['held'], lx, ly))**2, 0.0)
+ weight = np.minimum(rim, yielded) # the lesser of the rim and the upper yield
+ assert np.allclose(move_x, answer.dx[k]*weight, rtol=0, atol=1e-9) and np.allclose(move_y, answer.dy[k]*weight, rtol=0, atol=1e-9), k
+ binds += int((sets['region'] & (yielded < rim - 1e-9)).sum())
+ assert not (sets['region'] & (yielded < rim - 1e-9) & (yy > PART[1]+carried[1])).any(), k # below the centre the rim's
+ assert binds > 0
+ masked = record['region_mask']
+ assert masked['asked']['up'] == {'flat': 0.2, 'band': 'auto'}
+ band, margin = math.ceil(answer.reach_requested*math.pi/2)+1, math.ceil(answer.reach_requested)+1
+ assert (masked['up']['band_px'], masked['up']['margin_px']) == (band, margin) and len(masked['up']['carry']['cells']) == N
+ assert masked['up']['regions'][0]['flat_px'] == [PART[2]+margin, round(0.2*PART[3], 4), PART[3]+margin]
+ assert masked['up']['regions'][0]['band_px'] == [band, round(max(band, 0.8*PART[3]+3), 4), band]
+
+
+# ---------------------------------------------------------------- the mask as given: worn in, its crease
+
+def test_a_mask_drawn_2_px_large_holds_the_belly_once_it_is_worn_in(tmp_path):
+ big = grow4(part_at(0), 2) & (np.asarray(part_figure(0))[..., 3] >= 128) # past the part into the crease and the torso
+ mask = mask_png(tmp_path/'big.png', big)
+ source = cells_of(strip_dir(tmp_path/'source', part_figure))
+ worn_dir, given_dir = strip_dir(tmp_path/'worn', part_figure), strip_dir(tmp_path/'given', part_figure)
+ record = sway.sway_loop(worn_dir, [PART], region_mask=mask)
+ sway.sway_loop(given_dir, [PART], region_mask=mask, region_shrink=0)
+ worn, given = cells_of(worn_dir), cells_of(given_dir)
+ yy = np.mgrid[0:H, 0:W][0]
+ belly_given = 0
+ for k in range(N):
+ belly = (source[k][..., 3] > 0) & ~ours(k) & (yy > BOTTOM + body_sway(k)[1]) # the crease and the torso under it
+ assert np.array_equal(worn[k][belly], source[k][belly]), k
+ belly_given += int(np.any(given[k][belly] != source[k][belly], axis=-1).sum())
+ assert belly_given > 0 # as given, the mask moves the belly's top rows
+ masked = record['region_mask']
+ assert masked['asked']['shrink_px'] == 2 and masked['mask']['carried_by_px'] == int(big.sum())
+ assert masked['mask']['px'] == int(shrink4(big, 2).sum())
+
+
+def test_the_crease_ends_the_mask_on_the_darkest_row_under_it_before_it_is_worn_in(tmp_path):
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ source = cells_of(strip_dir(tmp_path/'source', part_figure))
+ creased_dir, plain_dir = strip_dir(tmp_path/'creased', part_figure), strip_dir(tmp_path/'plain', part_figure)
+ record = sway.sway_loop(creased_dir, [PART], region_mask=mask, region_shrink=0, region_crease=True)
+ sway.sway_loop(plain_dir, [PART], region_mask=mask, region_shrink=0)
+ creased, plain = cells_of(creased_dir), cells_of(plain_dir)
+ yy = np.mgrid[0:H, 0:W][0]
+ crease_moved = 0
+ for k in range(N):
+ crease = np.all(source[k][..., :3] == CREASE, axis=-1) & (source[k][..., 3] == 255)
+ below = (source[k][..., 3] >= 128) & ~ours(k) & ~crease & (yy > BOTTOM + body_sway(k)[1])
+ assert crease.any() and np.array_equal(plain[k][crease], source[k][crease]), k # without it the crease is held
+ for cells in (creased, plain):
+ assert np.array_equal(cells[k][below], source[k][below]), k
+ crease_moved += int(np.any(creased[k][crease] != source[k][crease], axis=-1).sum())
+ assert crease_moved > 0 # with it the crease is the region's last row, and moves with it
+ part0 = part_at(0)
+ over_torso = [x for x in range(W) if part0[:, x].any() and x <= 85]
+ over_air = [x for x in range(W) if part0[:, x].any() and x > 85]
+ assert record['region_mask']['crease'] == [{'rows': {str(x): BOTTOM+1 for x in over_torso}, 'free_columns': len(over_air)}]
+ worn = sway.sway_loop(strip_dir(tmp_path/'worn', part_figure), [PART], region_mask=mask, region_crease=True)
+ assert worn['region_mask']['mask']['box'][3] == BOTTOM + 1 - 2 # the crease, then worn in by 2
+ assert worn['region_mask']['mask']['carried_by_px'] == int(part0.sum()) + len(over_torso)
+
+
+# ---------------------------------------------------------------- the same region on every path
+
+def test_a_folder_of_the_masks_carried_moves_as_the_one_mask(tmp_path):
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ one_dir, folder_dir = strip_dir(tmp_path/'one', part_figure), strip_dir(tmp_path/'folder', part_figure)
+ one = sway.sway_loop(one_dir, [PART], region_mask=mask)
+ held_kept(cells_of(one_dir), cells_of(strip_dir(tmp_path/'source', part_figure)))
+ answer = answer_of(strip_dir(tmp_path/'again', part_figure), [PART], region_mask=mask)
+ masks = tmp_path/'masks'
+ masks.mkdir()
+ for k in range(N):
+ region = answer.mask.region_in(k, np.asarray(answer.cells[k])[..., 3] >= 128)
+ Image.fromarray(np.where(region, 255, 0).astype(np.uint8), 'L').save(masks/f'cell-{k:03d}.png')
+ given = sway.sway_loop(folder_dir, [PART], region_mask=masks, region_shrink=0)
+ assert (one_dir/'walk.strip.png').read_bytes() == (folder_dir/'walk.strip.png').read_bytes()
+ masked = given['region_mask']
+ assert masked['asked']['per_cell'] and len(masked['asked']['sha256']) == N
+ assert masked['carry'] is None and masked['mask'] is None and masked['kept'] == []
+ assert masked['ledger'] == one['region_mask']['ledger'] and masked['rim'] == one['region_mask']['rim']
+
+
+def test_the_frames_are_moved_as_the_strip(tmp_path):
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ frames = tmp_path/'frames'
+ frames.mkdir()
+ for k, name in enumerate(FILES):
+ part_figure(k).save(frames/name)
+ loop_dir = strip_dir(tmp_path/'loop', part_figure, delay_ms=41.67) # a frame at --fps 24, as a strip's meta writes it
+ assert cli.main(['video-sway', '--frames', str(frames), '--out', str(tmp_path/'out'), '--fps', '24', '--region', text(PART),
+ '--region-mask', str(mask)]) == 0
+ strip_record = sway.sway_loop(loop_dir, [PART], region_mask=mask)
+ strip = cells_of(loop_dir)
+ out = [np.asarray(Image.open(tmp_path/'out'/name).convert('RGBA')) for name in FILES]
+ held_kept(out, [np.asarray(part_figure(k)) for k in range(N)])
+ assert all(np.array_equal(out[k], strip[k]) for k in range(N))
+ assert json.loads((tmp_path/'out'/'sway.json').read_text())['region_mask'] == strip_record['region_mask']
+
+
+def test_a_turned_loop_moved_on_the_cuts_reading_is_the_cuts_cell_for_cell(origin, tmp_path):
+ # The mask is drawn on the cut's first cell, where the regions were read; the turned loop carries it from there.
+ o, read_on, _ = origin
+ cell0 = cut_cells(o)[0]
+ cx, cy, rx, ry = cut_chest(o)
+ yy, xx = np.mgrid[0:cell0.shape[0], 0:cell0.shape[1]]
+ mask = tmp_path/'mask.png'
+ Image.fromarray(np.where((np.hypot((xx-cx)/rx, (yy-cy)/ry) < 1) & (cell0[..., 3] >= 128), 255, 0).astype(np.uint8), 'L').save(mask)
+ sway.sway_loop(shutil.copytree(o, tmp_path/'plain'), [cut_chest(o)], on_fold='lower')
+ masked = sway.sway_loop(shutil.copytree(o, tmp_path/'masked'), [cut_chest(o)], on_fold='lower', region_mask=mask)
+ loop_dir = aligned(o, tmp_path/'turned')
+ turned = meta_of(loop_dir)['cycle_align']['turned_by']
+ result = sway.sway_loop(loop_dir, [cut_chest(o)], on_fold='lower', read_on=read_on, region_mask=mask)
+ moved, reference, ellipse = cut_cells(loop_dir), cut_cells(tmp_path/'masked'), cut_cells(tmp_path/'plain')
+ n = len(reference)
+ assert sum(not np.array_equal(reference[k], ellipse[k]) for k in range(n)) > n//2 # the mask moves the part otherwise
+ assert all(np.array_equal(moved[k], reference[(k+turned) % n]) for k in range(n))
+ assert result['read_on']['relation'] == 'transported'
+ cut_carry, turned_carry = masked['region_mask']['carry']['cells'], result['region_mask']['carry']['cells']
+ assert [entry['px'] for entry in turned_carry] == [cut_carry[(k+turned) % n]['px'] for k in range(n)]
+
+
+# ---------------------------------------------------------------- refused, and said
+
+def test_what_a_region_mask_is_refused_for_leaves_the_loop_as_it_was(tmp_path):
+ loop_dir = strip_dir(tmp_path/'loop', part_figure)
+ as_cut = (loop_dir/'walk.strip.png').read_bytes()
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ small = tmp_path/'small.png'
+ Image.new('RGBA', (W-1, H), (255, 255, 255, 255)).save(small)
+ empty = tmp_path/'empty.png'
+ Image.new('RGBA', (W, H)).save(empty)
+ dot = np.zeros((H, W), bool)
+ dot[70:73, 70:73] = True
+ tiny = mask_png(tmp_path/'tiny.png', dot)
+ air = np.zeros((H, W), bool)
+ air[2:6, 2:6] = True
+ clear = mask_png(tmp_path/'clear.png', air)
+ few = tmp_path/'few'
+ few.mkdir()
+ for k in range(3):
+ Image.new('L', (W, H), 255).save(few/f'{k}.png')
+ for region, args, said in (
+ (text(PART), ['--region-mask', str(mask), '--band', 'auto'],
+ r"--region-mask moves the region's own pixels and holds every visible pixel round it, the weight falling over a rim "
+ r"inside it; --band moves an ellipse over a band outside it: give one of them$"),
+ (text(PART), ['--region-mask', str(mask), '--band-margin', '2'], r'--band-margin shapes a band; with --region-mask the rim is read off'),
+ (f'{text(PART)},0.5', ['--region-mask', str(mask)], r"--region-mask gives the region as a mask, and a region's fifth number \(flat, 0.5"),
+ (text(PART), ['--region-mask', str(mask), '--stretch-floor', '0.5'], r"--stretch-floor reads the weight that falls from a region's centre; with --region-mask"),
+ (text(PART), ['--region-mask', str(mask), '--hold-mask', str(mask)], r'--region-mask holds every visible pixel outside the region already'),
+ (text(PART), ['--region-mask', str(mask), '--region-rim', '0.5'], r"--region-rim is how many times the fold rule's least band the rim starts at, 1 or more; got 0.5$"),
+ (text(PART), ['--region-mask', str(mask), '--region-shrink', '-1'], r'--region-shrink is the px the mask is worn in by, a whole number, 0 or more; got -1$'),
+ (text(PART), ['--region-rim', '1.5'], r'--region-rim, --region-shrink and --region-crease shape a region mask; they need --region-mask$'),
+ (text(PART), ['--region-crease'], r'they need --region-mask$'),
+ (text(PART), ['--region-mask', str(small)], rf'--region-mask is {W-1}x{H}, the cells are {W}x{H}: a mask is drawn on a cell'),
+ (text(PART), ['--region-mask', str(empty)], r'holds no pixel \(alpha 128 or more'),
+ (text(PART), ['--region-mask', str(few)], rf'--region-mask holds 3 masks and there are {N} cells: a folder gives one mask per cell'),
+ (text(PART), ['--region-mask', str(tiny)], r'--region-shrink 2 wears the region mask away: no pixel of it is left to move$'),
+ (text(PART), ['--region-mask', str(clear)], r'--region-mask holds no solid pixel of the cell it was drawn on')):
+ with pytest.raises(SystemExit, match=said) as refused:
+ cli.main(['video-sway', '--loop-dir', str(loop_dir), '--region', region, *args])
+ assert refused.value.code not in (0, None), args
+ assert (loop_dir/'walk.strip.png').read_bytes() == as_cut and 'follow' not in json.loads((loop_dir/'walk.strip.json').read_text())
+
+
+# ---------------------------------------------------------------- the ledger
+
+def test_the_ledger_counts_each_cell_and_a_warning_says_what_is_in_it(tmp_path, capsys):
+ mask = mask_png(tmp_path/'mask.png', part_at(0))
+ loop_dir = strip_dir(tmp_path/'loop', part_figure)
+ assert cli.main(['video-sway', '--loop-dir', str(loop_dir), '--region', text(PART), '--region-mask', str(mask)]) == 0
+ out = capsys.readouterr()
+ held_kept(cells_of(loop_dir), cells_of(strip_dir(tmp_path/'source', part_figure)))
+ record = json.loads((loop_dir/'walk.strip.json').read_text())['follow']
+ masked = record['region_mask']
+ assert masked['policy'] == POLICY and record['carry_basis'] == {'reading': 'outline-lay', 'region': 'own-pixels'}
+ assert masked['asked'] == {'per_cell': False, 'sha256': hashlib.sha256(mask.read_bytes()).hexdigest(), 'rim': 1.0,
+ 'shrink_px': 2, 'crease': False, 'up': None}
+ assert masked['mask']['px'] == int(shrink4(part_at(0), 2).sum()) and masked['crease'] is None and masked['up'] is None
+ ledger = masked['ledger']
+ for key in ('region_px', 'soft_px', 'air_px', 'held_px', 'held_changed_px', 'pressed_px', 'stretched_px', 'folded_px',
+ 'read_held_half_px', 'renormalised_px', 'walked_px'):
+ assert len(ledger[key]) == N and ledger[f'{key}_max'] == max(ledger[key]), key
+ for key in ('move_most', 'pressed_box', 'area_least', 'stretched_box', 'area_most', 'jacobian_min', 'read_held_weight'):
+ assert len(ledger[key]) == N, key
+ answer = answer_of(strip_dir(tmp_path/'again', part_figure), [PART], region_mask=mask)
+ for k in range(N): # the most a pixel of the part moves, and where
+ offset = math.hypot(answer.dx[k], answer.dy[k])
+ most = ledger['move_most'][k]
+ assert (most is None) == (offset == 0), k
+ if most is not None:
+ share, sets = weights(answer, k)
+ assert abs(most[0] - offset*float(share[sets['region']].max())) < 1e-4 and sets['region'][most[2], most[1]], k
+ assert ledger['move_most_max'] == max(m[0] for m in ledger['move_most'] if m)
+ for key, what in (('pressed_px', 'moved pixels are left under 0.85 of their area'),
+ ('renormalised_px', 'reads took a held pixel and were read from the others'),
+ ('walked_px', 'reads took a held pixel and were walked back'),
+ ('held_changed_px', 'held pixels do not keep their bytes')):
+ assert (f'--region-mask: {what}' in out.err) == (ledger[f'{key}_max'] > 0), key
+ assert (f'follow.region_mask.ledger.{key}' in out.err) == (ledger[f'{key}_max'] > 0), key
+ summary = json.loads(out.out)['region_mask']
+ assert summary == {'kept_cells': [], 'rim_px': [masked['rim']['across_px'], masked['rim']['down_px']],
+ 'move_most_px': ledger['move_most_max'], 'walked_px_max': 0}