I copy the locations for each bone in my armature (left) by using a Template armature (right) to copy from.
But I see that all parented object get moved after I have applied the changes:
You can see the "Cube" object moves after running the script. I have found no way to overcome this offset.
I have included the .blend file which contains the script and the two armatures ("run script" to test).
Also here is just the script. It tries to copy the edit bones from the template avatar to the final avatar, then it attempts to remove the offsets for all child objects (but slight offsets still persists):
import bpy
from mathutils import Matrix
def get_bone_children(parent, objects):
children = []
for ob in objects:
if ob.parent_bone == parent.name:
print(bpy.data.objects[ob.name])
children.append(bpy.data.objects[ob.name])
return children
armature = bpy.data.objects['Armature'] #The "destination" armature
bones = bpy.data.armatures['Armature.001'].bones #the source "template" bones
for i, bone in enumerate(bones):
#match the head/tail local positions between the two armatures
head_pos = bone.head_local
tail_pos = bone.tail_local
armature.data.bones[bone.name].head_local = head_pos
armature.data.bones[bone.name].tail_local = tail_pos #Removed from main loop because makehuman rigs showed overlapping bones, besides the tail is unnecessary for pose
bpy.ops.object.mode_set(mode='EDIT') #must do this or else the new positions will not be updated
bpy.ops.object.mode_set(mode='OBJECT')
pBone = armature.pose.bones.get(bone.name)
children = get_bone_children(armature.data.bones[bone.name], bpy.data.objects)
for c in children: #Parent object to a bone and object becomes offsets - https://blender.stackexchange.com/a/139180/32655
c.matrix_parent_inverse = (armature.matrix_world * Matrix.Translation(pBone.tail - pBone.head) * pBone.matrix).inverted()
bpy.ops.object.mode_set(mode='EDIT') #must do this or else the new positions will not be updated
bpy.ops.object.mode_set(mode='OBJECT')
Could somebody please kindly help me figure out why my child objects are being offset?