1
$\begingroup$

I'm making a small operator that aligns the 3D cursor to the selected face normal. I have the following code:

fnormal = obj.matrix_world @ selected_faces[0].normal       
bpy.context.scene.cursor.rotation_mode = 'XYZ'
bpy.context.scene.cursor.rotation_euler = fnormal.to_track_quat('Z', 'X').to_euler()

This mostly works. The cursor gets aligned with the face normal like expected but the other axes are not aligned with the face. When comparing with the "normal" transform orientation, its easier to see what I mean: enter image description here

How should I change the code so that the 3D cursor would align with the face the same way as the "normal" transform orientation works?

$\endgroup$

1 Answer 1

2
$\begingroup$

Change 3D cursor Rotation

import bpy

# Select a face in edit mode first...

# change cursor rotation. First create an orientation and get the matrix, and finally delete it.
scene = bpy.context.scene

bpy.ops.transform.create_orientation(use=False)
slot = scene.transform_orientation_slots[0]

def get_orientation_list(slot):
    try: slot.type = ""
    except Exception as inst:
        s = str(inst)
        s = s[50:]
        return eval(s)

slots = get_orientation_list(slot)

old_type = slot.type
slot.type = slots[-1]

mat4x4 = slot.custom_orientation.matrix.to_4x4()
loc, rot, sca = mat4x4.decompose()
print(loc)
print(rot)

cursor = scene.cursor
old_mode = cursor.rotation_mode
cursor.rotation_mode = 'QUATERNION'
scene.cursor.rotation_quaternion = rot

cursor.rotation_mode = old_mode

bpy.ops.transform.delete_orientation()
slot.type = old_type
# change cursor rotation END
$\endgroup$
2
  • $\begingroup$ Do you happen to know where I could find the source code for the bpy.ops.transform.create_orientation operator? I would like to learn more about the math behind it. I tried searching on the Blender github but did not find it. $\endgroup$
    – nyaol9
    Jun 28, 2022 at 18:25
  • 1
    $\begingroup$ github.com/blender/blender/blob/master/source/blender/editors/… $\endgroup$
    – X Y
    Jun 29, 2022 at 0:59

You must log in to answer this question.

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