1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
7 // https://www.artsoft.org/
8 // ----------------------------------------------------------------------------
10 // ============================================================================
16 * Copyright (c) 1983 Regents of the University of California.
17 * All rights reserved.
19 * Redistribution and use in source and binary forms are permitted
20 * provided that the above copyright notice and this paragraph are
21 * duplicated in all such forms and that any documentation,
22 * advertising materials, and other materials related to such
23 * distribution and use acknowledge that the software was developed
24 * by the University of California, Berkeley. The name of the
25 * University may not be used to endorse or promote products derived
26 * from this software without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
28 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
29 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
33 * This is derived from the Berkeley source:
34 * @(#)random.c 5.5 (Berkeley) 7/6/88
35 * It was reworked for the GNU C Library by Roland McGrath.
43 /* An improved random number generation package. In addition to the standard
44 rand()/srand() like interface, this package also has a special state info
45 interface. The initstate() routine is called with a seed, an array of
46 bytes, and a count of how many bytes are being passed in; this array is
47 then initialized to contain information for random number generation with
48 that much state information. Good sizes for the amount of state
49 information are 32, 64, 128, and 256 bytes. The state can be switched by
50 calling the setstate() function with the same array as was initiallized
51 with initstate(). By default, the package runs with 128 bytes of state
52 information and generates far better random numbers than a linear
53 congruential generator. If the amount of state information is less than
54 32 bytes, a simple linear congruential R.N.G. is used. Internally, the
55 state information is treated as an array of longs; the zeroeth element of
56 the array is the type of R.N.G. being used (small integer); the remainder
57 of the array is the state information for the R.N.G. Thus, 32 bytes of
58 state information will give 7 longs worth of state information, which will
59 allow a degree seven polynomial. (Note: The zeroeth word of state
60 information also has some other information stored in it; see setstate
61 for details). The random number generation technique is a linear feedback
62 shift register approach, employing trinomials (since there are fewer terms
63 to sum up that way). In this approach, the least significant bit of all
64 the numbers in the state table will act as a linear feedback shift register,
65 and will have period 2^deg - 1 (where deg is the degree of the polynomial
66 being used, assuming that the polynomial is irreducible and primitive).
67 The higher order bits will have longer periods, since their values are
68 also influenced by pseudo-random carries out of the lower bits. The
69 total period of the generator is approximately deg*(2**deg - 1); thus
70 doubling the amount of state information has a vast influence on the
71 period of the generator. Note: The deg*(2**deg - 1) is an approximation
72 only good for large deg, when the period of the shift register is the
73 dominant factor. With deg equal to seven, the period is actually much
74 longer than the 7*(2**7 - 1) predicted by this formula. */
78 /* For each of the currently supported random number generators, we have a
79 break value on the amount of state information (you need at least thi
80 bytes of state info to support this random number generator), a degree for
81 the polynomial (actually a trinomial) that the R.N.G. is based on, and
82 separation between the two lower order coefficients of the trinomial. */
84 /* Linear congruential. */
90 /* x**7 + x**3 + 1. */
102 /* x**31 + x**3 + 1. */
115 /* Array versions of the above information to make code run faster.
116 Relies on fact that TYPE_i == i. */
118 #define MAX_TYPES 5 /* Max number of types above. */
122 /* Initially, everything is set up as if from:
123 initstate(1, randtbl, 128);
124 Note that this initialization takes advantage of the fact that srandom
125 advances the front and rear pointers 10*rand_deg times, and hence the
126 rear pointer which starts at 0 will also end up at zero; thus the zeroeth
127 element of the state information, which contains info about the current
128 position of the rear pointer is just
129 (MAX_TYPES * (rptr - state)) + TYPE_3 == TYPE_3. */
131 static int randtbl_0[DEG_3 + 1] =
134 -851904987, -43806228, -2029755270, 1390239686, -1912102820,
135 -485608943, 1969813258, -1590463333, -1944053249, 455935928, 508023712,
136 -1714531963, 1800685987, -2015299881, 654595283, -1149023258,
137 -1470005550, -1143256056, -1325577603, -1568001885, 1275120390,
138 -607508183, -205999574, -1696891592, 1492211999, -1528267240,
139 -952028296, -189082757, 362343714, 1424981831, 2039449641,
141 static int randtbl_1[DEG_3 + 1] =
144 -851904987, -43806228, -2029755270, 1390239686, -1912102820,
145 -485608943, 1969813258, -1590463333, -1944053249, 455935928, 508023712,
146 -1714531963, 1800685987, -2015299881, 654595283, -1149023258,
147 -1470005550, -1143256056, -1325577603, -1568001885, 1275120390,
148 -607508183, -205999574, -1696891592, 1492211999, -1528267240,
149 -952028296, -189082757, 362343714, 1424981831, 2039449641,
153 /* FPTR and RPTR are two pointers into the state info, a front and a rear
154 pointer. These two pointers are always rand_sep places aparts, as they
155 cycle through the state information. (Yes, this does mean we could get
156 away with just one pointer, but the code for random is more efficient
157 this way). The pointers are left positioned as they would be from the call:
158 initstate(1, randtbl, 128);
159 (The position of the rear pointer, rptr, is really 0 (as explained above
160 in the initialization of randtbl) because the state table pointer is set
161 to point to randtbl[1] (as explained below).) */
163 static int *fptr[2] = { &randtbl_0[SEP_3 + 1], &randtbl_1[SEP_3 + 1] };
164 static int *rptr[2] = { &randtbl_0[1], &randtbl_1[1] };
168 /* The following things are the pointer to the state information table,
169 the type of the current generator, the degree of the current polynomial
170 being used, and the separation between the two pointers.
171 Note that for efficiency of random, we remember the first location of
172 the state information, not the zeroeth. Hence it is valid to access
173 state[-1], which is used to store the type of the R.N.G.
174 Also, we remember the last location, since this is more efficient than
175 indexing every time to find the address of the last element to see if
176 the front and rear pointers have wrapped. */
178 static int *state[2] = { &randtbl_0[1], &randtbl_1[1] };
180 static int rand_type[2] = { TYPE_3, TYPE_3 };
181 static int rand_deg[2] = { DEG_3, DEG_3 };
182 static int rand_sep[2] = { SEP_3, SEP_3 };
184 static int *end_ptr[2] =
186 &randtbl_0[sizeof(randtbl_0) / sizeof(randtbl_0[0])],
187 &randtbl_1[sizeof(randtbl_1) / sizeof(randtbl_1[0])]
190 /* Initialize the random number generator based on the given seed. If the
191 type is the trivial no-state-information type, just remember the seed.
192 Otherwise, initializes state[] based on the given "seed" via a linear
193 congruential generator. Then, the pointers are set to known locations
194 that are exactly rand_sep places apart. Lastly, it cycles the state
195 information a given number of times to get rid of any initial dependencies
196 introduced by the L.C.R.N.G. Note that the initialization of randtbl[]
197 for default usage relies on values produced by this routine. */
199 void srandom_linux_libc(int nr, unsigned int x)
203 if (rand_type[nr] != TYPE_0)
207 for (i = 1; i < rand_deg[nr]; ++i)
208 state[nr][i] = (1103515145 * state[nr][i - 1]) + 12345;
210 fptr[nr] = &state[nr][rand_sep[nr]];
211 rptr[nr] = &state[nr][0];
213 for (i = 0; i < 10 * rand_deg[nr]; ++i)
214 random_linux_libc(nr);
218 /* If we are using the trivial TYPE_0 R.N.G., just do the old linear
219 congruential bit. Otherwise, we do our fancy trinomial stuff, which is the
220 same in all ther other cases due to all the global variables that have been
221 set up. The basic operation is to add the number at the rear pointer into
222 the one at the front pointer. Then both pointers are advanced to the next
223 location cyclically in the table. The value returned is the sum generated,
224 reduced to 31 bits by throwing away the "least random" low bit.
225 Note: The code takes advantage of the fact that both the front and
226 rear pointers can't wrap on the same call by not testing the rear
227 pointer if the front one has wrapped. Returns a 31-bit random number. */
229 int random_linux_libc(int nr)
231 if (rand_type[nr] == TYPE_0)
233 state[nr][0] = ((state[nr][0] * 1103515245) + 12345) & INT_MAX;
240 *fptr[nr] += *rptr[nr];
242 /* Chucking least random bit. */
243 i = (*fptr[nr] >> 1) & INT_MAX;
246 if (fptr[nr] >= end_ptr[nr])
248 fptr[nr] = state[nr];
254 if (rptr[nr] >= end_ptr[nr])
255 rptr[nr] = state[nr];
263 // ============================================================================
266 * prng.c - Portable, ISO C90 and C99 compliant high-quality
267 * pseudo-random number generator based on the alleged RC4
268 * cipher. This PRNG should be suitable for most general-purpose
269 * uses. Not recommended for cryptographic or financial
270 * purposes. Not thread-safe.
274 * Copyright (c) 2004 Ben Pfaff <blp@cs.stanford.edu>.
275 * All rights reserved.
277 * Redistribution and use in source and binary forms, with or
278 * without modification, are permitted provided that the
279 * following conditions are met:
281 * 1. Redistributions of source code must retain the above
282 * copyright notice, this list of conditions and the following
285 * 2. Redistributions in binary form must reproduce the above
286 * copyright notice, this list of conditions and the following
287 * disclaimer in the documentation and/or other materials
288 * provided with the distribution.
290 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS
291 * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
292 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
293 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
294 * SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
295 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
296 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
297 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
298 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
299 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
300 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
301 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
312 /* RC4-based pseudo-random state. */
313 static unsigned char s[256];
316 /* Nonzero if PRNG has been seeded. */
319 /* Swap bytes that A and B point to. */
320 #define SWAP_BYTE(A, B) \
322 unsigned char swap_temp = *(A); \
327 /* Seeds the pseudo-random number generator based on the current
330 If the user calls neither this function nor prng_seed_bytes()
331 before any prng_get*() function, this function is called
332 automatically to obtain a time-based seed. */
334 prng_seed_time (void)
342 prng_seed_bytes (&t, sizeof t);
345 /* Retrieves one octet from the array BYTES, which is N_BYTES in
346 size, starting at an offset of OCTET_IDX octets. BYTES is
347 treated as a circular array, so that accesses past the first
348 N_BYTES bytes wrap around to the beginning. */
350 get_octet (const void *bytes_, size_t n_bytes, size_t octet_idx)
352 const unsigned char *bytes = bytes_;
354 return bytes[octet_idx % n_bytes];
357 size_t first_byte = octet_idx * 8 / CHAR_BIT % n_bytes;
358 size_t start_bit = octet_idx * 8 % CHAR_BIT;
359 unsigned char c = (bytes[first_byte] >> start_bit) & 255;
361 size_t bits_filled = CHAR_BIT - start_bit;
362 if (CHAR_BIT % 8 != 0 && bits_filled < 8)
364 size_t bits_left = 8 - bits_filled;
365 unsigned char bits_left_mask = (1u << bits_left) - 1;
366 size_t second_byte = first_byte + 1 < n_bytes ? first_byte + 1 : 0;
368 c |= (bytes[second_byte] & bits_left_mask) << bits_filled;
375 /* Seeds the pseudo-random number based on the SIZE bytes in
376 KEY. At most the first 2048 bits in KEY are used. */
378 prng_seed_bytes (const void *key, size_t size)
382 assert (key != NULL && size > 0);
384 for (i = 0; i < 256; i++)
386 for (i = j = 0; i < 256; i++)
388 j = (j + s[i] + get_octet (key, size, i)) & 255;
389 SWAP_BYTE (s + i, s + j);
396 /* Returns a pseudo-random integer in the range [0, 255]. */
398 prng_get_octet (void)
403 s_i = (s_i + 1) & 255;
404 s_j = (s_j + s[s_i]) & 255;
405 SWAP_BYTE (s + s_i, s + s_j);
407 return s[(s[s_i] + s[s_j]) & 255];
410 /* Returns a pseudo-random integer in the range [0, UCHAR_MAX]. */
417 byte = prng_get_octet ();
418 for (bits = 8; bits < CHAR_BIT; bits += 8)
419 byte = (byte << 8) | prng_get_octet ();
423 /* Fills BUF with SIZE pseudo-random bytes. */
425 prng_get_bytes (void *buf_, size_t size)
429 for (buf = buf_; size-- > 0; buf++)
430 *buf = prng_get_byte ();
433 /* Returns a pseudo-random unsigned long in the range [0,
436 prng_get_ulong (void)
441 ulng = prng_get_octet ();
442 for (bits = 8; bits < CHAR_BIT * sizeof ulng; bits += 8)
443 ulng = (ulng << 8) | prng_get_octet ();
447 /* Returns a pseudo-random long in the range [0, LONG_MAX]. */
451 return prng_get_ulong () & LONG_MAX;
454 /* Returns a pseudo-random unsigned int in the range [0,
462 uint = prng_get_octet ();
463 for (bits = 8; bits < CHAR_BIT * sizeof uint; bits += 8)
464 uint = (uint << 8) | prng_get_octet ();
468 /* Returns a pseudo-random int in the range [0, INT_MAX]. */
472 return prng_get_uint () & INT_MAX;
475 /* Returns a pseudo-random floating-point number from the uniform
476 distribution with range [0,1). */
478 prng_get_double (void)
482 double dbl = prng_get_ulong () / (ULONG_MAX + 1.0);
483 if (dbl >= 0.0 && dbl < 1.0)
488 /* Returns a pseudo-random floating-point number from the
489 distribution with mean 0 and standard deviation 1. (Multiply
490 the result by the desired standard deviation, then add the
493 prng_get_double_normal (void)
495 /* Knuth, _The Art of Computer Programming_, Vol. 2, 3.4.1C,
497 static int has_next = 0;
498 static double next_normal;
503 this_normal = next_normal;
512 limit = log (DBL_MAX / 2) / (DBL_MAX / 2);
516 double u1 = prng_get_double ();
517 double u2 = prng_get_double ();
520 s = v1 * v1 + v2 * v2;
521 if (s > limit && s < 1)
525 this_normal = v1 * sqrt (-2. * log (s) / s);
526 next_normal = v2 * sqrt (-2. * log (s) / s);