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 breath sized by width and height minimum and maximum, in the bake, the sidecar, the CLI and the curator

Soohong Kim2e3828ddb77d
diff --git a/sprite_gen/curate/curation.py b/sprite_gen/curate/curation.py
index 2303451..4e7426a 100644
--- a/sprite_gen/curate/curation.py
+++ b/sprite_gen/curate/curation.py
@@ -260,6 +260,13 @@ BREATHE_STRETCH_KEYS = ("start_cell", "loop_cells")
# 쓰지 않는다.
BREATHE_ROUND_KEYS = ("chest_round", "arms_x")
BREATHE_ROUND_MAX = 0.20
+# 가로·세로 최소·최대 (pixel·smooth): 세기(`depth`·`depth_x`) 대신 숨 곡선의 바닥과 꼭대기를 원래 크기 대비 몫으로 바로
+# 적는다 — 최소 0 이면 숨의 그쪽 절반이 원래 크기에 머문다. 가로는 몸통이 가장 크게 숨쉬는 자리에서 넓어지는 몫(pixel: 그
+# 행의 몸통 열, smooth: 가슴 꼭대기의 부풂), 세로는 목 아래 몸통 높이(정규화 기준) 대비 오르는 몫(pixel: 머리 윗선, smooth:
+# 가슴)이다. 음수가 원래보다 좁거나 낮은 쪽이다. 곡선 모양과 박자(breaths·lag·inhale)는 세기 줄과 같고, 넓어질 때 낮아지는
+# 짝(pixel)과 부풀 때 오르는 짝(smooth)도 그대로다. 적지 않은 경계는 0(원래 크기)이고, 세기와 같이 쓰면 거부한다.
+BREATHE_RANGE_KEYS = ("width_min", "width_max", "height_min", "height_max")
+BREATHE_RANGE_MAX = 0.20
BREATHE_ROUND_SHAPE = ("chest_y", "chest_rx", "chest_ry", "chest_tilt", "chest_bias", "chest_x", "chest_bias_y", "inhale")
RETIRED_BREATHE_KEYS = {
@@ -307,7 +314,10 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]
예외는 둥근 가슴 pixel 줄이다 (`chest_round`·`arms_x` 중 하나가 0 보다 큼, `BREATHE_ROUND_KEYS`): 그 줄은 가슴 타원 키
(`BREATHE_ROUND_SHAPE`, 들숨 몫 포함)·숨 꼭대기·토막을 smooth 와 같은 검사로 읽고, 봉투 값(`depth`·`depth_x`·`lag`)과
smooth 만 쓰는 모양 값(어깨·chest_dir·chest_flat)은 거부한다. 반환은 {"chest_round", "arms_x", "breaths", "breath_peaks",
- 가슴 타원 키, "start_cell", "loop_cells", "rigid_row", "axis_x", "torso_half", "anatomy"} 다."""
+ 가슴 타원 키, "start_cell", "loop_cells", "rigid_row", "axis_x", "torso_half", "anatomy"} 다.
+
+ 최소·최대 키(`BREATHE_RANGE_KEYS`)를 하나라도 적은 pixel·smooth 줄은 반환에 `depth`·`depth_x` 대신 네 키가 다 실린다
+ (적지 않은 경계는 0). 세기만 적은 줄은 반환이 이전과 같다."""
if not curation:
return None
entry = curation.get("states", {}).get(state)
@@ -347,7 +357,7 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]
f"조용히 깎지 않는다 — 사이드카를 고쳐라.")
rounded = any(amps.values())
if rounded:
- envelope = sorted(k for k in ("depth", "depth_x", "lag") if raw.get(k) is not None)
+ envelope = sorted(k for k in ("depth", "depth_x", "lag", *BREATHE_RANGE_KEYS) if raw.get(k) is not None)
if envelope:
raise SystemExit(
f"curation: states.{state}.breathe 의 {', '.join(envelope)} 는 봉투 스쿼시의 값이다 — 둥근 가슴 줄"
@@ -394,6 +404,7 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]
raise SystemExit(
f"curation: states.{state}.breathe.{name} = {value!r} 가 범위 [{lo}, {hi}] 밖이다. "
f"조용히 깎지 않는다 — 사이드카를 고쳐라 (큐레이터 컨트롤은 이 범위 안에서만 값을 낸다).")
+ bounds = _breathe_bounds(raw, state)
rigid_row = raw.get("rigid_row")
if rigid_row is not None:
rigid_row = _exact_int("rigid_row", rigid_row, state)
@@ -466,17 +477,52 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]
"rigid_row": rigid_row, "axis_x": axis_x, "torso_half": torso_half,
"anatomy": frozen if isinstance(frozen, dict) else None}
return cfg if mode is None else {"mode": mode, **cfg}
- return {"mode": mode, "depth": depth,
- "depth_x": BREATHE_SMOOTH_DEPTH_X if depth_x is None else depth_x,
+ amplitude = bounds or {"depth": depth, "depth_x": BREATHE_SMOOTH_DEPTH_X if depth_x is None else depth_x}
+ return {"mode": mode, **amplitude,
"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,
+ cfg = {**(bounds or {"depth": depth, "depth_x": depth_x}), "breaths": breaths, "lag": lag,
"rigid_row": rigid_row, "axis_x": axis_x, "torso_half": torso_half,
"anatomy": frozen if isinstance(frozen, dict) else None}
return cfg if mode is None else {"mode": mode, **cfg}
+def _breathe_bounds(raw: dict[str, Any], state: str) -> dict[str, float] | None:
+ """줄의 가로·세로 최소·최대 (`BREATHE_RANGE_KEYS`, 적지 않은 경계는 0) — 하나도 안 적었으면(null 은 생략) None.
+
+ 세기(`depth`·`depth_x`)와 같이 적으면 거부한다: 둘 다 같은 곡선의 크기를 말해 어느 쪽을 따를지 조용히 고를 수 없다.
+ 범위 밖, 수가 아닌 값, 최소가 최대보다 큰 축도 거부한다."""
+ given = {k: raw[k] for k in BREATHE_RANGE_KEYS if raw.get(k) is not None}
+ if not given:
+ return None
+ both = sorted(k for k in ("depth", "depth_x") if raw.get(k) is not None)
+ if both:
+ raise SystemExit(
+ f"curation: states.{state}.breathe 에 세기({', '.join(both)})와 최소·최대({', '.join(sorted(given))})가 같이 "
+ f"있다 — 둘 다 숨의 크기를 말한다. 하나만 적어라 (세기 d 는 최소 -0.9009 d, 최대 +0.9009 d 인 대칭 범위다). "
+ f"조용히 고르지 않는다.")
+ bounds = {}
+ for name in BREATHE_RANGE_KEYS:
+ try:
+ if isinstance(given.get(name), bool): # float(False) 는 0 — 미러처럼 참거짓을 수로 읽지 않는다
+ raise TypeError
+ value = float(given.get(name, 0.0))
+ except (TypeError, ValueError):
+ raise SystemExit(f"curation: states.{state}.breathe.{name} 를 숫자로 못 읽는다: {given[name]!r}")
+ if not -BREATHE_RANGE_MAX <= value <= BREATHE_RANGE_MAX:
+ raise SystemExit(
+ f"curation: states.{state}.breathe.{name} = {given[name]!r} 가 범위 [{-BREATHE_RANGE_MAX}, "
+ f"{BREATHE_RANGE_MAX}] 밖이다. 조용히 깎지 않는다 — 사이드카를 고쳐라.")
+ bounds[name] = value
+ for axis in ("width", "height"):
+ if bounds[f"{axis}_min"] > bounds[f"{axis}_max"]:
+ raise SystemExit(
+ f"curation: states.{state}.breathe.{axis}_min {bounds[f'{axis}_min']:g} 가 {axis}_max "
+ f"{bounds[f'{axis}_max']:g} 보다 크다 — 숨의 바닥이 꼭대기 위에 있을 수 없다 (적지 않은 경계는 0).")
+ return bounds
+
+
def edit_index(curation: dict[str, Any] | None, state: str, index: int) -> int:
"""인스턴스의 편집(변형/픽셀) truth 인덱스 — 링크된 복제는 원본을 가리킨다.
diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.py
index 6994d23..9534331 100644
--- a/sprite_gen/effects/breathe.py
+++ b/sprite_gen/effects/breathe.py
@@ -122,6 +122,12 @@ def wave(t: float) -> float:
return 0.86 * math.sin(2 * math.pi * t) + 0.14 * math.sin(4 * math.pi * t)
+# `wave` 의 꼭대기 — 곡선이 홀함수라 바닥은 그 음수다. 세기 d 의 숨은 이 곡선에 d 를 곱해 바닥 -WAVE_PEAK·d 에서 꼭대기
+# +WAVE_PEAK·d 를 오가고, 최소·최대 키는 같은 곡선의 바닥과 꼭대기를 쓴 값에 놓는다. 식(wave' = 0 인 cos 2πt 가 이차식의
+# 근)으로 풀지 않고 수로 적는다 — 미러(breathe.js)가 다른 libm 으로 끝자리가 다른 값을 내지 않게.
+WAVE_PEAK = 0.9008738286182177
+
+
def smoothstep(a: float, b: float, x: float) -> float:
if b <= a:
return 1.0 if x >= b else 0.0
@@ -172,11 +178,66 @@ def protect(anat: Anatomy):
return lambda x: _smoothstep_array(t0, t1, np.abs(np.asarray(x) - cx))
+def envelope_peak(anat: Anatomy) -> float:
+ """봉투의 가장 큰 값 — 숨이 가장 크게 걸리는 행의 env (보통 1)."""
+ env, _ = envelope(anat)
+ return max(env(j / max(1, anat.height - 1)) for j in range(anat.height))
+
+
def row_strain(anat: Anatomy, depth: float) -> float:
- """행당 최대 변형 — MAX_ROW_STRAIN 초과 여부 판정용 (관측 가능하게 노출)."""
- env, norm = envelope(anat)
- peak = max(env(j / max(1, anat.height - 1)) for j in range(anat.height))
- return depth * norm * peak
+ """행당 최대 변형 — MAX_ROW_STRAIN 초과 여부 판정용 (관측 가능하게 노출). 세기 줄의 판정이다: 세기 d 의 실제 극값은
+ WAVE_PEAK·d 라 이 값은 극값보다 1/WAVE_PEAK 배 넉넉하게 막는다 (그대로 둔다 — 옛 줄의 판정이 바뀌지 않게)."""
+ _, norm = envelope(anat)
+ return depth * norm * envelope_peak(anat)
+
+
+# ── 숨의 크기: 세기 또는 최소·최대 ─────────────────────────────────
+#
+# 세기(`depth`·`depth_x`)는 곡선 `wave` 에 곱하는 진폭이고, 최소·최대(`width_min`·`width_max`·`height_min`·`height_max`)는 같은
+# 곡선의 바닥과 꼭대기를 원래 크기 대비 몫으로 바로 적은 것이다. 굽기는 둘 다 축마다 이득 계수 (B, A) 로 읽어 행 u·위상 t 의
+# 이득을 g = (B + A·wave(t - lag·u'))·env(u) 로 쓴다 — 세기 줄은 B = 0, A = d·norm 이라 옛 식 d·norm·wave·env 와 같은 연산이다.
+# pixel 의 짝: 곡선 꼭대기에서 가로 최대·세로 최소(넓어질 때 낮아진다), 바닥에서 가로 최소·세로 최대.
+# 가로 몫 = 몸통 열이 가장 크게 숨쉬는 행(env 최대)에서 넓어지는 몫 = g 그 자체
+# 세로 몫 = 목 아래 몸통(기준 행 수) 대비 머리 윗선이 오르는 몫 ≈ -Σg / 기준 행 수 = -(B + A·wave)/norm
+# smooth 의 짝: 쉼(곡선 0)에서 최소, 들숨 꼭대기(곡선 1)에서 최대 — 가슴이 부풀며 오른다.
+
+def _bounds(cfg: dict) -> tuple[tuple[float, float], tuple[float, float]] | None:
+ """((가로 최소, 최대), (세로 최소, 최대)) — 줄이 최소·최대 키로 적혔으면(정규화가 네 키를 다 싣는다). 세기 줄은 None."""
+ if cfg.get("width_min") is None:
+ return None
+ return ((float(cfg["width_min"]), float(cfg["width_max"])),
+ (float(cfg["height_min"]), float(cfg["height_max"])))
+
+
+def pixel_gains(anat: Anatomy, cfg: dict) -> tuple[tuple[float, float], tuple[float, float]]:
+ """pixel 봉투의 이득 계수 ((세로 B, A), (가로 B, A)) — 행 u·위상 t 의 이득은 (B + A·wave(t - lag·u'))·env(u), 가로 배율
+ 1 + g, 세로 배율 1 / (1 + g). 세기 줄은 (0, d·norm) 이라 옛 굽기와 같은 연산이고, 최소·최대 줄은 곡선의 꼭대기
+ (wave = WAVE_PEAK)와 바닥(-WAVE_PEAK)에서 쓴 값이 나오게 둔다."""
+ _, norm = envelope(anat)
+ bounds = _bounds(cfg)
+ if bounds is None:
+ depth, depth_x = _pixel_depths(cfg)
+ return (0.0, depth * norm), (0.0, (depth if depth_x is None else depth_x) * norm)
+ (w_lo, w_hi), (h_lo, h_hi) = bounds
+ peak = envelope_peak(anat)
+ across = (0.0, 0.0) if peak <= 0.0 else ((w_lo + w_hi) / (2.0 * peak), (w_hi - w_lo) / (2.0 * WAVE_PEAK * peak))
+ return (-norm * (h_lo + h_hi) / 2.0, norm * (h_hi - h_lo) / (2.0 * WAVE_PEAK)), across
+
+
+def breathe_range(anat: Anatomy, cfg: dict) -> dict[str, tuple[float, float]]:
+ """줄의 숨이 오가는 가로·세로 (최소, 최대) — 최소·최대 키의 단위로. 최소·최대 줄은 쓴 값 그대로, 세기 줄은 그 세기의
+ 극값이다 (pixel: 세로 ∓WAVE_PEAK·depth, 가로 ∓WAVE_PEAK·depth_x·norm·봉투 최대; smooth: 쉼 0 에서 depth·depth_x).
+ `sprite-gen breathe` 가 breathe.json `range` 에 싣는다 — 세기로 구운 판을 최소·최대로 옮길 때 읽는 수다."""
+ bounds = _bounds(cfg)
+ if bounds is not None:
+ return {"width": bounds[0], "height": bounds[1]}
+ if breathe_mode(cfg) == "smooth":
+ depth, swell = _smooth_depths(cfg)
+ return {"width": (0.0, swell), "height": (0.0, depth)}
+ _, norm = envelope(anat)
+ depth, depth_x = _pixel_depths(cfg)
+ across = (depth if depth_x is None else depth_x) * WAVE_PEAK * norm * envelope_peak(anat)
+ return {"width": (-across, across), "height": (-depth * WAVE_PEAK, depth * WAVE_PEAK)}
# ── 외곽선 1px 다듬기 ───────────────────────────────────────────────
@@ -314,8 +375,8 @@ def _thin_outline_pass(rgba: np.ndarray) -> int:
# ── 워프 ────────────────────────────────────────────────────────────
-def _warp(frame: Image.Image, anat: Anatomy, depth: float, lag: float, t: float,
- depth_x: float | None = None) -> Image.Image:
+def _warp(frame: Image.Image, anat: Anatomy, lag: float, t: float,
+ gains: tuple[tuple[float, float], tuple[float, float]]) -> Image.Image:
"""한 위상 t 의 프레임 — 캔버스 크기 불변, 발바닥 고정.
세로는 행 국소 배율을 누적해 각 원본 행이 출력에서 몇 행을 차지하는지 정하고,
@@ -323,9 +384,9 @@ def _warp(frame: Image.Image, anat: Anatomy, depth: float, lag: float, t: float,
연산이라 출력이 정수 도트다. 한 행의 사상은 배열 하나로 만든다 — 밀도 누적합은 차례대로
더하고(`np.cumsum`), 출력 열마다의 원본 열은 축 기준 경계를 넘은 개수다(`searchsorted`).
- `depth_x` 는 가로 성분의 독립 진폭이다 (maintainer 요청 2026-07-30 — 가로/세로 분리).
- None 이면 depth 를 따른다(레거시와 바이트 동일), 0 이면 가로 사상이 전 위상
- 항등이다. 파형·봉투·지연은 두 축이 공유한다 — 축마다 다른 건 스칼라뿐이다."""
+ `gains` 는 축마다 이득 계수 ((세로 B, A), (가로 B, A)) — `pixel_gains`. 가로 성분은 세로와 따로다 (maintainer 요청
+ 2026-07-30 — 가로/세로 분리): 가로 (0, 0) 이면 가로 사상이 전 위상 항등이다. 파형·봉투·지연은 두 축이 공유한다 —
+ 축마다 다른 건 계수뿐이다."""
box = solid_alpha_bbox(frame)
if not box:
return frame.copy()
@@ -335,22 +396,22 @@ def _warp(frame: Image.Image, anat: Anatomy, depth: float, lag: float, t: float,
anchor_x = box[0] + anat.axis_x
baseline = box[3]
- env, norm = envelope(anat)
+ env, _ = envelope(anat)
keep_cols = 1.0 - protect(anat)(np.arange(width)) # 열마다 늘어나는 몫 — 행마다 같다
ru = anat.rigid_u
- dx_amp = depth if depth_x is None else depth_x
+ down, across = gains
- def gain(u: float, d: float) -> float:
+ def gain(u: float, k: tuple[float, float]) -> float:
e = env(u)
if e <= 0.0:
return 0.0
- return d * norm * wave(t - lag * min(1.0, u / max(1e-6, ru))) * e
+ return (k[0] + k[1] * wave(t - lag * min(1.0, u / max(1e-6, ru)))) * e
# 세로 누적 — j=0 이 정수리
heights: list[float] = []
acc = 0.0
for j in range(height):
- g = gain(1.0 - j / max(1, height - 1), depth)
+ g = gain(1.0 - j / max(1, height - 1), down)
acc += 1.0 if g == 0.0 else 1.0 / (1.0 + g)
heights.append(acc)
total = max(1, math.floor(acc + 0.5))
@@ -369,7 +430,7 @@ def _warp(frame: Image.Image, anat: Anatomy, depth: float, lag: float, t: float,
prev = cur
if reps == 0:
continue
- g = gain(u, dx_amp) # 가로 성분 — 독립 진폭 (depth_x)
+ g = gain(u, across) # 가로 성분 — 독립 계수 (depth_x, width_*)
if reps != 1:
deformed = True # 행 복제/삭제 = 세로 변형이 실재
if g == 0.0:
@@ -443,12 +504,12 @@ def _clip_advice(frame: Image.Image, off: dict[str, int]) -> str:
sides, outer = own_border(np.asarray(frame.convert("RGBA"))[..., 3] != 0)
crossed = [s for s in FRAME_SIDES if off[s] and s in sides]
if not crossed:
- return "셀 여백을 늘리거나 depth 를 낮춰라."
+ return "셀 여백을 늘리거나 숨의 크기(depth, 또는 최소·최대)를 줄여라."
covers = ", ".join(f"{SIDE_NAMES[s]} 변 바깥 줄 {outer[s]} px" for s in crossed)
return (f"그림이 {covers} 를 덮는다 — 그 변 길이의 {BORDER_MIN_FRACTION * 100:g} % 이상이라 그림 자체의 테두리로 "
f"읽힌다. 원래 화면에 잘린 그림(큰 일러·영상 칸)이면 mode smooth(`--mode smooth`)로 구워라 — 머리와 "
f"화면 변이 제자리에 있다. 여백을 붙여 굽고 잘라 내지 마라 — 밀려 나간 만큼 조용히 잃는다. 도트 "
- f"스프라이트면 셀 여백을 늘리거나 depth 를 낮춰라.")
+ f"스프라이트면 셀 여백을 늘리거나 숨의 크기(depth, 또는 최소·최대)를 줄여라.")
# ── smooth 모드 (큰 일러·영상 프레임) ───────────────────────────────
@@ -573,9 +634,27 @@ def flat_cos2(r: np.ndarray, flat: float = 0.0) -> np.ndarray:
def smooth_lift(anat: Anatomy, cfg: dict) -> float:
- """smooth 의 가슴이 들숨 꼭대기에서 오르는 px — depth × 기준 높이. Sway 레이어가 숨 박자를 받을 때(`video-sway
- --breathe`) 같은 식으로 그 크기를 읽는다."""
- return float(cfg.get("depth") if cfg.get("depth") is not None else DEFAULT_SMOOTH_DEPTH) * anat.basis_rows
+ """smooth 의 가슴이 쉼에서 들숨 꼭대기까지 오르는 px — depth × 기준 높이 (최소·최대 줄은 (height_max - height_min) ×
+ 기준 높이). Sway 레이어가 숨 박자를 받을 때(`video-sway --breathe`)와 박자 고르기(`--avoid-region`)가 같은 식으로 그
+ 크기를 읽는다 — 둘 다 쉼에서 움직인 만큼을 본다."""
+ return _smooth_amounts(anat, cfg)[1]
+
+
+def _smooth_depths(cfg: dict) -> tuple[float, float]:
+ """smooth 세기 줄의 (depth, depth_x) — 생략은 기본값."""
+ return (float(cfg.get("depth") if cfg.get("depth") is not None else DEFAULT_SMOOTH_DEPTH),
+ float(cfg.get("depth_x") if cfg.get("depth_x") is not None else DEFAULT_SMOOTH_DEPTH_X))
+
+
+def _smooth_amounts(anat: Anatomy, cfg: dict) -> tuple[float, float, float, float]:
+ """smooth 의 (쉼의 오름 px, 쉼에서 꼭대기까지 오름 px, 쉼의 부풂, 쉼에서 꼭대기까지 부풂) — 곡선 c 에서 가슴은
+ 쉼 + c × 폭만큼 오르고 부푼다. 세기 줄은 쉼이 0 이고 폭이 depth × 기준 높이·depth_x 다 (위상 0 이 원본 바이트)."""
+ bounds = _bounds(cfg)
+ if bounds is None:
+ depth, swell = _smooth_depths(cfg)
+ return 0.0, depth * anat.basis_rows, 0.0, swell
+ (w_lo, w_hi), (h_lo, h_hi) = bounds
+ return h_lo * anat.basis_rows, (h_hi - h_lo) * anat.basis_rows, w_lo, w_hi - w_lo
def _smoothstep_array(a: float, b: float, x: np.ndarray) -> np.ndarray:
@@ -614,16 +693,20 @@ def smooth_displacement(anat: Anatomy, cfg: dict, x: np.ndarray, y: np.ndarray,
across = np.minimum(1.0, np.abs(np.abs(x - axis) - SHOULDER_X * torso) / (SHOULDER_RX * torso))
down = np.minimum(1.0, np.abs(y - smooth_shoulder_row(anat)) / (1.4 * band)) # 양 어깨 높이가 달라도
w_shoulder = np.cos(0.5 * np.pi * down) ** 2 * np.cos(0.5 * np.pi * across) ** 2
- lift = smooth_lift(anat, cfg)
- swell = float(cfg.get("depth_x") if cfg.get("depth_x") is not None else DEFAULT_SMOOTH_DEPTH_X)
- # 어깨가 켜지는 구간은 오르는 양의 8배 이상 — 더 짧으면 그 사이가 행당 상한 넘게 눌린다.
- quick = max(0.15 * band, 8.0 * shape["shoulder"] * lift)
+ rest, lift, rest_swell, swell = _smooth_amounts(anat, cfg)
+ # 어깨가 켜지는 구간은 오르는 양(쉼과 꼭대기 중 큰 쪽)의 8배 이상 — 더 짧으면 그 사이가 행당 상한 넘게 눌린다.
+ quick = max(0.15 * band, 8.0 * shape["shoulder"] * (lift if rest == 0.0 else max(abs(rest), abs(rest + lift))))
u = np.clip((y - top) / (quick + (band - quick) * neckness), 0.0, 1.0) if band > quick else \
np.clip((y - top) / quick, 0.0, 1.0)
guard = u * u * (3.0 - 2.0 * u) * (1.0 - _smoothstep_array(height - 0.5 * band, height, y))
rise = lift * (chest * w_chest * math.cos(heading) + shape["shoulder"] * shoulders * w_shoulder * (1.0 - w_chest))
forward = lift * chest * w_chest * math.sin(heading)
puff = swell * chest * w_chest
+ if rest != 0.0 or rest_swell != 0.0:
+ # 최소가 0 이 아닌 줄 — 쉼(곡선 0)에서도 가슴과 어깨가 그만큼 올라(내려) 있고 부풀어(줄어) 있다.
+ rise = rise + rest * (w_chest * math.cos(heading) + shape["shoulder"] * w_shoulder * (1.0 - w_chest))
+ forward = forward + rest * w_chest * math.sin(heading)
+ puff = puff + rest_swell * w_chest
return (puff * (x - px) + forward) * guard, (puff * (y - py) - rise) * guard
@@ -636,7 +719,19 @@ def smooth_strain(anat: Anatomy, cfg: dict) -> tuple[float, float]:
grid = _content_grid(anat)
if grid is None:
return 0.0, 1.0
- return _strain(*smooth_displacement(anat, cfg, *grid, 1.0, 1.0))
+ return _worst(_strain(*smooth_displacement(anat, cfg, *grid, c, c)) for c in _smooth_ends(anat, cfg))
+
+
+def _smooth_ends(anat: Anatomy, cfg: dict) -> tuple[float, ...]:
+ """변형을 잴 곡선 값 — 들숨 꼭대기(1), 최소가 0 이 아닌 줄은 쉼(0)도. 장은 곡선에 대해 일차라 두 끝 밖에서 더 크지 않다."""
+ rest, _, rest_swell, _ = _smooth_amounts(anat, cfg)
+ return (1.0,) if rest == 0.0 and rest_swell == 0.0 else (0.0, 1.0)
+
+
+def _worst(strains) -> tuple[float, float]:
+ """(행당 최대 변형, 최소 면적비) 여럿 중 가장 나쁜 것 — 큰 변형, 작은 면적비."""
+ found = list(strains)
+ return max(s for s, _ in found), min(a for _, a in found)
def _content_grid(anat: Anatomy) -> tuple[np.ndarray, np.ndarray] | None:
@@ -712,8 +807,9 @@ def _smooth_warp(frame: Image.Image, anat: Anatomy, cfg: dict, t: float,
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 — 원본 그대로 (바이트)
+ rest, _, rest_swell, _ = _smooth_amounts(anat, cfg)
+ if not box or (chest == 0.0 and shoulders == 0.0 and rest == 0.0 and rest_swell == 0.0):
+ return rgba # 위상 0 — 원본 그대로 (바이트; 최소가 0 인 줄)
if anat.origin is not None:
# 줄의 기준 칸에서 잰 자리 — 해부가 한 벌이듯 경계·축·발바닥의 자리도 한 벌이다.
# 영상 루프는 머리 윗선이 칸마다 흔들려, 칸마다 다시 놓으면 경계 위 행이 움직인다.
@@ -786,12 +882,14 @@ def _smooth_refusals(cfg: dict, anat: Anatomy, pins: "Pins | None" = None) -> No
if pins is None or grid is None:
strain, area = smooth_strain(anat, cfg)
else:
- strain, area = _pinned_strain(anat, pins, *smooth_displacement(anat, cfg, *grid, 1.0, 1.0))
+ strain, area = _worst(_pinned_strain(anat, pins, *smooth_displacement(anat, cfg, *grid, c, c))
+ for c in _smooth_ends(anat, cfg))
if strain > MAX_ROW_STRAIN or area < 1.0 - MAX_ROW_STRAIN:
+ size = "depth·depth_x" if _bounds(cfg) is None else "height_*·width_*"
raise SystemExit(
f"breathe(smooth): 행당 변형 {strain:.3f}·최소 면적비 {area:.3f} — 상한 {MAX_ROW_STRAIN} 을 넘는다. "
f"가슴·어깨가 오르는 만큼을 목 밴드와 가슴 무게가 못 받는다 (강체 경계 {anat.rigid_row}/{anat.height}, "
- f"기준 {anat.basis_rows}행). depth·depth_x 를 낮추거나 chest_rx·chest_ry 를 넓혀라. 조용히 깎지 않는다.")
+ f"기준 {anat.basis_rows}행). {size} 를 줄이거나 chest_rx·chest_ry 를 넓혀라. 조용히 깎지 않는다.")
def _pinned_strain(anat: Anatomy, pins: "Pins", dx: np.ndarray, dy: np.ndarray) -> tuple[float, float]:
@@ -1743,16 +1841,20 @@ def _row_refusals(cfg: dict, anat: Anatomy, pins: Pins | None = None) -> None:
if pixel_round(cfg):
_round_refusals(cfg, anat, pins)
return
- depth, depth_x = _pixel_depths(cfg)
- for axis, d in (("depth", depth), ("depth_x", depth_x)):
- if d is None:
- continue
- strain = row_strain(anat, d)
+ if _bounds(cfg) is None:
+ depth, depth_x = _pixel_depths(cfg)
+ strains = [(axis, row_strain(anat, d)) for axis, d in (("depth", depth), ("depth_x", depth_x)) if d is not None]
+ else:
+ # 최소·최대 줄은 극값 그대로 잰다 — 이득 (B ± A·WAVE_PEAK) 의 큰 쪽이 봉투 최대 행에서 걸린다.
+ peak = envelope_peak(anat)
+ strains = [(f"{axis}_min·{axis}_max", (abs(b) + abs(a) * WAVE_PEAK) * peak)
+ for axis, (b, a) in zip(("height", "width"), pixel_gains(anat, cfg))]
+ for axis, strain in strains:
if strain > MAX_ROW_STRAIN:
raise SystemExit(
f"breathe: 행당 변형({axis}) {strain:.3f} > 상한 {MAX_ROW_STRAIN} — 변형 구간이 너무 "
f"좁다 (강체 경계 {anat.rigid_row}/{anat.height}, 정규화 기준 {anat.basis_row}). "
- f"{axis} 를 낮추거나 rigid_row 를 올려라. 조용히 깎지 않는다.")
+ f"{axis} 를 줄이거나 rigid_row 를 올려라. 조용히 깎지 않는다.")
def _bake_phase(frame: Image.Image, cfg: dict, phase: float, anat: Anatomy, pins: Pins | None = None) -> Image.Image:
@@ -1768,8 +1870,7 @@ def _bake_phase_pieces(frame: Image.Image, cfg: dict, phase: float, anat: Anatom
return _smooth_warp(frame, anat, cfg, phase, pins), [], []
if pixel_round(cfg):
return _round_warp(frame, anat, cfg, phase, pins)
- depth, depth_x = _pixel_depths(cfg)
- return _warp(frame, anat, depth, float(cfg.get("lag", DEFAULT_LAG)), phase, depth_x=depth_x), [], []
+ return _warp(frame, anat, float(cfg.get("lag", DEFAULT_LAG)), phase, pixel_gains(anat, cfg)), [], []
def bake_breathe_sequence(images: list[Image.Image], cfg: dict, anat: Anatomy | None = None,
@@ -1858,6 +1959,19 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--depth-x", type=float, default=None,
help=f"sideways swell (pixel: follows --depth; smooth: the chest puffs out by this share, "
f"default {DEFAULT_SMOOTH_DEPTH_X})")
+ size = parser.add_argument_group(
+ "the breath's size as its extremes, shares of the original (instead of --depth and --depth-x; a bound left out "
+ "is 0, the original size; pixel: wider while lower, smooth: the chest puffs as it rises)")
+ size.add_argument("--width-min", type=float, default=None,
+ help="the narrowest the body gets, a share of its width where it breathes most (pixel: the "
+ "torso's columns on the fullest row; smooth: the chest's swell at its peak); 0 never "
+ "narrower than the original")
+ size.add_argument("--width-max", type=float, default=None, help="the widest, the same share (-0.2..0.2)")
+ size.add_argument("--height-min", type=float, default=None,
+ help="the lowest, a share of the body's height below the neck (pixel: the head's top line; "
+ "smooth: the chest), negative down")
+ size.add_argument("--height-max", type=float, default=None,
+ help="the highest, the same share; 0 never higher than the original")
parser.add_argument("--breaths", type=int, default=None, help="breaths per loop (default 1)")
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,
@@ -1970,7 +2084,8 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =
reference: str | None = None, loop_cells: int | None = None, start_cell: int | None = None,
chest_round: float | None = None, arms_x: float | None = None, hold_mask: str | None = None,
props_mask: str | None = None, axis_x: int | None = None, torso_half: int | None = None,
- props_behind_mask: str | None = None, props_groups: str | None = None) -> int:
+ props_behind_mask: str | None = None, props_groups: str | None = None, width_min: float | None = None,
+ width_max: float | None = None, height_min: float | None = None, height_max: float | None = None) -> int:
"""프레임 폴더에 Breathe 레이어를 굽는다 — 큐레이션 사이드카 `breathe` 와 같은 값, 같은 정규화,
같은 굽기(`bake_breathe_sequence`). 영상 루프의 칸처럼 큐레이션 런이 아닌 프레임이 이 길로 온다.
@@ -1982,7 +2097,9 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =
꼭대기의 가로 px, 칸마다 고정 칸 밑으로 가려진 칸 수(`hidden`)와 떠난 자리로 늘어나 지어낸 칸 수(`filled`), 그 최대
(`hidden_max`·`filled_max`)가 실리고, 가려진 칸이나 지어낸 칸이 있는 조각마다 경고 줄이 나온다. `props_behind_mask` 는 몸 뒤
물건의 같은 기록(`props_behind`)이다. `props_groups` 가 colour 면 두 마스크의 한 색 조각들이 같은 칸만큼 가고, 조각마다 그 색
- (`colour`)이 실린다."""
+ (`colour`)이 실린다. `width_min`·`width_max`·`height_min`·`height_max` 는 세기(`depth`·`depth_x`) 대신 숨의 극값이고,
+ breathe.json 의 `range` 는 어느 줄이든 그 극값을 최소·최대 키의 단위로 싣는다 (`breathe_range` — 세기로 구운 판을
+ 최소·최대로 옮길 때 그 수를 그대로 쓴다)."""
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),
@@ -1991,7 +2108,8 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =
("chest_x", chest_x), ("chest_bias_y", chest_bias_y), ("chest_flat", chest_flat),
("inhale", inhale), ("breath_peaks", breath_peaks), ("loop_cells", loop_cells),
("start_cell", start_cell), ("chest_round", chest_round), ("arms_x", arms_x),
- ("axis_x", axis_x), ("torso_half", torso_half))
+ ("axis_x", axis_x), ("torso_half", torso_half), ("width_min", width_min),
+ ("width_max", width_max), ("height_min", height_min), ("height_max", height_max))
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 의 것이다 — 손 상자 없이는 읽지 않는다")
@@ -2038,8 +2156,10 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =
for line in piece_warnings(record, flag):
print(f"breathe: warning: {line}", file=sys.stderr)
# 다 굽고 나서 한 번에 내놓는다 — 굽기가 중간에 거부되면 반쯤 찬 폴더를 남기지 않는다(frames.folder.publish).
+ span = {} if pixel_round(cfg) else {"range": {k: list(v) for k, v in breathe_range(anat, cfg).items()}}
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} | span
+ | ({} if beat is None else {"beat": beat})
| ({} if held is None else {"reference": held})
| ({} if kept is None else {"hold": kept})
| ({} if grips is None else {"props": grips})
@@ -2047,6 +2167,9 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =
if pixel_round(cfg):
print(f"breathe: {len(images)} frames, pixel round chest, chest_round {cfg['chest_round']}, arms_x {cfg['arms_x']}, "
f"breaths {cfg['breaths']} -> {out_dir}")
+ elif _bounds(cfg) is not None:
+ print(f"breathe: {len(images)} frames, {breathe_mode(cfg)}, width {cfg['width_min']}..{cfg['width_max']}, "
+ f"height {cfg['height_min']}..{cfg['height_max']}, breaths {cfg['breaths']} -> {out_dir}")
else:
print(f"breathe: {len(images)} frames, {breathe_mode(cfg)}, depth {cfg['depth']}, "
f"breaths {cfg['breaths']} -> {out_dir}")
diff --git a/sprite_gen/serve/curator/curator.css b/sprite_gen/serve/curator/curator.css
index d3e97fd..cccddbe 100644
--- a/sprite_gen/serve/curator/curator.css
+++ b/sprite_gen/serve/curator/curator.css
@@ -1289,11 +1289,13 @@ body.show-grid .stage { background-image: none; background-color: #eef0f3; }
.breathe-bar { display: inline-flex; align-items: center; gap: 6px; margin-left: 8px; }
.breathe-auto { padding: 2px 7px; font-size: 11px; border: 1px solid var(--line); border-radius: 4px; background: transparent; color: inherit; cursor: pointer; }
.breathe-auto:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }
-.breathe-bar select { padding: 2px 4px; font-size: 11px; border: 1px solid var(--line); border-radius: 4px; background: transparent; color: inherit; }
.breathe-count { display: inline-flex; align-items: center; gap: 3px; font-size: 11px; color: var(--muted); }
.breathe-count input { width: 44px; padding: 2px 4px; font-size: 11px; border: 1px solid var(--line); border-radius: 4px; text-align: center; }
.breathe-count button { padding: 2px 7px; font-size: 12px; border: 1px solid var(--line); border-radius: 4px; background: transparent; cursor: pointer; }
.breathe-count button:hover { border-color: var(--accent); color: var(--accent); }
+.breathe-range { display: inline-flex; align-items: center; gap: 8px; font-size: 11px; color: var(--muted); }
+.breathe-range > span { display: inline-flex; align-items: center; gap: 3px; }
+.breathe-range input { width: 50px; padding: 2px 4px; font-size: 11px; border: 1px solid var(--line); border-radius: 4px; text-align: center; }
.breathe-fit-badge { color: #b45309; font-size: 11px; font-weight: 600; margin-left: 2px; }
/* 줄 fps 스텝퍼 — 전체 재생 속도 (프레임별 시간은 복제가 담당) */
.fps-stepper { display: inline-flex; align-items: center; gap: 3px; font-size: 11px; color: var(--fg-dim, #64748b); }
diff --git a/sprite_gen/serve/curator/src/breathe.js b/sprite_gen/serve/curator/src/breathe.js
index a2f214c..d5a3f6a 100644
--- a/sprite_gen/serve/curator/src/breathe.js
+++ b/sprite_gen/serve/curator/src/breathe.js
@@ -3,7 +3,8 @@
// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
//
// 호흡은 프레임 선택(깜빡임)과 직교하는 변조 레이어다 (maintainer 확정 2026-07-18).
-// truth = entries[state].breathe = {depth, breaths, lag, rigid_row, anatomy} | null.
+// truth = entries[state].breathe = {depth, breaths, lag, rigid_row, anatomy} | null — 숨의 크기는 세기(depth·depth_x)
+// 대신 가로·세로 최소·최대(width_min·width_max·height_min·height_max)로 적을 수도 있다 (둘을 같이 쓰면 굽기가 거부).
// `mode: "smooth"` 줄은 미러하지 않는다 — breatheComposite 가 거부한다 (아래).
//
// **검출은 여기서 하지 않는다** (maintainer 결정 2026-07-25 b안). 목 병목·대칭 눈쌍·부속
@@ -23,6 +24,11 @@ const BREATHE_MAX_ROW_STRAIN = 0.25;
const BREATHE_DEPTH_MAX = 0.20;
const BREATHE_BREATHS_MAX = 8;
const BREATHE_LAG_MAX = 0.45;
+// 숨 곡선의 꼭대기와 최소·최대 키 — 파이썬 breathe.WAVE_PEAK·curation.BREATHE_RANGE_KEYS·BREATHE_RANGE_MAX 미러.
+// 꼭대기는 식으로 풀지 않고 같은 수를 적는다 (Math.acos 와 libm 이 끝자리에서 갈릴 수 있다).
+const BREATHE_WAVE_PEAK = 0.9008738286182177;
+const BREATHE_RANGE_KEYS = ["width_min", "width_max", "height_min", "height_max"];
+const BREATHE_RANGE_MAX = 0.20;
// 그림 자체의 테두리 — 파이썬 frames.extract.FRAME_SIDES·BORDER_MIN_FRACTION 미러 (거절 문구가 쓴다).
const BREATHE_SIDES = ["top", "left", "right"];
const BREATHE_SIDE_NAMES = { top: "위", left: "왼쪽", right: "오른쪽" };
@@ -84,6 +90,59 @@ function breatheEnvelope(anat) {
return { env, ru, norm: total > 1e-6 ? basisRows / total : 0 };
}
+// 봉투의 가장 큰 값 (파이썬 envelope_peak 미러).
+function breatheEnvelopePeak(anat, env) {
+ let peak = 0;
+ for (let j = 0; j < anat.height; j++) peak = Math.max(peak, env(j / Math.max(1, anat.height - 1)));
+ return peak;
+}
+
+// 줄이 최소·최대 키로 적혔나 — 하나라도 있으면 (null 은 생략). 적지 않은 경계는 0 (파이썬 state_breathe 와 같다).
+function breatheHasBounds(cfg) {
+ return !!cfg && BREATHE_RANGE_KEYS.some((k) => cfg[k] != null);
+}
+
+function breatheBounds(cfg) {
+ if (!breatheHasBounds(cfg)) return null;
+ const v = (k) => (cfg[k] == null ? 0 : Number(cfg[k]));
+ return { width: [v("width_min"), v("width_max")], height: [v("height_min"), v("height_max")] };
+}
+
+// pixel 봉투의 이득 계수 [[세로 B, A], [가로 B, A]] — 행·위상의 이득은 (B + A·wave)·env (파이썬 pixel_gains 미러,
+// 같은 연산 순서). 세기 줄은 [0, d·norm] 이라 옛 식 d·norm·wave·env 와 같은 바이트다.
+function breatheGains(anat, cfg) {
+ const { env, norm } = breatheEnvelope(anat);
+ const bounds = breatheBounds(cfg);
+ if (!bounds) {
+ const depth = cfg.depth || 0.06;
+ const depthX = cfg.depth_x == null ? depth : Number(cfg.depth_x);
+ return [[0, depth * norm], [0, depthX * norm]];
+ }
+ const [wLo, wHi] = bounds.width;
+ const [hLo, hHi] = bounds.height;
+ const peak = breatheEnvelopePeak(anat, env);
+ const across = peak <= 0 ? [0, 0]
+ : [(wLo + wHi) / (2.0 * peak), (wHi - wLo) / (2.0 * BREATHE_WAVE_PEAK * peak)];
+ return [[-norm * (hLo + hHi) / 2.0, norm * (hHi - hLo) / (2.0 * BREATHE_WAVE_PEAK)], across];
+}
+
+// 줄의 숨이 오가는 {width: [최소, 최대], height: [최소, 최대]} — 최소·최대 키의 단위 (파이썬 breathe_range 미러).
+// 세기만 적힌 줄을 편집기가 네 손잡이로 보여 줄 때 읽는다. pixel 세기 줄의 가로는 해부가 있어야 안다 (없으면 null).
+function breatheRange(anat, cfg) {
+ const bounds = breatheBounds(cfg);
+ if (bounds) return bounds;
+ if (cfg.mode === "smooth") {
+ return { width: [0, cfg.depth_x == null ? 0.028 : Number(cfg.depth_x)],
+ height: [0, cfg.depth == null ? 0.0085 : Number(cfg.depth)] };
+ }
+ if (!anat) return null;
+ const { env, norm } = breatheEnvelope(anat);
+ const depth = cfg.depth || 0.06;
+ const across = (cfg.depth_x == null ? depth : Number(cfg.depth_x)) * BREATHE_WAVE_PEAK * norm
+ * breatheEnvelopePeak(anat, env);
+ return { width: [-across, across], height: [-depth * BREATHE_WAVE_PEAK, depth * BREATHE_WAVE_PEAK] };
+}
+
// 부속 보호 가중 — 1 이면 그 열은 가로로 안 늘어난다 (밀리기만 한다).
// 수동 밴드(영역 UI)는 무조건 켜지고 램프를 밴드 자체에 앵커한다 — 파이썬 protect 미러
// (자동 램프는 max_half 앵커라 블롭에서 밴드 조정이 무력했다, 2026-07-30).
@@ -192,14 +251,14 @@ function breatheClipWording(off, data, w, h) {
const where = BREATHE_SIDES.filter((s) => off[s]).map((s) => `${BREATHE_SIDE_NAMES[s]} 변 밖 ${off[s]}`).join(", ");
const border = breatheOwnBorder(data, w, h);
const crossed = BREATHE_SIDES.filter((s) => off[s] && border.sides.includes(s));
- if (!crossed.length) return { where, advice: "셀 여백을 늘리거나 depth 를 낮춰라." };
+ if (!crossed.length) return { where, advice: "셀 여백을 늘리거나 숨의 크기(depth, 또는 최소·최대)를 줄여라." };
const covers = crossed.map((s) => `${BREATHE_SIDE_NAMES[s]} 변 바깥 줄 ${border.outer[s]} px`).join(", ");
return {
where,
advice: `그림이 ${covers} 를 덮는다 — 그 변 길이의 ${BREATHE_BORDER_MIN_FRACTION * 100} % 이상이라 그림 자체의 테두리로 `
+ "읽힌다. 원래 화면에 잘린 그림(큰 일러·영상 칸)이면 mode smooth(`--mode smooth`)로 구워라 — 머리와 "
+ "화면 변이 제자리에 있다. 여백을 붙여 굽고 잘라 내지 마라 — 밀려 나간 만큼 조용히 잃는다. 도트 "
- + "스프라이트면 셀 여백을 늘리거나 depth 를 낮춰라.",
+ + "스프라이트면 셀 여백을 늘리거나 숨의 크기(depth, 또는 최소·최대)를 줄여라.",
};
}
@@ -329,30 +388,33 @@ function breatheComposite(base, cfg, phase) {
const baseline = by1;
const { env, ru, norm } = breatheEnvelope(anat);
const pOf = breatheProtect(anat);
- const depth = cfg.depth || 0.06;
- // 가로 독립 진폭 — null/undefined 는 depth 따름(레거시 동일), 0 은 가로 항등 (파이썬 미러).
- const depthX = cfg.depth_x == null ? depth : Number(cfg.depth_x);
- let peak = 0;
- for (let j = 0; j < anat.height; j++) peak = Math.max(peak, env(j / Math.max(1, anat.height - 1)));
- for (const [axis, d] of [["depth", depth], ["depth_x", depthX]]) {
- const strain = d * norm * peak;
+ // 축마다 이득 계수 — 세기 줄의 가로 null/undefined 는 depth 따름(레거시 동일), 0 은 가로 항등 (파이썬 미러).
+ const [down, across] = breatheGains(anat, cfg);
+ const peak = breatheEnvelopePeak(anat, env);
+ // 행당 변형 상한 — 세기 줄은 세기 그대로(극값보다 넉넉한 옛 판정), 최소·최대 줄은 극값으로 (파이썬 _row_refusals 미러).
+ const strains = breatheHasBounds(cfg)
+ ? [["height_min·height_max", down], ["width_min·width_max", across]].map(
+ ([axis, [b, a]]) => [axis, (Math.abs(b) + Math.abs(a) * BREATHE_WAVE_PEAK) * peak])
+ : [["depth", cfg.depth || 0.06], ["depth_x", cfg.depth_x == null ? cfg.depth || 0.06 : Number(cfg.depth_x)]].map(
+ ([axis, d]) => [axis, d * norm * peak]);
+ for (const [axis, strain] of strains) {
if (strain > BREATHE_MAX_ROW_STRAIN) {
throw new BreatheRefused(
`행당 변형(${axis}) ${strain.toFixed(3)} > 상한 ${BREATHE_MAX_ROW_STRAIN} — 변형 구간이 너무 좁다 `
- + `(강체 경계 ${anat.rigid_row}/${anat.height}). ${axis} 를 낮추거나 경계를 올려라.`);
+ + `(강체 경계 ${anat.rigid_row}/${anat.height}). ${axis} 를 줄이거나 경계를 올려라.`);
}
}
const lag = cfg.lag == null ? 0.1 : cfg.lag;
- const gain = (u, d) => {
+ const gain = (u, k) => {
const e = env(u);
if (e <= 0) return 0;
- return d * norm * breatheWave(phase - lag * Math.min(1, u / Math.max(1e-6, ru))) * e;
+ return (k[0] + k[1] * breatheWave(phase - lag * Math.min(1, u / Math.max(1e-6, ru)))) * e;
};
const heights = [];
let acc = 0;
for (let j = 0; j < height; j++) {
- const g = gain(1 - j / Math.max(1, height - 1), depth);
+ const g = gain(1 - j / Math.max(1, height - 1), down);
acc += g === 0 ? 1 : 1 / (1 + g);
heights.push(acc);
}
@@ -371,7 +433,7 @@ function breatheComposite(base, cfg, phase) {
const reps = Math.max(0, cur - prev);
prev = cur;
if (reps === 0) continue;
- const g = gain(u, depthX); // 가로 성분 — 독립 진폭 (depth_x)
+ const g = gain(u, across); // 가로 성분 — 독립 계수 (depth_x, width_*)
if (reps !== 1) deformed = true; // 행 복제/삭제 = 세로 변형이 실재
let rowMap;
if (g === 0) {
@@ -548,11 +610,10 @@ async function defaultBreatheConfig(stateName) {
// 같은 런에서 사람이 이미 튜닝한 세기를 물려받는다 (사람 판단 > 기본값).
const sibling = run.states
.map((s) => (s.name !== stateName && entries[s.name] ? entries[s.name].breathe : null))
- .find((b) => b && typeof b.depth === "number");
+ .find((b) => b && (typeof b.depth === "number" || breatheHasBounds(b)));
const { anatomy, defaults } = await fetchBreatheAnatomy(stateName);
return {
- depth: sibling ? sibling.depth : defaults.depth,
- depth_x: sibling && sibling.depth_x != null ? sibling.depth_x : null,
+ ...breatheSizeOf(sibling, defaults),
breaths: sibling ? sibling.breaths : defaults.breaths,
lag: sibling ? sibling.lag : defaults.lag,
rigid_row: null,
@@ -560,6 +621,15 @@ async function defaultBreatheConfig(stateName) {
};
}
+// 숨의 크기 키 — 형제 줄이 최소·최대로 적혔으면 그 네 값, 세기로 적혔으면 세기, 없으면 서버 기본 세기.
+function breatheSizeOf(sibling, defaults) {
+ if (sibling && breatheHasBounds(sibling)) {
+ return Object.fromEntries(BREATHE_RANGE_KEYS.filter((k) => sibling[k] != null).map((k) => [k, sibling[k]]));
+ }
+ return { depth: sibling ? sibling.depth : defaults.depth,
+ depth_x: sibling && sibling.depth_x != null ? sibling.depth_x : null };
+}
+
// 사이드카에서 breathe 가 켜진 채 로드됐지만 anatomy 캐시가 비어 있으면(뷰 없이
// 에이전트/CLI 가 breathe 만 쓴 런, 레거시 이전 직후) 미리보기 미러는 해부를 로컬로 못
// 재 조용히 정지 그림을 그린다 (breatheComposite: !anat → base 원본). 굽기는 서버가
diff --git a/sprite_gen/serve/curator/src/i18n.js b/sprite_gen/serve/curator/src/i18n.js
index 1275c3c..70e2980 100644
--- a/sprite_gen/serve/curator/src/i18n.js
+++ b/sprite_gen/serve/curator/src/i18n.js
@@ -50,9 +50,12 @@ const STR = {
unlinked: (s) => `unlinked from ${s} — now an independent frame`,
tFpsStepper: "whole-row playback speed (state fps, saved to sprite-request) — per-frame hold time is expressed by duplicating frames (atlas cells are shared, so clones cost nothing)",
fpsSet: (s, f) => `${s}: ${f}fps`, fpsFail: "fps change failed: ",
- rowBreathe: "Breathe", tRowBreathe: "breathing is a POST-PROCESS LAYER, orthogonal to frame selection — a blink frame breathes too. Check: turn it on (instant, saved to the sidecar; compose/GIF bake it deterministically). Uncheck: turn it off. Click the label to drag the rigid boundary and tune depth / breaths over the LIVE playing sequence.",
+ rowBreathe: "Breathe", tRowBreathe: "breathing is a POST-PROCESS LAYER, orthogonal to frame selection — a blink frame breathes too. Check: turn it on (instant, saved to the sidecar; compose/GIF bake it deterministically). Uncheck: turn it off. Click the label to drag the rigid boundary and tune the width / height range and breaths over the LIVE playing sequence.",
tRowBreatheEdit: "open the breathing editor — adjustments apply instantly over the playing sequence; Esc restores the previous setting",
- breatheAmp: "v depth", breatheAmpX: "h depth", breatheAmpXFollow: "h depth = v",
+ breatheWidth: "width", breatheHeight: "height", breatheMin: "min — the smallest the breath gets on this axis",
+ breatheMax: "max — the largest the breath gets on this axis",
+ tBreatheWidth: "how much the torso widens at the row where the breath is fullest, as a share of the original (0 = original width, -20..20%). Pixel: the widest moment is also the lowest head",
+ tBreatheHeight: "how far the head top (smooth: the chest) rises, as a share of the body below the neck (negative = down, 0 = original height, -20..20%)",
breatheCountLabel: "breaths/loop", breatheFitted: (n) => n === 0 ? "→ no room to breathe" : `→ ${n} applied`,
breatheAuto: "auto", tBreatheAuto: "drop the manual boundary and use the detected one (neck bottleneck, or below the face when the face sits on the body)",
tBreatheFitted: (len) => `the loop is ${len} frames — add frames to the sequence for a smoother breath`, tBreatheCount: "breath count per loop (1-8) — phases are continuous, so the requested count applies exactly",
@@ -220,9 +223,12 @@ const STR = {
unlinked: (s) => `${s} 와 링크 해제 — 독립 프레임이 됐습니다`,
tFpsStepper: "줄 전체 재생 속도 (state fps — sprite-request 에 저장). 특정 프레임을 길게 보여주려면 프레임 복제를 쓰세요 (복제는 아틀라스 셀 공유 = 부하 0)",
fpsSet: (s, f) => `${s}: ${f}fps`, fpsFail: "fps 변경 실패: ",
- rowBreathe: "호흡", tRowBreathe: "호흡은 프레임 선택과 직교하는 후처리 레이어입니다 — 깜빡임 프레임도 그대로 숨쉽니다. 체크: 켜기 (즉시, 사이드카 저장 — 아틀라스/GIF 굽기에 결정론 반영), 해제: 끄기. 라벨 클릭: 실제 재생 위에서 강체 경계·진폭·호흡 횟수 조정.",
+ rowBreathe: "호흡", tRowBreathe: "호흡은 프레임 선택과 직교하는 후처리 레이어입니다 — 깜빡임 프레임도 그대로 숨쉽니다. 체크: 켜기 (즉시, 사이드카 저장 — 아틀라스/GIF 굽기에 결정론 반영), 해제: 끄기. 라벨 클릭: 실제 재생 위에서 강체 경계·가로·세로 범위·호흡 횟수 조정.",
tRowBreatheEdit: "호흡 편집기 열기 — 조정은 재생 중인 시퀀스에 즉시 반영됩니다. Esc = 이전 설정 복원",
- breatheAmp: "세로 진폭", breatheAmpX: "가로 진폭", breatheAmpXFollow: "가로 진폭 =세로",
+ breatheWidth: "가로", breatheHeight: "세로", breatheMin: "최소 — 이 축에서 숨이 가장 작을 때",
+ breatheMax: "최대 — 이 축에서 숨이 가장 클 때",
+ tBreatheWidth: "숨이 가장 큰 줄에서 몸통이 넓어지는 비율, 원본 대비 (0 = 원래 폭, -20~20%). pixel 은 가장 넓을 때 머리가 가장 낮다",
+ tBreatheHeight: "목 아래 몸 높이 대비 머리 끝(smooth 는 가슴)이 올라가는 비율 (음수 = 내려감, 0 = 원래 높이, -20~20%)",
breatheCountLabel: "호흡/루프", breatheFitted: (n) => n === 0 ? "→ 숨쉴 자리 없음" : `→ 적용 ${n}회`,
breatheAuto: "자동", tBreatheAuto: "수동 경계를 버리고 검출값을 쓴다 (목 병목, 얼굴이 몸통에 있으면 얼굴 아래)",
tBreatheFitted: (len) => `루프가 ${len}프레임 — 더 부드럽게 하려면 시퀀스에 프레임을 늘리세요`, tBreatheCount: "루프당 호흡 횟수 (1~8) — 위상이 연속값이라 요청한 횟수가 그대로 적용됩니다",
diff --git a/sprite_gen/serve/curator/src/store.js b/sprite_gen/serve/curator/src/store.js
index 439a3fa..3106158 100644
--- a/sprite_gen/serve/curator/src/store.js
+++ b/sprite_gen/serve/curator/src/store.js
@@ -46,7 +46,7 @@ function breatheRangeProblems(raw) {
if (!Number.isFinite(v) || v < 0 || v > BREATHE_ROUND_MAX) bad.push(`${key}=${JSON.stringify(raw[key])}`);
}
if (rounded) {
- for (const key of ["depth", "depth_x", "lag"]) {
+ for (const key of ["depth", "depth_x", "lag", ...BREATHE_RANGE_KEYS]) {
if (raw[key] != null) bad.push(`${key} (둥근 가슴 줄은 봉투 값을 쓰지 않는다)`);
}
}
@@ -112,6 +112,21 @@ function breatheRangeProblems(raw) {
if (!Number.isFinite(dx) || dx < 0 || dx > 0.20) bad.push(`depth_x=${JSON.stringify(raw.depth_x)}`);
}
}
+ // 가로·세로 최소·최대 (2026-10-29) — 파이썬 curation._breathe_bounds 미러. null 은 생략, 적지 않은 경계는 0.
+ // 세기와 같이 적으면 어느 쪽을 따를지 모르므로 굽기가 거부한다. 참거짓은 수로 읽지 않는다 (isNumericScalar).
+ const written = BREATHE_RANGE_KEYS.filter((k) => raw[k] != null);
+ if (written.length) {
+ const strength = ["depth", "depth_x"].filter((k) => raw[k] != null);
+ if (strength.length) bad.push(`${strength.join("·")} + ${written.join("·")} (세기와 최소·최대를 같이 적었다)`);
+ const v = {};
+ for (const key of BREATHE_RANGE_KEYS) {
+ v[key] = raw[key] == null ? 0 : isNumericScalar(raw[key]) ? Number(raw[key]) : NaN;
+ if (!Number.isFinite(v[key]) || Math.abs(v[key]) > BREATHE_RANGE_MAX) bad.push(`${key}=${JSON.stringify(raw[key])}`);
+ }
+ for (const axis of ["width", "height"]) {
+ if (v[`${axis}_min`] > v[`${axis}_max`]) bad.push(`${axis}_min > ${axis}_max`);
+ }
+ }
if (raw.rigid_row != null) {
// `Number("")` 과 `Number([])` 는 **0** 이라 정수 검사만 하면 통과한다 — 그러면 첫
// autosave 가 사용자 사이드카를 0 으로 덮고 굽기의 loud reject 근거가 사라진다
@@ -686,11 +701,20 @@ function seedEntries() {
// `depth` 생략은 굽기에서 0.06 이다. `Number(undefined)` = NaN 이고
// `JSON.stringify(NaN)` 은 `null` 이라, 기본값 분기가 없으면 첫 autosave 가
// 사이드카에 `depth: null` 을 박아 **굽기가 죽는다** (validator 실측 2026-07-26).
- : { depth: rawBreathe.depth == null ? 0.06 : Number(rawBreathe.depth),
+ // 최소·최대 줄은 적힌 경계만 들고 세기를 채우지 않는다 — depth 0.06 을 넣으면 첫 autosave 가 둘을 같이 적어
+ // 굽기가 거부한다. 세기 줄의 depth_x 와 영역 손잡이(axis_x·torso_half)도 되쓴다: 빼면 편집기에서 고친 가로
+ // 진폭과 몸통 띠가 다시 열 때 사라진다. 영역 값은 굽기가 정수 검사를 하므로 적힌 그대로 둔다.
+ : { ...(breatheHasBounds(rawBreathe)
+ ? Object.fromEntries(BREATHE_RANGE_KEYS.filter((k) => rawBreathe[k] != null)
+ .map((k) => [k, Number(rawBreathe[k])]))
+ : { depth: rawBreathe.depth == null ? 0.06 : Number(rawBreathe.depth),
+ ...(rawBreathe.depth_x != null ? { depth_x: Number(rawBreathe.depth_x) } : {}) }),
// 위에서 정수 검증을 통과했으므로 반올림이 필요 없다 — 반올림하면 굽기와 갈린다
breaths: Number(rawBreathe.breaths == null ? 1 : rawBreathe.breaths),
lag: Number(rawBreathe.lag == null ? 0.1 : rawBreathe.lag),
rigid_row: rawBreathe.rigid_row == null ? null : Number(rawBreathe.rigid_row),
+ ...(rawBreathe.axis_x != null ? { axis_x: rawBreathe.axis_x } : {}),
+ ...(rawBreathe.torso_half != null ? { torso_half: rawBreathe.torso_half } : {}),
anatomy: rawBreathe.anatomy || null,
// 적힌 `mode: "pixel"` 은 그대로 되쓴다 — 생략과 같은 뜻이지만 사용자가 쓴 키다.
...(rawBreathe.mode != null ? { mode: rawBreathe.mode } : {}) }
diff --git a/sprite_gen/serve/curator/src/zoom-editor.js b/sprite_gen/serve/curator/src/zoom-editor.js
index a117b95..f830a9e 100644
--- a/sprite_gen/serve/curator/src/zoom-editor.js
+++ b/sprite_gen/serve/curator/src/zoom-editor.js
@@ -930,6 +930,7 @@ function openZoom(stateName, idx, keepWidth) {
const { anatomy } = await fetchBreatheAnatomy(
stateName, bm.cfg.rigid_row, bm.cfg.axis_x, bm.cfg.torso_half);
bm.cfg.anatomy = anatomy;
+ syncRange(); // 세기 줄의 가로 범위는 해부(봉투)에 달렸다
syncLines();
commit();
rebuildStrip();
@@ -1149,10 +1150,11 @@ function openZoom(stateName, idx, keepWidth) {
if (!e0.breathe && !beforeCfg && bm.histPos <= 0) {
const sib = run.states
.map((s) => (s.name !== stateName && entries[s.name] ? entries[s.name].breathe : null))
- .find((b) => b && typeof b.depth === "number");
+ .find((b) => b && (typeof b.depth === "number" || breatheHasBounds(b)));
if (sib) {
- bm.cfg.depth = sib.depth;
- bm.cfg.depth_x = sib.depth_x == null ? null : sib.depth_x;
+ // 형제 줄의 크기 키(최소·최대 넷 또는 세기) — 둘을 같이 적으면 굽기가 거부하므로 기본 세기를 먼저 지운다
+ for (const k of ["depth", "depth_x", ...BREATHE_RANGE_KEYS]) delete bm.cfg[k];
+ Object.assign(bm.cfg, breatheSizeOf(sib));
bm.cfg.breaths = sib.breaths;
bm.cfg.lag = sib.lag;
}
@@ -1252,18 +1254,6 @@ function openZoom(stateName, idx, keepWidth) {
onWrap.appendChild(onCheck);
onWrap.appendChild(Object.assign(document.createElement("span"), { textContent: t("rowBreathe") }));
bar.appendChild(onWrap);
- const mkSel = (values, current, fmt, onchange) => {
- const sel = document.createElement("select");
- for (const v of values) {
- const o = document.createElement("option");
- o.value = String(v);
- o.textContent = fmt(v);
- if (v === current) o.selected = true;
- sel.appendChild(o);
- }
- sel.addEventListener("change", () => onchange(parseInt(sel.value, 10)));
- return sel;
- };
// 강체 경계는 하나뿐이라 +선/−선 버튼이 없다. 경계는 드래그로만 움직이고,
// 자동 검출값으로 되돌리는 버튼을 대신 둔다 (수동 override 해제).
const autoBtn = document.createElement("button");
@@ -1279,25 +1269,61 @@ function openZoom(stateName, idx, keepWidth) {
pushHist();
});
bar.appendChild(autoBtn);
- // 진폭 = 몸통 높이 비율. px 가 아니라 비율이라 캐릭터가 달라도 같은 뜻을 갖는다.
- const depthSel = mkSel([3, 4, 5, 6, 8, 10, 12], Math.round((bm.cfg.depth || 0.06) * 100),
- (v) => `${t("breatheAmp")} ${v}%`,
- (v) => { bm.cfg.depth = (v || 6) / 100; commit(); pushHist(); });
- // 가로 독립 진폭 (maintainer 요청 2026-07-30): "따름" = depth 와 동일(레거시), 0 = 가로 끄기.
- const depthXSel = document.createElement("select");
- for (const v of ["follow", 0, 3, 4, 5, 6, 8, 10, 12]) {
- const o = document.createElement("option");
- o.value = String(v);
- o.textContent = v === "follow" ? t("breatheAmpXFollow") : `${t("breatheAmpX")} ${v}%`;
- depthXSel.appendChild(o);
+ // 숨의 크기 = 가로·세로 최소·최대 (2026-10-29). 원본 대비 비율이라 캐릭터가 달라도 같은 뜻이다: 가로는 숨이 가장 큰
+ // 줄에서 몸통이 넓어지는 몫, 세로는 목 아래 몸 높이 대비 머리 끝(smooth 는 가슴)이 오르는 몫 (음수 = 내려감).
+ // 세기(depth)만 적힌 줄은 그 세기가 오가는 범위(breatheRange)를 보여 주고, 손잡이 하나를 고치면 줄을 네 키로 옮긴다 —
+ // 손대지 않은 손잡이는 반올림하지 않은 값 그대로 옮겨 그 축은 옛 세기와 같은 바이트로 구워진다.
+ const rangeInputs = {};
+ const rangeWrap = document.createElement("span");
+ rangeWrap.className = "breathe-range";
+ for (const axis of ["width", "height"]) {
+ const group = document.createElement("span");
+ group.title = t(axis === "width" ? "tBreatheWidth" : "tBreatheHeight");
+ group.appendChild(Object.assign(document.createElement("span"),
+ { textContent: t(axis === "width" ? "breatheWidth" : "breatheHeight") }));
+ for (const end of ["min", "max"]) {
+ const key = `${axis}_${end}`;
+ const input = document.createElement("input");
+ input.type = "number";
+ input.step = "0.5";
+ input.min = String(-BREATHE_RANGE_MAX * 100);
+ input.max = String(BREATHE_RANGE_MAX * 100);
+ input.title = t(end === "min" ? "breatheMin" : "breatheMax");
+ input.addEventListener("change", () => setRange(key, input.value));
+ if (end === "max") group.appendChild(Object.assign(document.createElement("span"), { textContent: "~" }));
+ group.appendChild(input);
+ rangeInputs[key] = input;
+ }
+ group.appendChild(Object.assign(document.createElement("span"), { textContent: "%" }));
+ rangeWrap.appendChild(group);
}
- depthXSel.value = bm.cfg.depth_x == null ? "follow" : String(Math.round(bm.cfg.depth_x * 100));
- if (depthXSel.selectedIndex < 0) depthXSel.value = "follow"; // 목록 밖 수동값 — 표시만 따름으로
- depthXSel.addEventListener("change", () => {
- bm.cfg.depth_x = depthXSel.value === "follow" ? null : Number(depthXSel.value) / 100;
+ // 둥근 가슴 줄은 봉투 값을 안 쓰고(굽기가 거부), pixel 세기 줄의 가로는 해부가 와야 안다 — 그때는 null.
+ const currentRange = () => (breatheRound(bm.cfg) ? null : breatheRange(bm.cfg.anatomy, bm.cfg));
+ // 입력은 0.1% 단위로 받아 ±상한 안, 같은 축의 다른 끝을 넘지 않게 둔다 (최소 > 최대는 굽기가 거부한다).
+ const setRange = (key, pct) => {
+ const range = currentRange();
+ const v = Number(pct);
+ if (!range || pct === "" || !Number.isFinite(v)) { syncRange(); return; }
+ const now = { width_min: range.width[0], width_max: range.width[1],
+ height_min: range.height[0], height_max: range.height[1] };
+ const share = Math.max(-BREATHE_RANGE_MAX, Math.min(BREATHE_RANGE_MAX, Math.round(v * 10) / 1000));
+ now[key] = key.endsWith("_min") ? Math.min(share, now[key.replace("_min", "_max")])
+ : Math.max(share, now[key.replace("_max", "_min")]);
+ delete bm.cfg.depth;
+ delete bm.cfg.depth_x;
+ Object.assign(bm.cfg, now);
+ syncRange();
commit();
pushHist();
- });
+ };
+ function syncRange() {
+ const range = currentRange();
+ for (const [key, input] of Object.entries(rangeInputs)) {
+ const [axis, end] = key.split("_");
+ input.disabled = !bm.enabled || !range;
+ input.value = range ? String(Math.round(range[axis][end === "min" ? 0 : 1] * 1000) / 10) : "";
+ }
+ }
// 호흡 횟수: 숫자 입력 + −/+ 스텝퍼 (maintainer 2026-07-18 — 약수 셀렉트 대신 자유 입력;
// 나눠떨어지지 않으면 fit_breathe_pattern 이 보정하고 스트립 캡션이 알려준다)
const breathWrap = document.createElement("span");
@@ -1346,17 +1372,14 @@ function openZoom(stateName, idx, keepWidth) {
breathWrap.appendChild(breathInput);
breathWrap.appendChild(plusBtn);
breathWrap.appendChild(fitBadge);
- bar.appendChild(depthSel);
- bar.appendChild(depthXSel);
+ bar.appendChild(rangeWrap);
bar.appendChild(breathWrap);
toolbar.appendChild(bar);
function syncBreatheControls() {
onCheck.checked = bm.enabled;
const off = !bm.enabled;
- for (const el of [autoBtn, depthSel, depthXSel, minusBtn, breathInput, plusBtn]) el.disabled = off;
- depthSel.value = String(Math.round((bm.cfg.depth || 0.06) * 100));
- depthXSel.value = bm.cfg.depth_x == null ? "follow" : String(Math.round(bm.cfg.depth_x * 100));
- if (depthXSel.selectedIndex < 0) depthXSel.value = "follow";
+ for (const el of [autoBtn, minusBtn, breathInput, plusBtn]) el.disabled = off;
+ syncRange();
breathInput.value = String(bm.cfg.breaths || 1);
syncFitBadge();
}
diff --git a/tests/effects/test_breathe.py b/tests/effects/test_breathe.py
index 1582cac..946feff 100644
--- a/tests/effects/test_breathe.py
+++ b/tests/effects/test_breathe.py
@@ -587,7 +587,7 @@ def test_a_clip_off_the_drawings_border_keeps_the_margin_advice() -> None:
message = _clip_refusal(_cut_bust(touch=False))
assert re.search(r"왼쪽 변 밖 \d+", message), message
assert "--mode smooth" not in message, message
- assert "셀 여백을 늘리거나 depth 를 낮춰라" in message, message
+ assert "셀 여백을 늘리거나 숨의 크기(depth, 또는 최소·최대)를 줄여라" in message, message
# ── 8. 얼굴이 몸통에 있는 실루엣 (목 없음) ─────────────────────────
diff --git a/tests/effects/test_breathe_js_mirror.py b/tests/effects/test_breathe_js_mirror.py
index e96da0e..22addac 100644
--- a/tests/effects/test_breathe_js_mirror.py
+++ b/tests/effects/test_breathe_js_mirror.py
@@ -24,7 +24,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
-from sprite_gen.effects.breathe import (MAX_ROW_STRAIN, anatomy_fingerprint, # noqa: E402
+from sprite_gen.effects.breathe import (MAX_ROW_STRAIN, anatomy_fingerprint, breathe_range, # noqa: E402
freeze_anatomy, phase_frame, reference_key, resolve_anatomy,
row_strain)
from sprite_gen.frames.extract import solid_alpha_bbox # noqa: E402
@@ -100,18 +100,28 @@ def _rgba(image):
# 큰 도트 그림 — 다듬기·부속 보호·행 사상이 수백 줄에서 돈다. 굽기를 numpy 로 바꿔도 미러(바꾸지
# 않은 화소 순회)와 바이트가 같은지 여기서 본다.
(_outlined_figure, {}),
+ # 가로·세로 최소·최대 (2026-10-29): 최소 0 / 양쪽 / 원래 크기를 안 지나는 범위. 이득 계수(B + A·wave)의 연산 순서가
+ # 파이썬과 갈리면 여기서 잡힌다 — 세기 줄은 B = 0 이라 위 칸들이 못 본다.
+ (_outlined_figure, {"width_min": 0.0, "width_max": 0.06, "height_min": -0.05, "height_max": 0.0, "lag": 0.0}),
+ (_dome, {"width_min": -0.03, "width_max": 0.08, "height_min": -0.06, "height_max": 0.02}),
+ (_small_outlined, {"width_min": 0.02, "width_max": 0.07, "height_min": -0.05, "height_max": -0.01,
+ "breaths": 3}),
], ids=["humanoid", "winged", "small-outlined-thinning",
- "dome-depth-x", "dome-depth-x-zero", "dome-manual-band", "outlined-figure"])
+ "dome-depth-x", "dome-depth-x-zero", "dome-manual-band", "outlined-figure",
+ "figure-min-zero", "dome-both-sides", "small-outlined-off-the-original"])
def test_curator_mirror_is_byte_identical_to_the_bake(build, overrides, tmp_path):
src = build()
cfg = {**CFG, **overrides}
+ bounds = {k: cfg[k] for k in ("width_min", "width_max", "height_min", "height_max") if k in cfg}
+ if bounds:
+ del cfg["depth"] # 최소·최대 줄은 세기를 같이 쓰지 않는다
cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
payload = {
"script": str(CURATOR_BREATHE),
"width": src.width,
"height": src.height,
- "cfg": {"depth": cfg["depth"], "breaths": cfg["breaths"], "lag": cfg["lag"],
+ "cfg": {**({"depth": cfg["depth"]} if "depth" in cfg else bounds), "breaths": cfg["breaths"], "lag": cfg["lag"],
**({"depth_x": cfg["depth_x"]} if "depth_x" in cfg else {}),
**({"torso_half": cfg["torso_half"]} if "torso_half" in cfg else {}),
"anatomy": cfg["anatomy"]},
@@ -473,3 +483,45 @@ def test_the_mirror_refuses_when_it_cannot_verify(tmp_path):
got = json.loads((tmp_path / "out.json").read_text(encoding="utf-8"))
assert not got["ok"] and got["refused"], (
"지문이 null 인데 미러가 신선하다고 판정했다 — 확인 불가는 괜찮음이 아니다")
+
+
+RANGE_HARNESS = r"""
+const fs = require("fs");
+const vm = require("vm");
+const payload = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
+const sandbox = { console, entries: {}, run: { states: [] }, t: () => "", setStatus: () => {}, fetch: () => {} };
+sandbox.globalThis = sandbox;
+vm.createContext(sandbox);
+vm.runInContext(fs.readFileSync(payload.script, "utf8"), sandbox);
+fs.writeFileSync(payload.out, JSON.stringify(payload.cases.map((c) => sandbox.breatheRange(c.anatomy, c.cfg))));
+"""
+
+
[email protected](shutil.which("node") is None, reason="node 가 없어 JS 미러를 실행할 수 없다")
+def test_the_mirror_reads_the_same_range_as_the_bake(tmp_path):
+ """편집기가 세기만 적힌 줄을 네 손잡이로 보여 줄 때 읽는 범위 — 파이썬 breathe_range 와 같은 double 이어야 한다.
+ 갈리면 손대지 않은 손잡이를 저장해도 옛 판과 다른 바이트가 구워진다."""
+ rows = [(_humanoid, {}), (_dome, {"depth": 0.10, "depth_x": 0.0}), (_dome, {"depth_x": 0.12}),
+ (_humanoid, {"mode": "smooth"}), (_humanoid, {"mode": "smooth", "depth": 0.01, "depth_x": 0.03}),
+ (_humanoid, {"width_min": 0.0, "width_max": 0.05, "height_min": -0.04, "height_max": 0.0})]
+ cases = []
+ for build, overrides in rows:
+ src = build()
+ cfg = {**CFG, **overrides}
+ if "mode" in cfg or "width_min" in cfg:
+ cfg.pop("lag", None)
+ if "width_min" in cfg:
+ del cfg["depth"]
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ py = breathe_range(resolve_anatomy(src, cfg), cfg)
+ cases.append({"anatomy": cfg["anatomy"], "cfg": cfg, "py": {k: list(v) for k, v in py.items()}})
+
+ payload = {"script": str(CURATOR_BREATHE), "out": str(tmp_path / "js.json"),
+ "cases": [{"anatomy": c["anatomy"], "cfg": c["cfg"]} for c in cases]}
+ (tmp_path / "payload.json").write_text(json.dumps(payload), encoding="utf-8")
+ (tmp_path / "harness.cjs").write_text(RANGE_HARNESS, encoding="utf-8")
+ proc = subprocess.run([shutil.which("node"), str(tmp_path / "harness.cjs"),
+ str(tmp_path / "payload.json")], capture_output=True, encoding="utf-8")
+ assert proc.returncode == 0, f"node 하네스 실패:\n{proc.stderr}"
+ for case, js in zip(cases, json.loads((tmp_path / "js.json").read_text(encoding="utf-8"))):
+ assert js == case["py"], f"{case['cfg']}: py={case['py']} js={js}"
diff --git a/tests/effects/test_breathe_min_max.py b/tests/effects/test_breathe_min_max.py
new file mode 100644
index 0000000..3c84304
--- /dev/null
+++ b/tests/effects/test_breathe_min_max.py
@@ -0,0 +1,302 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Breathe 의 가로·세로 최소·최대 (`width_min`·`width_max`·`height_min`·`height_max`).
+
+세기(`depth`·`depth_x`)는 숨 곡선의 진폭이라 곡선이 0 아래로 내려가는 뒤 절반에 몸이 원래보다 좁아지고 머리가
+원래보다 올라간다. 최소·최대 키는 같은 곡선·같은 박자의 바닥과 꼭대기를 사람이 쓴 값에 놓는다 — 최소 0 이면 그 뒤
+절반이 원래 크기에 머문다. 지키는 것:
+
+ 1. 옛 키(`depth`·`depth_x` 만 쓴 줄)와 기본값은 이전과 바이트 같다.
+ 2. 최소 0 이면 어느 칸도 원래보다 좁거나 높지 않다.
+ 3. 쓴 값이 판에서 잰 극값과 1 칸 안에서 맞는다.
+ 4. 곡선 모양과 박자는 그대로다 — 옛 세기의 극값을 새 키로 쓰면 옛 바이트가 나오고, 곡선을 바닥 0 으로 옮겨
+ 구운 판(엔진을 고치기 전의 런타임 바꿔치기)과 새 키의 판이 바이트 같다.
+ 5. 새 키와 세기를 같이 쓰거나, 최소가 최대보다 크거나, 범위 밖이면 조용히 고르지 않고 거부한다.
+"""
+
+import hashlib
+import json
+import math
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from sprite_gen.curate.curation import BREATHE_RANGE_MAX, state_breathe
+from sprite_gen.effects import breathe as B
+from sprite_gen.frames.extract import solid_alpha_bbox
+from tests.effects.test_breathe import _dome, _humanoid, _outlined_figure, _small_outlined, _winged
+from tests.effects.test_breathe_smooth import _bust
+
+
+def _cfg(raw: dict) -> dict:
+ return state_breathe({"states": {"idle": {"breathe": raw}}}, "idle")
+
+
+def _digest(frames) -> str:
+ return hashlib.sha256(b"".join(f.tobytes() for f in frames)).hexdigest()
+
+
+def _tall_humanoid() -> Image.Image:
+ """`_humanoid` 를 3 배 — 몸통 행에 부속이 없어 한 행의 폭이 곧 몸통 폭이다 (84 px)."""
+ src = _humanoid()
+ return src.resize((src.width * 3, src.height * 3), Image.NEAREST)
+
+
+TORSO = 84 # `_tall_humanoid` 의 몸통 폭 — 머리(60)·목(24)보다 넓은 행이 몸통 행이다
+
+
+def _torso_widths(frame: Image.Image) -> list[int]:
+ """`_tall_humanoid` 칸의 몸통 행 폭들 — 콘텐츠 상자 폭은 숨이 안 걸리는 발끝 행이 원래 폭을 지켜 좁아짐을 못 본다."""
+ counts = (np.asarray(frame.convert("RGBA"))[..., 3] != 0).sum(axis=1)
+ return [int(c) for c in counts if c > 70]
+
+
+def _extremes(src: Image.Image, frames, torso: bool = False) -> tuple[int, int, int, int]:
+ """(가로 폭 변화 최소, 최대, 머리 윗선 오름 최소, 최대) — 칸마다 원본과 댄다. 오름은 위가 +. 가로는 콘텐츠 상자 폭
+ (가장 넓은 행이 숨쉬는 부속인 그림), `torso` 면 숨이 가장 크게 걸린 몸통 행의 폭이다."""
+ x0, y0, x1, _ = solid_alpha_bbox(src)
+ widths, lifts = [], []
+ for frame in frames:
+ a0, b0, a1, _ = solid_alpha_bbox(frame)
+ if torso:
+ # 숨이 가장 크게 걸리는 행 = 원래 폭에서 가장 멀어진 몸통 행 (발끝 행은 원래 폭을 지킨다)
+ widths.append(max((w - TORSO for w in _torso_widths(frame)), key=abs))
+ else:
+ widths.append((a1 - a0) - (x1 - x0))
+ lifts.append(y0 - b0)
+ return min(widths), max(widths), min(lifts), max(lifts)
+
+
+# ── 1. 옛 키는 바이트 그대로 ─────────────────────────────────────────
+
+# 최소·최대 키가 생기기 전(3.6.0, bf8db30)의 pixel 굽기 — 12칸. smooth 는 test_breathe_smooth 의 골든이 본다.
+PIXEL_GOLDEN = [
+ (_humanoid, {"depth": 0.06, "breaths": 1, "lag": 0.1},
+ "cc0c43833127364ec4fc1c200f43269a712248f2d3b165b2197e22791ff2ea66"),
+ (_winged, {"breaths": 2}, "5bdf0c0997cf799bc7e3a82374dce16fb65db3545fb3a5f1f1df7b249fcbaf0d"),
+ (_dome, {"depth": 0.06, "depth_x": 0.12, "breaths": 1},
+ "367ee5c53e9e8cbad436d4701aa733fda984cacc891263a20eb96cf8bd6f2cc2"),
+ (_dome, {"depth": 0.10, "depth_x": 0.0, "breaths": 1},
+ "50b19b67cbe3841f926e9c2d3cbbfb01e7354f77aaaabc38705adc1d962f2e2f"),
+ (_small_outlined, {"depth": 0.08, "breaths": 3},
+ "9aecdf05a249637d70962524deb794a2bd827edaea6c85936022eb705ee2296f"),
+ (_outlined_figure, {"depth": 0.06, "breaths": 2, "lag": 0.0},
+ "19ef450d0c6f972f84b53f9a9f864d4369b46277aec968e84357e49a05b4827a"),
+]
+
+
[email protected]("build,raw,digest", PIXEL_GOLDEN,
+ ids=["humanoid", "winged-default", "dome-depth-x", "dome-depth-x-zero", "small-outlined",
+ "figure-lag0"])
+def test_old_keys_keep_their_bytes(build, raw, digest) -> None:
+ frames, _ = B.bake_breathe_sequence([build()] * 12, _cfg(raw))
+ assert _digest(frames) == digest, "세기(depth·depth_x)만 쓴 줄의 굽기가 바뀌었다"
+
+
+def test_old_keys_keep_their_normalized_sidecar() -> None:
+ """옛 줄의 정규화(breathe.json 의 config, 미리보기가 읽는 값)도 이전과 같은 키·같은 값이다."""
+ assert _cfg({"depth": 0.06, "breaths": 2}) == {"depth": 0.06, "depth_x": None, "breaths": 2, "lag": 0.10,
+ "rigid_row": None, "axis_x": None, "torso_half": None,
+ "anatomy": None}
+ smooth = _cfg({"mode": "smooth", "breaths": 1})
+ assert (smooth["depth"], smooth["depth_x"]) == (0.0085, 0.028)
+ assert not any(k in smooth for k in ("width_min", "width_max", "height_min", "height_max"))
+
+
+# ── 2. 곡선의 바닥과 꼭대기 ──────────────────────────────────────────
+
+def test_the_wave_peak_is_the_curve_top() -> None:
+ """`WAVE_PEAK` 는 숨 곡선 `wave` 의 꼭대기다 (곡선이 홀함수라 바닥은 그 음수) — 최소·최대가 여기에 놓인다."""
+ c = (-0.86 + math.sqrt(0.86 ** 2 + 4 * 0.56 * 0.28)) / (2 * 0.56) # wave' = 0 의 cos(2πt)
+ t = math.acos(c) / (2 * math.pi)
+ assert B.WAVE_PEAK == pytest.approx(B.wave(t), abs=1e-15)
+ grid = np.linspace(0.0, 1.0, 200001)
+ values = 0.86 * np.sin(2 * np.pi * grid) + 0.14 * np.sin(4 * np.pi * grid)
+ assert values.max() <= B.WAVE_PEAK + 1e-12 and values.min() >= -B.WAVE_PEAK - 1e-12
+
+
+def test_old_depth_reads_as_a_range_around_the_original() -> None:
+ """세기 d 는 바닥 -0.9009 d, 꼭대기 +0.9009 d 인 대칭 범위다 (세로; 가로는 몸통이 가장 크게 숨쉬는 행의 몫).
+ breathe.json 의 `range` 가 이 값을 밝힌다 — 옛 판을 새 키로 옮길 때 읽는 숫자다."""
+ src = _humanoid()
+ cfg = _cfg({"depth": 0.06, "depth_x": 0.04, "breaths": 1})
+ anat = B.resolve_anatomy(src, cfg)
+ env, norm = B.envelope(anat)
+ peak = max(env(j / max(1, anat.height - 1)) for j in range(anat.height))
+ got = B.breathe_range(anat, cfg)
+ assert got["height"] == pytest.approx((-0.06 * B.WAVE_PEAK, 0.06 * B.WAVE_PEAK))
+ assert got["width"] == pytest.approx((-0.04 * B.WAVE_PEAK * norm * peak, 0.04 * B.WAVE_PEAK * norm * peak))
+ raw = {"width_min": -0.01, "width_max": 0.05, "height_min": -0.04, "height_max": 0.0, "breaths": 1}
+ assert B.breathe_range(anat, _cfg(raw)) == {"width": (-0.01, 0.05), "height": (-0.04, 0.0)}
+
+
[email protected]("build,torso", [(_tall_humanoid, True), (_outlined_figure, False), (_winged, False)],
+ ids=["humanoid", "figure", "winged"])
+def test_min_zero_is_never_narrower_nor_taller(build, torso) -> None:
+ """가로 최소 0, 세로 최대 0 이면 어느 칸도 원래보다 좁지 않고 머리가 원래보다 높지 않다 — 숨의 뒤 절반이
+ 원래 크기에 머문다. 같은 그림을 세기로 구우면 좁고 높은 칸이 있다 (이 시험이 무엇을 잡는지)."""
+ src = build()
+ frames, _ = B.bake_breathe_sequence([src] * 24, _cfg({"width_min": 0.0, "width_max": 0.06, "height_min": -0.05,
+ "height_max": 0.0, "breaths": 2, "lag": 0.0}))
+ narrowest, widest, lowest, highest = _extremes(src, frames, torso)
+ assert narrowest >= 0, f"가로 최소 0 인데 원래보다 {-narrowest} 칸 좁은 칸이 있다"
+ assert highest <= 0, f"세로 최대 0 인데 머리가 원래보다 {highest} 칸 높은 칸이 있다"
+ assert widest > 0 and lowest < 0, "숨이 넓어지고 낮아지지 않는다"
+ old, _ = B.bake_breathe_sequence([src] * 24, _cfg({"depth": 0.06, "breaths": 2, "lag": 0.0}))
+ narrowest, _, _, highest = _extremes(src, old, torso)
+ assert narrowest < 0 and highest > 0, "세기로 구운 판에 좁고 높은 칸이 없다 — 이 시험이 아무것도 못 가른다"
+
+
+def test_min_zero_holds_on_every_row_and_phase() -> None:
+ """칸 상자만이 아니라 행마다: 가로 이득 g 가 0 아래로, 세로 이득이 0 아래로 내려가는 위상·행이 없다."""
+ src = _outlined_figure()
+ cfg = _cfg({"width_min": 0.0, "width_max": 0.08, "height_min": -0.05, "height_max": 0.0, "breaths": 1,
+ "lag": 0.1})
+ anat = B.resolve_anatomy(src, cfg)
+ (by, ay), (bx, ax) = B.pixel_gains(anat, cfg)
+ curve = np.array([B.wave(t) for t in np.linspace(0.0, 1.0, 4001)] + [-B.WAVE_PEAK, B.WAVE_PEAK])
+ assert (bx + ax * curve).min() >= -1e-15 and (by + ay * curve).min() >= -1e-15
+
+
[email protected]("width,height", [((0.0, 0.06), (-0.05, 0.0)), ((-0.03, 0.08), (-0.06, 0.02)),
+ ((0.02, 0.05), (-0.04, -0.01))],
+ ids=["min-zero", "both-sides", "never-the-original"])
+def test_the_written_extremes_are_what_the_plate_measures(width, height) -> None:
+ """쓴 값 = 판에서 잰 극값 (1 칸 안). 가로는 몸통 폭(이 그림의 몸통 행은 부속이 없어 콘텐츠 폭)이 가장 크게 숨쉬는
+ 행에서 늘거나 준 몫, 세로는 머리 윗선이 오르내린 칸을 목 아래 몸통 높이(기준 행 수)로 나눈 몫이다."""
+ src = _tall_humanoid()
+ cfg = _cfg({"width_min": width[0], "width_max": width[1], "height_min": height[0], "height_max": height[1],
+ "breaths": 1, "lag": 0.0})
+ anat = B.resolve_anatomy(src, cfg)
+ frames, _ = B.bake_breathe_sequence([src] * 48, cfg, anat)
+ narrowest, widest, lowest, highest = _extremes(src, frames, torso=True)
+ want = (width[0] * TORSO, width[1] * TORSO, height[0] * anat.basis_rows, height[1] * anat.basis_rows)
+ for name, got, expect in zip(("width_min", "width_max", "height_min", "height_max"),
+ (narrowest, widest, lowest, highest), want):
+ assert abs(got - expect) <= 1.0, f"{name}: 쓴 값은 {expect:.2f} 칸, 판에서 잰 극값은 {got} 칸"
+
+
+# ── 3. 곡선 모양과 박자 그대로 ───────────────────────────────────────
+
[email protected]("build,depth,depth_x", [(_humanoid, 0.06, None), (_outlined_figure, 0.06, None),
+ (_dome, 0.08, 0.12)], ids=["humanoid", "figure", "dome-depth-x"])
+def test_the_old_extremes_as_new_keys_bake_the_old_bytes(build, depth, depth_x) -> None:
+ """옛 세기의 극값을 새 키로 쓰면 옛 판과 바이트 같다 — 새 키는 같은 곡선·같은 박자의 바닥과 꼭대기만 정한다."""
+ src = build()
+ old = _cfg({"depth": depth, "breaths": 2, "lag": 0.1, **({} if depth_x is None else {"depth_x": depth_x})})
+ anat = B.resolve_anatomy(src, old)
+ width, height = B.breathe_range(anat, old)["width"], B.breathe_range(anat, old)["height"]
+ new = _cfg({"width_min": width[0], "width_max": width[1], "height_min": height[0], "height_max": height[1],
+ "breaths": 2, "lag": 0.1})
+ want, phases = B.bake_breathe_sequence([src] * 24, old, anat)
+ got, new_phases = B.bake_breathe_sequence([src] * 24, new, anat)
+ assert new_phases == phases, "박자가 바뀌었다"
+ assert _digest(got) == _digest(want), "옛 세기의 극값을 새 키로 썼는데 판이 다르다 — 곡선 모양이 바뀌었다"
+
+
[email protected]("build", [_outlined_figure, _tall_humanoid], ids=["figure", "humanoid"])
+def test_min_zero_is_the_wave_moved_onto_zero(build, monkeypatch) -> None:
+ """엔진을 고치기 전, 곡선만 런타임에 [0, 원래 꼭대기] 로 옮겨 구운 판(`(wave(t) - wmin) / (wmax - wmin) * wmax`,
+ depth 0.06)과 새 키(가로 최소 0, 세로 최대 0, 꼭대기는 depth 0.06 의 꼭대기)의 판이 바이트 같다."""
+ src = build()
+ old = _cfg({"depth": 0.06, "breaths": 2, "lag": 0.0})
+ anat = B.resolve_anatomy(src, old)
+ top = B.breathe_range(anat, old)
+ new = _cfg({"width_min": 0.0, "width_max": top["width"][1], "height_min": top["height"][0],
+ "height_max": 0.0, "breaths": 2, "lag": 0.0})
+ got, _ = B.bake_breathe_sequence([src] * 24, new, anat)
+ grid = np.linspace(0.0, 1.0, 200001)
+ values = 0.86 * np.sin(2 * np.pi * grid) + 0.14 * np.sin(4 * np.pi * grid)
+ wmin, wmax = float(values.min()), float(values.max())
+ wave = B.wave
+ monkeypatch.setattr(B, "wave", lambda t: (wave(t) - wmin) / (wmax - wmin) * wmax)
+ want, _ = B.bake_breathe_sequence([src] * 24, old, anat)
+ assert _digest(got) == _digest(want), "새 키의 최소 0 판이 곡선을 옮겨 구운 판과 다르다"
+
+
+# ── 4. smooth ─────────────────────────────────────────────────────────
+
+def test_smooth_from_zero_is_the_old_smooth_bytes() -> None:
+ """smooth 의 세기는 쉼에서 0, 들숨 꼭대기에서 depth·depth_x 다 — 새 키로 [0, depth]·[0, depth_x] 를 쓰면 같은 판."""
+ src = _bust(120)
+ old = _cfg({"mode": "smooth", "depth": 0.02, "depth_x": 0.04, "breaths": 2})
+ new = _cfg({"mode": "smooth", "width_min": 0.0, "width_max": 0.04, "height_min": 0.0, "height_max": 0.02,
+ "breaths": 2})
+ want, _ = B.bake_breathe_sequence([src] * 12, old)
+ got, _ = B.bake_breathe_sequence([src] * 12, new)
+ assert _digest(got) == _digest(want)
+ anat = B.resolve_anatomy(src, new)
+ assert B.smooth_lift(anat, new) == B.smooth_lift(anat, old) == 0.02 * anat.basis_rows
+ assert B.breathe_range(anat, old) == {"width": (0.0, 0.04), "height": (0.0, 0.02)}
+
+
+def test_smooth_min_moves_the_rest() -> None:
+ """smooth 의 최소가 0 이 아니면 쉼(위상 0)의 칸도 그만큼 옮겨진다 — 위상 0 이 원본인 것은 최소 0 일 때다.
+ 오름 px(`smooth_lift`, Sway·박자 고르기가 읽는 값)는 쉼에서 꼭대기까지다."""
+ src = _bust(120)
+ cfg = _cfg({"mode": "smooth", "width_min": 0.01, "width_max": 0.04, "height_min": 0.005, "height_max": 0.02,
+ "breaths": 1})
+ anat = B.resolve_anatomy(src, cfg)
+ assert B.phase_frame(src, cfg, 0.0, anat).tobytes() != src.tobytes()
+ zero = _cfg({"mode": "smooth", "width_max": 0.04, "height_max": 0.02, "breaths": 1})
+ assert B.phase_frame(src, zero, 0.0, anat).tobytes() == src.tobytes()
+ assert B.smooth_lift(anat, cfg) == pytest.approx(0.015 * anat.basis_rows)
+
+
+# ── 5. 거부 ───────────────────────────────────────────────────────────
+
[email protected]("raw,word", [
+ ({"depth": 0.06, "width_max": 0.05}, "depth"),
+ ({"depth_x": 0.04, "height_min": -0.03}, "depth_x"),
+ ({"mode": "smooth", "depth": 0.01, "height_max": 0.02}, "depth"),
+ ({"width_min": 0.05, "width_max": 0.01}, "width_min"),
+ ({"height_min": 0.0, "height_max": -0.02}, "height_min"),
+ ({"width_max": BREATHE_RANGE_MAX + 0.01}, "width_max"),
+ ({"height_min": -BREATHE_RANGE_MAX - 0.01}, "height_min"),
+ ({"width_max": "wide"}, "width_max"),
+ ({"width_max": True}, "width_max"),
+ ({"chest_round": 0.05, "width_max": 0.05}, "width_max"),
+], ids=["with-depth", "with-depth-x", "smooth-with-depth", "width-upside-down", "height-upside-down",
+ "width-over", "height-under", "not-a-number", "a-bool", "round-chest"])
+def test_refusals(raw, word) -> None:
+ with pytest.raises(SystemExit, match=word):
+ _cfg({"breaths": 1, **raw})
+
+
+def test_a_bound_left_out_is_the_original_size() -> None:
+ """적지 않은 경계는 0 — 원래 크기다. `width_max` 하나만 쓰면 가로만 넓어지고 세로는 그대로다."""
+ cfg = _cfg({"width_max": 0.05, "breaths": 1})
+ assert (cfg["width_min"], cfg["width_max"], cfg["height_min"], cfg["height_max"]) == (0.0, 0.05, 0.0, 0.0)
+ assert "depth" not in cfg and "depth_x" not in cfg
+
+
+def test_the_row_strain_cap_reads_the_extremes() -> None:
+ """행당 변형 상한(0.25)은 새 키의 극값으로 잰다 — 가로 극값은 그 자체가 가장 크게 숨쉬는 행의 몫이라 범위
+ 안(0.20 까지)이면 걸리지 않고, 세로 극값은 목 아래 몸통에 고루 나눈 몫이라 변형 구간이 좁은 그림에서 걸린다."""
+ src = _humanoid()
+ anat = B.resolve_anatomy(src, {"rigid_row": 40}) # 목 아래가 짧아 세로 몫이 좁은 구간에 몰린다
+ env, norm = B.envelope(anat)
+ peak = max(env(j / max(1, anat.height - 1)) for j in range(anat.height))
+ assert 0.20 * norm * peak > B.MAX_ROW_STRAIN, "이 그림은 세로 0.20 이 상한을 넘어야 시험이 된다"
+ B.bake_breathe_sequence([src] * 4, _cfg({"width_max": 0.20, "breaths": 1, "rigid_row": 40}))
+ with pytest.raises(SystemExit, match="height_min"):
+ B.bake_breathe_sequence([src] * 4, _cfg({"height_min": -0.20, "breaths": 1, "rigid_row": 40}))
+
+
+# ── 6. CLI ────────────────────────────────────────────────────────────
+
+def test_the_cli_takes_the_four_keys_and_records_the_range(tmp_path) -> None:
+ frames = tmp_path / "frames"
+ frames.mkdir()
+ for i in range(8):
+ _tall_humanoid().save(frames / f"{i:03d}.png")
+ out = tmp_path / "out"
+ assert B.run(frames=str(frames), out=str(out), width_min=0.0, width_max=0.05, height_min=-0.04, breaths=2,
+ lag=0.0) == 0
+ record = json.loads((out / "breathe.json").read_text(encoding="utf-8"))
+ assert {k: record["config"][k] for k in ("width_min", "width_max", "height_min", "height_max")} == \
+ {"width_min": 0.0, "width_max": 0.05, "height_min": -0.04, "height_max": 0.0}
+ assert record["range"] == {"width": [0.0, 0.05], "height": [-0.04, 0.0]}
+ with pytest.raises(SystemExit, match="depth"):
+ B.run(frames=str(frames), out=str(tmp_path / "out2"), depth=0.06, width_max=0.05)
+ assert not (tmp_path / "out2").exists()
diff --git a/tests/effects/test_breathe_reference_key.py b/tests/effects/test_breathe_reference_key.py
index 24f6c33..6db7c16 100644
--- a/tests/effects/test_breathe_reference_key.py
+++ b/tests/effects/test_breathe_reference_key.py
@@ -569,13 +569,19 @@ def test_the_mirrored_limits_are_the_same_numbers():
from sprite_gen.curate import curation as C
js = (SRC / "breathe.js").read_text(encoding="utf-8")
+ from sprite_gen.effects.breathe import WAVE_PEAK
for name, want in (("BREATHE_DEPTH_MAX", C.BREATHE_DEPTH_MAX),
("BREATHE_BREATHS_MAX", C.BREATHE_BREATHS_MAX),
- ("BREATHE_LAG_MAX", C.BREATHE_LAG_MAX)):
+ ("BREATHE_LAG_MAX", C.BREATHE_LAG_MAX),
+ ("BREATHE_RANGE_MAX", C.BREATHE_RANGE_MAX),
+ ("BREATHE_WAVE_PEAK", WAVE_PEAK)):
m = re.search(rf"const {name} = ([\d.]+);", js)
assert m, f"{name} 이 미러에 없다"
assert float(m.group(1)) == float(want), \
f"{name}: py={want} js={m.group(1)} — 갈리면 저장은 되는데 안 구워진다"
+ keys = re.search(r"const BREATHE_RANGE_KEYS = \[(.*?)\];", js)
+ assert keys, "최소·최대 키 목록이 미러에 없다"
+ assert [k.strip().strip('"') for k in keys.group(1).split(",")] == list(C.BREATHE_RANGE_KEYS)
retired = re.search(r"const RETIRED_BREATHE_KEYS = \[(.*?)\];",
(SRC / "store.js").read_text(encoding="utf-8"))
diff --git a/tests/effects/test_breathe_sidecar_roundtrip.py b/tests/effects/test_breathe_sidecar_roundtrip.py
index 5be7c7e..df1be79 100644
--- a/tests/effects/test_breathe_sidecar_roundtrip.py
+++ b/tests/effects/test_breathe_sidecar_roundtrip.py
@@ -33,7 +33,8 @@ node = pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없어
HARNESS = r"""
const fs = require("fs"), vm = require("vm");
const P = process.argv[2] + "/";
-const SOURCES = ["util.js", "store.js", "persistence.js"].map((f) => fs.readFileSync(P + f, "utf8"));
+// breathe.js 는 store.js 가 읽기 검사에 쓰는 최소·최대 키 목록·상한을 정의한다 (브라우저에서도 같이 실린다).
+const SOURCES = ["util.js", "store.js", "persistence.js", "breathe.js"].map((f) => fs.readFileSync(P + f, "utf8"));
// 왕복 하나 = 새 vm 컨텍스트 하나. 여러 왕복을 node 한 프로세스에 묶어도
// `run`·`entries`·상태 알림이 다음 왕복으로 새지 않는다.
@@ -65,7 +66,6 @@ if (input.mode === "roundtrip") {
fs.writeFileSync(input.out, JSON.stringify(out));
} else {
const sb = boot();
- vm.runInContext(fs.readFileSync(P + "breathe.js", "utf8"), sb);
const out = input.cases.map((c) => sb.breathePattern({ breaths: c.breaths }, c.seq));
fs.writeFileSync(input.out, JSON.stringify(out));
}
@@ -178,6 +178,9 @@ _VALUE_SHAPES = {
# 보므로 `0`/`""`/`[]` 가 서로 **동치**이고, 그 칸들은 통과해도 아무것도 보증하지 못한다.
# 대신 의미 있는 계약(유효한 해부가 왕복에서 그대로 살아남는가)을 아래 전용 테스트로 건다.
MATRIX_KEYS = ["depth", "breaths", "lag", "rigid_row"]
+# 세기 대신 가로·세로 최소·최대로 적은 줄 (2026-10-29) — 같은 값 모양 매트릭스를 네 키에 돌린다.
+RANGE_KEYS = ["width_min", "width_max", "height_min", "height_max"]
+RANGE_ROW = {"width_min": 0.0, "width_max": 0.06, "height_min": -0.05, "height_max": 0.0}
def _sidecar_for(key, shape):
@@ -190,12 +193,15 @@ def _sidecar_for(key, shape):
"rigid_source": "neck", "basis_row": 12, "torso_half": 9.0,
"max_half": 11.0, "face": None, "warnings": [],
"fingerprint": "pixel:0:deadbeef"}}
+ if key in RANGE_KEYS:
+ del base["depth"]
+ base.update(RANGE_ROW)
if shape == "omitted":
base.pop(key)
elif shape == "null":
base[key] = None
elif shape == "string":
- base[key] = "0.08" if key in ("depth", "lag") else "3"
+ base[key] = "0.08" if key in ("depth", "lag") else "0.03" if key in RANGE_KEYS else "3"
elif shape in ("empty-string", "empty-list"):
base[key] = "" if shape == "empty-string" else []
else:
@@ -256,7 +262,7 @@ def test_the_curator_agrees_with_the_bake_on_every_value_shape(tmp_path):
상태가 안 샌다. 칸은 하나도 줄이지 않고, 갈린 칸은 제 이름(`key-shape`)으로
전부 보고한다."""
cells = [(key, shape, _sidecar_for(key, shape))
- for key in MATRIX_KEYS for shape in sorted(_VALUE_SHAPES)]
+ for key in MATRIX_KEYS + RANGE_KEYS for shape in sorted(_VALUE_SHAPES)]
results = _roundtrips([_matrix_run(sidecar) for _, _, sidecar in cells], tmp_path)
assert len(results) == len(cells)
@@ -292,3 +298,32 @@ def test_a_valid_anatomy_survives_the_round_trip_verbatim(tmp_path):
assert saved.get("anatomy") == anatomy, (
f"왕복이 해부를 바꿨다 — 신선도 판정의 근거가 사라진다\n"
f" 전={anatomy}\n 후={saved.get('anatomy')}")
+
+
+# 최소·최대 줄과 세기 줄의 나머지 칸 — 값 모양 매트릭스가 못 만드는 조합. 앞 셋은 굽기가 받는 줄이라 왕복 뒤에도
+# 굽기가 쓰는 값이 같아야 하고(세기 줄의 depth_x·영역 손잡이도 되써야 한다), 뒤는 굽기가 거부하는 줄이라 원본 그대로 두고 알린다.
+_RANGE_CELLS = {
+ "depth-x-and-band": {"depth": 0.06, "depth_x": 0.12, "breaths": 2, "lag": 0.1, "rigid_row": 12,
+ "axis_x": 20, "torso_half": 6},
+ "smooth-range": {"mode": "smooth", "breaths": 2, **RANGE_ROW},
+ "range-partial": {"width_max": 0.05, "breaths": 2, "lag": 0.0},
+ "range-bool": {**RANGE_ROW, "width_max": True, "breaths": 2},
+ "range-flipped": {**RANGE_ROW, "width_min": 0.07, "breaths": 2},
+ "range-with-depth": {**RANGE_ROW, "depth": 0.06, "breaths": 2},
+ "range-with-depth-x": {**RANGE_ROW, "depth_x": 0.0, "breaths": 2},
+ "range-on-round-chest": {"chest_round": 0.05, "breaths": 2, "width_max": 0.05},
+}
+
+
+@node
+def test_the_curator_agrees_with_the_bake_on_min_max_rows(tmp_path):
+ results = _roundtrips([_matrix_run(sidecar) for sidecar in _RANGE_CELLS.values()], tmp_path)
+ failures = []
+ for (name, sidecar), got in zip(_RANGE_CELLS.items(), results):
+ try:
+ _check_matrix_cell(name, "cell", sidecar, got)
+ except Exception as exc:
+ failures.append(f"[{name}] {type(exc).__name__}: {exc}")
+ assert not failures, "\n\n".join(failures)
+ accepted = [name for name, sidecar in _RANGE_CELLS.items() if _bake_verdict(sidecar)[0]]
+ assert accepted == ["depth-x-and-band", "smooth-range", "range-partial"], accepted