Truebones-ZOO-Annotations / scripts /probes /fbx_embed_texture.py
Linzhan's picture
Initial release: prompts, metadata, T-pose renders, build pipeline (no commercial motion files)
a84fca7 verified
Raw
History Blame Contribute Delete
6.73 kB
#!/usr/bin/env python3
"""Graft an embedded texture into a binary FBX that references one externally.
fbx_embed_texture.py --selftest <fbx>... byte-identical round trip
fbx_embed_texture.py --donor <fbx> <fbx>... copy the donor's Video/Content
into each target, in place
Truebones embeds its textures in the FBX itself — 73 of the 74 species carry the
pixels in a `Video/Content` property, so a clip renders correctly wherever it is
opened. `Cat` is the exception: its four standalone clips were exported without
"embed media", so they carry only a `RelativeFilename` pointing at a `Cat.fbm/`
directory that does not exist. They render untextured from `animation/`, whose
flat layout puts no image anywhere the importer's search can reach.
The fix is not a re-export, which would rebuild the rig. The file is parsed into
its node tree, one `Content` node is inserted into `Video`, and the tree is
re-serialized with recomputed offsets — every node record stores an absolute end
offset, so an insertion shifts everything after it. Nothing else is touched.
The `Content` node is copied verbatim from a donor file of the same species that
does have it (`Cat-ALL.fbx`), rather than synthesised, so the property encoding
and node framing are known-good rather than guessed.
Correctness gate: with no edits the serializer must reproduce its input byte for
byte (`--selftest`). Some nodes carry a trailing null record despite having no
children; that is tracked per node so round trips stay exact.
Writes through a temporary file and renames it into place. Every clip here is a
hardlink of one in `Truebone_Z-OO/`, and writing to such a path writes through to
the original.
"""
import os, struct, sys
ELEM = {'f':4,'d':8,'l':8,'i':4,'b':1}
SCALAR = {"Y":2,"C":1,"I":4,"F":4,"D":8,"L":8}
class Node:
__slots__ = ("name","props","children","nullrec")
def __init__(s, name): s.name=name; s.props=[]; s.children=[]; s.nullrec=False
def parse(path):
d=open(path,'rb').read()
assert d[:21]==b"Kaydara FBX Binary \x00", "not a binary FBX"
version=struct.unpack("<I",d[23:27])[0]; u64=version>=7500
NREC=25 if u64 else 13
def rd_prop(p):
t=chr(d[p]); s=p; p+=1
if t in SCALAR:
p+=SCALAR[t]; return p,(t,d[s+1:p])
if t in ELEM:
length,enc,clen=struct.unpack("<III",d[p:p+12]); hdr=d[p:p+12]; p+=12
body=clen if enc else length*ELEM[t]
data=d[p:p+body]; p+=body
return p,(t,hdr+data)
if t in "SR":
ln=struct.unpack("<I",d[p:p+4])[0]; p+=4
data=d[p:p+ln]; p+=ln
return p,(t,data)
raise ValueError("bad prop type %r @%d"%(t,s))
def is_null(p): return p+NREC<=len(d) and d[p:p+NREC]==b"\x00"*NREC
def rd_node(p):
if u64: end,nprop,plen=struct.unpack("<QQQ",d[p:p+24]); q=p+24
else: end,nprop,plen=struct.unpack("<III",d[p:p+12]); q=p+12
if end==0 and nprop==0 and plen==0: return None,p+NREC
nl=d[q]; q+=1; name=d[q:q+nl]; q+=nl
n=Node(name); p=q
for _ in range(nprop):
p,pr=rd_prop(p); n.props.append(pr)
while p<end:
if is_null(p): n.nullrec=True; p+=NREC; break
c,p2=rd_node(p)
if c is None: n.nullrec=True; p=p2; break
n.children.append(c); p=p2
return n,end
p=27; top=[]; tnull=False
while p<len(d):
if is_null(p): tnull=True; p+=NREC; break
n,p2=rd_node(p)
if n is None: tnull=True; p=p2; break
top.append(n); p=p2
return {"header":d[:27],"u64":u64,"top":top,"footer":d[p:],
"toplevel_null":tnull,"orig":d,"version":version}
def pbytes(t,pay):
if t in "SR": return t.encode()+struct.pack("<I",len(pay))+pay
return t.encode()+pay
def nsize(n,u64):
NREC=25 if u64 else 13
sz=NREC+len(n.name)
sz+=sum(len(pbytes(t,p)) for t,p in n.props)
sz+=sum(nsize(c,u64) for c in n.children)
if n.nullrec: sz+=NREC
return sz
def wnode(out,n,u64):
NREC=25 if u64 else 13
props=b"".join(pbytes(t,p) for t,p in n.props)
end=len(out)+nsize(n,u64)
out += struct.pack("<QQQ",end,len(n.props),len(props)) if u64 else \
struct.pack("<III",end,len(n.props),len(props))
out += bytes([len(n.name)])+n.name+props
for c in n.children: wnode(out,c,u64)
if n.nullrec: out+=b"\x00"*NREC
def serialize(t):
out=bytearray(t["header"])
for n in t["top"]: wnode(out,n,t["u64"])
if t["toplevel_null"]: out+=b"\x00"*(25 if t["u64"] else 13)
out+=t["footer"]
return bytes(out)
def walk(nodes):
for n in nodes:
yield n
for x in walk(n.children): yield x
def donor_content(path):
"""The `Content` node of the donor's `Video`, with its raw payload."""
t=parse(path)
for n in walk(t["top"]):
if n.name!=b"Video": continue
for c in n.children:
if c.name==b"Content" and c.props and c.props[0][0]=="R" and len(c.props[0][1])>64:
return c
raise SystemExit("donor has no Video/Content: "+path)
def graft(path, content):
"""Insert a copy of `content` into every Video node that lacks one."""
t=parse(path); added=0
for n in walk(t["top"]):
if n.name!=b"Video": continue
if any(c.name==b"Content" for c in n.children): continue
c=Node(b"Content"); c.props=list(content.props); c.nullrec=content.nullrec
# sits after RelativeFilename, which is where every embedding export puts it
idx=max((i for i,ch in enumerate(n.children)
if ch.name in (b"RelativeFilename", b"Filename")), default=len(n.children)-1)
n.children.insert(idx+1, c); added+=1
return added, serialize(t)
if __name__=="__main__":
a=sys.argv[1:]
if a and a[0]=="--selftest":
ok=True
for f in a[1:]:
t=parse(f); same=serialize(t)==t["orig"]; ok&=same
print(" %-30s identical=%s (%d bytes)"%(os.path.basename(f),same,len(t["orig"])))
sys.exit(0 if ok else 1)
if a and a[0]=="--donor":
content=donor_content(a[1])
print("donor blob: %d bytes"%len(content.props[0][1]))
for f in a[2:]:
t=parse(f)
assert serialize(t)==t["orig"], "round trip failed, refusing to edit "+f
n,data=graft(f, content)
tmp=f+".tmp"
open(tmp,"wb").write(data)
os.replace(tmp, f) # replaces the name, leaves other hardlinks alone
print(" %-30s +%d Content %d -> %d bytes"%(os.path.basename(f),n,len(t["orig"]),len(data)))
sys.exit(0)
sys.exit(__doc__)