taisei/src/random.c

157 lines
3.4 KiB
C
Raw Normal View History

2012-07-27 19:11:45 +02:00
/*
* This software is licensed under the terms of the MIT-License
* See COPYING for further information.
2012-07-27 19:11:45 +02:00
* ---
* Copyright (c) 2011-2019, Lukas Weber <laochailan@web.de>.
* Copyright (c) 2012-2019, Andrei Alexeyev <akari@alienslab.net>.
2012-07-27 19:11:45 +02:00
*/
#include "taisei.h"
2012-07-27 19:11:45 +02:00
#include <stdio.h>
#include <stdlib.h>
2017-02-06 07:59:39 +01:00
#include <time.h>
#include "global.h"
2012-08-04 03:30:40 +02:00
#include "random.h"
2012-07-27 19:11:45 +02:00
2017-12-04 04:26:27 +01:00
static RandomState *tsrand_current;
2012-07-27 19:11:45 +02:00
/*
* Complementary-multiply-with-carry algorithm
2012-07-27 19:11:45 +02:00
*/
2017-12-04 04:26:27 +01:00
// CMWC engine
uint32_t tsrand_p(RandomState *rnd) {
assert(!rnd->locked);
2017-12-04 04:26:27 +01:00
uint64_t const a = 18782; // as Marsaglia recommends
uint32_t const m = 0xfffffffe; // as Marsaglia recommends
uint64_t t;
uint32_t x;
rnd->i = (rnd->i + 1) & (CMWC_CYCLE - 1);
t = a * rnd->Q[rnd->i] + rnd->c;
// Let c = t / 0xfffffff, x = t mod 0xffffffff
rnd->c = t >> 32;
x = t + rnd->c;
if(x < rnd->c) {
x++;
rnd->c++;
}
2012-07-27 19:11:45 +02:00
2017-12-04 04:26:27 +01:00
return rnd->Q[rnd->i] = m - x;
}
2012-07-27 19:11:45 +02:00
void tsrand_seed_p(RandomState *rnd, uint32_t seed) {
2017-12-04 04:26:27 +01:00
static const uint32_t phi = 0x9e3779b9;
2012-07-27 19:11:45 +02:00
2017-12-04 04:26:27 +01:00
rnd->Q[0] = seed;
rnd->Q[1] = seed + phi;
rnd->Q[2] = seed + phi + phi;
for(int i = 3; i < CMWC_CYCLE; ++i) {
rnd->Q[i] = rnd->Q[i - 3] ^ rnd->Q[i - 2] ^ phi ^ i;
}
rnd->c = 0x8edc04;
rnd->i = CMWC_CYCLE - 1;
for(int i = 0; i < CMWC_CYCLE*16; ++i) {
tsrand_p(rnd);
}
2017-12-04 04:26:27 +01:00
}
2017-12-04 04:26:27 +01:00
void tsrand_switch(RandomState *rnd) {
tsrand_current = rnd;
}
2017-12-04 04:26:27 +01:00
void tsrand_init(RandomState *rnd, uint32_t seed) {
memset(rnd, 0, sizeof(RandomState));
tsrand_seed_p(rnd, seed);
2012-07-27 19:11:45 +02:00
}
2012-08-10 21:27:46 +02:00
void tsrand_seed(uint32_t seed) {
2012-07-27 19:11:45 +02:00
tsrand_seed_p(tsrand_current, seed);
}
uint32_t tsrand(void) {
2012-07-27 19:11:45 +02:00
return tsrand_p(tsrand_current);
}
2017-12-04 04:26:27 +01:00
float frand(void) {
return (float)((double)tsrand()/(double)TSRAND_MAX);
2012-07-27 19:11:45 +02:00
}
2017-12-04 04:26:27 +01:00
float nfrand(void) {
return frand() * 2.0 - 1.0;
}
// we use this to support multiple rands in a single statement without breaking replays across different builds
static uint32_t tsrand_array[TSRAND_ARRAY_LIMIT];
2012-08-04 03:30:40 +02:00
static int tsrand_array_elems;
static uint64_t tsrand_fillflags = 0;
static void tsrand_error(const char *file, const char *func, uint line, const char *fmt, ...) {
char buf[2048] = { 0 };
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
2017-03-13 17:03:51 +01:00
log_fatal("%s(): %s [%s:%u]", func, buf, file, line);
}
Implemented a simple and consistent logging subsystem The goal of this change is mainly to clean up Taisei's codebase and improve its console output. I've been frustrated by files littered with inconsistent printf/fprintf/warnx/errx calls for a long time, and now I actually did something about it. All the above functions are now considered deprecated and result in a compile-time warning when used. Instead, the following macros should be used: log_debug(format, ...) log_info(format, ...) log_warn(format, ...) log_err(format, ...) As you can see, all of them have the same printf-like interface. But they have different functionality and purpose: log_debug is intended for very verbose and specific information. It does nothing in release builds, much like assert(), so don't use expressions with side-effects in its arguments. log_info is for various status updates that are expected during normal operation of the program. log_warn is for non-critical failures or other things that may be worth investigating, but don't inherently render the program non-functional. log_err is for when the only choice is to give up. Like errx, it also terminates the program. Unlike errx, it actually calls abort(), which means the cleanup functions are not ran -- but on the other hand, you get a debuggable backtrace. However, if you're trying to catch programming errors, consider using assert() instead. All of them produce output that contains a timestamp, the log level identifier, the calling function's name, and the formatted message. The newline at the end of the format string is not required -- no, it is actually *prohibited*. The logging system will take care of the line breaks by itself, don't litter the code with that shit. Internally, the logging system is based on the SDL_RWops abstraction, and may have multiple, configurable destinations. This makes it easily extensible. Currently, log_debug and log_info are set to write to stdout, log_warn and log_err to stderr, and all of them also to the file log.txt in the Taisei config directory. Consequently, the nasty freopen hacks we used to make Taisei write to log files on Windows are no longer needed -- which is a very good thing, considering they probably would break if the configdir path contains UTF-8 characters. SDL_RWFromFile does not suffer this limitation. As an added bonus, it's also thread-safe. Note about printf and fprintf: in very few cases, the logging system is not a good substitute for these functions. That is, when you care about writing exactly to stdout/stderr and about exactly how the output looks. However, I insist on keeping the deprecation warnings on them to not tempt anyone to use them for logging/debugging out of habit and/or laziness. For this reason, I've added a tsfprintf function to util.c. It is functionally identical to fprintf, except it returns void. Yes, the name is deliberately ugly. Avoid using it if possible, but if you must, only use it to write to stdout or stderr. Do not write to actual files with it, use SDL_RWops.
2017-03-13 03:51:58 +01:00
#define TSRANDERR(...) tsrand_error(file, __func__, line, __VA_ARGS__)
void __tsrand_fill_p(RandomState *rnd, int amount, const char *file, uint line) {
if(tsrand_fillflags) {
Implemented a simple and consistent logging subsystem The goal of this change is mainly to clean up Taisei's codebase and improve its console output. I've been frustrated by files littered with inconsistent printf/fprintf/warnx/errx calls for a long time, and now I actually did something about it. All the above functions are now considered deprecated and result in a compile-time warning when used. Instead, the following macros should be used: log_debug(format, ...) log_info(format, ...) log_warn(format, ...) log_err(format, ...) As you can see, all of them have the same printf-like interface. But they have different functionality and purpose: log_debug is intended for very verbose and specific information. It does nothing in release builds, much like assert(), so don't use expressions with side-effects in its arguments. log_info is for various status updates that are expected during normal operation of the program. log_warn is for non-critical failures or other things that may be worth investigating, but don't inherently render the program non-functional. log_err is for when the only choice is to give up. Like errx, it also terminates the program. Unlike errx, it actually calls abort(), which means the cleanup functions are not ran -- but on the other hand, you get a debuggable backtrace. However, if you're trying to catch programming errors, consider using assert() instead. All of them produce output that contains a timestamp, the log level identifier, the calling function's name, and the formatted message. The newline at the end of the format string is not required -- no, it is actually *prohibited*. The logging system will take care of the line breaks by itself, don't litter the code with that shit. Internally, the logging system is based on the SDL_RWops abstraction, and may have multiple, configurable destinations. This makes it easily extensible. Currently, log_debug and log_info are set to write to stdout, log_warn and log_err to stderr, and all of them also to the file log.txt in the Taisei config directory. Consequently, the nasty freopen hacks we used to make Taisei write to log files on Windows are no longer needed -- which is a very good thing, considering they probably would break if the configdir path contains UTF-8 characters. SDL_RWFromFile does not suffer this limitation. As an added bonus, it's also thread-safe. Note about printf and fprintf: in very few cases, the logging system is not a good substitute for these functions. That is, when you care about writing exactly to stdout/stderr and about exactly how the output looks. However, I insist on keeping the deprecation warnings on them to not tempt anyone to use them for logging/debugging out of habit and/or laziness. For this reason, I've added a tsfprintf function to util.c. It is functionally identical to fprintf, except it returns void. Yes, the name is deliberately ugly. Avoid using it if possible, but if you must, only use it to write to stdout or stderr. Do not write to actual files with it, use SDL_RWops.
2017-03-13 03:51:58 +01:00
TSRANDERR("Some indices left unused from the previous call");
return;
}
2012-08-04 03:30:40 +02:00
tsrand_array_elems = amount;
tsrand_fillflags = (1L << amount) - 1;
for(int i = 0; i < amount; ++i) {
tsrand_array[i] = tsrand_p(rnd);
}
}
void __tsrand_fill(int amount, const char *file, uint line) {
__tsrand_fill_p(tsrand_current, amount, file, line);
}
uint32_t __tsrand_a(int idx, const char *file, uint line) {
if(idx >= tsrand_array_elems || idx < 0) {
Implemented a simple and consistent logging subsystem The goal of this change is mainly to clean up Taisei's codebase and improve its console output. I've been frustrated by files littered with inconsistent printf/fprintf/warnx/errx calls for a long time, and now I actually did something about it. All the above functions are now considered deprecated and result in a compile-time warning when used. Instead, the following macros should be used: log_debug(format, ...) log_info(format, ...) log_warn(format, ...) log_err(format, ...) As you can see, all of them have the same printf-like interface. But they have different functionality and purpose: log_debug is intended for very verbose and specific information. It does nothing in release builds, much like assert(), so don't use expressions with side-effects in its arguments. log_info is for various status updates that are expected during normal operation of the program. log_warn is for non-critical failures or other things that may be worth investigating, but don't inherently render the program non-functional. log_err is for when the only choice is to give up. Like errx, it also terminates the program. Unlike errx, it actually calls abort(), which means the cleanup functions are not ran -- but on the other hand, you get a debuggable backtrace. However, if you're trying to catch programming errors, consider using assert() instead. All of them produce output that contains a timestamp, the log level identifier, the calling function's name, and the formatted message. The newline at the end of the format string is not required -- no, it is actually *prohibited*. The logging system will take care of the line breaks by itself, don't litter the code with that shit. Internally, the logging system is based on the SDL_RWops abstraction, and may have multiple, configurable destinations. This makes it easily extensible. Currently, log_debug and log_info are set to write to stdout, log_warn and log_err to stderr, and all of them also to the file log.txt in the Taisei config directory. Consequently, the nasty freopen hacks we used to make Taisei write to log files on Windows are no longer needed -- which is a very good thing, considering they probably would break if the configdir path contains UTF-8 characters. SDL_RWFromFile does not suffer this limitation. As an added bonus, it's also thread-safe. Note about printf and fprintf: in very few cases, the logging system is not a good substitute for these functions. That is, when you care about writing exactly to stdout/stderr and about exactly how the output looks. However, I insist on keeping the deprecation warnings on them to not tempt anyone to use them for logging/debugging out of habit and/or laziness. For this reason, I've added a tsfprintf function to util.c. It is functionally identical to fprintf, except it returns void. Yes, the name is deliberately ugly. Avoid using it if possible, but if you must, only use it to write to stdout or stderr. Do not write to actual files with it, use SDL_RWops.
2017-03-13 03:51:58 +01:00
TSRANDERR("Index out of range (%i / %i)", idx, tsrand_array_elems);
return 0;
}
if(tsrand_fillflags & (1L << idx)) {
tsrand_fillflags &= ~(1L << idx);
return tsrand_array[idx];
}
Implemented a simple and consistent logging subsystem The goal of this change is mainly to clean up Taisei's codebase and improve its console output. I've been frustrated by files littered with inconsistent printf/fprintf/warnx/errx calls for a long time, and now I actually did something about it. All the above functions are now considered deprecated and result in a compile-time warning when used. Instead, the following macros should be used: log_debug(format, ...) log_info(format, ...) log_warn(format, ...) log_err(format, ...) As you can see, all of them have the same printf-like interface. But they have different functionality and purpose: log_debug is intended for very verbose and specific information. It does nothing in release builds, much like assert(), so don't use expressions with side-effects in its arguments. log_info is for various status updates that are expected during normal operation of the program. log_warn is for non-critical failures or other things that may be worth investigating, but don't inherently render the program non-functional. log_err is for when the only choice is to give up. Like errx, it also terminates the program. Unlike errx, it actually calls abort(), which means the cleanup functions are not ran -- but on the other hand, you get a debuggable backtrace. However, if you're trying to catch programming errors, consider using assert() instead. All of them produce output that contains a timestamp, the log level identifier, the calling function's name, and the formatted message. The newline at the end of the format string is not required -- no, it is actually *prohibited*. The logging system will take care of the line breaks by itself, don't litter the code with that shit. Internally, the logging system is based on the SDL_RWops abstraction, and may have multiple, configurable destinations. This makes it easily extensible. Currently, log_debug and log_info are set to write to stdout, log_warn and log_err to stderr, and all of them also to the file log.txt in the Taisei config directory. Consequently, the nasty freopen hacks we used to make Taisei write to log files on Windows are no longer needed -- which is a very good thing, considering they probably would break if the configdir path contains UTF-8 characters. SDL_RWFromFile does not suffer this limitation. As an added bonus, it's also thread-safe. Note about printf and fprintf: in very few cases, the logging system is not a good substitute for these functions. That is, when you care about writing exactly to stdout/stderr and about exactly how the output looks. However, I insist on keeping the deprecation warnings on them to not tempt anyone to use them for logging/debugging out of habit and/or laziness. For this reason, I've added a tsfprintf function to util.c. It is functionally identical to fprintf, except it returns void. Yes, the name is deliberately ugly. Avoid using it if possible, but if you must, only use it to write to stdout or stderr. Do not write to actual files with it, use SDL_RWops.
2017-03-13 03:51:58 +01:00
TSRANDERR("Index %i used multiple times", idx);
return 0;
}
float __afrand(int idx, const char *file, uint line) {
2017-12-04 04:26:27 +01:00
return (float)((double)__tsrand_a(idx, file, line) / (double)TSRAND_MAX);
}
2012-08-04 02:56:51 +02:00
float __anfrand(int idx, const char *file, uint line) {
return __afrand(idx, file, line) * 2 - 1;
2012-08-04 02:56:51 +02:00
}
void tsrand_lock(RandomState *rnd) {
rnd->locked = true;
}
void tsrand_unlock(RandomState *rnd) {
rnd->locked = false;
}