View Full Version : working with quaternions

02-06-2007, 04:18 AM
i'm using quaternions to simulate rotations. now i need to multiply a vector by a quaternion in a vertex shader:

vec3 MultiplyVectorByQuaternion( vec3 vector, vec4 quaternion )
vec3 kVector1 = vec3( quaternion.x, quaternion.y, quaternion.z );
vec3 kVector2 = cross( kVector1, vector );

kVector2 += vector*quaternion.w;

vec3 kVector3 = cross( kVector2, kVector1 );

kVector1 *= vector*kVector1;

kVector1 += kVector2*quaternion.w;

return vec3( kVector1-kVector3 );
}this works fine but i guess there are better ways to do it - is there a chance that i can take advantage of glsl's built-in functions to do such calculations?

02-06-2007, 09:30 AM
There is some trick that allows you to transform (not multiply) a vector by a quaternion in 2 operations. It requires some clever use of swizzling, but it can be done (note to ARB: why isn't quaternion/vector transform a built-in function?).

Unfortunately I don't know it. ;)

But I know it exists. Try Google.

02-06-2007, 10:34 AM
Well, a quaternion product can be viewed as the product of a 4x4 matrix with a 4x1 vector, so I might start with that :)

02-07-2007, 06:08 AM
vec3 quat_transform( vec4 q, vec3 v )
return v + 2.*cross( q.xyz, cross( q.xyz, v ) + q.w*v );

03-18-2007, 10:11 AM
Could it be that the component of both crossproducts are swapped?
With swapped components


will be equal to


that is the part from a quaternion to matrix convertion code (the 3rd vector). Imho it should be:

vec3 qtransform( vec4 q, vec3 v ){
return v + 2.0*cross(cross(v, q.xyz ) + q.w*v, q.xyz);