February 27 2012
If you do a lot of graphics development, you’re sure to use lots of vector math. A while ago I wrote some C++ extensions to Apple’s GLKit Math utilities, but haven’t had a chance to explain why they would be helpful, and how they can improve your graphics code.
So, say you have a simple numerical solver that keeps track of the position of a ball over time written in straight C or Objective-C. You might have some code that looks like this:
That’s a tad awkward, so defining a struct to contain x,y,z floats together makes a lot of sense:
Functions operating on structs
Well that’s kind of better, but I want to do the same operation on every coordinate, and I don’t want to keep peppering around these identical bits of code everywhere, so I’ll define some convenience functions:
We can even do some optimizations for the processor architecture that we’re running on. For instance, ARMv7 (available on recent iOS devices) has a set of extensions called “NEON” that allow operations on multiple data simultaniously at a hardware level.
For iOS 5’s new GLKit framework, Apple created a set of functions like our
addVector that use NEON vector instructions to accelerate operations on vectors and matrices without having to pepper your own code with ifdefs.
The problem now is that these function names
mulVectorScalar have taken the place of much more intuitive operators like
*. Also, if we decide that the ball only needs to be a 2-element vector instead of a 3-element vector, we would need to switch all of the places where we update its position to new functions and new structs.
If we switch over to c++ land, we have a tool (operator overloading) that will let us have something both concise and efficient.
This is implemented in GLKVector2_cpp.h as follows:
So, if you don’t mind switching to c++, you can make your vector math a lot clearer to read (and hopefully reduce typos). If you notice anything amiss in with these headers or anything you think should be added, please create an issue or send a pull request on github