SVML

SVML @ Google Code

While working on my thesis, I needed to simulate GPU calculations and shader operations on the CPU. Shaders use a variation of the C language with a few helper functions, primitive vector types, and a rather interesting type of assisted operation called swizzling. Swizzling allows the rearranging, reading, and writing of a vector's parts in arbitrary, yet structured way. You can do things like this:

my3dVector.zyx = my2dVector.xyy;
// single operation shorthand for...
//   my3dVector.z = my2dVector.x;
//   my3dVector.y = my2dVector.y;
//   my3dVector.x = my2dVector.y;

my3dVector = my4dVector.xyz * 5;
// single operation shorthand for...
//   my3dVector.x = my4dVector.x * 5;
//   my3dVector.y = my4dVector.y * 5;
//   my3dVector.z = my4dVector.z * 5;

// And so on for any type of operation or valid conversion...

This swizzle syntax is not valid C++ code. However, I was just beginning to develop my code-smell sense and it told me that there had to be a way to achieve this syntax in C++ without macros or assembly instructions. After a lot of looking around and asking questions, I found that using a carefully constructed union of structs, I could abuse the dot operator's class method access to achieve the desired reading and writing operations. Unfortunately, it required manually specifying every possible combination of accessor name.

I called my library Simple Vector Math Library (SVML). "Simple" because it was implemented a single header file that could be included into any project and used immediately. The code itself was extremely complicated, topping out at 2996 lines after judicious use of long one-liners. With so much complexity and necessary repetition, I wrote a Perl script to assemble it.

Others expressed interest in making the whole library be templated, so that any number-like type could be used. That part was much more tricky. Eventually I made it work using Substitution Failure Is Not An Error (SFINAE). Finally, this project was my first experience with releasing open source software and unit testing.

By the time I released the first few versions, however, I had finished my thesis. I ran out of time and interest to continue developing the library. I would later learn that more modern C++ techniques using Boost, C++11, and better understanding of template metaprogramming would allow the construction of the same sort of library and syntax, but with drastically reduced amounts of code.