Skip to content

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

fix(breathe): pixel's refusal of a frame pushed off the cell says which sides and how many went past each, and when the side is the drawing's own border, that a drawing cut by its frame bakes with smooth and must not be padded, baked and cropped

Soohong Kim96d0bcb90e3d
diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.py
index fa2bdca..1830d97 100644
--- a/sprite_gen/effects/breathe.py
+++ b/sprite_gen/effects/breathe.py
@@ -77,7 +77,7 @@ from sprite_gen._deps import np
from sprite_gen.effects.anatomy import Anatomy, analyze
from sprite_gen.curate.curation import (BREATHE_MODES, BREATHE_SMOOTH_DEPTH, BREATHE_SMOOTH_DEPTH_X,
BREATHE_SMOOTH_SHAPE, normalize_transform, state_breathe)
-from sprite_gen.frames.extract import solid_alpha_bbox
+from sprite_gen.frames.extract import BORDER_MIN_FRACTION, FRAME_SIDES, own_border, solid_alpha_bbox
from sprite_gen.spec.runio import inside_folder, new_stage, same_folder
# 강체 경계에서 변형 강도가 0 이 되기까지의 테이퍼 반폭 (콘텐츠 높이 비율).
@@ -348,6 +348,7 @@ def _warp(frame: Image.Image, anat: Anatomy, depth: float, lag: float, t: float,
y_cursor = baseline - total
prev = 0
clipped = 0
+ off = dict.fromkeys(FRAME_SIDES, 0) # 변마다 밖으로 나간 불투명 (모서리 밖은 두 변 모두에 센다)
deformed = False # 이 위상에서 변형이 실제로 일어났나 (다듬기 게이트)
for j in range(height):
u = 1.0 - j / max(1, height - 1)
@@ -389,6 +390,8 @@ def _warp(frame: Image.Image, anat: Anatomy, depth: float, lag: float, t: float,
src_x[ends[0]] = row_op[0]
pixels = body[j, src_x]
shown = pixels[:, 3] != 0
+ left = int(np.count_nonzero(shown & (out_x < 0)))
+ right = int(np.count_nonzero(shown & (out_x >= canvas_w)))
inside = shown & (out_x >= 0) & (out_x < canvas_w)
n_shown, n_inside = int(np.count_nonzero(shown)), int(np.count_nonzero(inside))
for r in range(reps):
@@ -398,19 +401,44 @@ def _warp(frame: Image.Image, anat: Anatomy, depth: float, lag: float, t: float,
clipped += n_shown - n_inside
else:
clipped += n_shown
+ off["top"] += n_shown if yy < 0 else 0
+ off["left"] += left
+ off["right"] += right
y_cursor += reps
if clipped:
# 조용히 자르지 않는다 — 정수리나 옆구리가 셀 밖으로 나가면 스프라이트가
# 망가지고, 그건 여백이나 진폭을 사람이 정해야 하는 문제다 (No Silent Fallback).
raise SystemExit(
- f"breathe: 늘어난 프레임이 셀 밖으로 나가 불투명 픽셀 {clipped}개가 잘린다 "
- f"(셀 {canvas_w}x{canvas_h}, 콘텐츠 {box[0]},{box[1]}-{box[2]},{box[3]}). "
- f"셀 여백을 늘리거나 depth 를 낮춰라.")
+ f"breathe: 늘어난 프레임이 셀 밖으로 나가 불투명 픽셀 {clipped}개가 잘린다 — {_sides_off(off)} "
+ f"(셀 {canvas_w}x{canvas_h}, 콘텐츠 {box[0]},{box[1]}-{box[2]},{box[3]}). {_clip_advice(frame, off)}")
if deformed:
_thin_outline_1px(out)
return Image.fromarray(out, "RGBA")
+SIDE_NAMES = {"top": "위", "left": "왼쪽", "right": "오른쪽"}
+
+
+def _sides_off(off: dict[str, int]) -> str:
+ return ", ".join(f"{SIDE_NAMES[s]} 변 밖 {off[s]}" for s in FRAME_SIDES if off[s])
+
+
+def _clip_advice(frame: Image.Image, off: dict[str, int]) -> str:
+ """pixel 이 셀 밖으로 민 칸의 거절 문구 끝 — 무엇을 하라는지. 밀려 나간 변이 그 칸 그림 자체의 테두리면
+ (`own_border`, video-frames 와 같은 판정) 그림이 원래 화면에 잘린 것일 수 있다 — 큰 일러·영상 칸은 smooth 가
+ 머리와 화면 변을 제자리에 둔다. 여백 0 으로 자른 도트 스프라이트도 같은 판정에 걸려 둘을 가를 수 없으니 두
+ 길을 다 말한다. 여백을 붙여 굽고 잘라 내는 우회는 밀려 나간 만큼을 조용히 잃는다."""
+ sides, outer = own_border(np.asarray(frame.convert("RGBA"))[..., 3] != 0)
+ crossed = [s for s in FRAME_SIDES if off[s] and s in sides]
+ if not crossed:
+ return "셀 여백을 늘리거나 depth 를 낮춰라."
+ covers = ", ".join(f"{SIDE_NAMES[s]} 변 바깥 줄 {outer[s]} px" for s in crossed)
+ return (f"그림이 {covers} 를 덮는다 — 그 변 길이의 {BORDER_MIN_FRACTION * 100:g} % 이상이라 그림 자체의 테두리로 "
+ f"읽힌다. 원래 화면에 잘린 그림(큰 일러·영상 칸)이면 mode smooth(`--mode smooth`)로 구워라 — 머리와 "
+ f"화면 변이 제자리에 있다. 여백을 붙여 굽고 잘라 내지 마라 — 밀려 나간 만큼 조용히 잃는다. 도트 "
+ f"스프라이트면 셀 여백을 늘리거나 depth 를 낮춰라.")
+
+
# ── smooth 모드 (큰 일러·영상 프레임) ───────────────────────────────
def breathe_mode(cfg: dict) -> str:
diff --git a/sprite_gen/frames/extract.py b/sprite_gen/frames/extract.py
index eeea209..6825fac 100644
--- a/sprite_gen/frames/extract.py
+++ b/sprite_gen/frames/extract.py
@@ -53,6 +53,24 @@ def edge_alpha_count(image: Image.Image, margin: int) -> int:
return total
+# The sides a subject can leave its frame by — the bottom is the floor it stands on, contact there is expected.
+FRAME_SIDES = ("top", "left", "right")
+# The drawing's own border (`own_border`): a side the subject covers on its outermost row or column for this share of
+# its length. A drawing cut there (a sleeve, hair off the top) covers far more; a strand's tip grazing the edge covers less.
+BORDER_MIN_FRACTION = 0.02
+
+
+def own_border(subject: np.ndarray) -> tuple[list[str], dict[str, int]]:
+ """The drawing's own border — (sides, outer_px): the `FRAME_SIDES` whose outermost row or column `subject`, an
+ (h, w) bool mask of the subject's pixels, covers for at least BORDER_MIN_FRACTION of the side's length, and the
+ pixels it covers on each. `video-frames` accepts subject contact there in every frame of a clip; Breathe's pixel mode
+ names it when it refuses a frame pushed off the cell. The rule: docs/video-pipeline.md section 3."""
+ h, w = subject.shape
+ outer = {"top": int(subject[0].sum()), "left": int(subject[:, 0].sum()), "right": int(subject[:, -1].sum())}
+ length = {"top": w, "left": h, "right": h}
+ return [s for s in FRAME_SIDES if outer[s] and outer[s] >= BORDER_MIN_FRACTION * length[s]], outer
+
+
_KEY_CHANNEL_LIT = 192 # a channel the key saturates
_KEY_CHANNEL_DARK = 64 # a channel the key leaves dark — the one bar `is_key_family` / `is_border_key_candidate` reuse
diff --git a/sprite_gen/serve/curator/src/breathe.js b/sprite_gen/serve/curator/src/breathe.js
index 07e9113..69ffb0b 100644
--- a/sprite_gen/serve/curator/src/breathe.js
+++ b/sprite_gen/serve/curator/src/breathe.js
@@ -23,6 +23,10 @@ const BREATHE_MAX_ROW_STRAIN = 0.25;
const BREATHE_DEPTH_MAX = 0.20;
const BREATHE_BREATHS_MAX = 8;
const BREATHE_LAG_MAX = 0.45;
+// 그림 자체의 테두리 — 파이썬 frames.extract.FRAME_SIDES·BORDER_MIN_FRACTION 미러 (거절 문구가 쓴다).
+const BREATHE_SIDES = ["top", "left", "right"];
+const BREATHE_SIDE_NAMES = { top: "위", left: "왼쪽", right: "오른쪽" };
+const BREATHE_BORDER_MIN_FRACTION = 0.02;
// 굽기가 거부하는 프레임은 미리보기도 만들어 주지 않는다.
// 파이썬은 셀 밖으로 나간 불투명 픽셀을 세어 SystemExit 으로 멈추고 행당 변형 상한도
@@ -170,6 +174,35 @@ function breatheSolidBox(data, w, h) {
return x1 > x0 && y1 > y0 ? [x0, y0, x1, y1] : null;
}
+// 파이썬 `own_border` 미러 — 바깥 줄을 그 변 길이의 BREATHE_BORDER_MIN_FRACTION 이상 덮는 변.
+function breatheOwnBorder(data, w, h) {
+ const outer = { top: 0, left: 0, right: 0 };
+ for (let x = 0; x < w; x++) if (data[x * 4 + 3]) outer.top += 1;
+ for (let y = 0; y < h; y++) {
+ if (data[y * w * 4 + 3]) outer.left += 1;
+ if (data[(y * w + w - 1) * 4 + 3]) outer.right += 1;
+ }
+ const length = { top: w, left: h, right: h };
+ return { outer, sides: BREATHE_SIDES.filter((s) => outer[s] && outer[s] >= BREATHE_BORDER_MIN_FRACTION * length[s]) };
+}
+
+// 파이썬 `_sides_off`·`_clip_advice` 미러 — 셀 밖으로 민 칸의 거절 문구. 나간 변이 그 칸 그림 자체의
+// 테두리면 원래 화면에 잘린 그림일 수 있어 smooth 를 말한다 (여백 0 도트 스프라이트와 가를 수 없어 둘 다).
+function breatheClipWording(off, data, w, h) {
+ const where = BREATHE_SIDES.filter((s) => off[s]).map((s) => `${BREATHE_SIDE_NAMES[s]} 변 밖 ${off[s]}`).join(", ");
+ const border = breatheOwnBorder(data, w, h);
+ const crossed = BREATHE_SIDES.filter((s) => off[s] && border.sides.includes(s));
+ if (!crossed.length) return { where, advice: "셀 여백을 늘리거나 depth 를 낮춰라." };
+ const covers = crossed.map((s) => `${BREATHE_SIDE_NAMES[s]} 변 바깥 줄 ${border.outer[s]} px`).join(", ");
+ return {
+ where,
+ advice: `그림이 ${covers} 를 덮는다 — 그 변 길이의 ${BREATHE_BORDER_MIN_FRACTION * 100} % 이상이라 그림 자체의 테두리로 `
+ + "읽힌다. 원래 화면에 잘린 그림(큰 일러·영상 칸)이면 mode smooth(`--mode smooth`)로 구워라 — 머리와 "
+ + "화면 변이 제자리에 있다. 여백을 붙여 굽고 잘라 내지 마라 — 밀려 나간 만큼 조용히 잃는다. 도트 "
+ + "스프라이트면 셀 여백을 늘리거나 depth 를 낮춰라.",
+ };
+}
+
// 줄 단위 신선도 검사 — **기준 프레임 하나**에만 건다.
//
// 굽기는 줄의 첫 프레임으로 해부를 확정하고(`bake_breathe_sequence` 의 `images[0]`) 그
@@ -324,6 +357,7 @@ function breatheComposite(base, cfg, phase) {
let yCursor = baseline - total;
let prev = 0;
let clipped = 0;
+ const off = { top: 0, left: 0, right: 0 }; // 변마다 밖으로 나간 불투명 (모서리 밖은 두 변 모두)
let deformed = false; // 이 위상에서 변형이 실제로 일어났나 (다듬기 게이트, 파이썬 미러)
for (let j = 0; j < height; j++) {
const u = 1 - j / Math.max(1, height - 1);
@@ -370,7 +404,13 @@ function breatheComposite(base, cfg, phase) {
for (const [ox, si] of rowMap) {
const s4 = ((by0 + j) * w + (bx0 + si)) * 4;
if (!src[s4 + 3]) continue;
- if (yy < 0 || yy >= h || ox < 0 || ox >= w) { clipped += 1; continue; }
+ if (yy < 0 || yy >= h || ox < 0 || ox >= w) {
+ clipped += 1;
+ if (yy < 0) off.top += 1;
+ if (ox < 0) off.left += 1;
+ if (ox >= w) off.right += 1;
+ continue;
+ }
const d4 = (yy * w + ox) * 4;
od[d4] = src[s4];
od[d4 + 1] = src[s4 + 1];
@@ -381,9 +421,9 @@ function breatheComposite(base, cfg, phase) {
yCursor += reps;
}
if (clipped) {
+ const { where, advice } = breatheClipWording(off, src, w, h);
throw new BreatheRefused(
- `늘어난 프레임이 셀 밖으로 나가 불투명 픽셀 ${clipped}개가 잘린다 `
- + `(셀 ${w}x${h}). 셀 여백을 늘리거나 depth 를 낮춰라.`);
+ `늘어난 프레임이 셀 밖으로 나가 불투명 픽셀 ${clipped}개가 잘린다 — ${where} (셀 ${w}x${h}). ${advice}`);
}
if (deformed) breatheThinOutline(od, w, h);
ctx.putImageData(outImg, 0, 0);
diff --git a/sprite_gen/video/frames.py b/sprite_gen/video/frames.py
index 4614b17..8fab9a9 100644
--- a/sprite_gen/video/frames.py
+++ b/sprite_gen/video/frames.py
@@ -71,6 +71,7 @@ from sprite_gen.frames.cutout import cutout
from sprite_gen.frames.decontam import palette_from_stats
from sprite_gen.frames.extract import _border_key_candidate_field, _key_channel_split, _painted_key_leans
from sprite_gen.frames.extract import _SPILL_FULL_MIN_TINT, DEFAULT_UNMIX_REACH
+from sprite_gen.frames.extract import BORDER_MIN_FRACTION, FRAME_SIDES, own_border
from sprite_gen.spec.runio import atomic_write_text
from sprite_gen.util.console import utf8_streams
@@ -94,11 +95,7 @@ SPILL_REFERENCE_MAX = 0.005 # the still's own key material ≤ the engine's sma
SPILL_REFERENCE_MARGIN = 1
SPILL_REFERENCE_MAX_PIXELS = 6_000_000
EDGE_MAX_PIXELS = 0 # any opaque pixel on the top/left/right edge band = contact
-SIDES = ("top", "left", "right")
-# The drawing's own border (`edge_border`): a side the first frame's subject covers on its outermost row or
-# column for this share of its length. A drawing cut there (a sleeve, hair off the top) covers far more; a
-# strand's tip grazing the edge covers less.
-BORDER_MIN_FRACTION = 0.02
+SIDES = FRAME_SIDES # the top/left/right edge bands; the floor edge is expected contact
# The body's rim the matte cut loose: on a border side, a key-only piece is accepted when it lies wholly within
# RIM_REACH px of the frame's body (each way and diagonally) and holds fewer than SPECK_MIN_PX pixels — a few
# pixels of a thin outline the key was blended into, left at the edge between strands. Anything larger or farther
@@ -331,17 +328,14 @@ def classify_edge_contact(raw: Image.Image, keyed: Image.Image, chroma_key: tupl
return {"subject": int(pixels["contact"].sum()) - residual, "residual": residual, "rim": int(pixels["rim"].sum())}
-def _border(pixels: dict[str, np.ndarray] | None, size: tuple[int, int], frame: str) -> dict[str, Any]:
- """The drawing's own border, read on the first frame's edge pixels (`_edge_pixels`; None: it touches no edge),
- `size` (w, h): `edge_border` in the report."""
- w, h = size
- outer = {side: 0 for side in SIDES}
+def _border(pixels: dict[str, np.ndarray] | None, frame: str) -> dict[str, Any]:
+ """The drawing's own border (`extract.own_border`), read on the first frame's edge pixels that are the subject
+ (`_edge_pixels`; None: it touches no edge): `edge_border` in the report."""
+ sides, outer = [], {side: 0 for side in SIDES}
if pixels is not None:
- subject = pixels["contact"] & ~pixels["residual"]
- outer = {"top": int(subject[0].sum()), "left": int(subject[:, 0].sum()), "right": int(subject[:, -1].sum())}
- length = {"top": w, "left": h, "right": h}
- return {"frame": frame, "sides": [s for s in SIDES if outer[s] and outer[s] >= BORDER_MIN_FRACTION * length[s]],
- "outer_px": outer, "min_fraction": BORDER_MIN_FRACTION, "rim_reach": RIM_REACH, "rim_under_px": SPECK_MIN_PX}
+ sides, outer = own_border(pixels["contact"] & ~pixels["residual"])
+ return {"frame": frame, "sides": sides, "outer_px": outer, "min_fraction": BORDER_MIN_FRACTION,
+ "rim_reach": RIM_REACH, "rim_under_px": SPECK_MIN_PX}
def _taken(pixels: dict[str, np.ndarray], sides: list[str]) -> np.ndarray:
@@ -558,7 +552,7 @@ def _key_chroma(raw_files: list[Path], keyed_dir: Path, *, key: str, check_edges
contact.update(subject=int(pixels["contact"].sum()) - residual, residual=residual, rim=int(pixels["rim"].sum()))
contact["key_painted"] = stats.get("chroma_key_painted")
if policy == "border" and k == 0:
- border = _border(pixels, (w, h), src.name)
+ border = _border(pixels, src.name)
if border["sides"]:
print(f"video-frames: the first frame's subject runs off the {_sides(border['sides'])} — read as the "
"drawing's own border, where contact is accepted in every frame (`edge_border` in the report)",