OpenClonk
C4Random.cpp
Go to the documentation of this file.
1 /*
2  * OpenClonk, http://www.openclonk.org
3  *
4  * Copyright (c) 1998-2000, Matthes Bender
5  * Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de/
6  * Copyright (c) 2009-2016, The OpenClonk Team and contributors
7  *
8  * Distributed under the terms of the ISC license; see accompanying file
9  * "COPYING" for details.
10  *
11  * "Clonk" is a registered trademark of Matthes Bender, used with permission.
12  * See accompanying file "TRADEMARK" for details.
13  *
14  * To redistribute this file separately, substitute the full license texts
15  * for the above references.
16  */
17 
18 /* Network-safe random number generator */
19 
20 #include "C4Include.h"
21 #include "lib/C4Random.h"
22 
23 #include <random>
24 
25 #include <pcg/pcg_random.hpp>
26 
27 int RandomCount = 0;
28 
29 static pcg32 SeededRng()
30 {
31  pcg_extras::seed_seq_from<std::random_device> seed_source;
32  return pcg32(seed_source);
33 }
34 
35 static pcg32 RandomRng, UnsyncedRandomRng = SeededRng();
36 
37 void FixedRandom(uint64_t seed)
38 {
39  RandomRng.seed(seed);
40  RandomCount = 0;
41 }
42 
43 uint32_t Random()
44 {
45  uint32_t result = RandomRng();
46  RecordRandom(UINT32_MAX, result);
47  return result;
48 }
49 
50 uint32_t Random(uint32_t iRange)
51 {
52  if (!iRange) return 0u;
53  uint32_t result = RandomRng(iRange);
54  RecordRandom(iRange, result);
55  return result;
56 }
57 
58 uint32_t UnsyncedRandom()
59 {
60  return UnsyncedRandomRng();
61 }
62 
63 uint32_t UnsyncedRandom(uint32_t iRange)
64 {
65  if (!iRange) return 0u;
66  return UnsyncedRandomRng(iRange);
67 }
68 
69 uint32_t SeededRandom(uint64_t iSeed, uint32_t iRange)
70 {
71  if (!iRange) return 0;
72  pcg32 rng(iSeed);
73  return rng(iRange);
74 }
75 
uint32_t SeededRandom(uint64_t iSeed, uint32_t iRange)
Definition: C4Random.cpp:69
int RandomCount
Definition: C4Random.cpp:27
uint32_t UnsyncedRandom()
Definition: C4Random.cpp:58
void FixedRandom(uint64_t seed)
Definition: C4Random.cpp:37
uint32_t Random()
Definition: C4Random.cpp:43
void RecordRandom(uint32_t range, uint32_t val)