Prepare painted rigged Infernal STL model and approval previews

This commit is contained in:
JariKo
2026-10-28 22:07:14 +02:00
parent a99162ae33
commit e53a377ff3
54 changed files with 1618 additions and 44 deletions
+323
View File
@@ -0,0 +1,323 @@
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 (.065<a<.18 and y<.045 and z>1.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<width and bottom<z<top:return 1
if a<.080 and 1.635<z<1.705:return 1
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.05<zo<1.80) or (a<.17 and zo>1.75) or (a<.14 and y<.07 and zo<1.08):label=0
if 1.12<zo<1.34 and a<.185 and (y<-.095 or y>.130):label=0
if .98<zo<1.68 and -.080<y<.085 and arm_distance<.030:label=4 if x>0 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<distance[j]:distance[j]=nd;owner[j]=label;heapq.heappush(seeds,(nd,j,label))
owner[owner<0]=0
# Build separate closed surface pieces at printing contacts. Each piece owns
# its boundary vertices, so capping cannot join a hand back to the corset.
vertices=[];faces=[];labels=[];mapping={};old_coords=coords.copy()
for face in low.data.polygons:
roles=[int(owner[i]) for i in face.vertices];role=max(set(roles),key=roles.count)
indices=[]
for index in face.vertices:
key=(role,index)
if key not in mapping:
mapping[key]=len(vertices);vertices.append(tuple(old_coords[index]));labels.append(role)
indices.append(mapping[key])
faces.append(indices)
partition=bpy.data.meshes.new('Infernal separated printable contacts');partition.from_pydata(vertices,[],faces);partition.update()
low.data=partition
for material in materials:low.data.materials.append(material)
bm=bmesh.new();bm.from_mesh(low.data);bm.verts.ensure_lookup_table();layer=bm.verts.layers.int.new('SemanticRegion')
for vertex in bm.verts:vertex[layer]=labels[vertex.index]
for role in range(6):
boundary=[edge for edge in bm.edges if edge.is_boundary and all(v[layer]==role for v in edge.verts)]
if boundary:bmesh.ops.holes_fill(bm,edges=boundary,sides=0)
bmesh.ops.triangulate(bm,faces=list(bm.faces));bm.to_mesh(low.data);bm.free();low.data.validate(clean_customdata=False);low.data.update()
coords=np.empty(len(low.data.vertices)*3);low.data.vertices.foreach_get('co',coords);coords=coords.reshape(-1,3)
owner=np.array([v.value for v in low.data.attributes['SemanticRegion'].data],dtype=np.int8)
for face in low.data.polygons:face.use_smooth=True
log('separated and capped semantic surfaces',len(coords),'vertices')
region_tree=KDTree(len(coords))
for i,p in enumerate(coords):region_tree.insert(p,i)
region_tree.balance()
for p in low.data.polygons:
labels=[int(owner[i]) for i in p.vertices];label=max(set(labels),key=labels.count);p.material_index=color_role(p.center,label)
for p in high.data.polygons:
_,index,_=region_tree.find(p.center);p.material_index=color_role(p.center,int(owner[index]))
log('geodesic regions',{str(label):int((owner==label).sum()) for label in range(6)})
# Import and sample the exact old clips before changing any bind transforms.
existing=set(scene.objects)
bpy.ops.import_scene.gltf(filepath=str(ROOT/'Demon_v0.19/art/succubus/succubus_v02.glb'))
imported=set(scene.objects)-existing;source=next(o for o in imported if o.type=='ARMATURE')
body=next(o for o in imported if o.type=='MESH' and 'Succubus' in o.name)
source_tracks={t.name:t.strips[0].action for t in source.animation_data.nla_tracks if len(t.strips)}
for t in source.animation_data.nla_tracks:t.mute=True
source.animation_data.action=source_tracks['Idle'];scene.frame_set(1);bpy.context.view_layer.update()
names=[b.name for b in source.data.bones];base={b.name:source.pose.bones[b.name].matrix.copy() for b in source.data.bones}
old_head={name:base[name].translation.copy() for name in names}
sampled={}
for clip in ['Idle','Walk','Whip']:
action=source_tracks[clip];source.animation_data.action=action;frames=[]
for f in range(1,int(action.frame_range[1])+1):
scene.frame_set(f);bpy.context.view_layer.update();frames.append({n:source.pose.bones[n].matrix.copy() for n in names})
sampled[clip]=frames
log('sampled original clips',[(key,len(value)) for key,value in sampled.items()])
def warp(p):
x,y,z=p;a=abs(x)
if a>.155 and .78<z<1.48:
zz=float(np.interp(z,[.78,.97,1.124,1.363,1.48],[.66,.91,1.15,1.56,1.66]))
xx=x*float(np.interp(z,[.78,.97,1.124,1.363,1.48],[.80,.84,.95,1.02,1.02]));yy=y*.20+.010
else:
zz=float(np.interp(z,[0,.026,.072,.494,.89,1.10,1.36,1.575,1.72,2.0],[0,.022,.115,.605,1.055,1.30,1.56,1.69,1.88,2.16]))
if z<.95:
xx=x*float(np.interp(z,[0,.072,.494,.89,.95],[.42,.42,.65,1.05,1.05]))
yy=(y+.03)*.85+.04 if z<.1 else y*.4+float(np.interp(z,[.1,.5,.9],[.05,.02,.02]))
else:xx=x*1.01;yy=y*.7+.015
return Vector((xx,yy,zz))
target_data=bpy.data.armatures.new('Infernal_Retargeted_166');rig=bpy.data.objects.new('INFERNAL_RIG',target_data);scene.collection.objects.link(rig)
active(rig);bpy.ops.object.mode_set(mode='EDIT')
for name in names:
src=source.data.bones[name];b=target_data.edit_bones.new(name)
b.head=warp(base[name].translation);b.tail=warp(base[name]@Vector((0,src.length,0)))
if (b.tail-b.head).length<.001:b.tail=b.head+Vector((0,0,.008))
b.align_roll(base[name].to_3x3().col[2])
if name.startswith('Wing.'):
sign=1 if name.endswith('L') else -1;b.head=(sign*.18,.12,1.43);b.tail=(sign*.32,.15,1.58)
if name=='Tail':b.head=(0,.17,1.09);b.tail=(.07,.22,.96)
# Match the sculpture's elbow height rather than stretching its upper arm.
arm_heads=[(.153,.015,1.54),(.170,.025,1.42),(.194,.035,1.25),(.228,.005,1.09),(.257,-.020,.93)]
arm_bones=['upperarm01','upperarm02','lowerarm01','lowerarm02','wrist']
for side,sign in [('L',1),('R',-1)]:
for index,name in enumerate(arm_bones):
bone=target_data.edit_bones[name+'.'+side];head=Vector(arm_heads[index]);head.x*=sign;delta=head-bone.head
bone.head=head
if index<len(arm_heads)-1:
end=Vector(arm_heads[index+1]);end.x*=sign;bone.tail=end
else:bone.tail+=delta
for bone in target_data.edit_bones:
if bone.name.endswith('.'+side) and any(key in bone.name for key in ['finger','metacarpal']):bone.head.z+=.021;bone.tail.z+=.021
for name in names:
if source.data.bones[name].parent:target_data.edit_bones[name].parent=target_data.edit_bones[source.data.bones[name].parent.name]
bpy.ops.object.mode_set(mode='OBJECT')
rest={b.name:b.matrix_local.copy() for b in rig.data.bones}
# Transfer from the posed human surface, not from a T-pose or a distance grid.
source.animation_data.action=source_tracks['Idle'];scene.frame_set(1);bpy.context.view_layer.update()
evaluated=body.evaluated_get(bpy.context.evaluated_depsgraph_get());evaluated_mesh=evaluated.to_mesh()
body_materials={i for i,m in enumerate(body.data.materials) if m and any(s in m.name for s in ['Succubus skin','Bare thighs','Thigh high'])}
body_ids=set(i for p in body.data.polygons if p.material_index in body_materials for i in p.vertices)
transforms={n:rest[n]@base[n].inverted() for n in names};samples=[];sample_weights=[]
for i in sorted(body_ids):
weights=[(body.vertex_groups[g.group].name,g.weight) for g in body.data.vertices[i].groups if body.vertex_groups[g.group].name in transforms and g.weight>.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=.13<a<.28 and 1.48<zo<1.74 and y<.065
kd=tree if shoulder else part_trees[('L' if x>0 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.48<point[2]+CUT<1.74:
key=tuple(np.round(point,6));shoulder_seams.setdefault(key,[]).append(index)
for indices in shoulder_seams.values():
if len(indices)>1: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'))
+8
View File
@@ -0,0 +1,8 @@
"""Encode actual Godot captures for STL model approval."""
from pathlib import Path
import argparse,subprocess
parser=argparse.ArgumentParser();parser.add_argument('--ffmpeg',required=True);args=parser.parse_args()
r=Path(__file__).resolve().parent.parent;project=r/'Demon_v0.19';out=project/'reviews/infernal_v01'
for sequence,count,name in [('full',144,'walking'),('outfit',120,'turntable'),('action',96,'whip'),('portrait',72,'face')]:
subprocess.run([args.ffmpeg,'-hide_banner','-loglevel','error','-y','-framerate','24','-i',str(project/'captures/infernal'/sequence/'%03d.png'),'-filter_complex','[0:v]scale=1000:-1:flags=lanczos,split[a][b];[a]palettegen=max_colors=192[p];[b][p]paletteuse=dither=sierra2_4a','-frames:v',str(count),'-loop','0',str(out/(name+'.gif'))],check=True)
print(name,count,'frames',flush=True)
+40
View File
@@ -0,0 +1,40 @@
"""Finish paint from the rig checkpoint without repeating geometry conversion."""
import sys,json,bpy
from pathlib import Path
from mathutils import Matrix
sys.path.insert(0,str(Path(__file__).resolve().parent))
from infernal_bake import bake
from infernal_skinning import refine_weights
from infernal_whip import transfer_whip
r=Path(__file__).resolve().parent.parent;out=r/'Demon_v0.19/reviews/infernal_v01';qa=r/'Demon_v0.19/captures/infernal'
bpy.ops.wm.open_mainfile(filepath=str(qa/'retarget_checkpoint.blend'))
scene=bpy.context.scene;low=bpy.data.objects['Infernal_Game_Mesh'];rig=bpy.data.objects['INFERNAL_RIG'];high=bpy.data.objects['Infernal_High_Source_No_Pedestal']
source=next(o for o in scene.objects if o.type=='ARMATURE' and o!=rig)
materials=list(high.data.materials);palette=[(m.name,tuple(m.diffuse_color[:3]),next(n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED').inputs['Roughness'].default_value,next(n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED').inputs['Metallic'].default_value) for m in materials]
def log(*args):print('INFERNAL',*args,flush=True)
refine_weights(low)
# Keep exposed arms red; the hair mask must not paint forearms black.
from mathutils.kdtree import KDTree
kd=KDTree(len(low.data.vertices))
for vertex in low.data.vertices:kd.insert(vertex.co,vertex.index)
kd.balance();regions=low.data.attributes['SemanticRegion'].data
for face in high.data.polygons:
_,index,_=kd.find(face.center)
if regions[index].value in [4,5]:face.material_index=2 if face.center.z+.15<1.025 and abs(face.center.x)>.245 else 0
bake(scene,high,low,materials,palette,out,log)
whip=transfer_whip(scene,source,rig)
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=Matrix.Identity(4)
bpy.ops.object.select_all(action='DESELECT');low.select_set(True);rig.select_set(True)
if whip:whip.select_set(True)
bpy.context.view_layer.objects.active=low
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=json.loads((out/'manifest.json').read_text());report.update(textures_4k=True,animated_whip=whip is not None,facial_paint='aligned to sculpt: eyes z1.889, lips z1.817',game_vertices=len(low.data.vertices),game_triangles=len(low.data.polygons))
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('FINISHED',report)
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(r/'tools/model_sources/infernal_game.blend'))
+73
View File
@@ -0,0 +1,73 @@
import bpy,math,numpy as np
from mathutils import Matrix
def active(obj):
bpy.ops.object.select_all(action="DESELECT");obj.select_set(True);bpy.context.view_layer.objects.active=obj
def bake(scene,high,low,materials,palette,out,log):
rig=low.parent
from infernal_surface import prepare_surface
materials=prepare_surface(high,low)
# Bake colour, sculpt detail and material response into actual 4K maps.
for o in [o for o in scene.objects if o not in [high,low]]:o.hide_render=True
high.hide_render=False;low.hide_render=False
scene.render.engine='CYCLES';scene.cycles.samples=8
try:
preferences=bpy.context.preferences.addons['cycles'].preferences;preferences.compute_device_type='OPTIX';preferences.get_devices()
for device in preferences.devices:device.use=device.type!='CPU'
scene.cycles.device='GPU'
except Exception as error:log('CPU bake fallback',str(error))
active(low);bpy.ops.object.mode_set(mode='EDIT');bpy.ops.mesh.select_all(action='SELECT');bpy.ops.uv.smart_project(angle_limit=math.radians(66),island_margin=.003);bpy.ops.object.mode_set(mode='OBJECT')
final=bpy.data.materials.new('Infernal 4K PBR');final.use_nodes=True;low.data.materials.clear();low.data.materials.append(final)
for p in low.data.polygons:p.material_index=0
scene.render.bake.use_selected_to_active=True;scene.render.bake.cage_extrusion=.004;scene.render.bake.max_ray_distance=.010;scene.render.bake.margin=10
for bone in rig.pose.bones:bone.matrix_basis=Matrix.Identity(4)
low.modifiers['Transferred skeleton'].show_render=False;low.modifiers['Transferred skeleton'].show_viewport=False
for kind,filename in [('DIFFUSE','infernal_basecolor.png'),('NORMAL','infernal_normal.png'),('EMIT','infernal_orm.png')]:
image=bpy.data.images.new(filename,width=4096,height=4096,alpha=False)
if kind!='DIFFUSE':image.colorspace_settings.name='Non-Color'
node=final.node_tree.nodes.new('ShaderNodeTexImage');node.image=image;final.node_tree.nodes.active=node
if kind=='DIFFUSE':scene.render.bake.use_pass_direct=False;scene.render.bake.use_pass_indirect=False;scene.render.bake.use_pass_color=True
if kind=='EMIT':
for material in materials:
nodes=material.node_tree.nodes;links=material.node_tree.links
shader=next(n for n in nodes if n.type=='BSDF_PRINCIPLED')
combine=nodes.new('ShaderNodeCombineColor');combine.inputs[0].default_value=1
for key,index in [('Roughness',1),('Metallic',2)]:
socket=shader.inputs[key]
if socket.is_linked:links.new(socket.links[0].from_socket,combine.inputs[index])
else:combine.inputs[index].default_value=socket.default_value
emission=nodes.new('ShaderNodeEmission');links.new(combine.outputs[0],emission.inputs['Color']);links.new(emission.outputs[0],next(n for n in nodes if n.type=='OUTPUT_MATERIAL').inputs['Surface'])
bpy.ops.object.select_all(action='DESELECT');high.select_set(True);low.select_set(True);bpy.context.view_layer.objects.active=low
bpy.ops.object.bake(type=kind)
if kind=='NORMAL':
pixels=np.array(image.pixels[:],dtype=np.float32).reshape(-1,4)
empty=np.max(pixels[:,:3],axis=1)<.001
pixels[empty,:3]=(.5,.5,1)
image.pixels.foreach_set(pixels.ravel())
image.filepath_raw=str(out/filename);image.file_format='PNG';image.save();image.pack();log('baked',filename)
shader=next(n for n in final.node_tree.nodes if n.type=='BSDF_PRINCIPLED')
if kind=='DIFFUSE':final.node_tree.links.new(node.outputs['Color'],shader.inputs['Base Color'])
if kind=='NORMAL':
normal=final.node_tree.nodes.new('ShaderNodeNormalMap');final.node_tree.links.new(node.outputs['Color'],normal.inputs['Color']);final.node_tree.links.new(normal.outputs['Normal'],shader.inputs['Normal'])
if kind=='EMIT':
separate=final.node_tree.nodes.new('ShaderNodeSeparateColor');final.node_tree.links.new(node.outputs['Color'],separate.inputs[0]);final.node_tree.links.new(separate.outputs['Green'],shader.inputs['Roughness']);final.node_tree.links.new(separate.outputs['Blue'],shader.inputs['Metallic'])
low.modifiers['Transferred skeleton'].show_render=True;low.modifiers['Transferred skeleton'].show_viewport=True
# Exposed arms use a dedicated skin material, so rays through close printed
# contacts can never copy black clothing or hair onto their albedo.
skin=final.copy();skin.name='Infernal exposed arm skin'
shader=next(n for n in skin.node_tree.nodes if n.type=='BSDF_PRINCIPLED')
for key,value in [('Base Color',(.36,.012,.022,1)),('Roughness',.58),('Metallic',0.0)]:
socket=shader.inputs[key]
for link in list(socket.links):skin.node_tree.links.remove(link)
socket.default_value=value
from infernal_seams import cloth_at_point
low.data.materials.append(skin);region=low.data.attributes['SemanticRegion'].data
for face in low.data.polygons:
p=face.center
zo=p.z+.15;a=abs(p.x)
boundary=float(np.interp(zo,[1.,1.12,1.30,1.40,1.50,1.70],[.21,.21,.205,.15,.135,.135]))
anatomical_arm=.96<zo<1.70 and a>boundary and a<.30 and -.075<p.y<.095
if (all(region[index].value in [4,5] for index in face.vertices) or anatomical_arm) and not (zo>1.65 and p.y>.025 and a>.19) and not cloth_at_point(p):face.material_index=1
+47
View File
@@ -0,0 +1,47 @@
"""Continuous facial paint aligned to the supplied sculpt's actual landmarks."""
import bpy,numpy as np
def apply_facepaint(material):
size=1024
xx=np.linspace(-.085,.085,size,dtype=np.float32)
zz=np.linspace(1.76,1.98,size,dtype=np.float32)
x,z=np.meshgrid(xx,zz);a=np.abs(x)
pixels=np.zeros((size,size,4),dtype=np.float32)
def paint(mask,color):
pixels[mask,:3]=color;pixels[mask,3]=1
eye_z=1.889+.20*(a-.031)
ellipse=((a-.031)/.019)**2+((z-eye_z)/.0057)**2
paint(ellipse<1.30,(.012,.003,.007))
paint(ellipse<.90,(.32,.27,.16))
iris=((a-.031)/.0057)**2+((z-eye_z)/.0064)**2
paint((ellipse<.90)&(iris<1),(.18,.080,.005))
paint((ellipse<.90)&(iris<.60),(.45,.24,.018))
paint((ellipse<.90)&(abs(a-.031)<.0016),(.003,.002,.002))
glint=((a-.029)/.0012)**2+((z-eye_z-.0022)/.0012)**2
paint((ellipse<.90)&(glint<1),(.9,.85,.65))
eyebrow_z=1.911+.22*(a-.030)-3.0*(a-.030)**2
paint((abs(a-.031)<.024)&(abs(z-eyebrow_z)<.0025*(1-abs(a-.031)/.029)),(.010,.002,.005))
lips=(x/.026)**2+((z-1.817)/.0080)**2
paint(lips<1,(.075,.0025,.012))
paint((lips<.75)&(z<1.817),(.15,.005,.025))
line_z=1.819-.0018*np.cos(x/.026*np.pi)
paint((lips<1)&(abs(z-line_z)<.00065),(.020,.001,.003))
paint((lips<.5)&(z<1.815)&(z>1.814),(.22,.015,.035))
image=bpy.data.images.new('Infernal aligned facial paint',width=size,height=size,alpha=True)
image.colorspace_settings.name='Non-Color';image.pixels.foreach_set(pixels.ravel());image.pack()
nodes=material.node_tree.nodes;links=material.node_tree.links
geometry=nodes.new('ShaderNodeNewGeometry');split=nodes.new('ShaderNodeSeparateXYZ');links.new(geometry.outputs['Position'],split.inputs[0])
def math_node(operation,socket,value):
node=nodes.new('ShaderNodeMath');node.operation=operation;links.new(socket,node.inputs[0]);node.inputs[1].default_value=value;return node.outputs[0]
u=math_node('MULTIPLY_ADD',split.outputs['X'],1/.17)
# MULTIPLY_ADD has a separate add input.
u.node.inputs[2].default_value=.5
v=math_node('MULTIPLY_ADD',split.outputs['Z'],1/.22);v.node.inputs[2].default_value=-1.61/.22
vector=nodes.new('ShaderNodeCombineXYZ');links.new(u,vector.inputs['X']);links.new(v,vector.inputs['Y'])
texture=nodes.new('ShaderNodeTexImage');texture.image=image;texture.extension='CLIP';links.new(vector.outputs[0],texture.inputs['Vector'])
front=math_node('LESS_THAN',split.outputs['Y'],.015)
alpha=nodes.new('ShaderNodeMath');alpha.operation='MULTIPLY';links.new(front,alpha.inputs[0]);links.new(texture.outputs['Alpha'],alpha.inputs[1])
shader=next(n for n in nodes if n.type=='BSDF_PRINCIPLED')
mix=nodes.new('ShaderNodeMixRGB');mix.blend_type='MIX';mix.inputs[1].default_value=shader.inputs['Base Color'].default_value
if shader.inputs['Base Color'].is_linked:links.new(shader.inputs['Base Color'].links[0].from_socket,mix.inputs[1])
links.new(alpha.outputs[0],mix.inputs[0]);links.new(texture.outputs['Color'],mix.inputs[2]);links.new(mix.outputs[0],shader.inputs['Base Color'])
+126
View File
@@ -0,0 +1,126 @@
"""Paint contours traced from orthographic renders of the actual supplied sculpt.
Body guides: 1400 px, ortho .96 m, focus original Z 1.45.
Boot guides: 1400 px, ortho .62 m, focus original Z .42.
"""
import bpy,numpy as np
from pathlib import Path
from mathutils import Vector
from mathutils.kdtree import KDTree
_FILL_CLOTH=None
_FILL_SKIN=None
_MASKS={}
_DEPTHS={}
FRONT=[(525,416),(550,420),(570,432),(590,436),(602,458),(620,469),(630,486),(648,499),(663,520),(679,542),(690,550),(700,542),(710,554),(729,528),(746,503),(761,485),(775,465),(790,451),(806,435),(823,423),(839,418),(862,406),(884,443),(905,480),(919,528),(917,567),(907,610),(889,627),(866,690),(860,758),(875,820),(914,866),(1007,931),(1020,937),(1012,964),(994,980),(967,993),(948,1008),(920,1019),(897,1025),(883,1052),(867,1045),(853,1022),(826,1040),(805,1037),(792,1065),(777,1090),(753,1119),(731,1145),(713,1170),(700,1185),(688,1184),(673,1164),(648,1142),(628,1115),(609,1094),(591,1069),(578,1041),(568,1043),(557,1034),(547,1007),(532,1000),(509,1023),(498,1013),(486,988),(464,978),(444,1009),(429,1007),(415,977),(405,947),(387,939),(397,918),(430,902),(464,880),(492,863),(503,844),(510,798),(514,745),(512,707),(506,668),(499,630),(476,612),(461,583),(458,549),(464,505),(478,465),(496,434)]
COLLAR=[(622,201),(641,207),(663,215),(683,227),(700,237),(720,226),(741,214),(774,199),(775,231),(777,263),(784,284),(814,303),(782,314),(782,340),(767,320),(746,325),(737,344),(718,353),(713,376),(700,403),(685,376),(680,352),(658,344),(650,323),(631,321),(621,334),(620,320),(596,324),(612,301),(621,275),(621,234)]
BACK=[(548,380),(852,380),(863,550),(862,730),(883,808),(913,861),(950,901),(980,934),(1000,965),(982,994),(964,1005),(944,1007),(935,979),(916,995),(899,1013),(881,1012),(875,974),(854,991),(844,1025),(824,1028),(817,1007),(811,1052),(794,1102),(778,1143),(764,1168),(745,1158),(750,1120),(755,1080),(739,1052),(713,1037),(686,1037),(661,1050),(637,1079),(614,1112),(590,1141),(569,1156),(554,1135),(558,1095),(572,1055),(588,1025),(574,1006),(565,1029),(549,1026),(539,1006),(524,1026),(506,1019),(503,992),(485,986),(478,1009),(462,1015),(449,998),(434,985),(419,995),(408,979),(414,951),(432,919),(465,888),(488,866),(510,844),(520,798),(527,740),(531,648),(536,533)]
BOOT_FRONT=[(0,301),(392,298),(420,302),(450,301),(464,296),(465,278),(480,270),(510,264),(550,261),(590,261),(620,263),(640,269),(644,284),(659,290),(681,291),(699,282),(718,294),(745,303),(750,280),(770,271),(806,264),(847,262),(885,264),(921,270),(938,279),(938,298),(964,303),(1009,299),(1400,301),(1400,1400),(0,1400)]
BOOT_BACK=[(0,303),(395,299),(425,290),(465,280),(507,272),(548,264),(586,264),(620,267),(660,277),(700,285),(734,276),(780,268),(818,264),(850,264),(890,269),(938,281),(982,293),(1009,303),(1400,303),(1400,1400),(0,1400)]
def mask_image(name,polygons):
if name in _MASKS:return bpy.data.images[name]
size=2048;pixels=np.zeros((size,size,4),dtype=np.float32)
for polygon in polygons:
vertices=np.array(polygon,dtype=np.float64)*size/1400
for row in range(size):
yy=row+.5;cross=[]
for a,b in zip(vertices,np.roll(vertices,-1,axis=0)):
if (a[1]<=yy<b[1]) or (b[1]<=yy<a[1]):cross.append(a[0]+(yy-a[1])*(b[0]-a[0])/(b[1]-a[1]))
cross.sort()
for a,b in zip(cross[::2],cross[1::2]):
lo=max(0,int(np.floor(a)));hi=min(size,int(np.ceil(b)))
if hi>lo:pixels[size-1-row,lo:hi,:3]=1
pixels[:,:,3]=1
image=bpy.data.images.new(name,width=size,height=size,alpha=True);image.colorspace_settings.name='Non-Color';image.pixels.foreach_set(pixels.ravel());image.pack();_MASKS[name]=pixels;return image
def add_sculpt_seams(nodes,links,x,y,z):
def math(operation,socket,value):
n=nodes.new('ShaderNodeMath');n.operation=operation;links.new(socket,n.inputs[0])
if isinstance(value,(int,float)):n.inputs[1].default_value=value
else:links.new(value,n.inputs[1])
return n.outputs[0]
def sample(name,polygons,width,bottom,back=False):
xx=math('MULTIPLY',x,-1) if back else x
u=math('MULTIPLY_ADD',xx,1/width);u.node.inputs[2].default_value=.5
v=math('MULTIPLY_ADD',z,1/width);v.node.inputs[2].default_value=-bottom/width
vector=nodes.new('ShaderNodeCombineXYZ');links.new(u,vector.inputs['X']);links.new(v,vector.inputs['Y'])
tex=nodes.new('ShaderNodeTexImage');tex.image=polygons if isinstance(polygons,bpy.types.Image) else mask_image(name,polygons);tex.extension='CLIP';links.new(vector.outputs[0],tex.inputs['Vector']);return tex.outputs['Color']
side=math('MULTIPLY_ADD',y,12);side.node.inputs[2].default_value=.5
side=math('MAXIMUM',math('MINIMUM',side,1),0)
def blend(front,back):
mix=nodes.new('ShaderNodeMixRGB');links.new(side,mix.inputs[0]);links.new(front,mix.inputs[1]);links.new(back,mix.inputs[2]);return mix.outputs[0]
def visible(mask,depth):
delta=math('SUBTRACT',math('ADD',y,.5),depth)
near=math('LESS_THAN',math('ABSOLUTE',delta,0),.018)
return math('MULTIPLY',mask,near)
front=sample('Sculpt garment front',[FRONT,COLLAR],.96,.97)
back=sample('Sculpt garment back',[BACK,COLLAR],.96,.97,True)
front_depth=sample('Front depth',_DEPTHS['front'][0],.96,.97)
back_depth=sample('Back depth',_DEPTHS['back'][0],.96,.97,True)
body=math('MAXIMUM',visible(front,front_depth),visible(back,back_depth))
boots=blend(sample('Sculpt boot rim front',[BOOT_FRONT],.62,.11),sample('Sculpt boot rim back',[BOOT_BACK],.62,.11,True))
return math('MAXIMUM',body,boots)
def prepare_depths(high):
# Project onto the visible sculpt surface, not every surface behind it.
# This keeps the black ruffle from being projected onto a nearby forearm.
output=Path(__file__).resolve().parent.parent/'Demon_v0.19/captures/infernal'
scene=bpy.data.scenes.new('Sculpt seam depth');scene.render.engine='BLENDER_EEVEE'
scene.render.resolution_x=2048;scene.render.resolution_y=2048;scene.render.resolution_percentage=100;scene.render.film_transparent=True
scene.render.image_settings.file_format='OPEN_EXR';scene.render.image_settings.color_depth='32';scene.render.image_settings.color_mode='RGBA'
obj=high.copy();obj.hide_render=False;scene.collection.objects.link(obj)
mat=bpy.data.materials.new('Surface depth');mat.use_nodes=True;n=mat.node_tree.nodes;l=mat.node_tree.links;n.clear()
geo=n.new('ShaderNodeNewGeometry');split=n.new('ShaderNodeSeparateXYZ');l.new(geo.outputs['Position'],split.inputs[0])
add=n.new('ShaderNodeMath');add.operation='ADD';l.new(split.outputs['Y'],add.inputs[0]);add.inputs[1].default_value=.5
emission=n.new('ShaderNodeEmission');l.new(add.outputs[0],emission.inputs[0]);out=n.new('ShaderNodeOutputMaterial');l.new(emission.outputs[0],out.inputs[0]);scene.view_layers[0].material_override=mat
data=bpy.data.cameras.new('Seam projection camera');camera=bpy.data.objects.new('Seam projection camera',data);scene.collection.objects.link(camera);scene.camera=camera;data.type='ORTHO';data.ortho_scale=.96
for side,yy in [('front',-6),('back',6)]:
camera.location=(0,yy,1.30);camera.rotation_euler=(Vector((0,0,1.30))-camera.location).to_track_quat('-Z','Y').to_euler()
scene.render.filepath=str(output/('seam-depth-'+side+'.exr'));bpy.ops.render.render(scene=scene.name,write_still=True)
image=bpy.data.images.load(scene.render.filepath,check_existing=False);pixels=np.array(image.pixels[:],dtype=np.float32).reshape(2048,2048,4);_DEPTHS[side]=(image,pixels)
bpy.data.objects.remove(obj,do_unlink=True);bpy.data.objects.remove(camera,do_unlink=True);bpy.data.scenes.remove(scene)
mask_image('Sculpt garment front',[FRONT,COLLAR]);mask_image('Sculpt garment back',[BACK,COLLAR])
prepare_hidden_fill(high)
def cloth_at_point(point):
x,y,z=point;z+=.15;seen=False
for side in ['front','back']:
xx=-x if side=='back' else x
u=(xx/.96+.5)*2048;v=(z-.97)/.96*2048
if not (0<=u<2048 and 0<=v<2048):continue
column=int(u);row=int(v)
mask=_MASKS['Sculpt garment '+side][row,column,0]
depth=_DEPTHS[side][1][row,column,0]
if abs(y+.5-depth)<.018:
seen=True
if mask>.5:return True
if not seen and _FILL_CLOTH is not None and 1.09<z<1.85 and abs(x)<.26:
_,_,a=_FILL_CLOTH.find(point);_,_,b=_FILL_SKIN.find(point)
return a<b and a<.07
return False
def prepare_hidden_fill(high):
global _FILL_CLOTH,_FILL_SKIN
points=np.array([tuple(v.co) for v in high.data.vertices],dtype=np.float64);n=len(points)
visible=np.zeros(n,dtype=bool);clothing=np.zeros(n,dtype=bool)
original_z=points[:,2]+.15
for side,sign in [('front',1),('back',-1)]:
cols=np.clip(((points[:,0]*sign/.96+.5)*2048).astype(int),0,2047)
rows=np.clip(((original_z-.97)/.96*2048).astype(int),0,2047)
depth=_DEPTHS[side][1][rows,cols,0]
mask=_MASKS['Sculpt garment '+side][rows,cols,0]>.5
view=(abs(points[:,1]+.5-depth)<.006)&(original_z>.97)&(original_z<1.93)&(abs(points[:,0])<.48)
visible|=view;clothing|=view&mask
body=(original_z>1.09)&(original_z<1.85)&(abs(points[:,0])<.26)
cloth_ids=np.flatnonzero(clothing&body);skin_ids=np.flatnonzero(visible&~clothing&body)
_FILL_CLOTH=KDTree(len(cloth_ids));_FILL_SKIN=KDTree(len(skin_ids))
for i in cloth_ids:_FILL_CLOTH.insert(points[i],int(i))
for i in skin_ids:_FILL_SKIN.insert(points[i],int(i))
_FILL_CLOTH.balance();_FILL_SKIN.balance()
fill=np.zeros(n,dtype=np.float32)
for i in np.flatnonzero(~visible&body):
_,_,a=_FILL_CLOTH.find(points[i]);_,_,b=_FILL_SKIN.find(points[i])
if a<b and a<.07:fill[i]=1
attribute=high.data.attributes.new('GarmentHiddenFill','FLOAT','POINT');attribute.data.foreach_set('value',fill)
print('INFERNAL seam interior fill',int(fill.sum()),'hidden sculpt vertices',flush=True)
+73
View File
@@ -0,0 +1,73 @@
"""Anatomical weights for STL arms; avoid rolling helper-bone discontinuities."""
import numpy as np,bmesh
from mathutils import Vector
def clean_arm_contacts(obj):
if obj.get("arm_contacts_cleaned",False):return
path=[Vector(p) for p in [(.150,.015,1.70),(.170,.025,1.57),(.190,.035,1.40),(.235,.005,1.25),(.257,-.015,1.10),(.270,-.035,1.00)]]
bm=bmesh.new();bm.from_mesh(obj.data);region=bm.verts.layers.int.get('SemanticRegion');remove=[]
# The printed boots touch at the centre. Split that contact into two capped
# soles, otherwise one walking foot drags triangles from the other shoe.
lower=[f for f in bm.faces if all(v[region]==0 and v.co.z<.96 for v in f.verts)]
geom=set(lower)
for f in lower:geom.update(f.verts);geom.update(f.edges)
result=bmesh.ops.bisect_plane(bm,geom=list(geom),plane_co=(0,0,0),plane_no=(1,0,0),dist=1e-7)
cut=[e for e in result['geom_cut'] if isinstance(e,bmesh.types.BMEdge)]
if cut:bmesh.ops.split_edges(bm,edges=cut)
for sign in [-1,1]:
boundary=[e for e in bm.edges if e.is_boundary and all(v[region]==0 and abs(v.co.x)<1e-6 and v.co.z<.96 for v in e.verts) and e.link_faces and e.link_faces[0].calc_center_median().x*sign>0]
if boundary:bmesh.ops.holes_fill(bm,edges=boundary,sides=0)
foot_side=bm.verts.layers.int.new('FootSide')
for vertex in bm.verts:
if vertex[region]==0 and vertex.co.z<.95:
sign=1 if sum(f.calc_center_median().x for f in vertex.link_faces)>0 else -1
vertex[foot_side]=sign
if abs(vertex.co.x)<1e-6:vertex.co.x=sign*.0003
for face in bm.faces:
if not all(vertex[region] in [4,5] for vertex in face.verts):continue
p=face.calc_center_median();p.x=abs(p.x);p.z+=.15
if p.z<1.13 or p.z>1.65:continue
distance=10
for a,b in zip(path[:-1],path[1:]):
delta=b-a;t=max(0,min(1,(p-a).dot(delta)/delta.length_squared));distance=min(distance,(p-a-delta*t).length)
radius=.046 if p.z>1.30 else .042
if distance>radius:remove.append(face)
if remove:bmesh.ops.delete(bm,geom=remove,context='FACES')
for side in [4,5]:
edges=[e for e in bm.edges if e.is_boundary and all(v[region]==side for v in e.verts)]
if edges:bmesh.ops.holes_fill(bm,edges=edges,sides=0)
bmesh.ops.recalc_face_normals(bm,faces=list(bm.faces));bmesh.ops.triangulate(bm,faces=list(bm.faces));bm.to_mesh(obj.data);bm.free();obj.data.validate(clean_customdata=False);obj.data.update()
obj['arm_contacts_cleaned']=True
print('INFERNAL trimmed print-contact arm fins',len(remove),flush=True)
def refine_weights(obj):
clean_arm_contacts(obj)
attrs=obj.data.attributes['SemanticRegion'].data
names={g.name:g for g in obj.vertex_groups}
for vertex in obj.data.vertices:
x,y,z=vertex.co;zo=z+.15;region=attrs[vertex.index].value
if region==0 and z<.95:
side='L' if x>0 else 'R'
if z<.18:
for group in list(vertex.groups):obj.vertex_groups[group.group].remove([vertex.index])
names['foot.'+side].add([vertex.index],1,'REPLACE')
else:
for group in list(vertex.groups):
name=obj.vertex_groups[group.group].name
if name.endswith('.R' if side=='L' else '.L'):obj.vertex_groups[group.group].remove([vertex.index])
total=sum(group.weight for group in vertex.groups)
for group in list(vertex.groups):obj.vertex_groups[group.group].add([vertex.index],group.weight/max(total,1e-8),'REPLACE')
if region not in [4,5]:continue
side='L' if x>0 else 'R'
if zo>1.65 and y>.085:
weights={'Wing.'+side:1.0}
else:
wrist=float(np.clip((1.17-zo)/.08,0,1))
upper=float(np.clip((zo-1.36)/.12,0,1))
shoulder=float(np.clip((zo-1.62)/.09,0,1))
weights={'wrist.'+side:wrist,'lowerarm01.'+side:(1-wrist)*(1-upper),'upperarm01.'+side:upper*(1-shoulder),'spine02':upper*shoulder}
total=sum(weights.values())
for group in list(vertex.groups):obj.vertex_groups[group.group].remove([vertex.index])
for name,value in weights.items():
if value>1e-5:names[name].add([vertex.index],value/total,'REPLACE')
+68
View File
@@ -0,0 +1,68 @@
"""Continuous PBR surface masks in object space; no triangle-sized paint edges."""
import bpy,numpy as np
from mathutils.kdtree import KDTree
def prepare_surface(high,low):
from infernal_seams import prepare_depths
prepare_depths(high)
kd=KDTree(len(low.data.vertices));regions=low.data.attributes['SemanticRegion'].data
for vertex in low.data.vertices:kd.insert(vertex.co,vertex.index)
kd.balance()
values=np.zeros(len(high.data.vertices),dtype=np.float32)
arms=np.zeros(len(high.data.vertices),dtype=np.float32)
for vertex in high.data.vertices:
_,index,_=kd.find(vertex.co);role=regions[index].value
x,y,z=vertex.co
zo=z+.15;a=abs(x)
boundary=float(np.interp(zo,[1.,1.12,1.30,1.40,1.50,1.70],[.21,.21,.205,.15,.135,.135]))
arm=(role in [4,5] or (.96<zo<1.70 and a>boundary and -.075<y<.095 and a<.30)) and not (zo>1.65 and y>.025 and a>.19)
arms[vertex.index]=1 if arm else 0
values[vertex.index]=1 if (role in [1,2,3] or (a>.19 and y>.025 and zo>1.65)) and not arm else 0
attribute=high.data.attributes.new('AppendageMask','FLOAT','POINT');attribute.data.foreach_set('value',values)
arm_attr=high.data.attributes.new('ExposedArmMask','FLOAT','POINT');arm_attr.data.foreach_set('value',arms)
material=bpy.data.materials.new('Infernal continuous surface paint');material.use_nodes=True
high.data.materials.clear();high.data.materials.append(material)
for face in high.data.polygons:face.material_index=0
nodes=material.node_tree.nodes;links=material.node_tree.links
def op(operation,*args):
node=nodes.new('ShaderNodeMath');node.operation=operation
for i,value in enumerate(args):
if isinstance(value,(float,int)):node.inputs[i].default_value=value
else:links.new(value,node.inputs[i])
return node.outputs[0]
def AND(*args):
result=args[0]
for v in args[1:]:result=op('MULTIPLY',result,v)
return result
def OR(*args):
result=args[0]
for v in args[1:]:result=op('MAXIMUM',result,v)
return result
def within(value,lo,hi):return AND(op('GREATER_THAN',value,lo),op('LESS_THAN',value,hi))
geometry=nodes.new('ShaderNodeNewGeometry');split=nodes.new('ShaderNodeSeparateXYZ');links.new(geometry.outputs['Position'],split.inputs[0])
x=split.outputs['X'];y=split.outputs['Y'];z=op('ADD',split.outputs['Z'],.15);a=op('ABSOLUTE',x)
attr=nodes.new('ShaderNodeAttribute');attr.attribute_name='AppendageMask'
appendage=attr.outputs['Fac']
arm_attr=nodes.new('ShaderNodeAttribute');arm_attr.attribute_name='ExposedArmMask';exposed=op('SUBTRACT',1,arm_attr.outputs['Fac'])
hairline=op('SUBTRACT',1.968,op('MULTIPLY',a,.7))
hair=OR(AND(op('LESS_THAN',a,.19),op('GREATER_THAN',z,hairline)),AND(op('LESS_THAN',a,.17),op('GREATER_THAN',y,.078),op('GREATER_THAN',z,1.30)),AND(within(a,.072,.215),op('LESS_THAN',y,.045),op('GREATER_THAN',z,1.52)),op('GREATER_THAN',z,1.99))
from infernal_seams import add_sculpt_seams
clothes=add_sculpt_seams(nodes,links,x,y,z)
interior=nodes.new('ShaderNodeAttribute');interior.attribute_name='GarmentHiddenFill'
clothes=OR(clothes,interior.outputs['Fac'])
hair=AND(OR(hair,AND(within(a,.05,.19),op("GREATER_THAN",y,-.025),op("GREATER_THAN",z,1.68))),exposed)
shader=next(n for n in nodes if n.type=='BSDF_PRINCIPLED')
def mix_color(socket,mask,color):
mix=nodes.new('ShaderNodeMixRGB');links.new(mask,mix.inputs[0])
if hasattr(socket,'node'):links.new(socket,mix.inputs[1])
else:mix.inputs[1].default_value=(*socket,1)
mix.inputs[2].default_value=(*color,1)
return mix.outputs[0]
color=mix_color((.36,.012,.022),clothes,(.012,.015,.019))
color=mix_color(color,hair,(.008,.009,.012));color=mix_color(color,appendage,(.014,.016,.019));links.new(color,shader.inputs['Base Color'])
# Matte skin and restrained leather highlights preserve the sculpted detail.
rough=op('SUBTRACT',.58,op('MULTIPLY',clothes,.14));rough=op('SUBTRACT',rough,op('MULTIPLY',hair,.08))
links.new(rough,shader.inputs['Roughness']);shader.inputs['Metallic'].default_value=.03
from infernal_facepaint import apply_facepaint
apply_facepaint(material)
return [material]
+27
View File
@@ -0,0 +1,27 @@
"""Preserve the old animated whip and bind it to the retargeted right wrist."""
import bpy
def transfer_whip(scene,source,target):
whip=next((o for o in scene.objects if o.type=='MESH' and 'Flexible braided whip' in o.name),None)
if whip is None:return None
transform=target.data.bones['wrist.R'].matrix_local@source.data.bones['wrist.R'].matrix_local.inverted()
if whip.data.shape_keys:
for key in whip.data.shape_keys.key_blocks:
for point in key.data:point.co=transform@point.co
else:
for vertex in whip.data.vertices:vertex.co=transform@vertex.co
# Increase the actual cord radius, retaining its centreline and morph clips.
whip.data.update()
offsets=[vertex.normal.normalized()*.008 for vertex in whip.data.vertices]
if whip.data.shape_keys:
for key in whip.data.shape_keys.key_blocks:
for point,offset in zip(key.data,offsets):point.co+=offset
else:
for vertex,offset in zip(whip.data.vertices,offsets):vertex.co+=offset
whip.parent=target;whip.name='Infernal animated whip';whip.hide_render=False
for modifier in whip.modifiers:
if modifier.type=='ARMATURE':modifier.object=target
if whip.data.shape_keys and whip.data.shape_keys.animation_data:
whip.data.shape_keys.animation_data.action=None
for track in whip.data.shape_keys.animation_data.nla_tracks:track.mute=False
return whip
+35
View File
@@ -0,0 +1,35 @@
import bpy
import json
from pathlib import Path
from mathutils import Vector
root=Path(__file__).resolve().parent.parent
out=root/'Demon_v0.19/captures/infernal-inspect';out.mkdir(parents=True,exist_ok=True)
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.wm.stl_import(filepath=str(root/'tools/model_sources/infernal.stl'))
model=bpy.context.object;model.name='Infernal source - untouched statue'
original=list(model.dimensions)
model.scale*=2.2/model.dimensions.z
bpy.context.view_layer.update()
points=[model.matrix_world@Vector(c) for c in model.bound_box]
lo=Vector(tuple(min(p[i] for p in points) for i in range(3)));hi=Vector(tuple(max(p[i] for p in points) for i in range(3)))
model.location-=Vector(((lo.x+hi.x)/2,(lo.y+hi.y)/2,lo.z))
bpy.ops.object.transform_apply(location=True,rotation=True,scale=True)
scene=bpy.context.scene;scene.render.engine='BLENDER_WORKBENCH'
scene.render.resolution_x=1100;scene.render.resolution_y=1100;scene.render.resolution_percentage=100
scene.display.shading.light='STUDIO';scene.display.shading.color_type='SINGLE';scene.display.shading.single_color=(.58,.58,.61)
scene.display.shading.show_cavity=True;scene.display.shading.cavity_type='BOTH';scene.display.shading.curvature_ridge_factor=1.2;scene.display.shading.curvature_valley_factor=1.0
scene.display.shading.background_type='WORLD';scene.world=bpy.data.worlds.new('Inspection background');scene.world.color=(.10,.11,.13)
scene.view_settings.view_transform='Standard'
camera_data=bpy.data.cameras.new('Inspection Camera');camera=bpy.data.objects.new('Inspection Camera',camera_data);scene.collection.objects.link(camera);scene.camera=camera
camera_data.type='ORTHO';camera_data.ortho_scale=max(2.55,model.dimensions.x*1.15)
focus=Vector((0,0,1.1))
for name,at in [('front',(0,-6,1.15)),('back',(0,6,1.15)),('side',(6,0,1.15)),('angle',(4,-6,2.9))]:
camera.location=at;camera.rotation_euler=(focus-camera.location).to_track_quat('-Z','Y').to_euler()
scene.render.filepath=str(out/(name+'.png'));bpy.ops.render.render(write_still=True)
coords=[v.co.z for v in model.data.vertices]
import numpy as np
report={'source_dimensions':original,'normalized_dimensions':list(model.dimensions),'vertices':len(model.data.vertices),'triangles':len(model.data.polygons),'z_percentiles':np.percentile(coords,[0,1,3,5,10,15,20,25,50,75,95,100]).tolist()}
(out/'source_report.json').write_text(json.dumps(report,indent=2))
bpy.ops.wm.save_as_mainfile(filepath=str(out/'source_inspection.blend'))
print('INFERNAL_INSPECT',json.dumps(report),flush=True)
+11
View File
@@ -0,0 +1,11 @@
{
"provided_by_user": true,
"source_archive": "infernal.zip",
"archive_entry": "infernal .stl",
"source_stl_sha256": "9a0bad3fe47628b07b2bac1af2a22dbebc153f7bf4274346822515aab2801d3e",
"color_reference": "color_reference.png",
"color_reference_sha256": "34d8c86eb62cc36bb8dac449be8601893cb80c6b5f19e33dae563d5658d6a877",
"animation_source": "Demon_v0.19/art/succubus/succubus_v02.glb",
"paint_boundary_reference": "approved_paint_boundary.png",
"paint_boundary_sha256": "3193824095b8eafb02e0771085e00bc3b9d303f5d53e777972d11b63d71d6e8c"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 663 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 KiB

Binary file not shown.
Binary file not shown.
+31
View File
@@ -0,0 +1,31 @@
"""Validate the actual optimized mesh, paint protection and all transferred clips."""
import bpy,numpy as np,json,struct
from pathlib import Path
r=Path(__file__).resolve().parent.parent;out=r/'Demon_v0.19/reviews/infernal_v01'
bpy.ops.wm.open_mainfile(filepath=str(r/'tools/model_sources/infernal_game.blend'))
o=bpy.data.objects['Infernal_Game_Mesh'];rig=bpy.data.objects['INFERNAL_RIG'];v=np.array([tuple(x.co) for x in o.data.vertices]);edges=np.array([tuple(e.vertices) for e in o.data.edges]);initial=np.linalg.norm(v[edges[:,0]]-v[edges[:,1]],axis=1)
assert len(rig.data.bones)==166
assert np.isfinite(v).all() and v[:,2].min()>-.0001
floor=v[v[:,2]<.01];assert len(floor)>0 and abs(floor[:,0]).max()<.13,'pedestal left below feet'
assert len(o.data.polygons)<100000
for vertex in o.data.vertices:assert abs(sum(group.weight for group in vertex.groups)-1)<.001
skin=next(m for m in o.data.materials if m.name=='Infernal exposed arm skin');shader=next(n for n in skin.node_tree.nodes if n.type=='BSDF_PRINCIPLED')
assert not shader.inputs['Base Color'].is_linked and shader.inputs['Base Color'].default_value[0]>.3
for name in ['infernal_basecolor.png','infernal_normal.png','infernal_orm.png']:
image=bpy.data.images[name];assert tuple(image.size)==(4096,4096)
for t in rig.animation_data.nla_tracks:t.mute=True
metrics={}
for clip in ['Idle','Walk','Whip']:
action=bpy.data.actions['Infernal / '+clip];rig.animation_data.action=action;maximum=0.;max_edge=0.
for frame in range(1,int(action.frame_range[1])+1,4):
bpy.context.scene.frame_set(frame);bpy.context.view_layer.update();ev=o.evaluated_get(bpy.context.evaluated_depsgraph_get());mesh=ev.to_mesh();p=np.array([tuple(x.co) for x in mesh.vertices]);ev.to_mesh_clear()
assert np.isfinite(p).all()
maximum=max(maximum,float(np.linalg.norm(p-v,axis=1).max()));growth=np.linalg.norm(p[edges[:,0]]-p[edges[:,1]],axis=1)-initial;max_edge=max(max_edge,float(growth.max()))
if growth.max()>.14:
edge=edges[growth.argmax()];print('BAD EDGE',clip,frame,[(v[i].round(3).tolist(),[(o.vertex_groups[x.group].name,round(x.weight,3)) for x in o.data.vertices[i].groups]) for i in edge],float(growth.max()),flush=True)
assert maximum<1.2,(clip,maximum)
assert max_edge<.15,(clip,'long stretched film',max_edge)
metrics[clip]={'frames':int(action.frame_range[1]),'max_vertex_travel_m':round(maximum,5),'max_edge_growth_m':round(max_edge,5)}
b=(out/'infernal_game.glb').read_bytes();length=struct.unpack_from('<I',b,12)[0];g=json.loads(b[20:20+length]);assert {a['name'] for a in g['animations']}=={'Idle','Walk','Whip'}
report={'status':'PASS','mesh_vertices':len(v),'mesh_triangles':len(o.data.polygons),'bones':166,'floor_min_z':float(v[:,2].min()),'pedestal_removed':True,'skin_material_protected':True,'pbr_maps':'4096x4096 basecolor / normal / ORM','clips':metrics,'glb_bytes':len(b)}
(out/'validation.json').write_text(json.dumps(report,indent=2));print('INFERNAL ASSET QA',json.dumps(report),flush=True)