As @jeremydouglass points out the best solution is to use quaternions because they are flexible, powerful and don’t exhibit gimbol lock. Now having said that there are a number of caveats with using quaternions and using them with Processing.
Creating your own quaternion class is a possibility provided you are seriously good at maths and matrices, the alternative is to find a library implementation.
Both PeasyCam and Shapes3D libraries use the Apache Commons Maths Library which provides an easy to use Rotation class. This class is a wrapper for quaternions but concentrates on providing methods for rotating vectors which is what you want.
Sounds too good to be true? Here is the downside, the library uses the double
data type throughout and Processing uses the float
. The library also has its own vector class (Vector3D) and cannot (unsurprisingly) use Processing’s PVector class.
Just to prove we can all make mistakes, when I decided to incorporate this library into Shapes3D I spent days hacking the library code to provide a Rotation class that used float
and the PVector class, i.e. compatible with Processing. I did a load of static tests comparing the output of Apache and my float version and they looked good. The problem came when using it for real, I got some very unexpected visual rotations and when I debugged the code I found a lot of Float.NaN values (NaN - not a number). It was obvious the float
data type lacked the precision for some of the intermediate calculations. What a waste of time LOL.
PeasyCam and Shapes3D use slightly different approaches to using the library:
- PeasyCam a beautiful library, has created a separate jar file (peasy-math.jar) for the maths and links to that.
- Shapes3D is different because it needs a more intimate link with the Processing sketch and uses the PVector class. I have actually copied the source code of the relevant Maths library classes into Shapes3D and created a utility class to convert between PVector and Vector3D objects.
I suggest that you install Shapes3D because it exposes all of the Apche Maths library you need for rotations and the Util class in Shapes3D provided useful methods for converting between Vector3D and PVector objects.
Try some simple experiments first because it will take awhile to get to understand the Rotation class and how to use it, at least it did for me.