I have written this script to try and align the orientation of all selected faces with the last selected face:
import bpy
import bmesh
import mathutils
context = bpy.context
ob = context.object
me = ob.data
#Get the translation of the object in world space
mw = ob.matrix_world.copy()
selfaces =[]
bpy.ops.object.mode_set(mode='EDIT') #Processing must be done in EDIT mode
bm = bmesh.from_edit_mesh(me)
#Show face selection order
for e in bm.select_history:
if isinstance(e, bmesh.types.BMFace) and e.select:
selfaces.append(e)
# Get normal of last selected face
axis_src = selfaces[-1].normal
# local z-axis
axis_dst = mathutils.Vector((0, 0, 1))
#Rotate all faces to match the orientation of the last selected
for f in selfaces[:-1]:
diff = axis_src.rotation_difference(f.normal).to_matrix().inverted()
print(diff)
bmesh.ops.rotate(bm, cent=f.calc_center_median(), matrix=diff, verts=f.verts)
bmesh.update_edit_mesh(me)
It is aligning the faces as desired. But it also seems to mirror the vertices along the y axis intersecting the centre of the object. Can anyone figure out where this is happening? I have looked at the rotation matrices for this and it looks like it is just applying the 45 degree and -45 degree rotation around the y axis.