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(breathe): a stretch of a loop carries on the loop's breath — `loop_cells`/`start_cell` in the smooth sidecar, `sprite-gen breathe --loop-cells N --start-cell K --reference FRAME`; video-sway --breathe folds a stretch on its whole loop and `--frames --reference` carries the regions from the loop's first cell

Soohong Kimb85fc4aa5909
diff --git a/sprite_gen/curate/curation.py b/sprite_gen/curate/curation.py
index e2c9f98..b184be5 100644
--- a/sprite_gen/curate/curation.py
+++ b/sprite_gen/curate/curation.py
@@ -249,6 +249,10 @@ BREATHE_SMOOTH_SHAPE_RANGES = {"chest_y": (0.05, 0.95), "chest_rx": (0.2, 3.0),
"chest_bias_y": (-0.9, 0.9), "chest_flat": (0.0, 0.9), "inhale": (0.2, 0.8)}
# 꼭대기는 타원 안쪽이어야 한다 — 테두리에 닿으면 그쪽으로 무게가 줄어들 거리가 없다.
BREATHE_SMOOTH_PEAK_REACH = 0.9
+# 루프의 한 토막 (smooth): 줄이 `loop_cells` 칸 루프의 숨을 `start_cell` 칸째부터 이어 받는다 — 루프 세트의 들어감·나옴
+# 조각이 idle 의 숨을 위상 그대로 잇는다. 칸 i 의 위상은 루프 칸 (start_cell + i) mod loop_cells 의 위상이고 숨 박자
+# (breaths·breath_peaks)는 그 루프의 것이다. 생략은 줄이 곧 루프다 (start_cell 0, loop_cells 는 줄의 칸 수).
+BREATHE_STRETCH_KEYS = ("start_cell", "loop_cells")
RETIRED_BREATHE_KEYS = {
"splits": "분할선은 봉투 경계로 대체됐다 — 경계는 자동 검출되고 `rigid_row` 로만 덮어쓴다",
@@ -288,8 +292,9 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]
`mode` 를 적은 사이드카만 반환에 `mode` 가 실린다 — 안 적은 사이드카(지금까지의 전부)는
정규화 결과도 굽기도 이전과 바이트 같다. smooth 는 `lag` 가 없고(진행파는 첫 칸을 움직인다),
`depth` 생략은 `BREATHE_SMOOTH_DEPTH`, `depth_x` 생략은 `BREATHE_SMOOTH_DEPTH_X` 이며, 모양 값
- (`BREATHE_SMOOTH_SHAPE` 의 키, 들숨 몫 `inhale` 포함)이 기본값과 함께 실린다. 모양 값은 smooth 만 쓴다 — pixel
- 줄에 있으면 조용히 무시하지 않고 거부한다."""
+ (`BREATHE_SMOOTH_SHAPE` 의 키, 들숨 몫 `inhale` 포함)이 기본값과 함께 실린다. 루프의 한 토막(`start_cell`,
+ `loop_cells` — `BREATHE_STRETCH_KEYS`)도 smooth 에 늘 실린다 (생략이면 0 과 None, 줄이 곧 루프). 모양 값과 토막은
+ smooth 만 쓴다 — pixel 줄에 있으면 조용히 무시하지 않고 거부한다."""
if not curation:
return None
entry = curation.get("states", {}).get(state)
@@ -310,7 +315,7 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]
f"curation: states.{state}.breathe.mode = {mode!r} 를 모른다 — "
f"{' | '.join(BREATHE_MODES)} 중 하나다 (생략하면 pixel). 조용히 pixel 로 굽지 않는다.")
smooth = mode == "smooth"
- stray = sorted(k for k in (*BREATHE_SMOOTH_SHAPE, "breath_peaks") if k in raw)
+ stray = sorted(k for k in (*BREATHE_SMOOTH_SHAPE, "breath_peaks", *BREATHE_STRETCH_KEYS) if k in raw)
if stray and not smooth:
raise SystemExit(
f"curation: states.{state}.breathe 의 {', '.join(stray)} 는 smooth 의 모양 값이다 — "
@@ -381,6 +386,18 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]
raise SystemExit(
f"curation: states.{state}.breathe.breaths = {breaths} 인데 breath_peaks 는 {len(peaks)}개다 — "
f"숨 횟수는 꼭대기 수다. breaths 를 지우거나 맞춰라.")
+ # 루프의 한 토막 — 칸 수는 정수다. loop_cells 생략이면 줄의 칸 수라 start_cell 의 끝은 굽기가 본다.
+ start_cell = _exact_int("start_cell", raw.get("start_cell", 0), state)
+ loop_cells = raw.get("loop_cells")
+ if loop_cells is not None:
+ loop_cells = _exact_int("loop_cells", loop_cells, state)
+ if loop_cells is not None and loop_cells < 2:
+ raise SystemExit(f"curation: states.{state}.breathe.loop_cells = {loop_cells} — 숨이 놓일 루프는 두 칸 이상이다.")
+ if start_cell < 0 or (loop_cells is not None and start_cell >= loop_cells):
+ bound = "0 이상" if loop_cells is None else f"0 이상, 루프 칸 수 loop_cells {loop_cells} 미만"
+ raise SystemExit(
+ f"curation: states.{state}.breathe.start_cell = {start_cell} — 줄이 루프의 몇째 칸에서 시작하나다: {bound}"
+ f"이어야 한다. 조용히 접지 않는다.")
shape = {}
for name, default in BREATHE_SMOOTH_SHAPE.items():
given = raw.get(name, default)
@@ -401,7 +418,8 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]
f"{BREATHE_SMOOTH_PEAK_REACH:g} 안이어야 한다).")
return {"mode": mode, "depth": depth,
"depth_x": BREATHE_SMOOTH_DEPTH_X if depth_x is None else depth_x,
- "breaths": breaths, "breath_peaks": peaks, **shape, "rigid_row": rigid_row, "axis_x": axis_x,
+ "breaths": breaths, "breath_peaks": peaks, **shape, "start_cell": start_cell, "loop_cells": loop_cells,
+ "rigid_row": rigid_row, "axis_x": axis_x,
"torso_half": torso_half, "anatomy": frozen if isinstance(frozen, dict) else None}
cfg = {"depth": depth, "depth_x": depth_x, "breaths": breaths, "lag": lag,
"rigid_row": rigid_row, "axis_x": axis_x, "torso_half": torso_half,
diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.py
index 639a52a..b3f2dd9 100644
--- a/sprite_gen/effects/breathe.py
+++ b/sprite_gen/effects/breathe.py
@@ -61,6 +61,10 @@ AI 개입 0 — 같은 입력이면 항상 같은 출력.
바이트 같다. 가슴 무게가 몸통 안에서 0 으로 떨어져 화면 변에 닿은 그림도 밖으로 밀리지 않는다.
줄 전체가 기준 칸(첫 칸)에서 잰 해부와 그 자리를 쓴다 — 영상 루프의 머리 윗선이 칸마다 흔들려도
경계는 움직이지 않는다.
+
+루프 세트의 들어감·나옴 조각은 루프의 숨을 그 루프의 한 칸에서 잇는 토막이다 (`loop_cells`·`start_cell`): 칸 i 의
+위상은 루프 칸 (start_cell + i) mod loop_cells 의 위상이다. 토막의 첫 칸은 루프의 첫 칸이 아니라서 `sprite-gen breathe
+--reference` 로 루프의 첫 칸을 기준 칸으로 주면 해부와 그 자리가 루프의 것과 같다.
"""
from __future__ import annotations
@@ -76,7 +80,7 @@ from sprite_gen.effects.anatomy import Anatomy, analyze
from sprite_gen.curate.curation import (BREATHE_MODES, BREATHE_SMOOTH_DEPTH, BREATHE_SMOOTH_DEPTH_X,
BREATHE_SMOOTH_SHAPE, normalize_transform, state_breathe)
from sprite_gen.frames.extract import BORDER_MIN_FRACTION, FRAME_SIDES, own_border, solid_alpha_bbox
-from sprite_gen.frames.folder import cycle_frame_ms, open_frames, publish
+from sprite_gen.frames.folder import cycle_frame_ms, open_frames, publish, reference_frame
# 강체 경계에서 변형 강도가 0 이 되기까지의 테이퍼 반폭 (콘텐츠 높이 비율).
# 이 테이퍼가 이음매를 없앤다 — 경계에서 강도가 계단이 아니라 경사로 떨어진다.
@@ -890,13 +894,32 @@ def fit_breathe_pattern(seq_len: int, cfg: dict) -> list[float]:
**정수 나머지를 먼저 취한다.** `(i*breaths/seq_len) % 1.0` 로 쓰면 수학적으로 같은
위상이 서로 다른 double 이 되어(18슬롯 3호흡: 유니크 6 -> 14) 아틀라스 칸 재사용이
표현 노이즈로 깨진다. 분자를 정수로 접고 한 번만 나누면 반복 위상이 비트 동일하다
- (validator 검증 2026-07-25: 시트 1344x192 -> 576x192)."""
+ (validator 검증 2026-07-25: 시트 1344x192 -> 576x192).
+
+ 줄이 루프의 한 토막이면 (smooth `start_cell`·`loop_cells` — 루프 세트의 들어감·나옴 조각) 칸 i 의 위상은 그 루프
+ (`breathe_loop`)의 칸 (start_cell + i) mod loop_cells 의 위상, 같은 double 이다. 그래서 토막은 루프의 숨을 그 칸에서
+ 위상 그대로 잇는다. 둘 다 생략이면 줄이 곧 루프다."""
if seq_len <= 0:
return []
+ loop = breathe_loop(seq_len, cfg)
+ start = int(cfg.get("start_cell") or 0)
+ if start >= len(loop):
+ raise SystemExit(f"breathe: start_cell {start} 가 {len(loop)}칸 루프 밖이다 — 줄이 루프의 몇째 칸에서 시작하나다 "
+ f"(0 부터 {len(loop) - 1} 까지). 루프가 이 칸들보다 길면 loop_cells 로 그 칸 수를 주라.")
+ if start == 0 and len(loop) == seq_len:
+ return loop
+ return [loop[(start + i) % len(loop)] for i in range(seq_len)]
+
+
+def breathe_loop(seq_len: int, cfg: dict) -> list[float]:
+ """줄의 숨이 놓인 루프 한 바퀴의 위상 — `loop_cells` 칸(생략이면 줄의 `seq_len` 칸)에 숨 박자(`breaths` 회, 또는
+ `breath_peaks` 칸의 꼭대기)를 놓은 것. 줄이 곧 루프면 줄의 위상(`fit_breathe_pattern`)과 같고, 루프의 한 토막이면
+ 토막의 위상이 이 안에서 읽힌다. Sway 의 접힘 규칙이 토막을 루프의 숨 전체로 재는 것도 이것이다."""
+ n = int(cfg.get("loop_cells") or seq_len)
if cfg.get("breath_peaks"):
- return _peaked_phases(seq_len, list(cfg["breath_peaks"]), smooth_inhale(cfg))
+ return _peaked_phases(n, list(cfg["breath_peaks"]), smooth_inhale(cfg))
breaths = max(1, int(cfg.get("breaths", 1)))
- return [((i * breaths) % seq_len) / seq_len for i in range(seq_len)]
+ return [((i * breaths) % n) / n for i in range(n)]
def _peaked_phases(seq_len: int, peaks: list[int], inhale: float) -> list[float]:
@@ -1037,6 +1060,17 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--lag", type=float, default=None, help=f"pixel only: travelling-wave lag (default {DEFAULT_LAG})")
parser.add_argument("--rigid-row", type=int, default=None,
help="the row the head starts below, counted from the top of the figure (default: measured)")
+ parser.add_argument("--reference", default=None, metavar="FRAME.png",
+ help="the frame the row's anatomy is measured on, when it is not the first of these frames — a loop "
+ "set's first cell, for a way in or out of the loop that starts elsewhere: the head line, the chest and "
+ "its rise are the loop's (one size with the frames; default the first frame)")
+ stretch = parser.add_argument_group("a stretch of a loop (smooth; default the frames are the loop)")
+ stretch.add_argument("--loop-cells", type=int, default=None, metavar="N",
+ help="the frames carry on the breath of an N-cell loop — a way in or out of a loop set: the beat "
+ "(--breaths, --breath-peaks) is that loop's")
+ stretch.add_argument("--start-cell", type=int, default=None, metavar="K",
+ help="the loop's cell the frames start at, 0 to N - 1 (default 0): frame i breathes as the loop's "
+ "cell (K + i) mod N, the very phase")
shape = parser.add_argument_group("smooth shape (defaults in parentheses)")
shape.add_argument("--chest-y", type=float, default=None,
help=f"chest centre height, a share of the body below the neck ({SMOOTH_SHAPE['chest_y']})")
@@ -1095,29 +1129,37 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =
chest_x: float | None = None, chest_bias_y: float | None = None, chest_flat: float | None = None,
inhale: float | None = None, breath_peaks: list[int] | None = None,
avoid_region: tuple[float, float, float, float] | None = None,
- avoid_anchor: tuple[float, float, float, float] | None = None, fps: float | None = None) -> int:
+ avoid_anchor: tuple[float, float, float, float] | None = None, fps: float | None = None,
+ reference: str | None = None, loop_cells: int | None = None, start_cell: int | None = None) -> int:
"""프레임 폴더에 Breathe 레이어를 굽는다 — 큐레이션 사이드카 `breathe` 와 같은 값, 같은 정규화,
같은 굽기(`bake_breathe_sequence`). 영상 루프의 칸처럼 큐레이션 런이 아닌 프레임이 이 길로 온다.
- `avoid_region` 이면 숨 박자를 칸에서 고른다(`breath_beat`) — 고른 박자도 사이드카와 같은 검사를 다시 지난다."""
+ `avoid_region` 이면 숨 박자를 칸에서 고른다(`breath_beat`) — 고른 박자도 사이드카와 같은 검사를 다시 지난다.
+ `loop_cells`·`start_cell` 이면 칸들이 그 루프의 숨을 그 칸에서 잇는 토막이고(`fit_breathe_pattern`), `reference` 면
+ 해부를 첫 칸 대신 그 칸에서 잰다 — 루프 세트의 첫 칸에서 재면 토막의 머리선·가슴·오르는 양이 루프의 것과 같다."""
src_dir, out_dir = Path(frames), Path(out)
raw = {k: v for k, v in (("mode", mode), ("depth", depth), ("depth_x", depth_x), ("breaths", breaths),
("lag", lag), ("rigid_row", rigid_row), ("chest_y", chest_y), ("chest_rx", chest_rx),
("chest_ry", chest_ry), ("shoulder", shoulder), ("shoulder_lag", shoulder_lag),
("chest_tilt", chest_tilt), ("chest_bias", chest_bias), ("chest_dir", chest_dir),
("chest_x", chest_x), ("chest_bias_y", chest_bias_y), ("chest_flat", chest_flat),
- ("inhale", inhale), ("breath_peaks", breath_peaks))
+ ("inhale", inhale), ("breath_peaks", breath_peaks), ("loop_cells", loop_cells),
+ ("start_cell", start_cell))
if v is not None}
if avoid_region is None and (avoid_anchor is not None or fps is not None):
raise SystemExit("breathe: --avoid-anchor 와 --fps 는 --avoid-region 의 것이다 — 손 상자 없이는 읽지 않는다")
if avoid_region is not None and (breaths is not None or breath_peaks is not None):
raise SystemExit("breathe: --avoid-region 은 숨 박자를 칸에서 고른다 — --breaths·--breath-peaks 와 같이 주지 마라")
+ if avoid_region is not None and (loop_cells is not None or start_cell is not None):
+ raise SystemExit("breathe: --avoid-region 은 숨 박자를 이 칸들에서 고른다 — 루프의 한 토막(--loop-cells·--start-cell)은 "
+ "그 루프의 박자를 잇는다. 박자는 루프의 칸에서 골라 그 값을 주라")
cfg = _cli_breathe(raw)
if avoid_region is not None and breathe_mode(cfg) != "smooth":
raise SystemExit("breathe: --avoid-region 은 smooth 의 것이다 (--mode smooth) — pixel 숨은 진행파라 첫 칸이 쉼이 아니다")
folder = open_frames(src_dir, out_dir, "breathe") # 무엇을 만들거나 지우기 전에 — 실경로와 폴더 동일성으로 본다
images = folder.images
- anat = resolve_anatomy(images[0], cfg) # 보고와 굽기가 같은 한 벌 — 큰 칸은 재는 데 0.5 초다
+ basis, held = reference_frame(reference, folder, "breathe")
+ anat = resolve_anatomy(basis, cfg) # 보고와 굽기가 같은 한 벌 — 큰 칸은 재는 데 0.5 초다
beat = None
if avoid_region is not None:
from sprite_gen.effects import breath_beat # 박자 고르기가 이 모듈을 읽는다 — 돌아 들어오지 않게 여기서
@@ -1132,7 +1174,8 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =
baked, phases = bake_breathe_sequence(images, cfg, anat)
# 다 굽고 나서 한 번에 내놓는다 — 굽기가 중간에 거부되면 반쯤 찬 폴더를 남기지 않는다(frames.folder.publish).
publish(folder, baked, "breathe.json", {"frames": len(images), "source": str(src_dir), "config": cfg,
- "phases": phases, "resolved": resolved} | ({} if beat is None else {"beat": beat}))
+ "phases": phases, "resolved": resolved} | ({} if beat is None else {"beat": beat})
+ | ({} if held is None else {"reference": held}))
print(f"breathe: {len(images)} frames, {breathe_mode(cfg)}, depth {cfg['depth']}, "
f"breaths {cfg['breaths']} -> {out_dir}")
return 0
diff --git a/sprite_gen/frames/folder.py b/sprite_gen/frames/folder.py
index ef4faa2..ccf45c3 100644
--- a/sprite_gen/frames/folder.py
+++ b/sprite_gen/frames/folder.py
@@ -14,6 +14,7 @@ A frame's time is what a loop's strip meta writes (`delay_ms`), in ms rounded to
from __future__ import annotations
+import hashlib
import json
import shutil
from dataclasses import dataclass
@@ -70,6 +71,25 @@ def open_frames(frames: Path, out: Path, verb: str) -> Frames:
return Frames(paths, images, out_real)
+def reference_frame(path: Path | str | None, frames: Frames, verb: str) -> tuple[Image.Image, dict[str, Any] | None]:
+ """The frame the frames are read against (`--reference`) and its record (path and sha256 of its file): `path`, a loop
+ set's first cell for a stretch of the loop that starts elsewhere, one size with the frames — or, without it, the first
+ frame and no record."""
+ if path is None:
+ return frames.images[0], None
+ path = Path(path).expanduser()
+ try:
+ data = path.read_bytes()
+ with Image.open(path) as opened:
+ image = opened.convert("RGBA")
+ except OSError as exc:
+ raise SystemExit(f"{verb}: --reference {path}: not read ({exc})") from exc
+ if image.size != frames.images[0].size:
+ raise SystemExit(f"{verb}: --reference {path} is {image.size[0]}x{image.size[1]} and the frames are "
+ f"{frames.images[0].size[0]}x{frames.images[0].size[1]}; it is a cell of the same loop set")
+ return image, {"path": str(path), "sha256": hashlib.sha256(data).hexdigest()}
+
+
def publish(frames: Frames, images: list[Image.Image], record_name: str, record: dict[str, Any]) -> None:
"""`images` under the frames' names and `record` (JSON) as `record_name`, written whole into `frames.out`.
diff --git a/sprite_gen/serve/curator/src/store.js b/sprite_gen/serve/curator/src/store.js
index 21a5c81..e2deb2e 100644
--- a/sprite_gen/serve/curator/src/store.js
+++ b/sprite_gen/serve/curator/src/store.js
@@ -40,6 +40,19 @@ function breatheRangeProblems(raw) {
&& (raw.breaths == null || Number(raw.breaths) === p.length);
if (!ok) bad.push(`breath_peaks=${JSON.stringify(p)}`);
}
+ // 루프의 한 토막(smooth): 루프 칸 수 loop_cells 는 2 이상 정수, start_cell 은 0 이상이고 그보다 작은 정수 — 파이썬
+ // state_breathe 미러 (curation.BREATHE_STRETCH_KEYS).
+ const intAt = (v) => isNumericScalar(v) && Number.isInteger(Number(v));
+ // null 은 생략과 같다(줄이 곧 루프) — 단 pixel 줄에서는 키가 있는 것만으로 굽기가 거부한다.
+ if (raw.loop_cells !== undefined && (raw.mode !== "smooth"
+ || (raw.loop_cells !== null && (!intAt(raw.loop_cells) || Number(raw.loop_cells) < 2)))) {
+ bad.push(`loop_cells=${JSON.stringify(raw.loop_cells)}`);
+ }
+ if (raw.start_cell !== undefined) {
+ const loop = intAt(raw.loop_cells) ? Number(raw.loop_cells) : Infinity;
+ const ok = raw.mode === "smooth" && intAt(raw.start_cell) && Number(raw.start_cell) >= 0 && Number(raw.start_cell) < loop;
+ if (!ok) bad.push(`start_cell=${JSON.stringify(raw.start_cell)}`);
+ }
for (const [key, lo, hi, dflt] of bounds) {
// 생략(undefined)은 기본값. 명시적 null 은 굽기가 `float(None)` 으로 거부하므로
// **키와 무관하게** 여기서도 문제로 본다 — `Number(null) = 0` 이라 하한이 0 인 `lag`
diff --git a/sprite_gen/video/sway.py b/sprite_gen/video/sway.py
index 79be21f..77e9867 100644
--- a/sprite_gen/video/sway.py
+++ b/sprite_gen/video/sway.py
@@ -79,6 +79,14 @@ breath (the time warp the Breathe layer's shoulders are late by), and lies the d
offset = gain × lift × (w − w late), against the way the chest rises. Where the breath rests the offset is 0 — the first
cell, and where the loop closes — and a cell whose every offset is 0 is the cell as it was, byte for byte.
+A loop set's way in or out of its loop carries on the loop's breath from a cell of it: its record says the loop's
+length and the cell it starts at (`sprite-gen breathe --loop-cells N --start-cell K`), and its cell i has the phase of
+the loop's cell (K + i) mod N. An offset is its phase's alone, so that cell is offset as the loop's cell is, from the
+stretch's first cell on — there is nothing to wind up. The fold rule and the floor read the loop's whole breath, every
+cell of it, so the stretch moves by the gain the loop moves by and the record's reach is the loop's. Its regions were
+read on the loop's first cell, which is not one of its frames: `--reference` names that cell, the body is read from it
+and the regions are carried from there, as on the loop's own cells.
+
A region's fifth number, flat, is the share of the way from its centre to its rim that moves in full — the Breathe
layer's chest weight (`breathe.flat_cos2`) — so a large part moves as one piece instead of pressed in at its middle;
the fold rule and the floor read it by the radius left (1 − flat of it). `--gain-across` moves across by a gain of its
@@ -592,28 +600,42 @@ class Breath:
heading: float # degrees from straight up the chest rises toward (its chest_dir)
inhale: float # share of one breath the in-breath takes (its inhale): the phase the chest peaks at
lag: float # of one breath
-
- def unit(self) -> tuple[np.ndarray, np.ndarray]:
- """Per cell, the part's offset from where the breath carries it at gain 1, across and down: the chest rises
- `lift` × w (breathe.smooth_wave, of the record's in-breath share), the part as far late by `lag` (the time warp
- the Breathe layer's shoulders are late by, breathe.smooth_shoulder_wave), and the part lies the difference
- behind, against the way the chest rises. 0 where the breath rests — its first cell, and where the loop closes."""
+ start_cell: int = 0 # the loop's cell the cells start at (its start_cell)
+ loop_cells: int | None = None # the cells of the loop they are a stretch of (its loop_cells); None: they are the loop
+ loop: list[float] | None = None # the loop's phases (breathe.breathe_loop); None: the cells' own
+
+ def unit(self, phases: list[float] | None = None) -> tuple[np.ndarray, np.ndarray]:
+ """Per cell (or per phase of `phases`), the part's offset from where the breath carries it at gain 1, across and
+ down: the chest rises `lift` × w (breathe.smooth_wave, of the record's in-breath share), the part as far late by
+ `lag` (the time warp the Breathe layer's shoulders are late by, breathe.smooth_shoulder_wave), and the part lies
+ the difference behind, against the way the chest rises. 0 where the breath rests — the loop's first cell, and
+ where it closes. A phase's offset is the phase's alone, so a stretch's cell is offset as the loop's cell of its
+ phase is, from its first cell on: nothing is wound up before it."""
wave, late = breathe_mod.smooth_wave, breathe_mod.smooth_shoulder_wave
- share = np.asarray([wave(p, self.inhale) - late(p, self.lag, self.inhale) for p in self.phases])
+ share = np.asarray([wave(p, self.inhale) - late(p, self.lag, self.inhale)
+ for p in (self.phases if phases is None else phases)])
heading = math.radians(self.heading)
return self.lift * share * -math.sin(heading) + 0.0, self.lift * share * math.cos(heading)
+ def whole(self) -> tuple[np.ndarray, np.ndarray]:
+ """The offset at gain 1 over the whole breath the cells are swayed on, per phase: the loop's every cell for a
+ stretch of a loop, so the fold rule and the floor read the stretch as they read its loop; else the cells'."""
+ return self.unit(self.loop)
+
def record(self) -> dict[str, Any]:
return {"kind": "breath", "breathe_sha256": self.sha256, "lag": self.lag, "lift_px": round(self.lift, 4),
- "heading_deg": self.heading, "inhale": self.inhale, **self.beat}
+ "heading_deg": self.heading, "inhale": self.inhale, **self.beat, "start_cell": self.start_cell,
+ "loop_cells": self.loop_cells}
def read_breath(path: Path, lag: float | None, *, verb: str = VERB) -> Breath:
"""The breath of a Breathe layer's record (breathe.json): a smooth breath, whose phases are the ones its config
gives after the sidecar's checks (`state_breathe`, `breathe.fit_breathe_pattern`), whose chest rises as the anatomy it
was baked with says, on the curve of its in-breath share (`inhale`; a record written before the key was there says
- the default by leaving it out, as the sidecar does). A record written by hand for a breath made elsewhere is read
- alike and must say the same — its in-breath share among it."""
+ the default by leaving it out, as the sidecar does). A record of a stretch of a loop says the loop's length and the
+ cell it starts at (`loop_cells`, `start_cell`; one written before the keys were there is the loop itself from its
+ first cell). A record written by hand for a breath made elsewhere is read alike and must say the same — its in-breath
+ share and its place in the loop among it."""
lag = LAG_DEFAULT if lag is None else float(lag)
if not 0 < lag < LAG_MAX: # a NaN is not
raise SystemExit(f"{verb}: --lag is the share of a breath the part is late by, above 0 and under 1/π ({LAG_MAX:.4f}): at "
@@ -647,8 +669,10 @@ def read_breath(path: Path, lag: float | None, *, verb: str = VERB) -> Breath:
except (KeyError, TypeError) as exc:
raise SystemExit(f"{verb}: --breathe {path}: its resolved.anatomy is not one sprite-gen breathe writes ({exc})") from exc
beat = {"breath_peaks": list(cfg["breath_peaks"])} if cfg.get("breath_peaks") else {"breaths": cfg["breaths"]}
+ loop = breathe_mod.breathe_loop(len(phases), cfg)
return Breath(path, hashlib.sha256(data).hexdigest(), [float(p) for p in phases], beat,
- breathe_mod.smooth_lift(anatomy, cfg), float(cfg["chest_dir"]), float(cfg["inhale"]), lag)
+ breathe_mod.smooth_lift(anatomy, cfg), float(cfg["chest_dir"]), float(cfg["inhale"]), lag,
+ cfg["start_cell"], cfg["loop_cells"], None if loop == phases else loop)
@dataclass(frozen=True, eq=False)
@@ -769,7 +793,7 @@ class Answer:
ask: Ask
cells: list[Image.Image]
- cols: np.ndarray # per cell, how far its body lies from cell 0's: across
+ cols: np.ndarray # per cell, how far its body lies from cell 0's (or the reference frame's): across
rows: np.ndarray # and down
height0: int
worn: list[int]
@@ -789,11 +813,13 @@ class Answer:
groups: list[tuple[list[tuple[float, ...]], tuple[np.ndarray, np.ndarray]]]
read_on: dict[str, Any] | None = None # how the strip the regions were read on stands to this one (`--read-on`)
stretch: dict[str, Any] | None = None # the floor asked, and what it did to each region (`--stretch-floor`)
+ reference: dict[str, Any] | None = None # the frame the regions were read on, when not cell 0 (`--reference`)
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
- from the cut, the cells' motion is already from the cut's cell 0, where the regions were read."""
- if self.read_on is not None and self.read_on["relation"] == "transported":
+ from the cut, the cells' motion is already from the cut's cell 0, where the regions were read; read from a
+ reference frame, it is already from that frame."""
+ if self.reference is not None or (self.read_on is not None and self.read_on["relation"] == "transported"):
return self.cols[k], self.rows[k]
return self.cols[k] - self.cols[0], self.rows[k] - self.rows[0]
@@ -812,10 +838,12 @@ class Answer:
else {"drive": ask.breath.record()})
across = ({} if ask.gain_across is None else
{"gain_across": round(self.gain * ask.across, 4), "gain_across_requested": ask.gain_across})
+ # Read from a reference frame, the body's bob spans that frame too (at 0): it is where the regions were read.
+ cols, rows = (self.cols, self.rows) if self.reference is None else (np.append(self.cols, 0.0), np.append(self.rows, 0.0))
return {
"regions": [list(r) for r in ask.regions], "gain": self.gain, **across, **drive,
"source": source, "body_px": self.height0, "body_worn_px": self.worn,
- "body_bob_px": [round(float(np.ptp(self.cols)), 2), round(float(np.ptp(self.rows)), 2)],
+ "body_bob_px": [round(float(np.ptp(cols)), 2), round(float(np.ptp(rows)), 2)],
"dx_px": np.round(self.dx, 2).tolist(), "dy_px": np.round(self.dy, 2).tolist(),
"reach_px": round(self.reach, 2),
"gain_requested": requested, "on_fold": ask.on_fold,
@@ -830,7 +858,8 @@ class Answer:
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 else {"carry_basis": dict(CARRY_BASIS)})
+ | ({} if self.read_on is None and self.stretch is None else {"carry_basis": dict(CARRY_BASIS)}) \
+ | ({} if self.reference is None else {"reference": self.reference})
def solve(request: Request, strip: Image.Image, *, strip_name: str, verb: str = VERB,
@@ -876,12 +905,25 @@ def _unit_move(ask: Ask, rows: np.ndarray, cols: np.ndarray, frame_ms: float | N
return ask.across * across, down
+def _whole_move(ask: Ask, move: tuple[np.ndarray, np.ndarray]) -> tuple[np.ndarray, np.ndarray]:
+ """The move at gain 1 the fold rule and the floor read: on the breath of a stretch of a loop (the record's
+ start_cell and loop_cells — a loop set's way in or out), the loop's whole breath (`Breath.whole`), so the stretch
+ moves by the gain its loop moves by and their seams do not jump; else the cells' own `move`."""
+ if ask.breath is None or ask.breath.loop is None:
+ return move
+ across, down = ask.breath.whole()
+ return ask.across * across, down
+
+
def solve_cells(ask: Ask, cells: list[Image.Image], frame_ms: float | None, *, verb: str = VERB,
- read_on: dict[str, Any] | None = None, read_body: Any = None) -> Answer:
+ read_on: dict[str, Any] | None = None, read_body: Any = None,
+ reference: tuple[Image.Image, dict[str, Any]] | None = None) -> Answer:
"""The answer to `ask` on a cycle's cells (RGBA pictures of one size, in order; `frame_ms` one frame's time, which
the damped mass alone reads): a loop's strip cut into its cells (`solve`), or a folder of the cycle's frames
(`sway_frames`) — one answer, whatever the cells came from. The body's motion is read on the cells (`body_motion`)
- unless `read_body` gives it (a reading carried from the cut, `--read-on`). Reads nothing else and writes nothing."""
+ unless `read_body` gives it (a reading carried from the cut, `--read-on`); with a `reference` (the frame the regions
+ were read on and its record, `--reference`) it is read from that frame, laid first. Reads nothing else and writes
+ nothing."""
regions, gain, on_fold = ask.regions, ask.gain, ask.on_fold
w, h = cells[0].size
for cx, cy, *_ in regions:
@@ -894,22 +936,28 @@ def solve_cells(ask: Ask, cells: list[Image.Image], frame_ms: float | None, *, v
rows, cols, height0, worn = read_body()
else:
try:
- rows, cols, height0, worn = body_motion(cells)
+ rows, cols, height0, worn = body_motion(cells if reference is None else [reference[0], *cells])
except ValueError as exc:
raise SystemExit(f"{verb}: {exc}") from exc
+ if reference is not None: # each cell from the reference, which is not swayed
+ rows, cols = rows[1:], cols[1:]
across, down = _unit_move(ask, rows, cols, frame_ms)
+ whole_across, whole_down = _whole_move(ask, (across, down))
def move(g: float) -> tuple[np.ndarray, np.ndarray]:
"""The offset per cell at gain g, across and down: g times the move at gain 1."""
return g * across, g * down
- dx, dy = move(gain)
- reach = float(np.max(np.hypot(dx, dy)))
+ def reach_at(g: float) -> float:
+ """The largest offset at gain g over the whole move the fold rule reads (`_whole_move`)."""
+ return float(np.max(np.hypot(g * whole_across, g * whole_down)))
+
+ reach = reach_at(gain)
radii = [region_radius(region) for region in regions]
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.
- reach_per_gain = float(np.max(np.hypot(across, down)))
+ reach_per_gain = float(np.max(np.hypot(whole_across, whole_down)))
gains, held = [requested] * len(regions), [False] * len(regions)
if fold_ratio(reach, smallest) >= 1:
if on_fold == "refuse":
@@ -932,18 +980,20 @@ def solve_cells(ask: Ask, cells: list[Image.Image], frame_ms: float | None, *, v
gains = [0.0 if hold else g for g, hold in zip(gains, held)]
stretch = None
if ask.stretch_floor is not None:
- gains, held, stretch = _keep_floor(ask, radii, gains, held, (across, down), verb)
+ gains, held, stretch = _keep_floor(ask, radii, gains, held, (whole_across, whole_down), verb)
# One move per gain: a region's offset is its gain times the answer at gain 1. The strip's `gain`
- # is the largest any region moves by, and `dx_px`/`dy_px` and `reach_px` are that gain's.
+ # is the largest any region moves by, and `dx_px`/`dy_px` and `reach_px` are that gain's (the reach,
+ # like the fold, over the whole move the fold rule reads).
moves = {g: move(g) for g, hold in zip(gains, held) if not hold}
- reaches = {g: float(np.max(np.hypot(*offset))) for g, offset in moves.items()}
+ reaches = {g: reach_at(g) for g in moves}
gain = max(moves)
dx, dy = moves[gain]
reach = reaches[gain]
ratios = [0.0 if hold else fold_ratio(reaches[g], radius) for radius, g, hold in zip(radii, gains, held)]
groups = [([r for r, rg, hold in zip(regions, gains, held) if rg == g and not hold], offset) for g, offset in moves.items()]
return Answer(ask, cells, cols, rows, height0, worn, requested, reach_requested, reach_per_gain, radii, gains, held,
- ratios, moves, reaches, gain, dx, dy, reach, groups, read_on, stretch)
+ ratios, moves, reaches, gain, dx, dy, reach, groups, read_on, stretch,
+ None if reference is None else reference[1])
def _keep_floor(ask: Ask, radii: list[float], gains: list[float], held: list[bool],
@@ -1033,13 +1083,17 @@ def sway_frames(frames: Path, out: Path, regions: list[tuple[float, ...]], *, fp
gain: float | None = None, freq: float | None = None, zeta: float | None = None,
board: Path | 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, verb: str = VERB) -> dict[str, Any]:
+ gain_across: float | None = None, reference: Path | None = None, 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
folder is read and not written. Cell for cell it is the strip's sway (`solve_cells`): a strip cut from these frames
at scale 1, none left out, its regions moved by its crop origin, at the frame time its meta writes (`frame_ms` of
- `--fps`), moves its cells as these are moved."""
+ `--fps`), moves its cells as these are moved.
+
+ With `reference` (a loop set's first cell, for a stretch of the loop whose regions were read on that cell) the
+ regions are read on it and not on the first frame: each frame's body is read from it and the regions carried
+ 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, verb=verb)
if ask.read_on is not None:
@@ -1055,7 +1109,8 @@ def sway_frames(frames: Path, out: Path, regions: list[tuple[float, ...]], *, fp
if frame_ms is None:
raise SystemExit(f"{verb}: --frames {frames}: the damped mass answers the body's motion in time — give --fps (a "
"video-loop cycle/ folder has its own in the loop's strip meta), or sway on the breath (--breathe)")
- answer = solve_cells(ask, cells, frame_ms, verb=verb)
+ basis, held = folder_mod.reference_frame(reference, folder, verb)
+ answer = solve_cells(ask, cells, frame_ms, verb=verb, reference=None if held is None else (basis, held))
moved = [answer.moved(k) for k in range(len(cells))]
record = {"frames": len(cells), "frame_ms": frame_ms, **answer.record(source=str(frames))}
folder_mod.publish(folder, moved, FRAMES_RECORD, record)
@@ -1109,8 +1164,9 @@ def add_request_arguments(parser: argparse.ArgumentParser, *, loop_dir: bool = T
help="sway on the breath: the record sprite-gen breathe writes beside the frames it breathed (smooth). The part "
"follows the chest's rise late by --lag instead of answering the body's motion as a damped mass: its offset is "
"gain x the chest's rise x (w - w late), w the breath of the record's in-breath share (its config's "
- "inhale), against the way the chest rises, 0 where the breath rests (the first cell). The record's phases "
- "must be the ones its config gives, one for each cell swayed")
+ "inhale), against the way the chest rises, 0 where the breath rests (the loop's first cell). The record's "
+ "phases must be the ones its config gives, one for each cell swayed; a stretch of a loop (its loop_cells, "
+ "start_cell) is folded as its whole loop is")
parser.add_argument("--lag", type=float, default=None,
help=f"on the breath: the share of a breath the part peaks after the chest, above 0 and under 1/π (default {LAG_DEFAULT:g})")
parser.add_argument("--read-on", type=parse_read_on, default=None, metavar="SHA256",
@@ -1136,6 +1192,10 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--fps", type=float, default=None,
help="with --frames: their rate, for the damped mass (a video-loop cycle/ folder has its own in the loop's strip "
"meta); a frame's time is rounded to hundredths of a ms, as a strip's meta writes it")
+ parser.add_argument("--reference", type=Path, default=None, metavar="FRAME.png",
+ help="with --frames: the frame the regions were read on, when it is not the first of them — a loop set's "
+ "first cell, for a way in or out of the loop (sprite-gen breathe --loop-cells --start-cell): each "
+ "frame's body is read from it and the regions carried from there (one size with the frames)")
add_request_arguments(parser, loop_dir=False)
parser.add_argument("--board", type=Path, help="write a before/after picture at the frames where the part sits lowest and highest")
@@ -1180,9 +1240,9 @@ def run(**kwargs: object) -> int:
if kwargs.get("out") is None:
raise SystemExit(f"{verb}: --frames needs --out, a new folder for the swayed frames")
result = sway_frames(Path(str(kwargs["frames"])), Path(str(kwargs["out"])), list(kwargs["region"]), # type: ignore[arg-type]
- fps=kwargs.get("fps"), verb=verb, **asked) # type: ignore[arg-type]
+ fps=kwargs.get("fps"), reference=kwargs.get("reference"), verb=verb, **asked) # type: ignore[arg-type]
else:
- for flag in ("out", "fps"):
+ for flag in ("out", "fps", "reference"):
if kwargs.get(flag) is not None:
raise SystemExit(f"{verb}: --{flag} goes with --frames; a loop directory is swayed where it is")
result = sway_loop(Path(str(kwargs["loop_dir"])), list(kwargs["region"]), verb=verb, **asked) # type: ignore[arg-type]
diff --git a/tests/effects/test_breathe_smooth.py b/tests/effects/test_breathe_smooth.py
index 4c13424..d11f662 100644
--- a/tests/effects/test_breathe_smooth.py
+++ b/tests/effects/test_breathe_smooth.py
@@ -575,6 +575,66 @@ def test_breath_peaks_split_the_breaths_at_the_rows_inhale_share() -> None:
assert [B.smooth_wave(phases[p], 0.42) for p in (10, 40, 52)] == pytest.approx([1.0, 1.0, 1.0])
+# ── 루프의 한 토막: 루프 세트의 들어감·나옴 조각이 루프의 숨을 그 칸에서 잇는다 ──────────
+
[email protected]("beat", [{"breaths": 2}, {"breath_peaks": [10, 34], "breaths": None}], ids=["breaths", "peaks"])
[email protected]("start,count", [(13, 17), (40, 20), (0, 48), (5, 48)],
+ ids=["inside", "past-the-close", "whole", "turned"])
+def test_a_stretch_breathes_each_cell_at_its_loop_cells_phase(beat, start, count) -> None:
+ """`loop_cells`·`start_cell` 이면 줄은 그 루프의 한 토막이다 — 칸 i 의 위상은 루프 칸 (start_cell + i) mod
+ loop_cells 의 위상, 같은 double 이다. 루프 끝을 넘으면 루프 처음(쉼)으로 돈다. 숨 박자는 루프의 것이다."""
+ loop = B.fit_breathe_pattern(48, _cfg(_smooth(**beat)))
+ cfg = _cfg(_smooth(**beat, loop_cells=48, start_cell=start))
+ assert cfg["loop_cells"] == 48 and cfg["start_cell"] == start
+ assert B.breathe_loop(count, cfg) == loop
+ assert B.fit_breathe_pattern(count, cfg) == [loop[(start + i) % 48] for i in range(count)]
+
+
[email protected]("start,count", [(31, 20), (0, 16), (8, 16), (40, 16), (0, 96)],
+ ids=["way-in", "way-out-0", "way-out-8", "way-out-40", "loop"])
+def test_a_stretch_has_the_phases_the_pad_laid_it_at(start, count) -> None:
+ """토막의 위상은 손 단계(pad)가 내던 위상과 같은 double 이다 — 조각을 48칸 숨 m 번인 48m 칸 열의 제 위상 칸에
+ 깔고(앞뒤는 기준 칸, 위상 0 이면 둘째 숨 첫 칸) 그 열에 숨을 넣어 조각 칸만 읽던 것. 48칸 숨 둘인 96칸 루프의 한
+ 토막으로 말하면 엔진이 같은 위상을 낸다."""
+ p = start or 48
+ m = -(-(p + count) // 48)
+ padded = B.fit_breathe_pattern(48 * m, _cfg(_smooth(breaths=m)))
+ stretch = B.fit_breathe_pattern(count, _cfg(_smooth(breaths=2, loop_cells=96, start_cell=start)))
+ assert stretch == padded[p:p + count]
+
+
+def test_a_row_without_the_stretch_is_its_own_loop() -> None:
+ """생략은 줄이 곧 루프다 — 정규화가 start_cell 0, loop_cells None 을 싣고 위상이 이전 식 그대로(같은 double)다.
+ start_cell 만 주면 제 루프를 그 칸부터 돈다."""
+ for raw in (_smooth(), _smooth(breath_peaks=[10, 34], breaths=None)):
+ cfg = _cfg(raw)
+ assert cfg["start_cell"] == 0 and cfg["loop_cells"] is None
+ cfg = _cfg(_smooth(breaths=3))
+ own = B.fit_breathe_pattern(30, cfg)
+ assert own == [((i * 3) % 30) / 30 for i in range(30)] == B.breathe_loop(30, cfg)
+ assert B.fit_breathe_pattern(30, _cfg(_smooth(breaths=3, start_cell=7))) == [own[(7 + i) % 30] for i in range(30)]
+
+
[email protected]("raw,why", [
+ (_smooth(loop_cells=24, start_cell=24), "start_cell"), (_smooth(start_cell=-1), "start_cell"),
+ (_smooth(start_cell=2.5), "start_cell"), (_smooth(loop_cells=1), "loop_cells"),
+ (_smooth(loop_cells="many"), "loop_cells"),
+ ({"depth": 0.06, "breaths": 2, "start_cell": 3}, "start_cell"), ({"depth": 0.06, "breaths": 2, "loop_cells": 48}, "loop_cells"),
+], ids=["past-the-loop", "negative", "not-int", "one-cell", "not-a-number", "start-on-pixel", "loop-on-pixel"])
+def test_a_stretch_that_cannot_be_kept_is_refused(raw, why) -> None:
+ with pytest.raises(SystemExit, match=why):
+ _cfg(raw)
+
+
+def test_a_start_past_the_rows_own_loop_is_refused_at_the_bake() -> None:
+ """loop_cells 를 생략하면 루프는 줄의 칸 수라 start_cell 의 끝은 굽기가 본다 — 조용히 접지 않는다. 루프의 꼭대기 칸도
+ 그 루프 안에 들어야 한다."""
+ with pytest.raises(SystemExit, match="start_cell"):
+ B.fit_breathe_pattern(30, _cfg(_smooth(start_cell=30)))
+ with pytest.raises(SystemExit, match="breath_peaks"):
+ B.fit_breathe_pattern(30, _cfg(_smooth(breath_peaks=[10, 40], breaths=None, loop_cells=41)))
+
+
@pytest.mark.parametrize("angle", [-30.0, 20.0])
def test_the_chest_moves_along_its_direction(angle) -> None:
"""가슴 가운데는 `chest_dir` 쪽으로 간다 — 0 이 바로 위, 음수가 왼쪽 위. 크기는 그대로
@@ -698,9 +758,11 @@ def _blinking(h: int = 120, count: int = 12) -> list[Image.Image]:
"--chest-bias", "-0.4", "--chest-dir", "-25", "--chest-x", "-0.1", "--chest-bias-y", "0.2",
"--chest-flat", "0.25", "--inhale", "0.42"]),
(_smooth(breath_peaks=[3, 9], breaths=None), ["--mode", "smooth", "--depth", "0.025", "--breath-peaks", "3,9"]),
+ (_smooth(loop_cells=30, start_cell=23),
+ ["--mode", "smooth", "--depth", "0.025", "--breaths", "2", "--loop-cells", "30", "--start-cell", "23"]),
({"depth": 0.06, "breaths": 2, "lag": 0.1},
["--depth", "0.06", "--breaths", "2", "--lag", "0.1"]),
-], ids=["smooth", "smooth-shape", "smooth-peaks", "pixel"])
+], ids=["smooth", "smooth-shape", "smooth-peaks", "smooth-stretch", "pixel"])
def test_the_cli_bakes_what_the_curation_bake_bakes(tmp_path, raw, flags) -> None:
from sprite_gen import cli
@@ -759,3 +821,47 @@ def test_the_cli_refuses_what_the_sidecar_refuses(tmp_path) -> None:
cli.main(["breathe", str(src), str(tmp_path / "c"), "--chest-y", "0.3"]) # pixel 에 모양 값
with pytest.raises(SystemExit):
cli.main(["breathe", str(src), str(src), "--mode", "smooth"]) # 원본 위에 덮어쓰지 않는다
+ with pytest.raises(SystemExit, match="start_cell"):
+ cli.main(["breathe", str(src), str(tmp_path / "d"), "--start-cell", "3"]) # pixel 에 토막
+
+
+def _raised(image: Image.Image, rows: int) -> Image.Image:
+ """그림을 `rows` 행 위로 올린 칸 — 화면 아래 변에 닿은 몸통은 맨 아래 행을 이어 붙여 그대로 닿는다 (고개를 든 칸처럼
+ 콘텐츠가 위로 길어진다)."""
+ a = np.asarray(image.convert("RGBA"))
+ return Image.fromarray(np.concatenate([a[rows:], np.repeat(a[-1:], rows, axis=0)]), "RGBA")
+
+
+def test_the_reference_is_the_frame_the_rows_anatomy_is_measured_on(tmp_path) -> None:
+ """`--reference` 면 해부를 첫 칸 대신 그 칸에서 잰다 — 루프 세트의 첫 칸에서 재면 첫 칸이 다른(고개를 든) 토막도
+ 머리선·가슴·오르는 양이 루프의 것이다. 굽기는 그 한 벌로 굽고, 기록에 그 칸의 경로와 sha256 이 남는다."""
+ from sprite_gen import cli
+
+ base = _bust()
+ frames = [_raised(base, 4), *[base] * 7]
+ src = tmp_path / "piece"
+ src.mkdir()
+ for i, im in enumerate(frames):
+ im.save(src / f"frame-{i:03d}.png")
+ base.save(tmp_path / "base.png")
+ flags = ["--mode", "smooth", "--depth", "0.025", "--breaths", "2", "--loop-cells", "24", "--start-cell", "9"]
+ assert cli.main(["breathe", str(src), str(tmp_path / "own"), *flags]) == 0
+ assert cli.main(["breathe", str(src), str(tmp_path / "out"), *flags, "--reference", str(tmp_path / "base.png")]) == 0
+ own = json.loads((tmp_path / "own" / "breathe.json").read_text(encoding="utf-8"))
+ report = json.loads((tmp_path / "out" / "breathe.json").read_text(encoding="utf-8"))
+ assert report["resolved"]["anatomy"] == analyze(base).as_dict() != own["resolved"]["anatomy"]
+ assert own["resolved"]["anatomy"]["height"] == report["resolved"]["anatomy"]["height"] + 4 and "reference" not in own
+ assert report["reference"] == {"path": str(tmp_path / "base.png"),
+ "sha256": hashlib.sha256((tmp_path / "base.png").read_bytes()).hexdigest()}
+ expect, phases = B.bake_breathe_sequence(frames, _cfg(_smooth(loop_cells=24, start_cell=9)), analyze(base))
+ assert report["phases"] == phases == own["phases"]
+ for i, want in enumerate(expect):
+ with Image.open(tmp_path / "out" / f"frame-{i:03d}.png") as im:
+ assert im.convert("RGBA").tobytes() == want.tobytes(), f"{i}번 칸이 기준 칸의 해부로 구운 칸이 아니다"
+ Image.new("RGBA", (base.width + 2, base.height)).save(tmp_path / "wide.png")
+ with pytest.raises(SystemExit, match="--reference"):
+ cli.main(["breathe", str(src), str(tmp_path / "wide"), *flags, "--reference", str(tmp_path / "wide.png")])
+ with pytest.raises(SystemExit, match="--avoid-region"):
+ cli.main(["breathe", str(src), str(tmp_path / "beat"), "--mode", "smooth", "--avoid-region", "0.3,0.7,0.7,0.9",
+ "--fps", "24", "--loop-cells", "24", "--start-cell", "9"])
+ assert not any((tmp_path / name).exists() for name in ("wide", "beat"))
diff --git a/tests/effects/test_breathe_smooth_curator.py b/tests/effects/test_breathe_smooth_curator.py
index d6b5e17..fa2bbc6 100644
--- a/tests/effects/test_breathe_smooth_curator.py
+++ b/tests/effects/test_breathe_smooth_curator.py
@@ -62,7 +62,9 @@ def test_the_mirror_refuses_a_smooth_row_instead_of_drawing_pixel(tmp_path) -> N
"shoulder": 0.6, "shoulder_lag": 0.1, "chest_tilt": -20, "chest_bias": -0.4, "chest_dir": -30,
"chest_x": -0.1, "chest_bias_y": 0.3, "chest_flat": 0.25, "inhale": 0.45},
{"mode": "smooth", "breath_peaks": [21, 69, 118]},
-], ids=["smooth", "depth-omitted", "with-overrides", "with-shape", "with-peaks"])
+ {"mode": "smooth", "breaths": 2, "loop_cells": 96, "start_cell": 31},
+ {"mode": "smooth", "breaths": 2, "loop_cells": None, "start_cell": 5},
+], ids=["smooth", "depth-omitted", "with-overrides", "with-shape", "with-peaks", "with-stretch", "turned-own-loop"])
def test_the_round_trip_keeps_a_smooth_sidecar_as_written(tmp_path, sidecar) -> None:
got = _roundtrip(_run(sidecar), tmp_path)
saved = got["payload"]["states"]["idle"].get("breathe")
@@ -82,8 +84,14 @@ def test_the_round_trip_keeps_a_smooth_sidecar_as_written(tmp_path, sidecar) ->
{"depth": 0.06, "breaths": 2, "chest_tilt": 10},
{"depth": 0.06, "breath_peaks": [5, 15]},
{"mode": "smooth", "breath_peaks": [15, 5]},
+ {"depth": 0.06, "breaths": 2, "start_cell": 3},
+ {"depth": 0.06, "breaths": 2, "loop_cells": None},
+ {"mode": "smooth", "breaths": 2, "loop_cells": 24, "start_cell": 24},
+ {"mode": "smooth", "breaths": 2, "loop_cells": 1},
+ {"mode": "smooth", "breaths": 2, "start_cell": 2.5},
], ids=["unknown-mode", "smooth-with-lag", "shape-on-pixel", "shape-out-of-range", "dir-out-of-range",
- "tilt-on-pixel", "peaks-on-pixel", "peaks-unsorted"])
+ "tilt-on-pixel", "peaks-on-pixel", "peaks-unsorted", "start-on-pixel", "loop-on-pixel", "start-past-loop",
+ "one-cell-loop", "start-not-int"])
def test_a_sidecar_the_bake_refuses_is_kept_and_reported(tmp_path, sidecar) -> None:
with pytest.raises(SystemExit):
state_breathe({"states": {"idle": {"breathe": sidecar}}}, "idle")
diff --git a/tests/video/test_follow_inspect.py b/tests/video/test_follow_inspect.py
index dee4bb0..e8c932f 100644
--- a/tests/video/test_follow_inspect.py
+++ b/tests/video/test_follow_inspect.py
@@ -434,7 +434,7 @@ def test_the_command_takes_what_video_follow_takes(tmp_path, capsys):
cli.COMMANDS[cli.VERB_ALIASES['video-follow'][0]][1](parsers[0])
add_arguments(parsers[1])
followed, inspected = vars(parsers[0].parse_args(asked)), vars(parsers[1].parse_args([*asked, '--out-dir', str(out)]))
- own = {'board', 'frames', 'out', 'fps'} # video-sway's own: its board, and the frames path beside the loop directory
+ own = {'board', 'frames', 'out', 'fps', 'reference'} # video-sway's own: its board, and the frames path beside the loop directory
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_breath.py b/tests/video/test_sway_breath.py
index 52c0aeb..b5a95d1 100644
--- a/tests/video/test_sway_breath.py
+++ b/tests/video/test_sway_breath.py
@@ -75,7 +75,7 @@ def test_the_first_cell_every_rest_and_the_close_are_the_breathed_cells(breathed
report = json.loads((src/'breathe.json').read_text())
assert record['drive'] == {'kind': 'breath', 'breathe_sha256': hashlib.sha256((src/'breathe.json').read_bytes()).hexdigest(),
'lag': sway.LAG_DEFAULT, 'lift_px': round(lift(report), 4), 'heading_deg': 0.0, 'inhale': INHALE,
- 'breaths': BREATHS}
+ 'breaths': BREATHS, 'start_cell': 0, 'loop_cells': None}
assert 'freq_hz' not in record and record['frame_ms'] is None
@@ -132,17 +132,22 @@ def test_the_part_follows_the_in_breath_share_the_record_says(breathed, tmp_path
assert np.abs(offset(0.42) - offset(INHALE)).max() > 0.1
-def test_a_record_written_before_the_share_was_there_is_the_default_breath(breathed, tmp_path):
- """A record that does not say its in-breath share, as none did before the key was there, says the default, as a
- sidecar leaving it out does: the part follows the same breath to the bit."""
[email protected]('keys', [('inhale',), ('start_cell', 'loop_cells'), ('inhale', 'start_cell', 'loop_cells')],
+ ids=['share', 'stretch', 'both'])
+def test_a_record_written_before_the_keys_were_there_is_the_default_breath(breathed, tmp_path, keys):
+ """A record that does not say its in-breath share or its place in a loop, as none did before the keys were there,
+ says the default, as a sidecar leaving them out does — the share 0.40, and the frames are the loop from its first
+ cell: the part follows the same breath to the bit, and the drive says the defaults."""
src = breathed/'breathed'
report = json.loads((src/'breathe.json').read_text())
- assert report['config']['inhale'] == INHALE
+ assert (report['config']['inhale'], report['config']['start_cell'], report['config']['loop_cells']) == (INHALE, 0, None)
unsaid = tmp_path/'unsaid.json'
- unsaid.write_text(json.dumps(report | {'config': {k: v for k, v in report['config'].items() if k != 'inhale'}}))
+ unsaid.write_text(json.dumps(report | {'config': {k: v for k, v in report['config'].items() if k not in keys}}))
cells = [Image.fromarray(rgba(src/name)) for name in FILES]
a, b = (sway.solve_cells(sway.read_ask([CHEST], breathe=path), cells, None) for path in (src/'breathe.json', unsaid))
assert np.array_equal(a.dy, b.dy) and np.array_equal(a.dx, b.dx) and np.abs(a.dy).max() > 0
+ assert {k: v for k, v in b.record()['drive'].items() if k != 'breathe_sha256'} == \
+ {k: v for k, v in a.record()['drive'].items() if k != 'breathe_sha256'}
# The cells the default breath swayed into before a record could say its in-breath share (e18c905): the 48 cells of
@@ -157,6 +162,120 @@ def test_the_default_breath_sways_the_bytes_it_swayed_before(breathed, tmp_path)
assert hashlib.sha256(b''.join(rgba(out/name).tobytes() for name in FILES)).hexdigest() == SWAY_GOLDEN
+# A loop set's way out of its loop: 17 cells that leave the 48-cell loop (two breaths of 24) at its cell 13, past the rest at
+# 24. The body in them lies SHIFTS px across from where it lies in the loop's first cell, where the regions were read.
+START = 13
+SHIFTS = [3, 3, 2, 2, 1, 1, 0, 0, 1, 2, 3, 3, 2, 1, 0, 0, 1]
+WAY = [f'frame-{k:03d}.png' for k in range(len(SHIFTS))]
+
+
+def shifted(image, dx):
+ """The picture moved dx px across (the bust's sides are clear, so nothing wraps into sight)."""
+ return Image.fromarray(np.roll(np.asarray(image.convert('RGBA')), dx, axis=1), 'RGBA')
+
+
+def solved(frames, record, gain, reference=None):
+ cells = [Image.fromarray(rgba(frames/name)) for name in sorted(p.name for p in frames.glob('frame-*.png'))]
+ held = None if reference is None else (Image.open(reference).convert('RGBA'), {'path': str(reference)})
+ return sway.solve_cells(sway.read_ask([CHEST], breathe=record, gain=gain, on_fold='lower'), cells, None, reference=held)
+
+
[email protected](scope='module')
+def way_out(breathed, tmp_path_factory):
+ """The way out swayed on the loop's breath twice: by engine commands (its own 17 frames, `sprite-gen breathe
+ --loop-cells 48 --start-cell 13 --reference <the loop's first cell>`, then `video-sway --breathe --reference`), and by
+ the hand step those replace (the pad: the frames laid at cells 13..29 of 48, every other cell the loop's first, breathed
+ and swayed whole, cells 13..29 cut out). The gain folds the region on the loop's whole breath and not on the 17 cells'
+ own: the fold rule must read the loop's."""
+ root = tmp_path_factory.mktemp('way')
+ base = _bust()
+ base.save(root/'base.png')
+ for name, cells in (('way', [shifted(base, s) for s in SHIFTS]),
+ ('pad', [shifted(base, SHIFTS[k - START]) if 0 <= k - START < len(SHIFTS) else base for k in range(N)])):
+ (root/name).mkdir()
+ for k, cell in enumerate(cells):
+ cell.save(root/name/f'frame-{k:03d}.png')
+ per_cell = np.hypot(*answer(breathed, gain=1.0, on_fold='lower').moves[1.0]) # the loop's offset per cell at gain 1
+ stretch = [(START + i) % N for i in range(len(SHIFTS))]
+ radius = min(CHEST[2:4])
+ folds_at = [2*radius/(math.pi*float(reach)) for reach in (per_cell.max(), per_cell[stretch].max())]
+ assert folds_at[0] < folds_at[1] / 1.2, 'the loop does not reach far past the way out'
+ gain = round(sum(folds_at)/2, 2)
+ region_flag = ['--region', region(), '--gain', str(gain), '--on-fold', 'lower']
+ breath = ['--mode', 'smooth', '--depth', str(DEPTH), '--breaths', str(BREATHS)]
+ reference = ['--reference', str(root/'base.png')]
+ assert cli.main(['breathe', str(root/'way'), str(root/'way-b'), *breath, '--loop-cells', str(N), '--start-cell', str(START),
+ *reference]) == 0
+ assert cli.main(['video-sway', '--frames', str(root/'way-b'), '--out', str(root/'way-s'), '--breathe',
+ str(root/'way-b'/'breathe.json'), *region_flag, *reference]) == 0
+ assert cli.main(['breathe', str(root/'pad'), str(root/'pad-b'), *breath]) == 0
+ assert cli.main(['video-sway', '--frames', str(root/'pad-b'), '--out', str(root/'pad-s'), '--breathe',
+ str(root/'pad-b'/'breathe.json'), *region_flag]) == 0
+ return root, gain, stretch, float(per_cell[stretch].max())
+
+
+def test_a_way_out_is_offset_as_the_loop_cell_of_its_phase(breathed, way_out):
+ """Cell i of a stretch that starts at the loop's cell k is offset as the loop's cell (k + i) mod 48 is — the very
+ doubles, at the gain the loop moves by — from its first cell on: an offset is its phase's alone, so nothing is wound
+ up before the stretch starts (its first cell is not at rest, and is offset as the loop's cell 13 is)."""
+ root, gain, stretch, _ = way_out
+ loop = answer(breathed, gain=gain, on_fold='lower')
+ way = solved(root/'way-b', root/'way-b'/'breathe.json', gain, root/'base.png')
+ assert way.gain == loop.gain < gain
+ assert np.array_equal(way.dx, loop.dx[stretch]) and np.array_equal(way.dy, loop.dy[stretch])
+ assert way.dy[0] != 0 and abs(way.dy[0]) == abs(loop.dy[START])
+ report = json.loads((root/'way-b'/'breathe.json').read_text())
+ record = json.loads((root/'way-s'/'sway.json').read_text())
+ assert (report['config']['start_cell'], report['config']['loop_cells']) == (START, N)
+ assert (record['drive']['start_cell'], record['drive']['loop_cells']) == (START, N)
+ assert record['dx_px'] == np.round(loop.dx[stretch], 2).tolist() and record['dy_px'] == np.round(loop.dy[stretch], 2).tolist()
+
+
+def test_a_way_out_is_the_pad_hand_step_cut_out(way_out):
+ """What the pad hand step made, the engine makes: the same phases, offsets, fold, gain and reach, the regions
+ carried from the loop's first cell, and so the same cells byte for byte — breathed, and swayed."""
+ root, gain, stretch, own_reach = way_out
+ cut = slice(START, START + len(SHIFTS))
+ way_b, pad_b = (json.loads((root/name/'breathe.json').read_text()) for name in ('way-b', 'pad-b'))
+ assert way_b['phases'] == pad_b['phases'][cut]
+ assert way_b['resolved']['anatomy'] == pad_b['resolved']['anatomy']
+ for k, name in enumerate(WAY):
+ assert np.array_equal(rgba(root/'way-b'/name), rgba(root/'pad-b'/f'frame-{START + k:03d}.png')), f'breathed cell {k}'
+ assert np.array_equal(rgba(root/'way-s'/name), rgba(root/'pad-s'/f'frame-{START + k:03d}.png')), f'swayed cell {k}'
+ way_s, pad_s = (json.loads((root/name/'sway.json').read_text()) for name in ('way-s', 'pad-s'))
+ assert way_s['dx_px'] == pad_s['dx_px'][cut] and way_s['dy_px'] == pad_s['dy_px'][cut]
+ same = ('gain', 'gain_requested', 'reach_px', 'fold', 'body_px', 'body_worn_px', 'body_bob_px')
+ assert {k: way_s[k] for k in same} == {k: pad_s[k] for k in same}
+ assert way_s['fold']['lowered'] and way_s['gain'] < gain and gain*own_reach*math.pi/(2*min(CHEST[2:4])) < 1, \
+ 'the 17 cells alone would not have lowered the gain: the loop folds the way out'
+ way = solved(root/'way-b', root/'way-b'/'breathe.json', gain, root/'base.png')
+ pad = solved(root/'pad-b', root/'pad-b'/'breathe.json', gain)
+ assert [way.carry(k) for k in range(len(SHIFTS))] == [pad.carry(START + k) for k in range(len(SHIFTS))] \
+ == [(float(s), 0.0) for s in SHIFTS]
+ assert way_s['reference'] == {'path': str(root/'base.png'),
+ 'sha256': hashlib.sha256((root/'base.png').read_bytes()).hexdigest()}
+
+
+def test_without_the_reference_the_regions_are_carried_from_the_first_frame(way_out):
+ """The regions of a way out were read on the loop's first cell, which is not one of its frames: read from its own
+ first frame, every cell's carry is off by where the body lies in that frame (3 px), and the cells are not the pad's."""
+ root, gain, _, _ = way_out
+ own = solved(root/'way-b', root/'way-b'/'breathe.json', gain)
+ assert [own.carry(k) for k in range(len(SHIFTS))] == [(float(s - SHIFTS[0]), 0.0) for s in SHIFTS]
+ assert own.carry(0) == (0.0, 0.0) != (float(SHIFTS[0]), 0.0)
+
+
+def test_a_reference_is_one_size_with_the_frames_and_goes_with_them(breathed, tmp_path):
+ src = breathed/'breathed'
+ Image.new('RGBA', (10, 10)).save(tmp_path/'small.png')
+ asked = ['video-sway', '--region', region(), '--breathe', str(src/'breathe.json')]
+ with pytest.raises(SystemExit, match='--reference .* is 10x10'):
+ cli.main([*asked, '--frames', str(src), '--out', str(tmp_path/'out'), '--reference', str(tmp_path/'small.png')])
+ with pytest.raises(SystemExit, match='--reference goes with --frames'):
+ cli.main([*asked, '--loop-dir', str(tmp_path), '--reference', str(tmp_path/'small.png')])
+ assert not (tmp_path/'out').exists()
+
+
def test_a_heading_moves_the_part_against_the_way_the_chest_rises(breathed, tmp_path):
plain = breathed/'plain'
assert cli.main(['breathe', str(plain), str(tmp_path/'turned'), '--mode', 'smooth', '--depth', str(DEPTH),