from __future__ import annotations import json from pathlib import Path import numpy as np from PIL import Image, ImageDraw, ImageFont ROOT = Path(r"C:\milimoe\osm-game") CHARACTER = ROOT / "assets/images/2d-game-characters/02-xinyin" SOURCE_DIR = CHARACTER / "source/front-left" DIAGNOSTIC_DIR = CHARACTER / "diagnostics" OUTPUT_DIR = CHARACTER / "parts/front-left/v1" PREVIEW = CHARACTER / "previews/xinyin-front-left-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-front-left-core-parts-sheet-v1.png", "diagnostic": DIAGNOSTIC_DIR / "xinyin-front-left-core-parts-v1-components.json", }, "soft": { "source": SOURCE_DIR / "xinyin-front-left-soft-parts-sheet-v1.png", "diagnostic": DIAGNOSTIC_DIR / "xinyin-front-left-soft-parts-v1-components.json", }, } def part(sheet, component_id, name, label, category, pivot, next_joint, parent, layer, note): return { "sheet": sheet, "componentId": component_id, "name": name, "labelZh": label, "category": category, "pivot": pivot, "next": next_joint, "parent": parent, "layer": layer, "note": note, } PARTS = [ part("core", 1, "torso-upper", "上半身躯干", "body", (.50, .90), (.50, .08), "pelvis-hip-core", 10, "主躯干;上端连接颈部,左右连接上臂"), part("core", 2, "pelvis-hip-core", "骨盆与腰封核心", "body", (.50, .18), None, "character-root", 2, "角色主根节点候选;双腿和衣摆均挂接于此"), part("core", 3, "head-face", "头部与面部", "body", (.50, .91), None, "neck", 30, "不含前发;枢轴位于颈部连接区"), part("core", 4, "shoulder-armor-b", "肩甲 B", "armor", (.28, .24), None, "torso-upper", 20, "固定在躯干;装配后确认具体画面侧"), part("core", 5, "shoulder-armor-a", "肩甲 A", "armor", (.72, .24), None, "torso-upper", 20, "固定在躯干;装配后确认具体画面侧"), part("core", 6, "neck", "颈部连接件", "body", (.50, .78), (.50, .12), "torso-upper", 5, "下接躯干,上接头部"), part("core", 7, "upper-arm-a", "上臂 A", "arm", (.50, .08), (.50, .82), "torso-upper", 14, "放松手侧;肩点到肘点"), part("core", 8, "upper-arm-b", "上臂 B", "arm", (.50, .08), (.50, .82), "torso-upper", 14, "持械手侧;肩点到肘点"), part("core", 9, "hand-fan-grip-b", "持扇手 B", "hand", (.53, .88), None, "forearm-b", 18, "腕点位于下端;与独立羽扇叠加"), part("core", 10, "forearm-a", "前臂 A", "arm", (.50, .08), (.50, .92), "upper-arm-a", 16, "肘点到腕点"), part("core", 11, "forearm-b", "前臂 B", "arm", (.50, .08), (.50, .92), "upper-arm-b", 16, "肘点到腕点"), part("core", 12, "hand-relaxed-a", "放松手 A", "hand", (.50, .08), None, "forearm-a", 18, "腕点位于上端"), part("core", 13, "hand-throw-open-b", "投掷张手 B", "hand", (.23, .18), None, "forearm-b", 18, "投掷动作替换手;腕点位于左上袖口"), part("core", 14, "thigh-a", "大腿 A", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "髋点到膝点"), part("core", 15, "shin-boot-a", "小腿与靴 A", "leg", (.50, .05), None, "thigh-a", -7, "膝点位于上端"), part("core", 16, "shin-boot-b", "小腿与靴 B", "leg", (.50, .05), None, "thigh-b", -7, "膝点位于上端"), part("core", 17, "thigh-b", "大腿 B", "leg", (.50, .05), (.50, .92), "pelvis-hip-core", -8, "髋点到膝点"), part("soft", 1, "ponytail-root", "马尾根部", "hair", (.62, .15), (.18, .72), "hair-cap", -96, "含贴合头顶的花冠;体积偏大,需装配验证"), part("soft", 2, "ponytail-middle", "马尾中段", "hair", (.15, .14), (.82, .80), "ponytail-root", -95, "上下两端预留重叠;大幅旋转前需验证穿插"), part("soft", 3, "side-lock-a", "长侧发 A", "hair", (.50, .08), None, "hair-cap", 32, "面部侧边软性覆盖层"), part("soft", 4, "hair-front", "前发与侧鬓", "hair", (.50, .12), None, "head-face", 35, "位于面部之前"), part("soft", 5, "side-lock-b", "长侧发 B", "hair", (.50, .08), None, "hair-cap", 31, "面部另一侧软性覆盖层"), part("soft", 6, "hair-ornament-long", "长银花发饰", "ornament", (.50, .08), None, "head-face", 42, "画面左侧独立装饰层"), part("soft", 7, "ponytail-tip", "马尾末端", "hair", (.50, .06), (.50, .92), "ponytail-middle", -94, "末端链节;不再挂接子节"), part("soft", 8, "hair-cap", "后脑发帽", "hair", (.50, .82), None, "head-face", -90, "位于头部之后;马尾链根节点"), part("soft", 9, "outer-sleeve-cape-a", "外袖披 A", "cloth", (.62, .08), None, "upper-arm-a", 13, "随上臂小幅摆动,不承担手臂骨骼"), part("soft", 10, "outer-sleeve-cape-b", "外袖披 B", "cloth", (.38, .08), None, "upper-arm-b", 13, "随上臂小幅摆动,不承担手臂骨骼"), part("soft", 11, "coat-panel-01", "衣摆分片 01", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -39, "后层衣摆;具体左右在装配时确认"), part("soft", 12, "coat-panel-02", "衣摆分片 02", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -38, "后层衣摆;具体左右在装配时确认"), part("soft", 13, "coat-panel-03", "衣摆分片 03", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -37, "中后层衣摆"), part("soft", 14, "coat-panel-04", "衣摆分片 04", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -36, "中后层衣摆"), part("soft", 15, "coat-panel-05", "衣摆分片 05", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -35, "中层衣摆"), part("soft", 16, "coat-panel-06", "衣摆分片 06", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -34, "中层衣摆"), part("soft", 17, "coat-panel-07", "衣摆分片 07", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -33, "前层衣摆"), part("soft", 18, "coat-panel-08", "衣摆分片 08", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -32, "前层衣摆"), part("soft", 19, "coat-panel-alt-09", "衣摆替换片 09", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", -31, "动作替换候选;中性装配仅从九片中选八片"), part("soft", 20, "front-drape", "前腰布与基线系绳", "cloth", (.50, .04), (.50, .94), "pelvis-hip-core", 6, "位于腰封前侧;自带中性流苏"), part("soft", 21, "red-tassel-a", "红流苏替换件 A", "accessory", (.50, .08), None, "front-drape", 8, "动作替换件"), part("soft", 22, "weapon-double-feather", "双枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "追击或双刃攻击用独立物件"), part("soft", 23, "red-tassel-b", "红流苏替换件 B", "accessory", (.50, .08), None, "front-drape", 8, "动作替换件"), part("soft", 24, "weapon-fan-open", "三羽展开扇", "weapon", (.46, .88), None, "hand-fan-grip-b", 50, "与持扇手分层装配"), part("soft", 25, "weapon-blade-single", "单枚羽刃", "weapon", (.50, .88), None, "vfx-root", 50, "投掷物或手持替换件"), part("soft", 26, "waist-pouch", "黑色腰包", "accessory", (.50, .08), None, "pelvis-hip-core", 22, "固定在画面左侧腰部"), ] def load_labels(source_path: Path, diagnostic_path: Path): rgba = np.array(Image.open(source_path).convert("RGBA")) alpha = rgba[:, :, 3] # Image.fromarray can expose a read-only buffer; floodfill needs a mutable copy. labels_image = Image.fromarray(np.where(alpha >= ALPHA_THRESHOLD, 255, 0).astype(np.uint8), "L").copy() diagnostic = json.loads(diagnostic_path.read_text(encoding="utf-8-sig")) for component in diagnostic["components"]: current = np.array(labels_image) y = component["y"] x0 = component["x"] x1 = x0 + component["width"] candidates = np.flatnonzero(current[y, x0:x1] == 255) if not len(candidates): raise RuntimeError(f"No flood-fill seed for {source_path.name} component {component['id']}") seed = (x0 + int(candidates[0]), y) ImageDraw.floodfill(labels_image, seed, component["id"], thresh=0) labels = np.array(labels_image) # Pillow flood fill is four-connected. Attach any diagonal-only fragments to an # already labeled eight-neighbour; tiny unrelated specks remain discarded. for _ in range(8): pending = np.argwhere(labels == 255) if not len(pending): break changed = 0 for y, x in pending: y0, y1 = max(0, y - 1), min(labels.shape[0], y + 2) x0, x1 = max(0, x - 1), min(labels.shape[1], x + 2) neighbours = labels[y0:y1, x0:x1] valid = neighbours[(neighbours > 0) & (neighbours < 255)] if len(valid): values, counts = np.unique(valid, return_counts=True) labels[y, x] = values[np.argmax(counts)] changed += 1 if not changed: break return rgba, labels, diagnostic def joint_record(normalized, width, height): if normalized is None: return None return { "contentNormalized": {"x": normalized[0], "y": normalized[1]}, "outputPixels": { "x": round(PADDING + width * normalized[0], 2), "y": round(PADDING + height * normalized[1], 2), }, } def draw_cross(draw: ImageDraw.ImageDraw, x: float, y: float, color, radius=7, width=3): draw.line((x - radius, y, x + radius, y), fill=color, width=width) draw.line((x, y - radius, x, y + radius), fill=color, width=width) 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()} expected = {"core": 17, "soft": 26} for key, (_, labels, diagnostic) in loaded.items(): if len(diagnostic["components"]) != expected[key]: raise RuntimeError(f"Expected {expected[key]} components for {key}") if any(not np.any(labels == component_id) for component_id in range(1, expected[key] + 1)): raise RuntimeError(f"Missing labeled component in {key}") manifest_parts = [] exported = [] for spec in PARTS: rgba, labels, diagnostic = loaded[spec["sheet"]] component = diagnostic["components"][spec["componentId"] - 1] x, y, width, height = (component[k] for k in ("x", "y", "width", "height")) source_crop = rgba[y : y + height, x : x + width].copy() component_mask = labels[y : y + height, x : x + width] == spec["componentId"] source_crop[~component_mask] = 0 output = np.zeros((height + PADDING * 2, width + PADDING * 2, 4), dtype=np.uint8) output[PADDING : PADDING + height, PADDING : PADDING + width] = source_crop image = Image.fromarray(output, "RGBA") prefix = "fl-core" if spec["sheet"] == "core" else "fl-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": "front-left", "version": 1, "status": "extracted-unvalidated", "sources": { "core": "assets/images/2d-game-characters/02-xinyin/source/front-left/xinyin-front-left-core-parts-sheet-v1.png", "soft": "assets/images/2d-game-characters/02-xinyin/source/front-left/xinyin-front-left-soft-parts-sheet-v1.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", }, "warnings": [ "A/B limb and cloth ownership follows source-sheet grouping and must be frozen after the first front-left assembly.", "Ponytail root and middle are oversized source segments; validate overlap and rotation before animation use.", "Suggested hierarchy, layers, root pivots, and next joints are authoring recommendations and have not been engine-tested.", "Do not mirror asymmetric art automatically; weapon, pouch, hair ornament, and ponytail screen sides are fixed.", ], "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 = 5, 460, 320 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), 20) meta_font = ImageFont.truetype(str(FONT_PATH), 14) 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) max_width, max_height = 320, 220 scale = min(1.0, max_width / image.width, max_height / 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 + 48 + (max_height - 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 + 18, cell_y + 14), f"{code}{spec['componentId']:02d} {spec['name']}", font=title_font, fill=(241, 245, 252)) draw.text((cell_x + 18, cell_y + 282), 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()