sidrefresh's picture
Add files using upload-large-folder tool
92f480e verified
Raw History Blame Contribute Delete
12.5 kB
"""Read-only native evaluation and isolated pose probes; never saves candidate."""
import json,math,sys
from pathlib import Path
import bpy
from mathutils import Matrix,Vector
from statistics import median
out=Path(sys.argv[sys.argv.index('--')+1]);scene=bpy.context.scene
if scene.frame_end-scene.frame_start>2400:raise ValueError('Unsupported animation length; review required')
meshes=[o for o in scene.objects if o.type=='MESH' and len(o.data.polygons)>0]
# Select the course body through its native geometry fingerprint, not its name.
# Equivalent rig names/topology are unrestricted; body is supplied by task.
signature=json.loads(Path(__file__).with_name('character-signature.json').read_text())
def fingerprint(o):
import hashlib,struct
h=hashlib.sha256()
for v in o.data.vertices:h.update(struct.pack('<3f',*v.co))
for p in o.data.polygons:
h.update(struct.pack('<I',len(p.vertices)))
for i in p.vertices:h.update(struct.pack('<I',i))
return h.hexdigest()
body=next((o for o in meshes if fingerprint(o)==signature['mesh_geometry_sha256']),None)
if not body:
if meshes:
raise ValueError('Character geometry correspondence unresolved; review modified or alternate meshes rather than assign zero')
out.write_text(json.dumps({'native':{'editable':False,'weighted_binding':False},'reason':'Supplied character mesh missing or edited beyond supported correspondence'})+'\n');sys.exit(0)
mods=[m for m in body.modifiers if m.type=='ARMATURE' and m.object and m.show_viewport]
if not mods:
out.write_text(json.dumps({'native':{'editable':False,'weighted_binding':False},'reason':'Character has no enabled armature binding'})+'\n');sys.exit(0)
if len(mods)!=1:raise ValueError('Multiple character armature modifiers need evaluator review')
arm=mods[0].object;bones=arm.data.bones
if not bones:raise ValueError('Empty armature')
pts=[body.matrix_world@v.co for v in body.data.vertices];low=min(p.z for p in pts);height=max(p.z for p in pts)-low
if height<=0:raise ValueError('Invalid body height')
weights={v.index:[] for v in body.data.vertices};groups={g.index:g.name for g in body.vertex_groups}
for v in body.data.vertices:
weights[v.index]=[(groups[g.group],g.weight) for g in v.groups if groups[g.group] in bones and bones[groups[g.group]].use_deform and g.weight>1e-5]
weighted=sum(bool(x) for x in weights.values())/len(weights)
native={'editable':True,'weighted_binding':weighted>=.90,'weighted_vertex_fraction':weighted,'body':body.name,'armature':arm.name}
# Geometry of supplied T-pose locates lower legs and feet; vertex weights locate
# their deform bones. Topology and bone labels are not required.
foot_indices={};foot_names={};knee_names={};targets={};poles={}
mid=(min(p.x for p in pts)+max(p.x for p in pts))/2
for side,sign in [('L',1),('R',-1)]:
inds=[i for i,p in enumerate(pts) if sign*(p.x-mid)>.015*height and p.z<low+.045*height]
if len(inds)<4:raise ValueError('Cannot map bilateral foot geometry')
foot_indices[side]=inds
scored={}
for i in inds:
for n,w in weights[i]:scored[n]=scored.get(n,0)+w
# A foot rather than toe: highest support among bones beginning near ankle.
candidate=sorted(scored,key=lambda n:scored[n],reverse=True)
foot_names[side]=candidate[0] if candidate else None
legs=[]
for pb in arm.pose.bones:
for c in pb.constraints:
if c.type=='IK' and not c.mute and c.influence>0 and c.target:
world=arm.matrix_world@pb.bone.tail_local
if sign*(world.x-mid)>.015*height and world.z<low+.25*height:legs.append((pb,c))
if len(legs)>1:raise ValueError('Ambiguous leg IK mapping; review required')
if legs:
pb,c=legs[0];knee_names[side]=pb.name
targets[side]=(c.target,c.subtarget);poles[side]=(c.pole_target,c.pole_subtarget) if c.pole_target else None
# Use structural reachability to map roots, never as a rewarded hierarchy.
roots=[b for b in bones if b.parent is None]
# Detached controls and incomplete limbs are ordinary candidate outcomes.
# Choose the root supporting most weighted body geometry for motion tracking;
# probe every top-level bone independently for whole-character carry below.
if not roots:raise ValueError('Armature has no root bones')
def root_support(b):
names={b.name}|{child.name for child in b.children_recursive}
return sum(w for values in weights.values() for n,w in values if n in names)
ranked_roots=sorted(roots,key=lambda b:(-root_support(b),b.name))
root=ranked_roots[0].name
root_mapping={'method':'largest weighted descendant support',
'candidates':[{'name':b.name,'weighted_support':root_support(b)} for b in ranked_roots],
'multiple_roots':len(roots)>1}
head_scores={}
for i,p in enumerate(pts):
if p.z>low+.90*height:
for n,w in weights[i]:head_scores[n]=head_scores.get(n,0)+w
head=max(head_scores,key=head_scores.get) if head_scores else None
hats=[o for o in meshes if o!=body and len(o.data.vertices)>20 and max(o.dimensions)<height*.5]
# Prefer head-associated objects via modifier/parent; geometry still allows
# hats whose binding is missing to receive ordinary failed probe credit.
hat=next((o for o in hats if any(m.type=='ARMATURE' and m.object==arm for m in o.modifiers) or o.parent==arm),hats[0] if len(hats)==1 else None)
if len(hats)>1 and hat is None:raise ValueError('Ambiguous hat mapping')
def update():bpy.context.view_layer.update()
def vertices(obj):
dg=bpy.context.evaluated_depsgraph_get();e=obj.evaluated_get(dg);m=e.to_mesh()
try:return [e.matrix_world@v.co for v in m.vertices]
finally:e.to_mesh_clear()
def eval_arm():return arm.evaluated_get(bpy.context.evaluated_depsgraph_get())
def point(e,n,tail=False):return e.matrix_world@(e.pose.bones[n].tail if tail else e.pose.bones[n].head)
def control_matrix(control):
obj,name=control
return obj.pose.bones[name].matrix.copy() if name else obj.matrix_world.copy()
def set_control(control,m):
obj,name=control
if name:obj.pose.bones[name].matrix=m
else:obj.matrix_world=m
update()
def offset(control,delta):
obj,name=control;m=control_matrix(control)
m.translation+=obj.matrix_world.to_3x3().inverted()@delta if name else delta
set_control(control,m)
def clear_animation():
for o in scene.objects:
if o.animation_data:o.animation_data_clear()
for pb in arm.pose.bones:pb.matrix_basis=Matrix.Identity(4)
update()
# Preserve animation evidence before destructive evaluator-only probes.
rows=[];initial=None;edge_lengths=[];quality_rows=[]
edges=[tuple(e.vertices) for e in body.data.edges]
rest_lengths=[(pts[i]-pts[j]).length for i,j in edges]
forward=Vector((0,-1,0)) # supplied course mesh faces -Y in its authored basis
forward=body.matrix_world.to_3x3()@forward;forward.z=0;forward.normalize()
rest_root=arm.matrix_world@bones[root].matrix_local;local_forward=rest_root.to_3x3().inverted()@forward
for frame in range(scene.frame_start,scene.frame_end+1):
scene.frame_set(frame);update();ea=eval_arm();rm=ea.matrix_world@ea.pose.bones[root].matrix
direction=rm.to_3x3()@local_forward;direction.z=0;direction.normalize()
v=vertices(body)
if len(v)!=len(pts):raise ValueError('Changing topology unsupported')
local=[rm.inverted()@p for p in v]
if initial is None:initial=[p.copy() for p in local]
rms=(sum((a-b).length_squared for a,b in zip(local,initial))/len(local))**.5
soles=[];centres=[]
for side in ('L','R'):
subset=[v[i] for i in foot_indices[side]];z=sorted(p.z for p in subset)
soles.append(z[max(0,int(len(z)*.05))]);centres.append(sum(subset,Vector())/len(subset))
distorted=sum((v[i]-v[j]).length/r<.25 or (v[i]-v[j]).length/r>4 for (i,j),r in zip(edges,rest_lengths) if r>height*1e-5)/max(1,sum(r>height*1e-5 for r in rest_lengths))
rows.append({'frame':frame,'position':list(rm.translation),'forward':list(direction),'foot_lead':(centres[0]-centres[1]).dot(direction),
'foot_heights':[p.z-rm.translation.z for p in centres],'deformation_rms':rms})
quality_rows.append({'soles':soles,'centres':[list(p) for p in centres],'distorted':distorted})
fps=scene.render.fps/scene.render.fps_base
# Ground is the task's visible world XY grid (Z=0), fixed across poses. Evaluated
# contact tracks actual foot mesh vertices, not the ankle bone or arbitrary Z0.
def percentile(values,p):
s=sorted(values);return s[min(len(s)-1,int((len(s)-1)*p))] if s else 0
ground=0.0
slides=[]
for a,b in zip(quality_rows,quality_rows[1:]):
for i in (0,1):
if max(a['soles'][i],b['soles'][i])<=ground+.015*height:
pa,pb=a['centres'][i],b['centres'][i];slides.append(math.hypot(pa[0]-pb[0],pa[1]-pb[1])*fps/height)
quality={'supported':True,'ground_z':ground,'sole_range_h':[[min(r['soles'][i] for r in quality_rows)/height,max(r['soles'][i] for r in quality_rows)/height] for i in (0,1)],'stance_intervals':len(slides),'stance_slide_p90_h_per_s':percentile(slides,.90),
'penetration_p95_h':percentile([max(0,ground-z)/height for r in quality_rows for z in r['soles']],.95),
'distorted_edge_fraction_p95':percentile([r['distorted'] for r in quality_rows],.95)}
clear_animation();base=vertices(body);ea=eval_arm();functional={'legs':{}}
for side in ('L','R'):
result={'target_response':False,'pole_response':False};functional['legs'][side]=result
target=targets.get(side);pole=poles.get(side);knee=knee_names.get(side)
if not target or not knee:continue
original=control_matrix(target);ankle_before=point(ea,knee,True)
delta=Vector((0,0,.03*height));offset(target,delta);after=vertices(body);new_ea=eval_arm();ankle_after=point(new_ea,knee,True)
target_error=(ankle_after-ankle_before-delta).length/height
mesh_response=math.sqrt(sum((after[i]-base[i]).length_squared for i in foot_indices[side])/len(foot_indices[side]))/height
result.update(target_error_h=target_error,foot_mesh_response_h=mesh_response,target_response=target_error<=.01 and mesh_response>=.005)
set_control(target,original)
if pole:
pole_original=control_matrix(pole);before_ea=eval_arm();before_knee=point(before_ea,knee);before_ankle=point(before_ea,knee,True)
offset(pole,Vector((.08*height,0,0)));pe=eval_arm();response=(point(pe,knee)-before_knee).length/height;detach=(point(pe,knee,True)-before_ankle).length/height
result.update(knee_response_h=response,ankle_detachment_h=detach,pole_response=response>=.002 and detach<=.01)
set_control(pole,pole_original)
ea=eval_arm()
root_probes=[]
for candidate in ranked_roots:
root_control=(arm,candidate.name);original=control_matrix(root_control)
base=vertices(body);delta=Vector((.04*height,.03*height,0))
offset(root_control,delta);after=vertices(body)
err=math.sqrt(sum((b-a-delta).length_squared for a,b in zip(base,after))/len(base))/height
root_probes.append({'name':candidate.name,'passed':err<=.005,'carry_error_h':err})
set_control(root_control,original)
functional['root']=dict(min(root_probes,key=lambda p:p['carry_error_h']))
functional['root']['probes']=root_probes
functional['hat']={'passed':False}
if hat and head:
original=arm.pose.bones[head].matrix_basis.copy();before=vertices(hat);ea=eval_arm();old_world=ea.matrix_world@ea.pose.bones[head].matrix
arm.pose.bones[head].matrix_basis=original@Matrix.Rotation(math.radians(12),4,'X');update()
ea=eval_arm();new_world=ea.matrix_world@ea.pose.bones[head].matrix;expected=new_world@old_world.inverted();after=vertices(hat)
err=math.sqrt(sum((b-expected@a).length_squared for a,b in zip(before,after))/len(before))/height
response=math.sqrt(sum((expected@a-a).length_squared for a in before)/len(before))/height
functional['hat']={'passed':response>=.005 and err<=.005,'expected_hat_motion_h':response,'follow_error_h':err};arm.pose.bones[head].matrix_basis=original;update()
report={'native':native,'mapping':{'root':root,'root_selection':root_mapping,'feet':foot_names,'knees':knee_names,'head':head,'hat':hat.name if hat else None},'functional':functional,
'character_height':height,'fps':fps,'frames':rows,'bound_character':native['weighted_binding'],'has_pose_motion':max((r['deformation_rms'] for r in rows),default=0)>=height*.02,
'quality':quality,'blender_version':bpy.app.version_string,'never_saved':True}
out.write_text(json.dumps(report)+'\n')