18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-28 20:53:22 +01:00
Files
maszyna/utilities/utilities.h
jerrrrycho 3eb2fdf462 Merge staging into feat/gl46-migration
origin/staging 7ac2472c3 into feat/gl46-migration db26a33ed, so that #468
merges into staging. Merge base 037158104. Staging carries master up to
571487612 (squashed in #514); this branch had merged master up to 7c12b83ba.

Conflicts, file by file:
- README.md: WITH_BETTER_RENDERER row dropped (gl46), USE_SYSTEM_JSON row kept (staging)
- CMakeLists.txt: gl46 lists, plus staging's new core sources (hardwareinfo, sn_utils, regionfile, inionlysettings, fieldshunting, gaugewrap, drivingaid, signalpassing, brakereleaser, crew, brakecharge); none listed twice
- tests/unit/CMakeLists.txt: both (texturealpha, freecameramotion; editorSwitchDrives, Camera)
- vehicle/brakingcurve.{h,cpp}, tests/unit/test_braking_curve.cpp (add/add): staging (#479 brake_acting on the same #409 code)
- editor/editorHttp.cpp: staging (it has gl46's #432 and certificate fixes, plus #439 libcurl loaded at run time)
- tests/unit/test_editor_http.cpp (add/add): staging (adds the available() case of #439)
- utilities/Globals.h: gl46 crashdump_full (staging's CrashDumpFull is #425, replaced here by utilities/crashdump.cpp); fmradio and staging's OpenAL options both; gfx_headlights_beamwidth (#481) not taken
- utilities/Globals.cpp: both (odometer.expiry, OpenAL keys, fmradio, gl46 gfx keys); gfx.headlights.beamwidth (#481) not taken
- utilities/Logs.cpp: staging's log_file_name() for both files, with gl46's crashdump_set_log_file() for both
- utilities/utilities.h: gl46 set_thread_random_engine(); Random(int, int) gone on both sides
- tests/unit/test_utilities.cpp: staging's includes
- simulation/simulationtest.cpp: gl46 (no NvRenderer, LegacyRenderer, BasicRenderer here)
- ci_shadervalidator/* (incl. add/add utilities/Logs.h): gl46's validator of shaders/ogl46 and shaders/vk14; staging's #437 fixed the GL 3.3 one
- gl/shader.cpp, gl/glsl_common.cpp: gl46 (shaders come from rendering/common/shadersource.cpp); HEADLIGHT_BEAM_WIDTH (#481) not taken
- shaders/mat_wire.frag: gl46. Rename detection paired staging's mat_colored.frag (#481) with it
- lang/editor_pl.po: union; the 12 camera speed / orthophoto entries staging adds are here already (master #312)
- audio/audiorenderer.{h,cpp}: both (fmradio; startsample and the low-pass filter); the destructor releases the radio, then the filter
- application/editormode.h, application/editormodeswitchdrive.cpp: staging (#509 on #330, which is all this side had)
- application/application.cpp: gl46's start sequence (no init_ogl, ANGLE or NvRenderer; crash window after init_ui) with staging's hardware::log_system() (#389)
- EU07.cpp: gl46 (crash reports of utilities/crashdump.cpp); staging's side was #425's handler, replaced here
- model/Texture.{h,cpp}: gl46 (texture_source); staging's side is master #399/#411/#362/#386, merged here before
- world/Track.h, world/TrackSleepers.h: both (TrackBlend, lay(Fastened)/fasten; TrackBuckle, pack_models)
- world/Segment.cpp: staging's track buckling on the split stray factors both sides have
- vehicle/Driver.h: staging's additions (#444, #494, #473, #346, timetable flags)
- vehicle/Driver.cpp: staging's file, with this branch's f4f8c75e4 (road orders measured along the lane) and 8fbf05674 (a holding road order blocks the ones past it) applied again; #409's SeenAheadTolerance gives way to #473
- vehicle/DynObj.h: friend opengl46_renderer and friend class vehicle_table
- vehicle/DynObj.cpp: gl46's vehicle_table::update() with staging's update_off_track_contacts() and update_brake_pipes()
- McZapkie/Mover.cpp: staging's function splits (#239) and hose exchange (#388); every line this branch added to Mover.cpp/MOVER.h is kept
- .github/workflows/build_bin.yml: staging's apt-install step (#497) and pinned download-artifact (#331)

Modify/delete, kept deleted:
- rendering/opengl33renderer.{cpp,h}, rendering/openglparticles.cpp, rendering/openglrenderer.{cpp,h}: staging's versions are master's, and every master change to them is in this branch's history already
- shaders/light_common.glsl, shaders/mat_sunlessnormalmap_specgloss.frag: see below

Carried into this branch's code:
- the hose exchange after each sub-step (#387/#388) also in update_steps_parallel(), per group of vehicles, as update() does it single-threaded
- physics.pipewake (pipe_wakes(), wake_cause::scndpipe) in staging's GetScndDVc(), where the main reservoir hose exchange went
- hardware::log_gl_context() (#389) in after_window() of the GL 4.6 backend, init_ogl() being gone

Taken back out of the auto-merge (renderers this branch removed):
- shaders/vk14/tonemapping.glsl: #481's switch to ACES, applied there by rename detection
- environment/skydome.cpp, simulation/simulationenvironment.cpp: #415, the sky of the legacy renderer
- application/application.cpp: #384's fallback of an unknown gfxrenderer, which this branch had dropped

Not carried from staging (renderer files removed here):
- master #481 (571487612): old assets drawn as in 26.05 (metal diffuse, sun highlight tint, ACES, SUN_DIFFUSE_SCALE 2.5, untinted Diffuse, mat_colored base) and gfx.headlights.beamwidth. Made for the GL 3.3 shaders; the PBR shaders of shaders/ogl46 and vk14 (and their SPIR-V binaries) are the author's call
- #437: the unique temporary file of the shader validator (Sonar S5443); gl46's validator still writes /tmp/shader*

Unit tests: 1133 of 1137 cases pass. Four staging tests fail (derailment: a
repaired vehicle is back on the rails; three pullee cases): the vehicle
stands, and with physics.sleepheld (on by default here) its physics sleeps
with the Fb / FStand of before. With physics.sleepheld off they pass. Left
to the author.
2026-11-27 05:26:13 +01:00

513 lines
19 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include "stdafx.h"
#include "utilities/parser.h"
#include <optional>
/*rozne takie duperele do operacji na stringach w paszczalu, pewnie w delfi sa lepsze*/
/*konwersja zmiennych na stringi, funkcje matematyczne, logiczne, lancuchowe, I/O etc*/
template <typename T> T sign(T x)
{
return x < static_cast<T>(0) ? static_cast<T>(-1) : x > static_cast<T>(0) ? static_cast<T>(1) : static_cast<T>(0);
}
template <typename T> constexpr T sq(T v)
{
return v * v;
}
// a base folder of the XDG base directory spec, of the values of its variable (XDG_CONFIG_HOME, XDG_CACHE_HOME) and
// of HOME, either of them null when not set: the variable when it holds an absolute path, else `Fallback` (.config,
// .cache) in the home folder, else an empty path. what Linux uses; apart from the environment, so tests can call it
std::filesystem::path xdg_base_directory(char const *Variable, char const *Home, char const *Fallback);
// the folder of the settings on Linux, of the values of XDG_CONFIG_HOME and HOME: MaSzyna in the base folder of the
// settings, but ~/.config/MaSzyna, where the releases which didn't read XDG_CONFIG_HOME kept them, while it exists and
// the new one doesn't, so the settings already there keep working. an empty path as xdg_base_directory
std::filesystem::path xdg_config_folder(char const *Variable, char const *Home);
// returns the per-user config path for `filename` (platform-specific dir: %APPDATA%\MaSzyna,
// ~/Library/Application Support/MaSzyna, $XDG_CONFIG_HOME/MaSzyna or ~/.config/MaSzyna),
// or an empty path if the home/appdata env var is unavailable
std::filesystem::path user_config_path(const std::string &filename);
// the per-user path for `filename` among the files kept only to be fetched again faster, which don't roam with the profile:
// %LOCALAPPDATA%\MaSzyna\cache, ~/Library/Caches/MaSzyna, $XDG_CACHE_HOME/MaSzyna or ~/.cache/MaSzyna; empty as user_config_path
std::filesystem::path user_cache_path(const std::string &filename);
// TODO: Shouldn't this be in globals?
namespace paths
{
inline constexpr const char *scenery = "scenery/";
inline constexpr const char *textures = "textures/";
inline constexpr const char *models = "models/";
inline constexpr const char *dynamic = "dynamic/";
inline constexpr const char *sounds = "sounds/";
inline constexpr const char *data = "data/";
}
#define MAKE_ID4(a, b, c, d) (((std::uint32_t)(d) << 24) | ((std::uint32_t)(c) << 16) | ((std::uint32_t)(b) << 8) | (std::uint32_t)(a))
extern bool DebugModeFlag;
extern bool FreeFlyModeFlag;
extern bool EditorModeFlag;
extern bool DebugCameraFlag;
extern bool DebugTractionFlag;
/*funkcje matematyczne*/
inline double Sign(double x)
{
return x >= 0 ? 1.0 : -1.0;
}
inline long Round(double const f)
{
return (long)(f + 0.5);
// return lround(f);
}
double Random(double a, double b);
// whole numbers from min to max, both included. a name of its own keeps the calls of Random() with whole-number
// bounds (the wind, the wheel flats, the truck hunting, the tachometer) on Random(double, double), which draws the
// real number in between that they expect. drawn from the local engine, as up to 26.05.1 from an engine of its own: it
// picks what one machine shows (the trivia of the loading screen), and a draw from the engine of the run's seed would
// put that engine out of step with the other machines of a network session
int RandomInt(int min, int max);
// the engine Random() draws from in the calling thread, in place of Global.random_engine, or none for that one again. the threads
// of worker_pool have engines of their own: the one of the simulation can't be shared between threads
void set_thread_random_engine(std::mt19937 *Engine); // NOSONAR: randomness of the simulation, not of anything security-relevant
/// @author lxvia
/// @brief Returns a random seed from the system's entropy source, if available. Otherwise, falls back to a clock-based seed.
/// @return A random seed as 64 bit unsigned integer
std::uint64_t true_random_seed();
// The seed a word stands for. A number is taken as it is written - the whole text, so
// "4242abc" is a word, not 4242 - and 0 is a seed like any other; anything else is
// hashed the way Java's String.hashCode does it, so the same word gives the same
// world on every platform and every build - which is the whole point of telling
// somebody a seed.
std::uint32_t seed_of(std::string const &Text);
// the seed a text of the settings (randomseed) or of the command line (-seed) gives: none for
// an empty text, else seed_of() it, 0 included
std::optional<std::uint32_t> seed_given(std::string const &Text);
std::string generate_uuid_v4();
double LocalRandom(double a, double b);
inline double Random()
{
return Random(0.0, 1.0);
}
inline double Random(double b)
{
return Random(0.0, b);
}
inline double LocalRandom()
{
return LocalRandom(0.0, 1.0);
}
inline double LocalRandom(double b)
{
return LocalRandom(0.0, b);
}
inline double BorlandTime()
{
auto timesinceepoch = std::time(nullptr);
return static_cast<double>(timesinceepoch) / (24.0 * 60 * 60);
/*
// std alternative
auto timesinceepoch = std::chrono::system_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::seconds>( timesinceepoch ).count() / (24.0 * 60 * 60);
*/
}
std::string Now();
double CompareTime(double t1h, double t1m, double t2h, double t2m);
/*funkcje logiczne*/
inline bool TestFlag(int const Flag, int const Value)
{
return (Flag & Value) == Value;
}
inline bool TestFlagAny(int const Flag, int const Value)
{
return (Flag & Value) != 0;
}
bool SetFlag(int &Flag, int const Value);
bool ClearFlag(int &Flag, int const Value);
bool FuzzyLogic(double Test, double Threshold, double Probability);
/*jesli Test>Threshold to losowanie*/
bool FuzzyLogicAI(double Test, double Threshold, double Probability);
/*to samo ale zawsze niezaleznie od DebugFlag*/
/*operacje na stringach*/
std::vector<std::string> Split(std::string_view s, char delim);
std::pair<std::string, int> split_string_and_number(std::string const &Key);
std::string to_string(int Value, int width);
std::string to_string(double Value, int precision);
std::string to_string(double Value, int precision, int width);
std::string to_hex_str(int const Value, int const width = 4);
std::string to_minutes_str(float const Minutes, bool const Leadingzero, int const Width);
template <std::same_as<bool> T> // Without this line this function can be used with other types implicit casted to boolean which may create hard to debug bugs.
inline std::string to_string(T Value)
{
return Value == true ? "true" : "false";
}
template <typename Type_, glm::precision Precision_ = glm::defaultp> std::string to_string(glm::tvec3<Type_, Precision_> const &Value)
{
return to_string(Value.x, 2) + ", " + to_string(Value.y, 2) + ", " + to_string(Value.z, 2);
}
template <typename Type_, glm::precision Precision_ = glm::defaultp> std::string to_string(glm::tvec4<Type_, Precision_> const &Value, int const Width = 2)
{
return to_string(Value.x, Width) + ", " + to_string(Value.y, Width) + ", " + to_string(Value.z, Width) + ", " + to_string(Value.w, Width);
}
int stol_def(const std::string &str, const int &DefaultValue);
std::string ToLower(std::string const &text);
std::string ToUpper(std::string const &text);
// replaces polish letters with basic ascii
void win1250_to_ascii(std::string &Input);
// TODO: unify with win1250_to_ascii()
std::string Bezogonkow(std::string Input, bool const Underscorestospaces = false);
std::string win1250_to_utf8(const std::string &input);
// counterpart of win1250_to_utf8(): the polish letters, the other characters outside of ascii as question marks
std::string utf8_to_win1250(std::string const &Text);
// decodes utf-8 encoded text into unicode code points. returns false if the text isn't valid utf-8
bool utf8_to_utf32(std::string const &Text, std::u32string &Output);
// decodes windows-1250 (ansi) encoded text into unicode code points
void win1250_to_utf32(std::string const &Text, std::u32string &Output);
// a text of the data files as utf-8, for the user interface. the files are in windows-1250, some of the newer ones in
// utf-8: a text which is valid utf-8 stays as it is, any other is read as windows-1250, every letter of the code page
// (not only the polish ones win1250_to_utf8() knows) turned into utf-8
std::string data_text_to_utf8(std::string const &Text);
// the same for a name (of a station, a train, an event, a node, a file) shown in a line of the user interface: what
// Bezogonkow() is for, but the letters keep their marks. control characters become spaces and, when asked, underscores too
std::string data_name_to_utf8(std::string const &Name, bool Underscorestospaces = false);
// number of characters (code points) of a text in utf-8; a byte which isn't a part of a valid sequence counts as one
std::size_t utf8_length(std::string_view Text);
// a text in utf-8 cut or filled with spaces to given number of characters, for the columns of the fixed width
std::string utf8_fit(std::string_view Text, std::size_t Width);
inline std::string extract_value(std::string const &Key, std::string const &Input)
{
// NOTE, HACK: the leading space allows to uniformly look for " variable=" substring
std::string const input{" " + Input};
std::string value;
if (auto lookup = input.find(" " + Key + "="); lookup != std::string::npos)
{
value = input.substr(input.find_first_not_of(' ', lookup + Key.size() + 2));
lookup = value.find(' ');
if (lookup != std::string::npos)
{
// trim everything past the value
value.erase(lookup);
}
}
return value;
}
template <typename Type_> bool extract_value(Type_ &Variable, std::string const &Key, std::string const &Input, std::string const &Default)
{
auto value = extract_value(Key, Input);
if (false == value.empty())
{
// set the specified variable to retrieved value
std::stringstream converter;
converter << value;
converter >> Variable;
return true; // located the variable
}
else
{
// set the variable to provided default value
if (false == Default.empty())
{
std::stringstream converter;
converter << Default;
converter >> Variable;
}
return false; // couldn't locate the variable in provided input
}
}
template <> bool extract_value(bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default);
bool FileExists(std::string const &Filename);
// the file as it's named on the disk when only the case of its name or of its folders differs, as in the sceneries made on Windows;
// empty when there's none. on Windows, finding the names in any case itself, the file given or none
std::string FileCased(std::filesystem::path const &Filename);
// the file to open: as it's named on the disk, the name given when there's none
std::string FileOnDisk(std::string const &Filename);
// the name (relative to the folder, without extension) as it's named on the disk with the first of the extensions it has a file with,
// found in any case; the name given when there's none
std::string FileStemOnDisk(std::string const &Folder, std::string const &Name, std::vector<std::string> const &Extensions);
// the first name with one of the extensions which has a file in any case, in the order given; given back as named here, the file
// is opened by FileOnDisk()
std::pair<std::string, std::string> FileExists(std::vector<std::string> const &Names, std::vector<std::string> const &Extensions);
// returns time of last modification for specified file
std::time_t last_modified(std::string const &Filename);
// thread-safe replacements for std::localtime and std::gmtime, which hand out a pointer to shared static storage
std::tm local_tm(std::time_t Time);
std::tm utc_tm(std::time_t Time);
// potentially erases file extension from provided file name. returns: true if extension was removed, false otherwise
bool erase_extension(std::string &Filename);
// potentially erase leading slashes from provided file path
void erase_leading_slashes(std::string &Filename);
// potentially replaces backward slashes in provided file path with unix-compatible forward slashes
void replace_slashes(std::string &Filename);
// returns potential path part from provided file name
std::string substr_path(std::string const &Filename);
// returns common prefix of two provided strings
std::ptrdiff_t len_common_prefix(std::string_view a, std::string_view b);
// returns true if provided string contains another provided string
bool contains(std::string_view const String, std::string_view Substring);
bool contains(std::string_view const String, char Character);
// TODO: Ideally unique_ptr should be used instead of this (not safe) inline functions
template <typename T> inline void SafeDelete(T* &Pointer)
{
delete Pointer;
Pointer = nullptr;
}
template <typename T> inline void SafeDeleteArray(T *&Pointer)
{
delete[] Pointer;
Pointer = nullptr;
}
template <typename T> bool is_equal(T const &Left, T const &Right, T const Epsilon = T(1e-5))
{
if (Epsilon != T(0))
return glm::epsilonEqual(Left, Right, Epsilon);
return Left == Right;
}
// Tolerant clamp, the old custom clamp() of the project (up to 26.05.1). Unlike
// std::clamp, this does NOT invoke undefined behaviour when the bounds are inverted
// (Lo > Hi): the lower bound is applied first and the upper one last, so inverted
// bounds give the upper bound, as the old clamp() did. Every call of the old clamp()
// whose bounds can cross (they come from the .fiz, the .mmd or the window, or are
// computed from such values) uses it, so it gives what it gave before the move to
// std::clamp. Where the code keeps the bounds in order, std::clamp gives the same.
// New code uses std::clamp.
template <typename Type_>
constexpr Type_ safe_clamp( Type_ const Value, Type_ const Lo, Type_ const Hi )
{
return std::min( std::max( Value, Lo ), Hi );
}
// keeps the provided value in specified range 0-Range, as if the range was circular buffer
template <typename T> T clamp_circular(T Value, T const Range = T(360))
{
if constexpr (std::is_floating_point_v<T>)
{
Value = std::fmod(Value, Range);
}
else
{
Value %= Range;
}
if (Value < T(0))
Value += Range;
return Value;
}
// rounds down provided value to nearest power of two
template <typename T> T clamp_power_of_two(T Value, T const Min = T(1), T const Max = T(16384))
{
if (Value < Min)
return Min;
T p2 = std::bit_floor(Value);
if (p2 > Max)
return Max;
return p2;
}
template <typename Type_> Type_ quantize(Type_ const Value, Type_ const Step)
{
return static_cast<Type_>(Step * std::round(Value / Step));
}
template <typename T> T min_speed(T const Left, T const Right)
{
constexpr T none = T(-1);
if (Left == none)
return Right;
if (Right == none)
return Left;
return std::min(Left, Right);
}
template <typename T> T smoothInterpolate(T const &First, T const &Second, double Factor)
{
// Apply smoothing (ease-in-out quadratic)
Factor = Factor * Factor * (3 - 2 * Factor);
return First + (Second - First) * Factor;
}
// tests whether provided points form a degenerate triangle
template <typename VecType_> bool degenerate(VecType_ const &Vertex1, VecType_ const &Vertex2, VecType_ const &Vertex3)
{
// degenerate( A, B, C, minarea ) = ( ( B - A ).cross( C - A ) ).lengthSquared() < ( 4.0f * minarea * minarea );
return glm::length2(glm::cross(Vertex2 - Vertex1, Vertex3 - Vertex1)) == 0.0;
}
// calculates bounding box for provided set of points
template <class Iterator_, class VecType_> void bounding_box(VecType_ &Mincorner, VecType_ &Maxcorner, Iterator_ First, Iterator_ Last)
{
Mincorner = VecType_(std::numeric_limits<typename VecType_::value_type>::max());
Maxcorner = VecType_(std::numeric_limits<typename VecType_::value_type>::lowest());
std::for_each(First, Last,
[&](typename Iterator_::value_type &point)
{
Mincorner = glm::min(Mincorner, VecType_{point});
Maxcorner = glm::max(Maxcorner, VecType_{point});
});
}
// finds point on specified segment closest to specified point in 3d space. returns: point on segment as value in range 0-1 where 0 = start and 1 = end of the segment
template <typename VecType_> typename VecType_::value_type nearest_segment_point(VecType_ const &Segmentstart, VecType_ const &Segmentend, VecType_ const &Point)
{
auto const v = Segmentend - Segmentstart;
auto const w = Point - Segmentstart;
auto const c1 = glm::dot(w, v);
if (c1 <= 0.0)
{
return 0.0;
}
auto const c2 = glm::dot(v, v);
if (c2 <= c1)
{
return 1.0;
}
return c1 / c2;
}
glm::dvec3 LoadPoint(class cParser &Input);
// extracts a group of tokens from provided data stream
std::string deserialize_random_set(cParser &Input, char const *Break = "\n\r\t ;");
// extracts a group of tokens from provided data stream, returns all of them.
// a single token, not enclosed in "[]", is returned as one element sequence
std::vector<std::string> deserialize_set(cParser &Input, char const *Break = "\n\r\t ;");
// returns hash of provided string, combined with provided seed. FNV-1a, picked for having
// identical result regardless of platform and standard library, unlike std::hash
std::uint32_t hash_string(std::string const &String, std::uint32_t const Seed = 0);
// extracts a group of <key, value> pairs from provided data stream
// NOTE: expects no more than single pair per line
template <typename MapType_> void deserialize_map(MapType_ &Map, cParser &Input)
{
while (Input.ok() && !Input.eof())
{
auto const key{Input.getToken<typename MapType_::key_type>(false)};
auto const value{Input.getToken<typename MapType_::mapped_type>(false, "\n")};
Map.emplace(key, value);
}
}
namespace threading
{
// simple POD pairing of a data item and a mutex
// NOTE: doesn't do any locking itself, it's merely for cleaner argument arrangement and passing
template <typename Type_> struct lockable
{
Type_ data;
std::mutex mutex;
};
// basic wrapper simplifying use of std::condition_variable for most typical cases.
// has its own mutex and secondary variable to ignore spurious wakeups
class condition_variable
{
public:
// methods
void wait()
{
std::unique_lock lock(m_mutex);
m_condition.wait(lock, [this]() { return m_spurious == false; });
}
template <class Rep_, class Period_> void wait_for(const std::chrono::duration<Rep_, Period_> &Time)
{
std::unique_lock lock(m_mutex);
m_condition.wait_for(lock, Time, [this]() { return m_spurious == false; });
}
void notify_one()
{
spurious(false);
m_condition.notify_one();
}
void notify_all()
{
spurious(false);
m_condition.notify_all();
}
void spurious(bool const Spurious)
{
std::scoped_lock lock(m_mutex);
m_spurious = Spurious;
}
private:
// members
mutable std::mutex m_mutex;
std::condition_variable m_condition;
bool m_spurious{true};
};
} // namespace threading
//---------------------------------------------------------------------------