object rotation and alignment to a face in another objects

I want to rotate the Plane which I called face1 in the image attached to align with face2 in the cube. I want to do this in python. I tried several times using the normal of face 2 but did not work. I created vectors using vertices of face 2 but did not work. I don't know what I am doing wrong.

I want to align the two faces with all tangential axes, not only a vector. It is better to share the same position. But the important part is to rotate face1 to have same tangential axes.

Regarding the way to align them, I would like to know both ways, if the results of aligning both faces in these ways are the same. In what I'm trying to do, it does not matter which point to rotate around, I guess.

Consider face1 a face part of a different object than the cube. I want to align two different faces, each from a different object together. So, the object1 that face1 belongs to should move as well. (Thank you quiliup)

• I have several questions: 1. What does 'align' mean? The faces having only the same normal vector or all (tangential) axes too? Do they also want to share the same position (all vertices have same coordinates)? 2. How do you want to align them? Setting the vertices individually or only rotating Face1? If rotating, around which point? 3. What else is there that should be moved together with Face1? I guess you do not want to have just a duplicate (Shift-Ding ;) of Face2. Please add all answers to your question. – quiliup Aug 17 '18 at 6:39
• Have you looked and programmatically creating Constraints? – rob Aug 17 '18 at 9:29

This is how I got what I wanted:

1. I got 3 connected vertices of face2 (polygon5) from the cube (v1, v3, and v5).
2. the vertex (v1) connected to both other vertices (v3 and v5) is going to be the origin of my new local coordinates.
3. each vertex is represented by a vetcor (from origin to vertex) in Blender.
4. I chose vector v1-to-v3 to be x axis, vector v1-to-v5 to be y axis, then the cross product of both (normal between the two) to be z axis.
5. Construct the 4x4 rotation matrix.
6. give face 1 the same rotation.

code:

import bpy
import mathutils

p = bpy.data.objects['Plane']
c = bpy.data.objects['Cube']

# You need to know which face of the cube is selected, in my case it is no. 5
# you need to know the vertices of face 5, in my case they are 1,2,3,5
# you need to pick a vertex to be origin, I chose 1
# you need to know which vertices connected directly to vertex 1 by an edge, in my case 3 and 5

x = c.matrix_world * c.data.vertices[3].co - c.matrix_world * c.data.vertices[1].co
i = x.normalized()
y = c.matrix_world * c.data.vertices[5].co - c.matrix_world * c.data.vertices[1].co
j = y.normalized()
z = x.cross(y)
k = z.normalized()

rot = mathutils.Matrix((i,j,k)).transposed().to_4x4()

p.matrix_world = rot