导入上游源码,为所有面向用户的品牌显示处添加「增强版 / Enhanced」标识;包含 unitypackage→VRM 的纯色 Toon 材质、兽耳 SpringBone、Unity 描边、UV 接缝白边补偿修复,以及默认不强制 T-pose。146 个单元测试通过。
This commit is contained in:
+2418
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,459 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""转换日志的英文版。转换器里的日志直接写中文句子;界面是英文时按这里的对照表翻译。
|
||||
|
||||
logtext.to_en(msg) → 英文;对不上的返回 None(界面照常显示中文)
|
||||
|
||||
TEMPLATES 的中文句式和代码里的 log(...) / raise 一一对应(tests/test_logtext.py 扫描源码,漏了会报错),
|
||||
句式里的 %d / %s / %.1f 匹配成参数。参数是程序生成的中文(「需要反转」「左」、另一条句式)时再翻译,
|
||||
模型里的名字(骨骼、材质、文件名)原样保留。英文句式里用 {0} {1} … 引用参数,顺序可以和中文不同。
|
||||
"""
|
||||
import re
|
||||
|
||||
TEMPLATES = {
|
||||
# ---- 流程(pipeline / server / parallel)
|
||||
"→ %s": "→ {0}",
|
||||
"· %s": "· {0}",
|
||||
"输出目录:%s": "Output folder: {0}",
|
||||
"解压出 %d 个文件,其中模型 %d 个:%s": "Extracted {0} files, {1} of them models: {2}",
|
||||
"解压内层压缩包 %s": "Extracting the inner archive {0}",
|
||||
"用 %s 解压": "Extracting with {0}",
|
||||
"%s共有 %d 个模型,并行转换 %d 个": "{1} models {0}, converting {2} at a time",
|
||||
"压缩包中": "in the archive",
|
||||
"包中": "in the package",
|
||||
"解包 %s:%d 个文件,%d 个 FBX": "Unpacked {0}: {1} files, {2} FBX",
|
||||
"读取 FBX:%s": "Reading FBX: {0}",
|
||||
"PMX → VRM:%s": "PMX → VRM: {0}",
|
||||
"跳过 %s:%s(如需转换,请在「转换」页关闭「只转换人物」)":
|
||||
"Skipped {0}: {1} (to convert it anyway, turn off \"Characters only\" on the Convert tab)",
|
||||
"未识别到人形骨架,可能是道具": "no humanoid skeleton found, probably a prop",
|
||||
"头部没有网格,可能只有服装或配件": "nothing is attached to the head, probably only clothes or accessories",
|
||||
"手部没有网格,可能只有服装或配件": "nothing is attached to the hands, probably only clothes or accessories",
|
||||
"%s 转换失败:%s": "{0} failed: {1}",
|
||||
"没有执行": "not run",
|
||||
"已应用保存的调整(%d 项)": "Applied the saved Tune edits ({0})",
|
||||
"已写出 %s": "Wrote {0}",
|
||||
"无法启动子进程,改为逐个转换": "Couldn't start worker processes, converting one at a time",
|
||||
"完成,用时 %.1f 秒": "Done in {0} s",
|
||||
"并行转换 %d 个文件(共 %d 个)": "Converting {0} files at a time ({1} in total)",
|
||||
"已停止,%d 个文件未转换": "Stopped, {0} files not converted",
|
||||
"预览:未找到人物模型,忽略「只转换人物」生成预览":
|
||||
"Preview: no character found, previewing without \"Characters only\"",
|
||||
"调整写入 %s 失败:%s": "Writing the Tune edits to {0} failed: {1}",
|
||||
"调整已写入 %s": "Tune edits written to {0}",
|
||||
"缩略图已自动生成并写入 %s": "Thumbnail generated and written to {0}",
|
||||
# ---- 错误(raise,界面显示在文件下面)
|
||||
"包中没有 FBX 文件": "The package has no FBX files",
|
||||
"无法转换此文件:%s": "Can't convert this file: {0}",
|
||||
"压缩包中没有可转换的模型(PMX / FBX / uemodel / psk / xps)":
|
||||
"The archive has no models to convert (PMX / FBX / uemodel / psk / xps)",
|
||||
"不支持的输入:%s": "Unsupported input: {0}",
|
||||
"无法创建输出目录 %s:%s": "Can't create the output folder {0}: {1}",
|
||||
"此 PMX 没有可用的面数据": "This PMX has no faces to convert",
|
||||
"不是 VRM 文件": "Not a VRM file",
|
||||
"不是支持的压缩包:%s": "Not a supported archive: {0}",
|
||||
"既不是二进制 FBX,也解析不出 ASCII FBX 节点:%s": "Neither a binary FBX nor readable as ASCII FBX: {0}",
|
||||
"不是 PMX 文件:%s": "Not a PMX file: {0}",
|
||||
"PMX 解析后仍有 %d 字节未读完(已读 %d / 共 %d),说明某一段的结构与写入程序不一致,请反馈此模型文件。":
|
||||
"{0} bytes left after reading the PMX ({1} of {2} read): a section doesn't match what the writing "
|
||||
"program produced. Please report this model file.",
|
||||
"改写后回读校验失败,未写入:%s": "Verification after rewriting failed, nothing written: {0}",
|
||||
"%s读取「%s」时越过文件末尾(偏移 %d / 文件 %d 字节)。可能是某一段的结构与写入程序不一致,请反馈此模型文件。":
|
||||
"{0}reading \"{1}\" went past the end of the file (offset {2} of {3} bytes). A section may not match what "
|
||||
"the writing program produced. Please report this model file.",
|
||||
"%s「%s」长度 %d 超出文件剩余字节(偏移 %d / %d)。": "{0}\"{1}\" length {2} is past the end of the file (offset {3} / {4}).",
|
||||
"PMX 解析错位(段落:%s):": "PMX out of step (section: {0}): ",
|
||||
"头部": "header", "顶点": "vertices", "面": "faces", "贴图": "textures", "材质": "materials", "骨骼": "bones",
|
||||
"表情": "morphs", "表示枠": "display frames", "刚体": "rigid bodies", "关节": "joints",
|
||||
"顶点[%d]": "vertex [{0}]", "材质[%d]": "material [{0}]", "骨骼[%d]": "bone [{0}]", "表情[%d]": "morph [{0}]",
|
||||
"表示枠[%d]": "display frame [{0}]", "刚体[%d]": "rigid body [{0}]", "关节[%d]": "joint [{0}]",
|
||||
"该模型是 PMX 2.1 且含 %d 个 SoftBody,本转换器暂不支持 SoftBody。":
|
||||
"This is a PMX 2.1 model with {0} SoftBodies; SoftBody isn't supported yet.",
|
||||
"未知的 PMX 表情类型 %d": "Unknown PMX morph type {0}",
|
||||
"不是 UEFormat 文件(魔数不是 UEFORMAT):%s": "Not a UEFormat file (magic isn't UEFORMAT): {0}",
|
||||
"不是模型文件(Identifier=%r):%s": "Not a model file (Identifier={0}): {1}",
|
||||
"UEFormat 版本 %d 高于本库支持的 %d:%s": "UEFormat version {0} is newer than the supported {1}: {2}",
|
||||
"解析失步:消费 %d 字节,文件 %d 字节(差 %d)": "Parsing went out of step: read {0} bytes of {1} (off by {2})",
|
||||
"不支持的压缩格式 %r:%s": "Unsupported compression {0}: {1}",
|
||||
"该 .uemodel 是 ZSTD 压缩体,但运行环境缺少 zstandard 库,无法解压:%s":
|
||||
"This .uemodel is ZSTD compressed but the zstandard library is missing: {0}",
|
||||
"ZSTD 解压失败:%s(%s)": "ZSTD decompression failed: {0} ({1})",
|
||||
"GZIP 解压失败:%s(%s)": "GZIP decompression failed: {0} ({1})",
|
||||
"不是 GLB/VRM 文件:%s": "Not a GLB / VRM file: {0}",
|
||||
"GLB 里没有 JSON chunk": "The GLB has no JSON chunk",
|
||||
"此文件中没有网格数据(PNTS / VTXW 为空)": "The file has no mesh data (PNTS / VTXW are empty)",
|
||||
"此文件中没有面数据(FACE 块为空)": "The file has no faces (the FACE block is empty)",
|
||||
"此 .uemodel 中没有 LOD 数据": "This .uemodel has no LODs",
|
||||
"此文件中没有网格数据": "The file has no mesh data",
|
||||
"骨骼数异常(%d),文件可能不是 XPS 或已损坏": "Bad bone count ({0}): not an XPS file, or damaged",
|
||||
"网格数异常(%d)": "Bad mesh count ({0})",
|
||||
"文件太小,不是 XPS 模型": "The file is too small to be an XPS model",
|
||||
"文件中没有骨骼数据": "The file has no bones",
|
||||
"文件中没有网格数据": "The file has no meshes",
|
||||
"文件在偏移 %d 处提前结束(还需 %d 字节,仅剩 %d)": "The file ends early at offset {0} ({1} more bytes needed, {2} left)",
|
||||
"网格 %d 的 UV 层数/贴图数异常(%d / %d)": "Mesh {0} has a bad UV layer / texture count ({1} / {2})",
|
||||
"网格 %d 的顶点数异常(%d)": "Mesh {0} has a bad vertex count ({1})",
|
||||
"网格 %d 的三角面数异常(%d)": "Mesh {0} has a bad triangle count ({1})",
|
||||
"XPS 头部异常(countOfUnknownInts=%d)": "Bad XPS header (countOfUnknownInts={0})",
|
||||
"字符串长度编码异常(偏移 %d)": "Bad string length encoding (offset {0})",
|
||||
"顶点权重根数异常(%d)": "Bad number of vertex weights ({0})",
|
||||
# ---- PMX → VRM
|
||||
"PMX:顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d":
|
||||
"PMX: {0} vertices · {1} triangles · {2} bones · {3} materials · {4} morphs",
|
||||
"权重:左右对称的 %d 对顶点,右侧主要绑在 %s(%s),左侧却绑在 %s(%s),动作时这部分会变形。可能是模型的权重错误,建议在 PmxEditor 中检查":
|
||||
"Weights: in {0} mirrored vertex pairs the right side follows {1} ({2}) but the left follows {3} ({4}), "
|
||||
"so this part will deform when moving. Probably a weight mistake in the model; check it in PmxEditor",
|
||||
"绕序自动判定(手性修正后):与法线同向 %d 面 / 反向 %d 面 → %s":
|
||||
"Winding (after the handedness fix): {0} faces agree with the normals / {1} oppose → {2}",
|
||||
"需要反转": "flip",
|
||||
"保持不变": "keep",
|
||||
"反转": "flipped",
|
||||
"无": "none",
|
||||
"Z 轴取反": "Z mirrored",
|
||||
"X 轴取反": "X mirrored",
|
||||
"缩放:%.5f(MMD 单位 → 米)· 手性修正:%s · 绕序:%s":
|
||||
"Scale: {0} (MMD units → metres) · handedness fix: {1} · winding: {2}",
|
||||
"视线:左右 %.1f° · 下 %.1f° · 上 %.1f°(%s)": "Gaze: sideways {0}° · down {1}° · up {2}° ({3})",
|
||||
"视线:%s": "Gaze: {0}",
|
||||
"按眼球结构计算,瞳孔最多移动约 %d%% 瞳孔宽度": "from the eyeball shape, the pupil moves at most about {0}% of its width",
|
||||
"算出 %.1f°,限制到 %.0f°": "{0}° computed, limited to {1}°",
|
||||
"眼骨上没有瞳孔顶点,使用默认值 10°": "no pupil vertices on the eye bones, using the default 10°",
|
||||
"眼骨上的顶点不像一只眼睛(宽 %.2f、支点到表面 %.2f,两眼相距 %.2f),使用默认值 10°":
|
||||
"the eye bone vertices don't look like an eye (width {0}, pivot to surface {1}, eyes {2} apart), "
|
||||
"using the default 10°",
|
||||
"网格:按材质分为 %d 个部分": "Mesh: {0} parts by material",
|
||||
"网格:按表情分为 %d 个(%s)": "Mesh: split into {0} by morphs ({1})",
|
||||
"%s:%d 个表情": "{0}: {1} morphs",
|
||||
"已写出 %s(%.2f MB)· 节点 %d · morph target %d · 表情 %d":
|
||||
"Wrote {0} ({1} MB) · {2} nodes · {3} morph targets · {4} expressions",
|
||||
"骨骼:已去掉 %d 个不起作用的节点(%s),保留 %d 个": "Bones: removed {0} nodes that do nothing ({1}), {2} kept",
|
||||
"无权重且不属于 humanoid、物理的骨,包括中间的控制骨":
|
||||
"unweighted, not humanoid or physics, including the intermediate control bones",
|
||||
"IK、末端骨、已合并的付与骨等无权重且不属于 humanoid、物理的骨":
|
||||
"IK, tip and merged append bones and others that are unweighted and not humanoid or physics",
|
||||
"表情:补充视线表情 %s(由转动眼骨烘焙,lookAt 仍使用骨骼)":
|
||||
"Expressions: added gaze expressions {0} (baked from turning the eye bones; lookAt still uses the bones)",
|
||||
# ---- 骨骼(skeleton / humanoid)
|
||||
"朝向:模型%s,已绕 Y 轴旋转 %d° 校正(左右肩 / 胯不在 X 轴上)":
|
||||
"Facing: the model {0}, turned {1}° about Y (shoulders / hips weren't along X)",
|
||||
"背向前方": "faces backwards",
|
||||
"朝向侧面": "faces sideways",
|
||||
"付与骨合并:%d 根(%s)→ 权重并入付与親": "Append bones merged: {0} ({1}) → weights moved to their append parents",
|
||||
"付与骨合并:%s 与付与親的位置略有偏差,合并后绕付与親的位置转动":
|
||||
"Append bones merged: {0} sat slightly off their append parents and now turn about the parents' positions",
|
||||
"材质:%d 个 Unity 材质开了描边(_Outline_Width),已转成 MToon 轮廓线":
|
||||
"Materials: {0} Unity materials have outlines (_Outline_Width), converted to MToon outlines",
|
||||
"材质:%d 个材质是描边外壳或内侧面(%s),「所有材质双面」时仍保持单面,否则会盖住模型或重叠闪烁":
|
||||
"Materials: {0} are outline shells or inner sides ({1}) and stay single-sided with \"All materials double-sided\"; "
|
||||
"otherwise they would cover the model or flicker against the outer layer",
|
||||
"贴图:%d 张不在模型记录的位置,已按文件名在模型文件夹里找到(%s)":
|
||||
"Textures: {0} weren't where the model says; found them by name in the model folder ({1})",
|
||||
"贴图:%d 张找不到(%s),用到它们的材质只有底色。贴图要和模型放在一起:请加入整个文件夹或压缩包":
|
||||
"Textures: {0} not found ({1}); materials using them show only their base color. Textures must be next to "
|
||||
"the model: add the whole folder or archive",
|
||||
"贴图:%d 张读取失败(%s),用到它们的材质只有底色": "Textures: {0} couldn't be read ({1}); materials using them show only their base color",
|
||||
"系统里没有 WebView2 运行时(Windows 的网页组件),所以用浏览器打开。安装后重新打开程序就是独立窗口。":
|
||||
"WebView2 (the Windows web component) is not installed, so VRMify Enhanced opened in the browser. "
|
||||
"Install it and start VRMify Enhanced again to get its own window.",
|
||||
"没有安装 pywebview,所以用浏览器打开(pip install pywebview 后就是独立窗口)。":
|
||||
"pywebview is not installed, so VRMify Enhanced opened in the browser (pip install pywebview for its own window).",
|
||||
"上传中断": "Upload interrupted",
|
||||
"独立窗口启动失败(%s),所以用浏览器打开。": "VRMify Enhanced's window failed to start ({0}), so it opened in the browser.",
|
||||
"拖放不可用(%s),请用「添加文件」": "Drag and drop is unavailable ({0}); use \"Add files\"",
|
||||
"浏览器模式下只加入了 %s 本身,旁边的贴图没有一起传过来,转出来可能没有贴图:请拖入整个模型文件夹或压缩包":
|
||||
"In browser mode only {0} itself was added; the textures next to it weren't passed along, so the result may "
|
||||
"have no textures: drop the whole model folder or archive",
|
||||
"付与骨:%d 根按比例跟随关节的骨(%s)→ 权重按付与率分给关节骨,共 %d 个顶点":
|
||||
"Append bones: {0} bones that follow a joint partly ({1}) → their weights were shared with the joint "
|
||||
"by the append rate, {2} vertices",
|
||||
"自检:%d 个顶点主要挂在 %s 上,MMD 里跟着 %s 转 %d%%,VRM 里只跟 %d%%,动作时这部分会变形":
|
||||
"Self-check: {0} vertices mainly on {1} turn {3}% with {2} in MMD but only {4}% in the VRM; "
|
||||
"this part will deform when animated",
|
||||
"自检:humanoid 骨 %s(%s)在身体的另一侧,可能对应错了骨骼,动作时这部分会被拉开":
|
||||
"Self-check: humanoid bone {0} ({1}) is on the other side of the body; it may be the wrong bone, "
|
||||
"and this part will be pulled away when animated",
|
||||
"自检:humanoid 骨 %s(%s)离 %s 有 %d cm,可能对应错了骨骼,动作时这部分会被拉开":
|
||||
"Self-check: humanoid bone {0} ({1}) is {3} cm from {2}; it may be the wrong bone, "
|
||||
"and this part will be pulled away when animated",
|
||||
"自检:humanoid 骨 %s(%s)离网格超过 %d cm,可能对应错了骨骼,动作时这部分会被拉开":
|
||||
"Self-check: humanoid bone {0} ({1}) is more than {2} cm from the mesh; it may be the wrong bone, "
|
||||
"and this part will be pulled away when animated",
|
||||
"hips:已移至骨盆,下移 %.1f cm(原与 spine 相距 %.1f mm)": "hips: moved down to the pelvis by {0} cm (was {1} mm from spine)",
|
||||
"骨骼:模型缺少 %s,已生成占位骨骼": "Bones: the model has no {0}, added a placeholder bone",
|
||||
"骨骼:%s 与 %s 对应同一根骨骼,已忽略 %s": "Bones: {0} and {1} are the same bone, {2} ignored",
|
||||
"骨骼层级:%s(%s)不在 %s(%s)之下,已移至其下(原父骨骼 %s)":
|
||||
"Bone hierarchy: {0} ({1}) wasn't under {2} ({3}), moved there (parent was {4})",
|
||||
"骨骼层级:%s(%s)无法修正,已从 humanoid 中移除": "Bone hierarchy: {0} ({1}) can't be fixed, removed from the humanoid",
|
||||
"骨骼层级:%s(%s)无法修正,部分软件可能无法加载": "Bone hierarchy: {0} ({1}) can't be fixed, some programs may not load it",
|
||||
"T-pose:%s 上臂 %.1f° · 前臂 %.1f°": "T-pose: {0} upper arm {1}° · forearm {2}°",
|
||||
"T-pose:%s 手 %.1f° · 掌心 %.1f° · 四指最多 %.1f° · 拇指最多 %.1f°":
|
||||
"T-pose: {0} hand {1}° · palm {2}° · fingers up to {3}° · thumb up to {4}°",
|
||||
"骨骼:拇指只有两节(%s),已在手腕和第二节之间补上掌根那节,0.x 和 1.0 的拇指各节对应一致":
|
||||
"Bones: two-segment thumbs ({0}), so the root segment was added between the wrist and the second "
|
||||
"segment and the thumb segments match between 0.x and 1.0",
|
||||
"左": "left",
|
||||
"右": "right",
|
||||
"肩": "shoulder", "上臂": "upper arm", "前臂": "forearm", "手": "hand",
|
||||
"大腿": "thigh", "小腿": "lower leg", "脚": "foot", "脚趾": "toes",
|
||||
# ---- 物理(springbone / autophys)
|
||||
"物理:模型不含物理刚体,已按骨骼名和骨架结构自动添加 %d 根摆动骨(头发、裙摆、袖子、飘带、兽耳等)和 %d 个身体碰撞体":
|
||||
"Physics: the model has no rigid bodies, so {0} swaying bones (hair, skirts, sleeves, ribbons, "
|
||||
"animal ears …) and {1} body colliders were added from the bone names and the skeleton",
|
||||
"物理:识别到 %d 根兽耳骨,已加入摆动链":
|
||||
"Physics: {0} animal-ear bones detected and added to the swaying chains",
|
||||
"SpringBone:%d 条链(裙摆类 %d、头发等 %d)· 碰撞体 %d · 碰撞组 %d":
|
||||
"SpringBone: {0} chains ({1} skirt-like, {2} hair and others) · {3} colliders · {4} collider groups",
|
||||
"SpringBone:MMD 物理骨 %d 根 → SpringBone 关节 %d 个(头发等每节至少 %.0f cm、裙摆至少 %.0f cm,中间的骨骼刚性跟随)":
|
||||
"SpringBone: {0} MMD physics bones → {1} SpringBone joints (at least {2} cm per segment for hair, "
|
||||
"{3} cm for skirts; the bones in between follow rigidly)",
|
||||
"SpringBone:按设置跳过 %d 条下半身物理链(裙摆等)": "SpringBone: skipped {0} lower-body chains (skirts …) as set",
|
||||
"SpringBone:按设置跳过 %d 条下半身物理链,没有可输出的链": "SpringBone: skipped {0} lower-body chains as set, no chains left",
|
||||
"SpringBone:%d 条短链(不足 %.0f cm,四肢上不足 %.0f cm)不转换,以免末端高频抖动":
|
||||
"SpringBone: {0} short chains (under {1} cm, under {2} cm on limbs) left out to avoid jittery tips",
|
||||
"SpringBone:%d 条链的末端没有子骨骼,已补充末端节点": "SpringBone: {0} chains had no bone past their end, tip nodes added",
|
||||
"SpringBone:静止姿势下与碰撞体重叠,已%s": "SpringBone: overlapping colliders at rest, so {0}",
|
||||
"取消 %d 处链与碰撞体的碰撞": "turned off {0} chain–collider pairs",
|
||||
"缩小 %d 个节点的碰撞半径": "shrank the hit radius of {0} nodes",
|
||||
"SpringBone:%d 个链间横向关节(裙摆等)无法表达,已舍弃%s":
|
||||
"SpringBone: {0} sideways joints between chains (skirts …) can't be expressed and were dropped{1}",
|
||||
";已按裙片朝向修正 %d 处裙摆与腿的碰撞方向,减少裙片被腿分开":
|
||||
"; {0} skirt–leg collisions were adjusted to the skirt panels' direction so the legs split the skirt less",
|
||||
"已按裙片朝向修正 %d 处裙摆与腿的碰撞方向,减少裙片被腿分开":
|
||||
"{0} skirt–leg collisions were adjusted to the skirt panels' direction so the legs split the skirt less",
|
||||
"SpringBone:已按裙片朝向修正 %d 处裙摆与腿的碰撞方向":
|
||||
"SpringBone: {0} skirt–leg collisions adjusted to the skirt panels' direction",
|
||||
"SpringBone(0.x):%d 根随关节刚性转动的骨(中间节、链末端的配饰)权重并到关节上(%d 个顶点),0.x 会让组里所有子骨都摆动":
|
||||
"SpringBone (0.x): the weights of {0} bones that only follow a joint rigidly (in-between segments, "
|
||||
"accessories at chain ends) were moved onto that joint ({1} vertices), since 0.x sways every bone in a group",
|
||||
"SpringBone(0.x):%d 条链 → %d 个摆动组%s · 碰撞组 %d(胶囊换成 %d 个球)":
|
||||
"SpringBone (0.x): {0} chains → {1} spring groups{2} · {3} collider groups (capsules as {4} spheres)",
|
||||
"(%d 条分叉链并入上层链的组)": " ({0} branching chains joined the group of the chain they hang from)",
|
||||
"SpringBone(0.x):每组只有一个碰撞半径,静止时会重叠的碰撞体缩小 %d 处、取消 %d 处":
|
||||
"SpringBone (0.x): one hit radius per group, so colliders that would overlap at rest were shrunk "
|
||||
"{0} times and turned off {1} times",
|
||||
# ---- 表情
|
||||
"表情预设:%s": "Preset expressions: {0}",
|
||||
"%s · 未找到:%s": "{0} · not found: {1}",
|
||||
"表情:导出 %d 个 morph target(%s存储)": "Expressions: {0} morph targets ({1})",
|
||||
"稀疏": "sparse",
|
||||
"密集": "dense",
|
||||
"表情:%d 个包含材质变化(转为材质颜色绑定)": "Expressions: {0} change materials (written as material colour binds)",
|
||||
"表情:%d 个 UV 表情转为贴图偏移": "Expressions: {0} UV morphs written as texture offsets",
|
||||
"表情:%d 处 UV 表情不是整个材质统一平移 / 缩放,VRM 无法表示,已跳过":
|
||||
"Expressions: {0} UV morphs don't move or scale a whole material evenly, which VRM can't express; skipped",
|
||||
"表情:补充 hideHighlight(%s)": "Expressions: added hideHighlight ({0})",
|
||||
"表情:补充 hideHighlight(隐藏材质 %s)": "Expressions: added hideHighlight (hides the materials {0})",
|
||||
"表情:未找到眼睛高光材质或关闭高光的表情,未补充 hideHighlight":
|
||||
"Expressions: no eye highlight material or highlight-off morph found, hideHighlight not added",
|
||||
"表情:补充 tongue(%s)": "Expressions: added tongue ({0})",
|
||||
# ---- 材质 / 贴图
|
||||
"材质透明模式:不透明 %d · 裁剪(MASK)%d · 半透明(BLEND)%d":
|
||||
"Material transparency: {0} opaque · {1} cutout (MASK) · {2} semi-transparent (BLEND)",
|
||||
"材质:%d 个材质的贴图有透明部分,但模型只用到不透明的区域,按不透明处理":
|
||||
"Materials: {0} materials' textures have transparent parts the model doesn't use; treated as opaque",
|
||||
"材质:%d 个加算球面贴图转为 MToon 的 matcap": "Materials: {0} additive sphere maps became MToon matcaps",
|
||||
"材质:%d 个材质的乘算球面贴图(.sph)在 MToon 中没有对应项,已忽略":
|
||||
"Materials: {0} multiplicative sphere maps (.sph) have no MToon equivalent and were left out",
|
||||
"贴图:未安装 Pillow,缩小贴图和 JPEG 存储未生效": "Textures: Pillow isn't installed, so resizing and JPEG storage were skipped",
|
||||
"贴图:%d 张瘦身(%s%s)%.1f MB → %.1f MB": "Textures: {0} slimmed ({1}{2}) {3} MB → {4} MB",
|
||||
"最大边长 %d": "max size {0}",
|
||||
"不透明转 JPEG": "opaque ones as JPEG",
|
||||
"、不透明转 JPEG": ", opaque ones as JPEG",
|
||||
# ---- FBX → PMX
|
||||
"FBX 版本 %d · 对象 %d 个": "FBX version {0} · {1} objects",
|
||||
"模型 %d 个(其中骨骼 %d)· 几何体 %d · 材质 %d": "{0} models ({1} bones) · {2} geometries · {3} materials",
|
||||
"顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d · 缩放 %.4f":
|
||||
"{0} vertices · {1} triangles · {2} bones · {3} materials · {4} morphs · scale {5}",
|
||||
"大小 %.2f MB(顶点索引 %d 字节)": "Size {0} MB ({1}-byte vertex indices)",
|
||||
"朝向:%s%s": "Facing: {0}{1}",
|
||||
",旋转 180°": ", turned 180°",
|
||||
"未启用自动判定,按设置%s": "auto-detection off, {0} as set",
|
||||
"旋转 180°": "turned 180°",
|
||||
"不旋转": "not turned",
|
||||
"未找到脚尖骨骼": "no toe bones found",
|
||||
"脚尖骨骼(%s)朝向 X 轴,旋转 180° 无法修正": "the toe bones ({0}) point along X, turning 180° can't fix that",
|
||||
"按脚尖骨骼(%s)判定正面朝 %s": "the toe bones ({0}) show the front faces {1}",
|
||||
"脸部网格过少": "too few face meshes",
|
||||
"脸部网格前后偏移不明显": "the face meshes don't sit clearly to the front or back",
|
||||
"按脸部网格的位置判定正面朝 %s": "the face meshes show the front faces {0}",
|
||||
"%s,无法自动判定,按设置%s": "{0}, can't decide automatically, {1} as set",
|
||||
"绕序:%s": "Winding: {0}",
|
||||
"与顶点法线相反,已反转": "opposite to the vertex normals, flipped",
|
||||
"与顶点法线一致": "matches the vertex normals",
|
||||
"跳过无材质的网格 %d 个:%s": "Skipped {0} meshes without materials: {1}",
|
||||
"%s(%d 个三角面)": "{0} ({1} triangles)",
|
||||
"跳过无材质的网格 %s(%d 个三角面,通常是特效面片)": "Skipped the mesh {0} without a material ({1} triangles, usually an effect plane)",
|
||||
"贴图:已复制 %d / %d 个文件到 textures 文件夹": "Textures: copied {0} / {1} files to the textures folder",
|
||||
"贴图:%d 个引用的文件未找到(可稍后放入 textures 文件夹)":
|
||||
"Textures: {0} referenced files not found (they can be put into the textures folder later)",
|
||||
"贴图:已去除 %d 张贴图的透明通道": "Textures: removed the alpha channel of {0} textures",
|
||||
"贴图透明通道:去除 %d 张,保留 %d 张,%d 张本身不透明": "Texture alpha: removed in {0}, kept in {1}, {2} have none",
|
||||
"贴图:%d 张去除透明通道失败,已使用原图": "Textures: removing the alpha channel failed for {0}, the originals were used",
|
||||
"替换网格:显示 %s,%s 默认隐藏并做成切换表情": "Alternative meshes: showing {0}; {1} hidden by default, with morphs to switch",
|
||||
"居中:偏移 (%.2f, %.2f, %.2f)": "Centred: offset ({0}, {1}, {2})",
|
||||
"表情:由 %d 个 BlendShape 生成 %d 个顶点表情": "Morphs: {1} vertex morphs from {0} BlendShapes",
|
||||
"表情:共 %d 个,按上限只导出前 %d 个": "Morphs: {0} in total, only the first {1} exported (limit)",
|
||||
# ---- PSK / XPS / uemodel → PMX,PMX → FBX
|
||||
"提示:同一目录下有同名的 %s。PmxEditor 打开此 PMX 时会尝试将其作为「アンカーデータ」(锚点 / 权重数据)加载,并提示「アンカーデータの読み込みに失敗しました。」,点击确定即可,不影响模型。如需避免,可移动或重命名 PMX,或在 PmxEditor 中关闭[ファイル]→[アンカーデータの自動読み込み/保存]。":
|
||||
"Note: there is a {0} with the same name in the folder. PmxEditor will try to load it as anchor data when "
|
||||
"opening this PMX and report that it failed; click OK, the model is fine. To avoid it, move or rename the "
|
||||
"PMX, or turn off automatic anchor data loading in PmxEditor's File menu.",
|
||||
"读取 %s:顶点 %d · 楔 %d · 三角面 %d · 材质 %d · 骨骼 %d · 权重 %d":
|
||||
"Read {0}: {1} vertices · {2} wedges · {3} triangles · {4} materials · {5} bones · {6} weights",
|
||||
"表情 %d 个 · 附加 UV %d 套 · %s": "{0} morphs · {1} extra UV sets · {2}",
|
||||
"含法线": "with normals",
|
||||
"不含法线(将自动计算)": "no normals (they will be computed)",
|
||||
"骨骼:%d 根%s": "Bones: {0}{1}",
|
||||
"(其中 %d 根改为 MMD 标准日文名,原英文名保留在英文名中)":
|
||||
" ({0} renamed to the standard MMD Japanese names, the original names kept as English names)",
|
||||
"材质:%d 个 · 关联到贴图 %d 个%s": "Materials: {0} · {1} with textures{2}",
|
||||
"(源目录中没有同名贴图,导出为无贴图模型)": " (no matching textures in the source folder, exported without textures)",
|
||||
"已写出 %s(%.2f MB)· 顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d":
|
||||
"Wrote {0} ({1} MB) · {2} vertices · {3} triangles · {4} bones · {5} materials · {6} morphs",
|
||||
"已写出 %s(%.2f MB)· 顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d":
|
||||
"Wrote {0} ({1} MB) · {2} vertices · {3} triangles · {4} bones · {5} materials",
|
||||
"网格:%d 个楔的点索引越界,已改用第 0 个点": "Mesh: {0} wedges pointed past the vertex list, now use vertex 0",
|
||||
"缩放:源高 %.2f 单位 × %.6f → %.2f(MMD 标准身高 20)": "Scale: source height {0} units × {1} → {2} (MMD standard height 20)",
|
||||
"缩放:源高 %.3f 单位 × %.6f → %.2f(MMD 标准身高 20)": "Scale: source height {0} units × {1} → {2} (MMD standard height 20)",
|
||||
"缩放:保持源尺寸(scale=1.0),源高 %.2f 单位": "Scale: kept as is (scale=1.0), source height {0} units",
|
||||
"缩放:保持源尺寸(scale=1.0),源高 %.3f 单位": "Scale: kept as is (scale=1.0), source height {0} units",
|
||||
"缩放:源高 %.2f 单位 × %.6f → %.2f": "Scale: source height {0} units × {1} → {2}",
|
||||
"缩放:源高 %.3f 单位 × %.6f → %.2f": "Scale: source height {0} units × {1} → {2}",
|
||||
"缩放:源高 %.2f cm × %.6f → %.2f": "Scale: source height {0} cm × {1} → {2}",
|
||||
"居中:偏移 (%.3f, %.3f, %.3f)": "Centred: offset ({0}, {1}, {2})",
|
||||
"居中:按参考模型包围盒(偏移 (%.3f, %.3f, %.3f))": "Centred on the reference model's bounding box (offset ({0}, {1}, {2}))",
|
||||
"权重:%d 个顶点没有权重,已绑定到第 0 根骨骼": "Weights: {0} vertices had no weights, bound to bone 0",
|
||||
"权重:已丢弃 %d 条第 5 根及以后的骨骼权重(PMX 每个顶点最多 4 根)":
|
||||
"Weights: dropped {0} weights beyond the 4th bone per vertex (PMX allows 4)",
|
||||
"提示:%d 条第 5 及以后的骨骼权重被丢弃(PMX 最多 4 根)": "Note: dropped {0} weights beyond the 4th bone (PMX allows 4)",
|
||||
"表情:%d 个(顶点表情)": "Morphs: {0} (vertex morphs)",
|
||||
"足 IK:已补充 %d 根(足IK / つま先IK,父骨骼 センター)": "Leg IK: added {0} bones (足IK / つま先IK under センター)",
|
||||
"足 IK:源骨架中没有完整的腿部骨链,未补充 IK 骨": "Leg IK: the source skeleton has no complete leg chains, no IK bones added",
|
||||
"绕序自动判定:与法线同向 %d 面 / 反向 %d 面 → %s": "Winding: {0} faces agree with the normals / {1} oppose → {2}",
|
||||
"绕序:缺少法线数据,按坐标轴反射统一反转(保持正面朝外)":
|
||||
"Winding: no normals, flipped everywhere for the axis mirroring (front faces stay outside)",
|
||||
"绕序:法线数据不完整,按坐标轴反射统一反转(保持正面朝外)":
|
||||
"Winding: incomplete normals, flipped everywhere for the axis mirroring (front faces stay outside)",
|
||||
"绕序:%d 个顶点没有法线,判定时使用平均法线": "Winding: {0} vertices had no normals, the average normal was used",
|
||||
"已写出 %s(ASCII FBX 7.4 · %.2f MB)": "Wrote {0} (ASCII FBX 7.4 · {1} MB)",
|
||||
"FBX 导出失败:%s": "FBX export failed: {0}",
|
||||
"读取 %s:骨骼 %d 根 · 网格 %d 个 · 顶点 %d · 三角面 %d": "Read {0}: {1} bones · {2} meshes · {3} vertices · {4} triangles",
|
||||
"骨骼:%d 根%s%s": "Bones: {0}{1}{2}",
|
||||
";%d 根 unused 占位骨单独放进 unused 表示枠": "; {0} unused placeholder bones put into their own unused display frame",
|
||||
"%d 根 unused 占位骨单独放进 unused 表示枠": "{0} unused placeholder bones put into their own unused display frame",
|
||||
"贴图:源目录中未找到 %s": "Textures: {0} not found in the source folder",
|
||||
"对齐:匹配 %d 根骨骼,其中 %d 根位置一致(残差 ≤ %.4f cm)": "Alignment: matched {0} bones, {1} in the same place (residual ≤ {2} cm)",
|
||||
"对齐:平移 (%.4f, %.4f, %.4f) cm": "Alignment: moved by ({0}, {1}, {2}) cm",
|
||||
"UEFormat v%d · %s · 骨骼 %d · LOD %d": "UEFormat v{0} · {1} · {2} bones · {3} LODs",
|
||||
"使用 LOD[%d] %s:顶点 %d · 三角面 %d · 材质 %d · 表情 %d · UV %d":
|
||||
"Using LOD[{0}] {1}: {2} vertices · {3} triangles · {4} materials · {5} morphs · {6} UV sets",
|
||||
"骨骼:%d 根(原始 %d 根)": "Bones: {0} ({1} originally)",
|
||||
"材质:%d 个 · 关联到贴图 %d 个 · 拷贝贴图 %d 张%s": "Materials: {0} · {1} with textures · {2} textures copied{3}",
|
||||
"(注意:%d 个材质的面区间不连续)": " (note: {0} materials have non-contiguous face ranges)",
|
||||
"对齐:部件的 %d 根骨骼中没有与参考模型同名或相近的骨骼,已跳过对齐":
|
||||
"Alignment: none of the part's {0} bones match the reference model by name, skipped",
|
||||
"对齐:位置一致的骨骼只有 %d 根(共匹配 %d 根 · 最大残差 %.4f cm),结果不可靠,已跳过":
|
||||
"Alignment: only {0} bones in the same place ({1} matched · max residual {2} cm), unreliable, skipped",
|
||||
"对齐:参考模型的骨架跨度 %.1f cm,小于本文件的 %.1f cm,参考模型本身可能是部件(参考与部件可能选反了),已跳过对齐":
|
||||
"Alignment: the reference skeleton spans {0} cm, less than this file's {1} cm; the reference may itself be "
|
||||
"a part (reference and part swapped?), skipped",
|
||||
"提示:该文件有 %d 个 LOD,只导出第 %d 个": "Note: the file has {0} LODs, only LOD {1} exported",
|
||||
"对齐后:源高 %.2f cm → %.2f cm(缩放不变)": "After alignment: source height {0} cm → {1} cm (scale unchanged)",
|
||||
"对齐:已按 %s 对齐(源坐标整体平移)": "Alignment: aligned to {0} (source coordinates moved as a whole)",
|
||||
"对齐失败(匹配 %d / %d),按模型自身原点导出": "Alignment failed ({0} / {1} matched), exported at the model's own origin",
|
||||
"对齐失败:%s(按模型自身原点导出)": "Alignment failed: {0} (exported at the model's own origin)",
|
||||
"FBX:%d 顶点 · %d 三角面 · %d 骨骼 · %d 材质(ASCII 7.4,%s-up,前方 %s)%s":
|
||||
"FBX: {0} vertices · {1} triangles · {2} bones · {3} materials (ASCII 7.4, {4}-up, front {5}){6}",
|
||||
"· %d 个顶点表情写入 BlendShape": " · {0} vertex morphs written as BlendShapes",
|
||||
"FBX:%d 个 Cluster · %d 个表情 Shape · 引用贴图 %d 张 · %.2f MB":
|
||||
"FBX: {0} clusters · {1} morph shapes · {2} textures referenced · {3} MB",
|
||||
"PSK:顶点 %d · 楔 %d · 面 %d · 骨骼 %d · 材质 %d · 权重 %d%s":
|
||||
"PSK: {0} vertices · {1} wedges · {2} faces · {3} bones · {4} materials · {5} weights{6}",
|
||||
" · 表情 %d": " · {0} morphs",
|
||||
"提示:%d 个楔的点索引越界,已夹回合法范围": "Note: {0} wedges pointed past the vertex list, clamped",
|
||||
"提示:顶点数 %d 超过 16 位索引上限,已改用 FACE3200": "Note: {0} vertices exceed 16-bit indices, FACE3200 used",
|
||||
"提示:%d 个面的楔索引越界(文件可能显示为破面)": "Note: {0} faces point past the wedge list (the file may show holes)",
|
||||
"XPS 格式:旧版 XNALara 二进制格式(无 Generic Item 2 头)": "XPS format: old XNALara binary (no Generic Item 2 header)",
|
||||
"XPS 格式:Generic Item 2 · 版本 %d.%d · 作者 %s": "XPS format: Generic Item 2 · version {0}.{1} · author {2}",
|
||||
"XPS 格式:旧版格式含切线数据(转换时忽略)": "XPS format: old format with tangents (ignored)",
|
||||
"网格 %d 有 %d 个三角面索引越界,已跳过": "Mesh {0}: {1} triangles point past the vertex list, skipped",
|
||||
}
|
||||
# 转换失败时日志里的整段 traceback、程序本身的英文消息:不翻译
|
||||
|
||||
_PH = re.compile(r"%(?:\([^)]*\))?[-+ #0]*\d*(?:\.\d+)?[dsfrgx]|%%")
|
||||
|
||||
|
||||
def _compile(zh):
|
||||
out, pos = [], 0
|
||||
for m in _PH.finditer(zh):
|
||||
out.append(re.escape(zh[pos:m.start()]))
|
||||
ph = m.group()
|
||||
if ph == "%%":
|
||||
out.append("%")
|
||||
elif ph[-1] == "d":
|
||||
out.append(r"(-?\d+)")
|
||||
elif ph[-1] in "fg":
|
||||
out.append(r"(-?[\d.]+(?:e[-+]?\d+)?|nan|inf)")
|
||||
else:
|
||||
out.append(r"(.*?)")
|
||||
pos = m.end()
|
||||
out.append(re.escape(zh[pos:]))
|
||||
return re.compile("".join(out), re.S)
|
||||
|
||||
|
||||
# 固定文字多的先试:「已写出 %s」不能抢在「已写出 %s(%.2f MB)· …」前面
|
||||
_RULES = sorted(((_compile(zh.strip()), en) for zh, en in TEMPLATES.items() if _PH.search(zh)),
|
||||
key=lambda r: -len(_PH.sub("", r[0].pattern)))
|
||||
_FIXED = {zh.strip(): en for zh, en in TEMPLATES.items() if not _PH.search(zh)}
|
||||
_ERROR = re.compile(r"([A-Za-z_][\w.]*(?:Error|Exception|Warning)): (.*)", re.S)
|
||||
_CJK = re.compile("[ -〿-ヿ一-鿿-]")
|
||||
|
||||
|
||||
def _arg(s):
|
||||
"""参数:程序生成的中文翻成英文,模型里的名字原样。列表(、/ ;)逐项处理:
|
||||
「身体:13 个表情、头绳:1 个表情」不能整个当成一句「%s:%d 个表情」。"""
|
||||
if not s or not _CJK.search(s):
|
||||
return s
|
||||
if s in _FIXED:
|
||||
return _FIXED[s]
|
||||
for sep, out in ((";", "; "), ("、", ", ")):
|
||||
if sep in s:
|
||||
# 整句对得上、拆开的各项一个都对不上(「按脚尖骨骼(Toe.L、Toe.R)判定…」)就按整句
|
||||
parts = s.split(sep)
|
||||
whole = _translate(s)
|
||||
if whole is not None and not any(_CJK.search(p) and _translate(p) is not None for p in parts):
|
||||
return whole
|
||||
return out.join(_arg(p) for p in parts)
|
||||
t = _translate(s)
|
||||
if t is not None:
|
||||
return t
|
||||
m = _ERROR.fullmatch(s)
|
||||
if m:
|
||||
return "%s: %s" % (m.group(1), _arg(m.group(2)))
|
||||
return s
|
||||
|
||||
|
||||
def _translate(s):
|
||||
if s in _FIXED:
|
||||
return _FIXED[s]
|
||||
for rx, en in _RULES:
|
||||
m = rx.fullmatch(s)
|
||||
if m:
|
||||
return en.format(*(_arg(g) for g in m.groups()))
|
||||
return None
|
||||
|
||||
|
||||
def to_en(msg):
|
||||
"""一条日志的英文(开头的「[模型名] 」保留);对照表里没有的返回 None。"""
|
||||
if not msg or not _CJK.search(msg):
|
||||
return None
|
||||
m = re.match(r"((?:\[[^\]\n]*\] )*)(.*)", msg, re.S)
|
||||
prefix, body = m.group(1), m.group(2).strip()
|
||||
if "\n" in body: # traceback 之类
|
||||
return None
|
||||
t = _translate(body)
|
||||
if t is None:
|
||||
e = _ERROR.fullmatch(body)
|
||||
if e:
|
||||
inner = _translate(e.group(2))
|
||||
t = inner and "%s: %s" % (e.group(1), inner)
|
||||
return prefix + t if t is not None else None
|
||||
@@ -0,0 +1,240 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""多进程并行转换:几个文件(或一个包里的几个模型)同时转。
|
||||
|
||||
转换是纯 Python、吃 CPU 的活,线程受 GIL 限制快不了,所以开子进程(spawn)。每个任务的日志经队列送回主进程,
|
||||
交给这个任务自己的 log 回调(界面按文件分开显示);任务结束的回调在主进程里、并且在它的日志都送完之后调用。
|
||||
|
||||
results = parallel.run([(key, func, args, kwargs), ...], jobs, log_for, start=None, done=None, should_stop=None)
|
||||
|
||||
func 必须是模块顶层函数(子进程要能按名字导入),调用方式是 func(*args, log=..., **kwargs)。
|
||||
子进程里不再开并行(in_worker()),免得「4 个文件 × 每个包 4 个模型」叠出 16 个进程。
|
||||
单个转换内部贴图解码用的线程数见 threads()。
|
||||
打包的 exe 要在入口调用 multiprocessing.freeze_support()(ui/app.py),否则子进程会再开一个程序。
|
||||
"""
|
||||
import concurrent.futures as cf
|
||||
import functools
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
import traceback
|
||||
|
||||
WORKER_ENV = "VRMIFY_WORKER"
|
||||
MAX_AUTO = 8 # 自动时最多同时跑几个:再多也快不了多少(内存带宽、硬盘、进程启动),还多占内存
|
||||
GB_PER_JOB = 1.5 # 不知道任务多大时按这么多算(十几万顶点的模型转换时进程峰值约 0.5 GB)
|
||||
MEM_SHARE = 0.8 # 并行的任务加起来最多占可用内存的这么多
|
||||
|
||||
|
||||
def in_worker():
|
||||
return os.environ.get(WORKER_ENV) == "1"
|
||||
|
||||
|
||||
def free_memory_gb():
|
||||
"""可用物理内存(GB);拿不到时按 8 GB 算。"""
|
||||
try:
|
||||
if os.name == "nt":
|
||||
import ctypes
|
||||
|
||||
class MS(ctypes.Structure):
|
||||
_fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
|
||||
("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
|
||||
("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
|
||||
("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
|
||||
("ullAvailExtendedVirtual", ctypes.c_ulonglong)]
|
||||
m = MS()
|
||||
m.dwLength = ctypes.sizeof(m)
|
||||
if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)):
|
||||
return m.ullAvailPhys / 1024 ** 3
|
||||
else:
|
||||
return os.sysconf("SC_AVPHYS_PAGES") * os.sysconf("SC_PAGE_SIZE") / 1024 ** 3
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
return 8.0
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=None)
|
||||
def cores():
|
||||
"""物理核数(超线程的两个逻辑核算一个);拿不到时按逻辑核数。"""
|
||||
n = 0
|
||||
try:
|
||||
if os.name == "nt":
|
||||
import ctypes
|
||||
|
||||
class INFO(ctypes.Structure): # SYSTEM_LOGICAL_PROCESSOR_INFORMATION
|
||||
_fields_ = [("mask", ctypes.c_size_t), ("relationship", ctypes.c_int),
|
||||
("_", ctypes.c_ulonglong * 2)]
|
||||
k32, size = ctypes.windll.kernel32, ctypes.c_ulong(0)
|
||||
k32.GetLogicalProcessorInformation(None, ctypes.byref(size))
|
||||
buf = (INFO * (size.value // ctypes.sizeof(INFO)))()
|
||||
if k32.GetLogicalProcessorInformation(buf, ctypes.byref(size)):
|
||||
n = sum(1 for i in buf if i.relationship == 0) # RelationProcessorCore
|
||||
elif os.path.exists("/proc/cpuinfo"):
|
||||
seen, phys = set(), "0"
|
||||
with open("/proc/cpuinfo", encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
key, _, val = line.partition(":")
|
||||
if key.strip() == "physical id":
|
||||
phys = val.strip()
|
||||
elif key.strip() == "core id":
|
||||
seen.add((phys, val.strip()))
|
||||
n = len(seen)
|
||||
except (OSError, ValueError, AttributeError):
|
||||
n = 0
|
||||
return n or os.cpu_count() or 1
|
||||
|
||||
|
||||
def threads():
|
||||
"""一个转换内部同时处理几张贴图(Pillow 在 C 里解码 / 编码、不占 GIL,线程就够):最多 4 个;
|
||||
在并行转换的子进程里最多 2 个(核和内存已经被别的子进程占着,一张 4K 贴图解开约 64 MB)。"""
|
||||
return max(1, min(2 if in_worker() else 4, os.cpu_count() or 1))
|
||||
|
||||
|
||||
def auto_jobs():
|
||||
"""自动时最多同时跑几个(还没看内存):物理核数 − 1(留一个给界面和系统),最多 MAX_AUTO。
|
||||
8 核 16 线程上 20 个包:4 个 11.6 秒、8 个 9.1 秒、16 个 8.3 秒——超过物理核数快不了多少。"""
|
||||
return max(1, min(MAX_AUTO, cores() - 1))
|
||||
|
||||
|
||||
def jobs_for(n_tasks, setting=0, mem_gb=None):
|
||||
"""同时跑几个:setting > 0 时按设置;0 = 自动(auto_jobs,再看可用内存)。
|
||||
|
||||
mem_gb:每个任务的内存峰值估计(GB,见 pipeline.memory_estimate)。给了就取「最大的几个加起来
|
||||
不超过可用内存的 MEM_SHARE」——同时在跑的任意几个都不会超;不给按每个 GB_PER_JOB 算。
|
||||
"""
|
||||
if n_tasks <= 1 or in_worker():
|
||||
return 1
|
||||
try:
|
||||
setting = int(setting or 0)
|
||||
except (TypeError, ValueError):
|
||||
setting = 0
|
||||
if setting > 0:
|
||||
return min(setting, n_tasks)
|
||||
cap = max(1, min(auto_jobs(), n_tasks))
|
||||
free = free_memory_gb()
|
||||
if not mem_gb:
|
||||
return max(1, min(cap, int(free // GB_PER_JOB)))
|
||||
k, tot = 0, 0.0
|
||||
for m in sorted(mem_gb, reverse=True)[:cap]:
|
||||
tot += m
|
||||
if tot > free * MEM_SHARE:
|
||||
break
|
||||
k += 1
|
||||
return max(1, k)
|
||||
|
||||
|
||||
_QUEUE = None
|
||||
|
||||
|
||||
def _init(q):
|
||||
global _QUEUE
|
||||
_QUEUE = q
|
||||
os.environ[WORKER_ENV] = "1"
|
||||
_lower_priority()
|
||||
|
||||
|
||||
def _lower_priority():
|
||||
"""子进程降到「低于正常」:电脑空闲时照样用满 CPU,用户同时在用别的程序(或这个界面)时先让给它们。"""
|
||||
try:
|
||||
if os.name == "nt":
|
||||
import ctypes
|
||||
k32 = ctypes.windll.kernel32
|
||||
k32.SetPriorityClass(k32.GetCurrentProcess(), 0x4000) # BELOW_NORMAL_PRIORITY_CLASS
|
||||
else:
|
||||
os.nice(5)
|
||||
except (OSError, AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
def _call(key, func, args, kwargs):
|
||||
def log(msg, tag=None):
|
||||
_QUEUE.put((key, str(msg), tag))
|
||||
try:
|
||||
out = (True, func(*args, log=log, **kwargs))
|
||||
except Exception as e: # noqa: BLE001 一个任务失败不影响其它
|
||||
out = (False, ("%s: %s" % (type(e).__name__, e), traceback.format_exc()))
|
||||
_QUEUE.put((key, None, "__done__")) # 这个任务的日志到此为止
|
||||
return out
|
||||
|
||||
|
||||
def run(tasks, jobs, log_for, start=None, done=None, should_stop=None):
|
||||
"""→ {key: (成功?, 结果 或 (错误摘要, 完整 traceback))}。should_stop() 为真后不再开始新任务。"""
|
||||
ctx = mp.get_context("spawn")
|
||||
q = ctx.Queue()
|
||||
finished = {key: threading.Event() for key, *_ in tasks}
|
||||
stop_pump = threading.Event()
|
||||
|
||||
def pump():
|
||||
while not (stop_pump.is_set() and q.empty()):
|
||||
try:
|
||||
key, msg, tag = q.get(timeout=0.2)
|
||||
except queue.Empty:
|
||||
continue
|
||||
if tag == "__stop__": # 收尾时放进来的,不用再等 0.2 秒超时
|
||||
break
|
||||
if tag == "__done__":
|
||||
finished[key].set()
|
||||
else:
|
||||
log_for(key)(msg, tag)
|
||||
|
||||
th = threading.Thread(target=pump, daemon=True)
|
||||
th.start()
|
||||
by_key = {t[0]: t for t in tasks}
|
||||
results, pending, running, started = {}, list(tasks), {}, set()
|
||||
broken = False
|
||||
try:
|
||||
with cf.ProcessPoolExecutor(max_workers=jobs, mp_context=ctx, initializer=_init, initargs=(q,)) as ex:
|
||||
while (pending or running) and not broken:
|
||||
while pending and len(running) < jobs and not (should_stop and should_stop()):
|
||||
key, func, args, kwargs = pending.pop(0)
|
||||
if start and key not in started:
|
||||
start(key)
|
||||
started.add(key)
|
||||
try:
|
||||
running[ex.submit(_call, key, func, args, kwargs)] = key
|
||||
except cf.process.BrokenProcessPool:
|
||||
pending.insert(0, by_key[key])
|
||||
broken = True
|
||||
break
|
||||
if broken or not running:
|
||||
break # 停止了:剩下的不开始
|
||||
fin, _ = cf.wait(running, return_when=cf.FIRST_COMPLETED)
|
||||
for f in fin:
|
||||
key = running.pop(f)
|
||||
try:
|
||||
res = f.result()
|
||||
except cf.process.BrokenProcessPool:
|
||||
# 子进程开不起来 / 被杀(杀毒软件拦截、内存不够):这个任务和剩下的都在本进程里转
|
||||
pending.insert(0, by_key[key])
|
||||
broken = True
|
||||
continue
|
||||
finished[key].wait(10) # 先把它的日志送完
|
||||
results[key] = res
|
||||
if done:
|
||||
done(key, *res)
|
||||
if broken:
|
||||
pending = [by_key[k] for k in running.values()] + pending
|
||||
running.clear()
|
||||
except cf.process.BrokenProcessPool:
|
||||
broken = True
|
||||
finally:
|
||||
stop_pump.set()
|
||||
q.put((None, None, "__stop__")) # 子进程都已退出,它们的日志都在这之前
|
||||
th.join(5)
|
||||
if broken:
|
||||
pending = [t for t in pending if t[0] not in results]
|
||||
for key, func, args, kwargs in pending:
|
||||
if should_stop and should_stop():
|
||||
break
|
||||
log = log_for(key)
|
||||
if key == pending[0][0]:
|
||||
log("无法启动子进程,改为逐个转换", "warn")
|
||||
if start and key not in started:
|
||||
start(key)
|
||||
try:
|
||||
res = (True, func(*args, log=log, **kwargs))
|
||||
except Exception as e: # noqa: BLE001
|
||||
res = (False, ("%s: %s" % (type(e).__name__, e), traceback.format_exc()))
|
||||
results[key] = res
|
||||
if done:
|
||||
done(key, *res)
|
||||
return results
|
||||
@@ -0,0 +1,675 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""转换流程(与界面无关):识别输入格式 → 必要时先转 PMX → 再转 VRM。
|
||||
|
||||
import pipeline
|
||||
outs = pipeline.convert_file(path, opts, log) # → [输出文件路径, ...]
|
||||
|
||||
压缩包(模型网站下载的整包:zip / 7z / rar / tar.gz 等)会先解压到临时目录,再转换里面的模型:
|
||||
有 PMX 就转 PMX,没有再转其它能识别的格式;包里只有另一个压缩包时再解一层。输出放在压缩包
|
||||
旁边(或指定的输出文件夹),临时目录随后删除。zip 用 Python 自带的 zipfile(处理 GBK / cp932
|
||||
文件名),其它格式见 formats/archive.py(7-Zip / WinRAR / Bandizip / Windows 自带的 tar)。
|
||||
|
||||
opts 是纯 JSON 可序列化的 dict(界面直接存取),缺的键用 DEFAULTS 补齐:
|
||||
|
||||
target "vrm"(默认)| "pmx"(非 PMX 输入只转到 PMX 为止)
|
||||
output {"mode": "app" | "beside" | "folder", "folder": 路径, "subfolder": 是否建「名字_日期_序号」子文件夹}
|
||||
app = 程序目录下的 vrm 文件夹(界面用;路径由调用方放在 "app_folder",没有时同 beside)
|
||||
vrm {"spec": "1.0" | "0.x", "avatar_only", "spring", "spring_skirt", "spring_stiffness", "auto_spring",
|
||||
"morphs", "gaze", "combo_expr", "extra_expr", "outline", "tpose", "double_sided", "collapse_bones", "auto_thumb",
|
||||
"tex_max": 0 | 4096 | 2048 | 1024, "tex_jpeg", "tex_no_mip"}
|
||||
avatar_only:只转人物,道具(认不出人形骨架)和只有衣服 / 配件的模型跳过(见 not_an_avatar);
|
||||
一个文件里的模型全被跳过时 convert_file 返回 []
|
||||
meta VRM 作者 / 许可信息(键见 vrmconv/vrm_ext.build_vrm1),标题用模型文件名
|
||||
fbx {"alpha": "auto" | "keep" | "strip", "auto_facing", "face_180", "morphs", "center", "flip_z"}
|
||||
uemodel {"alpha", "align_ref"}
|
||||
psk {"jp_bones", "ik", "morphs", "alpha"}
|
||||
xps {"jp_bones", "ik", "hide_unused", "double_sided", "edge"}
|
||||
jobs 同时转几个(多个文件、或一个包里的几个模型):0 = 自动(见 parallel.jobs_for),1 = 一个一个转
|
||||
|
||||
log(msg, tag=None):tag 为 None / "info" / "ok" / "warn" / "err" / "head"。
|
||||
"""
|
||||
import contextlib
|
||||
import copy
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
import zipfile
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
for _p in (_HERE, os.path.join(os.path.dirname(_HERE), "formats")):
|
||||
if _p not in sys.path:
|
||||
sys.path.insert(0, _p)
|
||||
|
||||
import archive # noqa: E402
|
||||
import parallel # noqa: E402
|
||||
|
||||
KINDS = {".pmx": "pmx", ".vrm": "vrm", ".fbx": "fbx", ".unitypackage": "unitypackage",
|
||||
".uemodel": "uemodel", ".psk": "psk", ".pskx": "psk", ".xps": "xps", ".zip": "zip"}
|
||||
ARCHIVES = {"zip", "7z", "rar", "tar"}
|
||||
CONVERTIBLE = {"pmx", "fbx", "unitypackage", "uemodel", "psk", "xps"} | ARCHIVES
|
||||
|
||||
DEFAULTS = {
|
||||
"target": "vrm",
|
||||
"jobs": 0,
|
||||
"output": {"mode": "beside", "folder": "", "subfolder": True},
|
||||
"vrm": {"spec": "1.0", "avatar_only": True, "spring": True, "spring_skirt": True, "spring_stiffness": 1.0, "auto_spring": True, "gaze": True, "combo_expr": True, "extra_expr": True,
|
||||
"morphs": True, "outline": False, "unity_outline": True,
|
||||
"tpose": False, "double_sided": False,
|
||||
"collapse_bones": True, "auto_thumb": True, "tex_max": 0, "tex_jpeg": False,
|
||||
"tex_no_mip": False},
|
||||
"meta": {"author": "", "version": "", "contact": "", "copyright": "", "license_url": "",
|
||||
"avatar_permission": "everyone", "commercial_usage": "personalNonProfit",
|
||||
"credit_notation": "required", "allow_redistribution": False,
|
||||
"modification": "prohibited"},
|
||||
"fbx": {"alpha": "auto", "auto_facing": True, "face_180": False, "morphs": True,
|
||||
"center": True, "flip_z": True},
|
||||
"uemodel": {"alpha": True, "align_ref": ""},
|
||||
"psk": {"jp_bones": True, "ik": True, "morphs": True, "alpha": True},
|
||||
"xps": {"jp_bones": True, "ik": True, "hide_unused": True, "double_sided": True, "edge": False},
|
||||
}
|
||||
|
||||
|
||||
def classify(path):
|
||||
"""→ "pmx" / "vrm" / "fbx" / "unitypackage" / "uemodel" / "psk" / "xps" /
|
||||
"zip" / "7z" / "rar" / "tar",不支持的为 None(分卷压缩包只认第一卷)。"""
|
||||
return KINDS.get(os.path.splitext(path)[1].lower()) or archive.kind(path)
|
||||
|
||||
|
||||
def merged(opts):
|
||||
"""用户选项和 DEFAULTS 合并(两层),不改动传入的 dict。"""
|
||||
out = copy.deepcopy(DEFAULTS)
|
||||
for k, v in (opts or {}).items():
|
||||
if isinstance(v, dict) and isinstance(out.get(k), dict):
|
||||
out[k].update(v)
|
||||
else:
|
||||
out[k] = v
|
||||
return out
|
||||
|
||||
|
||||
def find_inputs(folder):
|
||||
"""文件夹里(递归)所有能转换或预览的文件。"""
|
||||
found = []
|
||||
for d, dirs, files in os.walk(folder):
|
||||
dirs[:] = [x for x in dirs if not x.startswith(".")]
|
||||
for f in sorted(files):
|
||||
if classify(f):
|
||||
found.append(os.path.join(d, f))
|
||||
return found
|
||||
|
||||
|
||||
def _score(text):
|
||||
"""文件名解码结果像不像正常的中日文:常用汉字、假名、ASCII 加分,半角片假名等乱码特征扣分。"""
|
||||
sc = 0
|
||||
for ch in text:
|
||||
o = ord(ch)
|
||||
if o < 0x80 or 0x4E00 <= o <= 0x9FFF or 0x3040 <= o <= 0x30FF or 0x3000 <= o <= 0x303F or 0xFF01 <= o <= 0xFF5E:
|
||||
sc += 1
|
||||
elif 0xFF61 <= o <= 0xFF9F or 0xE000 <= o <= 0xF8FF:
|
||||
sc -= 3 # 半角片假名 / 私用区:GBK 被当成 cp932 解的典型样子
|
||||
return sc
|
||||
|
||||
|
||||
def _decodings(raw, first):
|
||||
"""一个文件名的候选解码,按「常用字多」排序(同分时 first 优先),只保留严格解码得通的。
|
||||
|
||||
同一个包里常混着 GBK(中文系统)和 cp932(日文系统)的名字,而一种编码的字节按另一种解,
|
||||
得到的多半是生僻字(「武器」的 cp932 字节按 GBK 解成「晲婍」)。用 GB2312 能不能编码当作
|
||||
「常用字」的判断:它收了常用汉字和日文假名,GBK 扩展区的生僻字和半角片假名都不在里面。
|
||||
"""
|
||||
tries = [raw]
|
||||
# cp932 的「ダメ文字」:第二字节是 0x5C(反斜杠),有的打包工具把它当路径分隔符改成了 /
|
||||
fixed = re.sub(rb"([\x81-\x9f\xe0-\xfc])/", rb"\1\\", raw)
|
||||
if fixed != raw:
|
||||
tries.append(fixed)
|
||||
out = []
|
||||
for r in tries:
|
||||
for enc in (first, "gbk", "cp932", "utf-8"):
|
||||
try:
|
||||
name = r.decode(enc)
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
if name not in out:
|
||||
out.append(name)
|
||||
if not out:
|
||||
return [raw.decode(first, "replace")]
|
||||
|
||||
def common(n):
|
||||
k = 0
|
||||
for ch in n:
|
||||
try:
|
||||
ch.encode("gb2312")
|
||||
k += 1
|
||||
except UnicodeEncodeError:
|
||||
pass
|
||||
return k
|
||||
order = {n: i for i, n in enumerate(out)}
|
||||
out.sort(key=lambda n: (-common(n), order[n]))
|
||||
return out
|
||||
|
||||
|
||||
def zip_members(zf):
|
||||
"""→ [(ZipInfo, [候选文件名, …])],第一个是默认用的。
|
||||
|
||||
没设 UTF-8 标志的压缩包,文件名是打包那台电脑的本地编码(中文系统 GBK,日文系统 cp932),
|
||||
而且同一个包里可能两种混着(作者的日文原文件 + 后加的中文文件)。先给整包选一种主编码
|
||||
(严格解得通、且「像正常中日文」得分最高的),每个文件再按常用字多少挑解法(见 _decodings),
|
||||
解压后还会用 PMX 里记录的贴图路径纠正(见 extract_zip)。
|
||||
"""
|
||||
infos = zf.infolist()
|
||||
legacy = [i.filename.encode("cp437") for i in infos if not i.flag_bits & 0x800]
|
||||
best, best_score = "gbk", None
|
||||
for enc in ("utf-8", "gbk", "cp932"):
|
||||
try:
|
||||
text = "".join(r.decode(enc) for r in legacy)
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
sc = _score(text) + (len(text) if enc == "utf-8" else 0) # 严格 UTF-8 解得通基本就是它
|
||||
if best_score is None or sc > best_score:
|
||||
best, best_score = enc, sc
|
||||
return [(i, [i.filename] if i.flag_bits & 0x800 else _decodings(i.filename.encode("cp437"), best))
|
||||
for i in infos]
|
||||
|
||||
|
||||
def _safe_parts(name):
|
||||
parts = [p for p in name.replace("\\", "/").split("/") if p not in ("", ".", "..")]
|
||||
if parts and ":" in parts[0]: # 盘符
|
||||
parts = parts[1:]
|
||||
return parts
|
||||
|
||||
|
||||
def extract_zip(path, dest):
|
||||
"""安全解压(去掉绝对路径和 ..,不会写到 dest 外面),返回解出的文件数。
|
||||
|
||||
文件名按 zip_members 的默认解码落盘后,再读每个 PMX:某个文件换一种解码正好是 PMX 引用的
|
||||
贴图路径(或 PMX 自己的模型名),就改成那个名字——否则贴图对不上,转出来没有贴图。
|
||||
"""
|
||||
import pmxio
|
||||
entries = [] # (落盘相对路径, [候选相对路径])
|
||||
n = 0
|
||||
with zipfile.ZipFile(path) as zf:
|
||||
for info, names in zip_members(zf):
|
||||
if info.is_dir():
|
||||
continue
|
||||
cands = ["/".join(_safe_parts(x)) for x in names]
|
||||
cands = [c for c in cands if c]
|
||||
if not cands:
|
||||
continue
|
||||
target = os.path.join(dest, *cands[0].split("/"))
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
with zf.open(info) as src, open(target, "wb") as f:
|
||||
shutil.copyfileobj(src, f)
|
||||
entries.append((cands[0], cands))
|
||||
n += 1
|
||||
if all(len(c) == 1 for _, c in entries):
|
||||
return n
|
||||
wanted = set() # PMX 期望存在的相对路径(小写)
|
||||
pmx_names = {} # PMX 相对路径 → 内部模型名
|
||||
for rel, _ in entries:
|
||||
if not rel.lower().endswith(".pmx"):
|
||||
continue
|
||||
try:
|
||||
m = pmxio.read_pmx(os.path.join(dest, *rel.split("/")))
|
||||
except Exception: # noqa: BLE001 读不了就不纠正
|
||||
continue
|
||||
base = rel.rsplit("/", 1)[0] + "/" if "/" in rel else ""
|
||||
for t in m["textures"]:
|
||||
wanted.add((base + "/".join(_safe_parts(t))).lower())
|
||||
pmx_names[rel] = (m.get("name") or "").strip()
|
||||
for rel, cands in entries:
|
||||
if len(cands) < 2:
|
||||
continue
|
||||
fix = None
|
||||
if rel.lower() not in wanted:
|
||||
fix = next((c for c in cands[1:] if c.lower() in wanted), None)
|
||||
if fix is None and rel in pmx_names:
|
||||
stem = lambda c: os.path.splitext(c.rsplit("/", 1)[-1])[0]
|
||||
if stem(rel) != pmx_names[rel]:
|
||||
fix = next((c for c in cands[1:] if stem(c) == pmx_names[rel]), None)
|
||||
if fix:
|
||||
os.renames(os.path.join(dest, *rel.split("/")), os.path.join(dest, *fix.split("/")))
|
||||
return n
|
||||
|
||||
|
||||
GAMES = {"崩坏:星穹铁道": "星穹铁道"} # 下载站的游戏名 → 简称
|
||||
|
||||
|
||||
def nice_name(stem):
|
||||
"""「<名字>_by_<游戏>_<哈希>」(模之屋的下载命名)→「<游戏>—<名字>」,去掉「(修模绑骨后)」
|
||||
这类说明和结尾的版本号;「(星)」这种有意义的括号保留。其它名字原样返回。"""
|
||||
name, sep, rest = stem.partition("_by_")
|
||||
if not sep:
|
||||
return stem
|
||||
game = rest.rsplit("_", 1)[0]
|
||||
game = GAMES.get(game, game)
|
||||
name = name.strip("【】")
|
||||
m = re.search(r"[((][^((]*$", name)
|
||||
if m and re.search(r"修|绑|更新|版", m.group()):
|
||||
name = name[:m.start()]
|
||||
name = re.sub(r"\d+(\.\d+)*$", "", name)
|
||||
for pre in (game + "—", game + "_"):
|
||||
if name.startswith(pre):
|
||||
name = name[len(pre):]
|
||||
return game + "—" + name.strip("_— ")
|
||||
|
||||
|
||||
def output_dir(path, opts):
|
||||
"""按 output 选项决定这个源文件的输出目录(会建好)。"""
|
||||
o = opts["output"]
|
||||
if o.get("mode") == "folder" and o.get("folder"):
|
||||
base = o["folder"]
|
||||
elif o.get("mode") == "app" and o.get("app_folder"):
|
||||
base = o["app_folder"]
|
||||
else:
|
||||
base = os.path.dirname(os.path.abspath(path))
|
||||
if o.get("subfolder", True):
|
||||
stem = nice_name(os.path.splitext(os.path.basename(path))[0])
|
||||
day = time.strftime("%Y%m%d")
|
||||
for n in range(1, 10000):
|
||||
d = os.path.join(base, "%s_%s_%03d" % (stem, day, n))
|
||||
if not os.path.exists(d):
|
||||
base = d
|
||||
break
|
||||
os.makedirs(base, exist_ok=True)
|
||||
return base
|
||||
|
||||
|
||||
class _LogWriter(io.TextIOBase):
|
||||
"""把 print() 的输出转成 log 回调(fbx2pmx 用 print 汇报进度)。"""
|
||||
|
||||
def __init__(self, log):
|
||||
self._log = log
|
||||
self._buf = ""
|
||||
|
||||
def write(self, s):
|
||||
self._buf += s
|
||||
while "\n" in self._buf:
|
||||
line, self._buf = self._buf.split("\n", 1)
|
||||
if line.strip():
|
||||
self._log(line.rstrip(), None)
|
||||
return len(s)
|
||||
|
||||
def flush(self):
|
||||
if self._buf.strip():
|
||||
self._log(self._buf.rstrip(), None)
|
||||
self._buf = ""
|
||||
|
||||
|
||||
def _fmt_opts(opts, kind):
|
||||
"""某个输入格式的选项。转 VRM 时格式自己的「导出表情」跟着 VRM 的「表情」开关走(界面里只显示那一个;
|
||||
格式的开关只在「只转 PMX」时显示和生效)。"""
|
||||
o = opts[kind]
|
||||
if opts["target"] != "pmx" and "morphs" in o:
|
||||
o = dict(o, morphs=opts["vrm"]["morphs"])
|
||||
return o
|
||||
|
||||
|
||||
def to_pmx(path, kind, out_dir, opts, log):
|
||||
"""非 PMX 输入 → PMX,返回写出的 PMX 路径列表(unitypackage 可能有多个)。"""
|
||||
stem = os.path.splitext(os.path.basename(path))[0]
|
||||
# 有的转换器只在拷贝贴图时才建输出目录:没有贴图的模型(白模)写 PMX 时目录还不存在
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
if kind in ("fbx", "unitypackage"):
|
||||
fbxs, dest = _unpack_fbxs(path, log) if kind == "unitypackage" else ([path], None)
|
||||
try:
|
||||
return _fbxs_to_pmx(fbxs, out_dir, _fmt_opts(opts, "fbx"), log)
|
||||
finally:
|
||||
if dest:
|
||||
shutil.rmtree(dest, ignore_errors=True)
|
||||
out = os.path.join(out_dir, stem + ".pmx")
|
||||
if kind == "uemodel":
|
||||
import uemodel2pmx
|
||||
o = opts["uemodel"]
|
||||
uemodel2pmx.convert(path, out, scale_mode="auto", log=log, name=stem,
|
||||
remove_alpha=o["alpha"], align_to=o.get("align_ref") or None,
|
||||
force_double_sided=opts["vrm"]["double_sided"])
|
||||
elif kind == "psk":
|
||||
import psk2pmx
|
||||
o = _fmt_opts(opts, "psk")
|
||||
psk2pmx.convert(path, out, scale_mode="auto", log=log, name=stem,
|
||||
jp_bones=o["jp_bones"], make_ik=o["ik"], export_morphs=o["morphs"],
|
||||
remove_alpha=o["alpha"], force_double_sided=opts["vrm"]["double_sided"])
|
||||
elif kind == "xps":
|
||||
import xps2pmx
|
||||
o = opts["xps"]
|
||||
xps2pmx.convert(path, out, scale_mode="auto", log=log, name=stem,
|
||||
jp_bones=o["jp_bones"], make_ik=o["ik"], hide_unused=o["hide_unused"],
|
||||
all_double_sided=o["double_sided"], enable_edge=o["edge"],
|
||||
force_double_sided=opts["vrm"]["double_sided"])
|
||||
else:
|
||||
raise ValueError("不支持的输入:%s" % kind)
|
||||
return [out]
|
||||
|
||||
|
||||
def _unpack_fbxs(path, log):
|
||||
"""unitypackage 解到临时目录(几百个资源文件,转完就删)→ ([FBX,大的在前], 临时目录)。"""
|
||||
from unitypackage_unpack import unpack
|
||||
dest = tempfile.mkdtemp(prefix="vrmify_unitypackage_")
|
||||
with contextlib.redirect_stdout(_LogWriter(log)):
|
||||
unpack(path, dest, verbose=False)
|
||||
n = sum(len(fs) for _, _, fs in os.walk(dest))
|
||||
fbxs = [p for p in find_files(dest, ".fbx") if os.path.getsize(p) > 1024]
|
||||
log("解包 %s:%d 个文件,%d 个 FBX" % (os.path.basename(path), n, len(fbxs)), "info")
|
||||
if not fbxs:
|
||||
shutil.rmtree(dest, ignore_errors=True)
|
||||
raise RuntimeError("包中没有 FBX 文件")
|
||||
fbxs.sort(key=lambda p: -os.path.getsize(p))
|
||||
return fbxs, dest
|
||||
|
||||
|
||||
def _unique_names(paths):
|
||||
"""包里每个模型的输出名(文件名去掉扩展名);不同文件夹下的同名模型加 _2、_3,免得输出互相覆盖。"""
|
||||
names, used = [], set()
|
||||
for p in paths:
|
||||
base = name = os.path.splitext(os.path.basename(p))[0]
|
||||
k = 2
|
||||
while name.lower() in used:
|
||||
name = "%s_%d" % (base, k)
|
||||
k += 1
|
||||
used.add(name.lower())
|
||||
names.append(name)
|
||||
return names
|
||||
|
||||
|
||||
def _fbx_to_pmx(fbx, out, name, o, log):
|
||||
"""→ fbx2pmx.convert 的统计(其中 ["alpha"]["png_alpha"] 是已经算好的贴图透明统计)。"""
|
||||
import fbx2pmx
|
||||
log("读取 FBX:%s" % os.path.basename(fbx), "info")
|
||||
w = _LogWriter(log)
|
||||
with contextlib.redirect_stdout(w):
|
||||
scene = fbx2pmx.Scene(fbx)
|
||||
st = fbx2pmx.convert(scene, out, scale_mode="auto", flip_z=o["flip_z"],
|
||||
name=name, center=o["center"], morphs=o["morphs"],
|
||||
alpha_mode=o["alpha"], auto_facing=o["auto_facing"],
|
||||
face_180=o["face_180"], threads=parallel.threads())
|
||||
w.flush()
|
||||
return st
|
||||
|
||||
|
||||
def _fbxs_to_pmx(fbxs, out_dir, o, log):
|
||||
"""FBX → PMX(写进 out_dir,贴图在 out_dir/textures),返回 PMX 路径列表。"""
|
||||
outs = []
|
||||
for fbx, name in zip(fbxs, _unique_names(fbxs)):
|
||||
out = os.path.join(out_dir, name + ".pmx")
|
||||
_fbx_to_pmx(fbx, out, name, o, log)
|
||||
outs.append(out)
|
||||
return outs
|
||||
|
||||
|
||||
def fbx_to_vrm(fbx, name, out_dir, opts, log, edits=None):
|
||||
"""一个 FBX → VRM;中间的 PMX 和贴图放自己的临时目录。→ [VRM 路径],被「只转换人物」跳过时为 []。
|
||||
并行时在子进程里跑(parallel.run)。"""
|
||||
import pmxio
|
||||
work = tempfile.mkdtemp(prefix="vrmify_work_")
|
||||
try:
|
||||
pmx = os.path.join(work, name + ".pmx")
|
||||
st = _fbx_to_pmx(fbx, pmx, name, _fmt_opts(opts, "fbx"), log)
|
||||
n_ol = st.get("unity_outline", 0) if opts["vrm"].get("unity_outline", True) else 0
|
||||
if n_ol:
|
||||
# Unity 材质里的描边是源模型的设定,跟「描边(按 PMX 轮廓线)」这个针对 MMD
|
||||
# 模型的开关无关,所以单独透传,避免用户没勾那个选项时描边被整条丢掉。
|
||||
log("材质:%d 个 Unity 材质开了描边(_Outline_Width),已转成 MToon 轮廓线" % n_ol, "info")
|
||||
# 中间的 PMX 只读一次,「是不是人物」的检查和转 VRM 共用
|
||||
return _to_vrm(pmx, out_dir, opts, log, edits=edits, model=pmxio.read_pmx(pmx),
|
||||
tex_alpha=st["alpha"]["png_alpha"], unity_outline=bool(n_ol),
|
||||
step="PMX → VRM:%s.pmx" % name)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def _to_vrm(pmx, out_dir, opts, log, name=None, edits=None, model=None, step=None, **known):
|
||||
"""PMX → [VRM 路径]。opts["vrm"]["avatar_only"] 时先看是不是人物(not_an_avatar),不是就跳过、返回 [];
|
||||
检查用的模型和顶点权重接着给转换用。step:确定要转时先记一行日志。known 见 pmx_to_vrm。"""
|
||||
if opts["vrm"].get("avatar_only", True):
|
||||
import pmxio
|
||||
from vrmconv import mesh
|
||||
if model is None:
|
||||
model = pmxio.read_pmx(pmx)
|
||||
weights = mesh.vertex_weights(model["vertices"], len(model["bones"]), {})
|
||||
why = not_an_avatar(model, weights)
|
||||
if why:
|
||||
log("跳过 %s:%s(如需转换,请在「转换」页关闭「只转换人物」)"
|
||||
% (name or os.path.splitext(os.path.basename(pmx))[0], why), "warn")
|
||||
return []
|
||||
known["raw_weights"] = weights
|
||||
if step:
|
||||
log(step, "info")
|
||||
return [pmx_to_vrm(pmx, out_dir, opts, log, name=name, edits=edits, model=model, **known)]
|
||||
|
||||
|
||||
def _fbxs_to_vrm(fbxs, out_dir, opts, log, edits=None, name=None):
|
||||
"""几个 FBX(unitypackage 里常有好几套服装)→ VRM(见 _convert_each)。
|
||||
name:只有一个 FBX 时用它当输出名(压缩包里有同名模型时由调用方改过名)。"""
|
||||
names = [name] if name and len(fbxs) == 1 else _unique_names(fbxs)
|
||||
if len(fbxs) == 1:
|
||||
return fbx_to_vrm(fbxs[0], names[0], out_dir, opts, log, edits=edits)
|
||||
return _convert_each([(fbx_to_vrm, (fbx, names[i], out_dir, opts), {"edits": edits})
|
||||
for i, fbx in enumerate(fbxs)], names, [os.path.getsize(f) for f in fbxs], opts, log,
|
||||
"包中")
|
||||
|
||||
|
||||
SMALL_MODEL = 1 << 20 # 输入文件小于 1 MB 的模型(道具、配件)转得比开子进程还快,不为它们并行
|
||||
UNKNOWN_GB = 1.0 # 看不到里面的包(unitypackage / 7z / rar / tar)按这么多估
|
||||
|
||||
|
||||
def _model_gb(size):
|
||||
"""一个模型文件(PMX / FBX / …,size 字节)转换时的进程内存峰值估计(GB)。
|
||||
实测 VRM 1.0(主要花在 PMX 读进来的逐顶点字典上):PMX 约 0.09 GB + 文件大小 × 28
|
||||
(爱弥斯 16 MB → 0.51 GB,开拓者 2.2 MB → 0.15 GB);FBX 更省(12 MB → 0.14 GB)。按 × 35 估、留余量。"""
|
||||
return min(parallel.GB_PER_JOB, 0.15 + size * 35 / 1024 ** 3)
|
||||
|
||||
|
||||
def memory_estimate(path):
|
||||
"""转换这个文件时的进程内存峰值估计(GB),给 parallel.jobs_for 决定同时转几个。
|
||||
压缩包里的模型是一个一个转的,按最大的那个估:zip 直接看目录;看不到里面的按 UNKNOWN_GB
|
||||
(Marycia 154 MB 的 unitypackage 实测峰值 0.44 GB)。"""
|
||||
kind = classify(path)
|
||||
try:
|
||||
if kind == "zip":
|
||||
with zipfile.ZipFile(path) as zf:
|
||||
infos = zf.infolist()
|
||||
inner = [classify(i.filename) for i in infos]
|
||||
if any(k in ARCHIVES or k == "unitypackage" for k in inner):
|
||||
return UNKNOWN_GB
|
||||
sizes = [i.file_size for i, k in zip(infos, inner) if k in CONVERTIBLE]
|
||||
return _model_gb(max(sizes)) if sizes else UNKNOWN_GB
|
||||
if kind in ARCHIVES or kind == "unitypackage":
|
||||
return UNKNOWN_GB
|
||||
return _model_gb(os.path.getsize(path))
|
||||
except (OSError, zipfile.BadZipFile, ValueError):
|
||||
return UNKNOWN_GB
|
||||
|
||||
|
||||
def _convert_each(tasks, names, sizes, opts, log, where):
|
||||
"""几个模型(unitypackage 里的几套服装、压缩包里的几个模型)→ 输出路径列表:能并行时同时转,
|
||||
各自的日志前面带上模型名(parallel.run);某个模型失败不影响其它的,都失败才报错。
|
||||
|
||||
tasks:[(func, args, kwargs)],按 func(*args, log=…, **kwargs) 调用、返回输出路径列表;
|
||||
func 要是模块顶层函数(子进程按名字导入)。names / sizes:每个任务的模型名、输入文件大小。
|
||||
where:日志里说「包里」还是「压缩包里」。
|
||||
"""
|
||||
if len(tasks) == 1: # 只有一个:直接转,出错照常抛出
|
||||
func, args, kw = tasks[0]
|
||||
return func(*args, log=log, **kw)
|
||||
big = sum(1 for s in sizes if s >= SMALL_MODEL) # 一个人物 + 几个小道具:一个一个转更快
|
||||
jobs = parallel.jobs_for(big, opts.get("jobs"), [_model_gb(s) for s in sizes if s >= SMALL_MODEL]) if big > 1 else 1
|
||||
keyed = [(i,) + tuple(t) for i, t in enumerate(tasks)]
|
||||
if jobs > 1:
|
||||
log("%s共有 %d 个模型,并行转换 %d 个" % (where, len(tasks), jobs), "info")
|
||||
results = parallel.run(keyed, jobs, lambda i: (lambda m, t=None: log("[%s] %s" % (names[i], m), t)))
|
||||
else:
|
||||
results = {}
|
||||
for i, func, args, kw in keyed:
|
||||
try:
|
||||
results[i] = (True, func(*args, log=log, **kw))
|
||||
except Exception as e: # noqa: BLE001 一个模型失败不影响其它的
|
||||
results[i] = (False, ("%s: %s" % (type(e).__name__, e), traceback.format_exc()))
|
||||
outs, errors = [], []
|
||||
for i in range(len(tasks)):
|
||||
ok, r = results.get(i, (False, ("没有执行", "")))
|
||||
if ok:
|
||||
outs += r
|
||||
else:
|
||||
errors.append(r[0])
|
||||
log("%s 转换失败:%s" % (names[i], r[1] or r[0]), "err")
|
||||
if errors and not outs:
|
||||
raise RuntimeError(errors[0])
|
||||
return outs
|
||||
|
||||
|
||||
def find_files(root, ext):
|
||||
return [os.path.join(d, f) for d, _, fs in os.walk(root) for f in fs if f.lower().endswith(ext)]
|
||||
|
||||
|
||||
def pmx_to_vrm(pmx, out_dir, opts, log, name=None, edits=None, **known):
|
||||
"""PMX → VRM,返回 VRM 路径。edits:界面里对这个模型做的调整(见 vrm_edit),转完套上。
|
||||
known:调用方已经读好 / 算好的 model、raw_weights、tex_alpha(见 pmx2vrm.convert)。"""
|
||||
import pmx2vrm
|
||||
o = opts["vrm"]
|
||||
stem = name or os.path.splitext(os.path.basename(pmx))[0]
|
||||
out = os.path.join(out_dir, stem + ".vrm")
|
||||
spec = "1.0" if str(o["spec"]).startswith("1") else "0.x"
|
||||
meta = dict(opts.get("meta") or {}, title=stem)
|
||||
pmx2vrm.convert(pmx, out, spec=spec, meta=meta, log=log,
|
||||
max_morphs=None if o["morphs"] else 0,
|
||||
force_double_sided=o["double_sided"], tpose=o["tpose"],
|
||||
outline=o["outline"], spring=o["spring"], spring_skirt=o["spring_skirt"],
|
||||
spring_stiffness=float(o["spring_stiffness"]),
|
||||
tex_max=int(o.get("tex_max") or 0), tex_jpeg=bool(o.get("tex_jpeg")),
|
||||
tex_no_mip=bool(o.get("tex_no_mip", False)),
|
||||
auto_spring=bool(o.get("auto_spring", True)), gaze=bool(o.get("gaze", True)),
|
||||
combo_expr=bool(o.get("combo_expr", True)), extra_expr=bool(o.get("extra_expr", True)),
|
||||
collapse_bones=bool(o.get("collapse_bones", True)), threads=parallel.threads(), **known)
|
||||
if edits:
|
||||
import vrm_edit
|
||||
if not vrm_edit.is_empty(edits):
|
||||
n = vrm_edit.apply(out, edits)
|
||||
log("已应用保存的调整(%d 项)" % n, "info")
|
||||
return out
|
||||
|
||||
|
||||
def convert_file(path, opts=None, log=None, out_dir=None, edits=None):
|
||||
"""转换一个文件,返回输出文件列表。out_dir 不给时按 opts["output"] 决定;
|
||||
edits:这个文件在界面里的调整(vrm_edit),套到每个输出的 VRM 上。"""
|
||||
opts = merged(opts)
|
||||
log = log or (lambda m, t=None: None)
|
||||
kind = classify(path)
|
||||
if kind not in CONVERTIBLE:
|
||||
raise ValueError("无法转换此文件:%s" % os.path.basename(path))
|
||||
out_dir = out_dir or output_dir(path, opts)
|
||||
log("→ %s" % os.path.basename(path), "head")
|
||||
log("输出目录:%s" % out_dir, "info")
|
||||
if kind in ARCHIVES:
|
||||
return _convert_archive(path, kind, out_dir, opts, log, edits)
|
||||
return _convert_model(path, kind, out_dir, opts, log, edits)
|
||||
|
||||
|
||||
def extract_archive(path, kind, dest, log=None):
|
||||
"""解压任意支持的压缩包,返回文件数。"""
|
||||
if kind == "zip":
|
||||
return extract_zip(path, dest)
|
||||
return archive.extract(path, dest, log)
|
||||
|
||||
|
||||
def _convert_archive(path, kind, out_dir, opts, log, edits=None):
|
||||
tmp = tempfile.mkdtemp(prefix="vrmify_%s_" % kind)
|
||||
try:
|
||||
n = extract_archive(path, kind, tmp, log)
|
||||
found = find_inputs(tmp)
|
||||
inner = [p for p in found if classify(p) in CONVERTIBLE - ARCHIVES]
|
||||
if not inner: # 包里套包(zip 里放 7z 之类):再解一层
|
||||
for i, p in enumerate(x for x in found if classify(x) in ARCHIVES):
|
||||
sub = os.path.join(tmp, "__inner%d" % i)
|
||||
log("解压内层压缩包 %s" % os.path.relpath(p, tmp), "info")
|
||||
n += extract_archive(p, classify(p), sub, log)
|
||||
inner += [q for q in find_inputs(sub) if classify(q) in CONVERTIBLE - ARCHIVES]
|
||||
pmx = [p for p in inner if classify(p) == "pmx"]
|
||||
todo = pmx or inner # 有 PMX 就只转 PMX(同包里的 FBX 等通常是同一个模型)
|
||||
log("解压出 %d 个文件,其中模型 %d 个:%s" % (n, len(todo), "、".join(
|
||||
os.path.relpath(p, tmp) for p in todo)), "info")
|
||||
if not todo:
|
||||
raise RuntimeError("压缩包中没有可转换的模型(PMX / FBX / uemodel / psk / xps)")
|
||||
names = _unique_names(todo)
|
||||
# 只转 PMX 时几个模型的贴图都写进输出目录的同一个 textures 文件夹:一个一个转
|
||||
each = dict(opts, jobs=1) if opts["target"] == "pmx" else opts
|
||||
return _convert_each([(_convert_inner, (p, os.path.relpath(p, tmp), out_dir, opts),
|
||||
{"edits": edits, "name": names[i]}) for i, p in enumerate(todo)],
|
||||
names, [os.path.getsize(p) for p in todo], each, log, "压缩包中")
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
def _convert_inner(path, rel, out_dir, opts, log, edits=None, name=None):
|
||||
"""压缩包里的一个模型(rel:在包里的相对路径,日志用)。并行时在子进程里跑(见 _convert_each)。"""
|
||||
log("→ %s" % rel, "head")
|
||||
return _convert_model(path, classify(path), out_dir, opts, log, edits, name=name)
|
||||
|
||||
|
||||
def _convert_model(path, kind, out_dir, opts, log, edits=None, name=None):
|
||||
"""name:转 VRM 时的输出名(不给时用文件名;unitypackage 里的几个模型各用各的文件名)。"""
|
||||
if kind == "pmx":
|
||||
return _to_vrm(path, out_dir, opts, log, name=name, edits=edits)
|
||||
if opts["target"] == "pmx": # 只转 PMX:道具在 MMD 里照样有用,不挑
|
||||
pmxs = to_pmx(path, kind, out_dir, opts, log)
|
||||
for p in pmxs:
|
||||
log("已写出 %s" % os.path.basename(p), "ok")
|
||||
return pmxs
|
||||
# 转 VRM 时中间的 PMX 和它的贴图只是过渡:放临时目录,转完删掉,输出目录只留 VRM
|
||||
if kind in ("fbx", "unitypackage"):
|
||||
fbxs, dest = _unpack_fbxs(path, log) if kind == "unitypackage" else ([path], None)
|
||||
try:
|
||||
return _fbxs_to_vrm(fbxs, out_dir, opts, log, edits, name=name if kind == "fbx" else None)
|
||||
finally:
|
||||
if dest:
|
||||
shutil.rmtree(dest, ignore_errors=True)
|
||||
work = tempfile.mkdtemp(prefix="vrmify_work_")
|
||||
try:
|
||||
outs = []
|
||||
for p in to_pmx(path, kind, work, opts, log):
|
||||
outs += _to_vrm(p, out_dir, opts, log, name=name, edits=edits,
|
||||
step="PMX → VRM:%s" % os.path.basename(p))
|
||||
return outs
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def not_an_avatar(model, weights=None):
|
||||
"""看起来不是人物时返回原因,否则 None(「只转换人物」用)。
|
||||
|
||||
* 道具:骨架里认不出头或腰(剑、椅子、请柬……一般只有一两根骨)。模之屋的模型包里常带着。
|
||||
* 只有衣服 / 配件:VRChat 等的模型包里常有单独的服装 FBX,骨架是完整的,网格只有衣服。判断:
|
||||
头部(头骨及其子骨,包括头发、眼睛)没挂任何顶点,或者两只手都没挂顶点(认不出手时不看手)。
|
||||
model:PMX 路径或读好的模型(pmxio.read_pmx);weights:已经算好的不带别名的顶点权重。
|
||||
"""
|
||||
import pmxio
|
||||
from vrmconv import mesh
|
||||
from vrmconv.humanoid import _map_humanoid
|
||||
m = model if isinstance(model, dict) else pmxio.read_pmx(model)
|
||||
human = _map_humanoid(m["bones"], True, {})
|
||||
parents = [b["parent"] for b in m["bones"]]
|
||||
|
||||
def subtree(root):
|
||||
out, grew = {root}, True
|
||||
while grew:
|
||||
grew = False
|
||||
for i, p in enumerate(parents):
|
||||
if p in out and i not in out:
|
||||
out.add(i)
|
||||
grew = True
|
||||
return out
|
||||
|
||||
if "head" not in human or "hips" not in human:
|
||||
return "未识别到人形骨架,可能是道具"
|
||||
if weights is None:
|
||||
weights = mesh.vertex_weights(m["vertices"], len(m["bones"]), {})
|
||||
used = {b for wl in weights for b, w in wl if w > 0.3}
|
||||
if not used & subtree(human["head"]):
|
||||
return "头部没有网格,可能只有服装或配件"
|
||||
hands = [human[h] for h in ("leftHand", "rightHand") if h in human]
|
||||
if len(hands) == 2 and not used & (subtree(hands[0]) | subtree(hands[1])):
|
||||
return "手部没有网格,可能只有服装或配件"
|
||||
return None
|
||||
@@ -0,0 +1,492 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""pmx2vrm.py - 把 PMX 模型转成 VRM(glTF 2.0 / GLB 容器),纯 Python 标准库。
|
||||
|
||||
不需要 Blender、不需要 mmd_tools、不需要 Unity。
|
||||
|
||||
坐标约定(数值均指文件里存的原始数字)
|
||||
--------
|
||||
PMX(MMD) 正面 -Z,角色左手侧 +X,Y 向上(DirectX 左手系,逆时针缠绕)
|
||||
VRM 0.x 正面 -Z,角色左手侧 -X,Y 向上(glTF 右手系、逆时针为正面)
|
||||
VRM 1.0 正面 +Z,角色左手侧 +X,Y 向上
|
||||
|
||||
所以:
|
||||
* PMX(DirectX 左手系)与 glTF(右手系)手性相反:同一组数字直接
|
||||
解释是镜像人形,必须反射一个轴——转 0.x 取反 X;转 1.0 取反 Z。
|
||||
* 两种情况三角绕序都要反转(反射把「外面看逆时针」颠倒了)。
|
||||
* 尺寸:MMD 模型约 20 单位高,VRM 用米,默认按 1.6 m 归一。
|
||||
|
||||
用法:
|
||||
python pmx2vrm.py model.pmx -o model.vrm
|
||||
python pmx2vrm.py model.pmx --spec 0x --title "名字" --author "作者"
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
# 让 `python convert/pmx2vrm.py ...` 也能直接跑:脚本自己所在目录(convert/)和同级的
|
||||
# formats/ 都要进 sys.path。以前这里只加了 convert/,于是 `import pmxio` 之类会
|
||||
# ModuleNotFoundError —— 而 README 里给的命令行用法就是这么调的。
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
for _p in (_HERE, os.path.join(os.path.dirname(_HERE), "formats")):
|
||||
if _p not in sys.path:
|
||||
sys.path.insert(0, _p)
|
||||
import pmxio # noqa: E402
|
||||
import vrmio # noqa: E402
|
||||
from vrmconv import autophys, checks, expressions, mesh, morphbake, skeleton, springbone_v0, textures, vrm_ext # noqa: E402
|
||||
from vrmconv.materials import MaterialBuilder # noqa: E402
|
||||
from vrmconv.springbone import _build_springs # noqa: E402
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 主流程 --
|
||||
def convert(pmx_path, vrm_path, spec="1.0", scale_mode="auto",
|
||||
rotate="auto", reverse_winding="auto", meta=None,
|
||||
max_morphs=None, log=None, force_double_sided=False,
|
||||
tpose=False, outline=False, unity_outline=False, sparse_morphs=True,
|
||||
spring=True, spring_skirt=True, spring_stiffness=1.0,
|
||||
spring_gravity=0.0, spring_gravity_skirt=0.1, spring_center=True,
|
||||
spring_opts=None, tex_max=0, tex_jpeg=False, tex_no_mip=False, auto_spring=True, gaze=True,
|
||||
combo_expr=True, extra_expr=True, collapse_bones=True, model=None, raw_weights=None, tex_alpha=None,
|
||||
threads=4):
|
||||
"""PMX → VRM,返回统计 dict。log(msg, tag=None) 用于输出进度。
|
||||
|
||||
各阶段在 vrmconv/ 里:skeleton(骨骼、T-pose、节点)→ springbone(物理)→
|
||||
mesh + materials(网格、MToon)→ expressions(表情)→ vrm_ext(VRM 扩展)。
|
||||
|
||||
auto_spring:模型完全没有物理刚体时,按骨骼名 / 结构自动补(vrmconv/autophys)。
|
||||
tex_max / tex_jpeg:贴图最大边长(0 = 原样)/ 不透明贴图改存 JPEG(需要 Pillow,见 vrmconv/textures)。
|
||||
tex_no_mip:贴图采样器禁用 mipmap,缓解 UV 岛无 gutter 时沿接缝渗出的白边(默认 False)。
|
||||
gaze:有左右眼骨时补 lookUp / lookDown / lookLeft / lookRight 表情(转眼骨烘焙成顶点偏移,
|
||||
见 vrmconv/morphbake;模型自己有对应表情时不补)。
|
||||
combo_expr:情绪预设(happy / angry / sad / relaxed / surprised)组合眉、眼、嘴的表情,
|
||||
像 VRoid 一样整张脸一起变(见 vrmconv/expressions.COMBO);False 时每个预设只对应一个表情。
|
||||
extra_expr:补充自定义表情 hideHighlight(关掉眼睛高光)和 tongue(吐舌),见 expressions.add_extras。
|
||||
collapse_bones:没有权重的中间骨(全ての親 / センター / グルーブ / 腰 / 肩P 之类)也去掉,
|
||||
层级像 VRoid(Root > Hips);False 时留着它们(连接保留骨所需的祖先)。IK、合并掉的付与骨、末端骨这类完全不起作用的骨总会去掉(见 _prune_nodes)。
|
||||
meta:title / author / version / contact / copyright / license_url / avatar_permission /
|
||||
commercial_usage / credit_notation / allow_redistribution / modification(见 vrm_ext)。
|
||||
model / raw_weights / tex_alpha:调用方已经有的,省得再算一遍——读好的 PMX(pmxio.read_pmx,
|
||||
会被改动)、不带付与别名的顶点权重(mesh.vertex_weights(..., {}))、贴图透明统计
|
||||
{normcase 绝对路径: vrmio.png_alpha_stats 的结果}(FBX 转换判断透明时已经解过贴图)。
|
||||
threads:同时处理几张贴图(解码、瘦身)。
|
||||
|
||||
reverse_winding:
|
||||
"auto"(默认)——用「几何面法线 vs 顶点法线」投票自动判定;
|
||||
True / False ——手动强制反转 / 不反转。
|
||||
|
||||
手性说明(2026-09-18 重写):PMX(MMD / DirectX 左手系)数值上
|
||||
脸朝 -Z、左手在 +X;同一组数字按 glTF 右手系直接解释是镜像人形,
|
||||
必须做一次镜面反射(0.x 取反 x;1.0 取反 z)。反射会把
|
||||
「从外面看逆时针」颠倒成顺时针,所以 auto 绕序判定(用反射后的
|
||||
数据投票)正常会判「反转」。以前不做反射(或用 y180 纯旋转,
|
||||
旋转改不了手性)会让转出的模型左右翻转。
|
||||
"""
|
||||
# 确保输出目录存在(CLI 直接调用时尤其容易漏建)
|
||||
_odir = os.path.dirname(os.path.abspath(vrm_path))
|
||||
try:
|
||||
os.makedirs(_odir, exist_ok=True)
|
||||
except OSError as e:
|
||||
raise OSError("无法创建输出目录 %s:%s" % (_odir, e))
|
||||
|
||||
def _log(msg, tag=None):
|
||||
if log is not None:
|
||||
try:
|
||||
log(msg, tag)
|
||||
except TypeError:
|
||||
log(msg)
|
||||
|
||||
if model is None:
|
||||
model = pmxio.read_pmx(pmx_path)
|
||||
skeleton.fix_facing(model, _log)
|
||||
base_dir = os.path.dirname(os.path.abspath(pmx_path))
|
||||
verts = model["vertices"]
|
||||
bones = model["bones"]
|
||||
faces = model["faces"]
|
||||
materials = model["materials"]
|
||||
is1 = str(spec).startswith("1")
|
||||
|
||||
# ---- 缩放
|
||||
if scale_mode in ("auto", "mmd", None, ""):
|
||||
ys = [v["pos"][1] for v in verts] or [0.0]
|
||||
height = max(ys) - min(ys)
|
||||
scale = (1.6 / height) if height > 1e-6 else 0.08
|
||||
else:
|
||||
scale = float(scale_mode)
|
||||
|
||||
# ---- 手性修正(2026-09-18 重写,别改回「绕 Y 旋转 180°」)
|
||||
# PMX(左手系)数值:脸 -Z、左手 +X(实测小食Taberu:
|
||||
# 両目 Z=-0.75,左腕 X=+1.34 / 右腕 X=-1.34)。
|
||||
# glTF(右手系)里合法人形:脸 -Z ⇒ 左手 -X;脸 +Z ⇒ 左手 +X。
|
||||
# 所以必须反射一个轴:0.x(脸 -Z)取反 x;1.0(脸 +Z)取反 z。
|
||||
# y180 是纯旋转,改不了手性 → 转出的 VRM 左右翻转(实测 Blender 可见)。
|
||||
# rotate="none" 仅用于调试(原样输出,左右是反的)。
|
||||
if rotate in ("auto", "y180", None, ""): # y180 为旧值,视同 auto
|
||||
mx, mz = (1.0, -1.0) if is1 else (-1.0, 1.0)
|
||||
else: # "none"
|
||||
mx, mz = 1.0, 1.0
|
||||
|
||||
def xf(p):
|
||||
x, y, z = p
|
||||
return (x * mx * scale, y * scale, z * mz * scale)
|
||||
|
||||
def xf_dir(p):
|
||||
x, y, z = p
|
||||
return (x * mx, y, z * mz)
|
||||
|
||||
def unit(left_amount, up_amount, front_amount):
|
||||
if is1: # VRM 1.0:左 +X、前 +Z
|
||||
return (left_amount, up_amount, front_amount)
|
||||
return (-left_amount, up_amount, -front_amount)
|
||||
|
||||
_log("PMX:顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d"
|
||||
% (len(verts), len(faces) // 3, len(bones), len(materials),
|
||||
len(model["morphs"])))
|
||||
|
||||
# ---- 骨骼预处理(都在 PMX 坐标里做,最后统一过 xf):付与骨合并、humanoid、T-pose
|
||||
# 骨骼表情烘焙用不带别名的权重,网格用带别名的:先算前者,后者只重算挂在别名骨上的顶点
|
||||
if raw_weights is None:
|
||||
raw_weights = mesh.vertex_weights(verts, len(bones), {})
|
||||
bs = skeleton.prepare_bones(bones, is1, _log, weighted={b for wl in raw_weights for b, w in wl if w > 0})
|
||||
vweights = mesh.vertex_weights(verts, len(bones), bs.alias, base=raw_weights)
|
||||
for n, rb, rp, lb, lp in mesh.mirror_mismatches(verts, raw_weights, vweights, bs.human_b):
|
||||
_log("权重:左右对称的 %d 对顶点,右侧主要绑在 %s(%s),左侧却绑在 %s(%s),"
|
||||
"动作时这部分会变形。可能是模型的权重错误,建议在 PmxEditor 中检查"
|
||||
% (n, bones[rb]["name"], mesh.LIMB_PART.get(rp, rp), bones[lb]["name"],
|
||||
mesh.LIMB_PART.get(lp, lp)), "warn")
|
||||
glob, bpos, vpos, vnrm, vmat = skeleton.apply_tpose(verts, bones, bs, vweights, tpose, _log)
|
||||
|
||||
# ---- 缠绕顺序自动判定:必须用「镜像后」的数据投票。
|
||||
# 镜像反射会把「从外面看逆时针」颠倒成顺时针,所以正常情况下
|
||||
# auto 在这里会判定为「需要反转」——这不是回到老 bug,
|
||||
# 老 bug 是「没有反射时硬编码反转」。
|
||||
if reverse_winding in ("auto", None, ""):
|
||||
flip, ag, dis = pmxio.detect_winding(
|
||||
[xf(p) for p in vpos], [xf_dir(n) for n in vnrm], faces)
|
||||
reverse_winding = bool(flip)
|
||||
_log("绕序自动判定(手性修正后):与法线同向 %d 面 / 反向 %d 面 → %s"
|
||||
% (ag, dis, "需要反转" if flip else "保持不变"))
|
||||
else:
|
||||
reverse_winding = bool(reverse_winding)
|
||||
|
||||
_log("缩放:%.5f(MMD 单位 → 米)· 手性修正:%s · 绕序:%s"
|
||||
% (scale,
|
||||
("Z 轴取反" if is1 else "X 轴取反") if (mx, mz) != (1.0, 1.0) else "无",
|
||||
"反转" if reverse_winding else "保持不变"))
|
||||
|
||||
# ---- 骨骼 → glTF 节点;humanoid 缺的必需骨位补占位
|
||||
tree = skeleton.NodeTree(bones, bs, bpos, xf)
|
||||
# 0.x 的两节拇指(没有掌根那节):补上 ThumbProximal,和 1.0 一样从第二节(Intermediate)开始对应
|
||||
roots = [] if is1 else [s + "ThumbProximal" for s in ("left", "right")
|
||||
if s + "ThumbIntermediate" in bs.human_b and s + "ThumbProximal" not in bs.human_b]
|
||||
human = tree.humanoid(bs.human_b, bs.required, unit, _log, roots)
|
||||
tree.lower_hips(human, _log)
|
||||
|
||||
# ---- PMX 物理 → SpringBone(1.0 写 VRMC_springBone;0.x 由同一份结果换算成 secondaryAnimation)
|
||||
spring_ext = None
|
||||
if spring and auto_spring and autophys.needed(model):
|
||||
autophys.synthesize(model, bs.parents, bs.alias, bs.human_b, _log)
|
||||
# 按比例跟随的付与骨拆权重:放在自动补物理之后,补出来的摆动骨也算带物理、不拆
|
||||
vweights = skeleton.split_partial(bones, bs, vweights, model.get("rigid_bodies"), _log)
|
||||
checks.report(bones, bs, raw_weights, vweights, bpos, vpos, scale, _log)
|
||||
if spring:
|
||||
spring_ext = _build_springs(
|
||||
model, bs.parents, bs.alias, bs.human_b, glob, bpos, scale, xf,
|
||||
tree.bone_node, tree.node_pos, tree.add_node,
|
||||
include_lower=spring_skirt, stiffness_mul=spring_stiffness,
|
||||
gravity=spring_gravity, gravity_lower=spring_gravity_skirt,
|
||||
set_parent=tree.set_parent, cloth=(vnrm, vweights, xf_dir), log=_log,
|
||||
**(spring_opts or {}))
|
||||
if spring_ext and not is1:
|
||||
vweights = springbone_v0.fold(tree, bones, vweights, spring_ext, human.values(), _log)
|
||||
human = _prune_nodes(tree, bones, vweights, human, spring_ext, collapse_bones, _log)
|
||||
nodes, top_nodes = tree.gltf_nodes()
|
||||
if spring_ext and not is1:
|
||||
springbone_v0.order_children(nodes, spring_ext)
|
||||
|
||||
# ---- 视线转角:按眼球几何算(lookAt 和补的视线表情都用它)
|
||||
look, note = None, None
|
||||
if "leftEye" in bs.human_b or "rightEye" in bs.human_b:
|
||||
look, note = morphbake.eye_look_range(model, vweights, bs.parents,
|
||||
[bs.human_b.get("leftEye"), bs.human_b.get("rightEye")])
|
||||
if look:
|
||||
_log("视线:左右 %.1f° · 下 %.1f° · 上 %.1f°(%s)"
|
||||
% (look["lookLeft"], look["lookDown"], look["lookUp"], note))
|
||||
elif note:
|
||||
_log("视线:" + note, "warn")
|
||||
|
||||
# ---- 逐材质构建网格(材质表情会影响材质的 alphaMode,表情要先整理)
|
||||
gb = vrmio.GLBBuilder()
|
||||
gb.samplers.append(vrmio.default_sampler(tex_no_mip))
|
||||
gaze_extra = _gaze(model, bs.human_b, is1, gaze, _log, look)
|
||||
if extra_expr and max_morphs != 0:
|
||||
expressions.add_extras(model, _log)
|
||||
flat = expressions._flatten_morphs(model["morphs"], model, gaze_extra, weights=raw_weights)
|
||||
gaze_split = morphbake.split_gaze(flat, {n for n, _ in gaze_extra})
|
||||
# max_morphs: None = 全部;0 = 不导出;n = 只取前 n 个
|
||||
if max_morphs is not None and max_morphs >= 0:
|
||||
flat = flat[:int(max_morphs)]
|
||||
# unity_outline:源 Unity 材质自己开了描边(FBX → PMX 时写进了 edge 字段)。
|
||||
# 它和「按 PMX 轮廓线描边」是两回事,前者要无条件保留,后者由用户开关决定。
|
||||
mats = MaterialBuilder(model, base_dir, gb, is1, flat, outline=(outline or unity_outline),
|
||||
force_double_sided=force_double_sided,
|
||||
tex_opt=textures.Optimizer(tex_max, tex_jpeg), known_alpha=tex_alpha)
|
||||
mats.prefetch(threads)
|
||||
prims, mat_gidx = mesh.build_primitives(model, xf, xf_dir, vpos, vnrm, vweights,
|
||||
reverse_winding, mats.make)
|
||||
# skin.joints 只放留下的骨;JOINTS_0 从 PMX 骨序号换成在 joints 里的位置
|
||||
joint_bones = [i for i in range(len(bones)) if tree.bone_node(i) is not None]
|
||||
mesh.remap_joints(prims, {b: k for k, b in enumerate(joint_bones)})
|
||||
_log("网格:按材质分为 %d 个部分" % len(prims))
|
||||
mats.log_summary(_log)
|
||||
if not prims:
|
||||
raise RuntimeError("此 PMX 没有可用的面数据")
|
||||
mesh.write_accessors(gb, prims)
|
||||
|
||||
# ---- 表情 → morph target + VRM expression
|
||||
expr = expressions.build_expressions(flat, prims, mats, mat_gidx, gb, xf, vmat,
|
||||
is1, sparse_morphs, _log, combo=combo_expr,
|
||||
hidden={d for _, d, _ in gaze_split.values()})
|
||||
target_names = expr["target_names"]
|
||||
_gaze_binds(expr, gaze_split, look, is1)
|
||||
|
||||
# ---- 按表情分网格(每个网格只带动得到它的 morph target)
|
||||
groups = mesh.group_meshes(prims, len(target_names))
|
||||
gltf_meshes, where = mesh.build_meshes(gb, prims, groups, target_names,
|
||||
model["name"] or "body", sparse_morphs, prim_names=not is1)
|
||||
if len(gltf_meshes) > 1:
|
||||
_log("网格:按表情分为 %d 个(%s)" % (len(gltf_meshes), "、".join(
|
||||
"%s:%d 个表情" % (m["name"], len(m.get("extras", {}).get("targetNames", ()))) for m in gltf_meshes)))
|
||||
|
||||
inv = []
|
||||
for i in joint_bones:
|
||||
p = tree.node_pos(tree.bone_node(i)) # 节点位置(hips 下移过)
|
||||
inv.extend([1.0, 0.0, 0.0, 0.0,
|
||||
0.0, 1.0, 0.0, 0.0,
|
||||
0.0, 0.0, 1.0, 0.0,
|
||||
-p[0], -p[1], -p[2], 1.0])
|
||||
if not inv:
|
||||
inv = [1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0]
|
||||
ibm = gb.add_accessor(inv, vrmio.FLOAT, "MAT4", minmax=False)
|
||||
|
||||
mesh_nodes = []
|
||||
taken = {n.get("name") for n in nodes}
|
||||
for k, m in enumerate(gltf_meshes):
|
||||
mesh_nodes.append(len(nodes))
|
||||
# 网格按材质起名,可能和骨骼重名(「髪」):Unity 里按名字找物体的会找错,加后缀
|
||||
nm = expressions.uniq_name("mesh" if len(gltf_meshes) == 1 else m["name"], taken)
|
||||
taken.add(nm)
|
||||
nodes.append({"name": nm, "mesh": k, "skin": 0})
|
||||
root_index = len(nodes)
|
||||
nodes.append({"name": "root",
|
||||
"children": list(top_nodes) + mesh_nodes})
|
||||
|
||||
joints = [tree.bone_node(i) for i in joint_bones]
|
||||
if not joints:
|
||||
joints = [0]
|
||||
|
||||
gltf = {
|
||||
"asset": {"version": "2.0", "generator": "VRMify Enhanced"},
|
||||
"scene": 0,
|
||||
"scenes": [{"nodes": [root_index]}],
|
||||
"nodes": nodes,
|
||||
"meshes": gltf_meshes,
|
||||
"skins": [{"joints": joints, "inverseBindMatrices": ibm,
|
||||
"skeleton": root_index}],
|
||||
"materials": mats.materials,
|
||||
"accessors": gb.accessors,
|
||||
"bufferViews": gb.bufferViews,
|
||||
"buffers": [{"byteLength": len(gb.bin)}],
|
||||
}
|
||||
if gb.images:
|
||||
gltf["images"] = gb.images
|
||||
gltf["textures"] = gb.textures
|
||||
gltf["samplers"] = gb.samplers
|
||||
|
||||
# 绑定的 morph target 序号 → 各网格里的;1.0 的 node 指向网格节点,0.x 的 mesh 指向网格号
|
||||
mesh.remap_binds(expr, where, mesh_nodes, is1)
|
||||
|
||||
# ---- VRM 扩展
|
||||
meta = meta or {}
|
||||
title = meta.get("title") or model["name"] or "PMX Model"
|
||||
if is1:
|
||||
gltf["extensionsUsed"] = ["VRMC_vrm", "VRMC_materials_mtoon"]
|
||||
gltf["extensions"] = {"VRMC_vrm": vrm_ext.build_vrm1(meta, title, human,
|
||||
mesh_nodes, expr, look)}
|
||||
if spring_ext:
|
||||
if spring_center:
|
||||
# center = 根节点:在模型自身的空间里模拟。应用里人物整体移动(走路的
|
||||
# 根运动、平移)时,头发/裙摆不会因惯性被甩、往后拖压到腿上,只对身体本身
|
||||
# 的动作有反应。实测走路时头发摆幅 0.73→0.15、胸部配饰 0.28→0.05、
|
||||
# 裙摆穿进大腿的顶点 10→3。规范要求 center 是链首关节或其祖先,根节点满足
|
||||
for sp in spring_ext["springs"]:
|
||||
sp["center"] = root_index
|
||||
gltf["extensionsUsed"].append("VRMC_springBone")
|
||||
gltf["extensions"]["VRMC_springBone"] = spring_ext
|
||||
else:
|
||||
gltf["extensionsUsed"] = ["VRM"]
|
||||
secondary = (springbone_v0.to_secondary(spring_ext, nodes, root_index if spring_center else None, _log)
|
||||
if spring_ext else None)
|
||||
gltf["extensions"] = {"VRM": vrm_ext.build_vrm0(meta, title, human, expr,
|
||||
mats.props_0x, look, len(gltf_meshes),
|
||||
secondary)}
|
||||
|
||||
size = vrmio.write_glb(gltf, gb.bin, vrm_path)
|
||||
n_expr = (len(expr["preset"]) + len(expr["custom"])) if is1 else len(expr["blend_groups"])
|
||||
_log("已写出 %s(%.2f MB)· 节点 %d · morph target %d · 表情 %d"
|
||||
% (os.path.basename(vrm_path), size / 1048576.0, len(nodes),
|
||||
len(target_names), n_expr), "ok")
|
||||
return {"nodes": len(nodes), "primitives": len(prims), "meshes": len(gltf_meshes),
|
||||
"morphs": len(target_names), "bytes": size, "scale": scale,
|
||||
"vertices": sum(p["vcount"] for p in prims)}
|
||||
|
||||
|
||||
def _prune_nodes(tree, bones, vweights, human, spring_ext, collapse, log):
|
||||
"""去掉不起作用的节点,返回新的 humanoid 骨位 → 节点。
|
||||
|
||||
留下:humanoid 骨、有权重的骨、SpringBone 关节和碰撞体,以及连接它们的祖先(collapse 时祖先不留)。
|
||||
MMD 模型里 IK、合并进主骨的付与骨(足D 等)、末端骨(先)、操作中心之类的骨不带动任何顶点,
|
||||
在 VRM 里只是空节点,Blender / Unity 里看起来像一堆挂错位置的碎骨头。
|
||||
"""
|
||||
if not bones:
|
||||
return human
|
||||
core = set(human.values())
|
||||
for wl in vweights:
|
||||
for b, w in wl:
|
||||
if w > 0:
|
||||
core.add(tree.bone_node(b))
|
||||
refs = []
|
||||
if spring_ext:
|
||||
refs = [j for sp in spring_ext["springs"] for j in sp["joints"]] + spring_ext.get("colliders", [])
|
||||
core.update(o["node"] for o in refs)
|
||||
before = len(tree.names)
|
||||
new = tree.prune(core, collapse)
|
||||
for o in refs:
|
||||
o["node"] = new[o["node"]]
|
||||
if before > len(tree.names):
|
||||
log("骨骼:已去掉 %d 个不起作用的节点(%s),保留 %d 个"
|
||||
% (before - len(tree.names),
|
||||
"无权重且不属于 humanoid、物理的骨,包括中间的控制骨" if collapse
|
||||
else "IK、末端骨、已合并的付与骨等无权重且不属于 humanoid、物理的骨", len(tree.names)))
|
||||
return {k: new[v] for k, v in human.items()}
|
||||
|
||||
|
||||
# -------------------------------------------------------------------- cli --
|
||||
def _gaze(model, human_b, is1, enabled, log, look=None):
|
||||
"""要补的视线表情 → [(名字, 骨骼表情 offsets)](交给 _flatten_morphs 烘焙)。"""
|
||||
if not enabled or "leftEye" not in human_b or "rightEye" not in human_b:
|
||||
return []
|
||||
have = set()
|
||||
for mo in model["morphs"]:
|
||||
p = expressions._table_preset(mo["name"], True) or expressions._preset_en(mo["name"], True)
|
||||
if p:
|
||||
have.add(p)
|
||||
# 左右(上下)都要补时按 GAZE_MAX 烘焙,之后拆成横向 + 深度两个场、权重给出实际角度(morphbake.split_gaze);
|
||||
# 只补一边的按实际角度烘焙
|
||||
deg = dict(look or morphbake.GAZE_DEG)
|
||||
for a, b, axis in morphbake.GAZE_PAIRS:
|
||||
if a not in have and b not in have:
|
||||
deg[a] = deg[b] = morphbake.GAZE_MAX[axis]
|
||||
out = [(n, offs) for n, offs in morphbake.gaze_offsets(human_b["leftEye"], human_b["rightEye"], deg)
|
||||
if n not in have]
|
||||
if out:
|
||||
log("表情:补充视线表情 %s(由转动眼骨烘焙,lookAt 仍使用骨骼)" % " / ".join(n for n, _ in out))
|
||||
return out
|
||||
|
||||
|
||||
def _gaze_binds(expr, split, look, is1):
|
||||
"""拆过的视线表情 → 横向场 + 深度场两个绑定,权重按实际视线角度(vrm_edit 改视线角度时同样重算)。"""
|
||||
names = expr["target_names"]
|
||||
for p, (tan, depth, axis) in split.items():
|
||||
wt, wd = morphbake.gaze_weights((look or morphbake.GAZE_DEG)[p], axis)
|
||||
slots = [(len(names) - 1 - names[::-1].index(n), w) for n, w in ((tan, wt), (depth, wd))]
|
||||
if is1:
|
||||
obj = expr["preset"].get(p)
|
||||
if obj and (obj.get("extras") or {}).get("source") == p:
|
||||
obj["morphTargetBinds"] = [{"node": 0, "index": i, "weight": w} for i, w in slots]
|
||||
else:
|
||||
for gr in expr["blend_groups"]:
|
||||
if gr["name"] == p and gr["presetName"] == p.lower():
|
||||
gr["binds"] = [{"mesh": 0, "index": i, "weight": round(w * 100, 4)} for i, w in slots]
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description="PMX → VRM(纯 Python)")
|
||||
ap.add_argument("pmx")
|
||||
ap.add_argument("-o", "--out", default=None)
|
||||
ap.add_argument("--spec", default="1.0", choices=["1.0", "0x"])
|
||||
ap.add_argument("--scale", default="auto",
|
||||
help="auto(归一到 1.6 m)或具体倍率")
|
||||
ap.add_argument("--rotate", default="auto", choices=["auto", "none", "y180"])
|
||||
ap.add_argument("--flip-winding", action="store_true",
|
||||
help="强制反转三角形缠绕顺序(默认自动判定)")
|
||||
ap.add_argument("--force-double-sided", action="store_true",
|
||||
help="所有材质强制双面(模型仍有镂空时的兜底手段)")
|
||||
ap.add_argument("--tpose", action="store_true",
|
||||
help="把 A-pose 手臂抬成 VRM 规范的 T-pose(默认保留原始姿势,不重摆骨架)")
|
||||
ap.add_argument("--keep-pose", action="store_true", help=argparse.SUPPRESS) # 旧版兼容:默认已是保留原姿势
|
||||
ap.add_argument("--no-spring", action="store_true",
|
||||
help="不把 PMX 物理转成 SpringBone(默认转换,仅 VRM 1.0)")
|
||||
ap.add_argument("--no-spring-skirt", action="store_true",
|
||||
help="跳过下半身(hips / 腿)下的物理链,通常是裙摆")
|
||||
ap.add_argument("--spring-stiffness", type=float, default=1.0,
|
||||
help="SpringBone 硬度整体倍率(默认 1.0,越大越硬)")
|
||||
ap.add_argument("--spring-gravity", type=float, default=0.0,
|
||||
help="SpringBone 重力(头发等,默认 0:保持 PMX 原造型;"
|
||||
"斜着散开的长发加重力会被拉垂)")
|
||||
ap.add_argument("--spring-gravity-skirt", type=float, default=0.1,
|
||||
help="下半身(裙摆)SpringBone 重力(默认 0.1,抬腿时裙片落回腿上)")
|
||||
ap.add_argument("--no-auto-spring", action="store_true",
|
||||
help="模型没有物理刚体时不自动补(默认按骨骼名给头发、裙摆、袖子等加 SpringBone)")
|
||||
ap.add_argument("--no-combo-expr", action="store_true",
|
||||
help="情绪预设不组合眉 / 眼 / 嘴(默认组合,像 VRoid;关掉时每个预设只对应一个 PMX 表情)")
|
||||
ap.add_argument("--keep-control-bones", action="store_true",
|
||||
help="保留没有权重的中间骨(全ての親 / センター / グルーブ / 腰 等;默认去掉,层级像 VRoid)")
|
||||
ap.add_argument("--no-extra-expr", action="store_true",
|
||||
help="不补充 hideHighlight(关掉眼睛高光)、tongue(吐舌)表情")
|
||||
ap.add_argument("--no-gaze", action="store_true",
|
||||
help="不补视线表情(默认有左右眼骨时补 lookUp / lookDown / lookLeft / lookRight)")
|
||||
ap.add_argument("--no-spring-center", action="store_true",
|
||||
help="SpringBone 不设 center(默认以模型根节点为 center,人物整体移动时"
|
||||
"头发/裙摆不会被甩)")
|
||||
ap.add_argument("--outline", action="store_true",
|
||||
help="按 PMX 的轮廓线设置写出 MToon 描边(默认不描边)")
|
||||
ap.add_argument("--dense-morphs", action="store_true",
|
||||
help="表情用密集存储(默认稀疏存储,文件小很多)")
|
||||
ap.add_argument("--max-morphs", type=int, default=None,
|
||||
help="只导出前 N 个表情(0 = 不导出,默认全部)")
|
||||
ap.add_argument("--tex-max", type=int, default=0,
|
||||
help="贴图最大边长(如 2048 / 1024,默认 0 = 原样;需要 Pillow)")
|
||||
ap.add_argument("--tex-jpeg", action="store_true",
|
||||
help="不透明贴图改存 JPEG(文件小很多;需要 Pillow)")
|
||||
ap.add_argument("--tex-no-mip", action="store_true",
|
||||
help="贴图不生成 mipmap,缓解 UV 岛无边距时沿接缝渗出的白边(远景会有轻微锯齿)")
|
||||
ap.add_argument("--title", default=None)
|
||||
ap.add_argument("--author", default=None)
|
||||
a = ap.parse_args(argv)
|
||||
|
||||
out = a.out or (os.path.splitext(a.pmx)[0] + ".vrm")
|
||||
meta = {}
|
||||
if a.title:
|
||||
meta["title"] = a.title
|
||||
if a.author:
|
||||
meta["author"] = a.author
|
||||
st = convert(a.pmx, out, spec=("1.0" if a.spec == "1.0" else "0.x"),
|
||||
scale_mode=a.scale, rotate=a.rotate,
|
||||
reverse_winding=(True if a.flip_winding else "auto"),
|
||||
meta=meta, max_morphs=a.max_morphs,
|
||||
force_double_sided=a.force_double_sided,
|
||||
tpose=a.tpose, outline=a.outline,
|
||||
spring=not a.no_spring, spring_skirt=not a.no_spring_skirt,
|
||||
spring_stiffness=a.spring_stiffness,
|
||||
spring_gravity=a.spring_gravity,
|
||||
spring_gravity_skirt=a.spring_gravity_skirt,
|
||||
spring_center=not a.no_spring_center, auto_spring=not a.no_auto_spring,
|
||||
sparse_morphs=not a.dense_morphs,
|
||||
tex_max=a.tex_max, tex_jpeg=a.tex_jpeg, tex_no_mip=a.tex_no_mip, gaze=not a.no_gaze, combo_expr=not a.no_combo_expr, extra_expr=not a.no_extra_expr,
|
||||
collapse_bones=not a.keep_control_bones,
|
||||
log=lambda msg, tag=None: print(msg))
|
||||
print("完成:%s(%.2f MB)" % (out, st["bytes"] / 1048576.0))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,757 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""PSK / PSKX(Unreal ActorX)→ MMD PMX,纯 Python 标准库。
|
||||
|
||||
和项目里其它转换器保持同一套口径:
|
||||
· 换轴 (x, y, z)_psk → (x, z, y)_pmx(Y/Z 对调,详见 convert() 里的长注释)
|
||||
· 缩放 按包围盒高度归一到 MMD 常规的 20 单位
|
||||
· 居中 x/z 取包围盒中心、y 脚底归零
|
||||
· 骨骼 Bip001 这套 3dsMax Biped 命名默认转成 MMD 标准日文骨名,
|
||||
英文原名写进骨骼的英文名(name_en)字段,两边都不丢
|
||||
· 表情 PSK 的 MRPHINFO/MRPHDATA(顶点位移增量)→ PMX 顶点表情
|
||||
· 材质 按材质名在源目录找同名贴图;toon 一律不使用
|
||||
|
||||
骨骼世界矩阵的坑见 formats/pskio.py 头部注释(四元数要取共轭)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
for _sub in ("formats", "convert"):
|
||||
_p = os.path.join(BASE, _sub)
|
||||
if os.path.isdir(_p) and _p not in sys.path:
|
||||
sys.path.insert(0, _p)
|
||||
|
||||
import pskio
|
||||
import pmxio
|
||||
|
||||
|
||||
# --------------------------------------------------------- toon(不使用) ------
|
||||
# PMX 材质的 toon 字段由「共有Toonフラグ」决定宽度,两个方向都别搞反
|
||||
# (PMX 规范 + mmd_tools 的 `is_shared_toon_texture` 一致):
|
||||
#
|
||||
# flag = 1 → 共享/内建 toon。字段是 **1 字节编号**,引用 MMD 安装目录
|
||||
# `Data/` 下的 toon01.bmp … toon10.bmp。
|
||||
# ⚠ **编号 0 就是 toon01.bmp,不是「不使用」**。mmd_tools 源码里
|
||||
# 写死了这个 +1:
|
||||
# toon_path = "toon%02d.bmp" % (shared_toon_texture + 1)
|
||||
# MMD 的 Data 目录里**根本没有 toon00.bmp**(只有 toon01..toon10),
|
||||
# 所以「编号 0 = toon00.bmp = 不使用 toon」这个说法是错的。
|
||||
#
|
||||
# flag = 0 → 本模型**纹理表**里的贴图。字段是**纹理索引宽度**(ti),
|
||||
# **-1 = なし(不使用)**。
|
||||
#
|
||||
# 所以「不使用 toon」唯一正确的写法是 `toon_flag = 0, toon = -1`。
|
||||
#
|
||||
# 2026-09-24 修正:以前四个转换器都写 `flag=1, toon=0`(注释误以为 0 是
|
||||
# toon00.bmp = 不使用),实际等于给每个材质硬套了一层 **toon01.bmp**,用户反馈
|
||||
# 「PMX 文件还是自动上了 Toon 路径」。
|
||||
# 对照实测:用户本机那份公认正常的 `Anastasya.pmx`,全部 13 个材质都是
|
||||
# `toon_flag=0 / toon=-1`;而本工具产出的 `R2T1FeiBiMd10011.pmx` 是 `flag=1/0`。
|
||||
_TOON_NONE_FLAG = 0
|
||||
_TOON_NONE_INDEX = -1
|
||||
|
||||
|
||||
def _log_default(msg, tag=None):
|
||||
print(msg)
|
||||
|
||||
|
||||
# ------------------------------------------------------------- 骨名映射 ------
|
||||
# Bip001(3dsMax Biped)→ MMD 标准骨名。映射不到的保留原名。
|
||||
_BONE_JP = {
|
||||
"Root": "全ての親",
|
||||
"Bip001": "グルーブ",
|
||||
"Bip001Pelvis": "センター",
|
||||
"Bip001Spine": "上半身",
|
||||
"Bip001Spine1": "上半身1",
|
||||
"Bip001Spine2": "上半身2",
|
||||
"Bip001Neck": "首",
|
||||
"Bip001Head": "頭",
|
||||
"Bip001LClavicle": "左肩",
|
||||
"Bip001RClavicle": "右肩",
|
||||
"Bip001LUpperArm": "左腕",
|
||||
"Bip001RUpperArm": "右腕",
|
||||
"Bip001LForearm": "左ひじ",
|
||||
"Bip001RForearm": "右ひじ",
|
||||
"Bip001LHand": "左手首",
|
||||
"Bip001RHand": "右手首",
|
||||
"Bip001LThigh": "左足",
|
||||
"Bip001RThigh": "右足",
|
||||
"Bip001LCalf": "左ひざ",
|
||||
"Bip001RCalf": "右ひざ",
|
||||
"Bip001LFoot": "左足首",
|
||||
"Bip001RFoot": "右足首",
|
||||
"Bip001LToe0": "左つま先",
|
||||
"Bip001RToe0": "右つま先",
|
||||
}
|
||||
|
||||
# 手指:Bip001LFinger0 / LFinger01 / LFinger1 / LFinger11 ...
|
||||
# 拇指从 0 起,其余手指从 1 起(MMD 标准骨名的惯例)。
|
||||
_FINGER_JP = ("親指", "人指", "中指", "薬指", "小指")
|
||||
_FW = ("0", "1", "2", "3", "4", "5")
|
||||
_SIDE_JP = {"L": "左", "R": "右"}
|
||||
_FINGER_RE = re.compile(r"^Bip001([LR])Finger(\d)(\d?)$")
|
||||
|
||||
|
||||
def bone_jp(name):
|
||||
"""单根骨骼名 → MMD 日文名;没有对应条目就返回 None(保留原名)。"""
|
||||
if name in _BONE_JP:
|
||||
return _BONE_JP[name]
|
||||
m = _FINGER_RE.match(name or "")
|
||||
if m:
|
||||
side, finger, seg = m.group(1), int(m.group(2)), m.group(3)
|
||||
if 0 <= finger < len(_FINGER_JP):
|
||||
base = 0 if finger == 0 else 1 # 拇指从 0、其余从 1
|
||||
idx = base + (int(seg) if seg else 0)
|
||||
if idx < len(_FW):
|
||||
return "%s%s%s" % (_SIDE_JP[side], _FINGER_JP[finger], _FW[idx])
|
||||
return None
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- 小工具 ----
|
||||
def _uniq(name, used):
|
||||
base = (name or "").strip() or "bone"
|
||||
if base not in used:
|
||||
used.add(base)
|
||||
return base
|
||||
i = 1
|
||||
while "%s_%d" % (base, i) in used:
|
||||
i += 1
|
||||
nm = "%s_%d" % (base, i)
|
||||
used.add(nm)
|
||||
return nm
|
||||
|
||||
|
||||
def _morph_panel(name):
|
||||
"""PMX 表情面板:1=眉 2=目 3=口 4=その他(只影响 MMD 里的分组)。"""
|
||||
n = (name or "").lower()
|
||||
if n.startswith("b_") or "brow" in n or n.startswith("mayu"):
|
||||
return 1
|
||||
if n.startswith("e_") or "pupil" in n or "eye" in n or n.startswith("hitomi"):
|
||||
return 2
|
||||
if (n.startswith("l_") or n.startswith("r_") or n.startswith("aa")
|
||||
or n.startswith("mouth") or "lip" in n or "tooth" in n
|
||||
or "tongue" in n or n.startswith("kuch")):
|
||||
return 3
|
||||
return 4
|
||||
|
||||
|
||||
_TEX_EXT = (".png", ".bmp", ".tga", ".jpg", ".jpeg", ".dds")
|
||||
|
||||
|
||||
def _copy_tex(src, dst, remove_alpha):
|
||||
"""拷贴图;remove_alpha 时复用 uemodel2pmx 那套去 alpha 逻辑。"""
|
||||
if remove_alpha:
|
||||
try:
|
||||
import uemodel2pmx
|
||||
r = uemodel2pmx._copy_texture(src, dst, True)
|
||||
if r:
|
||||
return r
|
||||
except Exception:
|
||||
pass
|
||||
shutil.copyfile(src, dst)
|
||||
return "copied"
|
||||
|
||||
|
||||
def _find_texture(folder, mat_name):
|
||||
"""按材质名在同目录(含 Textures 子目录)找贴图文件,返回绝对路径或 None。"""
|
||||
cands = []
|
||||
nm = mat_name or ""
|
||||
cands.append(nm)
|
||||
if nm.startswith("MI_"):
|
||||
cands.append(nm[3:])
|
||||
if nm.startswith("M_"):
|
||||
cands.append(nm[2:])
|
||||
for base in list(cands):
|
||||
for suf in ("_D", "_Diffuse", "_BaseColor", "_Albedo", "_d", "_C"):
|
||||
cands.append(base + suf)
|
||||
dirs = [folder]
|
||||
for sub in ("Textures", "textures", "Texture"):
|
||||
d = os.path.join(folder, sub)
|
||||
if os.path.isdir(d):
|
||||
dirs.append(d)
|
||||
parent = os.path.dirname(folder)
|
||||
for sub in ("Textures", "textures"):
|
||||
d = os.path.join(parent, sub)
|
||||
if os.path.isdir(d):
|
||||
dirs.append(d)
|
||||
|
||||
lower = {}
|
||||
for d in dirs:
|
||||
try:
|
||||
for f in os.listdir(d):
|
||||
st, ext = os.path.splitext(f)
|
||||
if ext.lower() in _TEX_EXT:
|
||||
lower.setdefault((d, st.lower()), f)
|
||||
except OSError:
|
||||
pass
|
||||
for base in cands:
|
||||
if not base:
|
||||
continue
|
||||
for (d, st), f in lower.items():
|
||||
if st == base.lower():
|
||||
return os.path.join(d, f)
|
||||
return None
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- 主体 ----
|
||||
def _warn_anchor_collision(out_path, log):
|
||||
"""提示 `.psk` 同名冲突(PmxEditor 的「アンカーデータ」误读)。
|
||||
|
||||
PmxEditor 打开 `xxx.pmx` 时会自动去找**同名**的 `xxx.psk`,当成它的
|
||||
「アンカー(锚点/权重编辑)数据」加载 —— 见菜单
|
||||
`[ファイル] → [アンカーデータの自動読み込み/保存]` 与它的 readme:
|
||||
「モデルファイル名と同名のアンカーデータファイル(*.psk)がある場合自動読み込み」
|
||||
而 `*.psk` 恰好又是 Unreal ActorX 网格的扩展名,也就是本工具的**输入**格式。
|
||||
于是「源 psk 和输出 pmx 同名同目录」这种最自然的用法,一定会让 PmxEditor 弹:
|
||||
|
||||
アンカーデータの読み込みに失敗しました。
|
||||
|
||||
这个报错**不影响模型**(点确定后模型照常显示),但很吓人,所以主动说一声。
|
||||
"""
|
||||
d = os.path.dirname(os.path.abspath(out_path)) or "."
|
||||
stem = os.path.splitext(os.path.basename(out_path))[0]
|
||||
clash = [f for f in (stem + ".psk", stem + ".pskx")
|
||||
if os.path.isfile(os.path.join(d, f))]
|
||||
if not clash:
|
||||
return
|
||||
log("提示:同一目录下有同名的 %s。PmxEditor 打开此 PMX 时会尝试将其作为"
|
||||
"「アンカーデータ」(锚点 / 权重数据)加载,并提示"
|
||||
"「アンカーデータの読み込みに失敗しました。」,点击确定即可,不影响模型。"
|
||||
"如需避免,可移动或重命名 PMX,或在 PmxEditor 中关闭"
|
||||
"[ファイル]→[アンカーデータの自動読み込み/保存]。"
|
||||
% " / ".join(clash), "warn")
|
||||
|
||||
|
||||
def convert(path, out_path, scale_mode="mmd", log=None, name=None,
|
||||
enable_edge=False, force_double_sided=False, textures=True,
|
||||
keep_add_uv=True, remove_alpha=True, flip_winding="auto",
|
||||
center=True, jp_bones=True, make_ik=True, export_morphs=True,
|
||||
fbx_path=None):
|
||||
"""PSK/PSKX → PMX。返回统计 dict。"""
|
||||
_l = log or _log_default
|
||||
|
||||
m = pskio.read_psk(path)
|
||||
kind = "PSKX" if m.face32 else "PSK"
|
||||
_l("读取 %s:顶点 %d · 楔 %d · 三角面 %d · 材质 %d · 骨骼 %d · 权重 %d"
|
||||
% (kind, len(m.points), len(m.wedges), len(m.faces),
|
||||
len(m.materials), len(m.bones), len(m.weights)))
|
||||
if not m.points or not m.wedges:
|
||||
raise ValueError("此文件中没有网格数据(PNTS / VTXW 为空)")
|
||||
if not m.faces:
|
||||
raise ValueError("此文件中没有面数据(FACE 块为空)")
|
||||
_l("表情 %d 个 · 附加 UV %d 套 · %s"
|
||||
% (len(m.morphs), len(m.extra_uvs),
|
||||
"含法线" if m.normals else "不含法线(将自动计算)"))
|
||||
|
||||
# ---- 坐标变换
|
||||
#
|
||||
# 实测(R2T1FeiBiMd10011.psk / R2T1AimisiMd10011.pskx 两个文件一致):
|
||||
# Bip001LHand 在 +X、Bip001RHand 在 -X → PSK 的 +X = 模型**左手**
|
||||
# 脚踝 → 脚尖的方向 ≈ (0, -0.47, -0.88) → PSK 的 -Y = 模型**正面**
|
||||
# (另有一条独立佐证:整体包围盒在 +Y 侧明显更长,那是头发/披风/背包)
|
||||
# 整体 +Z = 上
|
||||
# 而 MMD/PMX 的约定是:**正面 -Z、左手 +X、上 +Y**
|
||||
# (见 pmx2vrm.py 里对实测模型「小食Taberu」的记录:両目 Z=-0.75、
|
||||
# 左腕 X=+1.34;本机 F:\测试\...\Anastasya.pmx 复核同样成立)。
|
||||
#
|
||||
# 所以只要把 PSK 的 Y 和 Z 对调就同时满足三条:
|
||||
# 左手 +X → +X ✓ 上 +Z → +Y ✓ 正面 -Y → -Z ✓
|
||||
#
|
||||
# 注意这里**不是** uemodel2pmx 那种 (x, z, -y):
|
||||
# (x, z, -y) 行列式 +1(纯旋转,不改手性),会把正面 -Y 送到 **+Z**,
|
||||
# 于是人物在 MMD 里背对镜头 —— 这正是 2026-09-24 修掉的那个 bug。
|
||||
# (x, z, y) 行列式 -1,正好把 PSK 的右手系翻成 MMD 的左手系,手性才对上。
|
||||
# 因为绕序会跟着反射一起翻,flip_winding="auto" 的投票(以及没有法线时的
|
||||
# 兜底)都要相应反转,见下面「绕序」那一段。
|
||||
def xf(p):
|
||||
return (p[0], p[2], p[1])
|
||||
|
||||
# ---- 顶点:一个 wedge 对应一个 PMX 顶点(UV/材质分流都在 wedge 上)
|
||||
n_wedge = len(m.wedges)
|
||||
n_point = len(m.points)
|
||||
raw_pos = []
|
||||
bad_wedge = 0
|
||||
for pi, u, v, _mi in m.wedges:
|
||||
if not (0 <= pi < n_point):
|
||||
pi = 0
|
||||
bad_wedge += 1
|
||||
raw_pos.append(m.points[pi])
|
||||
if bad_wedge:
|
||||
_l("网格:%d 个楔的点索引越界,已改用第 0 个点" % bad_wedge, "warn")
|
||||
|
||||
pts = [xf(p) for p in raw_pos]
|
||||
ys = [p[1] for p in pts]
|
||||
lo_y, hi_y = (min(ys), max(ys)) if ys else (0.0, 1.0)
|
||||
if scale_mode in ("mmd", "auto", None):
|
||||
scale = 20.0 / max(hi_y, 1e-6)
|
||||
if hi_y <= 0:
|
||||
scale = 20.0 / max(abs(lo_y), 1e-6)
|
||||
_l("缩放:源高 %.2f 单位 × %.6f → %.2f(MMD 标准身高 20)"
|
||||
% (hi_y, scale, hi_y * scale))
|
||||
elif scale_mode in ("raw", "none", 1, 1.0):
|
||||
# 与 fbx2pmx 的 --scale raw 对齐:保持源尺寸不动。
|
||||
# (以前这里只认 "mmd" 和数字,写 --scale raw 会直接
|
||||
# ValueError: could not convert string to float: 'raw'。)
|
||||
scale = 1.0
|
||||
_l("缩放:保持源尺寸(scale=1.0),源高 %.2f 单位" % hi_y)
|
||||
else:
|
||||
scale = float(scale_mode)
|
||||
_l("缩放:源高 %.2f 单位 × %.6f → %.2f"
|
||||
% (hi_y, scale, hi_y * scale))
|
||||
|
||||
if center and pts:
|
||||
xs = [p[0] for p in pts]
|
||||
zs = [p[2] for p in pts]
|
||||
off = (-(min(xs) + max(xs)) * 0.5 * scale,
|
||||
-lo_y * scale,
|
||||
-(min(zs) + max(zs)) * 0.5 * scale)
|
||||
_l("居中:偏移 (%.3f, %.3f, %.3f)" % off, "info")
|
||||
else:
|
||||
off = (0.0, 0.0, 0.0)
|
||||
|
||||
def sp(p):
|
||||
t = xf(p)
|
||||
return (t[0] * scale + off[0], t[1] * scale + off[1],
|
||||
t[2] * scale + off[2])
|
||||
|
||||
def sdir(d):
|
||||
"""源位移 → PMX 位移(只换轴 + 缩放,不带平移)。"""
|
||||
t = xf(d)
|
||||
return (t[0] * scale, t[1] * scale, t[2] * scale)
|
||||
|
||||
# ---- 骨骼世界坐标
|
||||
_wrot, wpos = pskio.bone_world(m)
|
||||
bone_pos = [sp(p) for p in wpos]
|
||||
n_src = len(m.bones)
|
||||
|
||||
# ---- 骨骼顺序:DFS,保证父在子前面
|
||||
kids = [[] for _ in range(n_src)]
|
||||
roots = []
|
||||
for i, b in enumerate(m.bones):
|
||||
p = b.parent_index
|
||||
if 0 <= p < n_src and p != i:
|
||||
kids[p].append(i)
|
||||
else:
|
||||
roots.append(i)
|
||||
order = []
|
||||
seen = [False] * n_src
|
||||
stack = list(reversed(roots))
|
||||
while stack:
|
||||
i = stack.pop()
|
||||
if seen[i]:
|
||||
continue
|
||||
seen[i] = True
|
||||
order.append(i)
|
||||
stack.extend(reversed(kids[i]))
|
||||
for i in range(n_src):
|
||||
if not seen[i]:
|
||||
seen[i] = True
|
||||
order.append(i)
|
||||
|
||||
slot = {bi: k for k, bi in enumerate(order)}
|
||||
used = set()
|
||||
pmx_bones = []
|
||||
n_renamed = 0
|
||||
for src in order:
|
||||
b = m.bones[src]
|
||||
jp = bone_jp(b.name) if jp_bones else None
|
||||
main_name = jp if jp else b.name
|
||||
if jp:
|
||||
n_renamed += 1
|
||||
p = b.parent_index if 0 <= b.parent_index < n_src else -1
|
||||
pmx_bones.append({
|
||||
"name": _uniq(main_name, used),
|
||||
"name_en": b.name or "bone",
|
||||
"pos": bone_pos[src],
|
||||
"parent": slot.get(p, -1),
|
||||
"layer": 0, "flag": 0, "tail_kind": 0, "tail": (0.0, 0.0, 0.0),
|
||||
"inherit_rot": None, "inherit_mov": None, "fixed_axis": None,
|
||||
"local_axis": None, "external": None, "ik": None,
|
||||
"_kids": [],
|
||||
})
|
||||
for src in order:
|
||||
b = m.bones[src]
|
||||
p = b.parent_index if 0 <= b.parent_index < n_src else -1
|
||||
if p in slot and slot[p] != slot[src]:
|
||||
pmx_bones[slot[p]]["_kids"].append(slot[src])
|
||||
|
||||
for bk in pmx_bones:
|
||||
flag = 0x0002 | 0x0004 | 0x0008 | 0x0010 # 可旋转/可移动/可显示/可操作
|
||||
k = bk.pop("_kids")
|
||||
if k:
|
||||
flag |= 0x0001 # 尾 = 骨骼(取第一个子骨骼)
|
||||
bk["tail_kind"] = 1
|
||||
bk["tail"] = k[0]
|
||||
else:
|
||||
p = bk["parent"]
|
||||
if 0 <= p < len(pmx_bones):
|
||||
d = (bk["pos"][0] - pmx_bones[p]["pos"][0],
|
||||
bk["pos"][1] - pmx_bones[p]["pos"][1],
|
||||
bk["pos"][2] - pmx_bones[p]["pos"][2])
|
||||
ln = (d[0] ** 2 + d[1] ** 2 + d[2] ** 2) ** 0.5
|
||||
bk["tail"] = ((d[0] / ln, d[1] / ln, d[2] / ln) if ln > 1e-9
|
||||
else (0.0, 1.0, 0.0))
|
||||
else:
|
||||
bk["tail"] = (0.0, 1.0, 0.0)
|
||||
bk["flag"] = flag
|
||||
_l("骨骼:%d 根%s"
|
||||
% (len(pmx_bones),
|
||||
"" if not jp_bones else "(其中 %d 根改为 MMD 标准日文名,"
|
||||
"原英文名保留在英文名中)" % n_renamed))
|
||||
|
||||
# ---- 足 IK(MMD 摆姿势几乎必用;源骨架没有,这里补标准的一套)
|
||||
def find_bone(jp_name):
|
||||
for i, b in enumerate(pmx_bones):
|
||||
if b["name"] == jp_name:
|
||||
return i
|
||||
return -1
|
||||
|
||||
ik_made = 0
|
||||
if make_ik:
|
||||
ground_y = min(p[1] for p in (sp(x) for x in raw_pos)) if raw_pos else 0.0
|
||||
center_i = find_bone("センター")
|
||||
for side, s in (("左", "L"), ("右", "R")):
|
||||
i_ankle = find_bone(side + "足首")
|
||||
i_knee = find_bone(side + "ひざ")
|
||||
i_leg = find_bone(side + "足")
|
||||
i_toe = find_bone(side + "つま先")
|
||||
if min(i_ankle, i_knee, i_leg) < 0:
|
||||
continue
|
||||
ankle = pmx_bones[i_ankle]["pos"]
|
||||
i_legik = len(pmx_bones)
|
||||
pmx_bones.append({
|
||||
"name": _uniq(side + "足IK", used),
|
||||
"name_en": "LegIK_" + s,
|
||||
"pos": (ankle[0], ground_y, ankle[2]),
|
||||
"parent": center_i if center_i >= 0 else 0,
|
||||
"layer": 0,
|
||||
"flag": 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020,
|
||||
"tail_kind": 0, "tail": (0.0, 1.0, 0.0),
|
||||
"inherit_rot": None, "inherit_mov": None,
|
||||
"fixed_axis": None, "local_axis": None, "external": None,
|
||||
"ik": {"target": i_ankle, "iterations": 40,
|
||||
"limit_angle": 1.0,
|
||||
"links": [{"bone": i_knee, "min": None, "max": None},
|
||||
{"bone": i_leg, "min": None, "max": None}]},
|
||||
})
|
||||
ik_made += 1
|
||||
if i_toe >= 0:
|
||||
toe = pmx_bones[i_toe]["pos"]
|
||||
pmx_bones.append({
|
||||
"name": _uniq(side + "つま先IK", used),
|
||||
"name_en": "ToeIK_" + s,
|
||||
"pos": (toe[0], ground_y, toe[2]),
|
||||
"parent": i_legik,
|
||||
"layer": 0,
|
||||
"flag": 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020,
|
||||
"tail_kind": 0, "tail": (0.0, 1.0, 0.0),
|
||||
"inherit_rot": None, "inherit_mov": None,
|
||||
"fixed_axis": None, "local_axis": None,
|
||||
"external": None,
|
||||
"ik": {"target": i_toe, "iterations": 3,
|
||||
"limit_angle": 1.0,
|
||||
"links": [{"bone": i_ankle,
|
||||
"min": None, "max": None}]},
|
||||
})
|
||||
ik_made += 1
|
||||
if ik_made:
|
||||
_l("足 IK:已补充 %d 根(足IK / つま先IK,父骨骼 センター)" % ik_made,
|
||||
"info")
|
||||
else:
|
||||
_l("足 IK:源骨架中没有完整的腿部骨链,未补充 IK 骨", "info")
|
||||
|
||||
# ---- 面:按材质排序,保证 PMX 材质吃连续的面段
|
||||
nmats = max(1, len(m.materials))
|
||||
tri = []
|
||||
for (i0, i1, i2), mi in m.faces:
|
||||
if i0 >= n_wedge or i1 >= n_wedge or i2 >= n_wedge:
|
||||
continue
|
||||
if not (0 <= mi < nmats):
|
||||
mi = 0
|
||||
tri.append((mi, i0, i1, i2))
|
||||
tri.sort(key=lambda t: t[0])
|
||||
|
||||
# ---- 绕序自动判定(用变换后的数据投票;缩放/平移不影响手性)
|
||||
# xf 是一次反射(行列式 -1),几何绕序会跟着翻,所以下面「没有法线」的兜底
|
||||
# 也从「保持不变」改成「反转」——不然没带 VTXNORMS 的 psk 会整片背面朝外。
|
||||
pos_t = [sp(p) for p in raw_pos]
|
||||
if m.normals and len(m.normals) == n_point:
|
||||
nrm_t = []
|
||||
for pi, _u, _v, _mi in m.wedges:
|
||||
n = m.normals[pi] if 0 <= pi < len(m.normals) else (0.0, 0.0, 1.0)
|
||||
t = xf(n)
|
||||
ln = (t[0] ** 2 + t[1] ** 2 + t[2] ** 2) ** 0.5 or 1.0
|
||||
nrm_t.append((t[0] / ln, t[1] / ln, t[2] / ln))
|
||||
else:
|
||||
nrm_t = []
|
||||
face_idx = []
|
||||
for _mi, a, b, c in tri:
|
||||
face_idx.extend((a, b, c))
|
||||
if flip_winding in ("auto", None, ""):
|
||||
if nrm_t:
|
||||
need_flip, ag, dis = pmxio.detect_winding(pos_t, nrm_t, face_idx)
|
||||
_l("绕序自动判定:与法线同向 %d 面 / 反向 %d 面 → %s"
|
||||
% (ag, dis, "需要反转" if need_flip else "保持不变"))
|
||||
else:
|
||||
need_flip = True
|
||||
_l("绕序:缺少法线数据,按坐标轴反射统一反转(保持正面朝外)", "info")
|
||||
else:
|
||||
need_flip = bool(flip_winding)
|
||||
|
||||
pmx_faces = []
|
||||
for _mi, a, b, c in tri:
|
||||
pmx_faces.extend((c, b, a) if need_flip else (a, b, c))
|
||||
|
||||
# ---- 权重:RAWWEIGHTS 是按「点」索引的,楔要按 point_index 去查
|
||||
per_point = {}
|
||||
for w, pi, bi in m.weights:
|
||||
if 0 <= pi < n_point:
|
||||
per_point.setdefault(pi, []).append((w, bi))
|
||||
|
||||
n_dropped = 0
|
||||
no_weight = 0
|
||||
pmx_verts = []
|
||||
n_add = min(4, len(m.extra_uvs)) if keep_add_uv else 0
|
||||
for wi, (pi, u, v, _mi) in enumerate(m.wedges):
|
||||
P = sp(m.points[pi] if 0 <= pi < n_point else (0.0, 0.0, 0.0))
|
||||
if nrm_t:
|
||||
N = nrm_t[wi]
|
||||
else:
|
||||
N = (0.0, 0.0, 1.0)
|
||||
wl = [(b, w) for w, b in per_point.get(pi, []) if w > 1e-6]
|
||||
if len(wl) > 4:
|
||||
n_dropped += len(wl) - 4
|
||||
wl.sort(key=lambda t: -t[1])
|
||||
wl = wl[:4]
|
||||
wl = [(b, w) for b, w in wl if 0 <= b < n_src]
|
||||
if not wl:
|
||||
no_weight += 1
|
||||
wl = [(0, 1.0)]
|
||||
tot = sum(w for _, w in wl) or 1.0
|
||||
wl = [(slot.get(b, 0), w / tot) for b, w in wl]
|
||||
if len(wl) == 1:
|
||||
wtype, wbones, wweights = 0, [wl[0][0]], []
|
||||
elif len(wl) == 2:
|
||||
wtype, wbones, wweights = 1, [wl[0][0], wl[1][0]], [wl[0][1]]
|
||||
else:
|
||||
wtype = 2
|
||||
wbones = [wl[k][0] if k < len(wl) else wl[0][0] for k in range(4)]
|
||||
wweights = [wl[k][1] if k < len(wl) else 0.0 for k in range(4)]
|
||||
add = []
|
||||
for k in range(n_add):
|
||||
st = m.extra_uvs[k]
|
||||
uv = st[wi] if wi < len(st) else (0.0, 0.0)
|
||||
add.append((uv[0], uv[1], 0.0, 0.0))
|
||||
pmx_verts.append({"pos": P, "normal": N, "uv": (u, v),
|
||||
"add_uv": add, "wtype": wtype, "wbones": wbones,
|
||||
"wweights": wweights, "sdef": None, "edge": 1.0})
|
||||
if no_weight:
|
||||
_l("权重:%d 个顶点没有权重,已绑定到第 0 根骨骼" % no_weight, "warn")
|
||||
if n_dropped:
|
||||
_l("权重:已丢弃 %d 条第 5 根及以后的骨骼权重(PMX 每个顶点最多 4 根)"
|
||||
% n_dropped, "info")
|
||||
|
||||
# ---- 材质 + 贴图
|
||||
folder = os.path.dirname(os.path.abspath(path))
|
||||
out_dir = os.path.dirname(os.path.abspath(out_path))
|
||||
tex_dir = os.path.join(out_dir, "textures")
|
||||
pmx_textures = []
|
||||
tex_slot = {}
|
||||
n_linked = 0
|
||||
|
||||
def use_texture(mat_name):
|
||||
if mat_name in tex_slot:
|
||||
return tex_slot[mat_name]
|
||||
real = _find_texture(folder, mat_name)
|
||||
if real is None:
|
||||
real = _find_texture(out_dir, mat_name)
|
||||
if real is None:
|
||||
tex_slot[mat_name] = -1
|
||||
return -1
|
||||
ext = os.path.splitext(real)[1].lower()
|
||||
if ext not in _TEX_EXT:
|
||||
tex_slot[mat_name] = -1
|
||||
return -1
|
||||
dst = os.path.join(tex_dir, os.path.basename(real))
|
||||
try:
|
||||
os.makedirs(tex_dir, exist_ok=True)
|
||||
_copy_tex(real, dst, remove_alpha)
|
||||
except OSError:
|
||||
tex_slot[mat_name] = -1
|
||||
return -1
|
||||
pmx_textures.append("textures/" + os.path.basename(real))
|
||||
tex_slot[mat_name] = len(pmx_textures) - 1
|
||||
return tex_slot[mat_name]
|
||||
|
||||
counts = [0] * nmats
|
||||
for _mi, _a, _b, _c in tri:
|
||||
counts[_mi] += 1
|
||||
|
||||
pmx_materials = []
|
||||
for k in range(nmats):
|
||||
mt = m.materials[k] if k < len(m.materials) else None
|
||||
mname = (mt.name if mt and mt.name else "mat%d" % k)
|
||||
ti = use_texture(mname) if textures else -1
|
||||
if ti >= 0:
|
||||
n_linked += 1
|
||||
flag = 0x0E | (0x10 if enable_edge else 0)
|
||||
if force_double_sided:
|
||||
flag |= 0x01
|
||||
pmx_materials.append({
|
||||
"name": mname, "name_en": mname,
|
||||
"diffuse": (1.0, 1.0, 1.0, 1.0),
|
||||
"specular": (0.0, 0.0, 0.0),
|
||||
"shininess": 0.0,
|
||||
"ambient": (0.5, 0.5, 0.5),
|
||||
"flag": flag,
|
||||
"edge_color": (0.0, 0.0, 0.0, 1.0),
|
||||
"edge_size": 1.0 if enable_edge else 0.0,
|
||||
"tex": ti, "sph": -1, "sph_mode": 0,
|
||||
# toon:**不使用**。见文件顶部 _TOON_NONE_FLAG 的说明。
|
||||
"toon_flag": _TOON_NONE_FLAG, "toon": _TOON_NONE_INDEX, "memo": "",
|
||||
"faces": counts[k],
|
||||
})
|
||||
# 空材质(源里声明了但一个面都没用上)会让 PMX 出现 0 面材质段,去掉更干净
|
||||
pmx_materials = [x for x in pmx_materials if x["faces"] > 0]
|
||||
if not pmx_materials:
|
||||
pmx_materials.append({
|
||||
"name": "material_0", "name_en": "material_0",
|
||||
"diffuse": (1.0, 1.0, 1.0, 1.0), "specular": (0.0, 0.0, 0.0),
|
||||
"shininess": 0.0, "ambient": (0.5, 0.5, 0.5),
|
||||
"flag": 0x0E | (0x10 if enable_edge else 0),
|
||||
"edge_color": (0.0, 0.0, 0.0, 1.0),
|
||||
"edge_size": 1.0 if enable_edge else 0.0, "tex": -1, "sph": -1,
|
||||
"sph_mode": 0, "toon_flag": _TOON_NONE_FLAG,
|
||||
"toon": _TOON_NONE_INDEX, "memo": "",
|
||||
"faces": len(pmx_faces) // 3,
|
||||
})
|
||||
# PMX 材质的「面数」字段其实是**索引数**(每个三角面占 3 个)
|
||||
for x in pmx_materials:
|
||||
x["faces"] = int(x["faces"]) * 3
|
||||
_l("材质:%d 个 · 关联到贴图 %d 个%s"
|
||||
% (len(pmx_materials), n_linked,
|
||||
"" if n_linked else "(源目录中没有同名贴图,导出为无贴图模型)"))
|
||||
|
||||
# ---- 表情:MRPH 的位移是按「点」索引的,要摊到该点对应的所有楔上
|
||||
point_to_wedges = {}
|
||||
for wi, (pi, _u, _v, _mi) in enumerate(m.wedges):
|
||||
if 0 <= pi < n_point:
|
||||
point_to_wedges.setdefault(pi, []).append(wi)
|
||||
|
||||
used_mo = set()
|
||||
pmx_morphs = []
|
||||
if export_morphs:
|
||||
for mo in m.morphs:
|
||||
offs = []
|
||||
for pi, d in mo.offsets:
|
||||
dp = sdir(d)
|
||||
if abs(dp[0]) + abs(dp[1]) + abs(dp[2]) < 1e-9:
|
||||
continue
|
||||
for wi in point_to_wedges.get(pi, ()):
|
||||
if wi < len(pmx_verts):
|
||||
offs.append((wi, dp))
|
||||
if not offs:
|
||||
continue
|
||||
nm = _uniq(mo.name, used_mo)
|
||||
pmx_morphs.append({"name": nm, "name_en": mo.name or nm,
|
||||
"panel": _morph_panel(mo.name), "kind": 1,
|
||||
"offsets": offs})
|
||||
_l("表情:%d 个(顶点表情)" % len(pmx_morphs))
|
||||
|
||||
# ---- 表示枠 / 模型信息
|
||||
frames = []
|
||||
if pmx_bones:
|
||||
frames.append({"name": "Root", "name_en": "Root", "special": 0,
|
||||
"items": [(0, i) for i in range(len(pmx_bones))]})
|
||||
if pmx_morphs:
|
||||
frames.append({"name": "表情", "name_en": "Exp", "special": 1,
|
||||
"items": [(1, i) for i in range(len(pmx_morphs))]})
|
||||
|
||||
stem = os.path.splitext(os.path.basename(path))[0]
|
||||
title = name or stem
|
||||
comment = ["由 %s 转换:%s" % (kind, os.path.basename(path)),
|
||||
"骨骼 %d 根 · 材质 %d 个 · 表情 %d 个" % (len(pmx_bones),
|
||||
len(pmx_materials),
|
||||
len(pmx_morphs)),
|
||||
"converted by psk2pmx.py"]
|
||||
model = pmxio.new_model(title)
|
||||
model["name"] = title
|
||||
model["name_en"] = stem
|
||||
model["comment"] = "\r\n".join(comment)
|
||||
model["comment_en"] = "\r\n".join(comment)
|
||||
model["vertices"] = pmx_verts
|
||||
model["faces"] = pmx_faces
|
||||
model["textures"] = pmx_textures
|
||||
model["materials"] = pmx_materials
|
||||
model["bones"] = pmx_bones
|
||||
model["morphs"] = pmx_morphs
|
||||
model["frames"] = frames
|
||||
model["add_uv"] = n_add
|
||||
if not enable_edge:
|
||||
pmxio.strip_edges(model, force_double_sided=False)
|
||||
|
||||
size = pmxio.write_pmx(model, out_path)
|
||||
_l("已写出 %s(%.2f MB)· 顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d"
|
||||
% (os.path.basename(out_path), size / 1048576.0, len(pmx_verts),
|
||||
len(pmx_faces) // 3, len(pmx_bones), len(pmx_materials),
|
||||
len(pmx_morphs)), "ok")
|
||||
_warn_anchor_collision(out_path, _l)
|
||||
|
||||
st = {"bytes": size, "vertices": len(pmx_verts),
|
||||
"tris": len(pmx_faces) // 3, "bones": len(pmx_bones),
|
||||
"materials": len(pmx_materials), "morphs": len(pmx_morphs),
|
||||
"textures": len(pmx_textures), "scale": scale}
|
||||
|
||||
if fbx_path:
|
||||
try:
|
||||
import fbxout
|
||||
st["fbx"] = fbxout.export_model(
|
||||
fbx_path, pmx_verts, pmx_faces, pmx_materials,
|
||||
pmx_bones, pmx_morphs,
|
||||
mirror_z=True, reverse_winding=True, tex_dir=tex_dir,
|
||||
log=_l, name=title)
|
||||
_l("已写出 %s(ASCII FBX 7.4 · %.2f MB)"
|
||||
% (os.path.basename(fbx_path),
|
||||
st["fbx"]["bytes"] / 1048576.0), "ok")
|
||||
except Exception as e:
|
||||
st["fbx_error"] = str(e)
|
||||
_l("FBX 导出失败:%s" % e, "err")
|
||||
return st
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
import argparse
|
||||
ap = argparse.ArgumentParser(description="PSK / PSKX → MMD PMX(纯 Python)")
|
||||
ap.add_argument("src")
|
||||
ap.add_argument("-o", "--out", default=None)
|
||||
ap.add_argument("--scale", default="mmd",
|
||||
help="mmd(归一到 20 单位,默认)/ raw(保持源尺寸)/ 具体倍率")
|
||||
ap.add_argument("--edge", action="store_true", help="给材质开启 MMD 轮廓线")
|
||||
ap.add_argument("--force-double-sided", action="store_true")
|
||||
ap.add_argument("--no-textures", action="store_true")
|
||||
ap.add_argument("--keep-alpha", action="store_true", help="保留贴图 alpha")
|
||||
ap.add_argument("--no-add-uv", action="store_true")
|
||||
ap.add_argument("--raw-bone-names", action="store_true",
|
||||
help="骨骼保留原始英文名,不转 MMD 日文标准名")
|
||||
ap.add_argument("--no-ik", action="store_true", help="不补 MMD 足 IK 骨")
|
||||
ap.add_argument("--no-morphs", action="store_true")
|
||||
ap.add_argument("--fbx", action="store_true", help="同时导出 FBX")
|
||||
ap.add_argument("--name", default=None)
|
||||
a = ap.parse_args(argv)
|
||||
out = a.out or (os.path.splitext(a.src)[0] + ".pmx")
|
||||
fbx = (os.path.splitext(out)[0] + ".fbx") if a.fbx else None
|
||||
st = convert(a.src, out, scale_mode=a.scale,
|
||||
log=lambda m_, t=None: print(m_), name=a.name,
|
||||
enable_edge=a.edge, force_double_sided=a.force_double_sided,
|
||||
textures=not a.no_textures, keep_add_uv=not a.no_add_uv,
|
||||
remove_alpha=not a.keep_alpha, jp_bones=not a.raw_bone_names,
|
||||
make_ik=not a.no_ik, export_morphs=not a.no_morphs,
|
||||
fbx_path=fbx)
|
||||
print("完成:%s(%.2f MB)" % (out, st["bytes"] / 1048576.0))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,545 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""转换好的 VRM 再调整(不用重新转换):预设表情指定和强度、视线范围、SpringBone 参数、标题、缩略图。
|
||||
|
||||
import vrm_edit
|
||||
info = vrm_edit.describe(path) # 界面要的:可选表情、当前预设指定、物理链、标题
|
||||
vrm_edit.apply(path, edits) # 套用调整,原地改写文件
|
||||
|
||||
edits(纯 JSON,界面按源文件存):
|
||||
|
||||
{"title": "名字",
|
||||
"expressions": {"happy": "笑い", "blink": "", ...}, 预设 → 来源表情 id("" = 不设这个预设)
|
||||
"intensity": {"angry": 0.8, ...}, 预设强度 ×(形态键权重相乘,单个权重最多到 1)
|
||||
"lookAt": {"h": 15.0, "down": 10.0, "up": 7.0}, 视线最大转角(度):左右 / 向下 / 向上;不给 = 转换时的值
|
||||
"spring": {"stiffness": 1.0, "drag": 1.0, "gravity": 0.0, 整体:硬度 ×、阻尼 ×、重力 +
|
||||
"chains": {"链 key": {"stiffness": 1.0, "gravity": 0.0, "off": false}}},
|
||||
"thumbnails": {"模型名": {"path": "缩略图 PNG 的路径", "auto": true}}}
|
||||
|
||||
缩略图按模型分开(一个包里几个模型各用各的):模型名 = 输出 VRM 的文件名去掉扩展名(model_key)。
|
||||
旧版的 "thumbnail": "路径" 对这个文件的所有模型都有效,没有按模型设置的模型仍然用它。
|
||||
|
||||
可重复套用:第一次调整时把原始的表情 / 物理 / meta 存进 glTF 根节点的 extras.vrmconv_base,
|
||||
以后每次都先还原再套用,不会越调越歪;edits 为空就是还原成转换时的样子。
|
||||
来源表情 id:转换时给预设表情记了来源 PMX 表情名(extras.source),自定义表情就是它的名字。
|
||||
"""
|
||||
import copy
|
||||
import os
|
||||
import time
|
||||
|
||||
import vrmio
|
||||
from vrmconv import morphbake
|
||||
|
||||
PRESETS_1 = ["happy", "angry", "sad", "relaxed", "surprised", "neutral",
|
||||
"aa", "ih", "ou", "ee", "oh", "blink", "blinkLeft", "blinkRight",
|
||||
"lookUp", "lookDown", "lookLeft", "lookRight"]
|
||||
PRESETS_0 = ["joy", "angry", "sorrow", "fun", "neutral", "a", "i", "u", "e", "o",
|
||||
"blink", "blink_l", "blink_r", "lookup", "lookdown", "lookleft", "lookright"]
|
||||
BASE_KEY = "vrmconv_base"
|
||||
SPRING_DEFAULTS = {"stiffness": 1.0, "gravityPower": 0.0, "dragForce": 0.5}
|
||||
|
||||
|
||||
def _uniq(name, used):
|
||||
if name not in used:
|
||||
return name
|
||||
k = 2
|
||||
while "%s_%d" % (name, k) in used:
|
||||
k += 1
|
||||
return "%s_%d" % (name, k)
|
||||
|
||||
|
||||
def _num(v, default):
|
||||
try:
|
||||
v = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return v if v == v and abs(v) < 1e6 else default
|
||||
|
||||
|
||||
# ------------------------------------------------------------- baseline --
|
||||
def _base(g, create):
|
||||
"""glTF 根 extras 里的原始值;create=True 时没有就现在记下来。"""
|
||||
ext = g.get("extensions", {})
|
||||
b = g.get("extras", {}).get(BASE_KEY)
|
||||
if b is not None or not create:
|
||||
return b
|
||||
if "VRMC_vrm" in ext:
|
||||
v = ext["VRMC_vrm"]
|
||||
b = {"spec": "1.0", "expressions": copy.deepcopy(v.get("expressions")),
|
||||
"meta": copy.deepcopy(v["meta"]),
|
||||
"springBone": copy.deepcopy(ext.get("VRMC_springBone"))}
|
||||
else:
|
||||
v = ext["VRM"]
|
||||
b = {"spec": "0.x", "groups": copy.deepcopy(v.get("blendShapeMaster", {}).get("blendShapeGroups", [])),
|
||||
"meta": copy.deepcopy(v["meta"])}
|
||||
b["thumb"] = None
|
||||
_base_look(b, v)
|
||||
_base_secondary(b, v)
|
||||
g.setdefault("extras", {})[BASE_KEY] = b
|
||||
return b
|
||||
|
||||
|
||||
_LOOK_1 = {"h": ("rangeMapHorizontalInner", "rangeMapHorizontalOuter"), "down": ("rangeMapVerticalDown",),
|
||||
"up": ("rangeMapVerticalUp",)}
|
||||
_LOOK_0 = {"h": ("lookAtHorizontalInner", "lookAtHorizontalOuter"), "down": ("lookAtVerticalDown",),
|
||||
"up": ("lookAtVerticalUp",)}
|
||||
|
||||
|
||||
def _base_look(b, vrm):
|
||||
"""基准里记下转换时的视线设置(以前调整过、基准里还没有这一项的文件,补记当前的——
|
||||
那时还没有视线调整,当前值就是转换时的值)。"""
|
||||
if "look" not in b:
|
||||
b["look"] = copy.deepcopy(vrm.get("lookAt") if b["spec"] == "1.0" else
|
||||
{k: vrm.get("firstPerson", {}).get(k) for ks in _LOOK_0.values() for k in ks})
|
||||
|
||||
|
||||
def _base_secondary(b, vrm):
|
||||
"""0.x 的基准里记下转换时的物理(以前调整过、基准里还没有这一项的文件,补记当前的——
|
||||
那时还不能调 0.x 的物理,当前值就是转换时的值)。"""
|
||||
if b["spec"] != "1.0" and "secondary" not in b:
|
||||
b["secondary"] = copy.deepcopy(vrm.get("secondaryAnimation"))
|
||||
|
||||
|
||||
def _subtree(nodes, roots):
|
||||
out, stack = [], list(roots)
|
||||
while stack:
|
||||
n = stack.pop(0)
|
||||
if 0 <= n < len(nodes) and n not in out:
|
||||
out.append(n)
|
||||
stack[:0] = nodes[n].get("children", [])
|
||||
return out
|
||||
|
||||
|
||||
def _look_deg(b):
|
||||
"""基准里的视线最大转角 → {"h", "down", "up"}(度),没有视线设置时 None。"""
|
||||
look = b.get("look") or {}
|
||||
out = {}
|
||||
for k, names in (_LOOK_1 if b["spec"] == "1.0" else _LOOK_0).items():
|
||||
m = look.get(names[0])
|
||||
if not m:
|
||||
return None
|
||||
out[k] = m.get("outputScale") if b["spec"] == "1.0" else m.get("yRange")
|
||||
return out
|
||||
|
||||
|
||||
def _apply_look(vrm, b, edits, g=None):
|
||||
"""视线:先还原转换时的设置,再套用 edits(左右 / 向下 / 向上的最大转角)。
|
||||
转换时补的视线表情(lookLeft 等,横向场 + 深度场两个绑定,见 morphbake.split_gaze)按新角度重算权重。"""
|
||||
is1 = b["spec"] == "1.0"
|
||||
if is1:
|
||||
if b.get("look") is not None:
|
||||
vrm["lookAt"] = copy.deepcopy(b["look"])
|
||||
else:
|
||||
for k, m in (b.get("look") or {}).items():
|
||||
if m is not None:
|
||||
vrm.setdefault("firstPerson", {})[k] = copy.deepcopy(m)
|
||||
if not edits or _look_deg(b) is None:
|
||||
return
|
||||
target = vrm["lookAt"] if is1 else vrm["firstPerson"]
|
||||
for k, names in (_LOOK_1 if is1 else _LOOK_0).items():
|
||||
deg = _num(edits.get(k), None)
|
||||
if deg is None:
|
||||
continue
|
||||
deg = min(90.0, max(0.0, deg))
|
||||
for n in names:
|
||||
target[n]["outputScale" if is1 else "yRange"] = deg
|
||||
if g is not None:
|
||||
_gaze_weights(g, vrm, is1, edits)
|
||||
|
||||
|
||||
def _target_name(g, bind, is1):
|
||||
"""表情绑定指向的 morph target 名(找不到时 None)。1.0 的 node 是网格节点,0.x 的 mesh 是网格号。"""
|
||||
try:
|
||||
m = g["nodes"][bind["node"]]["mesh"] if is1 else bind["mesh"]
|
||||
names = g["meshes"][m]["extras"]["targetNames"]
|
||||
return names[bind["index"]] if 0 <= bind["index"] < len(names) else None
|
||||
except (KeyError, IndexError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def _gaze_weights(g, vrm, is1, edits):
|
||||
depth = set(morphbake.GAZE_DEPTH.values())
|
||||
for p, key in morphbake.GAZE_KEY.items():
|
||||
deg = _num(edits.get(key), None)
|
||||
if deg is None:
|
||||
continue
|
||||
axis = "h" if key == "h" else "v"
|
||||
wt, wd = morphbake.gaze_weights(deg, axis)
|
||||
if is1:
|
||||
obj = (vrm.get("expressions") or {}).get("preset", {}).get(p)
|
||||
binds = obj and (obj.get("extras") or {}).get("source") == p and obj.get("morphTargetBinds")
|
||||
scale = 1.0
|
||||
else:
|
||||
gr = next((x for x in vrm.get("blendShapeMaster", {}).get("blendShapeGroups", [])
|
||||
if x.get("name") == p and x.get("presetName") == p.lower()), None)
|
||||
binds = gr and gr.get("binds")
|
||||
scale = 100.0
|
||||
# 只认转换时补的那种:横向场 + 深度场(眼睛分在几个网格里时每个网格各一对)
|
||||
names = [_target_name(g, bd, is1) for bd in binds or ()]
|
||||
if not names or None in names or len(set(names)) != 2 or not depth.intersection(names):
|
||||
continue
|
||||
for bd, n in zip(binds, names):
|
||||
bd["weight"] = round((wd if n in depth else wt) * scale, 6)
|
||||
|
||||
|
||||
def _apply_intensity(vrm, is1, edits):
|
||||
"""预设强度:把预设里的形态键权重乘上系数(单个权重最多到 1 / 100)。材质颜色、贴图偏移不变。"""
|
||||
for p, f in (edits or {}).items():
|
||||
f = _num(f, 1.0)
|
||||
if f == 1.0:
|
||||
continue
|
||||
f = max(0.0, f)
|
||||
if is1:
|
||||
obj = ((vrm.get("expressions") or {}).get("preset") or {}).get(p)
|
||||
for bd in (obj or {}).get("morphTargetBinds", []):
|
||||
bd["weight"] = round(min(1.0, bd["weight"] * f), 4)
|
||||
else:
|
||||
for gr in vrm.get("blendShapeMaster", {}).get("blendShapeGroups", []):
|
||||
if gr.get("presetName") == p:
|
||||
for bd in gr.get("binds", []):
|
||||
bd["weight"] = round(min(100.0, bd["weight"] * f), 2)
|
||||
|
||||
|
||||
def _sources_1(expressions):
|
||||
"""VRM 1.0 原始表情 → (pool {id: 表情}, 预设指定 {预设: id})。"""
|
||||
pool, assign = {}, {}
|
||||
for p, obj in ((expressions or {}).get("preset") or {}).items():
|
||||
sid = (obj.get("extras") or {}).get("source") or "@" + p
|
||||
if sid in pool:
|
||||
sid = "@" + p
|
||||
pool[sid] = obj
|
||||
assign[p] = sid
|
||||
for name, obj in ((expressions or {}).get("custom") or {}).items():
|
||||
pool[_uniq(name, pool)] = obj
|
||||
return pool, assign
|
||||
|
||||
|
||||
def _sources_0(groups):
|
||||
pool, assign = {}, {}
|
||||
for gr in groups:
|
||||
sid = _uniq(gr.get("name") or "expression", pool)
|
||||
pool[sid] = gr
|
||||
p = str(gr.get("presetName") or "unknown").lower()
|
||||
if p in PRESETS_0 and p not in assign:
|
||||
assign[p] = sid
|
||||
return pool, assign
|
||||
|
||||
|
||||
def _chain_keys(springs):
|
||||
keys, used = [], set()
|
||||
for i, sp in enumerate(springs or []):
|
||||
k = _uniq(sp.get("name") or "spring%d" % i, used)
|
||||
used.add(k)
|
||||
keys.append(k)
|
||||
return keys
|
||||
|
||||
|
||||
# 1.0 关节参数名 → 0.x 组参数名(硬度是规范里拼错的 stiffiness)
|
||||
_FIELDS_0 = {"stiffness": "stiffiness", "gravityPower": "gravityPower", "dragForce": "dragForce"}
|
||||
|
||||
|
||||
def _group_keys(groups):
|
||||
return _chain_keys([{"name": grp.get("comment")} for grp in groups])
|
||||
|
||||
|
||||
def _label(sid):
|
||||
return sid[1:] if sid.startswith("@") else sid
|
||||
|
||||
|
||||
# -------------------------------------------------------------- describe --
|
||||
def describe(path):
|
||||
"""→ 界面要的信息(都按转换时的原始值,不含已套用的调整)。"""
|
||||
g, _ = vrmio.read_glb(path)
|
||||
ext = g.get("extensions", {})
|
||||
if "VRMC_vrm" not in ext and "VRM" not in ext:
|
||||
raise ValueError("不是 VRM 文件")
|
||||
b = _base(g, create=True)
|
||||
out = {"spec": b["spec"], "springs": []}
|
||||
if b["spec"] == "1.0":
|
||||
pool, assign = _sources_1(b["expressions"])
|
||||
out["presets"] = PRESETS_1
|
||||
out["title"] = b["meta"].get("name", "")
|
||||
sb = b.get("springBone") or {}
|
||||
for k, sp in zip(_chain_keys(sb.get("springs")), sb.get("springs") or []):
|
||||
out["springs"].append({
|
||||
"key": k, "name": sp.get("name") or k,
|
||||
"joints": [{"node": j["node"], **{f: j.get(f, d) for f, d in SPRING_DEFAULTS.items()}}
|
||||
for j in sp.get("joints", [])]})
|
||||
else:
|
||||
pool, assign = _sources_0(b["groups"])
|
||||
out["presets"] = PRESETS_0
|
||||
out["title"] = b["meta"].get("title", "")
|
||||
# 0.x 的一个摆动组 = 界面里的一条链;组根下面整棵子树都是关节,参数整组共用
|
||||
_base_secondary(b, ext["VRM"])
|
||||
groups = (b.get("secondary") or {}).get("boneGroups") or []
|
||||
for k, grp in zip(_group_keys(groups), groups):
|
||||
par = {f: grp.get(f0, SPRING_DEFAULTS[f]) for f, f0 in _FIELDS_0.items()}
|
||||
out["springs"].append({
|
||||
"key": k, "name": grp.get("comment") or k,
|
||||
"joints": [dict(node=n, **par) for n in _subtree(g["nodes"], grp.get("bones") or [])]})
|
||||
out["expressions"] = [{"id": sid, "label": _label(sid)} for sid in pool]
|
||||
out["assign"] = assign
|
||||
_base_look(b, ext["VRMC_vrm"] if b["spec"] == "1.0" else ext["VRM"])
|
||||
out["look"] = _look_deg(b) # 转换时的视线最大转角(没有视线设置时 None)
|
||||
return out
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- apply --
|
||||
def _apply_expr_1(vrm, base_expr, edits):
|
||||
pool, assign = _sources_1(base_expr)
|
||||
for p, sid in (edits or {}).items():
|
||||
if p in PRESETS_1:
|
||||
if not sid:
|
||||
assign.pop(p, None)
|
||||
elif sid in pool:
|
||||
assign[p] = sid
|
||||
preset, custom, used = {}, {}, set(assign.values())
|
||||
for p in PRESETS_1:
|
||||
sid = assign.get(p)
|
||||
if sid:
|
||||
obj = copy.deepcopy(pool[sid])
|
||||
if sid.startswith("@"):
|
||||
obj.pop("extras", None)
|
||||
else:
|
||||
obj["extras"] = dict(obj.get("extras") or {}, source=sid)
|
||||
preset[p] = obj
|
||||
for sid, obj in pool.items():
|
||||
if sid in used:
|
||||
continue
|
||||
obj = copy.deepcopy(obj)
|
||||
obj.pop("extras", None)
|
||||
# 规范:自定义表情名不能和预设名重名
|
||||
name = _uniq(_label(sid) if not sid.startswith("@") else "orig_" + sid[1:],
|
||||
set(custom) | set(PRESETS_1))
|
||||
custom[name] = obj
|
||||
expressions = {}
|
||||
if preset:
|
||||
expressions["preset"] = preset
|
||||
if custom:
|
||||
expressions["custom"] = custom
|
||||
if expressions:
|
||||
vrm["expressions"] = expressions
|
||||
else:
|
||||
vrm.pop("expressions", None)
|
||||
|
||||
|
||||
def _apply_expr_0(vrm, base_groups, edits):
|
||||
pool, assign = _sources_0(base_groups)
|
||||
for p, sid in (edits or {}).items():
|
||||
if p in PRESETS_0:
|
||||
if not sid:
|
||||
assign.pop(p, None)
|
||||
elif sid in pool:
|
||||
assign[p] = sid
|
||||
by_sid = {}
|
||||
for p, sid in assign.items():
|
||||
by_sid.setdefault(sid, []).append(p)
|
||||
groups = []
|
||||
for sid, gr in pool.items():
|
||||
ps = by_sid.get(sid) or ["unknown"]
|
||||
for k, p in enumerate(ps): # 一个表情指定给多个预设:复制一份
|
||||
ng = copy.deepcopy(gr)
|
||||
ng["presetName"] = p
|
||||
if k:
|
||||
ng["name"] = "%s_%s" % (ng.get("name") or sid, p)
|
||||
groups.append(ng)
|
||||
vrm.setdefault("blendShapeMaster", {})["blendShapeGroups"] = groups
|
||||
|
||||
|
||||
def _apply_spring(g, base_sb, edits):
|
||||
ext = g["extensions"]
|
||||
used = g.setdefault("extensionsUsed", [])
|
||||
if base_sb is None:
|
||||
return
|
||||
sb = copy.deepcopy(base_sb)
|
||||
if edits:
|
||||
gs = _num(edits.get("stiffness"), 1.0)
|
||||
gd = _num(edits.get("drag"), 1.0)
|
||||
gg = _num(edits.get("gravity"), 0.0)
|
||||
chains = edits.get("chains") or {}
|
||||
springs = []
|
||||
for k, sp in zip(_chain_keys(sb.get("springs")), sb.get("springs") or []):
|
||||
c = chains.get(k) or {}
|
||||
if c.get("off"):
|
||||
continue
|
||||
cs, cg = _num(c.get("stiffness"), 1.0), _num(c.get("gravity"), 0.0)
|
||||
for j in sp.get("joints", []):
|
||||
st = j.get("stiffness", SPRING_DEFAULTS["stiffness"])
|
||||
gp = j.get("gravityPower", SPRING_DEFAULTS["gravityPower"])
|
||||
dr = j.get("dragForce", SPRING_DEFAULTS["dragForce"])
|
||||
j["stiffness"] = round(max(0.0, st * gs * cs), 4)
|
||||
j["gravityPower"] = round(max(0.0, gp + gg + cg), 4)
|
||||
j["dragForce"] = round(min(1.0, max(0.0, dr * gd)), 4)
|
||||
springs.append(sp)
|
||||
sb["springs"] = springs
|
||||
if sb.get("springs"):
|
||||
ext["VRMC_springBone"] = sb
|
||||
if "VRMC_springBone" not in used:
|
||||
used.append("VRMC_springBone")
|
||||
else: # 全部关掉:规范要求 springs 非空,整个扩展去掉
|
||||
ext.pop("VRMC_springBone", None)
|
||||
if "VRMC_springBone" in used:
|
||||
used.remove("VRMC_springBone")
|
||||
|
||||
|
||||
def _apply_secondary(vrm, base_sa, edits):
|
||||
"""0.x:和 _apply_spring 一样的倍率 / 按链覆盖 / 关闭,作用在每个摆动组的参数上。"""
|
||||
if base_sa is None:
|
||||
return
|
||||
sa = copy.deepcopy(base_sa)
|
||||
if edits:
|
||||
gs = _num(edits.get("stiffness"), 1.0)
|
||||
gd = _num(edits.get("drag"), 1.0)
|
||||
gg = _num(edits.get("gravity"), 0.0)
|
||||
chains = edits.get("chains") or {}
|
||||
groups = []
|
||||
for k, grp in zip(_group_keys(sa.get("boneGroups") or []), sa.get("boneGroups") or []):
|
||||
c = chains.get(k) or {}
|
||||
if c.get("off"):
|
||||
continue
|
||||
cs, cg = _num(c.get("stiffness"), 1.0), _num(c.get("gravity"), 0.0)
|
||||
st = grp.get("stiffiness", SPRING_DEFAULTS["stiffness"])
|
||||
gp = grp.get("gravityPower", SPRING_DEFAULTS["gravityPower"])
|
||||
dr = grp.get("dragForce", SPRING_DEFAULTS["dragForce"])
|
||||
grp["stiffiness"] = round(max(0.0, st * gs * cs), 4)
|
||||
grp["gravityPower"] = round(max(0.0, gp + gg + cg), 4)
|
||||
grp["dragForce"] = round(min(1.0, max(0.0, dr * gd)), 4)
|
||||
groups.append(grp)
|
||||
sa["boneGroups"] = groups
|
||||
vrm["secondaryAnimation"] = sa
|
||||
|
||||
|
||||
def _drop_thumb(g, bin_data, thumb):
|
||||
"""去掉上一次加的缩略图。它总是追加在最后,在末尾时连数据一起截掉。"""
|
||||
if not thumb:
|
||||
return bin_data
|
||||
tex, img, bv = thumb.get("texture"), thumb.get("image"), thumb.get("bufferView")
|
||||
if tex is not None and tex == len(g.get("textures", [])) - 1:
|
||||
g["textures"].pop()
|
||||
if not g["textures"]:
|
||||
del g["textures"]
|
||||
if img is not None and img == len(g.get("images", [])) - 1:
|
||||
g["images"].pop()
|
||||
if not g["images"]:
|
||||
del g["images"]
|
||||
bvs = g.get("bufferViews", [])
|
||||
if bv is not None and bv == len(bvs) - 1:
|
||||
v = bvs.pop()
|
||||
if v.get("byteOffset", 0) + v["byteLength"] >= len(bin_data) - 3:
|
||||
bin_data = bin_data[:v.get("byteOffset", 0)]
|
||||
return bin_data
|
||||
|
||||
|
||||
def _add_thumb(g, bin_data, png, is1):
|
||||
bin_data = bytearray(bin_data)
|
||||
while len(bin_data) % 4:
|
||||
bin_data += b"\x00"
|
||||
off = len(bin_data)
|
||||
bin_data += png
|
||||
bvs = g.setdefault("bufferViews", [])
|
||||
bvs.append({"buffer": 0, "byteOffset": off, "byteLength": len(png)})
|
||||
imgs = g.setdefault("images", [])
|
||||
mime = "image/jpeg" if png[:3] == b"\xff\xd8\xff" else "image/png"
|
||||
imgs.append({"name": "thumbnail", "bufferView": len(bvs) - 1, "mimeType": mime})
|
||||
thumb = {"bufferView": len(bvs) - 1, "image": len(imgs) - 1, "texture": None}
|
||||
if not is1: # 0.x 的 meta.texture 是贴图(texture)序号
|
||||
texs = g.setdefault("textures", [])
|
||||
if not g.get("samplers"):
|
||||
g["samplers"] = [vrmio.default_sampler()]
|
||||
texs.append({"sampler": 0, "source": len(imgs) - 1})
|
||||
thumb["texture"] = len(texs) - 1
|
||||
return bytes(bin_data), thumb
|
||||
|
||||
|
||||
def model_key(path):
|
||||
"""缩略图按模型存的键:VRM 文件名去掉扩展名。"""
|
||||
return os.path.splitext(os.path.basename(path))[0]
|
||||
|
||||
|
||||
def thumb_for(edits, path):
|
||||
"""这个 VRM 的缩略图 PNG 路径:按模型设置的,否则旧版对所有模型的那张;没有 → None。"""
|
||||
t = ((edits or {}).get("thumbnails") or {}).get(model_key(path))
|
||||
return (t or {}).get("path") or (edits or {}).get("thumbnail") or None
|
||||
|
||||
|
||||
def is_empty(edits):
|
||||
if not edits:
|
||||
return True
|
||||
sp = edits.get("spring") or {}
|
||||
neutral_spring = (_num(sp.get("stiffness"), 1.0) == 1.0 and _num(sp.get("drag"), 1.0) == 1.0
|
||||
and _num(sp.get("gravity"), 0.0) == 0.0
|
||||
and not any(c.get("off") or _num(c.get("stiffness"), 1.0) != 1.0
|
||||
or _num(c.get("gravity"), 0.0) != 0.0
|
||||
for c in (sp.get("chains") or {}).values()))
|
||||
return (not edits.get("title") and not edits.get("expressions") and neutral_spring
|
||||
and not edits.get("thumbnail") and not edits.get("lookAt")
|
||||
and not any((t or {}).get("path") for t in (edits.get("thumbnails") or {}).values())
|
||||
and all(_num(v, 1.0) == 1.0 for v in (edits.get("intensity") or {}).values()))
|
||||
|
||||
|
||||
def apply(path, edits, out_path=None):
|
||||
"""把 edits 套到 VRM 上(先还原成转换时的样子再套),写到 out_path(默认原地)。返回改了几项。"""
|
||||
g, bin_data = vrmio.read_glb(path)
|
||||
ext = g.get("extensions", {})
|
||||
if "VRMC_vrm" not in ext and "VRM" not in ext:
|
||||
raise ValueError("不是 VRM 文件")
|
||||
edits = edits or {}
|
||||
empty = is_empty(edits)
|
||||
b = _base(g, create=not empty)
|
||||
if b is None: # 从没调过、这次也没有调整
|
||||
if out_path and out_path != path:
|
||||
vrmio.write_glb(g, bin_data, out_path)
|
||||
return 0
|
||||
is1 = b["spec"] == "1.0"
|
||||
vrm = ext["VRMC_vrm"] if is1 else ext["VRM"]
|
||||
# ---- 还原
|
||||
bin_data = _drop_thumb(g, bin_data, b.get("thumb"))
|
||||
b["thumb"] = None
|
||||
vrm["meta"] = copy.deepcopy(b["meta"])
|
||||
n = 0
|
||||
# ---- 套用
|
||||
_base_look(b, vrm)
|
||||
if is1:
|
||||
_apply_expr_1(vrm, b["expressions"], edits.get("expressions"))
|
||||
_apply_spring(g, b.get("springBone"), edits.get("spring"))
|
||||
else:
|
||||
_apply_expr_0(vrm, b["groups"], edits.get("expressions"))
|
||||
_base_secondary(b, vrm)
|
||||
_apply_secondary(vrm, b.get("secondary"), edits.get("spring"))
|
||||
_apply_intensity(vrm, is1, edits.get("intensity"))
|
||||
_apply_look(vrm, b, edits.get("lookAt"), g)
|
||||
n += bool(edits.get("expressions")) + bool(edits.get("spring")) + bool(edits.get("lookAt"))
|
||||
n += any(_num(v, 1.0) != 1.0 for v in (edits.get("intensity") or {}).values())
|
||||
if edits.get("title"):
|
||||
vrm["meta"]["name" if is1 else "title"] = str(edits["title"])
|
||||
n += 1
|
||||
thumb = thumb_for(edits, path)
|
||||
if thumb and os.path.isfile(thumb):
|
||||
with open(thumb, "rb") as f:
|
||||
png = f.read()
|
||||
bin_data, b["thumb"] = _add_thumb(g, bin_data, png, is1)
|
||||
if is1:
|
||||
vrm["meta"]["thumbnailImage"] = b["thumb"]["image"]
|
||||
else:
|
||||
vrm["meta"]["texture"] = b["thumb"]["texture"]
|
||||
n += 1
|
||||
if empty: # 全部还原:不留痕迹
|
||||
del g["extras"][BASE_KEY]
|
||||
if not g["extras"]:
|
||||
del g["extras"]
|
||||
if g.get("buffers"):
|
||||
g["buffers"][0]["byteLength"] = len(bin_data)
|
||||
_write(g, bin_data, out_path or path)
|
||||
return n
|
||||
|
||||
|
||||
def _write(g, bin_data, path):
|
||||
tmp = path + ".tmp"
|
||||
vrmio.write_glb(g, bin_data, tmp)
|
||||
for k in range(20): # 预览正在读这个文件时 Windows 不让替换,稍等再试
|
||||
try:
|
||||
os.replace(tmp, path)
|
||||
return
|
||||
except PermissionError:
|
||||
if k == 19:
|
||||
raise
|
||||
time.sleep(0.1)
|
||||
@@ -0,0 +1,14 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""PMX → VRM 转换的各个阶段(入口是 convert/pmx2vrm.py 的 convert())。
|
||||
|
||||
humanoid MMD 骨骼名 → VRM 骨位、付与骨合并、层级修正、A-pose → T-pose
|
||||
skeleton 骨骼预处理流程、glTF 节点树、占位骨
|
||||
mesh 顶点权重、按材质切 primitive、写 accessor
|
||||
materials MToon 材质(toon 渐变 → 阴影色 / 明暗交界,线性颜色,透明判定)
|
||||
expressions 顶点 / 材质表情 → morph target 与 VRM 表情
|
||||
springbone PMX 刚体物理 → VRMC_springBone
|
||||
vrm_ext VRMC_vrm / VRM 0.x 扩展本体
|
||||
mathutil 3x3 矩阵小工具
|
||||
|
||||
依赖 formats/ 下的 pmxio、vrmio(作为顶层模块导入,调用方负责把 formats/ 放进 sys.path)。
|
||||
"""
|
||||
@@ -0,0 +1,199 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""没有物理的模型(FBX / psk / xps 转来的 PMX 常见):按骨骼名和骨架结构自动补一套 MMD 刚体,
|
||||
再交给 springbone._build_springs 按同一套规则转成 VRM SpringBone。
|
||||
|
||||
* 摆动链(动态刚体,mode 1):名字像头发 / 裙摆 / 袖子 / 飘带 / 尾巴的非人形骨;
|
||||
另外挂在头骨下面、不像五官和头饰的非人形骨也算头发(Query 酱的头发骨叫 H01_Front、H02_L)。
|
||||
兽耳(Ear_0_L → Ear_1_L → … 这种挂在头下、连成多节的链)单独识别:_FACE 里的 ear/耳
|
||||
是为了挡住人形模型的单根耳饰 / 表情骨,但兽耳必须能摆,否则导出的 VRM 耳朵完全不动。
|
||||
胸部骨、扭转骨、IK、辅助骨不动。
|
||||
* 碰撞体(跟随骨骼的刚体,mode 0):头(球)、胸 / 腰(球)、上下臂和大小腿(胶囊),
|
||||
尺寸按身高比例给。
|
||||
裙摆 / 头发的区分、抽稀、硬度、碰撞的取舍都沿用 _build_springs(按挂点和高度自动判断)。
|
||||
"""
|
||||
import math
|
||||
import re
|
||||
|
||||
_SWING = re.compile(
|
||||
r"hair|kami|髪|ahoge|bang|fringe|pony|twin|braid|"
|
||||
r"skirt|スカート|suso|裾|dress|"
|
||||
r"sode|sleeve|袖|"
|
||||
r"ribbon|ribon|リボン|necktie|cape|cloak|mantle|scarf|マフラー|tassel|frill|フリル|"
|
||||
r"tail|尻尾|shippo|しっぽ|coat|jacket_?(?:l|r|b|f)", re.I)
|
||||
_NEVER = re.compile(
|
||||
r"mune|bust|breast|chichi|oppai|胸|pai_|^pai|twist|twst|捩|roll|(?:^|_)ik|ik(?:$|_)|helper|ctrl|"
|
||||
r"control|adj|root|dummy|ダミー|先$|tip$|nub$|ndl|offset|target|master|aim|socket|attach|"
|
||||
r"weapon|gun|holster|pocket|pouch|buckle|shell|prop|point", re.I)
|
||||
_FACE = re.compile(
|
||||
r"eye|目|jaw|顎|tongue|舌|teeth|tooth|歯|mouth|口|brow|眉|lid|瞼|cheek|頬|nose|鼻|face|顔|"
|
||||
r"lip|唇|chin|smile|crease|corner|nostril|temple|forehead|lash|pupil|iris|dimple|"
|
||||
r"hat|cap|crown|glass|megane|眼鏡|horn|角|acc|ear|耳|head_?end|headtop|top$", re.I)
|
||||
# 兽耳:日语模型常写作 mimi / みみ。耳环、耳机之类是挂件,不是耳朵骨
|
||||
_EAR = re.compile(r"ear|耳|mimi|みみ", re.I)
|
||||
_EAR_NOT = re.compile(
|
||||
r"earring|ear_ring|ear_?pierce|pierce|耳环|耳饰|earphone|headphone|イヤホン|イヤリング", re.I)
|
||||
|
||||
|
||||
def _ear_chains(bones, parents, nb, human, alias, head, under):
|
||||
"""→ 兽耳骨集合。条件:挂在头骨下、名字像耳朵、且至少两节连成链。
|
||||
|
||||
_FACE 把 ear/耳 当五官挡掉了,但那只该挡人形模型的单根耳饰 / 表情骨;
|
||||
Ear_0_L → Ear_1_L → Ear_2_L 这种多节兽耳是正经的动骨链,要放行。
|
||||
只认「有同组父骨或子骨」的骨,孤零零一根 ear 骨仍交给 _FACE 拦住。
|
||||
"""
|
||||
if head is None:
|
||||
return set()
|
||||
ear = {b for b in range(nb)
|
||||
if b not in human and b not in alias
|
||||
and _EAR.search(bones[b]["name"] or "")
|
||||
and not _EAR_NOT.search(bones[b]["name"] or "")
|
||||
and under(b, head)}
|
||||
if len(ear) < 2:
|
||||
return set()
|
||||
has_child = {parents[b] for b in ear if parents[b] in ear}
|
||||
return {b for b in ear if parents[b] in ear or b in has_child}
|
||||
|
||||
_ARM_SEG = (("leftUpperArm", "leftLowerArm"), ("leftLowerArm", "leftHand"),
|
||||
("rightUpperArm", "rightLowerArm"), ("rightLowerArm", "rightHand"))
|
||||
_LEG_SEG = (("leftUpperLeg", "leftLowerLeg"), ("leftLowerLeg", "leftFoot"),
|
||||
("rightUpperLeg", "rightLowerLeg"), ("rightLowerLeg", "rightFoot"))
|
||||
|
||||
|
||||
def _rot_for_dir(d):
|
||||
"""胶囊沿局部 Y:求 PMX 刚体旋转(Ry·Rx·Rz,取 ry=0)使 Y 轴指向 d。"""
|
||||
n = math.sqrt(sum(x * x for x in d)) or 1.0
|
||||
dx, dy, dz = (x / n for x in d)
|
||||
rz = math.asin(max(-1.0, min(1.0, -dx)))
|
||||
rx = math.atan2(dz, dy)
|
||||
return (rx, 0.0, rz)
|
||||
|
||||
|
||||
def _rb(name, bone, pos, mode, radius, height=0.0, rot=(0.0, 0.0, 0.0)):
|
||||
return {"name": name, "name_en": name, "bone": bone, "group": 1 if mode else 0, "mask": 0xFFFF,
|
||||
"shape": 2 if height > 0 else 0, "size": (radius, height, 0.0), "pos": tuple(pos),
|
||||
"rot": tuple(rot), "mass": 1.0, "move_damp": 0.5, "rot_damp": 0.5, "repulsion": 0.0,
|
||||
"friction": 0.5, "mode": mode}
|
||||
|
||||
|
||||
def _leaf_tails(model, dyn, children):
|
||||
"""链尾骨没有子骨时(FBX 里的单根发束骨很常见),按它带动的顶点估计长度:
|
||||
以这根骨为主权重的顶点里离骨头最远的那个,取 90% 当 tail。
|
||||
不估的话 tail 只有默认的一小截,整条链被当成「过短」不做物理。"""
|
||||
bones = model["bones"]
|
||||
dset = set(dyn)
|
||||
leaves = [b for b in dyn if not any(c in dset for c in children[b])
|
||||
and not any(c not in dset for c in children[b])]
|
||||
if not leaves:
|
||||
return
|
||||
far = {b: (0.0, None) for b in leaves}
|
||||
for v in model.get("vertices") or []:
|
||||
ws = v.get("wweights") or [1.0]
|
||||
bs = v.get("wbones") or []
|
||||
if not bs:
|
||||
continue
|
||||
k = max(range(min(len(bs), len(ws)) or 1), key=lambda i: ws[i] if i < len(ws) else 0)
|
||||
b = bs[k]
|
||||
if b in far:
|
||||
p, q = v["pos"], bones[b]["pos"]
|
||||
d = sum((p[i] - q[i]) ** 2 for i in range(3))
|
||||
if d > far[b][0]:
|
||||
far[b] = (d, p)
|
||||
for b, (d, p) in far.items():
|
||||
if p is None:
|
||||
continue
|
||||
q = bones[b]["pos"]
|
||||
off = tuple((p[i] - q[i]) * 0.9 for i in range(3))
|
||||
cur = bones[b].get("tail")
|
||||
cur_len = math.sqrt(sum(x * x for x in cur)) if bones[b].get("tail_kind") == 0 and cur else 0.0
|
||||
if math.sqrt(d) * 0.9 > cur_len:
|
||||
bones[b]["tail_kind"] = 0
|
||||
bones[b]["tail"] = off
|
||||
|
||||
|
||||
def needed(model):
|
||||
"""模型里没有任何会动的刚体(mode 1/2)时才自动补。"""
|
||||
return not any(rb.get("mode") in (1, 2) for rb in model.get("rigid_bodies") or [])
|
||||
|
||||
|
||||
def synthesize(model, parents, alias, human_b, log=None):
|
||||
"""往 model["rigid_bodies"] 里追加自动生成的刚体。返回 (摆动骨数, 碰撞体数)。"""
|
||||
bones = model["bones"]
|
||||
nb = len(bones)
|
||||
human = set(human_b.values())
|
||||
head = human_b.get("head")
|
||||
ys = [v["pos"][1] for v in model.get("vertices") or []] or [b["pos"][1] for b in bones] or [0.0]
|
||||
H = max(1e-6, max(ys) - min(ys)) # 模型身高(PMX 单位)
|
||||
children = [[] for _ in range(nb)]
|
||||
for i, p in enumerate(parents):
|
||||
if 0 <= p < nb:
|
||||
children[p].append(i)
|
||||
|
||||
def under(b, anc):
|
||||
p = parents[b]
|
||||
seen = set()
|
||||
while 0 <= p < nb and p not in seen:
|
||||
if p == anc:
|
||||
return True
|
||||
if p in human: # 中间隔着别的人形骨:不算直接挂在 anc 下面
|
||||
return False
|
||||
seen.add(p)
|
||||
p = parents[p]
|
||||
return False
|
||||
|
||||
ear_dyn = _ear_chains(bones, parents, nb, human, alias, head, under)
|
||||
|
||||
def swing(b):
|
||||
if b in human or b in alias:
|
||||
return False
|
||||
nm = bones[b]["name"] or ""
|
||||
if b in ear_dyn: # 多节兽耳链优先于 _FACE 的「五官」排除
|
||||
return True
|
||||
if _NEVER.search(nm):
|
||||
return False
|
||||
if _SWING.search(nm):
|
||||
return True
|
||||
# 名字看不出来、挂在头下面的:只有模型里一根名字像头发的骨都没有时才当头发
|
||||
# (Query 酱的 H01_Front)。有表情骨架的模型头下面是几十根嘴唇 / 眼睑骨,不能动
|
||||
return by_struct and head is not None and under(b, head) and not _FACE.search(nm)
|
||||
|
||||
by_struct = not any(re.search(r"hair|kami|髪|bang|fringe|pony|twin|braid", bones[b]["name"] or "", re.I)
|
||||
for b in range(nb) if b not in human)
|
||||
dyn = [b for b in range(nb) if swing(b)]
|
||||
_leaf_tails(model, dyn, children)
|
||||
rbs = model.setdefault("rigid_bodies", [])
|
||||
for b in dyn:
|
||||
nm = (bones[b]["name"] or "").lower()
|
||||
lower = bool(re.search(r"skirt|スカート|suso|裾|dress", nm))
|
||||
rbs.append(_rb("auto_" + (bones[b]["name"] or str(b)), b, bones[b]["pos"], 1,
|
||||
H * (0.02 if lower else 0.012)))
|
||||
|
||||
# ---- 碰撞体
|
||||
n_col = 0
|
||||
pos = {k: bones[v]["pos"] for k, v in human_b.items()}
|
||||
if "head" in human_b:
|
||||
c = pos["head"]
|
||||
rbs.append(_rb("auto_col_head", human_b["head"], (c[0], c[1] + H * 0.045, c[2]), 0, H * 0.055))
|
||||
n_col += 1
|
||||
for k, r in (("upperChest", 0.065), ("chest", 0.065), ("spine", 0.06), ("hips", 0.06)):
|
||||
if k in human_b and not (k == "chest" and "upperChest" in human_b):
|
||||
rbs.append(_rb("auto_col_" + k, human_b[k], pos[k], 0, H * r))
|
||||
n_col += 1
|
||||
for a, b in _ARM_SEG + _LEG_SEG:
|
||||
if a not in human_b or b not in human_b:
|
||||
continue
|
||||
p0, p1 = pos[a], pos[b]
|
||||
d = [p1[k] - p0[k] for k in range(3)]
|
||||
ln = math.sqrt(sum(x * x for x in d))
|
||||
if ln < 1e-6:
|
||||
continue
|
||||
r = H * (0.04 if "UpperLeg" in a else 0.03 if "LowerLeg" in a else 0.028)
|
||||
mid = [(p0[k] + p1[k]) / 2 for k in range(3)]
|
||||
rbs.append(_rb("auto_col_" + a, human_b[a], mid, 0, r, max(0.0, ln - 2 * r) or ln * 0.5,
|
||||
_rot_for_dir(d)))
|
||||
n_col += 1
|
||||
if log and dyn:
|
||||
log("物理:模型不含物理刚体,已按骨骼名和骨架结构自动添加 %d 根摆动骨(头发、裙摆、袖子、飘带、兽耳等)"
|
||||
"和 %d 个身体碰撞体" % (len(dyn), n_col))
|
||||
if log and ear_dyn:
|
||||
log("物理:识别到 %d 根兽耳骨,已加入摆动链" % len(ear_dyn))
|
||||
return len(dyn), n_col
|
||||
@@ -0,0 +1,149 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""转换后的自检:只在日志里提示,不改输出。
|
||||
|
||||
follow 网格在 MMD 里跟着哪些关节动、在 VRM 里还跟不跟(付与骨没处理到之类)
|
||||
odd_bones humanoid 骨位置明显不对:在身体另一侧、离父骨太远、离网格太远(多半是把模型外面的控制骨当成了 humanoid 骨)
|
||||
"""
|
||||
import math
|
||||
|
||||
from .humanoid import _clean_parents, _vrm_anchor
|
||||
|
||||
MIN_VERTS = 20 # 少于这么多顶点的不提示(个别顶点权重刷错很常见,看不出来)
|
||||
|
||||
|
||||
def follow(bones, bs, raw_weights, vweights, tol=0.3):
|
||||
"""→ [(顶点数, 骨, humanoid 骨位, MMD 里的跟随率, VRM 里的跟随率)],按顶点数从多到少。
|
||||
|
||||
MMD 里顶点跟某个关节转多少:按原始权重,累加每根骨沿父骨链和付与(按付与率)得到的该关节的旋转;
|
||||
VRM 里:按最终权重,累加祖先里有该关节的骨。差 tol 以上的顶点按「主要挂在哪根骨上」归类。
|
||||
hips 不比(MMD 的 上半身 不在 下半身 下,VRM 要求在,这是有意改的)。
|
||||
"""
|
||||
n = len(bones)
|
||||
if not n:
|
||||
return []
|
||||
orig = _clean_parents(bones)
|
||||
slot = {i: h for h, i in bs.human_b.items() if h != "hips"}
|
||||
memo_l, memo_m = {}, {}
|
||||
|
||||
def local(i, depth=0): # 骨自己的旋转里有哪些关节:{骨位: 比例}
|
||||
if i in memo_l:
|
||||
return memo_l[i]
|
||||
out = {slot[i]: 1.0} if i in slot else {}
|
||||
ir = bones[i].get("inherit_rot")
|
||||
if ir and depth < 16 and 0 <= ir[0] < n and ir[0] != i:
|
||||
for h, r in local(ir[0], depth + 1).items():
|
||||
out[h] = out.get(h, 0.0) + ir[1] * r
|
||||
memo_l[i] = out
|
||||
return out
|
||||
|
||||
order = sorted(range(n), key=lambda i: _depth(orig, i)) # 父在前(PMX 的骨序不一定是)
|
||||
for i in order:
|
||||
out = dict(memo_m.get(orig[i], {})) if orig[i] >= 0 else {}
|
||||
for h, r in local(i).items():
|
||||
out[h] = out.get(h, 0.0) + r
|
||||
memo_m[i] = out
|
||||
|
||||
vrm = {}
|
||||
|
||||
def vrm_of(b):
|
||||
if b not in vrm:
|
||||
s, k, seen = set(), b, set()
|
||||
while 0 <= k < n and k not in seen:
|
||||
if k in slot:
|
||||
s.add(slot[k])
|
||||
seen.add(k)
|
||||
k = bs.parents[k]
|
||||
vrm[b] = s
|
||||
return vrm[b]
|
||||
|
||||
# 只看可能不一致的骨上的顶点:MMD 的跟随和它(并入后)在 VRM 里的祖先不一样的
|
||||
odd = set()
|
||||
for b in range(n):
|
||||
want = memo_m[b]
|
||||
got = vrm_of(bs.alias.get(b, b))
|
||||
if any(abs(r - (1.0 if h in got else 0.0)) >= tol for h, r in want.items()) or \
|
||||
any(h not in want for h in got):
|
||||
odd.add(b)
|
||||
found = {}
|
||||
for vi, wl in enumerate(raw_weights):
|
||||
if odd.isdisjoint(b for b, _ in wl):
|
||||
continue
|
||||
want = {}
|
||||
for b, w in wl:
|
||||
for h, r in memo_m[b].items():
|
||||
want[h] = want.get(h, 0.0) + w * r
|
||||
got = {}
|
||||
for b, w in vweights[vi]:
|
||||
for h in vrm_of(b):
|
||||
got[h] = got.get(h, 0.0) + w
|
||||
for h, r in want.items():
|
||||
if r - got.get(h, 0.0) >= tol:
|
||||
main = max(wl, key=lambda t: t[1])[0]
|
||||
e = found.setdefault((main, h), [0, 0.0, 0.0])
|
||||
e[0] += 1
|
||||
e[1] += r
|
||||
e[2] += got.get(h, 0.0)
|
||||
return sorted(((c, b, h, sw / c, sg / c) for (b, h), (c, sw, sg) in found.items() if c >= MIN_VERTS),
|
||||
key=lambda t: -t[0])
|
||||
|
||||
|
||||
def _depth(parents, i):
|
||||
d, seen = 0, set()
|
||||
while 0 <= parents[i] < len(parents) and i not in seen:
|
||||
seen.add(i)
|
||||
i = parents[i]
|
||||
d += 1
|
||||
return d
|
||||
|
||||
|
||||
def odd_bones(bs, bpos, vpos, far=0.1, seg=0.35, side=0.02):
|
||||
"""→ [(humanoid 骨位, 骨, 原因, 数值)]:位置明显不对的 humanoid 骨(PMX 坐标、T-pose 后,角色左边是 +X)。
|
||||
|
||||
多半是模型外面的控制骨(调整用的「肩調整」之类)被当成了 humanoid 骨,动作时肩膀、手臂会被拉过去:
|
||||
side 左边的骨在身体右侧(或反过来)超过模型高度的 side 倍
|
||||
seg 离 humanoid 父骨位超过模型高度的 seg 倍(大腿、小腿最长也只有 1/4 左右)
|
||||
far 附近(模型高度的 far 倍以内)没有任何顶点:关节都在身体里,离皮肤顶多几厘米。用网格哈希,不逐点算
|
||||
数值:side / far 是模型高度的倍数,seg 是 (父骨位, 距离 / 模型高度)。
|
||||
"""
|
||||
if not vpos or not bs.human_b:
|
||||
return []
|
||||
ys = [p[1] for p in vpos]
|
||||
h = max(ys) - min(ys)
|
||||
if h <= 1e-6:
|
||||
return []
|
||||
cell = h * far / 2
|
||||
occ = {(int(p[0] // cell), int(p[1] // cell), int(p[2] // cell)) for p in vpos}
|
||||
out = []
|
||||
for slot_, i in bs.human_b.items():
|
||||
p = bpos[i]
|
||||
if (slot_.startswith("left") and p[0] < -side * h) or (slot_.startswith("right") and p[0] > side * h):
|
||||
out.append((slot_, i, "side", abs(p[0]) / h))
|
||||
continue
|
||||
par = _vrm_anchor(slot_, bs.human_b)
|
||||
if par and math.dist(p, bpos[bs.human_b[par]]) > seg * h:
|
||||
out.append((slot_, i, "seg", (par, math.dist(p, bpos[bs.human_b[par]]) / h)))
|
||||
continue
|
||||
x, y, z = (int(c // cell) for c in p)
|
||||
if not any((x + dx, y + dy, z + dz) in occ
|
||||
for dx in (-2, -1, 0, 1, 2) for dy in (-2, -1, 0, 1, 2) for dz in (-2, -1, 0, 1, 2)):
|
||||
out.append((slot_, i, "far", far))
|
||||
return out
|
||||
|
||||
|
||||
def report(bones, bs, raw_weights, vweights, bpos, vpos, scale, log):
|
||||
"""跑两项检查,把问题写进日志(warn)。"""
|
||||
for c, b, h, want, got in follow(bones, bs, raw_weights, vweights)[:6]:
|
||||
log("自检:%d 个顶点主要挂在 %s 上,MMD 里跟着 %s 转 %d%%,VRM 里只跟 %d%%,动作时这部分会变形"
|
||||
% (c, bones[b]["name"], h, round(want * 100), round(got * 100)), "warn")
|
||||
ys = [p[1] for p in vpos] or [0.0]
|
||||
cm = (max(ys) - min(ys)) * scale * 100
|
||||
for h, i, why, v in odd_bones(bs, bpos, vpos)[:6]:
|
||||
name = bones[i]["name"]
|
||||
if why == "side":
|
||||
log("自检:humanoid 骨 %s(%s)在身体的另一侧,可能对应错了骨骼,动作时这部分会被拉开" % (h, name), "warn")
|
||||
elif why == "seg":
|
||||
log("自检:humanoid 骨 %s(%s)离 %s 有 %d cm,可能对应错了骨骼,动作时这部分会被拉开"
|
||||
% (h, name, v[0], round(v[1] * cm)), "warn")
|
||||
else:
|
||||
log("自检:humanoid 骨 %s(%s)离网格超过 %d cm,可能对应错了骨骼,动作时这部分会被拉开"
|
||||
% (h, name, round(v * cm)), "warn")
|
||||
@@ -0,0 +1,787 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""表情:PMX 顶点 / 材质表情(含グループ展开)→ morph target + VRM 表情(1.0 expressions / 0.x blendShapeGroups)。"""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
import vrmio
|
||||
|
||||
from . import morphbake
|
||||
from .materials import _lin_rgb, _mmd_color, _morph_material
|
||||
from .mathutil import _m3vec
|
||||
|
||||
# MMD 标准表情名 → VRM 预设
|
||||
# 单眼眨眼(ウィンク…)不在表里:名字靠不住,按顶点在哪一边决定(wink_presets)
|
||||
EXPR_1_0 = {
|
||||
"まばたき": "blink", "瞬き": "blink",
|
||||
"びっくり": "surprised", "怒り": "angry", "怒る": "angry",
|
||||
"悲しみ": "sad", "困る": "sad",
|
||||
"にこり": "happy", "笑い": "happy", "にやり": "happy",
|
||||
"あ": "aa", "あ2": "aa", "い": "ih", "う": "ou", "え": "ee", "お": "oh",
|
||||
}
|
||||
# 「真面目」是严肃的眉毛,不是 relaxed(放松、愉快);relaxed 交给下面的组合。
|
||||
# 注意:MMD 标准表情里的「上」「下」是**眉毛**表情(眉パネル),不是视线,
|
||||
# 所以不映射到 lookUp / lookDown(以前映射了,VRM 里一看上方眉毛就跳起来)。
|
||||
# MMD 没有标准的视线表情,视线交给 lookAt(type=bone)。
|
||||
# VRM 0.x 的 presetName 规范里是小写枚举(three-vrm 也只认小写,"Joy" 会被当成自定义表情)
|
||||
EXPR_0X = {
|
||||
"まばたき": "blink", "瞬き": "blink",
|
||||
"怒り": "angry", "悲しみ": "sorrow", "困る": "sorrow",
|
||||
"にこり": "joy", "笑い": "joy",
|
||||
"あ": "a", "あ2": "a", "い": "i", "う": "u", "え": "e", "お": "o",
|
||||
}
|
||||
|
||||
|
||||
# 中文表情名(整张脸,单独对应一个预设;比日文名、英文名优先级低)。左右单眼的「左眨眼」等走 _WINK
|
||||
EXPR_CN = {"眨眼": "blink", "闭眼": "blink", "啊": "aa", "阿": "aa", "咿": "ih", "伊": "ih", "呜": "ou", "乌": "ou",
|
||||
"诶": "ee", "欸": "ee", "哦": "oh", "喔": "oh", "开心": "happy", "高兴": "happy", "微笑": "happy",
|
||||
"生气": "angry", "愤怒": "angry", "伤心": "sad", "难过": "sad", "悲伤": "sad",
|
||||
"惊讶": "surprised", "吃惊": "surprised", "放松": "relaxed"}
|
||||
|
||||
# 英文表情名(FBX 等转来的模型)→ VRM 1.0 预设。只在日文名没占用这个预设时才用。
|
||||
# VRChat:vrc.v_aa / vrc.blink_left VRoid:Fcl_MTH_A / Fcl_EYE_Close_L / Fcl_ALL_Joy
|
||||
# Unity 酱:MTH_A / EYE_DEF_C(闭眼) 通用:blink、mouth_a、happy …
|
||||
_EN_VOWEL = {"a": "aa", "aa": "aa", "i": "ih", "ih": "ih", "u": "ou", "ou": "ou",
|
||||
"e": "ee", "ee": "ee", "o": "oh", "oh": "oh"}
|
||||
_EN_EMO = {"joy": "happy", "happy": "happy", "smile": "happy", "angry": "angry", "anger": "angry",
|
||||
"sorrow": "sad", "sad": "sad", "fun": "relaxed", "relaxed": "relaxed",
|
||||
"surprised": "surprised", "surprise": "surprised", "neutral": "neutral"}
|
||||
_TO_0X = {"happy": "joy", "aa": "a", "ih": "i", "ou": "u", "ee": "e", "oh": "o", "sad": "sorrow",
|
||||
"relaxed": "fun", "blinkLeft": "blink_l", "blinkRight": "blink_r", "lookUp": "lookup",
|
||||
"lookDown": "lookdown", "lookLeft": "lookleft", "lookRight": "lookright"}
|
||||
|
||||
|
||||
# 情绪预设组合眉 / 眼 / 嘴(像 VRoid 的 Fcl_ALL_*)。MMD 的情绪表情是按面板拆开的,
|
||||
# 一个预设只对应一个表情时,sad / angry 只动眉毛、happy / surprised 只动眼睛,游戏里很弱。
|
||||
# 每个部位:(PMX 面板:1 眉 / 2 目 / 3 口, [(候选表情名, 权重)],取第一个模型里有的)。
|
||||
# 闭眼类的眼睛表情(なごみ、笑い)不用半权重:很多模型是把瞳孔压扁来闭眼,一半时瞳孔缩成小点。
|
||||
# 眼睛是闭着笑的预设(BLINK_BLEND)设 overrideBlink: blend,不然再眨眼会闭两遍;
|
||||
# 别的预设不设——游戏播难过、生气时照样眨眼,blend 会把眨眼压没。
|
||||
# 候选可以是一个名字,也可以是几个名字的元组(ARKit 的左右各一个:都有才算,一起用);
|
||||
# EN 是「英文部位名」:VRoid 的 Fcl_BRW_Angry / Fcl_EYE_Joy / Fcl_MTH_Sad、Mouth_Sad 之类(_en_part)。
|
||||
# 每个部位按 MMD 名 → 英文部位名 → ARKit 的顺序找,取第一个模型里有的。
|
||||
EN = "@en"
|
||||
_L_R = lambda a: (a + "Left", a + "Right") # noqa: E731 ARKit 的左右一对
|
||||
COMBO = {
|
||||
"happy": [(1, [("にこり", 1.0), ("にこり2", 1.0), ("喜び", 1.0), ("上", 0.3), (EN, 1.0)]),
|
||||
(2, [("笑い", 1.0), ("笑い2", 1.0), ("喜び", 1.0), ("なごみ", 1.0), (EN, 1.0),
|
||||
(_L_R("eyeBlink"), 0.8)]),
|
||||
(3, [("にやり", 1.0), ("口角上げ", 1.0), ("にやり2", 1.0), (EN, 1.0), (_L_R("mouthSmile"), 1.0)])],
|
||||
# 生气比 MMD 原表情含蓄(和 VRoid 的 Angry 差不多):VRM 预设通常和眨眼、口型、别的预设叠着用
|
||||
# (游戏常拿 angry 当「痛苦、用力」,再叠 ih / oh / 闭眼)。满值的「怒り」皱眉太重、「キリッ」是瞪眼、
|
||||
# 「∧」拱起的嘴叠上张嘴就成了龇牙,所以都降权重,嘴优先用嘴角下撇
|
||||
"angry": [(1, [("怒り", 0.5), (EN, 0.5), (_L_R("browDown"), 0.5)]),
|
||||
(2, [("怒り目", 0.3), ("キリッ", 0.3), ("じと目", 0.25), ("ジト目", 0.25), (EN, 0.3),
|
||||
(_L_R("eyeSquint"), 0.3)]),
|
||||
(3, [("口角下げ", 0.4), ("ムッ", 0.4), ("∧", 0.3), ("怒った", 0.3), (EN, 0.4),
|
||||
(_L_R("mouthFrown"), 0.4)])],
|
||||
# 难过不用「じと目」「∧」:半眯眼 + 撇嘴就是生气的样子(游戏里 sad 和 angry 分不出来)。
|
||||
# 星铁系模型没有难过的眼形,只用眉毛 +「心配する」(担心的波浪嘴)
|
||||
"sad": [(1, [("困る", 1.0), ("悲しい", 1.0), ("悲しむ", 1.0), (EN, 1.0), ("browInnerUp", 1.0)]),
|
||||
(2, [("悲しむ", 0.6), ("垂れ目", 0.6), (EN, 0.6)]),
|
||||
(3, [("心配する", 1.0), ("口角下げ", 0.5), (EN, 1.0), (_L_R("mouthFrown"), 0.7)])],
|
||||
"relaxed": [(1, [("にこり", 0.5), ("喜び", 0.5), ("上", 0.2), (EN, 0.5)]),
|
||||
(2, [("慈愛", 1.0), ("笑い目", 1.0), ("喜び", 0.7), ("なごみ", 1.0), (EN, 1.0),
|
||||
(_L_R("eyeBlink"), 0.4)]),
|
||||
(3, [("にやり", 0.6), ("口角上げ", 0.6), (EN, 0.6), (_L_R("mouthSmile"), 0.6)])],
|
||||
# 惊讶只睁眼、抬眉,不张嘴:常和口型(aa / oh)、生气叠用,再带张嘴会撑得过大
|
||||
"surprised": [(1, [("上", 0.7), (EN, 0.7), (("browInnerUp",) + _L_R("browOuterUp"), 0.7)]),
|
||||
(2, [("びっくり", 1.0), ("見開く", 1.0), ("驚かす", 1.0), (EN, 1.0), (_L_R("eyeWide"), 1.0)])],
|
||||
}
|
||||
# 名字对应不上单个表情时的退路(1.0 名):ARKit 的眨眼、口型(粗略:张嘴 / 嘟嘴 / 噘圆 / 咧嘴)。
|
||||
# ARKit 的笑眼用 eyeBlink 半闭(eyeSquint 只抬下眼睑,很多模型几乎看不出来)。
|
||||
# 第一项必须有,后面的有就加上
|
||||
FALLBACK = {"blink": [(_L_R("eyeBlink"), 1.0)],
|
||||
"aa": [(("jawOpen",), 1.0)], "ou": [(("mouthPucker",), 1.0)],
|
||||
"oh": [(("mouthFunnel",), 1.0), (("jawOpen",), 0.3)],
|
||||
# mouthStretch 单用是嘴角往下拉的苦脸:e / i 要和 mouthSmile、一点张嘴混起来
|
||||
"ee": [(_L_R("mouthStretch"), 0.4), (_L_R("mouthSmile"), 0.4), (("jawOpen",), 0.25)],
|
||||
"ih": [(_L_R("mouthStretch"), 0.3), (_L_R("mouthSmile"), 0.3), (("jawOpen",), 0.12)]}
|
||||
# VRM 0.x 没有 surprised 预设:和 VRoid 的 0.x 一样写成 unknown、名字叫 Surprised
|
||||
BLINK_BLEND = {"happy", "relaxed"}
|
||||
_COMBO_0X = {"happy": "joy", "angry": "angry", "sad": "sorrow", "relaxed": "fun", "surprised": None}
|
||||
PRESETS_1 = {"happy", "angry", "sad", "relaxed", "surprised", "neutral", "aa", "ih", "ou", "ee", "oh",
|
||||
"blink", "blinkLeft", "blinkRight", "lookUp", "lookDown", "lookLeft", "lookRight"}
|
||||
PRESETS_0 = {"neutral", "a", "i", "u", "e", "o", "blink", "joy", "angry", "sorrow", "fun",
|
||||
"lookup", "lookdown", "lookleft", "lookright", "blink_l", "blink_r"}
|
||||
|
||||
|
||||
def _covers(big, small):
|
||||
"""big 的偏移已经包含了 small(八成以上顶点相同、幅度一半以上):两个一起用就动两遍。
|
||||
比如有的模型「キリッ」「垂れ目」里自带了「怒り」「困る」的眉毛。"""
|
||||
shared = [v for v in small if v in big]
|
||||
if not small or len(shared) < 0.8 * len(small):
|
||||
return False
|
||||
a = sum(abs(big[v][0]) + abs(big[v][1]) + abs(big[v][2]) for v in shared)
|
||||
b = sum(abs(small[v][0]) + abs(small[v][1]) + abs(small[v][2]) for v in shared)
|
||||
return b > 0 and a >= 0.5 * b
|
||||
|
||||
|
||||
def _key(name):
|
||||
"""比较用的名字:全角半角统一(キリッ = キリッ、2 = 2)、小写、去掉 blendShape. / vrc. 前缀和
|
||||
英文分隔符(_ . - 空格),结尾的 _L / _R 写成 left / right(eyeBlink_L = eyeBlinkLeft)。
|
||||
∧ ω ▲ 这类符号表情名不动。"""
|
||||
s = unicodedata.normalize("NFKC", name or "").strip().lower()
|
||||
s = re.sub(r"^(?:blendshape\d*|vrc)\.", "", s)
|
||||
s = re.sub(r"[_.\- ]+([lr])$", lambda m: "left" if m.group(1) == "l" else "right", s)
|
||||
return re.sub(r"[_.\- ]+", "", s)
|
||||
|
||||
|
||||
_TABLE_KEY = {True: {_key(n): p for n, p in EXPR_1_0.items()}, False: {_key(n): p for n, p in EXPR_0X.items()}}
|
||||
_CN_KEY = {_key(n): p for n, p in EXPR_CN.items()}
|
||||
|
||||
|
||||
class Lookup:
|
||||
"""模型里的表情名索引:按 _key 找;找不到时认变体后缀 A / B / 1 / 2 / 3(怒りA、にこりB、笑い2),
|
||||
不认 L / R 这类单边的。"""
|
||||
|
||||
def __init__(self, names):
|
||||
self.names = list(names)
|
||||
self.by_key = {}
|
||||
for n in self.names:
|
||||
self.by_key.setdefault(_key(n), n)
|
||||
|
||||
def get(self, cand):
|
||||
k = _key(cand)
|
||||
if k in self.by_key:
|
||||
return self.by_key[k]
|
||||
for suf in ("a", "b", "1", "2", "3"):
|
||||
if k + suf in self.by_key:
|
||||
return self.by_key[k + suf]
|
||||
return None
|
||||
|
||||
def all(self, cands):
|
||||
"""几个名字都有 → 实际名字的元组;缺一个就 None。"""
|
||||
got = tuple(self.get(c) for c in cands)
|
||||
return got if all(got) and len(set(got)) == len(got) else None
|
||||
|
||||
|
||||
_EN_PART_WORD = {"brow": 1, "brw": 1, "eyebrow": 1, "eyebrows": 1,
|
||||
"eye": 2, "eyes": 2, "mouth": 3, "mth": 3, "lip": 3, "lips": 3}
|
||||
# 每种情绪的英文词,按优先顺序(嘴:smile 是抿嘴笑,laugh 是张嘴大笑,先用 smile)
|
||||
_EN_FEEL_WORDS = {"happy": ["joy", "happy", "smile", "laugh"], "angry": ["angry", "anger", "mad"],
|
||||
"sad": ["sorrow", "sad", "trouble", "worried", "worry"],
|
||||
"relaxed": ["fun", "relaxed", "relax", "gentle"],
|
||||
"surprised": ["surprised", "surprise", "shock", "wide"]}
|
||||
_EN_SIDE = {"l", "r", "left", "right"}
|
||||
|
||||
|
||||
def _en_words(name):
|
||||
"""Fcl_BRW_Angry → [fcl, brw, angry];Mouth_Smile1 → [mouth, smile];eyeSmileLeft → [eye, smile, left]。"""
|
||||
s = unicodedata.normalize("NFKC", name or "")
|
||||
s = re.sub(r"([a-z])([A-Z])", r"_", s).lower()
|
||||
return [re.sub(r"\d+$", "", w) for w in re.split(r"[^a-z0-9]+", s) if w]
|
||||
|
||||
|
||||
def _en_part(lookup, preset, part):
|
||||
"""英文部位名里找「这个部位 + 这种情绪」的表情:VRoid 的 Fcl_EYE_Joy、通用的 Mouth_Sad 等。
|
||||
单边的(带 L / R)不算;有几个时按情绪词的优先顺序、再按模型里的顺序。"""
|
||||
best = None
|
||||
for k, n in enumerate(lookup.names):
|
||||
ws = _en_words(n)
|
||||
if not ws or set(ws) & _EN_SIDE or "all" in ws:
|
||||
continue
|
||||
parts = {_EN_PART_WORD[w] for w in ws if w in _EN_PART_WORD}
|
||||
feels = [i for i, w in enumerate(_EN_FEEL_WORDS[preset]) if w in ws]
|
||||
if parts == {part} and feels:
|
||||
rank = (min(feels), k)
|
||||
if best is None or rank < best[0]:
|
||||
best = (rank, n)
|
||||
return best[1] if best else None
|
||||
|
||||
|
||||
def _covers_any(deltas, a, b):
|
||||
"""两组表情(各是名字元组)动的是不是同一批顶点(任一方向 _covers)。"""
|
||||
def merged(names):
|
||||
out = {}
|
||||
for n in names:
|
||||
for v, d in deltas[n].items():
|
||||
o = out.get(v, (0.0, 0.0, 0.0))
|
||||
out[v] = (o[0] + d[0], o[1] + d[1], o[2] + d[2])
|
||||
return out
|
||||
da, db = merged(a), merged(b)
|
||||
return _covers(da, db) or _covers(db, da)
|
||||
|
||||
|
||||
def combo_recipes(deltas, panel, lookup=None):
|
||||
"""→ {预设(1.0 名): [(表情名, 权重, 部位 1 眉 / 2 目 / 3 口)]}(ARKit 左右一对时同一部位有两项)。
|
||||
|
||||
deltas:表情名 → 顶点偏移(只算有顶点偏移的表情);panel:表情名 → PMX 面板。
|
||||
每个部位按 COMBO 的候选顺序找(名字按 Lookup 规则匹配)。MMD 名的候选放在别的脸部面板
|
||||
(眉 / 目 / 口)时不算(比如眼睛面板的「喜び」不当眉毛);「其他」面板不限制(有的模型眉毛放在那里)。
|
||||
和已选的部位动同一批顶点(_covers)的候选跳过、换下一个。至少两个部位找到才组合。
|
||||
"""
|
||||
lookup = lookup or Lookup(deltas)
|
||||
out = {}
|
||||
for p, parts in COMBO.items():
|
||||
got = [] # [(名字元组, 权重, 部位)]
|
||||
for pn, cands in parts:
|
||||
for c, w in cands:
|
||||
if c == EN:
|
||||
n = _en_part(lookup, p, pn)
|
||||
names = (n,) if n else None
|
||||
elif isinstance(c, tuple):
|
||||
names = lookup.all(c)
|
||||
else:
|
||||
n = lookup.get(c)
|
||||
names = (n,) if n and panel.get(n) in (pn, 0, 4, None) else None
|
||||
if not names or any(n not in deltas for n in names):
|
||||
continue
|
||||
if all(not set(names) & set(g[0]) and not _covers_any(deltas, names, g[0]) for g in got):
|
||||
got.append((names, w, pn))
|
||||
break
|
||||
if len(got) >= 2:
|
||||
out[p] = [(n, w, pn) for names, w, pn in got for n in names]
|
||||
return out
|
||||
|
||||
|
||||
_WINK = re.compile(r"ウィンク|ウィンク|wink", re.I)
|
||||
_BLINK_SIDE = re.compile(r"(?:blink|eye_?close[d]?|eye_def_c)[._ ]?(?:l|r|left|right)$|[左右]眨眼|眨眼[左右]", re.I)
|
||||
|
||||
|
||||
def _wink_rank(name):
|
||||
"""单眼闭眼的表情 → 优先级(0 = 名字就是单眼闭眼:eyeBlinkLeft、blink_R、左眨眼;
|
||||
1 = ウィンク;2 = ウィンク2 这类笑眼版);不是单眼闭眼 → None。"""
|
||||
if _BLINK_SIDE.search(re.sub(r"(?<=[a-z])(?=[A-Z])", "_", name or "")):
|
||||
return 0
|
||||
if _WINK.search(name or ""):
|
||||
return 2 if re.search(r"[22]", name) else 1
|
||||
return None
|
||||
|
||||
|
||||
def _wink_sides(flat, vertices):
|
||||
"""→ {("L" / "R", 优先级): 表情名},同一格取最前面的。
|
||||
|
||||
MMD 惯例「ウィンク」闭左眼、「ウィンク右」闭右眼、「ウィンク2」是同一只眼的笑眼版,
|
||||
但不少模型不守(鸣潮的「ウィンク2」闭右眼,有的「ウィンク」闭右眼);ARKit 的 eyeBlinkLeft
|
||||
是角色自己的左眼还是镜像也看工具。所以看顶点:PMX 里角色的左边是 +X,动的顶点九成以上在一边才算。
|
||||
"""
|
||||
out = {}
|
||||
for n, d, _, _ in flat:
|
||||
rank = _wink_rank(n)
|
||||
if not d or rank is None:
|
||||
continue
|
||||
left = sum(1 for v in d if vertices[v]["pos"][0] > 0) / len(d)
|
||||
side = "L" if left >= 0.9 else "R" if left <= 0.1 else None
|
||||
if side:
|
||||
out.setdefault((side, rank), n)
|
||||
return out
|
||||
|
||||
|
||||
# ---- 补充的自定义表情(add_extras):名字统一,程序按名字就能找到
|
||||
# 关掉眼睛高光的表情(模型自带时用它;几组高光各有一个时合起来)
|
||||
_HL_OFF = re.compile(r"(ハイライト|ハイライト|高光|目光|瞳光|eye[ _]?hi\d*|hi[ _]?light|high[ _]?light)"
|
||||
r"[ _]*(消し?|消失|消去|オフ|オフ|off|なし|無し|hide|隠し?)", re.I)
|
||||
# 眼睛高光材质(模型没有上面的表情时,生成一个把它们收起来的表情)
|
||||
_HL_MAT = re.compile(r"目光|瞳光|ハイライト|ハイライト|高光|high[ _]?light|hi[ _]?light|eye[ _]?hi(?![a-z])", re.I)
|
||||
_HL_HI = re.compile(r"(?:^|[^a-z])hi\d*(?:[^a-z]|$)", re.I) # 「hi」「hi2」「+hi」这样单独的词
|
||||
_HL_EYE = re.compile(r"目|瞳|眼|eye", re.I)
|
||||
_HL_NOT = re.compile(r"髪|髮|发|hair", re.I) # 头发高光不算
|
||||
# 吐舌:按顺序取模型里第一个有的(てへぺろ 还带着眨一只眼,放最后)
|
||||
TONGUE = ["舌出し", "舌だし", "ぺろっ", "ぺろり", "べー", "吐舌", "吐舌头", "tongueOut", "tongue_out", "てへぺろ"]
|
||||
|
||||
|
||||
def _highlight_materials(model):
|
||||
"""眼睛高光材质的序号:名字像高光(目光、ハイライト、eye hi …),或名字里有单独的 hi、
|
||||
又像眼睛(eye hi1、MI_Eye+hi);头发高光除外。"""
|
||||
tex = model.get("textures") or []
|
||||
out = []
|
||||
for mi, mat in enumerate(model["materials"]):
|
||||
name = mat.get("name") or ""
|
||||
t = mat.get("tex", -1)
|
||||
tname = tex[t].replace("\\", "/").rsplit("/", 1)[-1] if 0 <= t < len(tex) else ""
|
||||
if _HL_NOT.search(name) or mat["faces"] < 3:
|
||||
continue
|
||||
if _HL_MAT.search(name) or (_HL_HI.search(name) and _HL_EYE.search(name)) or \
|
||||
(_HL_EYE.search(name) and _HL_MAT.search(tname)):
|
||||
out.append(mi)
|
||||
return out
|
||||
|
||||
|
||||
def _collapse_morph(model, mats):
|
||||
"""把这些材质的顶点各自收到所在那一块(相连的面)的中心:面积为 0,看不见了。
|
||||
→ PMX 顶点表情的 offsets(和别的材质共用的顶点不动)。"""
|
||||
faces = model["faces"]
|
||||
owner = {} # 顶点 → 用到它的材质(只记是不是全在 mats 里)
|
||||
ranges, cur = [], 0
|
||||
for mi, mat in enumerate(model["materials"]):
|
||||
ranges.append((cur, cur + mat["faces"]))
|
||||
cur += mat["faces"]
|
||||
want = set(mats)
|
||||
for mi, (a, b) in enumerate(ranges):
|
||||
inside = mi in want
|
||||
for vi in faces[a:b]:
|
||||
owner[vi] = owner.get(vi, True) and inside
|
||||
parent = {}
|
||||
|
||||
def find(x):
|
||||
while parent.setdefault(x, x) != x:
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
return x
|
||||
for mi in mats:
|
||||
a, b = ranges[mi]
|
||||
for k in range(a, b - 2, 3):
|
||||
ra, rb, rc = find(faces[k]), find(faces[k + 1]), find(faces[k + 2])
|
||||
parent[rb] = ra
|
||||
parent[find(rc)] = ra
|
||||
groups = {}
|
||||
for vi in parent:
|
||||
if owner.get(vi):
|
||||
groups.setdefault(find(vi), []).append(vi)
|
||||
verts = model["vertices"]
|
||||
offsets = []
|
||||
for vs in groups.values():
|
||||
c = [sum(verts[v]["pos"][j] for v in vs) / len(vs) for j in range(3)]
|
||||
for v in vs:
|
||||
p = verts[v]["pos"]
|
||||
offsets.append((v, (c[0] - p[0], c[1] - p[1], c[2] - p[2])))
|
||||
return offsets
|
||||
|
||||
|
||||
def add_extras(model, log):
|
||||
"""补充两个自定义表情,加在 model["morphs"] 末尾(之后和别的表情一样转换):
|
||||
|
||||
hideHighlight 关掉眼睛高光:模型有对应的表情(「ハイライト消し」「eye hi off」…)就用它(几个合成一组);
|
||||
没有就按材质名找眼睛高光,生成一个把这些面收成一点的顶点表情
|
||||
tongue 吐舌:模型里「舌出し」「ぺろっ」等表情的一组副本
|
||||
模型已经有同名表情时不补。返回补上的名字。
|
||||
"""
|
||||
morphs = model["morphs"]
|
||||
names = {mo["name"] for mo in morphs}
|
||||
added = []
|
||||
|
||||
def group(name, subs):
|
||||
morphs.append({"name": name, "name_en": name, "panel": 4, "kind": 0, "offsets": [(i, 1.0) for i in subs]})
|
||||
added.append(name)
|
||||
|
||||
if "hideHighlight" not in names:
|
||||
offs = [i for i, mo in enumerate(morphs) if _HL_OFF.search(mo["name"] or "")]
|
||||
if offs:
|
||||
group("hideHighlight", offs)
|
||||
log("表情:补充 hideHighlight(%s)" % " + ".join(morphs[i]["name"] for i in offs))
|
||||
else:
|
||||
mats = _highlight_materials(model)
|
||||
offsets = _collapse_morph(model, mats) if mats else []
|
||||
if offsets:
|
||||
morphs.append({"name": "hideHighlight", "name_en": "hideHighlight", "panel": 4, "kind": 1,
|
||||
"offsets": offsets})
|
||||
added.append("hideHighlight")
|
||||
log("表情:补充 hideHighlight(隐藏材质 %s)"
|
||||
% "、".join(model["materials"][mi]["name"] for mi in mats))
|
||||
elif any(mo["kind"] in (1, 0) for mo in morphs):
|
||||
log("表情:未找到眼睛高光材质或关闭高光的表情,未补充 hideHighlight")
|
||||
if "tongue" not in names:
|
||||
low = {}
|
||||
for i, mo in enumerate(morphs):
|
||||
low.setdefault((mo["name"] or "").strip().lower(), i)
|
||||
src = next((low[n.lower()] for n in TONGUE if n.lower() in low), None)
|
||||
if src is not None:
|
||||
group("tongue", [src])
|
||||
log("表情:补充 tongue(%s)" % morphs[src]["name"])
|
||||
return added
|
||||
|
||||
|
||||
def wink_presets(flat, vertices, is1):
|
||||
"""单眼眨眼 → {表情名: blinkLeft / blinkRight}(0.x:blink_l / blink_r);按 _wink_rank 的优先级。"""
|
||||
sides = _wink_sides(flat, vertices)
|
||||
to = {"L": "blinkLeft" if is1 else "blink_l", "R": "blinkRight" if is1 else "blink_r"}
|
||||
out = {}
|
||||
for side in ("L", "R"):
|
||||
n = next((sides[(side, r)] for r in (0, 1, 2) if (side, r) in sides), None)
|
||||
if n:
|
||||
out[n] = to[side]
|
||||
return out
|
||||
|
||||
|
||||
def _table_preset(name, is1, keys=()):
|
||||
"""MMD 日文名、中文名 → 预设(按 _key 比较,キリッ / キリッ、あ2 / あ2 都认)。
|
||||
keys:模型里所有表情名的 _key;给了的话也认变体后缀(啊2、まばたきA),前提是模型里没有不带后缀的那个。"""
|
||||
k = _key(name)
|
||||
if k not in _TABLE_KEY[is1] and k not in _CN_KEY:
|
||||
m = re.fullmatch(r"(.+?)[ab123]", k)
|
||||
if m and m.group(1) not in keys:
|
||||
k = m.group(1)
|
||||
p = _TABLE_KEY[is1].get(k)
|
||||
if p:
|
||||
return p
|
||||
p = _CN_KEY.get(k)
|
||||
if p and not is1:
|
||||
p = _TO_0X.get(p, p)
|
||||
p = p if p in PRESETS_0 else None
|
||||
return p
|
||||
|
||||
|
||||
def _preset_en(name, is1):
|
||||
s = (name or "").strip().lower().replace("-", "_").replace(" ", "_")
|
||||
s = re.sub(r"^blendshape\d*\.", "", s)
|
||||
p = None
|
||||
m = re.fullmatch(r"(?:.*[._])?(?:mth|mouth|v)[._]?(aa|ih|ou|ee|oh|a|i|u|e|o)", s) \
|
||||
or re.fullmatch(r"(aa|ih|ou|ee|oh|a|i|u|e|o)", s)
|
||||
if m:
|
||||
p = _EN_VOWEL[m.group(1)]
|
||||
elif re.search(r"mouth_?open$", s):
|
||||
p = "aa"
|
||||
elif re.fullmatch(r"(?:.*[._])?look_?(up|down|left|right)", s):
|
||||
p = "look" + re.fullmatch(r"(?:.*[._])?look_?(up|down|left|right)", s).group(1).capitalize()
|
||||
elif re.search(r"(blink|eye_?close[d]?|eye_def_c)[._]?(l|left)$", s):
|
||||
p = "blinkLeft"
|
||||
elif re.search(r"(blink|eye_?close[d]?|eye_def_c)[._]?(r|right)$", s):
|
||||
p = "blinkRight"
|
||||
elif re.search(r"(?:^|[._])(blink|eye_?close[d]?|eye_def_c)$", s):
|
||||
p = "blink"
|
||||
else:
|
||||
m = re.search(r"(?:^|[._])(?:all_|face_)?([a-z]+)$", s)
|
||||
if m and m.group(1) in _EN_EMO and (s == m.group(1) or re.search(r"(?:^|_)(?:fcl_)?all_|^face_", s)):
|
||||
p = _EN_EMO[m.group(1)]
|
||||
if p and not is1:
|
||||
p = _TO_0X.get(p, p)
|
||||
if p not in PRESETS_0: # surprised 在 0.x 里不是预设
|
||||
p = None
|
||||
return p
|
||||
|
||||
|
||||
def _flatten_morphs(morphs, model=None, extra_bone=None, weights=None):
|
||||
"""把顶点 / 骨骼 / UV / 材质表情(含グループ展开)整理成
|
||||
[(名字, {顶点: (dx,dy,dz)}, [(材质, 运算, 28 个值, 比率)], {顶点: (du,dv)})]。
|
||||
|
||||
材质表情(kind 8)在 MMD 里常用来显示/隐藏部件(脸红、换道具),
|
||||
VRM 对应 expression 的 materialColorBinds。材质号 -1 表示所有材质。
|
||||
骨骼表情(kind 2)给了 model 时烘焙成顶点偏移(morphbake.BoneBaker);
|
||||
UV 表情(kind 3)留给 build_expressions 换成贴图偏移。
|
||||
extra_bone:[(名字, 骨骼表情 offsets)],追加的合成表情(视线),同样烘焙。
|
||||
weights:已经算好的不带付与别名的顶点权重(mesh.vertex_weights(..., {})),给了就不再算。
|
||||
"""
|
||||
baker = morphbake.BoneBaker(model, weights) if model is not None else None
|
||||
cache = {}
|
||||
|
||||
def resolve(i, seen):
|
||||
if i in seen:
|
||||
return {}, [], {}
|
||||
if i in cache:
|
||||
return cache[i]
|
||||
seen = seen | {i}
|
||||
mo = morphs[i]
|
||||
k = mo["kind"]
|
||||
if k == 1:
|
||||
d = {}
|
||||
for vi, off in mo["offsets"]:
|
||||
if abs(off[0]) + abs(off[1]) + abs(off[2]) > 1e-9:
|
||||
d[vi] = (off[0], off[1], off[2])
|
||||
res = d, [], {}
|
||||
elif k == 2:
|
||||
res = (baker.deltas(mo["offsets"]) if baker else {}), [], {}
|
||||
elif k == 3:
|
||||
res = {}, [], {vi: (off[0], off[1]) for vi, off in mo["offsets"]
|
||||
if abs(off[0]) + abs(off[1]) > 1e-9}
|
||||
elif k == 8:
|
||||
res = {}, [(mi, op, vals, 1.0) for mi, op, vals in mo["offsets"]], {}
|
||||
elif k == 0:
|
||||
out, mats, uvs = {}, [], {}
|
||||
for sub, rate in mo["offsets"]:
|
||||
if not (0 <= sub < len(morphs)) or abs(rate) < 1e-9:
|
||||
continue
|
||||
sd, sm, su = resolve(sub, seen)
|
||||
for vi, d in sd.items():
|
||||
ox, oy, oz = out.get(vi, (0.0, 0.0, 0.0))
|
||||
out[vi] = (ox + d[0] * rate, oy + d[1] * rate,
|
||||
oz + d[2] * rate)
|
||||
for vi, d in su.items():
|
||||
ox, oy = uvs.get(vi, (0.0, 0.0))
|
||||
uvs[vi] = (ox + d[0] * rate, oy + d[1] * rate)
|
||||
mats.extend((mi, op, vals, r * rate) for mi, op, vals, r in sm)
|
||||
res = out, mats, uvs
|
||||
else:
|
||||
res = {}, [], {}
|
||||
cache[i] = res
|
||||
return res
|
||||
|
||||
out = []
|
||||
for i, mo in enumerate(morphs):
|
||||
if mo["kind"] not in (0, 1, 2, 3, 8):
|
||||
continue
|
||||
d, m, u = resolve(i, frozenset())
|
||||
if d or m or u:
|
||||
out.append((mo["name"], d, m, u))
|
||||
for name, offsets in extra_bone or ():
|
||||
d = baker.deltas(offsets) if baker else {}
|
||||
if d:
|
||||
out.append((name, d, [], {}))
|
||||
return out
|
||||
|
||||
|
||||
def uniq_name(name, used):
|
||||
"""name 已在 used 里时加 _2、_3 … 直到不重名。"""
|
||||
if name not in used:
|
||||
return name
|
||||
k = 2
|
||||
while "%s_%d" % (name, k) in used:
|
||||
k += 1
|
||||
return "%s_%d" % (name, k)
|
||||
|
||||
|
||||
_REPORT_ORDER = ["happy", "angry", "sad", "relaxed", "surprised", "blink", "blinkLeft", "blinkRight",
|
||||
"aa", "ih", "ou", "ee", "oh"]
|
||||
|
||||
|
||||
def report(expr_preset, blend_groups, is1, log, sources0=None):
|
||||
"""一行汇总:每个预设用了哪些表情(权重不是 1 的标 ×w),缺哪些。眨眼、「あ」缺了是警告。
|
||||
sources0:0.x 组合表情的组名 → 来源表情(「上+びっくり」;0.x 的 surprised 组名是 Surprised)。"""
|
||||
got, miss = [], []
|
||||
for p in _REPORT_ORDER:
|
||||
if is1:
|
||||
obj = expr_preset.get(p)
|
||||
src = obj and ((obj.get("extras") or {}).get("source") or p)
|
||||
ws = [b["weight"] for b in (obj or {}).get("morphTargetBinds", [])]
|
||||
else:
|
||||
p0 = _TO_0X.get(p, p) if p != "surprised" else None
|
||||
gr = next((g for g in blend_groups if g["presetName"] == p0 or
|
||||
(p0 is None and g["name"] == "Surprised")), None)
|
||||
src = gr and ((sources0 or {}).get(gr["name"]) or gr["name"])
|
||||
ws = [b["weight"] / 100.0 for b in (gr or {}).get("binds", [])]
|
||||
if not src:
|
||||
miss.append(p)
|
||||
continue
|
||||
names = src.split("+") if len(ws) > 1 and len(src.split("+")) == len(ws) else [src]
|
||||
if len(names) == len(ws):
|
||||
src = " + ".join(n if abs(w - 1) < 1e-6 else "%s×%g" % (n, round(w, 3)) for n, w in zip(names, ws))
|
||||
got.append("%s ← %s" % (p, src))
|
||||
log("表情预设:" + (";".join(got) or "无") + ("" if not miss else " · 未找到:" + "、".join(miss)),
|
||||
"warn" if {"blink", "aa"} & set(miss) else None)
|
||||
|
||||
|
||||
def build_expressions(flat, prims, mats, mat_gidx, gb, xf, vmat, is1, sparse_morphs, log, combo=True, hidden=()):
|
||||
"""表情 → 各 primitive 的 morph target + VRM 表情。
|
||||
|
||||
flat:_flatten_morphs 的结果;prims:mesh.build_primitives 的结果(往 pr["tmap"] 里写 morph target);
|
||||
UV 表情能表示成整个材质的缩放 + 偏移时写 textureTransformBinds(0.x:_MainTex_ST);
|
||||
mats:materials.MaterialBuilder;vmat:T-pose 后每个顶点的混合旋转(表情偏移要跟着转)。
|
||||
combo:情绪预设组合眉 / 眼 / 嘴(COMBO);原来单个对应的表情回到自定义表情。
|
||||
hidden:只做 morph target、不做表情的名字(视线表情的深度场,见 morphbake.split_gaze)。
|
||||
返回 dict:target_names、preset / custom(1.0)、blend_groups(0.x)。
|
||||
绑定里的 index 先是全局的 morph target 序号、node / mesh 先写 0,分好网格后由
|
||||
mesh.remap_binds 改成各网格里的序号和网格节点。
|
||||
"""
|
||||
materials = mats.model["materials"]
|
||||
target_names = []
|
||||
target_set = set()
|
||||
expr_preset = {}
|
||||
expr_custom = {}
|
||||
blend_groups = []
|
||||
sources0 = {}
|
||||
n_mat_expr = 0
|
||||
winks = wink_presets(flat, mats.model["vertices"], is1)
|
||||
# 日文名 / 中文名占用的预设,英文名不抢
|
||||
keys = {_key(n) for n, *_ in flat}
|
||||
jp_presets = {_table_preset(n, is1, keys) for n, *_ in flat} - {None} | set(winks.values())
|
||||
used_0x = set()
|
||||
mat_verts = None
|
||||
n_uv_expr = n_uv_bad = 0
|
||||
slot_of = {} # PMX 表情名 → morph target 序号(组合预设用)
|
||||
delta_of = {} # PMX 表情名 → 顶点偏移(组合时查重叠)
|
||||
for mname, deltas, _, _ in flat:
|
||||
if deltas:
|
||||
delta_of.setdefault(mname, deltas)
|
||||
panel = {mo["name"]: mo.get("panel") for mo in mats.model["morphs"]}
|
||||
lookup = Lookup(delta_of)
|
||||
recipes = combo_recipes(delta_of, panel, lookup) if combo else {}
|
||||
|
||||
def add_target(name, deltas):
|
||||
"""一个 morph target → 序号。只写进它动得到的 primitive(pr["tmap"][序号] = accessor),
|
||||
其余的在分网格(mesh.group_meshes)后按需补零。"""
|
||||
slot = len(target_names)
|
||||
for pr in prims:
|
||||
loc = pr["local"]
|
||||
items = []
|
||||
for vi, d in deltas.items():
|
||||
j = loc.get(vi)
|
||||
if j is None:
|
||||
continue
|
||||
if vmat is not None and vmat[vi] is not None:
|
||||
d = _m3vec(vmat[vi], d)
|
||||
# 偏移量也要乘缩放(xf 是纯线性变换,正好适用于偏移)。
|
||||
# 以前用 xf_dir 只翻了轴没缩放,偏移大了 1/scale≈12 倍,
|
||||
# 表情一开脸就拉成长刺。
|
||||
items.append((j, xf(d)))
|
||||
if not items:
|
||||
continue
|
||||
if sparse_morphs:
|
||||
# 稀疏存储:一个表情通常只动几百个顶点,密集存储每个表情
|
||||
# 每个 primitive 都要「顶点数 × 12 字节」
|
||||
items.sort()
|
||||
acc = gb.add_sparse_accessor(
|
||||
pr["vcount"], [j for j, _ in items],
|
||||
[c for _, d in items for c in d], "VEC3")
|
||||
else:
|
||||
arr = [0.0] * (pr["vcount"] * 3)
|
||||
for j, d in items:
|
||||
arr[j * 3:j * 3 + 3] = d
|
||||
acc = gb.add_accessor(arr, vrmio.FLOAT, "VEC3", 34962)
|
||||
pr["tmap"][slot] = acc
|
||||
# Unity 的 BlendShape 名在一个网格内必须唯一,重名时 UniVRM 导入直接抛
|
||||
# 「Blend shape name already exists」中断(开拓者 PMX 里有两个「手前」)
|
||||
target_names.append(uniq_name(name, target_set))
|
||||
target_set.add(target_names[-1])
|
||||
return slot
|
||||
|
||||
for mname, deltas, ops, uvs in flat:
|
||||
slot = None
|
||||
if deltas or mname in hidden:
|
||||
slot = add_target(mname, deltas)
|
||||
slot_of.setdefault(mname, slot)
|
||||
if mname in hidden:
|
||||
continue
|
||||
|
||||
# 材质表情 → 目标颜色(权重 1 时的漫反射 RGBA)
|
||||
colors = []
|
||||
for mi_, mat in enumerate(materials):
|
||||
if mi_ not in mat_gidx:
|
||||
continue
|
||||
r = _morph_material(mat, ops, mi_)
|
||||
if r is None:
|
||||
continue
|
||||
base = _mmd_color(mat["diffuse"], mat["ambient"])
|
||||
c = _mmd_color(*r)
|
||||
if max(abs(c[k] - base[k]) for k in range(4)) < 1e-6:
|
||||
continue
|
||||
lit_c, shade_c, _, _ = mats.lit_shade(mat, c)
|
||||
colors.append((mi_, lit_c, shade_c, max(abs(c[k] - base[k])
|
||||
for k in range(3)) > 1e-6))
|
||||
# UV 表情 → 贴图缩放 + 偏移(只用于出现在网格里的材质)
|
||||
tex = []
|
||||
if uvs:
|
||||
if mat_verts is None:
|
||||
mat_verts = morphbake.material_vertices(mats.model)
|
||||
binds, bad = morphbake.uv_binds(mats.model, uvs, mat_verts)
|
||||
tex = [(mi_, sc, off) for mi_, sc, off in binds if mi_ in mat_gidx]
|
||||
n_uv_bad += bad
|
||||
if tex:
|
||||
n_uv_expr += 1
|
||||
if slot is None and not colors and not tex:
|
||||
continue
|
||||
if colors:
|
||||
n_mat_expr += 1
|
||||
|
||||
preset = winks.get(mname) or _table_preset(mname, is1, keys)
|
||||
if not preset and not _WINK.search(mname):
|
||||
preset = _preset_en(mname, is1)
|
||||
if preset in jp_presets:
|
||||
preset = None
|
||||
if is1:
|
||||
obj = {"morphTargetBinds": ([{"node": 0, "index": slot,
|
||||
"weight": 1.0}]
|
||||
if slot is not None else []),
|
||||
"materialColorBinds": [
|
||||
b for mi_, c, sc, rgb in colors for b in (
|
||||
[{"material": mat_gidx[mi_], "type": "color",
|
||||
"targetValue": _lin_rgb(c)}] +
|
||||
# targetValue 规范要求正好 4 个分量:UniVRM 直接读 [3],
|
||||
# 只写 RGB 会在导入时 IndexOutOfRange 中断
|
||||
([{"material": mat_gidx[mi_], "type": "shadeColor",
|
||||
"targetValue": _lin_rgb(sc) + [1.0]}]
|
||||
if rgb else []))],
|
||||
"textureTransformBinds": [
|
||||
{"material": mat_gidx[mi_], "scale": [sc[0], sc[1]], "offset": [off[0], off[1]]}
|
||||
for mi_, sc, off in tex],
|
||||
"isBinary": False}
|
||||
# 规范要求这些数组非空(minItems 1):没有就不写
|
||||
for k_ in ("morphTargetBinds", "materialColorBinds", "textureTransformBinds"):
|
||||
if not obj[k_]:
|
||||
del obj[k_]
|
||||
if preset and preset not in expr_preset:
|
||||
# 记下来源的 PMX 表情名:界面里重新指定预设表情(vrm_edit)时要用
|
||||
obj["extras"] = {"source": mname}
|
||||
expr_preset[preset] = obj
|
||||
else:
|
||||
# 自定义表情名必须唯一(PMX 里同名表情会互相覆盖)
|
||||
expr_custom[uniq_name(mname, set(expr_custom) | PRESETS_1)] = obj
|
||||
else:
|
||||
# 同一个预设只给第一个(「あ」「あ2」都是 a 时,第二个当自定义)
|
||||
if preset in used_0x:
|
||||
preset = None
|
||||
used_0x.add(preset)
|
||||
blend_groups.append({
|
||||
"name": mname,
|
||||
"presetName": preset or "unknown",
|
||||
"binds": ([{"mesh": 0, "index": slot, "weight": 100}]
|
||||
if slot is not None else []),
|
||||
"materialValues": [
|
||||
v for mi_, c, sc, rgb in colors for v in (
|
||||
[{"materialName": mats.materials[mat_gidx[mi_]]["name"],
|
||||
"propertyName": "_Color", "targetValue": c}] +
|
||||
([{"materialName":
|
||||
mats.materials[mat_gidx[mi_]]["name"],
|
||||
"propertyName": "_ShadeColor",
|
||||
"targetValue": sc + [1.0]}]
|
||||
if rgb else []))] + [
|
||||
# Unity 的 UV 原点在左下:v' = sv·v + ov 换成 ST 是 (sv, 1 - sv - ov)
|
||||
{"materialName": mats.materials[mat_gidx[mi_]]["name"],
|
||||
"propertyName": "_MainTex_ST",
|
||||
"targetValue": [s_[0], s_[1], o_[0], 1.0 - s_[1] - o_[1]]}
|
||||
for mi_, s_, o_ in tex],
|
||||
"isBinary": False})
|
||||
if target_names:
|
||||
log("表情:导出 %d 个 morph target(%s存储)"
|
||||
% (len(target_names), "稀疏" if sparse_morphs else "密集"))
|
||||
if n_mat_expr:
|
||||
log("表情:%d 个包含材质变化(转为材质颜色绑定)" % n_mat_expr)
|
||||
if n_uv_expr:
|
||||
log("表情:%d 个 UV 表情转为贴图偏移" % n_uv_expr)
|
||||
if n_uv_bad:
|
||||
log("表情:%d 处 UV 表情不是整个材质统一平移 / 缩放,VRM 无法表示,已跳过" % n_uv_bad, "warn")
|
||||
|
||||
for p, parts in recipes.items():
|
||||
label = "+".join(n for n, _, _ in parts)
|
||||
binds = [(slot_of[n], w) for n, w, _ in parts]
|
||||
if is1:
|
||||
old = expr_preset.pop(p, None)
|
||||
if old is not None: # 原来单个对应的表情回到自定义表情,界面里还能选
|
||||
src = (old.pop("extras", None) or {}).get("source") or p
|
||||
expr_custom[uniq_name(src, set(expr_custom) | PRESETS_1)] = old
|
||||
obj = {"morphTargetBinds": [{"node": 0, "index": s, "weight": w} for s, w in binds],
|
||||
"isBinary": False, "extras": {"source": label}}
|
||||
# 笑眼(已经闭着)时再眨眼会闭两遍(眼皮穿到脸颊里)。blend:情绪表情越强,眨眼越弱
|
||||
if p in BLINK_BLEND and any(pn == 2 for _, _, pn in parts):
|
||||
obj["overrideBlink"] = "blend"
|
||||
expr_preset[p] = obj
|
||||
else:
|
||||
p0 = _COMBO_0X[p]
|
||||
if p0:
|
||||
for gr in blend_groups:
|
||||
if gr["presetName"] == p0:
|
||||
gr["presetName"] = "unknown"
|
||||
name = uniq_name(label if p0 else p.capitalize(), {g["name"] for g in blend_groups})
|
||||
sources0[name] = label
|
||||
blend_groups.append({"name": name,
|
||||
"presetName": p0 or "unknown",
|
||||
"binds": [{"mesh": 0, "index": s, "weight": round(w * 100, 2)} for s, w in binds],
|
||||
"materialValues": [], "isBinary": False})
|
||||
# ---- 名字对应不上的预设:ARKit 的眨眼 / 口型(FALLBACK),眨眼再退一步用左右单眼合起来
|
||||
def add_multi(p, binds, label):
|
||||
if is1:
|
||||
expr_preset[p] = {"morphTargetBinds": [{"node": 0, "index": slot_of[n], "weight": w} for n, w in binds],
|
||||
"isBinary": False, "extras": {"source": label}}
|
||||
else:
|
||||
blend_groups.append({"name": uniq_name(label, {g["name"] for g in blend_groups}),
|
||||
"presetName": _TO_0X.get(p, p),
|
||||
"binds": [{"mesh": 0, "index": slot_of[n], "weight": round(w * 100, 2)}
|
||||
for n, w in binds],
|
||||
"materialValues": [], "isBinary": False})
|
||||
|
||||
def have(p):
|
||||
return p in expr_preset if is1 else any(g["presetName"] == _TO_0X.get(p, p) for g in blend_groups)
|
||||
|
||||
for p, items in FALLBACK.items():
|
||||
first = lookup.all(items[0][0])
|
||||
if have(p) or not first:
|
||||
continue
|
||||
binds = [(n, items[0][1]) for n in first]
|
||||
for names, w in items[1:]:
|
||||
binds += [(n, w) for n in lookup.all(names) or ()]
|
||||
add_multi(p, binds, "+".join(n for n, _ in binds))
|
||||
by_side = {v: k for k, v in winks.items()}
|
||||
lr = [by_side.get("blinkLeft" if is1 else "blink_l"), by_side.get("blinkRight" if is1 else "blink_r")]
|
||||
if not have("blink") and all(n in slot_of for n in lr if n) and all(lr):
|
||||
add_multi("blink", [(lr[0], 1.0), (lr[1], 1.0)], "+".join(lr))
|
||||
report(expr_preset, blend_groups, is1, log, sources0)
|
||||
return {"target_names": target_names, "preset": expr_preset, "custom": expr_custom,
|
||||
"blend_groups": blend_groups}
|
||||
@@ -0,0 +1,685 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""骨骼:MMD 骨骼名 → VRM humanoid 骨位、付与骨合并、层级修正、A-pose → T-pose。"""
|
||||
import math
|
||||
import re
|
||||
|
||||
from .mathutil import _I3, _align, _axis_angle, _m3mul, _m3T, _m3vec, _to_axis_angle
|
||||
|
||||
|
||||
# --------------------------------------------------------- 骨骼名映射表 ----
|
||||
MMD_TO_VRM = {
|
||||
"下半身": "hips",
|
||||
"上半身": "spine",
|
||||
"上半身2": "chest",
|
||||
"上半身3": "upperChest",
|
||||
"首": "neck",
|
||||
"頭": "head",
|
||||
# 「両目」是双眼共用的控制骨,不对应任何一只眼,不能映射成 leftEye
|
||||
# (以前这么写,导致左右眼都绑到両目上,而真正的 左目 被挤掉)。
|
||||
"左目": "leftEye", "右目": "rightEye",
|
||||
"左肩": "leftShoulder", "右肩": "rightShoulder",
|
||||
"左腕": "leftUpperArm", "右腕": "rightUpperArm",
|
||||
"左ひじ": "leftLowerArm", "右ひじ": "rightLowerArm",
|
||||
"左肘": "leftLowerArm", "右肘": "rightLowerArm",
|
||||
"左手首": "leftHand", "右手首": "rightHand",
|
||||
"左足": "leftUpperLeg", "右足": "rightUpperLeg",
|
||||
"左ひざ": "leftLowerLeg", "右ひざ": "rightLowerLeg",
|
||||
"左足首": "leftFoot", "右足首": "rightFoot",
|
||||
"左つま先": "leftToes", "右つま先": "rightToes",
|
||||
}
|
||||
# 手指不放进 MMD_TO_VRM:骨位名取决于规范版本和模型有哪几节,见 _finger_slots。
|
||||
# VRM 1.0:拇指 Metacarpal / Proximal / Distal,其余 Proximal / Intermediate / Distal
|
||||
# VRM 0.x:拇指也是 Proximal / Intermediate / Distal(0.x 没有 Metacarpal)
|
||||
# 两个版本都没有「食指~小指的 Metacarpal」,所以 人指0 之类不映射。
|
||||
_FINGERS = {"親指": "Thumb", "人指": "Index", "中指": "Middle",
|
||||
"薬指": "Ring", "小指": "Little"}
|
||||
_DIGITS = {"0": 0, "0": 0, "1": 1, "1": 1, "2": 2, "2": 2, "3": 3, "3": 3}
|
||||
|
||||
|
||||
def _finger_key(name):
|
||||
"""「左人指2」→ ("left", "Index", 2);不是手指骨返回 None。"""
|
||||
if not name or len(name) != 4 or name[0] not in "左右":
|
||||
return None
|
||||
f = _FINGERS.get(name[1:3])
|
||||
d = _DIGITS.get(name[3])
|
||||
if f is None or d is None:
|
||||
return None
|
||||
return ("left" if name[0] == "左" else "right"), f, d
|
||||
|
||||
|
||||
def _finger_slots(finger, digits, is1):
|
||||
"""digits: 该手指在模型里出现的节号集合 → {节号: 骨位后缀}。"""
|
||||
if finger != "Thumb":
|
||||
return {d: s for d, s in ((1, "Proximal"), (2, "Intermediate"),
|
||||
(3, "Distal")) if d in digits}
|
||||
# 拇指按解剖位置对应:节号 0 = 掌根那节(1.0 Metacarpal / 0.x Proximal),1 = 1.0 Proximal /
|
||||
# 0.x Intermediate,2 = Distal。两个版本同一根骨对应同一节,套同一个手部动作时拇指才一致
|
||||
# (以前 0.x 把没有 親指0 的两节拇指当成第一、二节,1.0 当成第二、三节)
|
||||
names = ("Metacarpal", "Proximal", "Distal") if is1 else ("Proximal", "Intermediate", "Distal")
|
||||
return {d: names[d] for d in (0, 1, 2) if d in digits}
|
||||
|
||||
# 英文名兜底
|
||||
ALT_TO_VRM = {
|
||||
"hips": "hips", "spine": "spine", "chest": "chest",
|
||||
"upperchest": "upperChest", "neck": "neck", "head": "head",
|
||||
"leye": "leftEye", "reye": "rightEye",
|
||||
"lowerbody": "hips", "upperbody": "spine", "upperbody2": "chest",
|
||||
"lshoulder": "leftShoulder", "rshoulder": "rightShoulder",
|
||||
"larm": "leftUpperArm", "rarm": "rightUpperArm",
|
||||
"lelbow": "leftLowerArm", "relbow": "rightLowerArm",
|
||||
"lwrist": "leftHand", "rwrist": "rightHand",
|
||||
"lleg": "leftUpperLeg", "rleg": "rightUpperLeg",
|
||||
"lknee": "leftLowerLeg", "rknee": "rightLowerLeg",
|
||||
"lankle": "leftFoot", "rankle": "rightFoot",
|
||||
"ltoe": "leftToes", "rtoe": "rightToes",
|
||||
}
|
||||
|
||||
# 英文骨名(FBX 转来的 PMX 保留原名):去掉前缀和左右标记后**整段**匹配,
|
||||
# 不会误伤 J_L_HairTail_00、skirt_L_01 这类非人形骨。
|
||||
# HumanIK / Mixamo / Unity:Character1_LeftUpLeg、mixamorig:LeftForeArm、Chr_LeftHandIndex1
|
||||
# VRoid:J_Bip_L_UpperArm、J_Bip_C_Chest Blender:thigh.L、upper_arm.R
|
||||
# 3ds Max Biped:Bip001 L Thigh、Bip001 Spine1
|
||||
_EN_PREFIX = re.compile(r"^(?:character\d*|chr|bip0*1|jbipc|jbip|j|def|org|mch|armature|skeleton|root|rig|"
|
||||
r"cc_base|valvebiped_bip01|bip01)(?=[a-z])")
|
||||
_EN_SIDE = re.compile(r"(?:^|[^a-z])(l|r)(?:[^a-z]|$)|left|right")
|
||||
_EN_BONES = {
|
||||
"hips": "hips", "hip": "hips", "pelvis": "hips",
|
||||
"spine": "spine", "spine0": "spine", "spine1": "chest", "spine01": "chest", "spine2": "upperChest",
|
||||
"spine02": "upperChest", "chest": "chest", "upperchest": "upperChest",
|
||||
"neck": "neck", "neck1": "neck", "head": "head",
|
||||
}
|
||||
_EN_LIMBS = {
|
||||
"eye": "Eye", "shoulder": "Shoulder", "clavicle": "Shoulder",
|
||||
"arm": "UpperArm", "upperarm": "UpperArm",
|
||||
"forearm": "LowerArm", "lowerarm": "LowerArm", "elbow": "LowerArm",
|
||||
"hand": "Hand", "wrist": "Hand",
|
||||
"upleg": "UpperLeg", "upperleg": "UpperLeg", "thigh": "UpperLeg", "hip": "UpperLeg",
|
||||
"leg": "LowerLeg", "lowerleg": "LowerLeg", "calf": "LowerLeg", "shin": "LowerLeg", "knee": "LowerLeg",
|
||||
"foot": "Foot", "ankle": "Foot",
|
||||
"toebase": "Toes", "toe": "Toes", "toes": "Toes", "toe0": "Toes",
|
||||
}
|
||||
_EN_FINGERS = {"thumb": "Thumb", "index": "Index", "middle": "Middle", "ring": "Ring",
|
||||
"pinky": "Little", "little": "Little"}
|
||||
|
||||
|
||||
def _en_bone(name, thumb_metacarpal=False):
|
||||
"""英文骨名 → ("slot", 骨位) / ("finger", (side, finger, 节号 0~3)) / None。
|
||||
|
||||
节号按 MMD 的口径:拇指 0~2(VRM 1.0 的 Metacarpal / Proximal / Distal),其余手指 1~3;
|
||||
HumanIK 的拇指是 Thumb1~3、指尖是 4,所以拇指减 1、第 4 节(指尖)丢掉。
|
||||
Unity / VRChat 的「Index Proximal.L」这类节名:其余手指 Proximal / Intermediate / Distal = 1~3;
|
||||
拇指在 Unity 和 VRM 0.x 里叫 Proximal / Intermediate / Distal(第一节在掌根)= 0~2,
|
||||
VRM 1.0 风格叫 Metacarpal / Proximal / Distal——同一个 Proximal 指的节不一样,
|
||||
所以由调用方看整副骨架里有没有 ThumbMetacarpal(thumb_metacarpal)。
|
||||
"""
|
||||
s = (name or "").split(":")[-1].split("|")[-1].lower()
|
||||
m = _EN_SIDE.search(s.replace(".", "_").replace(" ", "_"))
|
||||
side = None
|
||||
if m:
|
||||
side = "left" if (m.group(1) or m.group(0)).strip("_. ").startswith("l") else "right"
|
||||
base = re.sub(r"left|right", "", s)
|
||||
base = re.sub(r"(?:^|[_. ])[lr](?=[_. ]|$)", "_", base) # _L / .L / " L " / J_Bip_L_
|
||||
base = re.sub(r"[^a-z0-9]", "", base)
|
||||
base = _EN_PREFIX.sub("", base)
|
||||
if not base:
|
||||
return None
|
||||
if side is None:
|
||||
v = _EN_BONES.get(base)
|
||||
return ("slot", v) if v else None
|
||||
if base.startswith("hand") and base[4:] and not base[4:].isdigit():
|
||||
base = base[4:] # HumanIK: LeftHandIndex1
|
||||
m = re.fullmatch(r"(thumb|index|middle|ring|pinky|little)(\d)", base)
|
||||
if m:
|
||||
f, d = _EN_FINGERS[m.group(1)], int(m.group(2))
|
||||
if f == "Thumb":
|
||||
d -= 1
|
||||
return ("finger", (side, f, d)) if 0 <= d <= 3 and not (f != "Thumb" and d == 0) else None
|
||||
m = re.fullmatch(r"(thumb|index|middle|ring|pinky|little)(metacarpal|proximal|intermediate|distal)", base)
|
||||
if m:
|
||||
f, seg = _EN_FINGERS[m.group(1)], m.group(2)
|
||||
if f == "Thumb":
|
||||
segs = {"metacarpal": 0, "proximal": 1, "distal": 2} if thumb_metacarpal else \
|
||||
{"proximal": 0, "intermediate": 1, "distal": 2}
|
||||
else:
|
||||
segs = {"proximal": 1, "intermediate": 2, "distal": 3}
|
||||
return ("finger", (side, f, segs[seg])) if seg in segs else None
|
||||
v = _EN_LIMBS.get(base)
|
||||
return ("slot", side + v) if v else None
|
||||
|
||||
|
||||
VRM_PARENT = {
|
||||
"spine": "hips", "chest": "spine", "upperChest": "chest",
|
||||
"neck": "upperChest", "head": "neck",
|
||||
"leftEye": "head", "rightEye": "head", "jaw": "head",
|
||||
"leftShoulder": "upperChest", "leftUpperArm": "leftShoulder",
|
||||
"leftLowerArm": "leftUpperArm", "leftHand": "leftLowerArm",
|
||||
"rightShoulder": "upperChest", "rightUpperArm": "rightShoulder",
|
||||
"rightLowerArm": "rightUpperArm", "rightHand": "rightLowerArm",
|
||||
"leftUpperLeg": "hips", "leftLowerLeg": "leftUpperLeg",
|
||||
"leftFoot": "leftLowerLeg", "leftToes": "leftFoot",
|
||||
"rightUpperLeg": "hips", "rightLowerLeg": "rightUpperLeg",
|
||||
"rightFoot": "rightLowerLeg", "rightToes": "rightFoot",
|
||||
}
|
||||
for _s in ("left", "right"):
|
||||
VRM_PARENT[_s + "ThumbMetacarpal"] = _s + "Hand"
|
||||
VRM_PARENT[_s + "ThumbProximal"] = _s + "ThumbMetacarpal"
|
||||
VRM_PARENT[_s + "ThumbIntermediate"] = _s + "ThumbProximal"
|
||||
VRM_PARENT[_s + "ThumbDistal"] = _s + "ThumbIntermediate"
|
||||
for _f in ("Index", "Middle", "Ring", "Little"):
|
||||
VRM_PARENT[_s + _f + "Proximal"] = _s + "Hand"
|
||||
VRM_PARENT[_s + _f + "Intermediate"] = _s + _f + "Proximal"
|
||||
VRM_PARENT[_s + _f + "Distal"] = _s + _f + "Intermediate"
|
||||
|
||||
REQUIRED_1_0 = ["hips", "spine", "head",
|
||||
"leftUpperArm", "leftLowerArm", "leftHand",
|
||||
"rightUpperArm", "rightLowerArm", "rightHand",
|
||||
"leftUpperLeg", "leftLowerLeg", "leftFoot",
|
||||
"rightUpperLeg", "rightLowerLeg", "rightFoot"]
|
||||
REQUIRED_0X = REQUIRED_1_0 + ["chest", "neck"]
|
||||
|
||||
# 自动补齐时的相对偏移(左、上、前)
|
||||
_SYNTH = {
|
||||
"spine": (0.0, 0.12, 0.0), "chest": (0.0, 0.12, 0.0),
|
||||
"upperChest": (0.0, 0.10, 0.0), "neck": (0.0, 0.10, 0.0),
|
||||
"head": (0.0, 0.12, 0.0),
|
||||
"leftShoulder": (0.05, 0.10, 0.0), "rightShoulder": (-0.05, 0.10, 0.0),
|
||||
"leftUpperArm": (0.12, 0.0, 0.0), "rightUpperArm": (-0.12, 0.0, 0.0),
|
||||
"leftLowerArm": (0.25, 0.0, 0.0), "rightLowerArm": (-0.25, 0.0, 0.0),
|
||||
"leftHand": (0.24, 0.0, 0.0), "rightHand": (-0.24, 0.0, 0.0),
|
||||
"leftUpperLeg": (0.09, -0.08, 0.0), "rightUpperLeg": (-0.09, -0.08, 0.0),
|
||||
"leftLowerLeg": (0.0, -0.40, 0.0), "rightLowerLeg": (0.0, -0.40, 0.0),
|
||||
"leftFoot": (0.0, -0.40, 0.06), "rightFoot": (0.0, -0.40, 0.06),
|
||||
}
|
||||
_HIPS_Y = 0.90
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 工具 --
|
||||
def _norm(s):
|
||||
return (s or "").strip().replace(" ", "").replace("_", "").lower()
|
||||
|
||||
|
||||
def _clean_parents(bones):
|
||||
"""PMX 父骨索引表,越界/指向自己的记成 -1。"""
|
||||
n = len(bones)
|
||||
out = []
|
||||
for i, b in enumerate(bones):
|
||||
p = b["parent"]
|
||||
out.append(p if (0 <= p < n and p != i) else -1)
|
||||
return out
|
||||
|
||||
|
||||
def _is_ancestor(parents, a, b):
|
||||
"""a 是否是 b 的祖先(含 a == b)。遇到环也会停。"""
|
||||
seen = set()
|
||||
while 0 <= b < len(parents) and b not in seen:
|
||||
if b == a:
|
||||
return True
|
||||
seen.add(b)
|
||||
b = parents[b]
|
||||
return False
|
||||
|
||||
|
||||
def _reparent(parents, child, new_parent):
|
||||
"""把 child 挂到 new_parent 下;会成环就拒绝,返回是否成功。"""
|
||||
if new_parent == child or _is_ancestor(parents, child, new_parent):
|
||||
return False
|
||||
parents[child] = new_parent
|
||||
return True
|
||||
|
||||
|
||||
def _append_aliases(bones, parents, eps, loose=0.5):
|
||||
"""「付与回転 100%」跟随付与親的骨 → 付与親,返回 {骨: 付与親}。
|
||||
|
||||
典型是 足D / ひざD / 足首D:网格权重全在 D 骨上,D 骨靠 PMX 的付与
|
||||
跟随 足 / ひざ / 足首 转动;而 humanoid 映射指向的是 足 / ひざ / 足首。
|
||||
glTF/VRM 没有付与机制,原样导出时转大腿网格完全不动。
|
||||
和付与親在静止姿势下重合(差不超过 eps)、旋转也 1:1 跟随的,把权重和子骨并到付与親上是等价的。
|
||||
不重合的(足首D 比 足首 靠后 2~3 cm 之类)也合并,条件是:
|
||||
* 两者跟着同一根 humanoid 骨移动:各自的父骨往上找到的第一根 humanoid 骨相同(D 骨的父骨
|
||||
并入后算付与親那边的)。中间隔着 腰キャンセル 之类在 VRM 里不动的骨不要紧;挂在别处
|
||||
(全ての親 下的道具骨)的不并,否则它会跟着付与親整体平移
|
||||
* 偏差不超过付与親那一节骨长(父骨→付与親、付与親→它的尾端,取长的)的 loose 倍
|
||||
* D 骨本身不是 humanoid 骨位(左目 跟随 両目 就不能并)
|
||||
合并后网格绕付与親的位置转,和 MMD 只差一个平移(偏差 2.5 cm、转 30° 时约 1 cm);
|
||||
不合并的话它在 VRM 里完全不动,挂在付与親子骨上的部分(鞋尖)却跟着转,鞋子从中间裂开。
|
||||
付与率不是 1 的(ひざ補助 的 0.5 等)见 skeleton.split_partial;负的(腰キャンセル 的 -1)不动。
|
||||
"""
|
||||
n = len(bones)
|
||||
alias, near = {}, {}
|
||||
for i, b in enumerate(bones):
|
||||
ir = b.get("inherit_rot")
|
||||
if not ir:
|
||||
continue
|
||||
src, rate = ir
|
||||
if not (0 <= src < n) or src == i or abs(rate - 1.0) > 1e-4:
|
||||
continue
|
||||
im = b.get("inherit_mov")
|
||||
if im and im[0] != src:
|
||||
continue
|
||||
if _is_ancestor(parents, i, src): # 付与親在自己下面:并过去会成环
|
||||
continue
|
||||
d = math.dist(b["pos"], bones[src]["pos"])
|
||||
if d <= eps:
|
||||
alias[i] = src
|
||||
elif not MMD_TO_VRM.get(b["name"]):
|
||||
near[i] = (src, d)
|
||||
|
||||
def resolve(i):
|
||||
seen = set()
|
||||
while i in alias and i not in seen:
|
||||
seen.add(i)
|
||||
i = alias[i]
|
||||
return i
|
||||
hset = set(_map_humanoid(bones, True, {}).values()) if near else set()
|
||||
|
||||
def anchor(i): # 往上第一根 humanoid 骨(并入的骨按付与親算)
|
||||
seen = set()
|
||||
while i >= 0 and i not in seen:
|
||||
i = resolve(i)
|
||||
if i in hset:
|
||||
return i
|
||||
seen.add(i)
|
||||
i = parents[i]
|
||||
return -1
|
||||
grew = True
|
||||
while grew: # D 骨的父骨可能也是这样并进来的(ひざD → 足首D)
|
||||
grew = False
|
||||
for i, (src, d) in near.items():
|
||||
pi, ps = parents[i], parents[src]
|
||||
if i in alias or pi < 0 or ps < 0 or anchor(pi) != anchor(ps):
|
||||
continue
|
||||
if d <= loose * max(math.dist(bones[ps]["pos"], bones[src]["pos"]), _bone_len(bones, parents, src)):
|
||||
alias[i] = src
|
||||
grew = True
|
||||
return {i: resolve(i) for i in alias}
|
||||
|
||||
|
||||
def _bone_len(bones, parents, i):
|
||||
"""骨 i 到它尾端的长度:尾端指向的骨,或尾端偏移;都没有就取到最远子骨的距离。"""
|
||||
b = bones[i]
|
||||
t = b.get("tail")
|
||||
if b.get("tail_kind") == 1 and isinstance(t, int) and 0 <= t < len(bones) and t != i:
|
||||
return math.dist(b["pos"], bones[t]["pos"])
|
||||
if b.get("tail_kind") == 0 and t and not isinstance(t, int) and any(t):
|
||||
return math.hypot(*t)
|
||||
return max((math.dist(b["pos"], bones[c]["pos"]) for c, p in enumerate(parents) if p == i), default=0.0)
|
||||
|
||||
|
||||
def _pick_toes(bones, human, alias, weighted):
|
||||
"""humanoid 的脚趾:MMD 的 つま先 是足 IK 的末端点(鞋尖最前面),不是脚趾关节——动画转脚趾时
|
||||
绕着鞋尖最前面那一点转。有 足先EX(准标准骨,脚掌和脚趾之间的关节,鞋头的权重常在它上面)就用它;
|
||||
没有的话,つま先 没挂网格就留着(转了也没影响),挂了网格就不设脚趾(VRM 里可以不设,鞋子跟着脚整体转)。
|
||||
weighted:挂了网格的骨(PMX 骨索引)。只处理 MMD 名字的骨。"""
|
||||
names = {b["name"]: i for i, b in enumerate(bones) if i not in alias}
|
||||
for side, jp in (("left", "左"), ("right", "右")):
|
||||
slot = side + "Toes"
|
||||
cur = human.get(slot)
|
||||
if cur is not None and bones[cur]["name"] != jp + "つま先":
|
||||
continue
|
||||
ex = names.get(jp + "足先EX")
|
||||
if ex is not None:
|
||||
human[slot] = ex
|
||||
elif cur is not None and cur in weighted:
|
||||
del human[slot]
|
||||
|
||||
|
||||
def _map_humanoid(bones, is1, alias):
|
||||
"""PMX 骨 → VRM humanoid 骨位,返回 {骨位: PMX 骨索引}。"""
|
||||
human = {}
|
||||
fingers = {} # (side, finger) → {节号: 骨索引}
|
||||
alt = {} # PMX 英文名(name_en)对上的:骨位 → 骨索引,日文名都分完再补位
|
||||
en = {} # 英文骨名兜底:骨位 → 骨索引
|
||||
# HumanIK 的 LeftLeg 是小腿(大腿叫 LeftUpLeg);只有 Leg、没有 UpLeg / Thigh 时 Leg 才是大腿
|
||||
has_upleg = any(re.search(r"upleg|upperleg|thigh", (b["name"] or "").lower()) for b in bones)
|
||||
thumb_mc = any(re.search(r"thumb.?metacarpal", b["name"] or "", re.I) for b in bones)
|
||||
for i, b in enumerate(bones):
|
||||
if i in alias: # 已并入付与親的骨不参与映射
|
||||
continue
|
||||
fk = _finger_key(b["name"])
|
||||
if fk:
|
||||
fingers.setdefault(fk[:2], {}).setdefault(fk[2], i)
|
||||
continue
|
||||
v = MMD_TO_VRM.get(b["name"])
|
||||
if v:
|
||||
human.setdefault(v, i)
|
||||
else:
|
||||
# 英文名只补位:有的模型旁边另放一套控制骨(左肩調整 …),英文名和本体一样(L_Shoulder),
|
||||
# 排在前面的话会抢走 左肩 的骨位,肩膀跑到模型外面
|
||||
v = ALT_TO_VRM.get(_norm(b.get("name_en") or ""))
|
||||
if v:
|
||||
alt.setdefault(v, i)
|
||||
if not v:
|
||||
r = _en_bone(b["name"], thumb_mc)
|
||||
if r and r[0] == "finger":
|
||||
en.setdefault(("finger",) + r[1][:2], {}).setdefault(r[1][2], i)
|
||||
elif r:
|
||||
slot = r[1]
|
||||
if not has_upleg and slot.endswith("LowerLeg") and "leg" in _norm(b["name"]) \
|
||||
and not re.search(r"lower|calf|shin|knee", b["name"].lower()):
|
||||
slot = slot.replace("LowerLeg", "UpperLeg")
|
||||
en.setdefault(slot, i)
|
||||
# 两种叫法的冲突(UE / Maya 常见):
|
||||
# L_Clavicle + L_Shoulder:Clavicle 是肩、Shoulder 其实是上臂
|
||||
# Spine1~Spine4 而没有 Spine:第一节当 spine、最后一节当 upperChest、中间当 chest
|
||||
pairs = [] # (肩骨位, 上臂骨位, 锁骨, 「肩」骨)
|
||||
for side in ("left", "right"):
|
||||
sh = [i for i, b in enumerate(bones) if i not in alias
|
||||
and re.search(r"clavicle|shoulder", b["name"] or "", re.I)
|
||||
and (_en_bone(b["name"]) or ("", ""))[1] == side + "Shoulder"]
|
||||
if len(sh) == 2 and side + "UpperArm" not in en:
|
||||
par = bones[sh[1]].get("parent")
|
||||
a, b = (sh[0], sh[1]) if par == sh[0] else (sh[1], sh[0]) if bones[sh[0]].get("parent") == sh[1] else (None, None)
|
||||
if a is not None:
|
||||
en[side + "Shoulder"], en[side + "UpperArm"] = a, b
|
||||
pairs.append((side + "Shoulder", side + "UpperArm", a, b))
|
||||
if "spine" not in en and "spine" not in human:
|
||||
nums = sorted((int(m.group(1)), i) for i, b in enumerate(bones)
|
||||
for m in [re.fullmatch(r"(?:.*[_:. ])?spine_?0*(\d+)", (b["name"] or "").lower())] if m)
|
||||
if len(nums) >= 2:
|
||||
seq = [i for _, i in nums]
|
||||
en["spine"] = seq[0]
|
||||
if len(seq) >= 3:
|
||||
en["chest"] = seq[len(seq) // 2] if len(seq) >= 4 else seq[1]
|
||||
en["upperChest"] = seq[-1]
|
||||
else:
|
||||
en["chest"] = seq[1]
|
||||
en.pop("upperChest", None)
|
||||
# 英文名只在 MMD 名没对上时补位(同一个模型两套都有时以 MMD 名为准)
|
||||
for k, i in alt.items():
|
||||
human.setdefault(k, i)
|
||||
for k, i in en.items():
|
||||
if k[0] == "finger":
|
||||
if (k[1], k[2]) not in fingers:
|
||||
fingers[(k[1], k[2])] = i
|
||||
elif k not in human:
|
||||
human[k] = i
|
||||
for s_slot, u_slot, a, b in pairs: # 旧的英文名表把 L_Shoulder 当成了肩:以配对结果为准
|
||||
if human.get(s_slot) in (a, b) or human.get(u_slot) in (a, b, None):
|
||||
human[s_slot], human[u_slot] = a, b
|
||||
# 没有叫「下半身 / Hips」的骨:取腿和脊椎的最近公共祖先当 hips。XPS 的 root hips 被转成
|
||||
# センター(腿和上半身都直接挂在它下面),以前这时只能补一根占位骨
|
||||
if "hips" not in human and "spine" in human and ("leftUpperLeg" in human or "rightUpperLeg" in human):
|
||||
def chain(i):
|
||||
out, seen = [], set()
|
||||
while 0 <= i < len(bones) and i not in seen:
|
||||
out.append(i)
|
||||
seen.add(i)
|
||||
i = bones[i].get("parent", -1)
|
||||
return out
|
||||
leg = human.get("leftUpperLeg", human.get("rightUpperLeg"))
|
||||
spine_up = set(chain(bones[human["spine"]].get("parent", -1)))
|
||||
for a in chain(bones[leg].get("parent", -1)):
|
||||
if a in spine_up and a not in alias and a not in human.values():
|
||||
human["hips"] = a
|
||||
break
|
||||
# 上半身2 / 上半身3 的名字和层级反着的模型(鸣潮的娜波摩、秧秧:上半身 → 上半身3 → 上半身2 → 首):
|
||||
# 按实际的父子顺序分,下面那根是 chest、上面那根是 upperChest。按名字分的话 upperChest
|
||||
# 在 chest 上面,层级改不过来只能把它从 humanoid 里去掉,躯干少一节
|
||||
if "chest" in human and "upperChest" in human:
|
||||
parents = [b.get("parent", -1) for b in bones]
|
||||
if _is_ancestor(parents, human["upperChest"], human["chest"]):
|
||||
human["chest"], human["upperChest"] = human["upperChest"], human["chest"]
|
||||
for (side, finger), digits in fingers.items():
|
||||
if finger == "Thumb" and 0 not in digits and 1 in digits and _thumb_at_root(bones, human, fingers, side, digits[1]):
|
||||
digits = {d - 1: i for d, i in digits.items() if d >= 1}
|
||||
for d, slot in _finger_slots(finger, digits, is1).items():
|
||||
human.setdefault(side + finger + slot, digits[d])
|
||||
return human
|
||||
|
||||
|
||||
def _thumb_at_root(bones, human, fingers, side, b):
|
||||
"""只有 親指1、親指2 的拇指:親指1 是不是掌根那节(離手腕近)。
|
||||
|
||||
带 親指0 的模型里,按「手腕 → 中指根」的长度算,親指0 离手腕 0.1~0.6、親指1 在 0.7~1.0。
|
||||
老模型没有 親指0 时 親指1 一般还在 0.7 以上,是第二节;离手腕不到 0.65 的才当掌根那节。"""
|
||||
hd, mid = human.get(side + "Hand"), fingers.get((side, "Middle"), {}).get(1)
|
||||
if hd is None or mid is None:
|
||||
return False
|
||||
w = bones[hd]["pos"]
|
||||
ref = math.dist(w, bones[mid]["pos"])
|
||||
return ref > 1e-6 and math.dist(w, bones[b]["pos"]) < 0.65 * ref
|
||||
|
||||
|
||||
def _vrm_anchor(name, present):
|
||||
"""沿 VRM_PARENT 往上找第一个在 present 里的骨位(跳过模型没有的可选骨位)。"""
|
||||
p = VRM_PARENT.get(name)
|
||||
while p and p not in present:
|
||||
p = VRM_PARENT.get(p)
|
||||
return p
|
||||
|
||||
|
||||
def _vrm_depth(name):
|
||||
d = 0
|
||||
while name in VRM_PARENT:
|
||||
name = VRM_PARENT[name]
|
||||
d += 1
|
||||
return d
|
||||
|
||||
|
||||
def _fix_humanoid_hierarchy(human, parents, bones, required, log):
|
||||
"""保证每个 humanoid 骨都在它规范父骨位的子树里,必要时改挂父骨。
|
||||
|
||||
最常见的是 MMD 的 上半身 / 下半身 是「腰」下的兄弟骨,而 VRM 要求
|
||||
spine 是 hips 的后代——不改的话转 hips(全身朝向)只有下半身跟着转。
|
||||
静止姿势下节点只有平移,改挂父骨不改变任何顶点位置。
|
||||
"""
|
||||
for h in sorted(human, key=_vrm_depth):
|
||||
if h not in human:
|
||||
continue
|
||||
anc = _vrm_anchor(h, human)
|
||||
if anc is None:
|
||||
continue
|
||||
a, c = human[anc], human[h]
|
||||
if a == c:
|
||||
del human[h]
|
||||
log("骨骼:%s 与 %s 对应同一根骨骼,已忽略 %s" % (h, anc, h), "warn")
|
||||
continue
|
||||
if _is_ancestor(parents, a, c):
|
||||
continue
|
||||
old = parents[c]
|
||||
if _reparent(parents, c, a):
|
||||
log("骨骼层级:%s(%s)不在 %s(%s)之下,已移至其下(原父骨骼 %s)"
|
||||
% (h, bones[c]["name"], anc, bones[a]["name"],
|
||||
bones[old]["name"] if old >= 0 else "无"))
|
||||
elif h not in required:
|
||||
del human[h]
|
||||
log("骨骼层级:%s(%s)无法修正,已从 humanoid 中移除"
|
||||
% (h, bones[c]["name"]), "warn")
|
||||
else:
|
||||
log("骨骼层级:%s(%s)无法修正,部分软件可能无法加载"
|
||||
% (h, bones[c]["name"]), "warn")
|
||||
|
||||
|
||||
_DIGIT_SEGS = ("Metacarpal", "Proximal", "Intermediate", "Distal")
|
||||
_HAND_FINGERS = ("Thumb", "Index", "Middle", "Ring", "Little")
|
||||
|
||||
|
||||
def _seg_end(bones, kids, b):
|
||||
"""骨 b 这一节的末端位置(PMX 坐标):PMX 的 tail(偏移或骨)→ 第一根子骨 → None。"""
|
||||
bb, pos = bones[b], bones[b]["pos"]
|
||||
tail = bb.get("tail", -1)
|
||||
if bb.get("tail_kind") == 0 and isinstance(tail, (list, tuple)):
|
||||
if sum(x * x for x in tail) > 1e-10:
|
||||
return tuple(pos[k] + tail[k] for k in range(3))
|
||||
elif isinstance(tail, int) and 0 <= tail < len(bones) and tail != b:
|
||||
q = bones[tail]["pos"]
|
||||
if sum((q[k] - pos[k]) ** 2 for k in range(3)) > 1e-10:
|
||||
return q
|
||||
for c in kids.get(b, ()):
|
||||
q = bones[c]["pos"]
|
||||
if sum((q[k] - pos[k]) ** 2 for k in range(3)) > 1e-10:
|
||||
return q
|
||||
return None
|
||||
|
||||
|
||||
def _cross(a, b):
|
||||
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
|
||||
|
||||
|
||||
def _tpose_globals(bones, parents, order, human, log):
|
||||
"""算出把模型摆成 VRM T-pose 的逐骨全局变换。
|
||||
|
||||
VRM 规范(VRMC_vrm-1.0/tpose.md)要求静止姿势:上臂、前臂、手沿 ±X 水平伸直,掌心朝下;
|
||||
四指沿 ±X 伸直;拇指水平、指向 ±X 与正前方之间的 45°。动作数据(Unity 的 humanoid、
|
||||
VRMA、手部追踪)都是「从这个姿势开始转多少度」,静止姿势偏多少,套上任何动作后就一直
|
||||
偏多少。MMD 模型多是手臂下垂 30~40° 的 A-pose,手指微弯、拇指贴着手掌。
|
||||
|
||||
在 PMX 坐标里算(左 +X、前 -Z):
|
||||
* 上臂、前臂各转一次对齐到水平 ±X;
|
||||
* 手:先把「手腕 → 中指根」转到 ±X,再绕这个方向转,让掌心朝下(掌面横向取食指根 → 小指根);
|
||||
* 四指每节转到 ±X、拇指每节转到水平 45°(指甲的侧向朝向从骨骼位置看不出来,只转方向)。
|
||||
父骨先转、子骨跟着走,再算自己还差多少;带付与回転的骨(腕補助 等)按付与率跟转。
|
||||
返回 {骨: (M, t)},x' = M·x + t;没有需要转的返回 None。
|
||||
"""
|
||||
pos = [b["pos"] for b in bones]
|
||||
kids = {}
|
||||
for i, p in enumerate(parents):
|
||||
kids.setdefault(p, []).append(i)
|
||||
local = {}
|
||||
sides = {} # side → ±1(左右手伸出去的方向)
|
||||
for side in ("left", "right"):
|
||||
ua = human.get(side + "UpperArm")
|
||||
la = human.get(side + "LowerArm")
|
||||
hd = human.get(side + "Hand")
|
||||
if hd is not None:
|
||||
ref = pos[ua] if ua is not None else (0.0, 0.0, 0.0)
|
||||
sides[side] = 1.0 if pos[hd][0] - ref[0] >= 0 else -1.0
|
||||
if ua is None or la is None:
|
||||
continue
|
||||
d1 = [pos[la][k] - pos[ua][k] for k in range(3)]
|
||||
tgt = (1.0 if d1[0] >= 0 else -1.0, 0.0, 0.0)
|
||||
sides[side] = tgt[0]
|
||||
r1, a1 = _align(d1, tgt)
|
||||
if a1 > math.radians(1.0):
|
||||
local[ua] = r1
|
||||
else:
|
||||
r1, a1 = _I3, 0.0
|
||||
a2 = 0.0
|
||||
if hd is not None:
|
||||
d2 = _m3vec(r1, [pos[hd][k] - pos[la][k] for k in range(3)])
|
||||
r2w, a2 = _align(d2, tgt)
|
||||
if a2 > math.radians(1.0):
|
||||
# 局部旋转作用在父骨(上臂)旋转之前的空间里
|
||||
local[la] = _m3mul(_m3mul(_m3T(r1), r2w), r1)
|
||||
else:
|
||||
a2 = 0.0
|
||||
if a1 or a2:
|
||||
log("T-pose:%s 上臂 %.1f° · 前臂 %.1f°"
|
||||
% ("左" if side == "left" else "右",
|
||||
math.degrees(a1), math.degrees(a2)))
|
||||
|
||||
# 手和手指:要转到的方向,在下面按父骨在前的顺序边走边算(要用父骨转过之后的朝向)
|
||||
aim = {} # 骨 → (末端位置, 目标方向, 手的掌面 (食指根, 小指根) 或 None, side, 类别)
|
||||
for side, sx in sides.items():
|
||||
hd = human[side + "Hand"]
|
||||
chains = {}
|
||||
for f in _HAND_FINGERS:
|
||||
chains[f] = [human[side + f + s_] for s_ in _DIGIT_SEGS if side + f + s_ in human]
|
||||
mid, idx, lit = chains["Middle"][:1], chains["Index"][:1], chains["Little"][:1]
|
||||
if mid:
|
||||
aim[hd] = (pos[mid[0]], (sx, 0.0, 0.0),
|
||||
(idx[0], lit[0]) if idx and lit else None, side, "hand")
|
||||
thumb = (sx * math.sqrt(0.5), 0.0, -math.sqrt(0.5))
|
||||
for f, ch in chains.items():
|
||||
for k, b in enumerate(ch):
|
||||
end = pos[ch[k + 1]] if k + 1 < len(ch) else _seg_end(bones, kids, b)
|
||||
if end is not None and k + 1 == len(ch) and k > 0:
|
||||
# 末节的方向只能靠 tail / 子骨猜:FBX 转来的 PMX 末端骨 tail 是默认的朝上偏移,
|
||||
# 和上一节差得远(> 60°)的不可信,这一节就跟着上一节转
|
||||
prev = [pos[b][j] - pos[ch[k - 1]][j] for j in range(3)]
|
||||
if _align(prev, [end[j] - pos[b][j] for j in range(3)])[1] > math.radians(60.0):
|
||||
end = None
|
||||
if end is not None:
|
||||
aim[b] = (end, thumb if f == "Thumb" else (sx, 0.0, 0.0), None, side,
|
||||
"thumb" if f == "Thumb" else "finger")
|
||||
|
||||
# 付与回転:按付与率缩放付与親的局部旋转(递归处理付与链)
|
||||
memo = {}
|
||||
|
||||
def local_of(i, depth=0):
|
||||
if i in memo:
|
||||
return memo[i]
|
||||
m = local.get(i)
|
||||
ir = bones[i].get("inherit_rot")
|
||||
if ir and depth < 16 and 0 <= ir[0] < len(bones) and ir[0] != i:
|
||||
src = local_of(ir[0], depth + 1)
|
||||
if src is not None:
|
||||
ax, ang = _to_axis_angle(src)
|
||||
g = _axis_angle(ax, ang * ir[1])
|
||||
m = g if m is None else _m3mul(m, g)
|
||||
memo[i] = m
|
||||
return m
|
||||
|
||||
worst = {} # (side, 类别) → 最大转角(度)
|
||||
glob = {}
|
||||
for i in order:
|
||||
p = parents[i]
|
||||
pm, pt = glob.get(p, (_I3, (0.0, 0.0, 0.0)))
|
||||
lm = local_of(i)
|
||||
if i in aim:
|
||||
end, tgt, palm, side, kind = aim[i]
|
||||
base = pm if lm is None else _m3mul(pm, lm)
|
||||
fwd = [end[k] - pos[i][k] for k in range(3)]
|
||||
r, a = _align(_m3vec(base, fwd), tgt)
|
||||
roll = 0.0
|
||||
if palm is not None:
|
||||
# 掌面法线(掌心那一侧):左手 前进方向 × (小指根 − 食指根),右手反过来
|
||||
across = [pos[palm[1]][k] - pos[palm[0]][k] for k in range(3)]
|
||||
n = _m3vec(_m3mul(r, base), _cross(fwd, across))
|
||||
n = [x * tgt[0] for x in n]
|
||||
n = [n[k] - tgt[k] * sum(n[j] * tgt[j] for j in range(3)) for k in range(3)]
|
||||
if sum(x * x for x in n) > 1e-12:
|
||||
r2, roll = _align(n, (0.0, -1.0, 0.0))
|
||||
if roll > math.radians(1.0):
|
||||
r = _m3mul(r2, r)
|
||||
else:
|
||||
roll = 0.0
|
||||
if a > math.radians(1.0) or roll:
|
||||
lm = _m3mul(_m3T(pm), _m3mul(r, base))
|
||||
local[i] = memo[i] = lm
|
||||
key = (side, kind)
|
||||
worst[key] = max(worst.get(key, 0.0), math.degrees(a))
|
||||
if roll:
|
||||
worst[(side, "palm")] = math.degrees(roll)
|
||||
if lm is None:
|
||||
glob[i] = (pm, pt)
|
||||
continue
|
||||
# 绕骨骼自身位置旋转:x → R(x − p) + p,再叠父骨变换
|
||||
rp = _m3vec(lm, pos[i])
|
||||
lt = (pos[i][0] - rp[0], pos[i][1] - rp[1], pos[i][2] - rp[2])
|
||||
m = _m3mul(pm, lm)
|
||||
t = _m3vec(pm, lt)
|
||||
glob[i] = (m, (t[0] + pt[0], t[1] + pt[1], t[2] + pt[2]))
|
||||
for side in sides:
|
||||
w = [worst.get((side, k), 0.0) for k in ("hand", "palm", "finger", "thumb")]
|
||||
if any(w):
|
||||
log("T-pose:%s 手 %.1f° · 掌心 %.1f° · 四指最多 %.1f° · 拇指最多 %.1f°"
|
||||
% (("左" if side == "left" else "右",) + tuple(w)))
|
||||
if not local:
|
||||
return None
|
||||
return glob
|
||||
|
||||
|
||||
def _topo_bones(parents):
|
||||
"""把骨骼重排成「父在前」,返回 (新序号→原序号, 原序号→新序号)。
|
||||
|
||||
用「祖先链深度」排序:父节点的深度永远比子节点小 1,排序后父必在前。
|
||||
比递归/DFS 稳,遇到坏数据(成环)也不会死循环。
|
||||
"""
|
||||
n = len(parents)
|
||||
depth = [0] * n
|
||||
for i in range(n):
|
||||
seen = set()
|
||||
d = 0
|
||||
k = i
|
||||
while d <= n + 5:
|
||||
p = parents[k]
|
||||
if not (0 <= p < n) or p == k or p in seen:
|
||||
break
|
||||
seen.add(p)
|
||||
d += 1
|
||||
k = p
|
||||
depth[i] = d
|
||||
order = sorted(range(n), key=lambda i: (depth[i], i))
|
||||
remap = {old: new for new, old in enumerate(order)}
|
||||
return order, remap
|
||||
@@ -0,0 +1,633 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""材质:PMX 材质 → glTF 材质 + MToon(1.0 的 VRMC_materials_mtoon / 0.x 的 materialProperties)。
|
||||
|
||||
颜色按 MMD 的显示公式算,阴影色和明暗交界按 PMX 的 toon 渐变换算,VRM 1.0 的颜色因子写线性值;
|
||||
透明模式看漫反射 alpha、贴图的 alpha 分布(只算材质的 UV 用到的部分)和材质表情。
|
||||
"""
|
||||
import io
|
||||
import math
|
||||
import os
|
||||
|
||||
import vrmio
|
||||
|
||||
ALPHA_GRID = 1024 # 统计 UV 覆盖区域的透明度时,贴图 alpha 缩到的最长边(像素)
|
||||
|
||||
|
||||
def _alpha_grid(data):
|
||||
"""贴图字节 → 缩小的 alpha 通道(Pillow 灰度图;最近邻缩小,不造出假的中间值)。
|
||||
没有 alpha、没装 Pillow 或解不开时为 None。"""
|
||||
try:
|
||||
from PIL import Image
|
||||
im = Image.open(io.BytesIO(data))
|
||||
if im.mode in ("RGBA", "LA", "PA"):
|
||||
a = im.getchannel("A")
|
||||
elif im.mode == "P" and "transparency" in im.info:
|
||||
a = im.convert("RGBA").getchannel("A")
|
||||
else:
|
||||
return None
|
||||
k = ALPHA_GRID / max(a.size)
|
||||
if k < 1:
|
||||
a = a.resize((max(1, round(a.width * k)), max(1, round(a.height * k))), Image.NEAREST)
|
||||
return a
|
||||
except Exception: # noqa: BLE001 解不开就按整张图的统计
|
||||
return None
|
||||
|
||||
|
||||
def _lin(c):
|
||||
"""sRGB(gamma)分量 → 线性分量。
|
||||
|
||||
MMD 在 gamma 空间里算颜色(材质色、toon 贴图都是 sRGB 值,直接相乘);glTF 的
|
||||
baseColorFactor 和 VRM 1.0 MToon 的各个颜色因子规定是线性值,引擎会按线性来乘
|
||||
贴图。以前把 gamma 值原样写进去:阴影色 0.8 实际显示成 sRGB 0.9,只暗 10%,
|
||||
在游戏的环境光下基本看不见(原生 VRoid 皮肤的阴影色 0.x 写 (0.97, 0.81, 0.86),
|
||||
读进来是线性 (0.93, 0.63, 0.72))。gamma 空间的乘法 a·b 对应线性的 lin(a)·lin(b),
|
||||
所以换算后效果和 MMD 一致。VRM 0.x 的 materialProperties 本来就是 gamma 值,不用转。
|
||||
"""
|
||||
c = max(0.0, min(1.0, c))
|
||||
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
|
||||
|
||||
|
||||
def _lin_rgb(rgb):
|
||||
"""颜色列表的 RGB 分量转线性,第 4 个(alpha)原样保留。"""
|
||||
return [round(_lin(v), 5) if i < 3 else v for i, v in enumerate(rgb)]
|
||||
|
||||
|
||||
def _mmd_color(diffuse, ambient):
|
||||
"""MMD 实际显示的材质颜色(RGBA)。
|
||||
|
||||
MMD 默认着色器:颜色 = saturate(漫反射 × 光源色 + 环境色),光源色默认
|
||||
154/255 ≈ 0.6;alpha 取漫反射 alpha。常见的「漫反射 1、环境色 0.5」算出来
|
||||
就是白色,但有的材质靠环境色调色(比如脸红:漫反射白、环境色偏红),
|
||||
只用漫反射会把颜色丢掉。
|
||||
"""
|
||||
return [min(1.0, max(0.0, diffuse[k] * 0.6 + ambient[k]))
|
||||
for k in range(3)] + [diffuse[3]]
|
||||
|
||||
|
||||
# MMD 共享 toon(toon01~toon06.bmp)的渐变:上半白、v=0.5 处硬切到下半的颜色。
|
||||
# 取自 three.js MMDLoader 内嵌的 DEFAULT_TOON_TEXTURES;它的 toon07~10 是全白的
|
||||
# 占位图,不可信,这几张当作「不知道」走默认阴影
|
||||
_SHARED_TOON = {
|
||||
0: ((255, 255, 255), (205, 205, 205)),
|
||||
1: ((255, 255, 255), (245, 225, 225)),
|
||||
2: ((255, 255, 255), (154, 154, 154)),
|
||||
3: ((255, 255, 255), (248, 239, 235)),
|
||||
4: ((255, 255, 255), (254, 232, 223)),
|
||||
5: ((255, 237, 97), (195, 172, 3)),
|
||||
}
|
||||
|
||||
|
||||
def _toon_column(rows, w, h):
|
||||
"""toon 贴图 → 从上(v=0,正对光)到下(v=1,背光 / 自阴影)的平均颜色(0~1)。"""
|
||||
xs = sorted({0, w // 4, w // 2, (3 * w) // 4, w - 1})
|
||||
return [tuple(sum(rows[y][x][k] for x in xs) / (255.0 * len(xs)) for k in range(3))
|
||||
for y in range(h)]
|
||||
|
||||
|
||||
def _toon_shading(col):
|
||||
"""MMD toon 渐变 → MToon 1.0 的 (亮部色, 阴影色, shadingShift, shadingToony)。
|
||||
|
||||
MMD:颜色 ×= toon(v),v = 0.5 − 0.5·N·L;自阴影(投影)里取最下端 toon(1)。
|
||||
MToon 1.0:shading = linearstep(−1+toony, 1−toony, N·L + shift) × 投影,
|
||||
颜色 = lerp(阴影色, 亮部色, shading)。所以
|
||||
亮部色 = toon 最上端,阴影色 = 最下端(投影里正好也是它),
|
||||
明暗交界在亮度降到一半的 v_mid 处:N·L = 1 − 2·v_mid → shift = 2·v_mid − 1,
|
||||
过渡宽度 Δv(亮度 10%→90%)对应 N·L 的 2·Δv → toony = 1 − Δv。
|
||||
星铁 / 鸣潮的皮肤 toon 在 v≈0.75 以后才变暗,换算出来 shift≈+0.6:脸上基本全亮、
|
||||
只有投影是粉色——和原生 VRoid 皮肤(0.x ShadeShift −1 / Toony 1)的效果一致。
|
||||
渐变几乎没有明暗差(纯白 toon)时阴影色 = 亮部色:MMD 里这种材质本来就没有阴影。
|
||||
"""
|
||||
if not col:
|
||||
return None
|
||||
lum = [0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] for c in col]
|
||||
top, bot = lum[0], lum[-1]
|
||||
if top - bot < 0.02:
|
||||
return col[0], col[0], 0.0, 0.9
|
||||
n = len(col)
|
||||
|
||||
def first_below(level):
|
||||
for i, v in enumerate(lum):
|
||||
if v <= level:
|
||||
return i / max(1, n - 1)
|
||||
return 1.0
|
||||
|
||||
v_mid = first_below(top - 0.5 * (top - bot))
|
||||
dv = first_below(top - 0.9 * (top - bot)) - first_below(top - 0.1 * (top - bot))
|
||||
shift = max(-1.0, min(1.0, 2.0 * v_mid - 1.0))
|
||||
toony = max(0.0, min(1.0, 1.0 - dv))
|
||||
return col[0], col[-1], shift, toony
|
||||
|
||||
|
||||
def one_sided_layers(model, samples=300, inward_min=0.7, opposite_min=0.5):
|
||||
"""PMX 里设计成单面、背后紧贴着一层反向表面的材质 → {材质序号: (朝里的比例, 法线相反的比例)}。
|
||||
|
||||
两类:描边外壳(把脸 / 身体复制一份往外推、翻面、涂黑:单面时只在边缘露出一圈当轮廓线,叫
|
||||
「顔エッジ」「outline」之类)和内侧面(裙子、袖子里面另做一层翻过来的面显示里侧的贴图)。
|
||||
「所有材质双面」不能套到它们上:外壳会整片盖住脸和身体,内侧面会和外层重叠闪烁。
|
||||
|
||||
名字靠不住,按几何判断,每个单面材质抽样最多 samples 个三角面:
|
||||
朝里 面的朝向(PMX 绕序的叉积)指向它所属骨骼那一段(主要权重的骨,骨头 → 骨尾)
|
||||
反向 离它最近的别的材质的顶点(模型高度的 3% 以内),顶点法线和这个面相反——外壳和它下面的表面、
|
||||
内侧面和外层都是这样;眼睛、嘴里朝里的面旁边是方向一致的眼白、牙齿,不算
|
||||
两项都过半(朝里 ≥ inward_min,反向 ≥ opposite_min,有效样本至少 20 个)的才算。
|
||||
"""
|
||||
V, F, B = model["vertices"], model["faces"], model["bones"]
|
||||
mats = model["materials"]
|
||||
if not V or not B or not any(m["faces"] >= 3 and not (m["flag"] & 0x01) for m in mats):
|
||||
return {}
|
||||
ys = [v["pos"][1] for v in V]
|
||||
h = (max(ys) - min(ys)) or 1.0
|
||||
r, eps = 0.03 * h, 0.0003 * h
|
||||
tails = []
|
||||
for b in B:
|
||||
t = b.get("tail")
|
||||
if b.get("tail_kind") == 1 and isinstance(t, int) and 0 <= t < len(B):
|
||||
tails.append(B[t]["pos"])
|
||||
elif b.get("tail_kind") == 0 and t and not isinstance(t, int):
|
||||
tails.append(tuple(b["pos"][i] + t[i] for i in range(3)))
|
||||
else:
|
||||
tails.append(b["pos"])
|
||||
mat_of = [0] * len(V)
|
||||
k = 0
|
||||
for mi, m in enumerate(mats):
|
||||
for t in range(k, min(k + m["faces"], len(F))):
|
||||
mat_of[F[t]] = mi
|
||||
k += m["faces"]
|
||||
cell = r / 4 # 细网格,由近到远一圈圈找:外壳离下面的表面通常只有零点几毫米
|
||||
grid = {}
|
||||
for vi, v in enumerate(V):
|
||||
p = v["pos"]
|
||||
grid.setdefault((int(p[0] // cell), int(p[1] // cell), int(p[2] // cell)), []).append(vi)
|
||||
|
||||
def nearest_other(p, mi):
|
||||
cx, cy, cz = int(p[0] // cell), int(p[1] // cell), int(p[2] // cell)
|
||||
best, bd = -1, r
|
||||
for ring in range(5): # 第 ring 圈:切比雪夫距离正好是 ring 的格子
|
||||
if best >= 0 and bd <= (ring - 1) * cell:
|
||||
break
|
||||
rng = range(-ring, ring + 1)
|
||||
for dx in rng:
|
||||
for dy in rng:
|
||||
for dz in rng:
|
||||
if max(abs(dx), abs(dy), abs(dz)) != ring:
|
||||
continue
|
||||
for vi in grid.get((cx + dx, cy + dy, cz + dz), ()):
|
||||
if mat_of[vi] != mi:
|
||||
q = V[vi]["pos"]
|
||||
dd = math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2 + (p[2] - q[2]) ** 2)
|
||||
if eps < dd < bd:
|
||||
best, bd = vi, dd
|
||||
return best
|
||||
|
||||
def bone_of(v):
|
||||
ws = list(v["wweights"]) or [1.0]
|
||||
bi = max(zip(ws, v["wbones"]))[1] if v["wbones"] else -1
|
||||
return bi if 0 <= bi < len(B) else -1
|
||||
|
||||
out, k = {}, 0
|
||||
for mi, m in enumerate(mats):
|
||||
n = m["faces"] // 3
|
||||
start, k = k, k + m["faces"]
|
||||
if n < 1 or m["flag"] & 0x01:
|
||||
continue
|
||||
step = max(1, n // samples)
|
||||
tot, inward = 0, [] # 先只算朝里(便宜),不够的材质不用找邻居
|
||||
for t in range(start, start + n * 3, 3 * step):
|
||||
if t + 2 >= len(F):
|
||||
break
|
||||
a, b_, c = (V[F[t + j]]["pos"] for j in range(3))
|
||||
u = (b_[0] - a[0], b_[1] - a[1], b_[2] - a[2])
|
||||
w = (c[0] - a[0], c[1] - a[1], c[2] - a[2])
|
||||
fn = (u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0])
|
||||
ln = math.sqrt(fn[0] ** 2 + fn[1] ** 2 + fn[2] ** 2)
|
||||
bi = bone_of(V[F[t]])
|
||||
if ln < 1e-12 or bi < 0:
|
||||
continue
|
||||
p = ((a[0] + b_[0] + c[0]) / 3, (a[1] + b_[1] + c[1]) / 3, (a[2] + b_[2] + c[2]) / 3)
|
||||
s0, s1 = B[bi]["pos"], tails[bi] # 骨头 → 骨尾上离 p 最近的点
|
||||
ab = (s1[0] - s0[0], s1[1] - s0[1], s1[2] - s0[2])
|
||||
ll = ab[0] ** 2 + ab[1] ** 2 + ab[2] ** 2
|
||||
f = 0.0 if ll < 1e-12 else max(0.0, min(1.0, sum((p[i] - s0[i]) * ab[i] for i in range(3)) / ll))
|
||||
d = tuple(p[i] - s0[i] - ab[i] * f for i in range(3))
|
||||
if math.sqrt(d[0] ** 2 + d[1] ** 2 + d[2] ** 2) < eps:
|
||||
continue
|
||||
tot += 1
|
||||
if fn[0] * d[0] + fn[1] * d[1] + fn[2] * d[2] < 0:
|
||||
inward.append((p, fn, ln))
|
||||
if tot < 20 or len(inward) < inward_min * tot:
|
||||
continue
|
||||
opposite = 0
|
||||
for p, fn, ln in inward:
|
||||
q = nearest_other(p, mi)
|
||||
if q >= 0:
|
||||
nq = V[q]["normal"]
|
||||
lq = math.sqrt(nq[0] ** 2 + nq[1] ** 2 + nq[2] ** 2) or 1.0
|
||||
if (fn[0] * nq[0] + fn[1] * nq[1] + fn[2] * nq[2]) / (ln * lq) < -0.5:
|
||||
opposite += 1
|
||||
if opposite >= opposite_min * tot:
|
||||
break
|
||||
if opposite >= opposite_min * tot:
|
||||
out[mi] = (len(inward) / tot, opposite / tot)
|
||||
return out
|
||||
|
||||
|
||||
def _morph_material(mat, ops, mi):
|
||||
"""把材质表情作用到材质 mi 上,返回权重为 1 时的 (漫反射 RGBA, 环境色 RGB)。
|
||||
|
||||
PMX 材质表情:运算 0 = 乘算(基础 × 值),1 = 加算(基础 + 值);
|
||||
28 个值里 [0:4] 是漫反射 RGBA、[8:11] 是环境色。グループ里的比率按
|
||||
「基础 → 目标」线性插值(VRM 的 materialColorBinds 也是按权重插值)。
|
||||
没有作用到这个材质返回 None。
|
||||
"""
|
||||
dif = list(mat["diffuse"])
|
||||
amb = list(mat["ambient"])
|
||||
hit = False
|
||||
for m, op, vals, rate in ops:
|
||||
if m != mi and m != -1:
|
||||
continue
|
||||
hit = True
|
||||
for cur, off, n in ((dif, 0, 4), (amb, 8, 3)):
|
||||
for k in range(n):
|
||||
v = vals[off + k]
|
||||
tgt = cur[k] * v if op == 0 else cur[k] + v
|
||||
cur[k] = min(1.0, max(0.0, cur[k] + (tgt - cur[k]) * rate))
|
||||
return (dif, amb) if hit else None
|
||||
|
||||
|
||||
class MaterialBuilder:
|
||||
"""逐个 PMX 材质生成 glTF 材质,贴图写进 gb(vrmio.GLBBuilder)。
|
||||
|
||||
flat:_flatten_morphs 的结果——会把材质隐藏掉的材质表情决定该材质用 MASK。
|
||||
结果在 self.materials(glTF materials)和 self.props_0x(0.x 的 materialProperties)。
|
||||
"""
|
||||
|
||||
def __init__(self, model, base_dir, gb, is1, flat, outline=False, force_double_sided=False,
|
||||
tex_opt=None, known_alpha=None):
|
||||
self.model = model
|
||||
self.tex_opt = tex_opt # textures.Optimizer:嵌入前缩小 / 转 JPEG(None = 原样)
|
||||
# {贴图文件的 normcase 绝对路径: png_alpha_stats 结果}:调用方已经统计过的(FBX 转换时解过)
|
||||
self.known_alpha = known_alpha or {}
|
||||
self._pre = {} # prefetch 提前读好的贴图:PMX 贴图序号 → _load 的结果
|
||||
self.base_dir = base_dir
|
||||
self.finder = vrmio.TextureFinder(base_dir)
|
||||
self.tex_moved, self.tex_missing, self.tex_bad = set(), set(), set() # 贴图路径:日志里汇报
|
||||
self.gb = gb
|
||||
self.is1 = is1
|
||||
self.outline = outline
|
||||
self.force_double_sided = force_double_sided
|
||||
# 「所有材质双面」时仍保持单面的:描边外壳、内侧面(one_sided_layers)
|
||||
self.keep_one_sided = one_sided_layers(model) if force_double_sided else {}
|
||||
self.materials = []
|
||||
self.props_0x = []
|
||||
self.img_cache = {}
|
||||
self.tex_alpha = {} # PMX 贴图 → png_alpha_stats 结果
|
||||
self.tex_grid = {} # PMX 贴图 → _alpha_grid(只有整张图里有透明像素的贴图)
|
||||
self.alpha_by_uv = 0 # 按 UV 覆盖区域统计后不再算透明的材质数
|
||||
self.toon_cache = {}
|
||||
self.blend_rank = 0
|
||||
self.sph_skipped = 0
|
||||
self.morph_min_alpha = {} # PMX 材质 → 材质表情能把 alpha 压到多低
|
||||
self.morph_max_alpha = {} # PMX 材质 → 材质表情能把 alpha 抬到多高
|
||||
self.face_start = [] # PMX 材质 → 它的第一个面在 model["faces"] 里的位置
|
||||
k = 0
|
||||
for mat in model["materials"]:
|
||||
self.face_start.append(k)
|
||||
k += mat["faces"]
|
||||
for f in flat:
|
||||
ops = f[2]
|
||||
for mi_, mat in enumerate(model["materials"]):
|
||||
r = _morph_material(mat, ops, mi_)
|
||||
if r is not None:
|
||||
self.morph_min_alpha[mi_] = min(self.morph_min_alpha.get(mi_, 1.0), r[0][3])
|
||||
self.morph_max_alpha[mi_] = max(self.morph_max_alpha.get(mi_, 0.0), r[0][3])
|
||||
|
||||
def _find(self, idx):
|
||||
"""PMX 贴图序号 → 磁盘上的文件路径(找不到为 None;查找规则见 vrmio.TextureFinder)。"""
|
||||
return self.finder.find(self.model["textures"][idx])[0]
|
||||
|
||||
def _load(self, idx):
|
||||
"""PMX 贴图序号 → (原图数据, mime, 透明统计, 瘦身后的 (数据, mime), 缩小的 alpha),读不了为 None。
|
||||
不改动 self 的状态,可以在线程里跑(见 prefetch)。"""
|
||||
c = self._find(idx)
|
||||
data, mime = vrmio.load_texture(c) if c else (None, None)
|
||||
if not data:
|
||||
return None
|
||||
# 透明度统计用原图(瘦身后可能已是 JPEG);只有完全不透明的贴图才会转 JPEG,结论不变
|
||||
key = os.path.normcase(os.path.abspath(c))
|
||||
alpha = self.known_alpha[key] if key in self.known_alpha else vrmio.png_alpha_stats(data)
|
||||
grid = _alpha_grid(data) if alpha and alpha[0] and alpha[1] >= alpha[0] * 0.001 else None
|
||||
slim = self.tex_opt.process(data, mime) if self.tex_opt is not None else (data, mime)
|
||||
return data, mime, alpha, slim, grid
|
||||
|
||||
def prefetch(self, threads=1):
|
||||
"""材质要用的贴图先一起读好(读文件、透明统计、瘦身):Pillow 解码 / 编码在 C 里跑、不占 GIL,
|
||||
几张图可以同时处理。结果留给 resolve_tex,贴图写进 GLB 的顺序不变。"""
|
||||
textures = self.model["textures"]
|
||||
want = []
|
||||
for mat in self.model["materials"]:
|
||||
if mat["faces"] < 3: # 没有三角面的材质不会生成(见 mesh.build_primitives)
|
||||
continue
|
||||
for idx in (mat["tex"], mat["sph"] if mat["sph_mode"] == 2 else -1):
|
||||
if 0 <= idx < len(textures) and idx not in want:
|
||||
want.append(idx)
|
||||
if threads < 2 or len(want) < 2:
|
||||
return
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
with ThreadPoolExecutor(min(threads, len(want))) as ex:
|
||||
self._pre.update(zip(want, ex.map(self._load, want)))
|
||||
|
||||
def resolve_tex(self, idx):
|
||||
"""PMX 贴图序号 → glTF texture 序号(-1 = 没有 / 读不了)。"""
|
||||
if idx is None or idx < 0 or idx >= len(self.model["textures"]):
|
||||
return -1
|
||||
if idx in self.img_cache:
|
||||
return self.img_cache[idx]
|
||||
got = self._pre.pop(idx) if idx in self._pre else self._load(idx)
|
||||
rel = self.model["textures"][idx]
|
||||
path, how = self.finder.find(rel)
|
||||
if path is None:
|
||||
self.tex_missing.add(rel)
|
||||
elif got is None:
|
||||
self.tex_bad.add(rel)
|
||||
elif how == "moved":
|
||||
self.tex_moved.add(rel)
|
||||
if got is None:
|
||||
self.img_cache[idx] = -1
|
||||
return -1
|
||||
data, mime, self.tex_alpha[idx], slim, grid = got
|
||||
if grid is not None:
|
||||
self.tex_grid[idx] = grid
|
||||
if self.tex_opt is not None:
|
||||
data, mime = self.tex_opt.account(data, slim)
|
||||
ti = self.gb.add_texture(self.gb.add_image(data, mime))
|
||||
self.img_cache[idx] = ti
|
||||
return ti
|
||||
|
||||
def toon_params(self, mat):
|
||||
"""材质的 toon 渐变 → (亮部色, 阴影色, shift, toony)(见 _toon_shading);
|
||||
没有 toon、共享 toon07~10、贴图找不到或解不了时返回 None(走默认阴影)。"""
|
||||
if mat["toon_flag"]:
|
||||
key = ("shared", mat["toon"])
|
||||
elif 0 <= mat["toon"] < len(self.model["textures"]):
|
||||
key = ("tex", mat["toon"])
|
||||
else:
|
||||
return None
|
||||
if key not in self.toon_cache:
|
||||
r = None
|
||||
if key[0] == "shared":
|
||||
st = _SHARED_TOON.get(key[1])
|
||||
if st:
|
||||
t, b = [tuple(c / 255.0 for c in x) for x in st]
|
||||
r = _toon_shading([t] * 16 + [b] * 16)
|
||||
else:
|
||||
path = self._find(key[1])
|
||||
if path:
|
||||
with open(path, "rb") as f:
|
||||
img = vrmio.decode_rgba(f.read())
|
||||
if img:
|
||||
r = _toon_shading(_toon_column(img[2], img[0], img[1]))
|
||||
self.toon_cache[key] = r
|
||||
return self.toon_cache[key]
|
||||
|
||||
def lit_shade(self, mat, color):
|
||||
"""MMD 显示色(_mmd_color)→ MToon 的 (亮部 RGBA, 阴影 RGB, shift, toony)。"""
|
||||
tp = self.toon_params(mat)
|
||||
if tp is None:
|
||||
# 没有可用的 toon:实际几乎都是眼睛、高光、眉睫、嘴、表情贴片。按二次元的
|
||||
# 惯例(原生 VRoid 的眼睛、眉毛阴影色都是白)不画阴影,不然一进投影眼睛就发黑
|
||||
return list(color), list(color[:3]), 0.0, 0.9
|
||||
lit, dark, shift, toony = tp
|
||||
return ([color[k] * lit[k] for k in range(3)] + [color[3]],
|
||||
[color[k] * dark[k] for k in range(3)], shift, toony)
|
||||
|
||||
def used_alpha(self, mi_, mat):
|
||||
"""材质贴图的透明统计(同 png_alpha_stats),只算这个材质的 UV 覆盖到的部分。
|
||||
|
||||
有的模型几个部件共用一张大图集,或者贴图右边还拼着用不到的半透明图层(同一张图
|
||||
u 0~1/3 是颜色,后面是别的通道):按整张图统计,不透明的身体、衣服也被当成半透明,
|
||||
BLEND 的排序问题让部件在转动视角时消失、前后遮挡错乱。三角面按 UV 画到缩小的
|
||||
alpha 图上,只统计盖住的像素。整张图没有透明像素的贴图不用算。"""
|
||||
whole = self.tex_alpha.get(mat["tex"])
|
||||
grid = self.tex_grid.get(mat["tex"])
|
||||
if grid is None or mat["faces"] < 3:
|
||||
return whole
|
||||
from PIL import Image, ImageDraw
|
||||
w, h = grid.size
|
||||
mask = Image.new("L", (w, h), 0)
|
||||
draw = ImageDraw.Draw(mask)
|
||||
verts, faces = self.model["vertices"], self.model["faces"]
|
||||
s = self.face_start[mi_]
|
||||
for t in range(s, s + mat["faces"] - 2, 3):
|
||||
uv = [verts[faces[t + k]]["uv"] for k in range(3)]
|
||||
# 平铺(repeat):整个三角形移到最小角所在的那一格
|
||||
ou, ov = math.floor(min(p[0] for p in uv)), math.floor(min(p[1] for p in uv))
|
||||
draw.polygon([((u - ou) * w, (v - ov) * h) for u, v in uv], fill=255)
|
||||
hist = grid.histogram(mask=mask)
|
||||
st = (sum(hist), sum(hist[:250]), sum(hist[11:245]))
|
||||
# UV 全落在完全透明的地方:靠 UV 表情挪过去才显示的贴片(表情符号)、靠材质表情显示的部件,
|
||||
# 初始 UV 说明不了什么,按整张图
|
||||
return st if st[0] - st[1] + st[2] > 0 else whole
|
||||
|
||||
@staticmethod
|
||||
def _see_through(st):
|
||||
return bool(st and st[0] and st[1] >= st[0] * 0.001)
|
||||
|
||||
def alpha_mode(self, mi_, mat):
|
||||
"""OPAQUE / MASK / BLEND。
|
||||
|
||||
以前只看漫反射 alpha,贴图自带透明通道(头发高光层、瞳孔、
|
||||
镂空裙摆)的材质全被写成 OPAQUE,透明区域画成实心——
|
||||
实测头发被一层黑色盖住、眼睛一片黑。现在还看贴图的 alpha 分布:
|
||||
* 半透明像素占可见像素的比例低(只有抗锯齿边缘)→ MASK(裁剪,
|
||||
不需要排序,Unity 里最稳)
|
||||
* 比例高(柔和的叠加层、薄纱)→ BLEND
|
||||
材质表情会把它隐藏(alpha → 0)的不透明材质用 MASK,才能真的隐藏。
|
||||
"""
|
||||
st = self.used_alpha(mi_, mat)
|
||||
if self._see_through(self.tex_alpha.get(mat["tex"])) and not self._see_through(st):
|
||||
self.alpha_by_uv += 1
|
||||
if mat["diffuse"][3] <= 0.001 and self.morph_max_alpha.get(mi_, 0.0) > 0.5:
|
||||
# 默认隐藏、靠材质表情显示的部件(FBX 的替换网格:另一种手势 / 张嘴的头):
|
||||
# 用 MASK,显示出来时就是普通的不透明材质,不用 BLEND 的排序
|
||||
if self._see_through(st) and st[2] >= (st[0] - st[1] + st[2]) * 0.3:
|
||||
return "BLEND"
|
||||
return "MASK"
|
||||
if mat["diffuse"][3] < 0.999:
|
||||
return "BLEND"
|
||||
if self._see_through(st):
|
||||
n, trans, mid = st
|
||||
visible = n - trans + mid
|
||||
if visible <= 0 or mid >= visible * 0.3:
|
||||
return "BLEND"
|
||||
return "MASK"
|
||||
if self.morph_min_alpha.get(mi_, 1.0) < 0.5:
|
||||
return "MASK"
|
||||
return "OPAQUE"
|
||||
|
||||
def make(self, mi_, mat):
|
||||
"""生成一个 glTF 材质,返回它在 self.materials 里的序号。"""
|
||||
ti = self.resolve_tex(mat["tex"])
|
||||
# 亮部 / 阴影色和明暗交界按 PMX 的 toon 渐变换算(MMD 的暗部和自阴影都取
|
||||
# toon 最下端的颜色)。以前一律「阴影 = 亮部 × 0.8」:灰色的阴影叠在浅色皮肤上
|
||||
# 几乎看不出来,星铁、鸣潮的脸又白又平;原生 VRoid 皮肤的阴影是粉色的
|
||||
diff, shade, shift, toony = self.lit_shade(mat, _mmd_color(mat["diffuse"], mat["ambient"]))
|
||||
mode = self.alpha_mode(mi_, mat)
|
||||
double = bool(mat["flag"] & 0x01) or (self.force_double_sided and mi_ not in self.keep_one_sided)
|
||||
# 加算球面贴图(sph_mode 2)≈ MToon 的 matcap(同样是加算);
|
||||
# 乘算(1)没有对应项,跳过
|
||||
si = -1
|
||||
if mat["sph_mode"] == 2:
|
||||
si = self.resolve_tex(mat["sph"])
|
||||
elif mat["sph_mode"] == 1 and 0 <= mat["sph"] < len(self.model["textures"]):
|
||||
self.sph_skipped += 1
|
||||
rq = 0
|
||||
if mode == "BLEND": # 半透明按 PMX 材质顺序排绘制顺序
|
||||
rq = min(9, self.blend_rank)
|
||||
self.blend_rank += 1
|
||||
edge = self.outline and bool(mat["flag"] & 0x10) and mat["edge_size"] > 0
|
||||
# 材质名在模型内唯一:有的程序按材质名找材质,
|
||||
# PMX 允许重名,重名时只会找到第一个
|
||||
name = mat["name"] or ("mat%d" % mi_)
|
||||
used = {m["name"] for m in self.materials}
|
||||
k = 2
|
||||
while name in used:
|
||||
name = "%s_%d" % (mat["name"] or ("mat%d" % mi_), k)
|
||||
k += 1
|
||||
gmat = {
|
||||
"name": name,
|
||||
"pbrMetallicRoughness": {
|
||||
"baseColorFactor": _lin_rgb(diff),
|
||||
"metallicFactor": 0.0,
|
||||
"roughnessFactor": 0.9,
|
||||
},
|
||||
"doubleSided": double,
|
||||
"emissiveFactor": [0.0, 0.0, 0.0],
|
||||
"alphaMode": mode,
|
||||
}
|
||||
if mode == "MASK":
|
||||
gmat["alphaCutoff"] = 0.5
|
||||
if ti >= 0:
|
||||
gmat["pbrMetallicRoughness"]["baseColorTexture"] = {"index": ti}
|
||||
|
||||
if self.is1:
|
||||
mt = {
|
||||
"specVersion": "1.0",
|
||||
"transparentWithZWrite": False,
|
||||
"renderQueueOffsetNumber": rq,
|
||||
"shadeColorFactor": _lin_rgb(shade),
|
||||
"shadingShiftFactor": round(shift, 4),
|
||||
"shadingToonyFactor": round(toony, 4),
|
||||
"giEqualizationFactor": 0.9,
|
||||
"matcapFactor": [1.0, 1.0, 1.0] if si >= 0 else [0.0, 0.0, 0.0],
|
||||
"parametricRimColorFactor": [0.0, 0.0, 0.0],
|
||||
"parametricRimFresnelPowerFactor": 5.0,
|
||||
"parametricRimLiftFactor": 0.0,
|
||||
"rimLightingMixFactor": 1.0,
|
||||
"outlineWidthMode": "worldCoordinates" if edge else "none",
|
||||
"outlineWidthFactor": (mat["edge_size"] * 0.001) if edge else 0.0,
|
||||
"outlineColorFactor": _lin_rgb(mat["edge_color"][:3]),
|
||||
"outlineLightingMixFactor": 1.0,
|
||||
}
|
||||
if ti >= 0:
|
||||
mt["shadeMultiplyTexture"] = {"index": ti}
|
||||
if si >= 0:
|
||||
mt["matcapTexture"] = {"index": si}
|
||||
gmat["extensions"] = {"VRMC_materials_mtoon": mt}
|
||||
else:
|
||||
blend = mode == "BLEND"
|
||||
mask = mode == "MASK"
|
||||
tex_props = {}
|
||||
if ti >= 0:
|
||||
tex_props["_MainTex"] = ti
|
||||
tex_props["_ShadeTexture"] = ti # 以前没写,暗部只剩一块纯色
|
||||
if si >= 0:
|
||||
tex_props["_SphereAdd"] = si
|
||||
self.props_0x.append({
|
||||
"name": gmat["name"],
|
||||
"shader": "VRM/MToon",
|
||||
"renderQueue": (3000 + rq) if blend else (2450 if mask else 2000),
|
||||
"floatProperties": {
|
||||
"_Cutoff": 0.5, "_BumpScale": 1.0,
|
||||
# 0.x:smoothstep(shift, shift + 1 − toony, N·L),换算成同样的交界和宽度
|
||||
"_ReceiveShadowRate": 1.0,
|
||||
"_ShadeShift": round(max(-1.0, min(1.0, -shift - (1.0 - toony))), 4),
|
||||
"_ShadeToony": round(max(0.0, 2.0 * toony - 1.0), 4),
|
||||
"_LightColorAttenuation": 0.0,
|
||||
"_IndirectLightIntensity": 0.1, "_RimLightingMix": 0.0,
|
||||
"_RimFresnelPower": 1.0, "_RimLift": 0.0,
|
||||
# 0.x 世界坐标模式的线宽单位是厘米
|
||||
"_OutlineWidth": (mat["edge_size"] * 0.1) if edge else 0.0,
|
||||
"_OutlineScaledMaxDistance": 1.0,
|
||||
"_OutlineLightingMix": 1.0, "_UvAnimScrollX": 0.0,
|
||||
"_UvAnimScrollY": 0.0, "_UvAnimRotation": 0.0,
|
||||
"_MToonVersion": 38.0, "_DebugMode": 0.0,
|
||||
"_BlendMode": 2.0 if blend else (1.0 if mask else 0.0),
|
||||
"_OutlineWidthMode": 1.0 if edge else 0.0,
|
||||
"_OutlineColorMode": 0.0,
|
||||
# Unity CullMode:0 Off / 1 Front / 2 Back。以前单面写成 1,
|
||||
# 剔除的是正面
|
||||
"_CullMode": 0.0 if double else 2.0,
|
||||
"_OutlineCullMode": 1.0,
|
||||
# 半透明:SrcAlpha / OneMinusSrcAlpha、不写深度。
|
||||
# 以前透明材质也写 1/0/ZWrite=1,等于不透明
|
||||
"_SrcBlend": 5.0 if blend else 1.0,
|
||||
"_DstBlend": 10.0 if blend else 0.0,
|
||||
"_ZWrite": 0.0 if blend else 1.0,
|
||||
"_AlphaToMask": 0.0,
|
||||
},
|
||||
"vectorProperties": {
|
||||
"_Color": [diff[0], diff[1], diff[2], diff[3]],
|
||||
"_ShadeColor": shade + [1.0],
|
||||
"_EmissionColor": [0.0, 0.0, 0.0, 1.0],
|
||||
"_OutlineColor": list(mat["edge_color"][:3]) + [1.0],
|
||||
"_RimColor": [0.0, 0.0, 0.0, 1.0],
|
||||
},
|
||||
"textureProperties": tex_props,
|
||||
"keywordMap": {"_NORMALMAP": False, "_ALPHATEST_ON": mask,
|
||||
"_ALPHABLEND_ON": blend,
|
||||
"_ALPHAPREMULTIPLY_ON": False,
|
||||
"MTOON_OUTLINE_WIDTH_WORLD": edge,
|
||||
"MTOON_OUTLINE_COLOR_FIXED": edge},
|
||||
"tagMap": {"RenderType": ("Transparent" if blend else
|
||||
"TransparentCutout" if mask
|
||||
else "Opaque")},
|
||||
})
|
||||
self.materials.append(gmat)
|
||||
return len(self.materials) - 1
|
||||
|
||||
def log_summary(self, log):
|
||||
modes = [m["alphaMode"] for m in self.materials]
|
||||
log("材质透明模式:不透明 %d · 裁剪(MASK)%d · 半透明(BLEND)%d"
|
||||
% (modes.count("OPAQUE"), modes.count("MASK"), modes.count("BLEND")))
|
||||
if self.alpha_by_uv:
|
||||
log("材质:%d 个材质的贴图有透明部分,但模型只用到不透明的区域,按不透明处理" % self.alpha_by_uv)
|
||||
if self.is1:
|
||||
nmc = sum(1 for m in self.materials if "matcapTexture" in
|
||||
m["extensions"]["VRMC_materials_mtoon"])
|
||||
else:
|
||||
nmc = sum(1 for p in self.props_0x if "_SphereAdd" in p["textureProperties"])
|
||||
if nmc:
|
||||
log("材质:%d 个加算球面贴图转为 MToon 的 matcap" % nmc)
|
||||
if self.tex_opt is not None:
|
||||
if not self.tex_opt.active and (self.tex_opt.max_size or self.tex_opt.jpeg):
|
||||
log("贴图:未安装 Pillow,缩小贴图和 JPEG 存储未生效", "warn")
|
||||
elif self.tex_opt.summary():
|
||||
log(self.tex_opt.summary())
|
||||
if self.sph_skipped:
|
||||
log("材质:%d 个材质的乘算球面贴图(.sph)在 MToon 中没有对应项,已忽略"
|
||||
% self.sph_skipped, "warn")
|
||||
if self.keep_one_sided:
|
||||
names = [self.model["materials"][i]["name"] for i in sorted(self.keep_one_sided)]
|
||||
log("材质:%d 个材质是描边外壳或内侧面(%s),「所有材质双面」时仍保持单面,否则会盖住模型或重叠闪烁"
|
||||
% (len(names), "、".join(names[:6]) + ("…" if len(names) > 6 else "")))
|
||||
|
||||
def names(rels):
|
||||
rels = sorted(rels)
|
||||
return "、".join(r.replace("\\", "/").rsplit("/", 1)[-1] for r in rels[:6]) + ("…" if len(rels) > 6 else "")
|
||||
if self.tex_moved:
|
||||
log("贴图:%d 张不在模型记录的位置,已按文件名在模型文件夹里找到(%s)" % (len(self.tex_moved), names(self.tex_moved)))
|
||||
if self.tex_missing:
|
||||
log("贴图:%d 张找不到(%s),用到它们的材质只有底色。贴图要和模型放在一起:请加入整个文件夹或压缩包"
|
||||
% (len(self.tex_missing), names(self.tex_missing)), "warn")
|
||||
if self.tex_bad:
|
||||
log("贴图:%d 张读取失败(%s),用到它们的材质只有底色" % (len(self.tex_bad), names(self.tex_bad)), "warn")
|
||||
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""3x3 矩阵小工具(行主序元组,纯 Python)。"""
|
||||
import math
|
||||
|
||||
|
||||
_I3 = (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
|
||||
|
||||
|
||||
def _m3mul(a, b):
|
||||
return tuple(sum(a[r * 3 + k] * b[k * 3 + c] for k in range(3))
|
||||
for r in range(3) for c in range(3))
|
||||
|
||||
|
||||
def _m3vec(m, v):
|
||||
return (m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
|
||||
m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
|
||||
m[6] * v[0] + m[7] * v[1] + m[8] * v[2])
|
||||
|
||||
|
||||
def _m3T(m):
|
||||
return (m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8])
|
||||
|
||||
|
||||
def _axis_angle(axis, ang):
|
||||
x, y, z = axis
|
||||
c, s = math.cos(ang), math.sin(ang)
|
||||
t = 1.0 - c
|
||||
return (t * x * x + c, t * x * y - s * z, t * x * z + s * y,
|
||||
t * x * y + s * z, t * y * y + c, t * y * z - s * x,
|
||||
t * x * z - s * y, t * y * z + s * x, t * z * z + c)
|
||||
|
||||
|
||||
def _to_axis_angle(m):
|
||||
ang = math.acos(max(-1.0, min(1.0, (m[0] + m[4] + m[8] - 1.0) * 0.5)))
|
||||
if ang < 1e-9:
|
||||
return (1.0, 0.0, 0.0), 0.0
|
||||
ax = (m[7] - m[5], m[2] - m[6], m[3] - m[1])
|
||||
ln = math.sqrt(ax[0] ** 2 + ax[1] ** 2 + ax[2] ** 2)
|
||||
if ln < 1e-9: # 180°:取对角线最大的那列
|
||||
k = max(range(3), key=lambda i: m[i * 4])
|
||||
col = [(m[i * 3 + k] + (1.0 if i == k else 0.0)) for i in range(3)]
|
||||
ln = math.sqrt(sum(x * x for x in col)) or 1.0
|
||||
return tuple(x / ln for x in col), ang
|
||||
return (ax[0] / ln, ax[1] / ln, ax[2] / ln), ang
|
||||
|
||||
|
||||
def _align(d, t):
|
||||
"""把方向 d 转到方向 t 的最小旋转,返回 (矩阵, 角度)。"""
|
||||
ld = math.sqrt(sum(x * x for x in d))
|
||||
lt = math.sqrt(sum(x * x for x in t))
|
||||
if ld < 1e-9 or lt < 1e-9:
|
||||
return _I3, 0.0
|
||||
d = [x / ld for x in d]
|
||||
t = [x / lt for x in t]
|
||||
ax = (d[1] * t[2] - d[2] * t[1], d[2] * t[0] - d[0] * t[2],
|
||||
d[0] * t[1] - d[1] * t[0])
|
||||
s = math.sqrt(sum(x * x for x in ax))
|
||||
ang = math.atan2(s, sum(d[k] * t[k] for k in range(3)))
|
||||
if s < 1e-9:
|
||||
return _I3, 0.0
|
||||
return _axis_angle((ax[0] / s, ax[1] / s, ax[2] / s), ang), ang
|
||||
@@ -0,0 +1,329 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""网格:顶点权重整理、按材质切成 glTF primitive、写 accessor、按表情分成几个网格。"""
|
||||
import heapq
|
||||
import math
|
||||
|
||||
import vrmio
|
||||
|
||||
|
||||
def _weights_of(v, nb, alias):
|
||||
"""一个顶点的 [(PMX 骨, 权重)](见 vertex_weights)。"""
|
||||
wt = v["wtype"]
|
||||
bs = [x for x in v["wbones"] if 0 <= x < nb]
|
||||
if not bs:
|
||||
bs = [0]
|
||||
if wt == 0:
|
||||
return [(alias.get(bs[0], bs[0]), 1.0)]
|
||||
if wt in (1, 3): # BDEF2 / SDEF(SDEF 退化成线性混合)
|
||||
# 和下面的通用算法结果完全相同,只是不建字典、不排序(顶点大多是这种)
|
||||
w0 = v["wweights"][0] if v["wweights"] else 1.0
|
||||
a = alias.get(bs[0], bs[0])
|
||||
b = bs[1] if len(bs) > 1 else bs[0]
|
||||
b = alias.get(b, b)
|
||||
wa, wb = max(0.0, w0), max(0.0, 1.0 - w0)
|
||||
if a == b:
|
||||
tot = wa + wb
|
||||
return [(a, 1.0 if tot <= 1e-9 else tot / tot)]
|
||||
if wb > wa:
|
||||
a, b, wa, wb = b, a, wb, wa
|
||||
tot = wa + wb
|
||||
if tot <= 1e-9:
|
||||
return [(a, 1.0)]
|
||||
return [(a, wa / tot), (b, wb / tot)]
|
||||
# BDEF4 / QDEF
|
||||
ws = list(v["wweights"]) + [0.0] * 4
|
||||
wl = [(bs[k] if k < len(bs) else bs[0], ws[k]) for k in range(4)]
|
||||
if sum(x[1] for x in wl) <= 1e-9:
|
||||
wl = [(bs[0], 1.0)]
|
||||
acc = {}
|
||||
for b_, w in wl:
|
||||
b_ = alias.get(b_, b_)
|
||||
acc[b_] = acc.get(b_, 0.0) + max(0.0, w)
|
||||
wl = sorted(acc.items(), key=lambda x: -x[1])[:4]
|
||||
tot = sum(w for _, w in wl)
|
||||
if tot <= 1e-9:
|
||||
return [(wl[0][0] if wl else bs[0], 1.0)]
|
||||
return [(b_, w / tot) for b_, w in wl]
|
||||
|
||||
|
||||
def vertex_weights(verts, nb, alias, base=None):
|
||||
"""逐顶点 [(PMX 骨, 权重)]:已归一、已按付与别名合并、最多 4 个。
|
||||
|
||||
base:同一批顶点不带别名(alias={})的结果。给了就只重算挂在别名骨上的顶点——网格要带别名的、
|
||||
骨骼表情烘焙要不带的,两份不用各从头算一遍。
|
||||
"""
|
||||
if not nb:
|
||||
return [[(0, 1.0)] for _ in verts]
|
||||
if base is not None and 0 not in alias: # 没有有效骨的顶点算到骨 0 上
|
||||
if not alias:
|
||||
return base
|
||||
keys = set(alias)
|
||||
out = list(base)
|
||||
for i, v in enumerate(verts):
|
||||
if not keys.isdisjoint(v["wbones"]):
|
||||
out[i] = _weights_of(v, nb, alias)
|
||||
return out
|
||||
return [_weights_of(v, nb, alias) for v in verts]
|
||||
|
||||
|
||||
LIMB_PART = {"Shoulder": "肩", "UpperArm": "上臂", "LowerArm": "前臂", "Hand": "手",
|
||||
"UpperLeg": "大腿", "LowerLeg": "小腿", "Foot": "脚", "Toes": "脚趾"}
|
||||
|
||||
|
||||
def mirror_mismatches(verts, raw_weights, vweights, human, min_count=20):
|
||||
"""左右对称位置的顶点绑在四肢的不同部位上(一边大腿、一边小腿之类)→
|
||||
[(顶点对数, 右侧骨, 右侧部位, 左侧骨, 左侧部位)](骨是 PMX 索引,部位是 humanoid 骨位去掉 left / right)。
|
||||
|
||||
多半是模型镜像权重时弄错了:在 MMD 里同样会变形(膝盖一弯,绑在大腿上的鞋子就被扯开),
|
||||
转换器不改模型,只在日志里提示。PMX 坐标里角色的左边是 +X。只算两边都主要(≥ 0.5)挂在
|
||||
四肢的 humanoid 骨上、而且各自几乎不挂对面那个部位(< 0.2)的顶点对,关节处正常的混合权重不算。
|
||||
"""
|
||||
part = {}
|
||||
for s, b in human.items():
|
||||
for side in ("left", "right"):
|
||||
if s.startswith(side):
|
||||
part[b] = s[len(side):]
|
||||
if not part:
|
||||
return []
|
||||
|
||||
def key(x, y, z):
|
||||
return (round(x, 3), round(y, 3), round(z, 3))
|
||||
|
||||
def dom(wl):
|
||||
return max(wl, key=lambda t: t[1])
|
||||
|
||||
def on(wl, p):
|
||||
return sum(w for b, w in wl if part.get(b) == p)
|
||||
|
||||
left = {key(*v["pos"]): i for i, v in enumerate(verts) if v["pos"][0] > 1e-4}
|
||||
groups = {}
|
||||
for i, v in enumerate(verts):
|
||||
x, y, z = v["pos"]
|
||||
if x >= -1e-4:
|
||||
continue
|
||||
j = left.get(key(-x, y, z))
|
||||
if j is None:
|
||||
continue
|
||||
(br, wr), (bl, wl) = dom(vweights[i]), dom(vweights[j])
|
||||
pr, pl = part.get(br), part.get(bl)
|
||||
if not pr or not pl or pr == pl or wr < 0.5 or wl < 0.5:
|
||||
continue
|
||||
if on(vweights[i], pl) >= 0.2 or on(vweights[j], pr) >= 0.2:
|
||||
continue
|
||||
k = (dom(raw_weights[i])[0], pr, dom(raw_weights[j])[0], pl)
|
||||
groups[k] = groups.get(k, 0) + 1
|
||||
return sorted(((n,) + k for k, n in groups.items() if n >= min_count), reverse=True)
|
||||
|
||||
|
||||
def build_primitives(model, xf, xf_dir, vpos, vnrm, vweights, reverse_winding, make_material):
|
||||
"""按 PMX 材质切网格。make_material(PMX 材质号, 材质) → glTF 材质号(只给有面的材质调用)。
|
||||
|
||||
返回 (prims, mat_gidx):prims 每项含 local(PMX 顶点 → 本 primitive 顶点)、顶点数据、
|
||||
索引和 glTF 材质号;mat_gidx:PMX 材质号 → glTF 材质号(0 面的材质不在里面)。
|
||||
"""
|
||||
verts = model["vertices"]
|
||||
faces = model["faces"]
|
||||
prims = []
|
||||
mat_gidx = {}
|
||||
cursor = 0
|
||||
for mi_, mat in enumerate(model["materials"]):
|
||||
cnt = mat["faces"]
|
||||
tri_count = cnt // 3
|
||||
positions, normals, uvs, joints, weights = [], [], [], [], []
|
||||
local = {}
|
||||
idxs = []
|
||||
|
||||
def get_local(vi):
|
||||
j = local.get(vi)
|
||||
if j is not None:
|
||||
return j
|
||||
v = verts[vi]
|
||||
p = xf(vpos[vi])
|
||||
n = xf_dir(vnrm[vi])
|
||||
ln = math.sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]) or 1.0
|
||||
n = (n[0] / ln, n[1] / ln, n[2] / ln)
|
||||
j = len(positions) // 3
|
||||
local[vi] = j
|
||||
positions.extend(p)
|
||||
normals.extend(n)
|
||||
uvs.extend(v["uv"])
|
||||
# JOINTS_0 的值是「skin.joints 数组的下标」,不是 glTF 节点号!
|
||||
# 这里先写 PMX 骨索引 b,去掉无用节点后由 remap_joints 换成 joints 里的位置。以前错写成节点号 bone_node(b),
|
||||
# 拓扑排序一旦重排骨骼(remap 非恒等)权重就整体串位——
|
||||
# 症状是 Blender 里动某根骨头、别处的顶点跟着跑。
|
||||
wl = list(vweights[vi])
|
||||
while len(wl) < 4:
|
||||
wl.append((wl[0][0], 0.0))
|
||||
joints.extend([b for b, _ in wl[:4]])
|
||||
weights.extend([w for _, w in wl[:4]])
|
||||
return j
|
||||
|
||||
for t in range(tri_count):
|
||||
a = faces[cursor + t * 3]
|
||||
b = faces[cursor + t * 3 + 1]
|
||||
c = faces[cursor + t * 3 + 2]
|
||||
ia, ib, ic = get_local(a), get_local(b), get_local(c)
|
||||
if reverse_winding:
|
||||
ia, ic = ic, ia
|
||||
idxs.extend([ia, ib, ic])
|
||||
cursor += cnt
|
||||
|
||||
if not idxs:
|
||||
continue
|
||||
# 以前 primitive 直接用 PMX 材质号,PMX 里有 0 面材质时
|
||||
# 后面的材质会整体错一位;现在用实际写出的 glTF 材质号
|
||||
mat_gidx[mi_] = make_material(mi_, mat)
|
||||
prims.append({"local": local, "vcount": len(local),
|
||||
"idxs": idxs, "pos": positions, "nrm": normals,
|
||||
"uv": uvs, "jn": joints, "wt": weights,
|
||||
"mat": mat_gidx[mi_], "mat_name": mat.get("name") or "", "tmap": {}})
|
||||
return prims, mat_gidx
|
||||
|
||||
|
||||
def remap_joints(prims, slot):
|
||||
"""JOINTS_0 里的 PMX 骨序号 → skin.joints 里的位置(slot:PMX 骨 → 位置)。
|
||||
|
||||
不在 slot 里的骨(去掉的节点)只会以权重 0 出现(凑满 4 个的占位),换成本顶点第一根骨。
|
||||
"""
|
||||
for pr in prims:
|
||||
jn = pr["jn"]
|
||||
for k in range(0, len(jn), 4):
|
||||
first = slot.get(jn[k], 0)
|
||||
for q in range(k, k + 4):
|
||||
jn[q] = slot.get(jn[q], first)
|
||||
|
||||
|
||||
def write_accessors(gb, prims):
|
||||
"""顶点属性和索引写进 GLB,结果放在 pr["acc"] / pr["indices"]。"""
|
||||
for pr in prims:
|
||||
pr["acc"] = {
|
||||
"POSITION": gb.add_accessor(pr["pos"], vrmio.FLOAT, "VEC3", 34962),
|
||||
"NORMAL": gb.add_accessor(pr["nrm"], vrmio.FLOAT, "VEC3", 34962),
|
||||
"TEXCOORD_0": gb.add_accessor(pr["uv"], vrmio.FLOAT, "VEC2", 34962),
|
||||
"JOINTS_0": gb.add_accessor(pr["jn"], vrmio.UNSIGNED_SHORT,
|
||||
"VEC4", 34962),
|
||||
"WEIGHTS_0": gb.add_accessor(pr["wt"], vrmio.FLOAT, "VEC4", 34962),
|
||||
}
|
||||
pr["indices"] = gb.add_accessor(pr["idxs"], vrmio.UNSIGNED_INT,
|
||||
"SCALAR", 34963, minmax=False)
|
||||
|
||||
|
||||
# 多分一个网格折合多少「顶点 × morph target」:省下的不到这么多(密集存储约 1.2 MB)就不分
|
||||
MESH_COST = 100000
|
||||
MAX_MESHES = 8
|
||||
|
||||
|
||||
def group_meshes(prims, n_targets):
|
||||
"""按表情把 primitive 分成几个网格 → [(primitive 序号列表, 全局 morph target 序号列表)],按首个 primitive 排。
|
||||
|
||||
glTF 要求同一个网格里每个 primitive 带同样的 morph target,读取端(three.js、Unity)又多半按
|
||||
「顶点数 × target 数」展开成密集数组:全塞在一个网格里时,身体、衣服也要陪着脸带上全部表情
|
||||
(13 万顶点 × 180 个表情 ≈ 270 MB)。这里像 VRoid 的 Face / Body / Hair 那样分开:从「target 集合
|
||||
相同的放一起」开始,每次合并代价最小的两组(代价 = 网格顶点数 × target 数),直到再合并多出的
|
||||
比 MESH_COST 多、且网格数不超过 MAX_MESHES。哪个 primitive 都没动到的 target 放进 target 最多的网格,
|
||||
让表情还能引用它。
|
||||
"""
|
||||
by_set = {}
|
||||
for i, pr in enumerate(prims):
|
||||
by_set.setdefault(frozenset(pr["tmap"]), []).append(i)
|
||||
groups = {} # id → [target 集合, 顶点数, primitive 序号]
|
||||
for k, (ts, ids) in enumerate(by_set.items()):
|
||||
groups[k] = [ts, sum(prims[i]["vcount"] for i in ids), ids]
|
||||
|
||||
def extra(a, b):
|
||||
ta, va, _ = groups[a]
|
||||
tb, vb, _ = groups[b]
|
||||
return (va + vb) * len(ta | tb) - va * len(ta) - vb * len(tb)
|
||||
|
||||
heap = [(extra(a, b), a, b) for a in groups for b in groups if a < b]
|
||||
heapq.heapify(heap)
|
||||
nxt = len(groups)
|
||||
while heap and len(groups) > 1:
|
||||
d, a, b = heapq.heappop(heap)
|
||||
if a not in groups or b not in groups:
|
||||
continue
|
||||
if d > MESH_COST and len(groups) <= MAX_MESHES:
|
||||
break
|
||||
ta, va, ia = groups.pop(a)
|
||||
tb, vb, ib = groups.pop(b)
|
||||
groups[nxt] = [ta | tb, va + vb, sorted(ia + ib)]
|
||||
for c in list(groups):
|
||||
if c != nxt:
|
||||
heapq.heappush(heap, (extra(c, nxt), c, nxt))
|
||||
nxt += 1
|
||||
out = sorted(([ids, set(ts)] for ts, _, ids in groups.values()), key=lambda g: g[0][0])
|
||||
used = set().union(*(ts for _, ts in out))
|
||||
orphans = set(range(n_targets)) - used
|
||||
if orphans:
|
||||
max(out, key=lambda g: len(g[1]))[1].update(orphans)
|
||||
return [(ids, sorted(ts)) for ids, ts in out]
|
||||
|
||||
|
||||
def _zero_target(gb, pr, sparse):
|
||||
"""这个 primitive 上的全零 morph target(同一个 primitive 共用一个)。"""
|
||||
if "zero" not in pr:
|
||||
if sparse: # 稀疏 accessor 至少要一项
|
||||
pr["zero"] = gb.add_sparse_accessor(pr["vcount"], [], [], "VEC3")
|
||||
else:
|
||||
pr["zero"] = gb.add_accessor([0.0] * (pr["vcount"] * 3), vrmio.FLOAT, "VEC3", 34962)
|
||||
return pr["zero"]
|
||||
|
||||
|
||||
def build_meshes(gb, prims, groups, target_names, name, sparse=True, prim_names=False):
|
||||
"""group_meshes 的分组 → (glTF meshes, where)。where[全局 target 序号] = [(网格号, 网格内序号)]。
|
||||
|
||||
prim_names:morph target 名也写进每个 primitive 的 extras(VRM 0.x:UniVRM 自己导出时两处都写,
|
||||
老版本的读取端只看 primitive,读不到时 BlendShape 名变成编号)。"""
|
||||
meshes = []
|
||||
where = [[] for _ in target_names]
|
||||
for mi, (ids, slots) in enumerate(groups):
|
||||
m = {"name": name if len(groups) == 1 else _mesh_name(prims, ids, name), "primitives": []}
|
||||
for i in ids:
|
||||
pr = prims[i]
|
||||
p = {"attributes": pr["acc"], "indices": pr["indices"], "material": pr["mat"]}
|
||||
if slots:
|
||||
p["targets"] = [{"POSITION": pr["tmap"][s] if s in pr["tmap"] else _zero_target(gb, pr, sparse)}
|
||||
for s in slots]
|
||||
if prim_names:
|
||||
p["extras"] = {"targetNames": [target_names[s] for s in slots]}
|
||||
m["primitives"].append(p)
|
||||
if slots:
|
||||
m["extras"] = {"targetNames": [target_names[s] for s in slots]}
|
||||
for j, s in enumerate(slots):
|
||||
where[s].append((mi, j))
|
||||
meshes.append(m)
|
||||
used = set()
|
||||
for m in meshes: # 网格名会成为 Unity 里的物体名,别重
|
||||
base, k = m["name"], 2
|
||||
while m["name"] in used:
|
||||
m["name"] = "%s_%d" % (base, k)
|
||||
k += 1
|
||||
used.add(m["name"])
|
||||
return meshes, where
|
||||
|
||||
|
||||
def _mesh_name(prims, ids, name):
|
||||
"""几个网格时按里面最大的 primitive 的材质起名(在 Unity 的层级里一眼能认出是哪一块)。"""
|
||||
big = max(ids, key=lambda i: prims[i]["vcount"])
|
||||
return prims[big].get("mat_name") or name
|
||||
|
||||
|
||||
def remap_binds(expr, where, mesh_nodes, is1):
|
||||
"""表情绑定里的全局 morph target 序号 → 各网格里的(一个 target 分在几个网格时拆成几个绑定)。
|
||||
|
||||
1.0 的 node 是网格节点(mesh_nodes[网格号]),0.x 的 mesh 是网格号。哪个网格都没有的 target
|
||||
(group_meshes 已经避免)就丢掉这个绑定。
|
||||
"""
|
||||
if is1:
|
||||
for grp in (expr["preset"], expr["custom"]):
|
||||
for obj in grp.values():
|
||||
if "morphTargetBinds" not in obj:
|
||||
continue
|
||||
obj["morphTargetBinds"] = [{"node": mesh_nodes[m], "index": j, "weight": b["weight"]}
|
||||
for b in obj["morphTargetBinds"] for m, j in where[b["index"]]]
|
||||
if not obj["morphTargetBinds"]:
|
||||
del obj["morphTargetBinds"]
|
||||
else:
|
||||
for g in expr["blend_groups"]:
|
||||
g["binds"] = [{"mesh": m, "index": j, "weight": b["weight"]}
|
||||
for b in g["binds"] for m, j in where[b["index"]]]
|
||||
@@ -0,0 +1,332 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""VRM 表情只能动顶点(morph target)、材质颜色和贴图偏移,PMX 里另外两种表情要先「烘焙」:
|
||||
|
||||
BoneBaker 骨骼表情(kind 2,寄り目 / +目上 / 齿轮旋转 …)→ 顶点偏移:在静止姿势下
|
||||
按表情给的平移 / 旋转摆骨(付与骨跟着付与親转、子骨跟着父骨),线性混合蒙皮
|
||||
算出每个顶点的位移。以前直接丢掉,含骨骼表情的グループ表情也就缺了一块。
|
||||
gaze_offsets 视线表情(lookUp / lookDown / lookLeft / lookRight):转左右眼骨的骨骼表情,
|
||||
同样烘焙成顶点偏移。lookAt 仍然是 bone 类型;有的程序(游戏的表情动画)
|
||||
直接播这四个表情,模型里没有就看不到眼珠动。
|
||||
uv_binds UV 表情(kind 3,漫符 / 表情贴图切换)→ 贴图的缩放 + 偏移(VRM 1.0 的
|
||||
textureTransformBinds、0.x 的 _MainTex_ST)。只有整个材质的 UV 按同一个
|
||||
仿射变换移动时才能表示(漫符那种一个材质一块面片的正好是)。
|
||||
|
||||
都在 PMX 坐标里算(左手系,脸朝 -Z、左手 +X);结果和普通顶点表情一样交给 expressions。
|
||||
"""
|
||||
import math
|
||||
|
||||
from .mathutil import _I3, _axis_angle, _m3mul, _m3vec, _to_axis_angle
|
||||
from .mesh import vertex_weights
|
||||
|
||||
|
||||
def _quat_m3(q):
|
||||
"""PMX 骨骼表情的四元数 (x, y, z, w) → 旋转矩阵。
|
||||
|
||||
MMD 的矩阵是行向量约定(v' = v·M),换成列向量正好是标准公式,数值上不用改符号。
|
||||
"""
|
||||
x, y, z, w = q
|
||||
s = math.sqrt(x * x + y * y + z * z)
|
||||
if s < 1e-9:
|
||||
return _I3
|
||||
return _axis_angle((x / s, y / s, z / s), 2.0 * math.atan2(s, w))
|
||||
|
||||
|
||||
def _scale_rot(m, rate):
|
||||
"""旋转按比例缩放(付与率):轴不变、角度 × rate。"""
|
||||
if m is _I3 or abs(rate - 1.0) < 1e-9:
|
||||
return m
|
||||
ax, ang = _to_axis_angle(m)
|
||||
if abs(ang * rate) < 1e-9:
|
||||
return _I3
|
||||
return _axis_angle(ax, ang * rate)
|
||||
|
||||
|
||||
class BoneBaker:
|
||||
"""骨骼表情 → {顶点: (dx, dy, dz)}(PMX 坐标)。"""
|
||||
|
||||
def __init__(self, model, weights=None):
|
||||
"""weights:已经算好的不带付与别名的顶点权重(mesh.vertex_weights(..., {})),没给时用到再算。"""
|
||||
self.bones = model["bones"]
|
||||
self.verts = model["vertices"]
|
||||
self._weights = weights
|
||||
self._users = None
|
||||
|
||||
def _vertex_weights(self):
|
||||
if self._users is None:
|
||||
if self._weights is None:
|
||||
self._weights = vertex_weights(self.verts, len(self.bones), {})
|
||||
users = {}
|
||||
for vi, wl in enumerate(self._weights):
|
||||
for b, _ in wl:
|
||||
users.setdefault(b, []).append(vi)
|
||||
self._users = users
|
||||
return self._weights
|
||||
|
||||
def deltas(self, offsets):
|
||||
"""offsets:[(骨, (tx, ty, tz), (qx, qy, qz, qw))],即 PMX 骨骼表情的 offsets。"""
|
||||
bones = self.bones
|
||||
nb = len(bones)
|
||||
loc_r, loc_t = {}, {}
|
||||
for b, t, q in offsets:
|
||||
if not (0 <= b < nb):
|
||||
continue
|
||||
r = _quat_m3(q)
|
||||
if r is not _I3:
|
||||
loc_r[b] = _m3mul(r, loc_r.get(b, _I3))
|
||||
if abs(t[0]) + abs(t[1]) + abs(t[2]) > 1e-9:
|
||||
o = loc_t.get(b, (0.0, 0.0, 0.0))
|
||||
loc_t[b] = (o[0] + t[0], o[1] + t[1], o[2] + t[2])
|
||||
if not loc_r and not loc_t:
|
||||
return {}
|
||||
|
||||
# 付与:付与先的局部旋转 / 移动 = 自己的 + 付与親的 × 付与率(付与親也可能是付与骨)
|
||||
eff = {}
|
||||
|
||||
def local(b, depth=0):
|
||||
if b in eff:
|
||||
return eff[b]
|
||||
r, t = loc_r.get(b, _I3), loc_t.get(b, (0.0, 0.0, 0.0))
|
||||
if depth < 32:
|
||||
ir = bones[b].get("inherit_rot")
|
||||
if ir and 0 <= ir[0] < nb and ir[0] != b:
|
||||
rs = _scale_rot(local(ir[0], depth + 1)[0], ir[1])
|
||||
if rs is not _I3:
|
||||
r = rs if r is _I3 else _m3mul(rs, r)
|
||||
im = bones[b].get("inherit_mov")
|
||||
if im and 0 <= im[0] < nb and im[0] != b:
|
||||
ts = local(im[0], depth + 1)[1]
|
||||
t = (t[0] + ts[0] * im[1], t[1] + ts[1] * im[1], t[2] + ts[2] * im[1])
|
||||
eff[b] = (r, t)
|
||||
return eff[b]
|
||||
|
||||
# 全局:G_b = G_父 ∘ 平移(骨位置 + t) ∘ R ∘ 平移(-骨位置),只记不是恒等的
|
||||
glob = {}
|
||||
state = {}
|
||||
for start in range(nb):
|
||||
stack = [start]
|
||||
while stack:
|
||||
b = stack[-1]
|
||||
if b in state:
|
||||
stack.pop()
|
||||
continue
|
||||
p = bones[b]["parent"]
|
||||
if 0 <= p < nb and p not in state and p != b and len(stack) < nb:
|
||||
stack.append(p)
|
||||
continue
|
||||
stack.pop()
|
||||
r, t = local(b)
|
||||
par = glob.get(p) if (0 <= p < nb and p != b) else None
|
||||
if r is _I3 and abs(t[0]) + abs(t[1]) + abs(t[2]) < 1e-12 and par is None:
|
||||
state[b] = True
|
||||
continue
|
||||
pos = bones[b]["pos"]
|
||||
rp = _m3vec(r, pos)
|
||||
lt = (pos[0] + t[0] - rp[0], pos[1] + t[1] - rp[1], pos[2] + t[2] - rp[2])
|
||||
if par is None:
|
||||
glob[b] = (r, lt)
|
||||
else:
|
||||
pm, pt = par
|
||||
q = _m3vec(pm, lt)
|
||||
glob[b] = (_m3mul(pm, r), (q[0] + pt[0], q[1] + pt[1], q[2] + pt[2]))
|
||||
state[b] = True
|
||||
if not glob:
|
||||
return {}
|
||||
|
||||
weights = self._vertex_weights()
|
||||
touched = set()
|
||||
for b in glob:
|
||||
touched.update(self._users.get(b, ()))
|
||||
out = {}
|
||||
for vi in touched:
|
||||
p = self.verts[vi]["pos"]
|
||||
x = y = z = 0.0
|
||||
for b, w in weights[vi]:
|
||||
g = glob.get(b)
|
||||
if g is None:
|
||||
q = p
|
||||
else:
|
||||
q = _m3vec(g[0], p)
|
||||
q = (q[0] + g[1][0], q[1] + g[1][1], q[2] + g[1][2])
|
||||
x += q[0] * w
|
||||
y += q[1] * w
|
||||
z += q[2] * w
|
||||
d = (x - p[0], y - p[1], z - p[2])
|
||||
if abs(d[0]) + abs(d[1]) + abs(d[2]) > 1e-7:
|
||||
out[vi] = d
|
||||
return out
|
||||
|
||||
|
||||
# 视线表情的角度:VRoid 的 lookAt 量程(水平 / 垂直)同量级;眼骨在眼球中心附近,
|
||||
# 转 12° 眼珠大约移动眼宽的 1/4
|
||||
GAZE_DEG = {"lookLeft": 12.0, "lookRight": 12.0, "lookUp": 10.0, "lookDown": 10.0}
|
||||
LOOK_TRAVEL = 0.28 # 看到最边上时瞳孔走多远(瞳孔宽度的比例;VRoid 向内看约 29%)
|
||||
|
||||
|
||||
def eye_look_range(model, vweights, parents, eyes):
|
||||
"""按眼球几何算视线最大转角 → (角度, 说明)。
|
||||
|
||||
角度:{"lookLeft", "lookRight", "lookUp", "lookDown"}(度);算不出或测出来不合理时为 None
|
||||
(调用方用默认的 10°),说明给日志用。
|
||||
|
||||
瞳孔看起来移动多少 = 转角 × 支点到瞳孔的距离。VRoid 的眼骨支点很深(约 6 cm),转 8° 就走
|
||||
瞳孔宽度的 29%;MMD 模型的支点常常贴着眼球(2~4 cm),固定 10° 只走 15~25%,转眼不明显。
|
||||
所以按「瞳孔走 LOOK_TRAVEL × 瞳孔宽度」反推左右的角度(8°~20°)。上下按左右的比例:
|
||||
向下 0.7(动画眼睛竖向本来就扁,再多会钻到下眼皮里),向上 0.5(上眼皮挡着;VRoid 是 0°)。
|
||||
瞳孔 = 跟着眼骨及其子骨(左目先 等)走的顶点(权重 > 0.5)。
|
||||
"""
|
||||
bones, verts = model["bones"], model["vertices"]
|
||||
real = [e for e in eyes if e is not None]
|
||||
# 两眼间距:测出来的「瞳孔」比它还宽、或者支点离瞳孔比它还远,就是把别的东西也挂在眼骨上了
|
||||
# (整个眼部、脸),这时候算出来的角度不可信
|
||||
span = abs(bones[real[0]]["pos"][0] - bones[real[1]]["pos"][0]) if len(real) == 2 else None
|
||||
angles = []
|
||||
for eye in real:
|
||||
if eye is None:
|
||||
continue
|
||||
sub = {eye}
|
||||
grew = True
|
||||
while grew:
|
||||
grew = False
|
||||
for i, p in enumerate(parents):
|
||||
if p in sub and i not in sub:
|
||||
sub.add(i)
|
||||
grew = True
|
||||
pts = [verts[v]["pos"] for v in range(len(verts))
|
||||
if sum(w for b, w in vweights[v] if b in sub) > 0.5]
|
||||
if len(pts) < 8:
|
||||
continue
|
||||
px, _, pz = bones[eye]["pos"]
|
||||
xs = [q[0] for q in pts]
|
||||
dist = sorted(math.hypot(q[0] - px, q[2] - pz) for q in pts)
|
||||
far = dist[len(dist) // 2:] # 眼球前面(瞳孔表面)那一半
|
||||
r = sum(far) / len(far)
|
||||
width = max(xs) - min(xs)
|
||||
if span and (width > 0.8 * span or r > 1.5 * span):
|
||||
return None, ("眼骨上的顶点不像一只眼睛(宽 %.2f、支点到表面 %.2f,两眼相距 %.2f),使用默认值 10°"
|
||||
% (width, r, span))
|
||||
if r > 1e-6 and width > 1e-6:
|
||||
angles.append(math.degrees(math.atan(LOOK_TRAVEL * width / r)))
|
||||
if not angles:
|
||||
return None, "眼骨上没有瞳孔顶点,使用默认值 10°"
|
||||
raw = sum(angles) / len(angles)
|
||||
h = min(20.0, max(8.0, raw))
|
||||
note = "按眼球结构计算,瞳孔最多移动约 %d%% 瞳孔宽度" % round(LOOK_TRAVEL * 100)
|
||||
if h != raw:
|
||||
note += ";算出 %.1f°,限制到 %.0f°" % (raw, h)
|
||||
return {"lookLeft": h, "lookRight": h, "lookDown": round(h * 0.7, 2), "lookUp": round(h * 0.5, 2)}, note
|
||||
|
||||
|
||||
def gaze_offsets(left_eye, right_eye, deg=None):
|
||||
"""→ [(表情名, 骨骼表情 offsets)]:两只眼骨一起转(角度 deg,默认 GAZE_DEG)。
|
||||
|
||||
PMX 坐标里脸朝 -Z、角色的左边是 +X、上是 +Y:
|
||||
向左看(角色自己的左边,VRM 规范的 lookLeft)= 绕 Y 轴转负角,(0,0,-1) → +X
|
||||
向上看 = 绕 X 轴转正角,(0,0,-1) → +Y
|
||||
"""
|
||||
out = []
|
||||
for name, axis, sign in (("lookLeft", (0.0, 1.0, 0.0), -1.0), ("lookRight", (0.0, 1.0, 0.0), 1.0),
|
||||
("lookUp", (1.0, 0.0, 0.0), 1.0), ("lookDown", (1.0, 0.0, 0.0), -1.0)):
|
||||
half = math.radians((deg or GAZE_DEG)[name]) * sign * 0.5
|
||||
q = (axis[0] * math.sin(half), axis[1] * math.sin(half), axis[2] * math.sin(half), math.cos(half))
|
||||
out.append((name, [(b, (0.0, 0.0, 0.0), q) for b in (left_eye, right_eye) if b is not None]))
|
||||
return out
|
||||
|
||||
|
||||
# 视线表情按这个角度烘焙(和调整面板滑块的上限一样),实际角度靠权重:转眼骨 θ 时顶点的位移
|
||||
# 恰好是「横向场 × sinθ + 深度场 ×(1 − cosθ)」(Rodrigues),左右一对 ±Θ 的烘焙结果正好拆出这两个场:
|
||||
# 横向 = (d(+Θ) − d(−Θ)) / 2,深度 = (d(+Θ) + d(−Θ)) / 2
|
||||
# 表情 = 横向 × sinθ/sinΘ + 深度 × (1−cosθ)/(1−cosΘ),任意 θ ≤ Θ 都和真的转眼骨一样(蒙皮是线性混合,
|
||||
# 部分挂在眼骨上的眼皮也一样)。调整面板改视线角度时只改这两个权重,不用重新烘焙
|
||||
GAZE_MAX = {"h": 40.0, "v": 30.0}
|
||||
GAZE_PAIRS = (("lookLeft", "lookRight", "h"), ("lookUp", "lookDown", "v"))
|
||||
GAZE_DEPTH = {"h": "lookLeftRight_depth", "v": "lookUpDown_depth"}
|
||||
GAZE_KEY = {"lookLeft": "h", "lookRight": "h", "lookUp": "up", "lookDown": "down"} # 对应 lookAt 的哪个转角
|
||||
|
||||
|
||||
def gaze_weights(deg, axis):
|
||||
"""转 deg 度 → (横向权重, 深度权重)。超过烘焙角度时按烘焙角度。"""
|
||||
big = math.radians(GAZE_MAX[axis])
|
||||
t = math.radians(min(max(deg, 0.0), GAZE_MAX[axis]))
|
||||
return round(math.sin(t) / math.sin(big), 6), round((1 - math.cos(t)) / (1 - math.cos(big)), 6)
|
||||
|
||||
|
||||
def split_gaze(flat, names):
|
||||
"""flat(_flatten_morphs 的结果)里按 GAZE_MAX 烘焙的视线表情(成对的、从末尾找)拆成横向场 + 深度场:
|
||||
lookLeft / lookRight / lookUp / lookDown 原地换成横向场,再追加两个深度场。
|
||||
→ {预设: (横向名, 深度名, 轴)};names 是补进去的视线表情名,不成对的不拆。"""
|
||||
pos = {}
|
||||
for k in range(len(flat) - 1, -1, -1):
|
||||
if flat[k][0] in names and flat[k][0] not in pos:
|
||||
pos[flat[k][0]] = k
|
||||
out = {}
|
||||
for a, b, axis in GAZE_PAIRS:
|
||||
if a not in pos or b not in pos:
|
||||
continue
|
||||
da, db = flat[pos[a]][1], flat[pos[b]][1]
|
||||
tan, depth = {}, {}
|
||||
for v in set(da) | set(db):
|
||||
x, y = da.get(v, (0.0, 0.0, 0.0)), db.get(v, (0.0, 0.0, 0.0))
|
||||
t = tuple((x[i] - y[i]) * 0.5 for i in range(3))
|
||||
d = tuple((x[i] + y[i]) * 0.5 for i in range(3))
|
||||
if abs(t[0]) + abs(t[1]) + abs(t[2]) > 1e-9:
|
||||
tan[v] = t
|
||||
if abs(d[0]) + abs(d[1]) + abs(d[2]) > 1e-9:
|
||||
depth[v] = d
|
||||
flat[pos[a]] = (a, tan, [], {})
|
||||
flat[pos[b]] = (b, {v: (-t[0], -t[1], -t[2]) for v, t in tan.items()}, [], {})
|
||||
flat.append((GAZE_DEPTH[axis], depth, [], {}))
|
||||
out[a] = (a, GAZE_DEPTH[axis], axis)
|
||||
out[b] = (b, GAZE_DEPTH[axis], axis)
|
||||
return out
|
||||
|
||||
|
||||
def material_vertices(model):
|
||||
"""→ [每个材质用到的顶点集合]。"""
|
||||
faces = model["faces"]
|
||||
out = []
|
||||
f0 = 0
|
||||
for mat in model["materials"]:
|
||||
n = mat["faces"]
|
||||
out.append(set(faces[f0:f0 + n]))
|
||||
f0 += n
|
||||
return out
|
||||
|
||||
|
||||
def uv_binds(model, uvs, mat_verts=None, tol=2e-3):
|
||||
"""UV 表情 {顶点: (du, dv)} → ([(材质, (缩放 u, v), (偏移 u, v))], 表示不了的材质数)。
|
||||
|
||||
每个被动到的材质:所有顶点(没动的偏移算 0)的新 UV 要能写成
|
||||
u' = su·u + ou、v' = sv·v + ov(最小二乘拟合后误差 < tol),否则算「表示不了」。
|
||||
"""
|
||||
if not uvs:
|
||||
return [], 0
|
||||
mat_verts = mat_verts if mat_verts is not None else material_vertices(model)
|
||||
verts = model["vertices"]
|
||||
out, bad = [], 0
|
||||
for mi, vs in enumerate(mat_verts):
|
||||
if not vs or not any(v in uvs for v in vs):
|
||||
continue
|
||||
fit = []
|
||||
for k in (0, 1):
|
||||
xs = [verts[v]["uv"][k] for v in vs]
|
||||
ys = [xs[i] + uvs.get(v, (0.0, 0.0))[k] for i, v in enumerate(vs)]
|
||||
n = len(xs)
|
||||
mx, my = sum(xs) / n, sum(ys) / n
|
||||
sxx = sum((x - mx) ** 2 for x in xs)
|
||||
if sxx < 1e-12: # 所有顶点 UV 一样:只能是纯偏移
|
||||
s = 1.0
|
||||
else:
|
||||
s = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sxx
|
||||
o = my - s * mx
|
||||
if max(abs(s * x + o - y) for x, y in zip(xs, ys)) > tol:
|
||||
fit = None
|
||||
break
|
||||
fit.append((s, o))
|
||||
if fit is None:
|
||||
bad += 1
|
||||
continue
|
||||
(su, ou), (sv, ov) = fit
|
||||
if abs(su - 1) < 1e-6 and abs(sv - 1) < 1e-6 and abs(ou) < 1e-6 and abs(ov) < 1e-6:
|
||||
continue
|
||||
out.append((mi, (su, sv), (ou, ov)))
|
||||
return out, bad
|
||||
@@ -0,0 +1,410 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""骨骼预处理和 glTF 节点树。
|
||||
|
||||
fix_facing 模型侧着 / 背对时绕 Y 轴转正(Unreal 的 psk / uemodel 常见)
|
||||
prepare_bones 付与骨合并、humanoid 映射与层级修正、拓扑排序(PMX 坐标)
|
||||
apply_tpose A-pose → T-pose:骨骼位置和顶点一起重摆
|
||||
NodeTree 骨骼 → glTF 节点(先记父节点 + 世界坐标,最后统一换算 translation,
|
||||
所以补占位骨、SpringBone 改挂父节点都可以随意改)
|
||||
"""
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
from .humanoid import (REQUIRED_0X, REQUIRED_1_0, _HIPS_Y, _SYNTH, _append_aliases,
|
||||
_bone_len, _clean_parents, _fix_humanoid_hierarchy, _is_ancestor, _map_humanoid, _pick_toes, _reparent,
|
||||
_topo_bones, _tpose_globals, _vrm_anchor)
|
||||
from .mathutil import _I3, _m3vec
|
||||
|
||||
|
||||
def fix_facing(model, log):
|
||||
"""PMX 约定左手在 +X、脸朝 -Z。从 humanoid 的左右肩 / 胯算出左右方向,不在 X 轴上时
|
||||
绕 Y 轴转最近的 90° 倍数(Unreal 的前方是另一根轴,psk / uemodel 转来的模型常常侧着;
|
||||
xps / FBX 偶尔背对)。侧着的模型做 T-pose 时会把向前伸的手臂当成下垂的再转 90°。
|
||||
|
||||
只在没有物理刚体时转(刚体的欧拉角不好跟着转,原生 PMX 本来就是正的)。返回转的角度。
|
||||
"""
|
||||
bones = model["bones"]
|
||||
if model.get("rigid_bodies"):
|
||||
return 0
|
||||
human = _map_humanoid(bones, True, {})
|
||||
pairs = [(human[a], human[b]) for a, b in (("leftUpperArm", "rightUpperArm"), ("leftUpperLeg", "rightUpperLeg"),
|
||||
("leftShoulder", "rightShoulder")) if a in human and b in human]
|
||||
if not pairs:
|
||||
return 0
|
||||
sx = sum(bones[l]["pos"][0] - bones[r]["pos"][0] for l, r in pairs)
|
||||
sz = sum(bones[l]["pos"][2] - bones[r]["pos"][2] for l, r in pairs)
|
||||
if math.hypot(sx, sz) < 1e-6:
|
||||
return 0
|
||||
quarter = round(math.atan2(sz, sx) / (math.pi / 2)) % 4 # 0 = 已经是正的
|
||||
if quarter == 0:
|
||||
return 0
|
||||
t = quarter * math.pi / 2
|
||||
c, s = round(math.cos(t)), round(math.sin(t))
|
||||
|
||||
def rot(v): # 把「左」方向转到 +X:x' = x·c + z·s,z' = −x·s + z·c
|
||||
return (v[0] * c + v[2] * s, v[1], -v[0] * s + v[2] * c)
|
||||
|
||||
for v in model.get("vertices") or []:
|
||||
v["pos"] = rot(v["pos"])
|
||||
v["normal"] = rot(v["normal"])
|
||||
if v.get("sdef"):
|
||||
v["sdef"] = [rot(p) for p in v["sdef"]]
|
||||
for b in bones:
|
||||
b["pos"] = rot(b["pos"])
|
||||
if b.get("tail_kind") == 0 and b.get("tail") is not None and not isinstance(b["tail"], int):
|
||||
b["tail"] = rot(b["tail"])
|
||||
if b.get("fixed_axis"):
|
||||
b["fixed_axis"] = rot(b["fixed_axis"])
|
||||
if b.get("local_axis"):
|
||||
b["local_axis"] = tuple(rot(a) for a in b["local_axis"])
|
||||
for mo in model.get("morphs") or []:
|
||||
if mo["kind"] == 1:
|
||||
mo["offsets"] = [(i, rot(o)) for i, o in mo["offsets"]]
|
||||
elif mo["kind"] == 2:
|
||||
mo["offsets"] = [(i, rot(t_), q_) for i, t_, q_ in mo["offsets"]] # 骨骼表情的平移
|
||||
deg = quarter * 90
|
||||
if log:
|
||||
log("朝向:模型%s,已绕 Y 轴旋转 %d° 校正(左右肩 / 胯不在 X 轴上)"
|
||||
% ("背向前方" if quarter == 2 else "朝向侧面", deg), "warn")
|
||||
return deg
|
||||
|
||||
|
||||
def prepare_bones(bones, is1, log, weighted=()):
|
||||
"""→ SimpleNamespace(parents, alias, required, human_b, order, remap)。
|
||||
|
||||
1) 付与 100% 的骨(足D 等)并入付与親:权重与子骨都转过去
|
||||
2) humanoid 映射 + 层级修正(上半身 挂到 下半身 下等);脚趾按 _pick_toes 选
|
||||
weighted:挂了网格的骨(PMX 骨索引),选脚趾时用。
|
||||
"""
|
||||
nb = len(bones)
|
||||
parents = _clean_parents(bones)
|
||||
alias = _append_aliases(bones, parents, eps=0.01)
|
||||
if alias:
|
||||
for i, dst in alias.items():
|
||||
for c in range(nb):
|
||||
if parents[c] == i:
|
||||
_reparent(parents, c, dst)
|
||||
log("付与骨合并:%d 根(%s)→ 权重并入付与親"
|
||||
% (len(alias), "、".join(bones[i]["name"] for i in
|
||||
list(alias)[:6]) +
|
||||
("…" if len(alias) > 6 else "")))
|
||||
off = [bones[i]["name"] for i, s in alias.items() if math.dist(bones[i]["pos"], bones[s]["pos"]) > 0.01]
|
||||
if off:
|
||||
log("付与骨合并:%s 与付与親的位置略有偏差,合并后绕付与親的位置转动" % "、".join(off))
|
||||
# 1.0 规范里 chest / neck 可选,但不少程序、动作数据默认有(比如按躯干关节生成布娃娃),
|
||||
# 缺的话和 0.x 一样补占位骨
|
||||
required = REQUIRED_0X
|
||||
human_b = _map_humanoid(bones, is1, alias)
|
||||
_pick_toes(bones, human_b, alias, set(weighted))
|
||||
_fix_humanoid_hierarchy(human_b, parents, bones, set(required), log)
|
||||
order, remap = _topo_bones(parents)
|
||||
return SimpleNamespace(parents=parents, alias=alias, required=required,
|
||||
human_b=human_b, order=order, remap=remap)
|
||||
|
||||
|
||||
def split_partial(bones, bs, vweights, rigid_bodies, log):
|
||||
"""按比例跟随关节的付与骨(ひざ補助 跟 ひざ 转 0.5、尻 跟 足 转 0.5 之类)→ 新的逐顶点权重。
|
||||
|
||||
这些骨让关节弯曲时保持体积:MMD 里绕自己的位置转关节角度的一部分。VRM 没有付与,原样导出时它们
|
||||
只跟父骨走,关节一弯这部分就瘪下去。这里把它(和它下面的骨)上的权重按付与率拆开:付与率那份给
|
||||
关节骨,其余留在原骨上,线性混合出来约等于转了一部分角度(误差约为不拆的一半到四分之一)。
|
||||
静止姿势不变,在 T-pose 之后做(T-pose 里这些骨已按付与率跟转)。
|
||||
|
||||
只拆:付与親(并入后)是 humanoid 骨、付与率在 0.05~1 之间、和关节骨跟着同一根 humanoid 骨移动
|
||||
(见 humanoid._append_aliases)、自己和下面的骨都不带物理刚体的。付与率 1 却没能并入付与親的
|
||||
(偏差超过半节骨长)在偏差不超过一节骨长时整份转过去;再远的不动——它的顶点要是都在自己的转动点
|
||||
附近,改绕关节转反而比不动偏得多,留给自检在日志里提示。
|
||||
"""
|
||||
n = len(bones)
|
||||
if not n:
|
||||
return vweights
|
||||
hum = set(bs.human_b.values())
|
||||
phys = {rb.get("bone") for rb in rigid_bodies or () if rb.get("mode") in (1, 2)}
|
||||
kids = [[] for _ in range(n)]
|
||||
for c, p in enumerate(bs.parents):
|
||||
if 0 <= p < n and p != c:
|
||||
kids[p].append(c)
|
||||
|
||||
def anchor(i):
|
||||
seen = set()
|
||||
while 0 <= i < n and i not in seen:
|
||||
if i in hum:
|
||||
return i
|
||||
seen.add(i)
|
||||
i = bs.parents[i]
|
||||
return -1
|
||||
|
||||
def subtree(i): # 到下一根 humanoid 骨为止
|
||||
out, todo = {i}, [i]
|
||||
while todo:
|
||||
for c in kids[todo.pop()]:
|
||||
if c not in hum and c not in out:
|
||||
out.add(c)
|
||||
todo.append(c)
|
||||
return out
|
||||
|
||||
plan, names = {}, []
|
||||
for i, b in enumerate(bones):
|
||||
ir = b.get("inherit_rot")
|
||||
if not ir or i in hum or i in bs.alias or not (0 <= ir[0] < n) or not (0.05 <= ir[1] <= 1.0001):
|
||||
continue
|
||||
s = bs.alias.get(ir[0], ir[0])
|
||||
if s not in hum or _is_ancestor(bs.parents, i, s) or _is_ancestor(bs.parents, s, i):
|
||||
continue
|
||||
if anchor(bs.parents[i]) != anchor(bs.parents[s]):
|
||||
continue
|
||||
if ir[1] >= 0.999 and math.dist(b["pos"], bones[s]["pos"]) > max(
|
||||
math.dist(bones[bs.parents[s]]["pos"], bones[s]["pos"]) if bs.parents[s] >= 0 else 0.0,
|
||||
_bone_len(bones, bs.parents, s)):
|
||||
continue # 100% 跟随却离关节一节骨长以上:绕关节转可能比不动还偏,留给自检提示
|
||||
sub = subtree(i)
|
||||
if phys.intersection(sub):
|
||||
continue
|
||||
for k in sub:
|
||||
if k == i or not bones[k].get("inherit_rot"):
|
||||
plan.setdefault(k, (s, min(1.0, ir[1])))
|
||||
names.append(bones[i]["name"])
|
||||
if not plan:
|
||||
return vweights
|
||||
out, nv = list(vweights), 0
|
||||
for vi, wl in enumerate(vweights):
|
||||
if not any(b in plan for b, _ in wl):
|
||||
continue
|
||||
acc = {}
|
||||
for b, w in wl:
|
||||
if b in plan:
|
||||
s, r = plan[b]
|
||||
acc[s] = acc.get(s, 0.0) + w * r
|
||||
if r < 1.0:
|
||||
acc[b] = acc.get(b, 0.0) + w * (1.0 - r)
|
||||
else:
|
||||
acc[b] = acc.get(b, 0.0) + w
|
||||
top = sorted(acc.items(), key=lambda t: -t[1])[:4]
|
||||
tot = sum(w for _, w in top) or 1.0
|
||||
out[vi] = [(b, w / tot) for b, w in top]
|
||||
nv += 1
|
||||
if nv:
|
||||
log("付与骨:%d 根按比例跟随关节的骨(%s)→ 权重按付与率分给关节骨,共 %d 个顶点"
|
||||
% (len(names), "、".join(names[:6]) + ("…" if len(names) > 6 else ""), nv))
|
||||
return out
|
||||
|
||||
|
||||
def apply_tpose(verts, bones, bs, vweights, tpose, log):
|
||||
"""A-pose → T-pose(线性混合蒙皮),返回 (glob, bpos, vpos, vnrm, vmat)。
|
||||
|
||||
glob:每根骨的 T-pose 全局变换(没做 T-pose 时为 None);vmat:每个顶点的混合旋转,
|
||||
表情偏移要跟着转(没动的顶点为 None)。都是 PMX 坐标。
|
||||
"""
|
||||
nb = len(bones)
|
||||
vpos = [v["pos"] for v in verts]
|
||||
vnrm = [v["normal"] for v in verts]
|
||||
vmat = None
|
||||
bpos = [b["pos"] for b in bones]
|
||||
glob = _tpose_globals(bones, bs.parents, bs.order, bs.human_b, log) \
|
||||
if (tpose and nb) else None
|
||||
if glob:
|
||||
bpos = []
|
||||
for i in range(nb):
|
||||
m, t = glob[i]
|
||||
q = _m3vec(m, bones[i]["pos"])
|
||||
bpos.append((q[0] + t[0], q[1] + t[1], q[2] + t[2]))
|
||||
vpos, vnrm, vmat = [], [], [None] * len(verts)
|
||||
for vi, v in enumerate(verts):
|
||||
wl = vweights[vi]
|
||||
if all(glob[b_][0] is _I3 for b_, _ in wl):
|
||||
vpos.append(v["pos"])
|
||||
vnrm.append(v["normal"])
|
||||
continue
|
||||
m = [0.0] * 9
|
||||
t = [0.0, 0.0, 0.0]
|
||||
for b_, w in wl:
|
||||
gm, gt = glob[b_]
|
||||
for k in range(9):
|
||||
m[k] += gm[k] * w
|
||||
for k in range(3):
|
||||
t[k] += gt[k] * w
|
||||
q = _m3vec(m, v["pos"])
|
||||
vpos.append((q[0] + t[0], q[1] + t[1], q[2] + t[2]))
|
||||
vnrm.append(_m3vec(m, v["normal"]))
|
||||
vmat[vi] = m
|
||||
return glob, bpos, vpos, vnrm, vmat
|
||||
|
||||
|
||||
class NodeTree:
|
||||
"""glTF 节点:名字、父节点、世界坐标(VRM 坐标)。骨骼按拓扑序排在最前面。"""
|
||||
|
||||
def __init__(self, bones, bs, bpos, xf):
|
||||
self.names = []
|
||||
self.parent = []
|
||||
self.wpos = []
|
||||
self._remap = bs.remap
|
||||
self._of_bone = [0] * len(bones)
|
||||
self._name_set = None
|
||||
for new_i, old_i in enumerate(bs.order):
|
||||
par = bs.parents[old_i]
|
||||
self._of_bone[new_i] = len(self.names)
|
||||
self.names.append(bones[old_i]["name"] or ("bone%d" % old_i))
|
||||
self.parent.append(self._of_bone[bs.remap[par]]
|
||||
if (par >= 0 and bs.remap[par] < new_i) else None)
|
||||
self.wpos.append(xf(bpos[old_i]))
|
||||
if not bones: # 极端情况:没有骨骼
|
||||
self.names.append("root_bone")
|
||||
self.parent.append(None)
|
||||
self.wpos.append((0.0, 0.0, 0.0))
|
||||
|
||||
def bone_node(self, pmx_index):
|
||||
"""PMX 骨骼序号 → 节点序号。"""
|
||||
if 0 <= pmx_index < len(self._of_bone):
|
||||
return self._of_bone[self._remap[pmx_index]]
|
||||
return None
|
||||
|
||||
def node_pos(self, n):
|
||||
return self.wpos[n]
|
||||
|
||||
def is_ancestor(self, a, b):
|
||||
seen = set()
|
||||
while b is not None and b not in seen:
|
||||
if b == a:
|
||||
return True
|
||||
seen.add(b)
|
||||
b = self.parent[b]
|
||||
return False
|
||||
|
||||
def add_node(self, name, parent, pos):
|
||||
"""新增一个节点(重名时加 _2、_3 …),返回序号。"""
|
||||
if self._name_set is None:
|
||||
self._name_set = set(self.names)
|
||||
nm, k = name, 2
|
||||
while nm in self._name_set:
|
||||
nm = "%s_%d" % (name, k)
|
||||
k += 1
|
||||
self._name_set.add(nm)
|
||||
self.names.append(nm)
|
||||
self.parent.append(parent)
|
||||
self.wpos.append(pos)
|
||||
return len(self.names) - 1
|
||||
|
||||
def set_parent(self, node, parent):
|
||||
self.parent[node] = parent
|
||||
|
||||
def humanoid(self, human_b, required, unit, log, roots=()):
|
||||
"""humanoid 骨位 → 节点;缺失的必需骨位补占位骨(vrm_*)。
|
||||
|
||||
roots:另外要补的骨位(0.x 的两节拇指缺掌根那节 ThumbProximal 时补一个,插在手和第二节之间)。
|
||||
|
||||
unit(左, 上, 前) → 当前规范下的方向向量(1.0 左 +X 前 +Z;0.x 反过来)。
|
||||
"""
|
||||
human = {k: self.bone_node(v) for k, v in human_b.items()}
|
||||
req = set(required)
|
||||
|
||||
def ensure(name):
|
||||
if name in human:
|
||||
return human[name]
|
||||
pname = _vrm_anchor(name, set(human) | req)
|
||||
pnode = ensure(pname) if pname else None
|
||||
# 已有的、规范上应挂在本骨位下的 humanoid 骨(比如缺 spine 时的 chest)
|
||||
kids = [human[h] for h in list(human)
|
||||
if _vrm_anchor(h, set(human) | {name}) == name
|
||||
and not (pnode is not None and
|
||||
self.is_ancestor(human[h], pnode))]
|
||||
if kids:
|
||||
kc = [sum(self.wpos[k][j] for k in kids) / len(kids) for j in range(3)]
|
||||
if pnode is not None:
|
||||
pos = tuple((self.wpos[pnode][j] + kc[j]) * 0.5 for j in range(3))
|
||||
else:
|
||||
pos = tuple(kc)
|
||||
else:
|
||||
off = _SYNTH.get(name, (0.0, 0.05, 0.0))
|
||||
d = unit(off[0], off[1], off[2])
|
||||
if pnode is None:
|
||||
pos = (0.0, _HIPS_Y, 0.0) if name == "hips" else d
|
||||
else:
|
||||
pos = tuple(self.wpos[pnode][j] + d[j] for j in range(3))
|
||||
idx = len(self.names)
|
||||
self.names.append("vrm_" + name)
|
||||
self.parent.append(pnode)
|
||||
self.wpos.append(pos)
|
||||
for k in kids:
|
||||
self.parent[k] = idx
|
||||
human[name] = idx
|
||||
return idx
|
||||
|
||||
for r in required:
|
||||
if r not in human:
|
||||
ensure(r)
|
||||
log("骨骼:模型缺少 %s,已生成占位骨骼" % r, "warn")
|
||||
added = [r for r in roots if r not in human]
|
||||
for r in added:
|
||||
ensure(r)
|
||||
if added:
|
||||
log("骨骼:拇指只有两节(%s),已在手腕和第二节之间补上掌根那节,0.x 和 1.0 的拇指各节对应一致"
|
||||
% "、".join(added))
|
||||
return human
|
||||
|
||||
def lower_hips(self, human, log):
|
||||
"""hips 放到骨盆(大腿根往上一点),不和 spine 重合。
|
||||
|
||||
MMD 的「下半身」「上半身」从腰部同一点出发,映射成 hips / spine 后两者几乎重合(0~5 mm),
|
||||
hips 也比大腿根高出一截。按 hips → spine 的距离生成躯干碰撞体的程序(游戏布娃娃)会
|
||||
得到长度为 0 的一段。VRoid 的 hips 在大腿根往上约 43%(到 spine 的高度差)处。
|
||||
只改节点位置:子节点的局部偏移、逆绑定矩阵都按世界坐标算,网格和权重不受影响。
|
||||
"""
|
||||
if not all(k in human for k in ("hips", "spine", "leftUpperLeg", "rightUpperLeg")):
|
||||
return
|
||||
h, s = human["hips"], human["spine"]
|
||||
leg_y = (self.wpos[human["leftUpperLeg"]][1] + self.wpos[human["rightUpperLeg"]][1]) * 0.5
|
||||
gap = self.wpos[s][1] - leg_y
|
||||
# MMD 模型实测 0~5 mm(不到高度差的 5%);正常绑定的 FBX 等 hips 本来就在骨盆,
|
||||
# 离 spine 有高度差的 20% 以上,不动
|
||||
if gap <= 0.02 or self.wpos[s][1] - self.wpos[h][1] >= 0.1 * gap:
|
||||
return
|
||||
old = self.wpos[h]
|
||||
self.wpos[h] = (old[0], leg_y + 0.43 * gap, old[2])
|
||||
log("hips:已移至骨盆,下移 %.1f cm(原与 spine 相距 %.1f mm)"
|
||||
% ((old[1] - self.wpos[h][1]) * 100, abs(self.wpos[s][1] - old[1]) * 1000))
|
||||
|
||||
def prune(self, core, collapse=False):
|
||||
"""只留 core 里的节点和连接它们所需的祖先,其余(IK、合并掉的付与骨、末端骨等)删掉。
|
||||
|
||||
collapse:祖先也不留——没有权重的中间节点(MMD 的 全ての親 / センター / グルーブ / 腰 / 肩P 之类)
|
||||
一并去掉,子节点挂到最近的保留祖先上,层级像 VRoid(Root > Hips)。
|
||||
节点位置是世界坐标,删掉中间节点不改变其余节点的位置。返回 旧序号 → 新序号(删掉的不在里面)。
|
||||
"""
|
||||
keep = set(core)
|
||||
if not collapse:
|
||||
for n in core:
|
||||
p = self.parent[n]
|
||||
while p is not None and p not in keep:
|
||||
keep.add(p)
|
||||
p = self.parent[p]
|
||||
order = [i for i in range(len(self.names)) if i in keep]
|
||||
new = {o: k for k, o in enumerate(order)}
|
||||
|
||||
def up(i):
|
||||
p = self.parent[i]
|
||||
while p is not None and p not in new:
|
||||
p = self.parent[p]
|
||||
return None if p is None else new[p]
|
||||
|
||||
self.parent = [up(i) for i in order]
|
||||
self.names = [self.names[i] for i in order]
|
||||
self.wpos = [self.wpos[i] for i in order]
|
||||
self._of_bone = [new.get(n) for n in self._of_bone]
|
||||
self._name_set = None
|
||||
return new
|
||||
|
||||
def gltf_nodes(self):
|
||||
"""→ (glTF nodes 列表, 没有父节点的节点序号)。translation 按父节点换算成局部值。"""
|
||||
nodes = []
|
||||
top = []
|
||||
for i, nm in enumerate(self.names):
|
||||
p = self.parent[i]
|
||||
base = self.wpos[p] if p is not None else (0.0, 0.0, 0.0)
|
||||
nodes.append({"name": nm,
|
||||
"translation": [self.wpos[i][j] - base[j] for j in range(3)]})
|
||||
for i, p in enumerate(self.parent):
|
||||
if p is not None:
|
||||
nodes[p].setdefault("children", []).append(i)
|
||||
else:
|
||||
top.append(i)
|
||||
return nodes, top
|
||||
@@ -0,0 +1,612 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""PMX 刚体物理 → VRMC_springBone(VRM 1.0)。"""
|
||||
import math
|
||||
|
||||
from .mathutil import _I3, _m3mul, _m3vec
|
||||
|
||||
|
||||
_TORSO = {"hips", "spine", "chest", "upperChest"}
|
||||
_ARM_PARTS = ("Shoulder", "Arm", "Hand", "Thumb", "Index", "Middle", "Ring", "Little")
|
||||
_LEG_PARTS = ("Leg", "Foot", "Toes")
|
||||
|
||||
|
||||
def _limb_of(role):
|
||||
"""humanoid 骨位 → (侧, "arm"/"leg");不是四肢返回 None。"""
|
||||
for side in ("left", "right"):
|
||||
if role and role.startswith(side):
|
||||
if any(k in role for k in _ARM_PARTS):
|
||||
return side, "arm"
|
||||
if any(k in role for k in _LEG_PARTS):
|
||||
return side, "leg"
|
||||
return None
|
||||
|
||||
|
||||
def _euler_yxz(r):
|
||||
"""PMX 刚体旋转(弧度,DirectX 的 Yaw-Pitch-Roll)→ 3x3 矩阵 Ry·Rx·Rz。"""
|
||||
cx, sx = math.cos(r[0]), math.sin(r[0])
|
||||
cy, sy = math.cos(r[1]), math.sin(r[1])
|
||||
cz, sz = math.cos(r[2]), math.sin(r[2])
|
||||
rx = (1.0, 0.0, 0.0, 0.0, cx, -sx, 0.0, sx, cx)
|
||||
ry = (cy, 0.0, sy, 0.0, 1.0, 0.0, -sy, 0.0, cy)
|
||||
rz = (cz, -sz, 0.0, sz, cz, 0.0, 0.0, 0.0, 1.0)
|
||||
return _m3mul(_m3mul(ry, rx), rz)
|
||||
|
||||
|
||||
def _rigid_shape(rb, glob):
|
||||
"""刚体 → (中心, 半径, 半长轴向量),都在 PMX 坐标(T-pose 之后)。
|
||||
|
||||
球:半长轴为 0;胶囊:沿局部 Y,size = (半径, 圆柱长度);
|
||||
盒:近似成沿最长轴的胶囊,半径取另外两轴半长的平均。
|
||||
"""
|
||||
rot = _euler_yxz(rb["rot"])
|
||||
sx, sy, sz = rb["size"]
|
||||
shape = rb["shape"]
|
||||
if shape == 0:
|
||||
r, half = sx, (0.0, 0.0, 0.0)
|
||||
elif shape == 2:
|
||||
ax = (rot[1], rot[4], rot[7])
|
||||
r = sx
|
||||
half = tuple(ax[k] * sy * 0.5 for k in range(3))
|
||||
else:
|
||||
ext = (sx, sy, sz)
|
||||
k = max(range(3), key=lambda i: ext[i])
|
||||
others = [ext[i] for i in range(3) if i != k]
|
||||
r = sum(others) / 2.0
|
||||
ax = (rot[k], rot[3 + k], rot[6 + k])
|
||||
hl = max(0.0, ext[k] - r)
|
||||
half = tuple(ax[j] * hl for j in range(3))
|
||||
c = rb["pos"]
|
||||
g = glob.get(rb["bone"]) if glob else None
|
||||
if g:
|
||||
m, t = g
|
||||
q = _m3vec(m, c)
|
||||
c = (q[0] + t[0], q[1] + t[1], q[2] + t[2])
|
||||
half = _m3vec(m, half)
|
||||
return c, r, half
|
||||
|
||||
|
||||
def _build_springs(model, parents, alias, human_b, glob, bpos, scale, xf,
|
||||
bone_node, node_pos, add_node, include_lower=True,
|
||||
stiffness_mul=1.0, gravity=0.0, gravity_lower=0.1,
|
||||
seg_min=0.12, seg_min_lower=0.05, omega=0.15, omega_lower=2.0,
|
||||
drag=0.6, drag_lower=0.6, hit_min_lower=0.045,
|
||||
hair_arm_collide=True, stiff_min=2.0, limb_collide=False,
|
||||
gravity_limb=None, omega_max=None, min_chain_len=0.05,
|
||||
drag_limb=None, omega_max_lower=None, limb_min_len=0.12,
|
||||
stiff_max=10.0, shrink_leg_col=True, omega_limb=0.5,
|
||||
set_parent=None, cloth=None, leg_proxy=True, leg_proxy_max=1.0, leg_proxy_grid=0.005,
|
||||
log=None):
|
||||
"""PMX 刚体物理 → VRMC_springBone(VRM 1.0)。返回扩展 dict 或 None。
|
||||
|
||||
目标是「表现和原生 VRM 一致」,参数按 VRoid / VRM 官方示例模型
|
||||
(AvatarSample_B、VRM1_Constraint_Twist_Sample、Seed-san、Alicia)
|
||||
在同一套动作下的实测表现校准(见 docs/pmx-to-vrm.md)。
|
||||
|
||||
* 挂了物理刚体(mode 1/2)的骨 = 要模拟的骨;humanoid 骨和已并入付与親的
|
||||
骨不参与。从「自己要动、父骨不动」的骨开始沿子骨走成链;分叉处子树最深的
|
||||
一支继续,其余另起一条链。
|
||||
* **抽稀**:MMD 物理链切得很细(后发 1.2 m 分 24 节),原生 VRM 的发束是
|
||||
3~7 节、每节 7~15 cm。离上一个关节不到 seg_min(头发等 12 cm)的骨不做
|
||||
关节,刚性跟随上一个关节;相邻关节随后改挂成直接父子(set_parent)——
|
||||
规范虽允许隔代,three-vrm 却按「子关节相对直接父节点的位置」取静止方向,
|
||||
隔代的链在拐弯处第一帧就会被转开。
|
||||
裙摆(下半身)只并掉 seg_min_lower(5 cm)以内的:SpringBone 只在关节点
|
||||
检测碰撞,节太稀大腿会从关节之间穿过去。
|
||||
* **硬度按「每帧回正角度」换算**:stiffness 的单位是每秒移动的米数,不随节长
|
||||
缩放,同样的值在短节上力量大得多。stiffness = ω × 节长 × 60,
|
||||
头发等 ω=0.15(原生发束约 0.1~0.25 rad/帧),裙摆 ω=2.0(密集节需要更硬
|
||||
才能撑住长裙、少穿模)。以前「按节数放大硬度」让长发的回正力是原生的
|
||||
10~20 倍,每帧拉过头再被惯性甩回,就是肉眼看到的抖动(抖动/形变比约为
|
||||
原生的 2 倍)。
|
||||
* 硬度下限 stiff_min=2.0:原生模型的硬度基本是绝对值 0.5~4、和节长无关;
|
||||
只按角度换算的话 3 cm 的胸部物理骨硬度只有 0.25,走路时整个翻过去。
|
||||
上限 stiff_max=10:翅膀、长飘带的最后一节很长,按角度换算会到 50 以上。
|
||||
* dragForce 都是 0.6。重力:头发等 0(加了会把散开的发型拉垂);
|
||||
裙摆 gravity_lower=0.1,抬腿时裙片落回腿上而不是悬在侧面。
|
||||
* 裙摆类 = 挂在 hips 上的链,以及挂在躯干上、垂到胯部以下的链。挂在腿/脚上的
|
||||
(鞋带、腿环)是四肢配饰,和手臂上的一样处理。
|
||||
* 四肢配饰:不足 limb_min_len(12 cm)的不做 SpringBone(四肢动得快,弹簧追不上,
|
||||
只会在末端颤);不碰自己那条手臂/腿的碰撞体;手臂上的链完全不碰撞——T-pose 下
|
||||
它们跟着手臂转了,动画放下手臂后静止方向指向身体,碰撞会把它们卡在另一侧来回翻。
|
||||
手臂上的链(袖子)硬度单独按 omega_limb=0.5 换算:手臂是全身摆得最快的部位,
|
||||
按头发的 0.15 换算时长袖跑步时末端颤动是头发的 5~8 倍,0.5 时降到 1/3~1/4,
|
||||
仍有明显摆动(0.8 就几乎僵住了)。
|
||||
* center(在 convert 里设为模型根节点):人物整体移动时弹簧不被甩。
|
||||
* 碰撞体 ← 跟随骨骼的刚体(mode 0);按 PMX 碰撞组/掩码决定每条链和哪些碰撞体
|
||||
碰撞。头发也碰手臂(和 VRoid 一致,放下手臂时不会穿过头发)。
|
||||
hitRadius ← 刚体半径,裙摆不小于 hit_min_lower(4.5 cm);静止时确实贴着
|
||||
碰撞体的那几节缩到刚好不重叠(可低于下限,否则开始模拟就被推开,
|
||||
长裙从根部被撬开)。某节尾端在静止时就落在碰撞体里的,整条链不与它碰撞;
|
||||
例外是裙摆和大腿:PMX 的大腿刚体常比腿粗,贴腿的短裙静止时就在里面,
|
||||
这时给该链另配一个缩小到刚好让开的同位置碰撞体,而不是让腿完全拦不住裙片。
|
||||
* PMX 里链与链之间的横向关节(裙摆常见)在 VRM 里无法表达,舍弃。近似:裙摆链碰到的腿部
|
||||
胶囊换成按裙片朝向平移过的副本(leg_proxy,见 leg_proxy_shift),腿不再把相邻两条链分到两边。
|
||||
cloth = (顶点法线, 顶点权重, xf_dir),用来算裙片朝向;不给就不做这一步。
|
||||
"""
|
||||
def _log(msg, tag=None):
|
||||
if log:
|
||||
log(msg, tag)
|
||||
|
||||
bones = model["bones"]
|
||||
rbs = model.get("rigid_bodies") or []
|
||||
joints = model.get("joints") or []
|
||||
nb = len(bones)
|
||||
if not rbs or not nb:
|
||||
return None
|
||||
human_set = set(human_b.values())
|
||||
vrm_of = {v: k for k, v in human_b.items()}
|
||||
|
||||
dyn = {} # 骨 → 刚体序号
|
||||
for ri, rb in enumerate(rbs):
|
||||
b = rb["bone"]
|
||||
if rb["mode"] in (1, 2) and 0 <= b < nb and b not in alias \
|
||||
and b not in human_set and b not in dyn:
|
||||
dyn[b] = ri
|
||||
if not dyn:
|
||||
return None
|
||||
|
||||
children = [[] for _ in range(nb)]
|
||||
for i, p in enumerate(parents):
|
||||
if 0 <= p < nb:
|
||||
children[p].append(i)
|
||||
|
||||
def anchor(b):
|
||||
"""最近的 humanoid 祖先骨位名。"""
|
||||
p = parents[b]
|
||||
seen = set()
|
||||
while p >= 0 and p not in seen:
|
||||
if p in vrm_of:
|
||||
return vrm_of[p]
|
||||
seen.add(p)
|
||||
p = parents[p]
|
||||
return None
|
||||
|
||||
depth_memo = {}
|
||||
|
||||
def dyn_depth(b):
|
||||
if b not in depth_memo:
|
||||
depth_memo[b] = 1 + max([dyn_depth(c) for c in children[b]
|
||||
if c in dyn] or [0])
|
||||
return depth_memo[b]
|
||||
|
||||
# ---- 拆链
|
||||
hips_y = bpos[human_b["hips"]][1] if "hips" in human_b else None
|
||||
roots = [b for b in range(nb) if b in dyn and parents[b] not in dyn]
|
||||
pending = list(roots)
|
||||
chains = [] # [(骨列表, 类别)]
|
||||
used = set()
|
||||
skipped_lower = 0
|
||||
while pending:
|
||||
r = pending.pop(0)
|
||||
if r in used:
|
||||
continue
|
||||
cat = anchor(r)
|
||||
# 裙摆类只算挂在 hips 上的链(以及下面挂在躯干上、垂到胯部以下的)。
|
||||
# 挂在腿/脚上的是配饰(鞋带、腿环、脚踝蝴蝶结),不能按裙摆的高硬度处理——
|
||||
# 它们跟着动得最快的腿脚走,实测开拓者的鞋带跑步时末端颤动是全身最高
|
||||
lower = cat == "hips"
|
||||
chain = [r]
|
||||
used.add(r)
|
||||
cur = r
|
||||
while True:
|
||||
kids = sorted([c for c in children[cur] if c in dyn and c not in used],
|
||||
key=lambda c: -dyn_depth(c))
|
||||
if not kids:
|
||||
break
|
||||
pending.extend(kids[1:])
|
||||
cur = kids[0]
|
||||
chain.append(cur)
|
||||
used.add(cur)
|
||||
# 挂在躯干上、但垂到胯部以下的链(侧面裙片、腰后飘带)也按裙摆处理:
|
||||
# 它们和腿有碰撞关系,需要密集关节、重力和足够的碰撞半径。
|
||||
# 以前只看挂点,挂在上半身1 上的裙片被当成头发(稀、软、无重力),
|
||||
# 抬腿时被大腿横推出去悬在侧面
|
||||
if not lower and cat in _TORSO and hips_y is not None \
|
||||
and min(bpos[b][1] for b in chain) < hips_y:
|
||||
lower = True
|
||||
if lower and not include_lower:
|
||||
skipped_lower += 1
|
||||
continue
|
||||
chains.append((chain, lower))
|
||||
|
||||
# ---- 关节参数
|
||||
joint_of = {} # 刚体 → 连接父刚体的 PMX 关节
|
||||
for j in joints:
|
||||
a, b = j["rb_a"], j["rb_b"]
|
||||
if 0 <= b < len(rbs) and 0 <= a < len(rbs):
|
||||
ba, bb = rbs[a]["bone"], rbs[b]["bone"]
|
||||
if 0 <= bb < nb and parents[bb] == ba:
|
||||
joint_of.setdefault(b, j)
|
||||
for j in joints: # 没有严格父子关系的就退而求其次
|
||||
b = j["rb_b"]
|
||||
if 0 <= b < len(rbs):
|
||||
joint_of.setdefault(b, j)
|
||||
|
||||
def _stiff(w, length, lower=False):
|
||||
s_ = max(w * length * 60.0, stiff_min)
|
||||
cap = omega_max_lower if lower else omega_max
|
||||
if cap is not None:
|
||||
s_ = min(s_, cap * length * 60.0)
|
||||
# 绝对上限:裙摆的回正角度是按 5 cm 左右的密集短节定的,遇到很长的一节
|
||||
# (翅膀、长飘带的最后一节)会算出 50 以上,一样会每帧拉过头
|
||||
return min(s_, stiff_max)
|
||||
|
||||
def seg_params(seg, length, lower, arm):
|
||||
"""一节(seg = 这一节包含的骨,第一个是关节骨)的 SpringBone 参数。
|
||||
arm = 挂在手臂上的链(袖子、手肘吊坠),可单独设 omega/gravity/drag_limb。"""
|
||||
w = omega_lower if lower else omega
|
||||
if arm and omega_limb is not None:
|
||||
w = omega_limb
|
||||
g = gravity_lower if lower else gravity
|
||||
if arm and gravity_limb is not None:
|
||||
g = gravity_limb
|
||||
d = drag_lower if lower else drag
|
||||
if arm and drag_limb is not None:
|
||||
d = drag_limb
|
||||
rad = max(_rigid_shape(rbs[dyn[b]], None)[1] for b in seg) * scale
|
||||
rad = min(0.05, max(hit_min_lower if lower else 0.01, rad))
|
||||
return {"hitRadius": round(rad, 5),
|
||||
"stiffness": round(_stiff(w, length, lower) * stiffness_mul, 4),
|
||||
"gravityPower": g,
|
||||
"gravityDir": [0.0, -1.0, 0.0],
|
||||
"dragForce": d}
|
||||
|
||||
def tail_pos(b):
|
||||
"""链尾没有可用子骨时,造一个 tail 的位置(PMX 坐标)。"""
|
||||
bb = bones[b]
|
||||
lin = glob[b][0] if glob else _I3
|
||||
if bb["tail_kind"] == 0:
|
||||
off = bb["tail"]
|
||||
if sum(x * x for x in off) > 1e-8:
|
||||
o = _m3vec(lin, off)
|
||||
return tuple(bpos[b][k] + o[k] for k in range(3))
|
||||
elif 0 <= bb["tail"] < nb and bb["tail"] != b:
|
||||
q = bpos[bb["tail"]]
|
||||
if sum((q[k] - bpos[b][k]) ** 2 for k in range(3)) > 1e-8:
|
||||
return q
|
||||
p = parents[b]
|
||||
if p >= 0:
|
||||
d = [bpos[b][k] - bpos[p][k] for k in range(3)]
|
||||
if sum(x * x for x in d) > 1e-8:
|
||||
return tuple(bpos[b][k] + d[k] * 0.5 for k in range(3))
|
||||
return (bpos[b][0], bpos[b][1] - 0.5, bpos[b][2])
|
||||
|
||||
# ---- 碰撞体(跟随骨骼的刚体)
|
||||
colliders = []
|
||||
col_meta = [] # (group, mask)
|
||||
col_world = [] # (端点 a, 端点 b 或 None, 半径),VRM 坐标
|
||||
col_role = [] # 碰撞体所在骨的 humanoid 骨位(没有为空)
|
||||
for rb in rbs:
|
||||
b = rb["bone"]
|
||||
if rb["mode"] != 0 or not (0 <= b < nb):
|
||||
continue
|
||||
b = alias.get(b, b) # 挂在 足D 上的刚体改挂到 足
|
||||
node = bone_node(b)
|
||||
if node is None:
|
||||
continue
|
||||
c, r, half = _rigid_shape(rb, glob)
|
||||
base = node_pos(node)
|
||||
if sum(x * x for x in half) < 1e-12:
|
||||
p0 = xf(c)
|
||||
shape = {"sphere": {"offset": [p0[k] - base[k] for k in range(3)],
|
||||
"radius": r * scale}}
|
||||
col_world.append((p0, None, r * scale))
|
||||
else:
|
||||
p0 = xf(tuple(c[k] - half[k] for k in range(3)))
|
||||
p1 = xf(tuple(c[k] + half[k] for k in range(3)))
|
||||
shape = {"capsule": {"offset": [p0[k] - base[k] for k in range(3)],
|
||||
"radius": r * scale,
|
||||
"tail": [p1[k] - base[k] for k in range(3)]}}
|
||||
col_world.append((p0, p1, r * scale))
|
||||
colliders.append({"node": node, "shape": shape})
|
||||
col_meta.append((rb["group"], rb["mask"]))
|
||||
col_role.append(vrm_of.get(b, ""))
|
||||
|
||||
group_cache = {}
|
||||
collider_groups = []
|
||||
|
||||
n_pmx_cols = len(colliders)
|
||||
|
||||
def mask_ids(rb):
|
||||
"""按 PMX 碰撞组/掩码,该动态刚体能碰到的碰撞体(双方掩码都允许)。"""
|
||||
g, m = rb["group"], rb["mask"]
|
||||
return [i for i, (cg, cm) in enumerate(col_meta[:n_pmx_cols])
|
||||
if (m >> cg) & 1 and (cm >> g) & 1]
|
||||
|
||||
shrunk_cache = {}
|
||||
|
||||
def shrunk_collider(ci, r):
|
||||
"""碰撞体 ci 的缩小半径副本(同节点、同位置),相近半径的共用一个。
|
||||
半径向下取到 5 mm 的整数倍:向上取整会吃掉让开静止裙片的余量。"""
|
||||
key = (ci, math.floor(r * 200.0) / 200.0)
|
||||
if key not in shrunk_cache:
|
||||
shape = {k: dict(v) for k, v in colliders[ci]["shape"].items()}
|
||||
for v in shape.values():
|
||||
v["radius"] = key[1]
|
||||
colliders.append({"node": colliders[ci]["node"], "shape": shape})
|
||||
col_meta.append(col_meta[ci])
|
||||
col_world.append(col_world[ci][:2] + (key[1],))
|
||||
col_role.append(col_role[ci])
|
||||
shrunk_cache[key] = len(colliders) - 1
|
||||
return shrunk_cache[key]
|
||||
|
||||
moved_cache = {}
|
||||
|
||||
def moved_collider(ci, t):
|
||||
"""碰撞体 ci 平移 t(VRM 坐标)的副本,挂在同一节点上;平移量按 leg_proxy_grid 取整共用。"""
|
||||
t = tuple(round(x / leg_proxy_grid) * leg_proxy_grid for x in t)
|
||||
key = (ci, t)
|
||||
if key not in moved_cache:
|
||||
shape = {k: dict(v) for k, v in colliders[ci]["shape"].items()}
|
||||
for v in shape.values():
|
||||
for f in ("offset", "tail"):
|
||||
if f in v:
|
||||
v[f] = [v[f][k] + t[k] for k in range(3)]
|
||||
colliders.append({"node": colliders[ci]["node"], "shape": shape})
|
||||
col_meta.append(col_meta[ci])
|
||||
a, b, r = col_world[ci]
|
||||
col_world.append((tuple(a[k] + t[k] for k in range(3)),
|
||||
None if b is None else tuple(b[k] + t[k] for k in range(3)), r))
|
||||
col_role.append(col_role[ci])
|
||||
moved_cache[key] = len(colliders) - 1
|
||||
return moved_cache[key]
|
||||
|
||||
# ---- 裙片朝向:挂在链上的顶点法线的主方向(单双面都行:n 和 -n 贡献相同)
|
||||
cov = {} # 骨 → Σ w·n·nᵀ(VRM 坐标,6 个分量)
|
||||
if cloth and leg_proxy:
|
||||
vnrm, vweights, xf_dir = cloth
|
||||
want = {b for chain, lower in chains if lower for b in chain}
|
||||
for n, wl in zip(vnrm, vweights):
|
||||
for b, w in wl:
|
||||
if b in want and w > 0.3:
|
||||
x, y, z = xf_dir(n)
|
||||
c = cov.setdefault(b, [0.0] * 6)
|
||||
for k, v in enumerate((x * x, y * y, z * z, x * y, x * z, y * z)):
|
||||
c[k] += w * v
|
||||
|
||||
def cloth_normal(chain, guess):
|
||||
"""链上裙片的水平法线(单位向量,方向未定);顶点太少或裙片接近水平时 None。"""
|
||||
c = [0.0] * 6
|
||||
for b in chain:
|
||||
for k, v in enumerate(cov.get(b, ())):
|
||||
c[k] += v
|
||||
if c[0] + c[1] + c[2] < 1.0:
|
||||
return None
|
||||
m = (c[0], c[3], c[4], c[3], c[1], c[5], c[4], c[5], c[2])
|
||||
v = guess
|
||||
for _ in range(30): # 幂迭代求主特征向量
|
||||
v = _m3vec(m, v)
|
||||
s = math.sqrt(sum(x * x for x in v)) or 1.0
|
||||
v = tuple(x / s for x in v)
|
||||
h = math.hypot(v[0], v[2])
|
||||
if h < 0.6:
|
||||
return None
|
||||
return (v[0] / h, 0.0, v[2] / h)
|
||||
|
||||
def leg_proxy_shift(ci, pts, normal):
|
||||
"""裙摆链 × 腿部胶囊:把腿平移到「静止时从裙片法线方向正对这条链」的位置。
|
||||
|
||||
SpringBone 把关节沿「腿轴 → 关节」的方向推出去。腿正好落在两条相邻链之间时
|
||||
(大腿后摆碰后裙片),两条链被推向相反的两侧,裙子从中间劈开——MMD 里链间的
|
||||
横向关节会把它们拉在一起,整片往后推。这里给每条链单独一份平移过的腿:
|
||||
静止时离链的距离不变,但接触方向变成裙片法线,被推时整片沿法线方向走。
|
||||
平移量不超过腿半径 × leg_proxy_max,不然真正的腿会从让出来的那一侧穿过裙子。"""
|
||||
a, b, r = col_world[ci]
|
||||
best = None
|
||||
for q in pts:
|
||||
ab = [b[k] - a[k] for k in range(3)]
|
||||
l2 = sum(x * x for x in ab) or 1e-12
|
||||
t = min(1.0, max(0.0, sum((q[k] - a[k]) * ab[k] for k in range(3)) / l2))
|
||||
l_ = [a[k] + ab[k] * t for k in range(3)]
|
||||
d = math.dist(q, l_)
|
||||
if best is None or d < best[0]:
|
||||
best = (d, q, l_)
|
||||
_, q, l_ = best
|
||||
vh = (q[0] - l_[0], 0.0, q[2] - l_[2])
|
||||
m = math.hypot(vh[0], vh[2])
|
||||
if m < 1e-6:
|
||||
return None
|
||||
n = normal if normal[0] * vh[0] + normal[2] * vh[2] >= 0 else tuple(-x for x in normal)
|
||||
t = [vh[k] - n[k] * m for k in range(3)]
|
||||
tl = math.hypot(t[0], t[2])
|
||||
cap = r * leg_proxy_max
|
||||
if tl > cap:
|
||||
t = [x * cap / tl for x in t]
|
||||
return t if min(tl, cap) >= 0.005 else None
|
||||
|
||||
def clearance(pt, ci):
|
||||
"""点到碰撞体表面的距离(负数 = 在碰撞体内部)。"""
|
||||
a, b, r = col_world[ci]
|
||||
if b is None:
|
||||
q = a
|
||||
else:
|
||||
ab = [b[k] - a[k] for k in range(3)]
|
||||
l2 = sum(x * x for x in ab) or 1e-12
|
||||
t = sum((pt[k] - a[k]) * ab[k] for k in range(3)) / l2
|
||||
t = min(1.0, max(0.0, t))
|
||||
q = [a[k] + ab[k] * t for k in range(3)]
|
||||
return math.sqrt(sum((pt[k] - q[k]) ** 2 for k in range(3))) - r
|
||||
|
||||
def groups_for(ids):
|
||||
"""碰撞体集合 → colliderGroups 索引列表(相同集合共用一个组)。"""
|
||||
ids = tuple(sorted(ids))
|
||||
if not ids:
|
||||
return []
|
||||
if ids not in group_cache:
|
||||
group_cache[ids] = len(collider_groups)
|
||||
collider_groups.append({"name": "pmx_collision_%d" % len(collider_groups),
|
||||
"colliders": list(ids)})
|
||||
return [group_cache[ids]]
|
||||
|
||||
# ---- 写 springs
|
||||
springs = []
|
||||
n_virtual = 0
|
||||
n_dropped = [0]
|
||||
n_shrunk = [0]
|
||||
n_tiny = [0]
|
||||
n_proxy = [0]
|
||||
n_joints_mmd = n_joints_vrm = n_lower = 0
|
||||
for chain, lower in chains:
|
||||
last = chain[-1]
|
||||
real = [c for c in children[last]
|
||||
if c not in dyn and c not in human_set and c not in alias]
|
||||
tpos = node_pos(bone_node(real[0])) if real else xf(tail_pos(last))
|
||||
pos = {b: xf(bpos[b]) for b in chain}
|
||||
anc = anchor(chain[0]) or ""
|
||||
limb = _limb_of(anc)
|
||||
# 过短的链(3 cm 的胸部物理骨之类)只会高频颤动、看不出有意义的摆动,不做 SpringBone。
|
||||
# 挂在手臂/腿上的短配饰(手肘吊坠、鞋带、脚踝蝴蝶结)门槛更高:四肢动得快,
|
||||
# 弹簧追不上就在末端来回颤(实测是全身颤动最大的部位),不如跟着骨骼刚性移动
|
||||
length = math.dist(pos[last], tpos) + sum(
|
||||
math.dist(pos[a], pos[b]) for a, b in zip(chain, chain[1:]))
|
||||
if length < (max(min_chain_len, limb_min_len) if limb else min_chain_len):
|
||||
n_tiny[0] += 1
|
||||
continue
|
||||
if real:
|
||||
tnode = bone_node(real[0])
|
||||
else:
|
||||
tnode = add_node((bones[last]["name"] or "bone") + "_tail", bone_node(last), tpos)
|
||||
n_virtual += 1
|
||||
# 抽稀:离上一个关节不到 seg_min 的骨不做关节(刚性跟随上一个关节)
|
||||
smin = seg_min_lower if lower else seg_min
|
||||
# 自动补出来的兽耳链每节只有 2~3 cm,按头发的 12 cm 抽稀会只剩「根骨 + 末端」,
|
||||
# 整只耳朵变成一块刚性板。按链长自适应把各节都留住;只作用于自动生成的刚体,
|
||||
# 不动 MMD 原生物理和其它模型的头发。
|
||||
nm0 = (bones[chain[0]]["name"] or "").lower()
|
||||
if len(chain) >= 3 and rbs[dyn[chain[0]]].get("name", "").startswith("auto_") \
|
||||
and ("ear" in nm0 or "耳" in nm0 or "mimi" in nm0):
|
||||
span = sum(math.dist(pos[a], pos[b]) for a, b in zip(chain, chain[1:]))
|
||||
if span > 0:
|
||||
smin = min(smin, span / len(chain) * 0.9)
|
||||
kept = [chain[0]]
|
||||
for b in chain[1:]:
|
||||
if math.dist(pos[b], pos[kept[-1]]) >= smin:
|
||||
kept.append(b)
|
||||
if len(kept) > 1 and math.dist(pos[kept[-1]], tpos) < smin * 0.5:
|
||||
kept.pop() # 最后一节太短:并进上一节
|
||||
n_joints_mmd += len(chain)
|
||||
n_joints_vrm += len(kept)
|
||||
idx = [chain.index(b) for b in kept] + [len(chain)]
|
||||
arm = bool(limb) and limb[1] == "arm"
|
||||
pts = [pos[b] for b in kept] + [tpos]
|
||||
js = []
|
||||
for i, b in enumerate(kept):
|
||||
jt = seg_params(chain[idx[i]:idx[i + 1]], math.dist(pts[i], pts[i + 1]), lower, arm)
|
||||
jt["node"] = bone_node(b)
|
||||
js.append(jt)
|
||||
tj = dict(js[-1])
|
||||
tj["node"] = tnode
|
||||
js.append(tj)
|
||||
# 相邻关节改成直接父子(世界位置不变,被跳过的中间骨仍挂在原处、刚性跟随)。
|
||||
# 规范允许关节隔代,但 three-vrm 取「子关节相对它直接父节点的位置」当静止方向,
|
||||
# 隔代时链在拐弯处(前裙片转到侧裙片)第一帧就被转开,实测末端偏 24 cm
|
||||
if set_parent is not None:
|
||||
for a_, b_ in zip(js, js[1:]):
|
||||
set_parent(b_["node"], a_["node"])
|
||||
# 碰撞体:PMX 掩码允许的。挂在四肢上的链不碰同一条手臂/腿的碰撞体(本来就跟着它动,
|
||||
# 碰撞只会在手臂快速转动时——比如动画第一帧从 T-pose 放下——把链甩到碰撞体另一侧
|
||||
# 卡住,表现为配饰整个翻过去、一直抖);手臂上的链默认完全不碰撞(limb_collide)。
|
||||
on_head = anc in ("head", "neck", "jaw", "leftEye", "rightEye")
|
||||
normal = None
|
||||
if lower and not limb and cov:
|
||||
mid = pts[len(pts) // 2]
|
||||
hp = xf(bpos[human_b["hips"]]) if "hips" in human_b else (0.0, 0.0, 0.0)
|
||||
normal = cloth_normal(chain, (mid[0] - hp[0] + 1e-3, 0.0, mid[2] - hp[2]))
|
||||
ids = []
|
||||
for ci in ([] if arm and not limb_collide else mask_ids(rbs[dyn[chain[0]]])):
|
||||
role = col_role[ci]
|
||||
if limb and _limb_of(role) == limb:
|
||||
continue
|
||||
if on_head and not hair_arm_collide and (_limb_of(role) or ("", ""))[1] == "arm":
|
||||
continue
|
||||
if normal and ("UpperLeg" in role or "LowerLeg" in role) and col_world[ci][1] is not None:
|
||||
t = leg_proxy_shift(ci, pts[1:], normal)
|
||||
if t:
|
||||
ci = moved_collider(ci, t)
|
||||
n_proxy[0] += 1
|
||||
# 只看各节尾端(pts[1:]):SpringBone 用「这一节的 hitRadius、在尾端位置」检测,
|
||||
# 链根钉在父骨上,埋在碰撞体里也不会被推
|
||||
minc = min(clearance(pt, ci) for pt in pts[1:])
|
||||
if minc > 0.0:
|
||||
ids.append(ci)
|
||||
continue
|
||||
# 贴腿的短裙:PMX 的大腿刚体常比腿粗,静止时裙片就在里面。整个舍弃的话
|
||||
# 这条腿完全拦不住裙片(实测穗穗走路时 4.2% 的裙摆关节进了腿里,缩小后 1.7%),
|
||||
# 所以给这条链另配一个缩小到刚好让开静止裙片的同位置碰撞体
|
||||
r0 = col_world[ci][2]
|
||||
r1 = r0 + minc - 0.005
|
||||
if shrink_leg_col and lower and "UpperLeg" in role and r1 >= max(0.02, r0 * 0.4):
|
||||
ids.append(shrunk_collider(ci, r1))
|
||||
else:
|
||||
n_dropped[0] += 1
|
||||
# 只缩静止时确实贴着碰撞体的那几节(可以低于下限);其余节保持足够的
|
||||
# 碰撞半径。不能用「一律不低于下限」——贴着胯部的那几节会在开始模拟时
|
||||
# 被推开,长裙从根部被撬开,末端偏出 30 cm 以上
|
||||
for i, jt in enumerate(js[:-1]):
|
||||
for ci in ids:
|
||||
c = clearance(pts[i + 1], ci)
|
||||
if c < jt["hitRadius"]:
|
||||
jt["hitRadius"] = round(max(0.002, c * 0.9), 5)
|
||||
n_shrunk[0] += 1
|
||||
js[-1]["hitRadius"] = js[-2]["hitRadius"]
|
||||
n_lower += lower
|
||||
sp = {"name": bones[chain[0]]["name"] or ("spring%d" % len(springs)),
|
||||
"joints": js}
|
||||
cg = groups_for(ids)
|
||||
if cg:
|
||||
sp["colliderGroups"] = cg
|
||||
springs.append(sp)
|
||||
|
||||
if not springs:
|
||||
if skipped_lower:
|
||||
_log("SpringBone:按设置跳过 %d 条下半身物理链,没有可输出的链"
|
||||
% skipped_lower)
|
||||
return None
|
||||
# 平移 / 缩小出来的碰撞体里,有些随后又被它自己的缩小副本取代、没有组在用:删掉并重排序号
|
||||
used = {ci for g in collider_groups for ci in g["colliders"]}
|
||||
keep = [ci for ci in range(len(colliders)) if ci < n_pmx_cols or ci in used]
|
||||
if len(keep) < len(colliders):
|
||||
remap = {ci: k for k, ci in enumerate(keep)}
|
||||
colliders = [colliders[ci] for ci in keep]
|
||||
for g in collider_groups:
|
||||
g["colliders"] = [remap[ci] for ci in g["colliders"]]
|
||||
_log("SpringBone:%d 条链(裙摆类 %d、头发等 %d)· 碰撞体 %d · 碰撞组 %d"
|
||||
% (len(springs), n_lower, len(springs) - n_lower, len(colliders),
|
||||
len(collider_groups)))
|
||||
if skipped_lower:
|
||||
_log("SpringBone:按设置跳过 %d 条下半身物理链(裙摆等)" % skipped_lower)
|
||||
if n_tiny[0]:
|
||||
_log("SpringBone:%d 条短链(不足 %.0f cm,四肢上不足 %.0f cm)不转换,以免末端高频抖动"
|
||||
% (n_tiny[0], min_chain_len * 100, limb_min_len * 100))
|
||||
_log("SpringBone:MMD 物理骨 %d 根 → SpringBone 关节 %d 个(头发等每节至少 %.0f cm、"
|
||||
"裙摆至少 %.0f cm,中间的骨骼刚性跟随)"
|
||||
% (n_joints_mmd, n_joints_vrm, seg_min * 100, seg_min_lower * 100))
|
||||
if n_virtual:
|
||||
_log("SpringBone:%d 条链的末端没有子骨骼,已补充末端节点" % n_virtual)
|
||||
fixes = []
|
||||
if n_dropped[0]:
|
||||
fixes.append("取消 %d 处链与碰撞体的碰撞" % n_dropped[0])
|
||||
if n_shrunk[0]:
|
||||
fixes.append("缩小 %d 个节点的碰撞半径" % n_shrunk[0])
|
||||
if fixes:
|
||||
_log("SpringBone:静止姿势下与碰撞体重叠,已" + "、".join(fixes))
|
||||
cross = 0
|
||||
for j in joints:
|
||||
a, b = j["rb_a"], j["rb_b"]
|
||||
if 0 <= a < len(rbs) and 0 <= b < len(rbs):
|
||||
ba, bb = rbs[a]["bone"], rbs[b]["bone"]
|
||||
if ba in dyn and bb in dyn and 0 <= ba < nb and 0 <= bb < nb \
|
||||
and parents[bb] != ba and parents[ba] != bb:
|
||||
cross += 1
|
||||
if cross:
|
||||
_log("SpringBone:%d 个链间横向关节(裙摆等)无法表达,已舍弃%s"
|
||||
% (cross, ";已按裙片朝向修正 %d 处裙摆与腿的碰撞方向,减少裙片被腿分开"
|
||||
% n_proxy[0] if n_proxy[0] else ""), "warn")
|
||||
elif n_proxy[0]:
|
||||
_log("SpringBone:已按裙片朝向修正 %d 处裙摆与腿的碰撞方向" % n_proxy[0])
|
||||
ext = {"specVersion": "1.0", "springs": springs}
|
||||
if colliders:
|
||||
ext["colliders"] = colliders
|
||||
if collider_groups:
|
||||
ext["colliderGroups"] = collider_groups
|
||||
return ext
|
||||
@@ -0,0 +1,242 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""VRM 0.x 的 SpringBone(secondaryAnimation):由 springbone._build_springs 算好的 1.0 结构换算。
|
||||
|
||||
参数换算、碰撞关系、裙摆处理只在 1.0 那边维护一份,这里只处理两种结构的差别:
|
||||
|
||||
* 0.x 的 boneGroups.bones 只列根骨,**整棵子树都参与模拟**,每节的方向取它的第一个子节点
|
||||
(three-vrm 的 _v0Import、UniVRM、Blender 官方插件都是这样读的)。1.0 里有些骨只是跟着
|
||||
上一个关节刚性转动(抽稀掉的短节、链末端的配饰),照搬过去会全变成摆动骨。
|
||||
fold():把这些骨的权重并到最近的摆动关节上、子节点改挂过去,再由 _prune_nodes 删掉——
|
||||
它们在 1.0 里本来就随那个关节刚性转动,效果完全一样。尾节点留下当不带权重的叶子。
|
||||
order_children():每个关节的下一节排在第一个子节点。
|
||||
* 同一节点落在两个组的子树里会被模拟两次:从别的链上分叉出来的链并入上层链的组;
|
||||
组内的碰撞体按关节数多数决定。
|
||||
* 参数是每组一套:硬度 / 重力 / 阻尼取组内中位数(同一条链内本来就几乎一样);碰撞半径也取
|
||||
中位数,静止时会和碰撞体重叠的,给这一组配一个缩小的碰撞体副本(缩不下去才取消这处碰撞)。
|
||||
取最小值的话,1.0 里为贴着腿、贴着衣服单独缩小过的那几节会让整条链都几乎不碰撞,
|
||||
反过来不缩小碰撞体的话飘带一开始模拟就被推开 3~4 cm。
|
||||
* 碰撞体只有球:胶囊沿轴线每隔一个半径放一个球(两球之间最窄处是半径的 0.87 倍;
|
||||
更密的球实测效果差不多,球数却翻倍)。offset 是 Unity 坐标,Z 和 glTF 相反。
|
||||
* 参数相同的链也不合并成一组:调整页按组调参数、开关,一组一条链才对得上。
|
||||
* 硬度的键名是规范里拼错的 stiffiness。
|
||||
"""
|
||||
import math
|
||||
import statistics
|
||||
|
||||
|
||||
def _joint_sets(spring_ext):
|
||||
"""→ (模拟的关节节点, 尾节点, 关节 → 链上的下一节)。"""
|
||||
sim, tails, nxt = set(), set(), {}
|
||||
for sp in spring_ext["springs"]:
|
||||
js = [j["node"] for j in sp["joints"]]
|
||||
sim.update(js[:-1])
|
||||
tails.add(js[-1])
|
||||
for a, b in zip(js, js[1:]):
|
||||
nxt[a] = b
|
||||
return sim, tails, nxt
|
||||
|
||||
|
||||
def _sim_ancestor(parent_of, sim, x):
|
||||
p = parent_of(x)
|
||||
seen = set()
|
||||
while p is not None and p not in sim and p not in seen:
|
||||
seen.add(p)
|
||||
p = parent_of(p)
|
||||
return p if p in sim else None
|
||||
|
||||
|
||||
def fold(tree, bones, vweights, spring_ext, keep_nodes, log=None):
|
||||
"""组根子树里不是摆动关节的节点:权重并到最近的摆动关节、子节点改挂过去。返回新的 vweights。
|
||||
|
||||
在 _prune_nodes 之前调用(节点号是 tree 的)。keep_nodes:不动的节点(humanoid 骨)。
|
||||
"""
|
||||
sim, tails, _ = _joint_sets(spring_ext)
|
||||
par = tree.parent
|
||||
kids = [[] for _ in par]
|
||||
for i, p in enumerate(par):
|
||||
if p is not None:
|
||||
kids[p].append(i)
|
||||
up = lambda x: par[x] # noqa: E731
|
||||
roots = [sp["joints"][0]["node"] for sp in spring_ext["springs"]]
|
||||
tops = [r for r in roots if _sim_ancestor(up, sim, r) is None]
|
||||
sub, stack = set(), list(tops)
|
||||
while stack:
|
||||
x = stack.pop()
|
||||
if x not in sub:
|
||||
sub.add(x)
|
||||
stack.extend(kids[x])
|
||||
target = {} # 节点 → 并到哪个关节
|
||||
for x in sub - sim - set(keep_nodes):
|
||||
a = _sim_ancestor(up, sim, x)
|
||||
if a is not None:
|
||||
target[x] = a
|
||||
remove = {x for x in target if x not in tails}
|
||||
|
||||
bone_of = {}
|
||||
for b in range(len(bones)):
|
||||
n = tree.bone_node(b)
|
||||
if n is not None:
|
||||
bone_of.setdefault(n, b)
|
||||
bmap = {}
|
||||
for b in range(len(bones)):
|
||||
n = tree.bone_node(b)
|
||||
if n in target and target[n] in bone_of:
|
||||
bmap[b] = bone_of[target[n]]
|
||||
out, n_verts = [], 0
|
||||
for wl in vweights:
|
||||
if not any(b in bmap and w > 0 for b, w in wl):
|
||||
out.append(wl)
|
||||
continue
|
||||
n_verts += 1
|
||||
acc = {}
|
||||
for b, w in wl:
|
||||
b = bmap.get(b, b)
|
||||
acc[b] = acc.get(b, 0.0) + w
|
||||
out.append(sorted(acc.items(), key=lambda t: -t[1]))
|
||||
|
||||
for x in range(len(par)):
|
||||
if par[x] in remove and x not in remove:
|
||||
tree.set_parent(x, target[par[x]])
|
||||
for c in spring_ext.get("colliders", []):
|
||||
if c["node"] in remove:
|
||||
a = target[c["node"]]
|
||||
d = [tree.wpos[c["node"]][k] - tree.wpos[a][k] for k in range(3)]
|
||||
for v in c["shape"].values():
|
||||
for f in ("offset", "tail"):
|
||||
if f in v:
|
||||
v[f] = [v[f][k] + d[k] for k in range(3)]
|
||||
c["node"] = a
|
||||
if log and (remove or bmap):
|
||||
log("SpringBone(0.x):%d 根随关节刚性转动的骨(中间节、链末端的配饰)权重并到关节上(%d 个顶点),"
|
||||
"0.x 会让组里所有子骨都摆动" % (len(bmap), n_verts))
|
||||
return out
|
||||
|
||||
|
||||
def order_children(nodes, spring_ext):
|
||||
"""每个关节的下一节放到 children[0]:0.x 按第一个子节点定这一节的方向。"""
|
||||
_, _, nxt = _joint_sets(spring_ext)
|
||||
for a, b in nxt.items():
|
||||
ch = nodes[a].get("children") or []
|
||||
if b in ch and ch[0] != b:
|
||||
ch.remove(b)
|
||||
ch.insert(0, b)
|
||||
|
||||
|
||||
def _world(nodes):
|
||||
parent = {}
|
||||
for i, nd in enumerate(nodes):
|
||||
for c in nd.get("children", ()):
|
||||
parent[c] = i
|
||||
memo = {}
|
||||
|
||||
def pos(i):
|
||||
if i not in memo:
|
||||
t = nodes[i].get("translation") or [0.0, 0.0, 0.0]
|
||||
p = parent.get(i)
|
||||
memo[i] = tuple(t) if p is None else tuple(pos(p)[k] + t[k] for k in range(3))
|
||||
return memo[i]
|
||||
return pos, parent
|
||||
|
||||
|
||||
def spheres(shape):
|
||||
"""1.0 的碰撞形状 → [(offset, radius)](glTF 局部坐标)。胶囊沿轴线每隔一个半径放一个球。"""
|
||||
if "sphere" in shape:
|
||||
s = shape["sphere"]
|
||||
return [(tuple(s["offset"]), s["radius"])]
|
||||
c = shape["capsule"]
|
||||
a, b, r = c["offset"], c["tail"], c["radius"]
|
||||
n = max(2, int(math.ceil(math.dist(a, b) / max(r, 1e-4))) + 1)
|
||||
return [(tuple(a[k] + (b[k] - a[k]) * i / (n - 1) for k in range(3)), r) for i in range(n)]
|
||||
|
||||
|
||||
def _v3(v):
|
||||
"""glTF → 0.x 的 {x, y, z}(Unity 坐标:Z 取反)。"""
|
||||
return {"x": round(v[0], 6), "y": round(v[1], 6), "z": round(-v[2], 6) or 0.0}
|
||||
|
||||
|
||||
def to_secondary(spring_ext, nodes, center=None, log=None):
|
||||
"""1.0 的 VRMC_springBone(节点号已是最终的)→ 0.x 的 secondaryAnimation。"""
|
||||
pos, parent = _world(nodes)
|
||||
sim, _, _ = _joint_sets(spring_ext)
|
||||
cols = spring_ext.get("colliders", [])
|
||||
cgs = spring_ext.get("colliderGroups", [])
|
||||
sph = [spheres(c["shape"]) for c in cols]
|
||||
|
||||
groups = {} # 顶层根 → [spring]
|
||||
for sp in spring_ext["springs"]:
|
||||
t = sp["joints"][0]["node"]
|
||||
while True:
|
||||
a = _sim_ancestor(parent.get, sim, t)
|
||||
if a is None:
|
||||
break
|
||||
t = a
|
||||
groups.setdefault(t, []).append(sp)
|
||||
|
||||
v0_groups, v0_key = [], {}
|
||||
|
||||
def collider_group(ci, radius=None):
|
||||
key = (ci, None if radius is None else round(radius, 5))
|
||||
if key not in v0_key:
|
||||
v0_key[key] = len(v0_groups)
|
||||
v0_groups.append({"node": cols[ci]["node"], "colliders": [
|
||||
{"offset": _v3(o), "radius": round(r if radius is None else radius, 5)}
|
||||
for o, r in sph[ci]]})
|
||||
return v0_key[key]
|
||||
|
||||
def clearance(p, ci):
|
||||
base = pos(cols[ci]["node"])
|
||||
return min(math.dist(p, [base[k] + o[k] for k in range(3)]) - r for o, r in sph[ci])
|
||||
|
||||
bone_groups = []
|
||||
n_shrunk = n_dropped = 0
|
||||
for top, sps in groups.items():
|
||||
js = [j for sp in sps for j in sp["joints"][:-1]]
|
||||
tips = [pos(j["node"]) for sp in sps for j in sp["joints"][1:]]
|
||||
|
||||
def med(k, d):
|
||||
return statistics.median(j.get(k, d) for j in js)
|
||||
hit = med("hitRadius", 0.0)
|
||||
# 分叉链并进来以后整组只能共用一套碰撞体:按关节数多数决定(组内至少一半的关节在 1.0 里
|
||||
# 碰它才保留)。取并集的话,挂在长发上的一个小坠子(MMD 里和全身都碰)会让整条长发也去碰
|
||||
# 腿和手臂,实测摆幅只剩一半
|
||||
votes = {}
|
||||
for sp in sps:
|
||||
for ci in {ci for g in sp.get("colliderGroups", ()) for ci in cgs[g]["colliders"]}:
|
||||
votes[ci] = votes.get(ci, 0) + len(sp["joints"]) - 1
|
||||
ids = []
|
||||
for ci in sorted(votes):
|
||||
if votes[ci] * 2 < len(js):
|
||||
continue
|
||||
gap = min(clearance(p, ci) for p in tips)
|
||||
if gap >= hit:
|
||||
ids.append(collider_group(ci))
|
||||
continue
|
||||
r0 = sph[ci][0][1]
|
||||
r1 = r0 - (hit - gap) - 0.002
|
||||
if r1 >= max(0.01, r0 * 0.4):
|
||||
ids.append(collider_group(ci, r1))
|
||||
n_shrunk += 1
|
||||
else:
|
||||
n_dropped += 1
|
||||
gd = js[0].get("gravityDir", [0.0, -1.0, 0.0])
|
||||
bone_groups.append({
|
||||
"comment": sps[0].get("name") or "spring%d" % len(bone_groups),
|
||||
"stiffiness": round(med("stiffness", 1.0), 4),
|
||||
"gravityPower": round(med("gravityPower", 0.0), 4),
|
||||
"gravityDir": _v3(gd),
|
||||
"dragForce": round(med("dragForce", 0.5), 4),
|
||||
"center": -1 if center is None else center,
|
||||
"hitRadius": round(hit, 5),
|
||||
"bones": [top],
|
||||
"colliderGroups": sorted(set(ids)),
|
||||
})
|
||||
if log:
|
||||
n_nested = len(spring_ext["springs"]) - len(groups)
|
||||
log("SpringBone(0.x):%d 条链 → %d 个摆动组%s · 碰撞组 %d(胶囊换成 %d 个球)"
|
||||
% (len(spring_ext["springs"]), len(bone_groups),
|
||||
"(%d 条分叉链并入上层链的组)" % n_nested if n_nested else "",
|
||||
len(v0_groups), sum(len(g["colliders"]) for g in v0_groups)))
|
||||
if n_shrunk or n_dropped:
|
||||
log("SpringBone(0.x):每组只有一个碰撞半径,静止时会重叠的碰撞体缩小 %d 处、取消 %d 处"
|
||||
% (n_shrunk, n_dropped))
|
||||
return {"boneGroups": bone_groups, "colliderGroups": v0_groups}
|
||||
@@ -0,0 +1,94 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""贴图瘦身:限制最大边长、不透明贴图改存 JPEG。
|
||||
|
||||
HoYo 系 PMX 的贴图常是 2K~4K 的 PNG,原样塞进 VRM 文件动辄上百 MB,游戏导入和加载都慢。
|
||||
缩放和 JPEG 编码要用 Pillow(可选依赖);没装 Pillow 时原样返回,转换照常进行。
|
||||
|
||||
只有完全不透明的贴图才转 JPEG:带透明通道的(头发高光、睫毛、镂空)JPEG 存不了 alpha。
|
||||
"""
|
||||
import io
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError: # 纯标准库环境:不瘦身
|
||||
Image = None
|
||||
|
||||
JPEG_QUALITY = 90
|
||||
|
||||
|
||||
def available():
|
||||
return Image is not None
|
||||
|
||||
|
||||
class Optimizer:
|
||||
"""max_size:最大边长(0 = 不缩放);jpeg:不透明贴图改存 JPEG。统计在 before / after / changed。"""
|
||||
|
||||
def __init__(self, max_size=0, jpeg=False):
|
||||
self.max_size = int(max_size or 0)
|
||||
self.jpeg = bool(jpeg)
|
||||
self.before = self.after = self.changed = 0
|
||||
|
||||
@property
|
||||
def active(self):
|
||||
return Image is not None and (self.max_size > 0 or self.jpeg)
|
||||
|
||||
def __call__(self, data, mime):
|
||||
"""→ (data, mime)。处理失败或没变小时返回原数据。"""
|
||||
return self.account(data, self.process(data, mime))
|
||||
|
||||
def process(self, data, mime):
|
||||
"""只做处理、不计数(几张贴图可以在不同线程里同时处理),计数交给 account。"""
|
||||
if self.active:
|
||||
try:
|
||||
return self._process(data, mime)
|
||||
except Exception: # noqa: BLE001 坏图 / 不支持的格式:原样用
|
||||
pass
|
||||
return data, mime
|
||||
|
||||
def account(self, data, out):
|
||||
"""把一张贴图 data → out(process 的结果)记进统计,返回 out。"""
|
||||
self.before += len(data)
|
||||
self.after += len(out[0])
|
||||
if out[0] is not data:
|
||||
self.changed += 1
|
||||
return out
|
||||
|
||||
def _process(self, data, mime):
|
||||
im = Image.open(io.BytesIO(data))
|
||||
im.load()
|
||||
w, h = im.size
|
||||
resized = False
|
||||
if self.max_size and max(w, h) > self.max_size:
|
||||
k = self.max_size / float(max(w, h))
|
||||
if im.mode not in ("RGB", "RGBA", "L", "LA"):
|
||||
im = im.convert("RGBA")
|
||||
im = im.resize((max(1, round(w * k)), max(1, round(h * k))), Image.LANCZOS)
|
||||
resized = True
|
||||
opaque = True
|
||||
if im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info):
|
||||
a = im.convert("RGBA").getchannel("A")
|
||||
opaque = a.getextrema()[0] >= 255
|
||||
if self.jpeg and opaque:
|
||||
buf = io.BytesIO()
|
||||
# 4:4:4 不做色度抽样:二次元贴图的细线和色块边缘抽样后会发糊、渗色
|
||||
im.convert("RGB").save(buf, "JPEG", quality=JPEG_QUALITY, subsampling=0, optimize=True)
|
||||
if resized or buf.tell() < len(data):
|
||||
return buf.getvalue(), "image/jpeg"
|
||||
if not resized:
|
||||
return data, mime
|
||||
buf = io.BytesIO()
|
||||
if mime == "image/jpeg" and opaque:
|
||||
im.convert("RGB").save(buf, "JPEG", quality=JPEG_QUALITY, subsampling=0, optimize=True)
|
||||
return buf.getvalue(), "image/jpeg"
|
||||
if opaque and im.mode == "RGBA":
|
||||
im = im.convert("RGB")
|
||||
im.save(buf, "PNG", optimize=True)
|
||||
return buf.getvalue(), "image/png"
|
||||
|
||||
def summary(self):
|
||||
if not self.changed:
|
||||
return None
|
||||
return "贴图:%d 张瘦身(%s%s)%.1f MB → %.1f MB" % (
|
||||
self.changed, ("最大边长 %d" % self.max_size) if self.max_size else "",
|
||||
("、" if self.max_size and self.jpeg else "") + ("不透明转 JPEG" if self.jpeg else ""),
|
||||
self.before / 1048576.0, self.after / 1048576.0)
|
||||
@@ -0,0 +1,129 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""VRM 扩展本体:VRM 1.0 的 VRMC_vrm、VRM 0.x 的 VRM(meta / humanoid / firstPerson / lookAt / 表情)。"""
|
||||
|
||||
|
||||
def _look_deg(look):
|
||||
"""视线最大转角(morphbake.eye_look_range 的结果;没有时左右上下都 10°)。"""
|
||||
return look or {"lookLeft": 10.0, "lookRight": 10.0, "lookDown": 10.0, "lookUp": 10.0}
|
||||
|
||||
|
||||
def _degmap(xr, yr):
|
||||
return {"curve": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0],
|
||||
"xRange": xr, "yRange": yr}
|
||||
|
||||
|
||||
def _pick(meta, key, allowed, default):
|
||||
v = meta.get(key)
|
||||
return v if v in allowed else default
|
||||
|
||||
|
||||
def build_vrm1(meta, title, human, mesh_nodes, expr, look=None):
|
||||
"""VRMC_vrm。meta:用户给的作者 / 许可等;expr:expressions.build_expressions 的结果;mesh_nodes:网格节点。
|
||||
|
||||
默认值和以前一致:谁都可以「扮演」(avatarPermission=everyone,不然有的应用拒绝加载),
|
||||
其余取保守值(仅个人非商用、禁止再分发和修改、要求署名)——转换的大多是别人的模型,
|
||||
放宽要由用户在界面里明确选。
|
||||
"""
|
||||
author = meta.get("author") or ""
|
||||
vrm_ext = {
|
||||
"specVersion": "1.0",
|
||||
"humanoid": {"humanBones": {k: {"node": v}
|
||||
for k, v in human.items()}},
|
||||
"meta": {
|
||||
"name": title,
|
||||
"version": meta.get("version") or "1",
|
||||
"authors": [author] if author else ["unknown"],
|
||||
"copyrightInformation": meta.get("copyright") or "",
|
||||
"contactInformation": meta.get("contact") or "",
|
||||
"thirdPartyLicenses": "",
|
||||
# thumbnailImage 规范要求是图片索引(整数);没有缩略图就不写,
|
||||
# 写 null 过不了 VRM 1.0 schema 校验。缩略图由 vrm_edit 写入。
|
||||
"licenseUrl": meta.get("license_url") or "https://vrm.dev/licenses/1.0/",
|
||||
"avatarPermission": _pick(meta, "avatar_permission",
|
||||
("onlyAuthor", "onlySeparatelyLicensedPerson", "everyone"),
|
||||
"everyone"),
|
||||
"allowExcessivelyViolentUsage": False,
|
||||
"allowExcessivelySexualUsage": False,
|
||||
"commercialUsage": _pick(meta, "commercial_usage",
|
||||
("personalNonProfit", "personalProfit", "corporation"),
|
||||
"personalNonProfit"),
|
||||
"allowPoliticalOrReligiousUsage": False,
|
||||
"allowAntisocialOrHateUsage": False,
|
||||
"creditNotation": _pick(meta, "credit_notation", ("required", "unnecessary"), "required"),
|
||||
"allowRedistribution": bool(meta.get("allow_redistribution", False)),
|
||||
"modification": _pick(meta, "modification",
|
||||
("prohibited", "allowModification", "allowModificationRedistribution"),
|
||||
"prohibited"),
|
||||
},
|
||||
"firstPerson": {"meshAnnotations": [{"node": n, "type": "auto"} for n in mesh_nodes]},
|
||||
}
|
||||
if expr["preset"] or expr["custom"]:
|
||||
vrm_ext["expressions"] = {}
|
||||
if expr["preset"]:
|
||||
vrm_ext["expressions"]["preset"] = expr["preset"]
|
||||
if expr["custom"]:
|
||||
vrm_ext["expressions"]["custom"] = expr["custom"]
|
||||
if "leftEye" in human or "rightEye" in human:
|
||||
d = _look_deg(look)
|
||||
vrm_ext["lookAt"] = {
|
||||
"type": "bone",
|
||||
"offsetFromHeadBone": [0.0, 0.06, 0.0],
|
||||
"rangeMapHorizontalInner": {"inputMaxValue": 90.0, "outputScale": d["lookLeft"]},
|
||||
"rangeMapHorizontalOuter": {"inputMaxValue": 90.0, "outputScale": d["lookLeft"]},
|
||||
"rangeMapVerticalDown": {"inputMaxValue": 90.0, "outputScale": d["lookDown"]},
|
||||
"rangeMapVerticalUp": {"inputMaxValue": 90.0, "outputScale": d["lookUp"]},
|
||||
}
|
||||
return vrm_ext
|
||||
|
||||
|
||||
def build_vrm0(meta, title, human, expr, material_props, look=None, n_meshes=1, secondary=None):
|
||||
"""VRM 0.x 的 VRM 扩展。material_props:materials.MaterialBuilder.props_0x;
|
||||
secondary:springbone_v0.to_secondary 的结果(没有物理时 None)。"""
|
||||
return {
|
||||
"exporterVersion": "VRMify Enhanced",
|
||||
"specVersion": "0.0",
|
||||
"meta": {
|
||||
"title": title,
|
||||
"version": meta.get("version") or "1",
|
||||
"author": meta.get("author") or "",
|
||||
"contactInformation": meta.get("contact") or "",
|
||||
"reference": "",
|
||||
"allowedUserName": {"everyone": "Everyone",
|
||||
"onlySeparatelyLicensedPerson": "ExplicitlyLicensedPerson",
|
||||
"onlyAuthor": "OnlyAuthor"}.get(
|
||||
meta.get("avatar_permission"), "Everyone"),
|
||||
"violentUssageName": "Disallow",
|
||||
"sexualUssageName": "Disallow",
|
||||
"commercialUssageName": ("Allow" if meta.get("commercial_usage") in
|
||||
("personalProfit", "corporation") else "Disallow"),
|
||||
"otherPermissionUrl": "",
|
||||
# 0.x 只有 licenseName 这一项能表达再分发:没给许可链接时按「是否允许再分发」选,
|
||||
# 给了链接就是 Other + 链接(作者 / 改编 / 署名之类的条件写在链接的文档里)
|
||||
"licenseName": ("Other" if meta.get("license_url") or meta.get("allow_redistribution")
|
||||
else "Redistribution_Prohibited"),
|
||||
"otherLicenseUrl": meta.get("license_url") or "",
|
||||
},
|
||||
"humanoid": {
|
||||
"humanBones": [{"bone": k, "node": v, "useDefaultValues": True}
|
||||
for k, v in human.items()],
|
||||
"armStretch": 0.05, "legStretch": 0.05,
|
||||
"upperArmTwist": 0.5, "lowerArmTwist": 0.5,
|
||||
"upperLegTwist": 0.5, "lowerLegTwist": 0.5,
|
||||
"feetSpacing": 0.0, "hasTranslationDoF": False,
|
||||
},
|
||||
"firstPerson": {
|
||||
"firstPersonBone": human.get("head", 0),
|
||||
"firstPersonBoneOffset": {"x": 0.0, "y": 0.06, "z": 0.0},
|
||||
"meshAnnotations": [{"firstPersonFlag": "Auto", "mesh": k} for k in range(n_meshes)],
|
||||
"lookAtTypeName": ("Bone" if ("leftEye" in human or
|
||||
"rightEye" in human)
|
||||
else "BlendShape"),
|
||||
"lookAtHorizontalInner": _degmap(90, _look_deg(look)["lookLeft"]),
|
||||
"lookAtHorizontalOuter": _degmap(90, _look_deg(look)["lookLeft"]),
|
||||
"lookAtVerticalDown": _degmap(90, _look_deg(look)["lookDown"]),
|
||||
"lookAtVerticalUp": _degmap(90, _look_deg(look)["lookUp"]),
|
||||
},
|
||||
"blendShapeMaster": {"blendShapeGroups": expr["blend_groups"]},
|
||||
"secondaryAnimation": secondary or {"boneGroups": [], "colliderGroups": []},
|
||||
"materialProperties": material_props,
|
||||
}
|
||||
@@ -0,0 +1,759 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XPS / XNALara → MMD PMX,纯 Python 标准库。
|
||||
|
||||
和项目里其它转换器保持同一套口径(换轴 → 归一到 20 单位 → 居中 → 骨骼转
|
||||
MMD 标准日文名 → 材质按名字找贴图),差别只在本格式的坐标系:
|
||||
|
||||
换轴
|
||||
----
|
||||
实测样本(轩辕剑柒 chu hong):
|
||||
`head eyeball left` 在 +X、`head eyeball right` 在 -X → XPS 的 +X = **左**
|
||||
`head nose tip` z=1.030 > 头根 z=0.925,
|
||||
`leg left toes` z=0.974 > 脚踝 z=0.879 → XPS 的 +Z = **正面**
|
||||
`root ground` 在 y=0、头顶 y≈1.71 → XPS 的 +Y = **上**
|
||||
也就是「左手 +X、正面 +Z、上 +Y」的右手系。
|
||||
|
||||
MMD/PMX 的约定是「左手 +X、正面 -Z、上 +Y」(见 psk2pmx.py 里同一段推导)。
|
||||
两边只差**一个 Z 的符号**,所以:
|
||||
|
||||
(x, y, z)_xps → (x, y, -z)_pmx
|
||||
|
||||
这是**一次反射**(行列式 -1,右手系 → MMD 的左手系),几何绕序会跟着翻,
|
||||
所以绕序要么按法线投票自动判、要么在没法线时一律反转 —— 见下面「绕序」段。
|
||||
|
||||
注意**不能**照抄 uemodel2pmx 的 (x, z, -y),也不能照抄 psk2pmx 的 (x, z, y):
|
||||
那两个是给各自格式准备的,套到 XPS 上会把人物转成躺倒或背对镜头。
|
||||
|
||||
骨骼
|
||||
----
|
||||
XPS 的骨名是英文描述式(`spine lower` / `arm left elbow` / `leg right knee`),
|
||||
按规则转成 MMD 标准日文名,英文原名写进 PMX 的 name_en 字段,两边都不丢。
|
||||
以 `unused ` 开头的占位骨(XNALara 用来标记「不在姿势界面显示」的骨)默认
|
||||
保留在骨架里(权重可能引用它们,删了会破面),但放进独立的「unused」表示枠,
|
||||
免得主枠里 100 多根骨挤成一团。
|
||||
|
||||
贴图
|
||||
----
|
||||
XPS 每个网格带一组贴图,第 0 个是漫反射(实测样本 4 张一组时顺序是
|
||||
`_d / _l / _n / _s`)。贴图原样拷进输出目录的 `textures/`。**不去 alpha** ——
|
||||
XPS 的 alpha 就是头发/睫毛的透明度(和 UE 的「alpha 是数据遮罩」正好相反),
|
||||
去掉的话头发会变成实心板。DDS 也照拷:MMD 官方支持 .dds 贴图(见 VPVP wiki
|
||||
的「拡張子」表),不需要转码。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
for _sub in ("formats", "convert"):
|
||||
_p = os.path.join(BASE, _sub)
|
||||
if os.path.isdir(_p) and _p not in sys.path:
|
||||
sys.path.insert(0, _p)
|
||||
|
||||
import xpsio
|
||||
import pmxio
|
||||
|
||||
# toon 一律不使用:唯一正确的写法是 flag=0 / index=-1(原因见 psk2pmx.py 顶部)
|
||||
_TOON_NONE_FLAG = 0
|
||||
_TOON_NONE_INDEX = -1
|
||||
|
||||
_TEX_EXT = (".png", ".bmp", ".tga", ".jpg", ".jpeg", ".dds", ".hdr")
|
||||
|
||||
|
||||
def _log_default(msg, tag=None):
|
||||
print(msg)
|
||||
|
||||
|
||||
# ------------------------------------------------------------- 骨名映射 ------
|
||||
# XPS 的骨名是英文描述式,先按「整名」查表,再按「部位 + 左右」规则拆。
|
||||
_SIDE_JP = {"left": "左", "right": "右", "l": "左", "r": "右",
|
||||
"lt": "左", "rt": "右"}
|
||||
|
||||
# 主干(整名精确匹配,小写、空格归一化后比对)
|
||||
_EXACT = {
|
||||
"root ground": "全ての親",
|
||||
"root": "全ての親",
|
||||
"root hips": "センター",
|
||||
"root pelvis": "センター",
|
||||
"hips": "センター",
|
||||
"pelvis": "センター",
|
||||
"spine lower": "上半身",
|
||||
"spine": "上半身",
|
||||
"spine middle": "上半身2",
|
||||
"chest": "上半身2",
|
||||
"head neck lower": "首",
|
||||
"neck": "首",
|
||||
"head neck upper": "頭",
|
||||
"head": "頭",
|
||||
}
|
||||
|
||||
# 部位关键词 → MMD 骨名(不带左右)
|
||||
_PART = {
|
||||
"shoulder": "肩",
|
||||
"clavicle": "肩",
|
||||
"upperarm": "腕",
|
||||
"upper arm": "腕",
|
||||
"arm": "腕",
|
||||
"forearm": "ひじ",
|
||||
"elbow": "ひじ",
|
||||
"wrist": "手首",
|
||||
"hand": "手首",
|
||||
"thigh": "足",
|
||||
"upper leg": "足",
|
||||
"upperleg": "足",
|
||||
"knee": "ひざ",
|
||||
"shin": "ひざ",
|
||||
"calf": "ひざ",
|
||||
"ankle": "足首",
|
||||
"foot": "足首",
|
||||
"toes": "つま先",
|
||||
"toe": "つま先",
|
||||
}
|
||||
|
||||
# 手指:XPS 的 finger 1..5,其中 1 是拇指(实测「arm left finger 1a」相对
|
||||
# 其余四指在 Y 上明显错开,是拇指的特征)。段号 a/b/c → 0/1/2。
|
||||
_FINGER_JP = {1: "親指", 2: "人指", 3: "中指", 4: "薬指", 5: "小指"}
|
||||
_FW = ("0", "1", "2", "3", "4", "5")
|
||||
_FINGER_RE = re.compile(r"^(?:arm|hand)?\s*([lr]|left|right)[\s_-]*"
|
||||
r"(?:finger|thumb|index|middle|ring|pinky|little)"
|
||||
r"[\s_-]*(\d)([a-d]?)$")
|
||||
|
||||
|
||||
def _norm(name):
|
||||
"""骨名归一化:小写、下划线/连字符→空格、压缩空格。"""
|
||||
s = (name or "").strip().lower()
|
||||
s = s.replace("_", " ").replace("-", " ").replace(".", " ")
|
||||
return " ".join(s.split())
|
||||
|
||||
|
||||
def bone_jp(name):
|
||||
"""XPS 骨名 → MMD 日文名;没有对应条目返回 None(调用方保留原名)。"""
|
||||
n = _norm(name)
|
||||
if not n:
|
||||
return None
|
||||
if n in _EXACT:
|
||||
return _EXACT[n]
|
||||
if n.startswith("unused"):
|
||||
return None # 占位骨不映射
|
||||
|
||||
# 手指:arm left finger 2b / l finger 3a ...
|
||||
m = _FINGER_RE.match(n)
|
||||
if m:
|
||||
side, finger, seg = m.group(1), int(m.group(2)), m.group(3)
|
||||
jp = _FINGER_JP.get(finger)
|
||||
if jp and side in _SIDE_JP:
|
||||
# 拇指从 0 起,其余四指从 1 起(MMD 标准骨名惯例)
|
||||
base = 0 if finger == 1 else 1
|
||||
idx = base + (ord(seg) - ord("a") if seg else 0)
|
||||
if 0 <= idx < len(_FW):
|
||||
return "%s%s%s" % (_SIDE_JP[side], jp, _FW[idx])
|
||||
return None
|
||||
|
||||
# 眼珠:head eyeball left / left eye ...
|
||||
if "eyeball" in n or n.endswith(" eye") or n == "eye":
|
||||
side = None
|
||||
for tok in n.split():
|
||||
if tok in _SIDE_JP:
|
||||
side = _SIDE_JP[tok]
|
||||
if side:
|
||||
return side + "目"
|
||||
return None
|
||||
|
||||
# 四肢:arm left elbow / leg right knee / left upper arm ...
|
||||
side = None
|
||||
for tok in n.split():
|
||||
if tok in _SIDE_JP:
|
||||
side = _SIDE_JP[tok]
|
||||
break
|
||||
if not side:
|
||||
return None
|
||||
body = " ".join(t for t in n.split() if t not in _SIDE_JP)
|
||||
body = body.replace("arm ", "").replace("leg ", "").strip()
|
||||
if body in _PART:
|
||||
return side + _PART[body]
|
||||
# 带序号的部位:XPS 的 `arm left shoulder 1 / 2` 里 1 是锁骨、2 是大臂
|
||||
m2 = re.match(r"^(.+?)\s*(\d+)$", body)
|
||||
if m2:
|
||||
stem, num = m2.group(1), m2.group(2)
|
||||
if stem == "shoulder":
|
||||
return side + ("肩" if num == "1" else "腕")
|
||||
if stem in _PART:
|
||||
return side + _PART[stem]
|
||||
for key, jp in _PART.items():
|
||||
if body.endswith(key):
|
||||
return side + jp
|
||||
return None
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- 小工具 ----
|
||||
def _uniq(name, used):
|
||||
base = (name or "").strip() or "bone"
|
||||
if base not in used:
|
||||
used.add(base)
|
||||
return base
|
||||
i = 1
|
||||
while "%s_%d" % (base, i) in used:
|
||||
i += 1
|
||||
nm = "%s_%d" % (base, i)
|
||||
used.add(nm)
|
||||
return nm
|
||||
|
||||
|
||||
def _clean_name(name):
|
||||
"""网格名(如 `24_Material25_0.25_0_0`)→ 给 MMD 看的材质名。
|
||||
|
||||
XPS 的网格名常常是「渲染参数 + 材质名 + 一堆数值」拼起来的,末段那些
|
||||
`_0.25_0_0` 是着色器参数,对用户没意义,去掉后更干净;去不干净就原样保留。
|
||||
"""
|
||||
s = (name or "").strip()
|
||||
if not s:
|
||||
return ""
|
||||
m = re.match(r"^\d+_(.+?)(?:_\d+(?:\.\d+)?)+$", s)
|
||||
if m and m.group(1):
|
||||
return m.group(1)
|
||||
return s
|
||||
|
||||
|
||||
def _find_texture(folder, filename):
|
||||
"""按 XPS 里记的贴图名找文件(同目录 + Textures 子目录,大小写不敏感)。"""
|
||||
raw = (filename or "").strip().replace("\\", "/")
|
||||
if not raw:
|
||||
return None
|
||||
base = os.path.basename(raw)
|
||||
if not base:
|
||||
return None
|
||||
dirs = [folder]
|
||||
for sub in ("Textures", "textures", "Texture", "tex"):
|
||||
d = os.path.join(folder, sub)
|
||||
if os.path.isdir(d):
|
||||
dirs.append(d)
|
||||
parent = os.path.dirname(folder)
|
||||
for sub in ("Textures", "textures"):
|
||||
d = os.path.join(parent, sub)
|
||||
if os.path.isdir(d):
|
||||
dirs.append(d)
|
||||
|
||||
# 先按原名精确找
|
||||
for d in dirs:
|
||||
p = os.path.join(d, base)
|
||||
if os.path.isfile(p):
|
||||
return p
|
||||
# 再退一步:同目录(含子目录)里按小写名 + 换扩展名找
|
||||
stem = os.path.splitext(base)[0].lower()
|
||||
for d in dirs:
|
||||
try:
|
||||
for f in os.listdir(d):
|
||||
st, ext = os.path.splitext(f)
|
||||
if ext.lower() in _TEX_EXT and st.lower() == stem:
|
||||
return os.path.join(d, f)
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _copy_tex(src, dst):
|
||||
"""原样拷贴图(XPS 的 alpha 是真正的透明度,不能去)。"""
|
||||
shutil.copyfile(src, dst)
|
||||
return "copied"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- 主体 ----
|
||||
def convert(path, out_path, scale_mode="mmd", log=None, name=None,
|
||||
enable_edge=False, force_double_sided=False, textures=True,
|
||||
center=True, jp_bones=True, make_ik=True, hide_unused=True,
|
||||
all_double_sided=True, fbx_path=None):
|
||||
"""XPS / XNALara → PMX。返回统计 dict。"""
|
||||
_l = log or _log_default
|
||||
|
||||
m = xpsio.read_xps(path, log=_l)
|
||||
kind = "XPS" if m.is_generic2 else "XNALara"
|
||||
if not m.meshes:
|
||||
raise ValueError("此文件中没有网格数据")
|
||||
_l("读取 %s:骨骼 %d 根 · 网格 %d 个 · 顶点 %d · 三角面 %d"
|
||||
% (kind, len(m.bones), len(m.meshes), m.n_vertices, m.n_triangles))
|
||||
|
||||
# ---- 坐标变换:一次 Z 取反(反射),详见文件顶部说明
|
||||
def xf(p):
|
||||
return (p[0], p[1], -p[2])
|
||||
|
||||
# ---- 所有网格的顶点拼在一起(PMX 只有一张顶点表)
|
||||
raw_pos = []
|
||||
raw_nrm = []
|
||||
raw_uv = []
|
||||
raw_w = [] # [(bone_index, weight), ...]
|
||||
mesh_vert_start = [] # 每个网格在顶点表里的起始下标
|
||||
for mesh in m.meshes:
|
||||
mesh_vert_start.append(len(raw_pos))
|
||||
nv = len(mesh.positions)
|
||||
for vi in range(nv):
|
||||
raw_pos.append(mesh.positions[vi])
|
||||
n = mesh.normals[vi]
|
||||
raw_nrm.append(n if n and (n[0] or n[1] or n[2]) else None)
|
||||
raw_uv.append(mesh.uvs[vi] or (0.0, 0.0))
|
||||
idxs = mesh.bone_indices[vi] or ()
|
||||
wts = mesh.bone_weights[vi] or ()
|
||||
w = [(int(b), float(wt)) for b, wt in zip(idxs, wts)
|
||||
if int(b) < len(m.bones) and wt > 1e-6]
|
||||
raw_w.append(w)
|
||||
|
||||
n_vert = len(raw_pos)
|
||||
pts = [xf(p) for p in raw_pos]
|
||||
ys = [p[1] for p in pts]
|
||||
lo_y, hi_y = (min(ys), max(ys)) if ys else (0.0, 1.0)
|
||||
height = max(hi_y - lo_y, 1e-6)
|
||||
|
||||
if scale_mode in ("mmd", "auto", None):
|
||||
scale = 20.0 / height
|
||||
_l("缩放:源高 %.3f 单位 × %.6f → %.2f(MMD 标准身高 20)"
|
||||
% (height, scale, height * scale))
|
||||
elif scale_mode in ("raw", "none", 1, 1.0):
|
||||
scale = 1.0
|
||||
_l("缩放:保持源尺寸(scale=1.0),源高 %.3f 单位" % height)
|
||||
else:
|
||||
scale = float(scale_mode)
|
||||
_l("缩放:源高 %.3f 单位 × %.6f → %.2f"
|
||||
% (height, scale, height * scale))
|
||||
|
||||
if center and pts:
|
||||
xs = [p[0] for p in pts]
|
||||
zs = [p[2] for p in pts]
|
||||
off = (-(min(xs) + max(xs)) * 0.5 * scale,
|
||||
-lo_y * scale,
|
||||
-(min(zs) + max(zs)) * 0.5 * scale)
|
||||
_l("居中:偏移 (%.3f, %.3f, %.3f)" % off, "info")
|
||||
else:
|
||||
off = (0.0, 0.0, 0.0)
|
||||
|
||||
def sp(p):
|
||||
t = xf(p)
|
||||
return (t[0] * scale + off[0], t[1] * scale + off[1],
|
||||
t[2] * scale + off[2])
|
||||
|
||||
def sn(n):
|
||||
"""法线:只换轴(反射会把法线也翻一次,所以 Z 同样取反)。"""
|
||||
t = xf(n)
|
||||
ln = (t[0] ** 2 + t[1] ** 2 + t[2] ** 2) ** 0.5 or 1.0
|
||||
return (t[0] / ln, t[1] / ln, t[2] / ln)
|
||||
|
||||
# ---- 骨骼:世界坐标就是 XPS 里存的位置(不需要累乘父级)
|
||||
bone_pos = [sp(b.position) for b in m.bones]
|
||||
n_src = len(m.bones)
|
||||
|
||||
# ---- 骨骼顺序:DFS,保证父在子前面(PMX 要求父索引 < 子索引)
|
||||
kids = [[] for _ in range(n_src)]
|
||||
roots = []
|
||||
for i, b in enumerate(m.bones):
|
||||
p = b.parent_index
|
||||
if 0 <= p < n_src and p != i:
|
||||
kids[p].append(i)
|
||||
else:
|
||||
roots.append(i)
|
||||
order = []
|
||||
seen = [False] * n_src
|
||||
stack = list(reversed(roots))
|
||||
while stack:
|
||||
i = stack.pop()
|
||||
if seen[i]:
|
||||
continue
|
||||
seen[i] = True
|
||||
order.append(i)
|
||||
stack.extend(reversed(kids[i]))
|
||||
for i in range(n_src):
|
||||
if not seen[i]:
|
||||
seen[i] = True
|
||||
order.append(i)
|
||||
|
||||
slot = {bi: k for k, bi in enumerate(order)}
|
||||
used = set()
|
||||
pmx_bones = []
|
||||
n_renamed = 0
|
||||
n_unused = 0
|
||||
for src in order:
|
||||
b = m.bones[src]
|
||||
jp = bone_jp(b.name) if jp_bones else None
|
||||
main_name = jp if jp else (b.name or "bone")
|
||||
if jp:
|
||||
n_renamed += 1
|
||||
p = b.parent_index if 0 <= b.parent_index < n_src else -1
|
||||
pmx_bones.append({
|
||||
"name": _uniq(main_name, used),
|
||||
"name_en": b.name or "bone",
|
||||
"pos": bone_pos[src],
|
||||
"parent": slot.get(p, -1),
|
||||
"layer": 0, "flag": 0, "tail_kind": 0, "tail": (0.0, 0.0, 0.0),
|
||||
"inherit_rot": None, "inherit_mov": None, "fixed_axis": None,
|
||||
"local_axis": None, "external": None, "ik": None,
|
||||
"_kids": [], "_unused": (b.name or "").lower().startswith("unused"),
|
||||
})
|
||||
for src in order:
|
||||
b = m.bones[src]
|
||||
p = b.parent_index if 0 <= b.parent_index < n_src else -1
|
||||
if p in slot and slot[p] != slot[src]:
|
||||
pmx_bones[slot[p]]["_kids"].append(slot[src])
|
||||
|
||||
for bk in pmx_bones:
|
||||
flag = 0x0002 | 0x0004 | 0x0008 | 0x0010 # 可旋转/可移动/可显示/可操作
|
||||
k = bk.pop("_kids")
|
||||
if bk.pop("_unused"):
|
||||
n_unused += 1
|
||||
bk["_is_unused"] = True
|
||||
else:
|
||||
bk["_is_unused"] = False
|
||||
if k:
|
||||
flag |= 0x0001 # 尾 = 骨骼(取第一个子骨骼)
|
||||
bk["tail_kind"] = 1
|
||||
bk["tail"] = k[0]
|
||||
else:
|
||||
p = bk["parent"]
|
||||
if 0 <= p < len(pmx_bones):
|
||||
d = (bk["pos"][0] - pmx_bones[p]["pos"][0],
|
||||
bk["pos"][1] - pmx_bones[p]["pos"][1],
|
||||
bk["pos"][2] - pmx_bones[p]["pos"][2])
|
||||
ln = (d[0] ** 2 + d[1] ** 2 + d[2] ** 2) ** 0.5
|
||||
bk["tail"] = ((d[0] / ln, d[1] / ln, d[2] / ln) if ln > 1e-9
|
||||
else (0.0, 1.0, 0.0))
|
||||
else:
|
||||
bk["tail"] = (0.0, 1.0, 0.0)
|
||||
bk["flag"] = flag
|
||||
_l("骨骼:%d 根%s%s"
|
||||
% (len(pmx_bones),
|
||||
"" if not jp_bones else "(其中 %d 根改为 MMD 标准日文名,"
|
||||
"原英文名保留在英文名中)" % n_renamed,
|
||||
";%d 根 unused 占位骨单独放进 unused 表示枠" % n_unused
|
||||
if n_unused else ""))
|
||||
|
||||
# ---- 足 IK(MMD 摆姿势几乎必用;源骨架没有,这里补标准的一套)
|
||||
def find_bone(jp_name):
|
||||
for i, b in enumerate(pmx_bones):
|
||||
if b["name"] == jp_name:
|
||||
return i
|
||||
return -1
|
||||
|
||||
ik_made = 0
|
||||
if make_ik:
|
||||
ground_y = min(p[1] for p in pts) if pts else 0.0
|
||||
center_i = find_bone("センター")
|
||||
for side, s in (("左", "L"), ("右", "R")):
|
||||
i_ankle = find_bone(side + "足首")
|
||||
i_knee = find_bone(side + "ひざ")
|
||||
i_leg = find_bone(side + "足")
|
||||
i_toe = find_bone(side + "つま先")
|
||||
if min(i_ankle, i_knee, i_leg) < 0:
|
||||
continue
|
||||
ankle = pmx_bones[i_ankle]["pos"]
|
||||
i_legik = len(pmx_bones)
|
||||
pmx_bones.append({
|
||||
"name": _uniq(side + "足IK", used),
|
||||
"name_en": "LegIK_" + s,
|
||||
"pos": (ankle[0], ground_y, ankle[2]),
|
||||
"parent": center_i if center_i >= 0 else 0,
|
||||
"layer": 0,
|
||||
"flag": 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020,
|
||||
"tail_kind": 0, "tail": (0.0, 1.0, 0.0),
|
||||
"inherit_rot": None, "inherit_mov": None,
|
||||
"fixed_axis": None, "local_axis": None, "external": None,
|
||||
"_is_unused": False,
|
||||
"ik": {"target": i_ankle, "iterations": 40,
|
||||
"limit_angle": 1.0,
|
||||
"links": [{"bone": i_knee, "min": None, "max": None},
|
||||
{"bone": i_leg, "min": None, "max": None}]},
|
||||
})
|
||||
ik_made += 1
|
||||
if i_toe >= 0:
|
||||
toe = pmx_bones[i_toe]["pos"]
|
||||
pmx_bones.append({
|
||||
"name": _uniq(side + "つま先IK", used),
|
||||
"name_en": "ToeIK_" + s,
|
||||
"pos": (toe[0], ground_y, toe[2]),
|
||||
"parent": i_legik,
|
||||
"layer": 0,
|
||||
"flag": 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020,
|
||||
"tail_kind": 0, "tail": (0.0, 1.0, 0.0),
|
||||
"inherit_rot": None, "inherit_mov": None,
|
||||
"fixed_axis": None, "local_axis": None,
|
||||
"external": None,
|
||||
"_is_unused": False,
|
||||
"ik": {"target": i_toe, "iterations": 3,
|
||||
"limit_angle": 1.0,
|
||||
"links": [{"bone": i_ankle,
|
||||
"min": None, "max": None}]},
|
||||
})
|
||||
ik_made += 1
|
||||
if ik_made:
|
||||
_l("足 IK:已补充 %d 根(足IK / つま先IK,父骨骼 センター)" % ik_made,
|
||||
"info")
|
||||
else:
|
||||
_l("足 IK:源骨架中没有完整的腿部骨链,未补充 IK 骨", "info")
|
||||
|
||||
# ---- 面:按网格(= 材质)排序,保证 PMX 材质吃连续的面段
|
||||
nmats = len(m.meshes)
|
||||
tri = []
|
||||
for mi, mesh in enumerate(m.meshes):
|
||||
base = mesh_vert_start[mi]
|
||||
for (a, b, c) in mesh.triangles:
|
||||
tri.append((mi, base + a, base + b, base + c))
|
||||
tri.sort(key=lambda t: t[0])
|
||||
|
||||
# ---- 绕序自动判定(用变换后的数据投票)
|
||||
pos_t = [sp(p) for p in raw_pos]
|
||||
nrm_t = []
|
||||
n_has = 0
|
||||
for i, n in enumerate(raw_nrm):
|
||||
if n is None:
|
||||
nrm_t.append(None)
|
||||
else:
|
||||
nrm_t.append(sn(n))
|
||||
n_has += 1
|
||||
face_idx = []
|
||||
for _mi, a, b, c in tri:
|
||||
face_idx.extend((a, b, c))
|
||||
if n_has >= max(1, len(raw_nrm) // 2):
|
||||
# 少数顶点缺法线时用「有效法线的平均值」补上,别让投票函数拿到 None
|
||||
if n_has < len(raw_nrm):
|
||||
ax = ay = az = 0.0
|
||||
for n in nrm_t:
|
||||
if n is not None:
|
||||
ax += n[0]
|
||||
ay += n[1]
|
||||
az += n[2]
|
||||
ln = (ax * ax + ay * ay + az * az) ** 0.5 or 1.0
|
||||
fill = (ax / ln, ay / ln, az / ln)
|
||||
nrm_vote = [n if n is not None else fill for n in nrm_t]
|
||||
_l("绕序:%d 个顶点没有法线,判定时使用平均法线"
|
||||
% (len(raw_nrm) - n_has), "info")
|
||||
else:
|
||||
nrm_vote = nrm_t
|
||||
need_flip, ag, dis = pmxio.detect_winding(pos_t, nrm_vote, face_idx)
|
||||
_l("绕序自动判定:与法线同向 %d 面 / 反向 %d 面 → %s"
|
||||
% (ag, dis, "需要反转" if need_flip else "保持不变"))
|
||||
else:
|
||||
# Z 取反是一次反射,几何绕序必然翻面;没有法线时一律反转
|
||||
need_flip = True
|
||||
_l("绕序:法线数据不完整,按坐标轴反射统一反转(保持正面朝外)", "info")
|
||||
|
||||
pmx_faces = []
|
||||
for _mi, a, b, c in tri:
|
||||
pmx_faces.extend((c, b, a) if need_flip else (a, b, c))
|
||||
|
||||
# ---- 权重:XPS 的权重是按顶点索引的,直接摊到 PMX 顶点上
|
||||
n_dropped = 0
|
||||
no_weight = 0
|
||||
pmx_verts = []
|
||||
for vi in range(n_vert):
|
||||
P = sp(raw_pos[vi])
|
||||
N = nrm_t[vi] if nrm_t[vi] is not None else (0.0, 0.0, 1.0)
|
||||
wl = [(b, w) for b, w in raw_w[vi] if w > 1e-6]
|
||||
if len(wl) > 4:
|
||||
n_dropped += len(wl) - 4
|
||||
wl.sort(key=lambda t: -t[1])
|
||||
wl = wl[:4]
|
||||
if not wl:
|
||||
no_weight += 1
|
||||
wl = [(0, 1.0)]
|
||||
tot = sum(w for _, w in wl) or 1.0
|
||||
wl = [(slot.get(b, 0), w / tot) for b, w in wl]
|
||||
if len(wl) == 1:
|
||||
wtype, wbones, wweights = 0, [wl[0][0]], []
|
||||
elif len(wl) == 2:
|
||||
wtype, wbones, wweights = 1, [wl[0][0], wl[1][0]], [wl[0][1]]
|
||||
else:
|
||||
wtype = 2
|
||||
wbones = [wl[k][0] if k < len(wl) else wl[0][0] for k in range(4)]
|
||||
wweights = [wl[k][1] if k < len(wl) else 0.0 for k in range(4)]
|
||||
u, v = raw_uv[vi]
|
||||
pmx_verts.append({"pos": P, "normal": N, "uv": (u, v),
|
||||
"add_uv": [], "wtype": wtype, "wbones": wbones,
|
||||
"wweights": wweights, "sdef": None, "edge": 1.0})
|
||||
if no_weight:
|
||||
_l("权重:%d 个顶点没有权重,已绑定到第 0 根骨骼" % no_weight, "warn")
|
||||
if n_dropped:
|
||||
_l("权重:已丢弃 %d 条第 5 根及以后的骨骼权重(PMX 每个顶点最多 4 根)"
|
||||
% n_dropped, "info")
|
||||
|
||||
# ---- 材质 + 贴图
|
||||
folder = os.path.dirname(os.path.abspath(path))
|
||||
out_dir = os.path.dirname(os.path.abspath(out_path))
|
||||
tex_dir = os.path.join(out_dir, "textures")
|
||||
pmx_textures = []
|
||||
tex_slot = {}
|
||||
n_linked = 0
|
||||
n_missing = []
|
||||
|
||||
def use_texture(filename):
|
||||
key = os.path.basename((filename or "").replace("\\", "/")).lower()
|
||||
if key in tex_slot:
|
||||
return tex_slot[key]
|
||||
real = _find_texture(folder, filename) if filename else None
|
||||
if real is None:
|
||||
tex_slot[key] = -1
|
||||
return -1
|
||||
ext = os.path.splitext(real)[1].lower()
|
||||
if ext not in _TEX_EXT:
|
||||
tex_slot[key] = -1
|
||||
return -1
|
||||
dst_name = os.path.basename(real)
|
||||
dst = os.path.join(tex_dir, dst_name)
|
||||
try:
|
||||
os.makedirs(tex_dir, exist_ok=True)
|
||||
if not os.path.isfile(dst):
|
||||
_copy_tex(real, dst)
|
||||
except OSError:
|
||||
tex_slot[key] = -1
|
||||
return -1
|
||||
rel = "textures/" + dst_name
|
||||
if rel not in pmx_textures:
|
||||
pmx_textures.append(rel)
|
||||
tex_slot[key] = pmx_textures.index(rel)
|
||||
return tex_slot[key]
|
||||
|
||||
counts = [0] * max(1, nmats)
|
||||
for mi, _a, _b, _c in tri:
|
||||
counts[mi] += 1
|
||||
|
||||
pmx_materials = []
|
||||
for mi, mesh in enumerate(m.meshes):
|
||||
mname = _clean_name(mesh.name) or ("mat%d" % mi)
|
||||
diff = mesh.diffuse
|
||||
ti = use_texture(diff) if textures else -1
|
||||
if ti >= 0:
|
||||
n_linked += 1
|
||||
elif textures and diff:
|
||||
n_missing.append(os.path.basename(diff.replace("\\", "/")))
|
||||
flag = 0x0E | (0x10 if enable_edge else 0)
|
||||
if force_double_sided or all_double_sided:
|
||||
flag |= 0x01
|
||||
pmx_materials.append({
|
||||
"name": mname, "name_en": mname,
|
||||
"diffuse": (1.0, 1.0, 1.0, 1.0),
|
||||
"specular": (0.0, 0.0, 0.0),
|
||||
"shininess": 0.0,
|
||||
"ambient": (0.5, 0.5, 0.5),
|
||||
"flag": flag,
|
||||
"edge_color": (0.0, 0.0, 0.0, 1.0),
|
||||
"edge_size": 1.0 if enable_edge else 0.0,
|
||||
"tex": ti, "sph": -1, "sph_mode": 0,
|
||||
"toon_flag": _TOON_NONE_FLAG, "toon": _TOON_NONE_INDEX, "memo": "",
|
||||
"faces": counts[mi],
|
||||
})
|
||||
# 空材质(源里声明了但一个面都没用上)会让 PMX 出现 0 面材质段,去掉更干净
|
||||
pmx_materials = [x for x in pmx_materials if x["faces"] > 0]
|
||||
if not pmx_materials:
|
||||
pmx_materials.append({
|
||||
"name": "material_0", "name_en": "material_0",
|
||||
"diffuse": (1.0, 1.0, 1.0, 1.0), "specular": (0.0, 0.0, 0.0),
|
||||
"shininess": 0.0, "ambient": (0.5, 0.5, 0.5),
|
||||
"flag": 0x0E | (0x10 if enable_edge else 0),
|
||||
"edge_color": (0.0, 0.0, 0.0, 1.0),
|
||||
"edge_size": 1.0 if enable_edge else 0.0, "tex": -1, "sph": -1,
|
||||
"sph_mode": 0, "toon_flag": _TOON_NONE_FLAG,
|
||||
"toon": _TOON_NONE_INDEX, "memo": "",
|
||||
"faces": len(pmx_faces) // 3,
|
||||
})
|
||||
# PMX 材质的「面数」字段其实是**索引数**(每个三角面占 3 个)
|
||||
for x in pmx_materials:
|
||||
x["faces"] = int(x["faces"]) * 3
|
||||
_l("材质:%d 个 · 关联到贴图 %d 个%s"
|
||||
% (len(pmx_materials), n_linked,
|
||||
"" if n_linked else "(源目录中没有同名贴图,导出为无贴图模型)"))
|
||||
if n_missing:
|
||||
_l("贴图:源目录中未找到 %s"
|
||||
% " / ".join(n_missing[:8]), "warn")
|
||||
|
||||
# ---- 表示枠:主干骨进 Root,unused 占位骨单独一枠,表情一枠
|
||||
main_items = []
|
||||
unused_items = []
|
||||
for i, bk in enumerate(pmx_bones):
|
||||
(unused_items if (hide_unused and bk.get("_is_unused"))
|
||||
else main_items).append(i)
|
||||
frames = []
|
||||
if main_items:
|
||||
frames.append({"name": "Root", "name_en": "Root", "special": 0,
|
||||
"items": [(0, i) for i in main_items]})
|
||||
if unused_items:
|
||||
frames.append({"name": "unused", "name_en": "unused", "special": 0,
|
||||
"items": [(0, i) for i in unused_items]})
|
||||
|
||||
stem = os.path.splitext(os.path.basename(path))[0]
|
||||
title = name or stem
|
||||
comment = ["由 %s 转换:%s" % (kind, os.path.basename(path)),
|
||||
"骨骼 %d 根 · 材质 %d 个 · 顶点 %d · 三角面 %d"
|
||||
% (len(pmx_bones), len(pmx_materials), len(pmx_verts),
|
||||
len(pmx_faces) // 3),
|
||||
"converted by xps2pmx.py"]
|
||||
model = pmxio.new_model(title)
|
||||
model["name"] = title
|
||||
model["name_en"] = stem
|
||||
model["comment"] = "\r\n".join(comment)
|
||||
model["comment_en"] = "\r\n".join(comment)
|
||||
model["vertices"] = pmx_verts
|
||||
model["faces"] = pmx_faces
|
||||
model["textures"] = pmx_textures
|
||||
model["materials"] = pmx_materials
|
||||
model["bones"] = pmx_bones
|
||||
model["morphs"] = []
|
||||
model["frames"] = frames
|
||||
model["add_uv"] = 0
|
||||
if not enable_edge:
|
||||
pmxio.strip_edges(model, force_double_sided=False)
|
||||
|
||||
size = pmxio.write_pmx(model, out_path)
|
||||
_l("已写出 %s(%.2f MB)· 顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d"
|
||||
% (os.path.basename(out_path), size / 1048576.0, len(pmx_verts),
|
||||
len(pmx_faces) // 3, len(pmx_bones), len(pmx_materials)), "ok")
|
||||
|
||||
st = {"bytes": size, "vertices": len(pmx_verts),
|
||||
"tris": len(pmx_faces) // 3, "bones": len(pmx_bones),
|
||||
"materials": len(pmx_materials), "morphs": 0,
|
||||
"textures": len(pmx_textures), "scale": scale}
|
||||
|
||||
if fbx_path:
|
||||
try:
|
||||
import fbxout
|
||||
st["fbx"] = fbxout.export_model(
|
||||
fbx_path, pmx_verts, pmx_faces, pmx_materials,
|
||||
pmx_bones, [],
|
||||
mirror_z=True, reverse_winding=True, tex_dir=tex_dir,
|
||||
log=_l, name=title)
|
||||
_l("已写出 %s(ASCII FBX 7.4 · %.2f MB)"
|
||||
% (os.path.basename(fbx_path),
|
||||
st["fbx"]["bytes"] / 1048576.0), "ok")
|
||||
except Exception as e:
|
||||
st["fbx_error"] = str(e)
|
||||
_l("FBX 导出失败:%s" % e, "err")
|
||||
return st
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
import argparse
|
||||
ap = argparse.ArgumentParser(description="XPS / XNALara → MMD PMX(纯 Python)")
|
||||
ap.add_argument("src")
|
||||
ap.add_argument("-o", "--out", default=None)
|
||||
ap.add_argument("--scale", default="mmd",
|
||||
help="mmd(归一到 20 单位,默认)/ raw(保持源尺寸)/ 具体倍率")
|
||||
ap.add_argument("--edge", action="store_true", help="给材质开启 MMD 轮廓线")
|
||||
ap.add_argument("--no-textures", action="store_true")
|
||||
ap.add_argument("--raw-bone-names", action="store_true",
|
||||
help="骨骼保留原始英文名,不转 MMD 日文标准名")
|
||||
ap.add_argument("--no-ik", action="store_true", help="不补 MMD 足 IK 骨")
|
||||
ap.add_argument("--show-unused", action="store_true",
|
||||
help="unused 占位骨也放进 Root 表示枠")
|
||||
ap.add_argument("--one-sided", action="store_true",
|
||||
help="材质不默认开两面描画")
|
||||
ap.add_argument("--fbx", action="store_true", help="同时导出 FBX")
|
||||
ap.add_argument("--name", default=None)
|
||||
a = ap.parse_args(argv)
|
||||
out = a.out or (os.path.splitext(a.src)[0] + ".pmx")
|
||||
fbx = (os.path.splitext(out)[0] + ".fbx") if a.fbx else None
|
||||
st = convert(a.src, out, scale_mode=a.scale,
|
||||
log=lambda m_, t=None: print(m_), name=a.name,
|
||||
enable_edge=a.edge, textures=not a.no_textures,
|
||||
jp_bones=not a.raw_bone_names, make_ik=not a.no_ik,
|
||||
hide_unused=not a.show_unused,
|
||||
all_double_sided=not a.one_sided, fbx_path=fbx)
|
||||
print("完成:%s(%.2f MB)" % (out, st["bytes"] / 1048576.0))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user