diff --git a/Console.h b/Console.h index e99beb4b..1f7f9e2b 100644 --- a/Console.h +++ b/Console.h @@ -20,7 +20,8 @@ class TLPT; class TKeyTrans { // przekodowanie kodu naciśnięcia i zwolnienia klawisza public: - short int iDown, iUp; + short int iDown; + short int iUp; }; class Console diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index accbbbaa..228834b4 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -764,7 +764,7 @@ enum class TLocalBrake HydraulicBrake }; /// Brake delay parameter table (apply/release for passenger and freight). -typedef double TBrakeDelayTable[4]; +using TBrakeDelayTable = double[4]; /// One row of the brake pressure / pipe pressure / flow-speed table for a brake handle position. struct TBrakePressure @@ -780,7 +780,7 @@ struct TBrakePressure }; /// Brake pressure table indexed by handle position. -typedef std::map TBrakePressureTable; +using TBrakePressureTable = std::map; /// Engine / drive type. enum class TEngineType @@ -989,11 +989,11 @@ struct TTransducer struct TPowerParameters { /// Maximum source voltage [V]. - double MaxVoltage; + double MaxVoltage{0.0}; /// Maximum source current [A]. - double MaxCurrent; + double MaxCurrent{0.0}; /// Internal resistance [Ω]. - double IntR; + double IntR{0.001}; /// Type of source (selects which union member is meaningful). TPowerSource SourceType; union @@ -1028,10 +1028,7 @@ struct TPowerParameters }; }; inline TPowerParameters() - { - MaxVoltage = 0.0; - MaxCurrent = 0.0; - IntR = 0.001; + { SourceType = TPowerSource::NotDefined; PowerType = TPowerType::NoPower; RPowerCable.PowerTrans = TPowerType::NoPower; @@ -1048,7 +1045,7 @@ struct TScheme bool AutoSwitch = false; /*czy dana pozycja nastawniana jest recznie czy autom.*/ int ScndAct = 0; /*jesli ma bocznik w nastawniku, to ktory bocznik na ktorej pozycji*/ }; -typedef TScheme TSchemeTable[ResArraySize + 1]; /*tablica rezystorow rozr.*/ +using TSchemeTable = TScheme[ResArraySize + 1]; /*tablica rezystorow rozr.*/ struct TDEScheme { double RPM = 0.0; /*obroty diesla*/ @@ -1056,13 +1053,13 @@ struct TDEScheme double Umax = 0.0; /*napiecie maksymalne*/ double Imax = 0.0; /*prad maksymalny*/ }; -typedef TDEScheme TDESchemeTable[33]; /*tablica WWList dla silnikow spalinowych*/ +using TDESchemeTable = TDEScheme[33]; /*tablica WWList dla silnikow spalinowych*/ struct TFFScheme { double v = 0.0; // parametr wejsciowy double freq = 0.0; // wyjscie: czestotliwosc falownika }; -typedef TFFScheme TFFSchemeTable[33]; +using TFFSchemeTable = TFFScheme[33]; struct TWiperScheme { @@ -1071,7 +1068,7 @@ struct TWiperScheme double interval = 0.0; // interwal pracy wycieraczki double outBackDelay = 0.0; // czas po jakim wycieraczka zacznie wracac z konca do poczatku }; -typedef TWiperScheme TWiperSchemeTable[16]; +using TWiperSchemeTable = TWiperScheme[16]; struct TShuntScheme { @@ -1080,33 +1077,23 @@ struct TShuntScheme double Pmin = 0.0; double Pmax = 0.0; }; -typedef TShuntScheme TShuntSchemeTable[33]; +using TShuntSchemeTable = TShuntScheme[33]; struct TMPTRelay { /*lista przekaznikow bocznikowania*/ double Iup = 0.0; double Idown = 0.0; }; -typedef TMPTRelay TMPTRelayTable[MotorParametersArraySize + 1]; // indexed like MotorParam +using TMPTRelayTable = TMPTRelay[MotorParametersArraySize + 1]; // indexed like MotorParam struct TMotorParameters { - double mfi; - double mIsat; - double mfi0; // aproksymacja M(I) silnika} {dla dizla mIsat=przekladnia biegu - double fi; - double Isat; - double fi0; // aproksymacja E(n)=fi*n} {dla dizla fi, mfi: predkosci przelozenia biegu <-> - bool AutoSwitch; - TMotorParameters() - { - mfi = 0.0; - mIsat = 0.0; - mfi0 = 0.0; - fi = 0.0; - Isat = 0.0; - fi0 = 0.0; - AutoSwitch = false; - } + double mfi{0.0}; + double mIsat{0.0}; + double mfi0{0.0}; // aproksymacja M(I) silnika} {dla dizla mIsat=przekladnia biegu + double fi{0.0}; + double Isat{0.0}; + double fi0{0.0}; // aproksymacja E(n)=fi*n} {dla dizla fi, mfi: predkosci przelozenia biegu <-> + bool AutoSwitch{false}; }; struct TUniversalCtrl @@ -1240,7 +1227,7 @@ struct TCoupling { return adapter_type != TCouplerType::NoCoupler; } - inline TCouplerType const type() const + inline TCouplerType type() const { return adapter_type == TCouplerType::NoCoupler ? CouplerType : adapter_type; } @@ -1465,7 +1452,8 @@ class TMoverParameters { float temp_min{-1}; // lowest accepted temperature float temp_max{-1}; // highest accepted temperature - } config; + }; + heater_config_t config; // ld inputs bool breaker{false}; // device is allowed to operate bool is_enabled{false}; // device is requested to operate @@ -1500,12 +1488,17 @@ class TMoverParameters float temp_cooling{-1}; // active cooling activation point float temp_flow{-1}; // fluid flow activation point bool shutters{false}; // the radiator has shutters to assist the cooling - } config; + }; + circuit_config_t config; bool is_cold{false}; // fluid is too cold bool is_warm{false}; // fluid is too hot bool is_hot{false}; // fluid temperature crossed cooling threshold bool is_flowing{false}; // fluid is being pushed through the circuit - } water, water_aux, oil, engine; + }; + fluid_circuit_t water; + fluid_circuit_t water_aux; + fluid_circuit_t oil; + fluid_circuit_t engine; // output, state of affected devices bool PA{false}; // malfunction flag float rpmw{0.0}; // current main circuit fan revolutions @@ -1889,9 +1882,9 @@ class TMoverParameters double MED_Vmin = 0; // predkosc minimalna dla obliczen chwilowej sily hamowania EP w MED double MED_Vref = 0; // predkosc referencyjna dla obliczen dostepnej sily hamowania EP w MED double MED_amax{9.81}; // maksymalne opoznienie hamowania sluzbowego MED - bool MED_EPVC = 0; // czy korekcja sily hamowania EP, gdy nie ma dostepnego ED + bool MED_EPVC = false; // czy korekcja sily hamowania EP, gdy nie ma dostepnego ED double MED_EPVC_Time = 7; // czas korekcji sily hamowania EP, gdy nie ma dostepnego ED - bool MED_Ncor = 0; // czy korekcja sily hamowania z uwzglednieniem nacisku + bool MED_Ncor = false; // czy korekcja sily hamowania z uwzglednieniem nacisku double MED_MinBrakeReqED = 0; // minimalne zadanie sily hamowania uruchamiajace ED - ponizej tylko EP double MED_FrED_factor = 1; // mnoznik sily hamowania ED do korekty blendingu double MED_ED_Delay1 = 0; // opoznienie wdrazania hamowania ED (pierwszy raz) @@ -2099,7 +2092,7 @@ class TMoverParameters int CabActive = 0; // numer kabiny, z której jest sterowanie: 1 lub -1; w przeciwnym razie brak sterowania - rozrzad int CabOccupied = 0; // numer kabiny, w ktorej jest obsada (zwykle jedna na skład) // TODO: move to TController bool CabMaster = false; // czy pojazd jest nadrzędny w składzie - inline bool IsCabMaster() + inline bool IsCabMaster() const { return CabActive == CabOccupied && CabMaster; } // czy aktualna kabina jest na pewno tą, z której można sterować @@ -2294,8 +2287,7 @@ class TMoverParameters bool AIHintPantUpIfIdle{true}; // whether raise both pantographs if idling for a while double AIHintLocalBrakeAccFactor{1.05}; // suggested acceleration weight for local brake operation - public: - TMoverParameters(double VelInitial, std::string TypeNameInit, std::string NameInit, int Cab); + TMoverParameters(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab); // obsługa sprzęgów static double CouplerDist(TMoverParameters const *Left, TMoverParameters const *Right); static double Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2); @@ -2307,7 +2299,7 @@ class TMoverParameters bool DirectionForward(); bool DirectionBackward(void); /*! kierunek ruchu*/ bool EIMDirectionChangeAllow(void) const; - inline double IsVehicleEIMBrakingFactor() + inline double IsVehicleEIMBrakingFactor() const { return DynamicBrakeFlag && ResistorsFlag ? 0.0 : eimv[eimv_Ipoj] < 0 ? -1.0 : 1.0; } @@ -2319,32 +2311,32 @@ class TMoverParameters bool CurrentSwitch(bool const State); bool IsMotorOverloadRelayHighThresholdOn() const; void UpdateBatteryVoltage(double dt); - double ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam &Track, TTractionParam &ElectricTraction, TLocation const &NewLoc, + double ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot); // oblicza przesuniecie pojazdu double FastComputeMovement(double dt, const TTrackShape &Shape, TTrackParam &Track, TLocation const &NewLoc, TRotation const &NewRot); // oblicza przesuniecie pojazdu - wersja zoptymalizowana void compute_movement_(double const Deltatime); - double ShowEngineRotation(int VehN); + double ShowEngineRotation(int VehN) const; // Q ******************************************************************************************* double GetTrainsetVoltage(int const Coupling = coupling::heating | coupling::highvoltage) const; double GetTrainsetHighVoltage() const; bool switch_physics(bool const State); - double LocalBrakeRatio(void); - double ManualBrakeRatio(void); - double PipeRatio(void); /*ile napelniac*/ - double RealPipeRatio(void); /*jak szybko*/ + double LocalBrakeRatio(void) const; + double ManualBrakeRatio(void) const; + double PipeRatio(void) const; /*ile napelniac*/ + double RealPipeRatio(void) const; /*jak szybko*/ double BrakeVP(void) const; double EngineRPMRatio() const; // returns current engine revolutions as percentage of max engine revolutions, in range 0-1 double EngineIdleRPM() const; double EngineMaxRPM() const; /*! przesylanie komend sterujacych*/ - bool SendCtrlToNext(std::string const CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype = coupling::control); - bool SetInternalCommand(std::string NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); - double GetExternalCommand(std::string &Command); - bool RunCommand(std::string Command, double CValue1, double CValue2, int const Couplertype = coupling::control); + bool SendCtrlToNext(std::string const &CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype = coupling::control); + bool SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); + double GetExternalCommand(std::string &Command) const; + bool RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype = coupling::control); bool RunInternalCommand(); - void PutCommand(std::string NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation); + void PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation); bool CabActivisation(bool const Enforce = false); bool CabDeactivisation(bool const Enforce = false); bool CabActivisationAuto(bool const Enforce = false); @@ -2363,7 +2355,7 @@ class TMoverParameters /*! pomocniczy nastawnik:*/ bool IncScndCtrl(int CtrlSpeed); bool DecScndCtrl(int CtrlSpeed); - int GetVirtualScndPos(); + int GetVirtualScndPos() const; bool IsScndCtrlNoPowerPos() const; bool IsScndCtrlMaxPowerPos() const; @@ -2430,7 +2422,7 @@ class TMoverParameters double TractionForce(double dt); double FrictionForce() const; double BrakeForceR(double ratio, double velocity); - double BrakeForceP(double press, double velocity); + double BrakeForceP(double press, double velocity) const; double BrakeForce(const TTrackParam &Track); double CouplerForce(int const End, double dt); void CollisionDetect(int const End, double const dt); @@ -2488,8 +2480,8 @@ class TMoverParameters /*funkcje uzalezniajace sile pociagowa od predkosci: v2n, n2r, current, momentum*/ double v2n(void); double Current(double n, double U); - double Momentum(double I); - double MomentumF(double I, double Iw, int SCP); + double Momentum(double I) const; + double MomentumF(double I, double Iw, int SCP) const; bool CutOffEngine(void); // odlaczenie udszkodzonych silnikow /*funkcje automatycznego rozruchu np EN57*/ @@ -2526,7 +2518,7 @@ class TMoverParameters /* funckje dla wagonow*/ bool AssignLoad(std::string const &Name, float const Amount = 0.f); - bool LoadingDone(double LSpeed, std::string const &Loadname); + bool LoadingDone(double LSpeed, std::string_view Loadname); bool PermitDoors(side const Door, bool const State = true, range_t const Notify = range_t::consist); void PermitDoors_(side const Door, bool const State = true); bool ChangeDoorPermitPreset(int const Change, range_t const Notify = range_t::consist); @@ -2541,7 +2533,7 @@ class TMoverParameters bool ChangeOffsetH(double DeltaOffset); /*funkcje ladujace pliki opisujace pojazd*/ - bool LoadFIZ(std::string chkpath); // Q 20160717 bool LoadChkFile(std::string chkpath); + bool LoadFIZ(std::string const &chkpath); // Q 20160717 bool LoadChkFile(std::string chkpath); bool CheckLocomotiveParameters(bool ReadyFlag, int Dir); std::string EngineDescription(int what) const; @@ -2577,10 +2569,10 @@ class TMoverParameters void LoadFIZ_LightsList(std::string const &Input); void LoadFIZ_DimmerList(std::string const &Input); void LoadFIZ_CompressorList(std::string const &Input); - void LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const Prefix, std::string const &Input); - TPowerType LoadFIZ_PowerDecode(std::string const &Power); - TPowerSource LoadFIZ_SourceDecode(std::string const &Source); - TEngineType LoadFIZ_EngineDecode(std::string const &Engine); + void LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Input); + TPowerType LoadFIZ_PowerDecode(std::string const &Power) const; + TPowerSource LoadFIZ_SourceDecode(std::string const &Source) const; + TEngineType LoadFIZ_EngineDecode(std::string const &Engine) const; bool readMPT0(std::string const &line); bool readMPT(std::string const &line); // Q 20160717 bool readMPTElectricSeries(std::string const &line); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index ff60c27c..16fe3066 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -256,7 +256,7 @@ void TSecuritySystem::load(std::string const &line, double Vmax) double TableInterpolation(std::map &Map, double Parameter) { - if (Map.size() == 0) + if (Map.empty()) return 0.0; if (Map.size() == 1) return Map.begin()->second; @@ -289,8 +289,11 @@ double TMoverParameters::Current(double n, double U) // a takze wywala bezpiecznik nadmiarowy gdy za duzy prad lub za male napiecie // jest takze mozliwosc uszkodzenia silnika wskutek nietypowych parametrow - double R, MotorCurrent; - double Rz, Delta, Isf; + double R; + double MotorCurrent; + double Rz; + double Delta; + double Isf; double Mn; // przujmuje int, ale dla poprawnosci obliczeń double Bn; int SP = 0; @@ -347,7 +350,6 @@ double TMoverParameters::Current(double n, double U) Mn = RList[MainCtrlActualPos].Mn * RList[MainCtrlActualPos].Bn; if (RList[MainCtrlActualPos].Bn > 1) { - Bn = 1; R = CircuitRes; } } @@ -429,7 +431,6 @@ double TMoverParameters::Current(double n, double U) if (DynamicBrakeType == dbrake_switch && (BrakePress > 2.0 || PipePress < 3.6)) { Im = 0; - MotorCurrent = 0; // Im:=0; Itot = 0; } @@ -443,17 +444,13 @@ double TMoverParameters::Current(double n, double U) if (MotorCurrent > 0) { - if (FuzzyLogic(abs(n), nmax * 1.1, p_elengproblem)) - if (MainSwitch(false)) - EventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ - if (TestFlag(DamageFlag, dtrain_engine)) - if (FuzzyLogic(MotorCurrent, (double)ImaxLo / 10.0, p_elengproblem)) - if (MainSwitch(false)) - EventFlag = true; /*uszkodzony silnik (uplywy)*/ - if (FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) - /* or FuzzyLogic(Abs(U/Mn),2*NominalVoltage,1)) then */ /*poprawic potem*/ - if (SetFlag(DamageFlag, dtrain_engine)) - EventFlag = true; + if (FuzzyLogic(abs(n), nmax * 1.1, p_elengproblem) && MainSwitch(false)) + EventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ + if (TestFlag(DamageFlag, dtrain_engine) && FuzzyLogic(MotorCurrent, (double)ImaxLo / 10.0, p_elengproblem) && MainSwitch(false)) + EventFlag = true; /*uszkodzony silnik (uplywy)*/ + /* or FuzzyLogic(Abs(U/Mn),2*NominalVoltage,1)) then */ /*poprawic potem*/ + if ((FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) && SetFlag(DamageFlag, dtrain_engine)) + EventFlag = true; /*! dorobic grzanie oporow rozruchowych i silnika*/ } @@ -463,36 +460,37 @@ double TMoverParameters::Current(double n, double U) // ************************************************************************************************* // główny konstruktor // ************************************************************************************************* -TMoverParameters::TMoverParameters(double VelInitial, std::string TypeNameInit, std::string NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), CabOccupied(Cab) +TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), CabOccupied(Cab) { WriteLog("------------------------------------------------------"); WriteLog("init default physic values for " + NameInit + ", [" + TypeNameInit + "]"); - Dim = TDimension(); // BrakeLevelSet(-2); //Pascal ustawia na 0, przestawimy na odcięcie (CHK jest jeszcze nie wczytane!) iLights[0] = 0; iLights[1] = 0; // światła zgaszone // inicjalizacja stalych - for (int b = 0; b < ResArraySize + 1; ++b) + for (auto &scheme : RList) { - RList[b] = TScheme(); + scheme = TScheme(); } RlistSize = 0; - for (int b = 0; b < MotorParametersArraySize + 1; ++b) + for (auto &motorparam : MotorParam) { - MotorParam[b] = TMotorParameters(); + motorparam = TMotorParameters(); } - for (int b = 0; b < 2; ++b) + for (auto &cablights : Lights) for (int k = 0; k < 17; ++k) - Lights[b][k] = 0; + cablights[k] = 0; - for (int b = 0; b < 4; ++b) + for (auto &compressorrow : CompressorList) for (int k = 1; k < 9; ++k) - CompressorList[b][k] = 0; + compressorrow[k] = 0; CompressorList[0][0] = 0.0; - CompressorList[1][0] = CompressorList[2][0] = CompressorList[3][0] = 1.0; + CompressorList[1][0] = 1.0; + CompressorList[2][0] = 1.0; + CompressorList[3][0] = 1.0; for (int b = -1; b <= MainBrakeMaxPos; ++b) { @@ -506,9 +504,9 @@ TMoverParameters::TMoverParameters(double VelInitial, std::string TypeNameInit, BrakePressureTable[-2].BrakePressureVal = -1.0; BrakePressureTable[-2].FlowSpeedVal = 0.0; } - for (int b = 0; b < 4; ++b) + for (auto &delay : BrakeDelay) { - BrakeDelay[b] = 0.0; + delay = 0.0; } for (int b = 0; b < 2; ++b) // Ra: kto tu zrobił "for b:=1 to 2 do" ??? @@ -521,40 +519,40 @@ TMoverParameters::TMoverParameters(double VelInitial, std::string TypeNameInit, Couplers[b].DmaxC = 0.1; Couplers[b].FmaxC = 1000.0; } - for (int b = 0; b < 3; ++b) + for (auto &cylindermult : BrakeCylMult) { - BrakeCylMult[b] = 0.0; + cylindermult = 0.0; } - for (int b = 0; b < 26; ++b) + for (auto &eimcvalue : eimc) { - eimc[b] = 0.0; + eimcvalue = 0.0; } eimc[eimc_p_eped] = 1.5; - for (int b = 0; b < 2; ++b) + for (auto &couplerentry : Couplers) { - Couplers[b].AllowedFlag = 3; // domyślnie hak i hamulec, inne trzeba włączyć jawnie w FIZ - Couplers[b].CouplingFlag = 0; - Couplers[b].Connected = nullptr; - Couplers[b].ConnectedNr = 0; // Ra: to nie ma znaczenia jak nie podłączony - Couplers[b].Render = false; - Couplers[b].CForce = 0.0; - Couplers[b].Dist = 0.0; - Couplers[b].CheckCollision = false; + couplerentry.AllowedFlag = 3; // domyślnie hak i hamulec, inne trzeba włączyć jawnie w FIZ + couplerentry.CouplingFlag = 0; + couplerentry.Connected = nullptr; + couplerentry.ConnectedNr = 0; // Ra: to nie ma znaczenia jak nie podłączony + couplerentry.Render = false; + couplerentry.CForce = 0.0; + couplerentry.Dist = 0.0; + couplerentry.CheckCollision = false; } - for (int b = 0; b < 5; ++b) + for (auto &brakepress : MaxBrakePress) { - MaxBrakePress[b] = 0.0; + brakepress = 0.0; } Vel = abs(VelInitial); V = VelInitial / 3.6; - for (int b = 0; b < 21; b++) + for (auto &eimvvalue : eimv) { - eimv[b] = 0.0; + eimvvalue = 0.0; } RunningShape.Len = 1.0; @@ -592,30 +590,29 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * return false; } - auto &coupler{Couplers[ConnectNo]}; - auto &othercoupler = ConnectTo->Couplers[(ConnectToNr != 2 ? ConnectToNr : coupler.ConnectedNr)]; - auto const distance{CouplerDist(this, ConnectTo) - (coupler.adapter_length + othercoupler.adapter_length)}; + auto &thiscoupler{Couplers[ConnectNo]}; + auto &othercoupler = ConnectTo->Couplers[ConnectToNr != 2 ? ConnectToNr : thiscoupler.ConnectedNr]; + auto const distance{CouplerDist(this, ConnectTo) - (thiscoupler.adapter_length + othercoupler.adapter_length)}; - auto const couplercheck{Enforce || (distance <= dEpsilon && coupler.type() != TCouplerType::NoCoupler && coupler.type() == othercoupler.type())}; - if (false == couplercheck) + if (auto const couplercheck{Enforce || (distance <= dEpsilon && thiscoupler.type() != TCouplerType::NoCoupler && thiscoupler.type() == othercoupler.type())}; false == couplercheck) { return false; } // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie - if (coupler.CouplingFlag == coupling::faux) + if (thiscoupler.CouplingFlag == coupling::faux) { // jeśli wcześniej nie było połączone, ustalenie z której strony rysować sprzęg - coupler.Render = true; // tego rysować + thiscoupler.Render = true; // tego rysować othercoupler.Render = false; // a tego nie - }; - auto const couplingchange{CouplingType ^ coupler.CouplingFlag}; - coupler.Connected = ConnectTo; - coupler.CouplingFlag = CouplingType; // ustawienie typu sprzęgu + } + auto const couplingchange{CouplingType ^ thiscoupler.CouplingFlag}; + thiscoupler.Connected = ConnectTo; + thiscoupler.CouplingFlag = CouplingType; // ustawienie typu sprzęgu if (ConnectToNr != 2) { - coupler.ConnectedNr = ConnectToNr; // 2=nic nie podłączone + thiscoupler.ConnectedNr = ConnectToNr; // 2=nic nie podłączone } othercoupler.Connected = this; othercoupler.CouplingFlag = CouplingType; @@ -628,14 +625,14 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * std::vector> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose}, {coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol}, {coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}}; - for (auto const &soundmapping : soundmappings) + for (auto const &[mappingcoupling, mappingsound] : soundmappings) { - if ((couplingchange & soundmapping.first) != 0) + if ((couplingchange & mappingcoupling) != 0) { - soundflag |= soundmapping.second; + soundflag |= mappingsound; } } - SetFlag(coupler.sounds, soundflag); + SetFlag(thiscoupler.sounds, soundflag); } return true; @@ -659,44 +656,44 @@ int TMoverParameters::DettachStatus(int ConnectNo) bool TMoverParameters::Dettach(int ConnectNo) { // rozlaczanie - auto &coupler{Couplers[ConnectNo]}; - auto &othervehicle{coupler.Connected}; - auto &othercoupler{othervehicle->Couplers[coupler.ConnectedNr]}; + auto &thiscoupler{Couplers[ConnectNo]}; + auto &othervehicle{thiscoupler.Connected}; + auto &othercoupler{othervehicle->Couplers[thiscoupler.ConnectedNr]}; if (othervehicle == nullptr) { return true; } // nie ma nic, to odczepiono - auto couplingchange{coupler.CouplingFlag}; // presume we'll uncouple all active flags + auto couplingchange{thiscoupler.CouplingFlag}; // presume we'll uncouple all active flags auto const couplingstate{DettachStatus(ConnectNo)}; // stan sprzęgu if (couplingstate < 0) { // gdy scisniete zderzaki, chyba ze zerwany sprzeg (wirtualnego nie odpinamy z drugiej strony) - std::tie(coupler.Connected, coupler.ConnectedNr, coupler.CouplingFlag) = std::tie(othercoupler.Connected, othercoupler.ConnectedNr, othercoupler.CouplingFlag) = - std::make_tuple(nullptr, -1, coupling::faux); + std::tie(othercoupler.Connected, othercoupler.ConnectedNr, othercoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux); + std::tie(thiscoupler.Connected, thiscoupler.ConnectedNr, thiscoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux); } else if (couplingstate > 0) { // odłączamy węże i resztę, pozostaje sprzęg fizyczny, który wymaga dociśnięcia (z wirtualnym nic) - coupler.CouplingFlag &= coupling::coupler; + thiscoupler.CouplingFlag &= coupling::coupler; othercoupler.CouplingFlag &= coupling::coupler; } // set sound event flag - couplingchange ^= coupler.CouplingFlag; // remaining bits were removed from coupling + couplingchange ^= thiscoupler.CouplingFlag; // remaining bits were removed from coupling if (couplingchange != 0) { int soundflag{sound::detach}; // HACK: use detach flag to indicate removal of listed coupling std::vector> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose}, {coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol}, {coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}}; - for (auto const &soundmapping : soundmappings) + for (auto const &[mappingcoupling, mappingsound] : soundmappings) { - if ((couplingchange & soundmapping.first) != 0) + if ((couplingchange & mappingcoupling) != 0) { - soundflag |= soundmapping.second; + soundflag |= mappingsound; } } - SetFlag(coupler.sounds, soundflag); + SetFlag(thiscoupler.sounds, soundflag); } return couplingstate < 0; @@ -735,7 +732,7 @@ void TMoverParameters::BrakeLevelSet(double b) fBrakeCtrlPos = Handle->GetPos(bh_MAX); // TODO: verify whether BrakeCtrlPosR and fBrakeCtrlPos can be rolled into single variable BrakeCtrlPosR = fBrakeCtrlPos; - int x = static_cast(std::floor(fBrakeCtrlPos)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być + auto x = static_cast(std::floor(fBrakeCtrlPos)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być // obcięte a nie zaokrągone while (x > BrakeCtrlPos && BrakeCtrlPos < BrakeCtrlPosNo) // jeśli zwiększyło się o 1 if (!IncBrakeLevelOld()) // T_MoverParameters:: @@ -936,8 +933,11 @@ void TMoverParameters::UpdatePantVolume(double dt) void TMoverParameters::UpdateBatteryVoltage(double dt) { // przeliczenie obciążenia baterii - double sn1 = 0.0, sn2 = 0.0, sn3 = 0.0, sn4 = 0.0, - sn5 = 0.0; // Ra: zrobić z tego amperomierz NN + double sn1 = 0.0; + double sn2 = 0.0; + double sn3 = 0.0; + double sn4 = 0.0; + double sn5 = 0.0; // Ra: zrobić z tego amperomierz NN if (BatteryVoltage > 0 && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven && NominalBatteryVoltage > 0) { @@ -968,7 +968,7 @@ void TMoverParameters::UpdateBatteryVoltage(double dt) sn5 = dt * 0.001; else sn5 = 0; - }; + } if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) { // 90V if (PantCompFlag) @@ -991,7 +991,7 @@ void TMoverParameters::UpdateBatteryVoltage(double dt) sn5 = dt * 0.0010; else sn5 = 0; - }; + } if (!Battery) { if (NominalBatteryVoltage / BatteryVoltage < 1.22) @@ -1002,11 +1002,10 @@ void TMoverParameters::UpdateBatteryVoltage(double dt) sn3 = dt * 0.000001; sn4 = dt * 0.000001; sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach - }; + } BatteryVoltage -= sn1 + sn2 + sn3 + sn4 + sn5; - if (NominalBatteryVoltage / BatteryVoltage > 1.57) - if (MainSwitch(false) && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven) - EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia + if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven) + EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia if (BatteryVoltage > NominalBatteryVoltage) BatteryVoltage = NominalBatteryVoltage; // wstrzymanie ładowania pow. 110V if (BatteryVoltage < 0.01) @@ -1062,7 +1061,7 @@ ZN //masa // Q: 20160714 // Oblicza iloraz aktualnej pozycji do maksymalnej hamulca pomocnicznego // ***************************************************************************** -double TMoverParameters::LocalBrakeRatio(void) +double TMoverParameters::LocalBrakeRatio(void) const { double LBR; if (BrakeHandle == TBrakeHandle::MHZ_EN57) @@ -1086,7 +1085,7 @@ double TMoverParameters::LocalBrakeRatio(void) // Q: 20160714 // Oblicza iloraz aktualnej pozycji do maksymalnej hamulca ręcznego // ***************************************************************************** -double TMoverParameters::ManualBrakeRatio(void) +double TMoverParameters::ManualBrakeRatio(void) const { double MBR; @@ -1113,7 +1112,7 @@ double TMoverParameters::BrakeVP(void) const // Q: 20160713 // Zwraca iloraz różnicy między przewodem kontrolnym i głównym oraz DeltaPipePress // ***************************************************************************** -double TMoverParameters::RealPipeRatio(void) +double TMoverParameters::RealPipeRatio(void) const { double rpp; @@ -1128,7 +1127,7 @@ double TMoverParameters::RealPipeRatio(void) // Q: 20160713 // Zwraca iloraz ciśnienia w przewodzie do DeltaPipePress // ***************************************************************************** -double TMoverParameters::PipeRatio(void) +double TMoverParameters::PipeRatio(void) const { double pr; @@ -1188,27 +1187,27 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) return; } // shouldn't normally happen but, eh - auto &coupler{Couplers[End]}; + auto const &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; auto const otherend{Neighbours[End].vehicle_end}; - auto &othercoupler{othervehicle->Couplers[otherend]}; + auto const &othercoupler{othervehicle->Couplers[otherend]}; auto velocity{V}; auto othervehiclevelocity{othervehicle->V}; // calculate collision force and new velocities for involved vehicles - auto const VirtualCoupling{(coupler.CouplingFlag == coupling::faux)}; + auto const VirtualCoupling{(thiscoupler.CouplingFlag == coupling::faux)}; auto CCF{0.0}; switch (End) { case 0: { - CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, (coupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt; + CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, (thiscoupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt; break; // yB: ej ej ej, a po } case 1: { - CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, (coupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt; + CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, (thiscoupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt; break; } default: @@ -1219,13 +1218,13 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) if (Global.crash_damage) { - if (-coupler.Dist >= coupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (coupler.FmaxC + 1.0), p_coupldmg)) + if (-thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) { // small chance to smash the coupler if it's hit with excessive force damage_coupler(End); } - if (coupler.CouplingFlag == coupling::faux || true == TestFlag(othervehicle->DamageFlag, dtrain_out)) + if (thiscoupler.CouplingFlag == coupling::faux || true == TestFlag(othervehicle->DamageFlag, dtrain_out)) { // HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist auto const safevelocitylimit{15.0}; auto const velocitydifference{glm::length(glm::angleAxis(Rot.Rz, glm::dvec3{0, 1, 0}) * V - glm::angleAxis(othervehicle->Rot.Rz, glm::dvec3{0, 1, 0}) * othervehicle->V) * @@ -1276,9 +1275,9 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) void TMoverParameters::damage_coupler(int const End) { - auto &coupler{Couplers[End]}; + auto &thiscoupler{Couplers[End]}; - if (coupler.type() == TCouplerType::Articulated) + if (thiscoupler.type() == TCouplerType::Articulated) { return; } // HACK: don't break articulated couplings no matter what @@ -1286,27 +1285,27 @@ void TMoverParameters::damage_coupler(int const End) if (SetFlag(DamageFlag, dtrain_coupling)) EventFlag = true; - if ((coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose) + if ((thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose) { // hamowanie nagle - zerwanie przewodow hamulcowych AlarmChainFlag = true; } - coupler.CouplingFlag = 0; + thiscoupler.CouplingFlag = 0; - if (coupler.Connected != nullptr) + if (thiscoupler.Connected != nullptr) { switch (End) { // break connection with other vehicle, if there's any case 0: { - coupler.Connected->Couplers[end::rear].CouplingFlag = coupling::faux; + thiscoupler.Connected->Couplers[end::rear].CouplingFlag = coupling::faux; break; } case 1: { - coupler.Connected->Couplers[end::front].CouplingFlag = coupling::faux; + thiscoupler.Connected->Couplers[end::front].CouplingFlag = coupling::faux; break; } default: @@ -1353,10 +1352,8 @@ void TMoverParameters::Derail(DerailReason const Reason) // ************************************************************************************************* // Oblicza przemieszczenie taboru // ************************************************************************************************* -double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam &Track, TTractionParam &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) +double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) { - const double Vepsilon = 1e-5; - const double Aepsilon = 1e-3; // ASBSpeed=0.8; if (!TestFlag(DamageFlag, dtrain_out)) { // Ra: to przepisywanie tu jest bez sensu @@ -1377,12 +1374,11 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap if (CategoryFlag == 4) OffsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); - else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1)) - if (TestFlag(DamageFlag, dtrain_out)) - { - OffsetTrackV = -0.2; - OffsetTrackH = Sign(RunningShape.R) * 0.2; - } + else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out)) + { + OffsetTrackV = -0.2; + OffsetTrackH = Sign(RunningShape.R) * 0.2; + } // TODO: investigate, seems supplied NewRot is always 0 although the code here suggests some actual values are expected Loc = NewLoc; @@ -1477,9 +1473,8 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // Oblicza przemieszczenie taboru - uproszczona wersja // ************************************************************************************************* -double TMoverParameters::FastComputeMovement(double dt, const TTrackShape &Shape, TTrackParam &Track, TLocation const &NewLoc, TRotation const &NewRot) +double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Shape*/, TTrackParam & /*Track*/, TLocation const &NewLoc, TRotation const &NewRot) { - int b; // T_MoverParameters::FastComputeMovement(dt, Shape, Track, NewLoc, NewRot); Loc = NewLoc; @@ -1520,7 +1515,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape &Shape dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha // ale jesli jest kolizja (zas. zach. pedu) to... - for (b = 0; b < 2; b++) + for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! } // liczone dL, predkosc i przyspieszenie @@ -1548,24 +1543,21 @@ void TMoverParameters::compute_movement_(double const Deltatime) RunInternalCommand(); // relay settings - if (EngineType == TEngineType::ElectricSeriesMotor) + // adjust motor overload relay threshold + if (EngineType == TEngineType::ElectricSeriesMotor && ImaxHi > ImaxLo) { - // adjust motor overload relay threshold - if (ImaxHi > ImaxLo) - { - if (MotorOverloadRelayHighThreshold) - { // set high threshold - if (TrainType != dt_ET42 ? RList[MainCtrlPos].Bn < 2 : MainCtrlPos == 0) - { - Imax = ImaxHi; - } + if (MotorOverloadRelayHighThreshold) + { // set high threshold + if (TrainType != dt_ET42 ? RList[MainCtrlPos].Bn < 2 : MainCtrlPos == 0) + { + Imax = ImaxHi; } - else - { // set low threshold - if (TrainType != dt_ET42 || MainCtrlPos == 0) - { - Imax = ImaxLo; - } + } + else + { // set low threshold + if (TrainType != dt_ET42 || MainCtrlPos == 0) + { + Imax = ImaxLo; } } } @@ -1573,10 +1565,9 @@ void TMoverParameters::compute_movement_(double const Deltatime) // Uproszczona symulacja wentylatorow rezystora hamowania // Prad oddawany na rezystor - double Irh = abs(eimv[eimv_Pe]) - abs(eimv[eimv_Ipoj]); // Wlacz wentylator jesli prad rekuperacji przekroczy maksymalny dla pasywnego chlodzenia rezystora - if (Irh > Imaxrpc && eimv[eimv_Ipoj] < 0) + if (double Irh = abs(eimv[eimv_Pe]) - abs(eimv[eimv_Ipoj]); Irh > Imaxrpc && eimv[eimv_Ipoj] < 0) { BRVtimer = 0; BRVentilators = true; @@ -1589,20 +1580,14 @@ void TMoverParameters::compute_movement_(double const Deltatime) } // automatyczny rozruch - if (EngineType == TEngineType::ElectricSeriesMotor) + if (EngineType == TEngineType::ElectricSeriesMotor && AutoRelayCheck()) { - if (AutoRelayCheck()) - { - SetFlag(SoundFlag, sound::relay); - } + SetFlag(SoundFlag, sound::relay); } - if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) + if ((EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && dizel_Update(Deltatime)) { - if (dizel_Update(Deltatime)) - { - SetFlag(SoundFlag, sound::relay); - } + SetFlag(SoundFlag, sound::relay); } // TODO: gather and move current calculations to dedicated method @@ -1624,7 +1609,7 @@ void TMoverParameters::compute_movement_(double const Deltatime) { Compressor = 0; CompressorFlag = false; - }; + } if (VeselVolume > 0.0) { // sprężarka musi mieć jakąś niezerową wydajność żeby rozważać jej załączenie i pracę @@ -1725,14 +1710,12 @@ void TMoverParameters::MainsCheck(double const Deltatime) } } -void TMoverParameters::LowVoltagePowerCheck(double const Deltatime) +void TMoverParameters::LowVoltagePowerCheck(double const /*Deltatime*/) { auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - switch (EngineType) - { - case TEngineType::ElectricSeriesMotor: + if (EngineType == TEngineType::ElectricSeriesMotor) { GroundRelay &= lowvoltagepower; if (GroundRelayStart != start_t::manual) @@ -1741,16 +1724,10 @@ void TMoverParameters::LowVoltagePowerCheck(double const Deltatime) // TODO: generic check method which takes these into account GroundRelay |= lowvoltagepower; } - break; - } - default: - { - break; - } } } -void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const Coupling) +void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling const Coupling) { if (Coupling != coupling::highvoltage && Coupling != coupling::power110v && Coupling != coupling::power24v) { @@ -1795,17 +1772,9 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const } } // high voltage power sources - switch (EnginePowerSource.SourceType) - { - case TPowerSource::CurrentCollector: + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { localvoltage = std::max(localvoltage, PantographVoltage); - break; - } - default: - { - break; - } } break; } @@ -1845,9 +1814,9 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const for (auto side = 0; side < 2; ++side) { - auto &coupler{Couplers[side]}; + auto const &thiscoupler{Couplers[side]}; // NOTE: in the loop we actually update the state of the coupler on the opposite end of the vehicle - auto &oppositecoupler{Couplers[(side == end::front ? end::rear : end::front)]}; + auto &oppositecoupler{Couplers[side == end::front ? end::rear : end::front]}; bool oppositecouplingispresent; bool localpowerexportisenabled; @@ -1885,9 +1854,9 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const } } - auto const *coupling = Coupling == coupling::highvoltage ? &coupler.power_high : - Coupling == coupling::power110v ? &coupler.power_110v : - Coupling == coupling::power24v ? &coupler.power_24v : + auto const *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : + Coupling == coupling::power110v ? &thiscoupler.power_110v : + Coupling == coupling::power24v ? &thiscoupler.power_24v : nullptr; auto *oppositecoupling = Coupling == coupling::highvoltage ? &oppositecoupler.power_high : Coupling == coupling::power110v ? &oppositecoupler.power_110v : @@ -1899,9 +1868,9 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const oppositecoupling->is_live = false; oppositecoupling->is_local = localpowersource; // indicate power source // draw from external source - if (coupler.Connected != nullptr) + if (thiscoupler.Connected != nullptr) { - auto const &connectedcoupler{coupler.Connected->Couplers[coupler.ConnectedNr]}; + auto const &connectedcoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; auto const *connectedcoupling = Coupling == coupling::highvoltage ? &connectedcoupler.power_high : Coupling == coupling::power110v ? &connectedcoupler.power_110v : Coupling == coupling::power24v ? &connectedcoupler.power_24v : @@ -1924,17 +1893,17 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const { case coupling::highvoltage: { - couplervoltage = Couplers[end::front].power_high.voltage + Couplers[end::rear].power_high.voltage; + couplervoltage = static_cast(Couplers[end::front].power_high.voltage + Couplers[end::rear].power_high.voltage); break; } case coupling::power110v: { - couplervoltage = Couplers[end::front].power_110v.voltage + Couplers[end::rear].power_110v.voltage; + couplervoltage = static_cast(Couplers[end::front].power_110v.voltage + Couplers[end::rear].power_110v.voltage); break; } case coupling::power24v: { - couplervoltage = Couplers[end::front].power_24v.voltage + Couplers[end::rear].power_24v.voltage; + couplervoltage = static_cast(Couplers[end::front].power_24v.voltage + Couplers[end::rear].power_24v.voltage); break; } default: @@ -1948,23 +1917,21 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const Coupling == coupling::power24v ? &PowerCircuits[0].second : nullptr; - for (auto side = 0; side < 2; ++side) + for (auto &thiscoupler : Couplers) { - - auto &coupler{Couplers[side]}; - auto *coupling = Coupling == coupling::highvoltage ? &coupler.power_high : - Coupling == coupling::power110v ? &coupler.power_110v : - Coupling == coupling::power24v ? &coupler.power_24v : + auto *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : + Coupling == coupling::power110v ? &thiscoupler.power_110v : + Coupling == coupling::power24v ? &thiscoupler.power_24v : nullptr; coupling->current = 0.0; - if (coupler.Connected == nullptr) + if (thiscoupler.Connected == nullptr) { continue; } - auto const &connectedothercoupler{coupler.Connected->Couplers[(coupler.ConnectedNr == end::front ? end::rear : end::front)]}; + auto const &connectedothercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr == end::front ? end::rear : end::front]}; auto const *connectedothercoupling = Coupling == coupling::highvoltage ? &connectedothercoupler.power_high : Coupling == coupling::power110v ? &connectedothercoupler.power_110v : Coupling == coupling::power24v ? &connectedothercoupler.power_24v : @@ -1994,7 +1961,7 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const } } -double TMoverParameters::ShowEngineRotation(int VehN) +double TMoverParameters::ShowEngineRotation(int VehN) const { // Zwraca wartość prędkości obrotowej silnika wybranego pojazdu. Do 3 pojazdów (3×SN61). int b; switch (VehN) @@ -2003,19 +1970,17 @@ double TMoverParameters::ShowEngineRotation(int VehN) return std::abs(enrot); case 2: for (b = 0; b <= 1; ++b) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Power > 0.01) - return fabs(Couplers[b].Connected->enrot); + if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) + return fabs(Couplers[b].Connected->enrot); break; case 3: // to nie uwzględnia ewentualnego odwrócenia pojazdu w środku for (b = 0; b <= 1; ++b) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Power > 0.01) - if (TestFlag(Couplers[b].Connected->Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Couplers[b].Connected->Power > 0.01) - return fabs(Couplers[b].Connected->Couplers[b].Connected->enrot); + if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01 && TestFlag(Couplers[b].Connected->Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Couplers[b].Connected->Power > 0.01) + return fabs(Couplers[b].Connected->Couplers[b].Connected->enrot); break; - }; + default: + break; + } return 0.0; }; @@ -2080,14 +2045,12 @@ void TMoverParameters::ConverterCheck(double const Timestep) }; // heating system status check -void TMoverParameters::HeatingCheck(double const Timestep) +void TMoverParameters::HeatingCheck(double const /*Timestep*/) { // update heating devices // TBD, TODO: move this to a separate method? - switch (HeatingPowerSource.SourceType) - { - case TPowerSource::Generator: + if (HeatingPowerSource.SourceType == TPowerSource::Generator) { if (HeatingPowerSource.EngineGenerator.engine_revolutions != nullptr && HeatingPowerSource.EngineGenerator.revolutions_max > 0) { @@ -2106,12 +2069,6 @@ void TMoverParameters::HeatingCheck(double const Timestep) std::clamp((absrevolutions - generator.revolutions_min) / (generator.revolutions_max - generator.revolutions_min), 0.0, 1.0))) * sign(generator.revolutions); } - break; - } - default: - { - break; - } } // quick check first to avoid unnecessary calls... @@ -2166,7 +2123,7 @@ void TMoverParameters::HeatingCheck(double const Timestep) } // water pump status check -void TMoverParameters::WaterPumpCheck(double const Timestep) +void TMoverParameters::WaterPumpCheck(double const /*Timestep*/) { // NOTE: breaker override with start type is sm42 specific hack, replace with ability to define the presence of the breaker WaterPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterPump.breaker && false == WaterPump.is_disabled && @@ -2174,7 +2131,7 @@ void TMoverParameters::WaterPumpCheck(double const Timestep) } // water heater status check -void TMoverParameters::WaterHeaterCheck(double const Timestep) +void TMoverParameters::WaterHeaterCheck(double const /*Timestep*/) { WaterHeater.is_active = false == WaterHeater.is_damaged && true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && @@ -2189,13 +2146,14 @@ void TMoverParameters::WaterHeaterCheck(double const Timestep) } // fuel pump status update -void TMoverParameters::FuelPumpCheck(double const Timestep) +void TMoverParameters::FuelPumpCheck(double const /*Timestep*/) { + using enum start_t; FuelPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == FuelPump.is_disabled && - (FuelPump.is_active || (FuelPump.start_type == start_t::manual ? FuelPump.is_enabled : - FuelPump.start_type == start_t::automatic ? dizel_startup || Mains : - FuelPump.start_type == start_t::manualwithautofallback ? FuelPump.is_enabled || dizel_startup || Mains : + (FuelPump.is_active || (FuelPump.start_type == manual ? FuelPump.is_enabled : + FuelPump.start_type == automatic ? dizel_startup || Mains : + FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || dizel_startup || Mains : false)); // shouldn't ever get this far but, eh } @@ -2218,11 +2176,11 @@ void TMoverParameters::OilPumpCheck(double const Timestep) if (OilPump.pressure < OilPump.pressure_target) { // TODO: scale change rate from 0.01-0.05 with oil/engine temperature/idle time - OilPump.pressure = std::min(OilPump.pressure_target, OilPump.pressure + (enrot > 5.0 ? 0.05 : 0.035) * Timestep); + OilPump.pressure = std::min(OilPump.pressure_target, static_cast(OilPump.pressure + (enrot > 5.0 ? 0.05 : 0.035) * Timestep)); } if (OilPump.pressure > OilPump.pressure_target) { - OilPump.pressure = std::max(OilPump.pressure_target, OilPump.pressure - (enrot > 5.0 ? 0.05 : 0.035) * 0.5 * Timestep); + OilPump.pressure = std::max(OilPump.pressure_target, static_cast(OilPump.pressure - (enrot > 5.0 ? 0.05 : 0.035) * 0.5 * Timestep)); } OilPump.pressure = std::clamp(OilPump.pressure, 0.f, 1.5f); } @@ -2239,7 +2197,7 @@ void TMoverParameters::MotorBlowersCheck(double const Timestep) { if (stop) { - blower.stop_timer += Timestep; + blower.stop_timer += static_cast(Timestep); if (blower.stop_timer > blower.sustain_time) { disable = true; @@ -2279,23 +2237,24 @@ void TMoverParameters::MotorBlowersCheck(double const Timestep) if (revolutionstarget > 0.f) { auto const speedincreasecap{std::max(50.f, fan.speed * 0.05f * -1)}; // 5% of fixed revolution speed, or 50 - fan.revolutions += std::clamp(revolutionstarget - fan.revolutions, speedincreasecap * -2, speedincreasecap) * Timestep; + fan.revolutions += static_cast(std::clamp(revolutionstarget - fan.revolutions, speedincreasecap * -2, speedincreasecap) * Timestep); } else { - fan.revolutions *= std::max(0.0, 1.0 - Timestep); + fan.revolutions *= static_cast(std::max(0.0, 1.0 - Timestep)); } } } -void TMoverParameters::PantographsCheck(double const Timestep) +void TMoverParameters::PantographsCheck(double const /*Timestep*/) { + using enum start_t; { - auto &valve{PantsValve}; + auto const &valve{PantsValve}; auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; - auto const autostart{valve.start_type == start_t::automatic || valve.start_type == start_t::manualwithautofallback}; - auto const manualcontrol{valve.start_type == start_t::manual || valve.start_type == start_t::manualwithautofallback}; + auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; + auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; PantsValve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state @@ -2310,8 +2269,8 @@ void TMoverParameters::PantographsCheck(double const Timestep) auto &valve{pantograph.valve}; auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; - auto const autostart{valve.start_type == start_t::automatic || valve.start_type == start_t::manualwithautofallback}; - auto const manualcontrol{valve.start_type == start_t::manual || valve.start_type == start_t::manualwithautofallback}; + auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; + auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; valve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state, without it just pass through @@ -2326,7 +2285,7 @@ void TMoverParameters::PantographsCheck(double const Timestep) } } -void TMoverParameters::LightsCheck(double const Timestep) +void TMoverParameters::LightsCheck(double const /*Timestep*/) { auto &light{CompartmentLights}; @@ -2437,7 +2396,6 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) while (RList[MainCtrlPos].R > 0.0 && IncMainCtrl(1)) { // all work is done in the loop header - ; } OK = false; // shouldn't this be part of the loop above? // if (TrainType=dt_ET40) then @@ -2449,21 +2407,18 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) { // CtrlSpeed == 1 ++MainCtrlPos; OK = true; - if (Imax == ImaxHi) + if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) { - if (RList[MainCtrlPos].Bn > 1) + /* NOTE: disabled, relay configuration was moved to compute_movement_ + if( true == MaxCurrentSwitch( false )) { + // wylaczanie wysokiego rozruchu + SetFlag( SoundFlag, sound::relay ); + } + */ + if (TrainType == dt_ET42) { - /* NOTE: disabled, relay configuration was moved to compute_movement_ - if( true == MaxCurrentSwitch( false )) { - // wylaczanie wysokiego rozruchu - SetFlag( SoundFlag, sound::relay ); - } - */ - if (TrainType == dt_ET42) - { - --MainCtrlPos; - OK = false; - } + --MainCtrlPos; + OK = false; } } // @@ -2476,13 +2431,10 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) //} } - if (TrainType == dt_ET42 && true == DynamicBrakeFlag) + if (TrainType == dt_ET42 && true == DynamicBrakeFlag && MainCtrlPos > 20) { - if (MainCtrlPos > 20) - { - MainCtrlPos = 20; - OK = false; - } + MainCtrlPos = 20; + OK = false; } break; } @@ -2493,7 +2445,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) { while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) { - ; + // all work is done in the loop header } } else @@ -2510,6 +2462,8 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) OK = AddPulseForce(CtrlSpeed); break; } + default: + break; } // switch EngineType of } else @@ -2644,6 +2598,8 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) } break; } + default: + break; } // switch EngineType } } @@ -2776,9 +2732,8 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) OK = false; // if OK then LastRelayTime:=0; // hunter-101012: poprawka - if (OK) - if (LastRelayTime > CtrlDelay) - LastRelayTime = 0; + if (OK && LastRelayTime > CtrlDelay) + LastRelayTime = 0; if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && MainCtrlPos > 0) { @@ -2793,7 +2748,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) if (OK && SpeedCtrl && ScndCtrlPos == 1 && EngineType == TEngineType::DieselEngine) { // NOTE: round() already adds 0.5, are the ones added here as well correct? - SpeedCtrlValue = Round(Vel); + SpeedCtrlValue = static_cast(Round(Vel)); SpeedCtrlUnit.IsActive = true; } @@ -2839,9 +2794,8 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) OK = false; // if OK then LastRelayTime:=0; // hunter-101012: poprawka - if (OK) - if (LastRelayTime > CtrlDownDelay) - LastRelayTime = 0; + if (OK && LastRelayTime > CtrlDownDelay) + LastRelayTime = 0; if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1) { @@ -2866,13 +2820,10 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) return OK; } -int TMoverParameters::GetVirtualScndPos() +int TMoverParameters::GetVirtualScndPos() const { - if (TrainType == dt_ET42) - { - if (DynamicBrakeFlag && !ScndCtrlPos) - return -1; - } + if (TrainType == dt_ET42 && DynamicBrakeFlag && !ScndCtrlPos) + return -1; return ScndCtrlPos; } @@ -3032,8 +2983,7 @@ bool TMoverParameters::SandboxManual(bool const State, range_t const Notify) bool TMoverParameters::SandboxAuto(bool const State, range_t const Notify) { bool result{false}; - bool NewState = State && SandDoseAutoAllow; - if (SandDoseAuto != NewState) + if (bool NewState = State && SandDoseAutoAllow; SandDoseAuto != NewState) { if (SandDoseAuto == false) { @@ -3155,6 +3105,7 @@ void TMoverParameters::SecuritySystemCheck(double dt) // ************************************************************************************************* bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) { + using enum range_t; auto const initialstate{Battery}; // Ra: ukrotnienie załączania baterii jest jakąś fikcją... @@ -3164,10 +3115,10 @@ bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) } // switching batteries does not require activation - if (Notify != range_t::local) + if (Notify != local) { - SendCtrlToNext("BatterySwitch", State ? 1 : 0, 1, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - SendCtrlToNext("BatterySwitch", State ? 1 : 0, -1, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext("BatterySwitch", State ? 1 : 0, 1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext("BatterySwitch", State ? 1 : 0, -1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); } return Battery != initialstate; @@ -3250,11 +3201,10 @@ bool TMoverParameters::DirectionBackward(void) return false; } - if (DirActive == 1 && MainCtrlPos == 0 && TrainType == dt_EZT && EngineType != TEngineType::ElectricInductionMotor) - if (MinCurrentSwitch(false)) - { - return true; - } + if (DirActive == 1 && MainCtrlPos == 0 && TrainType == dt_EZT && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) + { + return true; + } if (MainCtrlPosNo > 0 && DirActive > -1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0)) { if (EngineType == TEngineType::WheelsDriven) @@ -3662,6 +3612,7 @@ void TMoverParameters::MainSwitch_(bool const State) bool TMoverParameters::MainSwitchCheck() const { + using enum TEngineType; // prevent the switch from working if there's no power // TODO: consider whether it makes sense for diesel engines and such @@ -3669,15 +3620,15 @@ bool TMoverParameters::MainSwitchCheck() const switch (EngineType) { - case TEngineType::DieselElectric: - case TEngineType::DieselEngine: - case TEngineType::Dumb: + case DieselElectric: + case DieselEngine: + case Dumb: { powerisavailable = Power24vIsAvailable; break; } - case TEngineType::ElectricSeriesMotor: - case TEngineType::ElectricInductionMotor: + case ElectricSeriesMotor: + case ElectricInductionMotor: { // TODO: check whether we can simplify this check and skip the outer EngineType switch powerisavailable = EnginePowerSourceVoltage() > 0.5 * EnginePowerSource.MaxVoltage; @@ -3689,7 +3640,7 @@ bool TMoverParameters::MainSwitchCheck() const } } - return powerisavailable && (ScndCtrlPos == 0 || EngineType == TEngineType::ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 && + return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 && (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && true == NoVoltRelay && true == OvervoltageRelay && LastSwitchingTime > CtrlDelay && (HasCamshaft ? IsMainCtrlActualNoPowerPos() : LineBreakerClosesOnlyAtNoPowerPos ? IsMainCtrlNoPowerPos() : @@ -3947,8 +3898,7 @@ double TMoverParameters::DynamicBrakeRatio(void) const bool TMoverParameters::DynamicBrakeAvailable(void) const { double const vh0{eimc[eimc_p_Vh0]}; - double const vh1{eimc[eimc_p_Vh1]}; - if (vh1 <= 0.001) + if (double const vh1{eimc[eimc_p_Vh1]}; vh1 <= 0.001) { // brak zdefiniowanej strefy - ED dziala zawsze return true; @@ -4012,10 +3962,10 @@ bool TMoverParameters::DynamicBrakeSwitch(bool Switch) { DynamicBrakeFlag = Switch; DBS = true; - for (int b = 0; b < 2; b++) + for (auto &thiscoupler : Couplers) // with Couplers[b] do - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - Couplers[b].Connected->DynamicBrakeFlag = Switch; + if (TestFlag(thiscoupler.CouplingFlag, coupling::control)) + thiscoupler.Connected->DynamicBrakeFlag = Switch; // end; // if (DynamicBrakeType=dbrake_passive) and (TrainType=dt_ET42) then // begin @@ -4345,7 +4295,7 @@ void TMoverParameters::CompressorCheck(double dt) EmergencyValveOpen = Compressor > (EmergencyValveOpen ? EmergencyValveOff : EmergencyValveOn); if (EmergencyValveOpen) { - float dV = PF(0, Compressor, EmergencyValveArea) * dt; + auto dV = static_cast(PF(0, Compressor, EmergencyValveArea) * dt); CompressedVolume -= dV; } @@ -4357,9 +4307,8 @@ void TMoverParameters::CompressorCheck(double dt) auto const MaxCompressorF{CompressorList[TCompressorList::cl_MaxFactor][CompressorListPos] * MaxCompressor}; auto const MinCompressorF{CompressorList[TCompressorList::cl_MinFactor][CompressorListPos] * MinCompressor}; auto const CompressorSpeedF{CompressorList[TCompressorList::cl_SpeedFactor][CompressorListPos] * CompressorSpeed}; - auto const AllowFactor{CompressorList[TCompressorList::cl_Allow][CompressorListPos]}; // checking the impact on the compressor allowance - if (AllowFactor > 0.5) + if (auto const AllowFactor{CompressorList[TCompressorList::cl_Allow][CompressorListPos]}; AllowFactor > 0.5) { CompressorAllow = AllowFactor > 1.5; } @@ -4419,21 +4368,16 @@ void TMoverParameters::CompressorCheck(double dt) } // working compressor adds air to the air reservoir - switch (CompressorPower) - { - case 3: + if (CompressorPower == 3) { // the compressor is coupled with the diesel engine, engine revolutions affect the output CompressedVolume += CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * EngineRPMRatio() * dt * (CompressorGovernorLock ? 0.0 : 1.0); // with the lock active air is vented out - break; } - default: + else { // the compressor is a stand-alone device, working at steady pace CompressedVolume += CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * dt; - break; - } } if (pressureistoohigh && (false == governorlockispresent || CompressorPower == 3)) @@ -4451,14 +4395,11 @@ void TMoverParameters::CompressorCheck(double dt) // tymczasowo tylko obciążenie sprężarki, tak z 5A na sprężarkę // TODO: draw power from proper high- or low voltage circuit - switch (CompressorPower) - { - case 3: + if (CompressorPower == 3) { // diesel-powered compressor doesn't draw power - break; } - default: + else { // TODO: drain power from 110v circuit /* @@ -4466,8 +4407,6 @@ void TMoverParameters::CompressorCheck(double dt) compressorowner->TotalCurrent += 0.0015 * compressorowner->PantographVoltage; } */ - break; - } } } @@ -4483,8 +4422,6 @@ void TMoverParameters::UpdatePipePressure(double dt) Pipe->Act(); } - const double LBDelay = 100; - const double kL = 0.5; // double dV; // TMoverParameters *c; // T_MoverParameters double temp; @@ -4575,6 +4512,7 @@ void TMoverParameters::UpdatePipePressure(double dt) } if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 + { if (Compressor > ScndPipePress) { CompressedVolume = CompressedVolume + dpMainValve / 1500.0; @@ -4582,12 +4520,12 @@ void TMoverParameters::UpdatePipePressure(double dt) } else Pipe2->Flow(dpMainValve); + } } // ulepszony hamulec bezp. EmergencyValveFlow = 0.0; - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with // the emergency brake (a broken coupler sets AlarmChainFlag instead) @@ -4640,11 +4578,11 @@ void TMoverParameters::UpdatePipePressure(double dt) { LocBrakePress = LocHandle->GetCP(); - for (int b = 0; b < 2; b++) - if ((TrainType & (dt_ET41 | dt_ET42)) != 0 && Couplers[b].Connected != nullptr) // nie podoba mi się to rozwiązanie, chyba trzeba - // dodać jakiś wpis do fizyki na to - if ((Couplers[b].Connected->TrainType & (dt_ET41 | dt_ET42)) != 0 && (Couplers[b].CouplingFlag & 36) == 36) - LocBrakePress = std::max(Couplers[b].Connected->LocHandle->GetCP(), LocBrakePress); + for (auto const &couplerentry : Couplers) + // nie podoba mi się to rozwiązanie, chyba trzeba + // dodać jakiś wpis do fizyki na to + if ((TrainType & (dt_ET41 | dt_ET42)) != 0 && couplerentry.Connected != nullptr && (couplerentry.Connected->TrainType & (dt_ET41 | dt_ET42)) != 0 && (couplerentry.CouplingFlag & 36) == 36) + LocBrakePress = std::max(couplerentry.Connected->LocHandle->GetCP(), LocBrakePress); // if ((DynamicBrakeFlag) && (EngineType == ElectricInductionMotor)) //{ @@ -4657,10 +4595,12 @@ void TMoverParameters::UpdatePipePressure(double dt) //(Hamulec as TLSt).SetLBP(LocBrakePress); Hamulec->SetLBP(LocBrakePress); if (BrakeValve == TBrakeValve::EStED) + { if (MBPM < 2) Hamulec->PLC(MaxBrakePress[LoadFlag]); else Hamulec->PLC(TotalMass - Mred); + } break; } @@ -4732,7 +4672,7 @@ void TMoverParameters::UpdatePipePressure(double dt) if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) temp1 = 0; Hamulec->SetEPS(temp1); - TUHEX_StageActual = EpForce; + TUHEX_StageActual = static_cast(EpForce); TUHEX_Active = TUHEX_StageActual > 0; // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach SendCtrlToNext("Brake", EpForce, CabActive); @@ -4782,7 +4722,9 @@ void TMoverParameters::UpdateScndPipePressure(double dt) const double Spz = 0.5067; TMoverParameters *c; - double dv1, dv2, dV; + double dv1; + double dv2; + double dV; UpdateSpringBrake(dt); @@ -4790,32 +4732,29 @@ void TMoverParameters::UpdateScndPipePressure(double dt) dv2 = 0; // sprzeg 1 - if (Couplers[0].Connected != nullptr) - if (TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[0].Connected; // skrot - dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - if (dv1 * dv1 > 0.00000000000001) - c->switch_physics(true); - c->Pipe2->Flow(-dv1); - } + if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[0].Connected; // skrot + dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + if (dv1 * dv1 > 0.00000000000001) + c->switch_physics(true); + c->Pipe2->Flow(-dv1); + } // sprzeg 2 - if (Couplers[1].Connected != nullptr) - if (TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - if (dv2 * dv2 > 0.00000000000001) - c->switch_physics(true); - c->Pipe2->Flow(-dv2); - } - if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr) - if (TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); - Couplers[0].Connected->Pipe2->Flow(+dV); - Couplers[1].Connected->Pipe2->Flow(-dV); - } + if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + if (dv2 * dv2 > 0.00000000000001) + c->switch_physics(true); + c->Pipe2->Flow(-dv2); + } + if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); + Couplers[0].Connected->Pipe2->Flow(+dV); + Couplers[1].Connected->Pipe2->Flow(-dV); + } Pipe2->Flow(Hamulec->GetHPFlow(ScndPipePress, dt)); // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well @@ -4841,7 +4780,7 @@ void TMoverParameters::UpdateScndPipePressure(double dt) // yB: 20190906 // Aktualizacja ciśnienia w hamulcu sprezynowym // ************************************************************************************************* -void TMoverParameters::UpdateSpringBrake(double dt) +void TMoverParameters::UpdateSpringBrake(double /*dt*/) { double BP = SpringBrake.PNBrakeConnection ? BrakePress : 0; double MSP = SpringBrake.ShuttOff ? 0 : SpringBrake.MaxSetPressure; @@ -4875,30 +4814,29 @@ double TMoverParameters::GetDVc(double dt) { // T_MoverParameters *c; TMoverParameters *c; - double dv1, dv2; // , dV; + double dv1; + double dv2; // , dV; dv1 = 0; dv2 = 0; // sprzeg 1 - if (Couplers[0].Connected != nullptr) - if (TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) - { //*0.85 - c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L - dv1 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); - if (dv1 * dv1 > 0.00000000000001) - c->switch_physics(true); - c->Pipe->Flow(-dv1); - } + if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) + { //*0.85 + c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L + dv1 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); + if (dv1 * dv1 > 0.00000000000001) + c->switch_physics(true); + c->Pipe->Flow(-dv1); + } // sprzeg 2 - if (Couplers[1].Connected != nullptr) - if (TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); - if (dv2 * dv2 > 0.00000000000001) - c->switch_physics(true); - c->Pipe->Flow(-dv2); - } + if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); + if (dv2 * dv2 > 0.00000000000001) + c->switch_physics(true); + c->Pipe->Flow(-dv2); + } // if ((Couplers[1].Connected != NULL) && (Couplers[0].Connected != NULL)) // if ((TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) && // (TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic))) @@ -4919,11 +4857,13 @@ double TMoverParameters::GetDVc(double dt) // ************************************************************************************************* void TMoverParameters::ComputeConstans(void) { - double BearingF, RollF, HideModifier; + double BearingF; + double RollF; + double HideModifier; double Curvature; // Ra 2014-07: odwrotność promienia TotalMassxg = TotalMass * g; // TotalMass*g - BearingF = DamageFlag & dtrain_bearing > 0 ? 2.0 : 0; + BearingF = (DamageFlag & dtrain_bearing) != 0 ? 2.0 : 0; HideModifier = 0; // int(Couplers[0].CouplingFlag>0)+int(Couplers[1].CouplingFlag>0); @@ -4948,7 +4888,7 @@ void TMoverParameters::ComputeConstans(void) // drag calculation { // NOTE: draft effect of previous vehicle is simplified and doesn't have much to do with reality - auto const *previousvehicle{Couplers[(V >= 0.0 ? end::front : end::rear)].Connected}; + auto const *previousvehicle{Couplers[V >= 0.0 ? end::front : end::rear].Connected}; auto dragarea{Dim.W * Dim.H}; if (previousvehicle) { @@ -5177,7 +5117,7 @@ double TMoverParameters::BrakeForceR(double ratio, double velocity) return BrakeForceP(press * ratio, velocity); } -double TMoverParameters::BrakeForceP(double press, double velocity) +double TMoverParameters::BrakeForceP(double press, double velocity) const { double BFP = 0; double K = ((press * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj) * BrakeRigEff; @@ -5190,10 +5130,11 @@ double TMoverParameters::BrakeForceP(double press, double velocity) // Q: 20160713 // oblicza siłę na styku koła i szyny // ************************************************************************************************* -double TMoverParameters::BrakeForce(TTrackParam const &Track) +double TMoverParameters::BrakeForce(TTrackParam const & /*Track*/) { - double K{0}, Fb{0}, sm{0}; + double K{0}; + double brakeforce{0}; switch (LocalBrake) { @@ -5250,11 +5191,11 @@ double TMoverParameters::BrakeForce(TTrackParam const &Track) // Fb:=UnitBrakeForce*NBpA {ham. reczny dziala na jedna os} // else //yB: to nie do konca ma sens, ponieważ ręczny w wagonie działa na jeden cylinder // hamulcowy/wózek, dlatego potrzebne są oddzielnie liczone osie - Fb = UnitBrakeForce * NBrakeAxles * std::max(1, NBpA); + brakeforce = UnitBrakeForce * NBrakeAxles * std::max(1, NBpA); // u:=((BrakePress*P2FTrans)-BrakeCylSpring*BrakeCylMult[BCMFlag]/BrakeCylNo-0.83*BrakeSlckAdj/(BrakeCylNo))*BrakeCylNo; // { end; } - return Fb; + return brakeforce; } // ************************************************************************************************* @@ -5334,7 +5275,7 @@ double TMoverParameters::Adhesive(double staticfriction) const double TMoverParameters::CouplerForce(int const End, double dt) { - auto &coupler{Couplers[End]}; + auto &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; auto const otherend{Neighbours[End].vehicle_end}; auto &othercoupler{othervehicle->Couplers[otherend]}; @@ -5349,81 +5290,81 @@ double TMoverParameters::CouplerForce(int const End, double dt) auto const absdV{std::abs(dV)}; // potentially generate sounds on clash or stretch - if (newdistance < 0.0 && coupler.Dist > newdistance && dV < -0.1 && false == coupler.has_adapter()) + if (newdistance < 0.0 && thiscoupler.Dist > newdistance && dV < -0.1 && false == thiscoupler.has_adapter()) { // HACK: with adapter present we presume buffers won't clash // 090503: dzwieki pracy zderzakow - SetFlag(coupler.sounds, absdV > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash); + SetFlag(thiscoupler.sounds, absdV > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash); } - else if (coupler.CouplingFlag != coupling::faux && newdistance > 0.001 && coupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0) + else if (thiscoupler.CouplingFlag != coupling::faux && newdistance > 0.001 && thiscoupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0) { // 090503: dzwieki pracy sprzegu - SetFlag(coupler.sounds, absdV > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch); + SetFlag(thiscoupler.sounds, absdV > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch); } - coupler.CheckCollision = false; - coupler.Dist = 0.0; + thiscoupler.CheckCollision = false; + thiscoupler.Dist = 0.0; double CF{0.0}; - if (coupler.CouplingFlag == coupling::faux && initialdistance > 0.05) + if (thiscoupler.CouplingFlag == coupling::faux && initialdistance > 0.05) { // arbitrary distance // potentially reset auto coupling lock - coupler.AutomaticCouplingAllowed = true; + thiscoupler.AutomaticCouplingAllowed = true; } - if (coupler.CouplingFlag != coupling::faux || initialdistance < 0) + if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) { - coupler.Dist = std::clamp(newdistance, coupler.has_adapter() ? 0 : -coupler.DmaxB, coupler.DmaxC); + thiscoupler.Dist = std::clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); double BetaAvg = 0; double Fmax = 0; - if (coupler.CouplingFlag == coupling::faux) + if (thiscoupler.CouplingFlag == coupling::faux) { - BetaAvg = coupler.beta; - Fmax = (coupler.FmaxC + coupler.FmaxB) * CouplerTune; + BetaAvg = thiscoupler.beta; + Fmax = (thiscoupler.FmaxC + thiscoupler.FmaxB) * CouplerTune; } else { // usrednij bo wspolny sprzeg - BetaAvg = 0.5 * (coupler.beta + othercoupler.beta); - Fmax = 0.5 * (coupler.FmaxC + coupler.FmaxB + othercoupler.FmaxC + othercoupler.FmaxB) * CouplerTune; + BetaAvg = 0.5 * (thiscoupler.beta + othercoupler.beta); + Fmax = 0.5 * (thiscoupler.FmaxC + thiscoupler.FmaxB + othercoupler.FmaxC + othercoupler.FmaxB) * CouplerTune; } - auto const distDelta{std::abs(newdistance) - std::abs(coupler.Dist)}; // McZapkie-191103: poprawka na histereze + auto const distDelta{std::abs(newdistance) - std::abs(thiscoupler.Dist)}; // McZapkie-191103: poprawka na histereze if (newdistance > 0) { if (distDelta > 0) { - CF = -(coupler.SpringKC + othercoupler.SpringKC) * coupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; + CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; } else { - CF = -(coupler.SpringKC + othercoupler.SpringKC) * coupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; + CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; } // liczenie sily ze sprezystosci sprzegu - if (newdistance > coupler.DmaxC + othercoupler.DmaxC) + if (newdistance > thiscoupler.DmaxC + othercoupler.DmaxC) { // zderzenie - coupler.CheckCollision = true; + thiscoupler.CheckCollision = true; } - if (std::abs(CF) > coupler.FmaxC) + if (std::abs(CF) > thiscoupler.FmaxC) { // coupler is stretched with excessive force, may break - coupler.stretch_duration += dt; + thiscoupler.stretch_duration += static_cast(dt); // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks // (arbitrary) chance to break grows from 10-100% over 10 sec period - if (Global.crash_damage && coupler.stretch_duration > 1.f && Random() < coupler.stretch_duration * 0.1f * dt) + if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) { damage_coupler(End); } } else { - coupler.stretch_duration = 0.f; + thiscoupler.stretch_duration = 0.f; } } if (newdistance < 0) @@ -5431,52 +5372,49 @@ double TMoverParameters::CouplerForce(int const End, double dt) if (distDelta > 0) { - CF = -(coupler.SpringKB + othercoupler.SpringKB) * coupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; + CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; } else { - CF = -(coupler.SpringKB + othercoupler.SpringKB) * coupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; + CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; } // liczenie sily ze sprezystosci zderzaka - auto const collisiondistance{(coupler.has_adapter() || othercoupler.has_adapter() ? - std::min(coupler.DmaxB, othercoupler.DmaxB) : // HACK: only take into account buffering ability of automatic coupler - coupler.DmaxB + othercoupler.DmaxB)}; + auto const collisiondistance{(thiscoupler.has_adapter() || othercoupler.has_adapter() ? + std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : // HACK: only take into account buffering ability of automatic coupler + thiscoupler.DmaxB + othercoupler.DmaxB)}; if (-newdistance > collisiondistance) { // zderzenie - coupler.CheckCollision = true; + thiscoupler.CheckCollision = true; } - if (-newdistance >= std::min(collisiondistance, dEpsilon)) - { - if (coupler.type() == TCouplerType::Automatic && coupler.type() == othercoupler.type() && coupler.CouplingFlag == coupling::faux && - coupler.AutomaticCouplingAllowed && + if (-newdistance >= std::min(collisiondistance, dEpsilon) && thiscoupler.type() == TCouplerType::Automatic && thiscoupler.type() == othercoupler.type() && thiscoupler.CouplingFlag == coupling::faux && + thiscoupler.AutomaticCouplingAllowed && othercoupler.AutomaticCouplingAllowed) + { + // sprzeganie wagonow z samoczynnymi sprzegami + auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; + // potentially exclude incompatible control coupling + if (thiscoupler.control_type != othercoupler.control_type) { - // sprzeganie wagonow z samoczynnymi sprzegami - auto couplingtype{coupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; - // potentially exclude incompatible control coupling - if (coupler.control_type != othercoupler.control_type) - { - couplingtype &= ~coupling::control; - } - - if (Attach(End, otherend, othervehicle, couplingtype)) - { - // HACK: we're reusing sound enum to mark whether vehicle was connected to another - SetFlag(AIFlag, sound::attachcoupler); - coupler.AutomaticCouplingAllowed = false; - othercoupler.AutomaticCouplingAllowed = false; - } - /* - coupler.CouplingFlag = ( coupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag ); - SetFlag( coupler.sounds, sound::attachcoupler ); - */ + couplingtype &= ~coupling::control; } + + if (Attach(End, otherend, othervehicle, couplingtype)) + { + // HACK: we're reusing sound enum to mark whether vehicle was connected to another + SetFlag(AIFlag, sound::attachcoupler); + thiscoupler.AutomaticCouplingAllowed = false; + othercoupler.AutomaticCouplingAllowed = false; + } + /* + coupler.CouplingFlag = ( coupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag ); + SetFlag( coupler.sounds, sound::attachcoupler ); + */ } } } - if (coupler.CouplingFlag != coupling::faux) + if (thiscoupler.CouplingFlag != coupling::faux) { // uzgadnianie prawa Newtona othervehicle->Couplers[1 - End].CForce = -CF; @@ -5491,7 +5429,10 @@ double TMoverParameters::CouplerForce(int const End, double dt) // ************************************************************************************************* double TMoverParameters::TractionForce(double dt) { - double PosRatio, dmoment, dtrans, tmp; + double PosRatio; + double dmoment; + double dtrans; + double tmp; Ft = 0; dtrans = 0; @@ -5507,7 +5448,7 @@ double TMoverParameters::TractionForce(double dt) if (EIMCtrlType > 0) // sterowanie cyfrowe tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; else - tmp = DElist[(ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos)].RPM / 60.0; + tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) { @@ -5628,14 +5569,14 @@ double TMoverParameters::TractionForce(double dt) { // TBD, TODO: currently ignores RVentType, fix this? RventRot += std::clamp(enrot - RventRot, -100.0, 50.0) * dt; - dizel_heat.rpmw += std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt; - dizel_heat.rpmw2 += std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt; + dizel_heat.rpmw += static_cast(std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt); + dizel_heat.rpmw2 += static_cast(std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt); } else { RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - dizel_heat.rpmw *= std::max(0.0, 1.0 - dizel_heat.rpmw * dt); - dizel_heat.rpmw2 *= std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt); + dizel_heat.rpmw *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw * dt)); + dizel_heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt)); } break; } @@ -5645,13 +5586,13 @@ double TMoverParameters::TractionForce(double dt) // NOTE: we update only radiator fans, as vehicles with diesel engine don't have other ventilators if (true == Mains) { - dizel_heat.rpmw += std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt; - dizel_heat.rpmw2 += std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt; + dizel_heat.rpmw += static_cast(std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt); + dizel_heat.rpmw2 += static_cast(std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt); } else { - dizel_heat.rpmw *= std::max(0.0, 1.0 - dizel_heat.rpmw * dt); - dizel_heat.rpmw2 *= std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt); + dizel_heat.rpmw *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw * dt)); + dizel_heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt)); } break; } @@ -5711,14 +5652,11 @@ double TMoverParameters::TractionForce(double dt) case TEngineType::ElectricInductionMotor: { // TODO: check if we can use instead the code for electricseriesmotor - if (Mains) + // nie wchodzić w funkcję bez potrzeby + if (Mains && (std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV || + std::max(GetTrainsetHighVoltage(), PantographVoltage) > EnginePowerSource.CollectorParameters.MaxV + 200)) { - // nie wchodzić w funkcję bez potrzeby - if (std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV || - std::max(GetTrainsetHighVoltage(), PantographVoltage) > EnginePowerSource.CollectorParameters.MaxV + 200) - { - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide - } + MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide } break; } @@ -5765,9 +5703,8 @@ double TMoverParameters::TractionForce(double dt) case TEngineType::WheelsDriven: { - if (EnginePowerSource.SourceType == TPowerSource::InternalSource) - if (EnginePowerSource.PowerType == TPowerType::BioPower) - Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; + if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) + Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; PulseForceTimer = PulseForceTimer + dt; if (PulseForceTimer > CtrlDelay) { @@ -5936,7 +5873,6 @@ double TMoverParameters::TractionForce(double dt) auto power = Power; tempImax = DElist[MainCtrlPos].Imax; tempUmax = DElist[MainCtrlPos].Umax; - tempPmax = DElist[MainCtrlPos].GenPower; if (true == Heating) { power -= HeatingPower; @@ -6193,24 +6129,21 @@ double TMoverParameters::TractionForce(double dt) } } // malenie - if (MainCtrlPos < 12 && ScndCtrlPos > 0) + if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) { - if (Vel < 50.0) + // above 50 km/h already active shunt field can be maintained until lower controller setting + if (ScndCtrlPos % 2 == 0) { - // above 50 km/h already active shunt field can be maintained until lower controller setting - if (ScndCtrlPos % 2 == 0) + if (MPTRelay[ScndCtrlPos].Idown < Im) { - if (MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } + --ScndCtrlPos; } - else + } + else + { + if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) { - if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } + --ScndCtrlPos; } } } @@ -6244,7 +6177,7 @@ double TMoverParameters::TractionForce(double dt) if (true == Mains && !SecuritySystem.is_engine_blocked()) { double ActiveInverters = 0.0; - for (auto &inv : Inverters) + for (auto const &inv : Inverters) { if (inv.IsActive) ActiveInverters += 1.0; @@ -6296,6 +6229,8 @@ double TMoverParameters::TractionForce(double dt) SpeedCtrlValue = Vmax; SpeedCtrlTimer = 10; break; + default: + break; } } else if (ScndCtrlPosNo > 1) @@ -6311,7 +6246,7 @@ double TMoverParameters::TractionForce(double dt) SpeedCtrlTimer += dt; if (SpeedCtrlTimer > SpeedCtrlDelay) { - int NewSCAP = (float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax; + auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); if (NewSCAP != SpeedCtrlValue) { SpeedCtrlValue = NewSCAP; @@ -6350,7 +6285,7 @@ double TMoverParameters::TractionForce(double dt) { PosRatio = 0; } - PosRatio = Round(20.0 * PosRatio) / 20.0; // stopniowanie PN/ED + PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED if (PosRatio < 19.5 / 20.0) PosRatio *= 0.9; Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia @@ -6397,7 +6332,6 @@ double TMoverParameters::TractionForce(double dt) // (Hamulec as TLSt).SetLBP(LocBrakePress); tmp = 4; // szybkie malenie, powolne wzrastanie } - dmoment = eimv[eimv_Fful]; // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions // TODO: gather these in single place so they can be resolved together if (SlippingWheels) @@ -6501,9 +6435,8 @@ double TMoverParameters::TractionForce(double dt) auto const tmpV{std::abs(eimv[eimv_fp])}; auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; auto const list = useFFEDList ? FFEDlist : FFlist; - auto const listSize = useFFEDList ? FFEDListSize : FFListSize; - if (listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) + if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) { int i = 0; @@ -6540,8 +6473,8 @@ double TMoverParameters::TractionForce(double dt) eimv_pr = 0.0; EnginePower = 0.0; { - for (int i = 0; i < 21; ++i) - eimv[i] = 0.0; + for (auto &eimvvalue : eimv) + eimvvalue = 0.0; } Hamulec->SetED(0.0); InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); @@ -6556,18 +6489,10 @@ double TMoverParameters::TractionForce(double dt) } } // case EngineType - switch (EngineType) - { - case TEngineType::DieselElectric: + if (EngineType == TEngineType::DieselElectric) { // rough approximation of extra effort to overcome friction etc EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; - break; - } - default: - { - break; - } } return Ft; @@ -6579,7 +6504,8 @@ double TMoverParameters::TractionForce(double dt) // ************************************************************************************************* double TMoverParameters::ComputeRotatingWheel(double WForce, double dt, double n) const { - double newn = 0, eps = 0; + double newn = 0; + double eps = 0; if (n == 0 && WForce * Sign(V) < 0) newn = 0; else @@ -6604,10 +6530,9 @@ bool TMoverParameters::FuseFlagCheck(void) const if (Power > 0.01) FFC = FuseFlag; else // pobor pradu jezeli niema mocy - for (int b = 0; b < 2; b++) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Power > 0.01) - FFC = Couplers[b].Connected->FuseFlagCheck(); + for (auto &thiscoupler : Couplers) + if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) + FFC = thiscoupler.Connected->FuseFlagCheck(); return FFC; } @@ -6641,8 +6566,7 @@ void TMoverParameters::FuseOff(void) bool TMoverParameters::UniversalResetButton(int const Button, range_t const Notify) { - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - if (false == lowvoltagepower) + if (auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; false == lowvoltagepower) { return false; } @@ -6665,43 +6589,34 @@ bool TMoverParameters::RelayReset(int const Relays, range_t const Notify) auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; bool reset{false}; - if (TestFlag(Relays, relay_t::maincircuitground)) - { - if ((EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && + if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && (GroundRelayStart == start_t::manual || GroundRelayStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && !TestFlag(EngDmgFlag, 1)) - { - // NOTE: true means the relay is operational - reset |= !GroundRelay && lowvoltagepower; - GroundRelay |= lowvoltagepower; - } + { + // NOTE: true means the relay is operational + reset |= !GroundRelay && lowvoltagepower; + GroundRelay |= lowvoltagepower; } - if (TestFlag(Relays, relay_t::tractionnmotoroverload)) - { - if ((EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && + if (TestFlag(Relays, relay_t::tractionnmotoroverload) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && !TestFlag(EngDmgFlag, 1)) - { - // NOTE: false means the relay is operational - // TODO: cleanup, flip the FuseFlag code to match other relays - // TODO: check whether the power is required, TBD, TODO: make it configurable? - reset |= FuseFlag && lowvoltagepower; - FuseFlag &= !lowvoltagepower; - } + { + // NOTE: false means the relay is operational + // TODO: cleanup, flip the FuseFlag code to match other relays + // TODO: check whether the power is required, TBD, TODO: make it configurable? + reset |= FuseFlag && lowvoltagepower; + FuseFlag &= !lowvoltagepower; } - if (TestFlag(Relays, relay_t::primaryconverteroverload)) - { - if (ConverterOverloadRelayStart == start_t::manual + if (TestFlag(Relays, relay_t::primaryconverteroverload) && ConverterOverloadRelayStart == start_t::manual // && ( false == Mains ) && false == ConverterAllow) - { - // NOTE: false means the relay is operational - // TODO: cleanup, flip the FuseFlag code to match other relays - // TODO: check whether the power is required, TBD, TODO: make it configurable? - reset |= ConvOvldFlag && lowvoltagepower; - ConvOvldFlag &= !lowvoltagepower; - } + { + // NOTE: false means the relay is operational + // TODO: cleanup, flip the FuseFlag code to match other relays + // TODO: check whether the power is required, TBD, TODO: make it configurable? + reset |= ConvOvldFlag && lowvoltagepower; + ConvOvldFlag &= !lowvoltagepower; } if (reset) @@ -6725,7 +6640,8 @@ double TMoverParameters::v2n(void) { // przelicza predkosc liniowa na obrotowa const double dmgn = 0.5; - double n, deltan = 0; + double n; + double deltan = 0; n = V / (M_PI * WheelDiameter); // predkosc obrotowa wynikajaca z liniowej [obr/s] deltan = n - nrot; //"pochodna" prędkości obrotowej @@ -6734,14 +6650,10 @@ double TMoverParameters::v2n(void) SlippingWheels = false; // wygaszenie poslizgu */ //poslizg jest w innym miejscu wygaszany też if (SlippingWheels) // nie ma zwiazku z predkoscia liniowa V { // McZapkie-221103: uszkodzenia kol podczas poslizgu - if (deltan > dmgn) - if (FuzzyLogic(deltan, dmgn, p_slippdmg)) - if (SetFlag(DamageFlag, dtrain_wheelwear)) // podkucie - EventFlag = true; - if (deltan < -dmgn) - if (FuzzyLogic(-deltan, dmgn, p_slippdmg)) - if (SetFlag(DamageFlag, dtrain_thinwheel)) // wycieranie sie obreczy - EventFlag = true; + if (deltan > dmgn && FuzzyLogic(deltan, dmgn, p_slippdmg) && SetFlag(DamageFlag, dtrain_wheelwear)) // podkucie + EventFlag = true; + if (deltan < -dmgn && FuzzyLogic(-deltan, dmgn, p_slippdmg) && SetFlag(DamageFlag, dtrain_thinwheel)) // wycieranie sie obreczy + EventFlag = true; n = nrot; // predkosc obrotowa nie zalezy od predkosci liniowej } return n; @@ -6751,15 +6663,14 @@ double TMoverParameters::v2n(void) // Q: 20160714 // Oblicza moment siły wytwarzany przez silnik // ************************************************************************************************* -double TMoverParameters::Momentum(double I) +double TMoverParameters::Momentum(double I) const { // liczy moment sily wytwarzany przez silnik elektryczny} int SP; SP = ScndCtrlActualPos; - if (ScndInMain) - if (!(RList[MainCtrlActualPos].ScndAct == 255)) - SP = RList[MainCtrlActualPos].ScndAct; + if (ScndInMain && !(RList[MainCtrlActualPos].ScndAct == 255)) + SP = RList[MainCtrlActualPos].ScndAct; // Momentum:=mfi*I*(1-1.0/(Abs(I)/mIsat+1)); return motor_param(SP).mfi * I * (abs(I) / (abs(I) + motor_param(SP).mIsat) - motor_param(SP).mfi0); @@ -6769,7 +6680,7 @@ double TMoverParameters::Momentum(double I) // Q: 20160714 // Oblicza moment siły do sterowania wzbudzeniem // ************************************************************************************************* -double TMoverParameters::MomentumF(double I, double Iw, int SCP) +double TMoverParameters::MomentumF(double I, double Iw, int SCP) const { // umozliwia dokladne sterowanie wzbudzeniem @@ -6783,13 +6694,10 @@ double TMoverParameters::MomentumF(double I, double Iw, int SCP) bool TMoverParameters::CutOffEngine(void) { bool COE = false; // Ra: wartość domyślna, sprawdzić to trzeba - if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor) + if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && SetFlag(DamageFlag, -dtrain_engine)) { - if (SetFlag(DamageFlag, -dtrain_engine)) - { - NPoweredAxles = NPoweredAxles / 2; // bylo div czyli mod? - COE = true; - } + NPoweredAxles = NPoweredAxles / 2; // bylo div czyli mod? + COE = true; } return COE; } @@ -6852,10 +6760,9 @@ bool TMoverParameters::ResistorsFlagCheck(void) const RFC = ResistorsFlag; else // pobor pradu jezeli niema mocy { - for (int b = 0; b < 2; b++) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Power > 0.01) - RFC = Couplers[b].Connected->ResistorsFlagCheck(); + for (auto &thiscoupler : Couplers) + if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) + RFC = thiscoupler.Connected->ResistorsFlagCheck(); } return RFC; } @@ -6887,7 +6794,6 @@ bool TMoverParameters::AutoRelaySwitch(bool State) bool TMoverParameters::AutoRelayCheck(void) { bool OK = false; // b:int; - bool ARC = false; auto const motorconnectorsoff{false == MotorConnectorsCheck()}; @@ -6944,16 +6850,13 @@ bool TMoverParameters::AutoRelayCheck(void) } else { // zmieniaj mainctrlactualpos - if (DirActive < 0 && TrainType != dt_PseudoDiesel) + if (DirActive < 0 && TrainType != dt_PseudoDiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed) { - if (RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed) - { - return false; // nie poprawiamy przy konwersji - // return ARC;// bbylo exit; //Ra: to powoduje, że EN57 nie wyłącza się przy IminLo - } + return false; // nie poprawiamy przy konwersji + // return ARC;// bbylo exit; //Ra: to powoduje, że EN57 nie wyłącza się przy IminLo } // main bez samoczynnego rozruchu - if (MainCtrlActualPos < sizeof(RList) / sizeof(TScheme) - 1 // crude guard against running out of current fixed table + if (MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || (TrainType == dt_ET22 && DelayCtrlFlag))) { @@ -7048,12 +6951,12 @@ bool TMoverParameters::AutoRelayCheck(void) --MainCtrlActualPos; OK = true; } - if (MainCtrlActualPos > 0) // hunter-111211: poprawki - if (RList[MainCtrlActualPos].R == 0) - { - // dzwieki schodzenia z bezoporowej} - SetFlag(SoundFlag, sound::parallel); - } + // hunter-111211: poprawki + if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) + { + // dzwieki schodzenia z bezoporowej} + SetFlag(SoundFlag, sound::parallel); + } } } else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) @@ -7205,40 +7108,41 @@ bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t switch (State) { - case operation_t::none: + using enum operation_t; + case none: { valve.is_enabled = false; valve.is_disabled = false; break; } - case operation_t::enable: + case enable: { valve.is_enabled = true; valve.is_disabled = false; break; } - case operation_t::disable: + case disable: { valve.is_enabled = false; valve.is_disabled = true; break; } - case operation_t::enable_on: + case enable_on: { valve.is_enabled = true; break; } - case operation_t::enable_off: + case enable_off: { valve.is_enabled = false; break; } - case operation_t::disable_on: + case disable_on: { valve.is_disabled = true; break; } - case operation_t::disable_off: + case disable_off: { valve.is_disabled = false; break; @@ -7264,40 +7168,41 @@ bool TMoverParameters::OperatePantographValve(end const End, operation_t const S switch (State) { - case operation_t::none: + using enum operation_t; + case none: { valve.is_enabled = false; valve.is_disabled = false; break; } - case operation_t::enable: + case enable: { valve.is_enabled = true; valve.is_disabled = false; break; } - case operation_t::disable: + case disable: { valve.is_enabled = false; valve.is_disabled = true; break; } - case operation_t::enable_on: + case enable_on: { valve.is_enabled = true; break; } - case operation_t::enable_off: + case enable_off: { valve.is_enabled = false; break; } - case operation_t::disable_on: + case disable_on: { valve.is_disabled = true; break; } - case operation_t::disable_off: + case disable_off: { valve.is_disabled = false; break; @@ -7390,6 +7295,8 @@ void TMoverParameters::CheckEIMIC(double dt) case 7: // TMax eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max break; + default: + break; } if (MainCtrlPos >= 3 && eimic < 0) eimic = 0; @@ -7419,6 +7326,8 @@ void TMoverParameters::CheckEIMIC(double dt) if (eimic < 0) eimic = 0; break; + default: + break; } } if (MainCtrlActualPos == MainCtrlPos) @@ -7537,11 +7446,8 @@ void TMoverParameters::CheckSpeedCtrl(double dt) { SpeedCtrlUnit.Standby = false; } - if (!SpeedCtrlUnit.BrakeIntervention) - { - if (Hamulec->GetEDBCP() > 0.4 || PipePress < HighPipePress - 0.2) - SpeedCtrlUnit.Standby = true; - } + if (!SpeedCtrlUnit.BrakeIntervention && (Hamulec->GetEDBCP() > 0.4 || PipePress < HighPipePress - 0.2)) + SpeedCtrlUnit.Standby = true; if (EIMCtrlType >= 3 && UniCtrlList[MainCtrlPos].SpeedUp <= 0) { accfactor = 0.0; @@ -7554,11 +7460,8 @@ void TMoverParameters::CheckSpeedCtrl(double dt) { if (!SpeedCtrlUnit.Standby) { - if (SpeedCtrlUnit.ManualStateOverride) - { - if (eimic > 0.0009) - eimic = 1.0; - } + if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) + eimic = 1.0; double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module @@ -7965,7 +7868,7 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) else dizel_nreg_min = dizel_nmin; } - if (dizel_vel2nmax_Table.size() > 0 && !hydro_TC_Lockup) + if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) { dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); } @@ -8034,30 +7937,36 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) // Q: 20160715 // Oblicza moment siły wytwarzany przez silnik spalinowy // ************************************************************************************************* -double TMoverParameters::dizel_Momentum(double dizel_fill, double n, double dt) +double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) { // liczy moment sily wytwarzany przez silnik spalinowy} - double Moment = 0, enMoment = 0, gearMoment = 0, eps = 0, newn = 0, friction = 0, neps = 0; - double TorqueH = 0, TorqueL = 0, TorqueC = 0; + double Moment = 0; + double enMoment = 0; + double gearMoment = 0; + double eps = 0; + double newn = 0; + double friction = 0; + double TorqueH = 0; + double TorqueL = 0; + double TorqueC = 0; n = n * CabActive; if (motor_param(ScndCtrlActualPos).mIsat < 0.001 || DirActive == 0) n = enrot; friction = dizel_engagefriction; hydro_TC_nIn = enrot; // wal wejsciowy przetwornika momentu hydro_TC_nOut = dizel_n_old; // wal wyjsciowy przetwornika momentu - neps = (n - dizel_n_old) / dt; // przyspieszenie katowe walu wejsciowego skrzyni biegow if (enrot > 0) { if (dizel_Momentum_Table.size() > 1) { - Moment = TableInterpolation(dizel_Momentum_Table, enrot) * dizel_fill - dizel_Mstand; + Moment = TableInterpolation(dizel_Momentum_Table, enrot) * Fill - dizel_Mstand; } else { - Moment = (dizel_Mmax - (dizel_Mmax - dizel_Mnmax) * square((enrot - dizel_nMmax) / (dizel_nMmax - dizel_nmax))) * dizel_fill - dizel_Mstand; + Moment = (dizel_Mmax - (dizel_Mmax - dizel_Mnmax) * square((enrot - dizel_nMmax) / (dizel_nMmax - dizel_nmax))) * Fill - dizel_Mstand; } Mm = Moment; - dizel_FuelConsumptionActual = dizel_FuelConsumption * enrot * dizel_fill; + dizel_FuelConsumptionActual = dizel_FuelConsumption * enrot * Fill; dizel_FuelConsumptedTotal += dizel_FuelConsumptionActual * dt / 3600.0; if (hydro_R && hydro_R_Placement == 2) Moment -= dizel_MomentumRetarder(enrot, dt); @@ -8188,7 +8097,6 @@ double TMoverParameters::dizel_Momentum(double dizel_fill, double n, double dt) { dizel_engagedeltaomega = 0; gearMoment = Moment; - enMoment = 0; double enrot_min = enrot - (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) - Moment) / dizel_AIM * dt; double enrot_max = enrot + (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) + Moment) / dizel_AIM * dt; enrot = safe_clamp(n, enrot_min, enrot_max); @@ -8244,8 +8152,7 @@ double TMoverParameters::dizel_MomentumRetarder(double n, double dt) } double Moment = hydro_R_MaxTorque; - double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; - if (pwr > hydro_R_MaxPower) + if (double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; pwr > hydro_R_MaxPower) Moment = Moment * hydro_R_MaxPower / pwr; double moment_in = n * n * hydro_R_TorqueInIn; Moment = std::min(moment_in, Moment * hydro_R_Fill); @@ -8259,8 +8166,16 @@ double TMoverParameters::dizel_MomentumRetarder(double n, double dt) void TMoverParameters::dizel_HeatSet(float const Value) { - dizel_heat.Te = // TODO: don't include ambient temperature, pull it from environment data instead - dizel_heat.Ts = dizel_heat.To = dizel_heat.Tsr = dizel_heat.Twy = dizel_heat.Tsr2 = dizel_heat.Twy2 = dizel_heat.temperatura1 = dizel_heat.temperatura2 = Value; + // TODO: don't include ambient temperature, pull it from environment data instead + dizel_heat.Te = Value; + dizel_heat.Ts = Value; + dizel_heat.To = Value; + dizel_heat.Tsr = Value; + dizel_heat.Twy = Value; + dizel_heat.Tsr2 = Value; + dizel_heat.Twy2 = Value; + dizel_heat.temperatura1 = Value; + dizel_heat.temperatura2 = Value; } // calculates diesel engine temperature and heat transfers @@ -8314,13 +8229,13 @@ void TMoverParameters::dizel_Heat(double const dt) // silnik oddaje czesc ciepla do wody chlodzacej, a takze pewna niewielka czesc do otoczenia, modyfikowane przez okienko auto const Qs{(Qd - dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) - dizel_heat.kfe * /* ( 0.3 + 0.7 * ( dizel_heat.okienko ? 1 : 0 ) ) * */ (dizel_heat.Ts - dizel_heat.Te))}; auto const dTss{Qs / Cs}; - dizel_heat.Ts += dTss * dt; + dizel_heat.Ts += static_cast(dTss * dt); // oil heat transfers // olej oddaje cieplo do wody gdy krazy przez wymiennik ciepla == wlaczona pompka lub silnik auto const dTo{(dizel_heat.auxiliary_water_circuit ? (dizel_heat.kfo * (dizel_heat.Ts - dizel_heat.To) - dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr2)) / (gwO * Co) : (dizel_heat.kfo * (dizel_heat.Ts - dizel_heat.To) - dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr)) / (gwO * Co))}; - dizel_heat.To += dTo * dt; + dizel_heat.To += static_cast(dTo * dt); // heater /* @@ -8339,7 +8254,7 @@ void TMoverParameters::dizel_Heat(double const dt) (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ && dizel_heat.water_aux.config.temp_cooling > 0 && dizel_heat.temperatura2 > dizel_heat.water_aux.config.temp_cooling - (dizel_heat.water_aux.is_warm ? 8 : 0)); auto const PTC2{(dizel_heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; - dizel_heat.rpmwz2 = PTC2 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1); + dizel_heat.rpmwz2 = static_cast(PTC2 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1)); dizel_heat.zaluzje2 = dizel_heat.water_aux.config.shutters ? PTC2 == 1 : true; // no shutters is an equivalent to having them open auto const zaluzje2{(dizel_heat.zaluzje2 ? 1 : 0)}; // auxiliary water circuit heat transfer values @@ -8351,8 +8266,8 @@ void TMoverParameters::dizel_Heat(double const dt) // auxiliary water circuit heat transfers finalization // NOTE: since primary circuit doesn't read data from the auxiliary one, we can pretty safely finalize auxiliary updates before touching the primary circuit auto const Twe2{dizel_heat.Twy2 + dTch2 * dt}; - dizel_heat.Twy2 = Twe2 + dTs2 * dt; - dizel_heat.Tsr2 = 0.5 * (dizel_heat.Twy2 + Twe2); + dizel_heat.Twy2 = static_cast(Twe2 + dTs2 * dt); + dizel_heat.Tsr2 = static_cast(0.5 * (dizel_heat.Twy2 + Twe2)); dizel_heat.temperatura2 = dizel_heat.Twy2; } // primary water circuit setup @@ -8362,7 +8277,7 @@ void TMoverParameters::dizel_Heat(double const dt) true == dizel_heat.cooling || (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ && dizel_heat.water.config.temp_cooling > 0 && dizel_heat.temperatura1 > dizel_heat.water.config.temp_cooling - (dizel_heat.water.is_warm ? 8 : 0)); auto const PTC1{(dizel_heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; - dizel_heat.rpmwz = PTC1 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1); + dizel_heat.rpmwz = static_cast(PTC1 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1)); dizel_heat.zaluzje1 = dizel_heat.water.config.shutters ? PTC1 == 1 : true; // no shutters is an equivalent to having them open auto const zaluzje1{(dizel_heat.zaluzje1 ? 1 : 0)}; // primary water circuit heat transfer values @@ -8373,8 +8288,8 @@ void TMoverParameters::dizel_Heat(double const dt) auto const dTch{Qch / (gw * Cw)}; // primary water circuit heat transfers finalization auto const Twe{dizel_heat.Twy + dTch * dt}; - dizel_heat.Twy = Twe + dTs * dt; - dizel_heat.Tsr = 0.5 * (dizel_heat.Twy + Twe); + dizel_heat.Twy = static_cast(Twe + dTs * dt); + dizel_heat.Tsr = static_cast(0.5 * (dizel_heat.Twy + Twe)); dizel_heat.temperatura1 = dizel_heat.Twy; /* fuelConsumed = fuelConsumed + ( Ge * 0.5 ); @@ -8422,10 +8337,10 @@ void TMoverParameters::dizel_Heat(double const dt) */ } -bool TMoverParameters::AssignLoad(std::string const &Name, float const Amount) +bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amount) { - if (Name == "pantstate") + if (Loadname == "pantstate") { if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { @@ -8465,40 +8380,38 @@ bool TMoverParameters::AssignLoad(std::string const &Name, float const Amount) } } - if (Name.empty()) + if (Loadname.empty()) { // empty the vehicle if requested - LoadTypeChange = LoadType.name != Name; + LoadTypeChange = LoadType.name != Loadname; LoadType = load_attributes(); LoadAmount = 0.f; return true; } // can't mix load types, at least for the time being - if (LoadAmount > 0 && LoadType.name != Name) + if (LoadAmount > 0 && LoadType.name != Loadname) { return false; } - for (auto const &loadattributes : LoadAttributes) + auto const loadattributes = std::ranges::find_if(LoadAttributes, [&](auto const &attributes) { return attributes.name == Loadname; }); + if (loadattributes == std::end(LoadAttributes)) { - if (Name == loadattributes.name) - { - LoadTypeChange = LoadType.name != Name; - LoadType = loadattributes; - LoadAmount = std::clamp(Amount, 0.f, MaxLoad); - ComputeMass(); - return true; - } + // didn't find matching load configuration, this type is unsupported + return false; } - // didn't find matching load configuration, this type is unsupported - return false; + LoadTypeChange = LoadType.name != Loadname; + LoadType = *loadattributes; + LoadAmount = std::clamp(Amount, 0.f, MaxLoad); + ComputeMass(); + return true; } // ************************************************************************************************* // Q: 20160713 // Test zakończenia załadunku / rozładunku // ************************************************************************************************* -bool TMoverParameters::LoadingDone(double const LSpeed, std::string const &Loadname) +bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadname) { if (LSpeed == 0.0) @@ -8555,7 +8468,7 @@ bool TMoverParameters::LoadingDone(double const LSpeed, std::string const &Loadn if (LoadAmount >= MaxLoad * (1.0 + OverLoadFactor) || CommandIn.Value1 <= 0) { LoadStatus = 4; // skończony załadunek - LoadAmount = std::min(MaxLoad * (1.0 + OverLoadFactor), LoadAmount); + LoadAmount = std::min(static_cast(MaxLoad * (1.0 + OverLoadFactor)), LoadAmount); } ComputeMass(); } @@ -8794,10 +8707,10 @@ void TMoverParameters::update_doors(double const Deltatime) if (false == door.step_unfolding // no wait if no doorstep || Doors.step_type == 2) { // no wait for rotating doorstep - door.open_delay += Deltatime; + door.open_delay += static_cast(Deltatime); if (door.open_delay > Doors.open_delay) { - door.position = std::min(Doors.range, door.position + Doors.open_rate * Deltatime); + door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); } } door.close_delay = 0.f; @@ -8805,10 +8718,10 @@ void TMoverParameters::update_doors(double const Deltatime) if (true == door.is_closing) { // close door - door.close_delay += Deltatime; + door.close_delay += static_cast(Deltatime); if (door.close_delay > Doors.close_delay) { - door.position = std::max(0.f, door.position - Doors.close_rate * Deltatime); + door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); } door.open_delay = 0.f; } @@ -8816,7 +8729,7 @@ void TMoverParameters::update_doors(double const Deltatime) if (door.step_unfolding) { // unfold left doorstep - door.step_position = std::min(1.f, door.step_position + Doors.step_rate * Deltatime); + door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); } if (door.step_folding) { @@ -8826,12 +8739,12 @@ void TMoverParameters::update_doors(double const Deltatime) // multi-unit vehicles typically fold the doorstep only after closing the door if (door.position <= 0.f) { - door.step_position = std::max(0.f, door.step_position - Doors.step_rate * Deltatime); + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); } } else { - door.step_position = std::max(0.f, door.step_position - Doors.step_rate * Deltatime); + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); } } } @@ -8854,7 +8767,7 @@ void TMoverParameters::update_doors(double const Deltatime) if (door.auto_timer > 0.f) { - door.auto_timer -= Deltatime; + door.auto_timer -= static_cast(Deltatime); } // if there's load exchange in progress, reset the timer(s) for already open doors if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0) @@ -8908,9 +8821,7 @@ bool TMoverParameters::ChangeOffsetH(double DeltaOffset) std::string TMoverParameters::EngineDescription(int what) const { std::string outstr{"OK"}; - switch (what) - { - case 0: + if (what == 0) { if (DamageFlag == 255) { @@ -8960,13 +8871,10 @@ std::string TMoverParameters::EngineDescription(int what) const outstr = "DERAILED"; } } - break; } - default: + else { outstr = "Invalid qualifier"; - break; - } } return outstr; } @@ -8978,22 +8886,21 @@ std::string TMoverParameters::EngineDescription(int what) const double TMoverParameters::GetTrainsetVoltage(int const Coupling) const { // ABu: funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT // TBD, TODO: call once per vehicle update, return cached results? - double voltages[] = {0.0, 0.0}; + std::array voltages{0.0, 0.0}; for (int end = end::front; end <= end::rear; ++end) { if (Couplers[end].Connected == nullptr) { continue; } - auto const &coupler{Couplers[end]}; - auto const fullcoupling{coupler.CouplingFlag | (TestFlag(coupler.CouplingFlag, coupler.PowerCoupling) ? coupler.PowerFlag : 0)}; - if ((fullcoupling & Coupling) == 0) + auto const &thiscoupler{Couplers[end]}; + if (auto const fullcoupling{thiscoupler.CouplingFlag | (TestFlag(thiscoupler.CouplingFlag, thiscoupler.PowerCoupling) ? thiscoupler.PowerFlag : 0)}; (fullcoupling & Coupling) == 0) { continue; } - auto *connectedpowercoupling = (Coupling & (coupling::highvoltage | coupling::heating)) != 0 ? &coupler.Connected->Couplers[coupler.ConnectedNr].power_high : - (Coupling & coupling::power110v) != 0 ? &coupler.Connected->Couplers[coupler.ConnectedNr].power_110v : - (Coupling & coupling::power24v) != 0 ? &coupler.Connected->Couplers[coupler.ConnectedNr].power_24v : + auto const *connectedpowercoupling = (Coupling & (coupling::highvoltage | coupling::heating)) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_high : + (Coupling & coupling::power110v) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_110v : + (Coupling & coupling::power24v) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_24v : nullptr; if (connectedpowercoupling != nullptr && connectedpowercoupling->is_live) { @@ -9032,15 +8939,25 @@ bool TMoverParameters::switch_physics(bool const State) // DO PRZETLUMACZENIA NA // FUNKCJE PARSERA WCZYTYWANIA PLIKU FIZYKI POJAZDU // ************************************************************************************************* bool startBPT; -bool startMPT, startMPT0; -bool startRLIST, startUCLIST; -bool startDIZELMOMENTUMLIST, startDIZELV2NMAXLIST, startHYDROTCLIST, startPMAXLIST; -bool startDLIST, startFFLIST, startWWLIST, startWiperList, startDimmerList, startFFEDLIST; +bool startMPT; +bool startMPT0; +bool startRLIST; +bool startUCLIST; +bool startDIZELMOMENTUMLIST; +bool startDIZELV2NMAXLIST; +bool startHYDROTCLIST; +bool startPMAXLIST; +bool startDLIST; +bool startFFLIST; +bool startWWLIST; +bool startWiperList; +bool startDimmerList; +bool startFFEDLIST; bool startLIGHTSLIST; bool startCOMPRESSORLIST; int LISTLINE; -bool issection(std::string const &Name, std::string const &Input) +bool issection(std::string_view Name, std::string_view Input) { return Input.compare(0, Name.size(), Name) == 0; @@ -9050,10 +8967,10 @@ int s2NPW(std::string s) { // wylicza ilosc osi napednych z opisu ukladu osi const char A = 64; int NPW = 0; - for (std::size_t k = 0; k < s.size(); ++k) + for (char const chentry : s) { - if (s[k] >= (char)65 && s[k] <= (char)90) - NPW += s[k] - A; + if (chentry >= (char)65 && chentry <= (char)90) + NPW += chentry - A; } return NPW; } @@ -9062,10 +8979,10 @@ int s2NNW(std::string s) { // wylicza ilosc osi nienapedzanych z opisu ukladu osi const char Zero = 48; int NNW = 0; - for (std::size_t k = 0; k < s.size(); ++k) + for (char const ch : s) { - if (s[k] >= (char)49 && s[k] <= (char)57) - NNW += s[k] - Zero; + if (ch >= (char)49 && ch <= (char)57) + NNW += ch - Zero; } return NNW; } @@ -9101,18 +9018,13 @@ bool TMoverParameters::readMPT0(std::string const &line) { return false; } - switch (EngineType) - { - case TEngineType::DieselEngine: + if (EngineType == TEngineType::DieselEngine) { parser >> MotorParam[idx].mIsat >> MotorParam[idx].fi0 >> MotorParam[idx].fi >> MotorParam[idx].mfi0 >> MotorParam[idx].mfi >> MotorParam[idx].Isat; - break; } - default: + else { parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].mfi0 >> MotorParam[idx].fi >> MotorParam[idx].Isat >> MotorParam[idx].fi0; - break; - } } if (true == parser.getTokens(1, false)) { @@ -9274,7 +9186,7 @@ bool TMoverParameters::readRList(std::string const &Input) return false; } auto idx = LISTLINE++; - if (idx >= sizeof(RList) / sizeof(TScheme)) + if (idx >= std::size(RList)) { WriteLog("Read RList: number of entries exceeded capacity of the data table"); return false; @@ -9299,7 +9211,7 @@ bool TMoverParameters::readUCList(std::string const &line) cParser parser(line); parser.getTokens(10, false); auto idx = LISTLINE++; - if (idx >= sizeof(UniCtrlList) / sizeof(TUniversalCtrl)) + if (idx >= std::size(UniCtrlList)) { WriteLog("Read UCList: number of entries exceeded capacity of the data table"); return false; @@ -9317,7 +9229,7 @@ bool TMoverParameters::readDList(std::string const &line) cParser parser(line); parser.getTokens(3, false); auto idx = LISTLINE++; - if (idx >= sizeof(RList) / sizeof(TScheme)) + if (idx >= std::size(RList)) { WriteLog("Read DList: number of entries exceeded capacity of the data table"); return false; @@ -9337,7 +9249,7 @@ bool TMoverParameters::readDMList(std::string const &line) WriteLog("Read DMList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - auto idx = LISTLINE++; + ++LISTLINE; double x = 0.0; double y = 0.0; parser >> x >> y; @@ -9357,7 +9269,7 @@ bool TMoverParameters::readV2NMAXList(std::string const &line) WriteLog("Read V2nmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - auto idx = LISTLINE++; + ++LISTLINE; double x = 0.0; double y = 0.0; parser >> x >> y; @@ -9377,7 +9289,7 @@ bool TMoverParameters::readHTCList(std::string const &line) WriteLog("Read HTCList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - auto idx = LISTLINE++; + ++LISTLINE; double x = 0.0; double y = 0.0; parser >> x >> y; @@ -9397,7 +9309,7 @@ bool TMoverParameters::readPmaxList(std::string const &line) WriteLog("Read PmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - auto idx = LISTLINE++; + ++LISTLINE; double x = 0.0; double y = 0.0; parser >> x >> y; @@ -9417,7 +9329,7 @@ bool TMoverParameters::readFFList(std::string const &line) return false; } int idx = LISTLINE++; - if (idx >= sizeof(FFlist) / sizeof(TFFScheme)) + if (idx >= std::size(FFlist)) { WriteLog("Read FList: number of entries exceeded capacity of the data table"); return false; @@ -9437,7 +9349,7 @@ bool TMoverParameters::readFFEDList(std::string const &line) return false; } int idx = LISTLINE++; - if (idx >= sizeof(FFEDlist) / sizeof(TFFScheme)) + if (idx >= std::size(FFEDlist)) { WriteLog("Read FList: number of entries exceeded capacity of the data table"); return false; @@ -9457,7 +9369,7 @@ bool TMoverParameters::readWiperList(std::string const &line) return false; } int idx = LISTLINE++; - if (idx >= sizeof(WiperList) / sizeof(TWiperScheme)) + if (idx >= std::size(WiperList)) { WriteLog("Read WiperList: number of entries exceeded capacity of the data table"); return false; @@ -9474,7 +9386,7 @@ bool TMoverParameters::readDimmerList(std::string const &line) WriteLog("Read DimmerList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - int idx = LISTLINE++; + ++LISTLINE; dimPosition dps; parser >> dps.isHighBeam >> dps.isDimmed >> dps.isOff; @@ -9493,7 +9405,7 @@ bool TMoverParameters::readWWList(std::string const &line) return false; } int idx = LISTLINE++; - if (idx >= sizeof(DElist) / sizeof(TDEScheme)) + if (idx >= std::size(DElist)) { WriteLog("Read WWList: number of entries exceeded capacity of the data table"); return false; @@ -9557,42 +9469,43 @@ bool TMoverParameters::readCompressorList(std::string const &Input) // ************************************************************************************************* void TMoverParameters::BrakeValveDecode(std::string const &Valve) { + using enum TBrakeValve; - std::map valvetypes{{"W", TBrakeValve::W}, - {"W_Lu_L", TBrakeValve::W_Lu_L}, - {"W_Lu_XR", TBrakeValve::W_Lu_XR}, - {"W_Lu_VI", TBrakeValve::W_Lu_VI}, - {"K", TBrakeValve::K}, - {"Kg", TBrakeValve::Kg}, - {"Kp", TBrakeValve::Kp}, - {"Kss", TBrakeValve::Kss}, - {"Kkg", TBrakeValve::Kkg}, - {"Kkp", TBrakeValve::Kkp}, - {"Kks", TBrakeValve::Kks}, - {"Hikp1", TBrakeValve::Hikp1}, - {"Hikss", TBrakeValve::Hikss}, - {"Hikg1", TBrakeValve::Hikg1}, - {"KE", TBrakeValve::KE}, - {"SW", TBrakeValve::SW}, - {"EStED", TBrakeValve::EStED}, - {"NESt3", TBrakeValve::NESt3}, - {"ESt3", TBrakeValve::ESt3}, - {"LSt", TBrakeValve::LSt}, - {"ESt4", TBrakeValve::ESt4}, - {"ESt3AL2", TBrakeValve::ESt3AL2}, - {"EP1", TBrakeValve::EP1}, - {"EP2", TBrakeValve::EP2}, - {"M483", TBrakeValve::M483}, - {"CV1_L_TR", TBrakeValve::CV1_L_TR}, - {"CV1", TBrakeValve::CV1}, - {"CV1_R", TBrakeValve::CV1_R}}; + std::map> valvetypes{{"W", W}, + {"W_Lu_L", W_Lu_L}, + {"W_Lu_XR", W_Lu_XR}, + {"W_Lu_VI", W_Lu_VI}, + {"K", K}, + {"Kg", Kg}, + {"Kp", Kp}, + {"Kss", Kss}, + {"Kkg", Kkg}, + {"Kkp", Kkp}, + {"Kks", Kks}, + {"Hikp1", Hikp1}, + {"Hikss", Hikss}, + {"Hikg1", Hikg1}, + {"KE", KE}, + {"SW", SW}, + {"EStED", EStED}, + {"NESt3", NESt3}, + {"ESt3", ESt3}, + {"LSt", LSt}, + {"ESt4", ESt4}, + {"ESt3AL2", ESt3AL2}, + {"EP1", EP1}, + {"EP2", EP2}, + {"M483", M483}, + {"CV1_L_TR", CV1_L_TR}, + {"CV1", CV1}, + {"CV1_R", CV1_R}}; auto lookup = valvetypes.find(Valve); - BrakeValve = lookup != valvetypes.end() ? lookup->second : TBrakeValve::Other; + BrakeValve = lookup != valvetypes.end() ? lookup->second : Other; - if (BrakeValve == TBrakeValve::Other && contains(Valve, "ESt")) + if (BrakeValve == Other && contains(Valve, "ESt")) { - BrakeValve = TBrakeValve::ESt3; + BrakeValve = ESt3; } } @@ -9601,32 +9514,36 @@ void TMoverParameters::BrakeValveDecode(std::string const &Valve) // ************************************************************************************************* void TMoverParameters::BrakeSubsystemDecode() { - BrakeSubsystem = TBrakeSubSystem::ss_None; + using enum TBrakeSubSystem; + BrakeSubsystem = ss_None; switch (BrakeValve) { - case TBrakeValve::W: - case TBrakeValve::W_Lu_L: - case TBrakeValve::W_Lu_VI: - case TBrakeValve::W_Lu_XR: - BrakeSubsystem = TBrakeSubSystem::ss_W; + using enum TBrakeValve; + case W: + case W_Lu_L: + case W_Lu_VI: + case W_Lu_XR: + BrakeSubsystem = ss_W; break; - case TBrakeValve::ESt3: - case TBrakeValve::ESt3AL2: - case TBrakeValve::ESt4: - case TBrakeValve::EP2: - case TBrakeValve::EP1: - BrakeSubsystem = TBrakeSubSystem::ss_ESt; + case ESt3: + case ESt3AL2: + case ESt4: + case EP2: + case EP1: + BrakeSubsystem = ss_ESt; break; - case TBrakeValve::KE: - BrakeSubsystem = TBrakeSubSystem::ss_KE; + case KE: + BrakeSubsystem = ss_KE; break; - case TBrakeValve::CV1: - case TBrakeValve::CV1_L_TR: - BrakeSubsystem = TBrakeSubSystem::ss_Dako; + case CV1: + case CV1_L_TR: + BrakeSubsystem = ss_Dako; break; - case TBrakeValve::LSt: - case TBrakeValve::EStED: - BrakeSubsystem = TBrakeSubSystem::ss_LSt; + case LSt: + case EStED: + BrakeSubsystem = ss_LSt; + break; + default: break; } } @@ -9637,12 +9554,9 @@ void TMoverParameters::BrakeSubsystemDecode() // TDynamicObject::Init() // Po niej wykonywana jest CreateBrakeSys(), ktora jest odpowiednikiem CheckLocomotiveParameters() // ************************************************************************************************* -bool TMoverParameters::LoadFIZ(std::string chkpath) +bool TMoverParameters::LoadFIZ(std::string const &chkpath) { chkPath = chkpath; // assign class path for reloading - const int param_ok = 1; - const int wheels_ok = 2; - const int dimensions_ok = 4; ConversionError = 666; LISTLINE = 0; @@ -9810,7 +9724,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Param.", inputline)) { startBPT = false; - fizlines.emplace("Param", inputline); + fizlines.try_emplace("Param", inputline); LoadFIZ_Param(inputline); continue; } @@ -9818,7 +9732,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Load:", inputline)) { startBPT = false; - fizlines.emplace("Load", inputline); + fizlines.try_emplace("Load", inputline); LoadFIZ_Load(inputline); continue; } @@ -9826,7 +9740,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Dimensions:", inputline)) { startBPT = false; - fizlines.emplace("Dimensions", inputline); + fizlines.try_emplace("Dimensions", inputline); LoadFIZ_Dimensions(inputline); continue; } @@ -9834,7 +9748,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Wheels:", inputline)) { startBPT = false; - fizlines.emplace("Wheels", inputline); + fizlines.try_emplace("Wheels", inputline); LoadFIZ_Wheels(inputline); continue; } @@ -9842,7 +9756,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Brake:", inputline)) { startBPT = false; - fizlines.emplace("Brake", inputline); + fizlines.try_emplace("Brake", inputline); LoadFIZ_Brake(inputline); continue; } @@ -9851,7 +9765,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("Doors", inputline); + fizlines.try_emplace("Doors", inputline); LoadFIZ_Doors(inputline); continue; } @@ -9860,7 +9774,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("BuffCoupl", inputline); + fizlines.try_emplace("BuffCoupl", inputline); LoadFIZ_BuffCoupl(inputline, 0); continue; } @@ -9869,7 +9783,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("BuffCoupl1", inputline); + fizlines.try_emplace("BuffCoupl1", inputline); LoadFIZ_BuffCoupl(inputline, 1); continue; } @@ -9878,7 +9792,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("BuffCoupl2", inputline); + fizlines.try_emplace("BuffCoupl2", inputline); LoadFIZ_BuffCoupl(inputline, 2); continue; } @@ -9887,7 +9801,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("TurboPos", inputline); + fizlines.try_emplace("TurboPos", inputline); LoadFIZ_TurboPos(inputline); continue; } @@ -9897,7 +9811,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startBPT = true; LISTLINE = 0; - fizlines.emplace("Cntrl", inputline); + fizlines.try_emplace("Cntrl", inputline); LoadFIZ_Cntrl(inputline); continue; } @@ -9905,7 +9819,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Headlights:", inputline)) { startBPT = false; - fizlines.emplace("Headlights", inputline); + fizlines.try_emplace("Headlights", inputline); LoadFIZ_Headlights(inputline); continue; } @@ -9915,7 +9829,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startBPT = false; LISTLINE = 0; - fizlines.emplace("Blending", inputline); + fizlines.try_emplace("Blending", inputline); LoadFIZ_Blending(inputline); continue; } @@ -9925,7 +9839,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startBPT = false; LISTLINE = 0; - fizlines.emplace("DCEMUED", inputline); + fizlines.try_emplace("DCEMUED", inputline); LoadFIZ_DCEMUED(inputline); continue; } @@ -9935,7 +9849,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startBPT = false; LISTLINE = 0; - fizlines.emplace("SpringBrake", inputline); + fizlines.try_emplace("SpringBrake", inputline); LoadFIZ_SpringBrake(inputline); continue; } @@ -9944,7 +9858,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("Light", inputline); + fizlines.try_emplace("Light", inputline); LoadFIZ_Light(inputline); continue; } @@ -9952,7 +9866,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Security:", inputline)) { startBPT = false; - fizlines.emplace("Security", inputline); + fizlines.try_emplace("Security", inputline); SecuritySystem.load(inputline, Vmax); extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); continue; @@ -9962,7 +9876,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("Clima", inputline); + fizlines.try_emplace("Clima", inputline); LoadFIZ_Clima(inputline); continue; } @@ -9970,7 +9884,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Power:", inputline)) { startBPT = false; - fizlines.emplace("Power", inputline); + fizlines.try_emplace("Power", inputline); LoadFIZ_Power(inputline); continue; } @@ -9978,7 +9892,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("SpeedControl:", inputline)) { startBPT = false; - fizlines.emplace("SpeedControl", inputline); + fizlines.try_emplace("SpeedControl", inputline); LoadFIZ_SpeedControl(inputline); continue; } @@ -9986,7 +9900,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Engine:", inputline)) { startBPT = false; - fizlines.emplace("Engine", inputline); + fizlines.try_emplace("Engine", inputline); LoadFIZ_Engine(inputline); continue; } @@ -9994,7 +9908,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Switches:", inputline)) { startBPT = false; - fizlines.emplace("Switches", inputline); + fizlines.try_emplace("Switches", inputline); LoadFIZ_Switches(inputline); continue; } @@ -10004,7 +9918,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startBPT = false; startMPT = true; LISTLINE = 0; - fizlines.emplace("MotorParamTable", inputline); + fizlines.try_emplace("MotorParamTable", inputline); LoadFIZ_MotorParamTable(inputline); continue; } @@ -10020,7 +9934,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Circuit:", inputline)) { startBPT = false; - fizlines.emplace("Circuit", inputline); + fizlines.try_emplace("Circuit", inputline); LoadFIZ_Circuit(inputline); continue; } @@ -10028,7 +9942,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("AI:", inputline)) { startBPT = false; - fizlines.emplace("AI", inputline); + fizlines.try_emplace("AI", inputline); LoadFIZ_AI(inputline); continue; } @@ -10036,7 +9950,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("RList:", inputline)) { startBPT = false; - fizlines.emplace("RList", inputline); + fizlines.try_emplace("RList", inputline); startRLIST = true; LISTLINE = 0; LoadFIZ_RList(inputline); @@ -10046,7 +9960,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("UCList:", inputline)) { startBPT = false; - fizlines.emplace("UCList", inputline); + fizlines.try_emplace("UCList", inputline); startUCLIST = true; LISTLINE = 0; LoadFIZ_UCList(inputline); @@ -10056,7 +9970,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("DList:", inputline)) { startBPT = false; - fizlines.emplace("DList", inputline); + fizlines.try_emplace("DList", inputline); startDLIST = true; LISTLINE = 0; LoadFIZ_DList(inputline); @@ -10066,7 +9980,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("DMList:", inputline)) { startBPT = false; - fizlines.emplace("DMList", inputline); + fizlines.try_emplace("DMList", inputline); startDIZELMOMENTUMLIST = true; LISTLINE = 0; continue; @@ -10075,7 +9989,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("HTCList:", inputline)) { startBPT = false; - fizlines.emplace("HTCList", inputline); + fizlines.try_emplace("HTCList", inputline); startHYDROTCLIST = true; LISTLINE = 0; continue; @@ -10084,7 +9998,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("PmaxList:", inputline)) { startBPT = false; - fizlines.emplace("PmaxList", inputline); + fizlines.try_emplace("PmaxList", inputline); startPMAXLIST = true; LISTLINE = 0; continue; @@ -10093,7 +10007,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("V2NList:", inputline)) { startBPT = false; - fizlines.emplace("V2NList", inputline); + fizlines.try_emplace("V2NList", inputline); startDIZELV2NMAXLIST = true; LISTLINE = 0; continue; @@ -10129,7 +10043,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("WiperList:", inputline)) { startBPT = false; - fizlines.emplace("WiperList", inputline); + fizlines.try_emplace("WiperList", inputline); startWiperList = true; LISTLINE = 0; LoadFIZ_WiperList(inputline); @@ -10142,7 +10056,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) dimPositions.clear(); // uzywamy customowej listy startBPT = false; startDimmerList = true; - fizlines.emplace("DimmerList", inputline); + fizlines.try_emplace("DimmerList", inputline); LoadFIZ_DimmerList(inputline); continue; } @@ -10150,7 +10064,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("LightsList:", inputline)) { startBPT = false; - fizlines.emplace("LightsList", inputline); + fizlines.try_emplace("LightsList", inputline); startLIGHTSLIST = true; LISTLINE = 0; LoadFIZ_LightsList(inputline); @@ -10160,7 +10074,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("CompressorList:", inputline)) { startBPT = false; - fizlines.emplace("CompressorList", inputline); + fizlines.try_emplace("CompressorList", inputline); startCOMPRESSORLIST = true; LISTLINE = 0; LoadFIZ_CompressorList(inputline); @@ -10288,7 +10202,7 @@ void TMoverParameters::LoadFIZ_Param(std::string const &line) extract_value(LightPower, "LightP", line, "0"); { - std::map categories{{"train", 1}, {"road", 2}, {"unimog", 3}, {"ship", 4}, {"airplane,", 8}}; + std::map> categories{{"train", 1}, {"road", 2}, {"unimog", 3}, {"ship", 4}, {"airplane,", 8}}; std::string category; extract_value(category, "Category", line, "none"); auto lookup = categories.find(category); @@ -10300,7 +10214,7 @@ void TMoverParameters::LoadFIZ_Param(std::string const &line) } { - std::map types{ + std::map> types{ {"pseudodiesel", dt_PseudoDiesel}, {"ezt", dt_EZT}, {"dmu", dt_DMU}, @@ -10383,7 +10297,7 @@ void TMoverParameters::LoadFIZ_Dimensions(std::string const &line) if (Dim.H <= 2.0) { // gdyby nie było parametru, lepsze to niż zero - Floor = Dim.H; + Floor = static_cast(Dim.H); } else { @@ -10485,7 +10399,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) extract_value(BrakeVVolume, "BVV", line, ""); { - std::map brakemethods{{"P10-Bg", bp_P10Bg}, {"P10-Bgu", bp_P10Bgu}, {"FR513", bp_FR513}, {"FR510", bp_FR510}, {"Cosid", bp_Cosid}, + std::map> brakemethods{{"P10-Bg", bp_P10Bg}, {"P10-Bgu", bp_P10Bgu}, {"FR513", bp_FR513}, {"FR510", bp_FR510}, {"Cosid", bp_Cosid}, {"P10yBg", bp_P10yBg}, {"P10yBgu", bp_P10yBgu}, {"Disk1", bp_D1}, {"Disk1+Mg", bp_D1 + bp_MHS}, {"Disk2", bp_D2}}; auto lookup = brakemethods.find(extract_value("BM", line)); BrakeMethod = lookup != brakemethods.end() ? lookup->second : 0; @@ -10529,7 +10443,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) extract_value(HandleUnlock, "HandlePipeUnlockPos", line, "-3"); extract_value(EmergencyCutsOffHandle, "EmergencyCutsOffHandle", line, ""); { - std::map compressorpowers{ + std::map> compressorpowers{ {"Main", 0}, // 1: default, powered by converter, with manual state control {"Converter", 2}, @@ -10572,7 +10486,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) void TMoverParameters::LoadFIZ_Doors(std::string const &line) { - std::map doorcontrols{ + std::map> doorcontrols{ {"Passenger", control_t::passenger}, {"AutomaticCtrl", control_t::autonomous}, {"DriverCtrl", control_t::driver}, {"Conductor", control_t::conductor}, {"Mixed", control_t::mixed}}; // opening method { @@ -10600,7 +10514,7 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) { // HACK: legacy position indices start from 1, so we deduct 1 to arrive at proper index into the array extract_value(Doors.permit_preset, "DoorPermitListDefault", line, "1"); - Doors.permit_preset = std::min(Doors.permit_presets.size(), Doors.permit_preset) - 1; + Doors.permit_preset = std::min(static_cast(Doors.permit_presets.size()), Doors.permit_preset) - 1; } } @@ -10612,7 +10526,7 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) extract_value(Doors.range, "DoorMaxShiftR", line, ""); extract_value(Doors.range_out, "DoorMaxShiftPlug", line, ""); - std::map doortypes{ + std::map> doortypes{ {"Shift", 1}, {"Rotate", 2}, {"Fold", 3}, @@ -10654,59 +10568,59 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) { - TCoupling *coupler; + TCoupling *thiscoupler; if (Index == 2) { - coupler = &Couplers[1]; + thiscoupler = &Couplers[1]; } else { - coupler = &Couplers[0]; + thiscoupler = &Couplers[0]; } - std::map couplertypes{ + std::map> couplertypes{ {"Automatic", TCouplerType::Automatic}, {"Screw", TCouplerType::Screw}, {"Chain", TCouplerType::Chain}, {"Bare", TCouplerType::Bare}, {"Articulated", TCouplerType::Articulated}, }; auto lookup = couplertypes.find(extract_value("CType", line)); - coupler->CouplerType = lookup != couplertypes.end() ? lookup->second : TCouplerType::NoCoupler; + thiscoupler->CouplerType = lookup != couplertypes.end() ? lookup->second : TCouplerType::NoCoupler; - extract_value(coupler->SpringKC, "kC", line, ""); - extract_value(coupler->DmaxC, "DmaxC", line, ""); - extract_value(coupler->FmaxC, "FmaxC", line, ""); - extract_value(coupler->SpringKB, "kB", line, ""); - extract_value(coupler->DmaxB, "DmaxB", line, ""); - extract_value(coupler->FmaxB, "FmaxB", line, ""); - extract_value(coupler->beta, "beta", line, ""); - extract_value(coupler->AutomaticCouplingFlag, "AutomaticFlag", line, ""); - extract_value(coupler->AllowedFlag, "AllowedFlag", line, ""); - if (coupler->AllowedFlag < 0) + extract_value(thiscoupler->SpringKC, "kC", line, ""); + extract_value(thiscoupler->DmaxC, "DmaxC", line, ""); + extract_value(thiscoupler->FmaxC, "FmaxC", line, ""); + extract_value(thiscoupler->SpringKB, "kB", line, ""); + extract_value(thiscoupler->DmaxB, "DmaxB", line, ""); + extract_value(thiscoupler->FmaxB, "FmaxB", line, ""); + extract_value(thiscoupler->beta, "beta", line, ""); + extract_value(thiscoupler->AutomaticCouplingFlag, "AutomaticFlag", line, ""); + extract_value(thiscoupler->AllowedFlag, "AllowedFlag", line, ""); + if (thiscoupler->AllowedFlag < 0) { - coupler->AllowedFlag = -coupler->AllowedFlag | coupling::permanent; + thiscoupler->AllowedFlag = -thiscoupler->AllowedFlag | coupling::permanent; } - extract_value(coupler->PowerCoupling, "PowerCoupling", line, ""); - extract_value(coupler->PowerFlag, "PowerFlag", line, ""); - extract_value(coupler->control_type, "ControlType", line, ""); + extract_value(thiscoupler->PowerCoupling, "PowerCoupling", line, ""); + extract_value(thiscoupler->PowerFlag, "PowerFlag", line, ""); + extract_value(thiscoupler->control_type, "ControlType", line, ""); - if (coupler->CouplerType != TCouplerType::NoCoupler && coupler->CouplerType != TCouplerType::Bare && coupler->CouplerType != TCouplerType::Articulated) + if (thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated) { - coupler->SpringKC *= 1000; - coupler->FmaxC *= 1000; - coupler->SpringKB *= 1000; - coupler->FmaxB *= 1000; + thiscoupler->SpringKC *= 1000; + thiscoupler->FmaxC *= 1000; + thiscoupler->SpringKB *= 1000; + thiscoupler->FmaxB *= 1000; } - else if (coupler->CouplerType == TCouplerType::Bare) + else if (thiscoupler->CouplerType == TCouplerType::Bare) { - coupler->SpringKC = 50.0 * Mass + Ftmax / 0.05; - coupler->DmaxC = 0.05; - coupler->FmaxC = 100.0 * Mass + 2 * Ftmax; - coupler->SpringKB = 60.0 * Mass + Ftmax / 0.05; - coupler->DmaxB = 0.05; - coupler->FmaxB = 50.0 * Mass + 2.0 * Ftmax; - coupler->beta = 0.3; + thiscoupler->SpringKC = 50.0 * Mass + Ftmax / 0.05; + thiscoupler->DmaxC = 0.05; + thiscoupler->FmaxC = 100.0 * Mass + 2 * Ftmax; + thiscoupler->SpringKB = 60.0 * Mass + Ftmax / 0.05; + thiscoupler->DmaxB = 0.05; + thiscoupler->FmaxB = 50.0 * Mass + 2.0 * Ftmax; + thiscoupler->beta = 0.3; } - else if (coupler->CouplerType == TCouplerType::Articulated) + else if (thiscoupler->CouplerType == TCouplerType::Articulated) { /* coupler->SpringKC = 60.0 * Mass + 1000; @@ -10717,13 +10631,13 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde coupler->FmaxB = 4000000.0 + 2.0 * Ftmax; coupler->beta = 0.55; */ - coupler->SpringKC = 4500 * 1000; - coupler->DmaxC = 0.05; - coupler->FmaxC = 850 * 1000; - coupler->SpringKB = 9200 * 1000; - coupler->DmaxB = 0.05; - coupler->FmaxB = 320 * 1000; - coupler->beta = 0.55; + thiscoupler->SpringKC = 4500 * 1000; + thiscoupler->DmaxC = 0.05; + thiscoupler->FmaxC = 850 * 1000; + thiscoupler->SpringKB = 9200 * 1000; + thiscoupler->DmaxB = 0.05; + thiscoupler->FmaxB = 320 * 1000; + thiscoupler->beta = 0.55; } if (Index == 0) @@ -10743,12 +10657,14 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) { { - std::map brakesystems{{"Pneumatic", TBrakeSystem::Pneumatic}, {"ElectroPneumatic", TBrakeSystem::ElectroPneumatic}}; + using enum TBrakeSystem; + std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; auto lookup = brakesystems.find(extract_value("BrakeSystem", line)); - BrakeSystem = lookup != brakesystems.end() ? lookup->second : TBrakeSystem::Individual; + BrakeSystem = lookup != brakesystems.end() ? lookup->second : Individual; } if (BrakeSystem != TBrakeSystem::Individual) { + using enum TBrakeHandle; extract_value(BrakeCtrlPosNo, "BCPN", line, ""); for (int idx = 0; idx < 4; ++idx) @@ -10758,7 +10674,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } // brakedelays, brakedelayflag { - std::map brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, + std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, {"PR", bdelay_P + bdelay_R}, {"GP", bdelay_G + bdelay_P}, {"R", bdelay_R}, @@ -10766,7 +10682,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) {"G", bdelay_G}, {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; - std::map brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; + std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; std::string brakedelay; extract_value(brakedelay, "BrakeDelays", line, ""); auto lookup = brakedelays.find(brakedelay); @@ -10776,18 +10692,18 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } // brakeopmode { - std::map brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; + std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; } // brakehandle { - std::map brakehandles{ - {"FV4a", TBrakeHandle::FV4a}, {"test", TBrakeHandle::testH}, {"D2", TBrakeHandle::D2}, {"MHZ_EN57", TBrakeHandle::MHZ_EN57}, {"MHZ_K5P", TBrakeHandle::MHZ_K5P}, - {"MHZ_K8P", TBrakeHandle::MHZ_K8P}, {"MHZ_6P", TBrakeHandle::MHZ_6P}, {"M394", TBrakeHandle::M394}, {"Knorr", TBrakeHandle::Knorr}, {"Westinghouse", TBrakeHandle::West}, - {"FVel6", TBrakeHandle::FVel6}, {"FVE408", TBrakeHandle::FVE408}, {"St113", TBrakeHandle::St113}}; + std::map> brakehandles{ + {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, + {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, + {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); - BrakeHandle = lookup != brakehandles.end() ? lookup->second : TBrakeHandle::NoHandle; + BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; } extract_value(Handle_AutomaticOverload, "HAO", line, ""); extract_value(Handle_ManualOverload, "HMO", line, ""); @@ -10797,9 +10713,9 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); // brakelochandle { - std::map locbrakehandles{{"FD1", TBrakeHandle::FD1}, {"Knorr", TBrakeHandle::Knorr}, {"Westinghouse", TBrakeHandle::West}}; + std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); - BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : TBrakeHandle::NoHandle; + BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; } // mbpm @@ -10839,9 +10755,10 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // localbrake { - std::map localbrakes{{"ManualBrake", TLocalBrake::ManualBrake}, {"PneumaticBrake", TLocalBrake::PneumaticBrake}, {"HydraulicBrake", TLocalBrake::HydraulicBrake}}; + using enum TLocalBrake; + std::map> localbrakes{{"ManualBrake", ManualBrake}, {"PneumaticBrake", PneumaticBrake}, {"HydraulicBrake", HydraulicBrake}}; auto lookup = localbrakes.find(extract_value("LocalBrake", line)); - LocalBrake = lookup != localbrakes.end() ? lookup->second : TLocalBrake::NoBrake; + LocalBrake = lookup != localbrakes.end() ? lookup->second : NoBrake; } // mbrake extract_value(MBrake, "ManualBrake", line, ""); @@ -10851,7 +10768,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // dynamicbrake { - std::map dynamicbrakes{{"Passive", dbrake_passive}, {"Switch", dbrake_switch}, {"Reversal", dbrake_reversal}, {"Automatic", dbrake_automatic}}; + std::map> dynamicbrakes{{"Passive", dbrake_passive}, {"Switch", dbrake_switch}, {"Reversal", dbrake_reversal}, {"Automatic", dbrake_automatic}}; auto lookup = dynamicbrakes.find(extract_value("DynamicBrake", line)); DynamicBrakeType = lookup != dynamicbrakes.end() ? lookup->second : dbrake_none; extract_value(DynamicBrakeAmpmeters, "DBAM", line, ""); @@ -10874,8 +10791,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(ScndInMain, "SCIM", line, ""); extract_value(MainCtrlMaxDirChangePos, "DirChangeMaxPos", line, ""); - auto const autorelay{ToLower(extract_value("AutoRelay", line))}; - if (autorelay == "optional") + if (auto const autorelay{ToLower(extract_value("AutoRelay", line))}; autorelay == "optional") { AutoRelayType = 2; } @@ -10925,7 +10841,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(shouldHoldBatteryButton, "SBBBH", line, ""); extract_value(BatteryButtonHoldTime, "BBHT", line, ""); - std::map starts{{"Disabled", start_t::disabled}, {"Manual", start_t::manual}, {"Automatic", start_t::automatic}, {"Mixed", start_t::manualwithautofallback}, + std::map> starts{{"Disabled", start_t::disabled}, {"Manual", start_t::manual}, {"Automatic", start_t::automatic}, {"Mixed", start_t::manualwithautofallback}, {"Battery", start_t::battery}, {"Converter", start_t::converter}, {"Direction", start_t::direction}}; // main circuit @@ -10998,7 +10914,8 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // traction motor fans { auto lookup = starts.find(extract_value("MotorBlowersStart", line)); - MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : start_t::manual; + MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : start_t::manual; + MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type; } // compartment lights { @@ -11078,7 +10995,7 @@ void TMoverParameters::LoadFIZ_Light(std::string const &line) extract_value(NominalVoltage, "Volt", line, ""); extract_value(BatteryVoltage, "LMaxVoltage", line, ""); - NominalBatteryVoltage = BatteryVoltage; + NominalBatteryVoltage = static_cast(BatteryVoltage); } void TMoverParameters::LoadFIZ_Clima(std::string const &line) @@ -11156,8 +11073,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); - std::string transmission = extract_value("Trans", Input); - if (false == transmission.empty()) + if (std::string transmission = extract_value("Trans", Input); false == transmission.empty()) { // transmission type. moved here because more than one engine type has this entry auto ratios = Split(transmission, ':'); // e.g. 18:79 @@ -11422,7 +11338,7 @@ void TMoverParameters::LoadFIZ_Switches(std::string const &Input) { auto &presets{PantsPreset.first}; extract_value(presets, "PantographPresets", Input, "0|1|3|2"); - presets.erase(std::remove(std::begin(presets), std::end(presets), '|'), std::end(presets)); + std::erase(presets, '|'); } } @@ -11481,8 +11397,7 @@ void TMoverParameters::LoadFIZ_RList(std::string const &Input) extract_value(RlistSize, "Size", Input, ""); - auto const venttype{ToLower(extract_value("RVent", Input))}; - if (venttype == "automatic") + if (auto const venttype{ToLower(extract_value("RVent", Input))}; venttype == "automatic") { RVentType = 2; @@ -11579,7 +11494,7 @@ void TMoverParameters::LoadFIZ_CompressorList(std::string const &Input) extract_value(CompressorListDefPos, "Default", Input, ""); } -void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const Prefix, std::string const &Line) +void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Line) { switch (Powerparameters.SourceType) @@ -11603,8 +11518,7 @@ void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparamete // prime mover for the generator auto &generatorparameters{Powerparameters.EngineGenerator}; - auto const enginetype{LoadFIZ_EngineDecode(extract_value(Prefix + "GeneratorEngine", Line))}; - if (enginetype == TEngineType::Main) + if (auto const enginetype{LoadFIZ_EngineDecode(extract_value(Prefix + "GeneratorEngine", Line))}; enginetype == TEngineType::Main) { generatorparameters.engine_revolutions = &enrot; } @@ -11700,51 +11614,53 @@ void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparamete } } -TPowerType TMoverParameters::LoadFIZ_PowerDecode(std::string const &Power) +TPowerType TMoverParameters::LoadFIZ_PowerDecode(std::string const &Powertype) const { + using enum TPowerType; - std::map powertypes{ - {"BioPower", TPowerType::BioPower}, {"MechPower", TPowerType::MechPower}, {"ElectricPower", TPowerType::ElectricPower}, {"SteamPower", TPowerType::SteamPower}}; - auto lookup = powertypes.find(Power); - return lookup != powertypes.end() ? lookup->second : TPowerType::NoPower; + std::map> powertypes{ + {"BioPower", BioPower}, {"MechPower", MechPower}, {"ElectricPower", ElectricPower}, {"SteamPower", SteamPower}}; + auto lookup = powertypes.find(Powertype); + return lookup != powertypes.end() ? lookup->second : NoPower; } -TPowerSource TMoverParameters::LoadFIZ_SourceDecode(std::string const &Source) +TPowerSource TMoverParameters::LoadFIZ_SourceDecode(std::string const &Source) const { + using enum TPowerSource; - std::map powersources{{"Transducer", TPowerSource::Transducer}, {"Generator", TPowerSource::Generator}, - {"Accu", TPowerSource::Accumulator}, // legacy compatibility leftover. TODO: check if we can get rid of it - {"Accumulator", TPowerSource::Accumulator}, {"CurrentCollector", TPowerSource::CurrentCollector}, - {"PowerCable", TPowerSource::PowerCable}, {"Heater", TPowerSource::Heater}, - {"Internal", TPowerSource::InternalSource}, {"Main", TPowerSource::Main}}; + std::map> powersources{{"Transducer", Transducer}, {"Generator", Generator}, + {"Accu", Accumulator}, // legacy compatibility leftover. TODO: check if we can get rid of it + {"Accumulator", Accumulator}, {"CurrentCollector", CurrentCollector}, + {"PowerCable", PowerCable}, {"Heater", Heater}, + {"Internal", InternalSource}, {"Main", Main}}; auto lookup = powersources.find(Source); - return lookup != powersources.end() ? lookup->second : TPowerSource::NotDefined; + return lookup != powersources.end() ? lookup->second : NotDefined; } -TEngineType TMoverParameters::LoadFIZ_EngineDecode(std::string const &Engine) +TEngineType TMoverParameters::LoadFIZ_EngineDecode(std::string const &Engine) const { + using enum TEngineType; - std::map enginetypes{{"ElectricSeriesMotor", TEngineType::ElectricSeriesMotor}, - {"DieselEngine", TEngineType::DieselEngine}, - {"SteamEngine", TEngineType::SteamEngine}, - {"WheelsDriven", TEngineType::WheelsDriven}, - {"Dumb", TEngineType::Dumb}, - {"DieselElectric", TEngineType::DieselElectric}, - {"DumbDE", TEngineType::DieselElectric}, - {"ElectricInductionMotor", TEngineType::ElectricInductionMotor}, - {"Main", TEngineType::Main}}; + std::map> enginetypes{{"ElectricSeriesMotor", ElectricSeriesMotor}, + {"DieselEngine", DieselEngine}, + {"SteamEngine", SteamEngine}, + {"WheelsDriven", WheelsDriven}, + {"Dumb", Dumb}, + {"DieselElectric", DieselElectric}, + {"DumbDE", DieselElectric}, + {"ElectricInductionMotor", ElectricInductionMotor}, + {"Main", Main}}; auto lookup = enginetypes.find(Engine); - return lookup != enginetypes.end() ? lookup->second : TEngineType::None; + return lookup != enginetypes.end() ? lookup->second : None; } // ************************************************************************************************* // Q: 20160717 // ************************************************************************************************* -bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) +bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { WriteLog("check locomotive parameters..."); - int b; bool OK = true; AutoRelayFlag = AutoRelayType == 1; @@ -11779,9 +11695,8 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) // WriteLogSS("aa ok", BoolToYN(OK)); } - if (BrakeSystem == TBrakeSystem::Individual) - if (BrakeSubsystem != TBrakeSubSystem::ss_None) - OK = false; //! + if (BrakeSystem == TBrakeSystem::Individual && BrakeSubsystem != TBrakeSubSystem::ss_None) + OK = false; //! if (BrakeVVolume == 0 && MaxBrakePress[3] > 0 && BrakeSystem != TBrakeSystem::Individual) { @@ -11890,35 +11805,36 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) switch (BrakeHandle) { - case TBrakeHandle::FV4a: + using enum TBrakeHandle; + case FV4a: Handle = std::make_shared(); break; - case TBrakeHandle::MHZ_EN57: - case TBrakeHandle::MHZ_K8P: + case MHZ_EN57: + case MHZ_K8P: Handle = std::make_shared(); break; - case TBrakeHandle::FVel6: + case FVel6: Handle = std::make_shared(); break; - case TBrakeHandle::FVE408: + case FVE408: Handle = std::make_shared(); break; - case TBrakeHandle::testH: + case testH: Handle = std::make_shared(); break; - case TBrakeHandle::M394: + case M394: Handle = std::make_shared(); break; - case TBrakeHandle::Knorr: + case Knorr: Handle = std::make_shared(); break; - case TBrakeHandle::St113: + case St113: Handle = std::make_shared(); break; - case TBrakeHandle::MHZ_K5P: + case MHZ_K5P: Handle = std::make_shared(); break; - case TBrakeHandle::MHZ_6P: + case MHZ_6P: Handle = std::make_shared(); break; default: @@ -12094,9 +12010,9 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) BrakeOpModeFlag = bom_PN; // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% - int DefBrakeTable[8] = {15, 4, 25, 25, 13, 3, 12, 2}; + std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; - for (b = 1; b < 4; b++) + for (int b = 1; b < 4; b++) { if (BrakeDelay[b] == 0) BrakeDelay[b] = DefBrakeTable[b]; @@ -12137,7 +12053,7 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) // Q: 20160714 // Wstawia komendę z parametrem, od sprzęgu i w lokalizacji do pojazdu // ************************************************************************************************* -void TMoverParameters::PutCommand(std::string NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) +void TMoverParameters::PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) { CommandLast = NewCommand; // zapamiętanie komendy @@ -12152,7 +12068,7 @@ void TMoverParameters::PutCommand(std::string NewCommand, double NewValue1, doub // Q: 20160714 // Pobiera komendę z parametru funkcji oraz wartość zmiennej jako return // ************************************************************************************************* -double TMoverParameters::GetExternalCommand(std::string &Command) +double TMoverParameters::GetExternalCommand(std::string &Command) const { Command = CommandOut; return ValueOut; @@ -12162,7 +12078,7 @@ double TMoverParameters::GetExternalCommand(std::string &Command) // Q: 20160714 // Ustawienie komendy wraz z parametrami // ************************************************************************************************* -bool TMoverParameters::SetInternalCommand(std::string NewCommand, double NewValue1, double NewValue2, int const Couplertype) +bool TMoverParameters::SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype) { bool SIC; if (CommandIn.Command == NewCommand && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.Coupling == Couplertype) @@ -12184,7 +12100,7 @@ bool TMoverParameters::SetInternalCommand(std::string NewCommand, double NewValu // Q: 20160714 // wysyłanie komendy w kierunku dir (1=przód, -1=tył) do kolejnego pojazdu (jednego) // ************************************************************************************************* -bool TMoverParameters::SendCtrlToNext(std::string const CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype) +bool TMoverParameters::SendCtrlToNext(std::string const &CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype) { bool OK; int d; // numer sprzęgu w kierunku którego wysyłamy @@ -12193,24 +12109,21 @@ bool TMoverParameters::SendCtrlToNext(std::string const CtrlCommand, double cons // Ra: problem jest również, jeśli AI będzie na końcu składu OK = true; // ( dir != 0 ); // experimentally disabled d = (1 + static_cast(Sign(dir))) / 2; // dir=-1=>d=0, dir=1=>d=1 - wysyłanie tylko w tył - if (OK) + // musi być wybrana niezerowa kabina + if (OK && Couplers[d].Connected != nullptr && TestFlag(Couplers[d].CouplingFlag, Couplertype)) { - // musi być wybrana niezerowa kabina - if (Couplers[d].Connected != nullptr && TestFlag(Couplers[d].CouplingFlag, Couplertype)) - { - if (Couplers[d].ConnectedNr != d) - { - // jeśli ten nastpęny jest zgodny z aktualnym - if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, dir, Couplertype)) - OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja - } - else - { - // jeśli następny jest ustawiony przeciwnie, zmieniamy kierunek - if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, -dir, Couplertype)) - OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja - } + if (Couplers[d].ConnectedNr != d) + { + // jeśli ten nastpęny jest zgodny z aktualnym + if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, dir, Couplertype)) + OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja + } + else + { + // jeśli następny jest ustawiony przeciwnie, zmieniamy kierunek + if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, -dir, Couplertype)) + OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja } } return OK; @@ -12227,7 +12140,7 @@ bool TMoverParameters::SendCtrlToNext(std::string const CtrlCommand, double cons // Komenda musi być zdefiniowana tutaj, a jeśli się wywołuje funkcję, to ona nie może // sama przesyłać do kolejnych pojazdów. Należy też się zastanowić, czy dla uzyskania // jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. -bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CValue2, int const Couplertype) +bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype) { bool OK{false}; @@ -12279,7 +12192,7 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) temp1 = 0; Hamulec->SetEPS(temp1); - TUHEX_StageActual = CValue1; + TUHEX_StageActual = static_cast(CValue1); TUHEX_Active = TUHEX_StageActual > 0; if (CValue1 < 0.001) DynamicBrakeEMUStatus = true; @@ -12289,7 +12202,7 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV } // youby - odluzniacz hamulcow, przyda sie else if (Command == "BrakeReleaser") { - OK = BrakeReleaser(Round(CValue1)); // samo się przesyła dalej + OK = BrakeReleaser(static_cast(Round(CValue1))); // samo się przesyła dalej // OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n } else if (Command == "WaterPumpBreakerSwitch") @@ -12500,7 +12413,7 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV } else if (Command == "RelayReset") { - RelayReset(CValue1, range_t::local); + RelayReset(static_cast(CValue1), range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == "ConverterSwitch") /*NBMX*/ @@ -12538,14 +12451,13 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV else if (Command == "DoorPermit") { - auto const left{CValue2 > 0 ? 1 : 2}; - auto const right{3 - left}; + auto const leftside{CValue2 > 0 ? 1 : 2}; - if (std::abs(static_cast(CValue1)) & right) + if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) { PermitDoors_(side::right, CValue1 > 0); } - if (std::abs(static_cast(CValue1)) & left) + if (std::abs(static_cast(CValue1)) & leftside) { PermitDoors_(side::left, CValue1 > 0); } @@ -12554,50 +12466,42 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV } else if (Command == "DoorOpen") /*NBMX*/ { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - if (Doors.open_control == control_t::conductor || Doors.open_control == control_t::driver || Doors.open_control == control_t::mixed) + // ignore remote command if the door is only operated locally + if ((Doors.open_control == control_t::conductor || Doors.open_control == control_t::driver || Doors.open_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) { - // ignore remote command if the door is only operated locally - if (Power24vIsAvailable || Power110vIsAvailable) + + auto const leftside{CValue2 > 0 ? 1 : 2}; + + if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) { - - auto const left{CValue2 > 0 ? 1 : 2}; - auto const right{3 - left}; - - if (static_cast(CValue1) & right) - { - Doors.instances[side::right].remote_open = true; - Doors.instances[side::right].remote_close = false; - } - if (static_cast(CValue1) & left) - { - Doors.instances[side::left].remote_open = true; - Doors.instances[side::left].remote_close = false; - } + Doors.instances[side::right].remote_open = true; + Doors.instances[side::right].remote_close = false; + } + if (static_cast(CValue1) & leftside) + { + Doors.instances[side::left].remote_open = true; + Doors.instances[side::left].remote_close = false; } } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == "DoorClose") /*NBMX*/ { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - if (Doors.close_control == control_t::conductor || Doors.close_control == control_t::driver || Doors.close_control == control_t::mixed) + // ignore remote command if the door is only operated locally + if ((Doors.close_control == control_t::conductor || Doors.close_control == control_t::driver || Doors.close_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) { - // ignore remote command if the door is only operated locally - if (Power24vIsAvailable || Power110vIsAvailable) + + auto const leftside{CValue2 > 0 ? 1 : 2}; + + if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) { - - auto const left{CValue2 > 0 ? 1 : 2}; - auto const right{3 - left}; - - if (static_cast(CValue1) & right) - { - Doors.instances[side::right].remote_close = true; - Doors.instances[side::right].remote_open = false; - } - if (static_cast(CValue1) & left) - { - Doors.instances[side::left].remote_close = true; - Doors.instances[side::left].remote_open = false; - } + Doors.instances[side::right].remote_close = true; + Doors.instances[side::right].remote_open = false; + } + if (static_cast(CValue1) & leftside) + { + Doors.instances[side::left].remote_close = true; + Doors.instances[side::left].remote_open = false; } } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -12628,9 +12532,8 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV auto const inputcab{(static_cast(CValue1) & 0x40) != 0 ? 1 : 0}; auto const inputoperation{static_cast(CValue1) & ~(0x80 | 0x40)}; auto const noswap{TrainType == dt_EZT || TrainType == dt_ET41}; - auto swap{false == noswap && TestFlag(Couplers[(CValue2 == -1 ? end::rear : end::front)].CouplingFlag, coupling::control)}; - auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; - if (reversed) + auto swap{false == noswap && TestFlag(Couplers[CValue2 == -1 ? end::rear : end::front].CouplingFlag, coupling::control)}; + if (auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; reversed) { swap = !swap; } // TODO: check whether this part has RL equivalent @@ -12673,8 +12576,7 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV } else if (Command == "BrakeDelay") { - auto const brakesetting = static_cast(std::floor(CValue1)); - if (true == Hamulec->SetBDF(brakesetting)) + if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) { BrakeDelayFlag = brakesetting; OK = true; @@ -12795,7 +12697,7 @@ bool TMoverParameters::RunInternalCommand() // ************************************************************************************************* double TMoverParameters::ShowCurrentP(int AmpN) const { - int b, Bn; + int Bn; bool Grupowy; // ClearPendingExceptions; @@ -12819,11 +12721,10 @@ double TMoverParameters::ShowCurrentP(int AmpN) const else // pobor pradu jezeli niema mocy { int current = 0; - for (b = 0; b < 2; b++) + for (int b = 0; b < 2; b++) // with Couplers[b] do - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Power > 0.01) - current = static_cast(Couplers[b].Connected->ShowCurrent(AmpN)); + if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) + current = static_cast(Couplers[b].Connected->ShowCurrent(AmpN)); return current; } } @@ -12833,8 +12734,7 @@ bool TMoverParameters::reload_FIZ() WriteLog("[DEV] Reloading FIZ for " + Name); // pause simulation Global.iPause |= 0b1000; - bool result = LoadFIZ(chkPath); - if (result == true) + if (bool result = LoadFIZ(chkPath); result == true) { // jesli sie udalo przeladowac FIZ Global.iPause &= 0b0111; diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp index 9559d305..17fa79ee 100644 --- a/McZapkie/Oerlikon_ESt.cpp +++ b/McZapkie/Oerlikon_ESt.cpp @@ -211,7 +211,7 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr double dV{ 0.0 }; double dV1{ 0.0 }; - double const nastG = static_cast(BrakeDelayFlag & bdelay_G); + auto const nastG = static_cast(BrakeDelayFlag & bdelay_G); // sprawdzanie stanu CheckState(BCP, dV1); @@ -294,8 +294,9 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr return dV - dV1; } -void TNESt3::EStParams( double const i_crc ) // parametry charakterystyczne dla ESt +void TNESt3::EStParams( double const /*i_crc*/ ) const // parametry charakterystyczne dla ESt { + // no effect for this device type } void TNESt3::Init( double const PP, double const HPP, double const LPP, double const BP, int const BDF ) @@ -318,7 +319,9 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c Zamykajacy = false; - if ( typeid(*FM) == typeid(TDisk1) || typeid(*FM) == typeid(TDisk2) ) // jesli zeliwo to schodz + auto const &frictionmaterial { *FM }; + auto const &frictionmaterialtype { typeid( frictionmaterial ) }; + if ( frictionmaterialtype == typeid(TDisk1) || frictionmaterialtype == typeid(TDisk2) ) // jesli zeliwo to schodz RapidStaly = true; else RapidStaly = false; @@ -331,9 +334,8 @@ double TNESt3::GetCRP() // return Miedzypoj.P; } -void TNESt3::CheckState(double const BCP, double &dV1) // glowny przyrzad rozrzadczy +void TNESt3::CheckState(double const BCP, double & /*dV1*/) // glowny przyrzad rozrzadczy { - double const BVP{ BrakeRes->P() }; //-> tu ma byc komora rozprezna double const VVP{ ValveRes->P() }; double const CVP{ CntrlRes->P() }; double const MPP{ Miedzypoj->P() }; @@ -355,14 +357,14 @@ void TNESt3::CheckState(double const BCP, double &dV1) // glowny przyrzad rozrza if( ( BrakeStatus & b_hld ) == 0 ) SoundFlag |= sf_CylU; - if (VVP + 0.10 < CVP && BCP < 0.25) // poczatek hamowania - if (false == Przys_blok) - { - ValveRes->CreatePress(0.1 * VVP); - SoundFlag |= sf_Acc; - ValveRes->Act(); - Przys_blok = true; - } + // poczatek hamowania + if (VVP + 0.10 < CVP && BCP < 0.25 && false == Przys_blok) + { + ValveRes->CreatePress(0.1 * VVP); + SoundFlag |= sf_Acc; + ValveRes->Act(); + Przys_blok = true; + } if (BCP > 0.5) Zamykajacy = true; @@ -384,7 +386,7 @@ void TNESt3::CheckReleaser(double const dt) // odluzniacz } } -double TNESt3::CVs(double const BP) // napelniacz sterujacego +double TNESt3::CVs(double const /*BP*/) const // napelniacz sterujacego { double const CVP{ CntrlRes->P() }; double const MPP{ Miedzypoj->P() }; @@ -398,7 +400,7 @@ double TNESt3::CVs(double const BP) // napelniacz sterujacego return Nozzles[dSm]; } -double TNESt3::BVs(double const BCP) // napelniacz pomocniczego +double TNESt3::BVs(double const BCP) const // napelniacz pomocniczego { double const CVP{ CntrlRes->P() }; double const MPP{ Miedzypoj->P() }; @@ -637,9 +639,9 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie Nozzles[dSm] = 0.9; // przeliczanie z mm^2 na l/m - for (int i = 0; i < dMAX; ++i) + for (auto &nozzle : Nozzles) { - Nozzles[i] = d2A(Nozzles[i]); //(/1000^2*pi/4*1000) + nozzle = d2A(nozzle); //(/1000^2*pi/4*1000) } for (int i = 1; i < 4; ++i) { diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h index c1269185..224ffecd 100644 --- a/McZapkie/Oerlikon_ESt.h +++ b/McZapkie/Oerlikon_ESt.h @@ -70,38 +70,32 @@ static int const P_ed = 5; class TPrzekladnik : public TReservoir // przekladnik (powtarzacz) { - private: public: std::shared_ptr BrakeRes; std::shared_ptr Next; - TPrzekladnik() : TReservoir() {}; + using TReservoir::TReservoir; virtual void Update(double dt); }; class TRura : public TPrzekladnik // nieprzekladnik, rura laczaca { - private: public: - TRura() : TPrzekladnik() {}; - virtual double P(void) /*override*/; - virtual void Update(double dt) /*override*/; + using TPrzekladnik::TPrzekladnik; + double P(void) override; + void Update(double dt) override; }; class TPrzeciwposlizg : public TRura // przy napelnianiu - rura, przy poslizgu - upust { private: - bool Poslizg; + bool Poslizg{false}; public: void SetPoslizg(bool flag); - void Update(double dt) /*override*/; - inline TPrzeciwposlizg() : TRura() - { - Poslizg = false; - } + void Update(double dt) override; }; // przekladnik dwustopniowy @@ -117,10 +111,8 @@ class TRapid : public TPrzekladnik { public: void SetRapidParams(double mult, double size); void SetRapidStatus(bool rs); - void Update(double dt) /*override*/; - inline TRapid() : - TPrzekladnik() - {} + void Update(double dt) override; + using TPrzekladnik::TPrzekladnik; }; // AL2 @@ -131,10 +123,8 @@ class TPrzekCiagly : public TPrzekladnik { public: void SetMult(double m); - void Update(double dt) /*override*/; - inline TPrzekCiagly() : - TPrzekladnik() - {} + void Update(double dt) override; + using TPrzekladnik::TPrzekladnik; }; // podwojny zawor zwrotny @@ -145,20 +135,15 @@ class TPrzek_PZZ : public TPrzekladnik { public: void SetLBP(double P); - void Update(double dt) /*override*/; - inline TPrzek_PZZ() : - TPrzekladnik() - {} + void Update(double dt) override; + using TPrzekladnik::TPrzekladnik; }; class TPrzekZalamany : public TPrzekladnik // Knicksventil { - private: public: - TPrzekZalamany() : - TPrzekladnik() - {} + using TPrzekladnik::TPrzekladnik; }; // przy napelnianiu - rura, przy hamowaniu - upust @@ -169,10 +154,8 @@ class TPrzekED : public TRura { public: void SetP(double P); - void Update(double dt) /*override*/; - inline TPrzekED() : - TRura() - {} + void Update(double dt) override; + using TRura::TRura; }; class TNESt3 : public TBrake { @@ -206,22 +189,20 @@ class TNESt3 : public TBrake { double LBP = 0.0; // cisnienie hamulca pomocniczego public: - inline TNESt3(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : - TBrake( i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) - {} - void Init( double const PP, double const HPP, double const LPP, double const BP, int const BDF ) /*override*/; - virtual double GetPF( double const PP, double const dt, double const Vel ) /*override*/; // przeplyw miedzy komora wstepna i PG - void EStParams(double i_crc); // parametry charakterystyczne dla ESt - virtual double GetCRP() /*override*/; + using TBrake::TBrake; + void Init( double const PP, double const HPP, double const LPP, double const BP, int const BDF ) override; + double GetPF( double const PP, double const dt, double const Vel ) override; // przeplyw miedzy komora wstepna i PG + void EStParams(double i_crc) const; // parametry charakterystyczne dla ESt + double GetCRP() override; void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy void CheckReleaser(double const dt); // odluzniacz - double CVs(double const BP); // napelniacz sterujacego - double BVs(double const BCP); // napelniacz pomocniczego + double CVs(double const BP) const; // napelniacz sterujacego + double BVs(double const BCP) const; // napelniacz pomocniczego void SetSize( int const size, std::string const ¶ms ); // ustawianie dysz (rozmiaru ZR), przekladniki - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej - virtual void ForceEmptiness() /*override*/; // wymuszenie bycia pustym - void SetLBP(double const P); // cisnienie z hamulca pomocniczego + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej + void ForceEmptiness() override; // wymuszenie bycia pustym + void SetLBP(double const P) override; // cisnienie z hamulca pomocniczego }; extern double d2A( double const d ); diff --git a/McZapkie/friction.h b/McZapkie/friction.h index 067a61b9..c58895a9 100644 --- a/McZapkie/friction.h +++ b/McZapkie/friction.h @@ -41,6 +41,7 @@ class TFricMat public: virtual double GetFC(double N, double Vel); + virtual ~TFricMat() = default; }; @@ -49,7 +50,7 @@ class TP10Bg: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -59,7 +60,7 @@ class TP10Bgu: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -69,7 +70,7 @@ class TP10yBg: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -79,7 +80,7 @@ class TP10yBgu: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -89,7 +90,7 @@ class TP10: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -99,7 +100,7 @@ class TFR513: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -109,7 +110,7 @@ class TFR510: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -119,7 +120,7 @@ class TCosid: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -129,7 +130,7 @@ class TDisk1: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -139,7 +140,7 @@ class TDisk2: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; diff --git a/McZapkie/hamulce.cpp b/McZapkie/hamulce.cpp index 64a7fb85..c0a7d2a0 100644 --- a/McZapkie/hamulce.cpp +++ b/McZapkie/hamulce.cpp @@ -357,21 +357,14 @@ end ; */ /// Friction material id (bp_* constant, optionally OR'ed with bp_MHS). /// Number of braked axles. /// Number of blocks per axle. -TBrake::TBrake(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) +TBrake::TBrake(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : + BCN(i_bcn), BCM(1), BCA(i_bcn * i_bcr * i_bcr * M_PI), BrakeDelays(i_BD), MaxBP(i_mbp), BA(i_ba), NBpA(i_nbpa), SizeBR(i_brc * 0.0128) { // inherited:: Create; - MaxBP = i_mbp; - BCN = i_bcn; - BCM = 1; - BCA = i_bcn * i_bcr * i_bcr * M_PI; - BA = i_ba; - NBpA = i_nbpa; - BrakeDelays = i_BD; BrakeDelayFlag = bdelay_P; // 210.88 // SizeBR:=i_bcn*i_bcr*i_bcr*i_bcd*40.17*MaxBP/(5-MaxBP); //objetosc ZP w stosunku do cylindra // 14" i cisnienia 4.2 atm - SizeBR = i_brc * 0.0128; SizeBC = i_bcn * i_bcr * i_bcr * i_bcd * 210.88 * MaxBP / 4.2; // objetosc CH w stosunku do cylindra 14" i cisnienia 4.2 atm BrakeCyl = std::make_shared(); @@ -450,7 +443,7 @@ double TBrake::GetFC(double const Vel, double const N) /// Returns the gauge pressure inside the brake cylinder. // cisnienie cylindra hamulcowego -double TBrake::GetBCP() +double TBrake::GetBCP() const { return BrakeCyl->P(); } @@ -464,14 +457,14 @@ double TBrake::GetEDBCP() /// Returns the auxiliary reservoir (ZP) pressure. // cisnienie zbiornika pomocniczego -double TBrake::GetBRP() +double TBrake::GetBRP() const { return BrakeRes->P(); } /// Returns the valve pre-chamber pressure. // cisnienie komory wstepnej -double TBrake::GetVRP() +double TBrake::GetVRP() const { return ValveRes->P(); } @@ -516,7 +509,7 @@ double TBrake::GetHPFlow(double const HP, double const dt) /// /// Returns the piston force from the cylinder pressure (BCA * 100 * P). /// -double TBrake::GetBCF() +double TBrake::GetBCF() const { return BCA * 100 * BrakeCyl->P(); } @@ -558,7 +551,7 @@ bool TBrake::Releaser() const /// support the EP brake (TWest, TEStEP1/2, ...). /// /// EP intensity. -void TBrake::SetEPS(double const nEPS) {} +void TBrake::SetEPS(double const nEPS) { /* no effect for this device type */ } /// /// Sets the anti-slip brake state flags. Bit 1 of @@ -572,7 +565,7 @@ void TBrake::ASB(int const state) } /// Returns the raw BrakeStatus bitfield. -int TBrake::GetStatus() +int TBrake::GetStatus() const { return BrakeStatus; } @@ -674,14 +667,14 @@ double TWest::GetPF(double const PP, double const dt, double const Vel) BCP = BrakeCyl->P(); if ((BrakeStatus & b_hld) == b_hld) + { if (VVP + 0.03 < BVP) BrakeStatus |= b_on; else if (VVP > BVP + 0.1) BrakeStatus &= ~(b_on | b_hld); else if (VVP > BVP) BrakeStatus &= ~b_on; - else - ; + } else if (VVP + 0.25 < BVP) BrakeStatus |= b_on | b_hld; @@ -707,7 +700,6 @@ double TWest::GetPF(double const PP, double const dt, double const Vel) temp = BVP * int(EPS > 0); dv = PF(temp, LBP, 0.0015) * dt * EPS * EPS * int(LBP * EPS < MaxBP * LoadC); LBP = LBP - dv; - dv = 0; // przeplyw ZP <-> silowniki if ((BrakeStatus & b_on) == b_on && (TareBP < 0.1 || BCP < MaxBP * LoadC)) @@ -781,20 +773,15 @@ void TWest::SetLBP(double const P) /// New EP intensity. void TWest::SetEPS(double const nEPS) { - double BCP; - BCP = BrakeCyl->P(); if (nEPS > 0) DCV = true; - else if (nEPS == 0) + else if (nEPS == 0 && EPS != 0) { - if (EPS != 0) - { - if (LBP > 0.4) - LBP = BrakeCyl->P(); - if (LBP < 0.15) - LBP = 0; - } + if (LBP > 0.4) + LBP = BrakeCyl->P(); + if (LBP < 0.15) + LBP = 0; } EPS = nEPS; } @@ -838,12 +825,14 @@ void TESt::CheckReleaser(double const dt) // odluzniacz if ((BrakeStatus & b_rls) == b_rls) + { if (CVP - VVP < 0) BrakeStatus &= ~b_rls; else { CntrlRes->Flow(+PF(CVP, 0, 0.1) * dt); } + } } /// @@ -854,11 +843,10 @@ void TESt::CheckReleaser(double const dt) /// /// Brake cylinder (or impulse-chamber) pressure. /// In/out brake-pipe flow correction (unused in this base impl). -void TESt::CheckState(double const BCP, double &dV1) +void TESt::CheckState(double const BCP, double & /*dV1*/) { double const VVP{ValveRes->P()}; - double const BVP{BrakeRes->P()}; double const CVP{CntrlRes->P()}; // sprawdzanie stanu @@ -927,7 +915,7 @@ void TESt::CheckState(double const BCP, double &dV1) /// /// Brake cylinder (or impulse) pressure. /// Opening coefficient (0 closed, 1 fully open). -double TESt::CVs(double const BP) +double TESt::CVs(double const BP) const { double VVP; double BVP; @@ -958,7 +946,7 @@ double TESt::CVs(double const BP) /// /// Brake cylinder pressure. /// Opening coefficient. -double TESt::BVs(double const BCP) +double TESt::BVs(double const BCP) const { double VVP; double BVP; @@ -1000,11 +988,8 @@ double TESt::GetPF(double const PP, double const dt, double const Vel) double CVP; BVP = BrakeRes->P(); - VVP = ValveRes->P(); BCP = BrakeCyl->P(); - CVP = CntrlRes->P() - 0.0; - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -1086,7 +1071,7 @@ void TESt::Init(double const PP, double const HPP, double const LPP, double cons /// derived variants and currently a no-op. /// /// Characteristic value. -void TESt::EStParams(double const i_crc) {} +void TESt::EStParams(double const /*i_crc*/) const { /* no effect for this device type */ } /// Returns the control reservoir (ZS) pressure. double TESt::GetCRP() @@ -1160,7 +1145,6 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) BCP = ImplsRes->P(); CVP = CntrlRes->P(); // 110115 - konsultacje warszawa1 - dv = 0; dV1 = 0; // odluzniacz @@ -1168,14 +1152,14 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) // sprawdzanie stanu if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) + { if (VVP + 0.003 + BCP / BVM < CVP - 0.12) BrakeStatus |= b_on; // hamowanie stopniowe; else if (VVP - 0.003 + BCP / BVM > CVP - 0.12) BrakeStatus &= ~(b_on | b_hld); // luzowanie; else if (VVP + BCP / BVM > CVP - 0.12) BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - else - ; + } else if (VVP + 0.10 < CVP - 0.12 && BCP < 0.25) // poczatek hamowania { // if ((BrakeStatus & 1) == 0) @@ -1343,9 +1327,9 @@ void TEStEP1::SetEPS(double const nEPS) double TESt3::GetPF(double const PP, double const dt, double const Vel) { double BVP{BrakeRes->P()}; - double VVP{ValveRes->P()}; + double VVP; double BCP{BrakeCyl->P()}; - double CVP{CntrlRes->P() - 0.0}; + double CVP; double dv{0.0}; double dV1{0.0}; @@ -1420,11 +1404,8 @@ double TESt4R::GetPF(double const PP, double const dt, double const Vel) double CVP; BVP = BrakeRes->P(); - VVP = ValveRes->P(); BCP = ImplsRes->P(); - CVP = CntrlRes->P(); - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -1543,11 +1524,9 @@ double TESt3AL2::GetPF(double const PP, double const dt, double const Vel) double CVP; BVP = BrakeRes->P(); - VVP = ValveRes->P(); BCP = ImplsRes->P(); CVP = CntrlRes->P() - 0.0; - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -1715,8 +1694,7 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) SoundFlag |= sf_CylU; } // equivalent of checkreleaser() in the base class? - bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; - if (is_releasing) + if (bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; is_releasing) { if (CVP < 0.0) { @@ -1934,14 +1912,14 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania BrakeStatus |= b_hld; - if (VVP + 0.10 < CVP && BCP < 0.25) // poczatek hamowania - if (!Przys_blok) - { - ValveRes->CreatePress(0.75 * VVP); - SoundFlag |= sf_Acc; - ValveRes->Act(); - Przys_blok = true; - } + // poczatek hamowania + if (VVP + 0.10 < CVP && BCP < 0.25 && !Przys_blok) + { + ValveRes->CreatePress(0.75 * VVP); + SoundFlag |= sf_Acc; + ValveRes->Act(); + Przys_blok = true; + } if (BCP > 0.5) Zamykajacy = true; @@ -2069,7 +2047,6 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) void TEStED::Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) { TLSt::Init(PP, HPP, LPP, BP, BDF); - int i; ValveRes->CreatePress(PP); BrakeCyl->CreatePress(BP); @@ -2104,7 +2081,7 @@ void TEStED::Init(double const PP, double const HPP, double const LPP, double co Nozzles[6] = 0.9; { - for (i = 0; i < 11; ++i) + for (int i = 0; i < 11; ++i) { Nozzles[i] = Nozzles[i] * Nozzles[i] * 3.14159 / 4000; } @@ -2165,14 +2142,14 @@ void TCV1::CheckState(double const BCP, double &dV1) // sprawdzanie stanu if ((BrakeStatus & b_hld) == b_hld) + { if (VVP + 0.003 + BCP / BVM < CVP) BrakeStatus |= b_on; // hamowanie stopniowe; else if (VVP - 0.003 + BCP * 1.0 / BVM > CVP) BrakeStatus &= ~(b_on | b_hld); // luzowanie; else if (VVP + BCP * 1.0 / BVM > CVP) BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - else - ; + } else if (VVP + 0.10 < CVP && BCP < 0.1) // poczatek hamowania { BrakeStatus |= b_on | b_hld; @@ -2188,7 +2165,7 @@ void TCV1::CheckState(double const BCP, double &dV1) /// /// Cylinder pressure. /// Opening coefficient. -double TCV1::CVs(double const BP) +double TCV1::CVs(double const BP) const { // przeplyw ZS <-> PG if (BP > 0.05) @@ -2204,7 +2181,7 @@ double TCV1::CVs(double const BP) /// /// Cylinder pressure. /// Opening coefficient. -double TCV1::BVs(double const BCP) +double TCV1::BVs(double const BCP) const { double VVP; double BVP; @@ -2243,11 +2220,9 @@ double TCV1::GetPF(double const PP, double const dt, double const Vel) double CVP; BVP = BrakeRes->P(); - VVP = std::min(ValveRes->P(), BVP + 0.05); BCP = BrakeCyl->P(); CVP = CntrlRes->P(); - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -2402,11 +2377,9 @@ double TCV1L_TR::GetPF(double const PP, double const dt, double const Vel) double CVP; BVP = BrakeRes->P(); - VVP = std::min(ValveRes->P(), BVP + 0.05); BCP = ImplsRes->P(); CVP = CntrlRes->P(); - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -2488,10 +2461,12 @@ void TKE::CheckReleaser(double const dt) // odluzniacz if (true == ((BrakeStatus & b_rls) == b_rls)) + { if (CVP - VVP < 0) BrakeStatus &= ~b_rls; else CntrlRes->Flow(+PF(CVP, 0, 0.1) * dt); + } } /// @@ -2502,13 +2477,11 @@ void TKE::CheckReleaser(double const dt) /// /// Cylinder (or impulse-chamber) pressure. /// In/out brake-pipe flow correction (unused here). -void TKE::CheckState(double const BCP, double &dV1) +void TKE::CheckState(double const BCP, double & /*dV1*/) { double VVP; - double BVP; double CVP; - BVP = BrakeRes->P(); VVP = ValveRes->P(); CVP = CntrlRes->P(); @@ -2578,13 +2551,11 @@ void TKE::CheckState(double const BCP, double &dV1) /// /// Cylinder (or impulse) pressure. /// Opening coefficient. -double TKE::CVs(double const BP) +double TKE::CVs(double const BP) const { double VVP; - double BVP; double CVP; - BVP = BrakeRes->P(); CVP = CntrlRes->P(); VVP = ValveRes->P(); @@ -2604,7 +2575,7 @@ double TKE::CVs(double const BP) /// /// Impulse-chamber pressure. /// Opening coefficient. -double TKE::BVs(double const BCP) +double TKE::BVs(double const /*BCP*/) const { double VVP; double BVP; @@ -2651,7 +2622,6 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) IMP = ImplsRes->P(); CVP = CntrlRes->P(); - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -2694,7 +2664,8 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) ImplsRes->Flow(-dv); // rapid - if (!(typeid(*FM) == typeid(TDisk1) || typeid(*FM) == typeid(TDisk2))) // jesli zeliwo to schodz + auto const &frictionmaterial{*FM}; + if (auto const &frictionmaterialtype{typeid(frictionmaterial)}; !(frictionmaterialtype == typeid(TDisk1) || frictionmaterialtype == typeid(TDisk2))) // jesli zeliwo to schodz RapidStatus = (BrakeDelayFlag & bdelay_R) == bdelay_R && (RV < 0 || (Vel > RV && RapidStatus) || Vel > RV + 20); else // jesli tarczowki, to zostan RapidStatus = (BrakeDelayFlag & bdelay_R) == bdelay_R; @@ -2872,7 +2843,7 @@ void TDriverHandle::Init(double Press) /// Default reductor adjustment — no-op. /// Pressure correction. -void TDriverHandle::SetReductor(double nAdj) {} +void TDriverHandle::SetReductor(double nAdj) { /* no effect for this device type */ } /// Default cab-gauge pressure — 0. double TDriverHandle::GetCP() @@ -2969,9 +2940,8 @@ double TFV4a::GetPF(double i_bcp, double PP, double HP, double dt, double ep) if (lround(i_bcp) == -1) { CP = CP + 5 * std::min(std::abs(LimPP - CP), 0.2) * PR(CP, LimPP) * dt / 2; - if (CP < RP + 0.03) - if (TP < 5) - TP = TP + dt; + if (CP < RP + 0.03 && TP < 5) + TP = TP + dt; // if(cp+0.03<5.4)then if (RP + 0.03 < 5.4 || CP + 0.03 < 5.4) // fala dpMainValve = PF(std::min(HP, 17.1), PP, ActFlowSpeed / LBDelay) * dt; @@ -3037,11 +3007,10 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) int const LBDelay{100}; double const xpM{0.3}; // mnoznik membrany komory pod - ep = PP / 2.0 * 1.5 + ep / 2.0 * 0.5; // SPKS!! - for (int idx = 0; idx < 5; ++idx) + for (auto &soundvalue : Sounds) { - Sounds[idx] = 0; + soundvalue = 0; } // na wszelki wypadek, zeby nie wyszlo poza zakres @@ -3134,13 +3103,9 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) } } - if (EQ(i_bcp, 0)) + if (EQ(i_bcp, 0) && TP > 2) { - - if (TP > 2) - { - dpMainValve *= 1.5; - } + dpMainValve *= 1.5; } ep = dpPipe; @@ -3239,16 +3204,16 @@ double TFV4aM::GetRP() /// /// Continuous handle position. /// Interpolated target pressure [bar]. -double TFV4aM::LPP_RP(double pos) // cisnienie z zaokraglonej pozycji; +double TFV4aM::LPP_RP(double pos) const // cisnienie z zaokraglonej pozycji; { - int const i_pos = 2 + std::floor(pos); // zaokraglone w dol + auto const i_pos = static_cast(2 + std::floor(pos)); // zaokraglone w dol return BPT[i_pos][1] + (BPT[i_pos + 1][1] - BPT[i_pos][1]) * (pos + 2 - i_pos); // interpolacja liniowa } /// Returns true if pos is within ±0.5 of i_pos (detent test). /// Continuous handle position. /// Detent centre. -bool TFV4aM::EQ(double pos, double i_pos) +bool TFV4aM::EQ(double pos, double i_pos) const { return pos <= i_pos + 0.5 && pos > i_pos - 0.5; } @@ -3279,12 +3244,11 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep double DP; double pom; - for (int idx = 0; idx < 5; ++idx) + for (auto &soundvalue : Sounds) { - Sounds[idx] = 0; + soundvalue = 0; } - DP = 0; i_bcp = std::clamp(i_bcp, -0.999, 9.999); // na wszelki wypadek, zeby nie wyszlo poza zakres @@ -3425,7 +3389,7 @@ double TMHZ_EN57::GetEP(double pos) /// /// Continuous handle position. /// Target brake-pipe pressure [bar]. -double TMHZ_EN57::LPP_RP(double pos) // cisnienie z zaokraglonej pozycji; +double TMHZ_EN57::LPP_RP(double pos) const // cisnienie z zaokraglonej pozycji; { if (pos > 8.5) return 5.0 - 0.15 * pos - 0.35; @@ -3456,7 +3420,7 @@ void TMHZ_EN57::SetParams(bool AO, bool MO, double OverP, double, double OMP, do } /// Returns true if pos is within ±0.5 of i_pos (detent test). -bool TMHZ_EN57::EQ(double pos, double i_pos) +bool TMHZ_EN57::EQ(double pos, double i_pos) const { return pos <= i_pos + 0.5 && pos > i_pos - 0.5; } @@ -3484,14 +3448,12 @@ double TMHZ_K5P::GetPF(double i_bcp, double PP, double HP, double dt, double ep) double dpMainValve; double ActFlowSpeed; double DP; - double pom; - for (int idx = 0; idx < 5; ++idx) + for (auto &soundvalue : Sounds) { - Sounds[idx] = 0; + soundvalue = 0; } - DP = 0; i_bcp = std::clamp(i_bcp, -0.999, 2.999); // na wszelki wypadek, zeby nie wyszlo poza zakres @@ -3512,7 +3474,6 @@ double TMHZ_K5P::GetPF(double i_bcp, double PP, double HP, double dt, double ep) LimCP = 3.4; else // luzowanie LimCP = 5.0; - pom = CP; LimCP = std::min(LimCP, HP); // pozycja + czasowy lub zasilanie ActFlowSpeed = 4; @@ -3636,7 +3597,7 @@ void TMHZ_K5P::SetParams(bool AO, bool MO, double OverP, double FSF, double OMP, } /// Returns true if pos is within ±0.5 of i_pos (detent test). -bool TMHZ_K5P::EQ(double pos, double i_pos) +bool TMHZ_K5P::EQ(double pos, double i_pos) const { return pos <= i_pos + 0.5 && pos > i_pos - 0.5; } @@ -3663,14 +3624,12 @@ double TMHZ_6P::GetPF(double i_bcp, double PP, double HP, double dt, double ep) double dpMainValve; double ActFlowSpeed; double DP; - double pom; - for (int idx = 0; idx < 5; ++idx) + for (auto &soundvalue : Sounds) { - Sounds[idx] = 0; + soundvalue = 0; } - DP = 0; i_bcp = std::clamp(i_bcp, -0.999, 3.999); // na wszelki wypadek, zeby nie wyszlo poza zakres @@ -3691,7 +3650,6 @@ double TMHZ_6P::GetPF(double i_bcp, double PP, double HP, double dt, double ep) LimCP = 3.4; else // luzowanie LimCP = 5.0; - pom = CP; LimCP = std::min(LimCP, HP); // pozycja + czasowy lub zasilanie ActFlowSpeed = 4; @@ -3815,7 +3773,7 @@ void TMHZ_6P::SetParams(bool AO, bool MO, double OverP, double FSF, double OMP, } /// Returns true if pos is within ±0.5 of i_pos (detent test). -bool TMHZ_6P::EQ(double pos, double i_pos) +bool TMHZ_6P::EQ(double pos, double i_pos) const { return pos <= i_pos + 0.5 && pos > i_pos - 0.5; } @@ -3844,7 +3802,7 @@ double TM394::GetPF(double i_bcp, double PP, double HP, double dt, double ep) double ActFlowSpeed; int BCP; - BCP = lround(i_bcp); + BCP = static_cast(lround(i_bcp)); if (BCP < -1) BCP = 1; @@ -3855,6 +3813,7 @@ double TM394::GetPF(double i_bcp, double PP, double HP, double dt, double ep) if (BCP == 0) LimPP = LimPP + RedAdj; if (BCP != 2) + { if (CP < LimPP) CP = CP + 4 * std::min(abs(LimPP - CP), 0.05) * PR(CP, LimPP) * dt; // zbiornik sterujacy // cp:=cp+6*(2+int(bcp<0))*std::min(abs(Limpp-cp),0.05)*PR(cp,Limpp)*dt //zbiornik @@ -3863,6 +3822,7 @@ double TM394::GetPF(double i_bcp, double PP, double HP, double dt, double ep) CP = CP - 0.2 * dt / 100; else CP = CP + 4 * (1 + int(BCP != 3) + int(BCP > 4)) * std::min(abs(LimPP - CP), 0.05) * PR(CP, LimPP) * dt; // zbiornik sterujacy + } LimPP = CP; dpPipe = std::min(HP, LimPP); @@ -3937,7 +3897,7 @@ double TH14K1::GetPF(double i_bcp, double PP, double HP, double dt, double ep) //{ (10, 0), (4, 1), (0, 1), (4, 0), (4, -1), (15, -1) }; double const NomPress = 5.0; - int BCP = std::lround(i_bcp); + auto BCP = static_cast(std::lround(i_bcp)); if (i_bcp < -1) { BCP = 1; @@ -4034,7 +3994,7 @@ double TSt113::GetPF(double i_bcp, double PP, double HP, double dt, double ep) CP = PP; - BCP = lround(i_bcp); + BCP = static_cast(lround(i_bcp)); EPS = BEP_K[BCP + 1]; diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index a05a3635..3074a2e7 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -272,10 +272,11 @@ class TReservoir /// Default constructor — creates a 1 L reservoir at zero pressure. TReservoir() = default; + virtual ~TReservoir() = default; }; /// Pointer typedef for a reservoir instance. -typedef TReservoir *PReservoir; +using PReservoir = TReservoir *; /// /// Brake cylinder reservoir — overrides pressure functions to model the @@ -290,15 +291,15 @@ class TBrakeCyl : public TReservoir /// Returns absolute pressure inside the brake cylinder (P() * 0.1). /// /// Absolute cylinder pressure. - virtual double pa() /*override*/; + double pa() override; /// /// Returns gauge pressure inside the brake cylinder, modelling the /// piston-stroke pressure curve (dead volume, linear stroke, fully extended). /// /// Cylinder pressure in bar. - virtual double P() /*override*/; + double P() override; /// Default constructor. - TBrakeCyl() : TReservoir() {}; + using TReservoir::TReservoir; }; /// @@ -399,7 +400,7 @@ class TBrake /// Returns the piston force produced by the brake cylinder pressure. /// /// Force in arbitrary engine units (BCA * 100 * P). - double GetBCF(); // sila tlokowa z tloka + double GetBCF() const; // sila tlokowa z tloka /// /// Computes the airflow drawn from the high-pressure (8 bar / main) line for one step. /// @@ -408,16 +409,16 @@ class TBrake /// Net flow from the high-pressure line. virtual double GetHPFlow(double const HP, double const dt); // przeplyw - 8 bar /// Returns brake cylinder gauge pressure [bar]. - double GetBCP(); // cisnienie cylindrow hamulcowych + double GetBCP() const; // cisnienie cylindrow hamulcowych /// /// Returns brake cylinder pressure originating only from the pneumatic /// (main) brake — used to drive the ED (electrodynamic) brake e.g. in EP09. /// virtual double GetEDBCP(); // cisnienie tylko z hamulca zasadniczego, uzywane do hamulca ED w EP09 /// Returns auxiliary reservoir (ZP) pressure [bar]. - double GetBRP(); // cisnienie zbiornika pomocniczego + double GetBRP() const; // cisnienie zbiornika pomocniczego /// Returns valve pre-chamber pressure [bar]. - double GetVRP(); // cisnienie komory wstepnej rozdzielacza + double GetVRP() const; // cisnienie komory wstepnej rozdzielacza /// Returns control reservoir (ZS) pressure [bar]; defaults to the auxiliary reservoir for valves without a dedicated ZS. virtual double GetCRP(); // cisnienie zbiornika sterujacego /// @@ -441,7 +442,7 @@ class TBrake virtual void SetEPS(double const nEPS); // hamulec EP /// Sets the rapid step ratio. Default no-op; overridden where supported. /// Rapid ratio. - virtual void SetRM(double const RMR) {}; // ustalenie przelozenia rapida + virtual void SetRM(double const RMR) { /* no effect for this device type */ } // ustalenie przelozenia rapida /// Sets the velocity threshold for the rapid step. /// Velocity threshold (same unit as Vel passed to GetPF). virtual void SetRV(double const RVR) @@ -455,20 +456,20 @@ class TBrake /// Tare (empty) mass. /// Loaded mass. /// Brake cylinder pressure for the tare mass. - virtual void SetLP(double const TM, double const LM, double const TBP) {}; // parametry przystawki wazacej + virtual void SetLP(double const TM, double const LM, double const TBP) { /* no effect for this device type */ } // parametry przystawki wazacej /// Sets the auxiliary (local) brake target pressure. /// Local brake pressure [bar]. - virtual void SetLBP(double const P) {}; // cisnienie z hamulca pomocniczego + virtual void SetLBP(double const P) { /* no effect for this device type */ } // cisnienie z hamulca pomocniczego /// Updates the load-weighing pressure coefficient based on current vehicle mass. /// Current vehicle mass. - virtual void PLC(double const mass) {}; // wspolczynnik cisnienia przystawki wazacej + virtual void PLC(double const mass) { /* no effect for this device type */ } // wspolczynnik cisnienia przystawki wazacej /// /// Engages the anti-slip brake function (set hold and/or release flags). /// /// Two-bit value: bit1 = hold (b_asb), bit0 = release (b_asb_unbrake). void ASB(int state); // hamulec przeciwposlizgowy /// Returns the raw BrakeStatus flags (for sound/visual cues). - int GetStatus(); // flaga statusu, moze sie przydac do odglosow + int GetStatus() const; // flaga statusu, moze sie przydac do odglosow /// Sets the anti-slip target pressure. /// Pressure [bar]. void SetASBP(double const Press); // ustalenie cisnienia pp @@ -497,13 +498,14 @@ class TBrake /// brake when ED braking is sufficient. Default no-op; overridden where supported. /// /// ED brake intensity (0..1). - virtual void SetED(double const EDstate) {}; // stan hamulca ED do luzowania + virtual void SetED(double const EDstate) { /* no effect for this device type */ } // stan hamulca ED do luzowania /// Sets the universal-button flags (see TUniversalBrake). /// Combined ub_* flags. virtual void SetUniversalFlag(int flag) { UniversalFlag = flag; } // przycisk uniwersalny + virtual ~TBrake() = default; }; /// @@ -537,26 +539,26 @@ class TWest : public TBrake /// Low pressure. /// Initial cylinder pressure. /// Initial brake delay flag. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// Sets the auxiliary brake target pressure and engages the DCV when above cylinder. /// Pressure [bar]. - void SetLBP(double const P); // cisnienie z hamulca pomocniczego + void SetLBP(double const P) override; // cisnienie z hamulca pomocniczego /// One-step distributor advance (Westinghouse logic). /// Net flow exchanged with the brake pipe. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Returns the high-pressure flow drawn during the last GetPF step. - double GetHPFlow(double const HP, double const dt) /*override*/; + double GetHPFlow(double const HP, double const dt) override; /// Recomputes the load-weighing pressure coefficient for the current mass. /// Vehicle mass. - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej /// Sets the EP brake state and toggles the DCV / latches LBP from cylinder pressure on release. /// New EP intensity. - void SetEPS(double const nEPS) /*override*/; // stan hamulca EP + void SetEPS(double const nEPS) override; // stan hamulca EP /// Stores the load-weighing parameters (TareM, LoadM, TareBP). - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej /// Constructs the distributor by forwarding all parameters to TBrake. - inline TWest(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TBrake(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) {} + using TBrake::TBrake; }; /// @@ -567,7 +569,6 @@ class TWest : public TBrake class TESt : public TBrake { - private: protected: /// Control reservoir (ZS) — long-term reference pressure. std::shared_ptr CntrlRes; // zbiornik sterujący @@ -576,15 +577,15 @@ class TESt : public TBrake public: /// Initialises the ESt distributor; sizes the control reservoir (15 l) and computes BVM. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for the ESt baseline. /// Net flow exchanged with the brake pipe. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Sets ESt-specific characteristic parameters (placeholder; used by some variants). /// Characteristic value. - void EStParams(double i_crc); // parametry charakterystyczne dla ESt + void EStParams(double i_crc) const; // parametry charakterystyczne dla ESt /// Returns the control reservoir (ZS) pressure. - double GetCRP() /*override*/; + double GetCRP() override; /// /// Updates BrakeStatus (b_on/b_hld) according to the relations between /// pre-chamber, cylinder and control reservoir pressures (the main slide valve). @@ -602,16 +603,16 @@ class TESt : public TBrake /// /// Cylinder pressure (or impulse-chamber pressure). /// Dimensionless opening coefficient. - double CVs(double BP); // napelniacz sterujacego + double CVs(double BP) const; // napelniacz sterujacego /// /// Returns the effective opening factor of the auxiliary-reservoir filling /// slide valve (ZP <-> pre-chamber path). /// /// Brake cylinder pressure. /// Dimensionless opening coefficient. - double BVs(double BCP); // napelniacz pomocniczego + double BVs(double BCP) const; // napelniacz pomocniczego /// Vents the valve, brake and control reservoirs to zero. - void ForceEmptiness() /*override*/; // wymuszenie bycia pustym + void ForceEmptiness() override; // wymuszenie bycia pustym /// Constructs the ESt distributor and creates the control reservoir. inline TESt(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TBrake(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -627,16 +628,15 @@ class TESt : public TBrake class TESt3 : public TESt { - private: // double CylFlowSpeed[2][2]; //zmienna nie uzywana public: /// One-step distributor advance for ESt3 (G/P-dependent fill/release curves). /// Net flow exchanged with the brake pipe. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Constructs the ESt3 distributor. - inline TESt3(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TESt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) {} + using TESt::TESt; }; /// @@ -660,13 +660,13 @@ class TESt3AL2 : public TESt3 public: /// Initialises the impulse chamber on top of the ESt initialisation. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for ESt3/AL2 with load-weighing relay. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Recomputes LoadC for the current vehicle mass. - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej /// Stores the load-weighing parameters. - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej /// Constructs the distributor and creates the impulse chamber. inline TESt3AL2(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TESt3(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -695,9 +695,9 @@ class TESt4R : public TESt public: /// Initialises the ESt4R; sizes the impulse chamber and selects the R delay. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for ESt4R (rapid step active above velocity threshold). - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Constructs the distributor and creates the impulse chamber. inline TESt4R(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TESt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -713,7 +713,6 @@ class TESt4R : public TESt class TLSt : public TESt4R { - private: // double CylFlowSpeed[2][2]; // zmienna nie używana protected: @@ -726,24 +725,24 @@ class TLSt : public TESt4R public: /// Initialises the LSt; resizes the valve and impulse reservoirs and presets pressures. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// Sets the auxiliary brake target pressure for the DCV. - void SetLBP(double const P); // cisnienie z hamulca pomocniczego + void SetLBP(double const P) override; // cisnienie z hamulca pomocniczego /// Sets the rapid step ratio (RM = 1 - RMR). /// Reduction ratio (0 disables rapid, > 0 enables). - void SetRM(double const RMR); // ustalenie przelozenia rapida + void SetRM(double const RMR) override; // ustalenie przelozenia rapida /// One-step distributor advance for LSt (DCV + rapid + ED release). - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Computes the high-pressure inflow (replenishes the auxiliary reservoir from the main line). - double GetHPFlow(double const HP, double const dt) /*override*/; // przeplyw - 8 bar + double GetHPFlow(double const HP, double const dt) override; // przeplyw - 8 bar /// Returns the brake-cylinder reference pressure used by the ED brake controller (CVP-BCP * BVM). - virtual double GetEDBCP(); // cisnienie tylko z hamulca zasadniczego, uzywane do hamulca ED w EP09 + double GetEDBCP() override; // cisnienie tylko z hamulca zasadniczego, uzywane do hamulca ED w EP09 /// Sets the ED brake state used to relax the pneumatic brake. /// ED intensity (0..1). - virtual void SetED(double const EDstate); // stan hamulca ED do luzowania + void SetED(double const EDstate) override; // stan hamulca ED do luzowania /// Constructs the LSt distributor. - inline TLSt(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TESt4R(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) {} + using TESt4R::TESt4R; }; /// @@ -774,15 +773,15 @@ class TEStED : public TLSt public: /// Initialises the EStED — sets up Miedzypoj, ImplsRes and the nozzle characteristics. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for EStED (full EP09 logic with intermediate reservoir). - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Returns ED-brake reference pressure (ImplsRes pressure scaled by load coefficient). - double GetEDBCP() /*override*/; // cisnienie tylko z hamulca zasadniczego, uzywane do hamulca ED + double GetEDBCP() override; // cisnienie tylko z hamulca zasadniczego, uzywane do hamulca ED /// Recomputes LoadC for the current vehicle mass. - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej /// Stores the load-weighing parameters. - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej /// Constructs the distributor and creates the intermediate reservoir. inline TEStED(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TLSt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -812,21 +811,21 @@ class TEStEP2 : public TLSt public: /// Initialises the EP2-equipped distributor (impulse chamber, P delay). - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; // inicjalizacja + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; // inicjalizacja /// One-step distributor advance with EP2 EP brake logic. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Recomputes LoadC for the current vehicle mass. - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej /// Sets EP intensity; if EP is active and LBP < cylinder pressure, latches LBP from cylinder. - void SetEPS(double const nEPS) /*override*/; // stan hamulca EP + void SetEPS(double const nEPS) override; // stan hamulca EP /// Stores the load-weighing parameters. - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej /// EP brake flow integration step. Override in EP1 for proportional control. /// Time step [s]. void virtual EPCalc(double dt); /// Constructs the EP2 distributor. - inline TEStEP2(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TLSt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) {} + using TLSt::TLSt; }; /// @@ -839,15 +838,13 @@ class TEStEP1 : public TEStEP2 public: /// Proportional EP flow integration step (uses fractional part of EPS as the EP target). - void EPCalc(double dt); + void EPCalc(double dt) override; /// Stores the EP intensity. /// Target EP value (integer part = direction, fractional part = magnitude). void SetEPS(double const nEPS) override; // stan hamulca EP /// Constructs the EP1 distributor. - inline TEStEP1(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TEStEP2(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) - { - } + using TEStEP2::TEStEP2; }; /// @@ -867,21 +864,21 @@ class TCV1 : public TBrake public: /// Initialises the CV1 distributor (sizes ZS, sets pressures, computes BVM). - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for the CV1 baseline. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Returns the control reservoir (ZS) pressure. - double GetCRP() /*override*/; + double GetCRP() override; /// Updates BrakeStatus based on pre-chamber/cylinder/control reservoir relations and the releaser. /// Cylinder (or impulse) pressure. /// In/out brake pipe flow correction. void CheckState(double const BCP, double &dV1); /// Returns the ZS-filling slide valve opening factor for the given cylinder pressure. - double CVs(double const BP); + double CVs(double const BP) const; /// Returns the ZP-filling slide valve opening factor for the given cylinder pressure. - double BVs(double const BCP); + double BVs(double const BCP) const; /// Vents valve, brake and control reservoirs to zero. - void ForceEmptiness() /*override*/; // wymuszenie bycia pustym + void ForceEmptiness() override; // wymuszenie bycia pustym /// Constructs the CV1 distributor and creates the control reservoir. inline TCV1(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TBrake(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -922,13 +919,13 @@ class TCV1L_TR : public TCV1 public: /// Initialises the CV1-L-TR (sizes the impulse chamber on top of CV1::Init). - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for CV1-L-TR (impulse chamber + DCV). - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Sets the auxiliary brake target pressure for the DCV. - void SetLBP(double const P); // cisnienie z hamulca pomocniczego + void SetLBP(double const P) override; // cisnienie z hamulca pomocniczego /// Computes the high-pressure (8 bar) inflow used to replenish the auxiliary reservoir. - double GetHPFlow(double const HP, double const dt) /*override*/; // przeplyw - 8 bar + double GetHPFlow(double const HP, double const dt) override; // przeplyw - 8 bar /// Constructs the CV1-L-TR and creates the impulse chamber. inline TCV1L_TR(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TCV1(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -971,31 +968,31 @@ class TKE : public TBrake public: /// Initialises the KE distributor (control / impulse / auxiliary reservoirs and BVM). - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// Sets the rapid step ratio (RM = 1 - RMR). - void SetRM(double const RMR); // ustalenie przelozenia rapida + void SetRM(double const RMR) override; // ustalenie przelozenia rapida /// One-step distributor advance for the KE distributor. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Computes the high-pressure (8 bar) inflow used to replenish the auxiliary reservoir. - double GetHPFlow(double const HP, double const dt) /*override*/; // przeplyw - 8 bar + double GetHPFlow(double const HP, double const dt) override; // przeplyw - 8 bar /// Returns the control reservoir (ZS) pressure. - double GetCRP() /*override*/; + double GetCRP() override; /// Updates BrakeStatus from cylinder/pre-chamber/control reservoir pressures (KE-specific thresholds). void CheckState(double const BCP, double &dV1); /// Drives the releaser logic for KE — bleeds the control reservoir while engaged. void CheckReleaser(double const dt); // odluzniacz /// ZS-filling slide valve opening factor for the given cylinder pressure. - double CVs(double const BP); // napelniacz sterujacego + double CVs(double const BP) const; // napelniacz sterujacego /// ZP-filling slide valve opening factor for the given cylinder pressure. - double BVs(double const BCP); // napelniacz pomocniczego + double BVs(double const BCP) const; // napelniacz pomocniczego /// Recomputes LoadC for the current vehicle mass. - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej /// Stores the load-weighing parameters. - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej /// Sets the auxiliary brake target pressure for the DCV. - void SetLBP(double const P); // cisnienie z hamulca pomocniczego + void SetLBP(double const P) override; // cisnienie z hamulca pomocniczego /// Vents valve, brake, control, impulse and secondary auxiliary reservoirs to zero. - void ForceEmptiness() /*override*/; // wymuszenie bycia pustym + void ForceEmptiness() override; // wymuszenie bycia pustym /// Constructs the KE distributor and creates the control / impulse / secondary reservoirs. inline TKE(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TBrake(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -1077,7 +1074,7 @@ class TDriverHandle /// Unbrake over-pressure [bar]. /// Overload (assimilation) max pressure [bar]. /// Overload pressure decay rate [bar/s]. - virtual void SetParams(bool AO, bool MO, double, double, double OMP, double OPD) {}; // ustawianie jakichs parametrow dla zaworu + virtual void SetParams(bool AO, bool MO, double, double, double OMP, double OPD) { /* no effect for this device type */ } // ustawianie jakichs parametrow dla zaworu /// Sets the manual overcharge button state. /// True while the button is pressed. virtual void OvrldButton(bool Active); // przycisk recznego przeladowania/asymilacji @@ -1089,6 +1086,7 @@ class TDriverHandle { memset(Sounds, 0, sizeof(Sounds)); } + virtual ~TDriverHandle() = default; }; /// @@ -1107,12 +1105,12 @@ class TFV4a : public TDriverHandle public: /// Computes brake pipe flow for the FV4a handle (uses BPT[] table). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and RP to the supplied pressure. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Default constructor. - inline TFV4a() : TDriverHandle() {} + using TDriverHandle::TDriverHandle; }; /// @@ -1143,27 +1141,27 @@ class TFV4aM : public TDriverHandle /// Returns the brake pipe pressure target interpolated from BPT[] for the given handle position. /// /// Handle position. - double LPP_RP(double pos); + double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos (detent comparison). - bool EQ(double pos, double i_pos); + bool EQ(double pos, double i_pos) const; public: /// Computes brake pipe flow for the FV4a/M handle (interpolated BPT, wave modelling, accelerator). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and RP. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns the time chamber pressure (TP). - double GetCP(); + double GetCP() override; /// Returns the regulator pressure (5 + TP*0.08 + RedAdj). - double GetRP(); + double GetRP() override; /// Default constructor. - inline TFV4aM() : TDriverHandle() {} + using TDriverHandle::TDriverHandle; }; /// @@ -1193,32 +1191,31 @@ class TMHZ_EN57 : public TDriverHandle static double const pos_table[11]; //= { -2, 10, -1, 0, 0, 2, 9, 10, 0, 0, 0 }; /// Returns the brake pipe pressure target for the given handle position (piecewise). - double LPP_RP(double pos); + double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos. - bool EQ(double pos, double i_pos); + bool EQ(double pos, double i_pos) const; public: /// Computes brake pipe flow for MHZ_EN57 (covers handle positions -1..10 with EP/pneumatic mix). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns the regulator pressure (RP). - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (5 + RedAdj). - double GetRP() /*override*/; + double GetRP() override; /// Returns EP brake intensity for the given handle position. - double GetEP(double pos); + double GetEP(double pos) override; /// Configures handle parameters (auto/manual overcharge, over-pressure, overcharge dynamics). - void SetParams(bool AO, bool MO, double OverP, double, double OMP, double OPD); + void SetParams(bool AO, bool MO, double OverP, double, double OMP, double OPD) override; /// Default constructor. - inline TMHZ_EN57(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// MHZ_K5P — Knorr 5-position combined brake handle. @@ -1232,7 +1229,6 @@ class TMHZ_K5P : public TDriverHandle /// Time chamber pressure [bar]. double TP = 0.0; // zbiornik czasowy /// Reductor reservoir pressure [bar]. - double RP = 0.0; // zbiornik redukcyjny /// Reductor adjustment offset. double RedAdj = 0.0; // dostosowanie reduktora cisnienia (krecenie kapturkiem) /// True while filling-stroke / release wave is active. @@ -1249,29 +1245,28 @@ class TMHZ_K5P : public TDriverHandle static double const pos_table[11]; //= { -2, 10, -1, 0, 0, 2, 9, 10, 0, 0, 0 }; /// Returns true if pos is within ±0.5 of i_pos. - bool EQ(double pos, double i_pos); + bool EQ(double pos, double i_pos) const; public: /// Computes brake pipe flow for the K5P 5-position handle (release / cut-off / brake / emergency). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (5 + TP + RedAdj). - double GetRP() /*override*/; + double GetRP() override; /// Configures handle parameters (auto/manual overcharge, over-pressure, filling-stroke factor, overcharge dynamics). - void SetParams(bool AO, bool MO, double, double, double OMP, double OPD); /*ovveride*/ + void SetParams(bool AO, bool MO, double, double, double OMP, double OPD) override; /// Default constructor. - inline TMHZ_K5P(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// MHZ_6P — 6-position combined brake handle (similar logic to K5P with one more detent). @@ -1285,7 +1280,6 @@ class TMHZ_6P : public TDriverHandle /// Time chamber pressure [bar]. double TP = 0.0; // zbiornik czasowy /// Reductor reservoir pressure [bar]. - double RP = 0.0; // zbiornik redukcyjny /// Reductor adjustment offset. double RedAdj = 0.0; // dostosowanie reduktora cisnienia (krecenie kapturkiem) /// True while filling-stroke / release wave is active. @@ -1302,29 +1296,28 @@ class TMHZ_6P : public TDriverHandle static double const pos_table[11]; //= { -2, 10, -1, 0, 0, 2, 9, 10, 0, 0, 0 }; /// Returns true if pos is within ±0.5 of i_pos. - bool EQ(double pos, double i_pos); + bool EQ(double pos, double i_pos) const; public: /// Computes brake pipe flow for the 6P handle. - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (5 + TP + RedAdj). - double GetRP() /*override*/; + double GetRP() override; /// Configures handle parameters (auto/manual overcharge, over-pressure, filling-stroke factor, overcharge dynamics). - void SetParams(bool AO, bool MO, double, double, double OMP, double OPD); /*ovveride*/ + void SetParams(bool AO, bool MO, double, double, double OMP, double OPD) override; /// Default constructor. - inline TMHZ_6P(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /* FBS2= class(TTDriverHandle) private @@ -1372,17 +1365,17 @@ class TM394 : public TDriverHandle public: /// Computes brake pipe flow for the M394 handle (uses BPT_394). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chamber. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns max(5, CP) + RedAdj. - double GetRP() /*override*/; + double GetRP() override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Default constructor — sets the maximum handle position to 5. inline TM394(void) : TDriverHandle() @@ -1411,17 +1404,17 @@ class TH14K1 : public TDriverHandle public: /// Computes brake pipe flow for the H14K1 handle. - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (5 + RedAdj). - double GetRP() /*override*/; + double GetRP() override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Default constructor — sets the maximum handle position to 4. inline TH14K1(void) : TDriverHandle() @@ -1450,21 +1443,20 @@ class TSt113 : public TH14K1 public: /// Computes brake pipe flow for the St113 handle (with EP). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (5 + RedAdj). - double GetRP() /*override*/; + double GetRP() override; /// Returns the current EP intensity. - double GetEP() /*override*/; + double GetEP() override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Enables the time chambers (no pressure init). - void Init(double Press) /*override*/; + void Init(double Press) override; /// Default constructor. - inline TSt113(void) : TH14K1() {} -}; + using TH14K1::TH14K1;}; /// /// Test handle — minimal implementation used during development for verifying @@ -1479,13 +1471,12 @@ class Ttest : public TDriverHandle public: /// Computes brake pipe flow using the FV4a-style BPT table for testing. - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Default constructor. - inline Ttest(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// FD1 auxiliary brake handle — directly drives the cylinder pressure between @@ -1505,18 +1496,17 @@ class TFD1 : public TDriverHandle double Speed = 0.0; // szybkosc dzialania /// Computes the auxiliary brake outflow for this step. - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises MaxBP and the action speed. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Returns the currently commanded cylinder pressure (BP). - double GetCP() /*override*/; + double GetCP() override; /// Sets the action speed multiplier. void SetSpeed(double nSpeed); // procedure Init(press: real; MaxBP: real); overload; /// Default constructor. - inline TFD1(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// H1405 — Knorr auxiliary brake handle (continuous, independent brake). @@ -1532,16 +1522,15 @@ class TH1405 : public TDriverHandle public: /// Computes the auxiliary brake outflow for this step (proportional to handle deflection). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises MaxBP and enables the time chamber. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Returns the currently commanded cylinder pressure (BP). - double GetCP() /*override*/; + double GetCP() override; // procedure Init(press: real; MaxBP: real); overload; /// Default constructor. - inline TH1405(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// FVel6 — combined EP + pneumatic brake handle (Czech, 6+1 positions). @@ -1559,23 +1548,22 @@ class TFVel6 : public TDriverHandle public: /// Computes brake pipe flow for FVel6 (continuous EP brake plus pneumatic emergency). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (constant 5 bar). - double GetRP() /*override*/; + double GetRP() override; /// Returns the current EP intensity. - double GetEP() /*override*/; + double GetEP() override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns Sounds[i] (or 0 if i > 2). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Enables the time chambers. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Default constructor. - inline TFVel6(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// FVE408 — newer combined EP + pneumatic brake handle (10 positions). @@ -1594,23 +1582,22 @@ class TFVE408 : public TDriverHandle public: /// Computes brake pipe flow for the FVE408 handle. - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the current EP intensity. - double GetEP() /*override*/; + double GetEP() override; /// Returns the regulator target (constant 5 bar). - double GetRP() /*override*/; + double GetRP() override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns Sounds[i] (or 0 if i > 2). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Enables the time chamber, disables the EP-time chamber. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Default constructor. - inline TFVE408(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// Pneumatic flow rate from one pressure to another through an orifice of area S. diff --git a/application/applicationmode.h b/application/applicationmode.h index feea3bdb..4f32fc5f 100644 --- a/application/applicationmode.h +++ b/application/applicationmode.h @@ -25,19 +25,19 @@ public: virtual bool update() = 0; // draws mode-specific user interface inline - void render_ui() { + void render_ui() const { if( m_userinterface != nullptr ) { m_userinterface->render(); } } inline - void begin_ui_frame() { + void begin_ui_frame() const { if( m_userinterface != nullptr ) { m_userinterface->begin_ui_frame(); } } inline - void set_progress( float const Progress = 0.f, float const Subtaskprogress = 0.f ) { + void set_progress( float const Progress = 0.f, float const Subtaskprogress = 0.f ) const { if( m_userinterface != nullptr ) { m_userinterface->set_progress( Progress, Subtaskprogress ); } } inline - void set_tooltip( std::string const &Tooltip ) { + void set_tooltip( std::string const &Tooltip ) const { if( m_userinterface != nullptr ) { m_userinterface->set_tooltip( Tooltip ); } } // maintenance method, called when the mode is activated diff --git a/application/driverhints.cpp b/application/driverhints.cpp index afa654cf..bcfd7dbd 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -38,7 +38,7 @@ void TController::remove_hint( driver_hint const Value ) { m_hints.remove_if( - [=]( auto const &Hint ) { + [Value]( auto const &Hint ) { return std::get(Hint) == Value; } ); } @@ -87,7 +87,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::batteryoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->BatteryStart != start_t::manual || mvOccupied->Power24vIsAvailable == true; } ); break; } @@ -98,7 +98,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::batteryon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->BatteryStart != start_t::manual || mvOccupied->Power24vIsAvailable == false; } ); break; } @@ -111,7 +111,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::cabdeactivation ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->AutomaticCabActivation || mvOccupied->IsCabMaster(); } ); break; } @@ -122,7 +122,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::cabactivation ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->AutomaticCabActivation || (mvOccupied->CabMaster == false && mvOccupied->CabActive == 0); } ); break; } @@ -134,7 +134,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::radiooff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->Radio == true; } ); break; } @@ -144,7 +144,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { return iRadioChannel == static_cast(Parameter); }, Actionparameter ); break; @@ -156,7 +156,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::radioon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->Radio == false; } ); break; } @@ -168,7 +168,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::oilpumpoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->OilPump }; return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true || mvOccupied->Mains; } ); break; @@ -180,7 +180,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::oilpumpon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->OilPump }; return device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; @@ -193,7 +193,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::fuelpumpoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->FuelPump }; return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true; } ); break; @@ -205,7 +205,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::fuelpumpon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->FuelPump }; return device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; @@ -218,7 +218,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::pantographairsourcesetauxiliary ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->bPantKurek3 == true; } ); break; } @@ -229,7 +229,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::pantographcompressoron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->bPantKurek3 == false; } ); break; } @@ -240,7 +240,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::pantographcompressoroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->PantCompFlag == true; } ); break; } @@ -251,7 +251,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::pantographcompressoron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->PantCompFlag == false; } ); break; } @@ -262,7 +262,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::pantographsvalveoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->PantsValve.is_active == true; } ); break; } @@ -273,7 +273,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::frontpantographvalveoff ); hint( Action, - [ this ]( float const Parameter ) -> bool { + [ this ]( float const Parameter ) { return mvPantographUnit->Pantographs[end::front].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, Actionparameter ); break; @@ -285,7 +285,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::frontpantographvalveon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->Pantographs[end::front].valve.is_active == false; } ); break; } @@ -296,7 +296,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::rearpantographvalveoff ); hint( Action, - [ this ]( float const Parameter ) -> bool { + [ this ]( float const Parameter ) { return mvPantographUnit->Pantographs[end::rear].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, Actionparameter ); break; @@ -308,7 +308,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::rearpantographvalveon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->Pantographs[end::rear].valve.is_active == false; } ); break; } @@ -320,7 +320,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::converteroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyConverterEnabled == true; } ); break; } @@ -331,7 +331,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::converteron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyConverterExplicitlyEnabled == false; } ); break; } @@ -342,7 +342,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->ConverterOverloadRelayStart != start_t::manual || mvOccupied->ConvOvldFlag == false; } ); break; } @@ -352,7 +352,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->GroundRelayStart != start_t::manual || mvOccupied->GroundRelay == true; } ); break; } @@ -362,7 +362,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->FuseFlag == false; } ); break; } @@ -374,7 +374,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::linebreakeropen ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyLineBreakerOpen == false; } ); break; } @@ -385,7 +385,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::linebreakerclose ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { // TBD, TODO: replace with consist-wide flag set true if any line breaker is closed? return mvControlling->Mains == false; } ); break; @@ -398,7 +398,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::compressoroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyCompressorEnabled == true; } ); break; } @@ -409,7 +409,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::compressoron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyCompressorExplicitlyEnabled == false; } ); break; } @@ -421,7 +421,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::frontmotorblowersoff ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { auto const &device { mvOccupied->MotorBlowers[ end::front ] }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false); } ); break; @@ -434,7 +434,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::rearmotorblowersoff ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { auto const &device { mvOccupied->MotorBlowers[ end::rear ] }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false); } ); break; @@ -447,7 +447,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::springbrakeoff ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvOccupied->SpringBrake.Activate == true; } ); break; } @@ -458,7 +458,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::springbrakeon ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvOccupied->SpringBrake.Activate == false; } ); break; } @@ -470,7 +470,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::manualbrakoff ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvOccupied->LocalBrake != TLocalBrake::ManualBrake || mvOccupied->MBrake == false || mvOccupied->ManualBrakePos == ManualBrakePosNo; } ); break; } @@ -481,7 +481,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::manualbrakon ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvOccupied->LocalBrake != TLocalBrake::ManualBrake || mvOccupied->MBrake == false || mvOccupied->ManualBrakePos == 0; } ); break; } @@ -490,33 +490,31 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) if( AIControllFlag ) { while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0 && mvControlling->IncMainCtrl(1) ) { - ; + // all work is done in the loop header } } remove_master_controller_hints(); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0; } ); break; } case driver_hint::mastercontrollersetseriesmode: { - if( AIControllFlag ) { - if( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) { - // limit yourself to series mode - if( mvControlling->ScndCtrlPos ) { - mvControlling->DecScndCtrl( 2 ); - } - while( mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 - && mvControlling->DecMainCtrl(1) ) { - ; // all work is performed in the header - } + if (AIControllFlag && mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1) { + // limit yourself to series mode + if( mvControlling->ScndCtrlPos ) { + mvControlling->DecScndCtrl( 2 ); + } + while( mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 + && mvControlling->DecMainCtrl(1) ) { + // all work is performed in the header } } remove_master_controller_hints(); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvControlling->RList[mvControlling->MainCtrlPos].Bn < 2; } ); break; } @@ -527,7 +525,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_master_controller_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->IsMainCtrlNoPowerPos() && mvControlling->IsScndCtrlNoPowerPos(); } ); break; } @@ -535,15 +533,15 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) if( AIControllFlag ) { while( false == mvControlling->EIMDirectionChangeAllow() && mvControlling->DecMainCtrl(1) ) { - ; + // all work is done in the loop header } } remove_master_controller_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->EIMDirectionChangeAllow(); }, - mvControlling->MainCtrlMaxDirChangePos ); + static_cast(mvControlling->MainCtrlMaxDirChangePos) ); break; } case driver_hint::tractiveforcedecrease: { @@ -553,13 +551,13 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_master_controller_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { return std::abs(mvControlling->Ft) <= Parameter; }, - std::min( + static_cast(std::min( 0.0, std::max( std::abs( mvControlling->Ft ) * 0.95, - std::abs( mvControlling->Ft ) - 5.0 ) ) ); + std::abs( mvControlling->Ft ) - 5.0 ) )) ); break; } case driver_hint::tractiveforceincrease: { @@ -575,21 +573,19 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return AccDesired <= EU07_AI_NOACCELERATION || (false == Ready && false == mvOccupied->ShuntMode) || AccDesired - AbsAccS <= 0.05 || (mvOccupied->EIMCtrlType > 0 ? mvControlling->eimic_real >= 1.0 : mvControlling->IsScndCtrlMaxPowerPos() && mvControlling->IsMainCtrlMaxPowerPos()); } ); break; } case driver_hint::bufferscompress: { - if( AIControllFlag ) { - if( std::abs( mvControlling->Ft ) < 50000.0 ) { - IncSpeed(); - } + if (AIControllFlag && std::abs( mvControlling->Ft ) < 50000.0) { + IncSpeed(); } remove_master_controller_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return std::abs(mvControlling->Ft) > 30.0 || (OrderCurrentGet() & Disconnect) == 0; } ); break; } @@ -601,7 +597,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_master_controller_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->IsScndCtrlNoPowerPos(); } ); break; } @@ -613,7 +609,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterpumpoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterPump }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false) || device.is_active == true; } ); break; @@ -625,7 +621,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterpumpon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterPump }; return device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; @@ -637,7 +633,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterpumpbreakeroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterPump }; return device.breaker == true; } ); break; @@ -649,7 +645,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterpumpbreakeron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterPump }; return device.breaker == false; } ); break; @@ -661,7 +657,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterheateroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterHeater }; return device.is_enabled == true; } ); break; @@ -673,7 +669,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterheateron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterHeater }; return device.is_enabled == false; } ); break; @@ -685,7 +681,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterheaterbreakeroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterHeater }; return device.breaker == true; } ); break; @@ -697,7 +693,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterheaterbreakeron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterHeater }; return device.breaker == false; } ); break; @@ -709,7 +705,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::watercircuitslinkoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->dizel_heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == true; } ); break; } @@ -720,7 +716,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::watercircuitslinkon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->dizel_heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == false; } ); break; } @@ -728,7 +724,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // NOTE: this action doesn't have AI component hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return false == IsHeatingTemperatureTooLow; } ); break; } @@ -736,7 +732,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // NOTE: this action doesn't have AI component hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0; } ); break; } @@ -744,7 +740,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // NOTE: this action doesn't have AI component hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->PantPress >= (is_emu() ? (mvPantographUnit->PantPressLockActive ? 4.6 : 2.6) : 4.2); } ); break; } @@ -752,7 +748,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // NOTE: this action doesn't have AI component hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return ExchangeTime <= 0; } ); break; } @@ -760,7 +756,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // NOTE: this action doesn't have AI component hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAtPassengerStop == false; } ); break; } @@ -773,19 +769,16 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // driver_hint_brakingforcesetzero // driver_hint_brakingforcelap case driver_hint::trainbrakesetpipeunlock: { - if( AIControllFlag ) { - if( mvOccupied->HandleUnlock != -3 ) { - while( BrakeCtrlPosition >= mvOccupied->HandleUnlock - && BrakeLevelAdd(-1) ) { - // all work is done in the header - ; - } + if (AIControllFlag && mvOccupied->HandleUnlock != -3) { + while( BrakeCtrlPosition >= mvOccupied->HandleUnlock + && BrakeLevelAdd(-1) ) { + // all work is done in the header } } remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->HandleUnlock == -3 || BrakeCtrlPosition == mvOccupied->HandleUnlock; } ); break; } @@ -797,7 +790,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2) || (mvOccupied->Handle->Time && mvOccupied->Handle->GetCP() > mvOccupied->HighPipePress - 0.05); } ); // return ( BrakeCtrlPosition == gbh_RP ); } ); break; @@ -815,7 +808,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsConsistBraked /*|| ( ( OrderCurrentGet() & Disconnect ) == 0 ) */; } ); break; } @@ -830,9 +823,9 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { return std::abs(mvControlling->Fb) <= Parameter; }, - std::min( 0.0, 0.95 * std::abs( mvControlling->Fb ) ) ); // keep hint until 5% decrease + static_cast(std::min( 0.0, 0.95 * std::abs( mvControlling->Fb ) )) ); // keep hint until 5% decrease break; } case driver_hint::brakingforceincrease: { @@ -846,23 +839,25 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { return std::abs(mvControlling->Fb) > Parameter || is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_EB), 0.2); }, - std::max( + static_cast(std::max( 0.0, std::max( std::abs( mvControlling->Fb ) * 1.05, - std::abs( mvControlling->Fb ) + 5.0 ) ) ); + std::abs( mvControlling->Fb ) + 5.0 ) )) ); break; } case driver_hint::brakingforcesetzero: { // releases both train and independent brake if( AIControllFlag ) { - while( true == DecBrake() ) { ; } + while( true == DecBrake() ) { + // all work is done in the loop condition + } } remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return Ready && fReady < 0.4 && is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2); } ); break; } @@ -877,18 +872,16 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // independent brake case driver_hint::independentbrakeapply: { - if( AIControllFlag ) { - if( mvOccupied->LocalBrakePosA < 1.0 ) { - mvOccupied->IncLocalBrakeLevel( LocalBrakePosNo ); - if (mvOccupied->EIMCtrlEmergency) { - mvOccupied->DecLocalBrakeLevel(1); + if (AIControllFlag && mvOccupied->LocalBrakePosA < 1.0) { + mvOccupied->IncLocalBrakeLevel( LocalBrakePosNo ); + if (mvOccupied->EIMCtrlEmergency) { + mvOccupied->DecLocalBrakeLevel(1); } - } } remove_hint( driver_hint::independentbrakerelease ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { return mvOccupied->LocalBrakePosA >= Parameter; }, ( LocalBrakePosNo - ( mvOccupied->EIMCtrlEmergency ? 1 : 0 ) ) / LocalBrakePosNo ); break; @@ -900,7 +893,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::independentbrakeapply ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->LocalBrakePosA < 0.05; } ); break; } @@ -912,7 +905,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_reverser_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->DirActive * mvOccupied->CabActive > 0; } ); break; } @@ -923,7 +916,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_reverser_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->DirActive * mvOccupied->CabActive < 0; } ); break; } @@ -936,7 +929,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_reverser_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return iDirection == iDirectionOrder; } ); break; } @@ -947,7 +940,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_reverser_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->DirActive == 0; } ); break; } @@ -959,7 +952,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::sandingoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->Sand == 0 || mvControlling->SandDose == true || mvControlling->SlippingWheels == false; } ); break; } @@ -970,7 +963,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::sandingon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->Sand == 0 || mvControlling->SandDose == false; } ); break; } @@ -980,7 +973,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->ASBType != 1 || (mvControlling->Hamulec->GetBrakeStatus() & b_asb) != 0 || mvControlling->SlippingWheels == false; } ); break; } @@ -992,7 +985,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::hornoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { // NOTE: we provide slightly larger horn activation window for human driver return fWarningDuration + 5.0 < 0.05 || mvOccupied->WarningSignal != 0; } ); break; @@ -1019,7 +1012,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // TODO: remove other door lock hints hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->Doors.has_lock == false || mvOccupied->Doors.lock_enabled == true; } ); break; } @@ -1031,7 +1024,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::departuresignaloff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->Doors.has_warning == false || mvOccupied->Doors.has_autowarning == true || mvOccupied->DepartureSignal == true || mvOccupied->Vel > 5.0; } ); break; } @@ -1042,7 +1035,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::departuresignalon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->Doors.has_warning == false || mvOccupied->Doors.has_autowarning == true || mvOccupied->DepartureSignal == false; } ); break; } @@ -1055,7 +1048,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorrightclose ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorOpen[side::right] == true; } ); break; } @@ -1067,7 +1060,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorrightopen ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorOpen[side::right] == false; } ); break; } @@ -1079,7 +1072,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorleftclose ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorOpen[side::left] == true; } ); break; } @@ -1091,7 +1084,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorleftopen ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorOpen[side::left] == false; } ); break; } @@ -1102,7 +1095,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorrightpermitoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorPermitActive[side::right] == true; } ); break; } @@ -1113,7 +1106,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorrightpermiton ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorPermitActive[side::right] == false; } ); break; } @@ -1124,7 +1117,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorleftpermitoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorPermitActive[side::left] == true; } ); break; } @@ -1135,7 +1128,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorleftpermiton ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorPermitActive[side::left] == false; } ); break; } @@ -1148,7 +1141,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::consistlightsoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->CompartmentLights }; return Global.fLuminance * ConsistShade > 0.40 || device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false) || device.is_active == true; } ); break; @@ -1161,7 +1154,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::consistlightson ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->CompartmentLights }; return Global.fLuminance * ConsistShade < 0.35 || device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; @@ -1174,7 +1167,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::consistheatingoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->HeatingAllow == true; } ); break; } @@ -1185,52 +1178,48 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::consistheatingon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->HeatingAllow == false; } ); break; } case driver_hint::securitysystemreset: { - if( AIControllFlag ) { - if (mvOccupied->SecuritySystem.is_blinking()) - mvOccupied->SecuritySystemReset(); - } + if (AIControllFlag && mvOccupied->SecuritySystem.is_blinking()) + mvOccupied->SecuritySystemReset(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return !mvOccupied->SecuritySystem.is_vigilance_blinking(); } ); break; } case driver_hint::shpsystemreset: { - if( AIControllFlag ) { - if (mvOccupied->SecuritySystem.is_cabsignal_blinking()) - mvOccupied->SecuritySystem.cabsignal_reset(); - } + if (AIControllFlag && mvOccupied->SecuritySystem.is_cabsignal_blinking()) + mvOccupied->SecuritySystem.cabsignal_reset(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return !mvOccupied->SecuritySystem.is_cabsignal_blinking(); } ); break; } case driver_hint::couplingadapterattach: { // TODO: run also for potential settings-based virtual assistant if( AIControllFlag ) { - pVehicles[ end::front ]->attach_coupler_adapter( Actionparameter ); + pVehicles[ end::front ]->attach_coupler_adapter( static_cast(Actionparameter) ); } hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { auto const &device { pVehicles[ end::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; return device.type() == TCouplerType::Automatic; } ); break; } case driver_hint::couplingadapterremove: { if( AIControllFlag || Global.AITrainman ) { - pVehicles[ end::front ]->remove_coupler_adapter( Actionparameter ); + pVehicles[ end::front ]->remove_coupler_adapter( static_cast(Actionparameter) ); } hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { auto const &device { pVehicles[ end::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; return false == device.has_adapter(); } ); break; @@ -1245,7 +1234,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::lightsoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return pVehicles[end::front]->has_signal_pc1_on(); } ); break; } @@ -1258,7 +1247,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::lightsoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return pVehicles[end::front]->has_signal_pc2_on(); } ); break; } @@ -1275,7 +1264,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::lightsoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const activeend { mvOccupied->CabActive >= 0 ? end::front : end::rear }; auto const consistfront { mvOccupied->DirActive >= 0 ? end::front : end::rear }; return pVehicles[consistfront]->has_signal_on(activeend, light::headlight_right) && pVehicles[1 - consistfront]->has_signal_on(1 - activeend, light::headlight_left); } ); @@ -1290,7 +1279,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::lightsoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return pVehicles[end::rear]->has_signal_pc5_on(); } ); break; } @@ -1304,7 +1293,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::headcodetb1 ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const activeend { mvOccupied->CabActive >= 0 ? end::front : end::rear }; auto const consistfront { mvOccupied->DirActive >= 0 ? end::front : end::rear }; return pVehicles[consistfront]->has_signal_on(activeend, 0) && pVehicles[1 - consistfront]->has_signal_on(1 - activeend, 0); } ); @@ -1318,7 +1307,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::releaseroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return true == mvOccupied->Hamulec->Releaser(); } ); break; } @@ -1329,7 +1318,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::releaseron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return false == mvOccupied->Hamulec->Releaser(); } ); break; } diff --git a/application/driverhints.h b/application/driverhints.h index 7b6130c2..140fe5f9 100644 --- a/application/driverhints.h +++ b/application/driverhints.h @@ -12,7 +12,7 @@ enum class driver_hint { #ifdef DRIVER_HINT_CONTENT #define DRIVER_HINT_DEF(a, b) b, -const char *driver_hints_texts[] = +const char *const driver_hints_texts[] = { #include "application/driverhints_def.h" }; diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 729b854c..e318d356 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -52,7 +52,7 @@ drivingaid_panel::update() { || controlled->Mechanik == nullptr ) { return; } auto const *mover = controlled->MoverParameters; - auto const *driver = controlled->Mechanik; + auto const *vehicledriver = controlled->Mechanik; auto const *owner = controlled->ctOwner != nullptr ? controlled->ctOwner : controlled->Mechanik; { // throttle, velocity, speed limits and grade @@ -61,8 +61,7 @@ drivingaid_panel::update() { // grade std::string gradetext; auto const reverser { ( mover->DirActive > 0 ? 1 : -1 ) }; - auto const grade { controlled->VectorFront().y * 100 * ( controlled->DirectionGet() == reverser ? 1 : -1 ) * reverser }; - if( std::abs( grade ) >= 0.25 ) { + if( auto const grade { controlled->VectorFront().y * 100 * ( controlled->DirectionGet() == reverser ? 1 : -1 ) * reverser }; std::abs( grade ) >= 0.25 ) { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C(" Grade: %.1f%%%%"), @@ -87,8 +86,7 @@ drivingaid_panel::update() { // then take into account speed change ahead, compare it with speed after potentially clearing last limit // lower of these two takes priority; otherwise limit lasts at least until potential last limit is cleared auto const noactivespeedlimit { owner->VelLimitLastDist.second < 0 }; - auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast( owner->VelNext ) ) }; - if( speedatproximitydistance == nextspeedlimit ) { + if( auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast( owner->VelNext ) ) }; speedatproximitydistance == nextspeedlimit ) { if( noactivespeedlimit ) { nextspeedlimit = speedatproximitydistance; nextspeedlimitdistance = owner->ActualProximityDist; @@ -142,8 +140,8 @@ drivingaid_panel::update() { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("Throttle: %3d+%d %c%s"), - mover->EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * mover->eimic_real)) : driver->Controlling()->MainCtrlPos, - mover->EIMCtrlType > 0 ? driver->Controlling()->MainCtrlPos : driver->Controlling()->ScndCtrlPos, + mover->EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * mover->eimic_real)) : vehicledriver->Controlling()->MainCtrlPos, + mover->EIMCtrlType > 0 ? vehicledriver->Controlling()->MainCtrlPos : vehicledriver->Controlling()->ScndCtrlPos, mover->SpeedCtrlUnit.IsActive ? 'T' : mover->DirActive > 0 ? 'D' : mover->DirActive < 0 ? 'R' : @@ -253,12 +251,7 @@ scenario_panel::render() { if( size_min.x > 0 ) { ImGui::SetNextWindowSizeConstraints( ImVec2S( size_min.x, size_min.y ), ImVec2S( size_max.x, size_max.y ) ); } - auto const panelname { ( - title.empty() ? - m_name : - title ) - + "###" + m_name }; - if( true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { + if( auto const panelname { ( title.empty() ? m_name : title ) + "###" + m_name }; true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { // potential assignment section auto const *owner { ( m_nearest->Mechanik != nullptr && m_nearest->Mechanik->primary() ? @@ -274,21 +267,19 @@ scenario_panel::render() { } // current task for( auto const &line : text_lines ) { - ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), line.data.c_str() ); + ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), "%s", line.data.c_str() ); } // hints - if( owner != nullptr ) { - if( true == ImGui::CollapsingHeader( STR_C("Hints"), ImGuiTreeNodeFlags_DefaultOpen ) ) { - for( auto const &hint : owner->m_hints ) { - auto const isdone { std::get( hint )( std::get( hint ) ) }; - auto const hintcolor{ ( - isdone ? - colors::uitextgreen : - Global.UITextColor ) }; - ImGui::PushStyleColor( ImGuiCol_Text, { hintcolor.r, hintcolor.g, hintcolor.b, hintcolor.a } ); - ImGui::TextWrapped( Translations.lookup_c(driver_hints_texts[(size_t)std::get( hint )], true), std::get( hint ) ); - ImGui::PopStyleColor(); - } + if (owner != nullptr && true == ImGui::CollapsingHeader( STR_C("Hints"), ImGuiTreeNodeFlags_DefaultOpen )) { + for( auto const &hint : owner->m_hints ) { + auto const isdone { std::get( hint )( std::get( hint ) ) }; + auto const hintcolor{ ( + isdone ? + colors::uitextgreen : + Global.UITextColor ) }; + ImGui::PushStyleColor( ImGuiCol_Text, { hintcolor.r, hintcolor.g, hintcolor.b, hintcolor.a } ); + ImGui::TextWrapped( Translations.lookup_c(driver_hints_texts[(size_t)std::get( hint )], true), std::get( hint ) ); + ImGui::PopStyleColor(); } } } @@ -364,8 +355,7 @@ timetable_panel::update() { //odejmij lokomotywy czynne, a przynajmniej aktualną consistmass -= owner->pVehicle->MoverParameters->TotalMass; // subtract potential other half of a two-part vehicle - auto const *previous { owner->pVehicle->Prev( coupling::permanent ) }; - if( previous != nullptr ) { consistmass -= previous->MoverParameters->TotalMass; } + if( auto const *previous { owner->pVehicle->Prev( coupling::permanent ) }; previous != nullptr ) { consistmass -= previous->MoverParameters->TotalMass; } auto const *next { owner->pVehicle->Next( coupling::permanent ) }; if( next != nullptr ) { consistmass -= next->MoverParameters->TotalMass; } } @@ -428,13 +418,13 @@ timetable_panel::update() { && i < table.StationIndex && ( tableline->Ah < 0 // pass-through, always valid || tableline->is_maintenance // maintenance stop, always valid - || time.wHour * 60 + time.wMinute + time.wSecond * 0.0167 >= tableline->Dh * 60 + tableline->Dm ) ) }; + || time.wHour * 60 + time.wMinute + time.wSecond * 0.0167 >= static_cast(tableline->Dh * 60) + tableline->Dm ) ) }; auto const loadchangeinprogress { ( static_cast(std::ceil(-1.0 * owner->fStopTime)) > 0 ) }; auto const isatpassengerstop { true == owner->IsAtPassengerStop && vehicle->MoverParameters->Vel < 1.0 }; auto const traveltime { ( i < 2 ? " " : - tableline->Ah >= 0 ? to_minutes_str( CompareTime( table.TimeTable[ i - 1 ].Dh, table.TimeTable[ i - 1 ].Dm, tableline->Ah, tableline->Am ), false, 3 ) : - to_minutes_str( std::max( 0.0, CompareTime( table.TimeTable[ i - 1 ].Dh, table.TimeTable[ i - 1 ].Dm, tableline->Dh, tableline->Dm ) - 0.5 ), false, 3 ) ) }; + tableline->Ah >= 0 ? to_minutes_str( static_cast(CompareTime( table.TimeTable[ i - 1 ].Dh, table.TimeTable[ i - 1 ].Dm, tableline->Ah, tableline->Am )), false, 3 ) : + to_minutes_str( static_cast(std::max( 0.0, CompareTime( table.TimeTable[ i - 1 ].Dh, table.TimeTable[ i - 1 ].Dm, tableline->Dh, tableline->Dm ) - 0.5 )), false, 3 ) ) }; auto const linecolor { ( i != table.StationStart ? Global.UITextColor : loadchangeinprogress ? colors::uitextred : @@ -486,19 +476,14 @@ timetable_panel::render() { if( size_min.x > 0 ) { ImGui::SetNextWindowSizeConstraints( ImVec2S( size_min.x * horizontalScale, size_min.y ), ImVec2S( size_max.x * horizontalScale, size_max.y ) ); } - auto const panelname { ( - title.empty() ? - m_name : - title ) - + "###" + m_name }; - if( true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { + if( auto const panelname { ( title.empty() ? m_name : title ) + "###" + m_name }; true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { for( auto const &line : text_lines ) { - ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), line.data.c_str() ); + ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), "%s", line.data.c_str() ); } if( is_expanded ) { ImGui::PushStyleVar( ImGuiStyleVar_ItemSpacing, ImVec2( 1, 0 ) ); for( auto const &line : m_tablelines ) { - ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), line.data.c_str() ); + ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), "%s", line.data.c_str() ); } ImGui::PopStyleVar(); } @@ -576,25 +561,16 @@ debug_panel::render() { if( size_min.x > 0 ) { ImGui::SetNextWindowSizeConstraints( ImVec2S( size_min.x, size_min.y ), ImVec2S( size_max.x, size_max.y ) ); } - auto const panelname { ( - title.empty() ? - m_name : - title ) - + "###" + m_name }; - if( true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { + if( auto const panelname { ( title.empty() ? m_name : title ) + "###" + m_name }; true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { // header section for( auto const &line : text_lines ) { - ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), line.data.c_str() ); + ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), "%s", line.data.c_str() ); } // sections ImGui::Separator(); - if( true == render_section( "Vehicle", m_vehiclelines ) ) { - if( DebugModeFlag && m_input.mover && m_input.mover->DamageFlag != 0 ) { - if( true == ImGui::Button( "Stop and repair consist" ) ) { - command_relay relay; - relay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &m_input.vehicle->name()); - } - } + if (true == render_section( "Vehicle", m_vehiclelines ) && DebugModeFlag && m_input.mover && m_input.mover->DamageFlag != 0 && true == ImGui::Button( "Stop and repair consist" )) { + command_relay commandrelay; + commandrelay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &m_input.vehicle->name()); } render_section( "Vehicle Engine", m_enginelines ); render_section( "Vehicle AI", m_ailines ); @@ -611,13 +587,13 @@ debug_panel::render() { render_section_developer(); // Developer tools #ifdef WITH_UART if(true == render_section( "UART", m_uartlines)) { - int ports_num = UartStatus.available_ports.size(); - char **avlports = new char*[ports_num]; + auto ports_num = static_cast(UartStatus.available_ports.size()); + auto avlports = new char*[ports_num]; for (int i=0; i < ports_num; i++) { avlports[i] = (char *) UartStatus.available_ports[i].c_str(); } ImGui::Combo("Port", &UartStatus.selected_port_index, avlports, ports_num); - ImGui::Combo("Baud", &UartStatus.selected_baud_index, uart_baudrates_list, uart_baudrates_list_num); + ImGui::Combo("Baud", &UartStatus.selected_baud_index, uart_baudrates_list, static_cast(uart_baudrates_list_num)); ImGui::Checkbox("Enabled", &UartStatus.enabled); } #endif @@ -625,8 +601,8 @@ debug_panel::render() { ImGui::Separator(); bool flag = DebugModeFlag; if (ImGui::Checkbox("Debug Mode", &flag)) { - command_relay relay; - relay.post(user_command::debugtoggle, 0.0, 0.0, GLFW_RELEASE, 0); + command_relay commandrelay; + commandrelay.post(user_command::debugtoggle, 0.0, 0.0, GLFW_RELEASE, 0); } } @@ -647,8 +623,8 @@ debug_panel::render_section_scenario() { auto fogrange = std::log( Global.fFogEnd ); if( ImGui::SliderFloat( ( to_string( std::exp( fogrange ), 0, 5 ) + " m###fogend" ).c_str(), &fogrange, std::log( 10.0f ), std::log( 50000.0f ), "Fog distance" ) ) { - command_relay relay; - relay.post( + command_relay commandrelay; + commandrelay.post( user_command::setweather, std::clamp( std::exp( fogrange ), 10.0f, 50000.0f ), Global.Overcast, @@ -661,8 +637,8 @@ debug_panel::render_section_scenario() { (to_string(Airtemperature, 1) + " deg C###Airtemperature").c_str(), &Airtemperature, -35.0f, 40.0f, "Air Temperature")) { - command_relay relay; - relay.post( + command_relay commandrelay; + commandrelay.post( user_command::settemperature, std::clamp(Airtemperature, -35.0f, 40.0f), Global.Overcast, @@ -673,8 +649,8 @@ debug_panel::render_section_scenario() { { if( ImGui::SliderFloat( ( to_string( Global.Overcast, 2, 5 ) + " (" + Global.Weather + ")###overcast" ).c_str(), &Global.Overcast, 0.0f, 2.0f, "Cloud cover" ) ) { - command_relay relay; - relay.post( + command_relay commandrelay; + commandrelay.post( user_command::setweather, Global.fFogEnd, std::clamp( Global.Overcast, 0.0f, 2.0f ), @@ -685,8 +661,8 @@ debug_panel::render_section_scenario() { { if( ImGui::SliderFloat( ( to_string( Global.fMoveLight, 0, 5 ) + " (" + Global.Season + ")###movelight" ).c_str(), &Global.fMoveLight, 0.0f, 364.0f, "Day of year" ) ) { - command_relay relay; - relay.post( + command_relay commandrelay; + commandrelay.post( user_command::setdatetime, std::clamp( Global.fMoveLight, 0.0f, 365.0f ), simulation::Time.data().wHour * 60 + simulation::Time.data().wMinute, @@ -695,10 +671,8 @@ debug_panel::render_section_scenario() { } // dynamic material update checkbox ImGui::Checkbox( "Update Item Materials", &Global.UpdateMaterials ); - if( DebugModeFlag ) { - if( ImGui::Checkbox( "Force Daylight", &Global.FakeLight ) ) { - simulation::Environment.on_daylight_change(); - } + if (DebugModeFlag && ImGui::Checkbox( "Force Daylight", &Global.FakeLight )) { + simulation::Environment.on_daylight_change(); } // advanced options, only visible in debug mode if( DebugModeFlag ) { @@ -713,8 +687,8 @@ debug_panel::render_section_scenario() { + ":" + std::string( std::to_string( int( 100 + simulation::Time.data().wMinute ) ).substr( 1, 2 ) ) ) }; if( ImGui::SliderInt( ( timestring + " (" + Global.Period + ")###simulationtime" ).c_str(), &time, 0, 1439, "Time of day" ) ) { - command_relay relay; - relay.post( + command_relay commandrelay; + commandrelay.post( user_command::setdatetime, Global.fMoveLight, std::clamp( time, 0, 1439 ), @@ -903,7 +877,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { mover.LoadFlag, mover.LocalBrakePosA, mover.LocalBrakePosAEIM, - mover.ManualBrakePos / static_cast(ManualBrakePosNo), + static_cast(mover.ManualBrakePos) / static_cast(ManualBrakePosNo), mover.SpringBrake.Activate ? 1.f : 0.f, // cylinders mover.BrakePress, @@ -981,11 +955,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { if (!std::isnan(last_time)) { double dt = Timer::GetTime() - last_time; - AccN_jerk_graph.update((mover.AccN - last_AccN) / dt); - AccN_acc_graph.update(mover.AccN); + AccN_jerk_graph.update(static_cast((mover.AccN - last_AccN) / dt)); + AccN_acc_graph.update(static_cast(mover.AccN)); } - last_AccN = mover.AccN; + last_AccN = static_cast(mover.AccN); last_time = Timer::GetTime(); } @@ -1002,7 +976,7 @@ void debug_panel::graph_data::update(float val) { void debug_panel::graph_data::render() { ImGui::PushID(this); ImGui::SliderFloat(STR_C("##Range"), &range, 0.5f, 60.0f, "%.1f"); - ImGui::PlotLines("##plot", data.data(), data.size(), pos, nullptr, 0.0f, range, ImVec2(0, 100)); + ImGui::PlotLines("##plot", data.data(), static_cast(data.size()), static_cast(pos), nullptr, 0.0f, range, ImVec2(0, 100)); ImGui::PopID(); } @@ -1047,9 +1021,9 @@ debug_panel::update_vehicle_brake() const { { bdelay_R, "R" }, { bdelay_M, "+Mg" } }; - for( auto const &delay : delays ) { - if( ( mover.BrakeDelayFlag & delay.first ) == delay.first ) { - brakedelay += delay.second; + for( auto const &[delayflag, delayname] : delays ) { + if( ( mover.BrakeDelayFlag & delayflag ) == delayflag ) { + brakedelay += delayname; } } @@ -1057,7 +1031,7 @@ debug_panel::update_vehicle_brake() const { } void -debug_panel::update_section_engine( std::vector &Output ) { +debug_panel::update_section_engine( std::vector &Output ) const { if( m_input.vehicle == nullptr ) { return; } if( m_input.mover == nullptr ) { return; } @@ -1072,9 +1046,9 @@ debug_panel::update_section_engine( std::vector &Output ) { for( int i = 0; i <= 20; ++i ) { std::string parameters = - mover.eimc_labels[ i ] + to_string( mover.eimc[ i ], 2, 9 ) + TMoverParameters::eimc_labels[ i ] + to_string( mover.eimc[ i ], 2, 9 ) + " | " - + mover.eimv_labels[ i ] + to_string( mover.eimv[ i ], 2, 9 ); + + TMoverParameters::eimv_labels[ i ] + to_string( mover.eimv[ i ], 2, 9 ); if( i < 10 ) { parameters += @@ -1084,7 +1058,7 @@ debug_panel::update_section_engine( std::vector &Output ) { parameters += " med:"; } else if( i >= 13 ) { - parameters += " | " + vehicle.MED_labels[ i - 13 ] + to_string( vehicle.MED[ 0 ][ i - 13 ], 2, 9 ); + parameters += " | " + TDynamicObject::MED_labels[ i - 13 ] + to_string( vehicle.MED[ 0 ][ i - 13 ], 2, 9 ); } Output.emplace_back( parameters, Global.UITextColor ); @@ -1112,8 +1086,8 @@ debug_panel::update_section_engine( std::vector &Output ) { { "cdesi: ", mover.dizel_engagestate }, { "cdelt: ", mover.dizel_engagedeltaomega }, { "gears: ", mover.dizel_automaticgearstatus} }; - for( auto const ¶meter : paramvalues ) { - parameterstext += "\n" + parameter.first + to_string( parameter.second, 2, 9 ); + for( auto const &[parametername, parametervalue] : paramvalues ) { + parameterstext += "\n" + parametername + to_string( parametervalue, 2, 9 ); } Output.emplace_back( parameterstext, Global.UITextColor ); @@ -1130,15 +1104,15 @@ debug_panel::update_section_engine( std::vector &Output ) { { "hRtTq: ", mover.hydro_R_Torque } }; - for( auto const ¶meter : hydrovalues ) { - parameterstext += "\n" + parameter.first + to_string( parameter.second, 2, 9 ); + for( auto const &[parametername, parametervalue] : hydrovalues ) { + parameterstext += "\n" + parametername + to_string( parametervalue, 2, 9 ); } Output.emplace_back( parameterstext, Global.UITextColor ); } } void -debug_panel::update_section_ai( std::vector &Output ) { +debug_panel::update_section_ai( std::vector &Output ) const { if( m_input.mover == nullptr ) { return; } if( m_input.mechanik == nullptr ) { return; } @@ -1202,14 +1176,14 @@ debug_panel::update_section_ai( std::vector &Output ) { { mover.RunningTrack.Velmax, "track" } }; std::string restrictionstext; - for( auto const &restriction : restrictions ) { - if( restriction.first < 0.0 ) { continue; } + for( auto const &[restrictionspeed, restrictionsource] : restrictions ) { + if( restrictionspeed < 0.0 ) { continue; } if( false == restrictionstext.empty() ) { restrictionstext += ", "; } restrictionstext += - to_string( restriction.first, 0 ) - + " (" + restriction.second + ")"; + to_string( restrictionspeed, 0 ) + + " (" + restrictionsource + ")"; } if( false == restrictionstext.empty() ) { @@ -1262,7 +1236,7 @@ debug_panel::update_section_ai( std::vector &Output ) { } void -debug_panel::update_section_scantable( std::vector &Output ) { +debug_panel::update_section_scantable( std::vector &Output ) const { if( m_input.mechanik == nullptr ) { return; } @@ -1284,8 +1258,8 @@ debug_panel::update_section_scantable( std::vector &Output ) { #ifdef WITH_UART void -debug_panel::update_section_uart( std::vector &Output ) { - uart_status *status = &UartStatus; +debug_panel::update_section_uart( std::vector &Output ) const { + uart_status const *status = &UartStatus; Output.emplace_back( ("Port: " + status->port_name).c_str(), @@ -1312,7 +1286,7 @@ debug_panel::update_section_uart( std::vector &Output ) { #endif void -debug_panel::update_section_scenario( std::vector &Output ) { +debug_panel::update_section_scenario( std::vector &Output ) const { auto textline = "vehicles: " + to_string( Timer::subsystem.sim_dynamics.average(), 2 ) + " msec" @@ -1326,7 +1300,7 @@ debug_panel::update_section_scenario( std::vector &Output ) { + to_string( simulation::Environment.wind_azimuth(), 0 ) // ma być azymut, czyli 0 na północy i rośnie na wschód + " " + std::string( "N NEE SES SWW NW" ) - .substr( 0 + 2 * std::floor( std::fmod( 8 + ( glm::radians( simulation::Environment.wind_azimuth() ) + 0.5 * M_PI_4 ) / M_PI_4, 8 ) ), 2 ) + .substr( static_cast( 2 * std::floor( std::fmod( 8 + ( glm::radians( simulation::Environment.wind_azimuth() ) + 0.5 * M_PI_4 ) / M_PI_4, 8 ) ) ), 2 ) + ", " + to_string( glm::length( simulation::Environment.wind() ), 1 ) + " m/s"; textline += "\nAir temperature: " + to_string( Global.AirTemperature, 1 ) + " deg C"; @@ -1340,36 +1314,36 @@ debug_panel::update_section_eventqueue( std::vector &Output ) { // current event queue auto const time { Timer::GetTime() }; - auto const *event { simulation::Events.begin() }; + auto const *queuedevent { simulation::Events.begin() }; auto const searchfilter { std::string( m_eventsearch.data() ) }; Output.emplace_back( "Delay: Event:", Global.UITextColor ); - while( event != nullptr + while( queuedevent != nullptr && Output.size() < 30 ) { - if( false == event->m_ignored - && false == event->m_passive + if( false == queuedevent->m_ignored + && false == queuedevent->m_passive && ( false == m_eventqueueactivevehicleonly - || event->m_activator == m_input.vehicle ) ) { + || queuedevent->m_activator == m_input.vehicle ) ) { - auto const label { event->m_name + ( event->m_activator ? " (by: " + event->m_activator->asName + ")" : "" ) }; + auto const label { queuedevent->m_name + ( queuedevent->m_activator ? " (by: " + queuedevent->m_activator->asName + ")" : "" ) }; if( false == searchfilter.empty() && false == contains(label, searchfilter) ) { - event = event->m_next; + queuedevent = queuedevent->m_next; continue; } - auto const delay { " " + to_string( std::max( 0.0, event->m_launchtime - time ), 1 ) }; + auto const delay { " " + to_string( std::max( 0.0, queuedevent->m_launchtime - time ), 1 ) }; textline = delay.substr( delay.length() - 6 ) + " " - + label + ( event->m_sibling ? " (joint event)" : "" ); + + label + ( queuedevent->m_sibling ? " (joint event)" : "" ); Output.emplace_back( textline, Global.UITextColor ); } - event = event->m_next; + queuedevent = queuedevent->m_next; } if( Output.size() == 1 ) { // event queue can be empty either because no event got through active filters, or because it is genuinely empty @@ -1378,7 +1352,7 @@ debug_panel::update_section_eventqueue( std::vector &Output ) { } void -debug_panel::update_section_powergrid( std::vector &Output ) { +debug_panel::update_section_powergrid( std::vector &Output ) const { auto const lowpowercolor { glm::vec4( 164.0f / 255.0f, 132.0f / 255.0f, 84.0f / 255.0f, 1.f ) }; auto const nopowercolor { glm::vec4( 164.0f / 255.0f, 84.0f / 255.0f, 84.0f / 255.0f, 1.f ) }; @@ -1420,7 +1394,7 @@ debug_panel::update_section_powergrid( std::vector &Output ) { } void -debug_panel::update_section_camera( std::vector &Output ) { +debug_panel::update_section_camera( std::vector &Output ) const { if( m_input.camera == nullptr ) { return; } @@ -1440,13 +1414,13 @@ debug_panel::update_section_camera( std::vector &Output ) { + to_string( 180.0 - glm::degrees( camera.Angle.y ), 0 ) // ma być azymut, czyli 0 na północy i rośnie na wschód + " " + std::string( "S SEE NEN NWW SW" ) - .substr( 0 + 2 * floor( fmod( 8 + ( camera.Angle.y + 0.5 * M_PI_4 ) / M_PI_4, 8 ) ), 2 ); + .substr( static_cast( 2 * floor( fmod( 8 + ( camera.Angle.y + 0.5 * M_PI_4 ) / M_PI_4, 8 ) ) ), 2 ); Output.emplace_back( textline, Global.UITextColor ); } void -debug_panel::update_section_renderer( std::vector &Output ) { +debug_panel::update_section_renderer( std::vector &Output ) const { // gfx renderer data auto textline = @@ -1526,7 +1500,7 @@ debug_panel::render_section( std::string const &Header, std::vector c } bool -debug_panel::render_section( std::vector const &Lines ) { +debug_panel::render_section( std::vector const &Lines ) const { for( auto const &line : Lines ) { ImGui::PushStyleColor( ImGuiCol_Text, { line.color.r, line.color.g, line.color.b, line.color.a } ); @@ -1537,7 +1511,7 @@ debug_panel::render_section( std::vector const &Lines ) { return true; } -bool debug_panel::render_section_developer() +bool debug_panel::render_section_developer() const { if (false == ImGui::CollapsingHeader("Developer tools")) return false; @@ -1553,7 +1527,7 @@ bool debug_panel::render_section_developer() } bool -debug_panel::render_section_settings() { +debug_panel::render_section_settings() const { if( false == ImGui::CollapsingHeader( "Settings" ) ) { return false; } @@ -1563,9 +1537,9 @@ debug_panel::render_section_settings() { // reflection fidelity ImGui::SliderInt( ( std::to_string( Global.reflectiontune.fidelity ) + "###reflectionfidelity" ).c_str(), &Global.reflectiontune.fidelity, 0, 2, "Reflection fidelity" ); ImGui::SliderInt( ( std::to_string( Global.gfx_shadow_rank_cutoff ) + "###shadowrankcutoff" ).c_str(), &Global.gfx_shadow_rank_cutoff, 1, 3, "Shadow ranks" ); - if( ImGui::SliderFloat( ( to_string( std::abs( Global.gfx_shadow_angle_min ), 2 ) + "###shadowanglecutoff" ).c_str(), &Global.gfx_shadow_angle_min, -1.0, -0.2, "Shadow angle cutoff" ) ) { + if( ImGui::SliderFloat( ( to_string( std::abs( Global.gfx_shadow_angle_min ), 2 ) + "###shadowanglecutoff" ).c_str(), &Global.gfx_shadow_angle_min, -1.0, -0.2f, "Shadow angle cutoff" ) ) { Global.gfx_shadow_angle_min = quantize( Global.gfx_shadow_angle_min, 0.05f ); - }; + } if( DebugModeFlag ) { // sky sliders { @@ -1595,8 +1569,8 @@ debug_panel::render_section_settings() { if (simulation::Train) { float val = simulation::Train->get_radiovolume(); if( ImGui::SliderFloat( ( std::to_string( static_cast( val * 100 ) ) + "%###volumeradio" ).c_str(), &val, 0.0f, 1.0f, "Vehicle radio volume" ) ) { - command_relay relay; - relay.post(user_command::radiovolumeset, val, 0.0, GLFW_PRESS, 0); + command_relay commandrelay; + commandrelay.post(user_command::radiovolumeset, val, 0.0, GLFW_PRESS, 0); } } @@ -1635,12 +1609,7 @@ transcripts_panel::render() { if( size_min.x > 0 ) { ImGui::SetNextWindowSizeConstraints( ImVec2S( size_min.x, size_min.y ), ImVec2S( size_max.x, size_max.y ) ); } - auto const panelname { ( - title.empty() ? - m_name : - title ) - + "###" + m_name }; - if( true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { + if( auto const panelname { ( title.empty() ? m_name : title ) + "###" + m_name }; true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { // header section for( auto const &line : text_lines ) { ImGui::TextWrapped( "%s", line.data.c_str() ); diff --git a/application/driveruipanels.h b/application/driveruipanels.h index da4cad87..96b9ac1c 100644 --- a/application/driveruipanels.h +++ b/application/driveruipanels.h @@ -54,7 +54,6 @@ public: private: // members - std::array m_buffer; TDynamicObject const *m_nearest { nullptr }; }; @@ -81,42 +80,41 @@ private: // methods // generate and send section data to provided output void update_section_vehicle( std::vector &Output ); - void update_section_engine( std::vector &Output ); - void update_section_ai( std::vector &Output ); - void update_section_scantable( std::vector &Output ); - void update_section_scenario( std::vector &Output ); + void update_section_engine( std::vector &Output ) const; + void update_section_ai( std::vector &Output ) const; + void update_section_scantable( std::vector &Output ) const; + void update_section_scenario( std::vector &Output ) const; void update_section_eventqueue( std::vector &Output ); - void update_section_powergrid( std::vector &Output ); - void update_section_camera( std::vector &Output ); - void update_section_renderer( std::vector &Output ); + void update_section_powergrid( std::vector &Output ) const; + void update_section_camera( std::vector &Output ) const; + void update_section_renderer( std::vector &Output ) const; #ifdef WITH_UART - void update_section_uart( std::vector &Output ); + void update_section_uart( std::vector &Output ) const; #endif // section update helpers std::string update_vehicle_coupler( int const Side ); std::string update_vehicle_brake() const; // renders provided lines, under specified collapsing header bool render_section( std::string const &Header, std::vector const &Lines ); - bool render_section( std::vector const &Lines ); + bool render_section( std::vector const &Lines ) const; bool render_section_scenario(); bool render_section_eventqueue(); - bool render_section_settings(); - bool render_section_developer(); + bool render_section_settings() const; + bool render_section_developer() const; // members std::array m_buffer; std::array m_eventsearch; input_data m_input; - std::vector - m_vehiclelines, - m_enginelines, - m_ailines, - m_scantablelines, - m_cameralines, - m_scenariolines, - m_eventqueuelines, - m_powergridlines, - m_rendererlines, - m_uartlines; + std::vector m_vehiclelines; + std::vector m_enginelines; + std::vector m_ailines; + std::vector m_scantablelines; + std::vector m_cameralines; + std::vector m_scenariolines; + std::vector m_eventqueuelines; + std::vector m_powergridlines; + std::vector m_rendererlines; + std::vector m_uartlines; double last_time = std::numeric_limits::quiet_NaN(); @@ -134,8 +132,6 @@ private: graph_data AccN_acc_graph; float last_AccN; - std::array queue_event_buf = { 0 }; - std::array queue_event_activator_buf = { 0 }; bool m_eventqueueactivevehicleonly { false }; }; diff --git a/application/uitranscripts.cpp b/application/uitranscripts.cpp index c9780e10..7ce36053 100644 --- a/application/uitranscripts.cpp +++ b/application/uitranscripts.cpp @@ -11,13 +11,13 @@ TTranscripts Transcripts; // dodanie linii do tabeli, (show) i (hide) w [s] od aktualnego czasu void -TTranscripts::AddLine( std::string const &txt, float show, float hide, bool it ) { +TTranscripts::AddLine( std::string_view txt, float show, float hide, bool it ) { if( show == hide ) { return; } // komentarz jest ignorowany // TODO: replace the timeangledeg mess with regular time points math - show = Global.fTimeAngleDeg + show / 240.0; // jeśli doba to 360, to 1s będzie równe 1/240 - hide = Global.fTimeAngleDeg + hide / 240.0; + show = static_cast(Global.fTimeAngleDeg + show / 240.0); // jeśli doba to 360, to 1s będzie równe 1/240 + hide = static_cast(Global.fTimeAngleDeg + hide / 240.0); TTranscript transcript; transcript.asText = txt; @@ -34,7 +34,7 @@ TTranscripts::AddLine( std::string const &txt, float show, float hide, bool it ) // dodanie tekstów, długość dźwięku, czy istotne void -TTranscripts::Add( std::string const &txt, bool backgorund ) { +TTranscripts::Add( std::string const &txt, bool /*backgorund*/ ) { if( true == txt.empty() ) { return; } @@ -42,20 +42,21 @@ TTranscripts::Add( std::string const &txt, bool backgorund ) { cParser parser( asciitext ); while( true == parser.getTokens( 3, false, "[]\n" ) ) { - float begin{ 0.f }, end{ 0.f }; + float begin{ 0.f }; + float end{ 0.f }; std::string transcript; parser >> begin >> end >> transcript; - AddLine( transcript, 0.10 * begin, 0.12 * end, false ); + AddLine( transcript, static_cast(0.10 * begin), static_cast(0.12 * end), false ); } // try to handle malformed(?) cases with no show/hide times std::string transcript; parser >> transcript; while( false == transcript.empty() ) { // WriteLog( "Transcript text with no display/hide times: \"" + transcript + "\"" ); - AddLine( transcript, 0.0, 0.12 * transcript.size(), false ); + AddLine( transcript, 0.0, static_cast(0.12 * static_cast(transcript.size())), false ); transcript = ""; parser >> transcript; } } diff --git a/application/uitranscripts.h b/application/uitranscripts.h index 7db201a1..4c24ffe4 100644 --- a/application/uitranscripts.h +++ b/application/uitranscripts.h @@ -22,7 +22,7 @@ public: // constructors TTranscripts() = default; // methods - void AddLine( std::string const &txt, float show, float hide, bool it ); + void AddLine( std::string_view txt, float show, float hide, bool it ); // dodanie tekstów, długość dźwięku, czy istotne void Add( std::string const &txt, bool background = false ); // usuwanie niepotrzebnych (ok. 10 razy na sekundę) diff --git a/audio/sound.cpp b/audio/sound.cpp index 0ff2eff9..785b976f 100644 --- a/audio/sound.cpp +++ b/audio/sound.cpp @@ -47,19 +47,18 @@ sound_source::deserialize( cParser &Input, sound_type const Legacytype, int cons if( Input.peek() == "{" ) { // block type config while( true == deserialize_mapping( Input ) ) { - ; // all work done by while() + // all work done by while() } if( false == m_soundchunks.empty() ) { // arrange loaded sound chunks in requested order - std::sort( - std::begin( m_soundchunks ), std::end( m_soundchunks ), - []( soundchunk_pair const &Left, soundchunk_pair const &Right ) { + std::ranges::sort( + m_soundchunks, []( soundchunk_pair const &Left, soundchunk_pair const &Right ) { return Left.second.threshold < Right.second.threshold; } ); // calculate and cache full range points for each chunk, including crossfade sections: // on the far end the crossfade section extends to the threshold point of the next chunk... for( std::size_t idx = 0; idx < m_soundchunks.size() - 1; ++idx ) { - m_soundchunks[ idx ].second.fadeout = m_soundchunks[ idx + 1 ].second.threshold; + m_soundchunks[ idx ].second.fadeout = static_cast(m_soundchunks[ idx + 1 ].second.threshold); /* m_soundchunks[ idx ].second.fadeout = interpolate( @@ -69,11 +68,11 @@ sound_source::deserialize( cParser &Input, sound_type const Legacytype, int cons */ } // ...and on the other end from the threshold point back into the range of previous chunk - m_soundchunks.front().second.fadein = std::max( 0, m_soundchunks.front().second.threshold ); + m_soundchunks.front().second.fadein = static_cast(std::max( 0, m_soundchunks.front().second.threshold )); // m_soundchunks.front().second.fadein = m_soundchunks.front().second.threshold; for( std::size_t idx = 1; idx < m_soundchunks.size(); ++idx ) { auto const previouschunkwidth { m_soundchunks[ idx ].second.threshold - m_soundchunks[ idx - 1 ].second.threshold }; - m_soundchunks[ idx ].second.fadein = m_soundchunks[ idx ].second.threshold - 0.01f * m_crossfaderange * previouschunkwidth; + m_soundchunks[ idx ].second.fadein = static_cast(m_soundchunks[ idx ].second.threshold) - 0.01f * static_cast(m_crossfaderange) * static_cast(previouschunkwidth); /* m_soundchunks[ idx ].second.fadein = interpolate( @@ -82,11 +81,11 @@ sound_source::deserialize( cParser &Input, sound_type const Legacytype, int cons m_crossfaderange * 0.01f ); */ } - m_soundchunks.back().second.fadeout = std::max( Chunkrange, m_soundchunks.back().second.threshold ); + m_soundchunks.back().second.fadeout = static_cast(std::max( Chunkrange, m_soundchunks.back().second.threshold )); // m_soundchunks.back().second.fadeout = m_soundchunks.back().second.threshold; // test if the chunk table contains any actual samples while at it - for( auto &soundchunk : m_soundchunks ) { - if( soundchunk.first.buffer != null_handle ) { + for( auto &[chunkbuffer, chunkdata] : m_soundchunks ) { + if( chunkbuffer.buffer != null_handle ) { m_soundchunksempty = false; break; } @@ -117,24 +116,18 @@ sound_source::deserialize( cParser &Input, sound_type const Legacytype, int cons } } - if( Legacyparameters & sound_parameters::range ) { - if( Input.getTokens( 1, false ) ) { - Input >> m_range; - } + if (Legacyparameters & sound_parameters::range && Input.getTokens( 1, false )) { + Input >> m_range; } - if( Legacyparameters & sound_parameters::amplitude ) { - if( Input.getTokens( 2, false ) ) { - Input - >> m_amplitudefactor - >> m_amplitudeoffset; - } + if (Legacyparameters & sound_parameters::amplitude && Input.getTokens( 2, false )) { + Input + >> m_amplitudefactor + >> m_amplitudeoffset; } - if( Legacyparameters & sound_parameters::frequency ) { - if( Input.getTokens( 2, false ) ) { - Input - >> m_frequencyfactor - >> m_frequencyoffset; - } + if (Legacyparameters & sound_parameters::frequency && Input.getTokens( 2, false )) { + Input + >> m_frequencyfactor + >> m_frequencyoffset; } } // restore parser behaviour @@ -225,9 +218,9 @@ sound_source::deserialize_mapping( cParser &Input ) { if( indexstart != std::string::npos ) { auto const index { std::stoi( key.substr( indexstart, indexend - indexstart ) ) }; auto const pitch { Input.getToken( false, "\n\r\t ,;" ) }; - for( auto &chunk : m_soundchunks ) { - if( chunk.second.threshold == index ) { - chunk.second.pitch = pitch > 0.f ? pitch : 1.f; + for( auto &[chunkbuffer, chunkdata] : m_soundchunks ) { + if( chunkdata.threshold == index ) { + chunkdata.pitch = pitch > 0.f ? pitch : 1.f; break; } } @@ -240,13 +233,14 @@ sound_source::deserialize_mapping( cParser &Input ) { m_crossfaderange = std::clamp( m_crossfaderange, 0, 100 ); } else if( key == "placement:" ) { + using enum sound_placement; auto const value { Input.getToken( true, "\n\r\t ,;" ) }; - std::map const placements { - { "internal", sound_placement::internal }, - { "engine", sound_placement::engine }, - { "external", sound_placement::external }, - { "custom", sound_placement::custom }, - { "general", sound_placement::general } }; + std::map> const placements { + { "internal", internal }, + { "engine", engine }, + { "external", external }, + { "custom", custom }, + { "general", general } }; auto lookup{ placements.find( value ) }; if( lookup != placements.end() ) { m_placement = lookup->second; @@ -262,7 +256,7 @@ sound_source::deserialize_mapping( cParser &Input ) { } else { // floating point properties - std::map const properties { + std::map> const properties { { "frequencyfactor:", m_frequencyfactor }, { "frequencyoffset:", m_frequencyoffset }, { "amplitudefactor:", m_amplitudefactor }, @@ -339,8 +333,8 @@ sound_source::copy_sounds( sound_source const &Source ) { for( auto &sound : m_sounds ) { sound.playing = 0; } - for( auto &sound : m_soundchunks ) { - sound.first.playing = 0; + for( auto &[chunkbuffer, chunkdata] : m_soundchunks ) { + chunkbuffer.playing = 0; } return *this; } @@ -400,7 +394,7 @@ sound_source::play_basic() { // dispatch appropriate sound if( true == m_playbeginning && sound(sound_id::begin).buffer != null_handle) { - std::vector sounds { sound_id::begin, sound_id::main }; + std::vector sounds { sound_id::begin, sound_id::main }; insert( std::begin( sounds ), std::end( sounds ) ); m_playbeginning = false; } @@ -424,14 +418,14 @@ sound_source::play_combined() { auto const soundpoint { compute_combined_point() }; for( std::uint32_t idx = 0; idx < m_soundchunks.size(); ++idx ) { - auto const &soundchunk { m_soundchunks[ idx ] }; + auto const &[chunkbuffer, chunkdata]{ m_soundchunks[ idx ] }; // a chunk covers range from fade in point, where it starts rising in volume over crossfade distance, // lasts until fadeout - crossfade distance point, past which it grows quiet until fade out point where it ends - if( soundpoint < soundchunk.second.fadein ) { break; } - if( soundpoint >= soundchunk.second.fadeout ) { continue; } + if( soundpoint < chunkdata.fadein ) { break; } + if( soundpoint >= chunkdata.fadeout ) { continue; } - if( soundchunk.first.buffer == null_handle || ( (m_flags & (sound_flags::exclusive | sound_flags::looping)) != 0 - && soundchunk.first.playing > 0 ) ) { + if( chunkbuffer.buffer == null_handle || ( (m_flags & (sound_flags::exclusive | sound_flags::looping)) != 0 + && chunkbuffer.playing > 0 ) ) { // combined sounds only play looped, single copy of each activated chunk continue; } @@ -675,9 +669,9 @@ sound_source::update_combined( audio::openal_source &Source ) { // for sound chunks, test whether the chunk should still be active given current value of the controlling variable if( ( m_flags & ( sound_flags::exclusive | sound_flags::looping ) ) != 0 ) { auto const soundpoint { compute_combined_point() }; - auto const &soundchunk { m_soundchunks[ soundhandle ^ sound_id::chunk ] }; - if( soundpoint < soundchunk.second.fadein - || soundpoint >= soundchunk.second.fadeout ) { + auto const &[chunkbuffer, chunkdata]{ m_soundchunks[ soundhandle ^ sound_id::chunk ] }; + if( soundpoint < chunkdata.fadein + || soundpoint >= chunkdata.fadeout ) { Source.stop(); update_counter( soundhandle, -1 ); return; @@ -761,7 +755,7 @@ sound_source::update_crossfade( sound_handle const Chunk ) { // relative pitch adjustment // pitch of each chunk is modified based on ratio of the chunk's pitch to that of its neighbour - if( soundpoint < chunkdata.threshold ) { + if( soundpoint < static_cast(chunkdata.threshold) ) { if( chunkindex > 0 ) { // interpolate between the pitch of previous chunk and this chunk's base pitch, @@ -772,7 +766,7 @@ sound_source::update_crossfade( sound_handle const Chunk ) { previouschunkdata.pitch / chunkdata.pitch, 1.f, std::clamp( - ( soundpoint - previouschunkdata.threshold ) / ( chunkdata.threshold - previouschunkdata.threshold ), + ( soundpoint - static_cast(previouschunkdata.threshold) ) / ( static_cast(chunkdata.threshold - previouschunkdata.threshold) ), 0.f, 1.f ) ); } } @@ -787,7 +781,7 @@ sound_source::update_crossfade( sound_handle const Chunk ) { 1.f, nextchunkdata.pitch / chunkdata.pitch, std::clamp( - ( soundpoint - chunkdata.threshold ) / ( nextchunkdata.threshold - chunkdata.threshold ), + ( soundpoint - static_cast(chunkdata.threshold) ) / ( static_cast(nextchunkdata.threshold - chunkdata.threshold) ), 0.f, 1.f ) ); } else { @@ -801,7 +795,7 @@ sound_source::update_crossfade( sound_handle const Chunk ) { if( chunkindex > 0 ) { // chunks other than the first can have fadein auto const fadeinwidth { chunkdata.threshold - chunkdata.fadein }; - if( soundpoint < chunkdata.threshold ) { + if( soundpoint < static_cast(chunkdata.threshold) ) { float lineargain = std::lerp( 0.f, 1.f, @@ -809,8 +803,8 @@ sound_source::update_crossfade( sound_handle const Chunk ) { ( soundpoint - chunkdata.fadein ) / fadeinwidth, 0.f, 1.f ) ); m_properties.gain *= - lineargain / - (1 + (1 - lineargain) * -0.57); // approximation of logarytmic fade in + static_cast(lineargain / + (1 + (1 - lineargain) * -0.57)); // approximation of logarytmic fade in return; } } @@ -828,8 +822,8 @@ sound_source::update_crossfade( sound_handle const Chunk ) { std::clamp( ( soundpoint - fadeoutstart ) / fadeoutwidth, 0.f, 1.f ) ); - m_properties.gain *= (-lineargain + 1) / - (1 + lineargain * -0.57); // approximation of logarytmic fade out + m_properties.gain *= static_cast((-lineargain + 1) / + (1 + lineargain * -0.57)); // approximation of logarytmic fade out return; } } @@ -867,14 +861,14 @@ sound_source::empty() const { // returns true if the source is emitting any sound bool -sound_source::is_playing( bool const Includesoundends ) const { +sound_source::is_playing( bool const /*Includesoundends*/ ) const { auto isplaying { sound(sound_id::begin).playing > 0 || sound(sound_id::main).playing > 0 }; if( false == isplaying && false == m_soundchunks.empty() ) { // for emitters with sample tables check also if any of the chunks is active - for( auto const &soundchunk : m_soundchunks ) { - if( soundchunk.first.playing > 0 ) { + for( auto const &[chunkbuffer, chunkdata] : m_soundchunks ) { + if( chunkbuffer.playing > 0 ) { isplaying = true; break; // one will do } @@ -905,7 +899,7 @@ sound_source::has_bookends() const { } // returns location of the sound source in simulation region space -glm::dvec3 const +glm::dvec3 sound_source::location() const { if( m_owner == nullptr ) { @@ -927,7 +921,7 @@ sound_source::range( float const Range ) { } // returns defined range of the sound -float const +float sound_source::range() const { return m_range; @@ -1016,7 +1010,7 @@ sound_source::update_soundproofing() { void sound_source::insert( sound_handle const Sound ) { - std::vector sounds { Sound }; + std::vector sounds { Sound }; return insert( std::begin( sounds ), std::end( sounds ) ); } diff --git a/audio/sound.h b/audio/sound.h index c0f14513..e9957be0 100644 --- a/audio/sound.h +++ b/audio/sound.h @@ -108,7 +108,7 @@ public: offset() const; // sound source name setter/getter void - name( std::string Name ); + name( std::string const &Name ); std::string const & name() const; // playback starting point shift setter/getter @@ -137,12 +137,12 @@ public: bool has_bookends() const; // returns location of the sound source in simulation region space - glm::dvec3 const + glm::dvec3 location() const; // returns defined range of the sound void range( float const Range ); - float const + float range() const; // members @@ -252,7 +252,7 @@ inline TDynamicObject const * sound_source::owner() const { return m_owner; } inline void sound_source::offset( glm::vec3 const Offset ) { m_offset = Offset; } inline glm::vec3 const & sound_source::offset() const { return m_offset; } // sound source name setter/getter -inline void sound_source::name( std::string Name ) { m_name = Name; } +inline void sound_source::name( std::string const &Name ) { m_name = Name; } inline std::string const & sound_source::name() const { return m_name; } // playback starting point shift setter/getter inline void sound_source::start( float const Offset ) { m_startoffset = Offset; } diff --git a/environment/moon.cpp b/environment/moon.cpp index 0cd4ce7d..302e5d8e 100644 --- a/environment/moon.cpp +++ b/environment/moon.cpp @@ -15,9 +15,7 @@ cMoon::cMoon() { m_observer.temp = 15.0; // ambient dry-bulb temperature, degrees C } -cMoon::~cMoon() { - -} +cMoon::~cMoon() = default; void cMoon::init() { @@ -74,8 +72,8 @@ float cMoon::getIntensity() { void cMoon::setLocation( float const Longitude, float const Latitude ) { // convert fraction from geographical base of 6o minutes - m_observer.longitude = (int)Longitude + (Longitude - (int)Longitude) * 100.0 / 60.0; - m_observer.latitude = (int)Latitude + (Latitude - (int)Latitude) * 100.0 / 60.0 ; + m_observer.longitude = (int)Longitude + (Longitude - static_cast((int)Longitude)) * 100.0 / 60.0; + m_observer.latitude = (int)Latitude + (Latitude - static_cast((int)Latitude)) * 100.0 / 60.0 ; } // sets current time, overriding one acquired from the system clock @@ -103,9 +101,9 @@ void cMoon::move() { SYSTEMTIME localtime = simulation::Time.data(); // time for the calculation - if( m_observer.hour >= 0 ) { localtime.wHour = m_observer.hour; } - if( m_observer.minute >= 0 ) { localtime.wMinute = m_observer.minute; } - if( m_observer.second >= 0 ) { localtime.wSecond = m_observer.second; } + if( m_observer.hour >= 0 ) { localtime.wHour = static_cast(m_observer.hour); } + if( m_observer.minute >= 0 ) { localtime.wMinute = static_cast(m_observer.minute); } + if( m_observer.second >= 0 ) { localtime.wSecond = static_cast(m_observer.second); } double localut = localtime.wHour @@ -158,7 +156,6 @@ void cMoon::move() { double const yeclip = m_body.distance * ( std::sin( degtorad * longascnode ) * std::cos( vpluswinrad ) + std::cos( degtorad * longascnode ) * std::sin( vpluswinrad ) * std::cos( degtorad * inclination ) ); double const zeclip = m_body.distance * std::sin( vpluswinrad ) * std::sin( degtorad * inclination ); // ecliptic coordinates - double ecliplat = radtodeg * std::atan2( zeclip, std::sqrt( xeclip*xeclip + yeclip*yeclip ) ); m_body.eclong = clamp_circular( radtodeg * std::atan2( yeclip, xeclip ) ); // distance m_body.distance = std::sqrt( xeclip*xeclip + yeclip*yeclip + zeclip*zeclip ); @@ -174,17 +171,13 @@ void cMoon::move() { m_body.mnlong = clamp_circular( longascnode + perigeearg + m_body.mnanom ); // Moon's mean elongation: D = Lm - Ls double const mnelong = clamp_circular( m_body.mnlong - sunmnlong ); - // Moon's argument of latitude: F = Lm - N - double const arglat = clamp_circular( m_body.mnlong - longascnode ); // longitude perturbations double const pertevection = -1.274 * std::sin( degtorad * ( m_body.mnanom - 2.0 * mnelong ) ); // Evection double const pertvariation = +0.658 * std::sin( degtorad * ( 2.0 * mnelong ) ); // Variation double const pertyearlyeqt = -0.186 * std::sin( degtorad * sunmnanom ); // Yearly equation // latitude perturbations - double const pertlat = -0.173 * std::sin( degtorad * ( arglat - 2.0 * mnelong ) ); m_body.eclong += pertevection + pertvariation + pertyearlyeqt; - ecliplat += pertlat; // declination m_body.declin = radtodeg * std::asin( std::sin (m_body.oblecl * degtorad) * std::sin(m_body.eclong * degtorad) ); @@ -267,7 +260,6 @@ void cMoon::refract() { void cMoon::irradiance() { - static double radtodeg = 57.295779513; // converts from radians to degrees static double degtorad = 0.0174532925; // converts from degrees to radians m_body.dayang = ( simulation::Time.year_day() - 1 ) * 360.0 / 365.0; @@ -299,7 +291,7 @@ cMoon::phase() { m_phase = 50; else { // calculate moon's age in days from new moon - float ip = normalize( ( simulation::Time.julian_day() - 2451550.1f ) / 29.530588853f ); + float ip = normalize( ( static_cast(simulation::Time.julian_day()) - 2451550.1f ) / 29.530588853f ); m_phase = ip * 29.53f; } } @@ -308,7 +300,7 @@ cMoon::phase() { float cMoon::normalize( const float Value ) const { - float value = Value - floor( Value ); + auto value = static_cast(Value - floor( Value )); if( value < 0.f ) { ++value; } return value; diff --git a/environment/skydome.cpp b/environment/skydome.cpp index 830eb145..654b3a34 100644 --- a/environment/skydome.cpp +++ b/environment/skydome.cpp @@ -53,8 +53,7 @@ CSkyDome::CSkyDome (int const Tesselation) : Generate(); } -CSkyDome::~CSkyDome() { -} +CSkyDome::~CSkyDome() = default; //******************************************************************************// @@ -71,13 +70,13 @@ void CSkyDome::Generate() { for( int i = 0; i <= latitudes; ++i ) { - float const latitude = M_PI * ( -0.5f + (float)i / latitudes / 2 ); // half-sphere only + auto const latitude = static_cast(M_PI * ( -0.5f + (float)i / static_cast(latitudes) / 2 )); // half-sphere only float const z = std::sin( latitude ); float const zr = std::cos( latitude ); for( int j = 0; j <= longitudes; ++j ) { - float const longitude = 2.0 * M_PI * (float)j / longitudes; + auto const longitude = static_cast(2.0 * M_PI * (float)j / longitudes); float const x = std::cos( longitude ); float const y = std::sin( longitude ); /* @@ -147,7 +146,7 @@ void CSkyDome::SetOvercastFactor( float const Overcast ) { m_overcast = std::clamp( Overcast, 0.0f, 1.0f ) * 0.75f; // going above 0.65 makes the model go pretty bad, appearance-wise } -void CSkyDome::GetPerez( float *Perez, float Distribution[ 5 ][ 2 ], const float Turbidity ) { +void CSkyDome::GetPerez( float *Perez, float Distribution[ 5 ][ 2 ], const float Turbidity ) const { Perez[ 0 ] = Distribution[ 0 ][ 0 ] * Turbidity + Distribution[ 0 ][ 1 ]; Perez[ 1 ] = Distribution[ 1 ][ 0 ] * Turbidity + Distribution[ 1 ][ 1 ]; @@ -156,7 +155,7 @@ void CSkyDome::GetPerez( float *Perez, float Distribution[ 5 ][ 2 ], const float Perez[ 4 ] = Distribution[ 4 ][ 0 ] * Turbidity + Distribution[ 4 ][ 1 ]; } -float CSkyDome::GetZenith( float Zenithmatrix[ 3 ][ 4 ], const float Theta, const float Turbidity ) { +float CSkyDome::GetZenith( float Zenithmatrix[ 3 ][ 4 ], const float Theta, const float Turbidity ) const { const float theta2 = Theta*Theta; const float theta3 = Theta*theta2; @@ -167,15 +166,15 @@ float CSkyDome::GetZenith( float Zenithmatrix[ 3 ][ 4 ], const float Theta, cons } -float CSkyDome::PerezFunctionO1( float Perezcoeffs[ 5 ], const float Thetasun, const float Zenithval ) { +float CSkyDome::PerezFunctionO1( float const Perezcoeffs[ 5 ], const float Thetasun, const float Zenithval ) const { - const float val = ( 1.0f + Perezcoeffs[ 0 ] * std::exp( Perezcoeffs[ 1 ] ) ) * - ( 1.0f + Perezcoeffs[ 2 ] * std::exp( Perezcoeffs[ 3 ] * Thetasun ) + Perezcoeffs[ 4 ] * std::pow( std::cos( Thetasun ), 2 ) ); + const auto val = static_cast(( 1.0f + Perezcoeffs[ 0 ] * std::exp( Perezcoeffs[ 1 ] ) ) * + ( 1.0f + Perezcoeffs[ 2 ] * std::exp( Perezcoeffs[ 3 ] * Thetasun ) + Perezcoeffs[ 4 ] * std::pow( std::cos( Thetasun ), 2 ) )); return Zenithval / val; } -float CSkyDome::PerezFunctionO2( float Perezcoeffs[ 5 ], const float Icostheta, const float Gamma, const float Cosgamma2, const float Zenithval ) { +float CSkyDome::PerezFunctionO2( float const Perezcoeffs[ 5 ], const float Icostheta, const float Gamma, const float Cosgamma2, const float Zenithval ) const { // iCosTheta = 1.0f / cosf(theta) // cosGamma2 = SQR( cosf( gamma ) ) return Zenithval * ( 1.0f + Perezcoeffs[ 0 ] * std::exp( Perezcoeffs[ 1 ] * Icostheta ) ) * @@ -188,7 +187,7 @@ void CSkyDome::RebuildColors() { auto gammacorrection = glm::mix( glm::vec3( 1.0f ), glm::vec3( 0.45f ), twilightfactor ); // get zenith luminance - float const chi = ( 4.0f / 9.0f - m_turbidity / 120.0f ) * ( M_PI - 2.0f * m_thetasun ); + auto const chi = static_cast(( 4.0f / 9.0f - m_turbidity / 120.0f ) * ( M_PI - 2.0f * m_thetasun )); float zenithluminance = ( 4.0453f * m_turbidity - 4.9710f ) * std::tan( chi ) - 0.2155f * m_turbidity + 2.4192f; // get x / y zenith @@ -196,22 +195,26 @@ void CSkyDome::RebuildColors() { float zenithy = GetZenith( m_zenithymatrix, m_thetasun, m_turbidity ); // get perez function parametrs - float perezluminance[5], perezx[5], perezy[5]; - GetPerez( perezluminance, m_distributionluminance, m_turbidity ); - GetPerez( perezx, m_distributionxcomp, m_turbidity ); - GetPerez( perezy, m_distributionycomp, m_turbidity ); + std::array perezluminance{}; + std::array perezx{}; + std::array perezy{}; + GetPerez( perezluminance.data(), m_distributionluminance, m_turbidity ); + GetPerez( perezx.data(), m_distributionxcomp, m_turbidity ); + GetPerez( perezy.data(), m_distributionycomp, m_turbidity ); // make some precalculation - zenithx = PerezFunctionO1( perezx, m_thetasun, zenithx ); - zenithy = PerezFunctionO1( perezy, m_thetasun, zenithy ); - zenithluminance = PerezFunctionO1( perezluminance, m_thetasun, zenithluminance ); + zenithx = PerezFunctionO1( perezx.data(), m_thetasun, zenithx ); + zenithy = PerezFunctionO1( perezy.data(), m_thetasun, zenithy ); + zenithluminance = PerezFunctionO1( perezluminance.data(), m_thetasun, zenithluminance ); // start with fresh average for the new pass - glm::vec3 averagecolor, averagehorizoncolor; + glm::vec3 averagecolor; + glm::vec3 averagehorizoncolor; // trough all vertices glm::vec3 vertex; - glm::vec3 color, colorconverter; + glm::vec3 color; + glm::vec3 colorconverter; for ( unsigned int i = 0; i < m_vertices.size(); ++i ) { // grab it @@ -235,14 +238,14 @@ void CSkyDome::RebuildColors() { // = 1.0f / cosf( arccos( vertex.y ) ); // = 1.0f / vertex.y; float const icostheta = 1.0f / vertex.y; - float const cosgamma2 = std::pow( std::cos( gamma ), 2 ); + auto const cosgamma2 = static_cast(std::pow( std::cos( gamma ), 2 )); // Compute x,y values - float const x = PerezFunctionO2( perezx, icostheta, gamma, cosgamma2, zenithx ); - float const y = PerezFunctionO2( perezy, icostheta, gamma, cosgamma2, zenithy ); + float const x = PerezFunctionO2( perezx.data(), icostheta, gamma, cosgamma2, zenithx ); + float const y = PerezFunctionO2( perezy.data(), icostheta, gamma, cosgamma2, zenithy ); // luminance(Y) for clear & overcast sky - float const yclear = std::max( 0.01f, PerezFunctionO2( perezluminance, icostheta, gamma, cosgamma2, zenithluminance ) ); + float const yclear = std::max( 0.01f, PerezFunctionO2( perezluminance.data(), icostheta, gamma, cosgamma2, zenithluminance ) ); float const yover = std::max( 0.01f, zenithluminance * ( 1.0f + 2.0f * vertex.y ) / 3.0f ); float const Y = std::lerp( yclear, yover, m_overcast ); @@ -271,7 +274,7 @@ void CSkyDome::RebuildColors() { // override the hue, based on sun height above the horizon. crude way to deal with model shortcomings // correction begins when the sun is higher than 10 degrees above the horizon, and fully in effect at 10+15 degrees - float const degreesabovehorizon = 90.0f - m_thetasun * ( 180.0f / M_PI ); + auto const degreesabovehorizon = static_cast(90.0f - m_thetasun * ( 180.0f / M_PI )); auto const sunbasedphase = std::clamp( 1.0f / 15.0f * ( degreesabovehorizon - 10.0f ), 0.0f, 1.0f ); // correction is applied in linear manner from the bottom, becomes fully in effect for vertices with y = 0.50 auto const heightbasedphase = std::clamp( vertex.y * 2.0f, 0.0f, 1.0f ); diff --git a/environment/skydome.h b/environment/skydome.h index 74d024d1..bc22f9c7 100644 --- a/environment/skydome.h +++ b/environment/skydome.h @@ -5,7 +5,7 @@ class CSkyDome { public: - CSkyDome( int const Tesselation = 54 ); + explicit CSkyDome( int const Tesselation = 54 ); ~CSkyDome(); void Generate(); void RebuildColors(); @@ -20,8 +20,8 @@ public: void Update( glm::vec3 const &Sun ); // retrieves average colour of the sky dome - glm::vec3 GetAverageColor() { return m_averagecolour * 8.f / 6.f; } - glm::vec3 GetAverageHorizonColor() { return m_averagehorizoncolour; } + glm::vec3 GetAverageColor() const { return m_averagecolour * 8.f / 6.f; } + glm::vec3 GetAverageHorizonColor() const { return m_averagehorizoncolour; } std::vector const & vertices() const { return m_vertices; } @@ -35,7 +35,8 @@ public: private: // shading parametrs glm::vec3 m_sundirection; - float m_thetasun, m_phisun; + float m_thetasun; + float m_phisun; float m_turbidity; bool m_linearexpcontrol; float m_expfactor; @@ -59,9 +60,9 @@ private: static float m_zenithymatrix[ 3 ][ 4 ]; // coloring - void GetPerez( float *Perez, float Distribution[ 5 ][ 2 ], const float Turbidity ); - float GetZenith( float Zenithmatrix[ 3 ][ 4 ], const float Theta, const float Turbidity ); - float PerezFunctionO1( float Perezcoeffs[ 5 ], const float Thetasun, const float Zenithval ); - float PerezFunctionO2( float Perezcoeffs[ 5 ], const float Icostheta, const float Gamma, const float Cosgamma2, const float Zenithval ); + void GetPerez( float *Perez, float Distribution[ 5 ][ 2 ], const float Turbidity ) const; + float GetZenith( float Zenithmatrix[ 3 ][ 4 ], const float Theta, const float Turbidity ) const; + float PerezFunctionO1( float const Perezcoeffs[ 5 ], const float Thetasun, const float Zenithval ) const; + float PerezFunctionO2( float const Perezcoeffs[ 5 ], const float Icostheta, const float Gamma, const float Cosgamma2, const float Zenithval ) const; }; diff --git a/environment/sun.cpp b/environment/sun.cpp index 1ecd94ed..c85fcacb 100644 --- a/environment/sun.cpp +++ b/environment/sun.cpp @@ -15,10 +15,7 @@ cSun::cSun() { m_observer.temp = 15.0; // ambient dry-bulb temperature, degrees C } -cSun::~cSun() -{ - -} +cSun::~cSun() = default; void cSun::init() { @@ -79,8 +76,8 @@ float cSun::getIntensity() { void cSun::setLocation( float const Longitude, float const Latitude ) { // convert fraction from geographical base of 6o minutes - m_observer.longitude = (int)Longitude + (Longitude - (int)Longitude) * 100.0 / 60.0; - m_observer.latitude = (int)Latitude + (Latitude - (int)Latitude) * 100.0 / 60.0 ; + m_observer.longitude = (int)Longitude + (Longitude - static_cast((int)Longitude)) * 100.0 / 60.0; + m_observer.latitude = (int)Latitude + (Latitude - static_cast((int)Latitude)) * 100.0 / 60.0 ; } // sets current time, overriding one acquired from the system clock @@ -108,9 +105,9 @@ void cSun::move() { SYSTEMTIME localtime = simulation::Time.data(); // time for the calculation - if( m_observer.hour >= 0 ) { localtime.wHour = m_observer.hour; } - if( m_observer.minute >= 0 ) { localtime.wMinute = m_observer.minute; } - if( m_observer.second >= 0 ) { localtime.wSecond = m_observer.second; } + if( m_observer.hour >= 0 ) { localtime.wHour = static_cast(m_observer.hour); } + if( m_observer.minute >= 0 ) { localtime.wMinute = static_cast(m_observer.minute); } + if( m_observer.second >= 0 ) { localtime.wSecond = static_cast(m_observer.second); } double localut = localtime.wHour diff --git a/extras/piped_proc.cpp b/extras/piped_proc.cpp index f7e4e67c..81684957 100644 --- a/extras/piped_proc.cpp +++ b/extras/piped_proc.cpp @@ -7,7 +7,7 @@ #include "utilities/Logs.h" #ifdef __unix__ -piped_proc::piped_proc(std::string cmd, bool write) +piped_proc::piped_proc(std::string const &cmd, bool write) { file = popen(cmd.c_str(), write ? "w" : "r"); } @@ -26,7 +26,7 @@ size_t piped_proc::read(unsigned char *buf, size_t len) return fread(buf, 1, len, file); } -size_t piped_proc::write(unsigned char *buf, size_t len) +size_t piped_proc::write(unsigned char const *buf, size_t len) { if (!file) return 0; @@ -34,7 +34,7 @@ size_t piped_proc::write(unsigned char *buf, size_t len) return fwrite(buf, 1, len, file); } #elif _WIN32 -piped_proc::piped_proc(std::string cmd, bool write) +piped_proc::piped_proc(std::string const &cmd, bool write) { PROCESS_INFORMATION process; STARTUPINFO siStartInfo; @@ -97,7 +97,7 @@ size_t piped_proc::read(unsigned char *buf, size_t len) return read; } -size_t piped_proc::write(unsigned char *buf, size_t len) +size_t piped_proc::write(unsigned char const *buf, size_t len) { if (!pipe_wr) return 0; diff --git a/extras/piped_proc.h b/extras/piped_proc.h index b16c6b3d..0e2cb31a 100644 --- a/extras/piped_proc.h +++ b/extras/piped_proc.h @@ -23,8 +23,8 @@ HANDLE pipe_wr = nullptr; #endif public: - piped_proc(std::string cmd, bool write = false); + explicit piped_proc(std::string const &cmd, bool write = false); size_t read(unsigned char *buf, size_t len); - size_t write(unsigned char *buf, size_t len); + size_t write(unsigned char const *buf, size_t len); ~piped_proc(); }; diff --git a/gl/buffer.cpp b/gl/buffer.cpp index b80cee3e..2ac6dbfb 100644 --- a/gl/buffer.cpp +++ b/gl/buffer.cpp @@ -3,7 +3,7 @@ GLenum gl::buffer::glenum_target(gl::buffer::targets target) { - static GLenum mapping[13] = + static std::array const mapping = { GL_ARRAY_BUFFER, GL_ATOMIC_COUNTER_BUFFER, @@ -22,7 +22,7 @@ GLenum gl::buffer::glenum_target(gl::buffer::targets target) return mapping[target]; } -void gl::buffer::bind(targets target) +void gl::buffer::bind(targets target) const { if (binding_points[target] == *this) return; @@ -31,7 +31,7 @@ void gl::buffer::bind(targets target) binding_points[target] = *this; } -void gl::buffer::bind_base(targets target, GLuint index) +void gl::buffer::bind_base(targets target, GLuint index) const { glBindBufferBase(glenum_target(target), index, *this); binding_points[target] = *this; @@ -47,7 +47,7 @@ void gl::buffer::unbind(targets target) void gl::buffer::unbind() { - for (size_t i = 0; i < sizeof(binding_points) / sizeof(GLuint); i++) + for (size_t i = 0; i < std::size(binding_points); i++) unbind((targets)i); } @@ -87,7 +87,7 @@ void gl::buffer::download(targets target, void *data, int offset, GLsizeiptr siz } else { - void *glbuf = glMapBufferRange(glenum_target(target), offset, size, GL_MAP_READ_BIT); + void const *glbuf = glMapBufferRange(glenum_target(target), offset, size, GL_MAP_READ_BIT); memcpy(data, glbuf, size); glUnmapBuffer(glenum_target(target)); } diff --git a/gl/buffer.h b/gl/buffer.h index 8b4e7d9c..3e66b516 100644 --- a/gl/buffer.h +++ b/gl/buffer.h @@ -34,8 +34,8 @@ namespace gl buffer(); ~buffer(); - void bind(targets target); - void bind_base(targets target, GLuint index); + void bind(targets target) const; + void bind_base(targets target, GLuint index) const; static void unbind(targets target); static void unbind(); diff --git a/gl/cubemap.cpp b/gl/cubemap.cpp index ca0e6c08..07aa1b1c 100644 --- a/gl/cubemap.cpp +++ b/gl/cubemap.cpp @@ -15,7 +15,7 @@ gl::cubemap::~cubemap() glDeleteTextures(1, *this); } -void gl::cubemap::alloc(GLint format, int width, int height, GLenum components, GLenum type) +void gl::cubemap::alloc(GLint format, int width, int height, GLenum components, GLenum type) const { glBindTexture(GL_TEXTURE_CUBE_MAP, *this); for (GLuint tgt = GL_TEXTURE_CUBE_MAP_POSITIVE_X; tgt <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; tgt++) @@ -29,13 +29,13 @@ void gl::cubemap::alloc(GLint format, int width, int height, GLenum components, glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } -void gl::cubemap::bind(int unit) +void gl::cubemap::bind(int unit) const { glActiveTexture(unit); glBindTexture(GL_TEXTURE_CUBE_MAP, *this); } -void gl::cubemap::generate_mipmaps() +void gl::cubemap::generate_mipmaps() const { glBindTexture(GL_TEXTURE_CUBE_MAP, *this); glGenerateMipmap(GL_TEXTURE_CUBE_MAP); diff --git a/gl/cubemap.h b/gl/cubemap.h index e874c221..f5706b65 100644 --- a/gl/cubemap.h +++ b/gl/cubemap.h @@ -12,8 +12,8 @@ namespace gl cubemap(); ~cubemap(); - void alloc(GLint format, int width, int height, GLenum components, GLenum type); - void bind(int unit); - void generate_mipmaps(); + void alloc(GLint format, int width, int height, GLenum components, GLenum type) const; + void bind(int unit) const; + void generate_mipmaps() const; }; } diff --git a/gl/framebuffer.cpp b/gl/framebuffer.cpp index af1f63de..207a0ea9 100644 --- a/gl/framebuffer.cpp +++ b/gl/framebuffer.cpp @@ -80,7 +80,7 @@ void gl::framebuffer::blit_from(framebuffer *other, int w, int h, GLbitfield mas blit(other, this, 0, 0, w, h, mask, attachment); } -void gl::framebuffer::blit(framebuffer *src, framebuffer *dst, int sx, int sy, int w, int h, GLbitfield mask, GLenum attachment) +void gl::framebuffer::blit(framebuffer const *src, framebuffer const *dst, int sx, int sy, int w, int h, GLbitfield mask, GLenum attachment) { glBindFramebuffer(GL_READ_FRAMEBUFFER, src ? *src : 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dst ? *dst : 0); @@ -90,17 +90,17 @@ void gl::framebuffer::blit(framebuffer *src, framebuffer *dst, int sx, int sy, i int attachment_n = attachment - GL_COLOR_ATTACHMENT0; { - GLenum outputs[8] = { GL_NONE }; - outputs[attachment_n] = src != 0 ? attachment : GL_BACK_LEFT; + std::array outputs{ GL_NONE }; + outputs[attachment_n] = src != nullptr ? attachment : GL_BACK_LEFT; glReadBuffer(attachment); } { - GLenum outputs[8] = { GL_NONE }; - outputs[attachment_n] = dst != 0 ? attachment : GL_BACK_LEFT; + std::array outputs{ GL_NONE }; + outputs[attachment_n] = dst != nullptr ? attachment : GL_BACK_LEFT; - glDrawBuffers(attachment_n + 1, outputs); + glDrawBuffers(attachment_n + 1, outputs.data()); } } diff --git a/gl/framebuffer.h b/gl/framebuffer.h index e5dccf57..f8bee46a 100644 --- a/gl/framebuffer.h +++ b/gl/framebuffer.h @@ -26,7 +26,7 @@ namespace gl void blit_to(framebuffer *other, int w, int h, GLbitfield mask, GLenum attachment); void blit_from(framebuffer *other, int w, int h, GLbitfield mask, GLenum attachment); - static void blit(framebuffer *src, framebuffer *dst, int sx, int sy, int w, int h, GLbitfield mask, GLenum attachment); + static void blit(framebuffer const *src, framebuffer const *dst, int sx, int sy, int w, int h, GLbitfield mask, GLenum attachment); using bindable::bind; static void bind(GLuint id); diff --git a/gl/object.h b/gl/object.h index eb200889..7bb95463 100644 --- a/gl/object.h +++ b/gl/object.h @@ -15,12 +15,12 @@ namespace gl return id; } - inline operator GLuint* const() + inline operator GLuint*() { return &id; } - inline operator const GLuint* const() const + inline operator const GLuint*() const { return &id; } diff --git a/gl/pbo.cpp b/gl/pbo.cpp index 6923e09d..4cad2c9d 100644 --- a/gl/pbo.cpp +++ b/gl/pbo.cpp @@ -12,7 +12,7 @@ void gl::pbo::request_read(int x, int y, int lx, int ly, int pixsize, GLenum for sync.reset(); bind(PIXEL_PACK_BUFFER); - glReadPixels(x, y, lx, ly, format, type, 0); + glReadPixels(x, y, lx, ly, format, type, nullptr); unbind(PIXEL_PACK_BUFFER); sync.emplace(); diff --git a/gl/postfx.h b/gl/postfx.h index cc0c5450..9ea4b719 100644 --- a/gl/postfx.h +++ b/gl/postfx.h @@ -15,8 +15,8 @@ namespace gl static std::shared_ptr vao; public: - postfx(const std::string &s); - postfx(const shader &s); + explicit postfx(const std::string &s); + explicit postfx(const shader &s); void attach(); void apply(opengl_texture &src, framebuffer *dst); diff --git a/gl/query.cpp b/gl/query.cpp index 3f3b56af..8e445612 100644 --- a/gl/query.cpp +++ b/gl/query.cpp @@ -49,9 +49,9 @@ std::optional gl::query::result() return std::nullopt; } -GLenum gl::query::glenum_target(targets target) +GLenum gl::query::glenum_target(targets Target) const { - static GLenum mapping[6] = + static std::array const mapping = { GL_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED, @@ -60,7 +60,7 @@ GLenum gl::query::glenum_target(targets target) GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, GL_TIME_ELAPSED }; - return mapping[target]; + return mapping[Target]; } thread_local gl::query* gl::query::active_queries[6]; diff --git a/gl/query.h b/gl/query.h index 83114092..12445790 100644 --- a/gl/query.h +++ b/gl/query.h @@ -22,10 +22,10 @@ private: thread_local static query* active_queries[6]; protected: - GLenum glenum_target(targets target); + GLenum glenum_target(targets target) const; public: - query(targets target); + explicit query(targets target); ~query(); void begin(); diff --git a/gl/shader.cpp b/gl/shader.cpp index 5d818833..9160a2c9 100644 --- a/gl/shader.cpp +++ b/gl/shader.cpp @@ -7,7 +7,7 @@ #include "glsl_common.h" #include "utilities/Logs.h" -inline bool strcend(std::string const &value, std::string const &ending) +inline bool strcend(std::string_view value, std::string_view ending) { if (ending.size() > value.size()) return false; @@ -41,7 +41,7 @@ bool has_gl_extension(char const *name) { GLint count = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &count); for (GLint i = 0; i < count; ++i) { - char const *ext = reinterpret_cast(glGetStringi(GL_EXTENSIONS, i)); + auto ext = reinterpret_cast(glGetStringi(GL_EXTENSIONS, i)); if (ext != nullptr && std::strcmp(ext, name) == 0) { return true; } @@ -52,7 +52,7 @@ bool has_gl_extension(char const *name) { } // anonymous namespace -std::string gl::shader::read_file(const std::string &filename) +std::string gl::shader::read_file(const std::string &filename) const { std::stringstream stream; std::ifstream f; @@ -73,11 +73,11 @@ void gl::shader::expand_includes(std::string &str, const std::string &basedir) size_t start_pos = 0; std::string magic = "#include"; - while ((start_pos = str.find(magic, start_pos)) != str.npos) + while ((start_pos = str.find(magic, start_pos)) != std::string::npos) { size_t fp = str.find('<', start_pos); size_t fe = str.find('>', start_pos); - if (fp == str.npos || fe == str.npos) + if (fp == std::string::npos || fe == std::string::npos) return; std::string filename = str.substr(fp + 1, fe - fp - 1); @@ -154,8 +154,7 @@ std::pair gl::shader::process_source(const std::string &fil // the driver advertises support (see desktop comment above). // (Glad config doesn't generate GLAD_GL_EXT_gpu_shader5 -- query // the live extension string the same way.) - static bool const have_gpu_shader5 = has_gl_extension("GL_EXT_gpu_shader5"); - if (have_gpu_shader5) + if (static bool const have_gpu_shader5 = has_gl_extension("GL_EXT_gpu_shader5"); have_gpu_shader5) str += "#extension GL_EXT_gpu_shader5 : enable\n"; if (type == GL_GEOMETRY_SHADER) str += "#extension GL_EXT_geometry_shader : require\n"; @@ -189,17 +188,17 @@ void gl::shader::parse_texture_entries(std::string &str) size_t start_pos = 0; std::string magic = "#texture"; - while ((start_pos = str.find(magic, start_pos)) != str.npos) + while ((start_pos = str.find(magic, start_pos)) != std::string::npos) { size_t fp = str.find('(', start_pos); size_t fe = str.find(')', start_pos); - if (fp == str.npos || fe == str.npos) + if (fp == std::string::npos || fe == std::string::npos) return; std::istringstream ss(str.substr(fp + 1, fe - fp - 1)); std::string token; - std::string name; + std::string uniformname; texture_entry conf; size_t arg = 0; @@ -207,14 +206,14 @@ void gl::shader::parse_texture_entries(std::string &str) { std::istringstream token_ss(token); if (arg == 0) - token_ss >> name; + token_ss >> uniformname; else if (arg == 1) token_ss >> conf.id; else if (arg == 2) { std::string comp; token_ss >> comp; - if (components_mapping.find(comp) == components_mapping.end()) + if (!components_mapping.contains(comp)) log_error("unknown components: " + comp); else conf.components = components_mapping[comp]; @@ -224,12 +223,12 @@ void gl::shader::parse_texture_entries(std::string &str) if (arg == 3) { - if (name.empty()) + if (uniformname.empty()) log_error("empty name"); else if (conf.id >= gl::MAX_TEXTURES) log_error("invalid texture binding: " + std::to_string(conf.id)); else - texture_conf.emplace(std::make_pair(name, conf)); + texture_conf.try_emplace(uniformname, conf); } else log_error("invalid argument count to #texture"); @@ -243,17 +242,17 @@ void gl::shader::parse_param_entries(std::string &str) size_t start_pos = 0; std::string magic = "#param"; - while ((start_pos = str.find(magic, start_pos)) != str.npos) + while ((start_pos = str.find(magic, start_pos)) != std::string::npos) { size_t fp = str.find('(', start_pos); size_t fe = str.find(')', start_pos); - if (fp == str.npos || fe == str.npos) + if (fp == std::string::npos || fe == std::string::npos) return; std::istringstream ss(str.substr(fp + 1, fe - fp - 1)); std::string token; - std::string name; + std::string uniformname; param_entry conf; size_t arg = 0; @@ -261,7 +260,7 @@ void gl::shader::parse_param_entries(std::string &str) { std::istringstream token_ss(token); if (arg == 0) - token_ss >> name; + token_ss >> uniformname; else if (arg == 1) token_ss >> conf.location; else if (arg == 2) @@ -272,7 +271,7 @@ void gl::shader::parse_param_entries(std::string &str) { std::string tok; token_ss >> tok; - if (defaultparams_mapping.find(tok) == defaultparams_mapping.end()) + if (!defaultparams_mapping.contains(tok)) log_error("unknown param default: " + tok); conf.defaultparam = defaultparams_mapping[tok]; } @@ -281,7 +280,7 @@ void gl::shader::parse_param_entries(std::string &str) if (arg == 5) { - if (name.empty()) + if (uniformname.empty()) log_error("empty name"); else if (conf.location >= gl::MAX_PARAMS) log_error("invalid param binding: " + std::to_string(conf.location)); @@ -290,7 +289,7 @@ void gl::shader::parse_param_entries(std::string &str) else if (conf.offset + conf.size > 4) log_error("invalid size: " + std::to_string(conf.size)); else - param_conf.emplace(std::make_pair(name, conf)); + param_conf.try_emplace(uniformname, conf); } else log_error("invalid argument count to #param"); @@ -299,32 +298,31 @@ void gl::shader::parse_param_entries(std::string &str) } } -void gl::shader::log_error(const std::string &str) +void gl::shader::log_error(const std::string &str) const { ErrorLog("bad shader: " + name + ": " + str, logtype::shader); } -gl::shader::shader(const std::string &filename) +gl::shader::shader(const std::string &filename) : name(filename) { - name = filename; - std::pair source = process_source(filename, "shaders/"); + auto [shadertype, shadersource] = process_source(filename, "shaders/"); - const GLchar *cstr = source.second.c_str(); + const GLchar *cstr = shadersource.c_str(); - **this = glCreateShader(source.first); - glShaderSource(*this, 1, &cstr, 0); + **this = glCreateShader(shadertype); + glShaderSource(*this, 1, &cstr, nullptr); glCompileShader(*this); GLint status; glGetShaderiv(*this, GL_COMPILE_STATUS, &status); if (!status) { - GLchar info[512]; - glGetShaderInfoLog(*this, 512, 0, info); - log_error(std::string(info)); + std::array info{}; + glGetShaderInfoLog(*this, static_cast(info.size()), nullptr, info.data()); + log_error(std::string(info.data())); - throw shader_exception("failed to compile " + filename + ": " + std::string(info)); + throw shader_exception("failed to compile " + filename + ": " + std::string(info.data())); } } @@ -339,11 +337,11 @@ void gl::program::init() { bind(); - for (auto it : texture_conf) + for (auto const &[texturename, textureentry] : texture_conf) { - shader::texture_entry &e = it.second; - GLuint loc = glGetUniformLocation(*this, it.first.c_str()); - glUniform1i(loc, e.id); + shader::texture_entry const &e = textureentry; + GLuint loc = glGetUniformLocation(*this, texturename.c_str()); + glUniform1i(loc, static_cast(e.id)); } glUniform1i(glGetUniformLocation(*this, "shadowmap"), gl::SHADOW_TEX); @@ -370,7 +368,7 @@ gl::program::program() **this = glCreateProgram(); } -gl::program::program(std::vector> shaders) : program() +gl::program::program(std::vector> const &shaders) : program() { for (const gl::shader &s : shaders) attach(s); @@ -379,10 +377,10 @@ gl::program::program(std::vector> shade void gl::program::attach(const gl::shader &s) { - for (auto it : s.texture_conf) - texture_conf.emplace(std::make_pair(it.first, std::move(it.second))); - for (auto it : s.param_conf) - param_conf.emplace(std::make_pair(it.first, std::move(it.second))); + for (auto [texturename, textureentry] : s.texture_conf) + texture_conf.try_emplace(texturename, std::move(textureentry)); + for (auto [paramname, paramentry] : s.param_conf) + param_conf.try_emplace(paramname, std::move(paramentry)); glAttachShader(*this, *s); } @@ -394,9 +392,9 @@ void gl::program::link() glGetProgramiv(*this, GL_LINK_STATUS, &status); if (!status) { - GLchar info[512]; - glGetProgramInfoLog(*this, 512, 0, info); - throw shader_exception("failed to link program: " + std::string(info)); + std::array info{}; + glGetProgramInfoLog(*this, static_cast(info.size()), nullptr, info.data()); + throw shader_exception("failed to link program: " + std::string(info.data())); } init(); diff --git a/gl/shader.h b/gl/shader.h index 4cd25f07..f1735a0e 100644 --- a/gl/shader.h +++ b/gl/shader.h @@ -21,7 +21,7 @@ namespace gl #ifdef SHADERVALIDATOR_STANDALONE shader() = default; #endif - shader(const std::string &filename); + explicit shader(const std::string &filename); ~shader(); enum class components_e @@ -73,19 +73,19 @@ namespace gl void parse_texture_entries(std::string &str); void parse_param_entries(std::string &str); - std::string read_file(const std::string &filename); + std::string read_file(const std::string &filename) const; static std::unordered_map components_mapping; static std::unordered_map defaultparams_mapping; - void log_error(const std::string &str); + void log_error(const std::string &str) const; }; class program : public object, public bindable { public: program(); - program(std::vector>); + explicit program(std::vector> const &); ~program(); using bindable::bind; diff --git a/gl/ubo.cpp b/gl/ubo.cpp index cecf84f0..ad6f1611 100644 --- a/gl/ubo.cpp +++ b/gl/ubo.cpp @@ -1,10 +1,9 @@ #include "stdafx.h" #include "ubo.h" -gl::ubo::ubo(size_t size, int idx, GLenum hint) +gl::ubo::ubo(size_t size, int idx, GLenum hint) : index(idx) { allocate(buffer::UNIFORM_BUFFER, size, hint); - index = idx; bind_uniform(); } diff --git a/gl/ubo.h b/gl/ubo.h index e4cb7c00..d5335b21 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -29,7 +29,7 @@ namespace gl void update(const uint8_t *data, int offset, GLsizeiptr size); template void update(const T &data, size_t offset = 0) { - update(reinterpret_cast(&data), offset, sizeof(data)); + update(reinterpret_cast(&data), static_cast(offset), sizeof(data)); } }; diff --git a/gl/vao.cpp b/gl/vao.cpp index 6d1e055d..e984ea3b 100644 --- a/gl/vao.cpp +++ b/gl/vao.cpp @@ -31,7 +31,7 @@ void gl::vao::setup_attrib(gl::buffer &buffer, int attrib, int size, int type, i else { if (attrib == 0) params.clear(); - params.push_back({buffer, attrib, size, type, stride, offset}); + params.emplace_back(buffer, attrib, size, type, stride, offset); active = nullptr; } } @@ -60,14 +60,14 @@ void gl::vao::bind() glBindVertexArray(*this); } else { - for (attrib_params ¶m : params) { + for (attrib_params const ¶m : params) { param.buffer.bind(gl::buffer::ARRAY_BUFFER); glVertexAttribPointer(param.attrib, param.size, param.type, GL_FALSE, param.stride, reinterpret_cast(param.offset)); glEnableVertexAttribArray(param.attrib); } for (size_t i = params.size(); i < 5; i++) - glDisableVertexAttribArray(i); + glDisableVertexAttribArray(static_cast(i)); if (ebo) ebo->bind(gl::buffer::ELEMENT_ARRAY_BUFFER); @@ -84,6 +84,6 @@ void gl::vao::unbind() } else { for (size_t i = 0; i < 4; i++) - glDisableVertexAttribArray(i); + glDisableVertexAttribArray(static_cast(i)); } } diff --git a/gl/vao.h b/gl/vao.h index a4415d03..0c017032 100644 --- a/gl/vao.h +++ b/gl/vao.h @@ -6,7 +6,7 @@ namespace gl { - class vao : object, public bindable + class vao : private object, public bindable { struct attrib_params { // TBD: should be shared_ptr? (when buffer is destroyed by owner VAO could still potentially exist) diff --git a/global_include/interfaces/IMaterial.h b/global_include/interfaces/IMaterial.h index eaf7268f..c6f3d123 100644 --- a/global_include/interfaces/IMaterial.h +++ b/global_include/interfaces/IMaterial.h @@ -19,42 +19,44 @@ struct IMaterial virtual texture_handle GetTexture(int slot) const = 0; static IMaterial *null_material() { - static struct NullMaterial : public IMaterial + struct NullMaterial : public IMaterial { - virtual void finalize(bool Loadnow) override {} - virtual bool update() override + void finalize(bool Loadnow) override { /* null implementation, nothing to do */ } + bool update() override { return false; } - virtual float get_or_guess_opacity() const override + float get_or_guess_opacity() const override { return 1.f; } - virtual bool is_translucent() const override + bool is_translucent() const override { return false; } - virtual glm::vec2 GetSize() const override + glm::vec2 GetSize() const override { return {-1.f, -1.f}; } - virtual std::string GetName() const override + std::string GetName() const override { return ""; } - virtual std::optional GetSelfillum() const override + std::optional GetSelfillum() const override { return std::nullopt; } - virtual int GetShadowRank() const override + int GetShadowRank() const override { return 0; } - virtual texture_handle GetTexture(int slot) const override + texture_handle GetTexture(int slot) const override { return 0; } - } null_material{}; + }; + static NullMaterial null_material{}; return &null_material; } + virtual ~IMaterial() = default; }; \ No newline at end of file diff --git a/global_include/interfaces/ITexture.h b/global_include/interfaces/ITexture.h index 8a1a6796..ce123829 100644 --- a/global_include/interfaces/ITexture.h +++ b/global_include/interfaces/ITexture.h @@ -1,6 +1,6 @@ #pragma once -typedef int texture_handle; +using texture_handle = int; #define null_handle (0) @@ -23,54 +23,56 @@ struct ITexture virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) = 0; static ITexture *null_texture() { - static struct NullTexture : public ITexture + struct NullTexture : public ITexture { - virtual bool create(bool Static = false) override + bool create(bool Static = false) override { return false; } - virtual bool is_stub() const override + bool is_stub() const override { return false; } - virtual int get_width() const override + int get_width() const override { return 1; } - virtual int get_height() const override + int get_height() const override { return 1; } - virtual size_t get_id() const override + size_t get_id() const override { return 0; } - virtual void release() override {} - virtual void make_stub() override {} - virtual std::string_view get_traits() const override + void release() override { /* null implementation, nothing to do */ } + void make_stub() override { /* null implementation, nothing to do */ } + std::string_view get_traits() const override { return ""; } - virtual std::string_view get_name() const override + std::string_view get_name() const override { return ""; } - virtual std::string_view get_type() const override + std::string_view get_type() const override { return ""; } - virtual bool get_has_alpha() const override + bool get_has_alpha() const override { return false; } - virtual bool get_is_ready() const override + bool get_is_ready() const override { return false; } - virtual void set_components_hint(int hint) override {} - virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) override {} - virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) override {} - } null_texture{}; + void set_components_hint(int hint) override { /* null implementation, nothing to do */ } + void make_from_memory(size_t width, size_t height, const uint8_t *data) override { /* null implementation, nothing to do */ } + void update_from_memory(size_t width, size_t height, const uint8_t *data) override { /* null implementation, nothing to do */ } + }; + static NullTexture null_texture{}; return &null_texture; } + virtual ~ITexture() = default; }; \ No newline at end of file diff --git a/input/command.cpp b/input/command.cpp index 9a373fef..d7966f37 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -408,7 +408,7 @@ commanddescription_sequence Commands_descriptions = { }; // Maps of command and coresponding strings -std::unordered_map commandMap = { +std::unordered_map const commandMap = { {"aidriverdisable", user_command::aidriverdisable}, {"jointcontrollerset", user_command::jointcontrollerset}, {"mastercontrollerincrease", user_command::mastercontrollerincrease}, @@ -796,12 +796,12 @@ std::unordered_map commandMap = { void command_queue::update() { double delta = Timer::GetDeltaTime(); - for (auto c : m_active_continuous) + for (auto [activecommand, activerecipient] : m_active_continuous) { - command_data data({c.first, GLFW_REPEAT, 0.0, 0.0, delta, false, glm::vec3()}); // todo: improve - auto lookup = m_commands.emplace( c.second, commanddata_sequence() ); + command_data data({activecommand, GLFW_REPEAT, 0.0, 0.0, delta, false, glm::vec3()}); // todo: improve + auto [queueiterator, queueinserted] = m_commands.try_emplace( activerecipient, commanddata_sequence() ); // recipient stack was either located or created, so we can add to it quite safely - lookup.first->second.emplace_back( data ); + queueiterator->second.emplace_back( data ); } } @@ -809,16 +809,15 @@ void command_queue::update() void command_queue::push( command_data const &Command, uint32_t const Recipient ) { if (is_network_target(Recipient)) { - auto lookup = m_intercept_queue.emplace(Recipient, commanddata_sequence()); - lookup.first->second.emplace_back(Command); + auto [queueiterator, queueinserted] = m_intercept_queue.try_emplace(Recipient, commanddata_sequence()); + queueiterator->second.emplace_back(Command); } else { push_direct(Command, Recipient); } } void command_queue::push_direct(const command_data &Command, const uint32_t Recipient) { - auto const &desc = simulation::Commands_descriptions[ static_cast( Command.command ) ]; - if (desc.mode == command_mode::continuous) + if (auto const &desc = simulation::Commands_descriptions[ static_cast( Command.command ) ]; desc.mode == command_mode::continuous) { if (Command.action == GLFW_PRESS) m_active_continuous.emplace(std::make_pair(Command.command, Recipient)); @@ -828,9 +827,9 @@ void command_queue::push_direct(const command_data &Command, const uint32_t Reci return; } - auto lookup = m_commands.emplace( Recipient, commanddata_sequence() ); + auto [queueiterator, queueinserted] = m_commands.try_emplace( Recipient, commanddata_sequence() ); // recipient stack was either located or created, so we can add to it quite safely - lookup.first->second.emplace_back( Command ); + queueiterator->second.emplace_back( Command ); } // retrieves oldest posted command for specified recipient, if any. returns: true on retrieval, false if there's nothing to retrieve @@ -854,10 +853,9 @@ command_queue::pop( command_data &Command, uint32_t const Recipient ) { return true; } -bool command_queue::is_network_target(uint32_t const Recipient) { - const command_target target = (command_target)(Recipient & ~0xffff); +bool command_queue::is_network_target(uint32_t const Recipient) const { - if (target == command_target::entity) + if (const auto target = (command_target)(Recipient & ~0xffff); target == command_target::entity) return false; return true; @@ -870,9 +868,9 @@ command_queue::commands_map command_queue::pop_intercept_queue() { } void command_queue::push_commands(const commands_map &commands) { - for (auto const &kv : commands) - for (command_data const &data : kv.second) - push_direct(data, kv.first); + for (auto const &[recipient, sequence] : commands) + for (command_data const &data : sequence) + push_direct(data, recipient); } void diff --git a/input/command.h b/input/command.h index 7ff5b272..e03622a9 100644 --- a/input/command.h +++ b/input/command.h @@ -455,8 +455,8 @@ class command_queue { public: // types - typedef std::deque commanddata_sequence; - typedef std::unordered_map commands_map; + using commanddata_sequence = std::deque; + using commands_map = std::unordered_map; // methods // posts specified command for specified recipient into m_intercept_queue void @@ -469,7 +469,7 @@ public: update(); // checks if given command must be scheduled on server bool - is_network_target(const uint32_t Recipient); + is_network_target(const uint32_t Recipient) const; // pops commands from intercept queue commands_map pop_intercept_queue(); @@ -511,13 +511,13 @@ void add_to_dequemap(std::unordered_map> &lhs, const std::unord // but realistically it's not like we're going to run more than one simulation at a time namespace simulation { -typedef std::vector commanddescription_sequence; +using commanddescription_sequence = std::vector; extern command_queue Commands; // TODO: add name to command map, and wrap these two into helper object extern commanddescription_sequence Commands_descriptions; -extern std::unordered_map commandMap; +extern std::unordered_map const commandMap; } // command_relay: composite class component, passes specified command to appropriate command stack @@ -530,7 +530,6 @@ public: void post(user_command const Command, double const Param1, double const Param2, int const Action, uint16_t Recipient, glm::vec3 Position = glm::vec3(0.0f) , const std::string *Payload = nullptr) const; -private: // types // members }; diff --git a/input/driverkeyboardinput.cpp b/input/driverkeyboardinput.cpp index 48c8c1fc..e7e636b3 100644 --- a/input/driverkeyboardinput.cpp +++ b/input/driverkeyboardinput.cpp @@ -22,276 +22,277 @@ driverkeyboard_input::init() { void driverkeyboard_input::default_bindings() { + using enum user_command; m_bindingsetups = { - { user_command::aidriverenable, {GLFW_KEY_Q | keymodifier::shift, ""} }, - { user_command::aidriverdisable, {GLFW_KEY_Q, ""} }, + { aidriverenable, {GLFW_KEY_Q | keymodifier::shift, ""} }, + { aidriverdisable, {GLFW_KEY_Q, ""} }, // jointcontrollerset, - { user_command::mastercontrollerincrease, {GLFW_KEY_KP_ADD, ""} }, - { user_command::mastercontrollerincreasefast, {GLFW_KEY_KP_ADD | keymodifier::shift, ""} }, - { user_command::mastercontrollerdecrease, {GLFW_KEY_KP_SUBTRACT, ""} }, - { user_command::mastercontrollerdecreasefast, {GLFW_KEY_KP_SUBTRACT | keymodifier::shift, ""} }, + { mastercontrollerincrease, {GLFW_KEY_KP_ADD, ""} }, + { mastercontrollerincreasefast, {GLFW_KEY_KP_ADD | keymodifier::shift, ""} }, + { mastercontrollerdecrease, {GLFW_KEY_KP_SUBTRACT, ""} }, + { mastercontrollerdecreasefast, {GLFW_KEY_KP_SUBTRACT | keymodifier::shift, ""} }, // mastercontrollerset, - { user_command::dynamicbrakecontrollerincrease, {GLFW_KEY_KP_3 | keymodifier::control, ""} }, - { user_command::dynamicbrakecontrollerdecrease, {GLFW_KEY_KP_9 | keymodifier::control, ""} }, + { dynamicbrakecontrollerincrease, {GLFW_KEY_KP_3 | keymodifier::control, ""} }, + { dynamicbrakecontrollerdecrease, {GLFW_KEY_KP_9 | keymodifier::control, ""} }, // mastercontrollerset, - { user_command::dynamicbrakecontrollerincreasefast, {GLFW_KEY_KP_3 | keymodifier::control | keymodifier::shift, ""} }, - { user_command::dynamicbrakecontrollerdecreasefast, {GLFW_KEY_KP_9 | keymodifier::control | keymodifier::shift, ""} }, + { dynamicbrakecontrollerincreasefast, {GLFW_KEY_KP_3 | keymodifier::control | keymodifier::shift, ""} }, + { dynamicbrakecontrollerdecreasefast, {GLFW_KEY_KP_9 | keymodifier::control | keymodifier::shift, ""} }, - { user_command::secondcontrollerincrease, {GLFW_KEY_KP_DIVIDE, ""} }, - { user_command::secondcontrollerincreasefast, {GLFW_KEY_KP_DIVIDE | keymodifier::shift, ""} }, - { user_command::secondcontrollerdecrease, {GLFW_KEY_KP_MULTIPLY, ""} }, - { user_command::secondcontrollerdecreasefast, {GLFW_KEY_KP_MULTIPLY | keymodifier::shift, ""} }, + { secondcontrollerincrease, {GLFW_KEY_KP_DIVIDE, ""} }, + { secondcontrollerincreasefast, {GLFW_KEY_KP_DIVIDE | keymodifier::shift, ""} }, + { secondcontrollerdecrease, {GLFW_KEY_KP_MULTIPLY, ""} }, + { secondcontrollerdecreasefast, {GLFW_KEY_KP_MULTIPLY | keymodifier::shift, ""} }, // secondcontrollerset, - { user_command::mucurrentindicatorothersourceactivate, {GLFW_KEY_Z | keymodifier::shift, ""} }, - { user_command::independentbrakeincrease, {GLFW_KEY_KP_1, ""} }, - { user_command::independentbrakeincreasefast, {GLFW_KEY_KP_1 | keymodifier::shift, ""} }, - { user_command::independentbrakedecrease, {GLFW_KEY_KP_7, ""} }, - { user_command::independentbrakedecreasefast, {GLFW_KEY_KP_7 | keymodifier::shift, ""} }, + { mucurrentindicatorothersourceactivate, {GLFW_KEY_Z | keymodifier::shift, ""} }, + { independentbrakeincrease, {GLFW_KEY_KP_1, ""} }, + { independentbrakeincreasefast, {GLFW_KEY_KP_1 | keymodifier::shift, ""} }, + { independentbrakedecrease, {GLFW_KEY_KP_7, ""} }, + { independentbrakedecreasefast, {GLFW_KEY_KP_7 | keymodifier::shift, ""} }, // independentbrakeset, - { user_command::independentbrakebailoff, {GLFW_KEY_KP_4, ""} }, + { independentbrakebailoff, {GLFW_KEY_KP_4, ""} }, // universalbrakebutton1, // universalbrakebutton2, // universalbrakebutton3, - { user_command::trainbrakeincrease, {GLFW_KEY_KP_3, ""} }, - { user_command::trainbrakedecrease, {GLFW_KEY_KP_9, ""} }, + { trainbrakeincrease, {GLFW_KEY_KP_3, ""} }, + { trainbrakedecrease, {GLFW_KEY_KP_9, ""} }, // trainbrakeset, - { user_command::trainbrakecharging, {GLFW_KEY_KP_DECIMAL, ""} }, - { user_command::trainbrakerelease, {GLFW_KEY_KP_6, ""} }, - { user_command::trainbrakefirstservice, {GLFW_KEY_KP_8, ""} }, - { user_command::trainbrakeservice, {GLFW_KEY_KP_5, ""} }, - { user_command::trainbrakefullservice, {GLFW_KEY_KP_2, ""} }, - { user_command::trainbrakehandleoff, {GLFW_KEY_KP_5 | keymodifier::control, ""} }, - { user_command::trainbrakeemergency, {GLFW_KEY_KP_0, ""} }, - { user_command::trainbrakebasepressureincrease, {GLFW_KEY_KP_3 | keymodifier::control, ""} }, - { user_command::trainbrakebasepressuredecrease, {GLFW_KEY_KP_9 | keymodifier::control, ""} }, - { user_command::trainbrakebasepressurereset, {GLFW_KEY_KP_6 | keymodifier::control, ""} }, - { user_command::trainbrakeoperationtoggle, {GLFW_KEY_KP_4 | keymodifier::control, ""} }, - { user_command::manualbrakeincrease, {GLFW_KEY_KP_1 | keymodifier::control, ""} }, - { user_command::manualbrakedecrease, {GLFW_KEY_KP_7 | keymodifier::control, ""} }, - { user_command::alarmchaintoggle, {GLFW_KEY_B | keymodifier::shift | keymodifier::control, ""} }, + { trainbrakecharging, {GLFW_KEY_KP_DECIMAL, ""} }, + { trainbrakerelease, {GLFW_KEY_KP_6, ""} }, + { trainbrakefirstservice, {GLFW_KEY_KP_8, ""} }, + { trainbrakeservice, {GLFW_KEY_KP_5, ""} }, + { trainbrakefullservice, {GLFW_KEY_KP_2, ""} }, + { trainbrakehandleoff, {GLFW_KEY_KP_5 | keymodifier::control, ""} }, + { trainbrakeemergency, {GLFW_KEY_KP_0, ""} }, + { trainbrakebasepressureincrease, {GLFW_KEY_KP_3 | keymodifier::control, ""} }, + { trainbrakebasepressuredecrease, {GLFW_KEY_KP_9 | keymodifier::control, ""} }, + { trainbrakebasepressurereset, {GLFW_KEY_KP_6 | keymodifier::control, ""} }, + { trainbrakeoperationtoggle, {GLFW_KEY_KP_4 | keymodifier::control, ""} }, + { manualbrakeincrease, {GLFW_KEY_KP_1 | keymodifier::control, ""} }, + { manualbrakedecrease, {GLFW_KEY_KP_7 | keymodifier::control, ""} }, + { alarmchaintoggle, {GLFW_KEY_B | keymodifier::shift | keymodifier::control, ""} }, // alarmchainenable, // alarmchaindisable, - { user_command::wheelspinbrakeactivate, {GLFW_KEY_KP_ENTER, ""} }, - { user_command::sandboxactivate, {GLFW_KEY_S | keymodifier::shift, ""} }, + { wheelspinbrakeactivate, {GLFW_KEY_KP_ENTER, ""} }, + { sandboxactivate, {GLFW_KEY_S | keymodifier::shift, ""} }, // autosandboxtoggle, // autosandboxactivate, // autosandboxdeactivate, - { user_command::reverserincrease, {GLFW_KEY_D, ""} }, - { user_command::reverserdecrease, {GLFW_KEY_R, ""} }, + { reverserincrease, {GLFW_KEY_D, ""} }, + { reverserdecrease, {GLFW_KEY_R, ""} }, // reverserforwardhigh, // reverserforward, // reverserneutral, // reverserbackward, - { user_command::waterpumpbreakertoggle, {GLFW_KEY_W | keymodifier::control, ""} }, + { waterpumpbreakertoggle, {GLFW_KEY_W | keymodifier::control, ""} }, // waterpumpbreakerclose, // waterpumpbreakeropen, - { user_command::waterpumptoggle, {GLFW_KEY_W, ""} }, + { waterpumptoggle, {GLFW_KEY_W, ""} }, // waterpumpenable, // waterpumpdisable, - { user_command::waterheaterbreakertoggle, {GLFW_KEY_W | keymodifier::control | keymodifier::shift, ""} }, + { waterheaterbreakertoggle, {GLFW_KEY_W | keymodifier::control | keymodifier::shift, ""} }, // waterheaterbreakerclose, // waterheaterbreakeropen, - { user_command::waterheatertoggle, {GLFW_KEY_W | keymodifier::shift, ""} }, + { waterheatertoggle, {GLFW_KEY_W | keymodifier::shift, ""} }, // waterheaterenable, // waterheaterdisable, - { user_command::watercircuitslinktoggle, {GLFW_KEY_H | keymodifier::shift, ""} }, + { watercircuitslinktoggle, {GLFW_KEY_H | keymodifier::shift, ""} }, // watercircuitslinkenable, // watercircuitslinkdisable, - { user_command::fuelpumptoggle, {GLFW_KEY_F, ""} }, + { fuelpumptoggle, {GLFW_KEY_F, ""} }, // fuelpumpenable, // fuelpumpdisable, - { user_command::oilpumptoggle, {GLFW_KEY_F | keymodifier::shift, ""} }, + { oilpumptoggle, {GLFW_KEY_F | keymodifier::shift, ""} }, // oilpumpenable, // oilpumpdisable, - { user_command::linebreakertoggle, {GLFW_KEY_M, ""} }, + { linebreakertoggle, {GLFW_KEY_M, ""} }, // linebreakeropen, // linebreakerclose, - { user_command::convertertoggle, {GLFW_KEY_X, ""} }, + { convertertoggle, {GLFW_KEY_X, ""} }, // converterenable, // converterdisable, - { user_command::convertertogglelocal, {GLFW_KEY_X | keymodifier::shift, ""} }, - { user_command::converteroverloadrelayreset, {GLFW_KEY_N | keymodifier::control, ""} }, - { user_command::compressortoggle, {GLFW_KEY_C, ""} }, + { convertertogglelocal, {GLFW_KEY_X | keymodifier::shift, ""} }, + { converteroverloadrelayreset, {GLFW_KEY_N | keymodifier::control, ""} }, + { compressortoggle, {GLFW_KEY_C, ""} }, // compressorenable, // compressordisable, - { user_command::compressortogglelocal, {GLFW_KEY_C | keymodifier::shift, ""} }, + { compressortogglelocal, {GLFW_KEY_C | keymodifier::shift, ""} }, // compressorpresetactivatenext, // compressorpresetactivateprevious, // compressorpresetactivatedefault, - { user_command::motoroverloadrelaythresholdtoggle, {GLFW_KEY_F | keymodifier::control, ""} }, + { motoroverloadrelaythresholdtoggle, {GLFW_KEY_F | keymodifier::control, ""} }, // motoroverloadrelaythresholdsetlow, // motoroverloadrelaythresholdsethigh, - { user_command::motoroverloadrelayreset, {GLFW_KEY_N, ""} }, + { motoroverloadrelayreset, {GLFW_KEY_N, ""} }, // universalrelayreset1, // universalrelayreset2, // universalrelayreset3, - { user_command::notchingrelaytoggle, {GLFW_KEY_G, ""} }, - { user_command::epbrakecontroltoggle, {GLFW_KEY_Z | keymodifier::control, ""} }, + { notchingrelaytoggle, {GLFW_KEY_G, ""} }, + { epbrakecontroltoggle, {GLFW_KEY_Z | keymodifier::control, ""} }, // epbrakecontrolenable // epbrakecontroldisable - { user_command::trainbrakeoperationmodeincrease, {GLFW_KEY_KP_2 | keymodifier::control, ""} }, - { user_command::trainbrakeoperationmodedecrease, {GLFW_KEY_KP_8 | keymodifier::control, ""} }, - { user_command::brakeactingspeedincrease, {GLFW_KEY_B | keymodifier::shift, ""} }, - { user_command::brakeactingspeeddecrease, {GLFW_KEY_B, ""} }, + { trainbrakeoperationmodeincrease, {GLFW_KEY_KP_2 | keymodifier::control, ""} }, + { trainbrakeoperationmodedecrease, {GLFW_KEY_KP_8 | keymodifier::control, ""} }, + { brakeactingspeedincrease, {GLFW_KEY_B | keymodifier::shift, ""} }, + { brakeactingspeeddecrease, {GLFW_KEY_B, ""} }, // brakeactingspeedsetcargo, // brakeactingspeedsetpassenger, // brakeactingspeedsetrapid, - { user_command::brakeloadcompensationincrease, {GLFW_KEY_H | keymodifier::shift | keymodifier::control, ""} }, - { user_command::brakeloadcompensationdecrease, {GLFW_KEY_H | keymodifier::control, ""} }, - { user_command::mubrakingindicatortoggle, {GLFW_KEY_L | keymodifier::shift, ""} }, - { user_command::alerteracknowledge, {GLFW_KEY_SPACE, ""} }, - { user_command::hornlowactivate, {GLFW_KEY_A, ""} }, - { user_command::hornhighactivate, {GLFW_KEY_S, ""} }, - { user_command::whistleactivate, {GLFW_KEY_Z, ""} }, - { user_command::radiotoggle, {GLFW_KEY_R | keymodifier::control, ""} }, + { brakeloadcompensationincrease, {GLFW_KEY_H | keymodifier::shift | keymodifier::control, ""} }, + { brakeloadcompensationdecrease, {GLFW_KEY_H | keymodifier::control, ""} }, + { mubrakingindicatortoggle, {GLFW_KEY_L | keymodifier::shift, ""} }, + { alerteracknowledge, {GLFW_KEY_SPACE, ""} }, + { hornlowactivate, {GLFW_KEY_A, ""} }, + { hornhighactivate, {GLFW_KEY_S, ""} }, + { whistleactivate, {GLFW_KEY_Z, ""} }, + { radiotoggle, {GLFW_KEY_R | keymodifier::control, ""} }, // radioenable // radiodisable - { user_command::radiochannelincrease, {GLFW_KEY_EQUAL, ""} }, - { user_command::radiochanneldecrease, {GLFW_KEY_MINUS, ""} }, + { radiochannelincrease, {GLFW_KEY_EQUAL, ""} }, + { radiochanneldecrease, {GLFW_KEY_MINUS, ""} }, // radiochannelset - { user_command::radiostopsend, {GLFW_KEY_PAUSE | keymodifier::shift | keymodifier::control, ""} }, + { radiostopsend, {GLFW_KEY_PAUSE | keymodifier::shift | keymodifier::control, ""} }, // radiostopenable // radiostopdisable - { user_command::radiostoptest, {GLFW_KEY_R | keymodifier::shift | keymodifier::control, ""} }, - { user_command::radiocall3send, {GLFW_KEY_BACKSPACE, ""} }, + { radiostoptest, {GLFW_KEY_R | keymodifier::shift | keymodifier::control, ""} }, + { radiocall3send, {GLFW_KEY_BACKSPACE, ""} }, // radiovolumeincrease, // radiovolumedecrease, // radiovolumeset, - { user_command::cabchangeforward, {GLFW_KEY_HOME, ""} }, - { user_command::cabchangebackward, {GLFW_KEY_END, ""} }, + { cabchangeforward, {GLFW_KEY_HOME, ""} }, + { cabchangebackward, {GLFW_KEY_END, ""} }, // viewturn, // movehorizontal, // movehorizontalfast, // movevertical, // moveverticalfast, - { user_command::moveleft, {GLFW_KEY_LEFT, "Move left"} }, - { user_command::moveright, {GLFW_KEY_RIGHT, "Move right"} }, - { user_command::moveforward, {GLFW_KEY_UP, "Move forwards"} }, - { user_command::moveback, {GLFW_KEY_DOWN, "Move backwards"} }, - { user_command::moveup, {GLFW_KEY_PAGE_UP, "Move up"} }, - { user_command::movedown, {GLFW_KEY_PAGE_DOWN, "Move down"} }, - { user_command::nearestcarcouplingincrease, {GLFW_KEY_INSERT, ""} }, - { user_command::nearestcarcouplingdisconnect, {GLFW_KEY_DELETE, ""} }, - { user_command::nearestcarcoupleradapterattach, {GLFW_KEY_INSERT | keymodifier::control, ""} }, - { user_command::nearestcarcoupleradapterremove, {GLFW_KEY_DELETE | keymodifier::control, ""} }, - { user_command::occupiedcarcouplingdisconnect, {GLFW_KEY_DELETE | keymodifier::shift, ""} }, - { user_command::doortoggleleft, {GLFW_KEY_COMMA, ""} }, - { user_command::doortoggleright, {GLFW_KEY_PERIOD, ""} }, - { user_command::doorpermitleft, {GLFW_KEY_COMMA | keymodifier::shift, ""} }, - { user_command::doorpermitright, {GLFW_KEY_PERIOD | keymodifier::shift, ""} }, - { user_command::doorpermitpresetactivatenext, {GLFW_KEY_PERIOD | keymodifier::shift | keymodifier::control, ""} }, - { user_command::doorpermitpresetactivateprevious, {GLFW_KEY_COMMA | keymodifier::shift | keymodifier::control, ""} }, + { moveleft, {GLFW_KEY_LEFT, "Move left"} }, + { moveright, {GLFW_KEY_RIGHT, "Move right"} }, + { moveforward, {GLFW_KEY_UP, "Move forwards"} }, + { moveback, {GLFW_KEY_DOWN, "Move backwards"} }, + { moveup, {GLFW_KEY_PAGE_UP, "Move up"} }, + { movedown, {GLFW_KEY_PAGE_DOWN, "Move down"} }, + { nearestcarcouplingincrease, {GLFW_KEY_INSERT, ""} }, + { nearestcarcouplingdisconnect, {GLFW_KEY_DELETE, ""} }, + { nearestcarcoupleradapterattach, {GLFW_KEY_INSERT | keymodifier::control, ""} }, + { nearestcarcoupleradapterremove, {GLFW_KEY_DELETE | keymodifier::control, ""} }, + { occupiedcarcouplingdisconnect, {GLFW_KEY_DELETE | keymodifier::shift, ""} }, + { doortoggleleft, {GLFW_KEY_COMMA, ""} }, + { doortoggleright, {GLFW_KEY_PERIOD, ""} }, + { doorpermitleft, {GLFW_KEY_COMMA | keymodifier::shift, ""} }, + { doorpermitright, {GLFW_KEY_PERIOD | keymodifier::shift, ""} }, + { doorpermitpresetactivatenext, {GLFW_KEY_PERIOD | keymodifier::shift | keymodifier::control, ""} }, + { doorpermitpresetactivateprevious, {GLFW_KEY_COMMA | keymodifier::shift | keymodifier::control, ""} }, // dooropenleft, // dooropenright, - { user_command::dooropenall, {GLFW_KEY_SLASH | keymodifier::shift, ""} }, + { dooropenall, {GLFW_KEY_SLASH | keymodifier::shift, ""} }, // doorcloseleft, // doorcloseright, - { user_command::doorcloseall, {GLFW_KEY_SLASH | keymodifier::control, ""} }, + { doorcloseall, {GLFW_KEY_SLASH | keymodifier::control, ""} }, // doorsteptoggle, - { user_command::doormodetoggle, {GLFW_KEY_SLASH | keymodifier::shift | keymodifier::control, ""} }, + { doormodetoggle, {GLFW_KEY_SLASH | keymodifier::shift | keymodifier::control, ""} }, // mirrorstoggle, - { user_command::departureannounce, {GLFW_KEY_SLASH, ""} }, - { user_command::doorlocktoggle, {GLFW_KEY_S | keymodifier::control, ""} }, - { user_command::pantographcompressorvalvetoggle, {GLFW_KEY_V | keymodifier::control, ""} }, + { departureannounce, {GLFW_KEY_SLASH, ""} }, + { doorlocktoggle, {GLFW_KEY_S | keymodifier::control, ""} }, + { pantographcompressorvalvetoggle, {GLFW_KEY_V | keymodifier::control, ""} }, // pantographcompressorvalveenable, // pantographcompressorvalvedisable, - { user_command::pantographcompressoractivate, {GLFW_KEY_V | keymodifier::shift, ""} }, - { user_command::pantographtogglefront, {GLFW_KEY_P, ""} }, - { user_command::pantographtogglerear, {GLFW_KEY_O, ""} }, + { pantographcompressoractivate, {GLFW_KEY_V | keymodifier::shift, ""} }, + { pantographtogglefront, {GLFW_KEY_P, ""} }, + { pantographtogglerear, {GLFW_KEY_O, ""} }, // pantographraisefront, // pantographraiserear, // pantographlowerfront, // pantographlowerrear, - { user_command::pantographlowerall, {GLFW_KEY_P | keymodifier::control, ""} }, - { user_command::pantographselectnext, {GLFW_KEY_P | keymodifier::shift, ""} }, - { user_command::pantographselectprevious, {GLFW_KEY_O | keymodifier::shift, ""} }, - { user_command::pantographtoggleselected, {GLFW_KEY_O | keymodifier::shift | keymodifier::control, ""} }, + { pantographlowerall, {GLFW_KEY_P | keymodifier::control, ""} }, + { pantographselectnext, {GLFW_KEY_P | keymodifier::shift, ""} }, + { pantographselectprevious, {GLFW_KEY_O | keymodifier::shift, ""} }, + { pantographtoggleselected, {GLFW_KEY_O | keymodifier::shift | keymodifier::control, ""} }, // pantographraiseselected, // pantographlowerselected, // pantographvalvesupdate, // pantographvalvesoff, - { user_command::heatingtoggle, {GLFW_KEY_H, ""} }, + { heatingtoggle, {GLFW_KEY_H, ""} }, // heatingenable, // heatingdisable, - { user_command::lightspresetactivatenext, {GLFW_KEY_T | keymodifier::shift, ""} }, - { user_command::lightspresetactivateprevious, {GLFW_KEY_T, ""} }, - { user_command::headlighttoggleleft, {GLFW_KEY_Y, ""} }, + { lightspresetactivatenext, {GLFW_KEY_T | keymodifier::shift, ""} }, + { lightspresetactivateprevious, {GLFW_KEY_T, ""} }, + { headlighttoggleleft, {GLFW_KEY_Y, ""} }, // headlightenableleft, // headlightdisableleft, - { user_command::headlighttoggleright, {GLFW_KEY_I, ""} }, + { headlighttoggleright, {GLFW_KEY_I, ""} }, // headlightenableright, // headlightdisableright, - { user_command::headlighttoggleupper, {GLFW_KEY_U, ""} }, + { headlighttoggleupper, {GLFW_KEY_U, ""} }, // headlightenableupper, // headlightdisableupper, - { user_command::redmarkertoggleleft, {GLFW_KEY_Y | keymodifier::shift, ""} }, + { redmarkertoggleleft, {GLFW_KEY_Y | keymodifier::shift, ""} }, // redmarkerenableleft, // redmarkerdisableleft, - { user_command::redmarkertoggleright, {GLFW_KEY_I | keymodifier::shift, ""} }, + { redmarkertoggleright, {GLFW_KEY_I | keymodifier::shift, ""} }, // redmarkerenableright, // redmarkerdisableright, - { user_command::headlighttogglerearleft, {GLFW_KEY_Y | keymodifier::control, ""} }, + { headlighttogglerearleft, {GLFW_KEY_Y | keymodifier::control, ""} }, // headlightenablerearleft // headlightdisablerearleft - { user_command::headlighttogglerearright, {GLFW_KEY_I | keymodifier::control, ""} }, + { headlighttogglerearright, {GLFW_KEY_I | keymodifier::control, ""} }, // headlightenablerearright // headlightdisablerearright - { user_command::headlighttogglerearupper, {GLFW_KEY_U | keymodifier::control, ""} }, + { headlighttogglerearupper, {GLFW_KEY_U | keymodifier::control, ""} }, // headlightenablerearupper // headlightdisablerearupper - { user_command::redmarkertogglerearleft, {GLFW_KEY_Y | keymodifier::control | keymodifier::shift, ""} }, + { redmarkertogglerearleft, {GLFW_KEY_Y | keymodifier::control | keymodifier::shift, ""} }, // redmarkerenablerearleft // redmarkerdisablerearleft - { user_command::redmarkertogglerearright, {GLFW_KEY_I | keymodifier::control | keymodifier::shift, ""} }, + { redmarkertogglerearright, {GLFW_KEY_I | keymodifier::control | keymodifier::shift, ""} }, // redmarkerenablerearright // redmarkerdisablerearright - { user_command::redmarkerstoggle, {GLFW_KEY_E | keymodifier::shift, ""} }, - { user_command::endsignalstoggle, {GLFW_KEY_E, ""} }, - { user_command::headlightsdimtoggle, {GLFW_KEY_L | keymodifier::control, ""} }, + { redmarkerstoggle, {GLFW_KEY_E | keymodifier::shift, ""} }, + { endsignalstoggle, {GLFW_KEY_E, ""} }, + { headlightsdimtoggle, {GLFW_KEY_L | keymodifier::control, ""} }, // headlightsdimenable, // headlightsdimdisable, - { user_command::motorconnectorsopen, {GLFW_KEY_L, ""} }, + { motorconnectorsopen, {GLFW_KEY_L, ""} }, // motorconnectorsclose, - { user_command::motordisconnect, {GLFW_KEY_E | keymodifier::control, ""} }, - { user_command::interiorlighttoggle, {GLFW_KEY_APOSTROPHE, ""} }, + { motordisconnect, {GLFW_KEY_E | keymodifier::control, ""} }, + { interiorlighttoggle, {GLFW_KEY_APOSTROPHE, ""} }, // interiorlightenable, // interiorlightdisable, - { user_command::interiorlightdimtoggle, {GLFW_KEY_APOSTROPHE | keymodifier::control, ""} }, + { interiorlightdimtoggle, {GLFW_KEY_APOSTROPHE | keymodifier::control, ""} }, // interiorlightdimenable, // interiorlightdimdisable, // compartmentlightstoggle, // compartmentlightsenable, // compartmentlightsdisable, - { user_command::instrumentlighttoggle, {GLFW_KEY_SEMICOLON, ""} }, + { instrumentlighttoggle, {GLFW_KEY_SEMICOLON, ""} }, // instrumentlightenable, // instrumentlightdisable, - { user_command::dashboardlighttoggle, {GLFW_KEY_SEMICOLON | keymodifier::shift, ""} }, + { dashboardlighttoggle, {GLFW_KEY_SEMICOLON | keymodifier::shift, ""} }, // dashboardlightenable // dashboardlightdisable - { user_command::timetablelighttoggle, {GLFW_KEY_APOSTROPHE | keymodifier::shift, ""} }, + { timetablelighttoggle, {GLFW_KEY_APOSTROPHE | keymodifier::shift, ""} }, // timetablelightenable // timetablelightdisable - { user_command::generictoggle0, {GLFW_KEY_0, ""} }, - { user_command::generictoggle1, {GLFW_KEY_1, ""} }, - { user_command::generictoggle2, {GLFW_KEY_2, ""} }, - { user_command::generictoggle3, {GLFW_KEY_3, ""} }, - { user_command::generictoggle4, {GLFW_KEY_4, ""} }, - { user_command::generictoggle5, {GLFW_KEY_5, ""} }, - { user_command::generictoggle6, {GLFW_KEY_6, ""} }, - { user_command::generictoggle7, {GLFW_KEY_7, ""} }, - { user_command::generictoggle8, {GLFW_KEY_8, ""} }, - { user_command::generictoggle9, {GLFW_KEY_9, ""} }, - { user_command::batterytoggle, {GLFW_KEY_J, ""} }, + { generictoggle0, {GLFW_KEY_0, ""} }, + { generictoggle1, {GLFW_KEY_1, ""} }, + { generictoggle2, {GLFW_KEY_2, ""} }, + { generictoggle3, {GLFW_KEY_3, ""} }, + { generictoggle4, {GLFW_KEY_4, ""} }, + { generictoggle5, {GLFW_KEY_5, ""} }, + { generictoggle6, {GLFW_KEY_6, ""} }, + { generictoggle7, {GLFW_KEY_7, ""} }, + { generictoggle8, {GLFW_KEY_8, ""} }, + { generictoggle9, {GLFW_KEY_9, ""} }, + { batterytoggle, {GLFW_KEY_J, ""} }, // batteryenable, // batterydisable, // cabactivationtoggle, // cabactivationenable, // cabactivationdisable, - { user_command::motorblowerstogglefront, {GLFW_KEY_N | keymodifier::shift, ""} }, - { user_command::motorblowerstogglerear, {GLFW_KEY_M | keymodifier::shift, ""} }, - { user_command::motorblowersdisableall, {GLFW_KEY_M | keymodifier::control, ""} }, + { motorblowerstogglefront, {GLFW_KEY_N | keymodifier::shift, ""} }, + { motorblowerstogglerear, {GLFW_KEY_M | keymodifier::shift, ""} }, + { motorblowersdisableall, {GLFW_KEY_M | keymodifier::control, ""} }, // coolingfanstoggle, // tempomattoggle, // springbraketoggle, @@ -317,14 +318,14 @@ driverkeyboard_input::default_bindings() { // speedcontrolbutton8, // speedcontrolbutton9, // admin_timejump, - { user_command::timejumplarge, {GLFW_KEY_F1 | keymodifier::control, "Big time jump (Debug Mode only)"} }, - { user_command::timejumpsmall, {GLFW_KEY_F1 | keymodifier::shift, "Small time jump (Debug Mode only)"} }, + { timejumplarge, {GLFW_KEY_F1 | keymodifier::control, "Big time jump (Debug Mode only)"} }, + { timejumpsmall, {GLFW_KEY_F1 | keymodifier::shift, "Small time jump (Debug Mode only)"} }, // admin_vehiclemove, - { user_command::vehiclemoveforwards, {GLFW_KEY_LEFT_BRACKET | keymodifier::control, "Move the train forwards (Debug Mode only)"} }, - { user_command::vehiclemovebackwards, {GLFW_KEY_RIGHT_BRACKET | keymodifier::control, "Move the train backwards (Debug Mode only)"} }, - { user_command::vehicleboost, {GLFW_KEY_TAB | keymodifier::control, "Boost the train (Debug Mode only)"} }, - { user_command::debugtoggle, {GLFW_KEY_F12 | keymodifier::control | keymodifier::shift, "Toggle Debug Mode"} }, - { user_command::pausetoggle, {GLFW_KEY_ESCAPE, "Pause the game"} } + { vehiclemoveforwards, {GLFW_KEY_LEFT_BRACKET | keymodifier::control, "Move the train forwards (Debug Mode only)"} }, + { vehiclemovebackwards, {GLFW_KEY_RIGHT_BRACKET | keymodifier::control, "Move the train backwards (Debug Mode only)"} }, + { vehicleboost, {GLFW_KEY_TAB | keymodifier::control, "Boost the train (Debug Mode only)"} }, + { debugtoggle, {GLFW_KEY_F12 | keymodifier::control | keymodifier::shift, "Toggle Debug Mode"} }, + { pausetoggle, {GLFW_KEY_ESCAPE, "Pause the game"} } }; } diff --git a/input/driverkeyboardinput.h b/input/driverkeyboardinput.h index 1e3f11b1..7ebf2cc5 100644 --- a/input/driverkeyboardinput.h +++ b/input/driverkeyboardinput.h @@ -21,7 +21,7 @@ public: protected: // methods void - default_bindings(); + default_bindings() override; }; //--------------------------------------------------------------------------- diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 2d5f3d24..ab3d0aaf 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -32,14 +32,15 @@ mouse_slider::bind( user_command const &Command ) { auto const *train { simulation::Train }; TMoverParameters const *vehicle { nullptr }; switch( m_command ) { - case user_command::jointcontrollerset: - case user_command::mastercontrollerset: - case user_command::secondcontrollerset: { + using enum user_command; + case jointcontrollerset: + case mastercontrollerset: + case secondcontrollerset: { vehicle = train ? train->Controlled() : nullptr; break; } - case user_command::trainbrakeset: - case user_command::independentbrakeset: { + case trainbrakeset: + case independentbrakeset: { vehicle = train ? train->Occupied() : nullptr; break; } @@ -61,7 +62,6 @@ mouse_slider::bind( user_command const &Command ) { vehicle->MainCtrlPosNo + vehicle->ScndCtrlPosNo : vehicle->MainCtrlPosNo ) }; // for simplicity upper half of the range controls power, lower controls brakes - auto const brakerangemultiplier { powerrange / LocalBrakePosNo }; m_valuerange = 1.0; m_value = @@ -133,7 +133,7 @@ mouse_slider::release() { } void -mouse_slider::on_move( double const Mousex, double const Mousey ) { +mouse_slider::on_move( double const /*Mousex*/, double const Mousey ) { auto const controlsize { Global.window_size.y * EU07_CONTROLLER_MOUSESLIDERSIZE }; auto const controledge { Global.window_size.y * 0.5 + controlsize * 0.5 }; @@ -171,11 +171,10 @@ drivermouse_input::recall_bindings() { std::string filePath = "eu07_input-mouse.ini"; - fs::path appPath = user_config_path("eu07_input-mouse.ini"); - if (!appPath.empty() && fs::exists(appPath)) + if (fs::path appPath = user_config_path("eu07_input-mouse.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; @@ -185,7 +184,7 @@ drivermouse_input::recall_bindings() { std::unordered_map nametocommandmap; std::size_t commandid = 0; for( auto const &description : simulation::Commands_descriptions ) { - nametocommandmap.emplace( + nametocommandmap.try_emplace( description.name, static_cast( commandid ) ); ++commandid; @@ -211,7 +210,7 @@ drivermouse_input::recall_bindings() { } // TODO: binding targets for mouse buttons - for( auto &bindingtarget : bindingtargets ) { + for( auto const &bindingtarget : bindingtargets ) { // grab command(s) associated with the input pin auto const bindingcommandname{ entryparser.getToken() }; if( true == bindingcommandname.empty() ) { @@ -276,7 +275,7 @@ drivermouse_input::move( double Mousex, double Mousey ) { } void -drivermouse_input::scroll( double const Xoffset, double const Yoffset ) { +drivermouse_input::scroll( double const /*Xoffset*/, double const Yoffset ) { if( Global.ctrlState ) { // ctrl + scroll wheel adjusts fov @@ -314,15 +313,13 @@ drivermouse_input::button( int const Button, int const Action ) { if( true == FreeFlyModeFlag ) { // freefly mode // left mouse button launches on_click event associated with to the node - if( Button == GLFW_MOUSE_BUTTON_LEFT ) { - if( Action == GLFW_PRESS ) { - GfxRenderer->Pick_Node_Callback( - [this](scene::basic_node *node) { - if( node == nullptr - || typeid(*node) != typeid(TAnimModel) ) - return; - simulation::Region->on_click( static_cast( node ) ); } ); - } + if (Button == GLFW_MOUSE_BUTTON_LEFT && Action == GLFW_PRESS) { + GfxRenderer->Pick_Node_Callback( + [](scene::basic_node const *node) { + if( node == nullptr + || typeid(*node) != typeid(TAnimModel) ) + return; + simulation::Region->on_click( static_cast( node ) ); } ); } // right button controls panning if( Button == GLFW_MOUSE_BUTTON_RIGHT ) { @@ -343,11 +340,9 @@ drivermouse_input::button( int const Button, int const Action ) { } else { m_pickwaiting = false; - if( Button == GLFW_MOUSE_BUTTON_LEFT ) { - if( m_slider.command() != user_command::none ) { - m_relay.post( m_slider.command(), 0, 0, Action, 0 ); - m_slider.release(); - } + if (Button == GLFW_MOUSE_BUTTON_LEFT && m_slider.command() != user_command::none) { + m_relay.post( m_slider.command(), 0, 0, Action, 0 ); + m_slider.release(); } // if it's the right mouse button that got released and we had no command active, we were potentially in view panning mode; stop it if( Button == GLFW_MOUSE_BUTTON_RIGHT ) { @@ -361,23 +356,24 @@ drivermouse_input::button( int const Button, int const Action ) { // if not release then it's press m_pickwaiting = true; GfxRenderer->Pick_Control_Callback( - [this, Button, Action, &mousecommand](TSubModel const *control, const glm::vec2 pos) { + [this, Button, Action, &mousecommand](TSubModel const *controlsubmodel, const glm::vec2 pos) { + using enum user_command; bool pickwaiting = m_pickwaiting; m_pickwaiting = false; // click on python screen if (Button == GLFW_MOUSE_BUTTON_LEFT - && control && control->screen_touch_list) { + && controlsubmodel && controlsubmodel->screen_touch_list) { - control->screen_touch_list->emplace_back(pos); + controlsubmodel->screen_touch_list->emplace_back(pos); } - auto const controlbindings { bindings( simulation::Train->GetLabel( control ) ) }; + auto const [leftbinding, rightbinding]{ bindings( simulation::Train->GetLabel( controlsubmodel ) ) }; // if the recognized element under the cursor has a command associated with the pressed button, notify the recipient - mousecommand = Button == GLFW_MOUSE_BUTTON_LEFT ? controlbindings.first : controlbindings.second; + mousecommand = Button == GLFW_MOUSE_BUTTON_LEFT ? leftbinding : rightbinding; - if( mousecommand == user_command::none ) { + if( mousecommand == none ) { // if we don't have any recognized element under the cursor and the right button was pressed, enter view panning mode if( Button == GLFW_MOUSE_BUTTON_RIGHT ) { m_pickmodepanning = true; @@ -387,38 +383,38 @@ drivermouse_input::button( int const Button, int const Action ) { // check manually for commands which have 'fast' variants launched with shift modifier if( Global.shiftState ) { switch( mousecommand ) { - case user_command::mastercontrollerincrease: { mousecommand = user_command::mastercontrollerincreasefast; break; } - case user_command::mastercontrollerdecrease: { mousecommand = user_command::mastercontrollerdecreasefast; break; } - case user_command::secondcontrollerincrease: { mousecommand = user_command::secondcontrollerincreasefast; break; } - case user_command::secondcontrollerdecrease: { mousecommand = user_command::secondcontrollerdecreasefast; break; } - case user_command::independentbrakeincrease: { mousecommand = user_command::independentbrakeincreasefast; break; } - case user_command::independentbrakedecrease: { mousecommand = user_command::independentbrakedecreasefast; break; } + case mastercontrollerincrease: { mousecommand = mastercontrollerincreasefast; break; } + case mastercontrollerdecrease: { mousecommand = mastercontrollerdecreasefast; break; } + case secondcontrollerincrease: { mousecommand = secondcontrollerincreasefast; break; } + case secondcontrollerdecrease: { mousecommand = secondcontrollerdecreasefast; break; } + case independentbrakeincrease: { mousecommand = independentbrakeincreasefast; break; } + case independentbrakedecrease: { mousecommand = independentbrakedecreasefast; break; } default: { break; } } } switch( mousecommand ) { - case user_command::mastercontrollerincrease: - case user_command::mastercontrollerdecrease: - case user_command::secondcontrollerincrease: - case user_command::secondcontrollerdecrease: - case user_command::trainbrakeincrease: - case user_command::trainbrakedecrease: - case user_command::independentbrakeincrease: - case user_command::independentbrakedecrease: { + case mastercontrollerincrease: + case mastercontrollerdecrease: + case secondcontrollerincrease: + case secondcontrollerdecrease: + case trainbrakeincrease: + case trainbrakedecrease: + case independentbrakeincrease: + case independentbrakedecrease: { // these commands trigger varying repeat rate mode, // which scales the rate based on the distance of the cursor from its point when the command was first issued m_varyingpollrateorigin = m_cursorposition; m_varyingpollrate = true; break; } - case user_command::jointcontrollerset: - case user_command::mastercontrollerset: - case user_command::secondcontrollerset: - case user_command::trainbrakeset: - case user_command::independentbrakeset: { + case jointcontrollerset: + case mastercontrollerset: + case secondcontrollerset: + case trainbrakeset: + case independentbrakeset: { m_slider.bind( mousecommand ); - mousecommand = user_command::none; + mousecommand = none; return; } default: { @@ -492,641 +488,643 @@ drivermouse_input::bindings( std::string const &Control ) const { void drivermouse_input::default_bindings() { + using enum user_command; // pierwsza komenda jest od zwiekszania a druga od zmniejszania - ewentualnie kolejno lewy i prawy przycisk m_buttonbindings = { { "jointctrl:", { - user_command::jointcontrollerset, - user_command::none } }, + jointcontrollerset, + none } }, { "mainctrl:", { - user_command::mastercontrollerset, - user_command::none } }, + mastercontrollerset, + none } }, { "dynamicbrakectrl:", { - user_command::dynamicbrakecontrollerset, - user_command::none } }, + dynamicbrakecontrollerset, + none } }, { "scndctrl:", { - user_command::secondcontrollerset, - user_command::none } }, + secondcontrollerset, + none } }, { "shuntmodepower:", { - user_command::secondcontrollerincrease, - user_command::secondcontrollerdecrease } }, + secondcontrollerincrease, + secondcontrollerdecrease } }, { "tempomat_sw:", { - user_command::tempomattoggle, - user_command::none } }, + tempomattoggle, + none } }, { "tempomatoff_sw:", { - user_command::tempomattoggle, - user_command::none } }, + tempomattoggle, + none } }, { "dirkey:", { - user_command::reverserincrease, - user_command::reverserdecrease } }, + reverserincrease, + reverserdecrease } }, { "dirforward_bt:", { - user_command::reverserforward, - user_command::none } }, + reverserforward, + none } }, { "dirneutral_bt:", { - user_command::reverserneutral, - user_command::none } }, + reverserneutral, + none } }, { "dirbackward_bt:", { - user_command::reverserbackward, - user_command::none } }, + reverserbackward, + none } }, { "brakectrl:", { - user_command::trainbrakeset, - user_command::none } }, + trainbrakeset, + none } }, { "localbrake:", { - user_command::independentbrakeset, - user_command::none } }, + independentbrakeset, + none } }, { "manualbrake:", { - user_command::manualbrakeincrease, - user_command::manualbrakedecrease } }, + manualbrakeincrease, + manualbrakedecrease } }, { "alarmchain:", { - user_command::alarmchaintoggle, - user_command::none } }, + alarmchaintoggle, + none } }, { "alarmchainon:", { - user_command::alarmchainenable, - user_command::none} }, + alarmchainenable, + none} }, { "alarmchainoff:", { - user_command::alarmchainenable, - user_command::none} }, + alarmchainenable, + none} }, { "brakeprofile_sw:", { - user_command::brakeactingspeedincrease, - user_command::brakeactingspeeddecrease } }, + brakeactingspeedincrease, + brakeactingspeeddecrease } }, // TODO: dedicated methods for braking speed switches { "brakeprofileg_sw:", { - user_command::brakeactingspeedsetcargo, - user_command::brakeactingspeedsetpassenger } }, + brakeactingspeedsetcargo, + brakeactingspeedsetpassenger } }, { "brakeprofiler_sw:", { - user_command::brakeactingspeedsetrapid, - user_command::brakeactingspeedsetpassenger } }, + brakeactingspeedsetrapid, + brakeactingspeedsetpassenger } }, { "brakeopmode_sw:", { - user_command::trainbrakeoperationmodeincrease, - user_command::trainbrakeoperationmodedecrease } }, + trainbrakeoperationmodeincrease, + trainbrakeoperationmodedecrease } }, { "maxcurrent_sw:", { - user_command::motoroverloadrelaythresholdtoggle, - user_command::none } }, + motoroverloadrelaythresholdtoggle, + none } }, { "waterpumpbreaker_sw:", { - user_command::waterpumpbreakertoggle, - user_command::none } }, + waterpumpbreakertoggle, + none } }, { "waterpump_sw:", { - user_command::waterpumptoggle, - user_command::none } }, + waterpumptoggle, + none } }, { "waterheaterbreaker_sw:", { - user_command::waterheaterbreakertoggle, - user_command::none } }, + waterheaterbreakertoggle, + none } }, { "waterheater_sw:", { - user_command::waterheatertoggle, - user_command::none } }, + waterheatertoggle, + none } }, { "fuelpump_sw:", { - user_command::fuelpumptoggle, - user_command::none } }, + fuelpumptoggle, + none } }, { "oilpump_sw:", { - user_command::oilpumptoggle, - user_command::none } }, + oilpumptoggle, + none } }, { "motorblowersfront_sw:", { - user_command::motorblowerstogglefront, - user_command::none } }, + motorblowerstogglefront, + none } }, { "motorblowersrear_sw:", { - user_command::motorblowerstogglerear, - user_command::none } }, + motorblowerstogglerear, + none } }, { "motorblowersalloff_sw:", { - user_command::motorblowersdisableall, - user_command::none } }, + motorblowersdisableall, + none } }, { "coolingfans_sw:", { - user_command::coolingfanstoggle, - user_command::none } }, + coolingfanstoggle, + none } }, { "main_off_bt:", { - user_command::linebreakeropen, - user_command::none } }, + linebreakeropen, + none } }, { "main_on_bt:",{ - user_command::linebreakerclose, - user_command::none } }, + linebreakerclose, + none } }, { "security_reset_bt:", { - user_command::alerteracknowledge, - user_command::none } }, + alerteracknowledge, + none } }, { "shp_reset_bt:", { - user_command::cabsignalacknowledge, - user_command::none } }, + cabsignalacknowledge, + none } }, { "releaser_bt:", { - user_command::independentbrakebailoff, - user_command::none } }, + independentbrakebailoff, + none } }, { "springbraketoggle_bt:",{ - user_command::springbraketoggle, - user_command::none } }, + springbraketoggle, + none } }, { "springbrakeon_bt:",{ - user_command::springbrakeenable, - user_command::none } }, + springbrakeenable, + none } }, { "springbrakeoff_bt:",{ - user_command::springbrakedisable, - user_command::none } }, + springbrakedisable, + none } }, { "universalbrake1_bt:",{ - user_command::universalbrakebutton1, - user_command::none } }, + universalbrakebutton1, + none } }, { "universalbrake2_bt:",{ - user_command::universalbrakebutton2, - user_command::none } }, + universalbrakebutton2, + none } }, { "universalbrake3_bt:",{ - user_command::universalbrakebutton3, - user_command::none } }, + universalbrakebutton3, + none } }, { "epbrake_bt:",{ - user_command::epbrakecontroltoggle, - user_command::none } }, + epbrakecontroltoggle, + none } }, { "epbrakeon_bt:",{ - user_command::epbrakecontrolenable, - user_command::none } }, + epbrakecontrolenable, + none } }, { "epbrakeoff_bt:",{ - user_command::epbrakecontroldisable, - user_command::none } }, + epbrakecontroldisable, + none } }, { "sand_bt:", { - user_command::sandboxactivate, - user_command::none } }, + sandboxactivate, + none } }, { "antislip_bt:", { - user_command::wheelspinbrakeactivate, - user_command::none } }, + wheelspinbrakeactivate, + none } }, { "horn_bt:", { - user_command::hornhighactivate, - user_command::hornlowactivate } }, + hornhighactivate, + hornlowactivate } }, { "hornlow_bt:", { - user_command::hornlowactivate, - user_command::none } }, + hornlowactivate, + none } }, { "hornhigh_bt:", { - user_command::hornhighactivate, - user_command::none } }, + hornhighactivate, + none } }, { "whistle_bt:", { - user_command::whistleactivate, - user_command::none } }, + whistleactivate, + none } }, { "fuse_bt:", { - user_command::motoroverloadrelayreset, - user_command::none } }, + motoroverloadrelayreset, + none } }, { "converterfuse_bt:", { - user_command::converteroverloadrelayreset, - user_command::none } }, + converteroverloadrelayreset, + none } }, { "relayreset1_bt:", { - user_command::universalrelayreset1, - user_command::none } }, + universalrelayreset1, + none } }, { "relayreset2_bt:", { - user_command::universalrelayreset2, - user_command::none } }, + universalrelayreset2, + none } }, { "relayreset3_bt:", { - user_command::universalrelayreset3, - user_command::none } }, + universalrelayreset3, + none } }, { "stlinoff_bt:", { - user_command::motorconnectorsopen, - user_command::none } }, + motorconnectorsopen, + none } }, { "doorleftpermit_sw:", { - user_command::doorpermitleft, - user_command::none } }, + doorpermitleft, + none } }, { "doorrightpermit_sw:", { - user_command::doorpermitright, - user_command::none } }, + doorpermitright, + none } }, { "doorpermitpreset_sw:", { - user_command::doorpermitpresetactivatenext, - user_command::doorpermitpresetactivateprevious } }, + doorpermitpresetactivatenext, + doorpermitpresetactivateprevious } }, { "door_left_sw:", { - user_command::doortoggleleft, - user_command::none } }, + doortoggleleft, + none } }, { "door_right_sw:", { - user_command::doortoggleright, - user_command::none } }, + doortoggleright, + none } }, { "doorlefton_sw:", { - user_command::dooropenleft, - user_command::none } }, + dooropenleft, + none } }, { "doorrighton_sw:", { - user_command::dooropenright, - user_command::none } }, + dooropenright, + none } }, { "doorleftoff_sw:", { - user_command::doorcloseleft, - user_command::none } }, + doorcloseleft, + none } }, { "doorrightoff_sw:", { - user_command::doorcloseright, - user_command::none } }, + doorcloseright, + none } }, { "doorallon_sw:", { - user_command::dooropenall, - user_command::none } }, + dooropenall, + none } }, { "dooralloff_sw:", { - user_command::doorcloseall, - user_command::none } }, + doorcloseall, + none } }, { "doorstep_sw:", { - user_command::doorsteptoggle, - user_command::none } }, + doorsteptoggle, + none } }, { "doormode_sw:", { - user_command::doormodetoggle, - user_command::none } }, + doormodetoggle, + none } }, { "mirrors_sw:", { - user_command::mirrorstoggle, - user_command::none } }, + mirrorstoggle, + none } }, { "departure_signal_bt:", { - user_command::departureannounce, - user_command::none } }, + departureannounce, + none } }, { "upperlight_sw:", { - user_command::headlighttoggleupper, - user_command::none } }, + headlighttoggleupper, + none } }, { "leftlight_sw:", { - user_command::headlighttoggleleft, - user_command::none } }, + headlighttoggleleft, + none } }, { "rightlight_sw:", { - user_command::headlighttoggleright, - user_command::none } }, + headlighttoggleright, + none } }, { "dimheadlights_sw:", { - user_command::headlightsdimtoggle, - user_command::none } }, + headlightsdimtoggle, + none } }, {"moderndimmer_sw:", { - user_command::modernlightdimmerincrease, - user_command::modernlightdimmerdecrease } }, + modernlightdimmerincrease, + modernlightdimmerdecrease } }, { "leftend_sw:", { - user_command::redmarkertoggleleft, - user_command::none } }, + redmarkertoggleleft, + none } }, { "rightend_sw:", { - user_command::redmarkertoggleright, - user_command::none } }, + redmarkertoggleright, + none } }, { "lights_sw:", { - user_command::lightspresetactivatenext, - user_command::lightspresetactivateprevious } }, + lightspresetactivatenext, + lightspresetactivateprevious } }, { "rearupperlight_sw:", { - user_command::headlighttogglerearupper, - user_command::none } }, + headlighttogglerearupper, + none } }, { "rearleftlight_sw:", { - user_command::headlighttogglerearleft, - user_command::none } }, + headlighttogglerearleft, + none } }, { "rearrightlight_sw:", { - user_command::headlighttogglerearright, - user_command::none } }, + headlighttogglerearright, + none } }, { "rearleftend_sw:", { - user_command::redmarkertogglerearleft, - user_command::none } }, + redmarkertogglerearleft, + none } }, { "rearrightend_sw:", { - user_command::redmarkertogglerearright, - user_command::none } }, + redmarkertogglerearright, + none } }, { "compressor_sw:", { - user_command::compressortoggle, - user_command::none } }, + compressortoggle, + none } }, { "compressorlocal_sw:", { - user_command::compressortogglelocal, - user_command::none } }, + compressortogglelocal, + none } }, { "compressorlist_sw:", { - user_command::compressorpresetactivatenext, - user_command::compressorpresetactivateprevious } }, + compressorpresetactivatenext, + compressorpresetactivateprevious } }, { "converter_sw:", { - user_command::convertertoggle, - user_command::none } }, + convertertoggle, + none } }, { "converterlocal_sw:", { - user_command::convertertogglelocal, - user_command::none } }, + convertertogglelocal, + none } }, { "converteroff_sw:", { - user_command::convertertoggle, - user_command::none } }, // TODO: dedicated converter shutdown command + convertertoggle, + none } }, // TODO: dedicated converter shutdown command { "main_sw:", { - user_command::linebreakertoggle, - user_command::none } }, + linebreakertoggle, + none } }, { "radio_sw:", { - user_command::radiotoggle, - user_command::none } }, + radiotoggle, + none } }, { "radioon_sw:", { - user_command::radioenable, - user_command::none } }, + radioenable, + none } }, { "radiooff_sw:", { - user_command::radiodisable, - user_command::none } }, + radiodisable, + none } }, { "radiochannel_sw:", { - user_command::radiochannelincrease, - user_command::radiochanneldecrease } }, + radiochannelincrease, + radiochanneldecrease } }, { "radiochannelprev_sw:", { - user_command::radiochanneldecrease, - user_command::none } }, + radiochanneldecrease, + none } }, { "radiochannelnext_sw:", { - user_command::radiochannelincrease, - user_command::none } }, + radiochannelincrease, + none } }, { "radiostop_sw:", { - user_command::radiostopsend, - user_command::none } }, + radiostopsend, + none } }, { "radiostopon_sw:", { - user_command::radiostopenable, - user_command::none } }, + radiostopenable, + none } }, { "radiostopoff_sw:", { - user_command::radiostopdisable, - user_command::none } }, + radiostopdisable, + none } }, { "radiotest_sw:", { - user_command::radiostoptest, - user_command::none } }, + radiostoptest, + none } }, { "radiocall1_sw:", { - user_command::radiocall1send, - user_command::none } }, + radiocall1send, + none } }, { "radiocall3_sw:", { - user_command::radiocall3send, - user_command::none } }, + radiocall3send, + none } }, { "radiovolume_sw:",{ - user_command::radiovolumeincrease, - user_command::radiovolumedecrease } }, + radiovolumeincrease, + radiovolumedecrease } }, { "radiovolumeprev_sw:",{ - user_command::radiovolumedecrease, - user_command::none } }, + radiovolumedecrease, + none } }, { "radiovolumenext_sw:",{ - user_command::radiovolumeincrease, - user_command::none } }, + radiovolumeincrease, + none } }, { "pantfront_sw:", { - user_command::pantographtogglefront, - user_command::none } }, + pantographtogglefront, + none } }, { "pantrear_sw:", { - user_command::pantographtogglerear, - user_command::none } }, + pantographtogglerear, + none } }, { "pantfrontoff_sw:", { - user_command::pantographlowerfront, - user_command::none } }, + pantographlowerfront, + none } }, { "pantrearoff_sw:", { - user_command::pantographlowerrear, - user_command::none } }, + pantographlowerrear, + none } }, { "pantalloff_sw:", { - user_command::pantographlowerall, - user_command::none } }, + pantographlowerall, + none } }, { "pantselected_sw:", { - user_command::pantographtoggleselected, - user_command::none } }, // TBD: bind lowerselected in case of toggle switch + pantographtoggleselected, + none } }, // TBD: bind lowerselected in case of toggle switch { "pantselectedoff_sw:", { - user_command::pantographlowerselected, - user_command::none } }, + pantographlowerselected, + none } }, { "pantselect_sw:", { - user_command::pantographselectnext, - user_command::pantographselectprevious } }, + pantographselectnext, + pantographselectprevious } }, { "pantvalves_sw:", { - user_command::pantographvalvesupdate, - user_command::pantographvalvesoff } }, + pantographvalvesupdate, + pantographvalvesoff } }, { "pantvalvesupdate_bt:", { - user_command::pantographvalvesupdate, - user_command::none}}, + pantographvalvesupdate, + none}}, { "pantvalvesoff_bt:", { - user_command::pantographvalvesoff, - user_command::none}}, + pantographvalvesoff, + none}}, { "pantcompressor_sw:", { - user_command::pantographcompressoractivate, - user_command::none } }, + pantographcompressoractivate, + none } }, { "pantcompressorvalve_sw:", { - user_command::pantographcompressorvalvetoggle, - user_command::none } }, + pantographcompressorvalvetoggle, + none } }, { "trainheating_sw:", { - user_command::heatingtoggle, - user_command::none } }, + heatingtoggle, + none } }, { "signalling_sw:", { - user_command::mubrakingindicatortoggle, - user_command::none } }, + mubrakingindicatortoggle, + none } }, { "door_signalling_sw:", { - user_command::doorlocktoggle, - user_command::none } }, + doorlocktoggle, + none } }, { "nextcurrent_sw:", { - user_command::mucurrentindicatorothersourceactivate, - user_command::none } }, + mucurrentindicatorothersourceactivate, + none } }, { "distancecounter_sw:", { - user_command::distancecounteractivate, - user_command::none } }, + distancecounteractivate, + none } }, { "instrumentlight_sw:", { - user_command::instrumentlighttoggle, - user_command::none } }, + instrumentlighttoggle, + none } }, { "dashboardlight_sw:", { - user_command::dashboardlighttoggle, - user_command::none } }, + dashboardlighttoggle, + none } }, { "dashboardlighton_sw:", { - user_command::dashboardlightenable, - user_command::none } }, + dashboardlightenable, + none } }, { "dashboardlightoff_sw:", { - user_command::dashboardlightdisable, - user_command::none } }, + dashboardlightdisable, + none } }, { "timetablelight_sw:", { - user_command::timetablelighttoggle, - user_command::none } }, + timetablelighttoggle, + none } }, { "timetablelighton_sw:", { - user_command::timetablelightenable, - user_command::none } }, + timetablelightenable, + none } }, { "timetablelightoff_sw:", { - user_command::timetablelightdisable, - user_command::none } }, + timetablelightdisable, + none } }, { "cablight_sw:", { - user_command::interiorlighttoggle, - user_command::none } }, + interiorlighttoggle, + none } }, { "cablightdim_sw:", { - user_command::interiorlightdimtoggle, - user_command::none } }, + interiorlightdimtoggle, + none } }, { "compartmentlights_sw:", { - user_command::compartmentlightstoggle, - user_command::none } }, + compartmentlightstoggle, + none } }, { "compartmentlightson_sw:", { - user_command::compartmentlightsenable, - user_command::none } }, + compartmentlightsenable, + none } }, { "compartmentlightsoff_sw:", { - user_command::compartmentlightsdisable, - user_command::none } }, + compartmentlightsdisable, + none } }, { "battery_sw:", { - user_command::batterytoggle, - user_command::none } }, + batterytoggle, + none } }, { "batteryon_sw:", { - user_command::batteryenable, - user_command::none } }, + batteryenable, + none } }, { "batteryoff_sw:", { - user_command::batterydisable, - user_command::none } }, + batterydisable, + none } }, { "cabactivation_sw:", { - user_command::cabactivationtoggle, - user_command::none } }, + cabactivationtoggle, + none } }, { "couplingdisconnect_sw:",{ - user_command::occupiedcarcouplingdisconnect, - user_command::none } }, + occupiedcarcouplingdisconnect, + none } }, { "couplingdisconnectback_sw:",{ - user_command::occupiedcarcouplingdisconnectback, - user_command::none } }, - {"universal0:", {user_command::generictoggle0, user_command::none}}, - {"universal1:", {user_command::generictoggle1, user_command::none}}, - {"universal2:", {user_command::generictoggle2, user_command::none}}, - {"universal3:", {user_command::generictoggle3, user_command::none}}, - {"universal4:", {user_command::generictoggle4, user_command::none}}, - {"universal5:", {user_command::generictoggle5, user_command::none}}, - {"universal6:", {user_command::generictoggle6, user_command::none}}, - {"universal7:", {user_command::generictoggle7, user_command::none}}, - {"universal8:", {user_command::generictoggle8, user_command::none}}, - {"universal9:", {user_command::generictoggle9, user_command::none}}, - {"universal10:", {user_command::generictoggle10, user_command::none}}, - {"universal11:", {user_command::generictoggle11, user_command::none}}, - {"universal12:", {user_command::generictoggle12, user_command::none}}, - {"universal13:", {user_command::generictoggle13, user_command::none}}, - {"universal14:", {user_command::generictoggle14, user_command::none}}, - {"universal15:", {user_command::generictoggle15, user_command::none}}, - {"universal16:", {user_command::generictoggle16, user_command::none}}, - {"universal17:", {user_command::generictoggle17, user_command::none}}, - {"universal18:", {user_command::generictoggle18, user_command::none}}, - {"universal19:", {user_command::generictoggle19, user_command::none}}, - {"universal20:", {user_command::generictoggle20, user_command::none}}, - {"universal21:", {user_command::generictoggle21, user_command::none}}, - {"universal22:", {user_command::generictoggle22, user_command::none}}, - {"universal23:", {user_command::generictoggle23, user_command::none}}, - {"universal24:", {user_command::generictoggle24, user_command::none}}, - {"universal25:", {user_command::generictoggle25, user_command::none}}, - {"universal26:", {user_command::generictoggle26, user_command::none}}, - {"universal27:", {user_command::generictoggle27, user_command::none}}, - {"universal28:", {user_command::generictoggle28, user_command::none}}, - {"universal29:", {user_command::generictoggle29, user_command::none}}, + occupiedcarcouplingdisconnectback, + none } }, + {"universal0:", {generictoggle0, none}}, + {"universal1:", {generictoggle1, none}}, + {"universal2:", {generictoggle2, none}}, + {"universal3:", {generictoggle3, none}}, + {"universal4:", {generictoggle4, none}}, + {"universal5:", {generictoggle5, none}}, + {"universal6:", {generictoggle6, none}}, + {"universal7:", {generictoggle7, none}}, + {"universal8:", {generictoggle8, none}}, + {"universal9:", {generictoggle9, none}}, + {"universal10:", {generictoggle10, none}}, + {"universal11:", {generictoggle11, none}}, + {"universal12:", {generictoggle12, none}}, + {"universal13:", {generictoggle13, none}}, + {"universal14:", {generictoggle14, none}}, + {"universal15:", {generictoggle15, none}}, + {"universal16:", {generictoggle16, none}}, + {"universal17:", {generictoggle17, none}}, + {"universal18:", {generictoggle18, none}}, + {"universal19:", {generictoggle19, none}}, + {"universal20:", {generictoggle20, none}}, + {"universal21:", {generictoggle21, none}}, + {"universal22:", {generictoggle22, none}}, + {"universal23:", {generictoggle23, none}}, + {"universal24:", {generictoggle24, none}}, + {"universal25:", {generictoggle25, none}}, + {"universal26:", {generictoggle26, none}}, + {"universal27:", {generictoggle27, none}}, + {"universal28:", {generictoggle28, none}}, + {"universal29:", {generictoggle29, none}}, { "speedinc_bt:",{ - user_command::speedcontrolincrease, - user_command::none } }, + speedcontrolincrease, + none } }, { "speeddec_bt:",{ - user_command::speedcontroldecrease, - user_command::none } }, + speedcontroldecrease, + none } }, { "speedctrlpowerinc_bt:",{ - user_command::speedcontrolpowerincrease, - user_command::none } }, + speedcontrolpowerincrease, + none } }, { "speedctrlpowerdec_bt:",{ - user_command::speedcontrolpowerdecrease, - user_command::none } }, + speedcontrolpowerdecrease, + none } }, { "speedbutton0:",{ - user_command::speedcontrolbutton0, - user_command::none } }, + speedcontrolbutton0, + none } }, { "speedbutton1:",{ - user_command::speedcontrolbutton1, - user_command::none } }, + speedcontrolbutton1, + none } }, { "speedbutton2:",{ - user_command::speedcontrolbutton2, - user_command::none } }, + speedcontrolbutton2, + none } }, { "speedbutton3:",{ - user_command::speedcontrolbutton3, - user_command::none } }, + speedcontrolbutton3, + none } }, { "speedbutton4:",{ - user_command::speedcontrolbutton4, - user_command::none } }, + speedcontrolbutton4, + none } }, { "speedbutton5:",{ - user_command::speedcontrolbutton5, - user_command::none } }, + speedcontrolbutton5, + none } }, { "speedbutton6:",{ - user_command::speedcontrolbutton6, - user_command::none } }, + speedcontrolbutton6, + none } }, { "speedbutton7:",{ - user_command::speedcontrolbutton7, - user_command::none } }, + speedcontrolbutton7, + none } }, { "speedbutton8:",{ - user_command::speedcontrolbutton8, - user_command::none } }, + speedcontrolbutton8, + none } }, { "speedbutton9:",{ - user_command::speedcontrolbutton9, - user_command::none } }, + speedcontrolbutton9, + none } }, { "inverterenable1_bt:",{ - user_command::inverterenable1, - user_command::none } }, + inverterenable1, + none } }, { "inverterenable2_bt:",{ - user_command::inverterenable2, - user_command::none } }, + inverterenable2, + none } }, { "inverterenable3_bt:",{ - user_command::inverterenable3, - user_command::none } }, + inverterenable3, + none } }, { "inverterenable4_bt:",{ - user_command::inverterenable4, - user_command::none } }, + inverterenable4, + none } }, { "inverterenable5_bt:",{ - user_command::inverterenable5, - user_command::none } }, + inverterenable5, + none } }, { "inverterenable6_bt:",{ - user_command::inverterenable6, - user_command::none } }, + inverterenable6, + none } }, { "inverterenable7_bt:",{ - user_command::inverterenable7, - user_command::none } }, + inverterenable7, + none } }, { "inverterenable8_bt:",{ - user_command::inverterenable8, - user_command::none } }, + inverterenable8, + none } }, { "inverterenable9_bt:",{ - user_command::inverterenable9, - user_command::none } }, + inverterenable9, + none } }, { "inverterenable10_bt:",{ - user_command::inverterenable10, - user_command::none } }, + inverterenable10, + none } }, { "inverterenable11_bt:",{ - user_command::inverterenable11, - user_command::none } }, + inverterenable11, + none } }, { "inverterenable12_bt:",{ - user_command::inverterenable12, - user_command::none } }, + inverterenable12, + none } }, { "inverterdisable1_bt:",{ - user_command::inverterdisable1, - user_command::none } }, + inverterdisable1, + none } }, { "inverterdisable2_bt:",{ - user_command::inverterdisable2, - user_command::none } }, + inverterdisable2, + none } }, { "inverterdisable3_bt:",{ - user_command::inverterdisable3, - user_command::none } }, + inverterdisable3, + none } }, { "inverterdisable4_bt:",{ - user_command::inverterdisable4, - user_command::none } }, + inverterdisable4, + none } }, { "inverterdisable5_bt:",{ - user_command::inverterdisable5, - user_command::none } }, + inverterdisable5, + none } }, { "inverterdisable6_bt:",{ - user_command::inverterdisable6, - user_command::none } }, + inverterdisable6, + none } }, { "inverterdisable7_bt:",{ - user_command::inverterdisable7, - user_command::none } }, + inverterdisable7, + none } }, { "inverterdisable8_bt:",{ - user_command::inverterdisable8, - user_command::none } }, + inverterdisable8, + none } }, { "inverterdisable9_bt:",{ - user_command::inverterdisable9, - user_command::none } }, + inverterdisable9, + none } }, { "inverterdisable10_bt:",{ - user_command::inverterdisable10, - user_command::none } }, + inverterdisable10, + none } }, { "inverterdisable11_bt:",{ - user_command::inverterdisable11, - user_command::none } }, + inverterdisable11, + none } }, { "inverterdisable12_bt:",{ - user_command::inverterdisable12, - user_command::none } }, + inverterdisable12, + none } }, { "invertertoggle1_bt:",{ - user_command::invertertoggle1, - user_command::none } }, + invertertoggle1, + none } }, { "invertertoggle2_bt:",{ - user_command::invertertoggle2, - user_command::none } }, + invertertoggle2, + none } }, { "invertertoggle3_bt:",{ - user_command::invertertoggle3, - user_command::none } }, + invertertoggle3, + none } }, { "invertertoggle4_bt:",{ - user_command::invertertoggle4, - user_command::none } }, + invertertoggle4, + none } }, { "invertertoggle5_bt:",{ - user_command::invertertoggle5, - user_command::none } }, + invertertoggle5, + none } }, { "invertertoggle6_bt:",{ - user_command::invertertoggle6, - user_command::none } }, + invertertoggle6, + none } }, { "invertertoggle7_bt:",{ - user_command::invertertoggle7, - user_command::none } }, + invertertoggle7, + none } }, { "invertertoggle8_bt:",{ - user_command::invertertoggle8, - user_command::none } }, + invertertoggle8, + none } }, { "invertertoggle9_bt:",{ - user_command::invertertoggle9, - user_command::none } }, + invertertoggle9, + none } }, { "invertertoggle10_bt:",{ - user_command::invertertoggle10, - user_command::none } }, + invertertoggle10, + none } }, { "invertertoggle11_bt:",{ - user_command::invertertoggle11, - user_command::none } }, + invertertoggle11, + none } }, { "invertertoggle12_bt:",{ - user_command::invertertoggle12, - user_command::none } }, + invertertoggle12, + none } }, { "wipers_sw:",{ - user_command::wiperswitchincrease, - user_command::wiperswitchdecrease + wiperswitchincrease, + wiperswitchdecrease } }, }; } user_command -drivermouse_input::adjust_command( user_command Command ) { +drivermouse_input::adjust_command( user_command Command ) const { + using enum user_command; if( true == Global.shiftState - && Command != user_command::none ) { + && Command != none ) { switch( Command ) { - case user_command::mastercontrollerincrease: { Command = user_command::mastercontrollerincreasefast; break; } - case user_command::mastercontrollerdecrease: { Command = user_command::mastercontrollerdecreasefast; break; } - case user_command::secondcontrollerincrease: { Command = user_command::secondcontrollerincreasefast; break; } - case user_command::secondcontrollerdecrease: { Command = user_command::secondcontrollerdecreasefast; break; } - case user_command::independentbrakeincrease: { Command = user_command::independentbrakeincreasefast; break; } - case user_command::independentbrakedecrease: { Command = user_command::independentbrakedecreasefast; break; } + case mastercontrollerincrease: { Command = mastercontrollerincreasefast; break; } + case mastercontrollerdecrease: { Command = mastercontrollerdecreasefast; break; } + case secondcontrollerincrease: { Command = secondcontrollerincreasefast; break; } + case secondcontrollerdecrease: { Command = secondcontrollerdecreasefast; break; } + case independentbrakeincrease: { Command = independentbrakeincreasefast; break; } + case independentbrakedecrease: { Command = independentbrakedecreasefast; break; } default: { break; } } } diff --git a/input/drivermouseinput.h b/input/drivermouseinput.h index 142ef99c..180e0335 100644 --- a/input/drivermouseinput.h +++ b/input/drivermouseinput.h @@ -84,14 +84,14 @@ private: user_command down; }; - typedef std::unordered_map buttonbindings_map; + using buttonbindings_map = std::unordered_map; // methods void default_bindings(); // potentially replaces supplied command with a more relevant one user_command - adjust_command( user_command Command ); + adjust_command( user_command Command ) const; // members command_relay m_relay; diff --git a/input/editorkeyboardinput.cpp b/input/editorkeyboardinput.cpp index 209ca65a..7f5a03a1 100644 --- a/input/editorkeyboardinput.cpp +++ b/input/editorkeyboardinput.cpp @@ -31,25 +31,26 @@ editorkeyboard_input::apply_scheme() { void editorkeyboard_input::default_bindings() { + using enum user_command; if (EditorSettings.movement() == editorSettings::movement_scheme::legacy) { m_bindingsetups = { - { user_command::moveleft, {GLFW_KEY_LEFT, "Move left"} }, - { user_command::moveright, {GLFW_KEY_RIGHT, "Move right"} }, - { user_command::moveforward, {GLFW_KEY_UP, "Move forwards"} }, - { user_command::moveback, {GLFW_KEY_DOWN, "Move backwards"} }, - { user_command::moveup, {GLFW_KEY_PAGE_UP, "Move up"} }, - { user_command::movedown, {GLFW_KEY_PAGE_DOWN, "Move down"} }, + { moveleft, {GLFW_KEY_LEFT, "Move left"} }, + { moveright, {GLFW_KEY_RIGHT, "Move right"} }, + { moveforward, {GLFW_KEY_UP, "Move forwards"} }, + { moveback, {GLFW_KEY_DOWN, "Move backwards"} }, + { moveup, {GLFW_KEY_PAGE_UP, "Move up"} }, + { movedown, {GLFW_KEY_PAGE_DOWN, "Move down"} }, }; } else { m_bindingsetups = { - { user_command::moveleft, {GLFW_KEY_A, "Move left"} }, - { user_command::moveright, {GLFW_KEY_D, "Move right"} }, - { user_command::moveforward, {GLFW_KEY_W, "Move forwards"} }, - { user_command::moveback, {GLFW_KEY_S, "Move backwards"} }, - { user_command::moveup, {GLFW_KEY_E, "Move up"} }, - { user_command::movedown, {GLFW_KEY_Q, "Move down"} }, + { moveleft, {GLFW_KEY_A, "Move left"} }, + { moveright, {GLFW_KEY_D, "Move right"} }, + { moveforward, {GLFW_KEY_W, "Move forwards"} }, + { moveback, {GLFW_KEY_S, "Move backwards"} }, + { moveup, {GLFW_KEY_E, "Move up"} }, + { movedown, {GLFW_KEY_Q, "Move down"} }, }; } } diff --git a/input/gamepadinput.cpp b/input/gamepadinput.cpp index ac819b82..c4e537b2 100644 --- a/input/gamepadinput.cpp +++ b/input/gamepadinput.cpp @@ -51,8 +51,7 @@ gamepad_input::init() { m_inputbuttons.clear(); // NOTE: we're only checking for joystick_1 and rely for it to stay connected throughout. // not exactly flexible, but for quick hack it'll do - auto const name = glfwGetJoystickName( GLFW_JOYSTICK_1 ); - if( name != nullptr ) { + if( auto const name = glfwGetJoystickName( GLFW_JOYSTICK_1 ); name != nullptr ) { WriteLog( "Connected gamepad: " + std::string( name ) ); m_deviceid = GLFW_JOYSTICK_1; } @@ -94,7 +93,7 @@ gamepad_input::poll() { if( button.state != buttons[ idx ] ) { // button pressed or released, both are important on_button( - idx, + static_cast(idx), buttons[idx] == 1 ? GLFW_PRESS : GLFW_RELEASE); } else { @@ -102,7 +101,7 @@ gamepad_input::poll() { if( button.state == GLFW_PRESS ) { on_button( - idx, + static_cast(idx), GLFW_REPEAT ); } } @@ -125,9 +124,9 @@ gamepad_input::poll() { } void -gamepad_input::bind( std::vector< std::reference_wrapper > &Targets, cParser &Input, std::unordered_map const &Translator, std::string const Point ) { +gamepad_input::bind( std::vector< std::reference_wrapper > const &Targets, cParser &Input, std::unordered_map const &Translator, std::string const &Point ) const { - for( auto &bindingtarget : Targets ) { + for( auto const &bindingtarget : Targets ) { // grab command(s) associated with the input pin auto const bindingcommandname{ Input.getToken() }; if( true == bindingcommandname.empty() ) { @@ -154,12 +153,11 @@ bool gamepad_input::recall_bindings() { std::string filePath = "eu07_input-gamepad.ini"; - fs::path appPath = user_config_path("eu07_input-gamepad.ini"); - if (!appPath.empty() && fs::exists(appPath)) + if (fs::path appPath = user_config_path("eu07_input-gamepad.ini"); !appPath.empty() && fs::exists(appPath)) filePath = appPath.string(); // bindingparser tworzony zawsze, z wybran� �cie�k� - cParser bindingparser(filePath.c_str(), cParser::buffer_FILE); + cParser bindingparser(filePath, cParser::buffer_FILE); if( false == bindingparser.ok() ) { return false; @@ -169,7 +167,7 @@ gamepad_input::recall_bindings() { std::unordered_map nametocommandmap; std::size_t commandid = 0; for( auto const &description : simulation::Commands_descriptions ) { - nametocommandmap.emplace( + nametocommandmap.try_emplace( description.name, static_cast( commandid ) ); ++commandid; @@ -191,16 +189,16 @@ gamepad_input::recall_bindings() { std::string bindingpoint {}; entryparser >> bindingpoint; - auto const splitbindingpoint { split_string_and_number( bindingpoint ) }; + auto const [pointtype, pointindex]{ split_string_and_number( bindingpoint ) }; - if( splitbindingpoint.first == "axis" ) { + if( pointtype == "axis" ) { // one or more sets of: [modeIDX] input type, parameters // [optional] modeIDX associates the set with control mode IDX // input types: // -- range commandname IDX; axis value is passed as paramIDX of commandname // -- 3state commandname commandname; positive axis value issues first commandname, negative value issues second commandname - auto const axisindex { splitbindingpoint.second }; + auto const axisindex { pointindex }; // sanity check, connected gamepad isn't guaranteed to have that many axes if( axisindex >= m_inputaxes.size() ) { continue; } @@ -211,8 +209,7 @@ gamepad_input::recall_bindings() { std::string key {}; entryparser >> key; // check for potential mode indicator - auto const splitkey { split_string_and_number( key ) }; - if( splitkey.first == "mode" ) { + if( auto const splitkey { split_string_and_number( key ) }; splitkey.first == "mode" ) { // indicate we'll be processing specified mode controlmode = splitkey.second; continue; @@ -231,12 +228,13 @@ gamepad_input::recall_bindings() { std::get<0>( m_inputaxes[ axisindex ].bindings[ controlmode ] ) = bindingtype; // retrieve regular commands associated with the axis and mode switch( bindingtype ) { - case input_type::value: - case input_type::value_invert: { + using enum gamepad_input::input_type; + case value: + case value_invert: { bindingtargets.emplace_back( std::ref( std::get<1>( m_inputaxes[ axisindex ].bindings[ controlmode ] ) ) ); break; } - case input_type::threestate: { + case threestate: { bindingtargets.emplace_back( std::ref( std::get<1>( m_inputaxes[ axisindex ].bindings[ controlmode ] ) ) ); bindingtargets.emplace_back( std::ref( std::get<2>( m_inputaxes[ axisindex ].bindings[ controlmode ] ) ) ); break; @@ -267,9 +265,9 @@ gamepad_input::recall_bindings() { } } } - else if( splitbindingpoint.first == "button" ) { + else if( pointtype == "button" ) { - auto const buttonindex { splitbindingpoint.second }; + auto const buttonindex { pointindex }; // sanity check, connected gamepad isn't guaranteed to have that many buttons if( buttonindex >= m_inputbuttons.size() ) { continue; } @@ -345,7 +343,8 @@ void gamepad_input::process_axes() { input_type inputtype; - user_command boundcommand1, boundcommand2; + user_command boundcommand1; + user_command boundcommand2; auto binding { std::tie( inputtype, boundcommand1, boundcommand2 ) }; // since some commands can potentially collect values from two different axes we can't post them directly @@ -369,20 +368,18 @@ gamepad_input::process_axes() { auto const deltatime { Timer::GetDeltaTime() * 15.0 }; if( axis.state >= 0.0f ) { // first bound command selected - if( axis.accumulator < 0.0f ) { - // we were issuing the other command, post notification that's no longer the case - if( boundcommand2 != user_command::none ) { - m_relay.post( - boundcommand2, - 0, 0, - GLFW_RELEASE, - 0 ); - axis.accumulator = 0.0f; - } + // we were issuing the other command, post notification that's no longer the case + if (axis.accumulator < 0.0f && boundcommand2 != user_command::none) { + m_relay.post( + boundcommand2, + 0, 0, + GLFW_RELEASE, + 0 ); + axis.accumulator = 0.0f; } if( boundcommand1 != user_command::none ) { if( axis.state > m_deadzone ) { - axis.accumulator += ( axis.state - m_deadzone ) / ( 1.0 - m_deadzone ) * deltatime; + axis.accumulator += static_cast(( axis.state - m_deadzone ) / ( 1.0 - m_deadzone ) * deltatime); // we're making sure there's always a positive charge left in the accumulator, // to more reliably decect when the stick goes from active to dead zone, below while( axis.accumulator > 1.0f ) { @@ -409,20 +406,18 @@ gamepad_input::process_axes() { } else { // second bound command selected - if( axis.accumulator > 0.0f ) { - // we were issuing the other command, post notification that's no longer the case - if( boundcommand1 != user_command::none ) { - m_relay.post( - boundcommand1, - 0, 0, - GLFW_RELEASE, - 0 ); - axis.accumulator = 0.0f; - } + // we were issuing the other command, post notification that's no longer the case + if (axis.accumulator > 0.0f && boundcommand1 != user_command::none) { + m_relay.post( + boundcommand1, + 0, 0, + GLFW_RELEASE, + 0 ); + axis.accumulator = 0.0f; } if( boundcommand1 != user_command::none ) { if( axis.state < -m_deadzone ) { - axis.accumulator += ( axis.state + m_deadzone ) / ( 1.0 - m_deadzone ) * deltatime; + axis.accumulator += static_cast(( axis.state + m_deadzone ) / ( 1.0 - m_deadzone ) * deltatime); // we're making sure there's always a positive charge left in the accumulator, // to more reliably decect when the stick goes from active to dead zone, below while( axis.accumulator < -1.0f ) { @@ -464,19 +459,18 @@ gamepad_input::process_axes() { else { param = param > 0.0 ? (param - m_deadzone) / (1.0 - m_deadzone) : (param + m_deadzone) / (1.0 - m_deadzone); } - if( param != 0.0 ) { - if( inputtype == input_type::value_invert ) { - param *= -1.0; - } + if (param != 0.0 && inputtype == input_type::value_invert) { + param *= -1.0; } // scale passed value according to command type switch( boundcommand1 ) { - case user_command::viewturn: { + using enum user_command; + case viewturn: { param *= 10.0 * ( Timer::GetDeltaRenderTime() * 60.0 ); break; } - case user_command::movehorizontal: - case user_command::movehorizontalfast: { + case movehorizontal: + case movehorizontalfast: { // these expect value in -1:1 range break; } @@ -494,17 +488,17 @@ gamepad_input::process_axes() { } } // issue remaining, assembled commands - for( auto const &command : commands ) { - auto const param1 { std::get<0>( command.second ) }; - auto const param2 { std::get<1>( command.second ) }; - auto &lastparams { m_lastcommandparams[ command.first ] }; + for( auto const &[commandid, commandparams] : commands ) { + auto const param1 { std::get<0>( commandparams ) }; + auto const param2 { std::get<1>( commandparams ) }; + auto &lastparams { m_lastcommandparams[ commandid ] }; if( param1 != 0.0 || std::get<0>(lastparams) != 0.0 || param2 != 0.0 || std::get<1>(lastparams) != 0.0 ) { m_relay.post( - command.first, + commandid, param1, param2, - std::get<2>( command.second ), + std::get<2>( commandparams ), // as we haven't yet implemented either item id system or multiplayer, the 'local' controlled vehicle and entity have temporary ids of 0 // TODO: pass correct entity id once the missing systems are in place 0 ); diff --git a/input/gamepadinput.h b/input/gamepadinput.h index ba8d4e38..6f411601 100644 --- a/input/gamepadinput.h +++ b/input/gamepadinput.h @@ -77,7 +77,7 @@ private: using inputaxis_sequence = std::vector; // methods bool recall_bindings(); - void bind( std::vector< std::reference_wrapper > &Targets, cParser &Input, std::unordered_map const &Translator, std::string const Point ); + void bind( std::vector< std::reference_wrapper > const &Targets, cParser &Input, std::unordered_map const &Translator, std::string const &Point ) const; void on_button( int const Button, int const Action ); void process_axes(); diff --git a/input/keyboardinput.cpp b/input/keyboardinput.cpp index 0279f055..4c2fdf8f 100644 --- a/input/keyboardinput.cpp +++ b/input/keyboardinput.cpp @@ -136,7 +136,7 @@ keyboard_input::recall_bindings() { // Fallback � plik w folderze symulatora path = "eu07_input-keyboard.ini"; } - cParser bindingparser(path.c_str(), cParser::buffer_FILE); + cParser bindingparser(path, cParser::buffer_FILE); bindingparser.skipComments = false; if( false == bindingparser.ok() ) { @@ -147,7 +147,7 @@ keyboard_input::recall_bindings() { std::unordered_map nametocommandmap; std::size_t commandid = 0; for( auto const &description : simulation::Commands_descriptions ) { - nametocommandmap.emplace( + nametocommandmap.try_emplace( description.name, static_cast( commandid ) ); ++commandid; @@ -155,7 +155,7 @@ keyboard_input::recall_bindings() { std::unordered_map nametokeymap; for (const std::pair &key : keytonamemap) { - nametokeymap.emplace(key.second, key.first); + nametokeymap.try_emplace(key.second, key.first); } // NOTE: to simplify things we expect one entry per line, and whole entry in one line @@ -225,7 +225,7 @@ keyboard_input::recall_bindings() { return true; } -void keyboard_input::dump_bindings() +void keyboard_input::dump_bindings() const { std::fstream stream("eu07_input-keyboard.ini", std::ios_base::binary | std::ios_base::trunc | std::ios_base::out); @@ -239,8 +239,7 @@ void keyboard_input::dump_bindings() stream << simulation::Commands_descriptions[static_cast(binding.first)].name << ' '; int keycode = std::get(binding.second); - auto it = keytonamemap.find(keycode & 0xFFFF); - if (it != keytonamemap.end()) { + if (auto it = keytonamemap.find(keycode & 0xFFFF); it != keytonamemap.end()) { if (keycode & keymodifier::control) stream << "ctrl "; if (keycode & keymodifier::shift) @@ -284,7 +283,7 @@ keyboard_input::key( int const Key, int const Action ) { if( Key == -1 ) { return false; } // store key state - input::keys[ Key ] = Action; + input::keys[ Key ] = static_cast( Action ); if( true == is_movement_key( Key ) ) { // if the received key was one of movement keys, it's been handled and we don't need to bother further @@ -298,8 +297,7 @@ keyboard_input::key( int const Key, int const Action ) { | ( modifier ? 0 : input::key_ctrl ? keymodifier::control : 0 ); if( Action == GLFW_RELEASE ) { - auto const stored = m_modsforkeys.find( Key ); - if( stored != m_modsforkeys.end() ) { + if( auto const stored = m_modsforkeys.find( Key ); stored != m_modsforkeys.end() ) { key = stored->second; } m_modsforkeys.erase( Key ); @@ -330,28 +328,29 @@ keyboard_input::key( int const Key ) const { void keyboard_input::bind() { + using enum user_command; m_bindings.clear(); - for( auto const &bindingsetup : m_bindingsetups ) { + for( auto const &[setupcommand, setupbinding] : m_bindingsetups ) { - m_bindings[ std::get(bindingsetup.second) ] = bindingsetup.first; + m_bindings[ std::get(setupbinding) ] = setupcommand; } // cache movement key bindings - m_bindingscache.forward = binding( user_command::moveforward ); - m_bindingscache.back = binding( user_command::moveback ); - m_bindingscache.left = binding( user_command::moveleft ); - m_bindingscache.right = binding( user_command::moveright ); - m_bindingscache.up = binding( user_command::moveup ); - m_bindingscache.down = binding( user_command::movedown ); + m_bindingscache.forward = binding( moveforward ); + m_bindingscache.back = binding( moveback ); + m_bindingscache.left = binding( moveleft ); + m_bindingscache.right = binding( moveright ); + m_bindingscache.up = binding( moveup ); + m_bindingscache.down = binding( movedown ); } int keyboard_input::binding( user_command const Command ) const { - for( auto const &binding : m_bindings ) { - if( binding.second == Command ) { - return binding.first; + for( auto const &[bindingkey, bindingcommand] : m_bindings ) { + if( bindingcommand == Command ) { + return bindingkey; } } return -1; @@ -413,7 +412,7 @@ keyboard_input::poll() { m_movementvertical = movementvertical; } -std::unordered_map keytonamemap = { +std::unordered_map const keytonamemap = { { GLFW_KEY_0, "0" }, { GLFW_KEY_1, "1" }, { GLFW_KEY_2, "2" }, { GLFW_KEY_3, "3" }, { GLFW_KEY_4, "4" }, { GLFW_KEY_5, "5" }, { GLFW_KEY_6, "6" }, { GLFW_KEY_7, "7" }, { GLFW_KEY_8, "8" }, { GLFW_KEY_9, "9" }, { GLFW_KEY_MINUS, "-" }, { GLFW_KEY_EQUAL, "=" }, diff --git a/input/keyboardinput.h b/input/keyboardinput.h index 1c1b5f2a..1611c9a3 100644 --- a/input/keyboardinput.h +++ b/input/keyboardinput.h @@ -56,7 +56,7 @@ public: void poll(); inline - user_command const + user_command command() const { return m_command; } bindingsetup_sequence& @@ -67,7 +67,7 @@ public: std::string binding_hint( user_command const Command ) const; void - dump_bindings(); + dump_bindings() const; // members static std::unordered_map keytonamemap; diff --git a/input/messaging.cpp b/input/messaging.cpp index 36ed853c..66a39e7d 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -32,7 +32,7 @@ namespace multiplayer { std::uint32_t const EU07_MESSAGEHEADER { MAKE_ID4( 'E','U','0','7' ) }; void -Navigate(std::string const &ClassName, UINT Msg, WPARAM wParam, LPARAM lParam) { +Navigate([[maybe_unused]] std::string const &ClassName, [[maybe_unused]] UINT Msg, [[maybe_unused]] WPARAM wParam, [[maybe_unused]] LPARAM lParam) { #ifdef _WIN32 // wysłanie komunikatu do sterującego HWND h = FindWindow(ClassName.c_str(), 0); // można by to zapamiętać @@ -43,7 +43,7 @@ Navigate(std::string const &ClassName, UINT Msg, WPARAM wParam, LPARAM lParam) { } void -OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) +OnCommandGet(multiplayer::DaneRozkaz const *pRozkaz) { // odebranie komunikatu z serwera if (pRozkaz->iSygn == EU07_MESSAGEHEADER ) switch (pRozkaz->iComm) @@ -62,15 +62,13 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) std::string( pRozkaz->cString + 1, (unsigned)pRozkaz->cString[0] ) + " rcvd" ); if( Global.iMultiplayer ) { - auto *event = simulation::Events.FindEvent( std::string( pRozkaz->cString + 1, (unsigned)pRozkaz->cString[0] ) ); - if( event != nullptr ) { - if( typeid(*event) == typeid(multi_event) - || typeid(*event) == typeid(lights_event) - || event->m_sibling != 0 ) { - // tylko jawne albo niejawne Multiple - command_relay relay; - relay.post(user_command::queueevent, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &event->name()); - } + auto const *foundevent = simulation::Events.FindEvent( std::string( pRozkaz->cString + 1, (unsigned)pRozkaz->cString[0] ) ); + if (foundevent != nullptr && (typeid(*foundevent) == typeid(multi_event) + || typeid(*foundevent) == typeid(lights_event) + || foundevent->m_sibling != nullptr)) { + // tylko jawne albo niejawne Multiple + command_relay commandrelay; + commandrelay.post(user_command::queueevent, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &foundevent->name()); } } break; @@ -78,7 +76,7 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) case 3: // rozkaz dla AI if (Global.iMultiplayer) { - int i = int(pRozkaz->cString[8]); // długość pierwszego łańcucha (z przodu dwa floaty) + auto i = int(pRozkaz->cString[8]); // długość pierwszego łańcucha (z przodu dwa floaty) CommLog( Now() + " " + std::to_string(pRozkaz->iComm) + " " + std::string(pRozkaz->cString + 11 + i, (unsigned)pRozkaz->cString[10 + i]) + @@ -110,21 +108,21 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) break; case 5: // ustawienie parametrów { - CommLog(Now() + " " + std::to_string(pRozkaz->iComm) + " params " + std::to_string(*pRozkaz->iPar) + " rcvd"); - if (*pRozkaz->iPar == 0) // sprawdzenie czasu - if (*pRozkaz->iPar & 1) // ustawienie czasu - { - auto t = pRozkaz->fPar[1]; - simulation::Time.data().wDay = std::floor(t); // niby nie powinno być dnia, ale... - if (Global.fMoveLight >= 0) - Global.fMoveLight = t; // trzeba by deklinację Słońca przeliczyć - simulation::Time.data().wHour = std::floor(24 * t) - 24.0 * simulation::Time.data().wDay; - simulation::Time.data().wMinute = std::floor(60 * 24 * t) - 60.0 * (24.0 * simulation::Time.data().wDay + simulation::Time.data().wHour); - simulation::Time.data().wSecond = std::floor( 60 * 60 * 24 * t ) - 60.0 * ( 60.0 * ( 24.0 * simulation::Time.data().wDay + simulation::Time.data().wHour ) + simulation::Time.data().wMinute ); - } - if (*pRozkaz->iPar & 2) + CommLog(Now() + " " + std::to_string(pRozkaz->iComm) + " params " + std::to_string(pRozkaz->iPar[0]) + " rcvd"); + // sprawdzenie czasu + if (pRozkaz->iPar[0] == 0 && pRozkaz->iPar[0] & 1) // ustawienie czasu + { + auto t = pRozkaz->fPar[1]; + simulation::Time.data().wDay = static_cast(std::floor(t)); // niby nie powinno być dnia, ale... + if (Global.fMoveLight >= 0) + Global.fMoveLight = t; // trzeba by deklinację Słońca przeliczyć + simulation::Time.data().wHour = static_cast(std::floor(24 * t) - 24.0 * simulation::Time.data().wDay); + simulation::Time.data().wMinute = static_cast(std::floor(60 * 24 * t) - 60.0 * (24.0 * simulation::Time.data().wDay + simulation::Time.data().wHour)); + simulation::Time.data().wSecond = static_cast(std::floor( 60 * 60 * 24 * t ) - 60.0 * ( 60.0 * ( 24.0 * simulation::Time.data().wDay + simulation::Time.data().wHour ) + simulation::Time.data().wMinute )); + } + if (pRozkaz->iPar[0] & 2) { // ustawienie flag zapauzowania - Global.iPause = pRozkaz->fPar[2]; // zakładamy, że wysyłający wie, co robi + Global.iPause = static_cast(pRozkaz->fPar[2]); // zakładamy, że wysyłający wie, co robi } } break; @@ -138,7 +136,7 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) + " rcvd" ); if (pRozkaz->cString[0]) { // jeśli długość nazwy jest niezerowa szukamy pierwszego pojazdu o takiej nazwie i odsyłamy parametry ramką #7 - auto *vehicle = pRozkaz->cString[1] == '*' ? simulation::Train->Dynamic() : simulation::Vehicles.find(std::string{pRozkaz->cString + 1, (unsigned)pRozkaz->cString[0]}); + auto const *vehicle = pRozkaz->cString[1] == '*' ? simulation::Train->Dynamic() : simulation::Vehicles.find(std::string{pRozkaz->cString + 1, (unsigned)pRozkaz->cString[0]}); if( vehicle != nullptr ) { WyslijNamiary( vehicle ); // wysłanie informacji o pojeździe } @@ -189,7 +187,7 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) d->Damage( pRozkaz->cString[ 0 ] ); d = d->Prev(); // w drugą stronę też } - WyslijUszkodzenia( lookup->asName, lookup->MoverParameters->EngDmgFlag ); // zwrot informacji o pojeździe + WyslijUszkodzenia( lookup->asName, static_cast(lookup->MoverParameters->EngDmgFlag) ); // zwrot informacji o pojeździe } break; default: @@ -198,7 +196,7 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) } void -WyslijEvent(const std::string &e, const std::string &d) +WyslijEvent([[maybe_unused]] const std::string &e, [[maybe_unused]] const std::string &d) { // Ra: jeszcze do wyczyszczenia #ifdef _WIN32 DaneRozkaz r; @@ -219,7 +217,7 @@ WyslijEvent(const std::string &e, const std::string &d) } void -WyslijUszkodzenia(const std::string &t, char fl) +WyslijUszkodzenia([[maybe_unused]] const std::string &t, [[maybe_unused]] char fl) { // wysłanie informacji w postaci pojedynczego tekstu #ifdef _WIN32 DaneRozkaz r; @@ -239,7 +237,7 @@ WyslijUszkodzenia(const std::string &t, char fl) } void -WyslijString(const std::string &t, int n) +WyslijString([[maybe_unused]] const std::string &t, [[maybe_unused]] int n) { // wysłanie informacji w postaci pojedynczego tekstu #ifdef _WIN32 DaneRozkaz r; @@ -264,7 +262,7 @@ WyslijWolny(const std::string &t) } void -WyslijNamiary(TDynamicObject const *Vehicle) +WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) { // wysłanie informacji o pojeździe - (float), długość ramki będzie zwiększana w miarę potrzeby #ifdef _WIN32 DaneRozkaz r; @@ -395,7 +393,7 @@ WyslijObsadzone() } void -WyslijParam(int nr, int fl) +WyslijParam([[maybe_unused]] int nr, [[maybe_unused]] int fl) { // wysłanie parametrów symulacji w ramce (nr) z flagami (fl) #ifdef _WIN32 DaneRozkaz r; diff --git a/input/messaging.h b/input/messaging.h index f3592b27..40434db2 100644 --- a/input/messaging.h +++ b/input/messaging.h @@ -38,7 +38,7 @@ struct DaneRozkaz2 { // struktura komunikacji z EU07.EXE void Navigate( std::string const &ClassName, UINT Msg, WPARAM wParam, LPARAM lParam ); -void OnCommandGet( multiplayer::DaneRozkaz *pRozkaz ); +void OnCommandGet( multiplayer::DaneRozkaz const *pRozkaz ); void WyslijEvent( const std::string &e, const std::string &d ); void WyslijString( const std::string &t, int n ); diff --git a/launcher/deferred_image.h b/launcher/deferred_image.h index 85582264..58850fb0 100644 --- a/launcher/deferred_image.h +++ b/launcher/deferred_image.h @@ -11,11 +11,11 @@ public: static constexpr GLuint invalid_id { std::numeric_limits::max() }; deferred_image() = default; - deferred_image(const std::string &p) : path(p) { } + explicit deferred_image(const std::string &p) : path(p) { } deferred_image(const deferred_image&) = delete; deferred_image(deferred_image&&) = default; deferred_image &operator=(deferred_image&&) = default; - operator bool() const + explicit operator bool() const { return image != null_handle || !path.empty(); } @@ -33,7 +33,7 @@ public: tex.create(); if (tex.get_is_ready()) - return tex.get_id(); + return static_cast(tex.get_id()); } return invalid_id; @@ -42,7 +42,7 @@ public: glm::ivec2 size() const { if (image != null_handle) { - auto &tex = GfxRenderer->Texture(image); + auto const &tex = GfxRenderer->Texture(image); return glm::ivec2(tex.get_width(), tex.get_height()); } return glm::ivec2(); diff --git a/launcher/launchermode.cpp b/launcher/launchermode.cpp index 08c4c101..5059fa37 100644 --- a/launcher/launchermode.cpp +++ b/launcher/launchermode.cpp @@ -29,7 +29,7 @@ void launcher_mode::enter() void launcher_mode::exit() { - + // nothing to do } void launcher_mode::on_key(const int Key, const int Scancode, const int Action, const int Mods) diff --git a/launcher/launchermode.h b/launcher/launchermode.h index 53a65f4d..0a9475e3 100644 --- a/launcher/launchermode.h +++ b/launcher/launchermode.h @@ -27,10 +27,10 @@ public: void exit() override; // input handlers void on_key( int Key, int Scancode, int Action, int Mods ) override; - void on_cursor_pos( double const Horizontal, double const Vertical ) override { ; } - void on_mouse_button( int const Button, int const Action, int const Mods ) override { ; } - void on_scroll( double const Xoffset, double const Yoffset ) override { ; } + void on_cursor_pos( double const Horizontal, double const Vertical ) override { /* not handled by the launcher */ } + void on_mouse_button( int const Button, int const Action, int const Mods ) override { /* not handled by the launcher */ } + void on_scroll( double const Xoffset, double const Yoffset ) override { /* not handled by the launcher */ } void on_window_resize( int w, int h ) override; - void on_event_poll() override { ; } + void on_event_poll() override { /* not handled by the launcher */ } bool is_command_processor() const override { return false; } }; diff --git a/launcher/textures_scanner.cpp b/launcher/textures_scanner.cpp index 201ff967..524a23ca 100644 --- a/launcher/textures_scanner.cpp +++ b/launcher/textures_scanner.cpp @@ -47,7 +47,7 @@ void ui::vehicles_bank::parse_entry(const std::string &line) if (line[0] == '!') parse_category_entry(param); - else if (line[0] == '*' && line[1] == '*') + else if (line.starts_with("**")) parse_texture_rule(target.substr(2), param); else if (line[0] == '*') parse_coupling_rule(target.substr(1), param); @@ -60,23 +60,24 @@ void ui::vehicles_bank::parse_entry(const std::string &line) void ui::vehicles_bank::parse_category_entry(const std::string ¶m) { + using enum ui::vehicle_type; static std::unordered_map type_map = { - { 'e', vehicle_type::electric_loco }, - { 's', vehicle_type::diesel_loco }, - { 'p', vehicle_type::steam_loco }, - { 'a', vehicle_type::railcar }, - { 'z', vehicle_type::emu }, - { 'r', vehicle_type::utility }, - { 'd', vehicle_type::draisine }, - { 't', vehicle_type::tram }, - { 'c', vehicle_type::truck }, - { 'b', vehicle_type::bus }, - { 'o', vehicle_type::car }, - { 'h', vehicle_type::man }, - { 'f', vehicle_type::animal }, + { 'e', electric_loco }, + { 's', diesel_loco }, + { 'p', steam_loco }, + { 'a', railcar }, + { 'z', emu }, + { 'r', utility }, + { 'd', draisine }, + { 't', tram }, + { 'c', truck }, + { 'b', bus }, + { 'o', car }, + { 'h', man }, + { 'f', animal }, }; - ctx_type = vehicle_type::unknown; + ctx_type = unknown; std::istringstream stream(param); @@ -86,16 +87,15 @@ void ui::vehicles_bank::parse_category_entry(const std::string ¶m) if (tok.size() < 1) return; - auto it = type_map.find(tok[0]); - if (it != type_map.end()) + if (auto it = type_map.find(tok[0]); it != type_map.end()) ctx_type = it->second; else if (tok[0] >= 'A' && tok[0] <= 'Z') - ctx_type = vehicle_type::carriage; + ctx_type = carriage; std::string mini; std::getline(stream, mini, ','); - category_icons.emplace(ctx_type, "textures/mini/" + ToLower(mini) + ".bmp"); + category_icons.try_emplace(ctx_type, "textures/mini/" + ToLower(mini) + ".bmp"); } void ui::vehicles_bank::parse_controllable_entry(const std::string &target, const std::string ¶m) @@ -108,7 +108,9 @@ void ui::vehicles_bank::parse_texture_info(const std::string &target, const std: { std::istringstream stream(param); - std::string model, mini, miniplus; + std::string model; + std::string mini; + std::string miniplus; std::getline(stream, model, ','); std::getline(stream, mini, ','); @@ -122,12 +124,12 @@ void ui::vehicles_bank::parse_texture_info(const std::string &target, const std: set.meta = meta; if (!mini.empty()) - group_icons.emplace(mini, std::move(deferred_image("textures/mini/" + ToLower(mini) + ".bmp"))); + group_icons.try_emplace(mini, deferred_image("textures/mini/" + ToLower(mini) + ".bmp")); if (!miniplus.empty()) - set.mini = std::move(deferred_image("textures/mini/" + ToLower(miniplus) + ".bmp")); + set.mini = deferred_image("textures/mini/" + ToLower(miniplus) + ".bmp"); else if (!mini.empty()) - set.mini = std::move(deferred_image("textures/mini/" + ToLower(mini) + ".bmp")); + set.mini = deferred_image("textures/mini/" + ToLower(mini) + ".bmp"); set.skin = ToLower(target); erase_extension(set.skin); @@ -143,7 +145,7 @@ void ui::vehicles_bank::parse_texture_info(const std::string &target, const std: vehicle->matching_skinsets.push_back(std::make_shared(std::move(set))); } -std::shared_ptr ui::vehicles_bank::parse_meta(const std::string &str) +std::shared_ptr ui::vehicles_bank::parse_meta(const std::string &str) const { std::istringstream stream(str); @@ -171,19 +173,20 @@ std::shared_ptr ui::vehicles_bank::parse_meta(const std::string & ToLower("n:" + meta->name + ":i:" + meta->short_id + ":d:" + meta->location + ":r:" + meta->rev_date + ":c:" + meta->rev_company + ":t:" + meta->texture_author + ":p:" + meta->photo_author); - std::replace(std::begin(meta->location), std::end(meta->location), '_', ' '); - std::replace(std::begin(meta->rev_company), std::end(meta->rev_company), '_', ' '); - std::replace(std::begin(meta->texture_author), std::end(meta->texture_author), '_', ' '); - std::replace(std::begin(meta->photo_author), std::end(meta->photo_author), '_', ' '); + std::ranges::replace(meta->location, '_', ' '); + std::ranges::replace(meta->rev_company, '_', ' '); + std::ranges::replace(meta->texture_author, '_', ' '); + std::ranges::replace(meta->photo_author, '_', ' '); if (!meta->rev_date.empty() && meta->rev_date != "?") { - std::istringstream stream(meta->rev_date); - std::string day, month; + std::istringstream datestream(meta->rev_date); + std::string day; + std::string month; - std::getline(stream, day, '.'); - std::getline(stream, month, '.'); + std::getline(datestream, day, '.'); + std::getline(datestream, month, '.'); - stream >> meta->rev_year; + datestream >> meta->rev_year; } return meta; @@ -205,7 +208,8 @@ void ui::vehicles_bank::parse_coupling_rule(const std::string &target, const std std::string connected; std::getline(stream, connected, ','); - std::string param1, param2; + std::string param1; + std::string param2; std::getline(stream, param1, ','); std::getline(stream, param2, ','); @@ -232,7 +236,8 @@ void ui::vehicles_bank::parse_texture_rule(const std::string &target, const std: std::istringstream rule_stream(replace_rule); - std::string src, dst; + std::string src; + std::string dst; std::getline(rule_stream, src, '-'); std::getline(rule_stream, dst, '-'); @@ -257,7 +262,7 @@ std::shared_ptr ui::vehicles_bank::get_vehicle(const std::stri auto desc = std::make_shared(); desc->type = ctx_type; desc->path = path; - vehicles.emplace(path, desc); + vehicles.try_emplace(path, desc); return desc; } } diff --git a/launcher/textures_scanner.h b/launcher/textures_scanner.h index affa0b94..5f4cb084 100644 --- a/launcher/textures_scanner.h +++ b/launcher/textures_scanner.h @@ -87,7 +87,7 @@ private: void parse_texture_rule(const std::string &target, const std::string ¶m); void parse_texture_info(const std::string &target, const std::string ¶m, std::shared_ptr meta); - std::shared_ptr parse_meta(const std::string &str); + std::shared_ptr parse_meta(const std::string &str) const; std::shared_ptr get_vehicle(const std::string &name); vehicle_type ctx_type = vehicle_type::unknown; diff --git a/model/MdlMngr.cpp b/model/MdlMngr.cpp index 9ead9716..680f67c4 100644 --- a/model/MdlMngr.cpp +++ b/model/MdlMngr.cpp @@ -47,11 +47,11 @@ TModelsManager::LoadModel(std::string const &Name, std::string const &virtualNam m_models.emplace_back(); auto model = m_models.back().LoadModel( Name, dynamic ); if( model != nullptr ) { - m_modelsmap.emplace( virtualName, m_models.size() - 1 ); + m_modelsmap.try_emplace( virtualName, m_models.size() - 1 ); } else { m_models.pop_back(); - m_modelsmap.emplace( virtualName, null_handle ); + m_modelsmap.try_emplace( virtualName, null_handle ); } return model; } @@ -95,17 +95,16 @@ TModelsManager::GetModel(std::string const &Name, bool const Dynamic, bool const postfix = "^^" + std::to_string(uid); // see if we have it in the databank - auto banklookup { find_in_databank( filename + postfix ) }; - TModel3d *model { banklookup.second }; - if( true == banklookup.first ) { + auto [banklookupfound, banklookupmodel]{ find_in_databank( filename + postfix ) }; + TModel3d *model { banklookupmodel }; + if( true == banklookupfound ) { Global.asCurrentTexturePath = buftp; return model; } // first load attempt, check if it's on disk - std::string disklookup { find_on_disk( filename ) }; - if( false == disklookup.empty() ) { + if( std::string disklookup { find_on_disk( filename ) }; false == disklookup.empty() ) { model = LoadModel( disklookup, disklookup + postfix, Dynamic ); // model nie znaleziony, to wczytać } else { @@ -114,7 +113,7 @@ TModelsManager::GetModel(std::string const &Name, bool const Dynamic, bool const ErrorLog( "Bad file: failed to locate 3d model file \"" + filename + "\"", logtype::file ); } // ...and link it with the error model slot - m_modelsmap.emplace( filename + postfix, null_handle ); + m_modelsmap.try_emplace( filename + postfix, null_handle ); } Global.asCurrentTexturePath = buftp; // odtworzenie ścieżki do tekstur return model; // NULL jeśli błąd diff --git a/model/MdlMngr.h b/model/MdlMngr.h index 94baf3d4..fb255f2e 100644 --- a/model/MdlMngr.h +++ b/model/MdlMngr.h @@ -12,7 +12,6 @@ http://mozilla.org/MPL/2.0/. class TMdlContainer { friend class TModelsManager; -private: TModel3d *LoadModel( std::string const &Name, bool const Dynamic ); std::shared_ptr Model { nullptr }; std::string m_name; @@ -26,8 +25,8 @@ public: private: // types: - typedef std::deque modelcontainer_sequence; - typedef std::unordered_map stringmodelcontainerindex_map; + using modelcontainer_sequence = std::deque; + using stringmodelcontainerindex_map = std::unordered_map; // members: static modelcontainer_sequence m_models; static stringmodelcontainerindex_map m_modelsmap; diff --git a/model/vertex.h b/model/vertex.h index 4c2ff2ad..3bcc7bd5 100644 --- a/model/vertex.h +++ b/model/vertex.h @@ -19,7 +19,7 @@ struct world_vertex { static world_vertex lerp(world_vertex const &a, world_vertex const &b, double factor) { - return static_cast(a * (1.0f - factor) + b * factor); + return a * (1.0f - factor) + b * factor; } // overloads diff --git a/network/backend/asio.cpp b/network/backend/asio.cpp index c2d1364d..f0400518 100644 --- a/network/backend/asio.cpp +++ b/network/backend/asio.cpp @@ -37,8 +37,7 @@ void network::tcp::connection::connected() void network::tcp::connection::read_header() { asio::async_read(m_socket, asio::buffer(m_header_buffer), - std::bind(&connection::handle_header, this, - std::placeholders::_1, std::placeholders::_2)); + std::bind_front(&connection::handle_header, this)); } void network::tcp::connection::handle_header(const asio::error_code &err, size_t bytes_transferred) @@ -54,8 +53,7 @@ void network::tcp::connection::handle_header(const asio::error_code &err, size_t return; } - uint32_t sig = sn_utils::ld_uint32(header); - if (sig != NETWORK_MAGIC) { + if (uint32_t sig = sn_utils::ld_uint32(header); sig != NETWORK_MAGIC) { disconnect(); return; } @@ -68,7 +66,7 @@ void network::tcp::connection::handle_header(const asio::error_code &err, size_t } asio::async_read(m_socket, asio::buffer(m_body_buffer), - std::bind(&connection::handle_data, this, std::placeholders::_1, std::placeholders::_2)); + std::bind_front(&connection::handle_data, this)); } void network::tcp::connection::handle_data(const asio::error_code &err, size_t bytes_transferred) @@ -91,9 +89,9 @@ void network::tcp::connection::handle_data(const asio::error_code &err, size_t b read_header(); } -void network::tcp::connection::write_message(const message &msg, std::ostream &stream) +void network::tcp::connection::write_message(const message &msg, std::ostream &stream) const { - size_t beg = (size_t)stream.tellp(); + auto beg = (size_t)stream.tellp(); sn_utils::ls_uint32(stream, NETWORK_MAGIC); sn_utils::ls_uint32(stream, 0); @@ -106,14 +104,14 @@ void network::tcp::connection::write_message(const message &msg, std::ostream &s return; } stream.seekp(beg + 4, std::ios_base::beg); - sn_utils::ls_uint32(stream, size); + sn_utils::ls_uint32(stream, static_cast(size)); stream.seekp(0, std::ios_base::end); } void network::tcp::connection::send_messages(const std::vector > &messages) { - if (messages.size() == 0) + if (messages.empty()) return; std::ostringstream stream; @@ -138,7 +136,7 @@ void network::tcp::connection::send_message(const message &msg) network::tcp::server::server(std::shared_ptr buf, asio::io_context &io_ctx, const std::string &host, uint32_t port) : network::server(buf), m_acceptor(io_ctx), m_io_ctx(io_ctx) { - auto endpoint = asio::ip::tcp::endpoint(asio::ip::make_address(host), port); + auto endpoint = asio::ip::tcp::endpoint(asio::ip::make_address(host), static_cast(port)); m_acceptor.open(endpoint.protocol()); m_acceptor.set_option(asio::socket_base::reuse_address(true)); m_acceptor.set_option(asio::ip::tcp::no_delay(true)); @@ -150,10 +148,10 @@ network::tcp::server::server(std::shared_ptr buf, asio::io_context void network::tcp::server::accept_conn() { - std::shared_ptr conn = std::make_shared(m_io_ctx); - conn->set_handler(std::bind(&server::handle_message, this, conn, std::placeholders::_1)); + auto conn = std::make_shared(m_io_ctx); + conn->set_handler(std::bind_front(&server::handle_message, this, conn)); - m_acceptor.async_accept(conn->m_socket, std::bind(&server::handle_accept, this, conn, std::placeholders::_1)); + m_acceptor.async_accept(conn->m_socket, std::bind_front(&server::handle_accept, this, conn)); } void network::tcp::server::handle_accept(std::shared_ptr conn, const asio::error_code &err) @@ -175,7 +173,7 @@ void network::tcp::server::handle_accept(std::shared_ptr conn, const // ------------------ network::tcp::client::client(asio::io_context &io_ctxx, const std::string &hostarg, uint32_t portarg) - : host(hostarg), port(portarg), io_ctx(io_ctxx) + : io_ctx(io_ctxx), host(hostarg), port(portarg) { } @@ -184,21 +182,21 @@ void network::tcp::client::connect() if (this->conn) return; - std::shared_ptr conn = std::make_shared(io_ctx, true, resume_frame_counter); - conn->set_handler(std::bind(&client::handle_message, this, conn, std::placeholders::_1)); + auto newconnection = std::make_shared(io_ctx, true, resume_frame_counter); + newconnection->set_handler(std::bind_front(&client::handle_message, this, newconnection)); asio::ip::tcp::endpoint endpoint( - asio::ip::make_address(host), port); - conn->m_socket.open(endpoint.protocol()); - conn->m_socket.set_option(asio::ip::tcp::no_delay(true)); - conn->m_socket.async_connect(endpoint, - std::bind(&client::handle_accept, this, std::placeholders::_1)); + asio::ip::make_address(host), static_cast(port)); + newconnection->m_socket.open(endpoint.protocol()); + newconnection->m_socket.set_option(asio::ip::tcp::no_delay(true)); + newconnection->m_socket.async_connect(endpoint, + std::bind_front(&client::handle_accept, this)); - this->conn = conn; + this->conn = newconnection; } -void network::tcp::client::handle_accept(const asio::error_code &err) +void network::tcp::client::handle_accept(const asio::error_code &err) const { if (!err) { @@ -212,7 +210,7 @@ void network::tcp::client::handle_accept(const asio::error_code &err) } network::tcp::asio_manager::asio_manager() { - backend_list().emplace("tcp", this); + backend_list().try_emplace("tcp", this); } std::shared_ptr network::tcp::asio_manager::create_server(std::shared_ptr backbuffer, const std::string &conf) { diff --git a/network/backend/asio.h b/network/backend/asio.h index 47e731c7..2bc4fc6b 100644 --- a/network/backend/asio.h +++ b/network/backend/asio.h @@ -18,13 +18,13 @@ namespace network::tcp friend class client; public: - connection(asio::io_context &io_ctx, bool client = false, size_t counter = 0); + explicit connection(asio::io_context &io_ctx, bool client = false, size_t counter = 0); ~connection(); - virtual void connected() override; - virtual void disconnect() override; - virtual void send_messages(const std::vector > &messages) override; - virtual void send_message(const message &msg) override; + void connected() override; + void disconnect() override; + void send_messages(const std::vector > &messages) override; + void send_message(const message &msg) override; asio::ip::tcp::socket m_socket; @@ -32,7 +32,7 @@ namespace network::tcp std::string m_header_buffer; std::string m_body_buffer; - void write_message(const message &msg, std::ostream &stream); + void write_message(const message &msg, std::ostream &stream) const; void send_data(std::shared_ptr buffer); void read_header(); void handle_header(const asio::error_code &err, size_t bytes_transferred); @@ -55,13 +55,13 @@ namespace network::tcp class client : public network::client { private: - void handle_accept(const asio::error_code &err); + void handle_accept(const asio::error_code &err) const; asio::io_context &io_ctx; std::string host; uint32_t port; protected: - virtual void connect() override; + void connect() override; public: client(asio::io_context &io_ctx, const std::string &host, uint32_t port); @@ -73,9 +73,9 @@ namespace network::tcp public: asio_manager(); - virtual std::shared_ptr create_server(std::shared_ptr, const std::string &conf) override; - virtual std::shared_ptr create_client(const std::string &conf) override; - virtual void update() override; + std::shared_ptr create_server(std::shared_ptr, const std::string &conf) override; + std::shared_ptr create_client(const std::string &conf) override; + void update() override; }; asio_manager manager; diff --git a/network/manager.cpp b/network/manager.cpp index 37d72401..932f9b08 100644 --- a/network/manager.cpp +++ b/network/manager.cpp @@ -17,7 +17,7 @@ network::server_manager::server_manager() backbuffer = std::make_shared("backbuffer.bin", std::ios::out | std::ios::in | std::ios::trunc | std::ios::binary); } -command_queue::commands_map network::server_manager::pop_commands() +command_queue::commands_map network::server_manager::pop_commands() const { command_queue::commands_map map; @@ -27,7 +27,7 @@ command_queue::commands_map network::server_manager::pop_commands() return map; } -void network::server_manager::push_delta(double render_dt, double dt, double sync, const command_queue::commands_map &commands) +void network::server_manager::push_delta(double render_dt, double dt, double sync, const command_queue::commands_map &commands) const { if (dt == 0.0 && commands.empty()) return; @@ -55,14 +55,12 @@ void network::server_manager::create_server(const std::string &backend, const st servers.emplace_back(it->second->create_server(backbuffer, conf)); } -network::manager::manager() -{ -} +network::manager::manager() = default; void network::manager::update() { - for (auto &backend : backend_list()) - backend.second->update(); + for (auto const &[backendname, backendinstance] : backend_list()) + backendinstance->update(); if (client) client->update(); diff --git a/network/manager.h b/network/manager.h index 572a8c6b..85f39d6c 100644 --- a/network/manager.h +++ b/network/manager.h @@ -14,8 +14,8 @@ namespace network public: server_manager(); - void push_delta(double render_dt, double dt, double sync, const command_queue::commands_map &commands); - command_queue::commands_map pop_commands(); + void push_delta(double render_dt, double dt, double sync, const command_queue::commands_map &commands) const; + command_queue::commands_map pop_commands() const; void create_server(const std::string &backend, const std::string &conf); }; diff --git a/network/message.cpp b/network/message.cpp index 12609905..a87269cd 100644 --- a/network/message.cpp +++ b/network/message.cpp @@ -32,12 +32,12 @@ void network::server_hello::deserialize(std::istream &stream) void ::network::request_command::serialize(std::ostream &stream) const { - sn_utils::ls_uint32(stream, commands.size()); - for (auto const &kv : commands) + sn_utils::ls_uint32(stream, static_cast(commands.size())); + for (auto const &[recipient, sequence] : commands) { - sn_utils::ls_uint32(stream, kv.first); - sn_utils::ls_uint32(stream, kv.second.size()); - for (command_data const &data : kv.second) + sn_utils::ls_uint32(stream, recipient); + sn_utils::ls_uint32(stream, static_cast(sequence.size())); + for (command_data const &data : sequence) { sn_utils::ls_uint32(stream, (uint32_t)data.command); sn_utils::ls_int32(stream, data.action); @@ -62,7 +62,7 @@ void network::request_command::deserialize(std::istream &stream) uint32_t sequence_size = sn_utils::ld_uint32(stream); command_queue::commanddata_sequence sequence; - for (uint32_t i = 0; i < sequence_size; i++) + for (uint32_t j = 0; j < sequence_size; j++) { command_data data; data.command = (user_command)sn_utils::ld_uint32(stream); @@ -79,7 +79,7 @@ void network::request_command::deserialize(std::istream &stream) sequence.emplace_back(data); } - commands.emplace(recipient, sequence); + commands.try_emplace(recipient, sequence); } } @@ -103,7 +103,7 @@ void network::frame_info::deserialize(std::istream &stream) std::shared_ptr network::deserialize_message(std::istream &stream) { - message::type_e type = (message::type_e)sn_utils::ld_uint16(stream); + auto type = (message::type_e)sn_utils::ld_uint16(stream); std::shared_ptr msg; diff --git a/network/message.h b/network/message.h index 5aa07d78..38a16c00 100644 --- a/network/message.h +++ b/network/message.h @@ -18,17 +18,18 @@ struct message type_e type; - message(type_e t) : type(t) {} - virtual void serialize(std::ostream &stream) const {} - virtual void deserialize(std::istream &stream) {} + explicit message(type_e t) : type(t) {} + virtual void serialize(std::ostream &stream) const { /* message carries no payload */ } + virtual void deserialize(std::istream &stream) { /* message carries no payload */ } + virtual ~message() = default; }; struct client_hello : public message { client_hello() : message(CLIENT_HELLO) {} - virtual void serialize(std::ostream &stream) const override; - virtual void deserialize(std::istream &stream) override; + void serialize(std::ostream &stream) const override; + void deserialize(std::istream &stream) override; int32_t version{0}; uint32_t start_packet{0}; @@ -43,19 +44,19 @@ struct server_hello : public message int64_t config{0}; std::string scenario; - virtual void serialize(std::ostream &stream) const override; - virtual void deserialize(std::istream &stream) override; + void serialize(std::ostream &stream) const override; + void deserialize(std::istream &stream) override; }; struct request_command : public message { - request_command(type_e type) : message(type) {} + using message::message; request_command() : message(REQUEST_COMMAND) {} command_queue::commands_map commands; - virtual void serialize(std::ostream &stream) const override; - virtual void deserialize(std::istream &stream) override; + void serialize(std::ostream &stream) const override; + void deserialize(std::istream &stream) override; }; struct frame_info : public request_command @@ -66,8 +67,8 @@ struct frame_info : public request_command double dt{0.0}; double sync{0.0}; - virtual void serialize(std::ostream &stream) const override; - virtual void deserialize(std::istream &stream) override; + void serialize(std::ostream &stream) const override; + void deserialize(std::istream &stream) override; }; std::shared_ptr deserialize_message(std::istream &stream); diff --git a/network/network.cpp b/network/network.cpp index ae83bf78..b5eeced4 100644 --- a/network/network.cpp +++ b/network/network.cpp @@ -30,9 +30,7 @@ void network::connection::set_handler(std::function hand message_handler = handler; } -network::connection::connection(bool client, size_t counter) { - packet_counter = counter; - is_client = client; +network::connection::connection(bool client, size_t counter) : is_client(client), packet_counter(counter) { state = AWAITING_HELLO; } @@ -43,7 +41,7 @@ void network::connection::connected() if (is_client) { client_hello msg; msg.version = EU07_NETWORK_VERSION; - msg.start_packet = packet_counter; + msg.start_packet = static_cast(packet_counter); send_message(msg); } } @@ -79,7 +77,7 @@ void network::connection::catch_up() send_messages(messages); } -void network::connection::send_complete(std::shared_ptr buf) +void network::connection::send_complete(std::shared_ptr /*buf*/) { if (!is_client && state == CATCHING_UP) { catch_up(); @@ -151,7 +149,7 @@ void network::server::handle_message(std::shared_ptr conn, const mes const auto& cmd = dynamic_cast(msg); for (auto const &kv : cmd.commands) - client_commands_queue.emplace(kv); + client_commands_queue.try_emplace(kv.first, kv.second); } } @@ -188,9 +186,9 @@ std::tuple network::client::get_nex } - float size = delta_queue.size() - consume_counter; + float size = static_cast(delta_queue.size()) - consume_counter; const auto& entry = delta_queue.front(); - float mult = entry.render_dt / std::chrono::duration_cast>(frame_time).count(); + auto mult = static_cast(entry.render_dt / std::chrono::duration_cast>(frame_time).count()); if (counter == 1 && size < MAX_BUFFER_SIZE * 2.0f) { last_target = last_target * TARGET_MIX + @@ -220,7 +218,7 @@ std::tuple network::client::get_nex } } -void network::client::send_commands(command_queue::commands_map commands) +void network::client::send_commands(command_queue::commands_map const &commands) const { if (!conn || conn->state == connection::DEAD || commands.empty()) return; @@ -232,17 +230,17 @@ void network::client::send_commands(command_queue::commands_map commands) conn->send_message(msg); } -void network::client::handle_message(std::shared_ptr conn, const message &msg) +void network::client::handle_message(std::shared_ptr Connection, const message &msg) { if (msg.type >= message::TYPE_MAX) { - conn->disconnect(); + Connection->disconnect(); return; } if (msg.type == message::SERVER_HELLO) { const auto& cmd = dynamic_cast(msg); - conn->state = connection::ACTIVE; + Connection->state = connection::ACTIVE; if (!Global.ready_to_load) { Global.random_seed = cmd.seed; @@ -253,14 +251,14 @@ void network::client::handle_message(std::shared_ptr conn, const mes Global.ready_to_load = true; } else if (Global.random_seed != cmd.seed) { ErrorLog("net: seed mismatch", logtype::net); - conn->disconnect(); + Connection->disconnect(); return; } WriteLog("net: accept received", logtype::net); } - if (conn->state != connection::ACTIVE) + if (Connection->state != connection::ACTIVE) return; if (msg.type == message::FRAME_INFO) { diff --git a/network/network.h b/network/network.h index 1ce802be..e1d7ec57 100644 --- a/network/network.h +++ b/network/network.h @@ -35,7 +35,7 @@ namespace network virtual void send_message(const message &msg) = 0; virtual void send_messages(const std::vector> &messages) = 0; - connection(bool client = false, size_t counter = 0); + explicit connection(bool client = false, size_t counter = 0); void set_handler(std::function handler); virtual void disconnect() = 0; @@ -47,6 +47,7 @@ namespace network DEAD }; peer_state state; + virtual ~connection() = default; }; class server @@ -62,7 +63,7 @@ namespace network command_queue::commands_map client_commands_queue; public: - server(std::shared_ptr buf); + explicit server(std::shared_ptr buf); void push_delta(const frame_info &msg); command_queue::commands_map pop_commands(); }; @@ -97,13 +98,14 @@ namespace network public: void update(); std::tuple get_next_delta(int counter); - void send_commands(command_queue::commands_map commands); - int get_frame_counter() { - return resume_frame_counter; + void send_commands(command_queue::commands_map const &commands) const; + int get_frame_counter() const { + return static_cast(resume_frame_counter); } - int get_awaiting_frames() { - return delta_queue.size(); + int get_awaiting_frames() const { + return static_cast(delta_queue.size()); } + virtual ~client() = default; }; class backend_manager @@ -112,6 +114,7 @@ namespace network virtual std::shared_ptr create_server(std::shared_ptr, const std::string &conf) = 0; virtual std::shared_ptr create_client(const std::string &conf) = 0; virtual void update() = 0; + virtual ~backend_manager() = default; }; // HACK: static initialization order fiasco fix diff --git a/rendering/flip-s3tc.h b/rendering/flip-s3tc.h index a529add4..ee05b73f 100644 --- a/rendering/flip-s3tc.h +++ b/rendering/flip-s3tc.h @@ -14,39 +14,43 @@ namespace flip_s3tc struct dxt1_block { - uint16_t c0, c1; - uint8_t dcba, - hgfe, - lkji, - ponm; + uint16_t c0; + uint16_t c1; + uint8_t dcba; + uint8_t hgfe; + uint8_t lkji; + uint8_t ponm; }; struct dxt23_block { - uint16_t adacabaa, - ahagafae, - alakajai, - apaoanam; - uint16_t c0, c1; - uint8_t dcba, - hgfe, - lkji, - ponm; + uint16_t adacabaa; + uint16_t ahagafae; + uint16_t alakajai; + uint16_t apaoanam; + uint16_t c0; + uint16_t c1; + uint8_t dcba; + uint8_t hgfe; + uint8_t lkji; + uint8_t ponm; }; struct dxt45_block { - uint8_t a0, a1; + uint8_t a0; + uint8_t a1; struct { uint8_t alpha[3]; } ahagafaeadacabaa, apaoanamalakajai; - uint16_t c0, c1; - uint8_t dcba, - hgfe, - lkji, - ponm; + uint16_t c0; + uint16_t c1; + uint8_t dcba; + uint8_t hgfe; + uint8_t lkji; + uint8_t ponm; }; #pragma pack(pop) @@ -123,16 +127,16 @@ void flip_dxt45_block(struct dxt45_block *block) */ void flip_dxt1_image(void *data, int width, int height) { - int x, y; - struct dxt1_block temp1, temp2; - struct dxt1_block *blocks = (struct dxt1_block *)data; + struct dxt1_block temp1; + struct dxt1_block temp2; + auto blocks = (struct dxt1_block *)data; width = (width + 3) / 4; height = (height + 3) / 4; - for (y = 0; y < height / 2; ++y) + for (int y = 0; y < height / 2; ++y) { - for (x = 0; x < width; ++x) + for (int x = 0; x < width; ++x) { temp1 = blocks[y * width + x]; temp2 = blocks[(height - y - 1) * width + x]; @@ -152,16 +156,16 @@ void flip_dxt1_image(void *data, int width, int height) */ void flip_dxt23_image(void *data, int width, int height) { - int x, y; - struct dxt23_block temp1, temp2; - struct dxt23_block *blocks = (struct dxt23_block *)data; + struct dxt23_block temp1; + struct dxt23_block temp2; + auto blocks = (struct dxt23_block *)data; width = (width + 3) / 4; height = (height + 3) / 4; - for (y = 0; y < height / 2; ++y) + for (int y = 0; y < height / 2; ++y) { - for (x = 0; x < width; ++x) + for (int x = 0; x < width; ++x) { temp1 = blocks[y * width + x]; temp2 = blocks[(height - y - 1) * width + x]; @@ -181,16 +185,16 @@ void flip_dxt23_image(void *data, int width, int height) */ void flip_dxt45_image(void *data, int width, int height) { - int x, y; - struct dxt45_block temp1, temp2; - struct dxt45_block *blocks = (struct dxt45_block *)data; + struct dxt45_block temp1; + struct dxt45_block temp2; + auto blocks = (struct dxt45_block *)data; width = (width + 3) / 4; height = (height + 3) / 4; - for (y = 0; y < height / 2; ++y) + for (int y = 0; y < height / 2; ++y) { - for (x = 0; x < width; ++x) + for (int x = 0; x < width; ++x) { temp1 = blocks[y * width + x]; temp2 = blocks[(height - y - 1) * width + x]; diff --git a/rendering/frustum.cpp b/rendering/frustum.cpp index f4677065..68349a5f 100644 --- a/rendering/frustum.cpp +++ b/rendering/frustum.cpp @@ -24,7 +24,7 @@ cFrustum::calculate( glm::mat4 const &Projection, glm::mat4 const &Modelview ) { // multiply the matrices to retrieve clipping planes (column-major, same layout as the old float[16] form) auto const clipmatrix { Projection * Modelview }; - float clip[ 16 ]; + std::array clip{}; for( int column = 0; column < 4; ++column ) { for( int row = 0; row < 4; ++row ) { clip[ column * 4 + row ] = clipmatrix[ column ][ row ]; @@ -73,16 +73,11 @@ bool cFrustum::point_inside( float const X, float const Y, float const Z ) const { // cycle through the sides of the frustum, checking if the point is behind them - for( int idx = 0; idx < 6; ++idx ) { - if( m_frustum[ idx ][ plane_A ] * X - + m_frustum[ idx ][ plane_B ] * Y - + m_frustum[ idx ][ plane_C ] * Z - + m_frustum[ idx ][ plane_D ] <= 0 ) - return false; - } - - // the point is in front of each frustum plane, i.e. inside of the frustum - return true; + return std::ranges::all_of( m_frustum, [&]( auto const &frustumplane ) { + return frustumplane[ plane_A ] * X + + frustumplane[ plane_B ] * Y + + frustumplane[ plane_C ] * Z + + frustumplane[ plane_D ] > 0; } ); } float @@ -90,12 +85,12 @@ cFrustum::sphere_inside( float const X, float const Y, float const Z, float cons float distance; // go through all the sides of the frustum. bail out as soon as possible - for( int idx = 0; idx < 6; ++idx ) { + for (auto &frustumplane : m_frustum) { distance = - m_frustum[ idx ][ plane_A ] * X - + m_frustum[ idx ][ plane_B ] * Y - + m_frustum[ idx ][ plane_C ] * Z - + m_frustum[ idx ][ plane_D ]; + frustumplane[ plane_A ] * X + + frustumplane[ plane_B ] * Y + + frustumplane[ plane_C ] * Z + + frustumplane[ plane_D ]; if( distance <= -Radius ) return 0.0f; } @@ -105,52 +100,50 @@ cFrustum::sphere_inside( float const X, float const Y, float const Z, float cons bool cFrustum::cube_inside( float const X, float const Y, float const Z, float const Size ) const { - for( int idx = 0; idx < 6; ++idx ) { - if( m_frustum[ idx ][ plane_A ] * ( X - Size ) - + m_frustum[ idx ][ plane_B ] * ( Y - Size ) - + m_frustum[ idx ][ plane_C ] * ( Z - Size ) - + m_frustum[ idx ][ plane_D ] > 0 ) - continue; - if( m_frustum[ idx ][ plane_A ] * ( X + Size ) - + m_frustum[ idx ][ plane_B ] * ( Y - Size ) - + m_frustum[ idx ][ plane_C ] * ( Z - Size ) - + m_frustum[ idx ][ plane_D ] > 0 ) - continue; - if( m_frustum[ idx ][ plane_A ] * ( X - Size ) - + m_frustum[ idx ][ plane_B ] * ( Y + Size ) - + m_frustum[ idx ][ plane_C ] * ( Z - Size ) - + m_frustum[ idx ][ plane_D ] > 0 ) - continue; - if( m_frustum[ idx ][ plane_A ] * ( X + Size ) - + m_frustum[ idx ][ plane_B ] * ( Y + Size ) - + m_frustum[ idx ][ plane_C ] * ( Z - Size ) - + m_frustum[ idx ][ plane_D ] > 0 ) - continue; - if( m_frustum[ idx ][ plane_A ] * ( X - Size ) - + m_frustum[ idx ][ plane_B ] * ( Y - Size ) - + m_frustum[ idx ][ plane_C ] * ( Z + Size ) - + m_frustum[ idx ][ plane_D ] > 0 ) - continue; - if( m_frustum[ idx ][ plane_A ] * ( X + Size ) - + m_frustum[ idx ][ plane_B ] * ( Y - Size ) - + m_frustum[ idx ][ plane_C ] * ( Z + Size ) - + m_frustum[ idx ][ plane_D ] > 0 ) - continue; - if( m_frustum[ idx ][ plane_A ] * ( X - Size ) - + m_frustum[ idx ][ plane_B ] * ( Y + Size ) - + m_frustum[ idx ][ plane_C ] * ( Z + Size ) - + m_frustum[ idx ][ plane_D ] > 0 ) - continue; - if( m_frustum[ idx ][ plane_A ] * ( X + Size ) - + m_frustum[ idx ][ plane_B ] * ( Y + Size ) - + m_frustum[ idx ][ plane_C ] * ( Z + Size ) - + m_frustum[ idx ][ plane_D ] > 0 ) - continue; + // the cube is inside unless all of its corners lie behind one of the frustum planes + return std::ranges::all_of( m_frustum, [&]( auto const &frustumplane ) { + if( frustumplane[ plane_A ] * ( X - Size ) + + frustumplane[ plane_B ] * ( Y - Size ) + + frustumplane[ plane_C ] * ( Z - Size ) + + frustumplane[ plane_D ] > 0 ) + return true; + if( frustumplane[ plane_A ] * ( X + Size ) + + frustumplane[ plane_B ] * ( Y - Size ) + + frustumplane[ plane_C ] * ( Z - Size ) + + frustumplane[ plane_D ] > 0 ) + return true; + if( frustumplane[ plane_A ] * ( X - Size ) + + frustumplane[ plane_B ] * ( Y + Size ) + + frustumplane[ plane_C ] * ( Z - Size ) + + frustumplane[ plane_D ] > 0 ) + return true; + if( frustumplane[ plane_A ] * ( X + Size ) + + frustumplane[ plane_B ] * ( Y + Size ) + + frustumplane[ plane_C ] * ( Z - Size ) + + frustumplane[ plane_D ] > 0 ) + return true; + if( frustumplane[ plane_A ] * ( X - Size ) + + frustumplane[ plane_B ] * ( Y - Size ) + + frustumplane[ plane_C ] * ( Z + Size ) + + frustumplane[ plane_D ] > 0 ) + return true; + if( frustumplane[ plane_A ] * ( X + Size ) + + frustumplane[ plane_B ] * ( Y - Size ) + + frustumplane[ plane_C ] * ( Z + Size ) + + frustumplane[ plane_D ] > 0 ) + return true; + if( frustumplane[ plane_A ] * ( X - Size ) + + frustumplane[ plane_B ] * ( Y + Size ) + + frustumplane[ plane_C ] * ( Z + Size ) + + frustumplane[ plane_D ] > 0 ) + return true; + if( frustumplane[ plane_A ] * ( X + Size ) + + frustumplane[ plane_B ] * ( Y + Size ) + + frustumplane[ plane_C ] * ( Z + Size ) + + frustumplane[ plane_D ] > 0 ) + return true; - return false; - } - - return true; + return false; } ); } void cFrustum::normalize_plane( cFrustum::side const Side ) { diff --git a/rendering/lightarray.cpp b/rendering/lightarray.cpp index 41bff159..15020894 100644 --- a/rendering/lightarray.cpp +++ b/rendering/lightarray.cpp @@ -29,12 +29,7 @@ light_array::insert( TDynamicObject const *Owner ) { void light_array::remove( TDynamicObject const *Owner ) { - data.erase( - std::remove_if( - data.begin(), - data.end(), - [=]( light_record const &light ){ return light.owner == Owner; } ), - data.end() ); + std::erase_if( data, [=]( light_record const &light ){ return light.owner == Owner; } ); } // updates records in the collection @@ -75,13 +70,13 @@ light_array::update() { light.intensity = std::max(0.0f, std::log((float)light.count + 1.0f)); if (light.owner->DimHeadlights && !light.owner->HighBeamLights && isEnabled) // tylko przyciemnione - light.intensity *= light.owner->MoverParameters->dimMultiplier; + light.intensity *= static_cast(light.owner->MoverParameters->dimMultiplier); else if (!light.owner->DimHeadlights && !light.owner->HighBeamLights && isEnabled) // normalne - light.intensity *= light.owner->MoverParameters->normMultiplier; + light.intensity *= static_cast(light.owner->MoverParameters->normMultiplier); else if (light.owner->DimHeadlights && light.owner->HighBeamLights && isEnabled) // przyciemnione dlugie - light.intensity *= light.owner->MoverParameters->highDimMultiplier; + light.intensity *= static_cast(light.owner->MoverParameters->highDimMultiplier); else if (!light.owner->DimHeadlights && light.owner->HighBeamLights && isEnabled) // dlugie zwykle - light.intensity *= light.owner->MoverParameters->highMultiplier; + light.intensity *= static_cast(light.owner->MoverParameters->highMultiplier); else if (!isEnabled) { light.intensity = 0.0f; diff --git a/rendering/lightarray.h b/rendering/lightarray.h index d7459fe9..a136dfbc 100644 --- a/rendering/lightarray.h +++ b/rendering/lightarray.h @@ -36,7 +36,7 @@ public: update(); // types - typedef std::vector lightrecord_array; + using lightrecord_array = std::vector; // members lightrecord_array data; diff --git a/rendering/nullrenderer.cpp b/rendering/nullrenderer.cpp index a37eddb9..332d357c 100644 --- a/rendering/nullrenderer.cpp +++ b/rendering/nullrenderer.cpp @@ -3,7 +3,7 @@ std::unique_ptr null_renderer::create_func() { - return std::unique_ptr(new null_renderer()); + return std::make_unique(); } bool null_renderer::renderer_register = gfx_renderer_factory::get_instance()->register_backend("null", null_renderer::create_func); diff --git a/rendering/nullrenderer.h b/rendering/nullrenderer.h index 69839f11..0b21580b 100644 --- a/rendering/nullrenderer.h +++ b/rendering/nullrenderer.h @@ -17,22 +17,22 @@ public: // constructors: null_geometrybank() = default; // destructor - ~null_geometrybank() {}; + ~null_geometrybank() = default; private: // methods: // create() subclass details void - create_( gfx::geometry_handle const &Geometry ) override {} + create_( gfx::geometry_handle const &Geometry ) override { /* null implementation, nothing to do */ } // replace() subclass details void - replace_( gfx::geometry_handle const &Geometry ) override {} + replace_( gfx::geometry_handle const &Geometry ) override { /* null implementation, nothing to do */ } // draw() subclass details auto draw_( gfx::geometry_handle const &Geometry, gfx::stream_units const &Units, unsigned int const Streams ) -> std::size_t override { return 0; } // release() subclass details void - release_() override {} + release_() override { /* null implementation, nothing to do */ } }; // bare-bones render controller, in lack of anything better yet @@ -43,7 +43,7 @@ public: // constructors null_renderer() = default; // destructor - ~null_renderer() { } + ~null_renderer() = default; // methods bool Init( GLFWwindow *Window ) override { return true; } @@ -51,14 +51,14 @@ public: bool Render() override { return true; } void - SwapBuffers() override {} + SwapBuffers() override { /* null implementation, nothing to do */ } inline float Framerate() override { return 10.0f; } bool AddViewport(const global_settings::extraviewport_config &conf) override { return false; } bool Debug_Ui_State(std::optional) override { return false; } - void Shutdown() override {} + void Shutdown() override { /* null implementation, nothing to do */ } // geometry methods // NOTE: hands-on geometry management is exposed as a temporary measure; ultimately all visualization data should be generated/handled automatically by the renderer itself @@ -100,10 +100,10 @@ public: Fetch_Material( std::string const &Filename, bool const Loadnow = true ) override { m_materials.push_back(std::make_shared()); m_materials.back()->name = Filename; - return m_materials.size(); + return static_cast(m_materials.size()); } void - Bind_Material( material_handle const Material, TSubModel const *sm = nullptr, lighting_data const *lighting = nullptr ) override {} + Bind_Material( material_handle const Material, TSubModel const *sm = nullptr, lighting_data const *lighting = nullptr ) override { /* null implementation, nothing to do */ } IMaterial const * Material( material_handle const Material ) const override { return m_materials.at(Material - 1).get(); } // shader methods @@ -112,18 +112,18 @@ public: texture_handle Fetch_Texture( std::string const &Filename, bool const Loadnow = true, GLint format_hint = GL_SRGB_ALPHA ) override { throw std::runtime_error("not impl"); } void - Bind_Texture( texture_handle const Texture ) override {} + Bind_Texture( texture_handle const Texture ) override { /* null implementation, nothing to do */ } void - Bind_Texture( std::size_t const Unit, texture_handle const Texture ) override {} + Bind_Texture( std::size_t const Unit, texture_handle const Texture ) override { /* null implementation, nothing to do */ } opengl_texture & Texture( texture_handle const Texture ) override { throw std::runtime_error("not impl"); } opengl_texture const & Texture( texture_handle const Texture ) const override { throw std::runtime_error("not impl"); } // utility methods void - Pick_Control_Callback( std::function Callback ) override {} + Pick_Control_Callback( std::function Callback ) override { /* null implementation, nothing to do */ } void - Pick_Node_Callback( std::function Callback ) override {} + Pick_Node_Callback( std::function Callback ) override { /* null implementation, nothing to do */ } TSubModel const * Pick_Control() const override { return nullptr; } scene::basic_node const * @@ -132,11 +132,11 @@ public: Mouse_Position() const override { return glm::dvec3(); } // maintenance methods void - Update( double const Deltatime ) override {} + Update( double const Deltatime ) override { /* null implementation, nothing to do */ } void - Update_Pick_Control() override {} + Update_Pick_Control() override { /* null implementation, nothing to do */ } void - Update_Pick_Node() override {} + Update_Pick_Node() override { /* null implementation, nothing to do */ } glm::dvec3 Update_Mouse_Position() override { return glm::dvec3(); } // debug methods @@ -144,13 +144,13 @@ public: info_times() const override { return empty_str; } std::string const & info_stats() const override { return empty_str; } - void MakeScreenshot() override {} + void MakeScreenshot() override { /* null implementation, nothing to do */ } static std::unique_ptr create_func(); static bool renderer_register; - virtual imgui_renderer *GetImguiRenderer() + imgui_renderer *GetImguiRenderer() override { return nullptr; } diff --git a/rendering/opengl33light.cpp b/rendering/opengl33light.cpp index ea1baf78..dddb3236 100644 --- a/rendering/opengl33light.cpp +++ b/rendering/opengl33light.cpp @@ -16,7 +16,7 @@ void opengl33_light::apply_intensity(float const Factor) { factor = Factor; } -void opengl33_light::apply_angle() {} +void opengl33_light::apply_angle() const { /* nothing to do */ } //--------------------------------------------------------------------------- diff --git a/rendering/opengl33light.h b/rendering/opengl33light.h index b87564aa..b36bad97 100644 --- a/rendering/opengl33light.h +++ b/rendering/opengl33light.h @@ -18,7 +18,7 @@ struct opengl33_light : public basic_light { float factor; void apply_intensity(float const Factor = 1.0f); - void apply_angle(); + void apply_angle() const; opengl33_light &operator=(basic_light const &Right) { basic_light::operator=(Right); diff --git a/rendering/opengl33particles.cpp b/rendering/opengl33particles.cpp index b869012b..8ff82b95 100644 --- a/rendering/opengl33particles.cpp +++ b/rendering/opengl33particles.cpp @@ -49,19 +49,19 @@ opengl33_particles::update( opengl_camera const &Camera ) { // build billboard data for particles from visible sources auto const camerarotation { glm::mat3( Camera.modelview() ) }; particle_vertex vertex; - for( auto const &source : sources ) { + for( auto const &[sourcekey, sourcedata] : sources ) { auto const particlecolor { glm::clamp( - source.second.color() + sourcedata.color() * ( glm::vec3 { Global.DayLight.ambient } + 0.35f * glm::vec3{ Global.DayLight.diffuse } ) * simulation::Environment.light_intensity(), glm::vec3{ 0.f }, glm::vec3{ 1.f } ) }; - auto const &particles { source.second.sequence() }; + auto const &particles { sourcedata.sequence() }; // TODO: put sanity cap on the overall amount of particles that can be drawn auto const sizestep { 256.0 * billboard_vertices.size() }; m_particlevertices.reserve( - sizestep * std::ceil( m_particlevertices.size() + ( particles.size() * billboard_vertices.size() ) / sizestep ) ); + static_cast( sizestep * std::ceil( static_cast(m_particlevertices.size()) + ( static_cast(particles.size() * billboard_vertices.size()) ) / sizestep ) ) ); for( auto const &particle : particles ) { // TODO: particle color support vertex.color[ 0 ] = particlecolor.r; @@ -72,9 +72,9 @@ opengl33_particles::update( opengl_camera const &Camera ) { auto const offset { glm::vec3{ particle.position - Camera.position() } }; auto const rotation { glm::angleAxis( particle.rotation, glm::vec3{ 0.f, 0.f, 1.f } ) }; - for( auto const &billboardvertex : billboard_vertices ) { - vertex.position = offset + ( rotation * billboardvertex.first * particle.size ) * camerarotation; - vertex.texture = billboardvertex.second; + for( auto const &[billboardoffset, billboardtexture] : billboard_vertices ) { + vertex.position = offset + ( rotation * billboardoffset * particle.size ) * camerarotation; + vertex.texture = billboardtexture; m_particlevertices.emplace_back( vertex ); } @@ -113,14 +113,14 @@ opengl33_particles::render() { m_vao->setup_attrib(*m_buffer, 1, 4, GL_FLOAT, sizeof(particle_vertex), 12); m_vao->setup_attrib(*m_buffer, 2, 2, GL_FLOAT, sizeof(particle_vertex), 28); - m_buffer->unbind(gl::buffer::ARRAY_BUFFER); - m_vao->unbind(); + gl::buffer::unbind(gl::buffer::ARRAY_BUFFER); + gl::vao::unbind(); } if (!m_shader) { gl::shader vert("smoke.vert"); gl::shader frag("smoke.frag"); - gl::program *prog = new gl::program({vert, frag}); + auto prog = new gl::program({vert, frag}); m_shader = std::unique_ptr(prog); } @@ -128,11 +128,11 @@ opengl33_particles::render() { m_shader->bind(); m_vao->bind(); - glDrawArrays(GL_TRIANGLES, 0, m_particlevertices.size()); + glDrawArrays(GL_TRIANGLES, 0, static_cast(m_particlevertices.size())); - m_shader->unbind(); - m_vao->unbind(); - m_buffer->unbind(gl::buffer::ARRAY_BUFFER); + gl::program::unbind(); + gl::vao::unbind(); + gl::buffer::unbind(gl::buffer::ARRAY_BUFFER); return m_particlevertices.size() / 6; } diff --git a/rendering/opengl33precipitation.cpp b/rendering/opengl33precipitation.cpp index e31eb25f..308248b7 100644 --- a/rendering/opengl33precipitation.cpp +++ b/rendering/opengl33precipitation.cpp @@ -36,7 +36,7 @@ opengl33_precipitation::create( int const Tesselation ) { std::uint16_t index = 0; // auto const radius { 25.f }; // cylinder radius - std::vector radii { 25.f, 10.f, 5.f, 1.f }; + std::vector radii { 25.f, 10.f, 5.f, 1.f }; for( auto radius : radii ) { for( int i = 0; i <= latitudes; ++i ) { @@ -121,7 +121,7 @@ opengl33_precipitation::update() { m_indexbuffer->upload(gl::buffer::ELEMENT_ARRAY_BUFFER, m_indices.data(), 0, m_indices.size() * sizeof( unsigned short )); m_vao->setup_ebo(*m_indexbuffer); - m_vao->unbind(); + gl::vao::unbind(); // NOTE: vertex and index source data is superfluous past this point, but, eh } @@ -155,5 +155,5 @@ opengl33_precipitation::render() { ::glDrawElements( GL_TRIANGLES, static_cast( m_indices.size() ), GL_UNSIGNED_SHORT, reinterpret_cast( 0 ) ); - m_vao->unbind(); + gl::vao::unbind(); } diff --git a/rendering/opengl33skydome.cpp b/rendering/opengl33skydome.cpp index 35e1d8c0..cbceeed4 100644 --- a/rendering/opengl33skydome.cpp +++ b/rendering/opengl33skydome.cpp @@ -44,15 +44,13 @@ void opengl33_skydome::update() { m_indexbuffer->upload(gl::buffer::ELEMENT_ARRAY_BUFFER, skydome.indices().data(), 0, skydome.indices().size() * sizeof( unsigned short )); m_vao->setup_ebo(*m_indexbuffer); - m_vao->unbind(); + gl::vao::unbind(); } // ship the current dynamic data to the gpu - if( true == skydome.is_dirty() ) { - if( m_coloursbuffer ) { - // the colour buffer was already initialized, so on this run we update its content - m_coloursbuffer->upload( gl::buffer::ARRAY_BUFFER, skydome.colors().data(), 0, skydome.colors().size() * sizeof( glm::vec3 ) ); - skydome.is_dirty() = false; - } + if (true == skydome.is_dirty() && m_coloursbuffer) { + // the colour buffer was already initialized, so on this run we update its content + m_coloursbuffer->upload( gl::buffer::ARRAY_BUFFER, skydome.colors().data(), 0, skydome.colors().size() * sizeof( glm::vec3 ) ); + skydome.is_dirty() = false; } } diff --git a/rendering/opengl33skydome.h b/rendering/opengl33skydome.h index 425c276b..287ac511 100644 --- a/rendering/opengl33skydome.h +++ b/rendering/opengl33skydome.h @@ -19,7 +19,7 @@ public: // constructors opengl33_skydome() = default; // destructor - ~opengl33_skydome() {;} + ~opengl33_skydome() = default; // methods // updates data stores on the opengl end. NOTE: unbinds buffers void update(); diff --git a/rendering/openglcamera.cpp b/rendering/openglcamera.cpp index 97891e63..418a120d 100644 --- a/rendering/openglcamera.cpp +++ b/rendering/openglcamera.cpp @@ -38,7 +38,7 @@ opengl_camera::visible( TDynamicObject const *Dynamic ) const { // sphere test is faster than AABB, so we'll use it here // we're giving vehicles some extra padding, to allow for things like shared bogeys extending past the main body - return ( m_frustum.sphere_inside( Dynamic->GetPosition(), Dynamic->radius() * 1.25 ) > 0.0f ); + return ( m_frustum.sphere_inside( Dynamic->GetPosition(), static_cast(Dynamic->radius() * 1.25) ) > 0.0f ); } // debug helper, draws shape of frustum in world space diff --git a/rendering/openglcamera.h b/rendering/openglcamera.h index 569a798c..ad223cbd 100644 --- a/rendering/openglcamera.h +++ b/rendering/openglcamera.h @@ -24,7 +24,7 @@ public: update_frustum() { update_frustum( m_projection, m_modelview ); } inline void - update_frustum(glm::mat4 frustumtest_proj) { + update_frustum(glm::mat4 const &frustumtest_proj) { update_frustum(frustumtest_proj, m_modelview); } void update_frustum( glm::mat4 const &Projection, glm::mat4 const &Modelview ); diff --git a/rendering/openglgeometrybank.cpp b/rendering/openglgeometrybank.cpp index ec950c0f..d020bb56 100644 --- a/rendering/openglgeometrybank.cpp +++ b/rendering/openglgeometrybank.cpp @@ -90,23 +90,23 @@ opengl_vbogeometrybank::draw_( gfx::geometry_handle const &Geometry, gfx::stream } ::glDrawRangeElementsBaseVertex( chunk.type, - 0, chunkrecord.vertex_count, - chunkrecord.index_count, GL_UNSIGNED_INT, reinterpret_cast( chunkrecord.index_offset * sizeof( gfx::basic_index ) ), - chunkrecord.vertex_offset ); + 0, static_cast(chunkrecord.vertex_count), + static_cast(chunkrecord.index_count), GL_UNSIGNED_INT, reinterpret_cast( chunkrecord.index_offset * sizeof( gfx::basic_index ) ), + static_cast(chunkrecord.vertex_offset) ); } else { bind_streams( Units, Streams, chunkrecord.vertex_offset ); ::glDrawRangeElements( chunk.type, - 0, chunkrecord.vertex_count, - chunkrecord.index_count, GL_UNSIGNED_INT, reinterpret_cast( chunkrecord.index_offset * sizeof( gfx::basic_index ) ) ); + 0, static_cast(chunkrecord.vertex_count), + static_cast(chunkrecord.index_count), GL_UNSIGNED_INT, reinterpret_cast( chunkrecord.index_offset * sizeof( gfx::basic_index ) ) ); } } else { if( m_activestreams != Streams ) { bind_streams( Units, Streams ); } - ::glDrawArrays( chunk.type, chunkrecord.vertex_offset, chunkrecord.vertex_count ); + ::glDrawArrays( chunk.type, static_cast(chunkrecord.vertex_offset), static_cast(chunkrecord.vertex_count) ); } // ...post-render cleanup /* @@ -139,9 +139,8 @@ opengl_vbogeometrybank::setup_buffer() { // may be better to initiate upload earlier (during update phase) and trust this effort won't go to waste if( true == m_chunks.empty() ) { return; } - std::size_t - vertexcount{ 0 }, - indexcount{ 0 }; + std::size_t vertexcount{ 0 }; + std::size_t indexcount{ 0 }; auto chunkiterator = m_chunks.cbegin(); for( auto &chunkrecord : m_chunkrecords ) { // fill records for all chunks, based on the chunk data @@ -195,7 +194,7 @@ opengl_vbogeometrybank::setup_buffer() { } void -opengl_vbogeometrybank::bind_buffer() { +opengl_vbogeometrybank::bind_buffer() const { ::glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_indexbuffer ); ::glBindBuffer( GL_ARRAY_BUFFER, m_vertexbuffer ); diff --git a/rendering/openglgeometrybank.h b/rendering/openglgeometrybank.h index ec6bdd89..7d260a82 100644 --- a/rendering/openglgeometrybank.h +++ b/rendering/openglgeometrybank.h @@ -58,7 +58,7 @@ private: void setup_buffer(); void - bind_buffer(); + bind_buffer() const; void delete_buffer(); static @@ -87,7 +87,7 @@ public: opengl_dlgeometrybank() = default; // destructor: ~opengl_dlgeometrybank() { - for( auto &chunkrecord : m_chunkrecords ) { + for( auto const &chunkrecord : m_chunkrecords ) { ::glDeleteLists( chunkrecord.list, 1 ); } } private: diff --git a/rendering/openglmatrixstack.h b/rendering/openglmatrixstack.h index 9ba2fa41..ea3be535 100644 --- a/rendering/openglmatrixstack.h +++ b/rendering/openglmatrixstack.h @@ -90,7 +90,7 @@ private: }; enum stack_mode { gl_modelview = 0, gl_projection = 1, gl_texture = 2 }; -typedef std::vector openglstack_array; +using openglstack_array = std::vector; public: // constructors: diff --git a/rendering/openglparticles.cpp b/rendering/openglparticles.cpp index 54db2ddf..3b8de946 100644 --- a/rendering/openglparticles.cpp +++ b/rendering/openglparticles.cpp @@ -47,19 +47,19 @@ opengl_particles::update( opengl_camera const &Camera ) { // build billboard data for particles from visible sources auto const camerarotation { glm::mat3( Camera.modelview() ) }; particle_vertex vertex; - for( auto const &source : sources ) { + for( auto const &[sourcekey, sourcedata] : sources ) { auto const particlecolor { glm::clamp( - source.second.color() + sourcedata.color() * ( glm::vec3 { Global.DayLight.ambient } + 0.35f * glm::vec3{ Global.DayLight.diffuse } ) * 255.f, glm::vec3{ 0.f }, glm::vec3{ 255.f } ) }; - auto const &particles { source.second.sequence() }; + auto const &particles { sourcedata.sequence() }; // TODO: put sanity cap on the overall amount of particles that can be drawn auto const sizestep { 256.0 * billboard_vertices.size() }; m_particlevertices.reserve( - sizestep * std::ceil( m_particlevertices.size() + ( particles.size() * billboard_vertices.size() ) / sizestep ) ); + static_cast( sizestep * std::ceil( static_cast(m_particlevertices.size()) + ( static_cast(particles.size() * billboard_vertices.size()) ) / sizestep ) ) ); for( auto const &particle : particles ) { // TODO: particle color support vertex.color[ 0 ] = static_cast( particlecolor.r ); @@ -70,9 +70,9 @@ opengl_particles::update( opengl_camera const &Camera ) { auto const offset { glm::vec3{ particle.position - Camera.position() } }; auto const rotation { glm::angleAxis( particle.rotation, glm::vec3{ 0.f, 0.f, 1.f } ) }; - for( auto const &billboardvertex : billboard_vertices ) { - vertex.position = offset + ( rotation * billboardvertex.first * particle.size ) * camerarotation; - vertex.texture = billboardvertex.second; + for( auto const &[billboardoffset, billboardtexture] : billboard_vertices ) { + vertex.position = offset + ( rotation * billboardoffset * particle.size ) * camerarotation; + vertex.texture = billboardtexture; m_particlevertices.emplace_back( vertex ); } @@ -147,7 +147,7 @@ opengl_particles::render( GLint const Textureunit ) { ::glTexCoordPointer( 2, GL_FLOAT, sizeof( particle_vertex ), reinterpret_cast( sizeof( float ) * 3 + sizeof( std::uint8_t ) * 4 ) ); ::glEnableClientState( GL_TEXTURE_COORD_ARRAY ); // ...draw... - ::glDrawArrays( GL_QUADS, 0, m_particlevertices.size() ); + ::glDrawArrays( GL_QUADS, 0, static_cast(m_particlevertices.size()) ); // ...and cleanup ::glPopClientAttrib(); ::glBindBuffer( GL_ARRAY_BUFFER, 0 ); diff --git a/rendering/openglprecipitation.cpp b/rendering/openglprecipitation.cpp index fc93b2a9..acf24687 100644 --- a/rendering/openglprecipitation.cpp +++ b/rendering/openglprecipitation.cpp @@ -39,7 +39,7 @@ opengl_precipitation::create( int const Tesselation ) { std::uint16_t index = 0; // auto const radius { 25.f }; // cylinder radius - std::vector radii { 25.f, 10.f, 5.f, 1.f }; + std::vector radii { 25.f, 10.f, 5.f, 1.f }; for( auto radius : radii ) { for( int i = 0; i <= latitudes; ++i ) { diff --git a/rendering/openglskydome.cpp b/rendering/openglskydome.cpp index 58951f17..6506482b 100644 --- a/rendering/openglskydome.cpp +++ b/rendering/openglskydome.cpp @@ -54,20 +54,18 @@ void opengl_skydome::update() { } // ship the current dynamic data to the gpu // TODO: ship the data if it changed since the last update - if( true == skydome.is_dirty() ) { - if( ( m_coloursbuffer > 0 ) && ( m_coloursbuffer != (GLuint)-1 ) ) { - ::glBindBuffer( GL_ARRAY_BUFFER, m_coloursbuffer ); - auto &colors{ skydome.colors() }; - /* - float twilightfactor = std::clamp( -simulation::Environment.sun().getAngle(), 0.0f, 18.0f ) / 18.0f; - auto gamma = std::lerp( glm::vec3( 0.45f ), glm::vec3( 1.0f ), twilightfactor ); - for( auto & color : colors ) { - color = glm::pow( color, gamma ); - } - */ - ::glBufferSubData( GL_ARRAY_BUFFER, 0, colors.size() * sizeof( glm::vec3 ), colors.data() ); - skydome.is_dirty() = false; + if (true == skydome.is_dirty() && ( m_coloursbuffer > 0 ) && ( m_coloursbuffer != (GLuint)-1 )) { + ::glBindBuffer( GL_ARRAY_BUFFER, m_coloursbuffer ); + auto &colors{ skydome.colors() }; + /* + float twilightfactor = std::clamp( -simulation::Environment.sun().getAngle(), 0.0f, 18.0f ) / 18.0f; + auto gamma = std::lerp( glm::vec3( 0.45f ), glm::vec3( 1.0f ), twilightfactor ); + for( auto & color : colors ) { + color = glm::pow( color, gamma ); } + */ + ::glBufferSubData( GL_ARRAY_BUFFER, 0, colors.size() * sizeof( glm::vec3 ), colors.data() ); + skydome.is_dirty() = false; } // cleanup ::glPopClientAttrib(); diff --git a/rendering/particles.cpp b/rendering/particles.cpp index eb02bf41..5f7158e0 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -56,7 +56,7 @@ smoke_source::particle_emitter::deserialize( cParser &Input ) { } void -smoke_source::particle_emitter::initialize( smoke_particle &Particle ) { +smoke_source::particle_emitter::initialize( smoke_particle &Particle ) const { auto const polarangle { glm::radians( LocalRandom( inclination[ value_limit::min ], inclination[ value_limit::max ] ) ) }; // theta auto const azimuthalangle { glm::radians( LocalRandom( -180, 180 ) ) }; // phi @@ -69,9 +69,9 @@ smoke_source::particle_emitter::initialize( smoke_particle &Particle ) { Particle.velocity = launchvector * launchvelocity; - Particle.rotation = glm::radians( LocalRandom( 0, 360 ) ); - Particle.size = LocalRandom( size[ value_limit::min ], size[ value_limit::max ] ); - Particle.opacity = LocalRandom( opacity[ value_limit::min ], opacity[ value_limit::max ] ) / Global.SmokeFidelity; + Particle.rotation = static_cast(glm::radians( LocalRandom( 0, 360 ) )); + Particle.size = static_cast(LocalRandom( size[ value_limit::min ], size[ value_limit::max ] )); + Particle.opacity = static_cast(LocalRandom( opacity[ value_limit::min ], opacity[ value_limit::max ] ) / Global.SmokeFidelity); Particle.age = 0; } @@ -81,7 +81,7 @@ smoke_source::deserialize( cParser &Input ) { if( false == Input.ok() ) { return false; } while( true == deserialize_mapping( Input ) ) { - ; // all work done by while() + // all work done by while() } return true; @@ -166,8 +166,8 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { ( ( false == Global.Smoke ) || ( true == Onlydespawn ) ) ? 0.f : std::min( - m_spawncount + ( m_spawnrate * Timedelta * Global.SmokeFidelity ), - m_max_particles ) ); + static_cast(m_spawncount + ( m_spawnrate * Timedelta * Global.SmokeFidelity )), + static_cast(m_max_particles) ) ); // consider special spawn rate cases if( m_ownertype == owner_type::vehicle ) { @@ -183,7 +183,7 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { 0.f : std::min( // m_spawncount + ( m_spawnrate * Timedelta * Global.SmokeFidelity ), - m_spawncount +(m_spawnrate * Timedelta * Global.SmokeFidelity * (((m_owner.vehicle->MoverParameters->enrot) / 4 ) * 0.01)), m_max_particles); + static_cast(m_spawncount +(m_spawnrate * Timedelta * Global.SmokeFidelity * (((m_owner.vehicle->MoverParameters->enrot) / 4 ) * 0.01))), static_cast(m_max_particles)); } else { @@ -195,7 +195,7 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { 0.f : std::min( // m_spawncount + ( m_spawnrate * Timedelta * Global.SmokeFidelity ), - m_spawncount + (m_spawnrate * Timedelta * Global.SmokeFidelity * ((((m_owner.vehicle->MoverParameters->DElist[m_owner.vehicle->MoverParameters->MainCtrlPosNo].RPM -m_owner.vehicle->MoverParameters->enrot) /60) *0.02) *(m_owner.vehicle->MoverParameters->EnginePower * 0.005))), m_max_particles); + static_cast(m_spawncount + (m_spawnrate * Timedelta * Global.SmokeFidelity * ((((m_owner.vehicle->MoverParameters->DElist[m_owner.vehicle->MoverParameters->MainCtrlPosNo].RPM -m_owner.vehicle->MoverParameters->enrot) /60) *0.02) *(m_owner.vehicle->MoverParameters->EnginePower * 0.005)))), static_cast(m_max_particles)); } else { @@ -205,7 +205,7 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { 0.f : std::min( // m_spawncount + ( m_spawnrate * Timedelta * Global.SmokeFidelity ), - m_spawncount + (m_spawnrate * Timedelta * Global.SmokeFidelity * ((((m_owner.vehicle->MoverParameters->DElist[m_owner.vehicle->MoverParameters->MainCtrlPosNo].RPM -m_owner.vehicle->MoverParameters->enrot) /60) * (sqrt(m_owner.vehicle->MoverParameters->Im) * 0.01) * 0.02) *(m_owner.vehicle->MoverParameters->EnginePower * 0.005))), m_max_particles); + static_cast(m_spawncount + (m_spawnrate * Timedelta * Global.SmokeFidelity * ((((m_owner.vehicle->MoverParameters->DElist[m_owner.vehicle->MoverParameters->MainCtrlPosNo].RPM -m_owner.vehicle->MoverParameters->enrot) /60) * (sqrt(m_owner.vehicle->MoverParameters->Im) * 0.01) * 0.02) *(m_owner.vehicle->MoverParameters->EnginePower * 0.005)))), static_cast(m_max_particles)); } } } @@ -254,10 +254,8 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { // if we still have pending requests after filling entire container replace older particles if( m_spawncount >= 1.f ) { // sort all particles from most to least transparent, oldest to youngest if it's a tie - std::sort( - std::begin( m_particles ), - std::end( m_particles ), - []( smoke_particle const &Left, smoke_particle const &Right ) { + std::ranges::sort( + m_particles, []( smoke_particle const &Left, smoke_particle const &Right ) { return ( Left.opacity != Right.opacity ? Left.opacity < Right.opacity : Left.age > Right.age ); } ); @@ -283,7 +281,7 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { // determine bounding area from calculated bounding box if( false == m_particles.empty() ) { m_area.center = glm::mix(boundingbox[value_limit::min], boundingbox[value_limit::max], 0.5); - m_area.radius = 0.5 * ( glm::length( boundingbox[ value_limit::max ] - boundingbox[ value_limit::min ] ) ); + m_area.radius = static_cast(0.5 * ( glm::length( boundingbox[ value_limit::max ] - boundingbox[ value_limit::min ] ) )); } else { m_area.center = location(); @@ -331,10 +329,9 @@ smoke_source::initialize( smoke_particle &Particle ) { Particle.position = location(); if( m_ownertype == owner_type::vehicle ) { - Particle.opacity *= m_owner.vehicle->MoverParameters->dizel_fill; - auto const enginerevolutionsfactor { 1.5f }; // high engine revolutions increase initial particle velocity - switch( m_owner.vehicle->MoverParameters->EngineType ) { - case TEngineType::DieselElectric: { + Particle.opacity *= static_cast(m_owner.vehicle->MoverParameters->dizel_fill); + if (m_owner.vehicle->MoverParameters->EngineType == TEngineType::DieselElectric) + { if (m_owner.vehicle->MoverParameters->dizel_spinup == true) { Particle.velocity *= 0.38*(((m_owner.vehicle->MoverParameters->enrot)/2)*0.5); // / m_owner.vehicle->MoverParameters->dizel_fill *0.01)) ; @@ -347,11 +344,6 @@ smoke_source::initialize( smoke_particle &Particle ) { //Particle.velocity *= m_owner.vehicle->GetVelocity(); // / m_owner.vehicle->MoverParameters->dizel_fill *0.01)) ; } - break; - } - default: { - break; - } } } } @@ -368,28 +360,23 @@ smoke_source::update( smoke_particle &Particle, bounding_box &Boundingbox, doubl // crude smoke dispersion simulation // http://www.auburn.edu/academic/forestry_wildlife/fire/smoke_guide/smoke_dispersion.htm - switch (m_ownertype) + if (m_ownertype == owner_type::vehicle) { - case owner_type::vehicle: + Particle.velocity.y += static_cast(( 0.025 * Particle.velocity.y ) * std::min( 0.f, Global.AirTemperature - 90 ) * Timedelta); // decelerate faster in cold weather + Particle.velocity.y -= static_cast(( (0.05 * (pow(m_owner.vehicle->GetVelocity()*1,0.4))) * Particle.velocity.y ) * Global.Overcast * Timedelta); // decelerate faster with high air humidity and/or precipitation + } + else { - Particle.velocity.y += ( 0.025 * Particle.velocity.y ) * std::min( 0.f, Global.AirTemperature - 90 ) * Timedelta; // decelerate faster in cold weather - Particle.velocity.y -= ( (0.05 * (pow(m_owner.vehicle->GetVelocity()*1,0.4))) * Particle.velocity.y ) * Global.Overcast * Timedelta; // decelerate faster with high air humidity and/or precipitation - break; - } - default: - { - Particle.velocity.y += ( 0.005 * Particle.velocity.y ) * std::min( 0.f, Global.AirTemperature - 10 ) * Timedelta; // decelerate faster in cold weather - Particle.velocity.y -= ( 0.050 * Particle.velocity.y ) * Global.Overcast * Timedelta; // decelerate faster with high air humidity and/or precipitation - Particle.velocity.y = std::max( 0.25 * ( 2.f - Global.Overcast ), Particle.velocity.y ); // put a cap on deceleration - break; - } - } + Particle.velocity.y += static_cast(( 0.005 * Particle.velocity.y ) * std::min( 0.f, Global.AirTemperature - 10 ) * Timedelta); // decelerate faster in cold weather + Particle.velocity.y -= static_cast(( 0.050 * Particle.velocity.y ) * Global.Overcast * Timedelta); // decelerate faster with high air humidity and/or precipitation + Particle.velocity.y = std::max( static_cast(0.25 * ( 2.f - Global.Overcast )), Particle.velocity.y ); // put a cap on deceleration + } Particle.position += Particle.velocity * static_cast( Timedelta ); Particle.position += 0.1f * Particle.age * simulation::Environment.wind() * static_cast( Timedelta ); // m_velocitymodifier.update( Particle.velocity, Timedelta ); - Particle.age += Timedelta; + Particle.age += static_cast(Timedelta); // update bounding box Boundingbox[ value_limit::min ] = glm::min( Boundingbox[ value_limit::min ], Particle.position - glm::dvec3{ Particle.size } ); @@ -467,21 +454,19 @@ particle_manager::find( std::string const &Template ) { auto const templatename { ToLower( Template ) }; // try to locate specified rail profile... - auto const lookup { m_sourcetemplates.find( templatename ) }; - if( lookup != m_sourcetemplates.end() ) { + if( auto const lookup { m_sourcetemplates.find( templatename ) }; lookup != m_sourcetemplates.end() ) { // ...if it works, we're done... return &(lookup->second); } // ... and if it fails try to add the template to the database from a data file smoke_source source; - cParser parser(templatepath + templatename + ".txt", cParser::buffer_FILE); - if (source.deserialize(parser)) + if (cParser parser(templatepath + templatename + ".txt", cParser::buffer_FILE); source.deserialize(parser)) { // if deserialization didn't fail finish source setup... source.m_opacitymodifier.bind( &Global.SmokeFidelity ); // ...then cache the source as template for future instances - m_sourcetemplates.emplace( templatename, source ); + m_sourcetemplates.try_emplace( templatename, source ); // should be 'safe enough' to return lookup result directly afterwards return &( m_sourcetemplates.find( templatename )->second ); } diff --git a/rendering/particles.h b/rendering/particles.h index 5ee44230..1d225e54 100644 --- a/rendering/particles.h +++ b/rendering/particles.h @@ -56,7 +56,7 @@ public: return ( m_valuechangemodifier == nullptr ? m_valuechange : - m_valuechange / *( m_valuechangemodifier ) ); } + m_valuechange / *m_valuechangemodifier ); } private: //types @@ -122,7 +122,7 @@ private: glm::vec3 color { 16.f / 255.f }; void deserialize( cParser &Input ); - void initialize( smoke_particle &Particle ); + void initialize( smoke_particle &Particle ) const; }; using bounding_box = glm::dvec3[ 2 ]; // bounding box of owned particles @@ -212,7 +212,7 @@ fixedstep_modifier::update( Type_ &Variable, double const Timedelta ) con auto const valuechange { ( m_valuechangemodifier == nullptr ? m_valuechange : - m_valuechange / *( m_valuechangemodifier ) ) }; + m_valuechange / *m_valuechangemodifier ) }; Variable += ( valuechange * static_cast( Timedelta ) ); // clamp down to allowed value range Variable = glm::max( Variable, m_valuelimits[ value_limit::min ] ); diff --git a/rendering/screenshot.cpp b/rendering/screenshot.cpp index eb7e7aac..88091703 100644 --- a/rendering/screenshot.cpp +++ b/rendering/screenshot.cpp @@ -29,9 +29,9 @@ void screenshot_manager::screenshot_save_thread( char *img, int w, int h ) stride = -w * 3; } - char datetime[64]; + std::array datetime{}; std::tm const tm_info = local_tm(std::time(nullptr)); - strftime(datetime, 64, "%Y-%m-%d_%H-%M-%S", &tm_info); + strftime(datetime.data(), datetime.size(), "%Y-%m-%d_%H-%M-%S", &tm_info); uint64_t perf; #ifdef _WIN32 @@ -42,7 +42,7 @@ void screenshot_manager::screenshot_save_thread( char *img, int w, int h ) perf = ts.tv_nsec; #endif - std::string filename = Global.screenshot_dir + "/" + std::string(datetime) + + std::string filename = Global.screenshot_dir + "/" + std::string(datetime.data()) + "_" + std::to_string(perf) + ".png"; if (png_image_write_to_file(&png, filename.c_str(), 0, img, stride, nullptr) == 1) @@ -55,7 +55,7 @@ void screenshot_manager::screenshot_save_thread( char *img, int w, int h ) void screenshot_manager::make_screenshot() { - char *img = new char[Global.fb_size.x * Global.fb_size.y * 4]; + auto img = new char[Global.fb_size.x * Global.fb_size.y * 4]; glReadPixels(0, 0, Global.fb_size.x, Global.fb_size.y, Global.gfx_usegles ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)img); //m7t: use pbo diff --git a/scene/sceneeditor.cpp b/scene/sceneeditor.cpp index 4516425d..5d56e915 100644 --- a/scene/sceneeditor.cpp +++ b/scene/sceneeditor.cpp @@ -50,9 +50,8 @@ basic_editor::translate( scene::basic_node *Node, glm::dvec3 const &Location, bo // TODO: contextual switch between group and item translation // TODO: translation of affected/relevant events auto &nodegroup { scene::Groups.group( Node->group() ).nodes }; - std::for_each( - std::begin( nodegroup ), std::end( nodegroup ), - [&]( auto *node ) { + std::ranges::for_each( + nodegroup, [&]( auto *node ) { translate_node( node, node->location() + translation ); } ); } } @@ -72,9 +71,8 @@ basic_editor::translate( scene::basic_node *Node, float const Offset ) { // TODO: contextual switch between group and item translation // TODO: translation of affected/relevant events auto &nodegroup { scene::Groups.group( Node->group() ).nodes }; - std::for_each( - std::begin( nodegroup ), std::end( nodegroup ), - [&]( auto *node ) { + std::ranges::for_each( + nodegroup, [&]( auto *node ) { translate_node( node, offset ); } ); } } @@ -102,7 +100,7 @@ basic_editor::translate_node( scene::basic_node *Node, float const Offset ) { } void -basic_editor::translate_instance( TAnimModel *Instance, glm::dvec3 const &Location ) { +basic_editor::translate_instance( TAnimModel *Instance, glm::dvec3 const &Location ) const { simulation::Region->erase( Instance ); Instance->location( Location ); @@ -110,7 +108,7 @@ basic_editor::translate_instance( TAnimModel *Instance, glm::dvec3 const &Locati } void -basic_editor::translate_instance( TAnimModel *Instance, float const Offset ) { +basic_editor::translate_instance( TAnimModel *Instance, float const Offset ) const { auto location { Instance->location() }; location.y += Offset; @@ -118,7 +116,7 @@ basic_editor::translate_instance( TAnimModel *Instance, float const Offset ) { } void -basic_editor::translate_memorycell( TMemCell *Memorycell, glm::dvec3 const &Location ) { +basic_editor::translate_memorycell( TMemCell *Memorycell, glm::dvec3 const &Location ) const { simulation::Region->erase( Memorycell ); Memorycell->location( Location ); @@ -126,7 +124,7 @@ basic_editor::translate_memorycell( TMemCell *Memorycell, glm::dvec3 const &Loca } void -basic_editor::translate_memorycell( TMemCell *Memorycell, float const Offset ) { +basic_editor::translate_memorycell( TMemCell *Memorycell, float const Offset ) const { auto location { Memorycell->location() }; location.y += Offset; @@ -161,9 +159,8 @@ basic_editor::rotate( scene::basic_node *Node, glm::vec3 const &Angle, float con // TODO: translation of affected/relevant events auto const &rotationcenter { Node->location() }; auto const &nodegroup { scene::Groups.group( Node->group() ).nodes }; - std::for_each( - std::begin( nodegroup ), std::end( nodegroup ), - [&]( auto *node ) { + std::ranges::for_each( + nodegroup, [&]( auto *node ) { rotate_node( node, rotation ); if( node != Node ) { translate_node( @@ -184,7 +181,7 @@ basic_editor::rotate_node( scene::basic_node *Node, glm::vec3 const &Angle ) { } void -basic_editor::rotate_instance( TAnimModel *Instance, glm::vec3 const &Angle ) { +basic_editor::rotate_instance( TAnimModel *Instance, glm::vec3 const &Angle ) const { auto targetangle { Instance->Angles() + Angle }; diff --git a/scene/sceneeditor.h b/scene/sceneeditor.h index bcff58b6..2b5418fe 100644 --- a/scene/sceneeditor.h +++ b/scene/sceneeditor.h @@ -19,14 +19,13 @@ struct node_snapshot { scene::basic_node *node; std::string data; - node_snapshot( scene::basic_node *Node ) : + explicit node_snapshot( scene::basic_node *Node ) : node( Node ) { if( Node != nullptr ) { Node->export_as_text( data ); } }; }; inline bool operator==( node_snapshot const &Left, node_snapshot const &Right ) { return Left.node == Right.node && Left.data == Right.data; } -inline bool operator!=( node_snapshot const &Left, node_snapshot const &Right ) { return !(Left == Right); } class basic_editor { @@ -46,17 +45,17 @@ private: void translate_node( scene::basic_node *Node, float const Offset ); void - translate_instance( TAnimModel *Instance, glm::dvec3 const &Location ); + translate_instance( TAnimModel *Instance, glm::dvec3 const &Location ) const; void - translate_instance( TAnimModel *Instance, float const Offset ); + translate_instance( TAnimModel *Instance, float const Offset ) const; void - translate_memorycell( TMemCell *Memorycell, glm::dvec3 const &Location ); + translate_memorycell( TMemCell *Memorycell, glm::dvec3 const &Location ) const; void - translate_memorycell( TMemCell *Memorycell, float const Offset ); + translate_memorycell( TMemCell *Memorycell, float const Offset ) const; void rotate_node( scene::basic_node *Node, glm::vec3 const &Angle ); void - rotate_instance( TAnimModel *Instance, glm::vec3 const &Angle ); + rotate_instance( TAnimModel *Instance, glm::vec3 const &Angle ) const; }; } // scene diff --git a/scene/sn_utils.cpp b/scene/sn_utils.cpp index 08825d91..b6a3f7c3 100644 --- a/scene/sn_utils.cpp +++ b/scene/sn_utils.cpp @@ -16,17 +16,17 @@ static_assert(-1 == ~0, "Two's complement required"); // deserialize little endian uint16 uint16_t sn_utils::ld_uint16(std::istream &s) { - uint8_t buf[2]; - s.read((char*)buf, 2); - uint16_t v = buf[1] << 8 | buf[0]; + std::array buf{}; + s.read(reinterpret_cast(buf.data()), buf.size()); + auto v = static_cast(buf[1] << 8 | buf[0]); return v; } // deserialize little endian uint32 uint32_t sn_utils::ld_uint32(std::istream &s) { - uint8_t buf[4]; - s.read((char*)buf, 4); + std::array buf{}; + s.read(reinterpret_cast(buf.data()), buf.size()); uint32_t v = buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0]; return v; } @@ -34,8 +34,8 @@ uint32_t sn_utils::ld_uint32(std::istream &s) // deserialize little endian int32 int32_t sn_utils::ld_int32(std::istream &s) { - uint8_t buf[4]; - s.read((char*)buf, 4); + std::array buf{}; + s.read(reinterpret_cast(buf.data()), buf.size()); uint32_t v = buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0]; return static_cast(v); } @@ -43,8 +43,8 @@ int32_t sn_utils::ld_int32(std::istream &s) // deserialize little endian uint64 uint64_t sn_utils::ld_uint64(std::istream &s) { - uint8_t buf[8]; - s.read((char*)buf, 8); + std::array buf{}; + s.read(reinterpret_cast(buf.data()), buf.size()); uint64_t v = (uint64_t)buf[7] << 56 | (uint64_t)buf[6] << 48 | (uint64_t)buf[5] << 40 | (uint64_t)buf[4] << 32 | (uint64_t)buf[3] << 24 | (uint64_t)buf[2] << 16 | @@ -55,8 +55,8 @@ uint64_t sn_utils::ld_uint64(std::istream &s) // deserialize little endian int64 int64_t sn_utils::ld_int64(std::istream &s) { - uint8_t buf[8]; - s.read((char*)buf, 8); + std::array buf{}; + s.read(reinterpret_cast(buf.data()), buf.size()); uint64_t v = (uint64_t)buf[7] << 56 | (uint64_t)buf[6] << 48 | (uint64_t)buf[5] << 40 | (uint64_t)buf[4] << 32 | (uint64_t)buf[3] << 24 | (uint64_t)buf[2] << 16 | @@ -67,8 +67,8 @@ int64_t sn_utils::ld_int64(std::istream &s) // deserialize little endian ieee754 float32 float sn_utils::ld_float32(std::istream &s) { - uint8_t buf[4]; - s.read((char*)buf, 4); + std::array buf{}; + s.read(reinterpret_cast(buf.data()), buf.size()); uint32_t v = buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0]; return std::bit_cast(v); } @@ -76,8 +76,8 @@ float sn_utils::ld_float32(std::istream &s) // deserialize little endian ieee754 float64 double sn_utils::ld_float64(std::istream &s) { - uint8_t buf[8]; - s.read((char*)buf, 8); + std::array buf{}; + s.read(reinterpret_cast(buf.data()), buf.size()); uint64_t v = (uint64_t)buf[7] << 56 | (uint64_t)buf[6] << 48 | (uint64_t)buf[5] << 40 | (uint64_t)buf[4] << 32 | (uint64_t)buf[3] << 24 | (uint64_t)buf[2] << 16 | @@ -90,13 +90,13 @@ std::string sn_utils::d_str(std::istream &s) { std::string r; r.reserve(32); - char buf[1]; + char c{}; while (true) { - s.read(buf, 1); - if (buf[0] == 0) + s.read(&c, 1); + if (c == 0) break; - r.push_back(buf[0]); + r.push_back(c); } return r; } @@ -141,84 +141,84 @@ uint8_t sn_utils::d_uint8( std::istream& s ) { void sn_utils::ls_uint16(std::ostream &s, uint16_t v) { - uint8_t buf[2]; - buf[0] = v; + std::array buf{}; + buf[0] = static_cast(v); buf[1] = v >> 8; - s.write((char*)buf, 2); + s.write(reinterpret_cast(buf.data()), buf.size()); } void sn_utils::ls_uint32(std::ostream &s, uint32_t v) { - uint8_t buf[4]; - buf[0] = v; - buf[1] = v >> 8; - buf[2] = v >> 16; + std::array buf{}; + buf[0] = static_cast(v); + buf[1] = static_cast(v >> 8); + buf[2] = static_cast(v >> 16); buf[3] = v >> 24; - s.write((char*)buf, 4); + s.write(reinterpret_cast(buf.data()), buf.size()); } void sn_utils::ls_int32(std::ostream &s, int32_t v) { - uint8_t buf[4]; - buf[0] = v; - buf[1] = v >> 8; - buf[2] = v >> 16; + std::array buf{}; + buf[0] = static_cast(v); + buf[1] = static_cast(v >> 8); + buf[2] = static_cast(v >> 16); buf[3] = v >> 24; - s.write((char*)buf, 4); + s.write(reinterpret_cast(buf.data()), buf.size()); } void sn_utils::ls_uint64(std::ostream &s, uint64_t v) { - uint8_t buf[8]; - buf[0] = v; - buf[1] = v >> 8; - buf[2] = v >> 16; - buf[3] = v >> 24; - buf[4] = v >> 32; - buf[5] = v >> 40; - buf[6] = v >> 48; + std::array buf{}; + buf[0] = static_cast(v); + buf[1] = static_cast(v >> 8); + buf[2] = static_cast(v >> 16); + buf[3] = static_cast(v >> 24); + buf[4] = static_cast(v >> 32); + buf[5] = static_cast(v >> 40); + buf[6] = static_cast(v >> 48); buf[7] = v >> 56; - s.write((char*)buf, 8); + s.write(reinterpret_cast(buf.data()), buf.size()); } void sn_utils::ls_int64(std::ostream &s, int64_t v) { - uint8_t buf[8]; - buf[0] = v; - buf[1] = v >> 8; - buf[2] = v >> 16; - buf[3] = v >> 24; - buf[4] = v >> 32; - buf[5] = v >> 40; - buf[6] = v >> 48; + std::array buf{}; + buf[0] = static_cast(v); + buf[1] = static_cast(v >> 8); + buf[2] = static_cast(v >> 16); + buf[3] = static_cast(v >> 24); + buf[4] = static_cast(v >> 32); + buf[5] = static_cast(v >> 40); + buf[6] = static_cast(v >> 48); buf[7] = v >> 56; - s.write((char*)buf, 8); + s.write(reinterpret_cast(buf.data()), buf.size()); } void sn_utils::ls_float32(std::ostream &s, float t) { - uint32_t v = std::bit_cast(t); - uint8_t buf[4]; - buf[0] = v; - buf[1] = v >> 8; - buf[2] = v >> 16; + auto v = std::bit_cast(t); + std::array buf{}; + buf[0] = static_cast(v); + buf[1] = static_cast(v >> 8); + buf[2] = static_cast(v >> 16); buf[3] = v >> 24; - s.write((char*)buf, 4); + s.write(reinterpret_cast(buf.data()), buf.size()); } void sn_utils::ls_float64(std::ostream &s, double t) { - uint64_t v = std::bit_cast(t); - uint8_t buf[8]; - buf[0] = v; - buf[1] = v >> 8; - buf[2] = v >> 16; - buf[3] = v >> 24; - buf[4] = v >> 32; - buf[5] = v >> 40; - buf[6] = v >> 48; + auto v = std::bit_cast(t); + std::array buf{}; + buf[0] = static_cast(v); + buf[1] = static_cast(v >> 8); + buf[2] = static_cast(v >> 16); + buf[3] = static_cast(v >> 24); + buf[4] = static_cast(v >> 32); + buf[5] = static_cast(v >> 40); + buf[6] = static_cast(v >> 48); buf[7] = v >> 56; - s.write((char*)buf, 8); + s.write(reinterpret_cast(buf.data()), buf.size()); } void sn_utils::s_uint8(std::ostream &s, uint8_t v) @@ -226,7 +226,7 @@ void sn_utils::s_uint8(std::ostream &s, uint8_t v) s.write((char*)&v, 1); } -void sn_utils::s_str(std::ostream &s, std::string v) +void sn_utils::s_str(std::ostream &s, std::string const &v) { const char* buf = v.c_str(); s.write(buf, v.size() + 1); diff --git a/scene/sn_utils.h b/scene/sn_utils.h index 54005c6c..4212ac29 100644 --- a/scene/sn_utils.h +++ b/scene/sn_utils.h @@ -29,7 +29,7 @@ public: static void ls_float32(std::ostream&, float); static void ls_float64(std::ostream&, double); static void s_uint8(std::ostream&, uint8_t); - static void s_str(std::ostream&, std::string); + static void s_str(std::ostream&, std::string const &); static void s_bool(std::ostream&, bool); static void s_dvec3(std::ostream&, glm::dvec3 const &); static void s_vec3(std::ostream&, glm::vec3 const &); diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index fbbd0b80..666609b0 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -30,36 +30,36 @@ void render_task::run() cancel(); return; } - for (auto const &datapair : m_input->floats) + for (auto const &[dataname, datavalue] : m_input->floats) { - auto *value{PyGetFloat(datapair.second)}; + auto *value{PyGetFloat(datavalue)}; if (value == nullptr) { PyErr_Clear(); continue; } - PyDict_SetItemString(input, datapair.first.c_str(), value); + PyDict_SetItemString(input, dataname.c_str(), value); Py_DECREF(value); } - for (auto const &datapair : m_input->integers) + for (auto const &[dataname, datavalue] : m_input->integers) { - auto *value{PyLong_FromLong(datapair.second)}; + auto *value{PyLong_FromLong(datavalue)}; if (value == nullptr) { PyErr_Clear(); continue; } - PyDict_SetItemString(input, datapair.first.c_str(), value); + PyDict_SetItemString(input, dataname.c_str(), value); Py_DECREF(value); } - for (auto const &datapair : m_input->bools) + for (auto const &[dataname, datavalue] : m_input->bools) { // Py_True / Py_False sa niesmiertelne, ale PyDict_SetItemString i tak // pobiera wlasna referencje - nie zwalniamy - auto *value{PyGetBool(datapair.second)}; - PyDict_SetItemString(input, datapair.first.c_str(), value); + auto *value{PyGetBool(datavalue)}; + PyDict_SetItemString(input, dataname.c_str(), value); } - for (auto const &datapair : m_input->strings) + for (auto const &[dataname, datavalue] : m_input->strings) { // Nazwy scenerii/wagonow (asName, SceneryFile, asCarName, cCode...) moga // byc albo w UTF-8, albo w starym kodowaniu Windows-1250. PyUnicode_FromString @@ -68,8 +68,8 @@ void render_task::run() // // Strategia: najpierw probujemy UTF-8 (strict). Jesli sie nie uda - probujemy // cp1250. Jesli oba zawioda - pomijamy klucz, ale nie wywracamy symulatora. - char const *const str{datapair.second.c_str()}; - Py_ssize_t const len{static_cast(datapair.second.size())}; + char const *const str{datavalue.c_str()}; + Py_ssize_t const len{static_cast(datavalue.size())}; auto *value{PyUnicode_DecodeUTF8(str, len, "strict")}; if (value == nullptr) @@ -82,16 +82,16 @@ void render_task::run() PyErr_Clear(); continue; } - PyDict_SetItemString(input, datapair.first.c_str(), value); + PyDict_SetItemString(input, dataname.c_str(), value); Py_DECREF(value); } - for (auto const &datapair : m_input->vec2_lists) + for (auto const &[dataname, datavalue] : m_input->vec2_lists) { - PyObject *list = PyList_New(datapair.second.size()); + PyObject *list = PyList_New(datavalue.size()); - for (size_t i = 0; i < datapair.second.size(); i++) + for (size_t i = 0; i < datavalue.size(); i++) { - auto const &vec = datapair.second[i]; + auto const &vec = datavalue[i]; WriteLog("passing " + glm::to_string(vec)); PyObject *tuple = PyTuple_New(2); @@ -101,24 +101,24 @@ void render_task::run() PyList_SetItem(list, i, tuple); // steals ref } - PyDict_SetItemString(input, datapair.first.c_str(), list); + PyDict_SetItemString(input, dataname.c_str(), list); Py_DECREF(list); } m_input = nullptr; // call the renderer - auto *output{PyObject_CallMethod(m_renderer, const_cast("render"), const_cast("O"), input)}; + auto *output{PyObject_CallMethod(m_renderer, "render", "O", input)}; Py_DECREF(input); if (output != nullptr) { - auto *outputWidth = PyObject_CallMethod(m_renderer, const_cast("get_width"), nullptr); - auto *outputHeight = PyObject_CallMethod(m_renderer, const_cast("get_height"), nullptr); + auto *outputWidth = PyObject_CallMethod(m_renderer, "get_width", nullptr); + auto *outputHeight = PyObject_CallMethod(m_renderer, "get_height", nullptr); if (outputWidth != nullptr && outputHeight != nullptr && m_target != nullptr) { - const int screenWidth = static_cast(PyLong_AsLong(outputWidth)); - const int screenHeight = static_cast(PyLong_AsLong(outputHeight)); + const auto screenWidth = static_cast(PyLong_AsLong(outputWidth)); + const auto screenHeight = static_cast(PyLong_AsLong(outputHeight)); const bool useRgb = false && !Global.gfx_usegles; @@ -166,7 +166,7 @@ void render_task::run() } // get commands from renderer - auto *commandsPO = PyObject_CallMethod(m_renderer, const_cast("getCommands"), nullptr); + auto *commandsPO = PyObject_CallMethod(m_renderer, "getCommands", nullptr); if (commandsPO != nullptr) { std::vector commands = python_external_utils::PyObjectToStringArray(commandsPO); @@ -178,10 +178,10 @@ void render_task::run() for (const auto &cmd : commands) { std::string baseCmd; - int p1 = 0, p2 = 0; + int p1 = 0; + int p2 = 0; - size_t pos1 = cmd.find(';'); - if (pos1 == std::string::npos) + if (size_t pos1 = cmd.find(';'); pos1 == std::string::npos) { baseCmd = cmd; } @@ -224,7 +224,7 @@ void render_task::run() } } -void render_task::upload() +void render_task::upload() const { if (Global.python_uploadmain && m_target && m_target->shared_tex) { @@ -232,7 +232,7 @@ void render_task::upload() } } -void render_task::cancel() {} +void render_task::cancel() const { /* nothing to do */ } // initializes the module. returns true on success auto python_taskqueue::init() -> bool @@ -310,7 +310,7 @@ auto python_taskqueue::init() -> bool stringiomodule = PyImport_ImportModule("io"); stringioclassname = stringiomodule != nullptr ? PyObject_GetAttrString(stringiomodule, "StringIO") : nullptr; stringioobject = stringioclassname != nullptr ? PyObject_CallObject(stringioclassname, nullptr) : nullptr; - m_stderr = {(stringioobject == nullptr ? nullptr : PySys_SetObject(const_cast("stderr"), stringioobject) != 0 ? nullptr : stringioobject)}; + m_stderr = {(stringioobject == nullptr ? nullptr : PySys_SetObject("stderr", stringioobject) != 0 ? nullptr : stringioobject)}; if (false == run_file("abstractscreenrenderer")) { @@ -362,23 +362,23 @@ void python_taskqueue::exit() // document intent. clearing the deque also actually releases the tasks, // which the previous code did not do (cancel() is a no-op stub). { - std::lock_guard lock(m_tasks.mutex); - for (auto &task : m_tasks.data) + std::scoped_lock lock(m_tasks.mutex); + for (auto const &task : m_tasks.data) { task->cancel(); } m_tasks.data.clear(); } { - std::lock_guard lock(m_uploadtasks.mutex); + std::scoped_lock lock(m_uploadtasks.mutex); m_uploadtasks.data.clear(); } // reclaim cached python objects while the interpreter is still alive, // so no Py_DECREF lands on a finalized interpreter during later teardown acquire_lock(); - for (auto &entry : m_renderers) + for (auto const &[renderername, rendererobject] : m_renderers) { - Py_XDECREF(entry.second); + Py_XDECREF(rendererobject); } m_renderers.clear(); Py_XDECREF(m_stderr); @@ -394,7 +394,7 @@ void python_taskqueue::exit() auto python_taskqueue::insert(task_request const &Task) -> bool { - if (!m_initialized || false == Global.python_enabled || Task.renderer.empty() || Task.input == nullptr || Task.target == 0) + if (!m_initialized || false == Global.python_enabled || Task.renderer.empty() || Task.input == nullptr || Task.target == nullptr) { return false; } @@ -409,7 +409,7 @@ auto python_taskqueue::insert(task_request const &Task) -> bool bool newtaskinserted{false}; // acquire a lock on the task queue and add the new task { - std::lock_guard lock(m_tasks.mutex); + std::scoped_lock lock(m_tasks.mutex); // check the task list for a pending request with the same target for (auto &task : m_tasks.data) { @@ -437,13 +437,13 @@ auto python_taskqueue::insert(task_request const &Task) -> bool auto python_taskqueue::run_file(std::string const &File, std::string const &Path) -> bool { - auto const lookup{FileExists({Path + File, "python/local/" + File}, {".py"})}; - if (lookup.first.empty()) + auto const [filepath, fileextension]{FileExists({Path + File, "python/local/" + File}, {".py"})}; + if (filepath.empty()) { return false; } - std::ifstream inputfile{lookup.first + lookup.second}; + std::ifstream inputfile{filepath + fileextension}; std::string input; input.assign(std::istreambuf_iterator(inputfile), std::istreambuf_iterator()); @@ -464,17 +464,16 @@ void python_taskqueue::acquire_lock() } // releases the python gil and swaps the main thread out -void python_taskqueue::release_lock() +void python_taskqueue::release_lock() const { PyEval_SaveThread(); } -auto python_taskqueue::fetch_renderer(std::string const Renderer) -> PyObject * +auto python_taskqueue::fetch_renderer(std::string const &Renderer) -> PyObject * { - auto const lookup{m_renderers.find(Renderer)}; - if (lookup != std::end(m_renderers)) + if (auto const lookup{m_renderers.find(Renderer)}; lookup != std::end(m_renderers)) { return lookup->second; } @@ -510,7 +509,7 @@ auto python_taskqueue::fetch_renderer(std::string const Renderer) -> PyObject * } renderer = PyObject_CallObject(renderername, rendererarguments); - PyObject_CallMethod(renderer, const_cast("manul_set_format"), const_cast("(s)"), "RGBA"); + PyObject_CallMethod(renderer, "manul_set_format", "(s)", "RGBA"); if (PyErr_Occurred() != nullptr) { @@ -527,11 +526,11 @@ auto python_taskqueue::fetch_renderer(std::string const Renderer) -> PyObject * } release_lock(); // cache the failures as well so we don't try again on subsequent requests - m_renderers.emplace(Renderer, renderer); + m_renderers.try_emplace(Renderer, renderer); return renderer; } -void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uploadtask_sequence &Upload_Tasks, threading::condition_variable &Condition, std::atomic &Exit) +void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uploadtask_sequence &Upload_Tasks, threading::condition_variable &Condition, std::atomic const &Exit) { if (Context) @@ -554,7 +553,7 @@ void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uplo task = nullptr; // acquire a lock on the task queue and potentially grab a task from it { - std::lock_guard lock(Tasks.mutex); + std::scoped_lock lock(Tasks.mutex); if (false == Tasks.data.empty()) { // fifo @@ -573,7 +572,7 @@ void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uplo task->upload(); else { - std::lock_guard lock(Upload_Tasks.mutex); + std::scoped_lock lock(Upload_Tasks.mutex); Upload_Tasks.data.push_back(task); } if (PyErr_Occurred() != nullptr) @@ -608,9 +607,9 @@ void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uplo void python_taskqueue::update() { - std::lock_guard lock(m_uploadtasks.mutex); + std::scoped_lock lock(m_uploadtasks.mutex); - for (auto &task : m_uploadtasks.data) + for (auto const &task : m_uploadtasks.data) task->upload(); m_uploadtasks.data.clear(); @@ -622,21 +621,21 @@ void python_taskqueue::error() { // std err pythona jest buforowane PyErr_Print(); - auto *errortext{PyObject_CallMethod(m_stderr, const_cast("getvalue"), nullptr)}; - if (errortext != nullptr) + if (auto *errortext{PyObject_CallMethod(m_stderr, "getvalue", nullptr)}; errortext != nullptr) { - const char *errstr = PyUnicode_AsUTF8(errortext); - if (errstr != nullptr) + if (const char *errstr = PyUnicode_AsUTF8(errortext); errstr != nullptr) ErrorLog(errstr); Py_DECREF(errortext); } - PyObject_CallMethod(m_stderr, const_cast("truncate"), const_cast("L"), (long long)0); - PyObject_CallMethod(m_stderr, const_cast("seek"), const_cast("L"), (long long)0); + PyObject_CallMethod(m_stderr, "truncate", "L", (long long)0); + PyObject_CallMethod(m_stderr, "seek", "L", (long long)0); } else { // nie dziala buffor pythona - PyObject *type, *value, *traceback; + PyObject *type; + PyObject *value; + PyObject *traceback; PyErr_Fetch(&type, &value, &traceback); if (type == nullptr) { @@ -647,11 +646,9 @@ void python_taskqueue::error() { ErrorLog("Python Interpreter: don't know how to handle null exception"); } - auto *typetext{PyObject_Str(type)}; - if (typetext != nullptr) + if (auto *typetext{PyObject_Str(type)}; typetext != nullptr) { - const char *s = PyUnicode_AsUTF8(typetext); - if (s) + if (const char *s = PyUnicode_AsUTF8(typetext); s) ErrorLog(s); Py_DECREF(typetext); } @@ -660,8 +657,7 @@ void python_taskqueue::error() auto *valuetext{PyObject_Str(value)}; if (valuetext != nullptr) { - const char *s = PyUnicode_AsUTF8(valuetext); - if (s) + if (const char *s = PyUnicode_AsUTF8(valuetext); s) ErrorLog(s); Py_DECREF(valuetext); } @@ -669,8 +665,7 @@ void python_taskqueue::error() auto *tracebacktext{PyObject_Str(traceback)}; if (tracebacktext != nullptr) { - const char *s = PyUnicode_AsUTF8(tracebacktext); - if (s) + if (const char *s = PyUnicode_AsUTF8(tracebacktext); s) ErrorLog(s); Py_DECREF(tracebacktext); } @@ -709,7 +704,7 @@ std::vector python_external_utils::PyObjectToStringArray(PyObject * return emptyIfError; } - result.push_back(std::string(str)); + result.emplace_back(str); Py_DECREF(item); // Decrease reference count for the item } diff --git a/scripting/PyInt.h b/scripting/PyInt.h index 1f1511a0..c8c41039 100644 --- a/scripting/PyInt.h +++ b/scripting/PyInt.h @@ -80,8 +80,8 @@ class render_task render_task(PyObject *Renderer, std::shared_ptr Input, std::shared_ptr Target) : m_renderer(Renderer), m_input(Input), m_target(Target) {} // methods void run(); - void upload(); - void cancel(); + void upload() const; + void cancel() const; auto target() const -> std::shared_ptr { return m_target; @@ -120,7 +120,7 @@ class python_taskqueue // acquires the python gil and sets the main thread as current void acquire_lock(); // releases the python gil and swaps the main thread out - void release_lock(); + void release_lock() const; void update(); @@ -131,8 +131,8 @@ class python_taskqueue using rendertask_sequence = threading::lockable>>; using uploadtask_sequence = threading::lockable>>; // methods - auto fetch_renderer(std::string const Renderer) -> PyObject *; - void run(GLFWwindow *Context, rendertask_sequence &Tasks, uploadtask_sequence &Upload_Tasks, threading::condition_variable &Condition, std::atomic &Exit); + auto fetch_renderer(std::string const &Renderer) -> PyObject *; + void run(GLFWwindow *Context, rendertask_sequence &Tasks, uploadtask_sequence &Upload_Tasks, threading::condition_variable &Condition, std::atomic const &Exit); void error(); // members diff --git a/scripting/ladderlogic.cpp b/scripting/ladderlogic.cpp index b86aba6f..5a0873d4 100644 --- a/scripting/ladderlogic.cpp +++ b/scripting/ladderlogic.cpp @@ -67,7 +67,7 @@ basic_controller::output( element_handle const Element ) const -> int { } auto -basic_controller::load( std::string const &Filename ) -> bool { +basic_controller::load( std::string_view Filename) -> bool { m_program.clear(); m_updateaccumulator = 0.0; @@ -111,7 +111,7 @@ basic_controller::update( double const Timestep ) -> int { return run(); } -std::map const basic_controller::m_operationcodemap = { +std::map> const basic_controller::m_operationcodemap = { { "ld", opcode_e::op_ld }, { "ldi", opcode_e::op_ldi }, { "and", opcode_e::op_and }, { "ani", opcode_e::op_ani }, { "anb", opcode_e::op_anb }, { "or", opcode_e::op_or }, { "ori", opcode_e::op_ori }, { "orb", opcode_e::op_orb }, @@ -130,10 +130,9 @@ basic_controller::deserialize_operation( cParser &Input ) -> bool { cParser operationparser( operationdata, cParser::buffer_TEXT ); // HACK: operation potentially contains 1-2 parameters so we try to grab the whole set operationparser.getTokens( 3, "\t " ); - std::string - operationname, - operationelement, - operationparameter; + std::string operationname; + std::string operationelement; + std::string operationparameter; operationparser >> operationname >> operationelement @@ -142,7 +141,7 @@ basic_controller::deserialize_operation( cParser &Input ) -> bool { auto const lookup { m_operationcodemap.find( operationname ) }; operation.code = lookup != m_operationcodemap.end() ? lookup->second : opcode_e::op_nop; if( lookup == m_operationcodemap.end() ) { - log_error( "contains unknown command \"" + operationname + "\"", Input.Line() - 1 ); + log_error( "contains unknown command \"" + operationname + "\"", static_cast(Input.Line() - 1) ); } if( operation.code == opcode_e::op_nop ) { return true; } @@ -155,8 +154,8 @@ basic_controller::deserialize_operation( cParser &Input ) -> bool { } if( false == operationparameter.empty() ) { - auto const parameter{ split_string_and_number( operationparameter ) }; - operation.parameter1 = static_cast( parameter.second ); + auto const [parametertype, parameterindex]{ split_string_and_number( operationparameter ) }; + operation.parameter1 = static_cast( parameterindex ); } m_program.emplace_back( operation ); @@ -165,7 +164,7 @@ basic_controller::deserialize_operation( cParser &Input ) -> bool { } auto -basic_controller::insert( std::string const Name, basic_element Element ) -> element_handle { +basic_controller::insert( std::string const &Name, basic_element Element ) -> element_handle { m_elements.push_back( Element ); m_elementnames.push_back( Name ); @@ -301,6 +300,8 @@ basic_controller::run() -> int { } break; } + default: + break; } // accumulator was published at least once, next ld(i) operation will start a new rung m_popstack = true; @@ -316,7 +317,6 @@ basic_controller::run() -> int { break; } auto &target { element( operation.element ) }; - auto const initialstate { target.input() }; target.input() = m_accumulator.back(); // additional operations for advanced element types switch( (basic_element::type_e)target.data.index() ) { @@ -334,6 +334,8 @@ basic_controller::run() -> int { */ break; } + default: + break; } // accumulator was published at least once, next ld(i) operation will start a new rung m_popstack = true; @@ -356,11 +358,16 @@ basic_controller::run() -> int { std::get(target.data).count_value = 0; break; } + default: + break; } // accumulator was published at least once, next ld(i) operation will start a new rung m_popstack = true; break; } + default: { + break; + } } ++programline; } @@ -381,17 +388,18 @@ basic_controller::log_error( std::string const &Error, int const Line ) const { auto basic_controller::guess_element_type_from_name( std::string const &Name ) const -> basic_element::type_e { + using enum plc::basic_element::type_e; - auto const name { split_string_and_number( Name ) }; + auto const [nametype, nameindex]{ split_string_and_number( Name ) }; - if( name.first == "t" || name.first == "ton" || name.first.find("timer.") == 0 ) { - return basic_element::type_e::timer; + if( nametype == "t" || nametype == "ton" || nametype.find("timer.") == 0 ) { + return timer; } - if( name.first == "c" || name.first.find("counter.") == 0 ) { - return basic_element::type_e::counter; + if( nametype == "c" || nametype.find("counter.") == 0 ) { + return counter; } - return basic_element::type_e::variable; + return variable; } } // plc diff --git a/scripting/ladderlogic.h b/scripting/ladderlogic.h index 075e4b0d..545456ab 100644 --- a/scripting/ladderlogic.h +++ b/scripting/ladderlogic.h @@ -27,7 +27,7 @@ public: }; // constructors template - basic_element( basic_element::type_e Type = basic_element::type_e::variable, Args_ ...Args ); + explicit basic_element( basic_element::type_e Type = basic_element::type_e::variable, Args_ ...Args ); // methods // data access auto input() -> int &; @@ -60,7 +60,7 @@ class basic_controller { public: // methods - auto load( std::string const &Filename ) -> bool; + auto load( std::string_view Filename) -> bool; auto update( double const Timestep ) -> int; // finds element with specified name, potentially creating new element of specified type initialized with provided arguments. returns: handle to the element template @@ -100,7 +100,7 @@ private: // methods auto deserialize_operation( cParser &Input ) -> bool; // adds provided item to the collection. returns: true if there's no duplicate with the same name, false otherwise - auto insert( std::string const Name, basic_element Element ) -> element_handle; + auto insert( std::string const &Name, basic_element Element ) -> element_handle; // runs one cycle of current program. returns: error code or 0 if there's no error auto run() -> int; void log_error( std::string const &Error, int const Line = -1 ) const; @@ -110,13 +110,13 @@ private: return Value == 0 ? 1 : 0; } // element access inline - auto element( element_handle const Element ) const -> basic_element const { + auto element( element_handle const Element ) const -> basic_element { return m_elements[ Element - 1 ]; } inline auto element( element_handle const Element ) -> basic_element & { return m_elements[ Element - 1 ]; } // members - static std::map const m_operationcodemap; + static std::map> const m_operationcodemap; element_sequence m_elements; // collection of elements accessed by the plc program name_sequence m_elementnames; handle_sequence m_timerhandles; // indices of timer elements, timer update optimization helper @@ -158,7 +158,7 @@ auto basic_controller::find_or_insert( std::string const &Name, basic_element::t auto index { 1 }; for( auto const &name : m_elementnames ) { if( name == Name ) { - return index; + return static_cast(index); } ++index; } diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 58cdd41a..14ecbb75 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -145,10 +145,10 @@ int lua::scriptapi_event_create(lua_State *L) int lua::scriptapi_event_find(lua_State *L) { std::string name = lua_tostring(L, 1); - basic_event *event = simulation::Events.FindEvent(name); - if (event) + basic_event *foundevent = simulation::Events.FindEvent(name); + if (foundevent) { - lua_pushlightuserdata(L, event); + lua_pushlightuserdata(L, foundevent); return 1; } ErrorLog("lua: missing event: " + name); @@ -158,8 +158,8 @@ int lua::scriptapi_event_find(lua_State *L) int lua::scriptapi_event_exists(lua_State *L) { std::string name = lua_tostring(L, 1); - basic_event *event = simulation::Events.FindEvent(name); - lua_pushboolean(L, event != nullptr); + basic_event *foundevent = simulation::Events.FindEvent(name); + lua_pushboolean(L, foundevent != nullptr); return 1; } @@ -189,9 +189,9 @@ int lua::scriptapi_event_dispatch_n(lua_State *L) std::string name = lua_tostring(L, 1); auto *activator = static_cast(lua_touserdata(L, 2)); double delay = lua_tonumber(L, 3); - basic_event *event = simulation::Events.FindEvent(name); - if (event) - simulation::Events.AddToQuery(event, activator, delay); + basic_event *foundevent = simulation::Events.FindEvent(name); + if (foundevent) + simulation::Events.AddToQuery(foundevent, activator, delay); else ErrorLog("lua: missing event: " + name); return 0; diff --git a/scripting/pythonscreenviewer.cpp b/scripting/pythonscreenviewer.cpp index fa15e9fa..4da50151 100644 --- a/scripting/pythonscreenviewer.cpp +++ b/scripting/pythonscreenviewer.cpp @@ -7,32 +7,31 @@ void texture_window_resize(GLFWwindow *win, int w, int h) { - python_screen_viewer *texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); + auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); texwindow->notify_window_size(win, w, h); } void texture_window_fb_resize(GLFWwindow *win, int w, int h) { - python_screen_viewer *texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); + auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); texwindow->notify_window_fb_size(win, w, h); } -void texture_window_mouse_button(GLFWwindow *win, int button, int action, int mods) +void texture_window_mouse_button(GLFWwindow *win, int button, int action, int /*mods*/) { - python_screen_viewer *texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); + auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); texwindow->notify_click(win, button, action); } void texture_window_cursor_pos(GLFWwindow *win, double x, double y) { - python_screen_viewer *texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); + auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); texwindow->notify_cursor_pos(win, x, y); } -python_screen_viewer::python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string surfacename) +python_screen_viewer::python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &surfacename) + : m_rt(rt), m_touchlist(touchlist) { - m_rt = rt; - m_touchlist = touchlist; for (const auto &viewport : Global.python_viewports) { if (viewport.surface == surfacename) { @@ -49,7 +48,8 @@ python_screen_viewer::python_screen_viewer(std::shared_ptr rt, std::s monitor, false, Global.python_sharectx); { - int w, h; + int w; + int h; glfwGetWindowSize(conf->window, &w, &h); conf->window_size = glm::ivec2(w, h); glfwGetFramebufferSize(conf->window, &w, &h); @@ -79,7 +79,7 @@ python_screen_viewer::~python_screen_viewer() void python_screen_viewer::threadfunc() { - for (auto &window : m_windows) { + for (auto const &window : m_windows) { glfwMakeContextCurrent(window->window); glfwSwapInterval(Global.python_vsync ? 1 : 0); @@ -90,7 +90,7 @@ void python_screen_viewer::threadfunc() glActiveTexture(GL_TEXTURE0); if (Global.python_sharectx) { - glBindTexture(GL_TEXTURE_2D, m_rt->shared_tex->get_id()); + glBindTexture(GL_TEXTURE_2D, static_cast(m_rt->shared_tex->get_id())); } else { GLuint tex; @@ -115,13 +115,16 @@ void python_screen_viewer::threadfunc() { auto start_time = std::chrono::high_resolution_clock::now(); - for (auto &window : m_windows) { + for (auto const &window : m_windows) { unsigned char *image = nullptr; - int format, components, width, height; + int format; + int components; + int width; + int height; if (!Global.python_sharectx) { - std::lock_guard guard(m_rt->mutex); + std::scoped_lock guard(m_rt->mutex); if (window->timestamp == m_rt->timestamp) continue; @@ -185,9 +188,9 @@ void python_screen_viewer::threadfunc() } } -void python_screen_viewer::notify_window_fb_size(GLFWwindow *window, int w, int h) +void python_screen_viewer::notify_window_fb_size(GLFWwindow const *window, int w, int h) const { - for (auto &conf : m_windows) { + for (auto const &conf : m_windows) { if (conf->window == window) { conf->fb_size.x = w; conf->fb_size.y = h; @@ -196,9 +199,9 @@ void python_screen_viewer::notify_window_fb_size(GLFWwindow *window, int w, int } } -void python_screen_viewer::notify_window_size(GLFWwindow *window, int w, int h) +void python_screen_viewer::notify_window_size(GLFWwindow const *window, int w, int h) const { - for (auto &conf : m_windows) { + for (auto const &conf : m_windows) { if (conf->window == window) { conf->window_size.x = w; conf->window_size.y = h; @@ -207,23 +210,23 @@ void python_screen_viewer::notify_window_size(GLFWwindow *window, int w, int h) } } -void python_screen_viewer::notify_cursor_pos(GLFWwindow *window, double x, double y) +void python_screen_viewer::notify_cursor_pos(GLFWwindow const *window, double x, double y) const { - for (auto &conf : m_windows) { + for (auto const &conf : m_windows) { if (conf->window == window) { - conf->cursor_pos.x = x; - conf->cursor_pos.y = y; + conf->cursor_pos.x = static_cast(x); + conf->cursor_pos.y = static_cast(y); return; } } } -void python_screen_viewer::notify_click(GLFWwindow *window, int button, int action) +void python_screen_viewer::notify_click(GLFWwindow const *window, int button, int action) const { if (button != GLFW_MOUSE_BUTTON_LEFT || action != GLFW_PRESS) return; - for (auto &conf : m_windows) { + for (auto const &conf : m_windows) { if (conf->window == window) { auto pos = glm::vec2(conf->cursor_pos) / glm::vec2(conf->window_size); pos.y = 1.0f - pos.y; diff --git a/scripting/pythonscreenviewer.h b/scripting/pythonscreenviewer.h index bd0634c3..ccd78f0e 100644 --- a/scripting/pythonscreenviewer.h +++ b/scripting/pythonscreenviewer.h @@ -35,11 +35,11 @@ class python_screen_viewer void threadfunc(); public: - python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string name); + python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &name); ~python_screen_viewer(); - void notify_window_size(GLFWwindow *window, int w, int h); - void notify_window_fb_size(GLFWwindow *window, int w, int h); - void notify_cursor_pos(GLFWwindow *window, double x, double y); - void notify_click(GLFWwindow *window, int button, int action); + void notify_window_size(GLFWwindow const *window, int w, int h) const; + void notify_window_fb_size(GLFWwindow const *window, int w, int h) const; + void notify_cursor_pos(GLFWwindow const *window, double x, double y) const; + void notify_click(GLFWwindow const *window, int button, int action) const; }; diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index 6c4061c4..14ad2353 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -46,11 +46,10 @@ world_environment::compute_season( int const Yearday ) { { 341, "autumn:" }, { 366, "winter:" } }; auto const lookup = - std::lower_bound( - std::begin( seasonsequence ), std::end( seasonsequence ), + std::ranges::lower_bound( + seasonsequence, std::clamp( Yearday, 1, seasonsequence.back().first ), - []( dayseasonpair const &Left, const int Right ) { - return Left.first < Right; } ); + {}, &dayseasonpair::first ); Global.Season = lookup->second; // season can affect the weather so if it changes, re-calculate weather as well @@ -59,7 +58,7 @@ world_environment::compute_season( int const Yearday ) { // calculates current weather void -world_environment::compute_weather() { +world_environment::compute_weather() const { Global.Weather = Global.Overcast <= 0.10 ? "clear:" : Global.Overcast <= 0.50 ? "scattered:" : @@ -196,7 +195,7 @@ world_environment::update() { if( true == (FreeFlyModeFlag || Global.CabWindowOpen) && Global.Weather == "rain:" ) { if( m_rainsound.is_combined() ) { - m_rainsound.pitch( Global.Overcast - 1.0 ); + m_rainsound.pitch( static_cast(Global.Overcast - 1.0) ); } m_rainsound .gain( m_rainsound.m_amplitudeoffset + m_rainsound.m_amplitudefactor * 1.f ) @@ -228,12 +227,12 @@ world_environment::update_wind() { m_wind.change_time -= timedelta; if( m_wind.change_time < 0 ) { - m_wind.change_time = Random( 5, 15 ); - m_wind.velocity_change = Random( -0.2, 0.2 ); + m_wind.change_time = static_cast(Random( 5, 15 )); + m_wind.velocity_change = static_cast(Random( -0.2, 0.2 )); if( Random() < 0.05 ) { // changes in wind direction should be less frequent than changes in wind speed // TBD, TODO: configuration-driven direction change frequency - m_wind.azimuth_change = Random( -5, 5 ); + m_wind.azimuth_change = static_cast(Random( -5, 5 )); } else { // keep direction change periods short, to avoid too drastic changes in direction diff --git a/simulation/simulationenvironment.h b/simulation/simulationenvironment.h index f4114d53..218a2d18 100644 --- a/simulation/simulationenvironment.h +++ b/simulation/simulationenvironment.h @@ -38,7 +38,7 @@ public: // calculates current season of the year based on set simulation date void compute_season( int const Yearday ); // calculates current weather - void compute_weather(); + void compute_weather() const; // data access inline auto const & sun() const { diff --git a/simulation/simulationtime.cpp b/simulation/simulationtime.cpp index f1683c53..6f9f87a5 100644 --- a/simulation/simulationtime.cpp +++ b/simulation/simulationtime.cpp @@ -27,20 +27,20 @@ scenario_time::init(std::time_t timestamp) { ::memcpy( m_monthdaycounts, monthdaycounts, sizeof( monthdaycounts ) ); // potentially adjust scenario clock - auto const requestedtime { clamp_circular( m_time.wHour * 60 + m_time.wMinute + Global.ScenarioTimeOffset * 60, 24 * 60 ) }; + auto const requestedtime { clamp_circular( static_cast(m_time.wHour * 60 + m_time.wMinute + Global.ScenarioTimeOffset * 60), 24 * 60 ) }; auto const requestedhour { requestedtime / 60 % 24 }; auto const requestedminute { requestedtime % 60 }; // cache requested elements, if any std::tm const tm = utc_tm(timestamp); std::tm const *tms = &tm; - m_time.wYear = tms->tm_year + 1900; - m_time.wMonth = tms->tm_mon + 1; - m_time.wDayOfWeek = tms->tm_wday; - m_time.wDay = tms->tm_mday; - m_time.wHour = tms->tm_hour; - m_time.wMinute = tms->tm_min; - m_time.wSecond = tms->tm_sec; + m_time.wYear = static_cast(tms->tm_year + 1900); + m_time.wMonth = static_cast(tms->tm_mon + 1); + m_time.wDayOfWeek = static_cast(tms->tm_wday); + m_time.wDay = static_cast(tms->tm_mday); + m_time.wHour = static_cast(tms->tm_hour); + m_time.wMinute = static_cast(tms->tm_min); + m_time.wSecond = static_cast(tms->tm_sec); m_time.wMilliseconds = 0; if( Global.fMoveLight > 0.0 ) { @@ -67,7 +67,8 @@ scenario_time::init(std::time_t timestamp) { long DaylightBias; SYSTEMTIME StandardDate; SYSTEMTIME DaylightDate; - } timezoneinfo = { -60, 0, -60, { 0, 10, 0, 5, 3, 0, 0, 0 }, { 0, 3, 0, 5, 2, 0, 0, 0 } }; + }; + registry_time_zone_info timezoneinfo = { -60, 0, -60, { 0, 10, 0, 5, 3, 0, 0, 0 }, { 0, 3, 0, 5, 2, 0, 0, 0 } }; convert_transition_time( timezoneinfo.StandardDate ); convert_transition_time( timezoneinfo.DaylightDate ); @@ -83,7 +84,7 @@ scenario_time::init(std::time_t timestamp) { zonebias += timezoneinfo.StandardBias; } - m_timezonebias = zonebias / 60.0; + m_timezonebias = static_cast(zonebias) / 60.0; } void @@ -95,7 +96,7 @@ scenario_time::update( double const Deltatime ) { ++m_time.wSecond; m_milliseconds -= 1000.0; } - m_time.wMilliseconds = std::floor( m_milliseconds ); + m_time.wMilliseconds = static_cast(std::floor( m_milliseconds )); while( m_time.wSecond >= 60 ) { ++m_time.wMinute; @@ -133,10 +134,10 @@ scenario_time::update( double const Deltatime ) { int scenario_time::year_day( int Day, const int Month, const int Year ) const { - char const daytab[ 2 ][ 13 ] = { + std::array, 2> const daytab = {{ { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } - }; + }}; int const leap { is_leap( Year ) }; for( int i = 1; i < Month; ++i ) @@ -146,12 +147,12 @@ scenario_time::year_day( int Day, const int Month, const int Year ) const { } void -scenario_time::daymonth( WORD &Day, WORD &Month, WORD const Year, WORD const Yearday ) { +scenario_time::daymonth( WORD &Day, WORD &Month, WORD const Year, WORD const Yearday ) const { - WORD daytab[ 2 ][ 13 ] = { + std::array, 2> const daytab = {{ { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 } - }; + }}; int const leap { is_leap( Year ) }; WORD idx = 1; @@ -166,20 +167,19 @@ scenario_time::daymonth( WORD &Day, WORD &Month, WORD const Year, WORD const Yea int scenario_time::julian_day() const { - int yy = ( m_time.wYear < 0 ? m_time.wYear + 1 : m_time.wYear ) - std::floor( ( 12 - m_time.wMonth ) / 10.f ); + auto yy = static_cast( m_time.wYear - std::floor( ( 12 - m_time.wMonth ) / 10.f )); int mm = m_time.wMonth + 9; if( mm >= 12 ) { mm -= 12; } - int K1 = std::floor( 365.25 * ( yy + 4712 ) ); - int K2 = std::floor( 30.6 * mm + 0.5 ); + auto K1 = static_cast(std::floor( 365.25 * ( yy + 4712 ) )); + auto K2 = static_cast(std::floor( 30.6 * mm + 0.5 )); // for dates in Julian calendar int JD = K1 + K2 + m_time.wDay + 59; // for dates in Gregorian calendar; 2299160 is October 15th, 1582 - const int gregorianswitchday = 2299160; - if( JD > gregorianswitchday ) { + if( const int gregorianswitchday = 2299160; JD > gregorianswitchday ) { - int K3 = std::floor( std::floor( yy * 0.01 + 49 ) * 0.75 ) - 38; + auto K3 = static_cast(std::floor( std::floor( yy * 0.01 + 49 ) * 0.75 ) - 38); JD -= K3; } @@ -188,8 +188,8 @@ scenario_time::julian_day() const { void scenario_time::set_time(int yearday, int minute) { m_yearday = yearday; - daymonth(m_time.wDay, m_time.wMonth, m_time.wYear, m_yearday); - m_time.wHour = minute / 60; + daymonth(m_time.wDay, m_time.wMonth, m_time.wYear, static_cast(m_yearday)); + m_time.wHour = static_cast(minute / 60); m_time.wMinute = minute % 60; } @@ -219,10 +219,10 @@ scenario_time::day_of_month( int const Week, int const Weekday, int const Month, if( Week == 5 ) { // 5th week potentially indicates last week in the month, not necessarily actual 5th - char const daytab[ 2 ][ 13 ] = { + std::array, 2> const daytab = {{ { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } - }; + }}; int const leap { is_leap( Year ) }; while( day > daytab[ leap ][ Month ] ) { @@ -246,7 +246,7 @@ void scenario_time::convert_transition_time( SYSTEMTIME &Time ) const { // NOTE: windows uses 0-6 range for days of week numbering, our methods use 1-7 - Time.wDay = day_of_month( Time.wDay, Time.wDayOfWeek + 1, Time.wMonth, m_time.wYear ); + Time.wDay = static_cast(day_of_month( Time.wDay, Time.wDayOfWeek + 1, Time.wMonth, m_time.wYear )); } bool diff --git a/simulation/simulationtime.h b/simulation/simulationtime.h index 49e1a012..aae98ee8 100644 --- a/simulation/simulationtime.h +++ b/simulation/simulationtime.h @@ -56,7 +56,7 @@ private: convert_transition_time( SYSTEMTIME &Time ) const; // calculates day and month from given day of year void - daymonth( WORD &Day, WORD &Month, WORD const Year, WORD const Yearday ); + daymonth( WORD &Day, WORD &Month, WORD const Year, WORD const Yearday ) const; // calculates day of year from given date int year_day( int Day, int const Month, int const Year ) const; diff --git a/utilities/Float3d.cpp b/utilities/Float3d.cpp index 29a63456..a1e4f0db 100644 --- a/utilities/Float3d.cpp +++ b/utilities/Float3d.cpp @@ -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; diff --git a/utilities/Float3d.h b/utilities/Float3d.h index 1e5e9892..027d4e89 100644 --- a/utilities/Float3d.h +++ b/utilities/Float3d.h @@ -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(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(sin((1.0f - t) * omega) * oneOverSinOmega); + k1 = static_cast(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) - diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index 5b4d1d9a..38f8062b 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/Logs.h" +#include + #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 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(tms->tm_year); + st.wMonth = static_cast(tms->tm_mon); + st.wDayOfWeek = static_cast(tms->tm_wday); + st.wDay = static_cast(tms->tm_mday); + st.wHour = static_cast(tms->tm_hour); + st.wMinute = static_cast(tms->tm_min); + st.wSecond = static_cast(tms->tm_sec); + st.wMilliseconds = static_cast(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 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 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); diff --git a/utilities/Timer.cpp b/utilities/Timer.cpp index 5cc9f93a..0b877f2b 100644 --- a/utilities/Timer.cpp +++ b/utilities/Timer.cpp @@ -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 diff --git a/utilities/Timer.h b/utilities/Timer.h index 0e47e14c..32e170a4 100644 --- a/utilities/Timer.h +++ b/utilities/Timer.h @@ -35,7 +35,7 @@ public: std::chrono::duration stop() { m_last = std::chrono::duration_cast( 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(m_last.count()) / 1000.f; return m_last; } float average() const { diff --git a/utilities/color.h b/utilities/color.h index 76aecf16..be853a3d 100644 --- a/utilities/color.h +++ b/utilities/color.h @@ -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(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) ); diff --git a/utilities/comparison.h b/utilities/comparison.h index 84f797a5..f0fc5d0a 100644 --- a/utilities/comparison.h +++ b/utilities/comparison.h @@ -27,12 +27,13 @@ enum class comparison_pass { template 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 } //--------------------------------------------------------------------------- diff --git a/utilities/dictionary.h b/utilities/dictionary.h index 1532b492..f4554583 100644 --- a/utilities/dictionary.h +++ b/utilities/dictionary.h @@ -23,11 +23,11 @@ struct dictionary_source { keyvaluepair_sequence> 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 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 const &Value ) { vec2_lists.emplace_back( Key, Value ); } }; diff --git a/utilities/headtrack.cpp b/utilities/headtrack.cpp index caf62bee..b6085bc1 100644 --- a/utilities/headtrack.cpp +++ b/utilities/headtrack.cpp @@ -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(i))) continue; - std::string name(glfwGetJoystickName(i)); + std::string name(glfwGetJoystickName(static_cast(i))); if (name == Global.headtrack_conf.joy) { - joy_id = i; + joy_id = static_cast(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) diff --git a/utilities/headtrack.h b/utilities/headtrack.h index e22cbe79..65d804d2 100644 --- a/utilities/headtrack.h +++ b/utilities/headtrack.h @@ -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(); diff --git a/utilities/motiontelemetry.cpp b/utilities/motiontelemetry.cpp index 473970d7..b0dd02dc 100644 --- a/utilities/motiontelemetry.cpp +++ b/utilities/motiontelemetry.cpp @@ -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 buffer{}; + buffer[0] = static_cast(Timer::GetTime()); + buffer[1] = static_cast(velocity); + buffer[2] = static_cast(local_acc.y); + buffer[3] = static_cast(local_acc.z); + buffer[4] = static_cast(local_acc.x); + buffer[5] = static_cast(glm::degrees(rot.x)); + buffer[6] = static_cast(glm::degrees(rot.z)); + buffer[7] = static_cast(glm::degrees(rot.y)); + buffer[8] = static_cast(yaw_vel); buffer[9] = 1.0f; - if (send(sock, (char*)buffer, sizeof(buffer), 0) == -1) + if (send(sock, reinterpret_cast(buffer.data()), sizeof(buffer), 0) == -1) WriteLog("motiontelemetry: socket send failed"); } diff --git a/utilities/uart.cpp b/utilities/uart.cpp index ab5060fa..632c2b4c 100644 --- a/utilities/uart.cpp +++ b/utilities/uart.cpp @@ -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 nametocommandmap; std::size_t commandid = 0; for( auto const &description : simulation::Commands_descriptions ) { - nametocommandmap.emplace( + nametocommandmap.try_emplace( description.name, static_cast( 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(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((buffer[12] & 0xF0) >> 4); + auto requested_volume = static_cast((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(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(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; diff --git a/utilities/uart.h b/utilities/uart.h index 1a0f344b..cee227d1 100644 --- a/utilities/uart.h +++ b/utilities/uart.h @@ -3,7 +3,7 @@ #include #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 { diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 804ca66c..ebeae5b3 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -17,6 +17,7 @@ Copyright (C) 2007-2014 Maciej Cierniak //#include #include #include +#include //#ifndef WIN32 //#include //#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 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 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 dist(0, 255); + std::uniform_int_distribution dist(0, 255); std::array 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 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(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?,?\"_++?%Sstzz" +char const charsetconversiontable[] = "E?,?\"_++?%Sstzz" " ^^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(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 diff --git a/utilities/utilities.h b/utilities/utilities.h index 6b8111e3..5392ba6c 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -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(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 T clamp_power_of_two(T Value, T const Min = T(1), T const template Type_ quantize(Type_ const Value, Type_ const Step) { - return Step * std::round(Value / Step); + return static_cast(Step * std::round(Value / Step)); } template T min_speed(T const Left, T const Right) @@ -427,12 +426,12 @@ class condition_variable // methods void wait() { - std::unique_lock lock(m_mutex); + std::unique_lock lock(m_mutex); m_condition.wait(lock, [this]() { return m_spurious == false; }); } template void wait_for(const std::chrono::duration &Time) { - std::unique_lock 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 lock(m_mutex); + std::scoped_lock lock(m_mutex); m_spurious = Spurious; } diff --git a/vehicle/AirCoupler.cpp b/vehicle/AirCoupler.cpp index 81253d60..cf6b3bc5 100644 --- a/vehicle/AirCoupler.cpp +++ b/vehicle/AirCoupler.cpp @@ -18,16 +18,14 @@ AirCoupler::AirCoupler() Clear(); } -AirCoupler::~AirCoupler() -{ -} +AirCoupler::~AirCoupler() = default; /** * \return 1 when \(straight\) TModel3d \c only ModelOn exists * \return 2 when \(slanted\) TModel3d \c ModelxOn exists * \return 0 when neither of them exist */ -int AirCoupler::GetStatus() +int AirCoupler::GetStatus() const { if (ModelxOn) return 2; @@ -51,7 +49,7 @@ void AirCoupler::Clear() /** * Looks for submodels in the model and updates pointers. */ -void AirCoupler::Init(std::string const &asName, TModel3d *Model) +void AirCoupler::Init(std::string const &asName, TModel3d const *Model) { if (!Model) return; diff --git a/vehicle/AirCoupler.h b/vehicle/AirCoupler.h index 3f860e63..2de380fa 100644 --- a/vehicle/AirCoupler.h +++ b/vehicle/AirCoupler.h @@ -14,7 +14,9 @@ http://mozilla.org/MPL/2.0/. class AirCoupler { private: - TSubModel *ModelOn, *ModelOff, *ModelxOn; + TSubModel *ModelOn; + TSubModel *ModelOff; + TSubModel *ModelxOn; bool On; bool xOn; void Update(); @@ -25,10 +27,10 @@ public: ///Reset members. void Clear(); ///Looks for submodels. - void Init(std::string const &asName, TModel3d *Model); + void Init(std::string const &asName, TModel3d const *Model); ///Loads info about coupler. void Load(cParser *Parser, TModel3d *Model); - int GetStatus(); + int GetStatus() const; inline void TurnOn() ///Turns on straight coupler. { On = true; diff --git a/vehicle/Button.cpp b/vehicle/Button.cpp index d4d31877..bdd579a3 100644 --- a/vehicle/Button.cpp +++ b/vehicle/Button.cpp @@ -51,7 +51,7 @@ void TButton::Load( cParser &Parser, TDynamicObject const *Owner ) { // TODO: rework the base part into yaml-compatible flow style mapping submodelname = Parser.getToken( false ); while( true == Load_mapping( Parser ) ) { - ; // all work done by while() + // all work done by while() } } @@ -123,9 +123,8 @@ TButton::Turn( bool const State ) { void TButton::Update( bool const Power ) { // TODO: remove passing manually power state when LD is in place - auto const state { Power && ( bData ? *bData : m_state ) }; - if( state != m_state ) { + if( auto const state { Power && ( bData ? *bData : m_state ) }; state != m_state ) { m_state = state; play(); diff --git a/vehicle/Button.h b/vehicle/Button.h index e2eb38cb..691915b5 100644 --- a/vehicle/Button.h +++ b/vehicle/Button.h @@ -27,7 +27,7 @@ public: bool GetValue() const { return m_state; } inline - bool Active() { + bool Active() const { return pModelOn != nullptr || pModelOff != nullptr; } void Update( bool const Power = true ); bool Init( std::string const &asName, TModel3d const *pModel, bool bNewOn = false ); @@ -36,7 +36,7 @@ public: // returns offset of submodel associated with the button from the model centre glm::vec3 model_offset() const; void gain(float new_volume); - inline uint8_t b() { return m_state ? 1 : 0; }; + inline uint8_t b() const { return m_state ? 1 : 0; }; private: // methods @@ -48,9 +48,8 @@ private: play(); // members - TSubModel - *pModelOn { nullptr }, - *pModelOff { nullptr }; // submodel dla stanu załączonego i wyłączonego + TSubModel *pModelOn { nullptr }; + TSubModel *pModelOff { nullptr }; // submodel dla stanu załączonego i wyłączonego bool m_state { false }; bool const *bData { nullptr }; int iFeedbackBit { 0 }; // Ra: bit informacji zwrotnej, do wyprowadzenia na pulpit diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index 3186030e..e2fe5846 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -40,8 +40,8 @@ void TCamera::Reset() { void TCamera::OnCursorMove(double x, double y) { - m_rotationoffsets.x += y; - m_rotationoffsets.y += x; + m_rotationoffsets.x += static_cast(y); + m_rotationoffsets.y += static_cast(x); } static double ComputeAxisSpeed(double param, double walkspeed, double maxspeed, double threshold) { @@ -142,13 +142,13 @@ void TCamera::Update() // update rotation auto const rotationfactor { std::min( 1.0, 20 * deltatime ) }; - Angle.y -= m_rotationoffsets.y * rotationfactor; - m_rotationoffsets.y *= 1.0 - rotationfactor; - Angle.y = std::remainder(Angle.y, 2.0 * M_PI); + Angle.y -= static_cast(m_rotationoffsets.y * rotationfactor); + m_rotationoffsets.y *= static_cast(1.0 - rotationfactor); + Angle.y = static_cast(std::remainder(Angle.y, 2.0 * M_PI)); // Limit the camera pitch to +/- 90°. - Angle.x = std::clamp(Angle.x - m_rotationoffsets.x * rotationfactor, -M_PI_2, M_PI_2); - m_rotationoffsets.x *= 1.0 - rotationfactor; + Angle.x = static_cast(std::clamp(Angle.x - m_rotationoffsets.x * rotationfactor, -M_PI_2, M_PI_2)); + m_rotationoffsets.x *= static_cast(1.0 - rotationfactor); // update position if( m_owner == nullptr @@ -172,11 +172,7 @@ void TCamera::Update() // attached movement position update auto movement { Velocity * -2.0 }; movement.y = -movement.y; - auto const *owner { ( - m_owner->Mechanik ? - m_owner->Mechanik : - m_owner->ctOwner ) }; - if( owner && owner->Occupied() + if( auto const *owner { ( m_owner->Mechanik ? m_owner->Mechanik : m_owner->ctOwner ) }; owner && owner->Occupied() && owner->Occupied()->CabOccupied < 0 ) { movement *= -1.f; movement.y = -movement.y; @@ -194,7 +190,7 @@ void TCamera::Update() } } -bool TCamera::SetMatrix( glm::dmat4 &Matrix ) { +bool TCamera::SetMatrix( glm::dmat4 &Matrix ) const { Matrix = glm::rotate(Matrix, -(double)Angle.x, glm::dvec3(1, 0, 0)); Matrix = glm::rotate(Matrix, -(double)Angle.y, glm::dvec3(0, 1, 0)); // w zewnętrznym widoku: kierunek patrzenia @@ -215,12 +211,12 @@ void TCamera::RaLook() { // zmiana kierunku patrzenia - przelicza Yaw auto where = LookAt - Pos /*+ Math3D::vector3(0, 3, 0)*/; // trochę w górę od szyn if( where.x != 0.0 || where.z != 0.0 ) { - Angle.y = atan2( -where.x, -where.z ); // kąt horyzontalny + Angle.y = static_cast(atan2( -where.x, -where.z )); // kąt horyzontalny m_rotationoffsets.y = 0.0; } double l = glm::length(where); if( l > 0.0 ) { - Angle.x = asin( where.y / l ); // kąt w pionie + Angle.x = static_cast(asin( where.y / l )); // kąt w pionie m_rotationoffsets.x = 0.0; } }; diff --git a/vehicle/Camera.h b/vehicle/Camera.h index 4b91caf2..5e2f7281 100644 --- a/vehicle/Camera.h +++ b/vehicle/Camera.h @@ -22,7 +22,7 @@ class TCamera { void OnCursorMove(double const x, double const y); bool OnCommand( command_data const &Command ); void Update(); - bool SetMatrix(glm::dmat4 &Matrix); + bool SetMatrix(glm::dmat4 &Matrix) const; void RaLook(); glm::vec3 Angle; // pitch, yaw, roll diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index 63c042d3..d7a41062 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -76,7 +76,7 @@ void TGauge::Init(TSubModel *Submodel, TSubModel *Submodelon, TGaugeAnimation Ty auto const nulloffset { glm::vec3{} }; auto const offset { model_offset() }; { - std::vector soundfxs = { + std::vector soundfxs = { &m_soundfxincrease, &m_soundfxdecrease, &m_soundfxon, @@ -88,17 +88,22 @@ void TGauge::Init(TSubModel *Submodel, TSubModel *Submodelon, TGaugeAnimation Ty } } } - for( auto &soundfx : m_soundfxvalues ) { - if( soundfx.second.offset() == nulloffset ) { - soundfx.second.offset( offset ); + for( auto &[soundfxkey, soundfxsource] : m_soundfxvalues ) { + if( soundfxsource.offset() == nulloffset ) { + soundfxsource.offset( offset ); } } }; void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mul ) { - std::string submodelname, gaugetypename; - float scale, endscale, endvalue, offset, friction; + std::string submodelname; + std::string gaugetypename; + float scale; + float endscale; + float endvalue; + float offset; + float friction; endscale = -1; endvalue = -1; bool interpolatescale { false }; @@ -144,7 +149,7 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu { scratch_data scratchpad; while( true == Load_mapping( Parser, scratchpad ) ) { - ; // all work done by while() + // all work done by while() } // post-deserialization cleanup // set provided custom soundproofing to assigned sounds (for sounds without their own custom soundproofing) @@ -161,9 +166,9 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu if( !m_soundfxoff.soundproofing() ) { m_soundfxoff.soundproofing() = scratchpad.soundproofing; } - for( auto &soundfxrecord : m_soundfxvalues ) { - if( !soundfxrecord.second.soundproofing() ) { - soundfxrecord.second.soundproofing() = scratchpad.soundproofing; + for( auto &[soundfxkey, soundfxsource] : m_soundfxvalues ) { + if( !soundfxsource.soundproofing() ) { + soundfxsource.soundproofing() = scratchpad.soundproofing; } } } @@ -175,13 +180,13 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu m_soundfxdecrease.owner( Owner ); m_soundfxon.owner( Owner ); m_soundfxoff.owner( Owner ); - for( auto &soundfxrecord : m_soundfxvalues ) { - soundfxrecord.second.owner( Owner ); + for( auto &[soundfxkey, soundfxsource] : m_soundfxvalues ) { + soundfxsource.owner( Owner ); } - scale *= mul; + scale *= static_cast(mul); if( interpolatescale ) { - endscale *= mul; + endscale *= static_cast(mul); } TSubModel *submodel { nullptr }; std::array sources { Owner->mdKabina, Owner->mdLowPolyInt }; @@ -211,7 +216,7 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu } } - std::map gaugetypes { + std::map> gaugetypes { { "rot", TGaugeAnimation::gt_Rotate }, { "rotvar", TGaugeAnimation::gt_Rotate }, { "mov", TGaugeAnimation::gt_Move }, @@ -235,13 +240,14 @@ TGauge::Load_mapping( cParser &Input, TGauge::scratch_data &Scratchpad ) { if( true == key.empty() || key == "}" ) { return false; } // if not block end then the key is followed by assigned value or sub-block if( key == "type:" ) { + using enum TGaugeType; auto const gaugetype { Input.getToken( true, "\n\r\t ,;" ) }; - m_type = gaugetype == "push" ? TGaugeType::push : - gaugetype == "impulse" ? TGaugeType::push : - gaugetype == "return" ? TGaugeType::push : - gaugetype == "delayed" ? TGaugeType::push_delayed : - gaugetype == "pushtoggle" ? TGaugeType::pushtoggle : - TGaugeType::toggle; // "toggle" and default + m_type = gaugetype == "push" ? push : + gaugetype == "impulse" ? push : + gaugetype == "return" ? push : + gaugetype == "delayed" ? push_delayed : + gaugetype == "pushtoggle" ? pushtoggle : + toggle; // "toggle" and default } else if( key == "soundinc:" ) { m_soundfxincrease.deserialize( Input, sound_type::single ); @@ -273,7 +279,7 @@ TGauge::Load_mapping( cParser &Input, TGauge::scratch_data &Scratchpad ) { auto const indexstart { key.find_first_of( "-1234567890" ) }; auto const indexend { key.find_first_not_of( "-1234567890", indexstart ) }; if( indexstart != std::string::npos ) { - m_soundfxvalues.emplace( + m_soundfxvalues.try_emplace( std::stoi( key.substr( indexstart, indexend - indexstart ) ), sound_source( m_soundtemplate ).deserialize( Input, sound_type::single ) ); } @@ -285,11 +291,9 @@ TGauge::Load_mapping( cParser &Input, TGauge::scratch_data &Scratchpad ) { bool TGauge::UpdateValue( float fNewDesired, std::optional &Fallbacksound ) { - if( false == UpdateValue( fNewDesired ) ) { - if( Fallbacksound ) { - Fallbacksound->play( m_soundtype ); - return true; - } + if (false == UpdateValue( fNewDesired ) && Fallbacksound) { + Fallbacksound->play( m_soundtype ); + return true; } return false; } @@ -304,8 +308,7 @@ TGauge::UpdateValue( float fNewDesired ) { m_targetvalue = fNewDesired; // if there's any sound associated with new requested value, play it // check value-specific table first... - auto const fullinteger { desiredtimes100 % 100 == 0 }; - if( fullinteger ) { + if( auto const fullinteger { desiredtimes100 % 100 == 0 }; fullinteger ) { // filter out values other than full integers auto const lookup = m_soundfxvalues.find( desiredtimes100 / 100 ); if( lookup != m_soundfxvalues.end() ) { @@ -318,9 +321,8 @@ TGauge::UpdateValue( float fNewDesired ) { m_soundtype = sound_flags::exclusive; } // ...and if there isn't any, fall back on the basic set... - auto const currentvalue = GetValue(); // HACK: crude way to discern controls with continuous and quantized value range - if( currentvalue < fNewDesired ) { + if( auto const currentvalue = GetValue(); currentvalue < fNewDesired ) { // shift up if( false == m_soundfxincrease.empty() ) { m_soundfxincrease.play( m_soundtype ); @@ -357,7 +359,7 @@ void TGauge::Update( bool const Power ) { // update value // TODO: remove passing manually power state when LD is in place if( m_value != m_targetvalue ) { - float dt = Timer::GetDeltaTime(); + auto dt = static_cast(Timer::GetDeltaTime()); if( m_friction > 0 && dt < 0.5 * m_friction ) { // McZapkie-281102: zabezpieczenie przed oscylacjami dla dlugich czasow m_value += dt * ( m_targetvalue - m_value ) / m_friction; @@ -424,11 +426,11 @@ void TGauge::UpdateValue() break; } case 'd': { - UpdateValue( *dData ); + UpdateValue( static_cast(*dData) ); break; } case 'i': { - UpdateValue( *iData ); + UpdateValue( static_cast(*iData) ); break; } case 'b': { @@ -452,13 +454,13 @@ float TGauge::GetScaledValue() const { } void -TGauge::UpdateAnimation( TSubModel *Submodel ) { +TGauge::UpdateAnimation( TSubModel *Submodel ) const { if( Submodel == nullptr ) { return; } switch (m_animation) { case TGaugeAnimation::gt_Rotate: { - Submodel->SetRotate( float3( 0, 1, 0 ), GetScaledValue() * 360.0 ); + Submodel->SetRotate( float3( 0, 1, 0 ), static_cast(GetScaledValue() * 360.0) ); break; } case TGaugeAnimation::gt_Move: { @@ -467,13 +469,12 @@ TGauge::UpdateAnimation( TSubModel *Submodel ) { } case TGaugeAnimation::gt_Wiper: { auto const scaledvalue { GetScaledValue() }; - Submodel->SetRotate( float3( 0, 1, 0 ), scaledvalue * 360.0 ); - auto *sm = Submodel->ChildGet(); - if( sm ) { - sm->SetRotate( float3( 0, 1, 0 ), scaledvalue * 360.0 ); + Submodel->SetRotate( float3( 0, 1, 0 ), static_cast(scaledvalue * 360.0) ); + if( auto *sm = Submodel->ChildGet(); sm ) { + sm->SetRotate( float3( 0, 1, 0 ), static_cast(scaledvalue * 360.0) ); sm = sm->ChildGet(); if( sm ) - sm->SetRotate( float3( 0, 1, 0 ), scaledvalue * 360.0 ); + sm->SetRotate( float3( 0, 1, 0 ), static_cast(scaledvalue * 360.0) ); } break; } @@ -488,7 +489,7 @@ TGauge::UpdateAnimation( TSubModel *Submodel ) { && std::isdigit(sm->pName[0]) ) { sm->SetRotate( float3( 0, 1, 0 ), - -36.0 * ( n[ '0' + 9 - sm->pName[ 0 ] ] - '0' ) ); + static_cast(-36.0 * ( n[ '0' + 9 - sm->pName[ 0 ] ] - '0' )) ); } sm = sm->NextGet(); } while( sm ); diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index bf0f83c3..fdef9c58 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -67,8 +67,8 @@ public: bool is_delayed() const { return ( static_cast( type() ) & static_cast( TGaugeType::delayed ) ) != 0; } // members - TSubModel *SubModel { nullptr }, // McZapkie-310302: zeby mozna bylo sprawdzac czy zainicjowany poprawnie - *SubModelOn { nullptr }; // optional submodel visible when the state input is set + TSubModel *SubModel { nullptr }; // McZapkie-310302: zeby mozna bylo sprawdzac czy zainicjowany poprawnie + TSubModel *SubModelOn { nullptr }; // optional submodel visible when the state input is set private: // types @@ -82,7 +82,7 @@ private: float GetScaledValue() const; void - UpdateAnimation( TSubModel *Submodel ); + UpdateAnimation( TSubModel *Submodel ) const; // members TGaugeAnimation m_animation { TGaugeAnimation::gt_Unknown }; // typ ruchu diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index a77c5749..f0b2367f 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -52,11 +52,11 @@ void control_mapper::insert(TGauge const &Gauge, std::string const &Label) if (Gauge.SubModel != nullptr) { - m_controlnames.emplace(Gauge.SubModel, Label); + m_controlnames.try_emplace(Gauge.SubModel, Label); } if (Gauge.SubModelOn != nullptr) { - m_controlnames.emplace(Gauge.SubModelOn, Label); + m_controlnames.try_emplace(Gauge.SubModelOn, Label); } m_names.emplace(Label); @@ -76,10 +76,10 @@ std::string control_mapper::find(TSubModel const *Control) const } } -bool control_mapper::contains(std::string const Control) const +bool control_mapper::contains(std::string const &Control) const { - return m_names.find(Control) != m_names.end(); + return m_names.contains(Control); } void TTrain::screen_entry::deserialize(cParser &Input) @@ -87,7 +87,7 @@ void TTrain::screen_entry::deserialize(cParser &Input) while (true == deserialize_mapping(Input)) { - ; // all work done by while() + // all work done by while() } } @@ -155,7 +155,7 @@ void TCab::Load(cParser &Parser) Parser.getTokens(); Parser >> token; } - CabPos1.x = std::stod(token); + CabPos1.x = static_cast(std::stod(token)); Parser.getTokens(5, false); Parser >> CabPos1.y >> CabPos1.z >> CabPos2.x >> CabPos2.y >> CabPos2.z; @@ -585,20 +585,11 @@ std::vector const TTrain::fPress_labels = { TTrain::TTrain() { - ShowNextCurrent = false; // McZapkie-240302 - przyda sie do tachometru - fTachoVelocity = 0; - fTachoCount = 0; - fPPress = fNPress = 0; // asMessage=""; - pMechOffset = glm::dvec3(0, 0, 0); - fBlinkTimer = 0; - fHaslerTimer = 0; DynamicSet(nullptr); // ustawia wszystkie mv* //----- - pMechSittingPosition = glm::dvec3(0, 0, 0); // ABu: 180404 - fTachoTimer = 0.0; // włączenie skoków wskazań prędkościomierza // for (int i = 0; i < 8; i++) @@ -626,13 +617,14 @@ TTrain::TTrain() for (int i = 0; i < 20; ++i) { - for (int j = 0; j < 7; ++j) - fPress[i][j] = 0.0; - bBrakes[i][0] = bBrakes[i][1] = false; + for (auto &press : fPress[i]) + press = 0.0; + bBrakes[i][0] = false; + bBrakes[i][1] = false; } } -TTrain::~TTrain() {} +TTrain::~TTrain() = default; bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) { // powiązanie ręcznego sterowania kabiną z pojazdem @@ -765,7 +757,8 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const bool const bEP = mvControlled->LocHandle->GetCP() > 0.2 || fEIMParams[0][5] > 0.01; dict->insert("dir_brake", bEP); bool bPN{false}; - if (typeid(*mvOccupied->Hamulec) == typeid(TLSt) || typeid(*mvOccupied->Hamulec) == typeid(TEStED)) + auto const &brakevalve{*mvOccupied->Hamulec}; + if (auto const &brakevalvetype{typeid(brakevalve)}; brakevalvetype == typeid(TLSt) || brakevalvetype == typeid(TEStED)) { TBrake *temp_ham = mvOccupied->Hamulec.get(); @@ -812,10 +805,10 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("power_returned", mvOccupied->EnergyMeter.second); // induction motor state data - char const *TXTT[10] = {"fd", "fdt", "fdb", "pd", "pdt", "pdb", "itothv", "1", "2", "3"}; - char const *TXTC[10] = {"fr", "frt", "frb", "pr", "prt", "prb", "im", "vm", "ihv", "uhv"}; - char const *TXTD[10] = {"enrot", "nrot", "fill_des", "fill_real", "clutch_des", "clutch_real", "water_temp", "oil_press", "engine_temp", "retarder_fill"}; - char const *TXTP[7] = {"bc", "bp", "sp", "cp", "rp", "mass", "spring"}; + std::array const TXTT{"fd", "fdt", "fdb", "pd", "pdt", "pdb", "itothv", "1", "2", "3"}; + std::array const TXTC{"fr", "frt", "frb", "pr", "prt", "prb", "im", "vm", "ihv", "uhv"}; + std::array const TXTD{"enrot", "nrot", "fill_des", "fill_real", "clutch_des", "clutch_real", "water_temp", "oil_press", "engine_temp", "retarder_fill"}; + std::array const TXTP{"bc", "bp", "sp", "cp", "rp", "mass", "spring"}; char const *TXTB[2] = {"spring_active", "spring_shutoff"}; for (int j = 0; j < 10; ++j) dict->insert("eimp_t_" + std::string(TXTT[j]), fEIMParams[0][j]); @@ -898,19 +891,19 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("slip_" + caridx, bSlip[i]); } // ai state data - auto const *driver{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; + auto const *vehicledriver{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; - dict->insert("velocity_desired", driver->VelDesired); - dict->insert("velroad", driver->VelRoad); - dict->insert("vellimitlast", driver->VelLimitLast); - dict->insert("velsignallast", driver->VelSignalLast); - dict->insert("velsignalnext", driver->VelSignalNext); - dict->insert("velnext", driver->VelNext); - dict->insert("actualproximitydist", driver->ActualProximityDist); + dict->insert("velocity_desired", vehicledriver->VelDesired); + dict->insert("velroad", vehicledriver->VelRoad); + dict->insert("vellimitlast", vehicledriver->VelLimitLast); + dict->insert("velsignallast", vehicledriver->VelSignalLast); + dict->insert("velsignalnext", vehicledriver->VelSignalNext); + dict->insert("velnext", vehicledriver->VelNext); + dict->insert("actualproximitydist", vehicledriver->ActualProximityDist); // train data - driver->TrainTimetable().serialize(dict.get()); - dict->insert("train_atpassengerstop", driver->IsAtPassengerStop); - dict->insert("train_length", driver->fLength); + vehicledriver->TrainTimetable().serialize(dict.get()); + dict->insert("train_atpassengerstop", vehicledriver->IsAtPassengerStop); + dict->insert("train_length", vehicledriver->fLength); // world state data dict->insert("scenario", Global.SceneryFile); dict->insert("hours", static_cast(simulation::Time.data().wHour)); @@ -983,7 +976,7 @@ bool TTrain::is_eztoer() const void TTrain::set_master_controller(double const Position) { - auto positionchange{std::min(Position, mvControlled->CoupledCtrl ? mvControlled->MainCtrlPosNo + mvControlled->ScndCtrlPosNo : mvControlled->MainCtrlPosNo) - + auto positionchange{std::min(static_cast(Position), mvControlled->CoupledCtrl ? mvControlled->MainCtrlPosNo + mvControlled->ScndCtrlPosNo : mvControlled->MainCtrlPosNo) - (mvControlled->CoupledCtrl ? mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos : mvControlled->MainCtrlPos)}; while (positionchange < 0 && true == mvControlled->DecMainCtrl(1)) { @@ -1007,21 +1000,19 @@ void TTrain::set_train_brake(double const Position) return; } - if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (mvOccupied->BrakeCtrlPos == 0 || mvOccupied->BrakeCtrlPos >= 5))) + // sound feedback if the lever movement activates one of the switches + if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (mvOccupied->BrakeCtrlPos == 0 || mvOccupied->BrakeCtrlPos >= 5)) && dsbPneumaticSwitch) { - // sound feedback if the lever movement activates one of the switches - if (dsbPneumaticSwitch) - { - dsbPneumaticSwitch->play(); - } + dsbPneumaticSwitch->play(); } } void TTrain::zero_charging_train_brake() { + using enum TBrakeHandle; if (mvOccupied->BrakeCtrlPos == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && - (mvOccupied->BrakeHandle == TBrakeHandle::FVel6 || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P)) + (mvOccupied->BrakeHandle == FVel6 || mvOccupied->BrakeHandle == MHZ_EN57 || mvOccupied->BrakeHandle == MHZ_K8P)) { // Odskakiwanie hamulce EP set_train_brake(0); @@ -1031,24 +1022,21 @@ void TTrain::zero_charging_train_brake() void TTrain::set_train_brake_speed(TDynamicObject *Vehicle, int const Speed) { - if (true == Vehicle->MoverParameters->BrakeDelaySwitch(Speed)) + // visual feedback + // TODO: add setting indicator to vehicle class, for external lever/indicator + if (true == Vehicle->MoverParameters->BrakeDelaySwitch(Speed) && Vehicle == DynamicObject) { - // visual feedback - // TODO: add setting indicator to vehicle class, for external lever/indicator - if (Vehicle == DynamicObject) + if (ggBrakeProfileCtrl.SubModel != nullptr) { - if (ggBrakeProfileCtrl.SubModel != nullptr) - { - ggBrakeProfileCtrl.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.0 : mvOccupied->BrakeDelayFlag - 1, dsbSwitch); - } - if (ggBrakeProfileG.SubModel != nullptr) - { - ggBrakeProfileG.UpdateValue(mvOccupied->BrakeDelayFlag == bdelay_G ? 1.0 : 0.0, dsbSwitch); - } - if (ggBrakeProfileR.SubModel != nullptr) - { - ggBrakeProfileR.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.0 : 0.0, dsbSwitch); - } + ggBrakeProfileCtrl.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.0 : static_cast(mvOccupied->BrakeDelayFlag - 1), dsbSwitch); + } + if (ggBrakeProfileG.SubModel != nullptr) + { + ggBrakeProfileG.UpdateValue(mvOccupied->BrakeDelayFlag == bdelay_G ? 1.0 : 0.0, dsbSwitch); + } + if (ggBrakeProfileR.SubModel != nullptr) + { + ggBrakeProfileR.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.0 : 0.0, dsbSwitch); } } } @@ -1077,10 +1065,10 @@ TDynamicObject *TTrain::find_nearest_consist_vehicle(bool freefly, glm::vec3 pos if (!freefly) return DynamicObject; - auto coupler{-2}; // scan for vehicle, not any specific coupler - auto *vehicle{DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), 1, 1500, coupler)}; + auto couplerindex{-2}; // scan for vehicle, not any specific coupler + auto *vehicle{DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), 1, 1500, couplerindex)}; if (vehicle == nullptr) - vehicle = DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), -1, 1500, coupler); + vehicle = DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), -1, 1500, couplerindex); // TBD, TODO: perform owner test for the located vehicle return vehicle; } @@ -1109,13 +1097,9 @@ void TTrain::OnCommand_aidriverenable(TTrain *Train, command_data const &Command void TTrain::OnCommand_aidriverdisable(TTrain *Train, command_data const &Command) { - if (Command.action == GLFW_PRESS) - { - // on press - - if (Train->DynamicObject->Mechanik) - Train->DynamicObject->Mechanik->TakeControl(false); - } + // on press + if (Command.action == GLFW_PRESS && Train->DynamicObject->Mechanik) + Train->DynamicObject->Mechanik->TakeControl(false); } auto const EU07_CONTROLLER_BASERETURNDELAY{0.5f}; @@ -1624,13 +1608,10 @@ void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data cons if (Train->ggScndCtrl.is_push()) { // basic push control can't decrease state, but pushtoggle can - if (true == Train->ggScndCtrl.is_toggle()) + if (true == Train->ggScndCtrl.is_toggle() && Command.action == GLFW_PRESS) { - if (Command.action == GLFW_PRESS) - { - // activate on press - Train->mvControlled->DecScndCtrl(1); - } + // activate on press + Train->mvControlled->DecScndCtrl(1); } } // toggle control type @@ -1683,7 +1664,7 @@ void TTrain::OnCommand_secondcontrollerdecreasefast(TTrain *Train, command_data void TTrain::OnCommand_secondcontrollerset(TTrain *Train, command_data const &Command) { - auto const targetposition{std::min(Command.param1, Train->mvControlled->ScndCtrlPosNo)}; + auto const targetposition{std::min(static_cast(Command.param1), Train->mvControlled->ScndCtrlPosNo)}; // HACK: potentially animate push or pushtoggle control if (Train->ggScndCtrl.is_push()) { @@ -1703,12 +1684,10 @@ void TTrain::OnCommand_secondcontrollerset(TTrain *Train, command_data const &Co while (targetposition < Train->mvControlled->GetVirtualScndPos() && true == Train->mvControlled->DecScndCtrl(1)) { // all work is done in the header - ; } while (targetposition > Train->mvControlled->GetVirtualScndPos() && true == Train->mvControlled->IncScndCtrl(1)) { // all work is done in the header - ; } } } @@ -1731,7 +1710,7 @@ void TTrain::OnCommand_independentbrakeincrease(TTrain *Train, command_data cons } else { - Train->mvOccupied->IncLocalBrakeLevel(useStepped ? 1 : Global.brake_speed * Command.time_delta * LocalBrakePosNo); + Train->mvOccupied->IncLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); if (useStepped) { Train->m_mastercontrollerinuse = true; @@ -1786,7 +1765,7 @@ void TTrain::OnCommand_independentbrakedecrease(TTrain *Train, command_data cons } else { - Train->mvOccupied->DecLocalBrakeLevel(useStepped ? 1 : Global.brake_speed * Command.time_delta * LocalBrakePosNo); + Train->mvOccupied->DecLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); if (useStepped) { Train->m_mastercontrollerinuse = true; @@ -2082,18 +2061,13 @@ void TTrain::OnCommand_trainbrakebasepressureincrease(TTrain *Train, command_dat if (Command.action != GLFW_RELEASE) { - switch (Train->mvOccupied->BrakeHandle) - { - case TBrakeHandle::FV4a: + if (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) { Train->mvOccupied->BrakeCtrlPos2 = std::clamp(Train->mvOccupied->BrakeCtrlPos2 - 0.01, -1.5, 2.0); - break; } - default: + else { Train->mvOccupied->BrakeLevelAdd(0.01); - break; - } } } } @@ -2104,18 +2078,13 @@ void TTrain::OnCommand_trainbrakebasepressuredecrease(TTrain *Train, command_dat if (Command.action != GLFW_RELEASE) { - switch (Train->mvOccupied->BrakeHandle) - { - case TBrakeHandle::FV4a: + if (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) { Train->mvOccupied->BrakeCtrlPos2 = std::clamp(Train->mvOccupied->BrakeCtrlPos2 + 0.01, -1.5, 2.0); - break; } - default: + else { Train->mvOccupied->BrakeLevelAdd(-0.01); - break; - } } } } @@ -2136,7 +2105,7 @@ void TTrain::OnCommand_trainbrakeoperationtoggle(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + auto const *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; if (vehicle == nullptr) { return; @@ -2350,20 +2319,17 @@ void TTrain::OnCommand_autosandboxdeactivate(TTrain *Train, command_data const & void TTrain::OnCommand_epbrakecontrolenable(TTrain *Train, command_data const &Command) { auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - if (Command.action == GLFW_PRESS) + // command only works for bistable switch + if (Command.action == GLFW_PRESS && istoggle) { - // command only works for bistable switch - if (istoggle) + if (Train->mvOccupied->EpFuseSwitch(true)) { - if (Train->mvOccupied->EpFuseSwitch(true)) + // audio feedback + if (Train->dsbPneumaticSwitch) { - // audio feedback - if (Train->dsbPneumaticSwitch) - { - Train->dsbPneumaticSwitch->play(); - } - Train->ggEPFuseButton.UpdateValue(1.0f, Train->dsbSwitch); - }; + Train->dsbPneumaticSwitch->play(); + } + Train->ggEPFuseButton.UpdateValue(1.0f, Train->dsbSwitch); } } } @@ -2371,15 +2337,12 @@ void TTrain::OnCommand_epbrakecontrolenable(TTrain *Train, command_data const &C void TTrain::OnCommand_epbrakecontroldisable(TTrain *Train, command_data const &Command) { auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - if (Command.action == GLFW_PRESS) + // command only works for bistable switch + if (Command.action == GLFW_PRESS && istoggle) { - // command only works for bistable switch - if (istoggle) + if (Train->mvOccupied->EpFuseSwitch(false)) { - if (Train->mvOccupied->EpFuseSwitch(false)) - { - Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); - }; + Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); } } } @@ -2403,14 +2366,11 @@ void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &C if (false == Train->mvOccupied->EpFuse) { // turn on - if (Train->mvOccupied->EpFuseSwitch(true)) + // audio feedback + if (Train->mvOccupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) { - // audio feedback - if (Train->dsbPneumaticSwitch) - { - Train->dsbPneumaticSwitch->play(); - } - }; + Train->dsbPneumaticSwitch->play(); + } } else { @@ -2421,14 +2381,11 @@ void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &C else if (ispush) { // potentially turn on - if (Train->mvOccupied->EpFuseSwitch(true)) + // audio feedback + if (Train->mvOccupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) { - // audio feedback - if (Train->dsbPneumaticSwitch) - { - Train->dsbPneumaticSwitch->play(); - } - }; + Train->dsbPneumaticSwitch->play(); + } } // visual feedback Train->ggEPFuseButton.UpdateValue(ispush ? 1.0f : // push or pushtoggle @@ -2436,45 +2393,36 @@ void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &C 0.0f, // toggle Train->dsbSwitch); } - else if (Command.action == GLFW_RELEASE) + else if (Command.action == GLFW_RELEASE && ispush) { - if (ispush) - { - // return the switch to neutral position - Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); - } + // return the switch to neutral position + Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); } } void TTrain::OnCommand_trainbrakeoperationmodeincrease(TTrain *Train, command_data const &Command) { - if (Command.action == GLFW_PRESS) + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action == GLFW_PRESS && (Train->mvOccupied->BrakeOpModeFlag << 1 & Train->mvOccupied->BrakeOpModes) != 0) { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->BrakeOpModeFlag << 1 & Train->mvOccupied->BrakeOpModes) != 0) - { - // next mode - Train->mvOccupied->BrakeOpModeFlag <<= 1; - // visual feedback - Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? std::log2(Train->mvOccupied->BrakeOpModeFlag) : 0); // audio fallback - } + // next mode + Train->mvOccupied->BrakeOpModeFlag <<= 1; + // visual feedback + Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->mvOccupied->BrakeOpModeFlag)) : 0); // audio fallback } } void TTrain::OnCommand_trainbrakeoperationmodedecrease(TTrain *Train, command_data const &Command) { - if (Command.action == GLFW_PRESS) + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action == GLFW_PRESS && (Train->mvOccupied->BrakeOpModeFlag >> 1 & Train->mvOccupied->BrakeOpModes) != 0) { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->BrakeOpModeFlag >> 1 & Train->mvOccupied->BrakeOpModes) != 0) - { - // previous mode - Train->mvOccupied->BrakeOpModeFlag >>= 1; - // visual feedback - Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? std::log2(Train->mvOccupied->BrakeOpModeFlag) : 0); - } + // previous mode + Train->mvOccupied->BrakeOpModeFlag >>= 1; + // visual feedback + Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->mvOccupied->BrakeOpModeFlag)) : 0); } } @@ -2644,7 +2592,7 @@ void TTrain::OnCommand_wiperswitchincrease(TTrain *Train, command_data const &Co Train->mvOccupied->wiperSwitchPos = Train->mvOccupied->WiperListSize - 1; // Visual feedback - Train->ggWiperSw.UpdateValue(Train->mvOccupied->wiperSwitchPos, Train->dsbSwitch); + Train->ggWiperSw.UpdateValue(static_cast(Train->mvOccupied->wiperSwitchPos), Train->dsbSwitch); } } void TTrain::OnCommand_wiperswitchdecrease(TTrain *Train, command_data const &Command) @@ -2656,7 +2604,7 @@ void TTrain::OnCommand_wiperswitchdecrease(TTrain *Train, command_data const &Co Train->mvOccupied->wiperSwitchPos = 0; // visual feedback - Train->ggWiperSw.UpdateValue(Train->mvOccupied->wiperSwitchPos, Train->dsbSwitch); + Train->ggWiperSw.UpdateValue(static_cast(Train->mvOccupied->wiperSwitchPos), Train->dsbSwitch); } } @@ -2673,14 +2621,11 @@ void TTrain::OnCommand_reverserincrease(TTrain *Train, command_data const &Comma return; } - if (Train->mvOccupied->DirectionForward()) + // aktualizacja skrajnych pojazdów w składzie + if (Train->mvOccupied->DirectionForward() && Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) { - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) - { - Train->DynamicObject->Mechanik->DirectionChange(); - } + Train->DynamicObject->Mechanik->DirectionChange(); } } } @@ -2698,15 +2643,11 @@ void TTrain::OnCommand_reverserdecrease(TTrain *Train, command_data const &Comma return; } - if (Train->mvOccupied->DirectionBackward()) + // aktualizacja skrajnych pojazdów w składzie + if (Train->mvOccupied->DirectionBackward() && Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) { - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) - { - Train->DynamicObject->Mechanik->DirectionChange(); - ; - } + Train->DynamicObject->Mechanik->DirectionChange(); } } } @@ -3112,13 +3053,10 @@ void TTrain::OnCommand_cabactivationenable(TTrain *Train, command_data const &Co Train->Dynamic()->SetLights(); } } - else if (Command.action == GLFW_RELEASE) + else if (Command.action == GLFW_RELEASE && Train->ggCabActivationButton.type() == TGaugeType::push) { - if (Train->ggCabActivationButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->ggCabActivationButton.UpdateValue(0.5f); - } + // return the switch to neutral position + Train->ggCabActivationButton.UpdateValue(0.5f); } } @@ -3139,13 +3077,10 @@ void TTrain::OnCommand_cabactivationdisable(TTrain *Train, command_data const &C Train->Dynamic()->SetLights(); } } - else if (Command.action == GLFW_RELEASE) + else if (Command.action == GLFW_RELEASE && Train->ggCabActivationButton.type() == TGaugeType::push) { - if (Train->ggCabActivationButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->ggCabActivationButton.UpdateValue(0.5f); - } + // return the switch to neutral position + Train->ggCabActivationButton.UpdateValue(0.5f); } } @@ -3515,17 +3450,18 @@ void TTrain::OnCommand_pantographlowerselected(TTrain *Train, command_data const void TTrain::update_pantograph_valves() { + using enum operation_t; auto const &presets{mvOccupied->PantsPreset.first}; - auto &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; + auto const &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; auto const preset{presets[selection] - '0'}; auto const swapends{cab_to_end() != end::front}; // check desired states for both pantographs; value: whether the pantograph should be raised auto const frontstate{preset & (swapends ? 2 : 1)}; auto const rearstate{preset & (swapends ? 1 : 2)}; - mvOccupied->OperatePantographValve(end::front, frontstate ? operation_t::enable : operation_t::disable); - mvOccupied->OperatePantographValve(end::rear, rearstate ? operation_t::enable : operation_t::disable); + mvOccupied->OperatePantographValve(end::front, frontstate ? enable : disable); + mvOccupied->OperatePantographValve(end::rear, rearstate ? enable : disable); } void TTrain::change_pantograph_selection(int const Change) @@ -3534,7 +3470,7 @@ void TTrain::change_pantograph_selection(int const Change) auto const &presets{mvOccupied->PantsPreset.first}; auto &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; auto const initialstate{selection}; - selection = std::clamp(selection + Change, 0, std::max(presets.size() - 1, 0)); + selection = std::clamp(selection + Change, 0, std::max(static_cast(presets.size() - 1), 0)); if (selection == initialstate) { @@ -3642,9 +3578,8 @@ void TTrain::OnCommand_pantographcompressorvalvetoggle(TTrain *Train, command_da void TTrain::OnCommand_pantographcompressorvalveenable(TTrain *Train, command_data const &Command) { - auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; - if (false == valveispresent) + if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == valveispresent) { // tylko w maszynowym, unless actual device is present return; @@ -3663,9 +3598,8 @@ void TTrain::OnCommand_pantographcompressorvalveenable(TTrain *Train, command_da void TTrain::OnCommand_pantographcompressorvalvedisable(TTrain *Train, command_data const &Command) { - auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; - if (false == valveispresent) + if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == valveispresent) { // tylko w maszynowym, unless actual device is present return; @@ -3685,8 +3619,7 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data { // tylko w maszynowym, unless actual device is present - auto const switchispresent{Train->m_controlmapper.contains("pantcompressor_sw:") || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; - if (false == switchispresent) + if (auto const switchispresent{Train->m_controlmapper.contains("pantcompressor_sw:") || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == switchispresent) { return; } @@ -3841,12 +3774,9 @@ void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Comma // setup with two separate switches Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); } - else if (Train->ggMainButton.SubModel != nullptr) + else if (Train->ggMainButton.SubModel != nullptr && Train->ggMainButton.type() != TGaugeType::toggle) { - if (Train->ggMainButton.type() != TGaugeType::toggle) - { - Train->ggMainButton.UpdateValue(0.5, Train->dsbSwitch); - } + Train->ggMainButton.UpdateValue(0.5, Train->dsbSwitch); } if (Train->m_linebreakerstate == 1) @@ -3854,16 +3784,13 @@ void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Comma return; } // already in the desired state - if (Train->m_linebreakerstate == 2) + // we don't need to start the diesel twice, but the other types (with impulse switch setup) still need to be launched + // NOTE: this behaviour should depend on MainOnButton presence and type_delayed + // TODO: change it when/if vehicle definition files get their proper switch types + if (Train->m_linebreakerstate == 2 && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) { - // we don't need to start the diesel twice, but the other types (with impulse switch setup) still need to be launched - // NOTE: this behaviour should depend on MainOnButton presence and type_delayed - // TODO: change it when/if vehicle definition files get their proper switch types - if (Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) - { - // try to finalize state change of the line breaker, set the state based on the outcome - Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true) ? 1 : 0; - } + // try to finalize state change of the line breaker, set the state based on the outcome + Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true) ? 1 : 0; } // on button release reset the closing timer Train->fMainRelayTimer = 0.0f; @@ -4677,7 +4604,7 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data Train->mvOccupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->mvOccupied->CompressorListDefPos + 1 : Train->mvOccupied->CompressorListDefPos); // visual feedback - Train->ggCompressorListButton.UpdateValue(Train->mvOccupied->CompressorListPos - 1, Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); } else { @@ -4692,7 +4619,7 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data // active light preset is stored as value in range 1-LigthPosNo Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListPos < Train->mvOccupied->CompressorListPosNo ? Train->mvOccupied->CompressorListPos + 1 : 1); // wrap mode // visual feedback - Train->ggCompressorListButton.UpdateValue(Train->mvOccupied->CompressorListPos - 1, Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); } } } @@ -4723,7 +4650,7 @@ void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_d // visual feedback if (Train->ggCompressorListButton.SubModel != nullptr) { - Train->ggCompressorListButton.UpdateValue(Train->mvOccupied->CompressorListPos - 1, Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); } } } @@ -4745,7 +4672,7 @@ void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_da // visual feedback if (Train->ggCompressorListButton.SubModel != nullptr) { - Train->ggCompressorListButton.UpdateValue(Train->mvOccupied->CompressorListPos - 1, Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); } } @@ -5219,11 +5146,11 @@ void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data cons // HACK: skip submodel animation when restarting cycle, since it plays in the 'wrong' direction if (false == restartcycle) { - Train->ggLightsButton.UpdateValue(Train->mvOccupied->LightsPos - 1, Train->dsbSwitch); + Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); } else { - Train->ggLightsButton.PutValue(Train->mvOccupied->LightsPos - 1); + Train->ggLightsButton.PutValue(static_cast(Train->mvOccupied->LightsPos - 1)); } } } @@ -5256,11 +5183,11 @@ void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data // HACK: skip submodel animation when restarting cycle, since it plays in the 'wrong' direction if (false == restartcycle) { - Train->ggLightsButton.UpdateValue(Train->mvOccupied->LightsPos - 1, Train->dsbSwitch); + Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); } else { - Train->ggLightsButton.PutValue(Train->mvOccupied->LightsPos - 1); + Train->ggLightsButton.PutValue(static_cast(Train->mvOccupied->LightsPos - 1)); } } } @@ -5290,8 +5217,8 @@ void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Co void TTrain::OnCommand_lightsset(TTrain *Train, command_data const &Command) { // set custom item in Lights inventory - Train->mvOccupied->Lights[end::front][17] = Command.param1; - Train->mvOccupied->Lights[end::rear][17] = Command.param2; + Train->mvOccupied->Lights[end::front][17] = static_cast(Command.param1); + Train->mvOccupied->Lights[end::rear][17] = static_cast(Command.param2); Train->mvOccupied->LightsPos = 18; // nasza custom pozycja Train->Dynamic()->SetLights(); } @@ -5894,8 +5821,7 @@ void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data con // update modern dimmer state auto &dimPos = Train->mvOccupied->modernDimmerPosition; - auto dimCount = Train->mvOccupied->dimPositions.size(); - if (dimPos + 1 < dimCount) + if (auto dimCount = Train->mvOccupied->dimPositions.size(); dimPos + 1 < dimCount) dimPos++; else if (Train->mvOccupied->modernDimmerCanCycle) dimPos = 0; // return to 0 @@ -5907,7 +5833,7 @@ void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data con // visual feedback if (Train->ggModernLightDimSw.SubModel != nullptr) - Train->ggModernLightDimSw.UpdateValue(dimPos, Train->dsbSwitch); + Train->ggModernLightDimSw.UpdateValue(static_cast(dimPos), Train->dsbSwitch); } } void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data const &Command) @@ -5934,7 +5860,7 @@ void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data con Train->Dynamic()->SetLightDimmings(); if (Train->ggModernLightDimSw.SubModel != nullptr) - Train->ggModernLightDimSw.UpdateValue(dimPos, Train->dsbSwitch); + Train->ggModernLightDimSw.UpdateValue(static_cast(dimPos), Train->dsbSwitch); } } @@ -6075,7 +6001,7 @@ void TTrain::OnCommand_redmarkerdisablerearright(TTrain *Train, command_data con } } -void TTrain::OnCommand_redmarkerstoggle(TTrain *Train, command_data const &Command) +void TTrain::OnCommand_redmarkerstoggle(TTrain * /*Train*/, command_data const &Command) { if (true == Command.freefly && Command.action == GLFW_PRESS) @@ -6101,7 +6027,7 @@ void TTrain::OnCommand_redmarkerstoggle(TTrain *Train, command_data const &Comma } } -void TTrain::OnCommand_endsignalstoggle(TTrain *Train, command_data const &Command) +void TTrain::OnCommand_endsignalstoggle(TTrain * /*Train*/, command_data const &Command) { if (true == Command.freefly && Command.action == GLFW_PRESS) @@ -6405,15 +6331,12 @@ void TTrain::OnCommand_compartmentlightsenable(TTrain *Train, command_data const } else if (Command.action == GLFW_RELEASE) { - if (Train->m_controlmapper.contains("compartmentlights_sw:")) + if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) { - if (Train->ggCompartmentLightsButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->mvOccupied->CompartmentLightsSwitch(false); - Train->mvOccupied->CompartmentLightsSwitchOff(false); - Train->ggCompartmentLightsButton.UpdateValue(0.5f); - } + // return the switch to neutral position + Train->mvOccupied->CompartmentLightsSwitch(false); + Train->mvOccupied->CompartmentLightsSwitchOff(false); + Train->ggCompartmentLightsButton.UpdateValue(0.5f); } if (Train->m_controlmapper.contains("compartmentlightson_sw:")) { @@ -6449,15 +6372,12 @@ void TTrain::OnCommand_compartmentlightsdisable(TTrain *Train, command_data cons } else if (Command.action == GLFW_RELEASE) { - if (Train->m_controlmapper.contains("compartmentlights_sw:")) + if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) { - if (Train->ggCompartmentLightsButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->mvOccupied->CompartmentLightsSwitch(false); - Train->mvOccupied->CompartmentLightsSwitchOff(false); - Train->ggCompartmentLightsButton.UpdateValue(0.5f); - } + // return the switch to neutral position + Train->mvOccupied->CompartmentLightsSwitch(false); + Train->mvOccupied->CompartmentLightsSwitchOff(false); + Train->ggCompartmentLightsButton.UpdateValue(0.5f); } if (Train->m_controlmapper.contains("compartmentlightsoff_sw:")) { @@ -6685,15 +6605,11 @@ void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) OnCommand_heatingdisable(Train, Command); } } - else if (Command.action == GLFW_RELEASE) + else if (Command.action == GLFW_RELEASE && Train->ggTrainHeatingButton.type() == TGaugeType::push) { - - if (Train->ggTrainHeatingButton.type() == TGaugeType::push) - { - // impulse switch - // visual feedback - Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); - } + // impulse switch + // visual feedback + Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); } } @@ -6762,16 +6678,12 @@ void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) } } } - else if (Command.action == GLFW_RELEASE) + else if (Command.action == GLFW_RELEASE && item.type() == TGaugeType::push) { - - if (item.type() == TGaugeType::push) - { - // impulse switch - // turn off - // visual feedback - item.UpdateValue(0.0); - } + // impulse switch + // turn off + // visual feedback + item.UpdateValue(0.0); } } @@ -6879,8 +6791,7 @@ void TTrain::OnCommand_springbrakerelease(TTrain *Train, command_data const &Com { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) + if (auto const *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; vehicle == nullptr) { return; } @@ -6960,7 +6871,6 @@ void TTrain::OnCommand_speedcontrolbutton(TTrain *Train, command_data const &Com { auto const itemindex = static_cast(Command.command) - static_cast(user_command::speedcontrolbutton0); - auto &item = Train->ggSpeedCtrlButtons[itemindex]; if (Command.action == GLFW_PRESS) { @@ -7233,17 +7143,13 @@ void TTrain::OnCommand_doorpermitleft(TTrain *Train, command_data const &Command Train->ggDoorLeftPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); } } - else if (Command.action == GLFW_RELEASE) + else if (Command.action == GLFW_RELEASE && Train->ggDoorLeftPermitButton.is_push()) { - - if (Train->ggDoorLeftPermitButton.is_push()) - { - // impulse switch - // visual feedback - Train->ggDoorLeftPermitButton.UpdateValue(0.0, Train->dsbSwitch); - // reset potential remote door control timer - Train->m_doorpermittimers[side] = -1.f; - } + // impulse switch + // visual feedback + Train->ggDoorLeftPermitButton.UpdateValue(0.0, Train->dsbSwitch); + // reset potential remote door control timer + Train->m_doorpermittimers[side] = -1.f; } } @@ -7283,17 +7189,13 @@ void TTrain::OnCommand_doorpermitright(TTrain *Train, command_data const &Comman Train->ggDoorRightPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); } } - else if (Command.action == GLFW_RELEASE) + else if (Command.action == GLFW_RELEASE && Train->ggDoorRightPermitButton.type() == TGaugeType::push) { - - if (Train->ggDoorRightPermitButton.type() == TGaugeType::push) - { - // impulse switch - // visual feedback - Train->ggDoorRightPermitButton.UpdateValue(0.0, Train->dsbSwitch); - // reset potential remote door control timer - Train->m_doorpermittimers[side] = -1.f; - } + // impulse switch + // visual feedback + Train->ggDoorRightPermitButton.UpdateValue(0.0, Train->dsbSwitch); + // reset potential remote door control timer + Train->m_doorpermittimers[side] = -1.f; } } @@ -7305,7 +7207,7 @@ void TTrain::OnCommand_doorpermitpresetactivatenext(TTrain *Train, command_data Train->mvOccupied->ChangeDoorPermitPreset(1); // visual feedback - Train->ggDoorPermitPresetButton.UpdateValue(Train->mvOccupied->Doors.permit_preset, Train->dsbSwitch); + Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->mvOccupied->Doors.permit_preset), Train->dsbSwitch); } } @@ -7317,16 +7219,15 @@ void TTrain::OnCommand_doorpermitpresetactivateprevious(TTrain *Train, command_d Train->mvOccupied->ChangeDoorPermitPreset(-1); // visual feedback - Train->ggDoorPermitPresetButton.UpdateValue(Train->mvOccupied->Doors.permit_preset, Train->dsbSwitch); + Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->mvOccupied->Doors.permit_preset), Train->dsbSwitch); } } void TTrain::OnCommand_dooropenleft(TTrain *Train, command_data const &Command) { - auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; - if (false == remoteopencontrol) + if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) { return; } @@ -7366,9 +7267,8 @@ void TTrain::OnCommand_dooropenleft(TTrain *Train, command_data const &Command) void TTrain::OnCommand_doorcloseleft(TTrain *Train, command_data const &Command) { - auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; - if (false == remoteclosecontrol) + if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) { return; } @@ -7499,9 +7399,8 @@ void TTrain::OnCommand_doortoggleright(TTrain *Train, command_data const &Comman void TTrain::OnCommand_dooropenright(TTrain *Train, command_data const &Command) { - auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; - if (false == remoteopencontrol) + if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) { return; } @@ -7542,9 +7441,8 @@ void TTrain::OnCommand_dooropenright(TTrain *Train, command_data const &Command) void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command) { - auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; - if (false == remoteclosecontrol) + if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) { return; } @@ -7599,9 +7497,8 @@ void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command void TTrain::OnCommand_dooropenall(TTrain *Train, command_data const &Command) { - auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; - if (false == remoteopencontrol) + if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) { return; } @@ -7634,9 +7531,8 @@ void TTrain::OnCommand_dooropenall(TTrain *Train, command_data const &Command) void TTrain::OnCommand_doorcloseall(TTrain *Train, command_data const &Command) { - auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; - if (false == remoteclosecontrol) + if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) { return; } @@ -7754,15 +7650,15 @@ void TTrain::OnCommand_nearestcarcouplingincrease(TTrain *Train, command_data co if (true == Command.freefly && Command.action == GLFW_PRESS) { // tryb freefly, press only - auto coupler{-1}; - auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, coupler)}; + auto couplerindex{-1}; + auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, couplerindex)}; if (vehicle == nullptr) - vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, coupler); + vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, couplerindex); - if (coupler != -1 && vehicle != nullptr) + if (couplerindex != -1 && vehicle != nullptr) { - vehicle->couple(coupler); + vehicle->couple(couplerindex); } if (Train->DynamicObject->Mechanik) { @@ -7778,15 +7674,15 @@ void TTrain::OnCommand_nearestcarcouplingdisconnect(TTrain *Train, command_data if (true == Command.freefly && Command.action == GLFW_PRESS) { // tryb freefly, press only - auto coupler{-1}; - auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, coupler)}; + auto couplerindex{-1}; + auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, couplerindex)}; if (vehicle == nullptr) - vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, coupler); + vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, couplerindex); - if (coupler != -1 && vehicle != nullptr) + if (couplerindex != -1 && vehicle != nullptr) { - vehicle->uncouple(coupler); + vehicle->uncouple(couplerindex); } if (Train->DynamicObject->Mechanik) { @@ -7796,7 +7692,7 @@ void TTrain::OnCommand_nearestcarcouplingdisconnect(TTrain *Train, command_data } } -void TTrain::OnCommand_nearestcarcoupleradapterattach(TTrain *Train, command_data const &Command) +void TTrain::OnCommand_nearestcarcoupleradapterattach(TTrain * /*Train*/, command_data const &Command) { if (true == Command.freefly && Command.action == GLFW_PRESS) @@ -7808,14 +7704,14 @@ void TTrain::OnCommand_nearestcarcoupleradapterattach(TTrain *Train, command_dat return; } - auto const coupler = + auto const couplerindex = glm::length2(glm::vec3{vehicle->CouplerPosition(end::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(end::rear)} - Command.location) ? end::front : end::rear; - vehicle->attach_coupler_adapter(coupler); + vehicle->attach_coupler_adapter(couplerindex); } } -void TTrain::OnCommand_nearestcarcoupleradapterremove(TTrain *Train, command_data const &Command) +void TTrain::OnCommand_nearestcarcoupleradapterremove(TTrain * /*Train*/, command_data const &Command) { if (true == Command.freefly && Command.action == GLFW_PRESS) @@ -7827,10 +7723,10 @@ void TTrain::OnCommand_nearestcarcoupleradapterremove(TTrain *Train, command_dat return; } - auto const coupler = + auto const couplerindex = glm::length2(glm::vec3{vehicle->CouplerPosition(end::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(end::rear)} - Command.location) ? end::front : end::rear; - vehicle->remove_coupler_adapter(coupler); + vehicle->remove_coupler_adapter(couplerindex); } } @@ -8144,7 +8040,7 @@ void TTrain::OnCommand_radiochannelset(TTrain *Train, command_data const &Comman { // on press or hold Train->RadioChannel() = std::clamp((int)Command.param1, 1, 10); - Train->ggRadioChannelSelector.UpdateValue(Train->RadioChannel() - 1); + Train->ggRadioChannelSelector.UpdateValue(static_cast(Train->RadioChannel() - 1)); } } @@ -8284,7 +8180,7 @@ void TTrain::OnCommand_radiovolumeset(TTrain *Train, command_data const &Command if (Command.action != GLFW_RELEASE) { // on press or hold - Train->m_radiovolume = std::clamp(Command.param1, 0.0, 1.0); + Train->m_radiovolume = static_cast(std::clamp(Command.param1, 0.0, 1.0)); Train->ggRadioVolumeSelector.UpdateValue(Train->m_radiovolume); audio::event_volume_change = true; } @@ -8295,9 +8191,7 @@ void TTrain::OnCommand_cabchangeforward(TTrain *Train, command_data const &Comma if (Command.action == GLFW_PRESS) { - auto const *owner{(Train->DynamicObject->ctOwner != nullptr ? Train->DynamicObject->ctOwner : Train->DynamicObject->Mechanik)}; - auto const movedirection{1}; - if (false == Train->CabChange(movedirection)) + if (auto const movedirection{1}; false == Train->CabChange(movedirection)) { auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; if (TestFlag(Train->mvOccupied->Couplers[exitdirection].CouplingFlag, coupling::gangway)) @@ -8326,9 +8220,7 @@ void TTrain::OnCommand_cabchangebackward(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { - auto const *owner{(Train->DynamicObject->ctOwner != nullptr ? Train->DynamicObject->ctOwner : Train->DynamicObject->Mechanik)}; - auto const movedirection{-1}; - if (false == Train->CabChange(movedirection)) + if (auto const movedirection{-1}; false == Train->CabChange(movedirection)) { // current vehicle doesn't extend any farther in this direction, check if we there's one connected we can move to auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; @@ -8401,15 +8293,11 @@ void TTrain::UpdateCab() // Ra: przesiadka, jeśli AI zmieniło kabinę (a człon?)... if (DynamicObject->Mechanik // może nie być? - && DynamicObject->Mechanik->AIControllFlag) + && DynamicObject->Mechanik->AIControllFlag && iCabn != ( // numer kabiny (-1: kabina B) + mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied)) { - if (iCabn != ( // numer kabiny (-1: kabina B) - mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied)) - { - - InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd"); - } + InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd"); } iCabn = mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied; } @@ -8418,22 +8306,16 @@ bool TTrain::Update(double const Deltatime) { // train state update // line breaker: - if (m_linebreakerstate == 0) + if (m_linebreakerstate == 0 && true == mvControlled->Mains) { - if (true == mvControlled->Mains) - { - // crude way to sync state of the linebreaker with ai-issued commands - m_linebreakerstate = 1; - } + // crude way to sync state of the linebreaker with ai-issued commands + m_linebreakerstate = 1; } - if (m_linebreakerstate == 1) + if (m_linebreakerstate == 1 && false == (mvControlled->Mains || mvControlled->dizel_startup)) { - if (false == (mvControlled->Mains || mvControlled->dizel_startup)) - { - // crude way to catch cases where the main was knocked out - // because the state of the line breaker isn't changed to match, we need to do it here manually - m_linebreakerstate = 0; - } + // crude way to catch cases where the main was knocked out + // because the state of the line breaker isn't changed to match, we need to do it here manually + m_linebreakerstate = 0; } if ((ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || @@ -8443,7 +8325,7 @@ bool TTrain::Update(double const Deltatime) // keep track of period the line breaker button is held down, to determine when/if circuit closes if (mvControlled->MainSwitchCheck()) { - fMainRelayTimer += Deltatime; + fMainRelayTimer += static_cast(Deltatime); } } else @@ -8456,24 +8338,18 @@ bool TTrain::Update(double const Deltatime) // if the button disconnecting the line breaker is down prevent the timer from accumulating fMainRelayTimer = 0.0f; } - if (m_linebreakerstate == 0) + if (m_linebreakerstate == 0 && fMainRelayTimer > mvControlled->InitialCtrlDelay) { - if (fMainRelayTimer > mvControlled->InitialCtrlDelay) - { - // wlaczanie WSa z opoznieniem - // mark the line breaker as ready to close; for electric series vehicles with impulse switch the setup is completed on button release - m_linebreakerstate = 2; - } + // wlaczanie WSa z opoznieniem + // mark the line breaker as ready to close; for electric series vehicles with impulse switch the setup is completed on button release + m_linebreakerstate = 2; } - if (m_linebreakerstate == 2) + // for diesels and/or vehicles with toggle switch setup we complete the engine start here + // TODO: make it a test for main_on_bt of type push_delayed instead + if (m_linebreakerstate == 2 && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) { - // for diesels and/or vehicles with toggle switch setup we complete the engine start here - // TODO: make it a test for main_on_bt of type push_delayed instead - if (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor) - { - // try to finalize state change of the line breaker, set the state based on the outcome - m_linebreakerstate = mvControlled->MainSwitch(true) ? 1 : 0; - } + // try to finalize state change of the line breaker, set the state based on the outcome + m_linebreakerstate = mvControlled->MainSwitch(true) ? 1 : 0; } // door permits for (auto idx = 0; idx < 2; ++idx) @@ -8483,7 +8359,7 @@ bool TTrain::Update(double const Deltatime) { continue; } - doorpermittimer -= Deltatime; + doorpermittimer -= static_cast(Deltatime); if (doorpermittimer < 0.f) { mvOccupied->OperateDoors(static_cast(idx), true); @@ -8493,7 +8369,7 @@ bool TTrain::Update(double const Deltatime) // train measurement timer if (trainLenghtMeasureTimer >= 0.f) { - trainLenghtMeasureTimer -= Deltatime; + trainLenghtMeasureTimer -= static_cast(Deltatime); if (trainLenghtMeasureTimer < 0.f) trainLenghtMeasureTimer = -1.f; } @@ -8501,7 +8377,7 @@ bool TTrain::Update(double const Deltatime) // battery timer if (fBatteryTimer >= 0.f) { - fBatteryTimer -= Deltatime; + fBatteryTimer -= static_cast(Deltatime); if (fBatteryTimer < 0.f) fBatteryTimer = -1.f; } @@ -8511,14 +8387,14 @@ bool TTrain::Update(double const Deltatime) { m_doors = DynamicObject->Mechanik->IsAnyDoorOpen[side::right] || DynamicObject->Mechanik->IsAnyDoorOpen[side::left]; m_doorpermits = DynamicObject->Mechanik->IsAnyDoorPermitActive[side::right] || DynamicObject->Mechanik->IsAnyDoorPermitActive[side::left]; - m_doorspermitleft = mvOccupied->Doors.instances[(cab_to_end() == end::front ? side::left : side::right)].open_permit && + m_doorspermitleft = mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].open_permit && (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || - mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[(cab_to_end() == end::front ? side::left : side::right)] || - (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[(cab_to_end() == end::front ? side::left : side::right)])); - m_doorspermitright = mvOccupied->Doors.instances[(cab_to_end() == end::front ? side::right : side::left)].open_permit && + mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right] || + (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == end::front ? side::left : side::right])); + m_doorspermitright = mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].open_permit && (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || - mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[(cab_to_end() == end::front ? side::right : side::left)] || - (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[(cab_to_end() == end::front ? side::right : side::left)])); + mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left] || + (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == end::front ? side::right : side::left])); } m_dirforward = mvControlled->DirActive > 0; m_dirneutral = mvControlled->DirActive == 0; @@ -8547,34 +8423,31 @@ bool TTrain::Update(double const Deltatime) UpdateCab(); - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag) + // nie blokujemy AI + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag && (mvOccupied->TrainType == dt_ET40 || mvOccupied->TrainType == dt_EP05 || mvOccupied->HasCamshaft)) { - // nie blokujemy AI - if (mvOccupied->TrainType == dt_ET40 || mvOccupied->TrainType == dt_EP05 || mvOccupied->HasCamshaft) + // dla ET40 i EU05 automatyczne cofanie nastawnika - i tak nie będzie to działać dobrze... + // TODO: use deltatime to stabilize speed + /* + if( false == ( + ( input::command == user_command::mastercontrollerset ) + || ( input::command == user_command::mastercontrollerincrease ) + || ( input::command == user_command::mastercontrollerdecrease ) ) ) { + */ + if (false == (m_mastercontrollerinuse || Global.ctrlState)) { - // dla ET40 i EU05 automatyczne cofanie nastawnika - i tak nie będzie to działać dobrze... - // TODO: use deltatime to stabilize speed - /* - if( false == ( - ( input::command == user_command::mastercontrollerset ) - || ( input::command == user_command::mastercontrollerincrease ) - || ( input::command == user_command::mastercontrollerdecrease ) ) ) { - */ - if (false == (m_mastercontrollerinuse || Global.ctrlState)) + m_mastercontrollerreturndelay -= static_cast(Deltatime); + if (m_mastercontrollerreturndelay < 0.f) { - m_mastercontrollerreturndelay -= Deltatime; - if (m_mastercontrollerreturndelay < 0.f) + m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; + if (mvOccupied->MainCtrlPos > mvOccupied->MainCtrlActualPos) { - m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; - if (mvOccupied->MainCtrlPos > mvOccupied->MainCtrlActualPos) - { - mvOccupied->DecMainCtrl(1); - } - else if (mvOccupied->MainCtrlPos < mvOccupied->MainCtrlActualPos) - { - // Ra 15-01: a to nie miało być tylko cofanie? - mvOccupied->IncMainCtrl(1); - } + mvOccupied->DecMainCtrl(1); + } + else if (mvOccupied->MainCtrlPos < mvOccupied->MainCtrlActualPos) + { + // Ra 15-01: a to nie miało być tylko cofanie? + mvOccupied->IncMainCtrl(1); } } } @@ -8595,9 +8468,9 @@ bool TTrain::Update(double const Deltatime) if (ff != fTachoTimer) // jesli w tej sekundzie nie zmienial { if (fTachoVelocity >= 5) // jedzie - fTachoVelocityJump = fTachoVelocity + (2.0 - LocalRandom(3) + LocalRandom(3)) * 0.5; + fTachoVelocityJump = static_cast(fTachoVelocity + (2.0 - LocalRandom(3) + LocalRandom(3)) * 0.5); else if (fTachoVelocity < 5 && fTachoVelocity > 1) - fTachoVelocityJump = Random(0, 4); // tu ma sie bujac jak wariat i zatrzymac na jakiejs predkosci + fTachoVelocityJump = static_cast(Random(0, 4)); // tu ma sie bujac jak wariat i zatrzymac na jakiejs predkosci // fTachoVelocityJump = 0; // stoi fTachoTimer = ff; // juz zmienil } @@ -8605,43 +8478,48 @@ bool TTrain::Update(double const Deltatime) if (fTachoVelocity > 1) // McZapkie-270503: podkrecanie tachometru { // szybciej zacznij stukac - fTachoCount = std::min(maxtacho, fTachoCount + Deltatime * 3); + fTachoCount = static_cast(std::min(maxtacho, fTachoCount + Deltatime * 3)); } else if (fTachoCount > 0) { // schodz powoli - niektore haslery to ze 4 sekundy potrafia stukac - fTachoCount = std::max(0.0, fTachoCount - Deltatime * 0.66); + fTachoCount = static_cast(std::max(0.0, fTachoCount - Deltatime * 0.66)); } // Ra 2014-09: napięcia i prądy muszą być ustalone najpierw, bo wysyłane są ewentualnie na PoKeys if (mvControlled->EngineType != TEngineType::DieselElectric && mvControlled->EngineType != TEngineType::ElectricInductionMotor) { // Ra 2014-09: czy taki rozdzia? ma sens? - fHVoltage = std::max(mvControlled->PantographVoltage, - mvControlled->GetTrainsetHighVoltage()); // Winger czy to nie jest zle? + fHVoltage = static_cast(std::max(mvControlled->PantographVoltage, + mvControlled->GetTrainsetHighVoltage())); // Winger czy to nie jest zle? } // *mvControlled->Mains); else { - fHVoltage = mvControlled->EngineVoltage; + fHVoltage = static_cast(mvControlled->EngineVoltage); } if (ShowNextCurrent) { // jeśli pokazywać drugi człon if (mvSecond) { // o ile jest ten drugi - fHCurrent[0] = mvSecond->ShowCurrent(0) * 1.05; - fHCurrent[1] = mvSecond->ShowCurrent(1) * 1.05; - fHCurrent[2] = mvSecond->ShowCurrent(2) * 1.05; - fHCurrent[3] = mvSecond->ShowCurrent(3) * 1.05; + fHCurrent[0] = static_cast(mvSecond->ShowCurrent(0) * 1.05); + fHCurrent[1] = static_cast(mvSecond->ShowCurrent(1) * 1.05); + fHCurrent[2] = static_cast(mvSecond->ShowCurrent(2) * 1.05); + fHCurrent[3] = static_cast(mvSecond->ShowCurrent(3) * 1.05); } else - fHCurrent[0] = fHCurrent[1] = fHCurrent[2] = fHCurrent[3] = 0.0; // gdy nie ma człona + { + fHCurrent[0] = 0.0; // gdy nie ma człona + fHCurrent[1] = 0.0; + fHCurrent[2] = 0.0; + fHCurrent[3] = 0.0; + } } else { // normalne pokazywanie - fHCurrent[0] = mvControlled->ShowCurrent(0); - fHCurrent[1] = mvControlled->ShowCurrent(1); - fHCurrent[2] = mvControlled->ShowCurrent(2); - fHCurrent[3] = mvControlled->ShowCurrent(3); + fHCurrent[0] = static_cast(mvControlled->ShowCurrent(0)); + fHCurrent[1] = static_cast(mvControlled->ShowCurrent(1)); + fHCurrent[2] = static_cast(mvControlled->ShowCurrent(2)); + fHCurrent[3] = static_cast(mvControlled->ShowCurrent(3)); } bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; @@ -8672,13 +8550,13 @@ bool TTrain::Update(double const Deltatime) { if (p) { - fPress[i][0] = p->MoverParameters->BrakePress; - fPress[i][1] = p->MoverParameters->PipePress; - fPress[i][2] = p->MoverParameters->ScndPipePress; - fPress[i][3] = p->MoverParameters->CntrlPipePress; - fPress[i][4] = p->MoverParameters->Hamulec->GetBRP(); - fPress[i][5] = (p->MoverParameters->TotalMass - p->MoverParameters->Mred) * 0.001; - fPress[i][6] = p->MoverParameters->SpringBrake.SBP; + fPress[i][0] = static_cast(p->MoverParameters->BrakePress); + fPress[i][1] = static_cast(p->MoverParameters->PipePress); + fPress[i][2] = static_cast(p->MoverParameters->ScndPipePress); + fPress[i][3] = static_cast(p->MoverParameters->CntrlPipePress); + fPress[i][4] = static_cast(p->MoverParameters->Hamulec->GetBRP()); + fPress[i][5] = static_cast((p->MoverParameters->TotalMass - p->MoverParameters->Mred) * 0.001); + fPress[i][6] = static_cast(p->MoverParameters->SpringBrake.SBP); bBrakes[i][0] = p->MoverParameters->SpringBrake.IsActive; bBrakes[i][1] = p->MoverParameters->SpringBrake.ShuttOff; bDoors[i][1] = p->MoverParameters->Doors.instances[side::left].position > 0.f; @@ -8711,19 +8589,19 @@ bool TTrain::Update(double const Deltatime) bSlip[i] = p->MoverParameters->SlippingWheels; if (in < 8 && p->MoverParameters->eimc[eimc_p_Pmax] > 1) { - fEIMParams[1 + in][0] = p->MoverParameters->eimv[eimv_Fmax]; + fEIMParams[1 + in][0] = static_cast(p->MoverParameters->eimv[eimv_Fmax]); fEIMParams[1 + in][1] = std::max(fEIMParams[1 + in][0], 0.f); fEIMParams[1 + in][2] = -std::min(fEIMParams[1 + in][0], 0.f); - fEIMParams[1 + in][3] = p->MoverParameters->eimv[eimv_Fmax] / std::max(p->MoverParameters->eimv[eimv_Fful], 1.); + fEIMParams[1 + in][3] = static_cast(p->MoverParameters->eimv[eimv_Fmax] / std::max(p->MoverParameters->eimv[eimv_Fful], 1.)); fEIMParams[1 + in][4] = std::max(fEIMParams[1 + in][3], 0.f); fEIMParams[1 + in][5] = -std::min(fEIMParams[1 + in][3], 0.f); - fEIMParams[1 + in][6] = p->MoverParameters->eimv[eimv_If]; - fEIMParams[1 + in][7] = p->MoverParameters->eimv[eimv_U]; - fEIMParams[1 + in][8] = p->MoverParameters->Itot; // p->MoverParameters->eimv[eimv_Ipoj]; - fEIMParams[1 + in][9] = p->MoverParameters->EngineVoltage; + fEIMParams[1 + in][6] = static_cast(p->MoverParameters->eimv[eimv_If]); + fEIMParams[1 + in][7] = static_cast(p->MoverParameters->eimv[eimv_U]); + fEIMParams[1 + in][8] = static_cast(p->MoverParameters->Itot); // p->MoverParameters->eimv[eimv_Ipoj]; + fEIMParams[1 + in][9] = static_cast(p->MoverParameters->EngineVoltage); fEIMParams[0][6] += fEIMParams[1 + in][8]; bMains[in] = p->MoverParameters->Mains; - fCntVol[in] = p->MoverParameters->BatteryVoltage; + fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); bFuse[in] = p->MoverParameters->FuseFlag; bBatt[in] = p->MoverParameters->Battery; bConv[in] = p->MoverParameters->ConverterFlag; @@ -8735,18 +8613,18 @@ bool TTrain::Update(double const Deltatime) } if (in < 8 && (p->MoverParameters->EngineType == TEngineType::DieselEngine || p->MoverParameters->EngineType == TEngineType::DieselElectric)) { - fDieselParams[1 + in][0] = p->MoverParameters->enrot * 60; - fDieselParams[1 + in][1] = p->MoverParameters->nrot; - fDieselParams[1 + in][2] = p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].R; - fDieselParams[1 + in][3] = p->MoverParameters->dizel_fill; - fDieselParams[1 + in][4] = p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].Mn; - fDieselParams[1 + in][5] = p->MoverParameters->dizel_engage; + fDieselParams[1 + in][0] = static_cast(p->MoverParameters->enrot * 60); + fDieselParams[1 + in][1] = static_cast(p->MoverParameters->nrot); + fDieselParams[1 + in][2] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].R); + fDieselParams[1 + in][3] = static_cast(p->MoverParameters->dizel_fill); + fDieselParams[1 + in][4] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].Mn); + fDieselParams[1 + in][5] = static_cast(p->MoverParameters->dizel_engage); fDieselParams[1 + in][6] = p->MoverParameters->dizel_heat.Twy; fDieselParams[1 + in][7] = p->MoverParameters->OilPump.pressure; fDieselParams[1 + in][8] = p->MoverParameters->dizel_heat.Ts; - fDieselParams[1 + in][9] = p->MoverParameters->hydro_R_Fill; + fDieselParams[1 + in][9] = static_cast(p->MoverParameters->hydro_R_Fill); bMains[in] = p->MoverParameters->Mains; - fCntVol[in] = p->MoverParameters->BatteryVoltage; + fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); bFuse[in] = p->MoverParameters->FuseFlag; bBatt[in] = p->MoverParameters->Battery; bConv[in] = p->MoverParameters->ConverterFlag; @@ -8761,9 +8639,19 @@ bool TTrain::Update(double const Deltatime) } else { - fPress[i][0] = fPress[i][1] = fPress[i][2] = fPress[i][3] = fPress[i][4] = fPress[i][5] = 0; - bDoors[i][0] = bDoors[i][1] = bDoors[i][2] = bDoors[i][3] = bDoors[i][4] = false; - bBrakes[i][0] = bBrakes[i][1] = false; + fPress[i][0] = 0; + fPress[i][1] = 0; + fPress[i][2] = 0; + fPress[i][3] = 0; + fPress[i][4] = 0; + fPress[i][5] = 0; + bDoors[i][0] = false; + bDoors[i][1] = false; + bDoors[i][2] = false; + bDoors[i][3] = false; + bDoors[i][4] = false; + bBrakes[i][0] = false; + bBrakes[i][1] = false; bSlip[i] = false; iUnits[i] = 0; cCode[i] = 0; //'0'; @@ -8776,11 +8664,11 @@ bool TTrain::Update(double const Deltatime) // else // fEIMParams[0][3] = // mvControlled->eimv[eimv_Fzad] - mvOccupied->LocalBrakeRatio(); // procent zadany - fEIMParams[0][3] = mvOccupied->eimic_real; + fEIMParams[0][3] = static_cast(mvOccupied->eimic_real); fEIMParams[0][4] = std::max(fEIMParams[0][3], 0.f); fEIMParams[0][5] = -std::min(fEIMParams[0][3], 0.f); - fEIMParams[0][1] = fEIMParams[0][4] * mvControlled->eimv[eimv_Fful]; - fEIMParams[0][2] = fEIMParams[0][5] * mvControlled->eimv[eimv_Fful]; + fEIMParams[0][1] = static_cast(fEIMParams[0][4] * mvControlled->eimv[eimv_Fful]); + fEIMParams[0][2] = static_cast(fEIMParams[0][5] * mvControlled->eimv[eimv_Fful]); fEIMParams[0][0] = fEIMParams[0][1] - fEIMParams[0][2]; fEIMParams[0][7] = 0; fEIMParams[0][8] = 0; @@ -8819,7 +8707,7 @@ bool TTrain::Update(double const Deltatime) // Ra 15-01: to musi stąd wylecieć - zależności nie mogą być w kabinie if (mvControlled->ConverterFlag == true) { - fConverterTimer += Deltatime; + fConverterTimer += static_cast(Deltatime); if (mvControlled->CompressorFlag == true && mvControlled->CompressorPower == 1 && (mvControlled->EngineType == TEngineType::ElectricSeriesMotor || mvControlled->TrainType == dt_EZT) && DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT && false == DynamicObject->Mechanik->AIControllFlag) @@ -8844,47 +8732,42 @@ bool TTrain::Update(double const Deltatime) // youBy - prad w drugim czlonie: galaz lub calosc { - TDynamicObject *tmp{nullptr}; - if (DynamicObject->NextConnected()) - if (TestFlag(mvControlled->Couplers[end::rear].CouplingFlag, coupling::control) && mvOccupied->CabOccupied == 1) - tmp = DynamicObject->NextConnected(); - if (DynamicObject->PrevConnected()) - if (TestFlag(mvControlled->Couplers[end::front].CouplingFlag, coupling::control) && mvOccupied->CabOccupied == -1) - tmp = DynamicObject->PrevConnected(); - if (tmp) + TDynamicObject const *tmp{nullptr}; + if (DynamicObject->NextConnected() && TestFlag(mvControlled->Couplers[end::rear].CouplingFlag, coupling::control) && mvOccupied->CabOccupied == 1) + tmp = DynamicObject->NextConnected(); + if (DynamicObject->PrevConnected() && TestFlag(mvControlled->Couplers[end::front].CouplingFlag, coupling::control) && mvOccupied->CabOccupied == -1) + tmp = DynamicObject->PrevConnected(); + if (tmp && tmp->MoverParameters->Power > 0) { - if (tmp->MoverParameters->Power > 0) + if (ggI1B.SubModel) { - if (ggI1B.SubModel) - { - ggI1B.UpdateValue(tmp->MoverParameters->ShowCurrent(1)); - ggI1B.Update(); - } - if (ggI2B.SubModel) - { - ggI2B.UpdateValue(tmp->MoverParameters->ShowCurrent(2)); - ggI2B.Update(); - } - if (ggI3B.SubModel) - { - ggI3B.UpdateValue(tmp->MoverParameters->ShowCurrent(3)); - ggI3B.Update(); - } - if (ggItotalB.SubModel) - { - ggItotalB.UpdateValue(tmp->MoverParameters->ShowCurrent(0)); - ggItotalB.Update(); - } - if (ggWater1TempB.SubModel) - { - ggWater1TempB.UpdateValue(tmp->MoverParameters->dizel_heat.temperatura1); - ggWater1TempB.Update(); - } - if (ggOilPressB.SubModel) - { - ggOilPressB.UpdateValue(tmp->MoverParameters->OilPump.pressure); - ggOilPressB.Update(); - } + ggI1B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(1))); + ggI1B.Update(); + } + if (ggI2B.SubModel) + { + ggI2B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(2))); + ggI2B.Update(); + } + if (ggI3B.SubModel) + { + ggI3B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(3))); + ggI3B.Update(); + } + if (ggItotalB.SubModel) + { + ggItotalB.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(0))); + ggItotalB.Update(); + } + if (ggWater1TempB.SubModel) + { + ggWater1TempB.UpdateValue(tmp->MoverParameters->dizel_heat.temperatura1); + ggWater1TempB.Update(); + } + if (ggOilPressB.SubModel) + { + ggOilPressB.UpdateValue(tmp->MoverParameters->OilPump.pressure); + ggOilPressB.Update(); } } } @@ -8895,7 +8778,7 @@ bool TTrain::Update(double const Deltatime) ggClockSInd.Update(); ggClockMInd.UpdateValue(simulation::Time.data().wMinute); ggClockMInd.Update(); - ggClockHInd.UpdateValue(simulation::Time.data().wHour + simulation::Time.data().wMinute / 60.0); + ggClockHInd.UpdateValue(static_cast(simulation::Time.data().wHour + simulation::Time.data().wMinute / 60.0)); ggClockHInd.Update(); } @@ -8915,7 +8798,7 @@ bool TTrain::Update(double const Deltatime) { if (mvControlled->DynamicBrakeFlag) { - ggEngineVoltage.UpdateValue(std::abs(mvControlled->Im * 5)); + ggEngineVoltage.UpdateValue(static_cast(std::abs(mvControlled->Im * 5))); } else { @@ -8926,8 +8809,8 @@ bool TTrain::Update(double const Deltatime) x = 2; if (mvControlled->RList[mvControlled->MainCtrlActualPos].Mn > 0 && std::abs(mvControlled->Im) > 0) { - ggEngineVoltage.UpdateValue(x * (std::abs(mvControlled->EngineVoltage) - mvControlled->RList[mvControlled->MainCtrlActualPos].R * std::abs(mvControlled->Im)) / - mvControlled->RList[mvControlled->MainCtrlActualPos].Mn); + ggEngineVoltage.UpdateValue(static_cast(x * (std::abs(mvControlled->EngineVoltage) - mvControlled->RList[mvControlled->MainCtrlActualPos].R * std::abs(mvControlled->Im)) / + mvControlled->RList[mvControlled->MainCtrlActualPos].Mn)); } else { @@ -8942,25 +8825,25 @@ bool TTrain::Update(double const Deltatime) { // NOTE: since we don't have functional converter object, we're faking it here by simple check whether converter is on // TODO: implement object-based circuits and power systems model so we can have this working more properly - ggLVoltage.UpdateValue(std::max(mvOccupied->Power110vIsAvailable ? mvOccupied->NominalBatteryVoltage : 0.0, mvOccupied->Power24vIsAvailable ? mvOccupied->BatteryVoltage : 0.0)); + ggLVoltage.UpdateValue(static_cast(std::max(mvOccupied->Power110vIsAvailable ? mvOccupied->NominalBatteryVoltage : 0.0, mvOccupied->Power24vIsAvailable ? mvOccupied->BatteryVoltage : 0.0))); ggLVoltage.Update(); } if (mvControlled->EngineType == TEngineType::DieselElectric) { // ustawienie zmiennych dla silnika spalinowego - fEngine[1] = mvControlled->ShowEngineRotation(1); - fEngine[2] = mvControlled->ShowEngineRotation(2); + fEngine[1] = static_cast(mvControlled->ShowEngineRotation(1)); + fEngine[2] = static_cast(mvControlled->ShowEngineRotation(2)); } else if (mvControlled->EngineType == TEngineType::DieselEngine) { // albo dla innego spalinowego - fEngine[1] = mvControlled->ShowEngineRotation(1); - fEngine[2] = mvControlled->ShowEngineRotation(2); - fEngine[3] = mvControlled->ShowEngineRotation(3); + fEngine[1] = static_cast(mvControlled->ShowEngineRotation(1)); + fEngine[2] = static_cast(mvControlled->ShowEngineRotation(2)); + fEngine[3] = static_cast(mvControlled->ShowEngineRotation(3)); if (ggMainGearStatus.SubModel) { if (mvControlled->Mains) - ggMainGearStatus.UpdateValue(1.1 - std::abs(mvControlled->dizel_automaticgearstatus)); + ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(mvControlled->dizel_automaticgearstatus))); else ggMainGearStatus.UpdateValue(0.0); ggMainGearStatus.Update(); @@ -8978,13 +8861,10 @@ bool TTrain::Update(double const Deltatime) { // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax; - if (veldiff < -0.01) + // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza + if (veldiff < -0.01 && std::abs(mvControlled->Im) > 10.0) { - // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza - if (std::abs(mvControlled->Im) > 10.0) - { - btLampkaPoslizg.Turn(true); - } + btLampkaPoslizg.Turn(true); } } else @@ -9132,8 +9012,8 @@ bool TTrain::Update(double const Deltatime) // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu if (DynamicObject->Mechanik != nullptr) { - btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[(cab_to_end() == end::front ? side::left : side::right)]); - btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[(cab_to_end() == end::front ? side::right : side::left)]); + btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right]); + btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left]); } btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked); btLampkaDoorLockOff.Turn(false == mvOccupied->Doors.lock_enabled); @@ -9278,7 +9158,7 @@ bool TTrain::Update(double const Deltatime) } { // yB - wskazniki drugiego czlonu - TDynamicObject *tmp{nullptr}; //=mvControlled->mvSecond; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... + TDynamicObject const *tmp{nullptr}; //=mvControlled->mvSecond; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... // Ra 2014-07: no nie ma potrzeby szukać tego w każdej klatce if (TestFlag(mvControlled->Couplers[1].CouplingFlag, coupling::control) && mvOccupied->CabOccupied > 0) tmp = DynamicObject->NextConnected(); @@ -9384,9 +9264,9 @@ bool TTrain::Update(double const Deltatime) (mvControlled->DynamicBrakeCtrlPos > 0.0 ? mvControlled->DynamicBrakeCtrlPos * mvControlled->DynamicBrakeCtrlPosNo * -1 * brakerangemultiplier : 0.0) : mvOccupied->LocalBrakePosA > 0.0 ? mvOccupied->LocalBrakePosA * LocalBrakePosNo * -1 * brakerangemultiplier : 0.0}; - ggJointCtrl.UpdateValue(negativePart < 0.0 ? negativePart : - mvControlled->CoupledCtrl ? double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos) : - double(mvControlled->MainCtrlPos), + ggJointCtrl.UpdateValue(negativePart < 0.0 ? static_cast(negativePart) : + mvControlled->CoupledCtrl ? static_cast(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos)) : + static_cast(double(mvControlled->MainCtrlPos)), dsbNastawnikJazdy); ggJointCtrl.Update(); } @@ -9405,20 +9285,20 @@ bool TTrain::Update(double const Deltatime) if (mvControlled->CoupledCtrl) { - ggMainCtrl.UpdateValue(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos), dsbNastawnikJazdy); + ggMainCtrl.UpdateValue(static_cast(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos)), dsbNastawnikJazdy); } else { - ggMainCtrl.UpdateValue(double(mvControlled->MainCtrlPos), dsbNastawnikJazdy); + ggMainCtrl.UpdateValue(static_cast(double(mvControlled->MainCtrlPos)), dsbNastawnikJazdy); } ggMainCtrl.Update(); } if (ggMainCtrlAct.SubModel != nullptr) { if (mvControlled->CoupledCtrl) - ggMainCtrlAct.UpdateValue(double(mvControlled->MainCtrlActualPos + mvControlled->ScndCtrlActualPos)); + ggMainCtrlAct.UpdateValue(static_cast(double(mvControlled->MainCtrlActualPos + mvControlled->ScndCtrlActualPos))); else - ggMainCtrlAct.UpdateValue(double(mvControlled->MainCtrlActualPos)); + ggMainCtrlAct.UpdateValue(static_cast(double(mvControlled->MainCtrlActualPos))); ggMainCtrlAct.Update(); } if (ggScndCtrl.SubModel != nullptr) @@ -9426,7 +9306,7 @@ bool TTrain::Update(double const Deltatime) // Ra: od byte odejmowane boolean i konwertowane potem na double? if (false == ggScndCtrl.is_push()) { - ggScndCtrl.UpdateValue(double(mvControlled->ScndCtrlPos - (mvControlled->TrainType == dt_ET42 && mvControlled->DynamicBrakeFlag)), dsbNastawnikBocz); + ggScndCtrl.UpdateValue(static_cast(double(mvControlled->ScndCtrlPos - (mvControlled->TrainType == dt_ET42 && mvControlled->DynamicBrakeFlag))), dsbNastawnikBocz); } ggScndCtrl.Update(); } @@ -9450,11 +9330,11 @@ bool TTrain::Update(double const Deltatime) { if (mvControlled->TrainType != dt_EZT) { - ggDirKey.UpdateValue(double(mvControlled->DirActive), dsbReverserKey); + ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive)), dsbReverserKey); } else { - ggDirKey.UpdateValue(double(mvControlled->DirActive) + double(mvControlled->Imin == mvControlled->IminHi), dsbReverserKey); + ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive) + double(mvControlled->Imin == mvControlled->IminHi)), dsbReverserKey); } ggDirKey.Update(); } @@ -9495,7 +9375,7 @@ bool TTrain::Update(double const Deltatime) { // else //standardowa prodedura z kranem powiązanym z klawiaturą // ggBrakeCtrl.UpdateValue(double(mvOccupied->BrakeCtrlPos)); - ggBrakeCtrl.UpdateValue(mvOccupied->fBrakeCtrlPos); + ggBrakeCtrl.UpdateValue(static_cast(mvOccupied->fBrakeCtrlPos)); ggBrakeCtrl.Update(); } } @@ -9516,7 +9396,7 @@ bool TTrain::Update(double const Deltatime) #endif { // standardowa prodedura z kranem powiązanym z klawiaturą - ggLocalBrake.UpdateValue(mvOccupied->LocalBrakePosA * LocalBrakePosNo); + ggLocalBrake.UpdateValue(static_cast(mvOccupied->LocalBrakePosA * LocalBrakePosNo)); } ggLocalBrake.Update(); } @@ -9647,7 +9527,7 @@ bool TTrain::Update(double const Deltatime) ggWhistleButton.Update(); if (DynamicObject->Mechanik != nullptr) { - ggHelperButton.UpdateValue(DynamicObject->Mechanik->HelperState); + ggHelperButton.UpdateValue(static_cast(DynamicObject->Mechanik->HelperState)); } ggHelperButton.Update(); @@ -9737,12 +9617,9 @@ bool TTrain::Update(double const Deltatime) } // anti slip system activation, maintained while the control button is down - if (mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic) + if (mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) { - if (ggAntiSlipButton.GetDesiredValue() > 0.95) - { - mvControlled->AntiSlippingBrake(); - } + mvControlled->AntiSlippingBrake(); } // screens @@ -9798,22 +9675,22 @@ void TTrain::update_sounds(double const Deltatime) { // calculate rate of pressure drop in local brake cylinder, once it's been initialized auto const brakepressuredifference{mvOccupied->LocBrakePress - m_lastlocalbrakepressure}; - m_localbrakepressurechange = std::lerp(m_localbrakepressurechange, 10 * (brakepressuredifference / Deltatime), 0.1f); + m_localbrakepressurechange = static_cast(std::lerp(m_localbrakepressurechange, 10 * (brakepressuredifference / Deltatime), 0.1f)); } - m_lastlocalbrakepressure = mvOccupied->LocBrakePress; + m_lastlocalbrakepressure = static_cast(mvOccupied->LocBrakePress); // local brake, release if (rsSBHiss) { if (m_localbrakepressurechange < -0.05f && mvOccupied->LocBrakePress > mvOccupied->BrakePress - 0.05) { - rsSBHiss->gain(std::clamp(rsSBHiss->m_amplitudeoffset + rsSBHiss->m_amplitudefactor * -m_localbrakepressurechange * 0.05, 0.0, 1.5)); + rsSBHiss->gain(static_cast(std::clamp(rsSBHiss->m_amplitudeoffset + rsSBHiss->m_amplitudefactor * -m_localbrakepressurechange * 0.05, 0.0, 1.5))); rsSBHiss->play(sound_flags::exclusive | sound_flags::looping); } else { // don't stop the sound too abruptly volume = std::max(0.0, rsSBHiss->gain() - 0.1 * Deltatime); - rsSBHiss->gain(volume); + rsSBHiss->gain(static_cast(volume)); if (volume < 0.05) { rsSBHiss->stop(); @@ -9825,14 +9702,14 @@ void TTrain::update_sounds(double const Deltatime) { if (m_localbrakepressurechange > 0.05f) { - rsSBHissU->gain(std::clamp(rsSBHissU->m_amplitudeoffset + rsSBHissU->m_amplitudefactor * m_localbrakepressurechange * 0.05, 0.0, 1.5)); + rsSBHissU->gain(static_cast(std::clamp(rsSBHissU->m_amplitudeoffset + rsSBHissU->m_amplitudefactor * m_localbrakepressurechange * 0.05, 0.0, 1.5))); rsSBHissU->play(sound_flags::exclusive | sound_flags::looping); } else { // don't stop the sound too abruptly volume = std::max(0.0, rsSBHissU->gain() - 0.1 * Deltatime); - rsSBHissU->gain(volume); + rsSBHissU->gain(static_cast(volume)); if (volume < 0.05) { rsSBHissU->stop(); @@ -9851,7 +9728,7 @@ void TTrain::update_sounds(double const Deltatime) volume = fPPress > 0 ? rsHiss->m_amplitudefactor * fPPress * 0.25 + rsHiss->m_amplitudeoffset : 0; if (volume * brakevolumescale > 0.05) { - rsHiss->gain(volume * brakevolumescale); + rsHiss->gain(static_cast(volume * brakevolumescale)); rsHiss->play(sound_flags::exclusive | sound_flags::looping); } else @@ -9866,7 +9743,7 @@ void TTrain::update_sounds(double const Deltatime) volume = fNPress > 0 ? rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0; if (volume * brakevolumescale > 0.05) { - rsHissU->gain(volume * brakevolumescale); + rsHissU->gain(static_cast(volume * brakevolumescale)); rsHissU->play(sound_flags::exclusive | sound_flags::looping); } else @@ -9880,7 +9757,7 @@ void TTrain::update_sounds(double const Deltatime) volume = mvOccupied->Handle->GetSound(s_fv4a_e) * rsHissE->m_amplitudefactor + rsHissE->m_amplitudeoffset; if (volume * brakevolumescale > 0.05) { - rsHissE->gain(volume * brakevolumescale); + rsHissE->gain(static_cast(volume * brakevolumescale)); rsHissE->play(sound_flags::exclusive | sound_flags::looping); } else @@ -9894,7 +9771,7 @@ void TTrain::update_sounds(double const Deltatime) volume = mvOccupied->Handle->GetSound(s_fv4a_x) * rsHissX->m_amplitudefactor + rsHissX->m_amplitudeoffset; if (volume * brakevolumescale > 0.05) { - rsHissX->gain(volume * brakevolumescale); + rsHissX->gain(static_cast(volume * brakevolumescale)); rsHissX->play(sound_flags::exclusive | sound_flags::looping); } else @@ -9908,7 +9785,7 @@ void TTrain::update_sounds(double const Deltatime) volume = mvOccupied->Handle->GetSound(s_fv4a_t) * rsHissT->m_amplitudefactor + +rsHissT->m_amplitudeoffset; if (volume * brakevolumescale > 0.05) { - rsHissT->gain(volume * brakevolumescale); + rsHissT->gain(static_cast(volume * brakevolumescale)); rsHissT->play(sound_flags::exclusive | sound_flags::looping); } else @@ -9923,11 +9800,11 @@ void TTrain::update_sounds(double const Deltatime) // upuszczanie z PG if (rsHiss) { - fPPress = (4.0f * fPPress + std::max(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f); + fPPress = static_cast((4.0f * fPPress + std::max(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f)); volume = fPPress > 0.0f ? 2.0 * rsHiss->m_amplitudefactor * fPPress + rsHiss->m_amplitudeoffset : 0.0; if (volume > 0.05) { - rsHiss->gain(volume); + rsHiss->gain(static_cast(volume)); rsHiss->play(sound_flags::exclusive | sound_flags::looping); } else @@ -9938,11 +9815,11 @@ void TTrain::update_sounds(double const Deltatime) // napelnianie PG if (rsHissU) { - fNPress = (4.0f * fNPress + std::min(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f); + fNPress = static_cast((4.0f * fNPress + std::min(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f)); volume = fNPress < 0.0f ? -1.0 * rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0.0; if (volume > 0.01) { - rsHissU->gain(volume); + rsHissU->gain(static_cast(volume)); rsHissU->play(sound_flags::exclusive | sound_flags::looping); } else @@ -9962,8 +9839,8 @@ void TTrain::update_sounds(double const Deltatime) std::clamp(mvOccupied->UnitBrakeForce / std::max(1.0, mvOccupied->BrakeForceR(1.0, mvOccupied->Vel) / (mvOccupied->NAxles * std::max(1, mvOccupied->NBpA))), 0.0, 1.0)}; // HACK: in external view mute the sound rather than stop it, in case there's an opening bookend it'd (re)play on sound restart after returning inside volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, mvOccupied->Vel / (1 + mvOccupied->Vmax))) * rsBrake->m_amplitudefactor; - rsBrake->pitch(rsBrake->m_frequencyoffset + mvOccupied->Vel * rsBrake->m_frequencyfactor); - rsBrake->gain(volume); + rsBrake->pitch(static_cast(rsBrake->m_frequencyoffset + mvOccupied->Vel * rsBrake->m_frequencyfactor)); + rsBrake->gain(static_cast(volume)); rsBrake->play(sound_flags::exclusive | sound_flags::looping); } else @@ -10038,7 +9915,7 @@ void TTrain::update_sounds(double const Deltatime) auto const huntingamount = std::lerp( 0.0, 1.0, std::clamp((mvOccupied->Vel - DynamicObject->HuntingShake.fadein_begin) / (DynamicObject->HuntingShake.fadein_end - DynamicObject->HuntingShake.fadein_begin), 0.0, 1.0)); - rsHuntingNoise->gain(rsHuntingNoise->gain() * huntingamount); + rsHuntingNoise->gain(static_cast(rsHuntingNoise->gain() * huntingamount)); } else { @@ -10053,7 +9930,7 @@ void TTrain::update_sounds(double const Deltatime) { if (m_rainsound->is_combined()) { - m_rainsound->pitch(Global.Overcast - 1.0); + m_rainsound->pitch(static_cast(Global.Overcast - 1.0)); } m_rainsound->gain(m_rainsound->m_amplitudeoffset + m_rainsound->m_amplitudefactor * 1.f); m_rainsound->play(sound_flags::exclusive | sound_flags::looping); @@ -10068,8 +9945,8 @@ void TTrain::update_sounds(double const Deltatime) { if (fTachoCount >= 3.f) { - auto const frequency{(true == dsbHasler->is_combined() ? fTachoVelocity * 0.01 : dsbHasler->m_frequencyoffset + dsbHasler->m_frequencyfactor)}; - dsbHasler->pitch(frequency); + auto const soundfrequency{(true == dsbHasler->is_combined() ? fTachoVelocity * 0.01 : dsbHasler->m_frequencyoffset + dsbHasler->m_frequencyfactor)}; + dsbHasler->pitch(static_cast(soundfrequency)); dsbHasler->gain(dsbHasler->m_amplitudeoffset + dsbHasler->m_amplitudefactor); dsbHasler->play(sound_flags::exclusive | sound_flags::looping); } @@ -10143,23 +10020,18 @@ void TTrain::update_sounds(double const Deltatime) else { // stop power-reliant sounds if power is cut - if (dsbBuzzer) + if (dsbBuzzer && true == dsbBuzzer->is_playing()) { - if (true == dsbBuzzer->is_playing()) - { - dsbBuzzer->stop(); + dsbBuzzer->stop(); #ifdef _WIN32 - Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys + Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys #endif - } } if (dsbBuzzerShp && dsbBuzzerShp->is_playing()) { dsbBuzzerShp->stop(); } - { - } if (m_distancecounterclear) { @@ -10170,18 +10042,18 @@ void TTrain::update_sounds(double const Deltatime) update_sounds_radio(); } -void TTrain::update_sounds_resonancenoise(sound_source &Sound) +void TTrain::update_sounds_resonancenoise(sound_source &Sound) const { // frequency calculation auto const normalizer{mvOccupied->Vmax * 0.01f}; - auto const frequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; + auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; // volume calculation auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, 0.5); // scale base volume between 0.5-1.0 if (volume > 0.05) { - Sound.pitch(frequency).gain(volume).play(sound_flags::exclusive | sound_flags::looping); + Sound.pitch(static_cast(soundfrequency)).gain(static_cast(volume)).play(sound_flags::exclusive | sound_flags::looping); } else { @@ -10193,7 +10065,7 @@ void TTrain::update_sounds_runningnoise(sound_source &Sound) { // frequency calculation auto const normalizer{(true == Sound.is_combined() ? mvOccupied->Vmax * 0.01f : 1.f)}; - auto const frequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; + auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; // volume calculation auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, @@ -10216,7 +10088,7 @@ void TTrain::update_sounds_runningnoise(sound_source &Sound) if (volume > 0.05) { - Sound.pitch(frequency).gain(volume).play(sound_flags::exclusive | sound_flags::looping); + Sound.pitch(static_cast(soundfrequency)).gain(static_cast(volume)).play(sound_flags::exclusive | sound_flags::looping); } else { @@ -10231,16 +10103,15 @@ void TTrain::update_sounds_radio() if (false == m_radiomessages.empty()) { // erase completed radio messages from the list - m_radiomessages.erase(std::remove_if(std::begin(m_radiomessages), std::end(m_radiomessages), [](auto const &source) { return false == source.second->is_playing(); }), - std::end(m_radiomessages)); + std::erase_if(m_radiomessages, [](auto const &source) { return false == source.second->is_playing(); }); } // adjust audibility of remaining messages based on current radio conditions auto const radioenabled{true == mvOccupied->Radio && (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable)}; - for (auto &message : m_radiomessages) + for (auto const &[messagechannel, messagesound] : m_radiomessages) { - auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && message.first == RadioChannel() ? m_radiovolume : 0.0}; - message.second->gain(volume); - radio_message_played |= true == radioenabled && Dynamic()->Mechanik != nullptr && message.first == RadioChannel(); + auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel() ? m_radiovolume : 0.0}; + messagesound->gain(static_cast(volume)); + radio_message_played |= true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel(); } // radiostop if (m_radiostop) @@ -10289,7 +10160,7 @@ void TTrain::add_distance(double const Distance) if (true == meterenabled) { - m_distancecounter += Distance * Occupied()->CabOccupied; + m_distancecounter += static_cast(Distance * Occupied()->CabOccupied); } else { @@ -10310,15 +10181,12 @@ bool TTrain::CabChange(int iDirection) else { // jeśli pojazd prowadzony ręcznie albo wcale (wagon) mvOccupied->CabDeactivisationAuto(); - if (mvOccupied->ChangeCab(iDirection)) + if (mvOccupied->ChangeCab(iDirection) && InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd")) { - if (InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd")) - { - // zmiana kabiny w ramach tego samego pojazdu - mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) - DynamicObject->Mechanik->DirectionChange(); - return true; // udało się zmienić kabinę - } + // zmiana kabiny w ramach tego samego pojazdu + mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) + DynamicObject->Mechanik->DirectionChange(); + return true; // udało się zmienić kabinę } // aktywizacja poprzedniej, bo jeszcze nie wiadomo, czy jakiś pojazd jest mvOccupied->CabActivisationAuto(); @@ -10330,37 +10198,39 @@ bool TTrain::CabChange(int iDirection) // wczytywanie pliku z danymi multimedialnymi (dzwieki, kontrolki, kabiny) bool TTrain::LoadMMediaFile(std::string const &asFileName) { + using enum sound_placement; + using enum sound_type; // initialize sounds so potential entries from previous vehicle don't stick around std::unordered_map &, sound_placement, float, sound_type, int, double>> internalsounds = { - {"ctrl:", {dsbNastawnikJazdy, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"ctrlscnd:", {dsbNastawnikBocz, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"reverserkey:", {dsbReverserKey, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"buzzer:", {dsbBuzzer, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"buzzershp:", {dsbBuzzerShp, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"radiostop:", {m_radiostop, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"slipalarm:", {dsbSlipAlarm, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"distancecounter:", {m_distancecounterclear, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"tachoclock:", {dsbHasler, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"switch:", {dsbSwitch, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"pneumaticswitch:", {dsbPneumaticSwitch, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"airsound:", {rsHiss, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, sound_parameters::amplitude, 100.0}}, - {"airsound2:", {rsHissU, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, sound_parameters::amplitude, 100.0}}, - {"airsound3:", {rsHissE, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, sound_parameters::amplitude, 100.0}}, - {"airsound4:", {rsHissX, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, sound_parameters::amplitude, 100.0}}, - {"airsound5:", {rsHissT, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, sound_parameters::amplitude, 100.0}}, - {"localbrakesound:", {rsSBHiss, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, sound_parameters::amplitude, 100.0}}, - {"localbrakesound2:", {rsSBHissU, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, sound_parameters::amplitude, 100.0}}, - {"brakesound:", {rsBrake, sound_placement::internal, -1, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, 100.0}}, - {"fadesound:", {rsFadeSound, sound_placement::internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, sound_type::single, 0, 100.0}}, - {"runningnoise:", {rsRunningNoise, sound_placement::internal, EU07_SOUND_GLOBALRANGE, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"resonancenoise:", {rsResonanceNoise, sound_placement::internal, EU07_SOUND_GLOBALRANGE, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"windsound:", {rsWindSound, sound_placement::internal, EU07_SOUND_GLOBALRANGE, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"huntingnoise:", {rsHuntingNoise, sound_placement::internal, EU07_SOUND_GLOBALRANGE, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"rainsound:", {m_rainsound, sound_placement::internal, -1, sound_type::single, 0, 100.0}}, + {"ctrl:", {dsbNastawnikJazdy, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"ctrlscnd:", {dsbNastawnikBocz, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"reverserkey:", {dsbReverserKey, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"buzzer:", {dsbBuzzer, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"buzzershp:", {dsbBuzzerShp, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"radiostop:", {m_radiostop, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"slipalarm:", {dsbSlipAlarm, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"distancecounter:", {m_distancecounterclear, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"tachoclock:", {dsbHasler, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"switch:", {dsbSwitch, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"pneumaticswitch:", {dsbPneumaticSwitch, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"airsound:", {rsHiss, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound2:", {rsHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound3:", {rsHissE, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound4:", {rsHissX, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound5:", {rsHissT, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"localbrakesound:", {rsSBHiss, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"localbrakesound2:", {rsSBHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"brakesound:", {rsBrake, internal, -1, single, sound_parameters::amplitude | sound_parameters::frequency, 100.0}}, + {"fadesound:", {rsFadeSound, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"runningnoise:", {rsRunningNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, + {"resonancenoise:", {rsResonanceNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, + {"windsound:", {rsWindSound, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, + {"huntingnoise:", {rsHuntingNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, + {"rainsound:", {m_rainsound, internal, -1, single, 0, 100.0}}, }; - for (auto &soundconfig : internalsounds) + for (auto &[soundname, soundsource] : internalsounds) { - std::get &>(soundconfig.second).reset(); + std::get &>(soundsource).reset(); } // NOTE: since radiosound is an incomplete template not using std::optional it gets a special treatment m_radiosound.owner(DynamicObject); @@ -10394,7 +10264,7 @@ bool TTrain::LoadMMediaFile(std::string const &asFileName) auto const soundconfig{lookup->second}; sound_source sound{std::get(soundconfig), std::get(soundconfig)}; - sound.deserialize(parser, std::get(soundconfig), std::get(soundconfig), std::get(soundconfig)); + sound.deserialize(parser, std::get(soundconfig), std::get(soundconfig), static_cast(std::get(soundconfig))); sound.owner(DynamicObject); std::get &>(soundconfig) = sound; } while (token != ""); @@ -10403,7 +10273,7 @@ bool TTrain::LoadMMediaFile(std::string const &asFileName) if (!m_rainsound) { sound_source rainsound; - rainsound.deserialize("rainsound_default", sound_type::single); + rainsound.deserialize("rainsound_default", single); rainsound.owner(DynamicObject); m_rainsound = rainsound; } @@ -10419,26 +10289,25 @@ bool TTrain::LoadMMediaFile(std::string const &asFileName) } if (rsBrake) { - rsBrake->m_frequencyfactor /= 1 + mvOccupied->Vmax; + rsBrake->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); } if (rsResonanceNoise) { - rsResonanceNoise->m_frequencyfactor /= 1 + mvOccupied->Vmax; + rsResonanceNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); } if (rsWindSound) { - rsWindSound->m_frequencyfactor /= 1 + mvOccupied->Vmax; + rsWindSound->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); } if (rsRunningNoise) { - rsRunningNoise->m_frequencyfactor /= 1 + mvOccupied->Vmax; + rsRunningNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); } if (rsHuntingNoise) { - rsHuntingNoise->m_frequencyfactor /= 1 + mvOccupied->Vmax; + rsHuntingNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); } } - auto const nullvector{glm::vec3()}; std::vector>> sounds = { dsbReverserKey, dsbNastawnikJazdy, dsbNastawnikBocz, dsbSwitch, dsbPneumaticSwitch, rsHiss, rsHissU, rsHissE, rsHissX, rsHissT, rsSBHiss, rsSBHissU, rsFadeSound, rsRunningNoise, rsResonanceNoise, rsWindSound, rsHuntingNoise, dsbHasler, dsbBuzzer, dsbBuzzerShp, dsbSlipAlarm, m_distancecounterclear, @@ -10465,7 +10334,7 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) dsbReverserKey, dsbNastawnikJazdy, dsbNastawnikBocz, dsbSwitch, dsbPneumaticSwitch, rsHiss, rsHissU, rsHissE, rsHissX, rsHissT, rsSBHiss, rsSBHissU, rsFadeSound, rsRunningNoise, rsResonanceNoise, rsWindSound, rsHuntingNoise, dsbHasler, dsbBuzzer, dsbBuzzerShp, dsbSlipAlarm, m_distancecounterclear, m_rainsound, m_radiostop}; - for (auto &sound : sounds) + for (auto const &sound : sounds) { if (sound.get()) { @@ -10473,11 +10342,11 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) } } m_radiosound.offset(nullvector); - for (auto &sound : CabSoundLocations) + for (auto const &[soundsource, soundoffset] : CabSoundLocations) { - if (sound.first.get() && sound.first.get()->offset() == nullvector) + if (soundsource.get() && soundsource.get()->offset() == nullvector) { - sound.first.get()->offset(sound.second); + soundsource.get()->offset(soundoffset); } } // reset view angles @@ -10499,6 +10368,8 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) case 0: cabindex = 0; break; + default: + break; } iCabn = cabindex; @@ -10583,7 +10454,7 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) // model kabiny parser.getTokens(); parser >> token; - std::replace(token.begin(), token.end(), '\\', '/'); + std::ranges::replace(token, '\\', '/'); if (token != "none") { // bieżąca sciezka do tekstur to dynamic/... @@ -10766,19 +10637,19 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) {m_rainsound, caboffset}, {m_radiostop, m_radiosound.offset()}, }; - for (auto &sound : soundlocations) + for (auto const &[soundsource, soundoffset] : soundlocations) { - if (sound.first.get() && sound.first.get()->offset() == nullvector) + if (soundsource.get() && soundsource.get()->offset() == nullvector) { - sound.first.get()->offset(sound.second); + soundsource.get()->offset(soundoffset); } } // second pass, in case some items received no positioning due to missing submodels etc - for (auto &sound : soundlocations) + for (auto const &[soundsource, soundoffset] : soundlocations) { - if (sound.first.get() && sound.first.get()->offset() == nullvector) + if (soundsource.get() && soundsource.get()->offset() == nullvector) { - sound.first.get()->offset(caboffset); + soundsource.get()->offset(caboffset); } } @@ -10822,7 +10693,8 @@ void TTrain::DynamicSet(TDynamicObject *d) // jeździć dobrze // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... DynamicObject = d; // jedyne miejsce zmiany - mvOccupied = mvControlled = d ? DynamicObject->MoverParameters : nullptr; // albo silnikowy w EZT + mvControlled = d ? DynamicObject->MoverParameters : nullptr; // albo silnikowy w EZT + mvOccupied = mvControlled; if (DynamicObject == nullptr) { @@ -10832,18 +10704,20 @@ void TTrain::DynamicSet(TDynamicObject *d) mvControlled = DynamicObject->FindPowered()->MoverParameters; mvSecond = nullptr; // gdyby się nic nie znalazło if (mvOccupied->Power > 1.0) // dwuczłonowe lub ukrotnienia, żeby nie szukać każdorazowo + { if (mvOccupied->Couplers[1].Connected ? mvOccupied->Couplers[1].AllowedFlag & coupling::control : false) { // gdy jest człon od sprzęgu 1, a sprzęg łączony // warsztatowo (powiedzmy) if (mvOccupied->Couplers[1].Connected->Power > 1.0) // ten drugi ma moc - mvSecond = (TMoverParameters *)mvOccupied->Couplers[1].Connected; // wskaźnik na drugiego + mvSecond = mvOccupied->Couplers[1].Connected; // wskaźnik na drugiego } else if (mvOccupied->Couplers[0].Connected ? mvOccupied->Couplers[0].AllowedFlag & coupling::control : false) { // gdy jest człon od sprzęgu 0, a sprzęg łączony // warsztatowo (powiedzmy) if (mvOccupied->Couplers[0].Connected->Power > 1.0) // ale ten drugi ma moc - mvSecond = (TMoverParameters *)mvOccupied->Couplers[0].Connected; // wskaźnik na drugiego + mvSecond = mvOccupied->Couplers[0].Connected; // wskaźnik na drugiego } + } // cache nearest unit equipped with pantographs { auto *lookup{DynamicObject->FindPantographCarrier()}; @@ -11010,8 +10884,7 @@ const TTrain::screenentry_sequence &TTrain::get_screens() void TTrain::radio_message(sound_source *Message, int const Channel) { - auto const soundrange{Message->range()}; - if (soundrange > 0 && glm::length2(Message->location() - glm::dvec3{DynamicObject->GetPosition()}) > sq(soundrange)) + if (auto const soundrange{Message->range()}; soundrange > 0 && glm::length2(Message->location() - glm::dvec3{DynamicObject->GetPosition()}) > sq(soundrange)) { // skip message playback if the receiver is outside of the emitter's range return; @@ -11022,7 +10895,7 @@ void TTrain::radio_message(sound_source *Message, int const Channel) auto &message = *m_radiomessages.back().second.get(); auto const radioenabled{true == mvOccupied->Radio && (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable)}; auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && Channel == RadioChannel() ? 1.0 : 0.0}; - message.copy_sounds(*Message).gain(volume).play(); + message.copy_sounds(*Message).gain(static_cast(volume)).play(); } // clears state of all cabin controls @@ -11330,7 +11203,7 @@ void TTrain::set_cab_controls(int const Cab) if (ggModernLightDimSw.SubModel != nullptr) { mvOccupied->modernDimmerPosition = mvOccupied->modernDimmerDefaultPosition; - ggModernLightDimSw.PutValue(mvOccupied->modernDimmerDefaultPosition); + ggModernLightDimSw.PutValue(static_cast(mvOccupied->modernDimmerDefaultPosition)); } // Init separate buttons @@ -11346,7 +11219,7 @@ void TTrain::set_cab_controls(int const Cab) // motor connectors ggStLinOffButton.PutValue(mvControlled->StLinSwitchOff ? 1.f : 0.f); // radio - ggRadioChannelSelector.PutValue((Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1) - 1); + ggRadioChannelSelector.PutValue(static_cast((Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1) - 1)); // pantographs /* if( mvOccupied->PantSwitchType != "impulse" ) { @@ -11411,11 +11284,11 @@ void TTrain::set_cab_controls(int const Cab) // compressor ggCompressorButton.PutValue(mvControlled->CompressorAllow ? 1.f : 0.f); ggCompressorLocalButton.PutValue(mvControlled->CompressorAllowLocal ? 1.f : 0.f); - ggCompressorListButton.PutValue(mvOccupied->CompressorListPos - 1); + ggCompressorListButton.PutValue(static_cast(mvOccupied->CompressorListPos - 1)); // motor overload relay threshold / shunt mode ggMaxCurrentCtrl.PutValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); // lights - ggLightsButton.PutValue(mvOccupied->LightsPos - 1); + ggLightsButton.PutValue(static_cast(mvOccupied->LightsPos - 1)); auto const vehicleend{cab_to_end(Cab)}; @@ -11455,7 +11328,7 @@ void TTrain::set_cab_controls(int const Cab) } if (1 == DynamicObject->MoverParameters->modernDimmerPosition) { - ggDimHeadlightsButton.PutValue(DynamicObject->MoverParameters->modernDimmerPosition); + ggDimHeadlightsButton.PutValue(static_cast(DynamicObject->MoverParameters->modernDimmerPosition)); } // cab lights if (true == Cabine[Cab].bLightDim) @@ -11471,16 +11344,16 @@ void TTrain::set_cab_controls(int const Cab) // doors permits if (false == ggDoorLeftPermitButton.is_push()) { - ggDoorLeftPermitButton.PutValue(mvOccupied->Doors.instances[(cab_to_end() == end::front ? side::left : side::right)].open_permit ? 1.f : 0.f); + ggDoorLeftPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].open_permit ? 1.f : 0.f); } if (false == ggDoorRightPermitButton.is_push()) { - ggDoorRightPermitButton.PutValue(mvOccupied->Doors.instances[(cab_to_end() == end::front ? side::right : side::left)].open_permit ? 1.f : 0.f); + ggDoorRightPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].open_permit ? 1.f : 0.f); } - ggDoorPermitPresetButton.PutValue(mvOccupied->Doors.permit_preset); + ggDoorPermitPresetButton.PutValue(static_cast(mvOccupied->Doors.permit_preset)); // door controls - ggDoorLeftButton.PutValue(mvOccupied->Doors.instances[(cab_to_end() == end::front ? side::left : side::right)].is_closed ? 0.f : 1.f); - ggDoorRightButton.PutValue(mvOccupied->Doors.instances[(cab_to_end() == end::front ? side::right : side::left)].is_closed ? 0.f : 1.f); + ggDoorLeftButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].is_closed ? 0.f : 1.f); + ggDoorRightButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].is_closed ? 0.f : 1.f); // door lock ggDoorSignallingButton.PutValue(mvOccupied->Doors.lock_enabled ? 1.f : 0.f); // door step @@ -11496,7 +11369,7 @@ void TTrain::set_cab_controls(int const Cab) // brake acting time if (ggBrakeProfileCtrl.SubModel != nullptr) { - ggBrakeProfileCtrl.PutValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.f : mvOccupied->BrakeDelayFlag - 1); + ggBrakeProfileCtrl.PutValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.f : static_cast(mvOccupied->BrakeDelayFlag - 1)); } if (ggBrakeProfileG.SubModel != nullptr) { @@ -11509,12 +11382,12 @@ void TTrain::set_cab_controls(int const Cab) if (ggWiperSw.SubModel != nullptr) { - ggWiperSw.PutValue(mvOccupied->wiperSwitchPos); + ggWiperSw.PutValue(static_cast(mvOccupied->wiperSwitchPos)); } if (ggBrakeOperationModeCtrl.SubModel != nullptr) { - ggBrakeOperationModeCtrl.PutValue(mvOccupied->BrakeOpModeFlag > 0 ? std::log2(mvOccupied->BrakeOpModeFlag) : 0); + ggBrakeOperationModeCtrl.PutValue(mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(mvOccupied->BrakeOpModeFlag)) : 0); } // alarm chain ggAlarmChain.PutValue(mvControlled->AlarmChainFlag ? 1.f : 0.f); @@ -11578,7 +11451,7 @@ void TTrain::set_cab_controls(int const Cab) bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; int flag = DynamicObject->MoverParameters->InverterControlCouplerFlag; int itemstart = 0; - for (auto &item : ggInverterToggleButtons) // for each button + for ([[maybe_unused]] auto const &item : ggInverterToggleButtons) // for each button { int itemindex = itemstart; itemstart++; @@ -12147,7 +12020,8 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con else if (Label == "eimscreen:") { // amperomierz calkowitego pradu - int i, j; + int i; + int j; Parser.getTokens(2, false); Parser >> i >> j; auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka @@ -12157,7 +12031,8 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con else if (Label == "brakes:") { // specified pipe pressure of specified consist vehicle - int i, j; + int i; + int j; Parser.getTokens(2, false); Parser >> i >> j; auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka @@ -12281,15 +12156,12 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con else if (Label == "clock:") { // zegar analogowy - if (Parser.getToken() == "analog") + if (Parser.getToken() == "analog" && DynamicObject->mdKabina) { - if (DynamicObject->mdKabina) - { - // McZapkie-300302: zegarek - ggClockSInd.Init(DynamicObject->mdKabina->GetFromName("ClockShand"), nullptr, TGaugeAnimation::gt_Rotate, 1.0 / 60.0); - ggClockMInd.Init(DynamicObject->mdKabina->GetFromName("ClockMhand"), nullptr, TGaugeAnimation::gt_Rotate, 1.0 / 60.0); - ggClockHInd.Init(DynamicObject->mdKabina->GetFromName("ClockHhand"), nullptr, TGaugeAnimation::gt_Rotate, 1.0 / 12.0); - } + // McZapkie-300302: zegarek + ggClockSInd.Init(DynamicObject->mdKabina->GetFromName("ClockShand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 60.0)); + ggClockMInd.Init(DynamicObject->mdKabina->GetFromName("ClockMhand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 60.0)); + ggClockHInd.Init(DynamicObject->mdKabina->GetFromName("ClockHhand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 12.0)); } } else if (Label == "clock_seconds:") diff --git a/vehicle/Train.h b/vehicle/Train.h index 7627bbf8..4fc11dc2 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -59,7 +59,7 @@ private: }; class control_mapper { - typedef std::unordered_map< TSubModel const *, std::string> submodelstring_map; + using submodelstring_map = std::unordered_map< TSubModel const *, std::string>; submodelstring_map m_controlnames; using stringset = std::unordered_set; stringset m_names; // names of registered controls @@ -71,7 +71,7 @@ public: std::string find( TSubModel const *Control ) const; bool - contains( std::string const Control ) const; + contains( std::string const &Control ) const; }; class TTrain { @@ -142,11 +142,11 @@ class TTrain { bool deserialize_mapping( cParser &Input ); }; - typedef std::vector screenentry_sequence; + using screenentry_sequence = std::vector; // methods bool CabChange(int iDirection); - bool ShowNextCurrent; // pokaz przd w podlaczonej lokomotywie (ET41) + bool ShowNextCurrent{false}; // pokaz przd w podlaczonej lokomotywie (ET41) bool InitializeCab(int NewCabNo, std::string const &asFileName); TTrain(); ~TTrain(); @@ -181,8 +181,8 @@ class TTrain { private: // types - typedef void( *command_handler )( TTrain *Train, command_data const &Command ); - typedef std::unordered_map commandhandler_map; + using command_handler = void (*)( TTrain *Train, command_data const &Command ); + using commandhandler_map = std::unordered_map; // methods // clears state of all cabin controls void clear_cab_controls(); @@ -214,7 +214,7 @@ class TTrain { // update function subroutines void update_sounds( double const Deltatime ); void update_sounds_runningnoise( sound_source &Sound ); - void update_sounds_resonancenoise( sound_source &Sound ); + void update_sounds_resonancenoise( sound_source &Sound ) const; void update_sounds_radio(); inline end cab_to_end( int const End ) const { @@ -817,31 +817,31 @@ public: // reszta może by?publiczna TButton btHaslerBrakes; // ciśnienie w cylindrach TButton btHaslerCurrent; // prąd na silnikach - std::optional - dsbNastawnikJazdy, - dsbNastawnikBocz, - dsbReverserKey, - dsbBuzzer, dsbBuzzerShp, - m_radiostop, - dsbSlipAlarm, - m_distancecounterclear, - dsbHasler, - dsbSwitch, - dsbPneumaticSwitch, - rsHiss, - rsHissU, - rsHissE, - rsHissX, - rsHissT, - rsSBHiss, - rsSBHissU, - rsBrake, - rsFadeSound, - rsRunningNoise, - rsResonanceNoise, - rsWindSound, - rsHuntingNoise, - m_rainsound; + std::optional dsbNastawnikJazdy; + std::optional dsbNastawnikBocz; + std::optional dsbReverserKey; + std::optional dsbBuzzer; + std::optional dsbBuzzerShp; + std::optional m_radiostop; + std::optional dsbSlipAlarm; + std::optional m_distancecounterclear; + std::optional dsbHasler; + std::optional dsbSwitch; + std::optional dsbPneumaticSwitch; + std::optional rsHiss; + std::optional rsHissU; + std::optional rsHissE; + std::optional rsHissX; + std::optional rsHissT; + std::optional rsSBHiss; + std::optional rsSBHissU; + std::optional rsBrake; + std::optional rsFadeSound; + std::optional rsRunningNoise; + std::optional rsResonanceNoise; + std::optional rsWindSound; + std::optional rsHuntingNoise; + std::optional m_rainsound; sound_source m_radiosound { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // cached template for radio messages std::vector>> m_radiomessages; // list of currently played radio messages std::vector>, glm::vec3>> CabSoundLocations; // list of offsets for manually located sounds; @@ -857,14 +857,14 @@ public: // reszta może by?publiczna int iCabn { 0 }; // 0: mid, 1: front, 2: rear bool is_cab_initialized { false }; // McZapkie: do poruszania sie po kabinie - glm::dvec3 pMechSittingPosition; // ABu 180404 + glm::dvec3 pMechSittingPosition{0.0}; // ABu 180404 glm::dvec3 MirrorPosition(bool lewe); - glm::dvec3 pMechOffset; // base position of the driver in the cab + glm::dvec3 pMechOffset{0.0}; // base position of the driver in the cab glm::vec2 pMechViewAngle { 0.0, 0.0 }; // camera pitch and yaw values, preserved while in external view private: - double fBlinkTimer; - float fHaslerTimer; + double fBlinkTimer{0.0}; + float fHaslerTimer{0.0f}; float fConverterTimer; // hunter-261211: dla przekaznika float fMainRelayTimer; // hunter-141211: zalaczanie WSa z opoznieniem float fBatteryTimer = {-1.f}; // Hirek: zalaczanie baterii z opoznieniem (tylko gdy zdefiniowano takie zachowanie w fiz) @@ -879,7 +879,9 @@ private: float fHVoltage{ 0.0f }; // napi?cie dla dynamicznych ga?ek float fHCurrent[ 4 ] = { 0.0f, 0.0f, 0.0f, 0.0f }; // pr?dy: suma i amperomierze 1,2,3 float fEngine[ 4 ] = { 0.0f, 0.0f, 0.0f, 0.0f }; // obroty te? trzeba pobra? - int iCarNo, iPowerNo, iUnitNo; // liczba pojazdow, czlonow napednych i jednostek spiętych ze sobą + int iCarNo; + int iPowerNo; + int iUnitNo; // liczba pojazdow, czlonow napednych i jednostek spiętych ze sobą bool bDoors[20][5]; // drzwi dla wszystkich czlonow; left+right, left, right, step_left, step_right int iUnits[20]; // numer jednostki int iDoorNo[20]; // liczba drzwi @@ -896,7 +898,8 @@ private: std::vector> bCompressors; bool bHeat[8]; // grzanie // McZapkie: do syczenia - float fPPress, fNPress; + float fPPress{0.0f}; + float fNPress{0.0f}; bool m_mastercontrollerinuse { false }; float m_mastercontrollerreturndelay { 0.f }; screenentry_sequence m_screens; @@ -926,7 +929,7 @@ private: // plays provided sound from position of the radio bool radio_message_played; void radio_message( sound_source *Message, int const Channel ); - inline auto const RadioChannel() const { return Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1; } + inline auto RadioChannel() const { return Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1; } inline auto &RadioChannel() { return Dynamic()->Mechanik->iRadioChannel; } inline TDynamicObject *Dynamic() { return DynamicObject; }; inline TDynamicObject const *Dynamic() const { return DynamicObject; }; diff --git a/vr/vr_interface.cpp b/vr/vr_interface.cpp index 9f9ff4e4..c46bce56 100644 --- a/vr/vr_interface.cpp +++ b/vr/vr_interface.cpp @@ -12,8 +12,7 @@ bool vr_interface_factory::register_backend(const std::string &backend, vr_inter std::unique_ptr vr_interface_factory::create(const std::string &backend) { - auto it = backends.find(backend); - if (it != backends.end()) + if (auto it = backends.find(backend); it != backends.end()) return it->second(); ErrorLog("vr backend \"" + backend + "\" not found!"); diff --git a/widgets/cameraview_extcam.cpp b/widgets/cameraview_extcam.cpp index 80deddbe..0b7c1c41 100644 --- a/widgets/cameraview_extcam.cpp +++ b/widgets/cameraview_extcam.cpp @@ -62,8 +62,7 @@ void ui::cameraview_panel::render() ImGui::SetNextWindowSizeConstraints(ImVec2(200, 200), ImVec2(2500, 2500), cameraview_window_callback); - auto const panelname{(title.empty() ? m_name : title) + "###" + m_name}; - if (ImGui::Begin(panelname.c_str(), &is_open)) { + if (auto const panelname{(title.empty() ? m_name : title) + "###" + m_name}; ImGui::Begin(panelname.c_str(), &is_open)) { render_contents(); } @@ -90,7 +89,7 @@ void ui::cameraview_panel::render_contents() texture->bind(0); { - std::lock_guard lock(mutex); + std::scoped_lock lock(mutex); if (image_ptr) { glActiveTexture(GL_TEXTURE0); @@ -123,8 +122,8 @@ void ui::cameraview_panel::capture_func() piped_proc proc(cmdline); size_t frame_size = Global.extcam_res.x * Global.extcam_res.y * 3; - uint8_t *read_buffer = new uint8_t[frame_size]; - uint8_t *active_buffer = new uint8_t[frame_size]; + auto read_buffer = new uint8_t[frame_size]; + auto active_buffer = new uint8_t[frame_size]; size_t bufpos = 0; @@ -142,7 +141,7 @@ void ui::cameraview_panel::capture_func() bufpos = 0; - std::lock_guard lock(mutex); + std::scoped_lock lock(mutex); image_ptr = read_buffer; read_buffer = active_buffer; active_buffer = image_ptr; @@ -151,7 +150,7 @@ void ui::cameraview_panel::capture_func() notify_var.notify_one(); } - std::lock_guard lock(mutex); + std::scoped_lock lock(mutex); image_ptr = nullptr; delete[] read_buffer; delete[] active_buffer; @@ -165,15 +164,15 @@ void ui::cameraview_panel::record_func() if (!rec_name.empty()) { const std::string magic{"{RECORD}"}; - size_t pos = cmdline.find(magic); - if (pos != -1) - cmdline.replace(pos, magic.size(), rec_name); + size_t magicpos = cmdline.find(magic); + if (magicpos != -1) + cmdline.replace(magicpos, magic.size(), rec_name); } piped_proc proc(cmdline, true); size_t frame_size = Global.extcam_res.x * Global.extcam_res.y * 3; - uint8_t *read_buffer = new uint8_t[frame_size]; + auto read_buffer = new uint8_t[frame_size]; uint32_t last_cnt = 0; size_t bufpos = frame_size; @@ -181,7 +180,7 @@ void ui::cameraview_panel::record_func() while (record_state == RUNNING) { if (bufpos == frame_size) { - std::unique_lock lock(mutex); + std::unique_lock lock(mutex); auto r = notify_var.wait_for(lock, std::chrono::milliseconds(50), [this, last_cnt]{return last_cnt != frame_cnt;}); last_cnt = frame_cnt; if (!image_ptr || !r) diff --git a/widgets/map_objects.cpp b/widgets/map_objects.cpp index d67c73f5..af5bd2bc 100644 --- a/widgets/map_objects.cpp +++ b/widgets/map_objects.cpp @@ -5,7 +5,7 @@ map::objects map::Objects; -map::sorted_object_list map::objects::find_in_range(glm::vec3 from, float distance) +map::sorted_object_list map::objects::find_in_range(glm::vec3 from, float distance) const { sorted_object_list items; @@ -25,7 +25,7 @@ map::sorted_object_list map::objects::find_in_range(glm::vec3 from, float distan float dist = glm::distance2(entry_location, search_point); if (dist < max_distance2) { - items.emplace(dist, entry); + items.try_emplace(dist, entry); } } @@ -48,7 +48,7 @@ map::sorted_object_list map::objects::find_in_range(glm::vec3 from, float distan auto entry = std::make_shared(); entry->dynobj = dynobj; entry->name = dynobj->name(); - items.emplace(dist, std::move(entry)); + items.try_emplace(dist, std::move(entry)); } } diff --git a/widgets/map_objects.h b/widgets/map_objects.h index f5d07ebf..3754a146 100644 --- a/widgets/map_objects.h +++ b/widgets/map_objects.h @@ -29,7 +29,7 @@ struct semaphore : public map_object std::vector events; TMemCell *memcell = nullptr; - virtual gfx::basic_vertex vertex() override { + gfx::basic_vertex vertex() override { bool stop_signal = memcell->IsVelocity() && (memcell->Value1() == 0.0); return gfx::basic_vertex(location, glm::vec3(), (!stop_signal) ? glm::vec2(0.0f, 0.2f) : glm::vec2(0.2f, 0.4f)); @@ -45,9 +45,10 @@ struct launcher : public map_object enum type_e { track_switch, level_crossing - } type; + }; + type_e type; - virtual gfx::basic_vertex vertex() { + gfx::basic_vertex vertex() override { return gfx::basic_vertex(location, glm::vec3(), type == track_switch ? glm::vec2(0.4f, 0.6f) : glm::vec2(0.6f, 0.8f)); } @@ -60,7 +61,7 @@ struct track_switch : public map_object std::array preview; std::array track = { nullptr }; - virtual gfx::basic_vertex vertex() { + gfx::basic_vertex vertex() override { return gfx::basic_vertex(location, glm::vec3(), glm::vec2(0.4f, 0.6f)); } }; @@ -70,7 +71,7 @@ struct obstacle : public map_object { std::string model_name; - virtual gfx::basic_vertex vertex() { + gfx::basic_vertex vertex() override { return gfx::basic_vertex(location, glm::vec3(), glm::vec2(0.8f, 1.0f)); } }; @@ -87,7 +88,7 @@ struct objects bool poi_dirty = true; // returns objects in range from vec3, NaN in Y ignores it - sorted_object_list find_in_range(glm::vec3 from, float distance); + sorted_object_list find_in_range(glm::vec3 from, float distance) const; }; extern objects Objects; diff --git a/widgets/perfgraphs.cpp b/widgets/perfgraphs.cpp index 574cc7ef..041a2513 100644 --- a/widgets/perfgraphs.cpp +++ b/widgets/perfgraphs.cpp @@ -19,7 +19,7 @@ void perfgraph_panel::render_contents() { ImGui::EndCombo(); } - Timer::stopwatch *stopwatch = nullptr; + Timer::stopwatch const *stopwatch = nullptr; if (current_timer == gfx_total) stopwatch = &Timer::subsystem.gfx_total; @@ -49,7 +49,7 @@ void perfgraph_panel::render_contents() { if (!stopwatch) return; - history[pos] = stopwatch->last().count() / 1000.0; + history[pos] = static_cast(static_cast(stopwatch->last().count()) / 1000.0); const std::string label = std::to_string(history[pos]) + "ms"; pos++; @@ -57,5 +57,5 @@ void perfgraph_panel::render_contents() { pos = 0; ImGui::SliderFloat(STR_C("Range"), &max, 0.1f, 250.0f); - ImGui::PlotLines("##timer", &history[0], history.size(), pos, label.c_str(), 0.0f, max, ImVec2(500, 200)); + ImGui::PlotLines("##timer", &history[0], static_cast(history.size()), static_cast(pos), label.c_str(), 0.0f, max, ImVec2(500, 200)); } diff --git a/widgets/popup.cpp b/widgets/popup.cpp index 75633c38..64f7a634 100644 --- a/widgets/popup.cpp +++ b/widgets/popup.cpp @@ -3,7 +3,7 @@ ui::popup::popup(ui_panel &panel) : m_parent(panel) {} -ui::popup::~popup() {} +ui::popup::~popup() = default; bool ui::popup::render() { diff --git a/widgets/popup.h b/widgets/popup.h index 82c3f258..d91b9f8b 100644 --- a/widgets/popup.h +++ b/widgets/popup.h @@ -11,7 +11,7 @@ class popup static int id; public: - popup(ui_panel &panel); + explicit popup(ui_panel &panel); virtual ~popup(); virtual bool render(); diff --git a/widgets/time.cpp b/widgets/time.cpp index d299d17b..6cf89b62 100644 --- a/widgets/time.cpp +++ b/widgets/time.cpp @@ -18,15 +18,16 @@ void ui::time_panel::render_contents() if (ImGui::Button(STR_C("Apply"))) { - m_relay.post(user_command::setdatetime, (double)yearday, time * 60.0, 1, 0); - m_relay.post(user_command::setweather, fog, overcast, 1, 0); - m_relay.post(user_command::settemperature, temperature, overcast, 1, 0); + using enum user_command; + m_relay.post(setdatetime, (double)yearday, time * 60.0, 1, 0); + m_relay.post(setweather, fog, overcast, 1, 0); + m_relay.post(settemperature, temperature, overcast, 1, 0); } } void ui::time_panel::open() { - auto &data = simulation::Time.data(); + auto const &data = simulation::Time.data(); time = (float)data.wHour + (float)data.wMinute / 60.0f; yearday = simulation::Time.year_day(); diff --git a/widgets/trainingcard.cpp b/widgets/trainingcard.cpp index 27fb0965..b261a5d4 100644 --- a/widgets/trainingcard.cpp +++ b/widgets/trainingcard.cpp @@ -63,16 +63,16 @@ void trainingcard_panel::save_thread_func() if (in_line.compare(0, magic.size(), magic) == 0) { temp << "
Miejsce: " << (std::string(place.c_str())) << "

" << std::endl; - temp << "
Data: " << (date) << "

" << std::endl; - temp << "
Czas: " << (from) << " - " << (to) << "

" << std::endl; - temp << "
Imię (imiona) i nazwisko szkolonego: " << (trainee_name) << "

" << std::endl; - temp << "
Data urodzenia: " << (trainee_birthdate) << "

" << std::endl; - temp << "
Firma: " << (trainee_company) << "

" << std::endl; - temp << "
Imię i nazwisko instruktora: " << (instructor_name) << "

" << std::endl; - temp << "
Odcinek trasy: " << (track_segment) << "

" << std::endl; + temp << "
Data: " << date << "

" << std::endl; + temp << "
Czas: " << from << " - " << to << "

" << std::endl; + temp << "
Imię (imiona) i nazwisko szkolonego: " << trainee_name << "

" << std::endl; + temp << "
Data urodzenia: " << trainee_birthdate << "

" << std::endl; + temp << "
Firma: " << trainee_company << "

" << std::endl; + temp << "
Imię i nazwisko instruktora: " << instructor_name << "

" << std::endl; + temp << "
Odcinek trasy: " << track_segment << "

" << std::endl; if (distance > 0.0f) temp << "
Przebyta odległość: " << std::round(distance) << " km

" << std::endl; - temp << "
Uwagi:
" << (remarks) << "
" << std::endl; + temp << "
Uwagi:
" << remarks << "
" << std::endl; } else { @@ -119,7 +119,7 @@ void trainingcard_panel::render_contents() ImGui::EndPopup(); } - if (start_time_wall) + if (start_time_wall.has_value()) { std::tm const tm = local_tm(*start_time_wall); std::string rep = "Czas rozpoczęcia: " + std::to_string(tm.tm_year + 1900) + "-" + std::to_string(tm.tm_mon + 1) + "-" + std::to_string(tm.tm_mday) + " " + std::to_string(tm.tm_hour) + @@ -154,7 +154,7 @@ void trainingcard_panel::render_contents() ImGui::TextUnformatted("Uwagi"); ImGui::InputTextMultiline("##remarks", &remarks[0], remarks.size(), ImVec2(-1.0f, 200.0f)); - if (!start_time_wall) + if (!start_time_wall.has_value()) { if (ImGui::Button("Rozpocznij szkolenie")) { @@ -177,7 +177,7 @@ void trainingcard_panel::render_contents() { state.store(2); if (simulation::Trains.sequence().size() > 0) - distance = simulation::Trains.sequence()[0]->Dynamic()->MoverParameters->DistCounter; + distance = static_cast(simulation::Trains.sequence()[0]->Dynamic()->MoverParameters->DistCounter); if (save_thread.joinable()) save_thread.join(); @@ -187,9 +187,9 @@ void trainingcard_panel::render_contents() } } -const std::string *trainingcard_panel::is_recording() +const std::string *trainingcard_panel::is_recording() const { - if (!start_time_wall) + if (!start_time_wall.has_value()) return nullptr; return &recording_timestamp; diff --git a/widgets/trainingcard.h b/widgets/trainingcard.h index 9e4eafe9..c485e79c 100644 --- a/widgets/trainingcard.h +++ b/widgets/trainingcard.h @@ -31,7 +31,7 @@ class trainingcard_panel : public ui_panel ~trainingcard_panel(); void render_contents() override; - const std::string *is_recording(); + const std::string *is_recording() const; std::string recording_timestamp; }; diff --git a/widgets/vehiclelist.cpp b/widgets/vehiclelist.cpp index e8ee1e12..45293fa1 100644 --- a/widgets/vehiclelist.cpp +++ b/widgets/vehiclelist.cpp @@ -12,7 +12,7 @@ ui::vehiclelist_panel::vehiclelist_panel(ui_layer &parent) void ui::vehiclelist_panel::render_contents() { if (m_first_show && Global.gui_trainingdefault) { - for (TDynamicObject *vehicle : simulation::Vehicles.sequence()) + for (TDynamicObject const *vehicle : simulation::Vehicles.sequence()) { if (!vehicle->Mechanik || vehicle->name() != ToLower(Global.local_start_vehicle)) continue; @@ -26,7 +26,7 @@ void ui::vehiclelist_panel::render_contents() return; } - for (TDynamicObject *vehicle : simulation::Vehicles.sequence()) + for (TDynamicObject const *vehicle : simulation::Vehicles.sequence()) { if (!vehicle->Mechanik) continue; @@ -37,7 +37,7 @@ void ui::vehiclelist_panel::render_contents() if (vehicle->Mechanik) timetable = vehicle->Mechanik->TrainName() + ", "; - std::string label = std::string(name + ", " + timetable + std::to_string(speed) + " km/h###"); + auto label = std::string(name + ", " + timetable + std::to_string(speed) + " km/h###"); ImGui::PushID(vehicle); if (ImGui::Button(label.c_str())) { diff --git a/widgets/vehiclelist.h b/widgets/vehiclelist.h index b1dd509a..b2143b94 100644 --- a/widgets/vehiclelist.h +++ b/widgets/vehiclelist.h @@ -8,7 +8,7 @@ class vehiclelist_panel : public ui_panel bool m_first_show = true; public: - vehiclelist_panel(ui_layer &parent); + explicit vehiclelist_panel(ui_layer &parent); void render_contents() override; }; diff --git a/world/EvLaunch.cpp b/world/EvLaunch.cpp index 29c3104f..22cfa413 100644 --- a/world/EvLaunch.cpp +++ b/world/EvLaunch.cpp @@ -34,14 +34,14 @@ int vk_to_glfw_key( int const Keycode ) { char key = 0; if (Keycode < 'A') { - key = Keycode; + key = static_cast(Keycode); } else if (Keycode <= 'Z') { - key = Keycode; + key = static_cast(Keycode); modifier = GLFW_MOD_SHIFT; } else if (Keycode < 'a') { - key = Keycode; + key = static_cast(Keycode); } else if (Keycode <= 'z') { - key = Keycode - 32; + key = static_cast(Keycode - 32); } else { ErrorLog("unknown key: " + std::to_string(Keycode)); } @@ -66,7 +66,7 @@ bool TEventLauncher::Load(cParser *parser) } else { // this launcher may be activated by radio message - std::map messages { + std::map> messages { { "radio_call1", radio_message::call1 }, { "radio_call3", radio_message::call3 } }; @@ -138,8 +138,7 @@ bool TEventLauncher::Load(cParser *parser) iHour = int( DeltaTime - iMinute ) / 100; // godzina to setki DeltaTime = 0; // bez powtórzeń // potentially shift the provided time by requested offset - auto const timeoffset{ static_cast( Global.ScenarioTimeOffset * 60 ) }; - if( timeoffset != 0 ) { + if( auto const timeoffset{ static_cast( Global.ScenarioTimeOffset * 60 ) }; timeoffset != 0 ) { auto const adjustedtime{ clamp_circular( iHour * 60 + iMinute + timeoffset, 24 * 60 ) }; iHour = adjustedtime / 60 % 24; iMinute = adjustedtime % 60; @@ -156,7 +155,7 @@ bool TEventLauncher::Load(cParser *parser) return true; } -bool TEventLauncher::check_activation_key() { +bool TEventLauncher::check_activation_key() const { if (iKey <= 0) return false; @@ -164,7 +163,7 @@ bool TEventLauncher::check_activation_key() { bool result = Console::Pressed(key); - char modifier = iKey >> 8; + auto modifier = static_cast(iKey >> 8); if (modifier & GLFW_MOD_SHIFT) result &= Global.shiftState; if (modifier & GLFW_MOD_CONTROL) @@ -195,12 +194,10 @@ bool TEventLauncher::check_activation() { else { // jeśli nie cykliczny, to sprawdzić czas if( simulation::Time.data().wHour == iHour ) { - if( simulation::Time.data().wMinute == iMinute ) { - // zgodność czasu uruchomienia - if( UpdatedTime < 10 ) { - UpdatedTime = 20; // czas do kolejnego wyzwolenia? - bCond = true; - } + // zgodność czasu uruchomienia + if (simulation::Time.data().wMinute == iMinute && UpdatedTime < 10) { + UpdatedTime = 20; // czas do kolejnego wyzwolenia? + bCond = true; } } else { @@ -211,7 +208,7 @@ bool TEventLauncher::check_activation() { return bCond; } -bool TEventLauncher::check_conditions() { +bool TEventLauncher::check_conditions() const { auto bCond { true }; @@ -239,7 +236,7 @@ bool TEventLauncher::IsRadioActivated() const { float TEventLauncher::radius_() { - return std::sqrt( dRadius ); + return static_cast(std::sqrt( dRadius )); } // serialize() subclass details, sends content of the subclass to provided stream @@ -271,9 +268,8 @@ TEventLauncher::export_as_text_( std::ostream &Output ) const { // activation key if( iKey != 0 ) { auto key { iKey & 0xff }; - auto const modifier { iKey >> 8 }; - if (key >= 'A' && key <= 'Z' && !(modifier & GLFW_MOD_SHIFT)) + if (auto const modifier { iKey >> 8 }; key >= 'A' && key <= 'Z' && !(modifier & GLFW_MOD_SHIFT)) key += 32; Output << (char)key; diff --git a/world/EvLaunch.h b/world/EvLaunch.h index a38e9e4a..4756c72b 100644 --- a/world/EvLaunch.h +++ b/world/EvLaunch.h @@ -30,10 +30,10 @@ public: // methods bool Load( cParser *parser ); - bool check_activation_key(); + bool check_activation_key() const; bool check_activation(); // checks conditions associated with the event. returns: true if the conditions are met - bool check_conditions(); + bool check_conditions() const; inline auto key() const { return iKey; } @@ -53,13 +53,13 @@ public: private: // methods // radius() subclass details, calculates node's bounding radius - float radius_(); + float radius_() override; // serialize() subclass details, sends content of the subclass to provided stream - void serialize_( std::ostream &Output ) const; + void serialize_( std::ostream &Output ) const override; // deserialize() subclass details, restores content of the subclass from provided stream - void deserialize_( std::istream &Input ); + void deserialize_( std::istream &Input ) override; // export() subclass details, sends basic content of the class in legacy (text) format to provided stream - void export_as_text_( std::ostream &Output ) const; + void export_as_text_( std::ostream &Output ) const override; // members int iKey { 0 }; diff --git a/world/MemCell.cpp b/world/MemCell.cpp index 76e9e4f1..dd2fa241 100644 --- a/world/MemCell.cpp +++ b/world/MemCell.cpp @@ -25,7 +25,7 @@ http://mozilla.org/MPL/2.0/. TMemCell::TMemCell( scene::node_data const &Nodedata ) : basic_node( Nodedata ) {} -void TMemCell::UpdateValues( std::string const &szNewText, double const fNewValue1, double const fNewValue2, int const CheckMask ) +void TMemCell::UpdateValues( std::string_view szNewText, double const fNewValue1, double const fNewValue2, int const CheckMask ) { if (CheckMask & basic_event::flags::mode_add) { // dodawanie wartości @@ -51,48 +51,49 @@ void TMemCell::UpdateValues( std::string const &szNewText, double const fNewValu TCommandType TMemCell::CommandCheck() { // rozpoznanie komendy + using enum TCommandType; if( szText == "SetVelocity" ) // najpopularniejsze { - eCommand = TCommandType::cm_SetVelocity; + eCommand = cm_SetVelocity; bCommand = false; // ta komenda nie jest wysyłana } else if( szText == "ShuntVelocity" ) // w tarczach manewrowych { - eCommand = TCommandType::cm_ShuntVelocity; + eCommand = cm_ShuntVelocity; bCommand = false; // ta komenda nie jest wysyłana } else if( szText == "Change_direction" ) // zdarza się { - eCommand = TCommandType::cm_ChangeDirection; + eCommand = cm_ChangeDirection; bCommand = true; // do wysłania } else if( szText == "OutsideStation" ) // zdarza się { - eCommand = TCommandType::cm_OutsideStation; + eCommand = cm_OutsideStation; bCommand = false; // tego nie powinno być w komórce } else if( szText.starts_with("PassengerStopPoint:") ) // porównanie początków { - eCommand = TCommandType::cm_PassengerStopPoint; + eCommand = cm_PassengerStopPoint; bCommand = false; // tego nie powinno być w komórce } else if( szText == "SetProximityVelocity" ) // nie powinno tego być { - eCommand = TCommandType::cm_SetProximityVelocity; + eCommand = cm_SetProximityVelocity; bCommand = false; // ta komenda nie jest wysyłana } else if( szText == "Emergency_brake" ) { - eCommand = TCommandType::cm_EmergencyBrake; + eCommand = cm_EmergencyBrake; bCommand = false; } else if( szText == "CabSignal" ) { - eCommand = TCommandType::cm_SecuritySystemMagnet; + eCommand = cm_SecuritySystemMagnet; bCommand = false; } else { - eCommand = TCommandType::cm_Unknown; // ciąg nierozpoznany (nie jest komendą) + eCommand = cm_Unknown; // ciąg nierozpoznany (nie jest komendą) bCommand = true; // do wysłania } return eCommand; @@ -157,11 +158,11 @@ bool TMemCell::Compare( std::string const &szTestText, double const fTestValue1, if( TestFlag( CheckMask, basic_event::flags::text ) ) { // porównać teksty - auto range = szTestText.find( '*' ); + auto wildcardpos = szTestText.find( '*' ); auto const result { ( - range == std::string::npos ? + wildcardpos == std::string::npos ? compare( szText, szTestText, TextOperator ) : - compare( szText.substr( 0, range ), szTestText.substr( 0, range ), TextOperator ) ) }; + compare( szText.substr( 0, wildcardpos ), szTestText.substr( 0, wildcardpos ), TextOperator ) ) }; checkpassed |= result; checkfailed |= !result; } @@ -177,20 +178,22 @@ bool TMemCell::Compare( std::string const &szTestText, double const fTestValue1, } switch( Pass ) { - case comparison_pass::all: { return checkfailed == false; } - case comparison_pass::any: { return checkpassed == true; } - case comparison_pass::none: { return checkpassed == false; } + using enum comparison_pass; + case all: { return checkfailed == false; } + case any: { return checkpassed == true; } + case none: { return checkpassed == false; } default: { return false; } } }; bool TMemCell::IsVelocity() const { // sprawdzenie, czy event odczytu tej komórki ma być do skanowania, czy do kolejkowania - if (eCommand == TCommandType::cm_SetVelocity) + using enum TCommandType; + if (eCommand == cm_SetVelocity) return true; - if (eCommand == TCommandType::cm_ShuntVelocity) + if (eCommand == cm_ShuntVelocity) return true; - return eCommand == TCommandType::cm_SetProximityVelocity; + return eCommand == cm_SetProximityVelocity; }; void TMemCell::StopCommandSent() @@ -258,7 +261,7 @@ TMemCell::export_as_text_( std::ostream &Output ) const { // legacy method, initializes traction after deserialization from scenario file void -memory_table::InitCells() { +memory_table::InitCells() const { for( auto *cell : m_items ) { // Ra: eventy komórek pamięci, wykonywane po wysłaniu komendy do zatrzymanego pojazdu @@ -275,9 +278,9 @@ memory_table::InitCells() { // legacy method, sends content of all cells to the log void -memory_table::log_all() { +memory_table::log_all() const { - for( auto *cell : m_items ) { + for( auto const *cell : m_items ) { cell->LogValues(); } } diff --git a/world/MemCell.h b/world/MemCell.h index c2960f27..ff1781ce 100644 --- a/world/MemCell.h +++ b/world/MemCell.h @@ -21,7 +21,7 @@ public: explicit TMemCell( scene::node_data const &Nodedata ); // methods void - UpdateValues( std::string const &szNewText, double const fNewValue1, double const fNewValue2, int const CheckMask ); + UpdateValues( std::string_view szNewText, double const fNewValue1, double const fNewValue2, int const CheckMask ); bool Load(cParser *parser); void @@ -61,11 +61,11 @@ public: private: // methods // serialize() subclass details, sends content of the subclass to provided stream - void serialize_( std::ostream &Output ) const; + void serialize_( std::ostream &Output ) const override; // deserialize() subclass details, restores content of the subclass from provided stream - void deserialize_( std::istream &Input ); + void deserialize_( std::istream &Input ) override; // export() subclass details, sends basic content of the class in legacy (text) format to provided stream - void export_as_text_( std::ostream &Output ) const; + void export_as_text_( std::ostream &Output ) const override; // members // content @@ -85,10 +85,10 @@ class memory_table : public basic_table { public: // legacy method, initializes traction after deserialization from scenario file void - InitCells(); + InitCells() const; // legacy method, sends content of all cells to the log void - log_all(); + log_all() const; }; //--------------------------------------------------------------------------- diff --git a/world/Segment.cpp b/world/Segment.cpp index c963922a..34683b03 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -67,8 +67,8 @@ bool TSegment::Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 N CPointIn = NewCPointIn; Point2 = NewPoint2; // poprawienie przechyłki - fRoll1 = glm::radians(fNewRoll1); // Ra: przeliczone jest bardziej przydatne do obliczeń - fRoll2 = glm::radians(fNewRoll2); + fRoll1 = static_cast(glm::radians(fNewRoll1)); // Ra: przeliczone jest bardziej przydatne do obliczeń + fRoll2 = static_cast(glm::radians(fNewRoll2)); bCurve = bIsCurve; if (Global.bRollFix) { // Ra: poprawianie przechyłki @@ -85,7 +85,7 @@ bool TSegment::Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 N Point1.y += w1; // modyfikacja musi być przed policzeniem dalszych parametrów if (bCurve) CPointOut.y += w1; // prosty ma wektory jednostkowe - pOwner->MovedUp1(w1); // zwrócić trzeba informację o podwyższeniu podsypki + pOwner->MovedUp1(static_cast(w1)); // zwrócić trzeba informację o podwyższeniu podsypki } if (fRoll2 != 0.f) { @@ -125,7 +125,7 @@ bool TSegment::Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 N fStep = fLength / ( 3.0 * Global.SplineFidelity ); } // iSegCount = static_cast( std::ceil( fLength / fStep ) ); // potrzebne do VBO - iSegCount = pOwner->eType == tt_Switch ? 6 * Global.SplineFidelity : static_cast(std::ceil(fLength / fStep)); // potrzebne do VBO + iSegCount = pOwner->eType == tt_Switch ? static_cast(6 * Global.SplineFidelity) : static_cast(std::ceil(fLength / fStep)); // potrzebne do VBO fStep = fLength / iSegCount; // update step to equalize size of individual pieces @@ -242,7 +242,7 @@ double TSegment::FastGetTFromS(double const s) const double const h01 = -2.0 * u3 + 3.0 * u2; double const t = ( ( 1.0 - h01 ) * fTsBuffer[ i ] + ( u3 - 2.0 * u2 + u ) * fTsSlope [ i ] + - ( h01 ) * fTsBuffer[ i + 1 ] + + h01 * fTsBuffer[ i + 1 ] + ( u3 - u2 ) * fTsSlope [ i + 1 ] ); return t; } @@ -263,10 +263,11 @@ double TSegment::ComputeLength() const // McZapkie-150503: dlugosc miedzy punkta // Ra: koniec rekurencji jeśli po podziale suma długości nie różni się więcej niż 0.5mm od // poprzedniej // Ra: ewentualnie rozpoznać łuk okręgu płaskiego i liczyć ze wzoru na długość łuku - double t, l = 0; + double t; + double l = 0; glm::dvec3 last{0, 0, 0}; // długość liczona po przesunięciu odcinka do początku układu glm::dvec3 tmp = Point2 - Point1; - int m = 20.0 * glm::length(tmp); // było zawsze do 10000, teraz jest liczone odcinkami po około 5cm + auto m = static_cast(20.0 * glm::length(tmp)); // było zawsze do 10000, teraz jest liczone odcinkami po około 5cm for (int i = 1; i <= m; i++) { t = double(i) / double(m); // wyznaczenie parametru na krzywej z przedziału (0,1> @@ -334,7 +335,7 @@ glm::dvec3 TSegment::GetDirection(double const fDistance) const return FastGetPoint(t2) - FastGetPoint(t1); } -glm::dvec3 TSegment::FastGetDirection(double fDistance, double fOffset) +glm::dvec3 TSegment::FastGetDirection(double fDistance, double fOffset) const { // takie toporne liczenie pochodnej dla parametru 0.0÷1.0 double t1 = fDistance - fOffset; if (t1 <= 0.0) @@ -371,22 +372,22 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: auto const t = FastGetTFromS(fDistance); // aproksymacja dystansu na krzywej Beziera na parametr (t) position = FastGetPoint( t ); // przechyłka w danym miejscu (zmienia się liniowo) - rotation.x = std::lerp( fRoll1, fRoll2, t ); + rotation.x = static_cast(std::lerp( fRoll1, fRoll2, t )); // pochodna auto const tangent = GetFirstDerivative( t ); // pochylenie krzywej (w pionie) - rotation.y = std::atan( tangent.y ); + rotation.y = static_cast(std::atan( tangent.y )); // kierunek krzywej w planie - rotation.z = -std::atan2( tangent.x, tangent.z ); + rotation.z = static_cast(-std::atan2( tangent.x, tangent.z )); } else { // wyliczenie dla odcinka prostego jest prostsze auto const t = fDistance / fLength; // zerowych torów nie ma position = FastGetPoint( t ); // przechyłka w danym miejscu (zmienia się liniowo) - rotation.x = std::lerp( fRoll1, fRoll2, t ); - rotation.y = fStoop; // pochylenie toru prostego - rotation.z = fDirection; // kierunek toru w planie + rotation.x = static_cast(std::lerp( fRoll1, fRoll2, t )); + rotation.y = static_cast(fStoop); // pochylenie toru prostego + rotation.z = static_cast(fDirection); // kierunek toru w planie } }; @@ -404,20 +405,35 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, if( fTsBuffer.empty() ) return false; // prowizoryczne zabezpieczenie przed wysypem - ustalić faktyczną przyczynę - glm::vec3 pos1, pos2, dir, parallel1, parallel2, pt, norm; - float s, step, fOffset, tv1, tv2, t, fEnd; + glm::vec3 pos1; + glm::vec3 pos2; + glm::vec3 dir; + glm::vec3 parallel1; + glm::vec3 parallel2; + glm::vec3 pt; + glm::vec3 norm; + float s; + float step; + float fOffset; + float tv1; + float tv2; + float t; + float fEnd; auto const iNumShapePoints = Transition ? ShapePoints.size() / 2 : ShapePoints.size(); - float const texturelength = fTextureLength * Texturescale; - float const texturescale = Texturescale; + auto const texturelength = static_cast(fTextureLength * Texturescale); + auto const texturescale = static_cast(Texturescale); - float m1, jmm1, m2, jmm2; // pozycje względne na odcinku 0...1 (ale nie parametr Beziera) - step = fStep; + float m1; + float jmm1; + float m2; + float jmm2; // pozycje względne na odcinku 0...1 (ale nie parametr Beziera) + step = static_cast(fStep); tv1 = 1.0; // Ra: to by można było wyliczać dla odcinka, wyglądało by lepiej - s = fStep * iSkip; // iSkip - ile odcinków z początku pominąć + s = static_cast(fStep * iSkip); // iSkip - ile odcinków z początku pominąć int i = iSkip; // domyślnie 0 - t = fTsBuffer[ i ]; // tabela wattości t dla segmentów + t = static_cast(fTsBuffer[ i ]); // tabela wattości t dla segmentów // BUG: length of spline can be 0, we should skip geometry generation for such cases - fOffset = 0.1 / fLength; // pierwsze 10cm + fOffset = static_cast(0.1 / fLength); // pierwsze 10cm pos1 = glm::dvec3{ FastGetPoint( t ) - Origin }; // wektor początku segmentu dir = glm::dvec3{ FastGetDirection( t, fOffset ) }; // wektor kierunku parallel1 = glm::vec3{ -dir.z, 0.f, dir.x }; // wektor poprzeczny @@ -428,11 +444,11 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, parallel1 = glm::normalize( parallel1 ); if( iEnd == 0 ) iEnd = iSegCount; - fEnd = fLength * double( iEnd ) / double( iSegCount ); + fEnd = static_cast(fLength * double( iEnd ) / double( iSegCount )); /* m2 = s / fEnd; */ - m2 = static_cast( i - iSkip ) / ( iEnd - iSkip ); + m2 = static_cast( i - iSkip ) / ( static_cast(iEnd - iSkip) ); jmm2 = 1.f - m2; @@ -445,7 +461,7 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, /* m2 = s / fEnd; */ - m2 = static_cast( i - iSkip ) / ( iEnd - iSkip ); + m2 = static_cast( i - iSkip ) / ( static_cast(iEnd - iSkip) ); jmm2 = 1.f - m2; // nowa pozycja if( i == iEnd ) { // gdy przekroczyliśmy koniec - stąd dziury w torach... @@ -462,7 +478,7 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, tv1 = clamp_circular( tv1, 1.0f ); tv2 = tv1 - step / texturelength; // mapowanie na końcu segmentu - t = fTsBuffer[ i ]; // szybsze od GetTFromS(s); + t = static_cast(fTsBuffer[ i ]); // szybsze od GetTFromS(s); pos2 = glm::dvec3{ FastGetPoint( t ) - Origin }; dir = glm::dvec3{ FastGetDirection( t, fOffset ) }; // nowy wektor kierunku parallel2 = glm::vec3{ -dir.z, 0.f, dir.x }; // wektor poprzeczny @@ -486,13 +502,12 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, glm::normalize( norm ), glm::vec2 { ( jmm1 * ShapePoints[ j ].texture.x + m1 * ShapePoints[ j + iNumShapePoints ].texture.x ) / texturescale, tv1 } ); } - if( p ) // jeśli jest wskaźnik do tablicy - if( *p ) - if( !j ) // to dla pierwszego punktu - { - **p = pt; - ( *p )++; - } // zapamiętanie brzegu jezdni + // jeśli jest wskaźnik do tablicy + if (p && *p && !j) // to dla pierwszego punktu + { + **p = pt; + ( *p )++; + } // zapamiętanie brzegu jezdni // dla trapezu drugi koniec ma inne współrzędne pt = parallel2 * ( jmm2 * ( ShapePoints[ j ].position.x - fOffsetX.first ) + m2 * ( ShapePoints[ j + iNumShapePoints ].position.x - fOffsetX.second ) ) + pos2; pt.y += jmm2 * ShapePoints[ j ].position.y + m2 * ShapePoints[ j + iNumShapePoints ].position.y; @@ -505,13 +520,12 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, glm::normalize( norm ), glm::vec2 { ( jmm2 * ShapePoints[ j ].texture.x + m2 * ShapePoints[ j + iNumShapePoints ].texture.x ) / texturescale, tv2 } ); } - if( p ) // jeśli jest wskaźnik do tablicy - if( *p ) - if( !j ) // to dla pierwszego punktu - if( i == iSegCount ) { - **p = pt; - ( *p )++; - } // zapamiętanie brzegu jezdni + // jeśli jest wskaźnik do tablicy + // to dla pierwszego punktu + if (p && *p && !j && i == iSegCount) { + **p = pt; + ( *p )++; + } // zapamiętanie brzegu jezdni } } else { @@ -549,39 +563,38 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, void TSegment::render_lines(std::vector &out, float quality) const { - float step = 1.0f / iSegCount / quality; + float step = 1.0f / static_cast(iSegCount) / quality; - float x; glm::vec3 previous = FastGetPoint(0.0); - for (x = step; x <= 1.0f; x += step) { - out.push_back(gfx::basic_vertex(previous, glm::vec3(0.0f), glm::vec2(0.0f))); + for (int i = 1; static_cast(i) * step <= 1.0f; ++i) { + float const x = static_cast(i) * step; + out.emplace_back(previous, glm::vec3(0.0f), glm::vec2(0.0f)); previous = glm::vec3(FastGetPoint(x)); - out.push_back(gfx::basic_vertex(previous, glm::vec3(0.0f), glm::vec2(0.0f))); + out.emplace_back(previous, glm::vec3(0.0f), glm::vec2(0.0f)); } - out.push_back(gfx::basic_vertex(previous, glm::vec3(0.0f), glm::vec2(0.0f))); + out.emplace_back(previous, glm::vec3(0.0f), glm::vec2(0.0f)); previous = glm::vec3(FastGetPoint(1.0)); - out.push_back(gfx::basic_vertex(previous, glm::vec3(0.0f), glm::vec2(0.0f))); + out.emplace_back(previous, glm::vec3(0.0f), glm::vec2(0.0f)); } glm::vec3 TSegment::get_nearest_point(const glm::dvec3 &point, float quality) const { - float step = 1.0f / iSegCount / quality; + float step = 1.0f / static_cast(iSegCount) / quality; - float x; glm::vec3 nearest; float min = std::numeric_limits::max(); - for (x = step; x <= 1.0f; x += step) { + for (int i = 1; static_cast(i) * step <= 1.0f; ++i) { + float const x = static_cast(i) * step; glm::vec3 p1 = FastGetPoint(x); - glm::vec3 p2 = FastGetPoint(glm::min(1.0f, x + step)); - if (p1 != p2) { + if (glm::vec3 p2 = FastGetPoint(glm::min(1.0f, x + step)); p1 != p2) { float l2 = glm::distance2(p1, p2); float t = glm::max(0.0f, glm::min(1.0f, glm::dot((glm::vec3)point - p1, p2 - p1) / l2)); glm::vec3 proj = p1 + t * (p2 - p1); diff --git a/world/Segment.h b/world/Segment.h index 645e5663..a3c83ade 100644 --- a/world/Segment.h +++ b/world/Segment.h @@ -41,10 +41,12 @@ struct segment_data { class TSegment { // aproksymacja toru (zwrotnica ma dwa takie, jeden z nich jest aktywny) private: - glm::dvec3 Point1, CPointOut, CPointIn, Point2; - float - fRoll1 { 0.f }, - fRoll2 { 0.f }; // przechyłka na końcach + glm::dvec3 Point1; + glm::dvec3 CPointOut; + glm::dvec3 CPointIn; + glm::dvec3 Point2; + float fRoll1 { 0.f }; + float fRoll2 { 0.f }; // przechyłka na końcach double fLength { -1.0 }; // długość policzona std::vector fTsBuffer; // wartości parametru krzywej t dla równych odcinków s std::vector fTsSlope; // nachylenie dt/du (= dt/ds * fStep) w tych samych punktach @@ -52,7 +54,9 @@ class TSegment int iSegCount = 0; // ilość odcinków do rysowania krzywej double fDirection = 0.0; // Ra: kąt prostego w planie; dla łuku kąt od Point1 double fStoop = 0.0; // Ra: kąt wzniesienia; dla łuku od Point1 - glm::dvec3 vA, vB, vC; // współczynniki wielomianów trzeciego stopnia vD==Point1 + glm::dvec3 vA; + glm::dvec3 vB; + glm::dvec3 vC; // współczynniki wielomianów trzeciego stopnia vD==Point1 TTrack *pOwner = nullptr; // wskaźnik na właściciela glm::dvec3 GetFirstDerivative(double const fTime) const; @@ -66,7 +70,7 @@ class TSegment public: bool bCurve = false; - TSegment(TTrack *owner); + explicit TSegment(TTrack *owner); bool Init(glm::dvec3 NewPoint1, glm::dvec3 NewPoint2, double fNewStep, double fNewRoll1 = 0, double fNewRoll2 = 0); bool Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 NewCPointIn, glm::dvec3 &NewPoint2, double fNewStep, double fNewRoll1 = 0, double fNewRoll2 = 0, bool bIsCurve = true); double @@ -89,7 +93,7 @@ public: GetDirection() const { return CPointOut; }; glm::dvec3 - FastGetDirection(double const fDistance, double const fOffset); + FastGetDirection(double const fDistance, double const fOffset) const; /* Math3D::vector3 GetPoint(double const fDistance) const; diff --git a/world/Spring.cpp b/world/Spring.cpp index b58d8859..56bcb845 100644 --- a/world/Spring.cpp +++ b/world/Spring.cpp @@ -13,19 +13,18 @@ http://mozilla.org/MPL/2.0/. void TSpring::Init(double nKs, double nKd) { Ks = nKs; Kd = nKd; - ks = Ks; - kd = Kd; + ks = static_cast(Ks); + kd = static_cast(Kd); } -glm::dvec3 TSpring::ComputateForces(glm::dvec3 const &pPosition1, glm::dvec3 const &pPosition2) { +glm::dvec3 TSpring::ComputateForces(glm::dvec3 const &pPosition1, glm::dvec3 const &pPosition2) const { glm::vec3 springForce; // p1 = &system[spring->p1]; // p2 = &system[spring->p2]; // VectorDifference(&p1->pos,&p2->pos,&deltaP); // Vector distance auto deltaP = pPosition1 - pPosition2; // dist = VectorLength(&deltaP); // Magnitude of deltaP - auto dist = glm::length(deltaP); - if( dist > restLen ) { + if( auto dist = glm::length(deltaP); dist > restLen ) { // Hterm = (dist - spring->restLen) * spring->Ks; // Ks * (dist - rest) auto Hterm = ( dist - restLen ) * Ks; // Ks * (dist - rest) diff --git a/world/Spring.h b/world/Spring.h index 6800ba29..9e4ce685 100644 --- a/world/Spring.h +++ b/world/Spring.h @@ -27,7 +27,7 @@ public: // void Init(TParticnp1, TParticle *np2, double nKs= 0.5f, double nKd= 0.002f, // double nrestLen= -1.0f); void Init(double nKs = 0.5f, double nKd = 0.002f); - glm::dvec3 ComputateForces(glm::dvec3 const &pPosition1, glm::dvec3 const &pPosition2); + glm::dvec3 ComputateForces(glm::dvec3 const &pPosition1, glm::dvec3 const &pPosition2) const; //private: // members double restLen { 0.01 }; // LENGTH OF SPRING AT REST diff --git a/world/Traction.cpp b/world/Traction.cpp index ef0c85bd..b9e47d5b 100644 --- a/world/Traction.cpp +++ b/world/Traction.cpp @@ -114,10 +114,9 @@ TTraction::Load( cParser *parser, glm::dvec3 const &pOrigin ) { // SKB70-C, CuCd70-2C, KB95-2C, C95-C, C95-2C, YC95-2C, YpC95-2C, YC120-2C // YpC120-2C, YzC120-2C, YwsC120-2C, YC150-C150, YC150-2C150, C150-C150 // C120-2C, 2C120-2C, 2C120-2C-1, 2C120-2C-2, 2C120-2C-3, 2C120-2C-4 - auto const material = parser->getToken(); // 1=miedziana, rysuje się na zielono albo czerwono // 2=aluminiowa, rysuje się na czarno - if( material == "none" ) { Material = 0; } + if( auto const material = parser->getToken(); material == "none" ) { Material = 0; } else if( material == "al" ) { Material = 2; } else { Material = 1; } parser->getTokens( 2 ); @@ -131,7 +130,7 @@ TTraction::Load( cParser *parser, glm::dvec3 const &pOrigin ) { auto const minheight { parser->getToken() }; fHeightDifference = ( pPoint3.y - pPoint1.y + pPoint4.y - pPoint2.y ) * 0.5 - minheight; auto const segmentlength { parser->getToken() }; - iNumSections = segmentlength ? glm::length(pPoint1 - pPoint2) / segmentlength : 0; + iNumSections = segmentlength != 0.0 ? static_cast(glm::length(pPoint1 - pPoint2) / segmentlength) : 0; parser->getTokens( 2 ); *parser >> Wires @@ -164,7 +163,7 @@ TTraction::endpoints() const { } std::size_t -TTraction::create_geometry( gfx::geometrybank_handle const &Bank ) { +TTraction::create_geometry( gfx::geometrybank_handle const &Geometrybank ) { if( m_geometry != null_handle ) { return GfxRenderer->Vertices( m_geometry ).size() / 2; } @@ -175,7 +174,8 @@ TTraction::create_geometry( gfx::geometrybank_handle const &Bank ) { if( Wires == 2 ) WireOffset = 0; // jezdny - gfx::basic_vertex startvertex, endvertex; + gfx::basic_vertex startvertex; + gfx::basic_vertex endvertex; startvertex.position = glm::vec3( pPoint1.x - ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - m_origin.x, @@ -189,7 +189,12 @@ TTraction::create_geometry( gfx::geometrybank_handle const &Bank ) { vertices.emplace_back( startvertex ); vertices.emplace_back( endvertex ); // Nie wiem co 'Marcin - glm::dvec3 pt1, pt2, pt3, pt4, v1, v2; + glm::dvec3 pt1; + glm::dvec3 pt2; + glm::dvec3 pt3; + glm::dvec3 pt4; + glm::dvec3 v1; + glm::dvec3 v2; v1 = pPoint4 - pPoint3; v2 = pPoint2 - pPoint1; float step = 0; @@ -207,7 +212,7 @@ TTraction::create_geometry( gfx::geometrybank_handle const &Bank ) { pPoint3.z - m_origin.z ); for( int i = 0; i < iNumSections - 1; ++i ) { pt3 = pPoint3 + v1 * f; - t = 1 - std::fabs(f - mid) * 2; + t = static_cast(1 - std::fabs(f - mid) * 2); if( Wires < 4 || ( i != 0 && i != iNumSections - 2 ) ) { @@ -256,7 +261,7 @@ TTraction::create_geometry( gfx::geometrybank_handle const &Bank ) { pPoint3.z - m_origin.z ); for( int i = 0; i < iNumSections - 1; ++i ) { pt3 = pPoint3 + v1 * f; - t = 1 - std::fabs(f - mid) * 2; + t = static_cast(1 - std::fabs(f - mid) * 2); endvertex.position = glm::vec3( pt3.x - m_origin.x, @@ -288,7 +293,7 @@ TTraction::create_geometry( gfx::geometrybank_handle const &Bank ) { for( int i = 0; i < iNumSections - 1; ++i ) { pt3 = pPoint3 + v1 * f; pt4 = pPoint1 + v2 * f; - t = 1 - std::fabs(f - mid) * 2; + t = static_cast(1 - std::fabs(f - mid) * 2); if( i % 2 == 0 ) { startvertex.position = glm::vec3( @@ -338,12 +343,12 @@ TTraction::create_geometry( gfx::geometrybank_handle const &Bank ) { auto const elementcount = vertices.size() / 2; gfx::userdata_array empty_userdata{}; - m_geometry = GfxRenderer->Insert( vertices, empty_userdata, Bank, GL_LINES ); + m_geometry = GfxRenderer->Insert( vertices, empty_userdata, Geometrybank, GL_LINES ); return elementcount; } -int TTraction::TestPoint(glm::dvec3 const &Point) +int TTraction::TestPoint(glm::dvec3 const &Point) const { // sprawdzanie, czy przęsła można połączyć if( hvNext[0] == nullptr && glm::all(glm::epsilonEqual(Point, pPoint1, 0.025)) ) { @@ -410,7 +415,8 @@ void TTraction::ResistanceCalc(int d, double r, TTractionPowerSource *ps) { //(this) jest przęsłem zasilanym, o rezystancji (r), policzyć rezystancję zastępczą sąsiednich if (d >= 0) { // podążanie we wskazanym kierunku - TTraction *t = hvNext[d], *p; + TTraction *t = hvNext[d]; + TTraction const *p; if (ps) psPower[d ^ 1] = ps; // podłączenie podanego else @@ -432,7 +438,7 @@ void TTraction::ResistanceCalc(int d, double r, TTractionPowerSource *ps) } } t->psPower[d] = ps; // skopiowanie wskaźnika zasilacza od danej strony - t->fResistance[d] = r; // wpisanie rezystancji w kierunku tego zasilacza + t->fResistance[d] = static_cast(r); // wpisanie rezystancji w kierunku tego zasilacza r += t->fResistivity * glm::length(t->vParametric); // doliczenie oporu kolejnego odcinka p = t; // zapamiętanie dotychczasowego t = p->hvNext[d ^ 1]; // podążanie w tę samą stronę @@ -457,17 +463,18 @@ void TTraction::PowerSet(TTractionPowerSource *ps) else { // ustalenie punktu zasilania (nie ma jeszcze połączeń między przęsłami) psPowered = ps; // ustawienie bezpośredniego zasilania dla przęsła - psPower[0] = psPower[1] = ps; // a to chyba nie jest dobry pomysł, bo nawet zasilane przęsło + psPower[0] = ps; // a to chyba nie jest dobry pomysł, bo nawet zasilane przęsło + psPower[1] = ps; // powinno mieć wskazania na inne - fResistance[0] = fResistance[1] = 0.0; // a liczy się tylko rezystancja zasilacza + fResistance[0] = 0.0; // a liczy się tylko rezystancja zasilacza + fResistance[1] = 0.0; } }; double TTraction::VoltageGet(double u, double i) { // pobranie napięcia na przęśle po podłączeniu do niego rezystancji (res) - na razie jest to prąd - if (!psSection) - if (!psPowered) - return NominalVoltage; // jak nie ma zasilacza, to napięcie podane w przęśle + if (!psSection && !psPowered) + return NominalVoltage; // jak nie ma zasilacza, to napięcie podane w przęśle // na początek można założyć, że wszystkie podstacje mają to samo napięcie i nie płynie prąd // pomiędzy nimi // dla danego przęsła mamy 3 źródła zasilania @@ -485,8 +492,12 @@ double TTraction::VoltageGet(double u, double i) return 0.0; } - double r0t, r1t, r0g, r1g; - double i0, i1; + double r0t; + double r1t; + double r0g; + double r1g; + double i0; + double i1; r0t = fResistance[0]; //średni pomysł, ale lepsze niż nic r1t = fResistance[1]; // bo nie uwzględnia spadków z innych pojazdów if (psPower[0] && psPower[1]) @@ -729,29 +740,25 @@ traction_table::InitTraction() { break; } } - if( traction->hvNext[ 0 ] ) { - // jeśli został podłączony - if( traction->psSection != nullptr - && matchingtraction->psSection != nullptr ) { - // tylko przęsło z izolatorem może nie mieć zasilania, bo ma 2, trzeba sprawdzać sąsiednie - if( traction->psSection != matchingtraction->psSection ) { - // połączone odcinki mają różne zasilacze - // to może być albo podłączenie podstacji lub kabiny sekcyjnej do sekcji, albo błąd - if( true == traction->psSection->bSection - && false == matchingtraction->psSection->bSection ) { - //(tmp->psSection) jest podstacją, a (Traction->psSection) nazwą sekcji - matchingtraction->PowerSet( traction->psSection ); // zastąpienie wskazaniem sekcji - } - else if( false == traction->psSection->bSection - && true == matchingtraction->psSection->bSection ) { - //(Traction->psSection) jest podstacją, a (tmp->psSection) nazwą sekcji - traction->PowerSet( matchingtraction->psSection ); // zastąpienie wskazaniem sekcji - } - else { - // jeśli obie to sekcje albo obie podstacje, to będzie błąd - ErrorLog( "Bad scenario: faulty traction power connection at location " + to_string( traction->pPoint1 ) ); - } - } + // jeśli został podłączony + // tylko przęsło z izolatorem może nie mieć zasilania, bo ma 2, trzeba sprawdzać sąsiednie + if (traction->hvNext[ 0 ] && traction->psSection != nullptr + && matchingtraction->psSection != nullptr && traction->psSection != matchingtraction->psSection) { + // połączone odcinki mają różne zasilacze + // to może być albo podłączenie podstacji lub kabiny sekcyjnej do sekcji, albo błąd + if( true == traction->psSection->bSection + && false == matchingtraction->psSection->bSection ) { + //(tmp->psSection) jest podstacją, a (Traction->psSection) nazwą sekcji + matchingtraction->PowerSet( traction->psSection ); // zastąpienie wskazaniem sekcji + } + else if( false == traction->psSection->bSection + && true == matchingtraction->psSection->bSection ) { + //(Traction->psSection) jest podstacją, a (tmp->psSection) nazwą sekcji + traction->PowerSet( matchingtraction->psSection ); // zastąpienie wskazaniem sekcji + } + else { + // jeśli obie to sekcje albo obie podstacje, to będzie błąd + ErrorLog( "Bad scenario: faulty traction power connection at location " + to_string( traction->pPoint1 ) ); } } } @@ -768,28 +775,24 @@ traction_table::InitTraction() { break; } } - if( traction->hvNext[ 1 ] ) { - // jeśli został podłączony - if( traction->psSection != nullptr - && matchingtraction->psSection != nullptr ) { - // tylko przęsło z izolatorem może nie mieć zasilania, bo ma 2, trzeba sprawdzać sąsiednie - if( traction->psSection != matchingtraction->psSection ) { - // to może być albo podłączenie podstacji lub kabiny sekcyjnej do sekcji, albo błąd - if( true == traction->psSection->bSection - && false == matchingtraction->psSection->bSection ) { - //(tmp->psSection) jest podstacją, a (Traction->psSection) nazwą sekcji - matchingtraction->PowerSet( traction->psSection ); // zastąpienie wskazaniem sekcji - } - else if( false == traction->psSection->bSection - && true == matchingtraction->psSection->bSection ) { - //(Traction->psSection) jest podstacją, a (tmp->psSection) nazwą sekcji - traction->PowerSet( matchingtraction->psSection ); // zastąpienie wskazaniem sekcji - } - else { - // jeśli obie to sekcje albo obie podstacje, to będzie błąd - ErrorLog( "Bad scenario: faulty traction power connection at location " + to_string( traction->pPoint2 ) ); - } - } + // jeśli został podłączony + // tylko przęsło z izolatorem może nie mieć zasilania, bo ma 2, trzeba sprawdzać sąsiednie + if (traction->hvNext[ 1 ] && traction->psSection != nullptr + && matchingtraction->psSection != nullptr && traction->psSection != matchingtraction->psSection) { + // to może być albo podłączenie podstacji lub kabiny sekcyjnej do sekcji, albo błąd + if( true == traction->psSection->bSection + && false == matchingtraction->psSection->bSection ) { + //(tmp->psSection) jest podstacją, a (Traction->psSection) nazwą sekcji + matchingtraction->PowerSet( traction->psSection ); // zastąpienie wskazaniem sekcji + } + else if( false == traction->psSection->bSection + && true == matchingtraction->psSection->bSection ) { + //(Traction->psSection) jest podstacją, a (tmp->psSection) nazwą sekcji + traction->PowerSet( matchingtraction->psSection ); // zastąpienie wskazaniem sekcji + } + else { + // jeśli obie to sekcje albo obie podstacje, to będzie błąd + ErrorLog( "Bad scenario: faulty traction power connection at location " + to_string( traction->pPoint2 ) ); } } } @@ -822,8 +825,7 @@ traction_table::InitTraction() { } else if( traction->hvParallel == nullptr ) { // jeśli jeszcze nie został włączony w kółko - auto *nTemp = find( traction->asParallel ); - if( nTemp != nullptr ) { + if( auto *nTemp = find( traction->asParallel ); nTemp != nullptr ) { // o ile zostanie znalezione przęsło o takiej nazwie if( nTemp->hvParallel == nullptr ) { // jeśli tamten jeszcze nie ma wskaźnika bieżni wspólnej diff --git a/world/Traction.h b/world/Traction.h index 638f46b0..6506dfb3 100644 --- a/world/Traction.h +++ b/world/Traction.h @@ -29,8 +29,10 @@ class TTraction : public scene::basic_node TTraction *hvNext[ 2 ] { nullptr, nullptr }; //łączenie drutów w sieć int iNext[ 2 ] { 0, 0 }; // do którego końca się łączy int iLast { 0 }; //że niby ostatni drut // ustawiony bit 0, jeśli jest ostatnim drutem w sekcji; bit1 - przedostatni - public: - glm::dvec3 pPoint1, pPoint2, pPoint3, pPoint4; + glm::dvec3 pPoint1; + glm::dvec3 pPoint2; + glm::dvec3 pPoint3; + glm::dvec3 pPoint4; glm::dvec3 vParametric; // współczynniki równania parametrycznego odcinka double fHeightDifference { 0.0 }; int iNumSections { 0 }; @@ -66,7 +68,7 @@ class TTraction : public scene::basic_node // creates geometry data in specified geometry bank. returns: number of created elements, or NULL // NOTE: deleting nodes doesn't currently release geometry data owned by the node. TODO: implement erasing individual geometry chunks and banks std::size_t create_geometry( gfx::geometrybank_handle const &Bank ); - int TestPoint(glm::dvec3 const &Point); + int TestPoint(glm::dvec3 const &Point) const; void Connect(int my, TTraction *with, int to); void Init(); bool WhereIs(); @@ -78,13 +80,13 @@ private: // methods glm::vec3 wire_color() const; // radius() subclass details, calculates node's bounding radius - float radius_(); + float radius_() override; // serialize() subclass details, sends content of the subclass to provided stream - void serialize_( std::ostream &Output ) const; + void serialize_( std::ostream &Output ) const override; // deserialize() subclass details, restores content of the subclass from provided stream - void deserialize_( std::istream &Input ); + void deserialize_( std::istream &Input ) override; // export() subclass details, sends basic content of the class in legacy (text) format to provided stream - void export_as_text_( std::ostream &Output ) const; + void export_as_text_( std::ostream &Output ) const override; }; diff --git a/world/TractionPower.cpp b/world/TractionPower.cpp index 7d816e21..540c32fc 100644 --- a/world/TractionPower.cpp +++ b/world/TractionPower.cpp @@ -125,7 +125,7 @@ double TTractionPowerSource::CurrentGet(double res) } if (res > 0 || (res < 0 && (Recuperation || true))) TotalAdmitance += 1.0 / res; // połączenie równoległe rezystancji jest równoważne sumie admitancji - float NomVolt = TotalPreviousAdmitance < 0 ? NominalVoltage * 1.083 : NominalVoltage; + float NomVolt = TotalPreviousAdmitance < 0 ? static_cast(NominalVoltage * 1.083) : static_cast(NominalVoltage); TotalCurrent = TotalPreviousAdmitance != 0.0 ? NomVolt / (InternalRes + 1.0 / TotalPreviousAdmitance) : 0.0; // napięcie dzielone przez sumę rezystancji wewnętrznej i obciążenia diff --git a/world/TractionPower.h b/world/TractionPower.h index d1faa037..61127ae0 100644 --- a/world/TractionPower.h +++ b/world/TractionPower.h @@ -19,7 +19,7 @@ class TTractionPowerSource : public scene::basic_node { public: // constructor - TTractionPowerSource( scene::node_data const &Nodedata ); + explicit TTractionPowerSource( scene::node_data const &Nodedata ); // methods void Init(double const u, double const i); bool Load(cParser *parser); @@ -38,11 +38,11 @@ public: private: // methods // serialize() subclass details, sends content of the subclass to provided stream - void serialize_( std::ostream &Output ) const; + void serialize_( std::ostream &Output ) const override; // deserialize() subclass details, restores content of the subclass from provided stream - void deserialize_( std::istream &Input ); + void deserialize_( std::istream &Input ) override; // export() subclass details, sends basic content of the class in legacy (text) format to provided stream - void export_as_text_( std::ostream &Output ) const; + void export_as_text_( std::ostream &Output ) const override; // members double NominalVoltage = 0.0; diff --git a/world/mtable.cpp b/world/mtable.cpp index cec54f87..b69cacfb 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -14,7 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/dictionary.h" #include "utilities/utilities.h" -double TTrainParameters::CheckTrainLatency() +double TTrainParameters::CheckTrainLatency() const { if (LastStationLatency > 1.0 || LastStationLatency < 0) return LastStationLatency; /*spoznienie + lub do przodu - z tolerancja 1 min*/ @@ -22,7 +22,7 @@ double TTrainParameters::CheckTrainLatency() return 0; } -double TTrainParameters::WatchMTable(double DistCounter) +double TTrainParameters::WatchMTable(double DistCounter) const { // zwraca odleglość do najblizszej stacji z zatrzymaniem double dist; @@ -105,7 +105,7 @@ bool TTrainParameters::UpdateMTable( scenario_time const &Time, std::string cons return UpdateMTable( Time.data().wHour, Time.data().wMinute + Time.data().wSecond * 0.0167, NewName ); } -bool TTrainParameters::UpdateMTable(double hh, double mm, std::string const &NewName) +bool TTrainParameters::UpdateMTable(double hh, double mm, std::string_view NewName) /*odfajkowanie dojechania do stacji (NewName) i przeliczenie opóźnienia*/ { bool OK; @@ -163,7 +163,7 @@ void TTrainParameters::StationIndexInc() ++StationIndex; } -bool TTrainParameters::IsTimeToGo(double hh, double mm) +bool TTrainParameters::IsTimeToGo(double hh, double mm) const // sprawdzenie, czy można już odjechać z aktualnego zatrzymania // StationIndex to numer następnego po dodarciu do aktualnego { @@ -205,7 +205,7 @@ TTrainParameters::TTrainParameters(std::string const &NewTrainName) NewName(NewTrainName); } -void TTrainParameters::NewName(std::string const &NewTrainName) +void TTrainParameters::NewName(std::string_view NewTrainName) /*wstępne ustawienie parametrów rozkładu jazdy*/ { TrainName = NewTrainName; @@ -217,9 +217,9 @@ void TTrainParameters::NewName(std::string const &NewTrainName) Direction = 1; Relation1 = ""; Relation2 = ""; - for (int i = 0; i < MaxTTableSize + 1; ++i) + for (auto &tableline : TimeTable) { - TimeTable[ i ] = TMTableLine(); + tableline = TMTableLine(); } TTVmax = 100; /*wykasowac*/ BrakeRatio = 0; @@ -227,7 +227,7 @@ void TTrainParameters::NewName(std::string const &NewTrainName) LocLoad = 0; } -void TTrainParameters::UpdateVelocity(int StationCount, double vActual) +void TTrainParameters::UpdateVelocity(int /*Stationcount*/, double vActual) // zapisywanie prędkości maksymalnej do wcześniejszych odcinków // wywoływane z numerem ostatniego przetworzonego przystanku { @@ -235,7 +235,7 @@ void TTrainParameters::UpdateVelocity(int StationCount, double vActual) // TTVmax:=vActual; {PROWIZORKA!!!} while (i >= 0 && TimeTable[i].vmax == -1) { - TimeTable[i].vmax = vActual; // prędkość dojazdu do przystanku i + TimeTable[i].vmax = static_cast(vActual); // prędkość dojazdu do przystanku i --i; // ewentualnie do poprzedniego też } } @@ -245,7 +245,7 @@ void TTrainParameters::UpdateVelocity(int StationCount, double vActual) // return false; //} -bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) +bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double vmax) // wczytanie pliku-tabeli z rozkładem przesuniętym o (fPlus); (vMax) nie ma znaczenia { std::string lines; @@ -254,7 +254,7 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) bool EndTable; double vActual; - int ConversionError = 0; + int conversionerror = 0; EndTable = false; if (TrainName == "") { // jeśli pusty rozkład @@ -262,7 +262,6 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) } else { - ConversionError = 666; vActual = -1; s = scnpath + TrainName + ".txt"; replace_slashes(s); @@ -278,15 +277,15 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) { TTVmax = vmax; // Ra 2014-07: zamiast rozkładu można podać Vmax UpdateVelocity(StationCount, vmax); // ograniczenie do prędkości startowej - ConversionError = 0; + conversionerror = 0; } else - ConversionError = -8; /*Ra: ten błąd jest niepotrzebny*/ + conversionerror = -8; /*Ra: ten błąd jest niepotrzebny*/ } else { /*analiza rozkładu jazdy*/ - ConversionError = 0; - while (fin.good() && !(ConversionError != 0 || EndTable)) + conversionerror = 0; + while (fin.good() && !(conversionerror != 0 || EndTable)) { std::getline(fin, lines); /*wczytanie linii*/ if (contains( lines, "___________________") ) /*linia pozioma górna*/ @@ -354,7 +353,7 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) win1250_to_ascii( Relation1 ); } else - ConversionError = -5; + conversionerror = -5; while (fin >> s || !fin.bad()) { if (s == "Relacja") @@ -409,10 +408,10 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) if (s == "[") fin >> s; else - ConversionError = -4; + conversionerror = -4; if (false == contains( s,"|") ) { - record->km = atof(s.c_str()); + record->km = static_cast(atof(s.c_str())); fin >> s; } if (contains( s,"|_____|")) /*zmiana predkosci szlakowej*/ @@ -439,12 +438,12 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) if (contains( s, hrsd) ) { record->Ah = atoi( s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu - record->Am = atof(s.substr(s.find(hrsd) + 1, s.length()).c_str()); // minuta przyjazdu + record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu } else { record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji - record->Am = atof(s.c_str()); // bo tylko minuty podane + record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane } } do @@ -452,7 +451,7 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) fin >> s; } while (!(s != "|" || fin.bad())); if (s != "]") - record->tm = atof(s.c_str()); + record->tm = static_cast(atof(s.c_str())); do { fin >> s; @@ -490,10 +489,10 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) if( entry.front() != 'R' ) { continue; } - auto const entrysplit { split_string_and_number( entry ) }; - if( entrysplit.first == "R" - && entrysplit.second <= 10 ) { - auto const radiochannel { entrysplit.second }; + auto const [entrytype, entrynumber]{ split_string_and_number( entry ) }; + if( entrytype == "R" + && entrynumber <= 10 ) { + auto const radiochannel { entrynumber }; if( record->radio_channel == -1 || radiochannel != activeradiochannel ) { // if the station has more than one radiochannel listed, @@ -514,12 +513,12 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) if (contains( s, hrsd) ) { record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu - record->Dm = atof(s.substr(s.find(hrsd) + 1, s.length()).c_str()); // minuta odjazdu + record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu } else { record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji - record->Dm = atof(s.c_str()); // bo tylko minuty podane + record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane } } else @@ -532,7 +531,7 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) fin >> s; } while (!(s != "|" || fin.bad())); if (s != "]") - record->tm = atof(s.c_str()); + record->tm = static_cast(atof(s.c_str())); do { fin >> s; @@ -565,20 +564,16 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) fin.close(); } } - if (ConversionError == 0) - { - if (TimeTable[1].StationName == Relation1) // jeśli nazwa pierwszego zgodna z relacją - if (TimeTable[1].Ah < 0) // a nie podany czas przyjazdu - { // to mamy zatrzymanie na pierwszym, a nie przelot - TimeTable[1].Ah = TimeTable[1].Dh; - TimeTable[1].Am = TimeTable[1].Dm; - } + // jeśli nazwa pierwszego zgodna z relacją + if (conversionerror == 0 && TimeTable[1].StationName == Relation1 && TimeTable[1].Ah < 0) // a nie podany czas przyjazdu + { // to mamy zatrzymanie na pierwszym, a nie przelot + TimeTable[1].Ah = TimeTable[1].Dh; + TimeTable[1].Am = TimeTable[1].Dm; } // load_sounds(); // potentially offset table times - auto const timeoffset { static_cast( Global.ScenarioTimeOffset * 60 ) + iPlus }; - if( timeoffset != 0 ) // jeżeli jest przesunięcie rozkładu + if( auto const timeoffset { static_cast( Global.ScenarioTimeOffset * 60 ) + iPlus }; timeoffset != 0 ) // jeżeli jest przesunięcie rozkładu { long i_end = StationCount + 1; float adjustedtime; // do zwiększania czasu @@ -586,19 +581,19 @@ bool TTrainParameters::LoadTTfile(std::string scnpath, int iPlus, double vmax) { if (TimeTable[i].Ah >= 0) { - adjustedtime = clamp_circular( TimeTable[i].Ah * 60 + TimeTable[i].Am + timeoffset, 24 * 60 ); // nowe minuty + adjustedtime = clamp_circular( static_cast(TimeTable[i].Ah * 60) + TimeTable[i].Am + static_cast(timeoffset), 24 * 60 ); // nowe minuty TimeTable[i].Am = int(60 * adjustedtime) % 3600 / 60.f; TimeTable[i].Ah = int(adjustedtime / 60) % 24; } if (TimeTable[i].Dh >= 0) { - adjustedtime = clamp_circular( TimeTable[i].Dh * 60 + TimeTable[i].Dm + timeoffset, 24 * 60 ); // nowe minuty + adjustedtime = clamp_circular( static_cast(TimeTable[i].Dh * 60) + TimeTable[i].Dm + static_cast(timeoffset), 24 * 60 ); // nowe minuty TimeTable[i].Dm = int(60 * adjustedtime) % 3600 / 60.f; TimeTable[i].Dh = int(adjustedtime / 60) % 24; } } } - return ConversionError == 0; + return conversionerror == 0; } void @@ -615,26 +610,26 @@ TTrainParameters::load_sounds() { station.StationName.substr( 0, station.StationName.size() - 3 ) : station.StationName ) }; - auto const lookup { + auto const [filepath, fileextension]{ FileExists( { Global.asCurrentSceneryPath + stationname, std::string{ paths::sounds } + "sip/" + stationname }, { ".ogg", ".flac", ".wav" } ) }; - if( lookup.first.empty() ) { + if( filepath.empty() ) { continue; } // wczytanie dźwięku odjazdu w wersji radiowej (słychać tylko w kabinie) station.name_sound = sound_source{ sound_placement::engine, EU07_SOUND_CABANNOUNCEMENTCUTOFFRANGE } - .deserialize( lookup.first + lookup.second, sound_type::single ); + .deserialize( filepath + fileextension, sound_type::single ); } } -bool TTrainParameters::DirectionChange() +bool TTrainParameters::DirectionChange() const // sprawdzenie, czy po zatrzymaniu wykonać kolejne komendy { - if (StationIndex > 0 && StationIndex < StationCount) // dla ostatniej stacji nie - if (contains( TimeTable[StationIndex].StationWare, '@') ) - return true; + // dla ostatniej stacji nie + if (StationIndex > 0 && StationIndex < StationCount && contains( TimeTable[StationIndex].StationWare, '@')) + return true; return false; } diff --git a/world/mtable.h b/world/mtable.h index c58d120f..44cda731 100644 --- a/world/mtable.h +++ b/world/mtable.h @@ -18,7 +18,7 @@ namespace Mtable { static int const MaxTTableSize = 100; // można by to robić dynamicznie -static char const *hrsd = "."; +static char const *const hrsd = "."; // Ra: pozycja zerowa rozkładu chyba nie ma sensu // Ra: numeracja przystanków jest 1..StationCount @@ -42,7 +42,7 @@ struct TMTableLine sound_source name_sound{ sound_placement::engine }; }; -typedef TMTableLine TMTable[MaxTTableSize + 1]; +using TMTable = TMTableLine[MaxTTableSize + 1]; // typedef TTrainParameters *PTrainParameters; @@ -65,27 +65,27 @@ class TTrainParameters std::string NextStationName; double LastStationLatency; int Direction; /*kierunek jazdy w/g kilometrazu*/ - double CheckTrainLatency(); + double CheckTrainLatency() const; /*todo: str hh:mm to int i z powrotem*/ std::string ShowRelation() const; - double WatchMTable(double DistCounter); + double WatchMTable(double DistCounter) const; std::string NextStop() const; sound_source next_stop_sound() const; sound_source last_stop_sound() const; bool IsStop() const; bool IsLastStop() const; bool IsMaintenance() const; - bool IsTimeToGo(double hh, double mm); + bool IsTimeToGo(double hh, double mm) const; // returns: difference between specified time and scheduled departure from current stop, in seconds double seconds_until_departure( double const Hour, double const Minute ) const; - bool UpdateMTable(double hh, double mm, std::string const &NewName); + bool UpdateMTable(double hh, double mm, std::string_view NewName); bool UpdateMTable( scenario_time const &Time, std::string const &NewName ); bool RewindTimeTable( std::string actualStationName ); - TTrainParameters( std::string const &NewTrainName = "none" ); - void NewName(std::string const &NewTrainName); + explicit TTrainParameters( std::string const &NewTrainName = "none" ); + void NewName(std::string_view NewTrainName); void UpdateVelocity(int StationCount, double vActual); - bool LoadTTfile(std::string scnpath, int iPlus, double vmax); - bool DirectionChange(); + bool LoadTTfile(std::string const &scnpath, int iPlus, double vmax); + bool DirectionChange() const; void StationIndexInc(); void serialize( dictionary_source *Output ) const; // returns: radio channel associated with current station, or -1 diff --git a/world/station.cpp b/world/station.cpp index eae81d9e..90b443e8 100644 --- a/world/station.cpp +++ b/world/station.cpp @@ -22,7 +22,7 @@ basic_station Station; // exchanges load with consist attached to specified vehicle, operating on specified schedule double -basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Schedule, int const Platform ) { +basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Schedule, int const Platform ) const { // TODO: filter out maintenance stops when determining first and last stop auto const firststop { Schedule.StationIndex == 1 }; @@ -63,7 +63,7 @@ basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Sch maintenancestop ? 0 : std::min( parameters.LoadAmount, - Random( parameters.MaxLoad * 0.15f * stationsizemodifier ) ) ); + static_cast(Random( parameters.MaxLoad * 0.15f * stationsizemodifier )) ) ); auto loadcount = static_cast( TestFlag( parameters.DamageFlag, dtrain_out ) ? 0 : laststop ? 0 : diff --git a/world/station.h b/world/station.h index ecc60992..5c4a9507 100644 --- a/world/station.h +++ b/world/station.h @@ -18,7 +18,7 @@ public: // methods // exchanges load with consist attached to specified vehicle, operating on specified schedule; returns: time needed for exchange, in seconds double - update_load( TDynamicObject *First, Mtable::TTrainParameters &Schedule, int const Platform ); + update_load( TDynamicObject *First, Mtable::TTrainParameters &Schedule, int const Platform ) const; }; namespace simulation {