base_random.hh

Go to the documentation of this file.
00001 /*
00008  * LEGAL:   COPYRIGHT (C) 2004 JIM E. BROOKS
00009  *          THIS SOURCE CODE IS RELEASED UNDER THE TERMS
00010  *          OF THE GNU GENERAL PUBLIC LICENSE VERSION 2 (GPL 2).
00011  ******************************************************************************/
00012 
00013 #ifndef BASE_RANDOM_HH
00014 #define BASE_RANDOM_HH 1
00015 
00016 #include "base_common.hh"
00017 #include "base_thread.hh"
00018 #include "base_thread_per.hh"
00019 
00020 namespace base {
00021 
00022 #define gRandom base::global.mRandom
00023 
00024 const fp RAND_MAX_RECIP = 1.0 / fp(RAND_MAX);  // a constant (without division instruction)
00025 
00031 class Random : public Threadable
00032 {
00033 public:
00034             Random( void );
00035             ~Random();
00036     void    Init( void );
00037     void    randomize( uint seed );
00038     void    randomize( void );
00039     uint    random_ui( void );
00040     uint    random_ui( uint range );
00041     fp      random_f( void );
00042     fp      random_f( fp range );
00043     uint    random_ui_true( void );
00044     uint    GetSeed( void ) { return mSavedSeed; }
00045 
00046     // Fast methods which use a precomputed table but will repeat.
00047     uint fast_random_ui( void )
00048     {
00049         // Table has padding in case multiple threads trample at the end.
00050         uint r = mFastTable[mFastTableIdx];
00051         mFastTableIdx = (mFastTableIdx + 1) & FAST_TABLE_IDX_MASK;  // faster than %
00052         return r;
00053     }
00054 
00055     uint fast_random_ui( uint range )
00056     {
00057         return fast_random_ui() % range;
00058     }
00059 
00060     fp fast_random_f( void )
00061     {
00062         return fp(fast_random_ui()) * RAND_MAX_RECIP;
00063     }
00064 
00065     fp fast_random_f( fp range )
00066     {
00067         return fp(fast_random_ui()) * RAND_MAX_RECIP * range;
00068     }
00069 
00070 private:
00071     CLASS_CONST uint    FAST_TABLE_CNT      = 1024;  // small table is faster (4K : 1 page)
00072     CLASS_CONST uint    FAST_TABLE_IDX_MASK = 1023;  // table size must be power-of-2 for mask to be right
00073     PerThreadPtr<uint0> mSeed;  // rand_r() will change
00074     uint                mSavedSeed;
00075     uint                mFastTable[FAST_TABLE_CNT + 100];
00076     uint                mFastTableIdx;
00077 };
00078 
00079 } // namespace base
00080 
00081 #endif // BASE_RANDOM_HH
Palomino 3D Engine documents generated by doxygen 1.5.3 on Fri Nov 23 11:26:06 2007