16
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-07-17 23:39:18 +02:00

Merge pull request #99 from docentYT/utilities-simplification

Utilities simplification
This commit is contained in:
2026-05-06 18:35:29 +02:00
committed by GitHub
70 changed files with 703 additions and 935 deletions

View File

@@ -55,7 +55,7 @@ static void ParseOneClamped(cParser& parser, T& out, T minValue, T maxValue, int
{
parser.getTokens(tokenCount, convert);
parser >> out;
out = clamp(out, minValue, maxValue);
out = std::clamp(out, minValue, maxValue);
}
void global_settings::FinalizeConfig()
@@ -284,24 +284,24 @@ bool global_settings::ConfigParseGraphics(cParser& Parser, const std::string& to
if (token == "maxtexturesize")
{
int size = 0;
unsigned int size = 0;
ParseOne(Parser, size, 1, false);
iMaxTextureSize = clamp_power_of_two(size, 64, 8192);
iMaxTextureSize = static_cast<GLint>(clamp_power_of_two(size, 64u, 8192u));
return true;
}
if (token == "maxcabtexturesize")
{
int size = 0;
unsigned int size = 0;
ParseOne(Parser, size, 1, false);
iMaxCabTextureSize = clamp_power_of_two(size, 512, 8192);
iMaxCabTextureSize = static_cast<GLint>(clamp_power_of_two(size, 512u, 8192u));
return true;
}
if (token == "dynamiclights")
{
ParseOne(Parser, DynamicLightCount, 1, false);
DynamicLightCount = clamp(DynamicLightCount, 0, 7);
DynamicLightCount = std::clamp(DynamicLightCount, 0, 7);
return true;
}
@@ -358,7 +358,7 @@ bool global_settings::ConfigParseGraphics(cParser& Parser, const std::string& to
if (token == "multisampling")
{
ParseOne(Parser, iMultisampling, 1, false);
iMultisampling = clamp(iMultisampling, 0, 4);
iMultisampling = std::clamp(iMultisampling, 0, 4);
return true;
}
@@ -546,7 +546,7 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string&
stream >> ScenarioTimeOverride;
}
ScenarioTimeOverride = clamp(ScenarioTimeOverride, 0.f, 24 * 1439 / 1440.f);
ScenarioTimeOverride = std::clamp(ScenarioTimeOverride, 0.f, 24 * 1439 / 1440.f);
return true;
}
@@ -578,7 +578,7 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string&
{
float splinefidelity = 0.f;
ParseOne(Parser, splinefidelity);
SplineFidelity = clamp(splinefidelity, 1.f, 4.f);
SplineFidelity = std::clamp(splinefidelity, 1.f, 4.f);
return true;
}
@@ -1323,7 +1323,7 @@ global_settings::ConfigParse_gfx( cParser &Parser, std::string_view const Token
float smokefidelity;
Parser.getTokens();
Parser >> smokefidelity;
SmokeFidelity = clamp(smokefidelity, 1.f, 4.f);
SmokeFidelity = std::clamp(smokefidelity, 1.f, 4.f);
}
else if (Token == "gfx.resource.sweep")
{
@@ -1344,7 +1344,7 @@ global_settings::ConfigParse_gfx( cParser &Parser, std::string_view const Token
{
Parser.getTokens(1, false);
Parser >> reflectiontune.fidelity;
reflectiontune.fidelity = clamp(reflectiontune.fidelity, 0, 2);
reflectiontune.fidelity = std::clamp(reflectiontune.fidelity, 0, 2);
}
else if (Token == "gfx.reflections.range_instances")
{
@@ -1468,13 +1468,13 @@ global_settings::ConfigParse_gfx( cParser &Parser, std::string_view const Token
if( gfx_shadow_angle_min > 0 ) {
gfx_shadow_angle_min *= -1;
}
gfx_shadow_angle_min = clamp(gfx_shadow_angle_min, -1.f, -0.2f);
gfx_shadow_angle_min = std::clamp(gfx_shadow_angle_min, -1.f, -0.2f);
}
else if (Token == "gfx.shadow.rank.cutoff")
{
Parser.getTokens(1);
Parser >> gfx_shadow_rank_cutoff;
gfx_shadow_rank_cutoff = clamp(gfx_shadow_rank_cutoff, 1, 3);
gfx_shadow_rank_cutoff = std::clamp(gfx_shadow_rank_cutoff, 1, 3);
}
else
{

View File

@@ -52,7 +52,7 @@ struct global_settings {
basic_light DayLight;
float SunAngle{ 0.f }; // angle of the sun relative to horizon
int trainThreads{0};
double fLuminance{ 1.0 }; // jasność światła do automatycznego zapalania
double fLuminance{ 1.0 }; // jasność światła do automatycznego zapalania // TODO: Why double?
double fTimeAngleDeg{ 0.0 }; // godzina w postaci kąta
float fClockAngleDeg[ 6 ]; // kąty obrotu cylindrów dla zegara cyfrowego
std::string LastGLError;

View File

@@ -11,7 +11,6 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/dictionary.h"
#include "simulation/simulation.h"
#include "utilities/utilities.h"
#include "vehicle/DynObj.h"
#include "vehicle/Driver.h"
#include "world/mtable.h"

View File

@@ -9,7 +9,6 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "utilities/parser.h"
#include "utilities/utilities.h"
#include "utilities/Logs.h"
#include "scene/scenenodegroups.h"

View File

@@ -86,11 +86,11 @@ bool locale::parse_translation(std::istream &stream)
if (line.size() > 0 && line[0] == '#')
continue;
if (string_starts_with(line, "msgid"))
if (line.starts_with("msgid"))
last = 'i';
else if (string_starts_with(line, "msgstr"))
else if (line.starts_with("msgstr"))
last = 's';
else if (string_starts_with(line, "msgctxt"))
else if (line.starts_with("msgctxt"))
last = 'c';
if (line.size() > 1 && last != 'x') {

View File

@@ -11,56 +11,37 @@ MaSzyna EU07 - SPKS
Brakes.
Copyright (C) 2007-2014 Maciej Cierniak
*/
#include "stdafx.h"
#include <sys/types.h>
#include <sys/stat.h>
#ifndef WIN32
#include <unistd.h>
#endif
#ifdef WIN32
#define stat _stat
#endif
//#include "stdafx.h"
//
//#include <sys/types.h>
//#include <sys/stat.h>
#include <ranges>
//#ifndef WIN32
//#include <unistd.h>
//#endif
//
//#ifdef WIN32
//#define stat _stat
//#endif
#include "utilities/utilities.h"
#include "utilities/Globals.h"
#include "utilities/parser.h"
#include "utilities/Logs.h"
//#include "utilities/Logs.h"
// TODO: This shouldn't be in Globals?
bool DebugModeFlag = false;
bool FreeFlyModeFlag = false;
bool EditorModeFlag = false;
bool DebugCameraFlag = false;
bool DebugTractionFlag = false;
double Max0R(double x1, double x2)
{
if (x1 > x2)
return x1;
else
return x2;
}
double Min0R(double x1, double x2)
{
if (x1 < x2)
return x1;
else
return x2;
}
// shitty replacement for Borland timestamp function
// TODO: replace with something sensible
std::string Now()
{
std::time_t timenow = std::time(nullptr);
std::tm tm = *std::localtime(&timenow);
std::stringstream converter;
converter << std::put_time(&tm, "%c");
return converter.str();
auto now = std::chrono::system_clock::now();
auto local = std::chrono::current_zone()->to_local(now);
return std::format("{:%c}", local);
}
// zwraca różnicę czasu
@@ -117,15 +98,14 @@ bool ClearFlag(int &Flag, int const Value)
double Random(double a, double b)
{
uint32_t val = Global.random_engine();
return interpolate(a, b, (double)val / Global.random_engine.max());
std::uniform_real_distribution<double> dist(a, b);
return dist(Global.random_engine);
}
int RandomInt(int min, int max)
int Random(int min, int max)
{
static std::mt19937 engine(std::random_device{}());
std::uniform_int_distribution<int> dist(min, max);
return dist(engine);
return dist(Global.random_engine);
}
std::string generate_uuid_v4()
@@ -156,8 +136,8 @@ std::string generate_uuid_v4()
double LocalRandom(double a, double b)
{
uint32_t val = Global.local_random_engine();
return interpolate(a, b, (double)val / Global.random_engine.max());
std::uniform_real_distribution<double> dist(a, b);
return dist(Global.local_random_engine);
}
bool FuzzyLogic(double Test, double Threshold, double Probability)
@@ -176,71 +156,12 @@ bool FuzzyLogicAI(double Test, double Threshold, double Probability)
return false;
}
std::string DUE(std::string s) /*Delete Before Equal sign*/
{
// DUE = Copy(s, Pos("=", s) + 1, length(s));
return s.substr(s.find("=") + 1, s.length());
}
std::string DWE(std::string s) /*Delete After Equal sign*/
{
size_t ep = s.find("=");
if (ep != std::string::npos)
// DWE = Copy(s, 1, ep - 1);
return s.substr(0, ep);
else
return s;
}
std::string ExchangeCharInString(std::string const &Source, char const From, char const To)
{
std::string replacement;
replacement.reserve(Source.size());
std::for_each(std::begin(Source), std::end(Source),
[&](char const idx)
{
if (idx != From)
{
replacement += idx;
}
else
{
replacement += To;
}
});
return replacement;
}
std::vector<std::string> &Split(const std::string &s, char delim, std::vector<std::string> &elems)
std::vector<std::string> Split(std::string_view s, char delim)
{ // dzieli tekst na wektor tekstow
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
std::vector<std::string> Split(const std::string &s, char delim)
{ // dzieli tekst na wektor tekstow
std::vector<std::string> elems;
Split(s, delim, elems);
return elems;
}
std::vector<std::string> Split(const std::string &s)
{ // dzieli tekst na wektor tekstow po białych znakach
std::vector<std::string> elems;
std::stringstream ss(s);
std::string item;
while (ss >> item)
{
elems.push_back(item);
}
return elems;
std::vector<std::string> out;
for (const auto& part : s | std::ranges::views::split(delim))
out.emplace_back(part.begin(), part.end());
return out;
}
std::pair<std::string, int> split_string_and_number(std::string const &Key)
@@ -255,73 +176,34 @@ std::pair<std::string, int> split_string_and_number(std::string const &Key)
return {Key, 0};
}
std::string to_string(int Value)
{
std::ostringstream o;
o << Value;
return o.str();
};
std::string to_string(unsigned int Value)
{
std::ostringstream o;
o << Value;
return o.str();
};
std::string to_string(double Value)
{
std::ostringstream o;
o << Value;
return o.str();
};
std::string to_string(int Value, int width)
{
std::ostringstream o;
o.width(width);
o << Value;
return o.str();
o << std::setw(width) << Value;
return std::move(o).str();
};
std::string to_string(double Value, int precision)
{
std::ostringstream o;
o << std::fixed << std::setprecision(precision);
o << Value;
return o.str();
o << std::fixed << std::setprecision(precision) << Value;
return std::move(o).str();
};
std::string to_string(double const Value, int const Precision, int const Width)
{
std::ostringstream converter;
converter << std::setw(Width) << std::fixed << std::setprecision(Precision) << Value;
return converter.str();
std::ostringstream o;
o << std::setw(Width) << std::fixed << std::setprecision(Precision) << Value;
return std::move(o).str();
};
std::string to_hex_str(int const Value, int const Width)
{
std::ostringstream converter;
converter << "0x" << std::uppercase << std::setfill('0') << std::setw(Width) << std::hex << Value;
return converter.str();
std::ostringstream o;
o << "0x" << std::uppercase << std::setfill('0') << std::setw(Width) << std::hex << Value;
return o.str();
};
bool string_ends_with(const std::string &string, const std::string &ending)
{
if (string.length() < ending.length())
return false;
return string.compare(string.length() - ending.length(), ending.length(), ending) == 0;
}
bool string_starts_with(const std::string &string, const std::string &begin)
{
if (string.length() < begin.length())
return false;
return string.compare(0, begin.length(), begin) == 0;
}
std::string const fractionlabels[] = {" ", "¹", "²", "³", "", "", "", "", "", ""};
std::string to_minutes_str(float const Minutes, bool const Leadingzero, int const Width)
@@ -330,7 +212,7 @@ std::string to_minutes_str(float const Minutes, bool const Leadingzero, int cons
float minutesintegral;
auto const minutesfractional{std::modf(Minutes, &minutesintegral)};
auto const width{Width - 1};
auto minutes = (std::string(width - 1, ' ') + (Leadingzero ? to_string(100 + minutesintegral).substr(1, 2) : to_string(minutesintegral, 0)));
auto minutes = (std::string(width - 1, ' ') + (Leadingzero ? std::to_string(100 + minutesintegral).substr(1, 2) : to_string(minutesintegral, 0)));
return (minutes.substr(minutes.size() - width, width) + fractionlabels[static_cast<int>(std::floor(minutesfractional * 10 + 0.1))]);
}
@@ -499,61 +381,41 @@ bool erase_extension(std::string &Filename)
void erase_leading_slashes(std::string &Filename)
{
while (Filename[0] == '/')
{
Filename.erase(0, 1);
}
auto pos = Filename.find_first_not_of('/');
Filename.erase(0, pos);
}
// potentially replaces backward slashes in provided file path with unix-compatible forward slashes
void replace_slashes(std::string &Filename)
{
std::replace(std::begin(Filename), std::end(Filename), '\\', '/');
std::ranges::replace(Filename, '\\', '/');
}
// returns potential path part from provided file name
std::string substr_path(std::string const &Filename)
std::string_view substr_path(std::string const &Filename)
{
return (Filename.rfind('/') != std::string::npos ? Filename.substr(0, Filename.rfind('/') + 1) : "");
if (auto pos = Filename.rfind('/'); pos != std::string::npos)
return Filename.substr(0, pos + 1);
return {};
}
// returns length of common prefix between two provided strings
std::ptrdiff_t len_common_prefix(std::string const &Left, std::string const &Right)
std::ptrdiff_t len_common_prefix(std::string_view a, std::string_view b)
{
auto const *left{Left.data()};
auto const *right{Right.data()};
// compare up to the length of the shorter string
return (Right.size() <= Left.size() ? std::distance(right, std::mismatch(right, right + Right.size(), left).first) : std::distance(left, std::mismatch(left, left + Left.size(), right).first));
}
// returns true if provided string ends with another provided string
bool ends_with(std::string_view String, std::string_view Suffix)
{
return (String.size() >= Suffix.size()) && (0 == String.compare(String.size() - Suffix.size(), Suffix.size(), Suffix));
}
// returns true if provided string begins with another provided string
bool starts_with(std::string_view const String, std::string_view Prefix)
{
return (String.size() >= Prefix.size()) && (0 == String.compare(0, Prefix.size(), Prefix));
auto [it1, it2] = std::ranges::mismatch(a, b);
return std::distance(a.begin(), it1);
}
// returns true if provided string contains another provided string
bool contains(std::string_view const String, std::string_view Substring)
{
// To be replaced with string::contains in C++ 23
return (String.find(Substring) != std::string::npos);
}
bool contains(std::string_view const String, char Character)
{
// To be replaced with string::contains in C++ 23
return (String.find(Character) != std::string::npos);
}
@@ -597,14 +459,4 @@ std::string deserialize_random_set(cParser &Input, char const *Break)
// shouldn't ever get here but, eh
return "";
}
}
int count_trailing_zeros(uint32_t val)
{
int r = 0;
for (uint32_t shift = 1; !(val & shift); shift <<= 1)
r++;
return r;
}
}

View File

@@ -10,12 +10,6 @@ http://mozilla.org/MPL/2.0/.
#pragma once
#include "stdafx.h"
#include <string>
#include <fstream>
#include <ctime>
#include <vector>
#include <sstream>
#include "utilities/parser.h"
/*rozne takie duperele do operacji na stringach w paszczalu, pewnie w delfi sa lepsze*/
@@ -26,14 +20,12 @@ 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));
}
#define DegToRad(a) ((M_PI / 180.0) * (a)) //(a) w nawiasie, bo może być dodawaniem
#define RadToDeg(r) ((180.0 / M_PI) * (r))
template <typename T> constexpr T sq(T v)
{
return v * v;
}
// TODO: Shouldn't this be in globals?
namespace paths
{
inline constexpr const char *scenery = "scenery/";
@@ -53,9 +45,6 @@ extern bool DebugCameraFlag;
extern bool DebugTractionFlag;
/*funkcje matematyczne*/
double Max0R(double x1, double x2);
double Min0R(double x1, double x2);
inline double Sign(double x)
{
return x >= 0 ? 1.0 : -1.0;
@@ -68,7 +57,7 @@ inline long Round(double const f)
}
double Random(double a, double b);
int RandomInt(int min, int max);
int Random(int min, int max);
std::string generate_uuid_v4();
double LocalRandom(double a, double b);
@@ -125,24 +114,17 @@ bool FuzzyLogicAI(double Test, double Threshold, double Probability);
/*to samo ale zawsze niezaleznie od DebugFlag*/
/*operacje na stringach*/
std::string DUE(std::string s); /*Delete Until Equal sign*/
std::string DWE(std::string s); /*Delete While Equal sign*/
std::string ExchangeCharInString(std::string const &Source, char const From, char const To); // zamienia jeden znak na drugi
std::vector<std::string> &Split(const std::string &s, char delim, std::vector<std::string> &elems);
std::vector<std::string> Split(const std::string &s, char delim);
// std::vector<std::string> Split(const std::string &s);
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);
std::string to_string(unsigned int Value);
std::string to_string(int Value, int width);
std::string to_string(double Value);
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);
inline std::string to_string(bool Value)
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");
}
@@ -157,9 +139,6 @@ template <typename Type_, glm::precision Precision_ = glm::defaultp> std::string
return to_string(Value.x, Width) + ", " + to_string(Value.y, Width) + ", " + to_string(Value.z, Width) + ", " + to_string(Value.w, Width);
}
bool string_ends_with(std::string const &string, std::string const &ending);
bool string_starts_with(std::string const &string, std::string const &begin);
int stol_def(const std::string &str, const int &DefaultValue);
std::string ToLower(std::string const &text);
@@ -235,82 +214,65 @@ void erase_leading_slashes(std::string &Filename);
void replace_slashes(std::string &Filename);
// returns potential path part from provided file name
std::string substr_path(std::string const &Filename);
std::string_view substr_path(std::string const &Filename);
// returns common prefix of two provided strings
std::ptrdiff_t len_common_prefix(std::string const &Left, std::string const &Right);
std::ptrdiff_t len_common_prefix(std::string_view a, std::string_view b);
// returns true if provided string ends with another provided string
bool ends_with(std::string_view String, std::string_view Suffix);
// returns true if provided string begins with another provided string
bool starts_with(std::string_view String, std::string_view Prefix);
// 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);
template <typename Type_> void SafeDelete(Type_ &Pointer)
// 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 Type_> void SafeDeleteArray(Type_ &Pointer)
template <typename T> inline void SafeDeleteArray(T *&Pointer)
{
delete[] Pointer;
Pointer = nullptr;
}
template <typename Type_> Type_ is_equal(Type_ const &Left, Type_ const &Right, Type_ const Epsilon = 1e-5)
template <typename T> bool is_equal(T const &Left, T const &Right, T const Epsilon = T(1e-5))
{
if (Epsilon != 0)
{
if (Epsilon != T(0))
return glm::epsilonEqual(Left, Right, Epsilon);
}
else
{
return (Left == Right);
}
}
template <typename Type_> Type_ clamp(Type_ const Value, Type_ const Min, Type_ const Max)
{
Type_ value = Value;
if (value < Min)
{
value = Min;
}
if (value > Max)
{
value = Max;
}
return value;
return (Left == Right);
}
// keeps the provided value in specified range 0-Range, as if the range was circular buffer
template <typename Type_> Type_ clamp_circular(Type_ Value, Type_ const Range = static_cast<Type_>(360))
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;
}
Value -= Range * (int)(Value / Range); // clamp the range to 0-360
if (Value < Type_(0))
if (Value < T(0))
Value += Range;
return Value;
}
// rounds down provided value to nearest power of two
template <typename Type_> Type_ clamp_power_of_two(Type_ Value, Type_ const Min = static_cast<Type_>(1), Type_ const Max = static_cast<Type_>(16384))
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;
Type_ p2size{Min};
Type_ size;
while ((p2size <= Max) && (p2size <= Value))
{
size = p2size;
p2size = p2size << 1;
}
return size;
T p2 = std::bit_floor(Value);
if (p2 > Max)
return Max;
return p2;
}
template <typename Type_> Type_ quantize(Type_ const Value, Type_ const Step)
@@ -319,35 +281,23 @@ template <typename Type_> Type_ quantize(Type_ const Value, Type_ const Step)
return (Step * std::round(Value / Step));
}
template <typename Type_> Type_ min_speed(Type_ const Left, Type_ const Right)
template <typename T> T min_speed(T const Left, T const Right)
{
if (Left == Right)
{
constexpr T none = T(-1);
if (Left == none)
return Right;
if (Right == none)
return Left;
}
return std::min((Left != -1 ? Left : std::numeric_limits<Type_>::max()), (Right != -1 ? Right : std::numeric_limits<Type_>::max()));
return std::min(Left, Right);
}
template <typename Type_> Type_ interpolate(Type_ const &First, Type_ const &Second, float const Factor)
{
return static_cast<Type_>((First * (1.0f - Factor)) + (Second * Factor));
}
template <typename Type_> Type_ interpolate(Type_ const &First, Type_ const &Second, double const Factor)
{
return static_cast<Type_>((First * (1.0 - Factor)) + (Second * Factor));
}
template <typename Type_> Type_ smoothInterpolate(Type_ const &First, Type_ const &Second, double Factor)
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 static_cast<Type_>((First * (1.0 - Factor)) + (Second * Factor));
return First + (Second - First) * Factor;
}
// tests whether provided points form a degenerate triangle
@@ -398,8 +348,6 @@ 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 ;");
int count_trailing_zeros(uint32_t val);
// 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)