Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(breathe): pixel breathes round from the chest, the arms move sideways whole with what they hold, held cells keep their bytes, and every held piece's cell is drawn, counted or refused
Soohong Kim2a14057a4f57
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8bce3ce..ad7271f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,13 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased+**Upgrading from 3.3.0: a pixel Breathe row can now breathe round from the chest, with the arms moving sideways (`chest_round`, `arms_x`), and `sprite-gen breathe` takes cells held still (`--hold-mask`), what the arms hold (`--props-mask`), pieces held behind the body (`--props-behind-mask`), and props grouping (`--props-groups`). All are off by default: every existing sidecar, flag and output keeps its bytes, and so does every normalized sidecar.**++- **New: the round chest (pixel; `chest_round`, `arms_x`, flags `--chest-round`, `--arms-x`).** When either is above 0, a pixel row bakes the round chest instead of the envelope squash. Both are shares of the body below the neck (0 to 0.20). The rim of the chest ellipse (smooth's `chest_*` keys) moves out from its peak by `chest_round`. Inside the ellipse the body stretches evenly from the peak; outside it the body is pushed whole, so a 1 px outline stays 1 px. Above the peak the chest goes up and out; below the peak it goes sideways only, fading to nothing at the feet. The head above the rigid boundary keeps its place and bytes, as in smooth. Below the rigid boundary, the sideways share (the chest's sideways push and the arms) turns on over the longer of 0.15 of the neck band and 1.5 times the sideways px (`chest_round` plus `arms_x` in px), and the body's following of a held piece turns on over the longer of 0.15 of the neck band and 1.5 times the largest piece move in px (if it turns on over less, rows just below the head line slide more than one cell per row against each other and an outline crossing the head line breaks; with 1.5 times, no row slides more than about one cell against the next because the steepest slope of the smooth turn on is 1.5 over its length). The arms (the columns outside where appendage protection starts) are pushed whole by the chest and then sideways by `arms_x` on top, never stretched; the torso's sides take the stretch over 12 times that push. The breath is smooth's one-sided curve (`inhale`, `breaths`, `breath_peaks`, `loop_cells`, `start_cell`), so a cell at phase 0 is the source byte for byte. Every output cell is a cell of the source: no new colour, and no row or column is folded. A round row refuses `depth`, `depth_x`, `lag` and smooth-only shape keys; smooth refuses `chest_round` and `arms_x`. See [breathing](docs/breathing.md), "둥근 가슴".+- **New: held cells (`--hold-mask`), held props (`--props-mask`), props behind the body (`--props-behind-mask`), and props grouping (`--props-groups`).** All are PNGs the size of the frames; their light opaque pixels (lightness 128 or more, alpha 128 or more) are the cells. A cell may be in only one of the three masks; a cell in two is refused. Empty cells inside a props mask are not drawn; only the drawing's opaque cells of a piece move. A held cell keeps its bytes in every frame, because the field is 0 there (smooth and round rows; an envelope row refuses). Each piece of the props mask (8-connected, cells within 2 px of each other joined, as a hilt and blade parted by the hand) moves whole and sideways, as far as the hand holding it: the chest's sideways push where the piece touches the body, plus the full `arms_x` of the arm on its side. The body within 2 px of it moves the same whole cells, so no gap opens between hand and grip. A whole arm can move as one rigid block by masking it from the sleeve below the shoulder down to the hand together with what it holds as one `--props-mask` piece (one colour), starting below the sideways turn on rows. Where a piece moves onto held cells, held cells stay on top and those cells are not drawn; the engine counts them per piece and per frame in `props.pieces[i].hidden` and `hidden_max` of `breathe.json`, printing one warning line on stderr of the form `breathe: warning: --props-mask piece K of N (C cells) goes under held cells in F of T frames, up to M cells (frame X); those cells are not drawn` followed by `breathe.json props.pieces[K-1].hidden`. In each row, the engine looks at the first cell right behind the moved piece: when that cell is a held cell, it repeats over the cells the piece left (water fills where a blade left the water band; a held back fills where a sleeve moved away), and otherwise the body fills it; no empty cell is made up. The engine counts cells a piece fills by repeating a cell or left by the field where the body does not follow fully rather than moving them in `props.pieces[i].filled` and `filled_max` of `breathe.json` (held cells themselves are never counted), printing one warning line on stderr of the form `breathe: warning: --props-mask piece K of N (C cells) leaves cells it fills by repeating a cell in F of T frames, up to M cells (frame X); those cells are made up, not moved` followed by a space and `breathe.json props.pieces[K-1].filled`. Pieces held behind the body (`--props-behind-mask`, off by default) take the same sideways move, but the body stays in front, does not follow, and the piece is drawn under held cells, under the body, and under pieces held in front; all pieces behind the body are drawn first, then all pieces in front, including pieces that do not move in that frame (so a resting front piece is not covered by a behind piece), and held cells are always on top; where it pulls out from behind the body, the piece's cell touching the body in that row repeats over the cells it left (making the piece look wider by that many cells, as the shield's edge column repeats), while cells left where nothing was in front become empty; the cells it fills by repeating a cell are counted in `props_behind.pieces[i].filled` and `filled_max` with a warning line on stderr of the form `breathe: warning: --props-behind-mask piece K of N (C cells) leaves cells it fills by repeating a cell in F of T frames, up to M cells (frame X); those cells are made up, not moved` followed by a space and `breathe.json props_behind.pieces[K-1].filled`; its hidden cells (under held cells, the body, or a front piece) are counted in `props_behind.pieces[i].hidden` and `hidden_max` with a warning line reading `goes under held cells, the body or a piece held in front of it` and naming `--props-behind-mask`. A piece ledger maintains a source map of which source cell each output cell shows, reading all counts off this map in every frame. Before drawing, each piece is checked at its whole-cell destination and refused if pushed off the cell (naming the mask flag, piece as i/n with its cell count, opaque cells leaving, side crossed with its count like `왼쪽 변 밖 3`, cell size, and move, advising to widen the cell margin or lower `chest_round` or `arms_x`; covering behind pieces, rows above the head line, and rounding edges); the body's own off-cell refusal now counts body cells only and names the side crossed with its count. Two pieces of one layer landing on one cell are refused (advising `--props-groups colour` or moving one to the other mask); a behind piece and the body in front moving apart to leave empty cells is refused (advising to mask only the part showing outside the body as `--props-behind-mask` or give it as `--props-mask`); and in every frame the cells shown at destination plus hidden cells must equal the piece's opaque cells in the still, refusing as an engine defect if not. With `--props-groups colour` (default `piece`; refused without a props mask), both props masks are read by colour: light opaque cells of one colour form one group moving by the whole cells read where the group touches the body, allowing unheld elements like reflections to follow a prop. `breathe.json` records `hold`, `props`, and `props_behind` (path, sha256, cells, each piece's `shift_px`, `hidden`, `hidden_max`, `filled`, `filled_max`), with each piece carrying `colour` and the mask carrying `groups: "colour"` and `colours` when grouped by colour. `sprite-gen breathe` also takes `--axis-x` and `--torso-half`, the sidecar's existing overrides, so a figure whose arms lie inside the measured torso can name them.+- **Curator**: a round row is kept as written and its preview and video export are refused, as for smooth rows; the mirrored key lists are checked against the bake's.+- **Tests**: `tests/effects/test_breathe_round.py` (on a synthetic figure: the rest is the source and the head never moves; the chest swells round from one point, the line above the peak rises and the line below it does not; no new colour, no fold, a 1 px outline; the arms move sideways whole; a bar held in the hand moves with it and no gap opens; held cells keep their bytes under the round chest and under smooth; a bar going under a held water band is counted per frame in `breathe.json` and warned on stderr, held cells keep their bytes and the cells it left in the water rows are water (no gap); a reflection painted the bar's colour with `--props-groups colour` follows the bar by the same cells in every frame, the cells it left show the still's water, and no new colour appears; a shield given as `--props-behind-mask` slides out from behind a held arm with its rim cell filling the space and no gap, while given as `--props-mask` the held arm's outline fills that space instead; `--props-groups` without a props mask is refused; the new keys off keep every byte; wrong keys are refused; the CLI bakes what the library bakes and records both masks; a piece pushed off the canvas, behind the body or in front, is refused with its name and the side, and no folder is left; a piece above the head line pushed off the canvas is refused; the body pushed off the canvas names the side; the cells a piece fills (a shield sliding out from behind an arm, a bar leaving a held water band) are recorded per frame in `breathe.json` and warned, and match a count made independently from a tag picture (every cell carries its own index); in eight scenes every cell of every piece is drawn at its destination or counted as hidden in every frame, and the filled count matches the independent count; two pieces of one layer landing on one cell are refused; a piece in front stays over a piece behind, whether it moves over it or the behind piece moves under it; a piece behind the body moving apart from it is refused; the ledger changes no byte of seven scenes baked before it (no masks, held legs only, the held bar, the bar in the water, the colour group reflection, the shield behind and in front); a row with only held cells records no piece ledger) and `tests/effects/test_breathe_round_curator.py` (the mirror refuses a round row; the round trip keeps a round sidecar as written and keeps a refused one with a notice; the mirrored key lists).+**Upgrading from 3.3.0: A walk or run loop is cut to the same bytes, whether a part pops in it or not; every walk and run report gains `part_pop` and `retake`.** `--unfixed refuse` also refuses a loop recorded `retake` reason `part-pop`, whatever `--repair`. No flags are added; no frames are made and no other cut is taken.- **New: The part reading and the `retake` record.** Squares 8 % of the body height are followed drawing to drawing and a part whose jerk leaves the curve its steps either side draw pops at the wrap. The cut stays and the report records a take to film again (`retake`, reason `part-pop`): `remedy` is `retake` where the engine's search chose the cut, and `recut-or-retake` where the cut was given (`--cycle fixed`, or `pinned`); `searched` says which. See [loop-repair](docs/loop-repair.md) section 2, "The part pop".diff --git a/SKILL.md b/SKILL.mdindex d32b820..a50613a 100644--- a/SKILL.md+++ b/SKILL.md@@ -112,7 +112,7 @@ front-facing observations also remain unchanged. Mirroring does not preserve lef| Curation view or existing image candidates | `curation`, `unpack-atlas --pngs-dir` | [curation](docs/curation.md) || Uniform background removal or imported sheets | `cutout`, `slice-sheet` | [sheet-slicing](docs/sheet-slicing.md) || Palette swap | `sprite-gen recolor-palette`, `sprite-gen recolor` | [recolor](docs/recolor.md) |-| Idle breathing as a post-processing layer (the Breathe layer): pixel (default, pixel art) or smooth (large illustrations, video frames: head fixed, chest breathes, shoulders follow; facing values for a turned body); smooth can choose a beat that misses the hands with `--avoid-region`, and a way in or out of a loop carries on its breath with `--loop-cells`, `--start-cell` and `--reference` | curation sidecar, baked by compose; or `sprite-gen breathe <frames> <out>` on a folder of loop frames | [breathing](docs/breathing.md) |+| Idle breathing as a post-processing layer (the Breathe layer): pixel (default, pixel art) or smooth (large illustrations, video frames: head fixed, chest breathes, shoulders follow; facing values for a turned body); smooth can choose a beat that misses the hands with `--avoid-region`, and a way in or out of a loop carries on its breath with `--loop-cells`, `--start-cell` and `--reference`; pixel can breathe round from the chest with the arms moving sideways (`--chest-round`, `--arms-x`), cells held still (`--hold-mask`), what the arms hold moving whole with them (`--props-mask`), what the arms hold behind the body (a shield hung at the back) moves the same way with the body staying in front (`--props-behind-mask`), and pieces painted one colour move together (`--props-groups colour`, so a sword's reflection follows the sword) | curation sidecar, baked by compose; or `sprite-gen breathe <frames> <out>` on a folder of loop frames | [breathing](docs/breathing.md) || Engine exports | `export-aseprite`, `export-pngs` | [engine-export](docs/engine-export.md) || Background recipe or repeating tile | existing `gen` / `cutout`, then optional `background-tile` | [asset-tools](docs/asset-tools.md#background-recipe) || Ground tile that repeats both ways | `gen` (opaque), then `background-tile --axis xy` | [asset-tools](docs/asset-tools.md#both-axes-a-ground-tile) |diff --git a/docs/breathing.md b/docs/breathing.mdindex e93f365..0cdb088 100644--- a/docs/breathing.md+++ b/docs/breathing.md@@ -51,9 +51,11 @@ smooth 모드의 고정 영역과 동작 방식은 다음과 같다.| `start_cell` | 0 | 0 이상 loop_cells 미만의 정수 | 행이 시작하는 루프의 셀. 행의 셀 i는 루프의 셀 (start_cell + i) mod loop_cells의 위상을 갖는다 || `breaths` | - | 1에서 8 | 루프에 들어맞는 정수 호흡 횟수 || `breath_peaks` | - | - | 각 들숨 정점 셀 목록 (외부 타이밍 조절용) |+| `chest_round` | 0 (꺼짐) | 0에서 0.20 | pixel 둥근 가슴: 들숨 정점에서 가슴 테두리가 꼭대기 P 에서 바깥으로 나가는 양 (목 아래 몸통 높이 비율, 아래 "둥근 가슴" 절) |+| `arms_x` | 0 (꺼짐) | 0에서 0.20 | pixel 둥근 가슴: 들숨 정점에서 팔이 몸 바깥쪽으로 가로로 통째 밀리는 양 (목 아래 몸통 높이 비율) |거부 조건은 다음과 같다.-- 허용 범위를 벗어난 값은 무시되지 않고 거부된다. pixel 행에 smooth 전용 형상 키(`chest_y`, `chest_rx`, `chest_ry`, `shoulder`, `shoulder_lag`, `chest_tilt`, `chest_bias`, `chest_bias_y`, `chest_dir`, `chest_x`, `chest_flat`, `inhale`)나 `breath_peaks`, 또는 역시 smooth 전용인 `start_cell`과 `loop_cells`를 지정해도 무시되지 않고 거부된다.+- 허용 범위를 벗어난 값은 무시되지 않고 거부된다. pixel 행에 smooth 전용 형상 키(`chest_y`, `chest_rx`, `chest_ry`, `shoulder`, `shoulder_lag`, `chest_tilt`, `chest_bias`, `chest_bias_y`, `chest_dir`, `chest_x`, `chest_flat`, `inhale`)나 `breath_peaks`, 또는 역시 smooth 전용인 `start_cell`과 `loop_cells`를 지정해도 무시되지 않고 거부된다. 예외는 둥근 가슴 pixel 행(`chest_round`나 `arms_x`가 0보다 큼)이다. 이 행은 가슴 타원 키(`chest_y`, `chest_rx`, `chest_ry`, `chest_tilt`, `chest_bias`, `chest_bias_y`, `chest_x`)와 `inhale`, `breath_peaks`, `start_cell`, `loop_cells`를 smooth 와 같은 검사로 받는다.- 루프의 한 토막에 대한 값도 조정하거나 감싸지 않고 거부한다. `start_cell`이 음수이거나 정수가 아닌 경우, `loop_cells`가 2 미만이거나 정수가 아닌 경우, `start_cell`이 `loop_cells` 이상인 경우, `loop_cells`를 생략한 채 `start_cell`이 행의 셀 수 이상인 경우(베이크 시점에 거부), 그리고 `breath_peaks`의 마지막 정점이 `loop_cells`의 끝에서 한 셀 이내인 경우가 그렇다.- 정점 P는 타원 내부에 머물러야 하므로, `chest_bias`와 `chest_bias_y`를 합쳐 반지름의 0.9를 초과하면 거부된다.- `breath_peaks`에 셀 0의 정점이 포함되거나, 정점이 증가하는 순서가 아니거나, 정점 간격이 2셀보다 가깝거나, 마지막 정점이 루프 끝에서 1셀 이내인 경우 거부된다. `breaths`가 함께 지정되었으나 정점 개수와 일치하지 않는 경우도 거부된다.@@ -65,11 +67,13 @@ smooth 모드의 고정 영역과 동작 방식은 다음과 같다.비디오 루프 셀처럼 큐레이션 실행이 아닌 프레임 폴더를 처리할 때는 독립 명령어를 사용한다.```bash-sprite-gen breathe <frames> <out> [--mode pixel|smooth] [--depth D] [--depth-x D] [--breaths N] [--breath-peaks ...] [--lag L] [--rigid-row R] [--chest-y ...] [--chest-rx ...] [--chest-ry ...] [--shoulder ...] [--shoulder-lag ...] [--chest-tilt ...] [--chest-bias ...] [--chest-bias-y ...] [--chest-dir ...] [--chest-x ...] [--chest-flat ...] [--inhale S] [--loop-cells N] [--start-cell K] [--reference FRAME.png] [--avoid-region X0,Y0,X1,Y1 [--avoid-anchor X0,Y0,X1,Y1] [--fps F]]+sprite-gen breathe <frames> <out> [--mode pixel|smooth] [--depth D] [--depth-x D] [--breaths N] [--breath-peaks ...] [--lag L] [--rigid-row R] [--axis-x X] [--torso-half T] [--chest-y ...] [--chest-rx ...] [--chest-ry ...] [--shoulder ...] [--shoulder-lag ...] [--chest-tilt ...] [--chest-bias ...] [--chest-bias-y ...] [--chest-dir ...] [--chest-x ...] [--chest-flat ...] [--inhale S] [--loop-cells N] [--start-cell K] [--reference FRAME.png] [--avoid-region X0,Y0,X1,Y1 [--avoid-anchor X0,Y0,X1,Y1] [--fps F]] [--chest-round S] [--arms-x S] [--hold-mask MASK.png] [--props-mask MASK.png] [--props-behind-mask MASK.png] [--props-groups piece|colour]````<frames>`는 파일 이름 순서대로 재생되는 PNG 프레임 폴더다. 사이드카와 동일한 검증과 베이크 처리를 거치므로 같은 값이면 동일한 바이트를 출력한다. 변환된 프레임들을 원본과 동일한 이름으로 저장하고, 적용된 설정과 위상 및 해부학 측정값을 담은 `breathe.json`을 새 폴더에 한 번에 작성한다. 심볼릭 링크를 추적하고 대소문자를 구분하지 않는 디스크의 서로 다른 표기를 동일하게 취급하는 실제 위치를 기준으로, `<out>`과 `<frames>`가 같은 폴더이거나 어느 한쪽이 다른 쪽 내부에 있는 경우 및 이미 존재하면서 비어 있지 않은 폴더는 아무것도 생성하거나 삭제하지 않고 거부하되 기존의 빈 폴더는 허용한다. `<frames>` 폴더에는 어떤 파일도 새로 쓰지 않으며, 프레임을 비롯한 기존 파일을 변경하거나 삭제하지 않는다. 결과물은 `<out>` 옆에 다른 폴더와 겹치지 않는 고유한 이름의 자체 임시 폴더에서 빌드한 뒤 한 번에 제자리로 이동하며, 작업을 완료하지 못했을 때도 오직 직접 만든 임시 폴더만 삭제하고 이전 작업의 잔여 폴더처럼 직접 만들지 않은 폴더는 그대로 둔다.+`--axis-x X`와 `--torso-half T`는 사이드카의 `axis_x`·`torso_half`(큐레이터 영역 UI 가 쓰는 사람의 오버라이드)와 같은 값이다. 몸통 축 열과 몸통 반폭을 주면 그 반폭 밖의 열이 부속(팔)이 된다. 둘 다 생략하면 이전과 같이 잰다.+`--reference FRAME.png`(모든 모드)를 주면 행의 해부학 측정값(머리 선, 가슴, 상승 높이, 프레임 안에서 해부학이 차지하는 위치)을 행의 첫 프레임 대신 그 프레임에서 측정한다. 프레임들과 같은 크기여야 하며 다르면 거부된다. 루프 세트의 첫 셀을 지정하면, 첫 프레임이 루프와 다른 토막(예: 머리를 든 상태로 시작하는 경우)도 루프의 해부학으로 베이크된다. 이때 `breathe.json`에는 그 파일의 `path`와 `sha256`을 담은 `reference`가 기록된다. 예를 들어 두 번 호흡하는 96셀 루프의 셀 40에서 시작하는, 루프에서 빠져나가는 토막은 다음과 같이 베이크한다.```bash@@ -91,7 +95,35 @@ sprite-gen breathe way-out/ way-out-breathed/ --mode smooth --breaths 2 --loop-csprite-gen breathe frames/ out_frames/ --mode smooth --depth 0.0085 --breaths 2```-큐레이션 웹뷰 사용 시 제한사항이 있다. 웹뷰의 실시간 미리보기는 pixel 워프만 반영하므로 smooth 행은 미리보기를 지원하지 않는다. 웹뷰에서는 안내 문구와 함께 원본 프레임을 보여주며, smooth 행의 비디오 내보내기는 거부된다. 사이드카를 저장하면 smooth 설정은 작성한 내용 그대로 보존된다. 실제 결과는 compose 명령어(GIF, atlas) 또는 `sprite-gen breathe` 명령어로 확인해야 한다.+큐레이션 웹뷰 사용 시 제한사항이 있다. 웹뷰의 실시간 미리보기는 pixel 봉투 워프만 반영하므로 smooth 행과 둥근 가슴 pixel 행은 미리보기를 지원하지 않는다. 웹뷰에서는 안내 문구와 함께 원본 프레임을 보여주며, 이 행들의 비디오 내보내기는 거부된다. 사이드카를 저장하면 이 행들의 설정은 작성한 내용 그대로 보존된다. 실제 결과는 compose 명령어(GIF, atlas) 또는 `sprite-gen breathe` 명령어로 확인해야 한다.++## 둥근 가슴 (pixel) — `chest_round`·`arms_x`++pixel 의 봉투 스쿼시는 가로줄을 통째로 눌렀다 늘인다. 머리가 몸통 위에서 통째로 오르내리고, 팔과 쥔 물건과 다리까지 옆으로 밀리며, 숨이 줄 단위로 읽힌다. 둥근 가슴은 같은 도트 그림에서 가슴 한 점을 중심으로 둥글게 부풀었다 줄고, 팔은 옆으로 벌어졌다 모이며, 머리와 선 발은 그대로 둔다.++- 켜기: `chest_round`(가슴)나 `arms_x`(팔) 중 하나가 0보다 크면 그 pixel 행은 봉투 스쿼시 대신 둥근 가슴 장을 굽는다. 둘 다 목 아래 몸통 높이(정규화 기준 행)의 비율이고 범위는 0에서 0.20이다. 생략하거나 0이면 꺼져 있고, 출력과 정규화된 사이드카 모두 이전과 바이트 단위로 같다.+- 가슴: smooth 와 같은 가슴 타원(`chest_y`, `chest_rx`, `chest_ry`, `chest_tilt`, `chest_bias`, `chest_bias_y`, `chest_x`)의 테두리가 들숨 정점에서 꼭대기 P 로부터 바깥으로 `chest_round` × 기준 높이 px 나간다. 타원 안은 P 에서 테두리까지 고르게 늘고, 타원 밖은 같은 px 만큼 통째로 밀려 1 px 윤곽선이 1 px 로 남는다. P 보다 위는 위와 옆으로, P 보다 아래는 옆으로만 간다. 아래로 밀면 선 발이 눌리기 때문이다. 가로 밀림은 타원의 아래 테두리에서 콘텐츠 맨 아래까지 0으로 줄어든다.+- 머리: 강체 경계 위는 모든 셀에서 자리와 바이트가 그대로다 (smooth 와 같다). 오르는 몫은 목 밴드(강체 경계에서 smooth 와 같은 폭)에서 켜진다. 목 너비 안은 밴드 전체에 걸쳐 켜지고, 그 밖은 오르는 px 의 12배나 밴드의 0.15 가운데 긴 쪽(밴드보다 길지는 않다)에 걸쳐 켜진다. 더 짧으면 머리 밑이 행당 상한을 넘게 눌리기 때문이다. 옆으로 가는 몫(가슴의 가로 밀기와 팔)은 강체 경계 아래에서 목 밴드의 0.15나 가로 px(`chest_round` 더하기 `arms_x` px)의 1.5배 가운데 긴 쪽에 걸쳐 켜지고, 몸이 쥔 물건을 따라가는 움직임은 밴드의 0.15나 가장 큰 조각 이동 px의 1.5배 가운데 긴 쪽에 걸쳐 켜진다. 더 짧으면 머리선 바로 아래 행들이 서로 행당 한 칸 넘게 미끄러져 머리선을 넘나드는 외곽선(어깨선)이 깨지기 때문이다. 1.5배에서는 어떤 행도 다음 행에 대해 대략 한 칸 넘게 미끄러지지 않는다(부드러운 켜짐의 가장 가파른 기울기가 길이 대비 1.5다).+- 팔: 부속 경계(봉투 스쿼시의 부속 보호가 시작하는 자리 — 사람이 준 `torso_half`면 그 반폭, 아니면 해부가 잰 몸통 반폭의 1.15배) 바깥의 열은 가슴이 미는 대로 통째로 밀리고, 거기에 더해 몸통 축에서 먼 쪽으로 `arms_x` × 기준 높이 px 만큼 가로로 통째 간다. 팔은 늘지 않는다. 팔 몫이 켜지는 길은 팔이 아니라 몸통 쪽에 둔다. 부속 경계 안쪽으로 그 px 의 12배(몸통 축을 넘지 않는다)에 걸쳐 옆구리가 팔을 따라 벌어진다. 더 짧으면 어깨가 행당 상한을 넘게 늘어난다. 해부가 부속을 못 찾았고 `torso_half`도 주지 않았으면 팔 몫은 없다. 팔이 몸통 실루엣 안에 붙어 있으면 `torso_half`로 몸통 반폭을 주거나, 팔이 쥔 것을 `--props-mask`로 준다.+- 숨: smooth 와 같은 한쪽 혹 곡선이고 `inhale`, `breaths`, `breath_peaks`, `loop_cells`, `start_cell`을 같은 뜻으로 받는다. 위상 0인 셀은 원본과 바이트 단위로 같아서 루프 이음이 쉼에 놓인다. 진행파(`lag`)는 없다.+- 정수 칸: 정사상의 역을 고정점 반복으로 풀고, 그 자리에 놓인 원본 칸 하나를 통째로 옮긴다. 사잇값이 없어서 출력의 칸은 모두 원본에 있던 칸이고 새 색이 생기지 않는다. 장의 기울기가 행당 변형 상한(0.25) 아래라 어느 행과 열에서도 칸 순서가 뒤집히지 않는다.+- 거부: smooth 행의 `chest_round`, `arms_x`, 둥근 가슴 행의 `depth`, `depth_x`, `lag`(봉투 값), smooth 만 쓰는 모양 값(`shoulder`, `shoulder_lag`, `chest_dir`, `chest_flat`), 범위 밖 값, 행당 변형 상한 초과, 셀 밖으로 밀리는 불투명 칸, 그리고 해부가 팔(부속)을 못 찾았고 쥔 물건도 없는데 준 `arms_x`는 모두 조용히 넘기지 않고 거부된다. 몸 자체의 셀 밖 거부는 고정 칸이나 조각 칸을 빼고 몸 칸만 세며 pixel 봉투 거부와 같은 형식(`왼쪽 변 밖 3`, 모서리 칸은 양쪽 변 모두에 셈)으로 건넌 변과 그 수를 밝힌다. 조각이 셀 밖으로 밀리는 경우, 무엇이든 그리기 전에 각 조각을 자신의 온전한 칸 목적지(조각의 칸에 조각이 움직이는 온전한 칸 수를 더한 자리)에서 검사한다. 이 거부는 마스크 플래그, 조각의 i/n과 칸 수, 벗어난 불투명 칸 수, pixel 봉투 거부와 같은 형식(`왼쪽 변 밖 3`, 모서리 칸은 양쪽 변 모두에 셈)으로 건넌 변과 그 수, 셀 크기, 조각의 이동량을 밝히고, 셀 여백을 넓히거나 `chest_round` 또는 `arms_x`를 줄이라고 안내한다. 이는 몸 뒤 조각(장이 건너뜀), 머리선 위처럼 몸이 온전히 따르지 않는 행의 조각, 그리고 둥글림 가장자리를 포괄한다.++### 고정 칸, 쥔 물건, 등 뒤 물건, 묶음: `--hold-mask`, `--props-mask`, `--props-behind-mask`, `--props-groups`++`sprite-gen breathe`는 사람이 준 마스크 셋(`--hold-mask`, `--props-mask`, `--props-behind-mask`)을 받는다. 모두 프레임과 같은 크기의 PNG이고, 밝은(명도 128 이상) 불투명(알파 128 이상) 칸이 그 마스크의 칸이다. 물건 마스크 안의 빈 칸(마스크가 덮은 투명 칸)은 그려지지 않고, 그림의 불투명 칸만 조각으로 움직인다. 크기가 다르거나 칸이 하나도 없으면 거부된다. 한 칸이 셋 가운데 둘 이상의 마스크에 들어가면 거부된다.++- `--hold-mask`(고정 칸): 그 칸은 모든 셀에서 그 셀의 바이트 그대로다. 굽기가 덮어서 되돌리는 것이 아니라 변위장 자체가 고정 칸에서 0이다. 장은 고정 칸에서 그 줄을 따라(가로 성분은 같은 행, 세로 성분은 같은 열) 멀어지며 다시 켜지고, 줄의 몸(고정 칸도 쥔 물건도 아닌 불투명 칸)이 가장 크게 움직이는 px 의 12배를 지나면 온전하다. 그래서 고정 칸 옆을 나란히 지나는 움직임(고정된 다리 위 몸통의 가로 부풂)은 줄지 않는다. smooth 행과 둥근 가슴 pixel 행이 받는다. 봉투 스쿼시 행은 가로줄을 통째로 옮겨 칸을 제자리에 둘 수 없어 거부한다.+- `--props-mask`(쥔 물건, 칼이나 방패처럼 팔이 쥔 것): 마스크의 조각마다 가로로 통째 옮겨진다. 조각은 8-이웃으로 이어진 칸이고, 서로 2 px 안에 떨어진 칸들(쥔 손 칸이 사이에 끼어 갈라진 칼자루와 칼날처럼)은 한 조각이다. 늘지 않는다. 옮기는 양은 쥔 손이 가는 만큼이다. 조각이 몸(고정 칸도 쥔 물건도 아닌 불투명 칸)에 닿은 칸들에서 읽은 가슴의 가로 몫의 평균에, 조각 가운데가 놓인 쪽 팔의 몫(`arms_x` × 기준 높이 px, 몸 바깥쪽)을 다 더한다. 몸에 닿은 칸이 없으면 조각 전체에서 읽는다. 조각 둘레 2 px 안의 몸(쥔 손)은 정확히 같은 칸만큼 옮겨지고, 거기서 몸에 닿은 자리에서 몸의 장과 다른 px 의 12배에 걸쳐 몸의 장으로 돌아간다(두 조각의 길이 겹친 몸은 둘을 섞는다). 머리(강체 경계 위)는 쥔 물건 옆에서도 그대로다. 그래서 손과 손잡이 사이가 벌어지거나 겹치지 않는다. 조각이 고정 칸 쪽으로 가면 고정 칸 밑으로 들어가 그려지지 않고, 고정 칸이 위에 남는다(칼날이 고정된 물 밴드 밑으로 잠기는 식이다). 엔진은 이 칸들을 조용히 버리지 않고, 조각마다 프레임마다 고정 칸 밑으로 들어간 조각의 불투명 칸 수를 센다. `breathe.json`은 이를 `props.pieces`의 각 조각에 `hidden`(프레임 순서대로 프레임당 수를 담은 목록)과 `hidden_max`(그 가운데 최댓값)로 기록한다. 가려진 칸이 있는 조각마다 `sprite-gen breathe`는 stderr에 `breathe: warning: --props-mask piece K of N (C cells) goes under held cells in F of T frames, up to M cells (frame X); those cells are not drawn` 형태 뒤에 공백과 `breathe.json props.pieces[K-1].hidden`이 붙는 경고를 한 줄 출력한다. 조각이 떠난 칸의 경우, 각 행에서 조각 바로 뒤(움직이는 방향의 반대쪽) 첫 칸을 본다. 몸 앞에 쥔 조각은 둘레의 몸이 같은 온전한 칸만큼 움직여 장이 이미 채운다. 그러나 바로 뒤의 그 칸이 고정 칸이면 고정 칸은 제자리에 머물러 장이 가져올 수 없으므로, 그 고정 칸이 조각이 떠난 칸들에 걸쳐 반복된다(칼날이 물 밴드를 벗어난 자리를 물이 채우고, 소매가 물러난 자리를 고정된 등이 채운다). 빈 칸을 지어내지 않는다. 엔진은 이처럼 앞 조각이 떠난 칸에 고정 칸이 반복되거나 몸이 조각을 완전히 따르지 않는 행에서 장이 남긴 복사본처럼 그 프레임에서 옮겨진 것이 아니라 조각의 이동이 지어낸 칸 수를 센다(고정 칸 자체는 결코 세지 않는다). `breathe.json`은 이를 `props.pieces`의 각 조각에 `filled`(프레임 순서대로 프레임당 수를 담은 목록)와 `filled_max`(그 가운데 최댓값)로 기록한다. 채워진 칸이 있는 조각마다 `sprite-gen breathe`는 stderr에 `breathe: warning: --props-mask piece K of N (C cells) leaves cells it fills by repeating a cell in F of T frames, up to M cells (frame X); those cells are made up, not moved` 형태 뒤에 공백과 `breathe.json props.pieces[K-1].filled`가 붙는 경고를 한 줄 출력한다. 어깨 아래 소매부터 손까지 팔 전체를 쥔 물건과 함께 하나의 `--props-mask` 조각(한 색)으로 마스크하면 팔 전체를 하나의 강체 블록으로 옮길 수 있으며, 블록 둘레의 몸은 다른 쥔 물건처럼 이를 따라간다. 가로 움직임이 켜지는 행들 아래에서 블록을 시작해야 하며, 그렇지 않으면 맨 위 행이 바로 윗행에 대해 미끄러진다. 둥근 가슴 pixel 행에 `arms_x`가 있어야 받는다.+- `--props-behind-mask MASK.png`(등 뒤에 쥔 물건, 기본값 꺼짐): 등 뒤에 맨 방패처럼 몸 뒤에 쥔 물건이다. `--props-mask` 조각과 같은 가로 움직임을 취한다(조각이 몸에 닿은 자리에서 가슴의 가로 몫을 평균하고, 그쪽 팔의 온전한 `arms_x`를 더하는 같은 규칙이다). 그러나 몸이 그 앞에 머문다. 몸은 이를 따라가지 않고, 장은 이를 제외하며(몸과 외곽선은 몸 자체의 장을 계속 따른다), 고정 칸 밑, 몸 밑, 그리고 앞에 쥔 조각 밑에 그려진다. 조각이 몸 뒤에서 빠져나오는 곳에서는 그 행에서 몸에 닿아 있던 조각의 칸이 조각이 떠난 칸들에 걸쳐 반복된다(몸 뒤에 숨어 있던 조각 부분이 밖으로 나온다). 앞에 아무것도 없던 자리에서는 조각이 떠난 칸이 빈 칸이 된다. 반복된 칸들 때문에 조각이 그 칸 수만큼 더 넓어 보인다(방패 가장자리 열이 반복된다). 목적지에서 벗어나 나타난 조각 자체 칸의 복사본(조각이 빠져나오며 떠난 칸에 몸에 닿아 있던 칸이 반복되어 방패가 더 넓어 보이는 까닭)은 옮겨진 것이 아니라 조각의 이동이 지어낸 칸으로 센다. `breathe.json`은 이를 `props_behind.pieces`의 각 조각에 `filled`(프레임 순서대로 프레임당 수를 담은 목록)와 `filled_max`(그 가운데 최댓값)로 기록한다. 채워진 칸이 있는 조각마다 `sprite-gen breathe`는 stderr에 `breathe: warning: --props-behind-mask piece K of N (C cells) leaves cells it fills by repeating a cell in F of T frames, up to M cells (frame X); those cells are made up, not moved` 형태 뒤에 공백과 `breathe.json props_behind.pieces[K-1].filled`가 붙는 경고를 한 줄 출력한다. 고정 칸 밑, 몸 밑, 또는 앞에 쥔 조각 밑으로 들어간 가려진 칸은 똑같이 세어 `breathe.json`의 `props_behind.pieces[i].hidden`과 `hidden_max`에 기록되고, 이제 `goes under held cells, the body or a piece held in front of it`로 읽히며 `--props-behind-mask`를 명시하는 경고 줄이 stderr에 출력된다.+- 조각 원장(piece ledger): 조각을 배치하는 동안 베이크는 모든 출력 칸에 대해 그 칸이 어떤 원본 칸을 보여주는지를 기록하는 원본 맵(source map)을 유지한다. 아래의 모든 수치는 그리는 특수 사례가 아니라 매 프레임 이 맵에서 읽는다. 레이어 순서는 몸 뒤의 모든 조각을 먼저 그리고, 그 프레임에서 움직이지 않는 조각을 포함하여 앞의 모든 조각을 그 다음에 그리므로 앞 조각은 항상 뒤 조각 위에 온다. 고정 칸은 언제나 맨 위에 놓인다. 이동 후 한 레이어의 두 조각(두 앞 조각, 또는 몸 뒤의 두 조각)이 한 칸에 내리는 것은 마스크가 어느 쪽이 앞인지 말해주지 않으므로 거부된다(메시지의 안내: `--props-groups colour`로 한 색으로 묶거나 둘 중 하나를 다른 마스크로 옮길 것). 몸 뒤 조각과 그 앞의 몸이 서로 벌어져 스틸에서 불투명했던 칸이 몸도 조각도 없이 비게 되는 경우도 거부된다. 이는 몸 뒤 조각이 몸 안쪽까지 칠해졌을 때 일어나며, 메시지에서 몸 바깥으로 드러난 부분만 `--props-behind-mask`로 주거나 그 부분을 `--props-mask`로 주라고 안내한다. 매 프레임 검사: 각 조각마다 목적지에 표시된 칸과 가려진 칸의 합은 스틸에서 그 조각의 불투명 칸 수와 같아야 하며, 그렇지 않으면 베이크는 엔진 결함으로 거부된다.+- `--props-groups piece|colour`(기본값 `piece`, 조각마다 제 손을 따름): `colour`를 주면 두 물건 마스크 모두 색으로 읽는다. 한 색의 밝은 불투명 칸(명도 128 이상, 알파 128 이상)이 한 묶음을 이루며, 어느 마스크에 있든 어디에 놓여 있든 한 묶음의 모든 조각은 같은 온전한 칸만큼 움직인다. 이동량은 그 묶음이 몸에 닿은 자리에서 읽는다(가슴의 가로 몫을 거기서 평균하고, 묶음 중심이 놓인 쪽 팔의 온전한 `arms_x`를 더한다). 손이 닿지 않는 조각, 예컨대 칼과 같은 색으로 칠한 물속의 칼 반사도 칼을 따라 움직인다. 각 조각의 기록에는 `colour`("#rrggbb")가 실리고 마스크 기록에는 `groups: "colour"`와 `colours`(마스크가 가진 색의 수)가 실린다. 물건 마스크 없이 `--props-groups`를 쓰면 거부된다. 칸으로 인정받으려면 색이 밝아야 한다.+- 마스크를 주면 행당 변형 검사는 몸(고정 칸도 쥔 물건도 아닌 불투명 칸)과 그 둘레 한 칸에서 잰다. 고정 칸, 쥔 물건 조각과 그 이웃, 그리고 고정 칸과 조각의 통째 둘레가 2 px 안에서 맞닿는 이음은 뺀다. 통째로 옮겨지는 조각과 제자리인 고정 칸이 맞닿은 자리의 끊김은 접힘이 아니라 조각이 고정 칸 밑으로 들어가거나 거기서 나오는 것이고, 빈 칸끼리 늘고 주는 것은 보이는 것이 없기 때문이다. 마스크가 없으면 예전과 같이 콘텐츠 상자 전체에서 잰다.+- `breathe.json`에는 `hold`(`path`, `sha256`, `cells`)와 `props`(같은 기록과 조각마다 `cells`, 들숨 정점의 가로 `shift_px`, `hidden`, `hidden_max`, `filled`, `filled_max`)가 실린다. `--props-behind-mask`를 주면 `props_behind`에도 같은 기록과 조각마다 `cells`, `shift_px`, `hidden`, `hidden_max`, `filled`, `filled_max`가 실린다. 세 마스크는 아직 큐레이션 사이드카의 키가 아니고 `sprite-gen breathe`에서만 받는다.++```bash+sprite-gen breathe still-loop/ breathed/ --chest-round 0.04 --arms-x 0.03 --breath-peaks 72,192 --inhale 0.6 --hold-mask feet.png --props-mask sword-shield.png --props-behind-mask shield.png --props-groups colour+```## What Breathe does (from the README, 2026-09-09)diff --git a/sprite_gen/curate/curation.py b/sprite_gen/curate/curation.pyindex b184be5..2303451 100644--- a/sprite_gen/curate/curation.py+++ b/sprite_gen/curate/curation.py@@ -253,6 +253,14 @@ BREATHE_SMOOTH_PEAK_REACH = 0.9# 조각이 idle 의 숨을 위상 그대로 잇는다. 칸 i 의 위상은 루프 칸 (start_cell + i) mod loop_cells 의 위상이고 숨 박자# (breaths·breath_peaks)는 그 루프의 것이다. 생략은 줄이 곧 루프다 (start_cell 0, loop_cells 는 줄의 칸 수).BREATHE_STRETCH_KEYS = ("start_cell", "loop_cells")+# pixel 의 둥근 가슴과 양팔 가로 (`sprite_gen.effects.breathe` round 장): chest_round 는 들숨 꼭대기에서 가슴 테두리가+# 꼭대기 P 에서 바깥으로 나가는 양, arms_x 는 팔(해부가 몸통 밖 부속으로 읽은 열)이 옆으로 밀려 나가는 양 — 둘 다 목 아래+# 몸통 높이(정규화 기준) 비율이다. 둘 중 하나가 0 보다 크면 그 pixel 줄은 봉투 스쿼시 대신 이 장을 굽는다 (생략·0 은 꺼짐,+# 이전과 바이트 같다). 이 줄은 smooth 의 가슴 타원 키와 숨 박자 키를 읽는다 — 진행파(lag)와 봉투 진폭(depth·depth_x)은+# 쓰지 않는다.+BREATHE_ROUND_KEYS = ("chest_round", "arms_x")+BREATHE_ROUND_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 = {"splits": "분할선은 봉투 경계로 대체됐다 — 경계는 자동 검출되고 `rigid_row` 로만 덮어쓴다",@@ -294,7 +302,12 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]`depth` 생략은 `BREATHE_SMOOTH_DEPTH`, `depth_x` 생략은 `BREATHE_SMOOTH_DEPTH_X` 이며, 모양 값(`BREATHE_SMOOTH_SHAPE` 의 키, 들숨 몫 `inhale` 포함)이 기본값과 함께 실린다. 루프의 한 토막(`start_cell`,`loop_cells` — `BREATHE_STRETCH_KEYS`)도 smooth 에 늘 실린다 (생략이면 0 과 None, 줄이 곧 루프). 모양 값과 토막은- smooth 만 쓴다 — pixel 줄에 있으면 조용히 무시하지 않고 거부한다."""+ smooth 만 쓴다 — pixel 줄에 있으면 조용히 무시하지 않고 거부한다.++ 예외는 둥근 가슴 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"} 다."""if not curation:return Noneentry = curation.get("states", {}).get(state)@@ -315,8 +328,37 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]f"curation: states.{state}.breathe.mode = {mode!r} 를 모른다 — "f"{' | '.join(BREATHE_MODES)} 중 하나다 (생략하면 pixel). 조용히 pixel 로 굽지 않는다.")smooth = mode == "smooth"+ # pixel 의 둥근 가슴·양팔 가로 — 생략(None)·0 은 꺼짐. 하나라도 0 보다 크면 그 줄은 round 장을 굽는다.+ amps = {}+ for name in BREATHE_ROUND_KEYS:+ if raw.get(name) is None:+ continue+ if smooth:+ raise SystemExit(+ f"curation: states.{state}.breathe.{name} 는 pixel 의 둥근 가슴 값이다 — smooth 의 가슴은 depth·depth_x 로 "+ f"오르고 부푼다. 그 키를 지우거나 mode 를 지워라. 조용히 무시하지 않는다.")+ try:+ amps[name] = float(raw[name])+ except (TypeError, ValueError):+ raise SystemExit(f"curation: states.{state}.breathe.{name} 를 숫자로 못 읽는다: {raw[name]!r}")+ if not 0.0 <= amps[name] <= BREATHE_ROUND_MAX:+ raise SystemExit(+ f"curation: states.{state}.breathe.{name} = {raw[name]!r} 가 범위 [0.0, {BREATHE_ROUND_MAX}] 밖이다. "+ f"조용히 깎지 않는다 — 사이드카를 고쳐라.")+ rounded = any(amps.values())+ if rounded:+ envelope = sorted(k for k in ("depth", "depth_x", "lag") if raw.get(k) is not None)+ if envelope:+ raise SystemExit(+ f"curation: states.{state}.breathe 의 {', '.join(envelope)} 는 봉투 스쿼시의 값이다 — 둥근 가슴 줄"+ f"(chest_round·arms_x)은 그 진폭으로 숨쉬고 진행파가 없다. 그 키를 지워라. 조용히 무시하지 않는다.")+ stray = sorted(k for k in BREATHE_SMOOTH_SHAPE if k in raw and k not in BREATHE_ROUND_SHAPE)+ if stray:+ raise SystemExit(+ f"curation: states.{state}.breathe 의 {', '.join(stray)} 는 smooth 만 쓰는 모양 값이다 — 둥근 가슴 줄은 "+ f"가슴 타원({', '.join(BREATHE_ROUND_SHAPE)})과 숨 박자만 읽는다. 그 키를 지워라. 조용히 무시하지 않는다.")stray = sorted(k for k in (*BREATHE_SMOOTH_SHAPE, "breath_peaks", *BREATHE_STRETCH_KEYS) if k in raw)- if stray and not smooth:+ if stray and not (smooth or rounded):raise SystemExit(f"curation: states.{state}.breathe 의 {', '.join(stray)} 는 smooth 의 모양 값이다 — "f"pixel 은 쓰지 않는다. `mode: \"smooth\"` 를 적거나 그 키를 지워라. 조용히 무시하지 않는다.")@@ -330,7 +372,7 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]raw_dx = raw.get("depth_x")depth_x = None if raw_dx is None else float(raw_dx)lag = float(raw.get("lag", 0.0 if smooth else 0.10))- peaks = raw.get("breath_peaks") if smooth else None+ peaks = raw.get("breath_peaks") if smooth or rounded else Nonebreaths = _exact_int("breaths", raw.get("breaths", len(peaks) if isinstance(peaks, list) else 1), state)except (TypeError, ValueError) as exc:# 폐기 키는 요란하게 거부하면서 형식 오류만 조용히 호흡을 꺼버리면 계약이 어긋난다@@ -365,10 +407,10 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]if torso_half is not None:torso_half = _exact_int("torso_half", torso_half, state)frozen = raw.get("anatomy")- if smooth:+ if smooth or rounded:# 진행파(lag)는 윗행의 위상을 늦춰 위상 0 인 칸도 움직인다 — smooth 의 첫 칸은 원본- # 그대로여야 루프와 묶음의 이음이 안 바뀐다. 0 아닌 lag 를 조용히 버리지 않는다.- if lag != 0.0:+ # 그대로여야 루프와 묶음의 이음이 안 바뀐다. 0 아닌 lag 를 조용히 버리지 않는다 (둥근 가슴 줄은 위에서 거부했다).+ if smooth and lag != 0.0:raise SystemExit(f"curation: states.{state}.breathe.lag = {raw.get('lag')!r} — smooth 에는 진행파가 없다. "f"위상 0 인 칸이 원본 그대로여야 루프·묶음 이음이 안 바뀐다. lag 를 지워라.")@@ -400,6 +442,8 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]f"이어야 한다. 조용히 접지 않는다.")shape = {}for name, default in BREATHE_SMOOTH_SHAPE.items():+ if rounded and name not in BREATHE_ROUND_SHAPE:+ continuegiven = raw.get(name, default)try:value = float(given)@@ -416,6 +460,12 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]f"curation: states.{state}.breathe.chest_bias {shape['chest_bias']:g}, chest_bias_y "f"{shape['chest_bias_y']:g} — 꼭대기가 가슴 타원 테두리에 너무 가깝다 (반지름 비율 "f"{BREATHE_SMOOTH_PEAK_REACH:g} 안이어야 한다).")+ if rounded:+ cfg = {"chest_round": amps.get("chest_round", 0.0), "arms_x": amps.get("arms_x", 0.0), "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}+ 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,"breaths": breaths, "breath_peaks": peaks, **shape, "start_cell": start_cell, "loop_cells": loop_cells,diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.pyindex b3f2dd9..6994d23 100644--- a/sprite_gen/effects/breathe.py+++ b/sprite_gen/effects/breathe.py@@ -62,6 +62,15 @@ AI 개입 0 — 같은 입력이면 항상 같은 출력.줄 전체가 기준 칸(첫 칸)에서 잰 해부와 그 자리를 쓴다 — 영상 루프의 머리 윗선이 칸마다 흔들려도경계는 움직이지 않는다.+## 둥근 가슴 (pixel — `chest_round`·`arms_x`)++도트 그림을 봉투 대신 가슴 꼭대기 P 에서 둥글게 부푸는 2차원 변위장으로 굽는다 (`round_displacement`): 가슴 타원 안은+고르게 늘고 밖은 통째로 밀리며, 팔은 옆으로 통째 밀리고, 머리와 선 발은 그대로다. 정사상의 역을 smooth 처럼 풀되 그 자리의+원본 칸 하나를 통째로 옮긴다 — 출력의 칸은 모두 원본의 칸이라 새 색이 없다. 사람이 준 고정 칸(`--hold-mask`)은 장이 0 이라+바이트 그대로고, 팔이 쥔 물건(`--props-mask`, 몸 뒤에 든 것은 `--props-behind-mask`)은 조각마다 쥔 손과 같은 칸만큼 통째로+옮겨진다 (`row_pins`, `_place_pieces`). 고정 칸 밑으로 들어가 가려진 조각 칸은 조각마다 칸마다 세어 breathe.json 과 경고 줄에+남긴다 — 조용히 버리지 않는다.+루프 세트의 들어감·나옴 조각은 루프의 숨을 그 루프의 한 칸에서 잇는 토막이다 (`loop_cells`·`start_cell`): 칸 i 의위상은 루프 칸 (start_cell + i) mod loop_cells 의 위상이다. 토막의 첫 칸은 루프의 첫 칸이 아니라서 `sprite-gen breathe--reference` 로 루프의 첫 칸을 기준 칸으로 주면 해부와 그 자리가 루프의 것과 같다.@@ -70,7 +79,10 @@ AI 개입 0 — 같은 입력이면 항상 같은 출력.from __future__ import annotationsimport argparse+import hashlibimport math+import sys+from dataclasses import dataclassfrom pathlib import Pathfrom PIL import Image@@ -532,6 +544,25 @@ def smooth_chest_peak(anat: Anatomy, cfg: dict) -> tuple[float, float]:return cx + along * cos_t - across * sin_t, cy + along * sin_t + across * cos_t+def _chest_reach(anat: Anatomy, cfg: dict, x: np.ndarray, y: np.ndarray) -> np.ndarray:+ """콘텐츠 bbox 기준 점 (x, y) 가 가슴 타원 안에서 놓인 몫 — 꼭대기 P 에서 0, 테두리에서 1, 넘으면 밖. 꼭대기가 타원+ 가운데면 타원 반지름 그대로, 옮겨졌으면 P 에서 이 점을 지나 테두리에 닿는 반직선 위의 몫이다 (가까운 쪽은 짧은+ 거리에서, 돌아간 쪽은 긴 거리에서 1 에 닿는다). smooth 의 가슴 무게와 pixel 의 둥근 가슴이 이 한 식이다."""+ shape = _shape(cfg)+ cx, cy, rx, ry, cos_t, sin_t = _chest_frame(anat, cfg)+ along = (x - cx) * cos_t + (y - cy) * sin_t+ across_axis = (y - cy) * cos_t - (x - cx) * sin_t+ u, v = along / rx, across_axis / ry # 타원을 단위원으로 편 좌표+ pu, pv = shape["chest_bias"], shape["chest_bias_y"]+ if pu == 0.0 and pv == 0.0:+ return np.sqrt(u ** 2 + v ** 2)+ du, dv = u - pu, v - pv+ dd = du * du + dv * dv+ pd = pu * du + pv * dv+ reach = (-pd + np.sqrt(pd * pd + dd * (1.0 - pu * pu - pv * pv)))+ return np.where(dd > 0.0, dd / np.maximum(reach, 1e-300), 0.0)++def flat_cos2(r: np.ndarray, flat: float = 0.0) -> np.ndarray:"""가운데 1 에서 테두리 0 으로 떨어지는 cos² 무게 — `r` 은 가운데에서 테두리까지의 몫(0 가운데, 1 테두리, 넘으면밖). `flat` 은 가운데 둘레에서 전량(1)인 몫이고, 남은 길 (r − flat)/(1 − flat) 에서 cos² 로 떨어진다. 가슴 무게@@ -572,26 +603,11 @@ def smooth_displacement(anat: Anatomy, cfg: dict, x: np.ndarray, y: np.ndarray,band = band_end - topheight = float(anat.height)torso = float(anat.torso_half)- cx, cy, rx, ry, cos_t, sin_t = _chest_frame(anat, cfg)axis = anat.axis_x + 0.5neck_x, neck_half = _neck(anat)# 몸이 향한 쪽: 타원을 기울이고(chest_tilt), 꼭대기를 앞쪽으로 옮기고(chest_bias, chest_bias_y), 가슴이# 가는 쪽을 바로 위에서 돌린다(chest_dir). 모두 0 이면 아래 식은 이 값들이 생기기 전 식과 비트 같다.- along = (x - cx) * cos_t + (y - cy) * sin_t- across_axis = (y - cy) * cos_t - (x - cx) * sin_t- u, v = along / rx, across_axis / ry # 타원을 단위원으로 편 좌표- pu, pv = shape["chest_bias"], shape["chest_bias_y"]- if pu == 0.0 and pv == 0.0:- r = np.sqrt(u ** 2 + v ** 2)- else:- # 꼭대기 P 에서 이 점을 지나 테두리에 닿는 반직선 위의 몫 — P 에서 0, 테두리에서 1. 가까운 쪽은- # 짧은 거리에서, 돌아간 쪽은 긴 거리에서 0 으로 떨어진다.- du, dv = u - pu, v - pv- dd = du * du + dv * dv- pd = pu * du + pv * dv- reach = (-pd + np.sqrt(pd * pd + dd * (1.0 - pu * pu - pv * pv)))- r = np.where(dd > 0.0, dd / np.maximum(reach, 1e-300), 0.0)- w_chest = flat_cos2(r, shape["chest_flat"])+ w_chest = flat_cos2(_chest_reach(anat, cfg, x, y), shape["chest_flat"])px, py = smooth_chest_peak(anat, cfg)heading = math.radians(shape["chest_dir"])neckness = 1.0 - _smoothstep_array(neck_half, 1.5 * neck_half, np.abs(x - neck_x))@@ -617,20 +633,70 @@ def smooth_strain(anat: Anatomy, cfg: dict) -> tuple[float, float]:행당 변형은 늘고 주는 성분(∂dx/∂x, ∂dy/∂y)의 최대다 — pixel 의 행당 변형과 같은 뜻. 목 옆에서어깨가 오르며 생기는 비틀림(옆 칸끼리 오르는 양의 차)은 늘고 줄지 않으니 여기 세지 않고,대신 사상이 접히지 않는지를 면적비 det(I + ∇D) 로 본다."""+ grid = _content_grid(anat)+ if grid is None:+ return 0.0, 1.0+ return _strain(*smooth_displacement(anat, cfg, *grid, 1.0, 1.0))+++def _content_grid(anat: Anatomy) -> tuple[np.ndarray, np.ndarray] | None:+ """콘텐츠 bbox 의 픽셀 가운데 (x, y) 격자 — 변위장의 기울기를 재는 자리. 한 줄·한 열뿐이면 None."""ys = np.arange(anat.height, dtype=np.float64) + 0.5xs = np.arange(anat.width, dtype=np.float64) + 0.5if ys.size < 2 or xs.size < 2:- return 0.0, 1.0- gx, gy = np.meshgrid(xs, ys)- dx, dy = smooth_displacement(anat, cfg, gx, gy, 1.0, 1.0)+ return None+ return np.meshgrid(xs, ys)+++def _strain(dx: np.ndarray, dy: np.ndarray, skip: np.ndarray | None = None,+ only: np.ndarray | None = None) -> tuple[float, float]:+ """격자 위 변위장의 (행당 최대 변형, 최소 면적비) — 늘고 주는 성분(∂dx/∂x, ∂dy/∂y)의 최대와 det(I + ∇D) 의 최소.+ `skip` 칸과 그 가로·세로 이웃에서는 재지 않는다 (기울기가 그 칸을 건너 잰 값이다). `only` 를 주면 그 칸에서만 잰다."""dxy, dxx = np.gradient(dx)dyy, dyx = np.gradient(dy)+ area = (1.0 + dxx) * (1.0 + dyy) - dxy * dyx+ if skip is not None or only is not None:+ keep = np.ones(dx.shape, bool) if only is None else only.copy()+ if skip is not None:+ keep &= ~_widened(skip)+ if not keep.any():+ return 0.0, 1.0+ dxx, dyy, area = dxx[keep], dyy[keep], area[keep]stretch = float(max(np.abs(dxx).max(), np.abs(dyy).max()))- area = float(((1.0 + dxx) * (1.0 + dyy) - dxy * dyx).min())- return stretch, area+ return stretch, float(area.min())-def _smooth_warp(frame: Image.Image, anat: Anatomy, cfg: dict, t: float) -> Image.Image:+def _widened(mask: np.ndarray) -> np.ndarray:+ """마스크 칸과 그 가로·세로 이웃."""+ out = mask.copy()+ out[1:] |= mask[:-1]+ out[:-1] |= mask[1:]+ out[:, 1:] |= mask[:, :-1]+ out[:, :-1] |= mask[:, 1:]+ return out+++def _bilinear(grid: np.ndarray, sx: np.ndarray, sy: np.ndarray) -> np.ndarray:+ """캔버스 격자 값을 캔버스 인덱스 좌표 (sx, sy) 에서 쌍선형으로 — 칸 가운데(정수 좌표)에서는 그 칸 값 그대로."""+ canvas_h, canvas_w = grid.shape+ x0, y0 = np.floor(sx), np.floor(sy)+ ax, ay = sx - x0, sy - y0+ x0c, x1c = np.clip(x0, 0, canvas_w - 1).astype(np.int64), np.clip(x0 + 1, 0, canvas_w - 1).astype(np.int64)+ y0c, y1c = np.clip(y0, 0, canvas_h - 1).astype(np.int64), np.clip(y0 + 1, 0, canvas_h - 1).astype(np.int64)+ return ((grid[y0c, x0c] * (1.0 - ax) + grid[y0c, x1c] * ax) * (1.0 - ay)+ + (grid[y1c, x0c] * (1.0 - ax) + grid[y1c, x1c] * ax) * ay)+++def _row_box(anat: Anatomy) -> tuple[int, int, int, int]:+ """줄의 기준 칸이 정한 콘텐츠 자리 (캔버스 좌표) — 고정 칸·쥔 물건을 해부의 격자에 놓을 때 쓴다."""+ if anat.origin is None:+ raise SystemExit("breathe: 고정 칸(--hold-mask)·쥔 물건(--props-mask)은 기준 칸에서 잰 해부의 자리가 있어야 놓인다 — "+ "기록에서 읽은 해부(breathe.json)에는 그 자리가 없다. 프레임에서 다시 재라.")+ return anat.origin[0], anat.origin[1], anat.origin[0] + anat.width, anat.origin[1] + anat.height+++def _smooth_warp(frame: Image.Image, anat: Anatomy, cfg: dict, t: float,+ pins: "Pins | None" = None) -> Image.Image:"""smooth 의 한 위상 — 캔버스 크기 불변, 강체 경계 위와 발바닥 고정.정사상(원본 점 p 의 내용이 p + D(p) 로 간다)의 역을 고정점 반복(q = o - D(q))으로 풀고, 그@@ -665,7 +731,10 @@ def _smooth_warp(frame: Image.Image, anat: Anatomy, cfg: dict, t: float) -> Imagox += 0.5 - box[0]def field(x, y):- return smooth_displacement(anat, cfg, x, y, chest, shoulders)+ if pins is None:+ return smooth_displacement(anat, cfg, x, y, chest, shoulders)+ # 고정 칸에서 0 — 그 칸은 제자리에서 제 바이트를 그대로 뜬다+ return _pinned(pins, box, x, y, *smooth_displacement(anat, cfg, x, y, chest, shoulders))# 밀려 나가는 내용 — 원본 픽셀 중심이 가는 자리가 캔버스 밖이면 조용히 자르지 않는다.fx, fy = field(ox, oy)@@ -706,14 +775,18 @@ def _smooth_warp(frame: Image.Image, anat: Anatomy, cfg: dict, t: float) -> Imagreturn Image.fromarray(out, "RGBA")-def _smooth_refusals(cfg: dict, anat: Anatomy) -> None:- """smooth 줄이 굽기 전에 거부되는 까닭 — 해부와 설정에만 달려 줄에 한 번 본다."""+def _smooth_refusals(cfg: dict, anat: Anatomy, pins: "Pins | None" = None) -> None:+ """smooth 줄이 굽기 전에 거부되는 까닭 — 해부와 설정(과 고정 칸)에만 달려 줄에 한 번 본다."""lag = cfg.get("lag")if lag is not None and float(lag) != 0.0:# 진행파는 윗행 위상을 늦춰 위상 0 인 칸도 움직인다 — 조용히 버리지 않는다.raise SystemExit(f"breathe(smooth): lag {lag} — smooth 에는 진행파가 없다. 위상 0 인 칸이 원본 "f"그대로여야 루프·묶음 이음이 안 바뀐다. lag 를 지워라 (어깨가 늦는 건 shoulder_lag).")- strain, area = smooth_strain(anat, cfg)+ grid = _content_grid(anat)+ 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))if strain > MAX_ROW_STRAIN or area < 1.0 - MAX_ROW_STRAIN:raise SystemExit(f"breathe(smooth): 행당 변형 {strain:.3f}·최소 면적비 {area:.3f} — 상한 {MAX_ROW_STRAIN} 을 넘는다. "@@ -721,6 +794,681 @@ def _smooth_refusals(cfg: dict, anat: Anatomy) -> None:f"기준 {anat.basis_rows}행). depth·depth_x 를 낮추거나 chest_rx·chest_ry 를 넓혀라. 조용히 깎지 않는다.")+def _pinned_strain(anat: Anatomy, pins: "Pins", dx: np.ndarray, dy: np.ndarray) -> tuple[float, float]:+ """콘텐츠 격자 위 변위장에 고정 칸·쥔 물건을 얹은 장의 (행당 최대 변형, 최소 면적비) — 몸의 장만 잰다. 몸(고정 칸도 쥔+ 물건도 아닌 불투명 칸)과 그 둘레 한 칸에서 재고, 고정 칸·쥔 물건 조각과 그 이웃은 뺀다: 조각은 통째로 옮겨지고 고정 칸은+ 맨 위에 그대로 놓여, 둘이 맞닿은 자리의 끊김은 접힘이 아니라 조각이 고정 칸 밑으로 들어가거나 거기서 나오는 것이다. 빈+ 칸끼리 늘고 주는 것(칼날 밑 허공이 칼을 따라가다 몸의 장으로 돌아오는 길)은 보이는 것이 없어 세지 않는다."""+ gx, gy = _content_grid(anat)+ box = _row_box(anat)+ rows, cols = slice(box[1], box[3]), slice(box[0], box[2])+ held, piece = pins.hold[rows, cols], pins.props[rows, cols] > 0+ near_held, near_piece = held, piece # 고정 칸과 조각의 통째 둘레(GRIP)가 2 px 안에서 맞닿는 몸 — 그 사이가+ for _ in range(2): # 조각과 같이 가는 칸과 제자리 칸을 잇는 이음이다+ near_held = _widened(near_held)+ for _ in range(int(GRIP) + 2):+ near_piece = _widened(near_piece)+ skip = held | piece | (near_held & near_piece)+ return _strain(*_pinned(pins, box, gx, gy, dx, dy), skip, _widened(pins.body[rows, cols]))+++# ── 고정 칸과 쥔 물건 (--hold-mask, --props-mask, --props-behind-mask) ─+#+# 고정 칸: 사람이 준 마스크의 칸은 모든 칸에서 그 칸의 바이트 그대로다. 굽기가 덮어 되돌리는 게 아니라 변위장 자체가 고정+# 칸에서 0 이다 — 그 칸의 내용은 다른 데로 가지 않는다. 장은 고정 칸에서 그 줄을 따라(가로 성분은 같은 행, 세로 성분은 같은+# 열) 멀어지며 다시 켜져, 줄의 몸(고정 칸·쥔 물건이 아닌 불투명 칸)이 가장 크게 움직이는 px 의 REACH 배를 지나면 온전하다. 같은 줄로 재니 고정 칸 옆을 나란히 지나는+# 움직임(고정된 다리 위 몸통의 가로 부풂)은 줄지 않고, 고정 칸 쪽으로 밀거나 거기서 멀어지는 움직임만 준다 — 그보다 짧으면+# 그 사이가 행당 상한 넘게 눌리거나 늘어난다.+# 쥔 물건: 팔이 쥔 것(칼·방패 — 사람이 준 마스크의 8-이웃 조각 하나하나)은 그 조각이 놓인 쪽의 팔과 같이 `arms_x` 만큼+# 가로로 통째 옮겨진다 (늘지 않는다). 조각 둘레 GRIP px 안의 몸(쥔 손·팔)은 정확히 같은 칸만큼 옮겨져 손과 손잡이 사이가+# 벌어지거나 겹치지 않고, 거기서 몸의 장과 다른 px 의 REACH 배에 걸쳐 몸의 장으로 돌아간다. 고정 칸은 쥔 물건 옆에서도 제자리고,+# 조각이 고정 칸 쪽으로 가면 고정 칸 밑으로 들어간다. 마스크를 색으로 묶으면(`row_pins` 의 무리 번호) 한 색의 조각들은 같은+# 칸만큼 간다 — 손에 안 닿은 물속 반사가 칼을 따라간다.+# 몸 뒤 물건(`--props-behind-mask` — 등 뒤에 건 방패): 같은 길로 옮겨지되 몸이 그 앞에 있다. 둘레의 몸은 따라가지 않고, 조각이+# 몸 뒤에서 빠져나온 자리에는 몸 뒤에 가려 있던 조각의 나머지가 나온다.+# 장부: 조각을 놓을 때는 출력 칸마다 보이는 원본 칸(출처 지도)을 들고, 조각마다 칸마다 제자리에 그린 칸·가려진 칸·지어낸+# 칸(떠난 자리로 늘어난 칸)을 거기서 읽어 그린 칸과 가려진 칸의 합이 조각의 칸 수와 맞는지 본다 (`_piece_ledger`). 셀 밖으로+# 가는 조각 칸, 한 층의 두 조각이 한 칸에 놓이는 것, 몸 뒤 조각과 몸이 떨어져 생기는 구멍은 거부한다 — 칸을 조용히 버리거나+# 조용히 지어내지 않는다.+# 고정 칸 둘레·쥔 물건 둘레·팔 몫·오르는 몫이 켜지는 길은 미는 px 의 REACH 배다 — 켜지는 길의 늘어남이 많아야 1.5 / REACH 라,+# 가슴 타원 안의 늘어남(기준 가슴에서 0.1 남짓)과 한 자리에 겹쳐도 합이 행당 상한 아래에 남는다.+REACH = 12.0+GRIP = 2.0+# 옆으로 미끄러지는 몫이 켜지는 줄 수의 하한 — 미는 px 의 이 배 (smoothstep 의 가장 가파른 기울기가 1.5 / 길이라, 한 줄에 한+# 칸 넘게 미끄러지지 않는다).+SHEAR = 1.5+++@dataclass(frozen=True, eq=False)+class Pins:+ """줄의 고정 칸·쥔 물건이 정한 캔버스 격자 (`row_pins` — 줄에 한 번 잰다)."""++ hold: np.ndarray # bool — 고정 칸+ props: np.ndarray # int — 쥔 물건 조각 번호 (0 = 아님, 1 부터 맨 위 칸 순 — 몸 앞·몸 뒤 조각이 한 줄)+ shifts: np.ndarray # float — 조각 번호마다 들숨 꼭대기의 가로 px (0 번은 0, 한 무리의 조각은 같은 px)+ behind: np.ndarray # bool — 조각 번호마다 몸 뒤인가 (0 번은 False)+ colours: tuple # 조각 번호마다 무리의 마스크 색 "#rrggbb" — 색으로 묶지 않았으면 None (0 번도 None)+ wx: np.ndarray # float — 가로 성분에 곱하는 고정 무게 (고정 칸 0)+ wy: np.ndarray # float — 세로 성분에 곱하는 고정 무게+ grip: np.ndarray # float — 몸의 장이 몸 앞 조각들의 움직임을 따르는 몫 (조각 위와 둘레 GRIP px 는 1, 몸 뒤 조각은 끌지 않는다)+ grip_dx: np.ndarray # float — 그 몫으로 섞은 조각들의 가로 px (조각 위와 둘레 GRIP px 는 그 조각의 px)+ body: np.ndarray # bool — 몸: 기준 칸의 불투명 칸 가운데 고정 칸도 쥔 물건도 아닌 칸 (행당 변형을 재는 자리)++ def pieces(self, hidden: list[list[int]] | None = None, behind: bool = False,+ filled: list[list[int]] | None = None) -> list[dict]:+ """한 마스크(몸 앞, `behind` 면 몸 뒤)의 조각마다 칸 수, 들숨 꼭대기의 가로 px, 색으로 묶었으면 그 색 — breathe.json+ `props.pieces`·`props_behind.pieces`. `hidden`·`filled` (칸마다 조각 번호 순의 가려진 칸 수·지어낸 칸 수,+ `_piece_ledger`)를 주면 조각마다 칸마다의 수 `hidden`·`filled` 와 그 최대 `hidden_max`·`filled_max` 도."""+ rows = []+ for k in range(1, len(self.shifts)):+ if bool(self.behind[k]) != behind:+ continue+ row = {"cells": int(np.count_nonzero(self.props == k)), "shift_px": round(float(self.shifts[k]), 4)}+ if self.colours[k] is not None:+ row["colour"] = self.colours[k]+ for key, counts in (("hidden", hidden), ("filled", filled)):+ if counts is not None:+ row[key] = [int(frame[k - 1]) for frame in counts]+ row[f"{key}_max"] = max(row[key], default=0)+ rows.append(row)+ return rows+++def _line_reach(mask: np.ndarray, axis: int) -> np.ndarray:+ """`mask` 칸까지 한 줄(axis 1 = 같은 행, 0 = 같은 열)을 따라 잰 거리 — 그 줄에 하나도 없으면 inf."""+ m = np.moveaxis(np.asarray(mask, bool), axis, -1)+ idx = np.arange(m.shape[-1], dtype=np.float64)+ before = np.maximum.accumulate(np.where(m, idx, -np.inf), axis=-1)+ after = np.minimum.accumulate(np.where(m, idx, np.inf)[..., ::-1], axis=-1)[..., ::-1]+ return np.moveaxis(np.minimum(idx - before, after - idx), -1, axis)+++def _shifted(a: np.ndarray, dy: int, dx: int) -> np.ndarray:+ """`a` 를 (dy, dx) 칸 민 격자 — 밖에서 들어온 칸은 0."""+ out = np.zeros_like(a)+ h, w = a.shape+ out[max(0, dy):h + min(0, dy), max(0, dx):w + min(0, dx)] = a[max(0, -dy):h + min(0, -dy), max(0, -dx):w + min(0, -dx)]+ return out+++NEIGHBOURS = ((1, 0), (-1, 0), (0, 1), (0, -1))+DIAGONALS = ((1, 1), (1, -1), (-1, 1), (-1, -1))+++def _pieces(mask: np.ndarray, join: int = 0) -> np.ndarray:+ """마스크의 8-이웃 조각 번호 격자 — 0 = 아님, 조각은 맨 위(같으면 맨 왼쪽) 칸 순으로 1 부터. `join` px 안에 떨어진+ 칸들은 한 조각이다 (쥔 손 칸이 사이에 끼어 갈라진 칼자루와 칼날처럼)."""+ mask = np.asarray(mask, bool)+ if join > 0:+ grown = mask.copy()+ for _ in range(join):+ wider = grown.copy()+ for dy, dx in NEIGHBOURS + DIAGONALS:+ wider |= _shifted(grown, dy, dx)+ grown = wider+ joined = _pieces(grown)+ roots = np.unique(joined[mask])+ labels = np.zeros(mask.shape, np.int64)+ labels[mask] = np.searchsorted(roots, joined[mask]) + 1+ return labels+ seed = np.where(mask, np.arange(1, mask.size + 1).reshape(mask.shape), 0)+ while True: # 조각 안에서 가장 작은 칸 번호로 모은다+ low = seed.copy()+ for dy, dx in NEIGHBOURS + DIAGONALS:+ near = _shifted(seed, dy, dx)+ low = np.where(mask & (near > 0) & (near < low), near, low)+ if np.array_equal(low, seed):+ break+ seed = low+ roots = np.unique(seed[mask]) # 가장 작은 칸 번호 = 맨 위·맨 왼쪽 칸 → 그 순서+ labels = np.zeros(mask.shape, np.int64)+ labels[mask] = np.searchsorted(roots, seed[mask]) + 1+ return labels+++def _distance_to(mask: np.ndarray, reach: float) -> np.ndarray:+ """칸 가운데에서 `mask` 의 가장 가까운 칸 가운데까지의 곧은 거리 — `reach` 넘게 떨어진 칸은 `reach`. 계단 거리(팔각)로+ 재면 한 칸 사이에 두 걸음씩 뛰는 자리가 생겨 그 위에 얹은 무게의 기울기가 두 배가 된다."""+ mask = np.asarray(mask, bool)+ out = np.full(mask.shape, float(reach))+ if not mask.any():+ return out+ out[mask] = 0.0+ inner = mask.copy() # 테두리 칸만 재면 된다 — 안쪽 칸은 테두리보다 멀다+ inner[1:] &= mask[:-1]+ inner[:-1] &= mask[1:]+ inner[:, 1:] &= mask[:, :-1]+ inner[:, :-1] &= mask[:, 1:]+ by, bx = np.nonzero(mask & ~inner)+ pad = int(math.ceil(reach))+ y0, y1 = max(0, int(by.min()) - pad), min(mask.shape[0], int(by.max()) + pad + 1)+ x0, x1 = max(0, int(bx.min()) - pad), min(mask.shape[1], int(bx.max()) + pad + 1)+ gy, gx = np.mgrid[y0:y1, x0:x1]+ near = np.full(gy.shape, np.inf)+ for i in range(0, by.size, 256): # 테두리 칸 묶음마다 — 메모리를 묶음 크기로 묶어 둔다+ d = np.hypot(gy[..., None] - by[None, None, i:i + 256], gx[..., None] - bx[None, None, i:i + 256])+ near = np.minimum(near, d.min(axis=-1))+ region = out[y0:y1, x0:x1]+ region[...] = np.where(mask[y0:y1, x0:x1], 0.0, np.minimum(near, reach))+ return out+++def read_mask(path: str | Path, size: tuple[int, int], flag: str,+ colours: bool = False) -> tuple[np.ndarray, dict]:+ """마스크 PNG 를 읽는다 — 밝은(명도 128 이상) 불투명(알파 128 이상) 칸이 그 마스크의 칸이다. 프레임과 같은 크기여야+ 하고, 칸이 하나도 없으면 조용히 넘기지 않고 거부한다. (마스크, breathe.json 에 실을 기록).+ `colours` 면 마스크는 bool 이 아니라 칸마다 그 색의 무리 번호다 (0 = 칸 아님, 색 0xRRGGBB + 1 — 두 마스크에서 같은 색은 같은+ 번호) — 기록에 색 수 `colours` 가 더 실린다."""+ path = Path(path)+ try:+ data = path.read_bytes()+ with Image.open(path) as im:+ la = np.asarray(im.convert("LA"))+ rgb = np.asarray(im.convert("RGB")) if colours else None+ except OSError as exc:+ raise SystemExit(f"breathe: {flag} {path} 를 못 읽는다 ({exc})")+ if (la.shape[1], la.shape[0]) != tuple(size):+ raise SystemExit(f"breathe: {flag} {path} 는 {la.shape[1]}x{la.shape[0]} 인데 프레임은 {size[0]}x{size[1]} 이다 — "+ f"같은 크기여야 칸이 맞는다.")+ mask = (la[..., 0] >= 128) & (la[..., 1] >= 128)+ if not mask.any():+ raise SystemExit(f"breathe: {flag} {path} 에 칸(밝은 불투명 칸)이 하나도 없다 — 흰 칸이 그 마스크의 칸이다.")+ record = {"path": str(path), "sha256": hashlib.sha256(data).hexdigest(), "cells": int(mask.sum())}+ if rgb is None:+ return mask, record+ rgb = rgb.astype(np.int64)+ groups = np.where(mask, (rgb[..., 0] << 16 | rgb[..., 1] << 8 | rgb[..., 2]) + 1, 0)+ record["colours"] = int(np.unique(groups[mask]).size)+ return groups, record+++def _held_pieces(front: np.ndarray, back: np.ndarray) -> tuple[np.ndarray, list, list[bool]]:+ """몸 앞(`front`)·몸 뒤(`back`) 마스크의 (조각 번호 격자, 조각마다 무리 열쇠, 조각마다 몸 뒤인가). 조각은 한 마스크의 한+ 무리 안에서 8-이웃으로 잇고 GRIP px 안에 떨어진 칸도 한 조각이다 (`_pieces`). bool 마스크는 조각마다 제 무리고, 무리 번호+ 격자(int)는 같은 번호의 조각들이 한 무리다 — 두 마스크에 걸쳐서도. 번호는 두 마스크를 함께 맨 위(같으면 맨 왼쪽) 칸 순."""+ found = []+ for behind, grid in ((False, front), (True, back)):+ grid = np.asarray(grid)+ if grid.dtype == bool:+ parts = [(("piece", behind), grid)]+ else:+ parts = [(("colour", int(g)), grid == g) for g in np.unique(grid[grid != 0])]+ for key, mask in parts:+ labels = _pieces(mask, int(GRIP))+ for k in range(1, int(labels.max()) + 1):+ cells = labels == k+ found.append((int(np.flatnonzero(cells)[0]), cells, key if key[0] == "colour" else (key, k), behind))+ found.sort(key=lambda f: f[0])+ labels = np.zeros(np.shape(front), np.int64)+ for k, (_, cells, _, _) in enumerate(found, 1):+ labels[cells] = k+ return labels, [f[2] for f in found], [f[3] for f in found]+++def row_pins(anat: Anatomy, cfg: dict, frame: Image.Image, hold: np.ndarray | None = None,+ props: np.ndarray | None = None, behind: np.ndarray | None = None) -> Pins | None:+ """줄의 고정 칸(`hold`, 캔버스 크기 bool)·쥔 물건(`props`)·몸 뒤 물건(`behind`) 마스크를 변위장에 얹을 격자로 — 셋 다 없으면+ None. `props`·`behind` 는 bool(조각마다 제 손을 따른다)이거나 무리 번호 격자다 (int, 0 = 아님 — `read_mask(..., colours=True)`+ 의 색: 한 번호의 조각들은 두 마스크에 걸쳐 같은 칸만큼 간다). `frame` 은 줄의 기준 칸이다 (쥔 물건이 몸에 닿은 자리를 읽는다).++ 쥔 물건 조각은 쥔 팔과 같이 간다: 조각의 무리가 몸(고정 칸·쥔 물건이 아닌 불투명 칸)에 닿은 칸들에서 읽은 가슴의 가로 몫의+ 평균에, 무리 가운데가 놓인 쪽 팔의 몫(`arms_x` × 기준 높이 px, 몸 바깥쪽)을 다 더한 만큼 — 쥔 손이 가슴에 밀리는 만큼과+ 팔이 벌어지는 만큼이다. 몸에 닿은 칸이 없으면 무리 전체에서 읽는다 — 손에 안 닿은 반사는 칼과 한 무리로 묶어야 칼을 따른다.+ 몸 앞 조각은 둘레 GRIP px 의 몸을 끌고 가고(쥔 손이 손잡이와 같이 간다), 몸 뒤 조각은 장에 얹지 않는다 — 몸이 그 앞에서 몸의+ 장을 따르고, 조각은 `_place_pieces` 가 통째로 놓는다.+ 봉투 스쿼시 줄은 가로줄을 통째로 옮겨 칸 하나를 제자리에 둘 수 없으니 받지 않고, 쥔 물건은 팔과 같이 가니 pixel 의+ 둥근 가슴에 `arms_x` 가 있어야 받는다. 한 칸이 두 마스크에 있을 수 없다 — 조용히 한쪽을 고르지 않는다."""+ if hold is None and props is None and behind is None:+ return None+ w, h = frame.size+ masks = {}+ for flag, mask in (("--hold-mask", hold), ("--props-mask", props), ("--props-behind-mask", behind)):+ if mask is None:+ masks[flag] = np.zeros((h, w), bool)+ continue+ mask = np.asarray(mask)+ if (mask.shape[1], mask.shape[0]) != (w, h):+ raise SystemExit(f"breathe: {flag} 는 {mask.shape[1]}x{mask.shape[0]} 인데 프레임은 {w}x{h} 이다 — 같은 크기여야 "+ f"칸이 맞는다.")+ masks[flag] = mask if mask.dtype != bool and flag != "--hold-mask" else mask.astype(bool)+ hold, front, back = masks["--hold-mask"], masks["--props-mask"], masks["--props-behind-mask"]+ smooth, rounded = breathe_mode(cfg) == "smooth", pixel_round(cfg)+ if not (smooth or rounded):+ raise SystemExit("breathe: 고정 칸(--hold-mask)·쥔 물건(--props-mask, --props-behind-mask)은 변위장으로 굽는 줄의 것이다 — "+ "mode smooth, 또는 pixel 의 둥근 가슴(chest_round·arms_x). pixel 봉투 스쿼시는 가로줄을 통째로 옮겨 칸을 "+ "제자리에 둘 수 없다.")+ if (front.any() or back.any()) and not (rounded and cfg.get("arms_x")):+ raise SystemExit("breathe: 쥔 물건(--props-mask, --props-behind-mask)은 팔과 같이 가로로 옮겨진다 — pixel 의 둥근 가슴에 "+ "arms_x 를 주라.")+ for one, two, names in ((hold, front != 0, "고정 칸이면서 쥔 물건"), (hold, back != 0, "고정 칸이면서 몸 뒤 물건"),+ (front != 0, back != 0, "쥔 물건이면서 몸 뒤 물건")):+ both = int(np.count_nonzero(one & two))+ if both:+ raise SystemExit(f"breathe: {both} 칸이 {names}이다 — 한 칸은 하나만 된다. 두 마스크 중 하나에서 빼라.")+ held = (front != 0) | (back != 0)+ box = _row_box(anat)+ grid = _content_grid(anat)+ moving = (np.asarray(frame.convert("RGBA"))[..., 3] >= 128) & ~hold & ~held+ moving = moving[box[1]:box[3], box[0]:box[2]]+ if grid is None or not moving.any():+ biggest = 0.0+ else:+ dx, dy = smooth_displacement(anat, cfg, *grid, 1.0, 1.0) if smooth else round_displacement(anat, cfg, *grid)+ biggest = float(np.hypot(dx, dy)[moving].max()) # 몸이 가장 크게 움직이는 px — 빈 칸·고정 칸·쥔 물건은 안 센다+ reach = max(2.0, REACH * biggest)+ wx = _smoothstep_array(0.0, reach, np.minimum(_line_reach(hold, 1), reach))+ wy = _smoothstep_array(0.0, reach, np.minimum(_line_reach(hold, 0), reach))+ labels, keys, behinds = _held_pieces(front, back) # 쥔 손 칸이 사이에 낀 한 물건의 조각들은 한 조각+ arms = float(cfg.get("arms_x") or 0.0) * anat.basis_rows+ axis = box[0] + anat.axis_x + 0.5 # 캔버스 좌표의 몸통 축+ body = (np.asarray(frame.convert("RGBA"))[..., 3] >= 128) & ~hold & (labels == 0)+ touch = body.copy() # 몸 칸과 그 가로·세로 이웃+ touch[1:] |= body[:-1]+ touch[:-1] |= body[1:]+ touch[:, 1:] |= body[:, :-1]+ touch[:, :-1] |= body[:, 1:]++ def reads(cells: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:+ """(행, 열, 가슴의 가로 몫, 팔의 가로 몫) — 칸들이 몸에 닿은 자리에서 (닿은 칸이 없으면 칸 전체에서)."""+ ys, xs = np.nonzero(cells & touch) if (cells & touch).any() else np.nonzero(cells)+ chest, _, arm = (_round_parts(anat, cfg, xs + 0.5 - box[0], ys + 0.5 - box[1]) if rounded+ else (np.zeros(1), None, np.zeros(1)))+ return ys, xs, chest, arm++ moves = {} # 무리마다 들숨 꼭대기의 가로 px+ for key in dict.fromkeys(keys):+ cells = np.isin(labels, [k for k, g in enumerate(keys, 1) if g == key])+ side = -1.0 if np.nonzero(cells)[1].mean() + 0.5 < axis else 1.0 # 무리 가운데가 놓인 쪽의 팔 쪽으로+ moves[key] = float(np.mean(reads(cells)[2])) + side * arms+ shifts = np.asarray([0.0] + [moves[key] for key in keys])+ weight = np.zeros((h, w)) # 조각들이 몸의 장을 끄는 몫의 합+ pull = np.zeros((h, w)) # 그 몫마다 조각의 가로 px 를 곱한 합+ for k in range(1, len(shifts)):+ piece = labels == k+ if behinds[k - 1]:+ continue # 몸 뒤 조각은 몸을 끌지 않는다 — 장은 그 칸에서도 몸의 장이다 (`_place_pieces`)+ else:+ # 조각 둘레의 몸이 조각을 따라가는 길 — 닿은 자리에서 몸의 장(고정 칸 둘레에서 준 그대로)과 조각의 px 가 다른 만큼의+ # REACH 배. 조각이 가는 만큼이 아니라 몸과 다른 만큼이라, 가슴이 이미 미는 옆구리에 붙은 방패·칼은 짧은 길로 따라간다.+ ys, xs, chest, arm = reads(piece)+ ramp = max(2.0, REACH * float(np.abs(shifts[k] - wx[ys, xs] * (chest + arm)).max()))+ near = 1.0 - _smoothstep_array(GRIP, GRIP + ramp, _distance_to(piece, GRIP + ramp))+ weight += near+ pull += near * shifts[k]+ # 길이 겹친 자리(두 조각 사이의 몸)는 섞는다 — 가장 가까운 조각으로 갈라 끊지 않는다. 조각 위와 둘레 GRIP px 는 그 조각+ # 하나의 몫이 1 이라 정확히 그 조각의 px 다.+ grip = np.minimum(weight, 1.0)+ grip_dx = np.where(weight > 0.0, pull / np.maximum(weight, 1e-12), 0.0) # 조각들의 px 를 몫으로 고르게 — 한 조각이면 그 조각의 px+ # 머리(강체 경계 위)는 쥔 물건 옆에서도 제자리다 — 옆으로 가는 몫처럼 켜되, 조각이 가는 px 의 SHEAR 배 줄보다 짧지 않게: 더+ # 짧으면 머리선 밑의 줄이 한 줄에 한 칸 넘게 미끄러져, 머리선을 지나 내려오는 윤곽(어깨선)이 끊긴다.+ top, band_end = smooth_band(anat)+ rows = np.arange(h, dtype=np.float64) + 0.5 - box[1]+ turn = max(0.15 * (band_end - top), SHEAR * float(np.abs(shifts).max(initial=0.0)))+ grip *= _smoothstep_array(top, top + turn, rows)[:, None]+ grip[hold] = 0.0 # 고정 칸은 쥔 물건 옆에서도 제자리다+ colours = tuple([None] + [f"#{key[1] - 1:06x}" if key[0] == "colour" else None for key in keys])+ return Pins(hold=hold, props=labels, shifts=shifts, behind=np.asarray([False] + behinds), colours=colours, wx=wx,+ wy=wy, grip=grip, grip_dx=grip_dx, body=body)+++def _pinned(pins: Pins | None, box, x: np.ndarray, y: np.ndarray, dx: np.ndarray,+ dy: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ """콘텐츠 bbox 기준 점 (x, y) 의 변위 (dx, dy) 에 고정 칸·쥔 물건을 얹는다 — 고정 칸 쪽 줄로 준 몸의 장을 쥔 물건 둘레에서+ 그 조각의 가로 px 로 섞는다. 고정 칸 가운데에서 몸의 장은 정확히 0, 조각 위와 둘레 GRIP px 에서는 정확히 그 조각의 px."""+ if pins is None:+ return dx, dy+ sx, sy = x + box[0] - 0.5, y + box[1] - 0.5+ grip = _bilinear(pins.grip, sx, sy)+ return ((1.0 - grip) * _bilinear(pins.wx, sx, sy) * dx + grip * _bilinear(pins.grip_dx, sx, sy),+ (1.0 - grip) * _bilinear(pins.wy, sx, sy) * dy)+++# ── 둥근 가슴 (pixel — chest_round·arms_x) ─────────────────────────+#+# 봉투 스쿼시는 가로줄을 통째로 늘이고 줄인다 — 머리가 몸통 위에서 오르내리고 숨이 줄 단위로 읽힌다. 둥근 가슴은 가슴+# 꼭대기 P 에서 바깥으로 부푸는 2차원 변위장 하나를 정수 칸으로 굽는다: 출력의 칸은 전부 원본 칸 하나를 그대로 옮긴+# 것이다 (사잇값 없음 — 새 색이 없다). 장이 행당 상한 아래라 가로·세로 어느 줄에서도 칸 순서가 뒤집히지 않는다.++def pixel_round(cfg: dict) -> bool:+ """이 줄이 둥근 가슴 장을 굽나 — pixel 이고 `chest_round`·`arms_x` 중 하나가 0 보다 크다 (생략·0 은 봉투 스쿼시)."""+ return breathe_mode(cfg) == "pixel" and bool(cfg.get("chest_round") or cfg.get("arms_x"))+++def round_displacement(anat: Anatomy, cfg: dict, x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ """콘텐츠 bbox 기준 점 (x, y) 의 내용이 들숨 꼭대기에서 가는 변위 (dx, dy) — 정사상, 위로 오르면 dy < 0.++ 가슴: 가슴 타원(smooth 와 같은 chest_* 키)의 테두리가 꼭대기 P 에서 바깥으로 `chest_round × 기준 높이` px 나간다.+ 타원 안은 P 에서 테두리까지 고르게 늘고, 타원 밖은 같은 px 만큼 통째로 밀린다 — 늘지 않으니 윤곽선이 1 px 로 남는다.+ P 위쪽은 위·옆으로, P 아래쪽은 옆으로만 간다 — 아래로 밀면 서 있는 발이 눌린다.+ 팔: 몸통 밖 부속 열(부속 보호가 시작하는 자리 — 사람이 준 몸통 반폭이면 그 반폭, 아니면 그 1.15 배 — 바깥)은 가슴이+ 미는 대로 통째로 밀리고(타원 밖이다), 거기에 더해 몸통 축에서 먼 쪽으로 `arms_x × 기준 높이` px 가로로 통째 간다 — 팔은+ 늘지 않는다 (pixel 의 "날개·팔은 밀리기만 한다"). 그 몫이 켜지는 길은 팔이 아니라 몸통 쪽에 둔다: 부속 경계 안쪽+ REACH × 그 px 에 걸쳐 몸통 옆구리가 팔을 따라 벌어진다 — 더 짧으면 어깨가 행당 상한 넘게 늘어난다. 해부가 부속을+ 못 찾았고 몸통 반폭도 안 줬으면 팔 몫은 없다. 쥔 물건은 `row_pins` 가 얹는다.+ 고정: 강체 경계 위는 0 이라 머리가 자리·바이트 그대로다. 강체 경계 아래에서 오르는 몫은 smooth 의 목 밴드처럼 켜지고(목+ 너비 안은 밴드 전체에 걸쳐, 그 밖은 오르는 px 의 REACH 배나 밴드의 0.15 만에 — 그보다 짧으면 머리 밑이 행당 상한 넘게+ 눌린다), 옆으로 가는 몫은 밴드의 0.15 나 옆으로 가는 px(가슴과 팔)의 SHEAR 배 가운데 긴 쪽에 걸쳐 켜진다 — 옆으로는 머리+ 밑을 누르지 않고 비껴 지나갈 뿐이라, 머리가 크고 몸통이 짧은 그림에서도 어깨가 옆으로 숨쉰다. 그보다 짧으면 머리선 밑의 줄이+ 한 줄에 한 칸 넘게 미끄러져 머리선을 지나 내려오는 윤곽(어깨선)이 끊긴다. 가로 밀림은 가슴 타원의 아래 테두리에서 콘텐츠+ 맨 아래까지 0 으로 줄어든다 — 발은 선 자리에 있다."""+ chest_dx, chest_dy, arm_dx = _round_parts(anat, cfg, x, y)+ return chest_dx + arm_dx, chest_dy+++def _round_parts(anat: Anatomy, cfg: dict, x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ """`round_displacement` 의 몫 셋 — (가슴의 가로, 가슴의 세로, 팔의 가로). 쥔 물건 조각은 가슴의 가로 몫을 몸에 닿은+ 자리에서 읽는다 (`row_pins`)."""+ top, band_end = smooth_band(anat)+ band = band_end - top+ basis = float(anat.basis_rows)+ swell = float(cfg.get("chest_round") or 0.0) * basis+ arms = float(cfg.get("arms_x") or 0.0) * basis+ _cx, cy, _rx, ry, _cos, _sin = _chest_frame(anat, cfg)+ px, py = smooth_chest_peak(anat, cfg)+ ox, oy = x - px, y - py+ out = swell * np.minimum(_chest_reach(anat, cfg, x, y), 1.0) / np.maximum(np.hypot(ox, oy), 1e-12)+ away = np.where(x < anat.axis_x + 0.5, -1.0, 1.0)+ neck_x, neck_half = _neck(anat)+ neckness = 1.0 - _smoothstep_array(neck_half, 1.5 * neck_half, np.abs(x - neck_x))+ quick = min(band, max(0.15 * band, REACH * swell))+ rise = _smoothstep_array(0.0, 1.0, (y - top) / (quick + (band - quick) * neckness))+ turn = max(0.15 * band, SHEAR * (swell + arms))+ aside = _smoothstep_array(top, top + turn, y) * (1.0 - _smoothstep_array(cy + ry, float(anat.height), y))+ return ox * out * aside, np.minimum(oy, 0.0) * out * rise, _arm_side(anat, arms, x) * away * arms * aside+++def _arm_side(anat: Anatomy, arms: float, x: np.ndarray) -> np.ndarray | float:+ """`round_displacement` 의 팔 몫 무게 (콘텐츠 bbox 기준 점의 x) — 부속 경계 바깥은 1, 안쪽 REACH × 팔 px 에 걸쳐+ 0 으로. 부속 경계는 부속 보호(`protect`)가 시작하는 자리다. 팔 몫이 없으면 0."""+ if arms <= 0.0 or not arms_found(anat):+ return 0.0+ start = float(anat.torso_half) * (1.0 if anat.torso_source == "manual" else 1.15)+ reach = min(start, max(2.0, REACH * arms)) # 몸통 축을 넘지 않는다 — 축에서 왼쪽·오른쪽이 갈린다+ return _smoothstep_array(start - reach, start, np.abs(x - 0.5 - anat.axis_x))+++def arms_found(anat: Anatomy) -> bool:+ """해부가 몸통 밖 부속(팔)을 읽었나 — 부속 보호와 같은 판정: 사람이 몸통 반폭을 줬거나 실루엣이 몸통보다 넓게 뻗었다."""+ return anat.torso_source == "manual" or anat.has_appendage+++def round_strain(anat: Anatomy, cfg: dict, pins: Pins | None = None) -> tuple[float, float]:+ """(행당 최대 변형, 최소 면적비) — 둥근 가슴 장의 들숨 꼭대기(고정 칸·쥔 물건을 얹어)에서."""+ grid = _content_grid(anat)+ if grid is None:+ return 0.0, 1.0+ dx, dy = round_displacement(anat, cfg, *grid)+ return _strain(dx, dy) if pins is None else _pinned_strain(anat, pins, dx, dy)+++def _round_refusals(cfg: dict, anat: Anatomy, pins: Pins | None) -> None:+ """둥근 가슴 줄이 굽기 전에 거부되는 까닭 — 해부·설정·고정 칸·쥔 물건에만 달려 줄에 한 번 본다."""+ if cfg.get("arms_x") and not arms_found(anat) and (pins is None or not pins.props.any()):+ raise SystemExit(+ f"breathe(round): arms_x {cfg['arms_x']} — 옮길 팔이 없다: 해부가 몸통 밖 부속을 못 찾았고(실루엣 최대 반폭 "+ f"{anat.max_half} 가 몸통 반폭 {anat.torso_half} 의 1.3 배 아래) 쥔 물건(--props-mask)도 없다. torso_half 로 몸통 "+ f"폭을 주거나, 쥔 물건을 주거나, arms_x 를 지워라. 조용히 넘기지 않는다.")+ strain, area = round_strain(anat, cfg, pins)+ if strain > MAX_ROW_STRAIN or area < 1.0 - MAX_ROW_STRAIN:+ raise SystemExit(+ f"breathe(round): 행당 변형 {strain:.3f}·최소 면적비 {area:.3f} — 상한 {MAX_ROW_STRAIN} 을 넘는다. 가슴이 "+ f"부푸는 만큼을 가슴 타원·목 밴드·고정 칸 둘레가 못 받는다 (강체 경계 {anat.rigid_row}/{anat.height}, 기준 "+ f"{anat.basis_rows}행). chest_round·arms_x 를 낮추거나 chest_rx·chest_ry 를 넓혀라. 조용히 깎지 않는다.")+++def piece_step(pins: Pins, piece: int, curve: float) -> int:+ """조각 하나가 이 위상에서 옮겨지는 칸 — 몸을 뜨는 규칙(칸 가운데에서 변위를 빼고 내림)과 같은 반올림이라, 조각 둘레+ GRIP px 의 몸(변위가 정확히 그 조각의 px)과 늘 같은 칸이다."""+ return int(math.ceil(curve * float(pins.shifts[piece]) - 0.5))+++def _piece_name(pins: Pins, piece: int) -> tuple[str, int, int]:+ """조각 번호의 (마스크 플래그, 그 마스크에서 몇째, 그 마스크의 조각 수) — breathe.json 의 `pieces` 와 경고 줄이 세는 번호."""+ layer = [k for k in range(1, len(pins.shifts)) if bool(pins.behind[k]) == bool(pins.behind[piece])]+ return ("--props-behind-mask" if pins.behind[piece] else "--props-mask"), layer.index(piece) + 1, len(layer)+++def _place_pieces(out: np.ndarray, shows: np.ndarray, src: np.ndarray, pins: Pins, curve: float, came_body: np.ndarray,+ came_behind: np.ndarray) -> list[int]:+ """쥔 물건 조각을 통째로(`piece_step` 칸) 놓는다 — `_round_warp` 의 장이 이미 뜬 `out` 위에, 그 자리에서. `shows` 는 출력+ 칸마다 그 칸이 보이는 원본 칸 번호(-1 = 빈 칸)라, 여기서 쓰는 칸마다 같이 적는다. 조각 번호 순의 옮긴 칸을 돌려준다 — 가려진+ 칸과 지어낸 칸은 `_piece_ledger` 가 `shows` 에서 읽는다. `came_body` 는 장이 몸(고정 칸·쥔 물건이 아닌 불투명 칸)을 데려온 출력+ 칸, `came_behind` 는 몸 뒤 조각의 칸을 데려온 출력 칸이다 — 몸 뒤 조각은 몸을 끌지 않아 장이 그 칸을 몸의 장으로 옮겨+ 놓았으니, 먼저 비우고 아래에서 통째로 다시 그린다 (몸과 그 윤곽은 끊김 없이 몸의 장을 따른다).++ 그리기 전에 거부한다 — 조각의 불투명 칸이 셀 밖으로 가면(자르지 않는다), 그리고 한 층(몸 앞끼리, 몸 뒤끼리)의 두 조각이 한+ 칸에 놓이면(어느 쪽이 앞인지 마스크가 말하지 않는다 — 조용히 한쪽을 고르지 않는다).+ 떠난 칸 — 조각이 옮겨지며 비운 제 칸 — 은 그 줄에서 조각 바로 뒤(옮겨진 쪽의 반대)의 첫 칸을 본다. 몸 앞 조각: 둘레의 몸은+ 장이 이미 같은 칸만큼 데려왔다. 바로 뒤가 고정 칸이면 장이 그 칸을 데려올 수 없어(제자리다) 그 고정 칸이 떠난 칸들로+ 늘어난다 — 물에 잠긴 칼날이 떠난 자리에 물이, 소매가 떠난 자리에 고정된 등이 온다. 몸 뒤 조각: 앞의 몸은 제자리고, 몸 뒤에+ 가려 있던 조각의 나머지가 나온다 — 바로 뒤가 불투명하면 조각이 거기 닿았던 칸이 떠난 칸들로 늘어나고, 비었으면 빈 칸이+ 된다. 장이 몸을 데려온 칸은 몸이 앞이라 그대로 둔다. 늘어난 칸은 옮긴 칸이 아니라 지어낸 칸이다 — 장부가 센다.+ 그다음 몸 뒤 조각 전부, 몸 앞 조각 전부 순으로(제자리인 조각도) 옮겨진 자리에 그린다 — 몸 앞 조각이 언제나 몸 뒤 조각 위다.+ 조각의 빈 칸은 그리지 않는다. 고정 칸은 언제나 맨 위다."""+ h, w = src.shape[:2]+ opaque = src[..., 3] > 0+ count = len(pins.shifts) - 1+ steps = [piece_step(pins, k, curve) for k in range(1, count + 1)]+ cells = [np.nonzero((pins.props == k) & opaque) for k in range(1, count + 1)]+ for k, ((ys, xs), step) in enumerate(zip(cells, steps), 1):+ off = {"top": 0, "left": int(np.count_nonzero(xs + step < 0)), "right": int(np.count_nonzero(xs + step >= w))}+ if off["left"] or off["right"]:+ flag, i, n = _piece_name(pins, k)+ raise SystemExit(+ f"breathe(round): {flag} 조각 {i}/{n}({ys.size}칸)이 불투명 칸 {off['left'] + off['right']}개를 셀 밖으로 "+ f"민다 — {_sides_off(off)} (셀 {w}x{h}, 조각 {step:+d}칸). 셀 여백을 늘리거나 chest_round·arms_x 를 낮춰라.")+ for behind in (True, False):+ landed = np.zeros((h, w), np.int64) # 이 층의 조각이 놓인 칸 — 조각 번호 (0 = 아직 없음)+ for k in range(1, count + 1):+ if bool(pins.behind[k]) != behind:+ continue+ ys, xs = cells[k - 1]+ to = xs + steps[k - 1]+ clash = landed[ys, to]+ if clash.any():+ flag, i, n = _piece_name(pins, k)+ j = _piece_name(pins, int(clash[clash > 0].min()))[1]+ raise SystemExit(+ f"breathe(round): {flag} 의 두 조각({j}/{n}, {i}/{n})이 옮겨진 뒤 {int(np.count_nonzero(clash))}칸에 함께 "+ f"놓인다 — 어느 쪽이 앞인지 마스크가 말하지 않는다. 한 무리로 묶거나(같은 색, --props-groups colour) 한쪽을 "+ f"다른 마스크로 옮겨라.")+ landed[ys, to] = k+ columns = np.broadcast_to(np.arange(w), (h, w))+ out[came_behind] = 0+ shows[came_behind] = -1+ for k, step in enumerate(steps, 1):+ if not step:+ continue+ piece = (pins.props == k) & opaque+ ys, xs = cells[k - 1]+ covered = np.zeros_like(piece)+ covered[ys, xs + step] = True+ ly, lx = np.nonzero(piece & ~covered)+ if step > 0: # 그 줄에서 조각 바로 뒤의 첫 칸, 그리고 조각이 거기 닿은 칸+ back = np.maximum.accumulate(np.where(piece, -1, columns), axis=1)[ly, lx]+ edge = back + 1+ else:+ back = np.minimum.accumulate(np.where(piece, w, columns)[:, ::-1], axis=1)[:, ::-1][ly, lx]+ edge = back - 1+ there = (back >= 0) & (back < w)+ near = np.clip(back, 0, w - 1)+ if pins.behind[k]:+ free = ~came_body[ly, lx]+ solid = free & there & opaque[ly, near]+ out[ly[solid], lx[solid]] = src[ly[solid], edge[solid]]+ shows[ly[solid], lx[solid]] = ly[solid] * w + edge[solid]+ clear = free & there & ~opaque[ly, near]+ out[ly[clear], lx[clear]] = src[ly[clear], near[clear]]+ shows[ly[clear], lx[clear]] = ly[clear] * w + near[clear]+ out[ly[free & ~there], lx[free & ~there]] = 0+ shows[ly[free & ~there], lx[free & ~there]] = -1+ else:+ still = there & pins.hold[ly, near]+ out[ly[still], lx[still]] = src[ly[still], near[still]]+ shows[ly[still], lx[still]] = ly[still] * w + near[still]+ order = [k for k in range(1, count + 1) if pins.behind[k]] + [k for k in range(1, count + 1) if not pins.behind[k]]+ for k in order:+ ys, xs = cells[k - 1]+ to = xs + steps[k - 1]+ keep = ~(pins.hold[ys, to] | (came_body[ys, to] if pins.behind[k] else False))+ out[ys[keep], to[keep]] = src[ys[keep], xs[keep]]+ shows[ys[keep], to[keep]] = ys[keep] * w + xs[keep]+ return steps+++def _behind_apart(src: np.ndarray, shows: np.ndarray, pins: Pins, carried: np.ndarray, steps: list[int]) -> None:+ """몸 뒤 조각과 그 앞의 몸이 떨어져 그 사이가 비면 거부한다. 장이 몸 뒤 조각의 불투명 칸을 데려온 출력 칸은 비우고 조각은 제+ 칸만큼 다시 그리는데, 그 칸이 정지 그림에서 불투명한 조각 밖의 칸이었고 끝내 아무것도 안 그려졌으면, 몸은 장을 따라 떠났고+ 조각은 다른 칸만큼 가서 몸도 조각도 없는 구멍이다 — 몸 뒤 조각이 몸 안쪽까지 걸쳐 있을 때 생긴다. `carried` 는 출력 칸마다 장이+ 데려온 불투명 조각 칸의 조각 번호(0 = 아님)."""+ holes = (shows < 0) & (src[..., 3] > 0) & (pins.props == 0) & pins.behind[carried] & (carried > 0)+ if not holes.any():+ return+ k = int(carried[holes].min())+ flag, i, n = _piece_name(pins, k)+ raise SystemExit(+ f"breathe(round): {flag} 조각 {i}/{n}({int(np.count_nonzero((pins.props == k) & (src[..., 3] > 0)))}칸)과 그 앞의 몸이 "+ f"따로 움직여, 정지 그림에서 불투명하던 칸 {int(np.count_nonzero(holes & (carried == k)))}개가 빈다 (조각 "+ f"{steps[k - 1]:+d}칸) — 몸 뒤 조각이 몸 안쪽까지 걸쳐 있다. 몸 밖으로 보이는 부분만 --props-behind-mask 로 주거나 그 "+ f"부분을 --props-mask 로 주라.")+++def _piece_ledger(src: np.ndarray, shows: np.ndarray, pins: Pins, steps: list[int],+ t: float) -> tuple[list[int], list[int]]:+ """조각 번호 순으로 조각마다 (가려진 칸, 지어낸 칸) — 출처 지도(`shows`, 출력 칸마다 보이는 원본 칸 번호)에서 읽는다.+ 조각의 불투명 칸은 제 목적지(제 칸 + 옮긴 칸)에 그대로 보이거나(그린 칸) 거기 앞의 것이 보인다(가려진 칸 — 고정 칸은 모든+ 조각 앞이고, 몸과 몸 앞 조각은 몸 뒤 조각 앞이다). 둘의 합이 그 조각의 불투명 칸 수와 다르면 칸이 어디론가 샌 것이라 엔진+ 결함이다 — 조용히 넘기지 않고 거부한다. 지어낸 칸: 제 칸의 사본이 제 목적지가 아닌 자리에 보이는 칸(몸 뒤 조각이 빠져나오며+ 늘어난 테두리, 둘레의 몸이 다 못 따라간 행에 장이 남긴 사본)과, 조각이 떠난 칸에 다른 자리의 고정 칸이 보이는 칸(떠난+ 자리로 늘어난 고정 칸). 고정 칸 자체는 세지 않는다."""+ h, w = shows.shape+ opaque = src[..., 3] > 0+ valid = shows >= 0+ seen = np.maximum(shows, 0)+ sy, sx = seen // w, seen % w+ yy, xx = np.mgrid[0:h, 0:w]+ label = np.where(valid & opaque[sy, sx], pins.props[sy, sx], 0) # 보이는 불투명 조각 칸의 조각 번호 (0 = 아님)+ held = valid & pins.hold[sy, sx]+ body = valid & opaque[sy, sx] & ~pins.hold[sy, sx] & (pins.props[sy, sx] == 0)+ front = (label > 0) & ~pins.behind[label]+ hidden, filled = [], []+ for k, step in enumerate(steps, 1):+ piece = (pins.props == k) & opaque+ ys, xs = np.nonzero(piece)+ to = xs + step+ drawn = shows[ys, to] == ys * w + xs+ ahead = held[ys, to] | ((body[ys, to] | front[ys, to]) if pins.behind[k] else False)+ under = ~drawn & ahead+ if int(np.count_nonzero(drawn)) + int(np.count_nonzero(under)) != ys.size:+ flag, i, n = _piece_name(pins, k)+ raise SystemExit(+ f"breathe(round): 조각 장부가 안 맞는다 — {flag} 조각 {i}/{n}({ys.size}칸) 가운데 제자리 "+ f"{int(np.count_nonzero(drawn))}, 가려짐 {int(np.count_nonzero(under))} (위상 {t:.4f}). 엔진 결함이다 — 조용히 "+ f"넘기지 않는다.")+ covered = np.zeros_like(piece)+ covered[ys, to] = True+ copies = (label == k) & ~((sy == yy) & (sx + step == xx))+ repeated = piece & ~covered & held+ hidden.append(int(np.count_nonzero(under)))+ filled.append(int(np.count_nonzero(copies)) + int(np.count_nonzero(repeated)))+ return hidden, filled+++def _round_warp(frame: Image.Image, anat: Anatomy, cfg: dict, t: float,+ pins: Pins | None = None) -> tuple[Image.Image, list[int], list[int]]:+ """둥근 가슴의 한 위상 — (칸, 조각 번호 순의 가려진 칸 수, 지어낸 칸 수). 캔버스 크기 불변, 강체 경계 위·발·고정 칸 그대로,+ 정수 칸.++ 몸: smooth 처럼 정사상의 역을 고정점 반복(q = o - D(q))으로 풀되 그 자리를 쌍선형으로 뜨지 않고 그 자리에 놓인 원본 칸+ 하나를 통째로 옮긴다 — 출력의 칸은 모두 원본에 있던 칸이다. 장의 기울기가 행당 상한 아래라 이웃한 두 칸이 읽는 원본 칸은+ 같은 줄에서 0·1·2 칸만 떨어진다 (뒤집히지 않는다). 움직이지 않는 칸은 원본 바이트 그대로 둔다. 장이 몸 칸을 셀 밖으로 밀면+ 넘어간 변마다 칸 수를 밝혀 거부한다 — 고정 칸은 장이 0 이라 안 가고, 쥔 물건 조각은 `_place_pieces` 가 제 목적지로 본다.+ 쥔 물건 조각은 장 위에 통째로 놓이고(`_place_pieces` — 장도 몸 앞 조각 둘레를 같은 칸만큼 옮겨 이미 거기 그렸다), 고정 칸이+ 맨 위에 그 칸의 바이트로 놓인다. 조각이 떠난 칸은 빈 칸을 지어내지 않는다: 둘레의 몸이 같은 칸만큼 와서 덮거나, 바로 뒤의+ 고정 칸이 늘어나거나, 몸 뒤 조각이면 그 나머지가 나온다. 쥔 물건이 있으면 출력 칸마다 보이는 원본 칸(출처 지도)을 들고,+ 조각마다 가려진 칸과 지어낸 칸을 거기서 읽는다(`_piece_ledger`) — 그린 칸과 가려진 칸의 합이 조각의 칸 수와 맞는지 칸마다+ 확인한다. 쥔 물건이 없으면 그 길을 타지 않는다."""+ rgba = frame.convert("RGBA")+ curve = smooth_wave(t, _shape(cfg)["inhale"])+ box = solid_alpha_bbox(rgba)+ still = [0] * (0 if pins is None else len(pins.shifts) - 1)+ if not box or curve == 0.0:+ return rgba, still, still # 위상 0 — 원본 그대로 (바이트)+ if anat.origin is not None:+ box = (anat.origin[0], anat.origin[1], anat.origin[0] + anat.width, anat.origin[1] + anat.height)+ src = np.asarray(rgba)+ canvas_h, canvas_w = src.shape[:2]+ y_lo = max(0, int(math.floor(box[1] + anat.rigid_row)))+ y_hi = min(canvas_h, box[1] + anat.height)+ held = pins is not None and pins.props.any()+ if held: # 조각은 목 위에 있어도 옮겨진다+ rows = np.flatnonzero(pins.props.any(axis=1))+ y_lo, y_hi = min(y_lo, int(rows[0])), max(y_hi, int(rows[-1]) + 1)+ if y_hi <= y_lo:+ return rgba, still, still+ iy, ix = np.mgrid[y_lo:y_hi, 0:canvas_w]+ oy = iy.astype(np.float64) + 0.5 - box[1] # 콘텐츠 bbox 기준 픽셀 중심+ ox = ix.astype(np.float64) + 0.5 - box[0]++ def field(x, y):+ dx, dy = _pinned(pins, box, x, y, *round_displacement(anat, cfg, x, y))+ return curve * dx, curve * dy++ fx, fy = field(ox, oy)+ land_x, land_y = ox + fx + box[0], oy + fy + box[1]+ moving = src[y_lo:y_hi, :, 3] > 0 # 장이 옮기는 몸 칸 — 고정 칸은 장이 0 이라 안 가고, 쥔 물건 조각은+ if pins is not None: # `_place_pieces` 가 제 목적지로 본다. 세로 몫은 위로만이라 아래 변은 안 넘는다+ moving &= ~pins.hold[y_lo:y_hi] & (pins.props[y_lo:y_hi] == 0)+ off = {"top": int(np.count_nonzero(moving & (land_y < 0.0))), "left": int(np.count_nonzero(moving & (land_x < 0.0))),+ "right": int(np.count_nonzero(moving & (land_x >= canvas_w)))}+ clipped = int(np.count_nonzero(moving & ((land_y < 0.0) | (land_x < 0.0) | (land_x >= canvas_w))))+ if clipped:+ raise SystemExit(+ f"breathe(round): 가슴·팔이 불투명 픽셀 {clipped}개를 셀 밖으로 민다 — {_sides_off(off)} (셀 {canvas_w}x"+ f"{canvas_h}, 콘텐츠 {box[0]},{box[1]}-{box[2]},{box[3]}). 셀 여백을 늘리거나 chest_round·arms_x 를 낮춰라.")+ qx, qy = ox - fx, oy - fy # 첫걸음: q = o - D(o)+ going = (qx != ox) | (qy != oy)+ gx, gy = ox[going], oy[going]+ wx, wy = qx[going], qy[going]+ for _ in range(7):+ dx, dy = field(wx, wy)+ wx, wy = gx - dx, gy - dy+ qx[going], qy[going] = wx, wy+ sx = np.floor(qx + box[0]).astype(np.int64) # 그 자리에 놓인 원본 칸 (캔버스 인덱스)+ sy = np.floor(qy + box[1]).astype(np.int64)+ moved = (sx != ix) | (sy != iy)+ if pins is None and not moved.any():+ return rgba, still, still+ inside = (sx >= 0) & (sx < canvas_w) & (sy >= 0) & (sy < canvas_h)+ from_y, from_x = np.clip(sy, 0, canvas_h - 1), np.clip(sx, 0, canvas_w - 1)+ taken = src[from_y, from_x]+ taken[~inside] = 0 # 캔버스 밖에서 온 자리는 비어 있다+ out = src.copy()+ region = out[y_lo:y_hi]+ region[moved] = taken[moved]+ hidden = filled = still+ if held:+ opaque = src[..., 3] > 0+ body = opaque & ~pins.hold & (pins.props == 0)+ back = pins.behind[pins.props] # 몸 뒤 조각의 칸+ came_body, came_behind = body.copy(), back.copy() # 장이 몸을, 몸 뒤 조각의 칸을 데려온 출력 칸+ came_body[y_lo:y_hi] = body[from_y, from_x] & inside+ came_behind[y_lo:y_hi] = back[from_y, from_x] & inside+ index = np.arange(canvas_h * canvas_w, dtype=np.int64).reshape(canvas_h, canvas_w)+ shows = index.copy() # 출처 지도 — 출력 칸마다 그 칸이 보이는 원본 칸 번호 (-1 = 빈 칸)+ shows[y_lo:y_hi][moved] = np.where(inside, sy * canvas_w + sx, -1)[moved]+ carried = np.where(opaque, pins.props, 0) # 장이 데려온 불투명 조각 칸의 조각 번호 (0 = 아님)+ carried[y_lo:y_hi] = np.where(inside & opaque[from_y, from_x], pins.props[from_y, from_x], 0)+ steps = _place_pieces(out, shows, src, pins, curve, came_body, came_behind)+ _behind_apart(src, shows, pins, carried, steps)+ if pins is not None:+ out[pins.hold] = src[pins.hold] # 고정 칸이 맨 위 — 장이 그 칸에서 0 이라 이미 그대로다+ if held:+ shows[pins.hold] = index[pins.hold]+ hidden, filled = _piece_ledger(src, shows, pins, steps, t)+ return Image.fromarray(out, "RGBA"), hidden, filled++# ── 해부 결과 얼리기 / 자가 복구 ────────────────────────────────────def _fnv1a(data: bytes) -> int:@@ -966,17 +1714,20 @@ def breathe_reads_smoothly(seq_len: int, cfg: dict, per_cycle: int = SMOOTH_CYCLreturn seq_len // max(1, int(cfg.get("breaths", 1))) >= max(2, per_cycle)-def phase_frame(frame: Image.Image, cfg: dict, phase: float,- anat: Anatomy | None = None) -> Image.Image:+def phase_frame(frame: Image.Image, cfg: dict, phase: float, anat: Anatomy | None = None,+ hold: np.ndarray | None = None, props: np.ndarray | None = None,+ behind: np.ndarray | None = None) -> Image.Image:"""프레임에 호흡 위상 하나(0 <= phase < 1)를 적용.`anat` 를 주면 그것을 쓴다 — 줄 전체가 한 벌을 공유해야 하므로 호출자가 한 번확정해 넘기는 게 정석이다. 생략하면 이 프레임을 기준으로 확정한다 (단발 호출용).- `cfg["mode"]` 가 smooth 면 smooth 로 굽는다 — GIF·아틀라스·레이어·CLI 가 모두 여기를 탄다."""+ `cfg["mode"]` 가 smooth 면 smooth 로 굽는다 — GIF·아틀라스·레이어·CLI 가 모두 여기를 탄다.+ `hold`·`props`·`behind` 는 고정 칸·쥔 물건·몸 뒤 물건 마스크(캔버스 크기) — `bake_breathe_sequence`."""if anat is None:anat = resolve_anatomy(frame, cfg)- _row_refusals(cfg, anat)- return _bake_phase(frame, cfg, phase, anat)+ pins = row_pins(anat, cfg, frame, hold, props, behind)+ _row_refusals(cfg, anat, pins)+ return _bake_phase(frame, cfg, phase, anat, pins)def _pixel_depths(cfg: dict) -> tuple[float, float | None]:@@ -984,10 +1735,13 @@ def _pixel_depths(cfg: dict) -> tuple[float, float | None]:return float(cfg.get("depth", DEFAULT_DEPTH)), None if raw_dx is None else float(raw_dx)-def _row_refusals(cfg: dict, anat: Anatomy) -> None:- """줄이 굽기 전에 거부되는 까닭 — 해부와 설정에만 달려 있어 줄에 한 번 본다 (칸마다 다시 재지 않는다)."""+def _row_refusals(cfg: dict, anat: Anatomy, pins: Pins | None = None) -> None:+ """줄이 굽기 전에 거부되는 까닭 — 해부와 설정(과 고정 칸·쥔 물건)에만 달려 줄에 한 번 본다 (칸마다 다시 재지 않는다)."""if breathe_mode(cfg) == "smooth":- _smooth_refusals(cfg, anat)+ _smooth_refusals(cfg, anat, pins)+ return+ if pixel_round(cfg):+ _round_refusals(cfg, anat, pins)returndepth, depth_x = _pixel_depths(cfg)for axis, d in (("depth", depth), ("depth_x", depth_x)):@@ -1001,27 +1755,75 @@ def _row_refusals(cfg: dict, anat: Anatomy) -> None:f"{axis} 를 낮추거나 rigid_row 를 올려라. 조용히 깎지 않는다.")-def _bake_phase(frame: Image.Image, cfg: dict, phase: float, anat: Anatomy) -> Image.Image:- """거부 검사(`_row_refusals`)를 마친 줄의 한 칸."""+def _bake_phase(frame: Image.Image, cfg: dict, phase: float, anat: Anatomy, pins: Pins | None = None) -> Image.Image:+ """거부 검사(`_row_refusals`)를 마친 줄의 한 칸 (`pins` 는 줄의 고정 칸·쥔 물건)."""+ return _bake_phase_pieces(frame, cfg, phase, anat, pins)[0]+++def _bake_phase_pieces(frame: Image.Image, cfg: dict, phase: float, anat: Anatomy,+ pins: Pins | None = None) -> tuple[Image.Image, list[int], list[int]]:+ """`_bake_phase` 와 그 칸에서 조각 번호 순의 가려진 칸 수·지어낸 칸 수 (쥔 물건은 pixel 의 둥근 가슴만 받는다 — 다른 줄은+ 빈 목록). `bake_breathe_sequence` 의 `record`."""if breathe_mode(cfg) == "smooth":- return _smooth_warp(frame, anat, cfg, phase)+ 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, depth, float(cfg.get("lag", DEFAULT_LAG)), phase, depth_x=depth_x), [], []-def bake_breathe_sequence(images: list[Image.Image], cfg: dict,- anat: Anatomy | None = None) -> tuple[list[Image.Image], list[float]]:+def bake_breathe_sequence(images: list[Image.Image], cfg: dict, anat: Anatomy | None = None,+ hold: np.ndarray | None = None, props: np.ndarray | None = None,+ behind: np.ndarray | None = None,+ record: dict | None = None) -> tuple[list[Image.Image], list[float]]:"""재생 시퀀스에 호흡 레이어를 굽는다 -> (프레임들, 적용 위상들).출력 길이 = 입력 길이 (루프 불변 — 루프는 기존 프레임 그대로, 호흡이 그 안에서- breaths 회 딱 떨어진다). `anat` 는 줄의 해부 한 벌 — 생략하면 첫 칸에서 잰다."""+ breaths 회 딱 떨어진다). `anat` 는 줄의 해부 한 벌 — 생략하면 첫 칸에서 잰다.+ `hold` 는 고정 칸 마스크(캔버스 크기 bool, `read_mask`) — 그 칸은 모든 칸에서 그 칸의 바이트 그대로다. 변위장으로+ 굽는 줄(smooth, pixel 의 둥근 가슴)만 받는다. `props` 는 쥔 물건 마스크, `behind` 는 몸 뒤 물건 마스크 — 조각마다 그쪽+ 팔과 같이 통째로 옮겨진다 (pixel 의 둥근 가슴에 arms_x 가 있을 때만; 무리 번호 격자면 한 번호의 조각들이 같이 — `row_pins`).+ `record` 에 dict 를 주면 줄의 격자(`pins` — `row_pins`, 마스크가 없으면 None)와 칸마다 조각 번호 순의 가려진 칸 수+ (`hidden`)와 지어낸 칸 수(`filled`, 둘 다 `_piece_ledger`)를 거기 담는다: `sprite-gen breathe` 가 그 수를 breathe.json 과+ 경고 줄(`piece_warnings`)에 싣는다 — 가려진 칸을 조용히 버리지 않고, 지어낸 칸을 조용히 채우지 않는다."""if not images:return images, []phases = fit_breathe_pattern(len(images), cfg)if anat is None:anat = resolve_anatomy(images[0], cfg) # 줄 전체가 한 벌을 공유한다- _row_refusals(cfg, anat)- return [_bake_phase(images[i], cfg, phases[i], anat) for i in range(len(images))], phases+ pins = row_pins(anat, cfg, images[0], hold, props, behind)+ _row_refusals(cfg, anat, pins)+ baked = [_bake_phase_pieces(images[i], cfg, phases[i], anat, pins) for i in range(len(images))]+ if record is not None:+ record["pins"], record["hidden"], record["filled"] = pins, [b[1] for b in baked], [b[2] for b in baked]+ return [b[0] for b in baked], phases+++def piece_warnings(record: dict, flag: str) -> list[str]:+ """breathe.json 의 쥔 물건 기록 하나(`props`·`props_behind`, 조각마다 `hidden`·`filled`)에서 경고 줄 — 가려진 칸이 있는+ 조각마다 한 줄(고정 칸 밑으로, 몸 뒤 조각은 몸이나 몸 앞 조각 밑으로도 들어가 그리지 않은 칸), 지어낸 칸이 있는 조각마다 한 줄+ (옮긴 칸이 아니라 곁의 칸을 늘여 채운 칸). 가려진 칸은 조용히 버리지 않고, 지어낸 칸은 조용히 채우지 않는다."""+ lines = []+ pieces = record.get("pieces", [])+ section = "props_behind" if flag == "--props-behind-mask" else "props"+ for i, piece in enumerate(pieces):+ for key in ("hidden", "filled"):+ counts = piece.get(key, [])+ frames = [j for j, n in enumerate(counts) if n]+ if not frames:+ continue+ top = max(range(len(counts)), key=lambda j: counts[j])+ span = f"in {len(frames)} of {len(counts)} frames, up to {piece[key + '_max']} cells (frame {top})"+ head = f"{flag} piece {i + 1} of {len(pieces)} ({piece['cells']} cells)"+ if key == "hidden":+ under = ("held cells, the body or a piece held in front of it" if flag == "--props-behind-mask"+ else "held cells")+ lines.append(f"{head} goes under {under} {span}; those cells are not drawn — breathe.json "+ f"{section}.pieces[{i}].hidden")+ else:+ lines.append(f"{head} leaves cells it fills by repeating a cell {span}; those cells are made up, not moved "+ f"— breathe.json {section}.pieces[{i}].filled")+ return lines# ── CLI: 프레임 폴더에 굽기 (`sprite-gen breathe`) ─────────────────@@ -1060,18 +1862,53 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--lag", type=float, default=None, help=f"pixel only: travelling-wave lag (default {DEFAULT_LAG})")parser.add_argument("--rigid-row", type=int, default=None,help="the row the head starts below, counted from the top of the figure (default: measured)")+ parser.add_argument("--axis-x", type=int, default=None,+ help="the body's axis, a column counted from the left of the figure (default: measured)")+ parser.add_argument("--torso-half", type=int, default=None,+ help="the torso's half width in pixels: columns farther than this from the axis are appendages — "+ "pushed, never stretched; the round chest's arms (default: measured)")parser.add_argument("--reference", default=None, metavar="FRAME.png",help="the frame the row's anatomy is measured on, when it is not the first of these frames — a loop ""set's first cell, for a way in or out of the loop that starts elsewhere: the head line, the chest and ""its rise are the loop's (one size with the frames; default the first frame)")- stretch = parser.add_argument_group("a stretch of a loop (smooth; default the frames are the loop)")+ parser.add_argument("--hold-mask", default=None, metavar="MASK.png",+ help="cells held still: the mask's light opaque pixels (one size with the frames) keep their bytes "+ "in every frame; the breath fades to nothing along their rows and columns (smooth, or pixel "+ "with --chest-round or --arms-x; default none)")+ parser.add_argument("--props-mask", default=None, metavar="MASK.png",+ help="what the arms hold (a sword, a shield): each piece of the mask's light opaque pixels (8-connected, "+ "cells within 2 px joined) moves whole and sideways as far as the hand holding it, the chest's push "+ "there plus --arms-x, and the hand round it moves the same whole cells, so no gap opens between "+ "them; cells a piece leaves beside a held cell take that held cell, and cells it moves onto held "+ "cells stay hidden under them, both counted per frame in breathe.json (filled, hidden) and named "+ "in warning lines; a piece pushed off the frame, or two pieces landing on one cell, is refused "+ "(pixel with --arms-x; default none)")+ parser.add_argument("--props-behind-mask", default=None, metavar="MASK.png",+ help="what the arms hold behind the body (a shield hung at the back): its pieces move as --props-mask "+ "pieces do, but the body stays in front of them: it does not follow them, and where a piece pulls "+ "out from behind it the piece's cell beside it repeats over the cells it left, counted as filled; "+ "a piece and the body moving apart so that cells of the still go empty is refused (pixel with "+ "--arms-x; default none)")+ parser.add_argument("--props-groups", choices=("piece", "colour"), default=None,+ help="piece (default): each piece follows its own hand; colour: the pieces of one colour of the props "+ "masks move by the same cells, read where they touch the body, so a piece the hand does not touch "+ "(a sword's reflection in the water, painted the sword's colour) follows the hand")+ round_ = parser.add_argument_group("round chest (pixel; off by default)")+ round_.add_argument("--chest-round", type=float, default=None,+ help="the chest swells round from its peak: its rim moves out by this share of the body below "+ "the neck at the in-breath's top, whole cells, the head held (0..0.2; 0 or left out: off)")+ round_.add_argument("--arms-x", type=float, default=None,+ help="the arms beside the torso move sideways, out from the body, by this share of the body "+ "below the neck — pushed whole, never stretched (0..0.2; 0 or left out: off)")+ stretch = parser.add_argument_group("a stretch of a loop (smooth or round chest; default the frames are the loop)")stretch.add_argument("--loop-cells", type=int, default=None, metavar="N",help="the frames carry on the breath of an N-cell loop — a way in or out of a loop set: the beat ""(--breaths, --breath-peaks) is that loop's")stretch.add_argument("--start-cell", type=int, default=None, metavar="K",help="the loop's cell the frames start at, 0 to N - 1 (default 0): frame i breathes as the loop's ""cell (K + i) mod N, the very phase")- shape = parser.add_argument_group("smooth shape (defaults in parentheses)")+ shape = parser.add_argument_group("smooth shape (defaults in parentheses; the round chest reads the chest's ellipse "+ "and peak, --inhale and --breath-peaks too)")shape.add_argument("--chest-y", type=float, default=None,help=f"chest centre height, a share of the body below the neck ({SMOOTH_SHAPE['chest_y']})")shape.add_argument("--chest-rx", type=float, default=None,@@ -1130,13 +1967,22 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | 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,- reference: str | None = None, loop_cells: int | None = None, start_cell: int | None = None) -> int:+ 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:"""프레임 폴더에 Breathe 레이어를 굽는다 — 큐레이션 사이드카 `breathe` 와 같은 값, 같은 정규화,같은 굽기(`bake_breathe_sequence`). 영상 루프의 칸처럼 큐레이션 런이 아닌 프레임이 이 길로 온다.`avoid_region` 이면 숨 박자를 칸에서 고른다(`breath_beat`) — 고른 박자도 사이드카와 같은 검사를 다시 지난다.`loop_cells`·`start_cell` 이면 칸들이 그 루프의 숨을 그 칸에서 잇는 토막이고(`fit_breathe_pattern`), `reference` 면- 해부를 첫 칸 대신 그 칸에서 잰다 — 루프 세트의 첫 칸에서 재면 토막의 머리선·가슴·오르는 양이 루프의 것과 같다."""+ 해부를 첫 칸 대신 그 칸에서 잰다 — 루프 세트의 첫 칸에서 재면 토막의 머리선·가슴·오르는 양이 루프의 것과 같다.+ `hold_mask` 면 그 PNG 의 흰 칸이 모든 칸에서 바이트 그대로다 — breathe.json 의 `hold` 에 그 파일의 경로·sha256·칸 수가+ 실린다. `props_mask` 면 그 PNG 의 흰 칸 조각이 팔과 같이 통째로 옮겨진다 — `props` 에 같은 기록과 조각마다 칸 수·들숨+ 꼭대기의 가로 px, 칸마다 고정 칸 밑으로 가려진 칸 수(`hidden`)와 떠난 자리로 늘어나 지어낸 칸 수(`filled`), 그 최대+ (`hidden_max`·`filled_max`)가 실리고, 가려진 칸이나 지어낸 칸이 있는 조각마다 경고 줄이 나온다. `props_behind_mask` 는 몸 뒤+ 물건의 같은 기록(`props_behind`)이다. `props_groups` 가 colour 면 두 마스크의 한 색 조각들이 같은 칸만큼 가고, 조각마다 그 색+ (`colour`)이 실린다."""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),@@ -1144,7 +1990,8 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =("chest_tilt", chest_tilt), ("chest_bias", chest_bias), ("chest_dir", chest_dir),("chest_x", chest_x), ("chest_bias_y", chest_bias_y), ("chest_flat", chest_flat),("inhale", inhale), ("breath_peaks", breath_peaks), ("loop_cells", loop_cells),- ("start_cell", start_cell))+ ("start_cell", start_cell), ("chest_round", chest_round), ("arms_x", arms_x),+ ("axis_x", axis_x), ("torso_half", torso_half))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 의 것이다 — 손 상자 없이는 읽지 않는다")@@ -1170,12 +2017,37 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =chosen, beat = breath_beat.choose(images, smooth_lift(anat, cfg), smooth_inhale(cfg), avoid_region, avoid_anchor,frame_ms)cfg = _cli_breathe(raw | chosen)+ if props_groups is not None and props_mask is None and props_behind_mask is None:+ raise SystemExit("breathe: --props-groups 는 쥔 물건 마스크(--props-mask, --props-behind-mask)의 조각을 묶는다 — "+ "마스크 없이는 묶을 조각이 없다")+ by_colour = props_groups == "colour"+ hold, kept = (None, None) if hold_mask is None else read_mask(hold_mask, images[0].size, "--hold-mask")+ props, grips = ((None, None) if props_mask is None+ else read_mask(props_mask, images[0].size, "--props-mask", colours=by_colour))+ behind, backs = ((None, None) if props_behind_mask is None+ else read_mask(props_behind_mask, images[0].size, "--props-behind-mask", colours=by_colour))resolved = anatomy_report(images, cfg, anat)- baked, phases = bake_breathe_sequence(images, cfg, anat)+ pieces = {}+ baked, phases = bake_breathe_sequence(images, cfg, anat, hold, props, behind, record=pieces)+ for record, flag, back in ((grips, "--props-mask", False), (backs, "--props-behind-mask", True)):+ if record is None:+ continue+ if by_colour:+ record["groups"] = "colour"+ record["pieces"] = pieces["pins"].pieces(pieces["hidden"], behind=back, filled=pieces["filled"])+ for line in piece_warnings(record, flag):+ print(f"breathe: warning: {line}", file=sys.stderr)# 다 굽고 나서 한 번에 내놓는다 — 굽기가 중간에 거부되면 반쯤 찬 폴더를 남기지 않는다(frames.folder.publish).publish(folder, baked, "breathe.json", {"frames": len(images), "source": str(src_dir), "config": cfg,"phases": phases, "resolved": resolved} | ({} if beat is None else {"beat": beat})- | ({} if held is None else {"reference": held}))- print(f"breathe: {len(images)} frames, {breathe_mode(cfg)}, depth {cfg['depth']}, "- f"breaths {cfg['breaths']} -> {out_dir}")+ | ({} if held is None else {"reference": held})+ | ({} if kept is None else {"hold": kept})+ | ({} if grips is None else {"props": grips})+ | ({} if backs is None else {"props_behind": backs}))+ 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}")+ else:+ print(f"breathe: {len(images)} frames, {breathe_mode(cfg)}, depth {cfg['depth']}, "+ f"breaths {cfg['breaths']} -> {out_dir}")return 0diff --git a/sprite_gen/serve/curator/src/breathe.js b/sprite_gen/serve/curator/src/breathe.jsindex 69ffb0b..a2f214c 100644--- a/sprite_gen/serve/curator/src/breathe.js+++ b/sprite_gen/serve/curator/src/breathe.js@@ -280,6 +280,12 @@ function breatheComposite(base, cfg, phase) {throw new BreatheRefused("smooth 줄은 큐레이터가 따라 그리지 않는다 — 결과는 compose(GIF·아틀라스)나 `sprite-gen breathe` 로 본다.");}+ // 둥근 가슴 pixel 줄(chest_round·arms_x)도 미러가 없다 — 봉투 워프로 그리면 굽기와 다른 숨이다.+ if (cfg && ["chest_round", "arms_x"].some((k) => Number(cfg[k]) > 0)) {+ throw new BreatheRefused(+ "둥근 가슴 줄(chest_round·arms_x)은 큐레이터가 따라 그리지 않는다 — 결과는 compose(GIF·아틀라스)나 "+ + "`sprite-gen breathe` 로 본다.");+ }const anat = cfg && cfg.anatomy;// `rigid_row` 는 사람의 의도(입력)이고 `anatomy` 는 거기서 파생된 캐시다. 굽기는 둘이// 어긋나면 재검출해 의도를 따르는데(`resolve_anatomy` 의 stale_override), 미러는 검출을diff --git a/sprite_gen/serve/curator/src/store.js b/sprite_gen/serve/curator/src/store.jsindex e2deb2e..439a3fa 100644--- a/sprite_gen/serve/curator/src/store.js+++ b/sprite_gen/serve/curator/src/store.js@@ -16,6 +16,18 @@ 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], inhale: [0.2, 0.8] };+// pixel 의 둥근 가슴 — 파이썬 curation.BREATHE_ROUND_KEYS·BREATHE_ROUND_MAX·BREATHE_ROUND_SHAPE 미러. 둘 중 하나가 0 보다+// 크면 그 pixel 줄은 둥근 가슴 장을 굽는다: 가슴 타원 키·숨 꼭대기·토막을 smooth 처럼 읽고, 봉투 값(depth·depth_x·lag)은+// 거부한다. 큐레이터는 이 장을 따라 그리지 않는다 (breathe.js 가 거부) — 적힌 그대로 들고 있는다.+const BREATHE_ROUND_KEYS = ["chest_round", "arms_x"];+const BREATHE_ROUND_MAX = 0.20;+const BREATHE_ROUND_SHAPE = ["chest_y", "chest_rx", "chest_ry", "chest_tilt", "chest_bias", "chest_x", "chest_bias_y", "inhale"];++function breatheRound(raw) {+ return raw.mode !== "smooth"+ && BREATHE_ROUND_KEYS.some((k) => raw[k] != null && isNumericScalar(raw[k]) && Number(raw[k]) > 0);+}+function breatheRangeProblems(raw) {const bounds = [["depth", 0.005, 0.20, 0.06], ["breaths", 1, 8, 1], ["lag", 0, 0.45, 0.1]];const bad = [];@@ -25,17 +37,33 @@ function breatheRangeProblems(raw) {if (raw.mode === "smooth" && raw.lag != null && Number(raw.lag) !== 0) {bad.push(`lag=${JSON.stringify(raw.lag)} (smooth 에는 lag 가 없다)`);}- // 모양 값은 smooth 만 쓴다 — pixel 줄에 있으면 굽기가 거부하고, smooth 줄은 범위를 본다.+ // 둥근 가슴 값 — null 은 생략과 같다. smooth 줄에 있거나 범위 밖이면 굽기가 거부한다.+ const rounded = breatheRound(raw);+ for (const key of BREATHE_ROUND_KEYS) {+ if (raw[key] == null) continue;+ if (raw.mode === "smooth") { bad.push(`${key} (pixel 의 둥근 가슴 값)`); continue; }+ const v = isNumericScalar(raw[key]) ? Number(raw[key]) : NaN;+ 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"]) {+ if (raw[key] != null) bad.push(`${key} (둥근 가슴 줄은 봉투 값을 쓰지 않는다)`);+ }+ }+ // 모양 값은 smooth 만 쓴다 — 둥근 가슴 줄은 가슴 타원 키만. 그 밖의 pixel 줄에 있으면 굽기가 거부하고, 읽는 줄은 범위를 본다.for (const [key, [lo, hi]] of Object.entries(BREATHE_SMOOTH_SHAPE_RANGES)) {if (raw[key] === undefined) continue;- if (raw.mode !== "smooth") { bad.push(`${key} (smooth 만 쓰는 모양 값)`); continue; }+ if (raw.mode !== "smooth" && !(rounded && BREATHE_ROUND_SHAPE.includes(key))) {+ bad.push(`${key} (smooth 만 쓰는 모양 값)`);+ continue;+ }const v = isNumericScalar(raw[key]) ? Number(raw[key]) : NaN;if (!Number.isFinite(v) || v < lo || v > hi) bad.push(`${key}=${JSON.stringify(raw[key])}`);}- // 들숨 꼭대기 칸(smooth): 1 부터 커지는 정수, 서로 두 칸 이상 — 파이썬 state_breathe 미러.+ // 들숨 꼭대기 칸(smooth·둥근 가슴): 1 부터 커지는 정수, 서로 두 칸 이상 — 파이썬 state_breathe 미러.if (raw.breath_peaks !== undefined) {const p = raw.breath_peaks;- const ok = raw.mode === "smooth" && Array.isArray(p) && p.length > 0 && p.every(Number.isInteger)+ const ok = (raw.mode === "smooth" || rounded) && Array.isArray(p) && p.length > 0 && p.every(Number.isInteger)&& p[0] >= 1 && p.every((v, i) => i === 0 || v - p[i - 1] >= 2)&& (raw.breaths == null || Number(raw.breaths) === p.length);if (!ok) bad.push(`breath_peaks=${JSON.stringify(p)}`);@@ -44,13 +72,14 @@ function breatheRangeProblems(raw) {// state_breathe 미러 (curation.BREATHE_STRETCH_KEYS).const intAt = (v) => isNumericScalar(v) && Number.isInteger(Number(v));// null 은 생략과 같다(줄이 곧 루프) — 단 pixel 줄에서는 키가 있는 것만으로 굽기가 거부한다.- if (raw.loop_cells !== undefined && (raw.mode !== "smooth"+ if (raw.loop_cells !== undefined && ((raw.mode !== "smooth" && !rounded)|| (raw.loop_cells !== null && (!intAt(raw.loop_cells) || Number(raw.loop_cells) < 2)))) {bad.push(`loop_cells=${JSON.stringify(raw.loop_cells)}`);}if (raw.start_cell !== undefined) {const loop = intAt(raw.loop_cells) ? Number(raw.loop_cells) : Infinity;- const ok = raw.mode === "smooth" && intAt(raw.start_cell) && Number(raw.start_cell) >= 0 && Number(raw.start_cell) < loop;+ const ok = (raw.mode === "smooth" || rounded) && intAt(raw.start_cell) && Number(raw.start_cell) >= 0+ && Number(raw.start_cell) < loop;if (!ok) bad.push(`start_cell=${JSON.stringify(raw.start_cell)}`);}for (const [key, lo, hi, dflt] of bounds) {@@ -652,7 +681,8 @@ function seedEntries() {// smooth 줄은 적힌 그대로 들고 있다. 미러가 없어 미리보기도 편집 결과도 굽기와 맞출 수// 없고, 아래 pixel 정규화를 태우면 첫 autosave 가 pixel 기본값(depth 0.06, lag 0.1)을// 채워 넣어 smooth 줄의 진폭을 바꾸고 굽기가 lag 로 거부하게 된다.- ? rawBreathe.mode === "smooth" ? JSON.parse(JSON.stringify(rawBreathe))+ // 둥근 가슴 pixel 줄도 같다 — 아래 pixel 정규화는 chest_round·arms_x 를 버리고 depth·lag 를 채워 넣는다.+ ? rawBreathe.mode === "smooth" || breatheRound(rawBreathe) ? JSON.parse(JSON.stringify(rawBreathe))// `depth` 생략은 굽기에서 0.06 이다. `Number(undefined)` = NaN 이고// `JSON.stringify(NaN)` 은 `null` 이라, 기본값 분기가 없으면 첫 autosave 가// 사이드카에 `depth: null` 을 박아 **굽기가 죽는다** (validator 실측 2026-07-26).diff --git a/tests/effects/test_breathe_round.py b/tests/effects/test_breathe_round.pynew file mode 100644index 0000000..15001c6--- /dev/null+++ b/tests/effects/test_breathe_round.py@@ -0,0 +1,768 @@+# SPDX-License-Identifier: Apache-2.0+"""Breathe 레이어의 둥근 가슴 (pixel — `chest_round`·`arms_x`)과 고정 칸·쥔 물건 (`--hold-mask`·`--props-mask`).++pixel 봉투 스쿼시는 가로줄을 통째로 눌렀다 늘인다 — 머리가 몸통 위에서 오르내리고 숨이 줄 단위로 읽힌다. 둥근 가슴은+가슴 꼭대기 한 점에서 바깥으로 부풀었다 줄고, 팔은 옆으로 벌어졌다 모이고, 머리와 선 발은 그대로다. 도트 그림이라 출력의+칸은 모두 원본에 있던 칸이다.++지키는 것 (구현이 아니라 계약):+ 1. 위상 0 인 칸은 원본과 바이트 같다 — 루프 이음이 안 바뀐다+ 2. 머리(강체 경계 위)는 모든 칸에서 자리·바이트 그대로+ 3. 가슴은 한 점에서 둥글게 부푼다: 가슴 가운데 줄이 옆으로 가장 많이 나가고 그 아래 줄은 덜, 꼭대기 위는 위로 오르고+ 꼭대기 아래는 위아래로 안 간다 (발이 선다)+ 4. 새 색 0, 칸 순서가 안 뒤집힌다(접힘 없음), 1 px 윤곽선이 1 px 로 남는다+ 5. 팔(부속)은 옆으로 통째 밀린다 — 늘지 않는다+ 6. 쥔 물건은 그쪽 팔과 같은 칸만큼 통째로 가고, 쥔 손과의 사이에 빈 칸이 한 칸도 안 생긴다+ 7. 고정 칸은 모든 칸에서 그 칸의 바이트 그대로 (pixel 둥근 가슴과 smooth 둘 다)+ 8. 키를 안 주거나 0 이면 이전과 바이트 같다, 범위 밖·섞으면 안 되는 키는 조용히 버리지 않고 거부한다+ 9. 쥔 물건 조각의 칸은 모든 칸에서 장부가 맞는다 — 제자리에 그렸거나 앞의 것에 가려졌다(가려진 칸은 센다). 셀 밖으로 가는+ 조각 칸, 한 층의 두 조각이 한 칸에 놓이는 것, 몸 뒤 조각과 몸이 떨어져 생기는 구멍은 거부한다. 떠난 자리로 늘어나 지어낸+ 칸도 센다. 쥔 물건이 없으면 이 길을 타지 않아 바이트가 그대로다+"""++from __future__ import annotations++import dataclasses+import hashlib+import json+import re++import numpy as np+import pytest+from PIL import Image++from sprite_gen.curate.curation import state_breathe+from sprite_gen.effects import breathe as B+from sprite_gen.frames.extract import solid_alpha_bbox++FUR = (200, 140, 60, 255)+LINE = (40, 24, 16, 255)+HAND = (240, 210, 170, 255)+LEG = (170, 110, 50, 255)+HILT = (110, 70, 40, 255)+BLADE = (180, 190, 205, 255)+MARKS = ((255, 0, 0, 255), (0, 200, 0, 255), (0, 0, 255, 255)) # 몸통 안 세로 표시선 — 왼쪽, 가운데, 오른쪽+BAR = (255, 0, 255, 255) # 가슴 위쪽 가로 표시선+LOW = (0, 255, 255, 255) # 가슴 아래쪽 가로 표시선+W, H, AXIS = 150, 124, 75+TORSO = 19+++def _figure() -> tuple[Image.Image, np.ndarray, np.ndarray]:+ """곰 대신 합성 몸 — 둥근 머리, 목, 어깨가 처진 몸통, 어깨에 붙어 늘어진 두 팔과 손, 두 다리, 1 px 윤곽선, 오른손에 붙은+ 막대(칼). (그림, 고정 칸 = 다리, 쥔 물건 = 막대)."""+ yy, xx = np.mgrid[0:H, 0:W]+ dx = xx - AXIS+ head = ((dx + 0.5) / 15.0) ** 2 + ((yy + 0.5 - 24) / 14.0) ** 2 <= 1.0+ neck = (np.abs(dx) <= 6) & (yy >= 37) & (yy < 44)+ half = np.where(yy < 48, 13 + (yy - 42), TORSO)+ torso = (np.abs(dx) <= half) & (yy >= 42) & (yy < 90)+ shoulders = (np.abs(dx) <= 33) & (yy >= 48) & (yy < 53)+ arms = (np.abs(dx) >= 28) & (np.abs(dx) <= 33) & (yy >= 48) & (yy < 79)+ legs = (np.abs(dx) >= 4) & (np.abs(dx) <= 15) & (yy >= 88) & (yy < 113)+ body = head | neck | torso | shoulders | arms | legs+ inner = np.zeros_like(body)+ inner[1:-1, 1:-1] = body[1:-1, 1:-1] & body[:-2, 1:-1] & body[2:, 1:-1] & body[1:-1, :-2] & body[1:-1, 2:]+ a = np.zeros((H, W, 4), np.uint8)+ a[body] = FUR+ a[legs & inner] = LEG+ a[arms & (yy >= 74) & inner] = HAND+ for colour, x in zip(MARKS, (AXIS - 12, AXIS, AXIS + 12)):+ a[(xx == x) & (yy >= 50) & (yy < 86)] = colour+ a[(yy == 55) & (np.abs(dx) <= 14) & (xx != AXIS - 12) & (xx != AXIS) & (xx != AXIS + 12)] = BAR+ a[(yy == 74) & (np.abs(dx) <= 14) & (xx != AXIS - 12) & (xx != AXIS) & (xx != AXIS + 12)] = LOW+ a[body & ~inner] = LINE+ bar = (xx >= AXIS + 34) & (xx <= AXIS + 35) & (yy >= 66) & (yy < 105)+ a[bar] = BLADE+ a[bar & (yy >= 72) & (yy < 81)] = HILT+ hold = legs & (yy >= 90)+ return Image.fromarray(a, "RGBA"), hold, bar+++def _cfg(**raw) -> dict:+ return state_breathe({"states": {"idle": {"breathe": {k: v for k, v in raw.items() if v is not None}}}}, "idle")+++ROUND = dict(chest_round=0.025, breaths=1, torso_half=21)+++def _bake(cfg: dict, count: int = 24, hold=None, props=None):+ src, _, _ = _figure()+ return src, *B.bake_breathe_sequence([src] * count, cfg, hold=hold, props=props)+++def _peak(phases: list[float], inhale: float = 0.4) -> int:+ return min(range(len(phases)), key=lambda i: abs(phases[i] - inhale))+++def _edges(a: np.ndarray, y: int) -> tuple[int, int]:+ xs = np.flatnonzero(a[y, :, 3] > 0)+ return int(xs[0]), int(xs[-1])+++def _torso(a: np.ndarray, y: int) -> tuple[int, int]:+ """그 줄에서 몸통 축을 지나는 불투명 구간의 양 끝 — 팔과 사이가 떠 있어 팔은 안 센다."""+ left = right = AXIS+ while a[y, left - 1, 3] > 0:+ left -= 1+ while a[y, right + 1, 3] > 0:+ right += 1+ return left, right+++def _row_of(a: np.ndarray, colour, x: int) -> float:+ ys = np.flatnonzero((a[:, x] == colour).all(-1))+ assert ys.size, f"표시선 {colour} 를 열 {x} 에서 못 찾았다"+ return float(ys.mean())+++# ── 1·2. 쉼은 원본, 머리는 그대로 ────────────────────────────────────++def test_the_rest_is_the_source_and_the_head_never_moves() -> None:+ src, frames, phases = _bake(_cfg(**ROUND))+ anat = B.resolve_anatomy(src, _cfg(**ROUND))+ top = solid_alpha_bbox(src)[1] + anat.rigid_row+ base = np.asarray(src)+ assert frames[0].tobytes() == src.tobytes(), "위상 0 인 첫 칸이 원본과 다르다"+ assert any(f.tobytes() != src.tobytes() for f in frames), "숨을 한 번도 안 쉬었다"+ for i, f in enumerate(frames):+ assert np.array_equal(np.asarray(f)[:top], base[:top]), f"{i}번 칸: 강체 경계 위(머리)가 움직였다"+++# ── 3. 한 점에서 둥글게 ──────────────────────────────────────────────++def test_the_chest_swells_round_from_one_point() -> None:+ cfg = _cfg(**ROUND)+ src, frames, phases = _bake(cfg)+ anat = B.resolve_anatomy(src, cfg)+ box = solid_alpha_bbox(src)+ px, py = B.smooth_chest_peak(anat, cfg)+ centre, ry = int(box[1] + py), B._chest_frame(anat, cfg)[3]+ base, peak = np.asarray(src), np.asarray(frames[_peak(phases)])+ l0, r0 = _torso(base, centre)+ l1, r1 = _torso(peak, centre)+ assert l0 - l1 >= 2 and r1 - r0 >= 2, f"가슴 가운데 줄이 옆으로 안 부풀었다: {l0},{r0} -> {l1},{r1}"+ assert abs((l0 - l1) - (r1 - r0)) <= 1, "가운데에서 부푼 가슴이 한쪽으로 쏠렸다"+ lower = int(centre + 0.8 * ry)+ u0, v0 = _torso(base, lower)+ u1, v1 = _torso(peak, lower)+ assert 0 < (v1 - v0) < (r1 - r0), (f"둥근 부풂이 아니다 — 가슴 아래쪽 줄({lower})이 가운데 줄({centre})보다 덜 나가야 "+ f"한다: 아래 {v1 - v0}, 가운데 {r1 - r0}")+ # 꼭대기 위는 오르고, 꼭대기 아래는 위아래로 안 간다 — 선 발을 누르지 않는다+ assert _row_of(base, BAR, AXIS + 4) - _row_of(peak, BAR, AXIS + 4) >= 1.0, "꼭대기 위 가로선이 안 올랐다"+ assert _row_of(peak, LOW, AXIS + 4) == _row_of(base, LOW, AXIS + 4), "꼭대기 아래 가로선이 위아래로 움직였다"+ # 꼭대기 자리는 제자리다 — 부풂의 가운데+ assert (peak[int(box[1] + py), AXIS] == base[int(box[1] + py), AXIS]).all()+++def test_the_chest_comes_back_down_each_breath() -> None:+ _, frames, phases = _bake(_cfg(**{**ROUND, "breaths": 2}))+ rest = [i for i, p in enumerate(phases) if p == 0.0]+ assert rest == [0, 12]+ assert frames[12].tobytes() == frames[0].tobytes(), "둘째 숨이 쉼에서 시작하지 않는다"+++# ── 4. 도트 그대로 ───────────────────────────────────────────────────++def test_the_round_chest_is_pixel_true() -> None:+ src, frames, _ = _bake(_cfg(**{**ROUND, "arms_x": 0.02}))+ base = np.asarray(src)+ palette = {tuple(c) for c in base.reshape(-1, 4)[base[..., 3].reshape(-1) > 0].tolist()}+ for i, f in enumerate(frames):+ a = np.asarray(f)+ colours = {tuple(c) for c in a.reshape(-1, 4)[a[..., 3].reshape(-1) > 0].tolist()}+ assert colours <= palette, f"{i}번 칸에 원본에 없는 색 {len(colours - palette)}개"+ assert set(np.unique(a[..., 3])) <= {0, 255}, f"{i}번 칸에 반투명 칸이 생겼다"+ # 접힘 없음 — 몸통 안 세 세로선이 모든 줄에서 왼쪽·가운데·오른쪽 순서 그대로, 한 칸 두께 그대로+ for y in range(50, 86):+ at = [np.flatnonzero((a[y] == c).all(-1)) for c in MARKS]+ if all(x.size for x in at):+ assert at[0].max() < at[1].min() and at[1].max() < at[2].min(), f"{i}번 칸 {y}줄: 칸 순서가 뒤집혔다"+ # 1 px 윤곽선 — 몸통 줄의 양 끝 칸은 윤곽선이고 그 안쪽 칸은 아니다+ for y in range(56, 66): # 팔 줄 — 66 줄부터는 줄 끝이 윤곽선 없는 막대다+ left, right = _edges(a, y)+ assert tuple(a[y, left]) == LINE and tuple(a[y, right]) == LINE, f"{i}번 칸 {y}줄: 윤곽선이 빠졌다"+ assert tuple(a[y, left + 1]) != LINE and tuple(a[y, right - 1]) != LINE, f"{i}번 칸 {y}줄: 윤곽선이 두 칸이다"+++# ── 5. 팔은 옆으로 통째 ───────────────────────────────────────────────++def test_the_arms_move_sideways_whole() -> None:+ cfg = _cfg(arms_x=0.03, breaths=1, torso_half=21)+ src, frames, phases = _bake(cfg)+ base, peak = np.asarray(src), np.asarray(frames[_peak(phases)])+ for y in range(56, 72):+ for side, (lo, hi) in (("왼", (AXIS - 34, AXIS - 27)), ("오른", (AXIS + 27, AXIS + 34))):+ seg = base[y, lo:hi + 1]+ hits = [k for k in range(-5, 6) if np.array_equal(peak[y, lo + k:hi + 1 + k], seg)]+ assert hits, f"{y}줄 {side}팔이 통째로 옮겨지지 않았다 (늘었거나 찢겼다)"+ k = hits[0]+ assert (k < 0) if side == "왼" else (k > 0), f"{y}줄 {side}팔이 바깥으로 안 갔다: {k}"+++# ── 6. 쥔 물건은 손과 한 덩이 ─────────────────────────────────────────++def test_a_held_bar_moves_with_the_hand_and_no_gap_opens() -> None:+ src, hold, bar = _figure()+ cfg = _cfg(**{**ROUND, "arms_x": 0.02})+ frames, phases = B.bake_breathe_sequence([src] * 24, cfg, hold=hold, props=bar)+ base = np.asarray(src)+ ys, xs = np.nonzero(bar)+ steps = []+ for i, f in enumerate(frames):+ a = np.asarray(f)+ found = [k for k in range(-5, 6) if np.array_equal(a[ys, xs + k], base[ys, xs])]+ assert found, f"{i}번 칸: 막대가 통째로 옮겨지지 않았다"+ k = found[0]+ steps.append(k)+ for y in range(74, 79): # 막대를 쥔 손 줄 — 손 바깥 윤곽선과 막대 사이에 빈 칸이 없다+ hand = np.flatnonzero((a[y, :AXIS + 34 + k] == LINE).all(-1))+ assert hand.size and hand.max() == AXIS + 33 + k, (+ f"{i}번 칸 {y}줄: 손이 막대와 같은 {k}칸을 안 갔다 (손 끝 {hand.max() if hand.size else None})")+ assert max(steps) >= 2, f"팔이 들숨에 막대를 바깥으로 안 옮겼다: {steps}"+ assert steps[0] == 0+++# ── 7. 고정 칸 ───────────────────────────────────────────────────────+[email protected]("cfg", [_cfg(**{**ROUND, "arms_x": 0.02}), _cfg(mode="smooth", depth=0.02, breaths=1)],+ ids=["round", "smooth"])+def test_held_cells_keep_their_bytes_in_every_frame(cfg) -> None:+ src, hold, _ = _figure()+ frames, _ = B.bake_breathe_sequence([src] * 24, cfg, hold=hold)+ base = np.asarray(src)+ assert any(f.tobytes() != src.tobytes() for f in frames)+ for i, f in enumerate(frames):+ changed = int((np.asarray(f)[hold] != base[hold]).any(-1).sum())+ assert changed == 0, f"{i}번 칸: 고정 칸 {changed}개가 바뀌었다"+++# ── 8. 기본은 그대로, 거부는 요란하게 ───────────────────────────────++def test_the_new_keys_off_keep_every_byte() -> None:+ plain = _cfg(depth=0.06, breaths=2, lag=0.1)+ off = _cfg(depth=0.06, breaths=2, lag=0.1, chest_round=0, arms_x=0)+ assert off == plain, "chest_round·arms_x 가 0 인 줄의 정규화가 키 없는 줄과 다르다"+ src, _, _ = _figure()+ a, _ = B.bake_breathe_sequence([src] * 12, plain)+ b, _ = B.bake_breathe_sequence([src] * 12, off)+ assert [f.tobytes() for f in a] == [f.tobytes() for f in b]+++def test_a_round_row_reads_its_keys() -> None:+ cfg = _cfg(chest_round=0.05, arms_x=0.02, breath_peaks=[3, 9], inhale=0.5, chest_y=0.4)+ assert cfg["chest_round"] == 0.05 and cfg["arms_x"] == 0.02 and cfg["breath_peaks"] == [3, 9]+ assert cfg["breaths"] == 2 and cfg["inhale"] == 0.5 and cfg["chest_y"] == 0.4+ assert "depth" not in cfg and "lag" not in cfg and "shoulder" not in cfg+ assert B.pixel_round(cfg) and B.breathe_mode(cfg) == "pixel"++[email protected]("raw,match", [+ ({"chest_round": 0.3}, "chest_round"),+ ({"arms_x": -0.01}, "arms_x"),+ ({"chest_round": "a"}, "chest_round"),+ ({"chest_round": 0.04, "depth": 0.06}, "depth"),+ ({"chest_round": 0.04, "lag": 0.1}, "lag"),+ ({"arms_x": 0.03, "shoulder": 0.5}, "shoulder"),+ ({"chest_round": 0.04, "chest_flat": 0.2}, "chest_flat"),+ ({"mode": "smooth", "chest_round": 0.04}, "chest_round"),+ ({"chest_y": 0.4}, "smooth"),+])+def test_wrong_round_keys_are_refused(raw, match) -> None:+ with pytest.raises(SystemExit, match=match):+ _cfg(**raw)++[email protected]("masked", [False, True], ids=["bare", "with-hold"])[email protected]("cfg", [_cfg(chest_round=0.2, breaths=1, torso_half=21), _cfg(mode="smooth", depth=0.2, breaths=1)],+ ids=["round", "smooth"])+def test_a_strain_past_the_cap_is_refused_with_or_without_held_cells(cfg, masked) -> None:+ """고정 칸을 줘도 몸의 장이 행당 상한을 넘으면 거부는 그대로다 — 재지 않고 빼는 건 고정 칸·쥔 물건 칸과 그 이웃뿐이다."""+ src, hold, _ = _figure()+ with pytest.raises(SystemExit, match="상한"):+ B.bake_breathe_sequence([src] * 4, cfg, hold=hold if masked else None)+++def test_masks_need_a_field_bake_and_props_need_arms() -> None:+ src, hold, bar = _figure()+ with pytest.raises(SystemExit, match="hold-mask"):+ B.bake_breathe_sequence([src] * 4, _cfg(depth=0.06, breaths=1), hold=hold)+ with pytest.raises(SystemExit, match="arms_x"):+ B.bake_breathe_sequence([src] * 4, _cfg(**ROUND), props=bar)+ with pytest.raises(SystemExit, match="고정 칸이면서"):+ B.bake_breathe_sequence([src] * 4, _cfg(**{**ROUND, "arms_x": 0.02}), hold=hold | bar, props=bar)+ with pytest.raises(SystemExit, match="크기"):+ B.bake_breathe_sequence([src] * 4, _cfg(**ROUND), hold=hold[:-1])+++# ── CLI: 같은 값, 같은 굽기 ─────────────────────────────────────────++def test_the_cli_bakes_what_the_library_bakes(tmp_path) -> None:+ from sprite_gen import cli++ src, hold, bar = _figure()+ loop = tmp_path / "loop"+ loop.mkdir()+ for i in range(12):+ src.save(loop / f"frame-{i:03d}.png")+ masks = {}+ for name, m in (("hold", hold), ("props", bar)):+ masks[name] = tmp_path / f"{name}.png"+ Image.fromarray(np.where(m, 255, 0).astype(np.uint8), "L").save(masks[name])+ out = tmp_path / "out"+ assert cli.main(["breathe", str(loop), str(out), "--chest-round", "0.025", "--arms-x", "0.02", "--breaths", "1", "--torso-half", "21",+ "--hold-mask", str(masks["hold"]), "--props-mask", str(masks["props"])]) == 0+ cfg = _cfg(chest_round=0.025, arms_x=0.02, breaths=1, torso_half=21)+ want, phases = B.bake_breathe_sequence([src] * 12, cfg, hold=hold, props=bar)+ for i, frame in enumerate(want):+ with Image.open(out / f"frame-{i:03d}.png") as im:+ assert im.convert("RGBA").tobytes() == frame.tobytes(), f"{i}번 칸이 라이브러리 굽기와 다르다"+ report = json.loads((out / "breathe.json").read_text(encoding="utf-8"))+ assert report["config"] == json.loads(json.dumps(cfg)) and report["phases"] == phases+ assert report["hold"]["cells"] == int(hold.sum()) and len(report["hold"]["sha256"]) == 64+ assert report["props"]["cells"] == int(bar.sum())+ assert [p["cells"] for p in report["props"]["pieces"]] == [int(bar.sum())]+ assert report["props"]["pieces"][0]["shift_px"] > 0, "오른쪽 막대가 바깥(오른쪽)으로 가지 않는다"+++# ── 9. 고정 칸 밑으로 가는 쥔 물건: 세고, 경고하고, 떠난 자리는 고정 칸이 채운다 ─────────────++WATER = (90, 180, 170, 255)+GLINT = (225, 225, 235, 255)+RIM = (120, 120, 130, 255)+PLANK = (150, 100, 60, 255)+++def _wet_figure() -> tuple[Image.Image, np.ndarray, np.ndarray]:+ """막대(칼)의 아래 끝이 물 띠에 잠긴 몸 — 물 띠는 막대 양옆에 붙은 고정 칸이다. 막대가 들숨에 바깥(오른쪽)으로 가면 오른쪽+ 물 밑으로 들어가고, 왼쪽에 떠난 칸이 생긴다. (그림, 고정 칸 = 다리와 물, 쥔 물건 = 막대)."""+ src, legs, bar = _figure()+ a = np.asarray(src).copy()+ yy, xx = np.mgrid[0:H, 0:W]+ water = (yy >= 96) & (yy < 105) & (((xx >= AXIS + 28) & (xx < AXIS + 34)) | ((xx >= AXIS + 36) & (xx < AXIS + 45)))+ a[water] = WATER+ return Image.fromarray(a, "RGBA"), legs | water, bar+++def _bar_step(a: np.ndarray, base: np.ndarray, bar: np.ndarray) -> int:+ """막대가 옮겨진 칸 — 물 위의 막대 칸이 통째로 맞는 가로 칸."""+ ys, xs = np.nonzero(bar & (np.arange(H)[:, None] < 96))+ found = [k for k in range(-5, 6) if np.array_equal(a[ys, xs + k], base[ys, xs])]+ assert found, "막대가 통째로 옮겨지지 않았다"+ return found[0]+++def test_a_prop_going_under_held_cells_is_counted_warned_and_leaves_no_gap(tmp_path, capsys) -> None:+ from sprite_gen import cli++ src, hold, bar = _wet_figure()+ loop = tmp_path / "loop"+ loop.mkdir()+ for i in range(24):+ src.save(loop / f"frame-{i:03d}.png")+ masks = {}+ for name, m in (("hold", hold), ("props", bar)):+ masks[name] = tmp_path / f"{name}.png"+ Image.fromarray(np.where(m, 255, 0).astype(np.uint8), "L").save(masks[name])+ out = tmp_path / "out"+ assert cli.main(["breathe", str(loop), str(out), "--chest-round", "0.025", "--arms-x", "0.02", "--breaths", "1",+ "--torso-half", "21", "--hold-mask", str(masks["hold"]), "--props-mask", str(masks["props"])]) == 0+ base = np.asarray(src)+ report = json.loads((out / "breathe.json").read_text(encoding="utf-8"))+ piece = report["props"]["pieces"][0]+ want = []+ for i in range(24):+ with Image.open(out / f"frame-{i:03d}.png") as im:+ a = np.asarray(im.convert("RGBA"))+ assert np.array_equal(a[hold], base[hold]), f"{i}번 칸: 고정 칸이 바뀌었다 (쥔 물건이 고정 칸 위에 그려졌다)"+ k = _bar_step(a, base, bar)+ ys, xs = np.nonzero(bar)+ want.append(int(np.count_nonzero(hold[ys, xs + k])))+ if k > 0: # 물에 잠긴 줄에서 막대가 떠난 칸은 바로 뒤의 물이 채운다 — 빈 칸 없음+ for y in range(96, 105):+ left = a[y, AXIS + 34:AXIS + 34 + k]+ assert (left == WATER).all(), f"{i}번 칸 {y}줄: 막대가 떠난 자리가 물이 아니다 (틈)"+ assert max(want) > 0, "막대가 물 밑으로 한 번도 안 들어갔다 — 시험이 반례를 못 만든다"+ assert piece["hidden"] == want, "breathe.json 의 칸마다 가려진 칸 수가 물 밑으로 들어간 막대 칸 수와 다르다"+ assert piece["hidden_max"] == max(want)+ err = capsys.readouterr().err+ assert "breathe: warning: --props-mask piece 1 of 1" in err and f"up to {max(want)} cells" in err, err+++# ── 10. 손에 안 닿은 반사는 색으로 묶으면 칼과 같은 칸만큼 간다 ─────────────────────────────++def _reflected_figure() -> tuple[Image.Image, np.ndarray, np.ndarray, np.ndarray]:+ """막대 아래 물 띠에 막대의 반사(손에 안 닿은 따로 조각)가 비친 몸. (그림, 고정 칸 = 다리와 반사가 갈 자리 밖의 물, 막대,+ 반사)."""+ src, legs, bar = _figure()+ a = np.asarray(src).copy()+ yy, xx = np.mgrid[0:H, 0:W]+ water = (yy >= 109) & (yy < 116) & (xx >= AXIS + 22) & (xx < AXIS + 48)+ glint = (yy >= 110) & (yy < 113) & (xx >= AXIS + 34) & (xx < AXIS + 37)+ zone = (yy >= 110) & (yy < 113) & (xx >= AXIS + 37) & (xx < AXIS + 41) # 반사가 갈 물 — 고정에서 뺀다+ a[water] = WATER+ a[glint] = GLINT+ return Image.fromarray(a, "RGBA"), legs | (water & ~glint & ~zone), bar, glint+++def test_a_reflection_painted_the_swords_colour_follows_the_sword(tmp_path) -> None:+ """물 띠 안의 반사(손에 안 닿은 따로 조각)를 막대와 같은 색으로 칠하고 --props-groups colour 로 굽는다 — 모든 칸에서 반사가+ 막대와 같은 칸만큼 가고, 반사가 떠난 자리는 정지 그림의 물이고, 새 색이 없다."""+ from sprite_gen import cli++ src, hold, bar, glint = _reflected_figure()+ loop = tmp_path / "loop"+ loop.mkdir()+ for i in range(24):+ src.save(loop / f"frame-{i:03d}.png")+ paint = np.zeros((H, W, 3), np.uint8)+ paint[bar | glint] = (255, 255, 0) # 막대와 반사는 한 색, 한 무리+ Image.fromarray(paint, "RGB").save(tmp_path / "props.png")+ Image.fromarray(np.where(hold, 255, 0).astype(np.uint8), "L").save(tmp_path / "hold.png")+ out = tmp_path / "out"+ assert cli.main(["breathe", str(loop), str(out), "--chest-round", "0.025", "--arms-x", "0.02", "--breaths", "1",+ "--torso-half", "21", "--hold-mask", str(tmp_path / "hold.png"), "--props-mask",+ str(tmp_path / "props.png"), "--props-groups", "colour"]) == 0+ base = np.asarray(src)+ palette = {tuple(c) for c in base.reshape(-1, 4)[base[..., 3].reshape(-1) > 0].tolist()}+ report = json.loads((out / "breathe.json").read_text(encoding="utf-8"))+ pieces = report["props"]["pieces"]+ assert report["props"]["groups"] == "colour" and len(pieces) == 2+ assert {p["colour"] for p in pieces} == {"#ffff00"} and pieces[0]["shift_px"] == pieces[1]["shift_px"]+ gy, gx = np.nonzero(glint)+ steps = []+ for i in range(24):+ with Image.open(out / f"frame-{i:03d}.png") as im:+ f = np.asarray(im.convert("RGBA"))+ k = _bar_step(f, base, bar)+ steps.append(k)+ assert np.array_equal(f[gy, gx + k], base[gy, gx]), f"{i}번 칸: 반사가 막대와 같은 {k}칸을 안 갔다"+ left = glint & ~np.roll(glint, k, axis=1) if k else np.zeros_like(glint)+ assert (f[left] == WATER).all(), f"{i}번 칸: 반사가 떠난 자리가 정지 그림의 물이 아니다"+ assert np.array_equal(f[hold], base[hold]), f"{i}번 칸: 고정 칸이 바뀌었다"+ colours = {tuple(c) for c in f.reshape(-1, 4)[f[..., 3].reshape(-1) > 0].tolist()}+ assert colours <= palette, f"{i}번 칸에 원본에 없는 색"+ assert max(steps) >= 2, f"막대와 반사가 들숨에 바깥으로 안 갔다: {steps}"+++# ── 11. 몸 뒤 물건(등에 건 방패)은 몸 뒤에서 빠져나오고, 그 자리는 방패의 나머지다 ──────────++def _shielded_figure() -> tuple[Image.Image, np.ndarray, np.ndarray]:+ """고정된 왼팔 뒤에 방패가 걸린 몸 — 방패가 팔 뒤로 들어가는 열은 테두리 색. (그림, 고정 칸 = 다리와 왼팔, 방패)."""+ src, legs, _ = _figure()+ a = np.asarray(src).copy()+ yy, xx = np.mgrid[0:H, 0:W]+ arm = (xx >= AXIS - 33) & (xx <= AXIS - 28) & (yy >= 48) & (yy < 79)+ shield = (xx >= AXIS - 41) & (xx < AXIS - 33) & (yy >= 58) & (yy < 73)+ a[shield] = PLANK+ a[shield & (xx == AXIS - 34)] = RIM # 방패가 팔 뒤로 들어가는 테두리+ return Image.fromarray(a, "RGBA"), legs | arm, shield+++def test_a_shield_behind_the_body_slides_out_from_behind_it() -> None:+ """방패가 고정된 왼팔 뒤에 걸려 있다. 몸 뒤 물건으로 주면 들숨에 바깥(왼쪽)으로 빠져나오며, 팔과 방패 사이는 방패가 팔에+ 닿았던 칸(테두리)이 채운다 — 빈 칸도, 팔의 윤곽이 두꺼워지는 것도 없다. 몸 앞 물건으로 주면 그 자리는 고정된 팔의 윤곽이+ 늘어난다 (몸 앞 물건이 떠난 자리에는 그 뒤의 것이 나온다)."""+ src, hold, shield = _shielded_figure()+ cfg = _cfg(**{**ROUND, "arms_x": 0.02})+ base = np.asarray(src)+ behind, _ = B.bake_breathe_sequence([src] * 24, cfg, hold=hold, behind=shield)+ front, _ = B.bake_breathe_sequence([src] * 24, cfg, hold=hold, props=shield)+ ys, xs = np.nonzero(shield)+ moved = 0+ for i, (f, g) in enumerate(zip(behind, front)):+ f, g = np.asarray(f), np.asarray(g)+ assert np.array_equal(f[hold], base[hold]), f"{i}번 칸: 고정된 팔이 바뀌었다"+ found = [k for k in range(-5, 1) if np.array_equal(f[ys, xs + k], base[ys, xs])]+ assert found, f"{i}번 칸: 방패가 통째로 옮겨지지 않았다"+ k = found[0]+ if k:+ moved += 1+ gap = f[58:73, AXIS - 34 + k + 1:AXIS - 33]+ assert (gap == RIM).all(), f"{i}번 칸: 방패가 빠져나온 자리가 방패 테두리가 아니다 (틈이거나 팔 윤곽)"+ assert (np.asarray(g)[58:73, AXIS - 34 + k + 1:AXIS - 33] == LINE).all(), \+ f"{i}번 칸: 몸 앞 물건이 떠난 자리를 고정된 팔 윤곽이 채우지 않았다"+ assert moved, "방패가 한 번도 안 움직였다"+++def test_props_groups_without_a_props_mask_is_refused(tmp_path) -> None:+ from sprite_gen import cli++ src, _, _ = _figure()+ loop = tmp_path / "loop"+ loop.mkdir()+ src.save(loop / "frame-000.png")+ with pytest.raises(SystemExit, match="props-groups"):+ cli.main(["breathe", str(loop), str(tmp_path / "out"), "--chest-round", "0.025", "--arms-x", "0.02",+ "--torso-half", "21", "--props-groups", "colour"])+++# ── 12. 조각 장부: 셀 밖·한 칸 겹침·몸 뒤 구멍은 거부, 가려진 칸·지어낸 칸은 세고, 모든 칸에서 장부가 맞는다 ─────────────++INK = (37, 99, 203, 255)+HELD = _cfg(**{**ROUND, "arms_x": 0.02})+INHALE = B._shape(HELD)["inhale"] # 들숨 꼭대기의 위상 — 곡선이 1 이다+++def _with_piece(rows: slice, cols: slice) -> tuple[Image.Image, np.ndarray, np.ndarray]:+ """`_figure` 에 몸과 떨어진 네모 조각 하나를 칠한 그림. (그림, 고정 칸 = 다리, 조각)."""+ src, legs, _ = _figure()+ a = np.asarray(src).copy()+ piece = np.zeros(legs.shape, bool)+ piece[rows, cols] = True+ a[piece] = INK+ return Image.fromarray(a, "RGBA"), legs, piece+++def _scene(name: str) -> tuple[Image.Image, np.ndarray | None, np.ndarray | None, np.ndarray | None]:+ """장부 시험의 장면 — (그림, 고정 칸, 쥔 물건, 몸 뒤 물건). 쥔 물건은 bool 이거나 무리 번호 격자(색으로 묶은 것)다."""+ src, legs, bar = _figure()+ if name == "round":+ return src, None, None, None+ if name == "held legs":+ return src, legs, None, None+ if name == "bar":+ return src, legs, bar, None+ if name == "wet bar":+ return (*_wet_figure(), None)+ if name == "reflection":+ reflected, hold, bar, glint = _reflected_figure()+ return reflected, hold, np.where(bar | glint, 0xFFFF00 + 1, 0), None+ if name in ("shield behind", "shield in front"):+ shielded, hold, shield = _shielded_figure()+ return (shielded, hold, None, shield) if name == "shield behind" else (shielded, hold, shield, None)+ if name == "above the head line": # 몸이 조각을 따라가는 몫이 꺼진 행 — 장은 조각을 안 옮긴다+ return (*_with_piece(slice(20, 25), slice(30, 34)), None)+ if name == "across the head line": # 그 몫이 켜지는 행에 걸친 조각+ return (*_with_piece(slice(30, 60), slice(24, 27)), None)+ if name == "behind off the body": # 몸에 안 닿은 몸 뒤 조각 — 떠난 칸 뒤가 비어 빈 칸이 된다+ piece_src, legs, piece = _with_piece(slice(110, 113), slice(10, 13))+ return piece_src, legs, None, piece+ raise KeyError(name)+++def _traced(src: Image.Image, cfg: dict, phase: float, anat, pins) -> np.ndarray:+ """출처 꼬리표 — 칸마다 제 번호를 RGB 에 실은 그림을 같은 해부·핀으로 구워, 출력 칸마다 그 칸이 보이는 원본 칸 번호를 읽는다+ (-1 = 빈 칸). 엔진의 장부와 따로 세는 판정이다: 굽기의 결정은 알파와 마스크에만 달려 꼬리표 그림도 같은 길로 굽힌다."""+ a = np.asarray(src.convert("RGBA"))+ h, w = a.shape[:2]+ ids = np.arange(1, h * w + 1).reshape(h, w)+ tag = Image.fromarray(np.stack([(ids >> 16) & 255, (ids >> 8) & 255, ids & 255, a[..., 3]], -1).astype(np.uint8), "RGBA")+ out = np.asarray(B._bake_phase(tag, cfg, phase, anat, pins)).astype(np.int64)+ code = (out[..., 0] << 16) | (out[..., 1] << 8) | out[..., 2]+ return np.where((code > 0) & (out[..., 3] > 0), code - 1, -1)+++def _counted(src: Image.Image, seen: np.ndarray, pins, curve: float) -> list[tuple[int, int, int]]:+ """출처에서 센 조각마다 (불투명 칸 수, 제 목적지에 그대로 보이는 칸, 지어낸 칸). 지어낸 칸 = 제 칸이 제 목적지(제 칸 + 옮긴+ 칸)가 아닌 자리에 보이는 칸 + 조각이 떠난 칸에 보이는 다른 자리의 고정 칸."""+ a = np.asarray(src.convert("RGBA"))+ h, w = a.shape[:2]+ opaque = a[..., 3] > 0+ yy, xx = np.mgrid[0:h, 0:w]+ sy, sx = np.where(seen >= 0, seen // w, -1), np.where(seen >= 0, seen % w, -1)+ label = np.where(seen >= 0, np.where(opaque, pins.props, 0)[np.maximum(sy, 0), np.maximum(sx, 0)], 0)+ held = (seen >= 0) & pins.hold[np.maximum(sy, 0), np.maximum(sx, 0)]+ rows = []+ for k in range(1, len(pins.shifts)):+ step = B.piece_step(pins, k, curve)+ ys, xs = np.nonzero((pins.props == k) & opaque)+ drawn = int(np.count_nonzero(seen[ys, xs + step] == ys * w + xs))+ left = (pins.props == k) & opaque+ left[ys, xs + step] = False+ made = int(np.count_nonzero((label == k) & ~((sy == yy) & (sx + step == xx)))) + int(np.count_nonzero(left & held))+ rows.append((int(ys.size), drawn, made))+ return rows++[email protected]("layer", ["--props-behind-mask", "--props-mask"])+def test_a_piece_pushed_off_the_canvas_is_refused_not_cut(tmp_path, layer) -> None:+ """체크포인트 반례 — 몸과 떨어진 3x3 조각이 캔버스 왼쪽 변에 붙어 있고 들숨에 왼쪽으로 한 칸 간다. 몸 뒤 조각이든 몸 앞+ 조각이든 조각의 이름과 넘어간 변·칸 수를 밝혀 거부한다: 자르고 굽지 않으며(몸 뒤 조각은 장에서 빠져 장의 셀 밖 검사를+ 지나쳤다), 몸이 민 것으로 말하지 않는다(몸 앞 조각). 아무 폴더도 만들지 않는다."""+ from sprite_gen import cli++ src, legs, piece = _with_piece(slice(110, 113), slice(0, 3))+ loop = tmp_path / "loop"+ loop.mkdir()+ for i in range(3):+ src.save(loop / f"{i:03d}.png")+ Image.fromarray(np.where(legs, 255, 0).astype(np.uint8), "L").save(tmp_path / "hold.png")+ Image.fromarray(np.where(piece, 255, 0).astype(np.uint8), "L").save(tmp_path / "piece.png")+ out = tmp_path / "out"+ with pytest.raises(SystemExit) as err:+ cli.main(["breathe", str(loop), str(out), "--chest-round", "0.0001", "--arms-x", "0.02", "--breaths", "1",+ "--loop-cells", "24", "--start-cell", "9", "--torso-half", "21", "--hold-mask", str(tmp_path / "hold.png"),+ layer, str(tmp_path / "piece.png")])+ message = str(err.value)+ assert f"{layer} 조각 1/1(9칸)이 불투명 칸 3개를 셀 밖으로 민다 — 왼쪽 변 밖 3 (셀 150x124, 조각 -1칸)" in message, message+ assert not out.exists(), "거부한 굽기가 폴더를 남겼다"+++def test_a_piece_above_the_head_line_pushed_off_the_canvas_is_refused() -> None:+ """머리선 위는 몸이 조각을 따라가는 몫이 꺼진 행이라 장이 조각을 안 옮긴다 — 장의 셀 밖 검사로는 조각이 안 보인다. 조각은+ 제 칸만큼 통째로 가니 그 목적지로 본다."""+ src, legs, piece = _with_piece(slice(20, 23), slice(0, 3))+ with pytest.raises(SystemExit) as err:+ B.bake_breathe_sequence([src] * 24, HELD, hold=legs, props=piece)+ assert "--props-mask 조각 1/1(9칸)이 불투명 칸 3개를 셀 밖으로 민다 — 왼쪽 변 밖 3" in str(err.value), str(err.value)+++def test_the_body_pushed_off_the_canvas_names_the_side() -> None:+ """오른팔 바깥 윤곽이 캔버스 오른쪽 변인 그림 — 팔이 옆으로 밀려 셀 밖으로 나가면 넘어간 변과 칸 수를 밝혀 거부한다 (pixel+ 봉투의 거부와 같은 "오른쪽 변 밖 N" 꼴)."""+ src, _, _ = _figure()+ edge = Image.fromarray(np.asarray(src)[:, :AXIS + 34].copy(), "RGBA")+ with pytest.raises(SystemExit) as err:+ B.bake_breathe_sequence([edge] * 24, HELD)+ message = str(err.value)+ assert re.search(r"가슴·팔이 불투명 픽셀 (\d+)개를 셀 밖으로 민다 — 오른쪽 변 밖 \1 \(셀 109x124", message), message++[email protected]("scene,layer,key", [("shield behind", "--props-behind-mask", "props_behind"),+ ("wet bar", "--props-mask", "props")])+def test_cells_a_piece_fills_are_recorded_and_warned(tmp_path, capsys, scene, layer, key) -> None:+ """떠난 자리로 늘어나 지어낸 칸 — 몸 뒤에서 빠져나오는 방패의 늘어난 테두리, 물에 잠겼던 막대가 떠난 자리의 물 — 은 옮긴+ 칸이 아니다. breathe.json 의 조각마다 칸마다 `filled` 와 그 최대 `filled_max` 로 싣고, 경고 줄로 밝힌다. 수는 출처 꼬리표로+ 따로 센 것과 같다."""+ from sprite_gen import cli++ src, hold, props, behind = _scene(scene)+ piece = behind if behind is not None else props+ loop = tmp_path / "loop"+ loop.mkdir()+ for i in range(24):+ src.save(loop / f"frame-{i:03d}.png")+ Image.fromarray(np.where(hold, 255, 0).astype(np.uint8), "L").save(tmp_path / "hold.png")+ Image.fromarray(np.where(piece, 255, 0).astype(np.uint8), "L").save(tmp_path / "piece.png")+ out = tmp_path / "out"+ assert cli.main(["breathe", str(loop), str(out), "--chest-round", "0.025", "--arms-x", "0.02", "--breaths", "1",+ "--torso-half", "21", "--hold-mask", str(tmp_path / "hold.png"), layer, str(tmp_path / "piece.png")]) == 0+ anat = B.resolve_anatomy(src, HELD)+ pins = B.row_pins(anat, HELD, src, hold, props, behind)+ want = [_counted(src, _traced(src, HELD, phase, anat, pins), pins, B.smooth_wave(phase, INHALE))[0][2]+ for phase in B.fit_breathe_pattern(24, HELD)]+ piece_record = json.loads((out / "breathe.json").read_text(encoding="utf-8"))[key]["pieces"][0]+ assert max(want) > 0, "조각이 떠난 자리로 늘어난 칸이 없다 — 시험이 반례를 못 만든다"+ assert piece_record["filled"] == want and piece_record["filled_max"] == max(want), piece_record+ err = capsys.readouterr().err+ assert (f"breathe: warning: {layer} piece 1 of 1 ({piece_record['cells']} cells) leaves cells it fills by repeating a cell"+ in err and f"up to {max(want)} cells" in err and f"breathe.json {key}.pieces[0].filled" in err), err++[email protected]("scene", ["bar", "wet bar", "reflection", "shield behind", "shield in front", "above the head line",+ "across the head line", "behind off the body"])+def test_every_cell_of_every_piece_is_drawn_or_counted(scene) -> None:+ """출처 꼬리표로 따로 센 장부 — 모든 칸에서 조각마다 제 목적지에 그대로 보이는 칸과 엔진이 센 가려진 칸의 합이 조각의 불투명+ 칸 수이고, 엔진이 센 지어낸 칸이 출처로 센 것과 같다. 머리선 근처의 몸 앞 조각(장이 조각을 다 못 따라가 사본을 남기는 행)도,+ 몸 뒤 조각도 같다."""+ src, hold, props, behind = _scene(scene)+ record = {}+ B.bake_breathe_sequence([src] * 24, HELD, hold=hold, props=props, behind=behind, record=record)+ anat = B.resolve_anatomy(src, HELD)+ pins = record["pins"]+ for i, phase in enumerate(B.fit_breathe_pattern(24, HELD)):+ counted = _counted(src, _traced(src, HELD, phase, anat, pins), pins, B.smooth_wave(phase, INHALE))+ for k, (cells, drawn, made) in enumerate(counted):+ assert drawn + record["hidden"][i][k] == cells, (+ f"{i}번 칸 조각 {k + 1}: 제자리 {drawn} + 가려짐 {record['hidden'][i][k]} != 칸 {cells}")+ assert record["filled"][i][k] == made, f"{i}번 칸 조각 {k + 1}: 엔진의 지어낸 칸 {record['filled'][i][k]} != {made}"+++def _peak_pins(scene_src: Image.Image, hold, props, behind, shifts: list[float]):+ """들숨 꼭대기(위상 inhale, 곡선 1)에서 조각마다 원하는 칸만큼 가도록 핀의 가로 px 만 바꾼 (해부, 핀)."""+ anat = B.resolve_anatomy(scene_src, HELD)+ pins = B.row_pins(anat, HELD, scene_src, hold, props, behind)+ return anat, dataclasses.replace(pins, shifts=np.asarray([0.0] + shifts))+++def _two_bars(second_behind: bool) -> tuple[Image.Image, np.ndarray, np.ndarray, np.ndarray | None]:+ """손에 쥔 막대 오른쪽에 붙은 두 번째 막대. 둘 다 몸 앞이면 색으로 묶은 두 무리(한 칸도 안 떨어져 있다), 두 번째가 몸 뒤면+ 마스크가 둘이다. (그림, 다리, 쥔 물건, 몸 뒤 물건)."""+ src, legs, bar = _figure()+ a = np.asarray(src).copy()+ second = np.zeros_like(bar)+ second[66:105, AXIS + 36:AXIS + 38] = True+ a[second] = HILT+ if second_behind:+ return Image.fromarray(a, "RGBA"), legs, bar, second+ return Image.fromarray(a, "RGBA"), legs, np.where(bar, 0xFFFF00 + 1, 0) + np.where(second, 0x00FFFF + 1, 0), None+++def test_two_pieces_of_one_layer_landing_on_one_cell_are_refused() -> None:+ """한 층의 두 조각이 옮겨진 뒤 한 칸에 놓이면 어느 쪽이 앞인지 마스크가 말하지 않는다 — 나중 조각이 앞 조각을 조용히 덮지+ 않고 거부한다. 손에 쥔 막대가 세 칸 가고 바로 옆의 다른 무리는 제자리다."""+ src, legs, props, _ = _two_bars(second_behind=False)+ anat, pins = _peak_pins(src, legs, props, None, [3.0, 0.0])+ with pytest.raises(SystemExit) as err:+ B._bake_phase_pieces(src, HELD, INHALE, anat, pins)+ assert "--props-mask 의 두 조각(1/2, 2/2)이 옮겨진 뒤 39칸에 함께 놓인다" in str(err.value), str(err.value)++[email protected]("shifts", [[3.0, 0.0], [0.0, -3.0]], ids=["front-moves-over", "behind-moves-under"])+def test_a_piece_in_front_stays_over_a_piece_behind(shifts) -> None:+ """몸 앞 조각은 늘 몸 뒤 조각 위다 — 몸 앞 막대가 몸 뒤 막대 위로 가도, 몸 뒤 막대가 제자리의 몸 앞 막대 밑으로 와도 몸 앞+ 막대의 칸이 모두 보이고, 몸 앞 막대에 가린 몸 뒤 막대의 칸은 그 막대의 가려진 칸으로 센다."""+ src, legs, props, behind = _two_bars(second_behind=True)+ anat, pins = _peak_pins(src, legs, props, behind, shifts)+ baked = B._bake_phase_pieces(src, HELD, INHALE, anat, pins)+ frame, hidden = baked[0], baked[1]+ a, base = np.asarray(frame), np.asarray(src)+ ys, xs = np.nonzero(props)+ step = int(shifts[0])+ assert np.array_equal(a[ys, xs + step], base[ys, xs]), "몸 앞 막대가 몸 뒤 막대에 덮였다"+ assert hidden[0] == 0+ by, bx = np.nonzero(behind)+ under_front = int(np.count_nonzero(props[by, bx + int(shifts[1]) - step]))+ assert under_front == 39 and hidden[1] >= under_front, f"몸 앞 막대에 가린 몸 뒤 막대 칸 {under_front} 이 가려진 칸 {hidden[1]} 에 없다"++[email protected]("cols,cells", [(slice(AXIS - 10, AXIS + 9), 171), (slice(AXIS - 16, AXIS - 6), 90)],+ ids=["across-the-axis", "one-side"])+def test_a_piece_behind_the_body_moving_apart_from_it_is_refused(cols, cells) -> None:+ """몸통 안에 그려진 몸 뒤 조각 — 장은 그 앞의 몸을 몸의 장대로(축에 걸치면 양쪽으로 벌려) 옮기고 조각은 제 칸만큼 통째로+ 가서, 둘 사이 정지 그림의 불투명 칸이 몸도 조각도 없이 빈다. 조용히 구멍을 내지 않고 거부한다."""+ src, legs, piece = _with_piece(slice(58, 67), cols)+ with pytest.raises(SystemExit) as err:+ B.bake_breathe_sequence([src] * 24, HELD, hold=legs, behind=piece)+ assert f"--props-behind-mask 조각 1/1({cells}칸)과 그 앞의 몸이 따로 움직여, 정지 그림에서 불투명하던 칸" in str(err.value), \+ str(err.value)+++# 장부 앞(0787e37)에 구운 장면의 바이트 — 24칸을 이어 붙인 sha256. 출처 지도와 장부는 그리는 것을 바꾸지 않는다.+KEPT_BYTES = {+ "round": "b030ffd37acbd7c7966d121d61bb100541003720f1ea8daeedc1d4b94691fb16",+ "held legs": "39637a681597e51853aafba8fce2e2413db6d758d259c6085c561edbf1953e09",+ "bar": "a22ec4fa6d837a1f7363c68ab8dd3ea8ce3d7ea0d7a02529cf39b5a63054c077",+ "wet bar": "1f1c89d3b59004a15bdf4f0a0f3973f018c5b6eb53e8371119fab2063fce474a",+ "reflection": "1483e22d8484bedf0cd79edb5b248c7343593b1ab0c4c235d6a5e2e2dbab93e9",+ "shield behind": "f3d6e426890ebade2fa32152199610c4e413ed37fd9564d9459df3114ab223b0",+ "shield in front": "f0f755153c74be580314b8fd69efd5b347d81f0f734de54092bc031a87a74d5b",+}++[email protected]("scene", sorted(KEPT_BYTES))+def test_the_ledger_changes_no_byte_of_what_it_counts(scene) -> None:+ """마스크 없는 둥근 가슴, 고정 칸만 준 줄은 장부 길을 타지 않고, 손에 쥔 막대·물 띠 막대·색 무리 반사·몸 뒤와 몸 앞 방패는+ 장부가 세기만 한다 — 모두 장부 앞과 바이트가 같다."""+ src, hold, props, behind = _scene(scene)+ frames, _ = B.bake_breathe_sequence([src] * 24, HELD, hold=hold, props=props, behind=behind)+ assert hashlib.sha256(b"".join(f.tobytes() for f in frames)).hexdigest() == KEPT_BYTES[scene]+++def test_a_row_without_pieces_records_no_piece_ledger(tmp_path) -> None:+ """고정 칸만 준 줄의 breathe.json 에는 쥔 물건 기록이 없다 — 가려진 칸도 지어낸 칸도 실리지 않고, 경고 줄도 없다."""+ from sprite_gen import cli++ src, legs, _ = _figure()+ loop = tmp_path / "loop"+ loop.mkdir()+ for i in range(12):+ src.save(loop / f"frame-{i:03d}.png")+ Image.fromarray(np.where(legs, 255, 0).astype(np.uint8), "L").save(tmp_path / "hold.png")+ out = tmp_path / "out"+ assert cli.main(["breathe", str(loop), str(out), "--chest-round", "0.025", "--arms-x", "0.02", "--breaths", "1",+ "--torso-half", "21", "--hold-mask", str(tmp_path / "hold.png")]) == 0+ report = json.loads((out / "breathe.json").read_text(encoding="utf-8"))+ assert "hold" in report and "props" not in report and "props_behind" not in report+ assert "filled" not in json.dumps(report) and "hidden" not in json.dumps(report)diff --git a/tests/effects/test_breathe_round_curator.py b/tests/effects/test_breathe_round_curator.pynew file mode 100644index 0000000..dcb391f--- /dev/null+++ b/tests/effects/test_breathe_round_curator.py@@ -0,0 +1,98 @@+# SPDX-License-Identifier: Apache-2.0+"""큐레이터가 둥근 가슴 pixel 줄(`chest_round`·`arms_x`)을 조용히 봉투 스쿼시로 그리거나 지우지 않는지.++미러(`breathe.js`)는 봉투 워프만 바이트 같게 따라 그린다. 둥근 가슴 장은 미러가 없으니 smooth 줄처럼:+ 1. 미리보기·영상 내보내기는 봉투 워프로 그리지 않고 소리 내 거부한다+ 2. 사이드카를 읽고 되쓰는 왕복이 chest_round·arms_x 를 지우거나 pixel 기본값(depth 0.06, lag 0.1)을 채워 넣지 않는다 —+ 그러면 첫 autosave 가 둥근 가슴 줄을 조용히 봉투 스쿼시 줄로 바꾼다 (채워 넣은 depth 는 굽기가 거부하기도 한다)+ 3. 굽기가 거부하는 둥근 가슴 사이드카는 고쳐 쓰지 않고 그대로 들고 알린다+"""++import json+import re+import shutil+import subprocess++import pytest++from sprite_gen.curate import curation as C+from sprite_gen.curate.curation import state_breathe+from sprite_gen.effects.breathe import freeze_anatomy+from sprite_gen.serve.serve_curation import CURATOR_DIR++from tests.effects.test_breathe import _key+from tests.effects.test_breathe_js_mirror import CURATOR_BREATHE, HARNESS, _rgba+from tests.effects.test_breathe_round import _figure+from tests.effects.test_breathe_sidecar_roundtrip import _roundtrip+from tests.effects.test_breathe_smooth_curator import _run++node = pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없어 큐레이터 JS 를 실행할 수 없다")+++@node[email protected]("cfg", [{"chest_round": 0.04, "breaths": 2}, {"arms_x": 0.03, "breaths": 1}],+ ids=["chest-round", "arms-x"])+def test_the_mirror_refuses_a_round_row_instead_of_drawing_the_envelope(tmp_path, cfg) -> None:+ src = _figure()[0]+ cfg = {**cfg, "anatomy": freeze_anatomy(src, cfg, _key())}+ payload = {"script": str(CURATOR_BREATHE), "width": src.width, "height": src.height, "cfg": cfg,+ "cases": [{"phase": 0.4, "rgba": _rgba(src)}], "out": str(tmp_path / "js.json")}+ (tmp_path / "payload.json").write_text(json.dumps(payload), encoding="utf-8")+ (tmp_path / "harness.cjs").write_text(HARNESS, encoding="utf-8")+ proc = subprocess.run([shutil.which("node"), str(tmp_path / "harness.cjs"), str(tmp_path / "payload.json")],+ capture_output=True, text=True)+ assert proc.returncode == 0, f"node 하네스 실패:\n{proc.stderr}"+ got = json.loads((tmp_path / "js.json").read_text(encoding="utf-8"))[0]+ assert not got["ok"] and got["refused"], f"둥근 가슴 줄을 미러가 봉투 워프로 그렸다: {got}"+ assert "둥근 가슴" in got["message"]+++@node[email protected]("sidecar", [+ {"chest_round": 0.04, "breaths": 2},+ {"arms_x": 0.03, "breaths": 1, "torso_half": 21},+ {"chest_round": 0.05, "arms_x": 0.02, "breath_peaks": [72, 192], "inhale": 0.6, "chest_y": 0.4,+ "chest_rx": 0.9, "chest_ry": 0.3, "chest_tilt": -10, "chest_bias": 0.2, "chest_x": 0.1, "chest_bias_y": 0.1},+ {"chest_round": 0.04, "breaths": 2, "loop_cells": 96, "start_cell": 31},+ {"mode": "pixel", "chest_round": 0.04, "breaths": 2, "rigid_row": 30},+], ids=["chest-round", "arms-x", "with-shape", "with-stretch", "pixel-written"])+def test_the_round_trip_keeps_a_round_sidecar_as_written(tmp_path, sidecar) -> None:+ got = _roundtrip(_run(sidecar), tmp_path)+ saved = got["payload"]["states"]["idle"].get("breathe")+ assert saved == sidecar, f"왕복이 둥근 가슴 사이드카를 바꿨다\n 전={sidecar}\n 후={saved}"+ assert state_breathe({"states": {"idle": {"breathe": saved}}}, "idle") == \+ state_breathe({"states": {"idle": {"breathe": sidecar}}}, "idle")+ assert not [m for kind, m in got["status"] if kind == "err"]+++@node[email protected]("sidecar", [+ {"chest_round": 0.3, "breaths": 2},+ {"chest_round": "a", "breaths": 2},+ {"chest_round": 0.04, "depth": 0.06},+ {"chest_round": 0.04, "lag": 0.1},+ {"arms_x": 0.03, "shoulder": 0.5},+ {"chest_round": 0.04, "chest_flat": 0.2},+ {"mode": "smooth", "breaths": 2, "chest_round": 0.04},+ {"chest_round": 0.04, "chest_y": 1.5},+], ids=["out-of-range", "not-a-number", "with-depth", "with-lag", "smooth-shape", "flat", "on-smooth", "shape-range"])+def test_a_round_sidecar_the_bake_refuses_is_kept_and_reported(tmp_path, sidecar) -> None:+ with pytest.raises(SystemExit):+ state_breathe({"states": {"idle": {"breathe": sidecar}}}, "idle")+ got = _roundtrip(_run(sidecar), tmp_path)+ saved = got["payload"]["states"]["idle"].get("breathe")+ assert saved == sidecar, f"굽기가 거부하는 사이드카를 왕복이 고쳐 썼다: {saved}"+ assert [m for kind, m in got["status"] if kind == "err"], "거부할 사이드카인데 알림이 없다"+++def test_the_mirrored_round_keys_are_the_same() -> None:+ """큐레이터가 아는 둥근 가슴 키·상한·읽는 모양 값이 굽기와 같아야 한다 — 갈리면 웹뷰가 굽기가 받는 줄을 거부된+ 줄로 들고 있거나, 굽기가 거부하는 줄을 받아 되쓴다."""+ js = (CURATOR_DIR / "src" / "store.js").read_text(encoding="utf-8")+ keys = re.search(r"const BREATHE_ROUND_KEYS = \[(.*?)\];", js)+ top = re.search(r"const BREATHE_ROUND_MAX = ([0-9.]+);", js)+ shape = re.search(r"const BREATHE_ROUND_SHAPE = \[(.*?)\];", js)+ assert keys and top and shape, "둥근 가슴 키가 미러에 없다"+ assert [k.strip().strip('"') for k in keys.group(1).split(",")] == list(C.BREATHE_ROUND_KEYS)+ assert float(top.group(1)) == C.BREATHE_ROUND_MAX+ assert [k.strip().strip('"') for k in shape.group(1).split(",")] == list(C.BREATHE_ROUND_SHAPE)