Files
Oshima-Game/tools/build_xinyin_template_package.py
2026-09-19 17:24:02 +08:00

257 lines
12 KiB
Python

from __future__ import annotations
import json
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
ROOT = Path(__file__).resolve().parent.parent
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
DIRECTION_MAP_PATH = CHARACTER / "direction-map-v1.json"
PACKAGE_PATH = CHARACTER / "template-package-v1.json"
PREVIEW_PATH = CHARACTER / "previews/xinyin-template-role-handoff-v1.png"
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
DIRECTION_ORDER = ("up", "down", "left", "right")
EXPECTED_KEYFRAMES = (
("idle-inhale", 420),
("idle-neutral", 260),
("idle-exhale", 420),
("throw-ready", 150),
("throw-windup", 110),
("throw-release", 90),
("throw-recover", 180),
)
DISPLAY_PROFILES = (
{"label": "100%", "characterHeight": 176, "cell": {"width": 128, "height": 64}},
{"label": "75%", "characterHeight": 132, "cell": {"width": 96, "height": 48}},
{"label": "50%", "characterHeight": 88, "cell": {"width": 64, "height": 32}},
)
def load_json(path: Path) -> dict:
return json.loads(path.read_text(encoding="utf-8-sig"))
def resolve(path_text: str) -> Path:
path = ROOT / path_text
if not path.is_file():
raise FileNotFoundError(path)
return path
def relative(path: Path) -> str:
return path.relative_to(ROOT).as_posix()
def sequence_record(report: dict, name: str) -> dict:
output = report["outputs"][name]
return {
"frames": output["frames"],
"durationsMs": output["durationsMs"],
"cycleMs": output["cycleMs"],
"preview": output["file"],
"loop": name == "idle",
}
def direction_record(runtime_direction: str, source: dict, referenced: set[Path]) -> tuple[dict, Image.Image]:
assembly_path = resolve(source["assembly"])
motion_manifest_path = resolve(source["motionManifest"])
playback_report_path = motion_manifest_path.parent / "playback-report.json"
if not playback_report_path.is_file():
raise FileNotFoundError(playback_report_path)
motion = load_json(motion_manifest_path)
playback = load_json(playback_report_path)
keyframes = {frame["name"]: frame for frame in motion["frames"]}
authored = tuple((name, keyframes[name]["durationMs"]) for name, _ in EXPECTED_KEYFRAMES)
if authored != EXPECTED_KEYFRAMES:
raise ValueError(f"Unexpected keyframe contract for {runtime_direction}: {authored}")
if playback["status"] != "playback-preview-validated":
raise ValueError(f"Playback is not validated for {runtime_direction}")
if playback["sourceVisibleBottomRange"]["delta"] != 0:
raise ValueError(f"Foot baseline moves in {runtime_direction}")
frame_records = []
for name, duration in EXPECTED_KEYFRAMES:
frame_path = motion_manifest_path.parent / keyframes[name]["file"]
if not frame_path.is_file():
raise FileNotFoundError(frame_path)
referenced.add(frame_path)
frame_records.append({"name": name, "durationMs": duration, "file": relative(frame_path)})
for sequence in ("idle", "throw"):
referenced.add(resolve(playback["outputs"][sequence]["file"]))
referenced.update((assembly_path, motion_manifest_path, playback_report_path))
neutral_path = motion_manifest_path.parent / keyframes["idle-neutral"]["file"]
neutral = Image.open(neutral_path).convert("RGBA")
canvas = motion["canvas"]
if neutral.size != (canvas["width"], canvas["height"]):
raise ValueError(f"Neutral frame size mismatch for {runtime_direction}")
record = {
"runtimeDirection": runtime_direction,
"assetDirectionId": source.get("legacyDirectionId") or runtime_direction,
"legacyDirectionId": source.get("legacyDirectionId"),
"status": source["status"],
"assembly": relative(assembly_path),
"motionManifest": relative(motion_manifest_path),
"playbackReport": relative(playback_report_path),
"sourceCanvas": {"width": canvas["width"], "height": canvas["height"]},
"fixedCrop": playback["fixedCrop"],
"sourceVisibleBottom": playback["sourceVisibleBottomRange"]["min"],
"footAnchor": {"normalizedX": 0.5, "normalizedY": 1.0, "policy": "bottom-center of fixed crop"},
"neutralFrame": relative(neutral_path),
"keyframes": frame_records,
"sequences": {
"idle": sequence_record(playback, "idle"),
"throw": sequence_record(playback, "throw"),
},
"artNotes": source["notes"],
}
return record, neutral
def draw_diamond(draw: ImageDraw.ImageDraw, center_x: int, center_y: int, width: int = 128, height: int = 64) -> None:
draw.polygon(
[
(center_x, center_y - height // 2),
(center_x + width // 2, center_y),
(center_x, center_y + height // 2),
(center_x - width // 2, center_y),
],
fill=(38, 60, 85),
outline=(87, 160, 222),
width=2,
)
def make_preview(records: list[dict], neutrals: dict[str, Image.Image]) -> None:
board = Image.new("RGB", (1920, 760), (16, 20, 29))
draw = ImageDraw.Draw(board)
title = ImageFont.truetype(str(FONT_PATH), 38)
subtitle = ImageFont.truetype(str(FONT_PATH), 18)
heading = ImageFont.truetype(str(FONT_PATH), 27)
body = ImageFont.truetype(str(FONT_PATH), 16)
small = ImageFont.truetype(str(FONT_PATH), 14)
draw.text((42, 24), "02 汐月心音|四方向模板角色交付总览 v1", font=title, fill=(242, 246, 252))
draw.text((44, 78), "统一 176 px 显示高度 · 128×64 菱形格 · 固定裁切与脚底中心原点 · 待机/投掷节奏一致", font=subtitle, fill=(151, 171, 201))
labels = {"up": "UP 背面", "down": "DOWN 正面", "left": "LEFT 画面左", "right": "RIGHT 画面右"}
arrows = {"up": "↑", "down": "↓", "left": "←", "right": "→"}
for index, record in enumerate(records):
direction = record["runtimeDirection"]
x0 = 40 + index * 470
y0 = 118
draw.rounded_rectangle((x0, y0, x0 + 430, 650), radius=14, fill=(24, 30, 42), outline=(65, 82, 112), width=2)
draw.text((x0 + 20, y0 + 18), f"{arrows[direction]} {labels[direction]}", font=heading, fill=(242, 246, 252))
asset_id = record["assetDirectionId"]
alias = f"运行时 {direction} ← 历史 {asset_id}" if record["legacyDirectionId"] else f"运行时与素材目录均为 {direction}"
draw.text((x0 + 22, y0 + 58), alias, font=small, fill=(151, 171, 201))
center_x = x0 + 215
foot_y = 500
draw_diamond(draw, center_x, foot_y)
crop_data = record["fixedCrop"]
crop = (
crop_data["x"],
crop_data["y"],
crop_data["x"] + crop_data["width"],
crop_data["y"] + crop_data["height"],
)
cropped = neutrals[direction].crop(crop)
output_height = 176
output_width = max(1, round(cropped.width * output_height / cropped.height))
resized = cropped.resize((output_width, output_height), Image.Resampling.LANCZOS)
board.paste(resized, (center_x - output_width // 2, foot_y - output_height), resized)
draw.line((center_x - 8, foot_y, center_x + 8, foot_y), fill=(255, 88, 116), width=3)
draw.rounded_rectangle((x0 + 20, 530, x0 + 410, 575), radius=8, fill=(31, 48, 56), outline=(66, 156, 121), width=1)
draw.text((x0 + 34, 542), "ART TEMPLATE READY", font=body, fill=(132, 232, 184))
draw.text((x0 + 20, 590), "idle 420 / 260 / 420 / 260 ms", font=small, fill=(200, 211, 229))
draw.text((x0 + 20, 616), "throw 150 / 110 / 90 / 180 / 260 ms", font=small, fill=(200, 211, 229))
draw.rounded_rectangle((40, 674, 1880, 730), radius=10, fill=(22, 27, 38), outline=(52, 68, 94), width=1)
draw.text((60, 690), "当前交付:PNG 帧动画优先接入;分解件与枢轴清单保留给后续 Skeleton2D。尚未完成 Godot 导入、纹理设置、碰撞/选择框及引擎内性能验证。", font=body, fill=(177, 190, 212))
PREVIEW_PATH.parent.mkdir(parents=True, exist_ok=True)
board.save(PREVIEW_PATH, quality=95)
def main() -> None:
direction_map = load_json(DIRECTION_MAP_PATH)
referenced: set[Path] = {DIRECTION_MAP_PATH}
records = []
neutrals = {}
for direction in DIRECTION_ORDER:
record, neutral = direction_record(direction, direction_map["directions"][direction], referenced)
records.append(record)
neutrals[direction] = neutral
canvas_sizes = {(record["sourceCanvas"]["width"], record["sourceCanvas"]["height"]) for record in records}
if canvas_sizes != {(600, 760)}:
raise ValueError(f"Runtime motion canvases are not normalized: {canvas_sizes}")
package = {
"characterId": "02-xinyin",
"characterNameZh": "汐月心音",
"version": 1,
"status": "art-template-ready",
"engineIntegrationStatus": "not-started-no-godot-project",
"recommendedIntegration": {
"primary": "frame-animation",
"description": "Import the validated full-frame PNG keyframes first; use decomposed parts and pivots for a later Skeleton2D implementation.",
"spriteOrigin": "bottom-center",
"textureFilter": "linear at 176/132 px; compare linear and nearest at 88 px in-engine",
},
"directionModel": {
"type": direction_map["runtimeDirectionModel"],
"directions": list(DIRECTION_ORDER),
"selectionRule": direction_map["selectionRule"],
"aimingRule": direction_map["aimingRule"],
},
"displayProfiles": list(DISPLAY_PROFILES),
"animationContract": {
"keyframes": [{"name": name, "durationMs": duration} for name, duration in EXPECTED_KEYFRAMES],
"idle": {"frames": ["idle-inhale", "idle-neutral", "idle-exhale", "idle-neutral"], "cycleMs": 1360, "loop": True},
"throw": {"frames": ["throw-ready", "throw-windup", "throw-release", "throw-recover", "idle-neutral"], "cycleMs": 790, "loop": False},
},
"directions": records,
"rebuildTools": [
"tools/build_xinyin_motion_playback.py",
"tools/build_xinyin_down_assembly.py",
"tools/build_xinyin_down_motion.py",
"tools/build_xinyin_up_assembly.py",
"tools/build_xinyin_up_motion.py",
"tools/build_xinyin_template_package.py",
],
"validation": {
"directionCount": len(records),
"allDirectionsMotionValidated": all(record["status"] == "motion-art-validated" for record in records),
"commonMotionCanvas": {"width": 600, "height": 760},
"allPlaybackBaselinesFixed": True,
"referencedFileCount": len(referenced),
"missingReferencedFiles": [],
},
"limitations": [
"No Godot project exists yet, so import settings, AnimationPlayer/SpriteFrames resources, and engine-side playback remain unverified.",
"Collision, selection, navigation, shadow, sorting, and VFX sockets are not part of this art-only package.",
"LEFT and RIGHT retain legacy front-right/front-left directories; consume this package instead of guessing folder names.",
"Body facing is four-cardinal while projectile and VFX aim are free-angle.",
],
}
PACKAGE_PATH.write_text(json.dumps(package, ensure_ascii=False, indent=2), encoding="utf-8")
make_preview(records, neutrals)
for image in neutrals.values():
image.close()
print(PACKAGE_PATH)
print(PREVIEW_PATH)
print(json.dumps(package["validation"], ensure_ascii=False))
if __name__ == "__main__":
main()