Aligning one grid to another when rotation is already applied

Hey guys, I have 2 grids that have one face each in some random space in 3d and they’re both rotated. The rotation is applied so its all 0’s, but the transformation isn’t (it can be, but it doesn’t have to be). How can I match the rotation of plane A to plane B, without changing the position of plane A’s vertex[0]? Doesn’t matter if it does change first and then I just move it all, but that’s the whole picture.

Obviously this is all way easier to do when the rotation isn’t applied, but unfortunately this is what I have.

My initial feeling is to use the normal of each face to construct a matrix with up and cross product, but I don’t know what to do after that. Any ideas?

Here’s a GIF of what I have. As you can see, close but no cigar.

I am also looking for this. I have found some this, but I want it for Blender 2.8

Anyone how can fix that?

in a scene with the default cube, add a grid, then run this script. the grid will be aligned to the face at index zero on the cube. from this example you should be able to make whatever tweaks you need to achieve your desired results.

import bpy
import math
from mathutils import Matrix, Vector, Euler, Quaternion

cube =['Cube']
grid =['Grid']

def matrix_from_components(loc=(0,0,0), rot=(0,0,0), scale=(1,1,1)):
    mat_loc = Matrix.Translation(loc)
    rot = Vector(rot).to_track_quat('Z').to_euler()
    mat_rot = rot.to_matrix().to_4x4()
    mat_sca = Matrix.Scale(scale[0],4,(1,0,0)) @ Matrix.Scale(scale[1],4,(0,1,0)) @ Matrix.Scale(scale[2],4,(0,0,1))
    return mat_loc @ mat_rot @ mat_sca

cube_normal =[0].normal
cube_center = cube.matrix_world @[0].center
align_matrix = matrix_from_components(cube_center, cube_normal)

grid.matrix_world = align_matrix

It works if both the Grid and the Cube only have been rotated in object mode and they still have there rotation data left. If I go into edit mode and rotate the mesh on the Grid and the go back to object mode and run the script, I will not get the Grid aligend to the face of the Cube.
Any ideas on how a script for that will look like?

Hey guys, check out this other thread I posted- Creating a grid with bmesh results in 0,0,0 rotation

Icythe gives a solution there. The missing link is using invert rotation on the grids matrix to get it back to zero before placing it on the cube.