17
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-10-17 03:59:19 +02:00

Fix/sonar maintainability rebased (#209)

* refactor(sonar): use override instead of redundant virtual (cpp:S3471)

* refactor(sonar): remove empty statements, one declaration per statement (cpp:S1116, cpp:S1659)

* refactor(sonar): drop redundant lambda return types (cpp:S3574)

* refactor(sonar): prefer using over typedef (cpp:S5416)

* refactor(sonar): use =default for trivial special members (cpp:S3490)

* refactor(sonar): use nullptr literal (cpp:S4962)

* refactor(sonar): remove redundant access specifiers (cpp:S3539)

* refactor(sonar): remove redundant casts (cpp:S1905)

* refactor(sonar): use std::scoped_lock instead of std::lock_guard (cpp:S5997)

* refactor(sonar): construct elements in place with emplace_back (cpp:S6003)

* refactor(sonar): make narrowing conversions explicit (cpp:S5276)

* refactor(sonar): mark unused parameters (cpp:S1172)

Unused names are commented out; parameters used only on some platforms
are marked [[maybe_unused]].

* refactor(sonar): declare non-mutating member functions const (cpp:S5817)

Virtual functions are left untouched so overrides keep matching.

* refactor(sonar): merge collapsible nested if statements (cpp:S1066)

Comments that preceded the inner if are kept above the merged statement.

* refactor(sonar): scope single-use variables in if init-statements (cpp:S6004)

* fix(sonar): give polymorphic base classes virtual destructors (cpp:S1235)

* refactor(sonar): use try_emplace for map insertion (cpp:S6030)

* refactor(sonar): use auto where the type is spelled out on the right (cpp:S5827)

* refactor(sonar): remove redundant parentheses (cpp:S1110)

* refactor(sonar): document intentionally empty functions (cpp:S1186)

* refactor(sonar): remove dead stores (cpp:S1854)

Side effects (e.g. LISTLINE++) are kept.

* refactor(sonar): remove unused variables, captures and private fields (cpp:S1481, cpp:S1068)

* refactor(sonar): use structured bindings for pair access (cpp:S6005)

* refactor(sonar): use range-based loops and ranges algorithms (cpp:S5566)

* refactor(sonar): split chained assignments (cpp:S1121)

* refactor(sonar): add default cases to switch statements (cpp:S3562)

* refactor(sonar): use std::size for array lengths (cpp:S7127)

* refactor(sonar): use std::ranges algorithms and std::erase(_if) (cpp:S6197)

* refactor(sonar): access static members through the class (cpp:S2209)

* refactor(sonar): add braces around nested if-else (cpp:S5261)

* refactor(sonar): avoid side effects inside typeid operands (cpp:S5279)

* refactor(sonar): drop top-level const from by-value return types (cpp:S5951)

* refactor(sonar): declare variables separately from their type definitions (cpp:S3646)

* refactor(sonar): declare loop counters in the for statement (cpp:S5955)

* refactor(sonar): rely on class template argument deduction (cpp:S6012)

* refactor(sonar): inherit base constructors instead of forwarding them (cpp:S5952)

* refactor(sonar): rename locals that shadow outer declarations (cpp:S1117)

Only local variables and definition parameters are renamed; shadowing
struct fields and enumerators in headers are left for a separate change.

* refactor(sonar): reduce enum qualification with using enum (cpp:S6177)

Applied only where no unqualified name in the block could be captured by
the introduced enumerators.

* refactor(sonar): mark converting constructors explicit (cpp:S1709)

sound_source and the gl::object conversion operators stay implicit; they
are relied upon by copy-list-initialisation and GL calls.

* refactor(sonar): initialise members in initialiser lists or declarations (cpp:S3230)

* refactor(sonar): make read-only local references and pointers const (cpp:S5350)

* refactor(sonar): take read-only pointer and reference parameters as const (cpp:S995)

TTrain command handlers keep their signature, it is fixed by the handler table.

* refactor(sonar): pass expensive-to-copy parameters by const reference (cpp:S1238)

Signatures declared in files touched by PR 206 (Driver.h, EU07.cpp) and
virtual overrides are left unchanged.

* refactor(sonar): use transparent comparators for string-keyed maps (cpp:S6045)

std::unordered_map instances and map types exposed in headers used by
other modules are left as they are.

* fix(sonar): do not use UI text as a printf format string (cpp:S5281)

Text lines containing '%' would otherwise be interpreted as format
specifiers by ImGui::TextColored.

* refactor(sonar): use std::bind_front for callbacks (cpp:S5995)

* refactor(sonar): drop const_cast on string literals passed to the Python C API (cpp:S859)

* refactor(sonar): take read-only string parameters as std::string_view (cpp:S6009)

The Windows messaging helpers keep std::string, they need c_str().

* refactor(sonar): make read-only global tables const (cpp:S5421)

Mutable global state (flags, timers, singletons) is left as is.

* refactor(sonar): replace single-case switch statements with if (cpp:S1301)

* refactor(sonar): format UUIDs and log timestamps with std::format (cpp:S6494, cpp:S5945)

* refactor(sonar): use std::array for local fixed-size arrays (cpp:S5945)

Arrays that are class members or part of headers are left unchanged.

* fix(sonar): test the bearing damage bit, not bit 0 (cpp:S872)

'DamageFlag & dtrain_bearing > 0' parsed as 'DamageFlag & (dtrain_bearing > 0)',
i.e. DamageFlag & 1, so bearing friction reacted to the wrong damage flag.

* refactor(sonar): assorted small fixes

- empty() instead of size() comparisons (cpp:S1155)
- member initialisers in declaration order (cpp:S3229)
- no redundant c_str() when a std::string is accepted (cpp:S7121)
- contains() on associative containers (cpp:S6171)
- const reference instead of a copying range-for (cpp:S6032)
- starts_with() for prefix checks (cpp:S6178)
- no std::move on temporaries (cpp:S5274)
- has_value() on std::optional (cpp:S7172)
- bool literals for bool members (cpp:S5820)
- inline only on the definition (cpp:S3548)
- explicit base access specifier (cpp:S5965)
- explicit element access instead of dereferencing an array (cpp:S7116)
- rely on the C++20 rewritten operator!= (cpp:S6186)

* refactor(sonar): more small fixes

- std::format instead of iostream manipulators in to_string/to_hex_str (cpp:S6495);
  output verified identical, negative hex values keep the unsigned form
- remove an empty compound statement (cpp:S108)
- drop an always-false unsigned < 0 branch (cpp:S1768)
- explicit lambda capture (cpp:S3608)
- std::make_unique (cpp:S5950)

* chore: strip stray carriage returns left in TTrain constructor comments

* fix: keep quantize() in its own value type

The S5276 change cast the result of the generic quantize<Type_>() to
unsigned int, which truncated float/double callers (shadow angle slider,
editor rotation snapping, AI speed control steps) and broke negative values.

* fix(sonar): use integer loop counters in segment sampling (cpp:S2193)

* refactor(sonar): clean up issues reported on PR 209

- remove locals left unused after the dead-store cleanup (cpp:S1481, cpp:S1854)
- unnamed unused parameter (cpp:S1172)
- single-use declarations moved into if init-statements (cpp:S6004)
- auto for casted initialisers (cpp:S5827)
- const references and pointers where nothing is modified (cpp:S5350)
- rename structured bindings shadowed by inner declarations (cpp:S1117)
This commit is contained in:
jerrrrycho
2026-10-11 13:22:33 +02:00
committed by GitHub
parent c26041f2e7
commit 6263fe539b
162 changed files with 4220 additions and 4598 deletions

View File

@@ -15,27 +15,33 @@ http://mozilla.org/MPL/2.0/.
void float4x4::deserialize_float32(std::istream &s)
{
for (size_t i = 0; i < 16; i++)
e[i] = sn_utils::ld_float32(s);
for (auto &elemententry : e)
elemententry = sn_utils::ld_float32(s);
}
void float4x4::deserialize_float64(std::istream &s)
{
for (size_t i = 0; i < 16; i++)
e[i] = (float)sn_utils::ld_float64(s);
for (auto &elemententry : e)
elemententry = (float)sn_utils::ld_float64(s);
}
void float4x4::serialize_float32(std::ostream &s)
void float4x4::serialize_float32(std::ostream &s) const
{
for (size_t i = 0; i < 16; i++)
sn_utils::ls_float32(s, e[i]);
for (auto &element : e)
sn_utils::ls_float32(s, element);
}
void float4x4::Quaternion(float4 *q)
void float4x4::Quaternion(float4 const *q)
{ // konwersja kwaternionu obrotu na macierz obrotu
float xx = q->x * q->x, yy = q->y * q->y, zz = q->z * q->z;
float xy = q->x * q->y, xz = q->x * q->z, yz = q->y * q->z;
float wx = q->w * q->x, wy = q->w * q->y, wz = q->w * q->z;
float xx = q->x * q->x;
float yy = q->y * q->y;
float zz = q->z * q->z;
float xy = q->x * q->y;
float xz = q->x * q->z;
float yz = q->y * q->z;
float wx = q->w * q->x;
float wy = q->w * q->y;
float wz = q->w * q->z;
e[0] = 1.0f - yy - yy - zz - zz;
e[1] = xy + xy + wz + wz;
e[2] = xz + xz - wy - wy;

View File

@@ -15,14 +15,11 @@ http://mozilla.org/MPL/2.0/.
class float3
{ // wapółrzędne wierchołka 3D o pojedynczej precyzji
public:
float x, y, z;
float3(void){};
float3(float a, float b, float c)
{
x = a;
y = b;
z = c;
};
float x;
float y;
float z;
float3() = default;
float3(float a, float b, float c) : x(a), y(b), z(c) {}
float Length() const;
float LengthSquared() const;
@@ -74,7 +71,11 @@ inline float3 SafeNormalize(const float3 &v)
auto const l = v.Length();
float3 retVal;
if (l == 0)
retVal.x = retVal.y = retVal.z = 0;
{
retVal.x = 0;
retVal.y = 0;
retVal.z = 0;
}
else
retVal = v / l;
return retVal;
@@ -96,26 +97,19 @@ inline float3 Interpolate( float3 const &First, float3 const &Second, float cons
class float4
{ // kwaternion obrotu
public:
float x, y, z, w;
float4()
{
x = y = z = 0.f;
w = 1.f;
};
float4(float a, float b, float c, float d)
{
x = a;
y = b;
z = c;
w = d;
};
float x;
float y;
float z;
float w;
float4() : x(0.f), y(0.f), z(0.f), w(1.f) {}
float4(float a, float b, float c, float d) : x(a), y(b), z(c), w(d) {}
float inline LengthSquared() const
{
return x * x + y * y + z * z + w * w;
};
float inline Length() const
{
return sqrt(x * x + y * y + z * z + w * w);
return static_cast<float>(sqrt(x * x + y * y + z * z + w * w));
};
};
inline float4 operator*(const float4 &q1, const float4 &q2)
@@ -177,7 +171,8 @@ inline float4 Slerp(const float4 &q0, const float4 &q1, float t)
new_q1.w = -new_q1.w;
cosOmega = -cosOmega;
}
float k0, k1;
float k0;
float k1;
if (cosOmega > 0.9999f)
{ // jeśli jesteśmy z (t) na maksimum kosinusa, to tam prawie liniowo jest
k0 = 1.0f - t;
@@ -188,8 +183,8 @@ inline float4 Slerp(const float4 &q0, const float4 &q1, float t)
auto const sinOmega = std::sqrt(1.0f - cosOmega * cosOmega); // sinus z jedynki tryg.
auto const omega = std::atan2(sinOmega, cosOmega); // wyznaczenie kąta
auto const oneOverSinOmega = 1.0f / sinOmega; // odwrotność sinusa, bo sinus w mianowniku
k0 = sin((1.0f - t) * omega) * oneOverSinOmega;
k1 = sin(t * omega) * oneOverSinOmega;
k0 = static_cast<float>(sin((1.0f - t) * omega) * oneOverSinOmega);
k1 = static_cast<float>(sin(t * omega) * oneOverSinOmega);
}
return float4(q0.x * k0 + new_q1.x * k1, q0.y * k0 + new_q1.y * k1, q0.z * k0 + new_q1.z * k1,
q0.w * k0 + new_q1.w * k1);
@@ -200,7 +195,8 @@ struct float8
public:
float3 Point;
float3 Normal;
float tu, tv;
float tu;
float tv;
};
class float4x4
@@ -210,9 +206,9 @@ public:
void deserialize_float32(std::istream&);
void deserialize_float64(std::istream&);
void serialize_float32(std::ostream&);
float4x4(void){};
float4x4(const float f[16])
void serialize_float32(std::ostream&) const;
float4x4() = default;
explicit float4x4(const float f[16])
{
for (int i = 0; i < 16; ++i)
e[i] = f[i];
@@ -227,9 +223,12 @@ public:
}
void Identity()
{
for (int i = 0; i < 16; ++i)
e[i] = 0;
e[0] = e[5] = e[10] = e[15] = 1.0f;
for (auto &element : e)
element = 0;
e[0] = 1.0f;
e[5] = 1.0f;
e[10] = 1.0f;
e[15] = 1.0f;
}
const float *operator[](int i) const
{
@@ -246,15 +245,15 @@ public:
e[i + 2] = f; // zamiana Y i Z
}
};
inline float4x4 &Rotation(float const angle, float3 const &axis);
inline bool IdentityIs()
float4x4 &Rotation(float const angle, float3 const &axis);
inline bool IdentityIs() const
{ // sprawdzenie jednostkowości
for (int i = 0; i < 16; ++i)
if (e[i] != (i % 5 ? 0.0 : 1.0)) // jedynki tylko na 0, 5, 10 i 15
return false;
return true;
}
void Quaternion(float4 *q);
void Quaternion(float4 const *q);
inline float3 *TranslationGet()
{
return (float3 *)(e + 12);
@@ -345,10 +344,22 @@ inline float Det3x3(float a1, float a2, float a3, float b1, float b2, float b3,
inline
float Det(const float4x4 &m)
{ // obliczenie wyznacznika macierzy 4×4
float a1 = m[0][0], a2 = m[1][0], a3 = m[2][0], a4 = m[3][0];
float b1 = m[0][1], b2 = m[1][1], b3 = m[2][1], b4 = m[3][1];
float c1 = m[0][2], c2 = m[1][2], c3 = m[2][2], c4 = m[3][2];
float d1 = m[0][3], d2 = m[1][3], d3 = m[2][3], d4 = m[3][3];
float a1 = m[0][0];
float a2 = m[1][0];
float a3 = m[2][0];
float a4 = m[3][0];
float b1 = m[0][1];
float b2 = m[1][1];
float b3 = m[2][1];
float b4 = m[3][1];
float c1 = m[0][2];
float c2 = m[1][2];
float c3 = m[2][2];
float c4 = m[3][2];
float d1 = m[0][3];
float d2 = m[1][3];
float d3 = m[2][3];
float d4 = m[3][3];
return +a1 * Det3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4) -
b1 * Det3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4) +
c1 * Det3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4) -

View File

@@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "utilities/Logs.h"
#include <format>
#include "utilities/Globals.h"
#include "winheaders.h"
#include "utilities/utilities.h"
@@ -19,9 +21,8 @@ http://mozilla.org/MPL/2.0/.
std::ofstream output; // standardowy "log.txt", można go wyłączyć
std::ofstream errors; // lista błędów "errors.txt", zawsze działa
std::ofstream comms; // lista komunikatow "comms.txt", można go wyłączyć
char logbuffer[ 256 ];
char endstring[10] = "\n";
char const endstring[10] = "\n";
std::deque<std::string> log_scrollback;
@@ -33,30 +34,26 @@ std::string filename_date() {
clock_gettime(CLOCK_REALTIME, &ts);
std::tm const tm = local_tm(ts.tv_sec);
std::tm const *tms = &tm;
st.wYear = tms->tm_year;
st.wMonth = tms->tm_mon;
st.wDayOfWeek = tms->tm_wday;
st.wDay = tms->tm_mday;
st.wHour = tms->tm_hour;
st.wMinute = tms->tm_min;
st.wSecond = tms->tm_sec;
st.wMilliseconds = ts.tv_nsec / 1000000;
st.wYear = static_cast<uint16_t>(tms->tm_year);
st.wMonth = static_cast<uint16_t>(tms->tm_mon);
st.wDayOfWeek = static_cast<uint16_t>(tms->tm_wday);
st.wDay = static_cast<uint16_t>(tms->tm_mday);
st.wHour = static_cast<uint16_t>(tms->tm_hour);
st.wMinute = static_cast<uint16_t>(tms->tm_min);
st.wSecond = static_cast<uint16_t>(tms->tm_sec);
st.wMilliseconds = static_cast<uint16_t>(ts.tv_nsec / 1000000);
#elif _WIN32
::GetLocalTime( &st );
#endif
std::snprintf(
logbuffer,
sizeof(logbuffer),
"%d%02d%02d_%02d%02d%03d",
return std::format(
"{}{:02}{:02}_{:02}{:02}{:03}",
st.wYear,
st.wMonth,
st.wDay,
st.wHour,
st.wMinute,
st.wMilliseconds);
return std::string( logbuffer );
}
std::string filename_scenery() {
@@ -174,8 +171,8 @@ void WriteLog(std::string_view str, logtype type, bool isError)
const auto message = FormatLogMessage(str);
std::lock_guard<std::mutex> lock(logMutex);
InfoStack.push_back({message, isError});
std::scoped_lock lock(logMutex);
InfoStack.emplace_back(message, isError);
}
void ErrorLog(std::string_view str, logtype type)
@@ -185,7 +182,7 @@ void ErrorLog(std::string_view str, logtype type)
const auto message = FormatLogMessage(str);
std::lock_guard<std::mutex> lock(logMutex);
std::scoped_lock lock(logMutex);
ErrorStack.push_back(message);
}
@@ -206,14 +203,14 @@ void ErrorLog(const char* str, logtype type)
}
void Error(const std::string &asMessage, bool box)
void Error(const std::string &asMessage, bool /*box*/)
{
// if (box)
// MessageBox(NULL, asMessage.c_str(), string("EU07 " + Global.asRelease).c_str(), MB_OK);
ErrorLog(asMessage.c_str());
ErrorLog(asMessage);
}
void Error(const char *&asMessage, bool box)
void Error(const char *&asMessage, bool /*box*/)
{
// if (box)
// MessageBox(NULL, asMessage, string("EU07 " + Global.asRelease).c_str(), MB_OK);

View File

@@ -16,7 +16,8 @@ namespace Timer {
subsystem_stopwatches subsystem;
double DeltaTime = 0.0, DeltaRenderTime = 0.0;
double DeltaTime = 0.0;
double DeltaRenderTime = 0.0;
double fFPS{ 0.0f };
double fLastTime{ 0.0f };
DWORD dwFrames{ 0 };
@@ -59,7 +60,9 @@ void ResetTimers()
DeltaRenderTime = 0.0;
}
uint64_t fr, count, oldCount;
uint64_t fr;
uint64_t count;
uint64_t oldCount;
void UpdateTimers(bool pause)
{
@@ -92,7 +95,7 @@ void UpdateTimers(bool pause)
oldCount = count;
// Keep track of the time lapse and frame count
#if __unix__
double fTime = (double)(count / 1000000000);
auto fTime = (double)(count / 1000000000);
#elif _WIN32_WINNT >= _WIN32_WINNT_VISTA
double fTime = ::GetTickCount64() * 0.001f; // Get current time in seconds
#elif _WIN32

View File

@@ -35,7 +35,7 @@ public:
std::chrono::duration<float, std::milli>
stop() {
m_last = std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::steady_clock::now() - m_start );
m_accumulator = 0.95f * m_accumulator + m_last.count() / 1000.f;
m_accumulator = 0.95f * m_accumulator + static_cast<float>(m_last.count()) / 1000.f;
return m_last; }
float
average() const {

View File

@@ -59,10 +59,10 @@ RGBtoHSV( glm::vec3 const &RGB ) {
else
hsv.x = 4.f + ( RGB.r - RGB.g ) / delta; // between magenta & cyan
hsv.x *= 60.0; // degrees
hsv.x *= 60.0f; // degrees
if( hsv.x < 0.0 )
hsv.x += 360.0;
hsv.x += 360.0f;
return hsv;
}
@@ -81,9 +81,9 @@ HSVtoRGB( glm::vec3 const &HSV ) {
}
float hh = HSV.x;
if( hh >= 360.0 ) hh = 0.0;
hh /= 60.0;
int const i = (int)hh;
float const ff = hh - i;
hh /= 60.0f;
auto const i = (int)hh;
float const ff = hh - static_cast<float>(i);
float const p = HSV.z * ( 1.f - HSV.y );
float const q = HSV.z * ( 1.f - HSV.y * ff );
float const t = HSV.z * ( 1.f - HSV.y * (1.f - ff) );

View File

@@ -27,12 +27,13 @@ enum class comparison_pass {
template <typename Type_>
bool compare( Type_ const Left, Type_ const Right, comparison_operator const Operator ) {
switch( Operator ) {
case comparison_operator::equal: { return Left == Right; }
case comparison_operator::not_equal: { return Left != Right; }
case comparison_operator::lt: { return Left < Right; }
case comparison_operator::gt: { return Left > Right; }
case comparison_operator::lt_eq: { return Left <= Right; }
case comparison_operator::gt_eq: { return Left >= Right; }
using enum comparison_operator;
case equal: { return Left == Right; }
case not_equal: { return Left != Right; }
case lt: { return Left < Right; }
case gt: { return Left > Right; }
case lt_eq: { return Left <= Right; }
case gt_eq: { return Left >= Right; }
default: { return false; }
}
}
@@ -41,37 +42,40 @@ inline
std::string
to_string( comparison_operator const Operator ) {
switch( Operator ) {
case comparison_operator::equal: { return "=="; }
case comparison_operator::not_equal: { return "!="; }
case comparison_operator::lt: { return "<"; }
case comparison_operator::gt: { return ">"; }
case comparison_operator::lt_eq: { return "<="; }
case comparison_operator::gt_eq: { return ">"; }
using enum comparison_operator;
case equal: { return "=="; }
case not_equal: { return "!="; }
case lt: { return "<"; }
case gt: { return ">"; }
case lt_eq: { return "<="; }
case gt_eq: { return ">"; }
default: { return "??"; }
}
}
inline
comparison_pass
comparison_pass_from_string( std::string const Input ) {
if( Input == "all" ) { return comparison_pass::all; }
else if( Input == "any" ) { return comparison_pass::any; }
else if( Input == "none" ) { return comparison_pass::none; }
comparison_pass_from_string( std::string const &Input ) {
using enum comparison_pass;
if( Input == "all" ) { return all; }
else if( Input == "any" ) { return any; }
else if( Input == "none" ) { return none; }
return comparison_pass::all; // legacy default
return all; // legacy default
}
inline
comparison_operator
comparison_operator_from_string( std::string const Input ) {
if( Input == "==" ) { return comparison_operator::equal; }
else if( Input == "!=" ) { return comparison_operator::not_equal; }
else if( Input == "<" ) { return comparison_operator::lt; }
else if( Input == ">" ) { return comparison_operator::gt; }
else if( Input == "<=" ) { return comparison_operator::lt_eq; }
else if( Input == ">=" ) { return comparison_operator::gt_eq; }
comparison_operator_from_string( std::string const &Input ) {
using enum comparison_operator;
if( Input == "==" ) { return equal; }
else if( Input == "!=" ) { return not_equal; }
else if( Input == "<" ) { return lt; }
else if( Input == ">" ) { return gt; }
else if( Input == "<=" ) { return lt_eq; }
else if( Input == ">=" ) { return gt_eq; }
return comparison_operator::equal; // legacy default
return equal; // legacy default
}
//---------------------------------------------------------------------------

View File

@@ -23,11 +23,11 @@ struct dictionary_source {
keyvaluepair_sequence<std::vector<glm::vec2>> vec2_lists;
// constructors
dictionary_source() = default;
dictionary_source( std::string const &Input );
explicit dictionary_source( std::string const &Input );
// methods
inline void insert( std::string const &Key, double const Value ) { floats.emplace_back( Key, Value ); }
inline void insert( std::string const &Key, int const Value ) { integers.emplace_back( Key, Value ); }
inline void insert( std::string const &Key, bool const Value ) { bools.emplace_back( Key, Value ); }
inline void insert( std::string const &Key, std::string const Value ) { strings.emplace_back( Key, Value ); }
inline void insert( std::string const &Key, std::vector<glm::vec2> const Value ) { vec2_lists.emplace_back( Key, Value ); }
inline void insert( std::string const &Key, std::string const &Value ) { strings.emplace_back( Key, Value ); }
inline void insert( std::string const &Key, std::vector<glm::vec2> const &Value ) { vec2_lists.emplace_back( Key, Value ); }
};

View File

@@ -2,19 +2,16 @@
#include "utilities/headtrack.h"
#include "utilities/Globals.h"
headtrack::headtrack()
{
}
headtrack::headtrack() = default;
void headtrack::find_joy() {
for (size_t i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++) {
if (!glfwJoystickPresent(i))
if (!glfwJoystickPresent(static_cast<int>(i)))
continue;
std::string name(glfwGetJoystickName(i));
std::string name(glfwGetJoystickName(static_cast<int>(i)));
if (name == Global.headtrack_conf.joy) {
joy_id = i;
joy_id = static_cast<int>(i);
return;
}
}
@@ -22,7 +19,7 @@ void headtrack::find_joy() {
joy_id = -1;
}
float headtrack::get_axis(const float *data, int count, int axis, float mul) {
float headtrack::get_axis(const float *data, int count, int axis, float mul) const {
if (axis < 0)
return 0.0f;
if (axis >= count)

View File

@@ -5,7 +5,7 @@ class headtrack
int joy_id = -1;
void find_joy();
float get_axis(const float *data, int count, int axis, float mul);
float get_axis(const float *data, int count, int axis, float mul) const;
public:
headtrack();

View File

@@ -28,7 +28,8 @@ motiontelemetry::motiontelemetry()
throw std::runtime_error("failed to init winsock");
#endif
struct addrinfo hints, *res;
struct addrinfo hints;
struct addrinfo *res;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
@@ -72,9 +73,9 @@ void motiontelemetry::update()
double dt = Timer::GetDeltaTime();
glm::dvec3 front = t->Dynamic()->VectorFront();
glm::dvec3 frontvector = t->Dynamic()->VectorFront();
glm::dvec3 up = t->Dynamic()->VectorUp();
glm::dvec3 left = t->Dynamic()->VectorLeft();
glm::dvec3 leftvector = t->Dynamic()->VectorLeft();
glm::dvec3 pos = t->Dynamic()->GetPosition();
glm::dvec3 vel = (pos - last_pos) / dt;
@@ -85,18 +86,18 @@ void motiontelemetry::update()
if (conf.includegravity)
{
glm::dvec3 gravity(0.0, 9.81, 0.0);
local_acc = glm::dvec3(-glm::dot(gravity, left), glm::dot(gravity, up), glm::dot(gravity, front));
local_acc = glm::dvec3(-glm::dot(gravity, leftvector), glm::dot(gravity, up), glm::dot(gravity, frontvector));
}
if (conf.latposbased)
local_acc.x -= glm::dot(acc, left);
local_acc.x -= glm::dot(acc, leftvector);
else
local_acc.x -= t->Occupied()->AccN;
local_acc.y += glm::dot(acc, up) + t->Occupied()->AccVert * conf.axlebumpscale;
if (conf.fwdposbased)
local_acc.z += glm::dot(acc, front);
local_acc.z += glm::dot(acc, frontvector);
else
local_acc.z += t->Occupied()->AccSVBased;
@@ -105,16 +106,16 @@ void motiontelemetry::update()
// roll calculation, maybe too complicated?
// transform to left-handed
front.z *= -1;
frontvector.z *= -1;
up.z *= -1;
// make sure that vectors are orthonormal
glm::dvec3 oright = glm::normalize(glm::cross(up, front));
glm::dvec3 oup = glm::cross(front, oright);
glm::dvec3 oright = glm::normalize(glm::cross(up, frontvector));
glm::dvec3 oup = glm::cross(frontvector, oright);
// right and up vector without roll
glm::dvec3 right0 = glm::normalize(glm::cross(glm::dvec3(0.0, 1.0, 0.0), front));
glm::dvec3 up0 = glm::cross(front, right0);
glm::dvec3 right0 = glm::normalize(glm::cross(glm::dvec3(0.0, 1.0, 0.0), frontvector));
glm::dvec3 up0 = glm::cross(frontvector, right0);
double cosroll = glm::dot(up0, oup);
double sinroll;
@@ -126,7 +127,7 @@ void motiontelemetry::update()
else
sinroll = (up0.z * cosroll - oup.z) / right0.z;
glm::dvec3 rot(asin(-front.y), atan2(front.x, front.z), asin(sinroll));
glm::dvec3 rot(asin(-frontvector.y), atan2(frontvector.x, frontvector.z), asin(sinroll));
double velocity = t->Occupied()->V;
double yaw_vel = (rot.y - last_yaw) / dt;
@@ -144,18 +145,18 @@ void motiontelemetry::update()
rot *= -1;
}
float buffer[12] = { 0 };
buffer[0] = Timer::GetTime();
buffer[1] = velocity;
buffer[2] = local_acc.y;
buffer[3] = local_acc.z;
buffer[4] = local_acc.x;
buffer[5] = glm::degrees(rot.x);
buffer[6] = glm::degrees(rot.z);
buffer[7] = glm::degrees(rot.y);
buffer[8] = yaw_vel;
std::array<float, 12> buffer{};
buffer[0] = static_cast<float>(Timer::GetTime());
buffer[1] = static_cast<float>(velocity);
buffer[2] = static_cast<float>(local_acc.y);
buffer[3] = static_cast<float>(local_acc.z);
buffer[4] = static_cast<float>(local_acc.x);
buffer[5] = static_cast<float>(glm::degrees(rot.x));
buffer[6] = static_cast<float>(glm::degrees(rot.z));
buffer[7] = static_cast<float>(glm::degrees(rot.y));
buffer[8] = static_cast<float>(yaw_vel);
buffer[9] = 1.0f;
if (send(sock, (char*)buffer, sizeof(buffer), 0) == -1)
if (send(sock, reinterpret_cast<char const *>(buffer.data()), sizeof(buffer), 0) == -1)
WriteLog("motiontelemetry: socket send failed");
}

View File

@@ -10,7 +10,7 @@
#include "simulation/simulationtime.h"
#include "application/application.h"
const char* uart_baudrates_list[] = {
const char* const uart_baudrates_list[] = {
"300",
"1200",
"2400",
@@ -28,7 +28,7 @@ const char* uart_baudrates_list[] = {
"2000000"
};
const size_t uart_baudrates_list_num = sizeof(uart_baudrates_list) / sizeof(uart_baudrates_list[0]);
const size_t uart_baudrates_list_num = std::size(uart_baudrates_list);
void uart_status::reset_stats() {
packets_sent = 0;
@@ -193,10 +193,9 @@ uart_input::recall_bindings() {
m_inputbindings.clear();
std::string filePath = "eu07_input-uart.ini";
fs::path appPath = user_config_path("eu07_input-uart.ini");
if (!appPath.empty() && fs::exists(appPath))
if (fs::path appPath = user_config_path("eu07_input-uart.ini"); !appPath.empty() && fs::exists(appPath))
filePath = appPath.string();
cParser bindingparser(filePath.c_str(), cParser::buffer_FILE);
cParser bindingparser(filePath, cParser::buffer_FILE);
if (false == bindingparser.ok())
{
return false;
@@ -206,7 +205,7 @@ uart_input::recall_bindings() {
std::unordered_map<std::string, user_command> nametocommandmap;
std::size_t commandid = 0;
for( auto const &description : simulation::Commands_descriptions ) {
nametocommandmap.emplace(
nametocommandmap.try_emplace(
description.name,
static_cast<user_command>( commandid ) );
++commandid;
@@ -275,7 +274,7 @@ void uart_input::poll()
/* handle baud change */
if(status->active_baud_index != status->selected_baud_index) {
status->baud = std::stoul(uart_baudrates_list[status->selected_baud_index]);
status->baud = static_cast<int>(std::stoul(uart_baudrates_list[status->selected_baud_index]));
status->active_baud_index = status->selected_baud_index;
status->reset_stats();
status->is_connected = false;
@@ -283,7 +282,7 @@ void uart_input::poll()
}
/* handle port change */
if(status->available_ports.size() > 0 && status->selected_port_index >= 0 && status->active_port_index != status->selected_port_index) {
if(!status->available_ports.empty() && status->selected_port_index >= 0 && status->active_port_index != status->selected_port_index) {
status->port_name = status->available_ports[status->selected_port_index];
status->active_port_index = status->selected_port_index;
status->reset_stats();
@@ -467,7 +466,7 @@ void uart_input::poll()
}
if( true == conf.trainenable ) {
// train brake
double const position { (float)( ( (uint16_t)buffer[ 8 ] | (uint16_t)buffer[9] << 8 ) - conf.mainbrakemin ) / ( conf.mainbrakemax - conf.mainbrakemin ) };
double const position { ( ( (uint16_t)buffer[ 8 ] | (uint16_t)buffer[9] << 8 ) - conf.mainbrakemin ) / ( conf.mainbrakemax - conf.mainbrakemin ) };
relay.post(
user_command::trainbrakeset,
position,
@@ -478,7 +477,7 @@ void uart_input::poll()
}
if( true == conf.localenable ) {
// independent brake
double const position { (float)( ( (uint16_t)buffer[ 10 ] | (uint16_t)buffer[11] << 8 ) - conf.localbrakemin ) / ( conf.localbrakemax - conf.localbrakemin ) };
double const position { ( ( (uint16_t)buffer[ 10 ] | (uint16_t)buffer[11] << 8 ) - conf.localbrakemin ) / ( conf.localbrakemax - conf.localbrakemin ) };
relay.post(
user_command::independentbrakeset,
position,
@@ -497,7 +496,7 @@ void uart_input::poll()
);
}
if( true == conf.radiovolumeenable ) {
int8_t requested_volume = static_cast<int8_t>((buffer[12] & 0xF0) >> 4);
auto requested_volume = static_cast<int8_t>((buffer[12] & 0xF0) >> 4);
relay.post(
user_command::radiovolumeset,
requested_volume == 0xF ? 1.0 : requested_volume * (1.0 / 15.0),
@@ -509,7 +508,7 @@ void uart_input::poll()
if (true == conf.dynamicenable)
{
// dynamic brake 8 bit
double const position{(float)(buffer[13] - conf.dynamicbrakemin) / (conf.dynamicbrakemax - conf.dynamicbrakemin)};
double const position{(buffer[13] - conf.dynamicbrakemin) / (conf.dynamicbrakemax - conf.dynamicbrakemin)};
relay.post(
user_command::dynamicbrakecontrollerset,
@@ -534,17 +533,17 @@ void uart_input::poll()
auto const trainstate = t->get_state();
SYSTEMTIME time = simulation::Time.data();
uint16_t tacho = Global.iPause ? 0 : trainstate.velocity * conf.tachoscale;
uint16_t tank_press = (uint16_t)std::min(conf.tankuart, trainstate.reservoir_pressure * 0.1f / conf.tankmax * conf.tankuart);
uint16_t pipe_press = (uint16_t)std::min(conf.pipeuart, trainstate.pipe_pressure * 0.1f / conf.pipemax * conf.pipeuart);
uint16_t brake_press = (uint16_t)std::min(conf.brakeuart, trainstate.brake_pressure * 0.1f / conf.brakemax * conf.brakeuart);
uint16_t pantograph_press = (uint16_t)std::min(conf.pantographuart, trainstate.pantograph_pressure * 0.1f / conf.pantographmax * conf.pantographuart );
uint16_t hv_voltage = (uint16_t)std::min(conf.hvuart, trainstate.hv_voltage / conf.hvmax * conf.hvuart);
uint16_t current1 = (uint16_t)std::min(conf.currentuart, trainstate.hv_current[0] / conf.currentmax * conf.currentuart);
uint16_t current2 = (uint16_t)std::min(conf.currentuart, trainstate.hv_current[1] / conf.currentmax * conf.currentuart);
uint16_t current3 = (uint16_t)std::min(conf.currentuart, trainstate.hv_current[2] / conf.currentmax * conf.currentuart);
uint32_t odometer = trainstate.distance * 10000.0;
uint16_t lv_voltage = (uint16_t)std::min( conf.lvuart, trainstate.lv_voltage / conf.lvmax * conf.lvuart );
uint16_t tacho = Global.iPause ? 0 : static_cast<uint16_t>(trainstate.velocity * conf.tachoscale);
auto tank_press = (uint16_t)std::min(conf.tankuart, trainstate.reservoir_pressure * 0.1f / conf.tankmax * conf.tankuart);
auto pipe_press = (uint16_t)std::min(conf.pipeuart, trainstate.pipe_pressure * 0.1f / conf.pipemax * conf.pipeuart);
auto brake_press = (uint16_t)std::min(conf.brakeuart, trainstate.brake_pressure * 0.1f / conf.brakemax * conf.brakeuart);
auto pantograph_press = (uint16_t)std::min(conf.pantographuart, trainstate.pantograph_pressure * 0.1f / conf.pantographmax * conf.pantographuart );
auto hv_voltage = (uint16_t)std::min(conf.hvuart, trainstate.hv_voltage / conf.hvmax * conf.hvuart);
auto current1 = (uint16_t)std::min(conf.currentuart, trainstate.hv_current[0] / conf.currentmax * conf.currentuart);
auto current2 = (uint16_t)std::min(conf.currentuart, trainstate.hv_current[1] / conf.currentmax * conf.currentuart);
auto current3 = (uint16_t)std::min(conf.currentuart, trainstate.hv_current[2] / conf.currentmax * conf.currentuart);
uint32_t odometer = static_cast<uint32_t>(trainstate.distance * 10000.0);
auto lv_voltage = (uint16_t)std::min( conf.lvuart, trainstate.lv_voltage / conf.lvmax * conf.lvuart );
if( trainstate.cab > 0 ) {
// NOTE: moving from a cab to engine room doesn't change cab indicator
m_trainstatecab = trainstate.cab - 1;

View File

@@ -3,7 +3,7 @@
#include <libserialport.h>
#include "input/command.h"
extern const char* uart_baudrates_list[];
extern const char* const uart_baudrates_list[];
extern const size_t uart_baudrates_list_num;
class uart_status {

View File

@@ -17,6 +17,7 @@ Copyright (C) 2007-2014 Maciej Cierniak
//#include <sys/stat.h>
#include <charconv>
#include <ranges>
#include <format>
//#ifndef WIN32
//#include <unistd.h>
//#endif
@@ -127,14 +128,14 @@ bool ClearFlag(int &Flag, int const Value)
double Random(double min, double max)
{
if (max < min) { std::swap(min, max); } // std::uniform_real_distribution requires min <= max (inverted bounds are UB)
std::uniform_real_distribution<double> dist(min, max);
std::uniform_real_distribution dist(min, max);
return dist(Global.random_engine);
}
int Random(int min, int max)
{
if (max < min) { std::swap(min, max); } // std::uniform_int_distribution requires min <= max (inverted bounds are UB)
std::uniform_int_distribution<int> dist(min, max);
std::uniform_int_distribution dist(min, max);
return dist(Global.random_engine);
}
@@ -178,7 +179,7 @@ std::uint32_t seed_of(std::string const &Text)
std::string generate_uuid_v4()
{
std::uniform_int_distribution<int> dist(0, 255);
std::uniform_int_distribution dist(0, 255);
std::array<uint8_t, 16> bytes;
for (auto &b : bytes)
@@ -188,22 +189,18 @@ std::string generate_uuid_v4()
bytes[6] = bytes[6] & 0x0F | 0x40;
bytes[8] = bytes[8] & 0x3F | 0x80;
char buf[37]; // 36 znaków + \0
std::snprintf(buf, sizeof(buf),
"%02x%02x%02x%02x-"
"%02x%02x-"
"%02x%02x-"
"%02x%02x-"
"%02x%02x%02x%02x%02x%02x",
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]);
return std::string(buf);
return std::format("{:02x}{:02x}{:02x}{:02x}-"
"{:02x}{:02x}-"
"{:02x}{:02x}-"
"{:02x}{:02x}-"
"{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]);
}
double LocalRandom(double a, double b)
{
if (b < a) { std::swap(a, b); } // std::uniform_real_distribution requires a <= b (inverted bounds are UB)
std::uniform_real_distribution<double> dist(a, b);
std::uniform_real_distribution dist(a, b);
return dist(Global.local_random_engine);
}
@@ -252,23 +249,18 @@ std::string to_string(int Value, int width)
std::string to_string(double Value, int precision)
{
std::ostringstream o;
o << std::fixed << std::setprecision(precision) << Value;
return std::move(o).str();
return std::format("{:.{}f}", Value, precision);
};
std::string to_string(double const Value, int const Precision, int const Width)
{
std::ostringstream o;
o << std::setw(Width) << std::fixed << std::setprecision(Precision) << Value;
return std::move(o).str();
return std::format("{:>{}.{}f}", Value, Width, Precision);
};
std::string to_hex_str(int const Value, int const Width)
{
std::ostringstream o;
o << "0x" << std::uppercase << std::setfill('0') << std::setw(Width) << std::hex << Value;
return o.str();
// iostreams print negative values in hex as their unsigned representation
return std::format("0x{:0{}X}", static_cast<unsigned int>(Value), Width);
};
std::string const fractionlabels[] = {U8(" "), U8("¹"), U8("²"), U8("³"), U8("⁴"), U8("⁵"), U8("⁶"), U8("⁷"), U8("⁸"), U8("⁹")};
@@ -297,7 +289,7 @@ std::string ToLower(std::string const &text)
{
auto lowercase{text};
std::transform(std::begin(text), std::end(text), std::begin(lowercase), [](unsigned char c) { return std::tolower(c); });
std::ranges::transform(text, std::begin(lowercase), [](unsigned char c) { return std::tolower(c); });
return lowercase;
}
@@ -305,7 +297,7 @@ std::string ToUpper(std::string const &text)
{
auto uppercase{text};
std::transform(std::begin(text), std::end(text), std::begin(uppercase), [](unsigned char c) { return std::toupper(c); });
std::ranges::transform(text, std::begin(uppercase), [](unsigned char c) { return std::toupper(c); });
return uppercase;
}
@@ -421,7 +413,7 @@ void win1250_to_utf32(std::string const &Text, std::u32string &Output)
}
// Ra: tymczasowe rozwiązanie kwestii zagranicznych (czeskich) napisów
char charsetconversiontable[] = "E?,?\"_++?%S<STZZ?`'\"\".--??s>stzz"
char const charsetconversiontable[] = "E?,?\"_++?%S<STZZ?`'\"\".--??s>stzz"
" ^^L$A|S^CS<--RZo±,l'uP.,as>L\"lz"
"RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTB"
"raaaalccceeeeiiddnnoooo-ruuuuyt?";
@@ -607,7 +599,7 @@ std::string deserialize_random_set(cParser &Input, char const *Break)
{
auto token{Input.getToken<std::string>(true, Break)};
std::replace(token.begin(), token.end(), '\\', '/');
std::ranges::replace(token, '\\', '/');
if (token != "[")
{
// simple case, single token
@@ -622,7 +614,7 @@ std::string deserialize_random_set(cParser &Input, char const *Break)
}
if (false == tokens.empty())
{
std::shuffle(std::begin(tokens), std::end(tokens), Global.random_engine);
std::ranges::shuffle(tokens, Global.random_engine);
return tokens.front();
}
else

View File

@@ -100,7 +100,7 @@ inline double LocalRandom(double b)
inline double BorlandTime()
{
auto timesinceepoch = std::time(nullptr);
return timesinceepoch / (24.0 * 60 * 60);
return static_cast<double>(timesinceepoch) / (24.0 * 60 * 60);
/*
// std alternative
auto timesinceepoch = std::chrono::system_clock::now().time_since_epoch();
@@ -176,8 +176,7 @@ inline std::string extract_value(std::string const &Key, std::string const &Inpu
// NOTE, HACK: the leading space allows to uniformly look for " variable=" substring
std::string const input{" " + Input};
std::string value;
auto lookup = input.find(" " + Key + "=");
if (lookup != std::string::npos)
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(' ');
@@ -315,7 +314,7 @@ template <typename T> T clamp_power_of_two(T Value, T const Min = T(1), T const
template <typename Type_> Type_ quantize(Type_ const Value, Type_ const Step)
{
return Step * std::round(Value / Step);
return static_cast<Type_>(Step * std::round(Value / Step));
}
template <typename T> T min_speed(T const Left, T const Right)
@@ -427,12 +426,12 @@ class condition_variable
// methods
void wait()
{
std::unique_lock<std::mutex> lock(m_mutex);
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<std::mutex> lock(m_mutex);
std::unique_lock lock(m_mutex);
m_condition.wait_for(lock, Time, [this]() { return m_spurious == false; });
}
void notify_one()
@@ -447,7 +446,7 @@ class condition_variable
}
void spurious(bool const Spurious)
{
std::lock_guard<std::mutex> lock(m_mutex);
std::scoped_lock lock(m_mutex);
m_spurious = Spurious;
}