random_func.hpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #ifndef RANDOM_FUNC_HPP
00013 #define RANDOM_FUNC_HPP
00014
00015 #if defined(__APPLE__)
00016
00017 #define Random OTTD_Random
00018 #endif
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00036 struct Randomizer {
00038 uint32 state[2];
00039
00044 uint32 Next();
00045
00051 uint32 Next(uint16 max);
00052
00057 void SetSeed(uint32 seed);
00058 };
00059 extern Randomizer _random;
00060 extern Randomizer _interactive_random;
00061
00063 struct SavedRandomSeeds {
00064 Randomizer random;
00065 Randomizer interactive_random;
00066 };
00067
00071 static inline void SaveRandomSeeds(SavedRandomSeeds *storage)
00072 {
00073 storage->random = _random;
00074 storage->interactive_random = _interactive_random;
00075 }
00076
00080 static inline void RestoreRandomSeeds(const SavedRandomSeeds &storage)
00081 {
00082 _random = storage.random;
00083 _interactive_random = storage.interactive_random;
00084 }
00085
00086 void SetRandomSeed(uint32 seed);
00087 #ifdef RANDOM_DEBUG
00088 #define Random() DoRandom(__LINE__, __FILE__)
00089 uint32 DoRandom(int line, const char *file);
00090 #define RandomRange(max) DoRandomRange(max, __LINE__, __FILE__)
00091 uint DoRandomRange(uint max, int line, const char *file);
00092 #else
00093 static FORCEINLINE uint32 Random()
00094 {
00095 return _random.Next();
00096 }
00097
00098 static FORCEINLINE uint32 RandomRange(uint16 max)
00099 {
00100 return _random.Next(max);
00101 }
00102 #endif
00103
00104 static FORCEINLINE uint32 InteractiveRandom()
00105 {
00106 return _interactive_random.Next();
00107 }
00108
00109 static FORCEINLINE uint32 InteractiveRandomRange(uint16 max)
00110 {
00111 return _interactive_random.Next(max);
00112 }
00113
00129 static FORCEINLINE bool Chance16I(const uint a, const uint b, const uint32 r)
00130 {
00131 assert(b != 0);
00132 return (((uint16)r * b + b / 2) >> 16) < a;
00133 }
00134
00145 #ifdef RANDOM_DEBUG
00146 #define Chance16(a, b) Chance16I(a, b, DoRandom(__LINE__, __FILE__))
00147 #else
00148 static FORCEINLINE bool Chance16(const uint a, const uint b)
00149 {
00150 return Chance16I(a, b, Random());
00151 }
00152 #endif
00153
00169 #ifdef RANDOM_DEBUG
00170 #define Chance16R(a, b, r) (r = DoRandom(__LINE__, __FILE__), Chance16I(a, b, r))
00171 #else
00172 static FORCEINLINE bool Chance16R(const uint a, const uint b, uint32 &r)
00173 {
00174 r = Random();
00175 return Chance16I(a, b, r);
00176 }
00177 #endif
00178
00179 #endif