#!/usr/bin/env python3 """Graft a mesh and its skin from a donor FBX into one that was exported without geometry. fbx_graft_mesh.py --selftest ... byte-identical round trip fbx_graft_mesh.py --inspect ... what geometry/skin a file holds fbx_graft_mesh.py --donor [--bind X] graft, in place `--bind` decides whose bind pose — whose rest pose, as an importer will show it — the repaired clip ends up with. `donor` (the default) adopts the donor's, which is what keeps a species' clips sharing one rest pose; `self` keeps the target's own, re-posing the grafted mesh to match; a path takes a third file's. `KingCobra-Walk.fbx` is the one clip in this dataset with no geometry: the export dropped `Geometry::Mesh` and `Model::Mesh` while keeping the skeleton, the animation curves, the materials and the embedded textures. Its two `Deformer::Skin` objects survived as orphans, and they index a 1110-vertex mesh that exists in no file — every other KingCobra clip carries the same 2220-vertex mesh instead. The orphan skin is therefore unrecoverable, and the fix is to bring in a sibling's complete geometry-plus-skin package. That is sound because the two rigs are the same skeleton: identical bone names, identical parenting, and identical `PreRotation` on all 19 bones. The donor's bind *posture* differs, but a skin cluster stores `Transform = MeshGlobal_bind · inverse(TransformLink)`, which resolves a vertex into the bone's own local frame and so cancels the posture it was bound in. The deformation is then reconstructed from whatever world matrix the target's own animation gives each bone, frame by frame. What moves: `Geometry::Mesh`, `Model::Mesh`, `Deformer::Skin`, its `Cluster`s and `Pose::BindPose`. What is deleted: the target's orphan skins and clusters. Every copied object gets a fresh uid, and connections that point at the donor's bones, materials or textures are re-pointed at the target's own by name — nothing about the target's skeleton, curves or embedded pixels is touched. Correctness gate: with no edits the serializer must reproduce its input byte for byte (`--selftest`), the same gate `fbx_embed_texture.py` uses. Writes through a temporary file and renames it into place. Clips here are hardlinks of files in `Truebone_Z-OO/`, and writing to such a path writes through to the original; `os.replace` swaps the name and leaves the source alone. """ import collections, math, os, struct, sys, zlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from fbx_embed_texture import parse, serialize, Node, ELEM, SCALAR # ---------------------------------------------------------------- properties def sval(pr): t, pay = pr if t in "SR": return pay return {"L": " (class, name, subtype, node)""" o = top(tree, b"Objects"); out = {} if not o: return out for ch in o.children: if len(ch.props) >= 3: out[sval(ch.props[0])] = (ch.name, sval(ch.props[1]), sval(ch.props[2]), ch) return out def connections(tree): c = top(tree, b"Connections") return [] if not c else [tuple(sval(x) for x in ch.props) for ch in c.children] def copy_node(n): c = Node(n.name) c.props = list(n.props) c.nullrec = n.nullrec c.children = [copy_node(x) for x in n.children] return c # ---------------------------------------------------------------- inspection def inspect(path): t = parse(path); o = objects(t) verts = polys = 0 for uid, (cls, nm, sub, node) in o.items(): if cls == b"Geometry": for ch in node.children: if ch.name == b"Vertices": length = struct.unpack("= 3 and sval(ch.props[0]) in orphan)] tcon.children = [ch for ch in tcon.children if not ({sval(ch.props[1]), sval(ch.props[2])} & orphan)] log.append("删除孤儿 %d 个 Deformer 及其连接" % len(orphan)) # 2. name-indexed lookup into the target, for re-pointing -------------- by_name = collections.defaultdict(dict) for u, (c, n, s, _) in to.items(): by_name[c][clean(n)] = u # 3. copy the donor's geometry package in, with fresh uids ------------- nxt = max(list(to) + list(do)) + 1000 remap, moved = {}, [] for u, (c, n, s, node) in sorted(do.items()): if (c, s) in MOVE: remap[u] = nxt; nxt += 1 moved.append((u, c, n, s, node)) for u, c, n, s, node in moved: cp = copy_node(node) cp.props[0] = uid_prop(remap[u]) tobj.children.append(cp) log.append("移入 %d 个对象: %s" % (len(moved), ", ".join( "%s::%s" % (clean(c), clean(s)) for _, c, _, s, _ in moved[:3]) + " …")) # 4. re-point the donor's bind pose at the target's own nodes ---------- dropped_pose = 0 for u, c, n, s, node in moved: if (c, s) != (b"Pose", b"BindPose"): continue cp = [x for x in tobj.children if sval(x.props[0]) == remap[u]][0] keep = [] for pn in cp.children: if pn.name != b"PoseNode": keep.append(pn); continue ref = next((ch for ch in pn.children if ch.name == b"Node"), None) new = ref and translate(sval(ref.props[0]), do, remap, by_name) if new is None: dropped_pose += 1; continue ref.props[0] = uid_prop(new); keep.append(pn) cp.children = keep for ch in cp.children: # NbPoseNodes must follow if ch.name == b"Properties70": continue if ch.name == b"NbPoseNodes": ch.props[0] = ("I", struct.pack(" 3: n.props.append(("S", con[3])) tcon.children.append(n); added += 1 log.append("接入 %d 条连接(%d 条无对应端点已跳过,弃用 PoseNode %d 个)" % (added, skipped, dropped_pose)) # 6. put the mesh back into this clip's own bind pose if tl_target: rebind(tt, tl_target, log) if not had_pose and tl_target: # the donor's BindPose records the donor's posture; once the mesh has been # moved somewhere else it is wrong, and this clip shipped without one anyway gone = {u for u, (c, n, s, _) in objects(tt).items() if c == b"Pose"} if gone: tobj.children = [ch for ch in tobj.children if not (len(ch.props) >= 3 and sval(ch.props[0]) in gone)] tcon.children = [ch for ch in tcon.children if not ({sval(ch.props[1]), sval(ch.props[2])} & gone)] log.append("丢弃供体 BindPose %d 个(本片原本没有,且它记的是供体姿势)" % len(gone)) # 7. collapse the LayeredTexture indirection so importers find the pixels n_add, n_lay = collapse_layered(tt) if n_lay: log.append("压平 %d 个 LayeredTexture,改为 %d 条 Texture→Material 直连" % (n_lay, n_add)) # 8. keep Definitions counts honest ----------------------------------- defs = top(tt, b"Definitions") if defs: want = collections.Counter() for u, (c, n, s, _) in objects(tt).items(): want[c] += 1 for ch in defs.children: if ch.name != b"ObjectType": continue k = sval(ch.props[0]) if k in want: for cc in ch.children: if cc.name == b"Count": cc.props[0] = ("I", struct.pack(" Material` directly, dropping the `LayeredTexture` level. This clip routes its textures `Video -> Texture -> LayeredTexture -> Material`. That is legal FBX, but importers that only look for a texture connected straight to a material property see an untextured mesh — the pixels load and go unused. It is the only file in the dataset wired this way; the other 1,096 connect `Texture -> Material` directly, which is what this reproduces. """ to, tcon, tobj = objects(tt), top(tt, b"Connections"), top(tt, b"Objects") layered = {u for u, (c, n, s, _) in to.items() if c == b"LayeredTexture"} if not layered: return 0, 0 feed = {} # LayeredTexture uid -> Texture uid for con in connections(tt): if con[0] == b"OO" and con[2] in layered and to.get(con[1], (b"",))[0] == b"Texture": feed[con[2]] = con[1] kept, added = [], 0 for ch in tcon.children: p = [sval(x) for x in ch.props] if not ({p[1], p[2]} & layered): kept.append(ch); continue if p[1] in layered and len(p) > 3 and to.get(p[2], (b"",))[0] == b"Material" \ and p[1] in feed: n = Node(b"C") n.props = [("S", p[0]), uid_prop(feed[p[1]]), uid_prop(p[2]), ("S", p[3])] kept.append(n); added += 1 tcon.children = kept tobj.children = [ch for ch in tobj.children if not (len(ch.props) >= 3 and sval(ch.props[0]) in layered)] return added, len(layered) def translate(uid, do, remap, by_name): """A donor uid, as it should be referred to inside the target.""" if uid == 0: return 0 # scene root if uid in remap: return remap[uid] # object we just moved ent = do.get(uid) if not ent: return None cls, nm, sub, _ = ent return by_name.get(cls, {}).get(clean(nm)) # the target's own by name # ---------------------------------------------------------------- cli def main(argv): if not argv or argv[0] not in ("--selftest", "--donor", "--inspect"): print(__doc__); return 2 mode, rest = argv[0], argv[1:] if mode == "--selftest": bad = 0 for p in rest: same = serialize(parse(p)) == open(p, "rb").read() print("%-6s %s" % ("ok" if same else "DIFF", p)); bad += not same return 1 if bad else 0 if mode == "--inspect": for p in rest: i = inspect(p) print("%-34s verts %-6d idx %-6d geom %d meshnode %d limbs %-3d skin %d cluster %-3d bindpose %d" % (os.path.basename(p), i["verts"], i["poly_indices"], i["geometry"], i["model_mesh"], i["limbs"], i["skins"], i["clusters"], i["bindpose"])) return 0 bind = "donor" if "--bind" in rest: i = rest.index("--bind"); bind = rest[i + 1]; rest = rest[:i] + rest[i + 2:] donor, targets = rest[0], rest[1:] for t in targets: for p in (donor, t): if serialize(parse(p)) != open(p, "rb").read(): print("拒绝执行:%s 无法字节级往返" % p); return 1 before = os.path.getsize(t) log, size = graft(donor, t, bind=bind) print("%s ← %s" % (t, donor)) for line in log: print(" " + line) print(" %d → %d 字节" % (before, size)) return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))