Files
breeze/scripts/render-sun-salutation-characters.py
T

176 lines
7.3 KiB
Python

#!/usr/bin/env python3
"""Export the four approved characters to transparent app frames, offscreen.
Reuses the review pipeline's painted parts and attachment points, with the
app's three-second transitions. No image-generation service is called.
"""
from __future__ import annotations
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import numpy as np
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
PROPOSALS = ROOT / "character-proposals/2026-09-30-banner-style"
DIRECTORY = "assets/practices/sunsalutation/characters"
TABLE = ROOT / "src/practices/sun_salutation/sun_salutation_frames.zi"
MANIFEST = ROOT / "docs/sun-salutation-characters.json"
def load_pipeline():
spec = importlib.util.spec_from_file_location(
"inbe_approved_characters", PROPOSALS / "build_proposals.py"
)
pipeline = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pipeline)
return pipeline
def bounds(alpha):
ys, xs = np.nonzero(alpha > 0)
if not len(xs):
raise RuntimeError("The character frame is empty")
return [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]
def export_character(pipeline, concept):
module, rig = pipeline.configure_renderer(concept)
sprites = rig["sprites"]
# Hair is part of each bound/short hairstyle, so no settling frames are
# needed after the move. Keep the established app timing and frame rate.
sprites["settle"] = 0
rig["themes"]["clear"]["far"] = [50, 65, 49, .13]
camera = rig["camera"]
width = round(camera["designWidth"] * sprites["scale"] / 2) * 2
height = round(camera["designHeight"] * sprites["scale"] / 2) * 2
# Supersample the articulated meshes before reducing to the app's size.
# This smooths moving contours without increasing the texture dimensions.
sample_scale = 2
character = module.Girl(
rig, "clear", width * sample_scale, height * sample_scale, sprites["fps"]
)
surface = module.cairo.ImageSurface(module.cairo.FORMAT_ARGB32, width, height)
context = module.cairo.Context(surface)
context.scale(1 / sample_scale, 1 / sample_scale)
context.set_operator(module.cairo.OPERATOR_SOURCE)
directory = ROOT / DIRECTORY / concept["id"]
directory.mkdir(parents=True, exist_ok=True)
expected = set()
steps = []
for step, times in enumerate(module.sprite_times(rig, character.timeline)):
# Hold only one transition in memory, rather than all four loops.
frames = []
coverage = np.zeros((height, width), dtype=bool)
for second in times:
character.frame(second)
context.set_source_surface(character.surface)
context.get_source().set_filter(module.cairo.FILTER_BEST)
context.paint()
surface.flush()
stride = surface.get_stride()
pixels = np.frombuffer(surface.get_data(), np.uint8)
pixels = pixels.reshape(height, stride // 4, 4)[:, :width].copy()
coverage |= pixels[..., 3] > 0
frames.append(pixels)
box = bounds(coverage)
left, top, right, bottom = box
held = bounds(frames[-1][top:bottom, left:right, 3])
for index, pixels in enumerate(frames):
premultiplied = pixels[top:bottom, left:right].astype(np.float32)
alpha = premultiplied[..., 3:4]
color = np.where(
alpha > 0, premultiplied[..., :3] * 255 / np.maximum(alpha, 1), 0
)
rgba = np.concatenate([color[..., ::-1], alpha], -1)
rgba = rgba.clip(0, 255).round().astype(np.uint8)
picture = Image.fromarray(rgba).quantize(
sprites["colors"], method=Image.Quantize.FASTOCTREE
)
filename = f"{step + 1:02d}-{index + 1:03d}.png"
picture.save(directory / filename, optimize=True)
expected.add(filename)
steps.append({"frames": len(frames), "box": box, "held": held})
print(f"{concept['id']}: pose {step + 1}/12", flush=True)
for stale in directory.glob("*.png"):
if stale.name not in expected:
stale.unlink()
return {
"id": concept["id"], "name": concept["name"],
"directory": f"{DIRECTORY}/{concept['id']}/", "steps": steps,
"fps": sprites["fps"],
"transition_frames": round(rig["timing"]["transition"] * sprites["fps"]),
}
def write_tables(characters):
steps = [step for character in characters for step in character["steps"]]
boxes = [step["box"] for step in steps]
left = min(box[0] for box in boxes)
top = min(box[1] for box in boxes)
width = max(box[2] for box in boxes) - left
height = max(box[3] for box in boxes) - top
manifest = {
"generator": "scripts/render-sun-salutation-characters.py",
"stage": {"left": left, "top": top, "width": width, "height": height},
"characters": characters,
}
MANIFEST.write_text(json.dumps(manifest, indent=2) + "\n")
def row(values):
return ".[" + ", ".join(str(value) for value in values) + "];"
first = characters[0]
counts = [step["frames"] for step in first["steps"]]
if any([step["frames"] for step in c["steps"]] != counts for c in characters):
raise RuntimeError("All characters must share the same frame timing")
lines = [
"// Generated by scripts/render-sun-salutation-characters.py; do not edit.",
"// Each character has twelve poses. Geometry is indexed character * 12 + step.",
"// Frame F of pose S is its directory + SS-FFF.png, counted from 1.",
"// Every character shares one stage; thumbnails crop to the held pose.",
"",
f"SUN_SALUTATION_STAGE_W :: {width}",
f"SUN_SALUTATION_STAGE_H :: {height}",
f"SUN_SALUTATION_FRAME_FPS :: {first['fps']}",
f"SUN_SALUTATION_TRANSITION_FRAMES :: {first['transition_frames']}",
"",
f"sun_salutation_frame_directories: [{len(characters)}]string = .[",
*[f' "{character["directory"]}",' for character in characters],
"];",
f"sun_salutation_step_frames: [12]s32 = " + row(counts),
]
values = {
"step_x": [b[0] - left for b in boxes],
"step_y": [b[1] - top for b in boxes],
"step_w": [b[2] - b[0] for b in boxes],
"step_h": [b[3] - b[1] for b in boxes],
"held_x": [s["held"][0] for s in steps],
"held_y": [s["held"][1] for s in steps],
"held_w": [s["held"][2] - s["held"][0] for s in steps],
"held_h": [s["held"][3] - s["held"][1] for s in steps],
}
for name, entries in values.items():
lines.append(f"sun_salutation_{name}: [{len(steps)}]s32 = " + row(entries))
TABLE.write_text("\n".join(lines) + "\n")
total = sum(sum(step["frames"] for step in c["steps"]) for c in characters)
print(f"Exported {len(characters)} characters, {total} frames, {width}x{height} stage", flush=True)
def main():
pipeline = load_pipeline()
characters = [export_character(pipeline, concept) for concept in pipeline.CONCEPTS]
write_tables(characters)
subprocess.run([sys.executable, str(ROOT / "scripts/optimize-animation-pngs.py")],
check=True)
subprocess.run([sys.executable, str(ROOT / "scripts/animation_inventory.py")],
check=True)
if __name__ == "__main__":
main()