"""Versioned donor skinning trial. Never alters the preserved donor or stage01.""" import argparse,hashlib,json,math,pathlib,sys,time import bpy,numpy as np from mathutils import Vector,Matrix from mathutils.bvhtree import BVHTree p=argparse.ArgumentParser();p.add_argument('--config',required=True);a=p.parse_args(sys.argv[sys.argv.index('--')+1:]);cfg=json.loads(pathlib.Path(a.config).read_text());out=pathlib.Path(cfg['output']);out.mkdir(exist_ok=False) def save(n,d):(out/n).write_text(json.dumps(d,indent=2,default=str)+'\n') def mark(s):save('progress.json',{'stage':s,'time':time.time()}) def verify(f,h):assert hashlib.sha256(pathlib.Path(f).read_bytes()).hexdigest()==h,f verify(cfg['input'],cfg['input_sha256']);verify(cfg['donor'],cfg['donor_sha256']) bpy.ops.wm.open_mainfile(filepath=cfg['input']);sc=bpy.context.scene low=bpy.data.objects['EconomyKnight_Tripo_Low'];low.hide_set(False) for ob in list(sc.objects): if ob!=low:bpy.data.objects.remove(ob,do_unlink=True) # Tiny UV degeneracies are repaired within 1/4 texel around their current sample. uv=low.data.uv_layers.active.data;fixed=[] for face in low.data.polygons: ids=list(face.loop_indices);u=[uv[i].uv.copy() for i in ids];area=sum(u[i].x*u[(i+1)%3].y-u[(i+1)%3].x*u[i].y for i in range(3)) if abs(area)<1e-12: center=sum(u,Vector((0,0)))/3;eps=1/16384 for i,off in zip(ids,[(-eps,-eps),(eps,-eps),(0,eps)]):uv[i].uv=center+Vector(off) fixed.append(face.index) save('uv-repair.json',{'faces':fixed,'method':'Nonzero subpixel triangle around original centroid','maximum_offset_texels':math.sqrt(2)/4,'geometry_removed':False}) # Convert imported glTF metres/-Y-front to preserved donor centimetres/+X-front. low.data.transform(Matrix.Rotation(math.pi/2,4,'Z') @ Matrix.Scale(100,4));low.data.update();low.name='SK_EconomyKnight_Tripo01';low.data.name=low.name sc.unit_settings.system='METRIC';sc.unit_settings.scale_length=.01 mark('append-donor') with bpy.data.libraries.load(cfg['donor'],link=False) as (src,dst): dst.objects=list(src.objects);dst.actions=list(src.actions) loaded=[o for o in dst.objects if o] for ob in loaded: if ob.name not in sc.objects:sc.collection.objects.link(ob) rigs=[o for o in loaded if o.type=='ARMATURE'];assert len(rigs)==1;rig=rigs[0] rig.name='Armature';rig.animation_data_clear();rig.data.pose_position='REST' for b in rig.pose.bones:b.matrix_basis=Matrix.Identity(4) donors=[o for o in loaded if o.type=='MESH' and len(o.vertex_groups)>0];assert len(donors)==1,[(o.name,len(o.vertex_groups)) for o in donors];donor=donors[0] bpy.context.view_layer.update();assert len(rig.data.bones)==33 bones=[{'name':b.name,'parent':b.parent.name if b.parent else None,'head':list(b.head_local),'tail':list(b.tail_local),'matrix':[list(r) for r in b.matrix_local]} for b in rig.data.bones];save('rest.json',{'bones':bones,'rig_matrix':[list(r)for r in rig.matrix_world],'donor_bounds':[list(donor.matrix_world@Vector(c))for c in donor.bound_box],'target_bounds':[list(low.matrix_world@Vector(c))for c in low.bound_box]}) mark('transfer-weights') donor.data.calc_loop_triangles();triangles=[tuple(t.vertices) for t in donor.data.loop_triangles];verts=[donor.matrix_world@v.co for v in donor.data.vertices];tree=BVHTree.FromPolygons(verts,triangles,all_triangles=True) bnames=set(b.name for b in rig.data.bones);groupnames={g.index:g.name for g in donor.vertex_groups if g.name in bnames};dw=[{groupnames[g.group]:g.weight for g in v.groups if g.group in groupnames}for v in donor.data.vertices] for b in rig.data.bones:low.vertex_groups.new(name=b.name) distances=[];counts={b:0 for b in bnames};no_weights=[] for v in low.data.vertices: pt,normal,ti,distance=tree.find_nearest(low.matrix_world@v.co);distances.append(distance);ids=triangles[ti];aa,bb,cc=[verts[i]for i in ids];v0=bb-aa;v1=cc-aa;v2=pt-aa;d00=v0.dot(v0);d01=v0.dot(v1);d11=v1.dot(v1);den=d00*d11-d01*d01 if abs(den)>1e-12: wb=(d11*v2.dot(v0)-d01*v2.dot(v1))/den;wc=(d00*v2.dot(v1)-d01*v2.dot(v0))/den;ws=[max(0,1-wb-wc),max(0,wb),max(0,wc)] else:ws=[1,0,0] weights={} for i,w in zip(ids,ws): for name,dwgt in dw[i].items():weights[name]=weights.get(name,0)+w*dwgt weights=sorted(((name,w)for name,w in weights.items()if w>=.01),key=lambda a:-a[1])[:4];total=sum(w for _,w in weights) if total<=0:no_weights.append(v.index);continue for name,w in weights:low.vertex_groups[name].add([v.index],w/total,'REPLACE');counts[name]+=1 assert not no_weights,no_weights[:20] low.parent=rig;low.matrix_parent_inverse=rig.matrix_world.inverted();mod=low.modifiers.new('TripoSkin','ARMATURE');mod.object=rig for ob in loaded: if ob!=rig:bpy.data.objects.remove(ob,do_unlink=True) rig.data.pose_position='POSE';rig.animation_data_create() low.data.materials[0].name='M_EK_Tripo01' save('weights.json',{'method':'Nearest donor triangle barycentric interpolation','max_influences':max(len(v.groups)for v in low.data.vertices),'max_sum_error':max(abs(sum(g.weight for g in v.groups)-1)for v in low.data.vertices),'distance_cm_percentiles':np.percentile(distances,[0,50,90,99,100]).tolist(),'vertices_per_bone':counts,'unweighted':len(no_weights)}) # QA in metres to preserve the skill's geometric thresholds. mark('qa');skills=pathlib.Path(cfg['skills']);sys.path.insert(0,str(skills/'blender-asset-qa/scripts'));import qa_check qa=qa_check.run(objects=[low.name],profile='game');save('qa.json',qa) acts={} for name,fps,keys in [('Idle',30,61),('Walk',30,31),('Run',60,25),('Cast',30,10)]: act=bpy.data.actions.get('A_EconomyKnight_'+name);assert act,[(x.name)for x in bpy.data.actions];acts[name]=(act,fps,keys) # Capture actual evaluated geometry over every animation key, not just bone motion. mark('evaluate');base=np.array([v.co[:]for v in low.data.vertices]);clips={} for name,(act,fps,keys) in acts.items(): rig.animation_data.action=act;sc.render.fps=fps;frames=[] for f in range(keys): sc.frame_set(f);bpy.context.view_layer.update();dg=bpy.context.evaluated_depsgraph_get();eo=low.evaluated_get(dg);em=eo.to_mesh();co=np.empty(len(em.vertices)*3);em.vertices.foreach_get('co',co);co=co.reshape(-1,3) frames.append({'frame':f,'bounds_cm':[co.min(0).tolist(),co.max(0).tolist()],'max_vertex_displacement_cm':float(np.linalg.norm(co-base,axis=1).max()),'hand_R':list(rig.pose.bones['hand_R'].matrix.translation),'foot_L':list(rig.pose.bones['foot_L'].matrix.translation)}) eo.to_mesh_clear() clips[name]={'fps':fps,'keys':keys,'duration':(keys-1)/fps,'frames':frames} save('evaluation.json',clips) rig.animation_data.action=None for b in rig.pose.bones:b.matrix_basis=Matrix.Identity(4) bpy.context.view_layer.update();bpy.ops.wm.save_as_mainfile(filepath=str(out/'economy-knight-tripo-rigtrial.blend')) # Native review studio, cm-aware energy and clipping. mark('render');sc.render.engine='CYCLES';sc.cycles.samples=24;sc.cycles.use_denoising=True;sc.render.threads_mode='FIXED';sc.render.threads=4 prefs=bpy.context.preferences.addons['cycles'].preferences;prefs.compute_device_type='OPTIX';prefs.get_devices() for d in prefs.devices:d.use=d.type=='OPTIX' sc.cycles.device='GPU' if any(d.use for d in prefs.devices)else'CPU' sc.render.resolution_x=768;sc.render.resolution_y=768;sc.render.resolution_percentage=100;sc.render.image_settings.file_format='PNG';sc.view_settings.view_transform='Standard' world=bpy.data.worlds.new('ReviewWorld');world.use_nodes=True;sc.world=world;bg=world.node_tree.nodes.get('Background');bg.inputs['Color'].default_value=(.16,.18,.21,1);bg.inputs['Strength'].default_value=.5 for name,loc,power,size in [('Key',(400,-300,500),5500000,400),('Fill',(200,300,300),2000000,300)]: d=bpy.data.lights.new(name,'AREA');d.energy=power;d.shape='DISK';d.size=size;o=bpy.data.objects.new(name,d);sc.collection.objects.link(o);o.location=loc;o.rotation_euler=(Vector((0,0,100))-o.location).to_track_quat('-Z','Y').to_euler() d=bpy.data.cameras.new('ReviewCamera');cam=bpy.data.objects.new('ReviewCamera',d);sc.collection.objects.link(cam);sc.camera=cam;d.type='ORTHO';d.ortho_scale=230;d.clip_end=5000 shots=[] for name,f in [('Idle',0),('Walk',8),('Run',0),('Run',6),('Run',12),('Run',18),('Cast',0),('Cast',5)]: rig.animation_data.action=acts[name][0];sc.frame_set(f);bpy.context.view_layer.update() for view,loc in [('front',(500,0,100)),('quarter',(430,-300,120))]: cam.location=loc;cam.rotation_euler=(Vector((0,0,95))-cam.location).to_track_quat('-Z','Y').to_euler();fn=f'{name}-{f:02d}-{view}.png';sc.render.filepath=str(out/fn);bpy.ops.render.render(write_still=True);shots.append(fn) save('result.json',{'status':'RIG_TRIAL_REQUIRES_PIXEL_REVIEW_NOT_EXPORTED','qa_pass':qa.get('pass'),'qa_errors':qa.get('errors'),'qa_warnings':qa.get('warnings'),'shots':shots,'bones':len(bones),'triangles':len(low.data.polygons),'equipped':False,'files':[{'name':f.name,'bytes':f.stat().st_size,'sha256':hashlib.sha256(f.read_bytes()).hexdigest()}for f in out.iterdir()if f.is_file()]});mark('complete')