Skip to content

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

feat: generate centered pixel effects and extract brightness alpha

Soohong Kim4b8278e9cfb1
diff --git a/sprite_gen/gen/pixel_draw.py b/sprite_gen/gen/pixel_draw.py
index cac21de..ba42774 100644
--- a/sprite_gen/gen/pixel_draw.py
+++ b/sprite_gen/gen/pixel_draw.py
@@ -60,13 +60,15 @@ from .pixel_gates import colors_used, evaluate, safe_area
from .pixel_grid import (
FORMATS, Grid, Issue, PaletteRule, check_rows, frame_name_ok, frame_pixels, palette_rule, parse_answer,
parse_row_answers, png_bytes, preview_scale, preview_strip, read_grid_text, recovered, row_issues, row_text,
- save_gif, splice, structural, tiled_3x3, to_text,
+ save_gif, splice, structural, tiled_3x3, to_text, image_of,
)
VERB = "pixel-draw"
SIZE_MIN, SIZE_MAX, SIZE_DEFAULT = 8, 48, 32
FRAMES_MAX = 4
-KINDS = ("sprite", "icon", "tile")
+EFFECT_FRAMES_MAX = 8
+EFFECT_FRAMES = ("birth", "peak", "decay", "gone")
+KINDS = ("sprite", "icon", "tile", "effect")
CANDIDATES_MIN, CANDIDATES_MAX, CANDIDATES_DEFAULT = 1, 6, 2
EFFORT_CHOICES = ("medium", "high", "xhigh")
EFFORT_DEFAULT = "high"
@@ -144,7 +146,7 @@ def _refuse(message: str) -> SystemExit:
return SystemExit(f"{VERB}: {message}")
-def _frames(value: Any) -> tuple[str, ...]:
+def _frames(value: Any, kind: str = "sprite") -> tuple[str, ...]:
names = [n.strip() for n in value.split(",")] if isinstance(value, str) else value
if not isinstance(names, list) or not names or not all(isinstance(n, str) and n for n in names):
raise _refuse("--frames takes comma-separated frame names, e.g. down,up,left,right")
@@ -153,7 +155,9 @@ def _frames(value: Any) -> tuple[str, ...]:
raise _refuse("frame names are letters, digits, '_' or '-' (at most 32): " + ", ".join(map(repr, bad)))
if len(set(names)) != len(names):
raise _refuse("frame names must differ: " + ", ".join(names))
- if len(names) > FRAMES_MAX:
+ if kind == "effect" and not 2 <= len(names) <= EFFECT_FRAMES_MAX:
+ raise _refuse(f"an effect needs 2..{EFFECT_FRAMES_MAX} frames, got {len(names)}")
+ if kind != "effect" and len(names) > FRAMES_MAX:
raise _refuse(f"at most {FRAMES_MAX} frames in one call, got {len(names)}")
return tuple(names)
@@ -186,8 +190,10 @@ def resolve_request(args: argparse.Namespace) -> PixelRequest:
kind = merged.get("kind", "sprite")
if kind not in KINDS:
raise _refuse(f"--kind is one of {', '.join(KINDS)}, got {kind!r}")
- frames = _frames(merged["frames"]) if "frames" in merged else (kind,)
+ frames = _frames(merged["frames"], kind) if "frames" in merged else (EFFECT_FRAMES if kind == "effect" else (kind,))
walk_cycle = bool(merged.get("walk_cycle", False))
+ if walk_cycle and kind == "effect":
+ raise _refuse("--walk-cycle does not apply to an effect")
if walk_cycle and len(frames) != 4:
raise _refuse(f"--walk-cycle is four frames (contact, passing, contact, passing), got {len(frames)}")
try:
@@ -263,7 +269,11 @@ def safe_area_lines(request: PixelRequest) -> list[str]:
def generation_prompt(request: PixelRequest) -> str:
frames = request.frames
lines = [f"Draw: {request.subject}", f"Canvas: exactly {request.size}x{request.size} pixels per frame."]
- if len(frames) > 1:
+ if request.kind == "effect":
+ lines.append(f"Frames: {', '.join(frames)}. One effect's lifetime: appears, grows to a peak, then disappears. "
+ "Keep its origin fixed at the center of every frame. The final frame may be empty. "
+ "Share a palette with several brightness levels for the glow; extent and shape change over time.")
+ elif len(frames) > 1:
lines.append(f"Frames: {', '.join(frames)}. All frames share one palette and show the same subject with "
"the same proportions, colors and size.")
if request.walk_cycle:
@@ -282,6 +292,9 @@ def generation_prompt(request: PixelRequest) -> str:
"No border or outline around the tile.")
lines.append("Style: clean, readable pixel art for a 2D RPG: 2-3 shades per material, light from the "
"top-left, no noisy single-pixel speckle.")
+ elif request.kind == "effect":
+ lines.append("Background: transparent. Draw readable clusters of light; detached sparks are intentional. "
+ "No dark outline, no ground plane, no antialiasing. Use the full canvas around its fixed center.")
else:
lines.append("Background: transparent.")
lines += safe_area_lines(request)
@@ -350,7 +363,7 @@ def repair_prompt(request: PixelRequest, grid: Grid, issues: list[Issue]) -> tup
def _kept(request: PixelRequest) -> str:
"""The safe area in the pick's words, so a margin the prompt asked for is not read as wasted canvas."""
area = safe_area(request.size, request.size)
- if request.kind == "tile" or area["margin"][0] == 0:
+ if request.kind in ("tile", "effect") or area["margin"][0] == 0:
return ""
inner = area["size"][0]
return (f", the body about the size of the central {inner}x{inner}, inside a {area['margin'][0]}-pixel margin a "
@@ -376,7 +389,9 @@ def pick_prompt(request: PixelRequest, labels: list[str]) -> str:
"- craft 1-5: pixel-art craft: clean silhouette and outline, consistent shading and light, no noise, sensible "
"use of the canvas (5 professional, 3 acceptable indie, 1 broken)."
+ (" For tiles, visible seams in the 3x3 repeat count against craft." if request.kind == "tile" else ""),
- ("- consistency 1-5: the same subject, proportions and colours across frames, and correct poses/directions "
+ ("- consistency 1-5: a readable lifetime around a fixed center, with a peak and decay; "
+ "changing extent, detached sparks and an empty final frame are intentional." if request.kind == "effect" else
+ "- consistency 1-5: the same subject, proportions and colours across frames, and correct poses/directions "
"for the frame names." if multi else "- consistency: 0 (single frame)."),
"- verdict: ship (usable in a game as is), touch_up (usable after a few pixel fixes), redraw (not usable).",
"- note: one short sentence naming the main flaw or strength.",
@@ -848,8 +863,19 @@ def write_files(directory: Path, grid: Grid, request_frames: tuple[str, ...], ki
tiled_3x3(frames[request_frames[0]], scale).save(directory / "tiled-3x3.png")
files["tiled"] = "tiled-3x3.png"
if len(frames) > 1:
- save_gif(list(frames.values()), scale, directory / "anim.gif", GIF_FRAME_MS)
+ save_gif(list(frames.values()), scale, directory / "anim.gif", GIF_FRAME_MS, loop=None if kind == "effect" else 0)
files["gif"] = "anim.gif"
+ if kind == "effect":
+ strip = Image.new("RGBA", (grid.width * len(frames), grid.height))
+ for i, pixels in enumerate(frames.values()):
+ strip.paste(image_of(pixels), (i * grid.width, 0))
+ strip.save(directory / "effect.strip.png")
+ meta = {"kind": "effect", "frames": len(frames), "w": grid.width, "h": grid.height,
+ "loop": False, "hold_last": False, "end_frame": len(frames) - 1,
+ "events": [], "blend": "add", "anchor": [grid.width / 2, grid.height / 2],
+ "delay_ms": GIF_FRAME_MS, "frame_names": list(frames)}
+ atomic_write_text(directory / "effect.strip.json", json.dumps(meta, indent=2) + "\n")
+ files.update(strip="effect.strip.png", metadata="effect.strip.json")
return files
@@ -890,9 +916,9 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--size", type=int, help=f"canvas side in pixels, {SIZE_MIN}..{SIZE_MAX} (default {SIZE_DEFAULT}; "
"measured best at 32 or less)")
parser.add_argument("--kind", choices=KINDS, help="sprite (default) and icon have a transparent background; a tile is "
- "opaque and repeats")
+ "opaque and repeats; an effect has a centered lifetime")
parser.add_argument("--frames", help=f"comma-separated frame names drawn in one call, at most {FRAMES_MAX} "
- "(default: one frame named after --kind)")
+ "(effect: 2..8, default birth,peak,decay,gone; others: one named after --kind)")
parser.add_argument("--walk-cycle", action="store_true", default=None,
help="the four frames are one walk cycle (contact, passing, contact, passing): says so in the "
"prompt and checks the legs change sides")
@@ -955,6 +981,10 @@ def _run_grid(args: argparse.Namespace) -> int:
if grid is not None and not (SIZE_MIN <= grid.width <= SIZE_MAX and SIZE_MIN <= grid.height <= SIZE_MAX):
raise _refuse(f"--grid {args.grid}: {grid.width}x{grid.height}; each side is {SIZE_MIN}..{SIZE_MAX} pixels")
frames = tuple(grid.frames) if grid is not None else ()
+ if kind == "effect" and grid is not None:
+ _frames(list(frames), kind)
+ if args.walk_cycle:
+ raise _refuse("--walk-cycle does not apply to an effect")
if args.walk_cycle and len(frames) != 4:
raise _refuse(f"--walk-cycle is four frames, the grid holds {len(frames)}")
out_dir = Path(args.out_dir).expanduser().resolve()
diff --git a/sprite_gen/gen/pixel_gates.py b/sprite_gen/gen/pixel_gates.py
index 07b525f..011262d 100644
--- a/sprite_gen/gen/pixel_gates.py
+++ b/sprite_gen/gen/pixel_gates.py
@@ -91,6 +91,10 @@ def g3_alpha(frames: dict[str, Frame], kind: str) -> dict[str, Any]:
per = {name: _frame_alpha(frame) for name, frame in frames.items()}
if kind == "tile":
ok = all(m["verdict"] == RAW_ALPHA_NONE for m in per.values())
+ elif kind == "effect":
+ ok = (any(m["opaque_pixels"] > 0 for m in per.values())
+ and all(m["corners_transparent"] and (m["opaque_pixels"] == 0 or m["verdict"] == RAW_ALPHA_REAL)
+ for m in per.values()))
else:
ok = all(m["opaque_pixels"] > 0 and m["corners_transparent"] and m["verdict"] == RAW_ALPHA_REAL
for m in per.values())
@@ -252,16 +256,19 @@ def evaluate(frames: dict[str, Frame], *, kind: str, rule: PaletteRule, walk_cyc
warnings: list[str] = []
info: list[str] = []
first = next(iter(frames.values()))
- area = None if kind == "tile" else safe_area(len(first[0]), len(first))
+ area = None if kind in ("tile", "effect") else safe_area(len(first[0]), len(first))
if kind == "tile":
gates["G4"] = g4_seam(frames)
if gates["G4"]["warn"]:
warnings.append(_g4_line(gates["G4"]))
- else:
+ elif kind != "effect":
gates["G5"] = g5_isolated(frames)
if gates["G5"]["warn"]:
warnings.append(f"G5 {gates['G5']['isolated_pixels']} stray pixel(s) with no opaque neighbour")
- if len(frames) > 1:
+ if kind == "effect":
+ gates["G6"] = {"ok": 2 <= len(frames) <= 8 and any(frame != first for frame in frames.values()),
+ "rule": "2..8 frames with a visible change; extent, height and empty frames may differ"}
+ elif len(frames) > 1:
gates["G6"] = g6_frames(frames, walk_cycle=walk_cycle, box=area["box"] if area else None)
walk = gates["G6"].get("walk")
if walk and walk["warn"]:
diff --git a/sprite_gen/gen/pixel_grid.py b/sprite_gen/gen/pixel_grid.py
index a672991..b9dd52e 100644
--- a/sprite_gen/gen/pixel_grid.py
+++ b/sprite_gen/gen/pixel_grid.py
@@ -545,6 +545,6 @@ def tiled_3x3(pixels: Sequence[Sequence[Pixel]], scale: int) -> Image.Image:
return tiled.resize((tiled.width * scale, tiled.height * scale), Image.NEAREST)
-def save_gif(frames: Sequence[Sequence[Sequence[Pixel]]], scale: int, path: Path, duration_ms: int) -> None:
+def save_gif(frames: Sequence[Sequence[Sequence[Pixel]]], scale: int, path: Path, duration_ms: int, *, loop: int | None = 0) -> None:
images = [image_of(f).resize((len(f[0]) * scale, len(f) * scale), Image.NEAREST) for f in frames]
- save_clean_gif(images, path, duration_ms=duration_ms)
+ save_clean_gif(images, path, duration_ms=duration_ms, loop=loop)
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index 73877af..ed86345 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -55,7 +55,7 @@ STATE_DURATION_SECONDS = {"attack": 2}
# States whose clip is pinned to end on the frame it starts from (first-last mode): the model
# has to come back to the still, which closes a one-shot action instead of leaving it wherever
# the strike ended, and closes an idle without asking for a repeating rhythm.
-PIN_LAST_FRAME_STATES = frozenset({"attack", "idle"})
+PIN_LAST_FRAME_STATES = frozenset({"attack", "idle", "effect"})
# Pinned states whose whole clip is the loop: it starts and ends on the canvas, so `video-loop
# --cycle pinned` keeps every frame but the last (a re-render of the first). An attack asked
# for once is ready stance -> strike -> ready stance, so its whole clip is one attack too.
@@ -436,6 +436,9 @@ def clip_prompt_parts(direction: str, state: str, character: str | None, facing:
to the first frame (`handedness.text(clip=True)`), the one piece `prompt_parts.Prompt.add` checks.
"""
validate_facing(facing)
+ if state == "effect":
+ from . import effect
+ return prompt_parts.Prompt(effect.prompt(character, motion), caller=f"{character or ''} {motion or ''}", sep=" ")
view = VIEW_TEXT.get(direction, f"seen from the {direction}").format(facing=facing)
turned = facing if direction in handed_mod.LATERAL_VIEWS else None
if state in nonloop.STATES:
@@ -717,7 +720,7 @@ def run_item(
raise ValueError("incomplete canvas report")
if canvas_report.get("fit", "state") != fit:
raise ValueError("cached canvas was framed with another --fit")
- if direction == "side":
+ if direction == "side" and state != "effect":
prior = canvas_report.get("facing_check") or {}
if not isinstance(prior, dict):
raise ValueError("invalid cached facing")
@@ -733,7 +736,7 @@ def run_item(
still, result["walk_start"] = walk_start_still(base, direction, item_dir, key=key, force=force,
runner=redraw_runner, provider=still_provider, handed=handed,
body_plan=body_plan)
- if direction == "side":
+ if direction == "side" and state != "effect":
if prepare_side is not None:
still, facing_report = prepare_side(base)
else:
@@ -753,7 +756,8 @@ def run_item(
# One run of `sprite-gen video`: a 429 is sent again inside it (`gen.retry`), so a second run here
# would be a second retry loop on top of the first, each of its POSTs a request.
_staggered_start(gap)
- pin = {"last_frame": canvas_png} if pins_last_frame(state, direction) else {}
+ pin_frame = Path(canvas_report["end_frame"]) if state == "effect" else canvas_png
+ pin = {"last_frame": pin_frame} if pins_last_frame(state, direction) else {}
if end_frame is not None:
with Image.open(end_frame) as final, Image.open(canvas_png) as initial:
if final.size != initial.size or canvas_mod.corner_key(final) != canvas_mod.corner_key(initial):
@@ -772,11 +776,13 @@ def run_item(
# a tight frame is clipped on purpose; leftover key background still fails. The default
# call keeps its pre-decontam signature, so a stand-in for run_frames still fits
extra = {} if decontam == "off" else {"decontam": decontam}
+ if state == "effect":
+ extra["alpha_mode"] = "brightness"
fr = frames_mod.run_frames(clip, item_dir / "frames", key=key, allow_edge_contact=False, report_path=item_dir / "frames.report.json", spill=spill, reference=canvas_png, allow_subject_edge_contact=fit == "tight", **extra)
result["frames"] = {k: fr[k] for k in ("fps", "frames", "alpha_zero_pct_min", "alpha_zero_pct_max")}
result["frames"]["spill"] = fr.get("spill", {}).get("mode")
lp = loop_mod.run_loop(Path(fr["keyed_dir"]), item_dir / "loop", fps=float(fr["fps"]), state=state, min_len=None, max_len=None, n_out=None, seam_max=loop_mod.SEAM_RATIO_MAX, name=item, report_path=item_dir / "loop.report.json", anchor=anchor, body_height=body_height,
- cycle_mode="once" if state in nonloop.STATES else "pinned" if state in PINNED_LOOP_STATES else "auto",
+ cycle_mode="lifetime" if state == "effect" else "once" if state in nonloop.STATES else "pinned" if state in PINNED_LOOP_STATES else "auto",
facing=facing if direction in handed_mod.LATERAL_VIEWS else "right")
result["loop"] = {"kind": lp["cycle"].get("kind", "periodic"), "cycle": lp["cycle"]["length"], "period": lp["cycle"]["period_global"], "cycle_ratio": round(lp["cycle"]["ratio"], 3), "seam_ratio": lp["resampled_seam_ratio"], "n_out": lp["n_out"], "drift_px": lp["strip"].get("drift_px", 0), "gif": lp["gif"]["file"], "webp": lp["webp"]["file"], "strip": lp["strip"]["path"]}
result["loop"]["review_recommended"] = lp["cycle"].get("review_recommended", False)
diff --git a/sprite_gen/video/canvas.py b/sprite_gen/video/canvas.py
index 141ef9e..71f6582 100644
--- a/sprite_gen/video/canvas.py
+++ b/sprite_gen/video/canvas.py
@@ -349,13 +349,22 @@ def run_canvas(
raise SystemExit(f"video-canvas: still not found: {still}")
if fit == "tight" and (shape is not None or headroom is not None or lead is not None or trail is not None):
raise SystemExit("video-canvas: --fit tight picks its own shape and adds no room; drop --shape/--headroom/--lead/--trail")
- profile = profile_for(state, shape)
- canvas, report = pad_canvas(Image.open(still), profile, facing=facing, headroom=headroom, lead=lead, trail=trail, key=key, fit=fit)
+ if state == "effect":
+ from . import effect
+ if fit != "state" or any(v is not None for v in (shape, headroom, lead, trail)):
+ raise SystemExit("video-canvas: an effect keeps its source canvas and center; drop framing overrides")
+ with Image.open(still) as image:
+ canvas, report = effect.canvas(image)
+ else:
+ profile = profile_for(state, shape)
+ canvas, report = pad_canvas(Image.open(still), profile, facing=facing, headroom=headroom, lead=lead, trail=trail, key=key, fit=fit)
out = out.expanduser().resolve()
out.parent.mkdir(parents=True, exist_ok=True)
tmp = out.with_name(out.name + ".part")
canvas.save(tmp, format="PNG")
tmp.replace(out)
+ if state == "effect":
+ report["end_frame"] = str(effect.empty_end(out, out.with_name(out.stem + ".end.png")))
payload = {"kind": "sprite-gen-video-canvas-report", "still": str(still), "out": str(out), "state": state, **report}
if report_path is not None:
atomic_write_text(report_path.expanduser().resolve(), json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
diff --git a/sprite_gen/video/clip_prompt.py b/sprite_gen/video/clip_prompt.py
index 15b2724..eb8453d 100644
--- a/sprite_gen/video/clip_prompt.py
+++ b/sprite_gen/video/clip_prompt.py
@@ -53,6 +53,8 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:
if not last_frame:
raise SystemExit("video-prompt: this source cannot pin an end frame")
wants_pin = batch_mod.pins_last_frame(state, direction)
+ if state == "effect" and not last_frame:
+ raise SystemExit("video-prompt: an effect requires an empty black end-frame pin; this source cannot pin it")
warnings: list[str] = []
pinned: bool | None = None
if wants_pin and not last_frame:
@@ -70,13 +72,13 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:
prompt = parts.text
# the caller's own words (--character, --motion) against the engine's: a conflict is a warning
warnings += [note["text"] for note in parts.notes if note["kind"] == "conflict"]
- cycle = "once" if state in nonloop.STATES else "pinned" if pins and state in batch_mod.PINNED_LOOP_STATES else "auto"
+ cycle = "lifetime" if state == "effect" else "once" if state in nonloop.STATES else "pinned" if pins and state in batch_mod.PINNED_LOOP_STATES else "auto"
# as video-set places and cuts: a side or diagonal view takes the facing, front and back face right
canvas_facing = loop_facing = facing if direction in handed_mod.LATERAL_VIEWS else "right"
mid_step = batch_mod.starts_mid_step(state, direction, body_plan)
still = "<dir>/walk-start.png" if mid_step else "<still.png>"
duration = batch_mod.duration_for(state, duration)
- end = f", end frame {end_frame}" if end_frame is not None else ", end frame <dir>/canvas.png" if pins else ""
+ end = f", end frame {end_frame}" if end_frame is not None else (", end frame <dir>/canvas.end.png" if state == "effect" else ", end frame <dir>/canvas.png") if pins else ""
record: dict[str, Any] = {
"kind": "sprite-gen-video-prompt",
"direction": direction,
@@ -87,7 +89,7 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:
"model": model,
"prompt": prompt,
"duration": duration,
- "last_frame": str(end_frame) if end_frame is not None else "canvas" if pins else None,
+ "last_frame": str(end_frame) if end_frame is not None else ("black" if state == "effect" else "canvas") if pins else None,
"cycle": cycle,
"commands": {
"canvas": f"sprite-gen video-canvas --still {still} --state {state} --facing {canvas_facing} --out <dir>/canvas.png --report <dir>/canvas.report.json",
@@ -98,6 +100,9 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:
"warnings": warnings,
**({"notes": parts.notes} if parts.notes else {}),
}
+ if state == "effect":
+ record["commands"]["frames"] = "sprite-gen video-frames --clip <dir>/clip.mp4 --out-dir <dir>/frames --alpha-mode brightness"
+ record["blend"] = "add"
needs = handed_mod.first_frame_needs(handed or [], direction, canvas_facing if direction in handed_mod.LATERAL_VIEWS else None,
gait=state in batch_mod.GAIT_STATES)
if needs:
diff --git a/sprite_gen/video/effect.py b/sprite_gen/video/effect.py
new file mode 100644
index 0000000..080cd6d
--- /dev/null
+++ b/sprite_gen/video/effect.py
@@ -0,0 +1,74 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Emissive effects on black: straight-alpha conversion and generation framing.
+
+RGB on black is already multiplied by its coverage. The maximum channel is the
+smallest alpha that can reconstruct every channel without clipping. No threshold
+is applied: a dim wisp and a detached spark both carry intentional light.
+"""
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+from sprite_gen._deps import np
+
+STATE = "effect"
+ALPHA_MODES = ("chroma", "brightness")
+
+
+def brightness_alpha(image: Image.Image) -> Image.Image:
+ rgb = np.asarray(image.convert("RGB"), dtype=np.float32)
+ alpha = rgb.max(axis=2)
+ color = np.zeros_like(rgb)
+ np.divide(rgb * 255, alpha[:, :, None], out=color, where=alpha[:, :, None] > 0)
+ return Image.fromarray(np.dstack((np.rint(color), alpha)).astype(np.uint8), "RGBA")
+
+
+def key_frames(files: list[Path], directory: Path) -> dict[str, Any]:
+ if not files:
+ raise SystemExit("video-frames: no frames to convert")
+ directory.mkdir(parents=True, exist_ok=True)
+ rows = []
+ for src in files:
+ with Image.open(src) as raw:
+ image = brightness_alpha(raw)
+ image.save(directory / src.name)
+ zero = image.getchannel("A").histogram()[0]
+ rows.append({"frame": src.name, "alpha_zero_pct": round(100 * zero / (image.width * image.height), 2),
+ "route": "brightness", "specks": 0})
+ return {"alpha_mode": "brightness", "blend": "add", "frames": len(rows), "rows": rows,
+ "alpha_zero_pct_min": min(r["alpha_zero_pct"] for r in rows),
+ "alpha_zero_pct_max": max(r["alpha_zero_pct"] for r in rows),
+ "specks": {"dropped": 0, "frames": 0, "policy": "off"},
+ "edge_contacts": [], "edge_policy": "off", "decontam": {"mode": "off", "applied_frames": 0},
+ "warnings": ["Brightness alpha represents emitted light. Dark smoke becomes faint; "
+ "black cannot occlude the scene. Use chroma alpha for opaque smoke."]}
+
+
+def prompt(character: str | None, motion: str | None) -> str:
+ subject = character.strip().rstrip(".") if character else "A luminous game effect"
+ if motion is not None and not motion.strip():
+ raise SystemExit("video: motion description is empty")
+ action = f" {' '.join(motion.split())}" if motion else ""
+ return (f"2D game effect animation. {subject}.{action} One complete lifetime: the effect appears, "
+ "grows to its brightest peak, decays, and disappears completely. Its origin stays at the center "
+ "of the image. A perfectly black background (RGB 0,0,0), no scenery, ground, characters, "
+ "text or shadows. Only the effect emits light; sparks, glow and wisps are part of it. "
+ "Camera locked, no zoom, no pan, no reframing. End on the supplied empty black frame and "
+ "hold complete black with no remaining glow. Perform the effect once.")
+
+
+def canvas(image: Image.Image) -> tuple[Image.Image, dict[str, Any]]:
+ """Keep the effect's frame and centre; composite transparent artwork onto black."""
+ rgba = image.convert("RGBA")
+ black = Image.new("RGBA", rgba.size, (0, 0, 0, 255))
+ result = Image.alpha_composite(black, rgba).convert("RGB")
+ return result, {"fit": "state", "shape": "source", "canvas": list(result.size), "offset": [0, 0],
+ "key": "black", "key_rgb": [0, 0, 0], "why": "fixed effect origin on black"}
+
+
+def empty_end(canvas_path: Path, out: Path) -> Path:
+ with Image.open(canvas_path) as source:
+ blank = Image.new("RGB", source.size, (0, 0, 0))
+ blank.save(out)
+ return out
diff --git a/sprite_gen/video/frames.py b/sprite_gen/video/frames.py
index cbdc745..c3e4e55 100644
--- a/sprite_gen/video/frames.py
+++ b/sprite_gen/video/frames.py
@@ -337,7 +337,15 @@ def key_frames(
spill: str = "small",
allow_subject: bool = False,
decontam: str = "off",
+ alpha_mode: str = "chroma",
) -> dict[str, Any]:
+ from . import effect
+ if alpha_mode not in effect.ALPHA_MODES:
+ raise SystemExit(f"video-frames: unknown --alpha-mode {alpha_mode!r}")
+ if alpha_mode == "brightness":
+ if decontam != "off":
+ raise SystemExit("video-frames: brightness alpha does not use --decontam")
+ return effect.key_frames(raw_files, keyed_dir)
if spill not in ("small", "full"):
raise SystemExit(f"video-frames: key_frames takes a resolved spill mode (small|full), got {spill!r}")
if decontam not in DECONTAM_MODES:
@@ -460,7 +468,12 @@ def _edge_contact_message(contacts: list[dict[str, Any]]) -> str:
return message
-def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool, report_path: Path | None, spill: str = "small", reference: Path | None = None, allow_subject_edge_contact: bool = False, decontam: str = "off", source_manifest: Path | None = None) -> dict[str, Any]:
+def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool, report_path: Path | None, spill: str = "small", reference: Path | None = None, allow_subject_edge_contact: bool = False, decontam: str = "off", source_manifest: Path | None = None, alpha_mode: str = "chroma") -> dict[str, Any]:
+ from . import effect
+ if alpha_mode not in effect.ALPHA_MODES:
+ raise SystemExit(f"video-frames: unknown --alpha-mode {alpha_mode!r}")
+ if alpha_mode == "brightness" and decontam != "off":
+ raise SystemExit("video-frames: brightness alpha does not use --decontam")
if source_manifest is not None and reference is None:
raise SystemExit("video-frames: --source-manifest needs --reference (the source canvas)")
if source_manifest is not None:
@@ -472,7 +485,7 @@ def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool,
raise SystemExit("video-frames: source manifest cannot overwrite source files or report")
if spill not in SPILL_MODES:
raise SystemExit(f"video-frames: unknown --spill {spill!r}; expected one of {', '.join(SPILL_MODES)}")
- if spill == "auto" and reference is None:
+ if alpha_mode == "chroma" and spill == "auto" and reference is None:
raise SystemExit("video-frames: --spill auto needs --reference (the still the clip was made from)")
if decontam not in DECONTAM_MODES:
raise SystemExit(f"video-frames: unknown --decontam {decontam!r}; expected one of {', '.join(DECONTAM_MODES)}")
@@ -483,9 +496,10 @@ def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool,
meta = probe(clip)
raw_dir = out_dir / "raw"
keyed_dir = out_dir / "keyed"
- decision = decide_spill(Path(reference).expanduser().resolve(), key) if spill == "auto" else {"mode": spill, "reason": "explicit"}
+ decision = ({"mode": "off", "reason": "brightness alpha"} if alpha_mode == "brightness" else
+ decide_spill(Path(reference).expanduser().resolve(), key) if spill == "auto" else {"mode": spill, "reason": "explicit"})
files = extract(clip, raw_dir, meta["stream_index"])
- report = key_frames(files, keyed_dir, key=key, check_edges=not allow_edge_contact, spill=decision["mode"], allow_subject=allow_subject_edge_contact, decontam=decontam)
+ report = key_frames(files, keyed_dir, key=key, check_edges=not allow_edge_contact, spill=decision["mode"], allow_subject=allow_subject_edge_contact, decontam=decontam, alpha_mode=alpha_mode)
payload = {"kind": "sprite-gen-video-frames-report", "clip": str(clip), "out_dir": str(out_dir), "raw_dir": str(raw_dir), "keyed_dir": str(keyed_dir), "key": key, "spill": decision, **meta, **report}
target = (report_path or (out_dir / "frames.report.json")).expanduser().resolve()
if source_manifest is not None:
@@ -504,6 +518,7 @@ def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool,
def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--alpha-mode", choices=("chroma", "brightness"), default="chroma", help="chroma key (default), or emitted light on black: brightness alpha, unpremultiplied RGB, no speck/edge cleanup; dark smoke becomes faint")
parser.add_argument("--clip", required=True, type=Path, help="mp4 from `sprite-gen video`, or one made elsewhere from a `video-canvas` still (a video MCP such as ZCRE); an audio track and a cover image are left out")
parser.add_argument("--out-dir", required=True, type=Path, help="writes raw/ and keyed/ here")
parser.add_argument("--key", choices=("auto", "green", "magenta", "white"), default="auto", help="background key (auto reads the corners)")
@@ -521,7 +536,8 @@ def run(**kwargs: object) -> int:
allow_edge_contact=bool(kwargs.get("allow_edge_contact")), report_path=kwargs.get("report"), # type: ignore[arg-type]
spill=str(kwargs.get("spill") or "small"), reference=kwargs.get("reference"), # type: ignore[arg-type]
allow_subject_edge_contact=bool(kwargs.get("allow_subject_edge_contact")),
- decontam=str(kwargs.get("decontam") or "off"), source_manifest=kwargs.get("source_manifest")) # type: ignore[arg-type]
+ decontam=str(kwargs.get("decontam") or "off"), source_manifest=kwargs.get("source_manifest"),
+ alpha_mode=str(kwargs.get("alpha_mode") or "chroma")) # type: ignore[arg-type]
summary = {k: payload[k] for k in ("clip", "keyed_dir", "width", "height", "fps", "frames", "codec", "pix_fmt", "audio_streams", "alpha_zero_pct_min", "alpha_zero_pct_max", "edge_contacts", "edge_policy", "spill", "report")}
print(json.dumps(summary, ensure_ascii=False, indent=2))
return 0