0
$\begingroup$

I am trying to pose a hand using values read from an XML file. All the joints are parented to the previous joint and finally the fingers to the hand. Í am using the following code:

#imports

bpy.ops.wm.open_mainfile(filepath=filepath)

#load xml etc

for joint in joint_rotations:
    object = bpy.data.objects[joint.name]]
    rot_mat = Matrix.Rotation(joint.rotation, 4, 'X')
    object.matrix_world @= rot_mat

bpy.ops.wm.save_as_mainfile(filepath=outfilepath)

The code works, when I execute it joint for joint by myself, and gives the expected result. However, when I use a for loop to iterate over all elements, I get the wrong result where all elements rotate independently of their parent. Why would a for loop of the same instructions yield a different result than the instructions themselves?

What I want: Parent transformation applied

What I get: Joint rotated independently

$\endgroup$
1
  • $\begingroup$ Please correct the double bracket typo in your question. object = bpy.data.objects[joint.name]] $\endgroup$
    – tetii
    Commented Jul 16, 2023 at 11:58

1 Answer 1

0
$\begingroup$

The reason for this problem is that changing the parent matrix does not update the child matrix while the script is running. To fix this use:
(1) Dependency graph or
(2) matrix_local instead of matrix_world.


Dependency graph

dg = bpy.context.evaluated_depsgraph_get()

for joint in joint_rotations:
    object = bpy.data.objects[joint.name]
    rot_mat = Matrix.Rotation(joint.rotation, 4, 'X')

    obj_eval = object.evaluated_get(dg)
    object.matrix_world = obj_eval.matrix_world @ rot_mat
    dg.update()

matrix_local

for joint in joint_rotations:
    object = bpy.data.objects[joint.name]
    rot_mat = Matrix.Rotation(joint.rotation, 4, 'X')

    # Investigating.: for some reason this code doesn't work. 
    #object.matrix_local @= rot_mat 
    object.matrix_local = object.matrix_local @ rot_mat
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .