导入上游源码,为所有面向用户的品牌显示处添加「增强版 / Enhanced」标识;包含 unitypackage→VRM 的纯色 Toon 材质、兽耳 SpringBone、Unity 描边、UV 接缝白边补偿修复,以及默认不强制 T-pose。146 个单元测试通过。
This commit is contained in:
@@ -0,0 +1,358 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""VRM 文件静态检查:结构、SpringBone、官方 JSON Schema、导入器会踩的坑。
|
||||
|
||||
python tools/qa/check_vrm.py 文件或目录 [...] [--no-schema] [-v]
|
||||
|
||||
逐个文件检查(目录会递归找 .vrm),有问题的打印出来,最后汇总;有错误时退出码为 1。
|
||||
|
||||
* humanoid:骨位名合法、必需骨位齐全、每根骨的 VRM 父骨位确实是它的祖先、
|
||||
用占位骨(vrm_*)补的骨位(道具 / 非人形模型会有,记为提示)。
|
||||
* 网格:JOINTS_0 不越界;同一网格里 morph target 不重名(Unity 遇到重名的
|
||||
BlendShape 会抛异常,UniVRM 导入直接中断)。
|
||||
* 表情:materialColorBinds 的材质号、morphTargetBinds 的 node / index 在范围内。
|
||||
* SpringBone(VRM 1.0):相邻关节是祖先关系、关节不落在 humanoid 骨上、参数有限、
|
||||
碰撞组号合法、同一节点不重复当关节。
|
||||
* SpringBone(VRM 0.x):硬度键名是 stiffiness、参数有限、碰撞组号合法、组根子树不含
|
||||
humanoid 骨、同一节点不落在两个组的子树里(0.x 组根下面整棵子树都会摆动)。
|
||||
* Schema:用 vrm-c/vrm-specification 的官方 JSON Schema 校验 VRMC_vrm、
|
||||
VRMC_springBone、VRMC_materials_mtoon,以及 VRM 0.x 的 VRM 扩展。需要 jsonschema 包;第一次运行时从 GitHub
|
||||
下载固定版本的 schema,缓存在 tools/qa/.schema-cache/。UniVRM 对不合规的数据很少
|
||||
容错(例如 targetValue 少一个分量就 IndexOutOfRange),所以这一项很有用。
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import urllib.request
|
||||
from collections import Counter
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE))
|
||||
sys.path[:0] = [os.path.join(ROOT, "formats"), os.path.join(ROOT, "convert")]
|
||||
import vrmio # noqa: E402
|
||||
from vrmconv.humanoid import _vrm_anchor # noqa: E402
|
||||
|
||||
# ---------------------------------------------------------------- humanoid --
|
||||
_B10 = set("hips spine chest upperChest neck head leftEye rightEye jaw leftUpperLeg leftLowerLeg "
|
||||
"leftFoot leftToes rightUpperLeg rightLowerLeg rightFoot rightToes leftShoulder "
|
||||
"leftUpperArm leftLowerArm leftHand rightShoulder rightUpperArm rightLowerArm "
|
||||
"rightHand".split())
|
||||
_B0 = set(_B10)
|
||||
for _s in ("left", "right"):
|
||||
_B10 |= {_s + "ThumbMetacarpal", _s + "ThumbProximal", _s + "ThumbDistal"}
|
||||
_B0 |= {_s + "ThumbProximal", _s + "ThumbIntermediate", _s + "ThumbDistal"}
|
||||
for _f in ("Index", "Middle", "Ring", "Little"):
|
||||
for _j in ("Proximal", "Intermediate", "Distal"):
|
||||
_B10.add(_s + _f + _j)
|
||||
_B0.add(_s + _f + _j)
|
||||
_REQ = ("hips spine head leftUpperArm leftLowerArm leftHand rightUpperArm rightLowerArm "
|
||||
"rightHand leftUpperLeg leftLowerLeg leftFoot rightUpperLeg rightLowerLeg "
|
||||
"rightFoot").split()
|
||||
|
||||
# ------------------------------------------------------------------ schema --
|
||||
SPEC_COMMIT = "94e82dd346fa6cf0337c4421728640e5252dd38e" # vrm-c/vrm-specification
|
||||
SPEC_URL = "https://raw.githubusercontent.com/vrm-c/vrm-specification/%s/specification/%s/schema/%s"
|
||||
SPEC_FILES = {
|
||||
"VRMC_vrm-1.0": [
|
||||
"VRMC_vrm.schema.json", "VRMC_vrm.meta.schema.json", "VRMC_vrm.humanoid.schema.json",
|
||||
"VRMC_vrm.humanoid.humanBones.schema.json",
|
||||
"VRMC_vrm.humanoid.humanBones.humanBone.schema.json",
|
||||
"VRMC_vrm.firstPerson.schema.json", "VRMC_vrm.firstPerson.meshAnnotation.schema.json",
|
||||
"VRMC_vrm.lookAt.schema.json", "VRMC_vrm.lookAt.rangeMap.schema.json",
|
||||
"VRMC_vrm.expressions.schema.json", "VRMC_vrm.expressions.expression.schema.json",
|
||||
"VRMC_vrm.expressions.expression.materialColorBind.schema.json",
|
||||
"VRMC_vrm.expressions.expression.morphTargetBind.schema.json",
|
||||
"VRMC_vrm.expressions.expression.textureTransformBind.schema.json"],
|
||||
"VRMC_springBone-1.0": [
|
||||
"VRMC_springBone.schema.json", "VRMC_springBone.collider.schema.json",
|
||||
"VRMC_springBone.colliderGroup.schema.json", "VRMC_springBone.joint.schema.json",
|
||||
"VRMC_springBone.shape.schema.json", "VRMC_springBone.spring.schema.json"],
|
||||
"VRMC_materials_mtoon-1.0": [
|
||||
"VRMC_materials_mtoon.schema.json", "mtoon.shadingShiftTexture.schema.json"],
|
||||
"0.0": [
|
||||
"vrm.schema.json", "vrm.meta.schema.json", "vrm.humanoid.schema.json", "vrm.humanoid.bone.schema.json",
|
||||
"vrm.firstperson.schema.json", "vrm.firstperson.degreemap.schema.json",
|
||||
"vrm.firstperson.meshannotation.schema.json", "vrm.blendshape.schema.json",
|
||||
"vrm.blendshape.group.schema.json", "vrm.blendshape.bind.schema.json",
|
||||
"vrm.blendshape.materialbind.schema.json", "vrm.secondaryanimation.schema.json",
|
||||
"vrm.secondaryanimation.spring.schema.json", "vrm.secondaryanimation.collidergroup.schema.json",
|
||||
"vrm.material.schema.json"],
|
||||
}
|
||||
# glTF 本体的几个 schema 只被引用、不需要逐项校验,用最小定义代替
|
||||
_GLTF_STUBS = {
|
||||
"glTFProperty.schema.json": {"type": "object"},
|
||||
"glTFid.schema.json": {"type": "integer", "minimum": 0},
|
||||
"textureInfo.schema.json": {"type": "object", "required": ["index"],
|
||||
"properties": {"index": {"type": "integer", "minimum": 0},
|
||||
"texCoord": {"type": "integer", "minimum": 0}}},
|
||||
}
|
||||
_BASE = "https://vrm-spec.invalid/"
|
||||
|
||||
|
||||
def load_validators():
|
||||
"""→ {扩展名: validator};缺 jsonschema 或下载失败时返回 (None, 原因)。"""
|
||||
try:
|
||||
import jsonschema
|
||||
from referencing import Registry, Resource
|
||||
from referencing.jsonschema import DRAFT4
|
||||
except ImportError:
|
||||
return None, "未安装 jsonschema(pip install jsonschema),跳过 Schema 校验"
|
||||
cache = os.path.join(HERE, ".schema-cache", SPEC_COMMIT[:12])
|
||||
docs = dict(_GLTF_STUBS)
|
||||
for d, files in SPEC_FILES.items():
|
||||
for fn in files:
|
||||
path = os.path.join(cache, fn)
|
||||
if not os.path.isfile(path):
|
||||
os.makedirs(cache, exist_ok=True)
|
||||
try:
|
||||
with urllib.request.urlopen(SPEC_URL % (SPEC_COMMIT, d, fn), timeout=30) as r:
|
||||
data = r.read()
|
||||
except OSError as e:
|
||||
return None, "下载 schema 失败(%s),跳过 Schema 校验" % e
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
with open(path, encoding="utf-8") as f:
|
||||
docs[fn] = json.load(f)
|
||||
resources = []
|
||||
for fn, doc in docs.items():
|
||||
# draft-04 用 id(不是 $id)定基准 URI,相对的 $ref 才解析得到
|
||||
doc = dict({k: v for k, v in doc.items() if k not in ("$schema", "$id")}, id=_BASE + fn)
|
||||
resources.append((_BASE + fn, Resource.from_contents(doc, default_specification=DRAFT4)))
|
||||
registry = Registry().with_resources(resources)
|
||||
out = {}
|
||||
for ext, fn in (("VRMC_vrm", "VRMC_vrm"), ("VRMC_springBone", "VRMC_springBone"),
|
||||
("VRMC_materials_mtoon", "VRMC_materials_mtoon"), ("VRM", "vrm")):
|
||||
schema = registry.contents(_BASE + fn + ".schema.json")
|
||||
out[ext] = jsonschema.Draft4Validator(schema, registry=registry)
|
||||
return out, None
|
||||
|
||||
|
||||
def schema_errors(g, validators):
|
||||
errs = []
|
||||
|
||||
def run(ext, obj, where):
|
||||
for e in validators[ext].iter_errors(obj):
|
||||
path = "/".join(str(p) for p in e.absolute_path)
|
||||
errs.append("schema %s/%s: %s" % (where, path, e.message[:120]))
|
||||
|
||||
ext = g.get("extensions", {})
|
||||
if "VRMC_vrm" in ext:
|
||||
run("VRMC_vrm", ext["VRMC_vrm"], "VRMC_vrm")
|
||||
if "VRMC_springBone" in ext:
|
||||
run("VRMC_springBone", ext["VRMC_springBone"], "VRMC_springBone")
|
||||
if "VRM" in ext:
|
||||
run("VRM", ext["VRM"], "VRM")
|
||||
for i, m in enumerate(g.get("materials", [])):
|
||||
mt = m.get("extensions", {}).get("VRMC_materials_mtoon")
|
||||
if mt is not None:
|
||||
run("VRMC_materials_mtoon", mt, "materials/%d/mtoon" % i)
|
||||
return errs
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ checks --
|
||||
def check(path, validators=None):
|
||||
"""→ (错误列表, 提示列表, 摘要 dict)"""
|
||||
errs, notes = [], []
|
||||
g, b = vrmio.read_glb(path)
|
||||
ext = g.get("extensions", {})
|
||||
nodes = g["nodes"]
|
||||
par = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])}
|
||||
is1 = "VRMC_vrm" in ext
|
||||
if not is1 and "VRM" not in ext:
|
||||
return ["不是 VRM(没有 VRMC_vrm / VRM 扩展)"], [], {}
|
||||
|
||||
# humanoid
|
||||
if is1:
|
||||
hb = {k: v["node"] for k, v in ext["VRMC_vrm"]["humanoid"]["humanBones"].items()}
|
||||
valid, req = _B10, _REQ
|
||||
else:
|
||||
hb = {x["bone"]: x["node"] for x in ext["VRM"]["humanoid"]["humanBones"]}
|
||||
valid, req = _B0, _REQ + ["chest", "neck"]
|
||||
for k in sorted(set(hb) - valid):
|
||||
errs.append("humanoid:非法骨位 %s" % k)
|
||||
for k in req:
|
||||
if k not in hb:
|
||||
errs.append("humanoid:缺少必需骨位 %s" % k)
|
||||
for h, n in hb.items():
|
||||
a = _vrm_anchor(h, hb)
|
||||
if a is None:
|
||||
continue
|
||||
p = par.get(n)
|
||||
while p is not None and p != hb[a]:
|
||||
p = par.get(p)
|
||||
if p is None:
|
||||
errs.append("humanoid:%s 不在 %s 之下" % (h, a))
|
||||
placeholders = sorted(h for h, n in hb.items() if nodes[n].get("name", "").startswith("vrm_"))
|
||||
if placeholders:
|
||||
notes.append("humanoid:%d 根占位骨(%s)" % (len(placeholders), ", ".join(placeholders[:6])
|
||||
+ (" …" if len(placeholders) > 6 else "")))
|
||||
|
||||
# mesh
|
||||
njoints = len(g["skins"][0]["joints"]) if g.get("skins") else 0
|
||||
for mi, m in enumerate(g.get("meshes", [])):
|
||||
for pr in m["primitives"]:
|
||||
if "JOINTS_0" in pr["attributes"]:
|
||||
if max(vrmio.read_accessor(g, b, pr["attributes"]["JOINTS_0"])) >= njoints:
|
||||
errs.append("mesh %d:JOINTS_0 超出 skin.joints" % mi)
|
||||
break
|
||||
names = (m.get("extras") or {}).get("targetNames") or []
|
||||
for k, v in Counter(names).items():
|
||||
if v > 1:
|
||||
errs.append("mesh %d:morph target 重名「%s」×%d(Unity 导入会中断)" % (mi, k, v))
|
||||
|
||||
# expressions
|
||||
nm = len(g.get("materials", []))
|
||||
if is1:
|
||||
groups = ext["VRMC_vrm"].get("expressions", {})
|
||||
for grp in ("preset", "custom"):
|
||||
for name, e in (groups.get(grp) or {}).items():
|
||||
for bnd in e.get("materialColorBinds", []):
|
||||
if not 0 <= bnd["material"] < nm:
|
||||
errs.append("表情 %s:材质号 %d 越界" % (name, bnd["material"]))
|
||||
for bnd in e.get("morphTargetBinds", []):
|
||||
node = nodes[bnd["node"]] if 0 <= bnd["node"] < len(nodes) else {}
|
||||
if "mesh" not in node:
|
||||
errs.append("表情 %s:node %d 没有网格" % (name, bnd["node"]))
|
||||
continue
|
||||
nt = len(g["meshes"][node["mesh"]]["primitives"][0].get("targets", []))
|
||||
if not 0 <= bnd["index"] < nt:
|
||||
errs.append("表情 %s:morph 索引 %d 越界(共 %d)" % (name, bnd["index"], nt))
|
||||
|
||||
# SpringBone
|
||||
summary = {"spec": "1.0" if is1 else "0.x", "humanBones": len(hb),
|
||||
"placeholders": len(placeholders)}
|
||||
sb = ext.get("VRMC_springBone")
|
||||
if sb:
|
||||
hum = set(hb.values())
|
||||
seen = Counter()
|
||||
ncg = len(sb.get("colliderGroups", []))
|
||||
for sp in sb["springs"]:
|
||||
js = sp["joints"]
|
||||
for a, c in zip(js, js[1:]):
|
||||
q = par.get(c["node"])
|
||||
while q is not None and q != a["node"]:
|
||||
q = par.get(q)
|
||||
if q is None:
|
||||
errs.append("SpringBone %s:%s 不是 %s 的后代" % (
|
||||
sp.get("name"), nodes[c["node"]]["name"], nodes[a["node"]]["name"]))
|
||||
for j in js:
|
||||
seen[j["node"]] += 1
|
||||
if j["node"] in hum:
|
||||
errs.append("SpringBone %s:关节落在 humanoid 骨 %s 上"
|
||||
% (sp.get("name"), nodes[j["node"]]["name"]))
|
||||
for k in ("hitRadius", "stiffness", "gravityPower", "dragForce"):
|
||||
if k in j and not math.isfinite(j[k]):
|
||||
errs.append("SpringBone %s:%s 不是有限值" % (sp.get("name"), k))
|
||||
for cg in sp.get("colliderGroups", []):
|
||||
if not 0 <= cg < ncg:
|
||||
errs.append("SpringBone %s:碰撞组号 %d 越界" % (sp.get("name"), cg))
|
||||
for n, c in seen.items():
|
||||
if c > 1:
|
||||
errs.append("SpringBone:节点 %s 在 %d 条链里当关节" % (nodes[n]["name"], c))
|
||||
summary.update(springs=len(sb["springs"]),
|
||||
joints=sum(len(sp["joints"]) for sp in sb["springs"]),
|
||||
colliders=len(sb.get("colliders", [])))
|
||||
sa = None if is1 else ext["VRM"].get("secondaryAnimation")
|
||||
if sa and sa.get("boneGroups"):
|
||||
errs += _check_secondary(sa, nodes, par, set(hb.values()))
|
||||
summary.update(springs=len(sa["boneGroups"]),
|
||||
colliders=sum(len(c.get("colliders", [])) for c in sa.get("colliderGroups", [])))
|
||||
|
||||
if validators:
|
||||
errs += schema_errors(g, validators)
|
||||
return errs, notes, summary
|
||||
|
||||
|
||||
def _check_secondary(sa, nodes, par, hum):
|
||||
"""VRM 0.x 的 secondaryAnimation:组根子树整棵都会摆动,同一节点在两个组里会被模拟两次。"""
|
||||
errs = []
|
||||
kids = {i: n.get("children", []) for i, n in enumerate(nodes)}
|
||||
ncg = len(sa.get("colliderGroups", []))
|
||||
owner = {}
|
||||
for gi, grp in enumerate(sa["boneGroups"]):
|
||||
name = grp.get("comment") or "#%d" % gi
|
||||
if "stiffness" in grp and "stiffiness" not in grp:
|
||||
errs.append("secondaryAnimation %s:硬度要写成 stiffiness(规范里的拼写),stiffness 不会被读取" % name)
|
||||
for k in ("stiffiness", "gravityPower", "dragForce", "hitRadius"):
|
||||
if k in grp and not math.isfinite(grp[k]):
|
||||
errs.append("secondaryAnimation %s:%s 不是有限值" % (name, k))
|
||||
for cg in grp.get("colliderGroups", []):
|
||||
if not 0 <= cg < ncg:
|
||||
errs.append("secondaryAnimation %s:碰撞组号 %d 越界" % (name, cg))
|
||||
for r in grp.get("bones", []):
|
||||
if not 0 <= r < len(nodes):
|
||||
errs.append("secondaryAnimation %s:根节点 %d 越界" % (name, r))
|
||||
continue
|
||||
stack = [r]
|
||||
while stack:
|
||||
n = stack.pop()
|
||||
if n in hum:
|
||||
errs.append("secondaryAnimation %s:humanoid 骨 %s 在摆动子树里" % (name, nodes[n]["name"]))
|
||||
if n in owner:
|
||||
errs.append("secondaryAnimation:节点 %s 同时在组 %s 和 %s 的子树里(会被模拟两次)"
|
||||
% (nodes[n]["name"], owner[n], name))
|
||||
continue
|
||||
owner[n] = name
|
||||
stack.extend(kids[n])
|
||||
for ci, cg in enumerate(sa.get("colliderGroups", [])):
|
||||
if not 0 <= cg.get("node", -1) < len(nodes):
|
||||
errs.append("secondaryAnimation:碰撞组 %d 的节点越界" % ci)
|
||||
return errs
|
||||
|
||||
|
||||
def iter_files(paths):
|
||||
for p in paths:
|
||||
if os.path.isdir(p):
|
||||
for d, _, fs in os.walk(p):
|
||||
for f in sorted(fs):
|
||||
if f.lower().endswith(".vrm"):
|
||||
yield os.path.join(d, f)
|
||||
else:
|
||||
yield p
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description="VRM 文件静态检查")
|
||||
ap.add_argument("paths", nargs="+", help=".vrm 文件或目录")
|
||||
ap.add_argument("--no-schema", action="store_true", help="不做官方 JSON Schema 校验")
|
||||
ap.add_argument("-v", "--verbose", action="store_true", help="通过的文件也打印摘要和提示")
|
||||
a = ap.parse_args(argv)
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
validators = None
|
||||
if not a.no_schema:
|
||||
validators, why = load_validators()
|
||||
if why:
|
||||
print("提示:" + why)
|
||||
n = bad = 0
|
||||
for path in iter_files(a.paths):
|
||||
n += 1
|
||||
try:
|
||||
errs, notes, summ = check(path, validators)
|
||||
except Exception as e: # noqa: BLE001 坏文件也要继续往下查
|
||||
errs, notes, summ = ["读取失败:%s: %s" % (type(e).__name__, e)], [], {}
|
||||
if errs:
|
||||
bad += 1
|
||||
print("✗ %s" % path)
|
||||
shown = Counter()
|
||||
for e in errs: # 同类错误只列前几条
|
||||
key = e.split(":")[0] if ":" in e else e[:40]
|
||||
shown[key] += 1
|
||||
if shown[key] <= 5:
|
||||
print(" " + e)
|
||||
for k, c in shown.items():
|
||||
if c > 5:
|
||||
print(" …… %s 还有 %d 条" % (k, c - 5))
|
||||
elif a.verbose:
|
||||
print("✓ %s %s" % (path, " ".join("%s=%s" % kv for kv in summ.items())))
|
||||
for t in notes:
|
||||
print(" 提示:" + t)
|
||||
print("检查 %d 个文件,%d 个有错误" % (n, bad))
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,147 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""SpringBone 动态测试:静止偏移 + 待机 / 带位移走路 / 跑步时的末端颤动。
|
||||
|
||||
python tools/qa/dynamics.py 文件或目录 [...] [-j 4] [--motions idle,walk_real,run]
|
||||
[--fps 60] [--jitter 0] [--json 结果.json] [--strict]
|
||||
|
||||
用 three.js + three-vrm 在 Node 里无界面地跑物理(和 UniVRM 同一套 SpringBone 规则),
|
||||
每个文件一个进程并行。只测带 VRMC_springBone 的人形模型(占位骨补出来的道具跳过)。
|
||||
第一次用要先装依赖: cd tools/qa/harness && npm install
|
||||
|
||||
指标(越小越稳;参考范围来自 VRoid / VRM 官方示例模型在同样动作下的实测):
|
||||
静止偏移 站着不动 2 秒后弹簧末端离绑定姿势的最大距离。正常 < 5 cm
|
||||
hf 末端 8 Hz 以上的颤动能量 / 链长 ×1000(平均/最大)。原生模型头发 2~16、裙摆 3~58
|
||||
swing 末端最大摆幅 / 链长
|
||||
穿腿 裙摆关节落在模型自己的腿部碰撞体里的比例(含静止时就重叠的,要和 idle 对比看)
|
||||
超出范围的数值后面标「!」;--strict 时有标记就返回 1。
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
HARNESS = os.path.join(HERE, "harness")
|
||||
LIMITS = {"rest": 0.05, "hf": {"hair": 16.0, "skirt": 60.0, "torso": 60.0, "other": 60.0}}
|
||||
|
||||
|
||||
def glb_json(path):
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(20)
|
||||
n = struct.unpack_from("<I", head, 12)[0]
|
||||
return json.loads(f.read(n))
|
||||
|
||||
|
||||
def testable(path):
|
||||
"""有 SpringBone、humanoid 不是占位骨拼出来的 → True。"""
|
||||
try:
|
||||
g = glb_json(path)
|
||||
except (OSError, ValueError, struct.error):
|
||||
return False
|
||||
if "VRMC_springBone" not in g.get("extensionsUsed", []):
|
||||
return False
|
||||
hb = g.get("extensions", {}).get("VRMC_vrm", {}).get("humanoid", {}).get("humanBones", {})
|
||||
names = [g["nodes"][v["node"]].get("name", "") for v in hb.values()]
|
||||
return not any(n.startswith("vrm_") for n in names)
|
||||
|
||||
|
||||
def iter_files(paths):
|
||||
for p in paths:
|
||||
if os.path.isdir(p):
|
||||
for d, _, fs in os.walk(p):
|
||||
for f in sorted(fs):
|
||||
if f.lower().endswith(".vrm"):
|
||||
yield os.path.join(d, f)
|
||||
else:
|
||||
yield p
|
||||
|
||||
|
||||
def run_one(path, env):
|
||||
r = subprocess.run(["node", os.path.join(HARNESS, "measure.mjs"), os.path.abspath(path)],
|
||||
cwd=HARNESS, env=env, capture_output=True, encoding="utf-8")
|
||||
lines = [l for l in r.stdout.splitlines() if l.startswith("{")]
|
||||
if r.returncode or not lines:
|
||||
return {"file": path, "error": (r.stderr or r.stdout).strip()[-800:]}
|
||||
return json.loads(lines[-1])
|
||||
|
||||
|
||||
def fmt(res):
|
||||
"""一个文件的结果 → (文本行, 是否有超范围)"""
|
||||
flag = False
|
||||
name = os.path.basename(res["file"])
|
||||
if "error" in res:
|
||||
return ["✗ %s\n %s" % (name, res["error"].replace("\n", "\n "))], True
|
||||
rest = res["rest"]
|
||||
bad = rest["max"] > LIMITS["rest"]
|
||||
flag |= bad
|
||||
out = ["%s %s" % ("!" if bad else "·", name),
|
||||
" 静止偏移 最大 %.1f cm%s(%s)· 超过 1 cm 的 %d / %d" % (
|
||||
rest["max"] * 100, " !" if bad else "", rest["maxName"], rest["over1cm"], rest["joints"])]
|
||||
for m, r in res["motions"].items():
|
||||
parts = []
|
||||
for cat in ("hair", "skirt", "torso", "other"):
|
||||
c = r["cats"].get(cat)
|
||||
if not c:
|
||||
continue
|
||||
over = c["hfMax"] > LIMITS["hf"][cat]
|
||||
flag |= over
|
||||
parts.append("%s hf %.1f/%.1f%s swing %.2f" % (
|
||||
{"hair": "头发", "skirt": "裙摆", "torso": "躯干", "other": "其它"}[cat],
|
||||
c["hf"], c["hfMax"], "!" if over else "", c["swing"]))
|
||||
if r.get("skirtInside") is not None:
|
||||
parts.append("穿腿 %.1f%%" % (r["skirtInside"] * 100))
|
||||
if r.get("skirtGap"):
|
||||
g = r["skirtGap"]
|
||||
parts.append("张开 %.1f/%.1f/%.1f cm" % (g["mean"] * 100, g["p90"] * 100, g["max"] * 100))
|
||||
out.append(" %-9s %s" % (m, " | ".join(parts)))
|
||||
if r.get("worst") and any(w["hf"] > LIMITS["hf"][w["cat"]] for w in r["worst"]):
|
||||
for w in r["worst"]:
|
||||
out.append(" %s:%s hf %.1f swing %.2f(%d 节,%.2f m)" % (
|
||||
w["cat"], w["chain"], w["hf"], w["swing"], w["joints"], w["length"]))
|
||||
return out, flag
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description="SpringBone 动态测试(three-vrm,无界面)")
|
||||
ap.add_argument("paths", nargs="+", help=".vrm 文件或目录")
|
||||
ap.add_argument("-j", "--jobs", type=int, default=4, help="并行数(每个文件一个 Node 进程)")
|
||||
ap.add_argument("--motions", default="idle,walk_real,run",
|
||||
help="动作:idle, walk_real, run, leg_raise, yaw_gentle, yaw_strong, walk, static")
|
||||
ap.add_argument("--fps", type=float, default=60, help="物理帧率(默认 60)")
|
||||
ap.add_argument("--jitter", type=float, default=0, help="帧时间抖动比例,如 0.3")
|
||||
ap.add_argument("--json", help="把原始结果写成 JSON")
|
||||
ap.add_argument("--strict", action="store_true", help="有超范围的数值时返回 1")
|
||||
a = ap.parse_args(argv)
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
if not shutil.which("node"):
|
||||
sys.exit("需要 Node.js(https://nodejs.org)")
|
||||
if not os.path.isdir(os.path.join(HARNESS, "node_modules", "@pixiv", "three-vrm")):
|
||||
sys.exit("先安装依赖:cd %s && npm install" % HARNESS)
|
||||
files = list(iter_files(a.paths))
|
||||
todo = [f for f in files if testable(f)]
|
||||
if len(todo) < len(files):
|
||||
print("跳过 %d 个没有 SpringBone 或不是人形的文件" % (len(files) - len(todo)))
|
||||
env = dict(os.environ, MOTIONS=a.motions, FPS=str(a.fps), JITTER=str(a.jitter), DETAIL="3")
|
||||
with ThreadPoolExecutor(max_workers=max(1, a.jobs)) as ex:
|
||||
results = list(ex.map(lambda f: run_one(f, env), todo))
|
||||
n_flag = 0
|
||||
for res in results:
|
||||
lines, flag = fmt(res)
|
||||
n_flag += flag
|
||||
print("\n".join(lines))
|
||||
if a.json:
|
||||
with open(a.json, "w", encoding="utf-8") as f:
|
||||
json.dump(results, f, ensure_ascii=False, indent=1)
|
||||
print("测试 %d 个文件,%d 个有超出参考范围的数值(标「!」)" % (len(results), n_flag))
|
||||
return 1 if (a.strict and n_flag) else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,225 @@
|
||||
// SpringBone behaviour of one VRM, headless (three.js + three-vrm, no rendering).
|
||||
// node measure.mjs model.vrm → one JSON object on stdout
|
||||
// env: MOTIONS=idle,walk_real,run FPS=60 JITTER=0 (frame-time jitter ratio) DETAIL=3
|
||||
//
|
||||
// rest: after 2 s standing still, how far each spring tip has moved from the bind pose
|
||||
// (a correct setup stays put; large values = joints fight colliders / wrong rest dir)
|
||||
// motions: per chain category (hair = under head/neck, skirt = under hips/legs,
|
||||
// torso = under spine/chest/shoulders, other = arms etc.)
|
||||
// hf tip energy above 8 Hz / chain length ×1000 — genuine shake (gait content < 7 Hz);
|
||||
// mean and max over chains. Native VRoid/sample models: hair ≈ 2–16, skirt ≈ 3–58.
|
||||
// swing peak tip deformation / chain length (anchor-local)
|
||||
// skirtInside share of skirt joint samples inside the model's own leg colliders
|
||||
// (counts rest overlap too — compare against idle)
|
||||
import * as THREE from 'three';
|
||||
import fs from 'fs';
|
||||
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
|
||||
import { VRMLoaderPlugin, VRMUtils } from '@pixiv/three-vrm';
|
||||
import { MOTIONS, FRAMES } from './motions.mjs';
|
||||
|
||||
// Textures and MToon are irrelevant here and slow to decode in Node: strip them.
|
||||
function stripGlb(buf) {
|
||||
const jl = buf.readUInt32LE(12);
|
||||
const json = JSON.parse(buf.slice(20, 20 + jl).toString('utf8'));
|
||||
delete json.images; delete json.textures; delete json.samplers;
|
||||
for (const m of json.materials || []) {
|
||||
if (m.pbrMetallicRoughness) delete m.pbrMetallicRoughness.baseColorTexture;
|
||||
delete m.extensions; delete m.normalTexture; delete m.emissiveTexture; delete m.occlusionTexture;
|
||||
}
|
||||
json.extensionsUsed = (json.extensionsUsed || []).filter((e) => e !== 'VRMC_materials_mtoon' && e !== 'KHR_texture_transform');
|
||||
if (json.extensions && json.extensions.VRM) json.extensions.VRM.materialProperties = [];
|
||||
let js = Buffer.from(JSON.stringify(json));
|
||||
js = Buffer.concat([js, Buffer.alloc((4 - js.length % 4) % 4, 0x20)]);
|
||||
const bin = buf.slice(20 + jl);
|
||||
const h = Buffer.alloc(20);
|
||||
h.writeUInt32LE(0x46546c67, 0); h.writeUInt32LE(2, 4); h.writeUInt32LE(20 + js.length + bin.length, 8);
|
||||
h.writeUInt32LE(js.length, 12); h.writeUInt32LE(0x4e4f534a, 16);
|
||||
const o = Buffer.concat([h, js, bin]);
|
||||
return o.buffer.slice(o.byteOffset, o.byteOffset + o.byteLength);
|
||||
}
|
||||
|
||||
async function load(path) {
|
||||
const loader = new GLTFLoader();
|
||||
loader.register((p) => new VRMLoaderPlugin(p));
|
||||
const warn = console.warn; console.warn = () => {}; // material-bind warnings: materials were stripped
|
||||
try {
|
||||
const vrm = await new Promise((r, j) => loader.parse(stripGlb(fs.readFileSync(path)), '', (g) => r(g.userData.vrm), j));
|
||||
if (vrm.meta && vrm.meta.metaVersion === '0') VRMUtils.rotateVRM0(vrm);
|
||||
new THREE.Scene().add(vrm.scene);
|
||||
vrm.update(0); vrm.scene.updateMatrixWorld(true);
|
||||
return vrm;
|
||||
} finally { console.warn = warn; }
|
||||
}
|
||||
|
||||
const wp = (o) => new THREE.Vector3().setFromMatrixPosition(o.matrixWorld);
|
||||
const LEG = ['leftUpperLeg', 'rightUpperLeg', 'leftLowerLeg', 'rightLowerLeg'];
|
||||
const LEG_CHILD = { leftUpperLeg: 'leftLowerLeg', rightUpperLeg: 'rightLowerLeg', leftLowerLeg: 'leftFoot', rightLowerLeg: 'rightFoot' };
|
||||
|
||||
async function restDrift(path) {
|
||||
const vrm = await load(path);
|
||||
const joints = vrm.springBoneManager ? [...vrm.springBoneManager.joints] : [];
|
||||
if (!joints.length) return null;
|
||||
const pos = () => joints.map((j) => wp(j.child || j.bone));
|
||||
const p0 = pos();
|
||||
for (let i = 0; i < 120; i++) vrm.update(1 / 60);
|
||||
vrm.scene.updateMatrixWorld(true);
|
||||
const p1 = pos();
|
||||
const d = joints.map((j, i) => [p1[i].distanceTo(p0[i]), j.bone.name]).sort((a, b) => b[0] - a[0]);
|
||||
return { max: d[0][0], maxName: d[0][1], over1cm: d.filter((x) => x[0] > 0.01).length, joints: d.length,
|
||||
top: d.slice(0, 5).map(([v, n]) => [n, +v.toFixed(4)]) };
|
||||
}
|
||||
|
||||
function chainsOf(vrm) {
|
||||
const h = vrm.humanoid, sbm = vrm.springBoneManager;
|
||||
const roleOf = new Map(Object.keys(h.humanBones).map((r) => [h.getRawBoneNode(r), r]));
|
||||
const joints = [...sbm.joints];
|
||||
const jbones = new Set(joints.map((j) => j.bone));
|
||||
const chains = [];
|
||||
for (const j of joints) {
|
||||
let p = j.bone.parent;
|
||||
while (p && !jbones.has(p) && !roleOf.has(p)) p = p.parent;
|
||||
if (p && jbones.has(p)) continue; // not a chain root
|
||||
const path = [j];
|
||||
for (let cur = j; ;) {
|
||||
const nx = joints.find((k) => { let q = k.bone.parent; while (q && q !== cur.bone && !jbones.has(q)) q = q.parent; return q === cur.bone; });
|
||||
if (!nx) break;
|
||||
path.push(nx); cur = nx;
|
||||
}
|
||||
const tip = path[path.length - 1].child || path[path.length - 1].bone;
|
||||
let anc = j.bone.parent;
|
||||
while (anc && !roleOf.has(anc)) anc = anc.parent;
|
||||
const role = anc ? roleOf.get(anc) : '?';
|
||||
const cat = ['head', 'neck', 'jaw'].includes(role) ? 'hair'
|
||||
: (role === 'hips' || /Leg|Foot|Toes/.test(role)) ? 'skirt'
|
||||
: ['spine', 'chest', 'upperChest', 'leftShoulder', 'rightShoulder'].includes(role) ? 'torso' : 'other';
|
||||
let L = 0, prev = wp(j.bone);
|
||||
for (const k of path.slice(1)) { const q = wp(k.bone); L += q.distanceTo(prev); prev = q; }
|
||||
L += wp(tip).distanceTo(prev);
|
||||
chains.push({ root: j, tip, anchor: anc, cat, joints: path, L: Math.max(L, 0.02) });
|
||||
}
|
||||
return { chains, roleOf };
|
||||
}
|
||||
|
||||
async function measure(path, mname) {
|
||||
const vrm = await load(path);
|
||||
const h = vrm.humanoid, sbm = vrm.springBoneManager;
|
||||
const { chains, roleOf } = chainsOf(vrm);
|
||||
const loc = (c) => (c.anchor ? c.anchor.worldToLocal(wp(c.tip)) : wp(c.tip));
|
||||
// the leg itself: per leg bone the collider whose axis lies closest to the bone (skirt chains may also
|
||||
// have shifted copies of it — see springbone.leg_proxy_shift — those are not the leg)
|
||||
const legCols = [];
|
||||
for (const role of LEG) {
|
||||
const bone = h.getRawBoneNode(role), child = h.getRawBoneNode(LEG_CHILD[role]);
|
||||
if (!bone) continue;
|
||||
const end = child && child !== bone ? bone.worldToLocal(wp(child)) : new THREE.Vector3(0, -0.4, 0);
|
||||
const seg = new THREE.Line3(new THREE.Vector3(), end);
|
||||
let best = null;
|
||||
for (const g of sbm.colliderGroups) for (const col of g.colliders) {
|
||||
if (col.parent !== bone) continue;
|
||||
const s = col.shape, m = s.tail ? s.offset.clone().add(s.tail).multiplyScalar(0.5) : s.offset.clone();
|
||||
const d = seg.closestPointToPoint(m, true, new THREE.Vector3()).distanceTo(m) - (s.radius || 0) * 0.01;
|
||||
if (!best || d < best[0] - 1e-4) best = [d, col];
|
||||
}
|
||||
if (best) legCols.push(best[1]);
|
||||
}
|
||||
const node = (n) => h.getNormalizedBoneNode(n);
|
||||
// VRM 0.x normalized bones (after rotateVRM0) turn the other way round X and Z in three-vrm
|
||||
const sg = vrm.meta && vrm.meta.metaVersion === '0' ? -1 : 1;
|
||||
const rot = (n, x, y, z, order) => node(n).rotation.set(x * sg, y, z * sg, order);
|
||||
for (let i = 0; i < 60; i++) vrm.update(1 / 60); // settle before measuring
|
||||
vrm.scene.updateMatrixWorld(true);
|
||||
const rest = chains.map(loc);
|
||||
const traj = chains.map(() => []);
|
||||
// skirt opening: neighbouring skirt chains (each chain's 2 nearest roots, within 2× the median
|
||||
// nearest-root spacing) — how much further apart their tips get than at rest
|
||||
const hipsY = wp(h.getRawBoneNode('hips')).y;
|
||||
const ring = chains.filter((c) => (c.cat === 'skirt' && roleOf.get(c.anchor) === 'hips')
|
||||
|| (c.cat === 'torso' && wp(c.tip).y < hipsY));
|
||||
const pairs = [];
|
||||
if (ring.length > 2) {
|
||||
const rp = ring.map((c) => wp(c.root.bone));
|
||||
const near = ring.map((c, i) => rp.map((p, j) => [i === j ? Infinity : p.distanceTo(rp[i]), j]).sort((a, b) => a[0] - b[0]));
|
||||
const med = near.map((n) => n[0][0]).sort((a, b) => a - b)[ring.length >> 1];
|
||||
const seen = new Set();
|
||||
near.forEach((n, i) => n.slice(0, 2).forEach(([d, j]) => {
|
||||
const k = Math.min(i, j) + ':' + Math.max(i, j);
|
||||
if (d < med * 2 && !seen.has(k)) { seen.add(k); pairs.push([ring[i], ring[j], wp(ring[i].tip).distanceTo(wp(ring[j].tip)), 0]); }
|
||||
}));
|
||||
}
|
||||
let inside = 0, skirtTips = 0;
|
||||
const N = FRAMES[mname];
|
||||
const fps = +(process.env.FPS || 60), jit = +(process.env.JITTER || 0);
|
||||
let acc60 = 0, seed = 12345, nextDt = 1 / fps;
|
||||
const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
|
||||
for (let f = 0; f < N + 120; f++) {
|
||||
const p = f < N ? MOTIONS[mname](f) : (mname === 'idle' ? MOTIONS[mname](N - 1) : {});
|
||||
rot('hips', 0, p.yaw || 0, p.roll || 0);
|
||||
if (p.spineYaw != null) rot('spine', 0, p.spineYaw, 0);
|
||||
vrm.scene.position.set(0, p.bob || 0, p.rootZ || 0);
|
||||
rot('leftUpperLeg', p.lLeg || 0, 0, 0); rot('rightUpperLeg', p.rLeg || 0, 0, 0);
|
||||
rot('leftLowerLeg', p.lKnee || 0, 0, 0); rot('rightLowerLeg', p.rKnee || 0, 0, 0);
|
||||
if (p.armDown != null) {
|
||||
const a = 1.22 * Math.min(1, p.armDown / 0.7);
|
||||
rot('leftUpperArm', p.armSwingL || 0, 0, -a, 'XYZ'); rot('rightUpperArm', p.armSwingR || 0, 0, a, 'XYZ');
|
||||
rot('leftLowerArm', 0, p.armSwingL ? -0.3 : 0, 0); rot('rightLowerArm', 0, p.armSwingR ? 0.3 : 0, 0);
|
||||
}
|
||||
// physics at FPS (optionally jittered), motion sampled at 60 Hz
|
||||
acc60 += 1 / 60;
|
||||
while (acc60 >= nextDt - 1e-9) { vrm.update(nextDt); acc60 -= nextDt; nextDt = (1 / fps) * (1 + jit * (rnd() * 2 - 1)); }
|
||||
vrm.scene.updateMatrixWorld(true);
|
||||
chains.forEach((c, i) => traj[i].push(loc(c).sub(rest[i])));
|
||||
if (f < N) for (const p of pairs) p[3] = Math.max(p[3], wp(p[0].tip).distanceTo(wp(p[1].tip)) - p[2]);
|
||||
if (legCols.length) for (const c of chains) if (c.cat === 'skirt') {
|
||||
for (const j of c.joints) {
|
||||
const t = wp(j.child || j.bone); skirtTips++;
|
||||
for (const col of legCols) { if (col.shape.calculateCollision(col.colliderMatrix, t, 0, new THREE.Vector3()) < -0.005) { inside++; c.inside = (c.inside || 0) + 1; break; } }
|
||||
}
|
||||
}
|
||||
}
|
||||
const W0 = (mname === 'walk_real' || mname === 'run') ? 60 : 0; // skip the start-up transient
|
||||
const hfOf = (i) => { // spectral energy above 8 Hz
|
||||
const T = traj[i], hi = Math.min(N, T.length), n = hi - W0;
|
||||
if (n < 32) return 0;
|
||||
let e = 0;
|
||||
for (const ax of ['x', 'y', 'z']) {
|
||||
const xs = []; for (let t = W0; t < hi; t++) xs.push(T[t][ax]);
|
||||
const mean = xs.reduce((a, b) => a + b, 0) / n;
|
||||
for (let k = Math.ceil(8 * n / 60); k <= n / 2; k++) {
|
||||
let re = 0, im = 0;
|
||||
for (let t = 0; t < n; t++) { const a = 2 * Math.PI * k * t / n; re += (xs[t] - mean) * Math.cos(a); im -= (xs[t] - mean) * Math.sin(a); }
|
||||
e += (re * re + im * im) * 2 / (n * n);
|
||||
}
|
||||
}
|
||||
return Math.sqrt(e) / chains[i].L * 1000;
|
||||
};
|
||||
const hf = chains.map((c, i) => hfOf(i));
|
||||
const swingOf = (i) => Math.max(0, ...traj[i].slice(W0, N).map((v) => v.length())) / chains[i].L;
|
||||
const out = { cats: {} };
|
||||
for (const cat of ['hair', 'skirt', 'torso', 'other']) {
|
||||
const ids = chains.map((c, i) => (c.cat === cat ? i : -1)).filter((i) => i >= 0);
|
||||
if (!ids.length) continue;
|
||||
out.cats[cat] = { n: ids.length, hf: ids.reduce((a, i) => a + hf[i], 0) / ids.length,
|
||||
hfMax: Math.max(...ids.map((i) => hf[i])), swing: Math.max(...ids.map(swingOf)) };
|
||||
}
|
||||
const nd = +(process.env.DETAIL || 3);
|
||||
out.skirtInside = skirtTips ? inside / skirtTips : null;
|
||||
if (inside) out.insideWorst = chains.filter((c) => c.inside).sort((a, b) => b.inside - a.inside).slice(0, nd)
|
||||
.map((c) => [c.root.bone.name, +(c.inside / c.joints.length / (N + 120)).toFixed(3)]);
|
||||
if (pairs.length) {
|
||||
const g = pairs.map((p) => p[3]).sort((a, b) => a - b);
|
||||
out.skirtGap = { pairs: g.length, mean: g.reduce((a, b) => a + b, 0) / g.length, p90: g[Math.floor(g.length * 0.9)], max: g[g.length - 1],
|
||||
worst: pairs.sort((a, b) => b[3] - a[3]).slice(0, nd).map((p) => [p[0].root.bone.name, p[1].root.bone.name, +p[2].toFixed(3), +p[3].toFixed(3)]) };
|
||||
}
|
||||
out.worst = chains.map((c, i) => [hf[i], i]).sort((a, b) => b[0] - a[0]).slice(0, nd)
|
||||
.map(([v, i]) => ({ cat: chains[i].cat, chain: chains[i].root.bone.name, hf: +v.toFixed(2), swing: +swingOf(i).toFixed(3),
|
||||
joints: chains[i].joints.length, length: +chains[i].L.toFixed(3) }));
|
||||
return out;
|
||||
}
|
||||
|
||||
const path = process.argv[2];
|
||||
if (!path) { console.error('usage: node measure.mjs model.vrm'); process.exit(2); }
|
||||
const result = { file: path, rest: await restDrift(path), motions: {} };
|
||||
if (result.rest) {
|
||||
for (const m of (process.env.MOTIONS || 'idle,walk_real,run').split(',')) result.motions[m] = await measure(path, m);
|
||||
}
|
||||
process.stdout.write(JSON.stringify(result) + '\n');
|
||||
@@ -0,0 +1,42 @@
|
||||
// Test motions for measure.mjs. Each returns per-frame pose params (radians), 60 fps,
|
||||
// applied to the VRM's normalized humanoid bones.
|
||||
// yaw: hips rotation about +Y
|
||||
// lLeg/rLeg: thigh pitch about +X (negative = leg forward), lKnee/rKnee: knee bend (+X)
|
||||
const smooth = (t) => t * t * (3 - 2 * t);
|
||||
|
||||
export const MOTIONS = {
|
||||
static: (f) => ({}),
|
||||
yaw_gentle: (f) => ({ yaw: f < 150 ? Math.sin(f / 60 * Math.PI * 2 * 0.8) * 0.35 : 0 }),
|
||||
yaw_strong: (f) => ({ yaw: f < 150 ? Math.sin(f / 60 * Math.PI * 2 * 1.2) * 0.8 : 0 }),
|
||||
leg_raise: (f) => {
|
||||
const k = f < 40 ? smooth(f / 40) : f < 100 ? 1 : f < 140 ? smooth(1 - (f - 100) / 40) : 0;
|
||||
return { lLeg: -1.2 * k, lKnee: 1.0 * k };
|
||||
},
|
||||
walk: (f) => {
|
||||
const s = Math.sin(f / 60 * Math.PI * 2 * 0.9);
|
||||
const a = f < 180 ? 1 : 0;
|
||||
return {
|
||||
lLeg: -0.5 * s * a, rLeg: 0.5 * s * a,
|
||||
lKnee: Math.max(0, s) * 0.6 * a, rKnee: Math.max(0, -s) * 0.6 * a,
|
||||
yaw: Math.sin(f / 60 * Math.PI * 2 * 0.9) * 0.08 * a,
|
||||
};
|
||||
},
|
||||
};
|
||||
// idle: arms lowered from the T-pose rest over 1 s (armDown 0.7 ≈ 70°), slight sway.
|
||||
MOTIONS.idle = (f) => ({ armDown: 0.7 * smooth(Math.min(1, f / 60)), yaw: Math.sin(f / 60 * Math.PI * 2 * 0.25) * 0.05 });
|
||||
// Realistic gait with root motion (forward along +Z), pelvis bob/twist, arm swing.
|
||||
// rootZ: metres travelled; bob: pelvis vertical offset; roll: pelvis roll; arm: forward swing
|
||||
function gait(f, speed, freq, thigh, knee, bob, armSwing) {
|
||||
const t = f / 60, ph = t * Math.PI * 2 * freq;
|
||||
const s = Math.sin(ph);
|
||||
const kneeL = knee * Math.max(0, Math.sin(ph + 0.9)), kneeR = knee * Math.max(0, Math.sin(ph + 0.9 + Math.PI));
|
||||
return {
|
||||
rootZ: speed * t, bob: -bob * Math.cos(2 * ph),
|
||||
yaw: 0.08 * s, roll: 0.04 * Math.sin(2 * ph), spineYaw: -0.1 * s,
|
||||
lLeg: -thigh * s, rLeg: thigh * s, lKnee: 0.1 + kneeL, rKnee: 0.1 + kneeR,
|
||||
armDown: 0.7 * smooth(Math.min(1, f / 40)), armSwingL: armSwing * s, armSwingR: -armSwing * s,
|
||||
};
|
||||
}
|
||||
MOTIONS.walk_real = (f) => (f < 300 ? gait(f, 1.2, 0.9, 0.45, 0.9, 0.025, 0.35) : { ...gait(299, 1.2, 0.9, 0, 0, 0, 0), rootZ: 1.2 * 5, lLeg: 0, rLeg: 0, lKnee: 0, rKnee: 0, yaw: 0, roll: 0, spineYaw: 0, bob: 0, armSwingL: 0, armSwingR: 0 });
|
||||
MOTIONS.run = (f) => (f < 240 ? gait(f, 3.0, 1.4, 0.8, 1.6, 0.05, 0.7) : { rootZ: 3.0 * 4, armDown: 0.7 });
|
||||
export const FRAMES = { walk_real: 300, run: 240, idle: 240, static: 120, yaw_gentle: 240, yaw_strong: 240, leg_raise: 200, walk: 270 };
|
||||
Generated
+157
@@ -0,0 +1,157 @@
|
||||
{
|
||||
"name": "vrmify-qa-harness",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "vrmify-qa-harness",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"@pixiv/three-vrm": "3.5.5",
|
||||
"three": "0.169.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@pixiv/three-vrm": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/three-vrm/-/three-vrm-3.5.5.tgz",
|
||||
"integrity": "sha512-RPXy7jYAXs704NIpZlosB0U2ENu21G9DrqGWdQgRe8dShaCo1ugpj+6BVPRCy91nt+MPMA96j5rbsSzEl0HlQA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@pixiv/three-vrm-core": "3.5.5",
|
||||
"@pixiv/three-vrm-materials-hdr-emissive-multiplier": "3.5.5",
|
||||
"@pixiv/three-vrm-materials-mtoon": "3.5.5",
|
||||
"@pixiv/three-vrm-materials-v0compat": "3.5.5",
|
||||
"@pixiv/three-vrm-node-constraint": "3.5.5",
|
||||
"@pixiv/three-vrm-springbone": "3.5.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">=0.137"
|
||||
}
|
||||
},
|
||||
"node_modules/@pixiv/three-vrm-core": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/three-vrm-core/-/three-vrm-core-3.5.5.tgz",
|
||||
"integrity": "sha512-jjaXZbMVRsk2HAGVxqDLmSJyGOJqbMcJpuTHR1TY/TN1FxiKdAzSqdr/ZUcczYipNf8IL9vDT9NX2XmWj+ybRQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@pixiv/types-vrm-0.0": "3.5.5",
|
||||
"@pixiv/types-vrmc-vrm-1.0": "3.5.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">=0.137"
|
||||
}
|
||||
},
|
||||
"node_modules/@pixiv/three-vrm-materials-hdr-emissive-multiplier": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/three-vrm-materials-hdr-emissive-multiplier/-/three-vrm-materials-hdr-emissive-multiplier-3.5.5.tgz",
|
||||
"integrity": "sha512-XnHEqpY4ctYMucpeRcptdphOe0RrW7V5fUvojasD8Ja4MTjjrjCNFxsAvp3+HBkPZbkTM2sDCjJBJNzxN1scrA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@pixiv/types-vrmc-materials-hdr-emissive-multiplier-1.0": "3.5.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">=0.137"
|
||||
}
|
||||
},
|
||||
"node_modules/@pixiv/three-vrm-materials-mtoon": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/three-vrm-materials-mtoon/-/three-vrm-materials-mtoon-3.5.5.tgz",
|
||||
"integrity": "sha512-7lThHf4OKBOsVenD+R6L6HffNUlKO3Twnhr3+z77MnUsSzsOanjVKJtjSIly9QJ6hgl8YJmI6RnxCKqXcpplog==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@pixiv/types-vrm-0.0": "3.5.5",
|
||||
"@pixiv/types-vrmc-materials-mtoon-1.0": "3.5.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">=0.137"
|
||||
}
|
||||
},
|
||||
"node_modules/@pixiv/three-vrm-materials-v0compat": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/three-vrm-materials-v0compat/-/three-vrm-materials-v0compat-3.5.5.tgz",
|
||||
"integrity": "sha512-NjsTK4P4qdcr+RoL2gEUNgF2CY/aplNvyHHxI99N7D6CxDZ2H93FQ9aIuLCABj5b+4CIvldWMCcnS7YuLIr3Lw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@pixiv/types-vrm-0.0": "3.5.5",
|
||||
"@pixiv/types-vrmc-materials-mtoon-1.0": "3.5.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">=0.137"
|
||||
}
|
||||
},
|
||||
"node_modules/@pixiv/three-vrm-node-constraint": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/three-vrm-node-constraint/-/three-vrm-node-constraint-3.5.5.tgz",
|
||||
"integrity": "sha512-+ShEXioZ5Ctf0EZ5ZViZ4n0jhV/qtJRH0Juw8nRnMNODZXDSr+B3An2lrfRoMhowCzG63GiUG4lXWV9noMXosA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@pixiv/types-vrmc-node-constraint-1.0": "3.5.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">=0.137"
|
||||
}
|
||||
},
|
||||
"node_modules/@pixiv/three-vrm-springbone": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/three-vrm-springbone/-/three-vrm-springbone-3.5.5.tgz",
|
||||
"integrity": "sha512-GWAWrIegGH/u1ZA+Es03Qzc2yafrQOrhtal9jzUIAgU8Wm2DYuqAABOY+du/9RpBRK8D4T8DBPvRGQqvfrQ/uA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@pixiv/types-vrm-0.0": "3.5.5",
|
||||
"@pixiv/types-vrmc-springbone-1.0": "3.5.5",
|
||||
"@pixiv/types-vrmc-springbone-extended-collider-1.0": "3.5.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"three": ">=0.137"
|
||||
}
|
||||
},
|
||||
"node_modules/@pixiv/types-vrm-0.0": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/types-vrm-0.0/-/types-vrm-0.0-3.5.5.tgz",
|
||||
"integrity": "sha512-2S/0jswMjJTwL9ky8YzDR0CIaP6ZmE+HFuyW/0h+SA+awELf+J7WGgC8lTLM1MXzokO7Z2YVljU2F0fEhlKDIQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@pixiv/types-vrmc-materials-hdr-emissive-multiplier-1.0": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-materials-hdr-emissive-multiplier-1.0/-/types-vrmc-materials-hdr-emissive-multiplier-1.0-3.5.5.tgz",
|
||||
"integrity": "sha512-IuHw9ehXt2bymqfdFV+f2cCXo8kvJUfh0Zuut8qmKXoEb7HVyLGIQyS4TcQHG5yY22UTWHI1Axo5tQv35lPTgQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@pixiv/types-vrmc-materials-mtoon-1.0": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-materials-mtoon-1.0/-/types-vrmc-materials-mtoon-1.0-3.5.5.tgz",
|
||||
"integrity": "sha512-GFVuksAJVhrWTXYmI/ucNsE611/d8N6BoZrzhUAAINndt98loyzapW2+DJu+GsUBO5yxd+vLsL0FB16XD9+TGg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@pixiv/types-vrmc-node-constraint-1.0": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-node-constraint-1.0/-/types-vrmc-node-constraint-1.0-3.5.5.tgz",
|
||||
"integrity": "sha512-8EbJ1uzkn9yJQarCChmpG12+mc2c7PimHvQ8H6/tMh/hqp5NtJND0z2lR2KeVxw9A3M+TpF+xgImhLBxGjqwzQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@pixiv/types-vrmc-springbone-1.0": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-springbone-1.0/-/types-vrmc-springbone-1.0-3.5.5.tgz",
|
||||
"integrity": "sha512-gRQ5Y7PaGiMefvOrJ3hvoSPqpA67jiwyhwh8ItjsPi3yri/Hn3CeXplW3Cbx3ZPbfu+C3Q2MCRa2TqAUOjeMRA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@pixiv/types-vrmc-springbone-extended-collider-1.0": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-springbone-extended-collider-1.0/-/types-vrmc-springbone-extended-collider-1.0-3.5.5.tgz",
|
||||
"integrity": "sha512-+6RxLaAvVguP7upjS/OT4viNPWvac1HBRQY1nmdvfYNQuCMdrMsCZqvy2af0Fcjnda4V9JbKFIpZDC0lrw1+uQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@pixiv/types-vrmc-vrm-1.0": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-vrm-1.0/-/types-vrmc-vrm-1.0-3.5.5.tgz",
|
||||
"integrity": "sha512-WnemHHo2375BcBdumEhvrupZzsMSzTfdWlokmV9sUX2oC+OAQqJFfBjLF8ppkOhzHpl4MAPJqEfuhBJtNPm9ww==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/three": {
|
||||
"version": "0.169.0",
|
||||
"resolved": "https://registry.npmjs.org/three/-/three-0.169.0.tgz",
|
||||
"integrity": "sha512-Ed906MA3dR4TS5riErd4QBsRGPcx+HBDX2O5yYE5GqJeFQTPU+M56Va/f/Oph9X7uZo3W3o4l2ZhBZ6f6qUv0w==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "vrmify-qa-harness",
|
||||
"private": true,
|
||||
"description": "SpringBone behaviour tests for converted VRM files (three.js + three-vrm, headless)",
|
||||
"type": "module",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"@pixiv/three-vrm": "3.5.5",
|
||||
"three": "0.169.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""表情截图对照表:每个模型一行——全身、脸、各个表情预设、口型、眨眼、视线四个方向。
|
||||
|
||||
python tools/qa/snapshots.py a.vrm -o a.png
|
||||
python tools/qa/snapshots.py 旧版/a.vrm 新版/a.vrm -o 对比.png 一个输入一行,上下对照
|
||||
python tools/qa/snapshots.py model/角色/角色.pmx -o a.png 非 VRM 先用当前代码转一份(临时目录)
|
||||
python tools/qa/snapshots.py a.vrm --custom -o a.png 再加上模型自己的自定义表情
|
||||
|
||||
用无界面的 Edge / Chrome 渲染,渲染部分就是界面预览用的 ui/viewer/viewer-core.js(three-vrm + MToon),
|
||||
和程序里看到的一样。改表情相关代码前后各拍一张,比对哪里变了;也可以把 tools/regress.py 的样本拍下来看。
|
||||
模型自己没有的表情格子标「无」,不会拿中性脸冒充。
|
||||
|
||||
需要本机装了 Edge 或 Chrome(--browser 指定路径)。WebGL 走软件渲染(SwiftShader),不依赖显卡。
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import urllib.parse
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE))
|
||||
VIEWER = os.path.join(ROOT, "ui", "viewer")
|
||||
for _p in ("convert", "formats"):
|
||||
_d = os.path.join(ROOT, _p)
|
||||
if _d not in sys.path:
|
||||
sys.path.insert(0, _d)
|
||||
|
||||
# 列:[名字, 机位, 表情 {名字: 值}, 视线 (yaw, pitch) 或 None]
|
||||
SHOTS = [["全身", "body", {}, None], ["脸", "face", {}, None]]
|
||||
SHOTS += [[n, "face", {n: 1.0}, None] for n in ("happy", "angry", "sad", "relaxed", "surprised",
|
||||
"aa", "ih", "ou", "ee", "oh", "blink", "blinkLeft", "blinkRight")]
|
||||
SHOTS += [["look" + k, "face", {}, v] for k, v in
|
||||
(("Up", (0, 90)), ("Down", (0, -90)), ("Left", (90, 0)), ("Right", (-90, 0)))]
|
||||
|
||||
PAGE = r"""<!doctype html><meta charset="utf-8">
|
||||
<script type="importmap">{ "imports": {
|
||||
"three": "/viewer/vendor/three/three.module.min.js",
|
||||
"three/addons/": "/viewer/vendor/three/addons/",
|
||||
"@pixiv/three-vrm": "/viewer/vendor/three-vrm/three-vrm.module.min.js" } }</script>
|
||||
<body style="margin:0;background:#222">
|
||||
<script type="module">
|
||||
import { Viewer } from '/viewer/viewer-core.js';
|
||||
const job = await (await fetch('/job')).json();
|
||||
const send = (o) => fetch('/result', { method: 'POST', body: JSON.stringify(o) });
|
||||
try {
|
||||
const S = job.size, PAD = 6, LEFT = 150;
|
||||
const box = document.createElement('div');
|
||||
box.style.cssText = `width:${S}px;height:${S}px`;
|
||||
document.body.append(box);
|
||||
const v = new Viewer(box, { background: '#8a8f98' });
|
||||
v.paused = true;
|
||||
const rows = [];
|
||||
for (const m of job.models) {
|
||||
await v.loadUrl(m.url, m.name);
|
||||
const em = v.vrm.expressionManager, la = v.vrm.lookAt;
|
||||
const PRESET = new Set(['happy', 'angry', 'sad', 'relaxed', 'surprised', 'aa', 'ih', 'ou', 'ee', 'oh', 'blink',
|
||||
'blinkLeft', 'blinkRight', 'lookUp', 'lookDown', 'lookLeft', 'lookRight', 'neutral']);
|
||||
const custom = job.custom && em ? em.expressions.map((e) => e.expressionName).filter((n) => !PRESET.has(n)) : [];
|
||||
const shots = job.shots.concat(custom.map((n) => [n, 'face', { [n]: 1 }, null]));
|
||||
v.motion = 'idle'; v._applyMotion(0);
|
||||
v.vrm.update(1 / 60);
|
||||
const cells = [];
|
||||
for (const [label, cam, expr, look] of shots) {
|
||||
const missing = Object.keys(expr).find((n) => !(em && em.getExpression(n))) || (look && !(la && la.applier));
|
||||
v.resetExpressions();
|
||||
for (const [n, w] of Object.entries(expr)) if (!missing) v.setExpression(n, w);
|
||||
if (look && !missing) v.setLook(look[0], look[1]); else v.setLook(null);
|
||||
v.vrm.update(0);
|
||||
// 比界面预览的机位更紧:脸占满格子、全身刚好放下(竖直视角 30°)
|
||||
const H = v.height, h = v.headY, cy = v.centerY ?? H * 0.52;
|
||||
const [pos, tgt] = cam === 'face' ? [[0, h - H * 0.02, H * 0.34], [0, h - H * 0.024, 0]]
|
||||
: [[0, cy, H * 2.1], [0, cy, 0]];
|
||||
v.camera.position.set(...pos); v.controls.target.set(...tgt); v.controls.update();
|
||||
const c = document.createElement('canvas'); c.width = c.height = S;
|
||||
const g = c.getContext('2d');
|
||||
v.renderer.render(v.scene, v.camera);
|
||||
g.drawImage(v.renderer.domElement, 0, 0, S, S);
|
||||
if (missing) { g.fillStyle = 'rgba(0,0,0,.55)'; g.fillRect(0, 0, S, S); g.fillStyle = '#fff'; g.font = `bold ${S / 6}px sans-serif`; g.textAlign = 'center'; g.fillText('无', S / 2, S / 2 + S / 16); }
|
||||
cells.push([label, c]);
|
||||
}
|
||||
v.setLook(null);
|
||||
rows.push([m.label, cells]);
|
||||
}
|
||||
// 每 job.cols 列一段;每段里每个模型一行。每格自带标题(各模型的自定义表情不一样,不能共用表头)
|
||||
const CAP = 20, ncol = Math.max(...rows.map((r) => r[1].length)), cols = Math.min(job.cols, ncol);
|
||||
const bands = Math.ceil(ncol / cols), rowH = S + CAP + PAD;
|
||||
const W = LEFT + cols * (S + PAD) + PAD, H = PAD + bands * (rows.length * rowH + PAD);
|
||||
const out = document.createElement('canvas'); out.width = W; out.height = H;
|
||||
const g = out.getContext('2d');
|
||||
g.fillStyle = '#222'; g.fillRect(0, 0, W, H);
|
||||
g.font = '14px sans-serif'; g.textBaseline = 'middle';
|
||||
for (let b = 0; b < bands; b++) {
|
||||
rows.forEach(([label, cells], r) => {
|
||||
const y = PAD + b * (rows.length * rowH + PAD) + r * rowH;
|
||||
g.textAlign = 'left'; g.fillStyle = '#ddd';
|
||||
const lines = ['']; // 按实际宽度折行
|
||||
for (const ch of label) {
|
||||
if (g.measureText(lines[lines.length - 1] + ch).width > LEFT - 14) lines.push('');
|
||||
lines[lines.length - 1] += ch;
|
||||
}
|
||||
lines.slice(0, Math.floor(S / 18)).forEach((w, k) => g.fillText(w, 8, y + CAP + 12 + k * 18));
|
||||
cells.slice(b * cols, (b + 1) * cols).forEach(([name, c], i) => {
|
||||
const x = LEFT + PAD + i * (S + PAD);
|
||||
g.fillStyle = '#ddd'; g.textAlign = 'center';
|
||||
let t = name;
|
||||
while (t.length > 1 && g.measureText(t).width > S - 4) t = t.slice(0, -1);
|
||||
g.fillText(t === name ? t : t.slice(0, -1) + '…', x + S / 2, y + CAP / 2);
|
||||
g.drawImage(c, x, y + CAP);
|
||||
});
|
||||
});
|
||||
}
|
||||
await send({ png: out.toDataURL('image/png') });
|
||||
} catch (e) { await send({ error: String(e && e.stack || e) }); }
|
||||
</script>
|
||||
"""
|
||||
|
||||
|
||||
def find_browser(path=None):
|
||||
cands = [path] if path else []
|
||||
for env in ("PROGRAMFILES(X86)", "PROGRAMFILES", "LOCALAPPDATA"):
|
||||
base = os.environ.get(env)
|
||||
if base:
|
||||
cands += [os.path.join(base, "Microsoft", "Edge", "Application", "msedge.exe"),
|
||||
os.path.join(base, "Google", "Chrome", "Application", "chrome.exe")]
|
||||
cands += [shutil.which(n) for n in ("msedge", "chrome", "google-chrome", "chromium")]
|
||||
return next((c for c in cands if c and os.path.isfile(c)), None)
|
||||
|
||||
|
||||
# ---- 浏览器进程的清理
|
||||
# 只结束浏览器主进程是不够的:Windows 上它的子进程(GPU、渲染进程)会留下来,软件渲染的 GPU 进程
|
||||
# 一直占满一个核。所以结束时连同整棵进程树一起结束;每次开始前再按临时配置目录名找出以前遗留的进程。
|
||||
PROFILE_PREFIX = "vrmify_snap_profile_"
|
||||
OWNER_FILE = "owner.pid" # 配置目录里记着是哪个进程开的浏览器,用来判断是不是遗留的
|
||||
|
||||
|
||||
def browser_procs(marker=PROFILE_PREFIX):
|
||||
"""命令行里带 marker 的进程 → [(进程号, 命令行)](截图浏览器的命令行里有它的临时配置目录)。"""
|
||||
try:
|
||||
if os.name == "nt":
|
||||
ps = ("Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $PID -and "
|
||||
"$_.CommandLine -like '*%s*' } | ForEach-Object { \"$($_.ProcessId)`t$($_.CommandLine)\" }" % marker)
|
||||
out = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", ps],
|
||||
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60).stdout
|
||||
rows = [ln.split("\t", 1) for ln in out.splitlines() if "\t" in ln]
|
||||
else:
|
||||
out = subprocess.run(["ps", "-eo", "pid=,args="], capture_output=True, text=True, timeout=60).stdout
|
||||
rows = [ln.strip().split(None, 1) for ln in out.splitlines() if marker in ln]
|
||||
return [(int(p), cmd) for p, cmd in rows if p.strip().isdigit() and int(p) != os.getpid()]
|
||||
except (OSError, subprocess.SubprocessError, ValueError):
|
||||
return []
|
||||
|
||||
|
||||
def _kill_pid(pid):
|
||||
"""结束进程和它的子进程。"""
|
||||
try:
|
||||
if os.name == "nt":
|
||||
subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, timeout=60)
|
||||
else:
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
|
||||
|
||||
def _alive(pid):
|
||||
try:
|
||||
if os.name == "nt":
|
||||
out = subprocess.run(["tasklist", "/FI", "PID eq %d" % pid, "/NH", "/FO", "CSV"],
|
||||
capture_output=True, text=True, errors="replace", timeout=60).stdout
|
||||
return '"%d"' % pid in out
|
||||
os.kill(pid, 0)
|
||||
return True
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return False
|
||||
|
||||
|
||||
def stop_browser(proc, prof):
|
||||
"""结束这次截图的浏览器:整棵进程树;主进程先退出了的、树已经断开的,按配置目录名再找一遍。"""
|
||||
if os.name == "nt":
|
||||
_kill_pid(proc.pid)
|
||||
else:
|
||||
try:
|
||||
os.killpg(proc.pid, signal.SIGKILL) # 浏览器单独一个进程组(start_new_session)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
proc.wait(10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
for pid, _ in browser_procs(os.path.basename(prof)):
|
||||
_kill_pid(pid)
|
||||
|
||||
|
||||
def cleanup_stale(tmp=None):
|
||||
"""以前遗留的截图浏览器和临时配置目录(异常退出、或者旧版本没关干净的)。正在跑的别的截图
|
||||
(配置目录里记的进程还活着)不动。"""
|
||||
tmp = tmp or tempfile.gettempdir()
|
||||
live = set()
|
||||
try:
|
||||
names = [n for n in os.listdir(tmp) if n.startswith(PROFILE_PREFIX)]
|
||||
except OSError:
|
||||
names = []
|
||||
for n in names:
|
||||
try:
|
||||
with open(os.path.join(tmp, n, OWNER_FILE)) as f:
|
||||
owner = int(f.read().strip() or 0)
|
||||
except (OSError, ValueError):
|
||||
owner = 0
|
||||
if owner and owner != os.getpid() and _alive(owner):
|
||||
live.add(n)
|
||||
for pid, cmd in browser_procs():
|
||||
m = re.search(re.escape(PROFILE_PREFIX) + r"[^\s\"'\\/]*", cmd)
|
||||
if m and m.group(0) not in live:
|
||||
_kill_pid(pid)
|
||||
for n in names:
|
||||
if n not in live:
|
||||
shutil.rmtree(os.path.join(tmp, n), ignore_errors=True)
|
||||
|
||||
|
||||
def row_label(path, all_paths):
|
||||
"""行标签:文件名(不带扩展名);有同名的行时前面加上所在文件夹名。"""
|
||||
def short(p):
|
||||
return os.path.splitext(os.path.basename(p.split(" · ")[0]))[0] + (" · " + p.split(" · ")[1] if " · " in p else "")
|
||||
if sum(short(q) == short(path) for q in all_paths) > 1:
|
||||
return os.path.basename(os.path.dirname(os.path.abspath(path.split(" · ")[0]))) + "/" + short(path)
|
||||
return short(path)
|
||||
|
||||
|
||||
def to_vrms(paths, tmp, log):
|
||||
"""→ [(行标签, VRM 路径)];不是 VRM 的先用当前代码转(临时目录,按 VRM 1.0 的默认选项)。"""
|
||||
import pipeline
|
||||
out = []
|
||||
for i, p in enumerate(paths):
|
||||
if p.lower().endswith(".vrm"):
|
||||
out.append((p, p))
|
||||
continue
|
||||
d = os.path.join(tmp, "conv%d" % i)
|
||||
log("转换 %s …" % os.path.basename(p))
|
||||
vrms = [v for v in pipeline.convert_file(p, {}, out_dir=d) if v.lower().endswith(".vrm")]
|
||||
if not vrms:
|
||||
raise SystemExit("%s 没有转出 VRM" % p)
|
||||
out += [(p if len(vrms) == 1 else "%s · %s" % (p, os.path.basename(v)), v) for v in vrms]
|
||||
return out
|
||||
|
||||
|
||||
def shoot(models, out_png, size=224, custom=False, browser=None, timeout=300, cols=len(SHOTS)):
|
||||
exe = find_browser(browser)
|
||||
if not exe:
|
||||
raise SystemExit("找不到 Edge / Chrome(用 --browser 指定路径)")
|
||||
files = {"/model/%d.vrm" % i: p for i, (_, p) in enumerate(models)}
|
||||
models = [(row_label(label, [m[0] for m in models]), p) for label, p in models]
|
||||
job = {"size": size, "custom": custom, "shots": SHOTS, "cols": cols,
|
||||
"models": [{"url": "/model/%d.vrm" % i, "name": os.path.basename(p), "label": label}
|
||||
for i, (label, p) in enumerate(models)]}
|
||||
result, done = {}, threading.Event()
|
||||
|
||||
class H(SimpleHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _send(self, data, ctype):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
p = urllib.parse.unquote(urllib.parse.urlsplit(self.path).path)
|
||||
if p == "/":
|
||||
return self._send(PAGE.encode("utf-8"), "text/html; charset=utf-8")
|
||||
if p == "/job":
|
||||
return self._send(json.dumps(job, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
if p in files:
|
||||
with open(files[p], "rb") as f:
|
||||
return self._send(f.read(), "model/gltf-binary")
|
||||
return super().do_GET()
|
||||
|
||||
def translate_path(self, path):
|
||||
p = urllib.parse.unquote(urllib.parse.urlsplit(path).path)
|
||||
parts = [x for x in p[len("/viewer/"):].split("/") if x not in ("", ".", "..")] if p.startswith("/viewer/") else []
|
||||
return os.path.join(VIEWER, *parts) if parts else os.path.join(VIEWER, "__none__")
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
result.update(json.loads(self.rfile.read(n).decode("utf-8")))
|
||||
self._send(b"{}", "application/json")
|
||||
done.set()
|
||||
|
||||
cleanup_stale()
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
prof = tempfile.mkdtemp(prefix=PROFILE_PREFIX)
|
||||
with open(os.path.join(prof, OWNER_FILE), "w") as f:
|
||||
f.write(str(os.getpid()))
|
||||
url = "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
proc = None
|
||||
try:
|
||||
proc = subprocess.Popen([exe, "--headless=new", "--use-angle=swiftshader", "--enable-unsafe-swiftshader",
|
||||
"--no-first-run", "--no-default-browser-check", "--disable-extensions",
|
||||
"--user-data-dir=" + prof]
|
||||
# Linux 的 CI(Ubuntu 24.04 限制了非特权用户命名空间)里 Chrome 的沙箱起不来;只加载本地页面
|
||||
+ ([] if os.name == "nt" else ["--no-sandbox"]) + [url],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
start_new_session=os.name != "nt")
|
||||
if not done.wait(timeout):
|
||||
raise SystemExit("%d 秒内浏览器没有交回截图" % timeout)
|
||||
finally:
|
||||
if proc is not None:
|
||||
stop_browser(proc, prof)
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
shutil.rmtree(prof, ignore_errors=True)
|
||||
if "error" in result:
|
||||
raise SystemExit("页面出错:\n" + result["error"])
|
||||
data = base64.b64decode(result["png"].split(",", 1)[1])
|
||||
os.makedirs(os.path.dirname(os.path.abspath(out_png)), exist_ok=True)
|
||||
with open(out_png, "wb") as f:
|
||||
f.write(data)
|
||||
return out_png
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description="表情截图对照表(每个输入一行)")
|
||||
ap.add_argument("inputs", nargs="+", help=".vrm,或任何能转换的模型(先用当前代码转)")
|
||||
ap.add_argument("-o", "--out", default="snapshots.png", help="输出 PNG")
|
||||
ap.add_argument("--size", type=int, default=224, help="每格边长(像素)")
|
||||
ap.add_argument("--custom", action="store_true", help="再加上模型自己的自定义表情")
|
||||
ap.add_argument("--cols", type=int, default=len(SHOTS), help="每段多少列,超出的换到下一段(默认 %d,正好放下标准的一组)" % len(SHOTS))
|
||||
ap.add_argument("--browser", help="Edge / Chrome 的路径(默认自动找)")
|
||||
ap.add_argument("--timeout", type=int, default=300)
|
||||
a = ap.parse_args(argv)
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
tmp = tempfile.mkdtemp(prefix="vrmify_snap_")
|
||||
try:
|
||||
models = to_vrms(a.inputs, tmp, print)
|
||||
print("截图 %d 个模型 …" % len(models))
|
||||
shoot(models, a.out, a.size, a.custom, a.browser, a.timeout, a.cols)
|
||||
print("已写出 %s" % os.path.abspath(a.out))
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user