import sys from pathlib import Path sys.path.insert(0,str(Path(__file__).resolve().parent)) """Adapt the supplied sculpture, retain its detail and retarget the existing rig. Run with Blender 5: blender --background --python tools/build_infernal.py [-- --bake] """ import bpy,bmesh,math,json,sys,heapq import numpy as np from pathlib import Path from mathutils import Vector,Matrix from mathutils.kdtree import KDTree ROOT=Path(__file__).resolve().parent.parent OUT=ROOT/'Demon_v0.19/reviews/infernal_v01';OUT.mkdir(parents=True,exist_ok=True) QA=ROOT/'Demon_v0.19/captures/infernal';QA.mkdir(parents=True,exist_ok=True) CUT=.150 BAKE='--bake' in sys.argv bpy.ops.wm.read_factory_settings(use_empty=True) bpy.context.preferences.view.use_translate_new_dataname=False scene=bpy.context.scene;scene.render.fps=24 def active(obj): bpy.ops.object.select_all(action='DESELECT');obj.select_set(True);bpy.context.view_layer.objects.active=obj def log(*args):print('INFERNAL',*args,flush=True) def color_role(p,hint=None): x,y,z=p;z+=CUT;a=abs(x) if hint in [4,5]:return 2 if z<1.025 and a>.245 else 0 # The outer membranes and spars are behind the exposed arms. wing=(a>.39 and z>.54) or (a>.215 and y>.102 and z>1.12) or (a>.22 and z>1.72) tail=(z<1.27 and y>.085 and a<.40 and (z<.70 or a>.17 or y>.185)) hair=(a<.19 and z>1.968-(.85 if x<0 else .55)*a) or (a<.17 and y>.075 and z>1.30) or (.0651.52) horn=z>1.96 if hint in [1,2,3] or wing or tail:return 3 if hair or horn:return 2 if z<.615:return 1 top=1.545+.080*min(a/.12,1);bottom=1.10+.13*min(a/.19,1) width=float(np.interp(z,[1.1,1.25,1.4,1.55,1.63],[.18,.205,.17,.185,.17])) if a.245 and z<1.025:return 2 return 0 PALETTE=[('Crimson skin',(.42,.013,.024),.47,0),('Black leather corset and boots',(.012,.016,.019),.30,.12),('Black hair and horns',(.009,.010,.014),.41,.02),('Dark bat wings and armoured tail',(.018,.019,.023),.52,.04),('Amber eyes',(.32,.18,.02),.25,.10),('Dark red lips',(.045,.002,.008),.33,0)] materials=[] for name,color,rough,metal in PALETTE: m=bpy.data.materials.new(name);m.diffuse_color=(*color,1);m.use_nodes=True shader=next(n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED');shader.inputs['Base Color'].default_value=(*color,1);shader.inputs['Roughness'].default_value=rough;shader.inputs['Metallic'].default_value=metal materials.append(m) # Preserve the supplied geometry as the bake source, cutting only the pedestal. bpy.ops.wm.stl_import(filepath=str(ROOT/'tools/model_sources/infernal.stl')) high=bpy.context.object;high.name='Infernal_High_Source_No_Pedestal';high.scale*=2.2/high.dimensions.z bpy.context.view_layer.update();corners=[high.matrix_world@Vector(c) for c in high.bound_box] lo=Vector(tuple(min(p[i] for p in corners) for i in range(3)));hi=Vector(tuple(max(p[i] for p in corners) for i in range(3))) high.location-=Vector(((lo.x+hi.x)/2,(lo.y+hi.y)/2,lo.z));active(high);bpy.ops.object.transform_apply(location=True,rotation=True,scale=True) before=len(high.data.polygons);bm=bmesh.new();bm.from_mesh(high.data) result=bmesh.ops.bisect_plane(bm,geom=list(bm.verts)+list(bm.edges)+list(bm.faces),plane_co=(0,0,CUT),plane_no=(0,0,1),clear_inner=True,dist=.000001) boundary=[e for e in result['geom_cut'] if isinstance(e,bmesh.types.BMEdge) and e.is_boundary and all(abs(v.co.z-CUT)<.00001 for v in e.verts)] if boundary:bmesh.ops.holes_fill(bm,edges=boundary,sides=0) for v in bm.verts:v.co.z-=CUT bmesh.ops.triangulate(bm,faces=list(bm.faces));bm.to_mesh(high.data);bm.free();high.data.update() for m in materials:high.data.materials.append(m) for p in high.data.polygons:p.use_smooth=True;p.material_index=color_role(p.center) log('pedestal removed',before,'->',len(high.data.polygons),'triangles') # Real-time topology; the fine sculpt is retained in the baked normal texture. low=high.copy();low.data=high.data.copy();scene.collection.objects.link(low);low.name='Infernal_Game_Mesh' active(low);modifier=low.modifiers.new('Game topology','DECIMATE');modifier.ratio=.065;modifier.use_collapse_triangulate=True bpy.ops.object.modifier_apply(modifier=modifier.name) for p in low.data.polygons:p.use_smooth=True;p.material_index=color_role(p.center) log('game topology',len(low.data.vertices),'vertices',len(low.data.polygons),'triangles') # Use surface connectivity to distinguish the tail and wing tips from nearby # hands and boots. A spatial box alone stretches the sculpture when arms move. coords=np.empty(len(low.data.vertices)*3,dtype=np.float64);low.data.vertices.foreach_get('co',coords);coords=coords.reshape(-1,3) graph=[[] for _ in coords] for edge in low.data.edges: a,b=edge.vertices;length=float(np.linalg.norm(coords[a]-coords[b]));graph[a].append((b,length));graph[b].append((a,length)) tail_path=np.array([(0,.21,1.25),(.20,.21,1.05),(.33,.17,.85),(.36,.11,.65),(.30,.12,.43),(.12,.15,.26),(-.13,.15,.25),(-.30,.13,.37),(-.33,.12,.52),(-.23,.10,.60)]) arm_path=np.array([(.150,.015,1.70),(.170,.025,1.57),(.190,.035,1.40),(.235,.005,1.25),(.257,-.015,1.10),(.270,-.035,1.00)]) def path_distance(p,path): result=np.inf for start,end in zip(path[:-1],path[1:]): segment=end-start;t=np.clip(np.dot(p-start,segment)/np.dot(segment,segment),0,1);result=min(result,float(np.linalg.norm(p-(start+t*segment)))) return result seeds=[];owner=np.full(len(coords),-1,dtype=np.int8);distance=np.full(len(coords),np.inf) for i,(x,y,z) in enumerate(coords): zo=z+CUT;a=abs(x);label=-1 arm_distance=path_distance(np.array([a,y,zo]),arm_path) if (a<.105 and y<.08 and 1.051.75) or (a<.14 and y<.07 and zo<1.08):label=0 if 1.12.130):label=0 if .980 else 5 if a>.50 and zo>.65:label=1 if x>0 else 2 if a>.23 and zo>1.33 and y>.135:label=1 if x>0 else 2 if a>.32 and zo>1.15 and y>.12:label=1 if x>0 else 2 p=np.array([x,y,zo]);tail_distance=path_distance(p,tail_path) if tail_distance<.028 and y>.075 and zo<1.27:label=3 if label>=0:owner[i]=label;distance[i]=0;heapq.heappush(seeds,(0.,i,label)) while seeds: d,i,label=heapq.heappop(seeds) if d>distance[i]:continue for j,length in graph[i]: nd=d+length if nd.155 and .78.001] if not weights:continue p=body.matrix_world@evaluated_mesh.vertices[i].co;total=sum(w for _,w in weights);at=Vector((0,0,0)) for name,w in weights:at+=(transforms[name]@p)*(w/total) samples.append(at);sample_weights.append(weights) evaluated.to_mesh_clear();tree=KDTree(len(samples)) for i,p in enumerate(samples):tree.insert(p,i) tree.balance();log('skin transfer samples',len(samples)) def arm_name(name):return any(key in name for key in ['upperarm','lowerarm','wrist','finger','metacarpal']) part_trees={} for part in ['core','L','R']: ids=[] for i,weights in enumerate(sample_weights): amount=sum(w for name,w in weights if arm_name(name) and (part=='core' or name.endswith('.'+part))) if (part=='core' and amount<.01) or (part!='core' and amount>.4):ids.append(i) kd=KDTree(len(ids)) for i in ids:kd.insert(samples[i],i) kd.balance();part_trees[part]=kd for name in names:low.vertex_groups.new(name=name) for vertex in low.data.vertices: x,y,z=vertex.co;zo=z+CUT;a=abs(x);weights={} label=int(owner[vertex.index]) arm=label in [4,5] if label in [1,2]: wing_weight=float(np.clip((a-.16)/.16,0,1));weights={'Wing.L' if label==1 else 'Wing.R':wing_weight,'spine02':1-wing_weight} elif label==3: tail_weight=float(np.clip((Vector((x,y,z))-Vector((0,.17,1.09))).length/.16,0,1));weights={'Tail':tail_weight,'spine05':1-tail_weight} elif z<.15:weights={'foot.L' if x>0 else 'foot.R':1.0} elif arm and zo<1.12:weights={'wrist.L' if x>0 else 'wrist.R':1.0} else: shoulder=.130 else 'R') if arm else 'core'] for _,index,distance in kd.find_n(vertex.co,4): factor=1/max(.0001,distance)**2 for name,w in sample_weights[index]: if not shoulder and not arm and arm_name(name):continue if not shoulder and arm and not (arm_name(name) or 'clavicle' in name):continue if z<.95 and abs(x)>.025 and (name.endswith('.L') if x<0 else name.endswith('.R')):continue weights[name]=weights.get(name,0)+w*factor if y>.10 and zo>1.45 and a<.17: blend=float(np.clip((zo-1.45)/.45,.25,1));weights={'head':blend,'spine02':1-blend} pairs=sorted(weights.items(),key=lambda p:-p[1])[:4];total=sum(w for _,w in pairs) for name,w in pairs:low.vertex_groups[name].add([vertex.index],w/total,'REPLACE') # Smooth weights on connected surface regions without smearing hands into clothes. weights_array=np.zeros((len(coords),len(names)),dtype=np.float32) name_index={name:i for i,name in enumerate(names)} for vertex in low.data.vertices: for group in vertex.groups:weights_array[vertex.index,group.group]=group.weight edges=np.array([tuple(e.vertices) for e in low.data.edges],dtype=np.int32) edges=edges[owner[edges[:,0]]==owner[edges[:,1]]] first=np.concatenate((edges[:,0],edges[:,1]));second=np.concatenate((edges[:,1],edges[:,0])) counts=np.maximum(np.bincount(first,minlength=len(coords)),1) for iteration in range(6): average=np.zeros_like(weights_array) for column in range(len(names)): average[:,column]=np.bincount(first,weights=weights_array[second,column],minlength=len(coords))/counts weights_array=weights_array*.45+average*.55 shoulder_seams={} for index,point in enumerate(coords): if 1.481:weights_array[indices]=weights_array[indices].mean(axis=0) for vertex in low.data.vertices: weights=weights_array[vertex.index];indices=np.argsort(weights)[-4:];total=float(weights[indices].sum()) for group in list(vertex.groups):low.vertex_groups[group.group].remove([vertex.index]) for index in indices: if weights[index]>.00001:low.vertex_groups[int(index)].add([vertex.index],float(weights[index])/total,'REPLACE') from infernal_skinning import refine_weights refine_weights(low) log('weights smoothed with semantic boundaries') modifier=low.modifiers.new('Transferred skeleton','ARMATURE');modifier.object=rig;low.parent=rig # Retarget world-space animation deltas relative to the old Idle bind pose. rig.animation_data_create() for clip,frames in sampled.items(): action=bpy.data.actions.new('Infernal / '+clip);rig.animation_data.action=action for f,frame in enumerate(frames,1): desired={} for name in names: bone=rig.data.bones[name];parent=bone.parent head=(desired[parent.name]@(rest[parent.name].inverted()@rest[name]).translation) if parent else rest[name].translation+(frame[name].translation-base[name].translation) q=frame[name].to_quaternion()@base[name].to_quaternion().inverted()@rest[name].to_quaternion() matrix=Matrix.LocRotScale(head,q,Vector((1,1,1)));desired[name]=matrix kwargs={'matrix':matrix,'matrix_local':rest[name],'invert':True} if parent:kwargs.update(parent_matrix=desired[parent.name],parent_matrix_local=rest[parent.name]) basis=bone.convert_local_to_pose(**kwargs);pb=rig.pose.bones[name];pb.rotation_mode='QUATERNION';pb.rotation_quaternion=basis.to_quaternion();pb.location=basis.translation pb.keyframe_insert('rotation_quaternion',frame=f,group=name);pb.keyframe_insert('location',frame=f,group=name) rig.animation_data.action=None;track=rig.animation_data.nla_tracks.new();track.name=clip;strip=track.strips.new(clip,1,action);strip.frame_end=len(frames) track.mute=True log('retargeted',len(names),'bones') bpy.data.orphans_purge(do_recursive=True) bpy.context.preferences.filepaths.save_version=0 bpy.ops.wm.save_as_mainfile(filepath=str(QA/'retarget_checkpoint.blend')) if BAKE: from infernal_bake import bake bake(scene,high,low,materials,PALETTE,OUT,log) from infernal_whip import transfer_whip whip=transfer_whip(scene,source,rig) # Export only the new game mesh and retargeted rig; leave the old asset intact. for track in rig.animation_data.nla_tracks:track.mute=False rig.animation_data.action=None;scene.frame_set(1) for bone in rig.pose.bones:bone.matrix_basis.identity() active(low);rig.select_set(True) if whip:whip.select_set(True) bpy.ops.export_scene.gltf(filepath=str(OUT/'infernal_game.glb'),export_format='GLB',use_selection=True,export_animations=True,export_animation_mode='NLA_TRACKS',export_nla_strips=True,export_force_sampling=True,export_frame_range=False,export_skins=True,export_materials='EXPORT',export_yup=True) report={'source_triangles':before,'source_after_pedestal_cut':len(high.data.polygons),'game_vertices':len(low.data.vertices),'game_triangles':len(low.data.polygons),'bones':len(names),'clips':{k:len(v) for k,v in sampled.items()},'pedestal_removed':True,'cut_height':CUT,'textures_4k':BAKE} report.update(paint_boundary_reference='tools/model_sources/approved_paint_boundary.png',whip_radius_added_m=.008,approval_status='awaiting_visual_approval') (OUT/'manifest.json').write_text(json.dumps(report,indent=2));log('GAME ASSET READY',json.dumps(report)) # Keep an editable optimized source without copying the entire high-poly statue. for obj in list(scene.objects): if obj not in [rig,low,whip]:bpy.data.objects.remove(obj,do_unlink=True) bpy.data.orphans_purge(do_recursive=True) bpy.context.preferences.filepaths.save_version=0 bpy.ops.wm.save_as_mainfile(filepath=str(ROOT/'tools/model_sources/infernal_game.blend'))