Printing Matrices

Hey Guys. With modern openGL, you have to build all your matrices yourself, and I found that it was really helpful to be able to print your calculated matrices to make sure they are correct.
The LWJGL Matrix4f does provide a toString() method, but that looks like this:

1.0 0.0 0.0 0.0
0.0 0.52532196 -0.8509035 0.0
0.0 0.8509035 0.52532196 0.0
0.0 0.0 0.0 1.0

I built my own method printMatrix4f that formats it to look a lot nicer and makes it much easier to read:

printMatrix4f(mat);

Matrix4f: (
	1.00	0.00	0.00	0.00	

	0.00	0.53	-0.85	0.00	

	0.00	0.85	0.53	0.00	

	0.00	0.00	0.00	1.00	
	)

You can also change the name of the matrix and the number of decimal points shown:

printMatrix4f(mat, "Rotation Matrix", 4);

Rotation Matrix: (
	1.0000	0.0000	0.0000	0.0000	

	0.0000	0.5253	-0.8509	0.0000	

	0.0000	0.8509	0.5253	0.0000	

	0.0000	0.0000	0.0000	1.0000	
	)

I thought this might be useful for other people. Here’s the pastebin of the method I built.

Two things to keep in mind:

  1. It is built to print my own Matrix4f class, but mine is built exactly like the one in LWJGL. You shouldn’t have to change any code to use it.

  2. It uses the reflect package in Java, so it won’t really work if you use obfuscation.

It might not be the most efficient way to do this, but I use it pretty much just for debugging purposes. Also, my mistake if there is already a method available to do this. All I know of is the Matrix4f.toString().

That is pretty cool. In case anyone does not realize, you can define a custom variable formatter for use in your debugger or watch window. You just need something that returns a String instead of printing it.