Files
Diabolo/tools/preview_succubus_heels.py
T

189 lines
11 KiB
Python
Raw Normal View History

"""Build an approval-only shoe revision; keep the production GLB unchanged."""
from pathlib import Path
import copy
import json
import struct
import numpy as np
root = Path(__file__).resolve().parent.parent
source = root / 'Demon_v0.19/art/succubus/succubus_v02.glb'
target = root / 'Demon_v0.19/reviews/heels_v01/succubus_heels.glb'
raw = source.read_bytes()
length = struct.unpack_from('<I', raw, 12)[0]
doc = json.loads(raw[20:20+length])
blob = bytearray(raw[28+length:])
types = {5126:'<f4', 5125:'<u4', 5123:'<u2', 5121:'u1'}
sizes = {'SCALAR':1, 'VEC2':2, 'VEC3':3, 'VEC4':4, 'MAT4':16}
def read(i):
a = doc['accessors'][i]; v = doc['bufferViews'][a['bufferView']]
return np.frombuffer(blob, types[a['componentType']], a['count']*sizes[a['type']],
v.get('byteOffset',0)+a.get('byteOffset',0)).reshape(-1,sizes[a['type']]).copy()
def accessor(data, kind, component=5126):
data = np.asarray(data,dtype=types[component]); blob.extend(b'\0'*((-len(blob))%4))
offset=len(blob); blob.extend(data.tobytes()); view=len(doc['bufferViews'])
doc['bufferViews'].append({'buffer':0,'byteOffset':offset,'byteLength':data.nbytes})
a={'bufferView':view,'componentType':component,'count':len(data),'type':kind}
if kind=='VEC3': a.update(min=data.min(axis=0).tolist(),max=data.max(axis=0).tolist())
doc['accessors'].append(a); return len(doc['accessors'])-1
joints = doc['skins'][0]['joints']
foot_ids = {side:joints.index(next(i for i,n in enumerate(doc['nodes']) if n.get('name')=='foot.'+side)) for side in ['L','R']}
# Move the anatomical ankle above the raised heel, and rebind only these joints.
# Merely raising shoe vertices leaves a bare-foot ankle pivot inside the heel.
inverse=read(doc['skins'][0]['inverseBindMatrices']).reshape(-1,4,4).transpose(0,2,1)
bind=np.linalg.inv(inverse);parents={child:i for i,node in enumerate(doc['nodes']) for child in node.get('children',[])}
joint_map={node:i for i,node in enumerate(joints)};translation_delta={}
for side in ['L','R']:
joint=foot_ids[side];node=joints[joint];parent=parents[node]
delta=np.linalg.inv(bind[joint_map[parent],:3,:3])@np.array([0,.080,0])
doc['nodes'][node]['translation']=(np.array(doc['nodes'][node]['translation'])+delta).tolist();translation_delta[node]=delta
new_bind=bind[joint].copy();new_bind[1,3]+=.080
for child in doc['nodes'][node].get('children',[]):
if child not in joint_map:continue
local_bind=np.linalg.inv(new_bind)@bind[joint_map[child]]
old=np.array(doc['nodes'][child]['translation']);translation_delta[child]=local_bind[:3,3]-old
doc['nodes'][child]['translation']=local_bind[:3,3].tolist()
inverse[joint]=np.linalg.inv(new_bind)
doc['skins'][0]['inverseBindMatrices']=accessor(inverse.transpose(0,2,1).reshape(-1,16),'MAT4')
for animation in doc.get('animations',[]):
for channel in animation['channels']:
target_node=channel['target'].get('node')
if channel['target']['path']!='translation' or target_node not in translation_delta:continue
sampler=animation['samplers'][channel['sampler']]
sampler['output']=accessor(read(sampler['output'])+translation_delta[target_node],'VEC3')
initial=copy.deepcopy(doc['meshes'][1]['primitives'][:-2]) # Replace the old open-ended heel columns.
primitives=[]
wing_ids=[joints.index(next(i for i,n in enumerate(doc['nodes']) if n.get('name')=='Wing.'+side)) for side in ['L','R']]
doc['materials'][17]['pbrMetallicRoughness'].update(baseColorFactor=[.012,.014,.017,1],metallicFactor=.04,roughnessFactor=.27)
sole_material=len(doc['materials'])
doc['materials'].append({'name':'Dark tan outsole edge','pbrMetallicRoughness':{'baseColorFactor':[.15,.105,.065,1],'roughnessFactor':.62}})
for p in initial:
attr=p['attributes']; v=read(attr['POSITION'])
if not {'JOINTS_0','WEIGHTS_0'}<=attr.keys():continue
j=read(attr['JOINTS_0']); w=read(attr['WEIGHTS_0'])
faces=read(p['indices']).reshape(-1,3).astype(np.int64)
old_wing=(np.isin(j,wing_ids)*w).sum(axis=1)>.25
faces=faces[~old_wing[faces].any(axis=1)]
if p['material'] in [0,4,10]:
center=v[faces].mean(axis=1);x=center[:,0]
cup_top=1.313-.060*np.exp(-(x/.037)**2)+.018*np.exp(-((np.abs(x)-.105)/.055)**2)
trim=(center[:,1]>cup_top)&(center[:,1]<1.385)&(center[:,2]>.07)&(np.abs(x)<.225)
faces=faces[~trim]
if p['material']==3:
arm_ids=[k for k,node in enumerate(joints) if 'arm' in doc['nodes'][node].get('name','')]
arm=(np.isin(j,arm_ids)*w).sum(axis=1)>.30
faces=faces[~arm[faces].any(axis=1)]
faces=faces[v[faces].mean(axis=1)[:,1]>1.045]
if p['material'] in [4,10]:
center=v[faces].mean(axis=1)
faces=faces[~((center[:,1]>.12)&(center[:,1]<.74)&(np.abs(center[:,0])<.30))]
if not len(faces):continue
p['indices']=accessor(faces.reshape(-1,1),'SCALAR',5125)
if p['material'] in [0,1,10,16,17]:
mask=(v[:,1]<.17)&(v[:,2]>.09)&(np.abs(v[:,0])<.3)
t=np.clip((v[mask,2]-.09)/.15,0,1)
center=np.sign(v[mask,0])*.1745
v[mask,0]=center+(v[mask,0]-center)*(1-.78*t*t)
v[mask,2]+=.046*t*t
foot=(v[:,1]<.145)&(np.abs(v[:,0])<.3)
bottom=np.interp(v[foot,2],[-.06,-.025,.025,.080,.135,.190,.230,.285],[.105,.107,.091,.050,.013,.008,.010,.015])
v[foot,1]=np.maximum(v[foot,1],bottom+.015)
attr['POSITION']=accessor(v,'VEC3')
faces=read(p['indices']).reshape(-1,3).astype(np.int64)
normal=np.zeros_like(v);cross=np.cross(v[faces[:,1]]-v[faces[:,0]],v[faces[:,2]]-v[faces[:,0]])
for k in range(3):np.add.at(normal,faces[:,k],cross)
normal/=np.maximum(np.linalg.norm(normal,axis=1,keepdims=True),1e-12)
attr['NORMAL']=accessor(normal,'VEC3');attr.pop('TANGENT',None)
for i in np.flatnonzero((v[:,1]<.14)&(np.abs(v[:,0])<.30)):
side='L' if v[i,0]>0 else 'R'; foot=foot_ids[side]
# Shoes must not flex with the toes: a stiletto and sole are one rigid piece.
if v[i,1]<.105 or p['material'] in [0,10]:
j[i]=[foot,0,0,0]; w[i]=[1,0,0,0]
attr['JOINTS_0']=accessor(j,'VEC4',5123);attr['WEIGHTS_0']=accessor(w,'VEC4')
primitives.append(p)
def mesh(vertices, faces, foot, material,smooth=False):
vertices=np.asarray(vertices,dtype='<f4');faces=np.asarray(faces,dtype=np.int64)
cross=np.cross(vertices[faces[:,1]]-vertices[faces[:,0]],vertices[faces[:,2]]-vertices[faces[:,0]])
faces=faces[np.linalg.norm(cross,axis=1)>1e-10]
# Flat faces preserve crisp bevels on leather panels, soles and heels.
pos=vertices[faces].reshape(-1,3);normal=np.cross(vertices[faces[:,1]]-vertices[faces[:,0]],vertices[faces[:,2]]-vertices[faces[:,0]])
normal/=np.maximum(np.linalg.norm(normal,axis=1,keepdims=True),1e-12)
normals=np.repeat(normal,3,axis=0)
if smooth:
averaged=np.zeros_like(vertices)
for k in range(3):np.add.at(averaged,faces[:,k],normal)
averaged/=np.maximum(np.linalg.norm(averaged,axis=1,keepdims=True),1e-12)
normals=averaged[faces].reshape(-1,3)
attr={'POSITION':accessor(pos,'VEC3'),'NORMAL':accessor(normals,'VEC3'),
'JOINTS_0':accessor(np.tile([foot,0,0,0],(len(pos),1)),'VEC4',5123),
'WEIGHTS_0':accessor(np.tile([1,0,0,0],(len(pos),1)),'VEC4')}
primitives.append({'attributes':attr,'material':material,'indices':accessor(np.arange(len(pos)).reshape(-1,1),'SCALAR',5125)})
for side,sign in [('L',1),('R',-1)]:
x=sign*.1745;foot=foot_ids[side]
vertices=[];faces=[];rings=[(.006,.026,.031,-.040),(.018,.025,.030,-.039),(.078,.028,.032,-.030),(.112,.031,.034,-.024)]
outline=[(-.72,-1),(.72,-1),(1,-.72),(1,.72),(.72,1),(-.72,1),(-1,.72),(-1,-.72)]
for y,rx,rz,z in rings:
for dx,dz in outline:vertices.append([x+dx*rx,y,z+dz*rz])
for ring in range(3):
for n in range(8):
a=ring*8+n;b=ring*8+(n+1)%8;c=b+8;d=a+8;faces.extend([[a,c,b],[a,d,c]])
for n in range(1,7):faces.extend([[0,n,n+1],[24,24+n+1,24+n]])
mesh(vertices,faces,foot,17)
# Closed sculpted outsole: raised heel seat, concave arch, low forefoot.
sections=[(-.060,.021,.105),(-.025,.040,.107),(.025,.042,.091),(.080,.038,.050),(.135,.043,.013),(.190,.033,.008),(.250,.015,.010),(.285,.002,.015)]
vertices=[];faces=[]
for z,width,y in sections:
vertices.extend([[x-width,y,z],[x+width,y,z],[x+width,y+.013,z],[x-width,y+.013,z]])
for n in range(len(sections)-1):
for edge in range(4):
a=n*4+edge;b=n*4+(edge+1)%4;c=b+4;d=a+4;faces.extend([[a,b,c],[a,c,d]])
faces.extend([[0,2,1],[0,3,2]]);a=(len(sections)-1)*4;faces.extend([[a,a+1,a+2],[a,a+2,a+3]])
mesh(vertices,faces,foot,sole_material)
from succubus_review_outfit import augment
augment(doc,read,mesh,primitives,accessor)
primitives=[p for p in primitives if doc['accessors'][p['indices']]['count']>0 and doc['accessors'][p['attributes']['POSITION']]['count']>0]
doc['meshes'][1]['primitives']=primitives
doc['meshes'][1]['name']='Approval only - red bat corset, black block heel boots and curved wings'
# Remove superseded buffer data, so the approval model remains portable.
used=set()
for m in doc['meshes']:
for p in m['primitives']:
used.update(p['attributes'].values())
if 'indices' in p:used.add(p['indices'])
for morph in p.get('targets',[]):used.update(morph.values())
for skin in doc['skins']:
if 'inverseBindMatrices' in skin:used.add(skin['inverseBindMatrices'])
for animation in doc.get('animations',[]):
for sampler in animation['samplers']:used.update([sampler['input'],sampler['output']])
mapping={old:new for new,old in enumerate(sorted(used))}
doc['accessors']=[doc['accessors'][old] for old in sorted(used)]
for m in doc['meshes']:
for p in m['primitives']:
p['attributes']={key:mapping[value] for key,value in p['attributes'].items()}
if 'indices' in p:p['indices']=mapping[p['indices']]
p['targets']=[{key:mapping[value] for key,value in morph.items()} for morph in p.get('targets',[])] if 'targets' in p else []
for skin in doc['skins']:
if 'inverseBindMatrices' in skin:skin['inverseBindMatrices']=mapping[skin['inverseBindMatrices']]
for animation in doc.get('animations',[]):
for sampler in animation['samplers']:
sampler['input']=mapping[sampler['input']];sampler['output']=mapping[sampler['output']]
used_views={a['bufferView'] for a in doc['accessors']}
used_views.update(i['bufferView'] for i in doc.get('images',[]) if 'bufferView' in i)
view_map={old:new for new,old in enumerate(sorted(used_views))};new_blob=bytearray();views=[]
for old in sorted(used_views):
view=copy.deepcopy(doc['bufferViews'][old]);start=view.get('byteOffset',0)
new_blob.extend(b'\0'*((-len(new_blob))%4));view['byteOffset']=len(new_blob)
new_blob.extend(blob[start:start+view['byteLength']]);views.append(view)
for a in doc['accessors']:a['bufferView']=view_map[a['bufferView']]
for image in doc.get('images',[]):
if 'bufferView' in image:image['bufferView']=view_map[image['bufferView']]
doc['bufferViews']=views;blob=new_blob
doc['buffers'][0]['byteLength']=len(blob)
data=json.dumps(doc,separators=(',',':')).encode();data+=b' '*((-len(data))%4);blob.extend(b'\0'*((-len(blob))%4))
target.parent.mkdir(parents=True,exist_ok=True)
target.write_bytes(struct.pack('<III',0x46546c67,2,28+len(data)+len(blob))+struct.pack('<II',len(data),0x4e4f534a)+data+struct.pack('<II',len(blob),0x004e4942)+blob)
print('Review GLB:',target,'bytes:',target.stat().st_size,'foot joints:',foot_ids)