Files

233 lines
11 KiB
Python

"""Retarget one Octo (MD20 v256) character sequence onto a native MD21 character sequence stored in an external .anim.
World-space rotation retarget with per-bone bind-direction correction; root translation scaled by model height.
usage: retarget.py octo.m2 octo_anim_id native.m2 native_seq_index native.anim out.m2 out.anim report.json"""
import struct,sys,math,json
octo_p,oid,nat_p,nseq,anim_p,out_m2,out_anim,rep_p=sys.argv[1],int(sys.argv[2]),sys.argv[3],int(sys.argv[4]),sys.argv[5],sys.argv[6],sys.argv[7],sys.argv[8]
O=open(octo_p,'rb').read(); B=bytearray(open(nat_p,'rb').read()); A=bytearray(open(anim_p,'rb').read())
assert O[:8]==struct.pack('<4sI',b'MD20',256) and B[:4] in (b'MD21',b'SKL1')
def _chunk(tag):
at=0
while at<len(B):
t,n=struct.unpack_from('<4sI',B,at)
if t==tag: return memoryview(B)[at+8:at+8+n]
at+=8+n
raise SystemExit('missing chunk '+tag.decode())
# MD21: bones/sequences in MD20 (bones 0x2C, sequence offset 0x20). .skel (#56 Undead/Blood Elf HD): bones in SKB1 (offset 0),
# sequences in SKS1 (sequence offset 0x0C); track offsets are relative to their own chunk.
if B[:4]==b'MD21': N=_chunk(b'MD21'); S=N; BONES,SEQOFF=0x2C,0x20
else: N=_chunk(b'SKB1'); S=_chunk(b'SKS1'); BONES,SEQOFF=0x00,0x0C
# ---- quaternions (x,y,z,w)
def qm(a,b):
ax,ay,az,aw=a;bx,by,bz,bw=b
return (aw*bx+ax*bw+ay*bz-az*by, aw*by-ax*bz+ay*bw+az*bx, aw*bz+ax*by-ay*bx+az*bw, aw*bw-ax*bx-ay*by-az*bz)
qi=lambda q:(-q[0],-q[1],-q[2],q[3])
def qn(q):
l=math.sqrt(sum(c*c for c in q)) or 1; return tuple(c/l for c in q)
def slerp(a,b,t):
d=sum(x*y for x,y in zip(a,b))
if d<0: b=tuple(-c for c in b); d=-d
if d>0.9995: return qn(tuple(x+(y-x)*t for x,y in zip(a,b)))
th=math.acos(d); s=math.sin(th); return tuple((math.sin((1-t)*th)*x+math.sin(t*th)*y)/s for x,y in zip(a,b))
def arc(u,v):
u=norm(u);v=norm(v);d=sum(x*y for x,y in zip(u,v))
if d<-0.9999: return (0,0,1,0)
c=(u[1]*v[2]-u[2]*v[1],u[2]*v[0]-u[0]*v[2],u[0]*v[1]-u[1]*v[0]); return qn((c[0],c[1],c[2],1+d))
def norm(v):
l=math.sqrt(sum(c*c for c in v)) or 1; return tuple(c/l for c in v)
I=(0.0,0.0,0.0,1.0)
# ---- octo skeleton + sequence window
sc,so=struct.unpack_from('<II',O,0x1C)
oseqs=[(struct.unpack_from('<H',O,so+i*68)[0],struct.unpack_from('<H',O,so+i*68+2)[0])+struct.unpack_from('<II',O,so+i*68+4) for i in range(sc)]
SUB=next((int(a[6:]) for a in sys.argv if a.startswith('--sub=')),0)
si=next(i for i,s in enumerate(oseqs) if s[0]==oid and s[1]==SUB); w0,w1=oseqs[si][2],oseqs[si][3]; DUR=w1-w0
obc,obo=struct.unpack_from('<II',O,0x34)
ob=[dict(key=struct.unpack_from('<i',O,obo+i*108)[0],par=struct.unpack_from('<h',O,obo+i*108+8)[0],piv=struct.unpack_from('<3f',O,obo+i*108+96),at=obo+i*108) for i in range(obc)]
def otrack(at,stride,seq):
it,gs,nr,ro,nt,to,nk,ko=struct.unpack_from('<Hh6I',O,at)
if not nt: return None
times=struct.unpack_from(f'<{nt}I',O,to); keys=[struct.unpack_from(f'<{stride//4}f',O,ko+i*stride) for i in range(nk)]
if gs>=0 or nr==0: return [(0,keys[0])]
b,e=struct.unpack_from('<II',O,ro+seq*8)
if not (0<=b<=e<nt): return None
return [(times[k]-w0,keys[k]) for k in range(b,e+1)]
def sample(tr,t,rot):
if not tr: return I if rot else (0.0,0.0,0.0)
if t<=tr[0][0] or len(tr)==1: return qn(tr[0][1]) if rot else tr[0][1]
for (ta,a),(tb,b) in zip(tr,tr[1:]):
if ta<=t<=tb:
f=0 if tb==ta else (t-ta)/(tb-ta)
return slerp(qn(a),qn(b),f) if rot else tuple(x+(y-x)*f for x,y in zip(a,b))
return qn(tr[-1][1]) if rot else tr[-1][1]
orot=[otrack(x['at']+40,16,si) for x in ob]; otr=[otrack(x['at']+12,12,si) for x in ob]
# ---- native skeleton
nbc,nbo=struct.unpack_from('<II',N,BONES)
nb=[dict(key=struct.unpack_from('<i',N,nbo+i*88)[0],par=struct.unpack_from('<h',N,nbo+i*88+8)[0],piv=struct.unpack_from('<3f',N,nbo+i*88+76),at=nbo+i*88) for i in range(nbc)]
H=lambda bs:max(x['piv'][2] for x in bs)-min(x['piv'][2] for x in bs); Ho,Hn=H(ob),H(nb); RATIO=Hn/Ho
kids=lambda bs,i:[j for j,x in enumerate(bs) if x['par']==i]
def desc(i,depth):
out=[];fr=[(i,0)]
while fr:
j,d=fr.pop()
for c in kids(nb,j):
out.append((c,d+1))
if d+1<depth: fr.append((c,d+1))
return out
# ---- mapping
ko={x['key']:i for i,x in enumerate(ob) if x['key']>=0}; kn={x['key']:i for i,x in enumerate(nb) if x['key']>=0}
M={ko[k]:kn[k] for k in ko if k in kn}; used=set(M.values())
rel=lambda bs,i,j,h:tuple((a-b)/h for a,b in zip(bs[i]['piv'],bs[j]['piv']))
def chain(bs,lo,hi):
p=[hi]
while p[-1]!=lo:
q=bs[p[-1]]['par']
if q<0: return None
p.append(q)
return p[::-1]
def anc(bs,i):
out=[]
while bs[i]['par']>=0: i=bs[i]['par']; out.append(i)
return out
def subtree(bs,i):
out=[i];k=0
while k<len(out): out+=kids(bs,out[k]); k+=1
return out
def fill(a_o,d_o):
co,cn=chain(ob,a_o,d_o),chain(nb,M[a_o],M[d_o])
if not co or not cn or len(co)<3: return
def frac(bs,c):
L=[0.0]
for x,y in zip(c,c[1:]): L.append(L[-1]+math.dist(bs[x]['piv'],bs[y]['piv']))
return [l/(L[-1] or 1) for l in L]
fo,fn=frac(ob,co),frac(nb,cn); last=0
for k in range(1,len(co)-1):
if co[k] in M: continue
opts=[(abs(fn[m]-fo[k]),m) for m in range(max(last+1,1),len(cn)-1) if cn[m] not in used]
if not opts: continue
_,m=min(opts); M[co[k]]=cn[m]; used.add(cn[m]); last=m
# legs: Octo waist (key 5) -> common native ancestor of both native leg ends; leg ends = lowest pivot per side
def leg_end(bs,root,side):
c=[x for x in subtree(bs,root) if bs[x]['piv'][1]*side>0.02 and not kids(bs,x)]
return min(c,key=lambda x:bs[x]['piv'][2]) if c else None
ro,rn=ko.get(26),kn.get(26)
if ro is not None and rn is not None:
for side in (1,-1):
eo,en=leg_end(ob,ro,side),leg_end(nb,rn,side)
if eo is not None and en is not None and eo not in M and en not in used: M[eo]=en; used.add(en)
if 5 in ko and ko[5] not in M:
ends=[M[x] for x in M if ob[x]['piv'][2]<0.3*Ho+min(b['piv'][2] for b in ob)]
if len(ends)>=2:
common=[a for a in anc(nb,ends[0]) if all(a in anc(nb,e) for e in ends[1:])]
if common and common[0] not in used: M[ko[5]]=common[0]; used.add(common[0])
changed=True
while changed:
changed=False;n0=len(M)
for d in list(M):
for a in anc(ob,d):
if a in M: fill(a,d); break
changed=len(M)>n0
order=[];fr=[i for i,x in enumerate(ob) if x['par']<0]
while fr:
i=fr.pop(0); order.append(i); fr+=kids(ob,i)
for i in order:
if i in M: continue
p=ob[i]['par']
if p<0 or p not in M: continue
cands=desc(M[p],3); base=M[p]
vo=rel(ob,i,p,Ho); best=None
for j,d in cands:
if j in used or nb[j]['key']>=0: continue
vn=rel(nb,j,base,Hn); lo,ln=math.dist(vo,(0,0,0)),math.dist(vn,(0,0,0))
if lo<1e-4 and ln<1e-4: score=1-0.05*d
elif lo<1e-4 or ln<1e-4: continue
else: score=sum(a*b for a,b in zip(norm(vo),norm(vn)))-abs(math.log(ln/lo))*0.2-0.05*d
if best is None or score>best[0]: best=(score,j)
if best and best[0]>0.6: M[i]=best[1]; used.add(best[1])
# explicit pairs (--map o:n,o:n) override the heuristic: digitigrade legs (Tauren hip/knee/hock) mis-chain otherwise
for a in sys.argv:
if a.startswith('--map='):
for pr in a[6:].split(','):
o,n=map(int,pr.split(':'))
for k in [k for k,v in M.items() if v==n]: del M[k]
M[o]=n
inv={v:k for k,v in M.items()}
moving=[i for i in range(obc) if orot[i] and len({tuple(round(c,3) for c in k) for _,k in orot[i]})>1]
if '--diag' in sys.argv:
print('moving',len(moving),'mapped',sum(1 for i in moving if i in M))
for i in moving:
if i not in M: print(' unmapped',i,'key',ob[i]['key'],'par',ob[i]['par'],'pm',ob[i]['par'] in M,[round(c,2) for c in ob[i]['piv']])
for i in sorted(M):
if i in moving: print(' map',i,ob[i]['key'],[round(c,2) for c in ob[i]['piv']],'->',M[i],nb[M[i]]['key'],[round(c,2) for c in nb[M[i]]['piv']])
# ---- bind correction per native bone
C=[None]*nbc
def corr(j):
if C[j] is not None: return C[j]
o=inv.get(j); q=None
if o is not None:
pairs=[(c,M[c]) for c in kids(ob,o) if c in M]
pairs=[(c,n2) for c,n2 in pairs if math.dist(ob[c]['piv'],ob[o]['piv'])>1e-3 and math.dist(nb[n2]['piv'],nb[j]['piv'])>1e-3]
if pairs:
c,n2=max(pairs,key=lambda p:math.dist(ob[p[0]]['piv'],ob[o]['piv']))
q=arc(tuple(a-b for a,b in zip(nb[n2]['piv'],nb[j]['piv'])),tuple(a-b for a,b in zip(ob[c]['piv'],ob[o]['piv'])))
if q is None: q=corr(nb[j]['par']) if nb[j]['par']>=0 else I
C[j]=q; return q
for j in range(nbc): corr(j)
# ---- sample
FR=33; times=list(range(0,DUR,FR))+[DUR]
def oworld(t):
W=[None]*obc
def w(i):
if W[i] is None:
L=sample(orot[i],t,True); W[i]=L if ob[i]['par']<0 else qn(qm(w(ob[i]['par']),L))
return W[i]
for i in range(obc): w(i)
return W
rot_keys={j:[] for j in range(nbc)}; tr_keys={}
roots_o=[i for i in M if ob[i]['par']<0 or ob[i]['key'] in (26,)]
for t in times:
Wo=oworld(t); Wn=[None]*nbc
def wn(j):
if Wn[j] is None:
o=inv.get(j)
if o is not None: Wn[j]=qn(qm(Wo[o],C[j]))
else: Wn[j]=wn(nb[j]['par']) if nb[j]['par']>=0 else I
return Wn[j]
for j in range(nbc):
p=nb[j]['par']; L=qn(qm(qi(wn(p)),wn(j))) if p>=0 else wn(j)
# remove the bind correction itself at rest: native local = C_p^-1 Lo C_j already; keep
prev=rot_keys[j][-1] if rot_keys[j] else None
if prev and sum(a*b for a,b in zip(prev,L))<0: L=tuple(-c for c in L)
rot_keys[j].append(L)
for o in roots_o:
v=sample(otr[o],t,False)
tr_keys.setdefault(M[o],[]).append(tuple(c*RATIO for c in v))
def enc(q):
out=[]
for c in q:
c=max(-1,min(1,c)); out.append(round(c*32767-32768 if c>=0 else c*32767+32767))
return struct.pack('<4h',*out)
# ---- write: append to .anim, repoint seq nseq sub-arrays of every bone track
def app(data):
A.extend(bytes((-len(A))%16)); off=len(A); A.extend(data); return off
ts_bytes=struct.pack(f'<{len(times)}I',*times)
ts_off=app(ts_bytes)
written=0
for j in range(nbc):
keys=rot_keys[j]; moving=any(abs(k[3])<0.99995 for k in keys)
for k,(field,payload) in enumerate(((16,'t'),(36,'r'),(56,'s'))):
it,gs,tc,to,vc,vo=struct.unpack_from('<HhIIII',N,nb[j]['at']+field)
if gs>=0 or tc<=nseq: continue
if payload=='r' and moving:
struct.pack_into('<II',N,to+nseq*8,len(times),ts_off); struct.pack_into('<II',N,vo+nseq*8,len(times),app(b''.join(enc(q) for q in keys))); written+=1
struct.pack_into('<H',N,nb[j]['at']+field,1)
elif payload=='t' and j in tr_keys:
struct.pack_into('<II',N,to+nseq*8,len(times),ts_off); struct.pack_into('<II',N,vo+nseq*8,len(times),app(b''.join(struct.pack('<3f',*v) for v in tr_keys[j])))
else:
struct.pack_into('<II',N,to+nseq*8,0,0); struct.pack_into('<II',N,vo+nseq*8,0,0)
ss=struct.unpack_from('<I',S,SEQOFF)[0]
assert struct.unpack_from('<H',S,ss+nseq*64)[0]
struct.pack_into('<I',S,ss+nseq*64+4,DUR)
open(out_m2,'wb').write(B); open(out_anim,'wb').write(A)
json.dump(dict(octo_seq=si,duration=DUR,height_ratio=RATIO,mapped=len(M),octo_bones=obc,native_bones=nbc,rotated_tracks=written,
unmapped_octo=[i for i in range(obc) if i not in M],map={str(k):v for k,v in sorted(M.items())}),open(rep_p,'w'),indent=0)
print('dur',DUR,'mapped',len(M),'/',obc,'native',nbc,'rotated',written,'ratio',round(RATIO,3))