--- deliantra/server/include/util.h 2007/01/18 19:32:37 1.32 +++ deliantra/server/include/util.h 2007/01/19 22:47:57 1.35 @@ -37,9 +37,11 @@ void fork_abort (const char *msg); -template static inline T min (T a, U b) { return a < (T)b ? a : (T)b; } -template static inline T max (T a, U b) { return a > (T)b ? a : (T)b; } -template static inline T clamp (T v, U a, V b) { return v < (T)a ? a : v >(T)b ? b : v; } +// rationale for using (U) not (T) is to reduce signed/unsigned issues, +// as a is often a constant while b is the variable. it is still a bug, though. +template static inline T min (T a, U b) { return (U)a < b ? (U)a : b; } +template static inline T max (T a, U b) { return (U)a > b ? (U)a : b; } +template static inline T clamp (T v, U a, V b) { return v < (T)a ? (T)a : v >(T)b ? (T)b : v; } template static inline void swap (T& a, U& b) { T t=a; a=(T)b; b=(U)t; } @@ -196,26 +198,44 @@ // http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps struct tausworthe_random_generator { + // generator uint32_t state [4]; - tausworthe_random_generator (uint32_t seed); + void operator =(const tausworthe_random_generator &src) + { + state [0] = src.state [0]; + state [1] = src.state [1]; + state [2] = src.state [2]; + state [3] = src.state [3]; + } + + void seed (uint32_t seed); uint32_t next (); + // uniform distribution uint32_t operator ()(uint32_t r_max) { - return next () % r_max; + return is_constant (r_max) + ? this->next () % r_max + : get_range (r_max); } // return a number within (min .. max) int operator () (int r_min, int r_max) { - return r_min + next () % max (r_max - r_min + 1, 1); + return is_constant (r_min) && is_constant (r_max) + ? r_min + (*this) (max (r_max - r_min + 1, 1)) + : get_range (r_min, r_max); } double operator ()() { - return next () / (double)0xFFFFFFFFU; + return this->next () / (double)0xFFFFFFFFU; } + +protected: + uint32_t get_range (uint32_t r_max); + int get_range (int r_min, int r_max); }; typedef tausworthe_random_generator rand_gen;