# Correcting bone orientation in Python

I'm working on an importer from a game format, using an existing MaxScript for reference.

So far things have been working out pretty well, but I was wondering what the best way to solve this issue is: These bones should really be pointing down the line, and I'm not sure if it is the way I'm orienting them when they're created.

for bone in self.bones:
bone.blend_editbone = self.blend_armatureobj.data.edit_bones.new(bone.name)
bone.blend_editbone.tail = (1,0,0)
bone.blend_name = bone.blend_editbone.name # actual name
transform_loc = Matrix.Translation(bone.pos)
transform_rot = bone.rot.to_matrix()
transform_rot.resize_4x4()
if bone.parent_id is None: # no parent
bone.blend_editbone.matrix = transform_loc * transform_rot
else: #parent
parent_bone = self.bones[bone.parent_id]
bone.blend_editbone.parent = parent_bone.blend_editbone
bone.blend_editbone.matrix = parent_bone.blend_editbone.matrix * transform_loc * transform_rot


(all happening within EDIT mode of an armature, for each bone, in descending hierarchy -- parents first)

As I'm not a whizz at quaternions or matrices, let alone the two combined, I may have the order of operations wrong. Alternatively, the stored bone formats are of a different orientation.

I've got the bones importing as seen and parenting with the mesh correctly. It poses correctly, but I'm having trouble incorporating animation, and as the animation data's format is practically the same as that for setting the bone's original orientation, I figured getting this right would help getting the animations functioning.

I've attempted to use_connected, but as I expected it forces the rotation upon the bones, great for manual posing a model you made yourself I suppose, but results in a jumbled mess when I'm trying to set these orientations to precise values.

The orientation quaternions I'm reading in appear to be local for the bone, using the parent bone's orientation as a rotational origin. I'm wondering how to rotate these without causing the later bones to inherit an incorrect parent orientation.

Here's a different model with the same issue:

Any help with the correct way to orient these bones when importing would be greatly appreciated!

• The 90 degree out tends to suggest a different bone orientation. Blender uses y-up on bones, ie if the bone is facing up, it's the y axis of the bone. I came across this with bvh import. Look for axis_conversion in .../scripts/modules/bpy_extras/io_utils.py. – batFINGER Sep 20 '15 at 16:05
• @batFINGER Yeah after seeing how the FBX importer corrects object orientation I've given this a shot, but I can't get it working correctly -- I've tried multiplying the rotation matrix (transform_rot) with the correction matrix that axis_conversion spits out, but that appears to break all the child bone's orientations. – Frohman Sep 21 '15 at 9:06