Converting a matrix back to euler angles?

BlitzMax Forums/BlitzMax Programming/Converting a matrix back 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.

Pulled this out of my entity code, may be it will help, or give you some ideas...

Method Point(X#,Y#,Z#)

	Local mat:Float[16]
    	glMatrixMode(GL_MODELVIEW)
    	glPushMatrix()
    	glLoadIdentity()
	gluLookAt(Self.X#,Self.Y#,Self.Z#, X#,Y#,Z#, 0,1,0)
    	glGetFloatv(GL_MODELVIEW_MATRIX, Varptr(mat[0]) );
    	glPopMatrix()

	Local angle_x#, angle_z#
	Local tx#, ty#
	Local angle_y#  =  ASin( mat[8]);       	' /* Calculate Y-axis angle */
	Local C#         =  Cos( angle_y );

	If ( Abs( C ) > 0.005 )             		'/* Gimball lock? */
		tx      =  mat[10] / C           		'/* No, so get X-axis angle */
	    	ty      = -mat[9]  / C
	    	angle_x = ATan2( ty, tx )
	    	tx      =  mat[0] / C            		'/* Get Z-axis angle */
	    	ty      = -mat[4] / C
	    	angle_z = ATan2( ty, tx ) 
	Else                                 		'/* Gimball lock has occurred */
	      	angle_x = 0                      		'/* Set X-axis angle To zero */
	      	tx      = mat[5]                 		'/* And calculate Z-axis angle */
	      	ty      = mat[1]
	      	angle_z = ATan2( ty, tx )
	EndIf

	Yaw   = ATan2(-mat[8],mat[10])
	Pitch = -angle_x
	Roll  = angle_z
	
	If Pitch<0 Pitch:+360
	If Yaw<0 Yaw:+360
	If Roll<0 Roll:+360
	
EndMethod


It's not perfect, it flips 180 half way round, but its the best I've managed so far.