## RE: [Algorithms] Fastest way to rotate a vector by a quaternion in a shader

 RE: [Algorithms] Fastest way to rotate a vector by a quaternion in a shader From: Newport, Matthew - 2005-04-29 18:02:58 ```I actually reached exactly the same result by manipulation of my original version on further investigation yesterday. My orignal version (presented more compactly than in my original email) was: float3 RotateVectorByQuaternion(float3 v, float4 q) { float3 wv_plus_qcrossv =3D q.w * v + cross(q.xyz, v); return dot(q.xyz, v) * q.xyz + (q.w * wv_plus_qcrossv + cross(q.xyz, wv_plus_qcrossv)); } Which compiles down to 8 instructions. My version of the routine you give below was this: float3 RotateVectorByQuaternion2(float3 v, float4 q) { return 2 * (dot(q.xyz, v) * q.xyz + (q.w * q.w - 0.5) * v + q.w * cross(q.xyz, v)); } Which compiles to 9 instructions but has a scalar operation which some hardware may be able to do in parallel with one of the vector ops so it's probably the same speed.=20 Your original derivation is a lot simpler than the working I went through to get the second routine though :-) Thanks, Matt. -----Original Message----- From: gdalgorithms-list-admin@... [mailto:gdalgorithms-list-admin@...] On Behalf Of Willem de Boer Sent: Friday, April 29, 2005 5:14 AM To: gdalgorithms-list@... Subject: RE: [Algorithms] Fastest way to rotate a vector by a quaternion in a shader Hi, > off the top of my head, try this >=20 > x' =3D x + 2 * cross( Q.xyz, cross( Q.xyz, x ) - Q.w * x ) >=20 After some mulling over the result I previously obtained, I arrived at the following routine for rotating a vector v by a unit quaternion q: float3 RotateVector3ByQuaternion( float3 v, float4 q ) { w =3D q.xyz; float3 vww =3D dot(v,w)*w; float3 res =3D 2.f * (vww + (q.w*q.w - 0.5f) * v + q.w*cross(v,w) ); return res; } That's 1 dot product, 1 cross product, 7 adds, 11 multiplies, compared to 2 cross products, 6 adds, 6 multiplies for Christian's solution. --- Willem H. de Boer Homepage: http://www.whdeboer.com=20 ------------------------------------------------------- SF.Net email is sponsored by: Tell us your software development plans! Take this survey and enter to win a one-year sub to SourceForge.net Plus IDC's 2005 look-ahead and a copy of this survey Click here to start! http://www.idcswdc.com/cgi-bin/survey?id=105hix _______________________________________________ GDAlgorithms-list mailing list GDAlgorithms-list@... https://lists.sourceforge.net/lists/listinfo/gdalgorithms-list Archives: http://sourceforge.net/mailarchive/forum.php?forum_ida88 ```