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

187 lines
13 KiB
Python

from __future__ import annotations
import json
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from extract_xinyin_down_parts import draw_cross, joint_record, load_labels, part
ROOT = Path(r"C:\milimoe\osm-game")
CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin"
SOURCE_DIR = CHARACTER / "source/up"
DIAGNOSTIC_DIR = CHARACTER / "diagnostics"
OUTPUT_DIR = CHARACTER / "parts/up/v1"
PREVIEW = CHARACTER / "previews/xinyin-up-extracted-parts-v1.png"
MANIFEST = OUTPUT_DIR / "parts-manifest.json"
FONT_PATH = Path(r"C:\Windows\Fonts\msyh.ttc")
PADDING = 10
ALPHA_THRESHOLD = 16
SHEETS = {
"core": {
"source": SOURCE_DIR / "xinyin-up-core-parts-sheet-v2.png",
"diagnostic": DIAGNOSTIC_DIR / "xinyin-up-core-parts-v2-components.json",
"expected": 17,
},
"soft": {
"source": SOURCE_DIR / "xinyin-up-soft-parts-sheet-v2.png",
"diagnostic": DIAGNOSTIC_DIR / "xinyin-up-soft-parts-v2-components.json",
"expected": 24,
},
}
# UP owns a direction-specific convention: A is screen-right, B is screen-left.
# Do not mirror or copy the strict-front DOWN ownership table.
PARTS = [
part("core", 1, "torso-upper", "背面上半身躯干", "body", (.50, .90), (.50, .08), "pelvis-hip-core", 10, "严格背面主躯干;不含手臂、肩甲与袖披"),
part("core", 4, "pelvis-hip-core", "背面骨盆与腰封核心", "body", (.50, .18), None, "character-root", 2, "角色主根候选;双腿和背面衣摆挂接于此"),
part("core", 5, "head-back", "背面头部基底", "body", (.50, .91), None, "neck", 30, "无面部的严格背面头部;后脑发片覆盖其上"),
part("core", 2, "shoulder-armor-a", "肩甲 A/画面右", "armor", (.28, .24), None, "torso-upper", 20, "持扇手侧;固定于躯干"),
part("core", 3, "shoulder-armor-b", "肩甲 B/画面左", "armor", (.72, .24), None, "torso-upper", 20, "放松手与腰包侧;固定于躯干"),
part("core", 6, "neck", "背面颈部连接件", "body", (.50, .78), (.50, .12), "torso-upper", 5, "下接躯干,上接背面头部"),
part("core", 10, "upper-arm-a", "上臂 A/画面右", "arm", (.50, .08), (.50, .92), "torso-upper", 14, "持扇手侧;不含肩甲与袖披"),
part("core", 11, "upper-arm-b", "上臂 B/画面左", "arm", (.50, .08), (.50, .92), "torso-upper", 14, "放松手侧;不含肩甲与袖披"),
part("core", 9, "forearm-a", "前臂 A/画面右", "arm", (.50, .08), (.50, .92), "upper-arm-a", 16, "持扇手侧肘到腕"),
part("core", 8, "forearm-b", "前臂 B/画面左", "arm", (.50, .08), (.50, .92), "upper-arm-b", 16, "放松手侧肘到腕"),
part("core", 7, "hand-fan-grip-a", "持扇手 A", "hand", (.50, .88), None, "forearm-a", 18, "画面右侧;含三羽持握形态"),
part("core", 12, "hand-relaxed-b", "放松手 B", "hand", (.50, .08), None, "forearm-b", 18, "画面左侧;腕点位于上端"),
part("core", 17, "hand-throw-open-a", "投掷张手 A", "hand", (.82, .18), None, "forearm-a", 18, "持扇手侧动作替换件;腕点在部件右上"),
part("core", 15, "thigh-a", "大腿 A/画面右", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "画面右髋点到膝点"),
part("core", 16, "thigh-b", "大腿 B/画面左", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "画面左髋点到膝点"),
part("core", 13, "shin-boot-a", "小腿与靴 A/画面右", "leg", (.50, .05), None, "thigh-a", -7, "画面右;膝点位于上端"),
part("core", 14, "shin-boot-b", "小腿与靴 B/画面左", "leg", (.50, .05), None, "thigh-b", -7, "画面左;膝点位于上端"),
part("soft", 4, "hair-nape-overlay", "后颈发丝覆盖层", "hair", (.50, .12), None, "head-back", 35, "覆盖后脑与后颈的近景发丝层"),
part("soft", 5, "hair-cap", "后脑发帽", "hair", (.50, .82), None, "head-back", -90, "位于头部之后;马尾根父节点"),
part("soft", 2, "ponytail-root", "马尾根部", "hair", (.48, .10), (.46, .88), "hair-cap", -96, "严格背面马尾根;根部到第一连接点"),
part("soft", 1, "ponytail-middle", "马尾中段", "hair", (.50, .08), (.50, .90), "ponytail-root", -95, "上下端预留重叠"),
part("soft", 6, "ponytail-tip", "马尾末端", "hair", (.50, .08), None, "ponytail-middle", -94, "末端链节"),
part("soft", 3, "hair-ornament-long", "长银花发饰", "ornament", (.50, .08), None, "head-back", 42, "背面独立装饰层"),
part("soft", 12, "outer-sleeve-cape-a", "外袖披 A/画面右", "cloth", (.50, .08), None, "upper-arm-a", 13, "不含肩甲和手臂;随上臂小幅摆动"),
part("soft", 11, "outer-sleeve-cape-b", "外袖披 B/画面左", "cloth", (.50, .08), None, "upper-arm-b", 13, "不含肩甲和手臂;随上臂小幅摆动"),
part("soft", 9, "coat-panel-01", "背面衣摆分片 01", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -39, "中性八片之一"),
part("soft", 10, "coat-panel-02", "背面衣摆分片 02", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -38, "中性八片之一"),
part("soft", 8, "coat-panel-03", "背面衣摆分片 03", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -37, "中性八片之一"),
part("soft", 7, "coat-panel-04", "背面衣摆分片 04", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -36, "中性八片之一"),
part("soft", 16, "coat-panel-05", "背面衣摆分片 05", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -35, "中性八片之一"),
part("soft", 15, "coat-panel-06", "背面衣摆分片 06", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -34, "中性八片之一"),
part("soft", 14, "coat-panel-07", "背面衣摆分片 07", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -33, "中性八片之一"),
part("soft", 17, "coat-panel-08", "背面衣摆分片 08", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -32, "中性八片之一"),
part("soft", 18, "coat-panel-alt-09", "背面衣摆替换片 09", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -31, "动作轮廓替换件"),
part("soft", 13, "rear-drape", "中央腰后布", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", 6, "不含独立替换流苏"),
part("soft", 24, "waist-pouch", "黑色腰包", "accessory", (.50, .08), None, "pelvis-hip-core", 22, "固定在画面左侧腰部"),
part("soft", 19, "red-tassel-a", "红流苏替换件 A", "accessory", (.50, .08), None, "rear-drape", 8, "动作替换件"),
part("soft", 20, "red-tassel-b", "红流苏替换件 B", "accessory", (.50, .08), None, "rear-drape", 8, "动作替换件"),
part("soft", 21, "weapon-fan-open", "三羽展开扇", "weapon", (.50, .88), None, "hand-fan-grip-a", 50, "无手;与持扇手分层装配"),
part("soft", 23, "weapon-blade-single", "单枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "投掷物或手持替换件"),
part("soft", 22, "weapon-double-feather", "双枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "追击或双刃攻击用独立物件"),
]
def main():
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
PREVIEW.parent.mkdir(parents=True, exist_ok=True)
loaded = {key: load_labels(value["source"], value["diagnostic"]) for key, value in SHEETS.items()}
for key, (_, labels, diagnostic) in loaded.items():
expected = SHEETS[key]["expected"]
ids = {component["id"] for component in diagnostic["components"]}
if len(diagnostic["components"]) != expected or ids != set(range(1, expected + 1)):
raise RuntimeError(f"Expected component IDs 1..{expected} for {key}")
if any(not np.any(labels == component_id) for component_id in ids):
raise RuntimeError(f"Missing labeled component in {key}")
manifest_parts = []
exported = []
for spec in PARTS:
rgba, labels, diagnostic = loaded[spec["sheet"]]
component = next(item for item in diagnostic["components"] if item["id"] == spec["componentId"])
x, y, width, height = (component[key] for key in ("x", "y", "width", "height"))
crop = rgba[y : y + height, x : x + width].copy()
mask = labels[y : y + height, x : x + width] == spec["componentId"]
crop[~mask] = 0
output = np.zeros((height + PADDING * 2, width + PADDING * 2, 4), dtype=np.uint8)
output[PADDING : PADDING + height, PADDING : PADDING + width] = crop
image = Image.fromarray(output, "RGBA")
prefix = "up-core" if spec["sheet"] == "core" else "up-soft"
filename = f"{prefix}-c{spec['componentId']:02d}-{spec['name']}.png"
image.save(OUTPUT_DIR / filename)
record = {
"sourceSheet": spec["sheet"],
"componentId": spec["componentId"],
"name": spec["name"],
"labelZh": spec["labelZh"],
"category": spec["category"],
"file": filename,
"parent": spec["parent"],
"sourceRect": {"x": x, "y": y, "width": width, "height": height},
"outputSize": {"width": image.width, "height": image.height},
"rootPivot": joint_record(spec["pivot"], width, height),
"nextJoint": joint_record(spec["next"], width, height),
"suggestedLayer": spec["layer"],
"notes": spec["note"],
}
manifest_parts.append(record)
exported.append((spec, record, image))
manifest = {
"characterId": "02-xinyin",
"characterNameZh": "汐月心音",
"direction": "up",
"version": 1,
"status": "extracted-unvalidated",
"sources": {
"core": "assets/images/2d-game-characters/02-xinyin/source/up/xinyin-up-core-parts-sheet-v2.png",
"soft": "assets/images/2d-game-characters/02-xinyin/source/up/xinyin-up-soft-parts-sheet-v2.png",
},
"padding": PADDING,
"alphaExtraction": {"connectivity": 8, "alphaThreshold": ALPHA_THRESHOLD, "minimumComponentArea": 80, "mode": "connected-component-mask"},
"coordinateSystem": {"origin": "top-left", "xPositive": "right", "yPositive": "down", "units": "pixels", "jointBasis": "content bounds before export padding"},
"sideConvention": {"A": "screen-right / character-right / fan-hand side", "B": "screen-left / character-left / relaxed-hand and pouch side"},
"warnings": [
"A/B ownership is frozen for the strict-back UP direction and must not reuse the DOWN screen-side mapping.",
"Pivots, layers, and parent links are authoring recommendations until the first neutral assembly is validated.",
"The source pelvis contains neutral waist cords, pouch, rear cloth, and tassels; standalone pouch, rear drape, and tassels are replacement layers and may be excluded from the neutral assembly.",
"Core and soft sheet v1 are rejected source layouts; extraction uses v2 only.",
"Sleeve capes do not include shoulder armor, and coat panels do not include tassels or chains.",
],
"partCount": len(manifest_parts),
"parts": manifest_parts,
}
MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
columns, cell_width, cell_height = 6, 390, 300
rows = (len(exported) + columns - 1) // columns
sheet = Image.new("RGB", (columns * cell_width, rows * cell_height), (20, 24, 33))
draw = ImageDraw.Draw(sheet)
title_font = ImageFont.truetype(str(FONT_PATH), 18)
meta_font = ImageFont.truetype(str(FONT_PATH), 13)
for index, (spec, record, image) in enumerate(exported):
col, row = index % columns, index // columns
cell_x, cell_y = col * cell_width, row * cell_height
draw.rectangle((cell_x + 8, cell_y + 8, cell_x + cell_width - 9, cell_y + cell_height - 9), outline=(63, 78, 104), width=2)
scale = min(1.0, 270 / image.width, 200 / image.height)
resized = image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))), Image.Resampling.LANCZOS)
draw_x = cell_x + (cell_width - resized.width) // 2
draw_y = cell_y + 42 + (200 - resized.height) // 2
sheet.paste(resized, (draw_x, draw_y), resized)
root = record["rootPivot"]["outputPixels"]
draw_cross(draw, draw_x + root["x"] * scale, draw_y + root["y"] * scale, (255, 87, 115))
if record["nextJoint"]:
nxt = record["nextJoint"]["outputPixels"]
draw_cross(draw, draw_x + nxt["x"] * scale, draw_y + nxt["y"] * scale, (69, 211, 255))
code = "C" if spec["sheet"] == "core" else "S"
draw.text((cell_x + 16, cell_y + 12), f"{code}{spec['componentId']:02d} {spec['name']}", font=title_font, fill=(241, 245, 252))
draw.text((cell_x + 16, cell_y + 263), f"{spec['labelZh']} | parent: {spec['parent']}", font=meta_font, fill=(155, 174, 203))
sheet.save(PREVIEW)
print(f"Exported {len(exported)} parts")
print(MANIFEST)
print(PREVIEW)
if __name__ == "__main__":
main()