pipeline.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. """可被网站/命令行复用的生成管线。
  2. 读 manifest -> 生成各类资产 -> 写 library.json(供网站可视化列出与预览)。
  3. """
  4. import json
  5. import os
  6. import providers
  7. import spine_builder
  8. import particle_builder
  9. import tween_builder
  10. HERE = os.path.dirname(os.path.abspath(__file__))
  11. def run(manifest, out_root, creds=None, log=print):
  12. """manifest: dict; out_root: 输出根目录; creds: {provider,api_key,base_url,model,size}
  13. 返回 (library_dict, base_out)。"""
  14. creds = creds or {}
  15. game = manifest.get("game", "game")
  16. base_out = os.path.join(out_root, game)
  17. chars_out = os.path.join(base_out, "characters")
  18. vfx_out = os.path.join(base_out, "vfx")
  19. ui_out = os.path.join(base_out, "ui")
  20. style = manifest.get("style", "")
  21. library = {
  22. "game": game,
  23. "slot_config": manifest.get("slot_config", {}),
  24. "characters": [],
  25. "vfx": [],
  26. "ui": [],
  27. "ui_art": [],
  28. }
  29. total_steps = len(manifest.get("characters", [])) + len(manifest.get("ui_art", [])) + len(manifest.get("vfx", [])) + (1 if manifest.get("ui", []) else 0)
  30. done_steps = 0
  31. def progress(label):
  32. nonlocal done_steps
  33. done_steps += 1
  34. log(f"进度 {done_steps}/{max(1, total_steps)} · {label}")
  35. def transparent_prompt(extra):
  36. return ", ".join([
  37. extra,
  38. "生成纯透明背景 PNG,真实 Alpha 通道,不要棋盘格,不要白底,不要阴影。",
  39. ])
  40. def alpha_report(img):
  41. img = img.convert("RGBA")
  42. alpha = img.getchannel("A")
  43. mn, mx = alpha.getextrema()
  44. transparent = sum(1 for v in alpha.getdata() if v == 0)
  45. ratio = transparent / max(1, img.width * img.height)
  46. return mn, mx, ratio
  47. def has_alpha(img):
  48. return alpha_report(img)[0] == 0
  49. def log_alpha(label, img, required):
  50. if not required:
  51. return
  52. mn, mx, ratio = alpha_report(img)
  53. if mn == 0:
  54. log(f"✅ [{label}] Alpha 透明通道有效:透明像素 {ratio:.1%}")
  55. else:
  56. log(f"⚠️ [{label}] 模型返回 PNG 但没有透明 Alpha:alpha={mn}-{mx},请重新生成或换支持透明输出的图像模型")
  57. def generate_checked(label, prompt, size, require_alpha):
  58. retry_suffixes = [
  59. "",
  60. "这不是真透明背景。请重新生成:\n背景必须是 Alpha 透明通道,不是白色、灰色或棋盘格。\n去掉所有背景、阴影、光晕和底板,只保留主体,输出 PNG。",
  61. "这不是真透明背景。请重新生成:\n背景必须是 Alpha 透明通道,不是白色、灰色或棋盘格。\n去掉所有背景、阴影、光晕和底板,只保留主体,输出 PNG。",
  62. ]
  63. last = None
  64. for attempt, suffix in enumerate(retry_suffixes, start=1):
  65. attempt_prompt = ", ".join(x for x in [prompt, suffix] if x)
  66. if attempt > 1:
  67. log(f"🔁 [{label}] Alpha 不合格,重新生成透明 PNG(第 {attempt}/{len(retry_suffixes)} 次)…")
  68. img = providers.generate(creds["provider"], attempt_prompt, creds["api_key"],
  69. creds.get("base_url", "https://api.openai.com/v1"),
  70. creds.get("model", "gpt-image-2"),
  71. size)
  72. last = img
  73. log_alpha(label, img, require_alpha)
  74. if not require_alpha or has_alpha(img):
  75. return img
  76. raise RuntimeError(f"模型连续 {len(retry_suffixes)} 次没有返回真实 Alpha 透明通道;请换支持透明输出的图像模型或稍后重试")
  77. # ---- A. 角色(Spine)----
  78. for i, c in enumerate(manifest.get("characters", [])):
  79. cid = c.get("id", f"char_{i}")
  80. anims = c.get("animations", ["idle"])
  81. if not creds.get("api_key"):
  82. log(f"⚠️ 未填 key,跳过角色 {cid}")
  83. continue
  84. try:
  85. if c.get("type") == "spine_parts":
  86. part_images = {}
  87. parts = c.get("parts") or []
  88. for part in parts:
  89. part_id = part["id"]
  90. part_prompt = ", ".join(x for x in [
  91. c.get("prompt", ""),
  92. part.get("prompt", ""),
  93. style,
  94. transparent_prompt("single separated rigging part only, centered, no text, no other body parts")
  95. ] if x)
  96. log(f"🎨 [{cid}/{part_id}] 生成 Boss 拆件…")
  97. pimg = generate_checked(f"{cid}/{part_id}", part_prompt,
  98. part.get("size", c.get("size", creds.get("size", "1024x1024"))),
  99. True)
  100. part_images[part_id] = pimg
  101. spine_builder.build_parts_character(cid, part_images, chars_out, anims, parts)
  102. w, h = 1000, 1000
  103. files = [f"characters/{cid}.json", f"characters/{cid}.atlas", f"characters/{cid}.png"]
  104. else:
  105. full_prompt = ", ".join(x for x in [
  106. c.get("prompt", ""), style,
  107. transparent_prompt("single game icon character or slot symbol, centered, full body in frame, no text, not a boss, not a demon lord, not dark armor"),
  108. ] if x)
  109. log(f"🎨 [{cid}] 生成角色图…")
  110. img = generate_checked(cid, full_prompt, c.get("size", creds.get("size", "1024x1024")), True)
  111. spine_builder.build_character(cid, img, chars_out, anims)
  112. w, h = spine_builder.trim_to_content(img).size
  113. files = [f"characters/{cid}.json", f"characters/{cid}.atlas", f"characters/{cid}.png"]
  114. library["characters"].append({
  115. "id": cid,
  116. "png": f"characters/{cid}.png",
  117. "w": w, "h": h,
  118. "type": c.get("type", "spine"),
  119. "role": c.get("role", ""),
  120. "animations": spine_builder.anim_data(anims),
  121. "files": files,
  122. })
  123. log(f"✅ [{cid}] 完成 ({anims})")
  124. progress(f"{cid}")
  125. except Exception as e:
  126. log(f"❌ [{cid}] 失败: {e}")
  127. progress(f"{cid}")
  128. # ---- A2. UI 美术(背景 / Logo / 卷轴框 / 按钮 等整图)----
  129. ui_art_out = os.path.join(base_out, "ui_art")
  130. for a in manifest.get("ui_art", []):
  131. aid = a.get("id", "art")
  132. if not creds.get("api_key"):
  133. log(f"⚠️ 未填 key,跳过 UI 美术 {aid}")
  134. continue
  135. try:
  136. transparent = a.get("transparent", True)
  137. extra = (transparent_prompt("single clean UI element, no text")
  138. if transparent
  139. else "full-bleed illustration, no text, no UI elements")
  140. full_prompt = ", ".join(x for x in [a.get("prompt", ""), style if a.get("use_style") else "", extra] if x)
  141. log(f"🖼 [{aid}] 生成 UI 美术…")
  142. img = generate_checked(aid, full_prompt, a.get("size", creds.get("size", "1024x1024")), transparent)
  143. os.makedirs(ui_art_out, exist_ok=True)
  144. img.save(os.path.join(ui_art_out, f"{aid}.png"))
  145. library["ui_art"].append({"id": aid, "file": f"ui_art/{aid}.png",
  146. "w": img.width, "h": img.height,
  147. "transparent": transparent})
  148. log(f"✅ [{aid}] UI 美术完成")
  149. progress(f"{aid}")
  150. except Exception as e:
  151. log(f"❌ [{aid}] UI 美术失败: {e}")
  152. progress(f"{aid}")
  153. # ---- B. 粒子 VFX ----
  154. for v in manifest.get("vfx", []):
  155. vid = v.get("id", "vfx")
  156. try:
  157. path = particle_builder.build_particle(
  158. vid, v.get("template", "burst"), v.get("color", [255, 255, 255]), vfx_out)
  159. cfg = json.load(open(path, encoding="utf-8"))
  160. library["vfx"].append({"id": vid, "template": v.get("template"),
  161. "file": f"vfx/{vid}.particle.json", "config": cfg})
  162. log(f"✨ [{vid}] 粒子配置完成")
  163. progress(f"{vid}")
  164. except Exception as e:
  165. log(f"❌ [{vid}] 粒子失败: {e}")
  166. progress(f"{vid}")
  167. # ---- C. UI Tween ----
  168. ui = manifest.get("ui", [])
  169. if ui:
  170. used = [u.get("preset") for u in ui if u.get("preset")]
  171. try:
  172. tween_builder.build_tweens(used, ui_out)
  173. for u in ui:
  174. library["ui"].append({"id": u.get("id"), "preset": u.get("preset"),
  175. "params": u.get("params", {})})
  176. log(f"🎛 TweenPresets.ts 完成 ({used})")
  177. progress("TweenPresets")
  178. except Exception as e:
  179. log(f"❌ Tween 失败: {e}")
  180. progress("TweenPresets")
  181. os.makedirs(base_out, exist_ok=True)
  182. with open(os.path.join(base_out, "library.json"), "w", encoding="utf-8") as f:
  183. json.dump(library, f, ensure_ascii=False, indent=2)
  184. log("—— 完成 ——")
  185. return library, base_out