// This file is a part of Framsticks SDK. http://www.framsticks.com/ // Copyright (C) 1999-2024 Maciej Komosinski and Szymon Ulatowski. // See LICENSE.txt for details. #include "nonstd_math.h" #include #include // strncpy() #include #include // std::min() #include unsigned int rndUint(int limit_exclusive) { if (limit_exclusive < 0) { logPrintf("", "rndUint", LOG_ERROR, "rndUint(negative: %d)", limit_exclusive); return 0; } else return rndUint((unsigned int)limit_exclusive); } RandomGenerator &rndGetInstance() { static RandomGenerator rnd(0); return rnd; } std::string doubleToString(double x, int precision) //waiting for a proper, native C++ solution { std::stringstream ss; //or for pre-allocated buffer, sprintf(s, "%.*f", precision, x); std::string str; if (fabs(x) < 1e8) //limiting the precision of huge fp values makes little sense - better use scientific notation, unless we want a looong number { ss << std::fixed; ss.precision(precision); //set the number of places after decimal ss << x; str = ss.str(); char *s = #ifdef __BORLANDC__ //embarcadero 10.3u3 compiler does not support char* str.data() even in C++17 mode? (char*) #endif str.data(); //now we will be operating directly on the internal std::string buffer for (int i = int(str.length()) - 1, end = int(str.length()); i >= 0; i--) //remove trailing zeros, and maybe also '.' { if (s[i] == '0') { if (end == i + 1) end = i; } else if (s[i] == '.') { if (end == i + 1) end = i; s[end] = '\0'; break; } } } else { ss << x; str = ss.str(); } //printf("%.17g and %d decimals: %s\n", x, precision, str.c_str()); return str; } int doubleToString(double x, int precision, char *buffer, int bufferlen) { // C++ in 2020 and the impossible challenge https://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf if (precision < 0) { // The "g" format does not allow to use the number of decimal places after the decimal point. Dragon4 on the other hand fills in unnecessary trailinig zeros... so both are good only for "full precision". #ifdef USE_PRINTFLOAT_DRAGON4 return PrintFloat64(buffer, bufferlen, x, ((x < -1e17) || (x > 1e17) || ((x < 1e-4) && (x > -1e-4) && (x != 0.0))) ? PrintFloatFormat_Scientific : PrintFloatFormat_Positional, precision); //http://www.ryanjuckett.com/programming/printing-floating-point-numbers/ #else return sprintf(buffer, "%.17g", x); #endif } else { std::string s = doubleToString(x, precision); strncpy(buffer, s.c_str(), std::min(bufferlen, (int)s.length() + 1)); buffer[bufferlen - 1] = 0; //ensure the string is truncated return int(s.length()); } } double round(const double x, const int precision) { double rounded = std::stod(doubleToString(x, precision)); //printf("%d %20g \t %20g\n", precision, x, rounded); //for debugging return rounded; } namespace fpExcept { //shared for all platforms, using crossplatform constants, can be defined in build_config (but also conditionally changed from the code) int wanted_exceptions = #ifdef WANTED_FP_EXCEPTIONS WANTED_FP_EXCEPTIONS; #else FPEX_DIV0; //default when 'WANTED_FP_EXCEPTIONS' is not defined (add more?) #endif } // Idea: enable selected floating point exceptions when the app starts and disable them temporarily when dividing values in ExtValue, so that we can directly handle problematic cases there. // This allows to catch problematic situations when the program performs calculations using NaN, INF etc. #ifdef IPHONE //TODO! -> ? http://stackoverflow.com/questions/12762418/how-to-enable-sigfpe-signal-on-division-by-zero-in-ios-app namespace fpExcept { void init() {} void enable() {} void disable() {} } #endif #ifdef MACOS //TODO...? (even less reasons to omit this in macos :-P) namespace fpExcept { void init() {} void enable() {} void disable() {} } #endif #if defined LINUX || defined TIZEN || defined __ANDROID__ #include #ifdef __CYGWIN__ //since my cygwin update in 2024 (g++ (GCC) 11.4.0), these two are no longer found: #define feenableexcept(x) #define fedisableexcept(x) #endif namespace fpExcept { void init() {} void enable() { feclearexcept(wanted_exceptions); feenableexcept(wanted_exceptions); } void disable() { fedisableexcept(wanted_exceptions); } }; #endif #if defined(__BORLANDC__) || defined(_MSC_VER) namespace fpExcept { // in Borland, there was once a problem like this: // http://qc.embarcadero.com/wc/qcmain.aspx?d=5128 // http://www.delorie.com/djgpp/doc/libc/libc_112.html // ? http://www.c-jump.com/CIS77/reference/Intel/CIS77_24319002/pg_0211.htm // ? http://www.jaist.ac.jp/iscenter-new/mpc/altix/altixdata/opt/intel/vtune/doc/users_guide/mergedProjects/analyzer_ec/mergedProjects/reference_olh/mergedProjects/instructions/instruct32_hh/vc100.htm // ? http://www.plantation-productions.com/Webster/www.artofasm.com/Linux/HTML/RealArithmetica2.html // http://blogs.msdn.com/b/oldnewthing/archive/2008/07/03/8682463.aspx // where each cast of a double into an int would cause an exception. // But it was resolved by restarting windows and cleaning all intermediate compilation files :o (restarting windows was the key element! restarting BC++Builder and deleting files would not help) #if defined(__BORLANDC__) // adding a missing constant and a function #define _MCW_EM 0x0008001f // Interrupt Exception Masks - from Visual C++'s float.h void _controlfp_s(unsigned int* _CurrentState, unsigned int _NewValue, unsigned int _Mask) //pretends to be the real _controlfp_s() function { *_CurrentState = _control87(_NewValue, _Mask); } #endif #if defined(_MSC_VER) #pragma fenv_access (on) #endif // http://stackoverflow.com/questions/2769814/how-do-i-use-try-catch-to-catch-floating-point-errors //#include "log.h" unsigned int fp_control_word_std; unsigned int fp_control_word_muted; void init() { _controlfp_s(&fp_control_word_std, 0, 0); //in Visual C++, the default value is exactly the masks listed below, and we have to turn them off to enable exceptions // Make the new fp env same as the old one, except for the changes we're going to make fp_control_word_muted = fp_control_word_std & ~wanted_exceptions; } void enable() { //_fpreset(); //not needed since we just _clearfp()... mentioned in https://stackoverflow.com/questions/4282217/visual-c-weird-behavior-after-enabling-floating-point-exceptions-compiler-b unsigned int was = _clearfp(); //need to clean so that there is no exception... //logPrintf("","fpExceptEnable",LOG_INFO,"control87 status before clear was %08x", was); _controlfp_s(&was, fp_control_word_muted, _MCW_EM); } void disable() { //_fpreset(); //not needed since we just _clearfp()... mentioned in https://stackoverflow.com/questions/4282217/visual-c-weird-behavior-after-enabling-floating-point-exceptions-compiler-b unsigned int was = _clearfp(); //need to clean so that there is no exception... //logPrintf("","fpExceptDisable",LOG_INFO,"control87 status before clear was %08x", was); _controlfp_s(&was, fp_control_word_std, _MCW_EM); } }; #endif