Tekkotsu Homepage
Demos
Overview
Downloads
Dev. Resources
Reference
Credits

mathutils.h

Go to the documentation of this file.
00001 //-*-c++-*-
00002 #ifndef __mathutils_h__
00003 #define __mathutils_h__
00004 
00005 #include <math.h>
00006 
00007 //! a variety of handy mathematical functions, many of which are templated
00008 namespace mathutils {
00009   //! euclidean distance of two points (squared), see distance()
00010   template <class num>
00011   inline num squareDistance(num x1, num ya, num x2, num yb) {
00012     return (x1-x2)*(x1-x2)+(ya-yb)*(ya-yb);
00013   }
00014   
00015   //! euclidean distance of two points, see squareDistance()
00016   template <class num>
00017   inline num distance(num x1, num ya, num x2, num yb) {
00018     return sqrt(squareDistance(x1, ya, x2, yb));
00019   }
00020   
00021   //! Clips @a n to a minimum of @a low or maximum of @a high.
00022   /*! If @a low and @a high are inverted, high is returned. */
00023   template <class num>
00024   inline num limitRange(num n, num low, num high) {
00025     if (n<low) n=low;
00026     if (n>high) n=high;
00027     return n;
00028   }
00029   
00030   //! returns n*n;
00031   template <class num>
00032   inline num squared(num n) {
00033     return n*n;
00034   }
00035   
00036   //! returns the maximum of n or -n
00037   template <class num>
00038   inline num abs_t(num n) {
00039     return (n>-n)?n:-n;
00040   }
00041   
00042   //! Returns the log base 2 of a number
00043   /*! This template implementation does a bit shifting method appropriate for
00044    *  integers.  Specializations are provided for float and double to use the 'real' log() */
00045   template <class num>
00046   inline num log2t(num x) {
00047     num ans=0;
00048     for(unsigned int mag=sizeof(num)*4; mag>0; mag/=2) {
00049       num y=x>>mag;
00050       if(y>0) {
00051         x=y;
00052         ans+=mag;
00053       }
00054     }
00055     return ans;
00056   }
00057   //! returns the log base 2 for a 'float' value
00058   template <>
00059   inline float log2t(float x) {
00060     return log(x)/M_LN2;
00061   }
00062   //! returns the log base 2 for a 'double' value
00063   template <>
00064   inline double log2t(double x) {
00065     return log(x)/M_LN2;
00066   }
00067   
00068   //! converts from degrees to radians
00069   template <class num>
00070   inline num deg2rad(num x) {
00071     return x*M_PI/180;
00072   }
00073   
00074   //! converts from radians to degrees
00075   template <class num>
00076   inline num rad2deg(num x) {
00077     return x*180/M_PI;
00078   }
00079   
00080 }
00081 
00082 #endif

Tekkotsu v4.0
Generated Thu Nov 22 00:54:53 2007 by Doxygen 1.5.4