Search code examples
phpc++function3dquaternions

How to multiply two quaternions


I have two quaternions, as an example:

    w     x     y     z
1:  0.98  0.08  0.17  -0.01
2:  0.70  0.70  0.0   0.0

I need to multiply them, to get a third one, with all rotations in it.

How do I do that in PHP/C++/PAWN?


Solution

  • You should choose a language. In C++, the Boost.Math library includes quaternions; I don't know about the other languages you mention. Or for simple multiplication, you could just use the multiplication table (which I copied from Wikipedia):

    *| 1  i  j  k
    -------------
    1| 1  i  j  k
    i| i -1  k -j
    j| j -k -1  i
    k| k  j -i -1
    

    For example, i*j gives the value in row i and column j, which is k.

    So, assuming your quaternions represent w*1 + x*i + y*j + z*k, multiplication would be something like

    quaternion operator*(quaternion a, quaternion b) {
        return {
            a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,  // 1
            a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,  // i
            a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,  // j
            a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w   // k
        };
    }
    

    (NOTE: that's untested, and probably riddled with typos).