CGMatter

Normalize Armature (and Mesh)

Sep 2nd, 2026
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.27 KB | None | 0 0
  1. import bpy
  2. from mathutils import Matrix, Vector
  3.  
  4. MULT        = 1.0      # 1.0 = keep visual size; 100.0 = also make it 100x bigger
  5. CENTER      = "xy"     # axes to recenter; "xyz" = all, "" = off
  6. CENTER_MODE = "ZERO"   # ZERO  = armature location goes to 0 on those axes
  7.                        # BONES = rest-pose bone bbox center goes to the world origin
  8. KEEP_SOURCE = False
  9. REPARENT    = True
  10.  
  11.  
  12. def dims(ob, dg):
  13.     ev = ob.evaluated_get(dg)
  14.     return tuple(max(c) - min(c) for c in
  15.                  zip(*[ev.matrix_world @ Vector(v) for v in ev.bound_box]))
  16.  
  17.  
  18. def fcurves(act):
  19.     yield from getattr(act, "fcurves", [])
  20.     for l in getattr(act, "layers", []):
  21.         for s in l.strips:
  22.             for cb in getattr(s, "channelbags", []):
  23.                 yield from cb.fcurves
  24.  
  25.  
  26. def sel(*obs):
  27.     for o in bpy.context.selected_objects:
  28.         o.select_set(False)
  29.     for o in obs:
  30.         o.select_set(True)
  31.     if obs:
  32.         bpy.context.view_layer.objects.active = obs[0]
  33.  
  34.  
  35. def center_offset(arm, mw):
  36.     """World vector to subtract so the rig lands on the origin. No side effects."""
  37.     if not CENTER:
  38.         return Vector()
  39.     if CENTER_MODE.upper() == "ZERO":
  40.         t = mw.translation
  41.         return Vector([t[i] if a in CENTER else 0.0 for i, a in enumerate("xyz")])
  42.     pts = [mw @ v for b in arm.data.bones for v in (b.head_local, b.tail_local)]
  43.     if not pts:
  44.         return Vector()
  45.     return Vector([(min(c) + max(c)) / 2 if a in CENTER else 0.0
  46.                    for a, c in zip("xyz", zip(*pts))])
  47.  
  48.  
  49. def run():
  50.     s = bpy.context.selected_objects
  51.     rigs = [o for o in s if o.type == 'ARMATURE']
  52.     meshes = [o for o in s if o.type == 'MESH']
  53.     if len(rigs) != 1:
  54.         return f"select exactly one armature (found {len(rigs)})"
  55.     src = rigs[0]
  56.     if bpy.context.object and bpy.context.object.mode != 'OBJECT':
  57.         bpy.ops.object.mode_set(mode='OBJECT')
  58.  
  59.     sc = src.matrix_world.to_scale()
  60.     if max(sc) - min(sc) > 1e-6:
  61.         return f"rig has non-uniform scale {tuple(round(v, 4) for v in sc)} - not fixable this way"
  62.  
  63.     ad = src.animation_data
  64.     acts = set()
  65.     if ad:
  66.         acts = {st.action for t in ad.nla_tracks for st in t.strips if st.action}
  67.         if ad.action:
  68.             acts.add(ad.action)
  69.     bad = sorted({fc.data_path for a in acts for fc in fcurves(a)
  70.                   if fc.data_path.startswith(("location", "rotation", "scale", "delta_"))})
  71.     if bad:
  72.         return f"armature OBJECT is animated {bad} - bake or remove object-level animation first"
  73.  
  74.     shared = [o.name for o in meshes if o.data.users > 1]
  75.     if shared:
  76.         return f"multi-user mesh data on {shared} - make single-user first"
  77.  
  78.     scn = bpy.context.scene
  79.     f0, f1 = scn.frame_start, scn.frame_end
  80.     dg = bpy.context.evaluated_depsgraph_get()
  81.     before = {o.name: dims(o, dg) for o in meshes}
  82.  
  83.     src_mw = src.matrix_world.copy()
  84.     org = src_mw.translation
  85.  
  86.     # Recenter is folded into delta rather than applied afterwards, so the rig is
  87.     # already in its final position before the bake. delta is applied identically
  88.     # to the armature copy and every mesh copy, and src is temporarily moved by it
  89.     # too, so the world-space constraints still line up during the bake.
  90.     off = center_offset(src, src_mw)
  91.     delta = (Matrix.Translation(-off) @ Matrix.Translation(org)
  92.              @ Matrix.Scale(MULT, 4) @ Matrix.Translation(-org))
  93.  
  94.     copies = []
  95.     for ob in meshes:
  96.         sel(ob)
  97.         bpy.ops.object.duplicate(linked=False)
  98.         m = bpy.context.object
  99.         m.name = ob.name + "_scaled"
  100.         m.data.name = m.name
  101.         mw = m.matrix_world.copy()
  102.         m.parent = None
  103.         m.matrix_world = mw
  104.         copies.append((ob, m))
  105.  
  106.     sel(src)
  107.     bpy.ops.object.duplicate(linked=False)
  108.     dst = bpy.context.object
  109.     dst.name = src.name + "_scaled"
  110.     if dst.data == src.data:
  111.         dst.data = src.data.copy()
  112.     dst.data.name = dst.name
  113.     dst.animation_data_clear()
  114.     dst.matrix_world = delta @ src_mw
  115.     sel(dst)
  116.     bpy.ops.object.transform_apply(rotation=True, scale=True)
  117.  
  118.     for c in getattr(dst.data, "collections_all", []):
  119.         c.is_visible = True
  120.     for b in dst.data.bones:
  121.         b.hide = False
  122.  
  123.     for ob, m in copies:
  124.         m.matrix_world = delta @ ob.matrix_world
  125.         for mod in m.modifiers:
  126.             if mod.type == 'ARMATURE' and mod.object in (src, None):
  127.                 mod.object = dst
  128.  
  129.     sel(dst)
  130.     src.matrix_world = delta @ src_mw
  131.     bpy.context.view_layer.update()
  132.  
  133.     bpy.ops.object.mode_set(mode='POSE')
  134.     linked, missing = 0, []
  135.     for pb in dst.pose.bones:
  136.         if pb.name not in src.pose.bones:
  137.             missing.append(pb.name)
  138.             continue
  139.         for c in list(pb.constraints):
  140.             pb.constraints.remove(c)
  141.         for kind, space in (('COPY_LOCATION', 'WORLD'), ('COPY_ROTATION', 'WORLD'),
  142.                             ('COPY_SCALE', 'LOCAL')):
  143.             c = pb.constraints.new(kind)
  144.             c.target, c.subtarget = src, pb.name
  145.             c.target_space = c.owner_space = space
  146.         linked += 1
  147.  
  148.     if not linked:
  149.         bpy.ops.object.mode_set(mode='OBJECT')
  150.         src.matrix_world = src_mw
  151.         return "no matching bones - aborted, delete the copies"
  152.  
  153.     bpy.ops.nla.bake(frame_start=f0, frame_end=f1, step=1, only_selected=False,
  154.                      visual_keying=True, clear_constraints=True, clear_parents=False,
  155.                      use_current_action=False, bake_types={'POSE'})
  156.     bpy.ops.object.mode_set(mode='OBJECT')
  157.  
  158.     for pb in dst.pose.bones:
  159.         for c in list(pb.constraints):
  160.             pb.constraints.remove(c)
  161.     if dst.animation_data and dst.animation_data.action:
  162.         dst.animation_data.action.name = src.name + "_scaled_baked"
  163.     src.matrix_world = src_mw
  164.     bpy.context.view_layer.update()
  165.  
  166.     if copies:
  167.         sel(*[m for _, m in copies])
  168.         bpy.ops.object.transform_apply(rotation=True, scale=True)
  169.     if REPARENT:
  170.         bpy.context.view_layer.update()
  171.         inv = dst.matrix_world.inverted()
  172.         for _, m in copies:
  173.             m.parent = dst
  174.             m.matrix_parent_inverse = inv
  175.  
  176.     report = [(before[ob.name], m) for ob, m in copies]
  177.     if KEEP_SOURCE:
  178.         for o in [src] + [ob for ob, _ in copies]:
  179.             o.hide_set(True)
  180.             o.hide_render = True
  181.     else:
  182.         for ob, _ in copies:
  183.             bpy.data.objects.remove(ob, do_unlink=True)
  184.         bpy.data.objects.remove(src, do_unlink=True)
  185.     sel(dst, *[m for _, m in copies])
  186.  
  187.     dg = bpy.context.evaluated_depsgraph_get()
  188.     lines = [f"  {m.name}: " + " ".join(f"{b / a:.4g}" if a > 1e-9 else "n/a"
  189.              for a, b in zip(a0, dims(m, dg))) for a0, m in report]
  190.     note = f", {len(missing)} unmatched bone(s): {missing[:5]}" if missing else ""
  191.     mode = CENTER_MODE.upper() if CENTER else "off"
  192.     loc = tuple(round(v, 4) for v in dst.matrix_world.translation)
  193.     return (f"baked {linked} bones over {f0}-{f1}, size multiplier {MULT:g}, "
  194.             f"centering {mode} on '{CENTER or '-'}' removed "
  195.             f"{tuple(round(v, 4) for v in off)}, rig location now {loc}{note}\n"
  196.             "mesh size ratios (should all equal the multiplier):\n" + "\n".join(lines))
  197.  
  198.  
  199. print(run())
Advertisement
Add Comment
Please, Sign In to add comment