Convert Quat to Euler Angles?

Miscellaneous Forums/General Discussion/Convert Quat to Euler Angles?

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.


Const QuatToEuler_Epsilon# = 0.001


Function MyEulerToQuat(Pitch#, Yaw#, Roll#)
	
	Pitch# = Pitch# / 2.0
	Yaw#   = Yaw#   / 2.0
	Roll#  = Roll#  / 2.0
	
	Cos_Pitch# = Cos(Pitch#)
	Cos_Yaw#   = Cos(Yaw#)
	Cos_Roll#  = Cos(Roll#);
	
	Sin_Pitch# = Sin(Pitch#)
	Sin_Yaw#   = Sin(Yaw#)
	Sin_Roll#  = Sin(Roll#);
	
	CpCy# = Cos_Pitch# * Cos_Yaw#
	SpSy# = Sin_Pitch# * Sin_Yaw#
	SpCy# = Sin_Pitch# * Cos_Yaw#
	CpSy# = Cos_Pitch# * Sin_Yaw#

	QuatLib_Z# = ((Sin_Roll# * CpCy#) - (Cos_Roll# * SpSy#))*-1;x
	QuatLib_X# = ((Cos_Roll# * SpCy#) + (Sin_Roll# * CpSy#))*-1;y
	QuatLib_Y# = (Cos_Roll# * CpSy#) - (Sin_Roll# * SpCy#);z
	QuatLib_W# = (Cos_Roll# * CpCy#) + (Sin_Roll# * SpSy#);w

End Function


Function MyQuatToEuler(Qxx#, Qyy#, Qzz#, Qw#)
	Qx#=Qzz#*-1
	Qy#=Qxx#*-1
	Qz#=Qyy#

	Qx2# = Qx# * 2.0
	Qy2# = Qy# * 2.0
	Qz2# = Qz# * 2.0
	
	Sin_T# = (Qy2# * Qw#) - (Qx2# * Qz#)
	Cos_T# = 1.0 - (Sin_T# * Sin_T#)


	If Abs(Cos_T#) > QuatToEuler_Epsilon#
		Cos_T# = Sqr(Cos_T#)	
	Else
		Cos_T# = 0
	EndIf
		
		
	If Abs(Cos_T#) > QuatToEuler_Epsilon#

		Sin_V# = (      (Qy2# * Qz#) + (Qx2# * Qw#)) / Cos_T#
		Cos_V# = (1.0 - (Qx2# * Qx#) - (Qy2# * Qy#)) / Cos_T#
		Sin_F# = (      (Qx2# * Qy#) + (Qz2# * Qw#)) / Cos_T#
		Cos_F# = (1.0 - (Qy2# * Qy#) - (Qz2# * Qz#)) / Cos_T#

	Else

		Sin_V# =       (Qx2# * Qw#) - (Qy2# * Qz#)
		Cos_V# = 1.0 - (Qx2# * Qx#) - (Qz2# * Qz#)
		Sin_F# = 0
		Cos_F# = 1.0

	EndIf

	QuatLib_Pitch# =  ATan2(Sin_T#, Cos_T#)
	QuatLib_Yaw#   =  ATan2(Sin_F#, Cos_F#)
	QuatLib_Roll#  =  ATan2(Sin_V#, Cos_V#)

End Function


This is my tweaked variation of the functions - seems to work ok for me in Blitz3d at least.