Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(breathe): the in-breath share a smooth row's own setting — `inhale` (default 0.40, 0.2..0.8) in the sidecar, `sprite-gen breathe --inhale` and breathe.json; Sway on the breath follows the share its record says
Soohong Kim555fabc21ebf
diff --git a/sprite_gen/curate/curation.py b/sprite_gen/curate/curation.pyindex 36204e4..e2c9f98 100644--- a/sprite_gen/curate/curation.py+++ b/sprite_gen/curate/curation.py@@ -238,13 +238,15 @@ BREATHE_SMOOTH_DEPTH_X = 0.028# 아래) 옮긴다 — 무게는 꼭대기에서 테두리까지 반직선으로 줄어 가까운 쪽이 짧고 돌아간 쪽이 길다.# chest_x: 가슴 중심을 몸통 축에서 옮김 (몸통 반폭 비율 — 긴 머리처럼 한쪽으로 쏠린 것이 축을 끌 때),# chest_flat: 꼭대기 둘레에서 전량으로 오르는 몫 (꼭대기에서 테두리까지의 비율).+# inhale: 한 호흡에서 들숨이 차지하는 몫 — 들숨 꼭대기가 이 위상에 오고 나머지가 날숨이다 (기본은 들숨이 짧다).+# 바깥에서 만든 숨의 기록(breathe.json)도 이 값으로 제 곡선을 말한다.BREATHE_SMOOTH_SHAPE = {"chest_y": 0.31, "chest_rx": 0.83, "chest_ry": 0.28, "shoulder": 0.5, "shoulder_lag": 0.08,"chest_tilt": 0.0, "chest_bias": 0.0, "chest_dir": 0.0, "chest_x": 0.0, "chest_bias_y": 0.0,- "chest_flat": 0.0}+ "chest_flat": 0.0, "inhale": 0.40}BREATHE_SMOOTH_SHAPE_RANGES = {"chest_y": (0.05, 0.95), "chest_rx": (0.2, 3.0), "chest_ry": (0.05, 1.5),"shoulder": (0.0, 1.5), "shoulder_lag": (0.0, 0.3), "chest_tilt": (-60.0, 60.0),"chest_bias": (-0.9, 0.9), "chest_dir": (-90.0, 90.0), "chest_x": (-1.0, 1.0),- "chest_bias_y": (-0.9, 0.9), "chest_flat": (0.0, 0.9)}+ "chest_bias_y": (-0.9, 0.9), "chest_flat": (0.0, 0.9), "inhale": (0.2, 0.8)}# 꼭대기는 타원 안쪽이어야 한다 — 테두리에 닿으면 그쪽으로 무게가 줄어들 거리가 없다.BREATHE_SMOOTH_PEAK_REACH = 0.9@@ -286,8 +288,8 @@ 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` 의 키)이 기본값과 함께 실린다. 모양 값은 smooth 만 쓴다 — pixel 줄에- 있으면 조용히 무시하지 않고 거부한다."""+ (`BREATHE_SMOOTH_SHAPE` 의 키, 들숨 몫 `inhale` 포함)이 기본값과 함께 실린다. 모양 값은 smooth 만 쓴다 — pixel+ 줄에 있으면 조용히 무시하지 않고 거부한다."""if not curation:return Noneentry = curation.get("states", {}).get(state)diff --git a/sprite_gen/effects/breath_beat.py b/sprite_gen/effects/breath_beat.pyindex 7d4df30..c4d8f05 100644--- a/sprite_gen/effects/breath_beat.py+++ b/sprite_gen/effects/breath_beat.py@@ -8,7 +8,7 @@- 손 상자(`--avoid-region`)와 그 위 몸 상자(`--avoid-anchor`, 생략하면 손 상자 바로 위 띠 `anchor_band`)를 첫 칸기준 마스크 NCC 로 따라간다(`auto_motion.track_box`, 정수 px). 손의 제 오름 = 손 − 몸, 몸 오름 = 몸 (위 양수).- 후보는 한 숨이 `PERIOD_S` 안인 숨 수 k 를 고르게 둔 것, 그리고 고른 k 의 꼭대기를 앞뒤 `NUDGE` 칸까지 민 것이다- (k 가 3 이하면 꼭대기마다 따로, 넘으면 다 같이). 곡선은 굽기와 같은 `breathe.smooth_wave` 다.+ (k 가 3 이하면 꼭대기마다 따로, 넘으면 다 같이). 곡선은 굽기와 같은 `breathe.smooth_wave` 다 — 같은 들숨 몫(`inhale`)으로.- 점수 = 상관(숨, 몸 오름) − 상관(숨, 손 오름). 숨이 손과 같이 오르내리지 않고 영상의 몸과 같이 가면 높다.- 조건: 들숨 꼭대기마다 앞뒤 `NEAR` 칸에서 가슴 오름(가슴 오름 px × 숨) 이 손의 제 오름보다 낮지 않다 — 가슴이손 위에 있다. 가슴 오름 px 는 굽기가 쓰는 그 값(`breathe.smooth_lift`)이다.@@ -59,9 +59,10 @@ def _corr(a: np.ndarray, b: np.ndarray) -> float:return float((a * b).sum() / d) if d else 0.0-def _row(beat: dict, n: int, hands: np.ndarray, body: np.ndarray, lift: float) -> dict[str, Any]:- """한 박자 후보의 점수와 조건 — 그 박자로 굽기가 쓸 위상에서."""- w = np.asarray([breathe.smooth_wave(p) for p in breathe.fit_breathe_pattern(n, {"mode": "smooth", **beat})])+def _row(beat: dict, n: int, hands: np.ndarray, body: np.ndarray, lift: float, inhale: float) -> dict[str, Any]:+ """한 박자 후보의 점수와 조건 — 그 박자와 들숨 몫으로 굽기가 쓸 위상과 곡선에서."""+ phases = breathe.fit_breathe_pattern(n, {"mode": "smooth", "inhale": inhale, **beat})+ w = np.asarray([breathe.smooth_wave(p, inhale) for p in phases])peaks = [i for i in range(n) if w[i] > PEAK_LEVEL and w[i] >= w[i - 1] and w[i] >= w[(i + 1) % n]]margin = min(lift * w[p] - max(hands[(p + j) % n] for j in range(-NEAR, NEAR + 1)) for p in peaks)corr_hands, corr_body = _corr(w, hands), _corr(w, body)@@ -74,10 +75,11 @@ def candidates(n: int, frame_ms: float) -> list[int]:return [k for k in range(1, BREATHE_BREATHS_MAX + 1) if PERIOD_S[0] <= n * frame_ms / 1000 / k <= PERIOD_S[1]]-def nudged(n: int, k: int) -> list[list[int]]:- """숨 k 번을 고르게 둔 꼭대기를 앞뒤 `NUDGE` 칸까지 민 꼭대기 목록들 — 첫 칸은 쉼, 마지막 꼭대기 뒤에 날숨이 들어갈- 두 칸, 꼭대기 사이 두 칸 이상(curation 의 breath_peaks 검사와 _peaked_phases 의 끝 검사)."""- base = [round((i + breathe.INHALE) * n / k) for i in range(k)]+def nudged(n: int, k: int, inhale: float) -> list[list[int]]:+ """숨 k 번을 고르게 둔 꼭대기(숨마다 들숨 몫 `inhale` 자리)를 앞뒤 `NUDGE` 칸까지 민 꼭대기 목록들 — 첫 칸은 쉼,+ 마지막 꼭대기 뒤에 날숨이 들어갈 두 칸, 꼭대기 사이 두 칸 이상(curation 의 breath_peaks 검사와 _peaked_phases 의+ 끝 검사)."""+ base = [round((i + inhale) * n / k) for i in range(k)]span = range(-NUDGE, NUDGE + 1)moves = itertools.product(span, repeat=k) if k <= 3 else ((m,) * k for m in span)out = []@@ -102,10 +104,10 @@ def pick(evenly: list[dict[str, Any]], pushed: list[dict[str, Any]]) -> dict[strreturn top if top is not None and top["score"] > best["score"] + MARGIN else best-def choose(images: list[Image.Image], lift: float, avoid: tuple[float, float, float, float],+def choose(images: list[Image.Image], lift: float, inhale: float, avoid: tuple[float, float, float, float],anchor: tuple[float, float, float, float] | None, frame_ms: float) -> tuple[dict[str, Any], dict[str, Any]]:"""`images`(숨 넣기 전 칸들)에서 고른 숨 박자(`{"breaths": k}` 또는 `{"breath_peaks": [...]}`)와 breathe.json 에- 남길 `beat` 기록."""+ 남길 `beat` 기록 — 곡선은 줄의 들숨 몫 `inhale` 의 것이다."""n = len(images)size = images[0].sizeanchor = anchor_band(avoid) if anchor is None else anchor@@ -124,9 +126,9 @@ def choose(images: list[Image.Image], lift: float, avoid: tuple[float, float, flif not ks:raise SystemExit(f"breathe: --avoid-region — 루프가 {n * frame_ms / 1000:g} 초라 {PERIOD_S[0]:g}~{PERIOD_S[1]:g} 초 "f"숨이 정수 번 들어가지 않는다. --breaths 로 정해라.")- evenly = [_row({"breaths": k}, n, hands, body, lift) for k in ks]+ evenly = [_row({"breaths": k}, n, hands, body, lift, inhale) for k in ks]best = pick(evenly, [])- pushed = [_row({"breath_peaks": peaks}, n, hands, body, lift) for peaks in nudged(n, best["breaths"])]+ pushed = [_row({"breath_peaks": peaks}, n, hands, body, lift, inhale) for peaks in nudged(n, best["breaths"], inhale)]chosen = pick(evenly, pushed)beat = {"breaths": chosen["breaths"]} if "breaths" in chosen else {"breath_peaks": chosen["breath_peaks"]}top = max(pushed, key=lambda row: (row["keeps"], row["score"]), default=None)diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.pyindex cfb73c1..639a52a 100644--- a/sprite_gen/effects/breathe.py+++ b/sprite_gen/effects/breathe.py@@ -56,8 +56,8 @@ AI 개입 0 — 같은 입력이면 항상 같은 출력.목 밴드(강체 경계 ~ 어깨선)에서 켜지고 콘텐츠 맨 아래에서 꺼진다정사상(원본 점의 내용이 가는 자리)의 역을 고정점 반복으로 풀어 쌍선형으로 뜬다(곱한 알파).-강체 경계 위(목·턱 위)와 무게 밖은 원본 바이트 그대로다. 한 호흡은 0 에서 시작해 들숨(INHALE)에-1, 날숨에 0 으로 돌아오는 한쪽 혹이고 어깨의 늦음도 양 끝에서 0 이라, 위상 0 인 칸은 원본과+강체 경계 위(목·턱 위)와 무게 밖은 원본 바이트 그대로다. 한 호흡은 0 에서 시작해 들숨 몫(`inhale`)의+위상에 1, 날숨에 0 으로 돌아오는 한쪽 혹이고 어깨의 늦음도 양 끝에서 0 이라, 위상 0 인 칸은 원본과바이트 같다. 가슴 무게가 몸통 안에서 0 으로 떨어져 화면 변에 닿은 그림도 밖으로 밀리지 않는다.줄 전체가 기준 칸(첫 칸)에서 잰 해부와 그 자리를 쓴다 — 영상 루프의 머리 윗선이 칸마다 흔들려도경계는 움직이지 않는다.@@ -91,8 +91,6 @@ DEFAULT_DEPTH = 0.06DEFAULT_LAG = 0.10# 한 호흡이 부드럽게 읽히려면 필요한 최소 프레임 수 (프레임을 찍어낼 때의 권고치).SMOOTH_CYCLE_FRAMES = 6-# smooth 모드 — 들숨이 한 호흡에서 차지하는 비율 (들숨이 날숨보다 짧다).-INHALE = 0.40DEFAULT_SMOOTH_DEPTH = BREATHE_SMOOTH_DEPTHDEFAULT_SMOOTH_DEPTH_X = BREATHE_SMOOTH_DEPTH_XSMOOTH_SHAPE = dict(BREATHE_SMOOTH_SHAPE)@@ -449,25 +447,31 @@ def breathe_mode(cfg: dict) -> str:return mode-def smooth_wave(t: float) -> float:- """smooth 의 한 호흡 — 위상 0 에서 0, 들숨 끝(INHALE)에 1, 날숨 끝에 다시 0.+def smooth_wave(t: float, inhale: float) -> float:+ """smooth 의 한 호흡 — 위상 0 에서 0, 들숨 끝(위상 `inhale`)에 1, 날숨 끝에 다시 0.pixel 의 `wave` 는 위아래로 흔드는 사인이고 진행파 지연까지 있어 위상 0 에서도 윗행이움직인다. 여기는 쉼(0)에서 올랐다 돌아오기만 하는 한쪽 혹이고, 양 끝과 정점에서 기울기가- 0 이라 루프 이음에서 꺾이지 않는다."""+ 0 이라 루프 이음에서 꺾이지 않는다. 들숨 몫은 줄의 설정(`smooth_inhale`)에서 받는다 — 여기 기본값이 있으면+ 기록이 말하는 것과 다른 곡선이 조용히 나온다."""t = t % 1.0- g = 0.5 * t / INHALE if t < INHALE else 0.5 + 0.5 * (t - INHALE) / (1.0 - INHALE)+ g = 0.5 * t / inhale if t < inhale else 0.5 + 0.5 * (t - inhale) / (1.0 - inhale)return 0.5 - 0.5 * math.cos(2.0 * math.pi * g)-def smooth_shoulder_wave(t: float, lag: float) -> float:+def smooth_inhale(cfg: dict) -> float:+ """smooth 줄의 들숨 몫 — 설정의 `inhale` (생략이면 기본값, 다른 모양 값과 같다)."""+ return _shape(cfg)["inhale"]+++def smooth_shoulder_wave(t: float, lag: float, inhale: float) -> float:"""어깨의 호흡 — 가슴보다 `lag` 만큼 늦게 정점에 닿되 위상 0 과 1 에서는 가슴과 같이 0.`wave(t - lag)` 로 늦추면 위상 0 에서 어깨가 아직 날숨 끝에 걸려 있어 첫 칸이 원본이 아니게된다. 시간을 `t - lag·sin(πt)` 로 휘면 양 끝은 그대로 두고 가운데만 늦출 수 있다 (lag < 1/π이면 단조라 되감기지 않는다)."""t = t % 1.0- return smooth_wave(t - lag * math.sin(math.pi * t))+ return smooth_wave(t - lag * math.sin(math.pi * t), inhale)def smooth_band(anat: Anatomy) -> tuple[float, float]:@@ -634,8 +638,9 @@ def _smooth_warp(frame: Image.Image, anat: Anatomy, cfg: dict, t: float) -> Imag끝까지 제자리이므로, 둘째 걸음부터는 첫걸음에 움직인 픽셀(무게 띠 안)만 다시 푼다 — 같은 식을같은 점에서 재므로 결과가 같다."""rgba = frame.convert("RGBA")- chest = smooth_wave(t)- shoulders = smooth_shoulder_wave(t, _shape(cfg)["shoulder_lag"])+ shape = _shape(cfg)+ chest = smooth_wave(t, shape["inhale"])+ shoulders = smooth_shoulder_wave(t, shape["shoulder_lag"], shape["inhale"])box = solid_alpha_bbox(rgba)if not box or (chest == 0.0 and shoulders == 0.0):return rgba # 위상 0 — 원본 그대로 (바이트)@@ -889,19 +894,19 @@ def fit_breathe_pattern(seq_len: int, cfg: dict) -> list[float]:if seq_len <= 0:return []if cfg.get("breath_peaks"):- return _peaked_phases(seq_len, list(cfg["breath_peaks"]))+ return _peaked_phases(seq_len, 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)]-def _peaked_phases(seq_len: int, peaks: list[int]) -> list[float]:+def _peaked_phases(seq_len: int, peaks: list[int], inhale: float) -> list[float]:"""들숨 꼭대기 칸을 바깥에서 받은 위상 (smooth) — 숨 k 는 쉼에서 시작해 `peaks[k]` 칸에서 가득 차고(위상- INHALE) 다음 쉼으로 돌아간다. 쉼은 0 칸, 꼭대기 사이를 날숨 1-INHALE : 들숨 INHALE 로 나누는 자리, 그리고+ `inhale`) 다음 쉼으로 돌아간다. 쉼은 0 칸, 꼭대기 사이를 날숨 1-inhale : 들숨 inhale 로 나누는 자리, 그리고루프 끝이다 — 첫 칸이 쉼이고 루프가 쉼에서 닫힌다. 숨마다 위상은 [0, 1) 이다."""if peaks[-1] > seq_len - 2:raise SystemExit(f"breathe: breath_peaks 의 마지막 {peaks[-1]} 가 {seq_len}칸 루프의 끝에 너무 가깝다 — "f"꼭대기 뒤에 날숨이 들어갈 칸이 있어야 루프가 쉼에서 닫힌다 ({seq_len - 2} 까지).")- rests = [0.0] + [p + (1.0 - INHALE) * (q - p) for p, q in zip(peaks, peaks[1:])] + [float(seq_len)]+ rests = [0.0] + [p + (1.0 - inhale) * (q - p) for p, q in zip(peaks, peaks[1:])] + [float(seq_len)]phases = []k = 0for i in range(seq_len):@@ -909,9 +914,9 @@ def _peaked_phases(seq_len: int, peaks: list[int]) -> list[float]:k += 1start, peak, end = rests[k], peaks[k], rests[k + 1]if i <= peak:- phases.append(INHALE * (i - start) / (peak - start))+ phases.append(inhale * (i - start) / (peak - start))else:- phases.append(INHALE + (1.0 - INHALE) * (i - peak) / (end - peak))+ phases.append(inhale + (1.0 - inhale) * (i - peak) / (end - peak))return phases@@ -1055,6 +1060,9 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:help="the chest's peak moved across its long axis, times its half height, positive down (0)")shape.add_argument("--chest-flat", type=float, default=None,help="share of the way from the peak to the rim that rises in full (0)")+ shape.add_argument("--inhale", type=float, default=None,+ help="share of one breath the in-breath takes, the rest the out-breath; the in-breath peaks at this "+ f"phase ({SMOOTH_SHAPE['inhale']})")shape.add_argument("--breath-peaks", type=_cells, default=None, metavar="CELL,CELL,...",help="smooth: the cells where each in-breath peaks (the breath count is how many); the first ""cell stays at rest and the loop closes at rest")@@ -1085,7 +1093,8 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =chest_ry: float | None = None, shoulder: float | None = None, shoulder_lag: float | None = None,chest_tilt: float | None = None, chest_bias: float | None = None, chest_dir: float | None = None,chest_x: float | None = None, chest_bias_y: float | None = None, chest_flat: float | None = None,- breath_peaks: list[int] | None = None, avoid_region: tuple[float, float, float, 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:"""프레임 폴더에 Breathe 레이어를 굽는다 — 큐레이션 사이드카 `breathe` 와 같은 값, 같은 정규화,같은 굽기(`bake_breathe_sequence`). 영상 루프의 칸처럼 큐레이션 런이 아닌 프레임이 이 길로 온다.@@ -1097,7 +1106,7 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =("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),- ("breath_peaks", breath_peaks))+ ("inhale", inhale), ("breath_peaks", breath_peaks))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 의 것이다 — 손 상자 없이는 읽지 않는다")@@ -1116,7 +1125,8 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =if frame_ms is None:raise SystemExit("breathe: --avoid-region 은 한 숨의 길이를 초로 본다 — --fps 를 주라 (video-loop 의 cycle/ ""폴더면 루프의 strip meta 에서 읽는다)")- chosen, beat = breath_beat.choose(images, smooth_lift(anat, cfg), avoid_region, avoid_anchor, frame_ms)+ chosen, beat = breath_beat.choose(images, smooth_lift(anat, cfg), smooth_inhale(cfg), avoid_region, avoid_anchor,+ frame_ms)cfg = _cli_breathe(raw | chosen)resolved = anatomy_report(images, cfg, anat)baked, phases = bake_breathe_sequence(images, cfg, anat)diff --git a/sprite_gen/serve/curator/src/store.js b/sprite_gen/serve/curator/src/store.jsindex 3fc7e8a..21a5c81 100644--- a/sprite_gen/serve/curator/src/store.js+++ b/sprite_gen/serve/curator/src/store.js@@ -14,7 +14,7 @@ function isNumericScalar(v) {// 굽기 방식 — 파이썬 curation.BREATHE_MODES 미러. 생략 = pixel.const BREATHE_MODES = ["pixel", "smooth"];// smooth 모양 값의 허용 범위 — 파이썬 curation.BREATHE_SMOOTH_SHAPE_RANGES 미러.-const BREATHE_SMOOTH_SHAPE_RANGES = { chest_y: [0.05, 0.95], chest_rx: [0.2, 3.0], chest_ry: [0.05, 1.5], shoulder: [0.0, 1.5], shoulder_lag: [0.0, 0.3], chest_tilt: [-60.0, 60.0], chest_bias: [-0.9, 0.9], chest_dir: [-90.0, 90.0], chest_x: [-1.0, 1.0], chest_bias_y: [-0.9, 0.9], chest_flat: [0.0, 0.9] };+const BREATHE_SMOOTH_SHAPE_RANGES = { chest_y: [0.05, 0.95], chest_rx: [0.2, 3.0], chest_ry: [0.05, 1.5], shoulder: [0.0, 1.5], shoulder_lag: [0.0, 0.3], chest_tilt: [-60.0, 60.0], chest_bias: [-0.9, 0.9], chest_dir: [-90.0, 90.0], chest_x: [-1.0, 1.0], chest_bias_y: [-0.9, 0.9], chest_flat: [0.0, 0.9], inhale: [0.2, 0.8] };function breatheRangeProblems(raw) {const bounds = [["depth", 0.005, 0.20, 0.06], ["breaths", 1, 8, 1], ["lag", 0, 0.45, 0.1]];diff --git a/sprite_gen/video/sway.py b/sprite_gen/video/sway.pyindex 35d786f..79be21f 100644--- a/sprite_gen/video/sway.py+++ b/sprite_gen/video/sway.py@@ -73,8 +73,9 @@ are moved, at the frame time its meta writes — rounded to hundredths of a ms,A breathing idle's head stays where it is and its body moves a pixel or two: read off the outline, that motion iswhole-pixel steps, and the damped mass answers their jerks, not the breath. `--breathe <breathe.json>` sways the parton the breath instead: the Breathe layer's record of the breath the frames were given (`sprite-gen breathe` writes it-beside them), its phases checked against those its config gives. The chest rises lift × w; the part rises as far, late-by `--lag` of a breath (the time warp the Breathe layer's shoulders are late by), and lies the difference behind:+beside them), its phases checked against those its config gives. The chest rises lift × w, w the breath of the record's+in-breath share (its config's `inhale`, the phase the in-breath peaks at); the part rises as far, late by `--lag` of a+breath (the time warp the Breathe layer's shoulders are late by), and lies the difference behind:offset = gain × lift × (w − w late), against the way the chest rises. Where the breath rests the offset is 0 — the firstcell, and where the loop closes — and a cell whose every offset is 0 is the cell as it was, byte for byte.@@ -589,26 +590,30 @@ class Breath:beat: dict[str, Any] # the breath count, or the cell of each in-breath's peaklift: float # px the chest rises at the top of an in-breath (breathe.smooth_lift)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 atlag: float # of one breathdef 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), 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."""- share = np.asarray([breathe_mod.smooth_wave(p) - breathe_mod.smooth_shoulder_wave(p, self.lag) for p in self.phases])+ `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."""+ 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])heading = math.radians(self.heading)return self.lift * share * -math.sin(heading) + 0.0, self.lift * share * math.cos(heading)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, **self.beat}+ "heading_deg": self.heading, "inhale": self.inhale, **self.beat}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 configgives after the sidecar's checks (`state_breathe`, `breathe.fit_breathe_pattern`), whose chest rises as the anatomy it- was baked with says. A record written by hand for a breath made elsewhere is read alike and must say the same."""+ 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."""lag = LAG_DEFAULT if lag is None else float(lag)if not 0 < lag < LAG_MAX: # a NaN is notraise SystemExit(f"{verb}: --lag is the share of a breath the part is late by, above 0 and under 1/π ({LAG_MAX:.4f}): at "@@ -643,7 +648,7 @@ def read_breath(path: Path, lag: float | None, *, verb: str = VERB) -> Breath:raise SystemExit(f"{verb}: --breathe {path}: its resolved.anatomy is not one sprite-gen breathe writes ({exc})") from excbeat = {"breath_peaks": list(cfg["breath_peaks"])} if cfg.get("breath_peaks") else {"breaths": cfg["breaths"]}return Breath(path, hashlib.sha256(data).hexdigest(), [float(p) for p in phases], beat,- breathe_mod.smooth_lift(anatomy, cfg), float(cfg["chest_dir"]), lag)+ breathe_mod.smooth_lift(anatomy, cfg), float(cfg["chest_dir"]), float(cfg["inhale"]), lag)@dataclass(frozen=True, eq=False)@@ -1103,8 +1108,9 @@ def add_request_arguments(parser: argparse.ArgumentParser, *, loop_dir: bool = Tparser.add_argument("--breathe", type=Path, default=None, metavar="BREATHE.JSON",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), 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")+ "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")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",diff --git a/tests/effects/test_breath_beat.py b/tests/effects/test_breath_beat.pyindex dbd25e2..14a7feb 100644--- a/tests/effects/test_breath_beat.py+++ b/tests/effects/test_breath_beat.py@@ -51,7 +51,8 @@ def _loop(folder: Path, hands: list[int], body: list[int] | None = None) -> Pathdef _wave(cfg: dict) -> np.ndarray:- return np.asarray([breathe.smooth_wave(p) for p in breathe.fit_breathe_pattern(N, {"mode": "smooth", **cfg})])+ inhale = breathe.smooth_inhale(cfg)+ return np.asarray([breathe.smooth_wave(p, inhale) for p in breathe.fit_breathe_pattern(N, {"mode": "smooth", **cfg})])def _peaks(w: np.ndarray) -> list[int]:@@ -94,6 +95,15 @@ def test_hands_that_move_against_the_breath_keep_the_evenly_spaced_breaths(tmp_passert beat["nudged_best"]["score"] <= rows[2]["score"] + breath_beat.MARGIN+def test_each_beat_is_read_on_the_rows_in_breath_share(tmp_path) -> None:+ """`--inhale` 이 있으면 후보마다 그 들숨 몫의 곡선으로 꼭대기와 점수를 잰다 — 굽기가 쓸 곡선 그대로다."""+ report = _avoid(_loop(tmp_path / "loop", BUMP), tmp_path / "out", "--inhale", "0.3")+ assert report["config"]["inhale"] == 0.3+ for row in report["beat"]["candidates"]:+ k = row["breaths"]+ assert row["peaks"] == _peaks(_wave({"breaths": k, "inhale": 0.3})) != _peaks(_wave({"breaths": k}))++def test_the_hands_own_rise_is_read_against_the_band_just_above_them(tmp_path) -> None:"""몸 상자를 주지 않으면 손 상자와 같은 열, 바로 위 띠 — 몸이 숨과 같이 오르내리면 손의 제 오름은 0 이고 숨은 몸을 따른다."""with_body = [round(2 * w) for w in _wave({"breaths": 2})]diff --git a/tests/effects/test_breathe_smooth.py b/tests/effects/test_breathe_smooth.pyindex c2d0689..4c13424 100644--- a/tests/effects/test_breathe_smooth.py+++ b/tests/effects/test_breathe_smooth.py@@ -38,6 +38,7 @@ from sprite_gen.frames.extract import solid_alpha_bboxfrom tests.effects.test_breathe import _dome, _humanoid, _outlined_figure, _winged+INHALE = B.SMOOTH_SHAPE["inhale"] # 기본 들숨 몫 — 기본 숨이 가득 차는 위상SKIN = (222, 184, 150, 255)BODY = (170, 120, 96, 255)EYE = (24, 18, 22, 255)@@ -117,9 +118,9 @@ def test_a_cell_at_phase_zero_is_byte_identical_to_its_source() -> None:for i in zero:assert frames[i].tobytes() == src.tobytes(), f"{i}번 칸: 위상 0 인데 원본과 다르다"assert any(f.tobytes() != src.tobytes() for f in frames), "숨을 한 번도 안 쉬었다"- assert B.smooth_wave(0.0) == 0.0 and B.smooth_wave(B.INHALE) == 1.0+ assert B.smooth_wave(0.0, INHALE) == 0.0 and B.smooth_wave(INHALE, INHALE) == 1.0for lag in (0.0, 0.08, 0.2):- assert B.smooth_shoulder_wave(0.0, lag) == 0.0, "어깨 지연이 첫 칸을 움직인다"+ assert B.smooth_shoulder_wave(0.0, lag, INHALE) == 0.0, "어깨 지연이 첫 칸을 움직인다"# ── 2. 머리 자리·바이트 고정 ───────────────────────────────────────@@ -132,7 +133,7 @@ def test_the_head_stays_in_place_byte_for_byte(h: int) -> None:cut = top + anat.rigid_row # 이 위가 강체(목·턱 위) 구간cfg = _cfg(_smooth())expect = np.asarray(src)[:cut].tobytes()- for phase in (0.1, B.INHALE, 0.55, 0.8):+ for phase in (0.1, INHALE, 0.55, 0.8):got = B.phase_frame(src, cfg, phase, anat)assert np.asarray(got)[:cut].tobytes() == expect, \f"위상 {phase}: 강체 경계({cut}행) 위가 움직였다 — 목·턱 위는 자리·바이트 그대로여야 한다"@@ -183,10 +184,10 @@ def test_the_chest_rises_by_depth_and_settles_back(h: int) -> None:src, anat, cfg, rows, cols = _marked(h)lift = cfg["depth"] * anat.basis_rowsreach = int(lift) + 4- for phase in (0.0, 0.2, B.INHALE, 0.7, 0.95):+ for phase in (0.0, 0.2, INHALE, 0.7, 0.95):got = B.phase_frame(src, cfg, phase, anat)rise = _rise(src, got, rows["chest"], cols["axis"], reach)- want = lift * B.smooth_wave(phase)+ want = lift * B.smooth_wave(phase, INHALE)assert rise == pytest.approx(want, abs=0.3), \f"위상 {phase}: 가슴 가운데가 {rise:.2f}px 올랐다 — {want:.2f}px 여야 한다 (depth {cfg['depth']} × 기준 {anat.basis_rows}행)"@@ -198,7 +199,7 @@ def test_it_is_not_a_whole_row_moving_up(h: int) -> None:src, anat, cfg, rows, cols = _marked(h)lift = cfg["depth"] * anat.basis_rowsreach = int(lift) + 4- got = B.phase_frame(src, cfg, B.INHALE, anat)+ got = B.phase_frame(src, cfg, INHALE, anat)center = _rise(src, got, rows["chest"], cols["axis"], reach)side = _rise(src, got, rows["chest"], cols["side"], reach)tip = _rise(src, got, rows["shoulder"], cols["tip"], reach)@@ -258,7 +259,7 @@ def test_no_seam_or_tear_between_the_head_and_the_body(h: int) -> None:box = solid_alpha_bbox(src)slope = 180.0 / (h - 1)cfg = _cfg(_smooth())- for phase in (0.25, B.INHALE, 0.6):+ for phase in (0.25, INHALE, 0.6):got = np.asarray(B.phase_frame(src, cfg, phase, anat)).astype(int)for column in (box[0] + anat.axis_x, box[0] + anat.axis_x + int(B.SHOULDER_X * anat.torso_half)):red = got[box[1]:box[3], column, 0] # 정수리부터 발끝까지 — 경계를 가로지른다@@ -306,7 +307,7 @@ def test_the_default_pixel_mode_is_byte_identical_to_before(build, mode) -> None# ── 8. 사이드카 ─────────────────────────────────────────────────────SHAPE = ("chest_y", "chest_rx", "chest_ry", "shoulder", "shoulder_lag", "chest_tilt", "chest_bias", "chest_dir",- "chest_x", "chest_bias_y", "chest_flat")+ "chest_x", "chest_bias_y", "chest_flat", "inhale")def test_the_sidecar_reads_mode_depth_breaths_and_the_shape() -> None:@@ -322,16 +323,16 @@ def test_the_sidecar_reads_mode_depth_breaths_and_the_shape() -> None:assert {k: given[k] for k in SHAPE} == {"chest_y": 0.4, "chest_rx": 0.8, "chest_ry": 0.3,"shoulder": 0.6, "shoulder_lag": 0.1,"chest_tilt": 0.0, "chest_bias": 0.0, "chest_dir": 0.0,- "chest_x": 0.0, "chest_bias_y": 0.0, "chest_flat": 0.0}+ "chest_x": 0.0, "chest_bias_y": 0.0, "chest_flat": 0.0, "inhale": 0.4}assert _cfg({"mode": "pixel", "breaths": 2})["mode"] == "pixel"def test_the_shape_moves_the_bake() -> None:"""모양 값은 이름만 있는 게 아니다 — 가슴 높이를 바꾸면 다른 그림이 구워진다."""src = _bust()- a = B.phase_frame(src, _cfg(_smooth()), B.INHALE)- b = B.phase_frame(src, _cfg(_smooth(chest_y=0.6)), B.INHALE)- c = B.phase_frame(src, _cfg(_smooth(shoulder=0.0)), B.INHALE)+ a = B.phase_frame(src, _cfg(_smooth()), INHALE)+ b = B.phase_frame(src, _cfg(_smooth(chest_y=0.6)), INHALE)+ c = B.phase_frame(src, _cfg(_smooth(shoulder=0.0)), INHALE)assert a.tobytes() != b.tobytes() and a.tobytes() != c.tobytes()@@ -344,15 +345,17 @@ def test_an_unknown_mode_is_refused_loudly(bad) -> None:@pytest.mark.parametrize("key,value", [("chest_y", 0.0), ("chest_rx", 9.0), ("chest_ry", -1),("shoulder", 3.0), ("shoulder_lag", 0.5), ("chest_y", "x"),("chest_tilt", 75), ("chest_bias", -1.0), ("chest_dir", 120),- ("chest_x", 1.5), ("chest_bias_y", 0.95), ("chest_flat", 0.95)])+ ("chest_x", 1.5), ("chest_bias_y", 0.95), ("chest_flat", 0.95),+ ("inhale", 0.1), ("inhale", 0.85)])def test_a_shape_value_out_of_range_is_refused(key, value) -> None:with pytest.raises(SystemExit, match=key):_cfg(_smooth(**{key: value}))-def test_a_shape_value_on_pixel_is_refused_not_ignored() -> None:- with pytest.raises(SystemExit, match="chest_y"):- _cfg({"depth": 0.06, "breaths": 2, "chest_y": 0.3})[email protected]("key,value", [("chest_y", 0.3), ("inhale", 0.42)])+def test_a_shape_value_on_pixel_is_refused_not_ignored(key, value) -> None:+ with pytest.raises(SystemExit, match=key):+ _cfg({"depth": 0.06, "breaths": 2, key: value})def test_the_sidecar_picks_the_smooth_warp() -> None:@@ -513,7 +516,7 @@ def test_breath_peaks_put_each_in_breath_where_asked() -> None:cfg = _cfg(_smooth(breath_peaks=[10, 40, 52], breaths=None))assert cfg["breaths"] == 3 and cfg["breath_peaks"] == [10, 40, 52]phases = B.fit_breathe_pattern(60, cfg)- curve = [B.smooth_wave(t) for t in phases]+ curve = [B.smooth_wave(t, INHALE) for t in phases]assert phases[0] == 0.0 and curve[0] == 0.0for p in (10, 40, 52):assert curve[p] == pytest.approx(1.0), f"{p}번 칸이 들숨 꼭대기가 아니다: {curve[p]}"@@ -545,6 +548,33 @@ def test_breath_peaks_on_pixel_are_refused() -> None:_cfg({"depth": 0.06, "breath_peaks": [5, 15]})+# ── 들숨 몫: 한 호흡에서 들숨이 차지하는 몫은 줄의 값 ────────────────++def test_the_in_breath_takes_the_rows_inhale_share() -> None:+ """`inhale` 은 한 호흡에서 들숨이 차지하는 몫이다 — 들숨 몫 0.42 인 줄은 위상 0.21 에 들숨 절반, 0.42 에 꼭대기이고,+ 그 칸들은 기본 줄(0.40)의 위상 0.20·0.40 칸과 바이트 같다. 어깨 지연을 0 으로 두면 어깨도 같은 곡선을 타서 칸이 곡선+ 값 하나로 정해진다."""+ src = _bust(400)+ anat = analyze(src)+ row = _cfg(_smooth(inhale=0.42, shoulder_lag=0.0))+ default = _cfg(_smooth(shoulder_lag=0.0))+ for share in (0.5, 1.0):+ want = B.phase_frame(src, default, share * INHALE, anat).tobytes()+ assert want != src.tobytes()+ assert B.phase_frame(src, row, share * 0.42, anat).tobytes() == want, \+ f"들숨 몫 0.42 인데 위상 {share * 0.42:g} 가 들숨의 {share:g} 자리가 아니다"+ assert row["inhale"] == 0.42 and default["inhale"] == INHALE+++def test_breath_peaks_split_the_breaths_at_the_rows_inhale_share() -> None:+ """꼭대기 칸을 바깥에서 받아도 숨 사이 쉼은 꼭대기 사이를 날숨 1-inhale : 들숨 inhale 로 나누는 자리다 — 들숨 몫+ 0.42 면 10·40 칸 꼭대기 사이 쉼은 10 + 0.58 × 30 = 27.4 이고, 28 칸이 다음 숨의 들숨 0.42 × 0.6 / 12.6 자리다."""+ cfg = _cfg(_smooth(breath_peaks=[10, 40, 52], breaths=None, inhale=0.42))+ phases = B.fit_breathe_pattern(60, cfg)+ assert phases[27] > 0.9 and phases[28] == pytest.approx(0.42 * (28 - 27.4) / (40 - 27.4))+ assert [B.smooth_wave(phases[p], 0.42) for p in (10, 40, 52)] == pytest.approx([1.0, 1.0, 1.0])++@pytest.mark.parametrize("angle", [-30.0, 20.0])def test_the_chest_moves_along_its_direction(angle) -> None:"""가슴 가운데는 `chest_dir` 쪽으로 간다 — 0 이 바로 위, 음수가 왼쪽 위. 크기는 그대로@@ -562,7 +592,7 @@ def test_the_chest_moves_along_its_direction(angle) -> None:row, col = box[1] + int(cy), box[0] + int(cx)a[row - 24:row + 25, col] = MARK # 위로 가도 그 행에 선이 남게 길게marked = Image.fromarray(a, "RGBA")- got = np.asarray(B.phase_frame(marked, cfg, B.INHALE, anat), np.float64)+ got = np.asarray(B.phase_frame(marked, cfg, INHALE, anat), np.float64)def centre(img):line = img[row, col - 12:col + 13, :3].mean(axis=1)@@ -578,7 +608,7 @@ def test_facing_values_keep_the_head_still() -> None:anat = analyze(src)cut = solid_alpha_bbox(src)[1] + anat.rigid_rowcfg = _cfg(_smooth(chest_tilt=-25, chest_bias=-0.6, chest_dir=-35))- for phase in (0.2, B.INHALE, 0.7):+ for phase in (0.2, INHALE, 0.7):got = B.phase_frame(src, cfg, phase, anat)assert np.asarray(got)[:cut].tobytes() == np.asarray(src)[:cut].tobytes(), \f"위상 {phase}: 몸 방향 값을 줬더니 목·턱 위가 움직였다"@@ -603,7 +633,7 @@ def test_a_figure_cut_by_the_frame_is_not_refused() -> None:src = _bust(margin=0.0)anat = analyze(src)w, h = src.size- for phase in (0.2, B.INHALE, 0.7):+ for phase in (0.2, INHALE, 0.7):got = np.asarray(B.phase_frame(src, _cfg(_smooth()), phase, anat))assert (got[-1, :, 3] == np.asarray(src)[-1, :, 3]).all(), "아래 변이 비었다 — 발바닥이 떴다"for col in (0, w - 1): # 원본이 변까지 찬 행은 그대로 찬다@@ -616,7 +646,7 @@ def test_a_swell_reaching_past_the_canvas_is_still_refused() -> None:pixel 과 같이 조용히 자르지 않고 멈춘다. 기본 모양에서는 생기지 않는다(위 시험)."""src = _bust(margin=0.0)with pytest.raises(SystemExit, match="셀 밖"):- B.phase_frame(src, _cfg(_smooth(depth=0.01, chest_rx=2.5, depth_x=0.05)), B.INHALE)+ B.phase_frame(src, _cfg(_smooth(depth=0.01, chest_rx=2.5, depth_x=0.05)), INHALE)# 가슴 안에 그은 세로선은 depth_x 만큼 가운데에서 바깥으로 밀린다 (실루엣 밖 변은 그대로).probe = _bust(margin=0.12, gradient=False)anat = analyze(probe)@@ -628,8 +658,8 @@ def test_a_swell_reaching_past_the_canvas_is_still_refused() -> None:col = box[0] + int(cx + 0.4 * cfg["chest_rx"] * anat.torso_half)a[row - 4:row + 5, col] = MARKroomy = Image.fromarray(a, "RGBA")- still = np.asarray(B.phase_frame(roomy, {**cfg, "depth_x": 0.0}, B.INHALE, anat), np.float64)- puffed = np.asarray(B.phase_frame(roomy, cfg, B.INHALE, anat), np.float64)+ still = np.asarray(B.phase_frame(roomy, {**cfg, "depth_x": 0.0}, INHALE, anat), np.float64)+ puffed = np.asarray(B.phase_frame(roomy, cfg, INHALE, anat), np.float64)def centre(img):line = img[row, col - 4:col + 5, :3].mean(axis=1)@@ -641,7 +671,7 @@ def test_a_swell_reaching_past_the_canvas_is_still_refused() -> None:def test_a_strain_past_the_cap_is_refused() -> None:with pytest.raises(SystemExit, match="smooth"):- B.phase_frame(_bust(), _cfg(_smooth(depth=0.2)), B.INHALE)+ B.phase_frame(_bust(), _cfg(_smooth(depth=0.2)), INHALE)# ── CLI: 같은 값, 같은 함수 ────────────────────────────────────────@@ -662,11 +692,11 @@ def _blinking(h: int = 120, count: int = 12) -> list[Image.Image]:@pytest.mark.parametrize("raw,flags", [(_smooth(), ["--mode", "smooth", "--depth", "0.025", "--breaths", "2"]),(_smooth(chest_y=0.4, shoulder=0.3, shoulder_lag=0.12, depth_x=0.01, chest_tilt=-20, chest_bias=-0.4,- chest_dir=-25, chest_x=-0.1, chest_bias_y=0.2, chest_flat=0.25),+ chest_dir=-25, chest_x=-0.1, chest_bias_y=0.2, chest_flat=0.25, inhale=0.42),["--mode", "smooth", "--depth", "0.025", "--breaths", "2", "--chest-y", "0.4","--shoulder", "0.3", "--shoulder-lag", "0.12", "--depth-x", "0.01", "--chest-tilt", "-20","--chest-bias", "-0.4", "--chest-dir", "-25", "--chest-x", "-0.1", "--chest-bias-y", "0.2",- "--chest-flat", "0.25"]),+ "--chest-flat", "0.25", "--inhale", "0.42"]),(_smooth(breath_peaks=[3, 9], breaths=None), ["--mode", "smooth", "--depth", "0.025", "--breath-peaks", "3,9"]),({"depth": 0.06, "breaths": 2, "lag": 0.1},["--depth", "0.06", "--breaths", "2", "--lag", "0.1"]),diff --git a/tests/effects/test_breathe_smooth_curator.py b/tests/effects/test_breathe_smooth_curator.pyindex b646372..d6b5e17 100644--- a/tests/effects/test_breathe_smooth_curator.py+++ b/tests/effects/test_breathe_smooth_curator.py@@ -60,7 +60,7 @@ def test_the_mirror_refuses_a_smooth_row_instead_of_drawing_pixel(tmp_path) -> N{"mode": "smooth", "depth": 0.02, "depth_x": 0.01, "breaths": 3, "rigid_row": 40},{"mode": "smooth", "breaths": 2, "chest_y": 0.4, "chest_rx": 0.9, "chest_ry": 0.3,"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},+ "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"])def test_the_round_trip_keeps_a_smooth_sidecar_as_written(tmp_path, sidecar) -> None:diff --git a/tests/video/test_sway_breath.py b/tests/video/test_sway_breath.pyindex 3569e23..52c0aeb 100644--- a/tests/video/test_sway_breath.py+++ b/tests/video/test_sway_breath.py@@ -20,6 +20,7 @@ from sprite_gen.video import sway, sway_inspectfrom tests.effects.test_breathe_smooth import _bustN, BREATHS, DEPTH = 48, 2, 0.025+INHALE = breathe.SMOOTH_SHAPE['inhale'] # the default in-breath shareCHEST = (48.0, 80.0, 30.0, 20.0) # over the bust's chest, in frame pixelsFILES = [f'frame-{k:03d}.png' for k in range(N)]@@ -73,11 +74,12 @@ def test_the_first_cell_every_rest_and_the_close_are_the_breathed_cells(breathedassert abs(dy[0]-dy[-1]) <= np.abs(np.diff(dy)).max() / 4, 'the loop does not close at rest'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, 'breaths': BREATHS}+ 'lag': sway.LAG_DEFAULT, 'lift_px': round(lift(report), 4), 'heading_deg': 0.0, 'inhale': INHALE,+ 'breaths': BREATHS}assert 'freq_hz' not in record and record['frame_ms'] is None-def late_peak(lag, inhale=breathe.INHALE):+def late_peak(lag, inhale=INHALE):"""Where in a breath the part peaks: the phase t whose warped time t - lag sin(pi t) is the chest's peak."""t = inhalefor _ in range(60):@@ -89,19 +91,72 @@ def late_peak(lag, inhale=breathe.INHALE):def test_the_part_peaks_late_by_the_lag_and_reaches_gain_times_the_lift(breathed, lag):report = json.loads((breathed/'breathed'/'breathe.json').read_text())got = answer(breathed, lag=lag, gain=1.0)- w = np.asarray([breathe.smooth_wave(p) for p in report['phases']])+ w = np.asarray([breathe.smooth_wave(p, INHALE) for p in report['phases']])rise = lift(report)part = w - got.dy/rise # the part's own rise, as a share of the chest'sper = N//BREATHS- assert int(np.argmax(w[:per])) == round(breathe.INHALE*per)+ assert int(np.argmax(w[:per])) == round(INHALE*per)assert int(np.argmax(part[:per])) == round(late_peak(lag)*per)- late = np.asarray([breathe.smooth_shoulder_wave(p, lag) for p in report['phases']])+ late = np.asarray([breathe.smooth_shoulder_wave(p, lag, INHALE) for p in report['phases']])assert np.allclose(part, late, atol=1e-12)for gain in (1.0, 2.5):assert answer(breathed, lag=lag, gain=gain).reach == pytest.approx(gain*rise*float(np.max(np.abs(w-late))), rel=1e-12)assert np.all(got.dx == 0) and got.dy[0] == 0+def wave(t, inhale):+ """The breath as the Breathe layer defines it, written out: 0 at rest, 1 at the in-breath's share of the breath, a+ cosine half up and a cosine half down."""+ t %= 1.0+ g = 0.5*t/inhale if t < inhale else 0.5 + 0.5*(t-inhale)/(1-inhale)+ return 0.5 - 0.5*math.cos(2*math.pi*g)++[email protected]('beat', [['--breaths', str(BREATHS)], ['--breath-peaks', '10,34']], ids=['breaths', 'peaks'])+def test_the_part_follows_the_in_breath_share_the_record_says(breathed, tmp_path, beat):+ """A breath whose in-breath takes 0.42 of it, as a breath made elsewhere may: `sprite-gen breathe --inhale 0.42`+ writes the share into its record, and the sway on that record follows that breath — gain x lift x (w - w late) on+ the 0.42 curve, the default's curve a visible way off."""+ rec, out = tmp_path/'breathed', tmp_path/'swayed'+ assert cli.main(['breathe', str(breathed/'plain'), str(rec), '--mode', 'smooth', '--depth', str(DEPTH),+ '--inhale', '0.42', *beat]) == 0+ assert cli.main(['video-sway', '--frames', str(rec), '--out', str(out), '--breathe', str(rec/'breathe.json'),+ '--region', region(), '--lag', '0.15', '--gain', '3']) == 0+ report = json.loads((rec/'breathe.json').read_text())+ record = json.loads((out/'sway.json').read_text())+ assert report['config']['inhale'] == record['drive']['inhale'] == 0.42++ def offset(inhale):+ return np.asarray([3*lift(report)*(wave(p, inhale) - wave(p - 0.15*math.sin(math.pi*p), inhale)) for p in report['phases']])+ assert np.allclose(record['dy_px'], offset(0.42), rtol=0, atol=0.005+1e-9)+ 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."""+ src = breathed/'breathed'+ report = json.loads((src/'breathe.json').read_text())+ assert report['config']['inhale'] == INHALE+ unsaid = tmp_path/'unsaid.json'+ unsaid.write_text(json.dumps(report | {'config': {k: v for k, v in report['config'].items() if k != 'inhale'}}))+ 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+++# The cells the default breath swayed into before a record could say its in-breath share (e18c905): the 48 cells of+# `breathed`, swayed at gain 3, their RGBA bytes in name order.+SWAY_GOLDEN = '3ca59f0ac832805ba2045a6299bb9cf66c7fe5a971fc4e041e9e54a41dd1d03a'+++def test_the_default_breath_sways_the_bytes_it_swayed_before(breathed, tmp_path):+ src, out = breathed/'breathed', tmp_path/'swayed'+ assert cli.main(['video-sway', '--frames', str(src), '--out', str(out), '--breathe', str(src/'breathe.json'),+ '--region', region(), '--gain', '3']) == 0+ assert hashlib.sha256(b''.join(rgba(out/name).tobytes() for name in FILES)).hexdigest() == SWAY_GOLDEN++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),