How to calculate Y axis of rotation difference (pitch)

I want to calculate difference between two rotations in Y axis (pitch). I found this code in UE source:


const FVector RotationDiff = (InCurrentBoneTransform.GetRotation() * InRefPoseBoneTransform.GetRotation().Inverse()).Euler();

It works allright for yaw and roll, but cannot handle pitch > 90°. (I believe this is due to “gimbal lock” problem)

I found a way to calculate pitch correctly when there is no rotation around x/z axis: acos of a dot product between 2 forward vectors.

But I don’t understand what I’m supposed to do if there is rotation around 2 or 3 axis.

Help!