# JavaFX 3D using a single matrix for transformations

There are some advantages to using a scene graph, but the way things are implemented in JavaFX can mean half a dozen or so transformations, ( an axis angle rotation for each axis and a translation at least!).  This is well and good, but many people have their own library of code, for example you might want to use Quaternions for your rotations, the easiest way I have found is to use a single affine matrix for each scene node (parented on the root of the scene).  This allows you to adapt your normal 4×4 matrix math routines to work with JavaFX.

I’ve put a few simple routines into a Pivot class, the idea being you add the pivot to the root of your scene then add your 3d shape/model to the pivot.  Once the pivot is set up you use its functionality to move and rotate your model.  Using a pivot for the scenes camera as well allows you to point the camera at any arbitrary point.  It seems a little odd that JavaFX is trying to hide the lower level stuff, yet its missing higher level stuff like making one node face another…

Lets look at some code!

```public class Pivot extends Group {
private final double[] idt={1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
protected Affine matrix = new Affine(idt,MatrixType.MT_3D_4x4,0);```

While the Pivot extends Group (so you can use it as a parent) you shouldn’t use setTranslateX etcetera but rather manipulate the matrix via Pivot methods (extending or modifying Pivot if needed)

Get and set position are obvious and operate on Tx,Ty & Tz ( elements 3, 7, & 11)

There are really only two example utility routines setEularRotation(double rx, double ry, double rz) and lookAt(Vec3d centre, Vec3d up) – obviously in a more real world finished class you’d have more routines than this!

Both these routines leave the translation component of the matrix alone and operate just on the rotational part (the upper left 3×3 patch of the 4×4 matrix)

The Affine class is a welcome addition to JavaFX allowing better low level control for much more flexibility.  However from what I’ve seen of material handling things might not be as easy – I’m currently investigating lower level material handling (access to shaders is a must in this day and age!) but thats a topic for another day.

You can get the full source here jfxTest.tar.gz – you’ll note that there is nothing in the lib directory all dependencies are covered by JavaFX so class path and library path problems are just a bad memory! (the build script is also much easier)