1 /* ScummVM - Graphic Adventure Engine
2 *
3 * ScummVM is the legal property of its developers, whose names
4 * are too numerous to list here. Please refer to the COPYRIGHT
5 * file distributed with this source distribution.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 *
21 */
22
23 #include <limits.h>
24
25 #include "common/random.h"
26 #include "common/system.h"
27 #include "gui/EventRecorder.h"
28
29
30 namespace Common {
31
RandomSource(const String & name)32 RandomSource::RandomSource(const String &name) {
33 // Use system time as RNG seed. Normally not a good idea, if you are using
34 // a RNG for security purposes, but good enough for our purposes.
35 assert(g_system);
36
37 #ifdef ENABLE_EVENTRECORDER
38 setSeed(g_eventRec.getRandomSeed(name));
39 #else
40 TimeDate time;
41 g_system->getTimeAndDate(time);
42 uint32 newSeed = time.tm_sec + time.tm_min * 60 + time.tm_hour * 3600;
43 newSeed += time.tm_mday * 86400 + time.tm_mon * 86400 * 31;
44 newSeed += time.tm_year * 86400 * 366;
45 newSeed = newSeed * 1000 + g_system->getMillis();
46 setSeed(newSeed);
47 #endif
48 }
49
setSeed(uint32 seed)50 void RandomSource::setSeed(uint32 seed) {
51 _randSeed = seed;
52 }
53
getRandomNumber(uint max)54 uint RandomSource::getRandomNumber(uint max) {
55 _randSeed = 0xDEADBF03 * (_randSeed + 1);
56 _randSeed = (_randSeed >> 13) | (_randSeed << 19);
57
58 if (max == UINT_MAX)
59 return _randSeed;
60 return _randSeed % (max + 1);
61 }
62
getRandomBit()63 uint RandomSource::getRandomBit() {
64 _randSeed = 0xDEADBF03 * (_randSeed + 1);
65 _randSeed = (_randSeed >> 13) | (_randSeed << 19);
66 return _randSeed & 1;
67 }
68
getRandomNumberRng(uint min,uint max)69 uint RandomSource::getRandomNumberRng(uint min, uint max) {
70 return getRandomNumber(max - min) + min;
71 }
72
getRandomNumberRngSigned(int min,int max)73 int RandomSource::getRandomNumberRngSigned(int min, int max) {
74 return getRandomNumber(max - min) + min;
75 }
76
77 } // End of namespace Common
78