# random_func.hpp

Go to the documentation of this file.

    00001 /* $Id: random_func.hpp 12156 2008-02-16 00:46:38Z smatz $ */
    00002
    00005 #ifndef RANDOM_FUNC_HPP
    00006 #define RANDOM_FUNC_HPP
    00007
    00008 #if defined(__APPLE__)
    00009   /* Apple already has Random declared */
    00010   #define Random OTTD_Random
    00011 #endif /* __APPLE__ */
    00012
    00013 /**************
    00014  * Warning: DO NOT enable this unless you understand what it does
    00015  *
    00016  * If enabled, in a network game all randoms will be dumped to the
    00017  *  stdout if the first client joins (or if you are a client). This
    00018  *  is to help finding desync problems.
    00019  *
    00020  * Warning: DO NOT enable this unless you understand what it does
    00021  **************/
    00022
    00023 //#define RANDOM_DEBUG
    00024
    00025
    00026 // Enable this to produce higher quality random numbers.
    00027 // Doesn't work with network yet.
    00028 // #define MERSENNE_TWISTER
    00029
    00033 struct Randomizer {
    00035   uint32 state[2];
    00036
    00041   uint32 Next();
    00042
    00048   uint32 Next(uint16 max);
    00049
    00054   void SetSeed(uint32 seed);
    00055 };
    00056 extern Randomizer _random;
    00057 extern Randomizer _interactive_random;
    00058
    00059 void SetRandomSeed(uint32 seed);
    00060 #ifdef RANDOM_DEBUG
    00061   #define Random() DoRandom(__LINE__, __FILE__)
    00062   uint32 DoRandom(int line, const char *file);
    00063   #define RandomRange(max) DoRandomRange(max, __LINE__, __FILE__)
    00064   uint DoRandomRange(uint max, int line, const char *file);
    00065 #else
    00066   static inline uint32 Random() { return _random.Next(); }
    00067   static inline uint32 RandomRange(uint16 max) { return _random.Next(max); }
    00068 #endif
    00069
    00070 static inline uint32 InteractiveRandom() { return _interactive_random.Next(); }
    00071 static inline uint32 InteractiveRandomRange(uint16 max) { return _interactive_random.Next(max); }
    00072
    00088 static inline bool Chance16I(const uint a, const uint b, const uint32 r)
    00089 {
    00090   assert(b != 0);
    00091   return (uint16)r < (uint16)(((a << 16) + b / 2) / b);
    00092 }
    00093
    00106 static inline bool Chance16(const uint a, const uint b)
    00107 {
    00108   return Chance16I(a, b, Random());
    00109 }
    00110
    00126 static inline bool Chance16R(const uint a, const uint b, uint32 &r)
    00127 {
    00128   r = Random();
    00129   return Chance16I(a, b, r);
    00130 }
    00131
    00132 #endif /* RANDOM_FUNC_HPP */