From 22c8e7322fc73d72c67c17e77062667ad9583838 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sat, 7 Nov 2026 19:53:10 +0100 Subject: [PATCH 01/37] feat: Elf emergency brake position in the master controller (eu07/maszyna#413) The Elf's master controller (EIMCtrlType 2) gets an optional emergency brake position below its position 0, turned on by the new .fiz key EIMCtrlMainEmergency=Yes in Cntrl (default No, no change without it). With it the old positions move up by one (MCPN 5, neutral at 4): the emergency position brakes fully at once and vents the brake pipe, like the alarm chain or the Impuls's EIMCtrlEmergency. The loader raises a too small MCPN to 5 and logs it. The Elf code with hard-coded positions (CheckEIMIC, the MED full braking, the AI) takes the shift into account. SVN data to change afterwards (dynamic/pkp/elf_v1, needs this exe): - every .fiz with EIMCtrlType=2: EIMCtrlMainEmergency=Yes, MCPN=5, DirChangeMaxPos=4 where present; - the cab .mmd mainctrl entries: offset one notch lower (-0.06 -> -0.09), sounds shifted one index up, new sound0 with 26284_elf_nastawnik_nagle_*.wav. Issue: (eu07/maszyna#413) --- McZapkie/MOVER.h | 5 ++ McZapkie/Mover.cpp | 32 ++++++- tests/unit/test_elf_controller.cpp | 136 +++++++++++++++++++++++++++++ vehicle/Driver.cpp | 29 +++--- vehicle/DynObj.cpp | 3 +- 5 files changed, 189 insertions(+), 16 deletions(-) create mode 100644 tests/unit/test_elf_controller.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 199c65a0c..d96e0d10c 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2205,6 +2205,7 @@ class TMoverParameters int SpeedCtrlAutoTurnOffFlag = 0; /*czy tempomat sam się wyłącza*/ bool EIMCtrlAdditionalZeros = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ bool EIMCtrlEmergency = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ + bool EIMCtrlMainEmergency = false; /*czy zadajnik typu 2 (Elf) ma pozycje hamowania naglego ponizej swojej pozycji 0*/ double eimv_pr = 0; /*realizowany procent dostepnej sily rozruchu/hamowania*/ double eimv[21]; static std::vector const eimv_labels; @@ -2368,6 +2369,10 @@ class TMoverParameters int MainCtrlNoPowerPos() const; // highest setting of master controller which won't cause engine to generate extra power int MainCtrlActualPowerPos() const; // current actual setting of master controller, relative to the highest setting not generating extra power int MainCtrlPowerPos() const; // current setting of master controller, relative to the highest setting not generating extra power + // positions the master controller of the EIMCtrlType 2 (Elf) has below its own position 0, the emergency brake (0 or 1) + int EIMCtrlEmergencyPositions() const; + // whether the master controller is in its emergency brake position (EIMCtrlType 2 with EIMCtrlMainEmergency) + bool IsMainCtrlEmergencyPos() const; /*! pomocniczy nastawnik:*/ bool IncScndCtrl(int CtrlSpeed); bool DecScndCtrl(int CtrlSpeed); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 330e8eb8f..3499e16b3 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -2710,7 +2710,7 @@ int TMoverParameters::MainCtrlNoPowerPos() const } case 2: { - return 3; + return 3 + EIMCtrlEmergencyPositions(); } case 3: { @@ -2735,6 +2735,16 @@ int TMoverParameters::MainCtrlPowerPos() const return MainCtrlPos - MainCtrlNoPowerPos(); } +int TMoverParameters::EIMCtrlEmergencyPositions() const +{ + return (EIMCtrlType == 2 && EIMCtrlMainEmergency) ? 1 : 0; +} + +bool TMoverParameters::IsMainCtrlEmergencyPos() const +{ + return MainCtrlPos < EIMCtrlEmergencyPositions(); +} + // ************************************************************************************************* // Q: 20160710 // zwiększenie bocznika @@ -4577,7 +4587,7 @@ void TMoverParameters::UpdatePipePressure(double dt) // 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) - if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || SecuritySystem.is_braking() || + if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || IsMainCtrlEmergencyPos() || SecuritySystem.is_braking() || (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)) { @@ -7357,10 +7367,16 @@ void TMoverParameters::CheckEIMIC(double dt) eimic = 0; break; case 2: - if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + if (IsMainCtrlEmergencyPos()) + { + // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() + eimic = -1.0; + } + else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) { double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; - switch (MainCtrlPos) + // the positions below are those of the controller without the emergency brake position + switch (MainCtrlPos - EIMCtrlEmergencyPositions()) { case 0: case 1: @@ -10895,6 +10911,14 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(LocHandleTimeTraxx, "LocalBrakeTraxx", line, ""); extract_value(EIMCtrlAdditionalZeros, "EIMCtrlAddZeros", line, ""); extract_value(EIMCtrlEmergency, "EIMCtrlEmergency", line, ""); + // Elf (EIMCtrlType 2): an emergency brake position below the controller's position 0, which shifts the other positions up by one + extract_value(EIMCtrlMainEmergency, "EIMCtrlMainEmergency", line, ""); + if (auto const elfpositions{4 + EIMCtrlEmergencyPositions()}; EIMCtrlEmergencyPositions() > 0 && MainCtrlPosNo < elfpositions) + { + // without it the controller would have no power position + ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}", elfpositions, TypeName)); + MainCtrlPosNo = elfpositions; + } extract_value(ScndS, "ScndS", line, ""); // brak pozycji rownoleglej przy niskiej nastawie PSR diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp new file mode 100644 index 000000000..747a57630 --- /dev/null +++ b/tests/unit/test_elf_controller.cpp @@ -0,0 +1,136 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" + +#include "McZapkie/hamulce.h" + +// the master controller of the Elf (EIMCtrlType 2): its positions, and the emergency brake position below +// them which EIMCtrlMainEmergency adds (eu07/maszyna#413) + +using test::definition; +using test::vehicle; + +namespace { + +// a three-car Elf ready to run, standing with its brakes released and the driver in the front cab of the +// head car, which also drives (the controller's eimic is worked out there) +struct elf { + explicit elf(bool Emergency) { + for (auto const *car : {"elf_v1/21we-a", "elf_v1/21we-b", "elf_v1/21we-c"}) { + auto cardefinition{definition::fiz(car)}; + if (Emergency) { + cardefinition.set("Cntrl", "EIMCtrlMainEmergency", "Yes").set("Cntrl", "MCPN", 5); + } + unit.add(cardefinition, unit.size() == 0 ? 1 : 0); + } + ready = test::start_up(test::driving(unit), line); + // the start-up of the tests leaves the controller at its position 0 (close_line_breaker() in drive.cpp), + // the emergency brake one with EIMCtrlMainEmergency; the driver sets it to neutral, as the AI does. a unit + // moves its controller only with a direction set + for (int i = 0; i < 3 && cab().DirActive <= 0; ++i) { + cab().DirectionForward(); + } + while (cab().MainCtrlPos < cab().MainCtrlNoPowerPos() && cab().IncMainCtrl(1)) { + // up to neutral + } + test::release_brakes(cab()); + recharge(); + charged = cab().PipePress > 4.5; + } + // the pipe charged again after an emergency stop: the Elf locks its emptied pipe off the brake handle (LPOn, + // LPOff) until the unlock button (UBB1, the first universal brake button) is held, the handle at running + void recharge() { + cab().BrakeLevelSet(cab().Handle->GetPos(bh_RP)); + cab().UniversalBrakeButton(0, 1); + wait(30.0); + cab().UniversalBrakeButton(0, 0); + wait(30.0); + } + TMoverParameters &cab() { return unit[0].mover(); } + void wait(double Seconds) { test::drive(test::driving(unit), line, Seconds); } + test::consist unit; + test::track line{0.15, 0.0, test::catenary_3kv}; + bool ready{false}; + bool charged{false}; +}; + +} // namespace + +TEST_CASE("elf controller: without EIMCtrlMainEmergency the positions stay as they were") { + elf unit{false}; + REQUIRE(unit.ready); + REQUIRE(unit.charged); + auto &mover{unit.cab()}; + CHECK_FALSE(mover.EIMCtrlMainEmergency); + CHECK(mover.EIMCtrlEmergencyPositions() == 0); + CHECK(mover.MainCtrlPosNo == 4); + CHECK(mover.MainCtrlNoPowerPos() == 3); + CHECK(mover.MainCtrlPos == 3); + // the lowest position brakes fully, without emptying the pipe + mover.MainCtrlPos = 0; + CHECK_FALSE(mover.IsMainCtrlEmergencyPos()); + unit.wait(10.0); + CHECK(mover.eimic == doctest::Approx(-1.0)); + CHECK(mover.PipePress > 4.5); +} + +TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the emergency brake one") { + elf unit{true}; + REQUIRE(unit.ready); + REQUIRE(unit.charged); + auto &mover{unit.cab()}; + CHECK(mover.EIMCtrlMainEmergency); + CHECK(mover.EIMCtrlEmergencyPositions() == 1); + CHECK(mover.MainCtrlPosNo == 5); + CHECK(mover.MainCtrlNoPowerPos() == 4); + CHECK(mover.MainCtrlPos == 4); + CHECK_FALSE(mover.IsMainCtrlEmergencyPos()); + SUBCASE("the neutral position neither drives nor brakes") { + unit.wait(5.0); + CHECK(mover.eimic == doctest::Approx(0.0)); + } + SUBCASE("the full braking position, formerly 0, brakes fully without emptying the pipe") { + mover.MainCtrlPos = 1; + unit.wait(10.0); + CHECK(mover.eimic == doctest::Approx(-1.0)); + CHECK(mover.PipePress > 4.5); + } + SUBCASE("the braking position, formerly 1, ramps the braking up") { + mover.MainCtrlPos = 2; + unit.wait(1.0); + CHECK(mover.eimic < 0.0); + CHECK(mover.eimic > -1.0); + CHECK(mover.PipePress > 4.5); + } + SUBCASE("the emergency brake position brakes fully at once and empties the pipe") { + mover.MainCtrlPos = 0; + CHECK(mover.IsMainCtrlEmergencyPos()); + // a single step of the physics + unit.unit.step(unit.line); + CHECK(mover.eimic == doctest::Approx(-1.0)); + unit.wait(10.0); + CHECK(mover.PipePress < 0.5); + CHECK(mover.BrakePress > 1.0); + // out of it the pipe charges again + mover.MainCtrlPos = mover.MainCtrlNoPowerPos(); + CHECK_FALSE(mover.IsMainCtrlEmergencyPos()); + unit.recharge(); + CHECK(mover.PipePress > 4.5); + } +} + +TEST_CASE("elf controller: EIMCtrlMainEmergency with the old MCPN gets its positions all the same") { + vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "EIMCtrlMainEmergency", "Yes")}; + CHECK(car->MainCtrlPosNo == 5); + CHECK(car->MainCtrlNoPowerPos() == 4); +} + +TEST_CASE("elf controller: EIMCtrlMainEmergency leaves the other controllers alone") { + // the Impuls (EIMCtrlType 0) has its emergency brake in the brake range of its controller (EIMCtrlEmergency) + vehicle impuls{definition::fiz("impuls_v1/31we-a_pr").set("Cntrl", "EIMCtrlMainEmergency", "Yes"), 60.0, "impuls", 1}; + CHECK(impuls->EIMCtrlEmergencyPositions() == 0); + CHECK(impuls->MainCtrlPosNo == 10); + impuls->MainCtrlPos = 0; + CHECK_FALSE(impuls->IsMainCtrlEmergencyPos()); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 08f0c0d24..461c8d1af 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -3144,9 +3144,11 @@ bool TController::IncBrakeEIM() break; } case 2: { - OK = mvOccupied->MainCtrlPos > 1; + // the braking position, above the emergency brake one where the controller has it + auto const brakepos{1 + mvOccupied->EIMCtrlEmergencyPositions()}; + OK = mvOccupied->MainCtrlPos > brakepos; if( OK ) - mvOccupied->MainCtrlPos = 1; + mvOccupied->MainCtrlPos = brakepos; break; } case 3: { @@ -3300,9 +3302,10 @@ bool TController::DecBrakeEIM() break; } case 2: { - OK = mvOccupied->MainCtrlPos < 3; + auto const neutralpos{mvOccupied->MainCtrlNoPowerPos()}; + OK = mvOccupied->MainCtrlPos < neutralpos; if( OK ) - mvOccupied->MainCtrlPos = 3; + mvOccupied->MainCtrlPos = neutralpos; break; } case 3: { @@ -3663,12 +3666,14 @@ bool TController::IncSpeedEIM() { } */ break; - case 2: - OK = mvControlling->MainCtrlPos < 4; + case 2: { + auto const powerpos{4 + mvControlling->EIMCtrlEmergencyPositions()}; + OK = mvControlling->MainCtrlPos < powerpos; if( OK ) { - mvControlling->MainCtrlPos = 4; + mvControlling->MainCtrlPos = powerpos; } break; + } } return OK; } @@ -3696,9 +3701,10 @@ bool TController::DecSpeedEIM( int const Amount ) mvControlling->SpeedCtrlPowerDec(); } else { - OK = mvControlling->MainCtrlPos > 2; + auto const holdpos{2 + mvControlling->EIMCtrlEmergencyPositions()}; + OK = mvControlling->MainCtrlPos > holdpos; if( OK ) { - mvControlling->MainCtrlPos = 2; + mvControlling->MainCtrlPos = holdpos; } } break; @@ -4170,8 +4176,9 @@ void TController::CheckTimeControllers() } else if (mvOccupied->EIMCtrlType == 2) //elf { - if (mvOccupied->eimic > 0) mvOccupied->MainCtrlPos = 3; - if (mvOccupied->eimic < 0) mvOccupied->MainCtrlPos = 2; + auto const emergencypositions{mvOccupied->EIMCtrlEmergencyPositions()}; + if (mvOccupied->eimic > 0) mvOccupied->MainCtrlPos = 3 + emergencypositions; + if (mvOccupied->eimic < 0) mvOccupied->MainCtrlPos = 2 + emergencypositions; } } //4. Check Speed Control System diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index d5f60e332..46aba815f 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3238,7 +3238,8 @@ bool TDynamicObject::Update(double dt, double dt1) auto eimic = std::min(MoverParameters->eimic, MoverParameters->eimicSpeedCtrl); MoverParameters->eimic_real = eimic; - if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos == 0) + // Elf: full braking at once in the lowest position, and in the emergency brake position below it + if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos <= MoverParameters->EIMCtrlEmergencyPositions()) eimic = -1.0; MoverParameters->SendCtrlToNext("EIMIC", std::max(0., eimic), MoverParameters->CabActive); auto LBR = std::max(-eimic, 0.); From 636d29eb228f8ccb5737cb558168be45bd8a10f8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sat, 7 Nov 2026 21:53:25 +0100 Subject: [PATCH 02/37] fix: AI wagon inspector sets G/P/R by the instruction Cw-1 (eu07/maszyna#350) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The brake settings the AI chooses for a train (TController::AutoRewident) now follow Cw-1 (Mw56) §18 and §19: - freight trains: the 500 m / 1300 t and 300 m / 600 t limits apply to the wagons without the locomotives, limits included; - long locomotive setting: the five wagons on G are counted from the head of the train, not again after every locomotive in it; - a vehicle without the setting the train needs gets the other of G and P; - passenger trains run on R only with at most three cars on P, fewer than those on R; cars with a magnetic rail brake run on R+Mg. The choice moves to vehicle/brakesetting.{h,cpp} in eu07_core, with unit tests. The old inspector stays behind the new eu07.ini key ai.brakesetting.cw1 (default yes; no restores the earlier behaviour). No game data changes needed. (eu07/maszyna#350) --- CMakeLists.txt | 1 + tests/unit/test_brake_setting.cpp | 171 +++++++++++++++++++++++ utilities/Globals.cpp | 7 + utilities/Globals.h | 1 + vehicle/Driver.cpp | 123 ++++------------- vehicle/brakesetting.cpp | 216 ++++++++++++++++++++++++++++++ vehicle/brakesetting.h | 57 ++++++++ 7 files changed, 477 insertions(+), 99 deletions(-) create mode 100644 tests/unit/test_brake_setting.cpp create mode 100644 vehicle/brakesetting.cpp create mode 100644 vehicle/brakesetting.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f34ad61f..c8422e62f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -462,6 +462,7 @@ set(CORE_SOURCES "utilities/parser.cpp" "utilities/utilities.cpp" "scripting/ladderlogic.cpp" +"vehicle/brakesetting.cpp" "vehicle/handover.cpp" "vehicle/horn.cpp" "vehicle/smoke.cpp" diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp new file mode 100644 index 000000000..7e598ad6e --- /dev/null +++ b/tests/unit/test_brake_setting.cpp @@ -0,0 +1,171 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "McZapkie/hamulce.h" +#include "vehicle/brakesetting.h" + +// the brake settings the AI wagon inspector (TController::AutoRewident) chooses for a train, by the +// brake instruction Cw-1 (Mw56) §18 and §19 (eu07/maszyna#350) + +namespace { + +using brake_setting::train_setting; + +constexpr int G{bdelay_G}; +constexpr int P{bdelay_P}; +constexpr int R{bdelay_R}; +constexpr int M{bdelay_M}; + +brake_setting::vehicle locomotive(int const Delays = G | P | R) { + return {Delays, true, 17.0, 80000.0}; +} +// a freight wagon of the given length [m] and mass [t] +brake_setting::vehicle freight_wagon(double const Length = 15.0, double const Tonnes = 80.0) { + return {G | P, false, Length, Tonnes * 1000.0}; +} +brake_setting::vehicle passenger_car(int const Delays = P | R) { + return {Delays, false, 24.5, 45000.0}; +} + +std::vector train(brake_setting::vehicle const &Locomotive, int const Count, brake_setting::vehicle const &Wagon) { + std::vector consist{Locomotive}; + consist.insert(consist.end(), Count, Wagon); + return consist; +} + +} // namespace + +TEST_CASE("brake setting: a freight train runs on P only up to 500 m and 1300 t of wagons (Cw-1 §19.2)") { + // 25 wagons of 20 m and 52 t: 500 m and 1300 t exactly, the limits included + CHECK(brake_setting::choose_train_setting(train(locomotive(), 25, freight_wagon(20.0, 52.0))) == train_setting::freight_gp); + // one metre longer + CHECK(brake_setting::choose_train_setting(train(locomotive(), 25, freight_wagon(20.04, 52.0))) == train_setting::freight_g); + // one tonne heavier + CHECK(brake_setting::choose_train_setting(train(locomotive(), 25, freight_wagon(20.0, 52.04))) == train_setting::freight_g); +} + +TEST_CASE("brake setting: the locomotives don't count into the length and mass of a freight train's wagons") { + // 300 m and 600 t of wagons behind two locomotives of 80 t: all the wagons on P (Cw-1 §19.3a) + auto consist{train(locomotive(), 20, freight_wagon(15.0, 30.0))}; + consist.insert(consist.begin(), locomotive()); + CHECK(brake_setting::choose_train_setting(consist) == train_setting::freight_p); + auto const settings{brake_setting::choose(consist)}; + CHECK(settings[0] == G); + CHECK(settings[1] == G); + for (std::size_t i = 2; i < settings.size(); ++i) { + CAPTURE(i); + CHECK(settings[i] == P); + } + // a wagon more makes it the long locomotive setting (Cw-1 §19.3b) + consist.emplace_back(freight_wagon(15.0, 30.0)); + CHECK(brake_setting::choose_train_setting(consist) == train_setting::freight_gp); +} + +TEST_CASE("brake setting: the locomotive and the first five wagons on G, the rest on P (Cw-1 §19.3b)") { + auto const consist{train(locomotive(), 12, freight_wagon(15.0, 60.0))}; + REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_gp); + auto const settings{brake_setting::choose(consist)}; + REQUIRE(settings.size() == consist.size()); + for (std::size_t i = 0; i < settings.size(); ++i) { + CAPTURE(i); + CHECK(settings[i] == (i <= 5 ? G : P)); + } +} + +TEST_CASE("brake setting: a locomotive in the middle of the train doesn't put five more wagons on G") { + auto consist{train(locomotive(), 8, freight_wagon(15.0, 60.0))}; + consist.emplace_back(locomotive()); + consist.insert(consist.end(), 8, freight_wagon(15.0, 60.0)); + REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_gp); + auto const settings{brake_setting::choose(consist)}; + CHECK(settings[1] == G); + CHECK(settings[5] == G); + CHECK(settings[6] == P); + CHECK(settings[9] == G); // the locomotive + CHECK(settings[10] == P); + + // the inspector of the earlier releases started counting anew at it + auto const legacy{brake_setting::choose_legacy(consist)}; + CHECK(legacy[10] == G); + CHECK(legacy[14] == G); + CHECK(legacy[15] == P); +} + +TEST_CASE("brake setting: a heavy freight train runs on G, a vehicle without G on P") { + auto consist{train(locomotive(), 30, freight_wagon(15.0, 80.0))}; + consist.emplace_back(passenger_car(P)); + REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_g); + auto const settings{brake_setting::choose(consist)}; + for (std::size_t i = 0; i + 1 < settings.size(); ++i) { + CAPTURE(i); + CHECK(settings[i] == G); + } + CHECK(settings.back() == P); +} + +TEST_CASE("brake setting: a vehicle without the setting the train needs gets the other one of G and P") { + // a light freight train with a wagon which has G only + auto consist{train(locomotive(), 4, freight_wagon(15.0, 20.0))}; + consist.emplace_back(G, false, 15.0, 20000.0); + REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_p); + CHECK(brake_setting::choose(consist).back() == G); + // and a vehicle with neither is left alone + consist.emplace_back(R, false, 15.0, 20000.0); + CHECK(brake_setting::choose(consist).back() == 0); +} + +TEST_CASE("brake setting: a passenger train on R carries at most three cars on P, fewer than those on R (Cw-1 §18.3)") { + auto consist{train(locomotive(), 4, passenger_car())}; + consist.insert(consist.end(), 3, passenger_car(P)); + CHECK(brake_setting::choose_train_setting(consist) == train_setting::passenger_r); + auto const settings{brake_setting::choose(consist)}; + CHECK(settings[0] == R); + CHECK(settings[1] == R); + CHECK(settings.back() == P); + + // as many cars on P as on R: all on P + consist.emplace_back(passenger_car(P)); + CHECK(brake_setting::choose_train_setting(consist) == train_setting::passenger_p); + for (auto const setting : brake_setting::choose(consist)) { + CHECK(setting == P); + } + // the inspector of the earlier releases kept such a train on R + CHECK(brake_setting::choose_legacy(consist)[1] == R); + + // four cars on P are too many even with more on R + consist.insert(consist.end(), 6, passenger_car()); + CHECK(brake_setting::choose_train_setting(consist) == train_setting::passenger_p); +} + +TEST_CASE("brake setting: freight wagons in a passenger train on R count as cars on P (Cw-1 §18.4)") { + auto consist{train(locomotive(), 6, passenger_car())}; + consist.emplace_back(freight_wagon()); + REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::passenger_r); + CHECK(brake_setting::choose(consist).back() == P); +} + +TEST_CASE("brake setting: cars with a magnetic rail brake run on R+Mg in a train on R (Cw-1 §18.2)") { + auto consist{train(locomotive(G | P | R | M), 3, passenger_car(P | R | M))}; + consist.emplace_back(passenger_car()); + REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::passenger_r); + auto const settings{brake_setting::choose(consist)}; + CHECK(settings[0] == R); // the locomotive stays on R + CHECK(settings[1] == (R | M)); + CHECK(settings.back() == R); +} + +TEST_CASE("brake setting: a light engine runs on R where it has it") { + std::vector const consist{locomotive(), locomotive(G | P)}; + CHECK(brake_setting::choose_train_setting(consist) == train_setting::light_engine); + auto const settings{brake_setting::choose(consist)}; + CHECK(settings[0] == R); + CHECK(settings[1] == P); +} + +TEST_CASE("brake setting: the inspector of the earlier releases counted the locomotives into the train's mass") { + // 300 m and 600 t of wagons: P by Cw-1, the long locomotive setting before + auto const consist{train(locomotive(), 20, freight_wagon(15.0, 30.0))}; + CHECK(brake_setting::choose(consist)[1] == P); + CHECK(brake_setting::choose_legacy(consist)[1] == G); + CHECK(brake_setting::choose_legacy(consist)[6] == P); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index b4f2e14be..9a3c81fc2 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -699,6 +699,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "ai.brakesetting.cw1") + { + ParseOne(Parser, AIBrakeSettingCw1, 1, false); + return true; + } + if (token == "pause") { std::string value; @@ -1590,6 +1596,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "scenario.time.current", ScenarioTimeCurrent ); export_as_text( Output, "scenario.weather.temperature", AirTemperature ); export_as_text( Output, "ai.trainman", AITrainman ); + export_as_text( Output, "ai.brakesetting.cw1", AIBrakeSettingCw1 ); export_as_text( Output, "scalespeculars", ScaleSpecularValues ); export_as_text( Output, "gfxrenderer", GfxRenderer ); export_as_text( Output, "shadows", RenderShadows ); diff --git a/utilities/Globals.h b/utilities/Globals.h index ad216cd96..31510aa34 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -130,6 +130,7 @@ struct global_settings { bool bJoinEvents{ false }; // czy grupować eventy o tych samych nazwach int iHiddenEvents{ 1 }; // czy łączyć eventy z torami poprzez nazwę toru bool AITrainman{ true }; // virtual assistant performing consist coupling/decoupling and other maintenance tasks + bool AIBrakeSettingCw1{ true }; // ai.brakesetting.cw1: the AI wagon inspector sets the brakes (G/P/R/Mg) by the instruction Cw-1, no: as before eu07/maszyna#350 // ui int PythonScreenUpdateRate{ 200 }; // delay between python-based screen updates, in milliseconds int iTextMode{ 0 }; // tryb pracy wyświetlacza tekstowego diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 9f83b6d53..db6a8b7fd 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "utilities/Logs.h" #include "vehicle/Train.h" +#include "vehicle/brakesetting.h" #include "vehicle/handover.h" #include "world/mtable.h" #include "vehicle/DynObj.h" @@ -2080,106 +2081,30 @@ void TController::Activation() void TController::AutoRewident() { // autorewident: nastawianie hamulców w składzie - int r = 0, g = 0, p = 0; // ilości wagonów poszczególnych typów - TDynamicObject *d = pVehicles[0]; // pojazd na czele składu - // 1. Zebranie informacji o składzie pociągu — przejście wzdłuż składu i odczyt parametrów: - // · ilość wagonów -> są zliczane, wszystkich pojazdów jest (iVehicles) - // · długość (jako suma) -> jest w (fLength) - // · masa (jako suma) -> jest w (fMass) - while (d) - { // klasyfikacja pojazdów wg BrakeDelays i mocy (licznik) - if (d->MoverParameters->Power < 1) // - lokomotywa - Power>1 - ale może być nieczynna na końcu... - if (TestFlag(d->MoverParameters->BrakeDelays, bdelay_R)) - ++r; // - wagon pospieszny - jest R - else if (TestFlag(d->MoverParameters->BrakeDelays, bdelay_G)) - ++g; // - wagon towarowy - jest G (nie ma R) - else - ++p; // - wagon osobowy - reszta (bez G i bez R) - d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + // 1. Zebranie informacji o składzie pociągu, od czoła do końca + std::vector consist; + for (auto const *d = pVehicles[0]; d != nullptr; d = d->Next()) { + auto const *mover{d->MoverParameters}; + // a locomotive has Power > 1, though it may be a dead one at the end of the train + consist.emplace_back(mover->BrakeDelays, mover->Power >= 1.0, mover->Dim.L, mover->TotalMass); } - // 2. Określenie typu pociągu i nastawy: - int ustaw; //+16 dla pasażerskiego - if (r + g + p == 0) - ustaw = 16 + bdelay_R; // lokomotywa luzem (może być wieloczłonowa) - else - { // jeśli są wagony - ustaw = g < std::min(4, r + p) ? 16 : 0; - if (ustaw) // jeśli towarowe < Min(4, pospieszne+osobowe) - { // to skład pasażerski - nastawianie pasażerskiego - ustaw += g && r < g + p ? bdelay_P : bdelay_R; - // jeżeli towarowe>0 oraz pospiesze<=towarowe+osobowe to P (0) - // inaczej R (2) - } - else - { // inaczej towarowy - nastawianie towarowego - if (fLength < 300.0 && fMass < 600000.0) //[kg] - ustaw |= bdelay_P; // jeżeli długość<300 oraz masa<600 to P (0) - else if (fLength < 500.0 && fMass < 1300000.0) - ustaw |= bdelay_R; // jeżeli długość<500 oraz masa<1300 to GP (2) - else - ustaw |= bdelay_G; // inaczej G (1) - } - // zasadniczo na sieci PKP kilka lat temu na P/GP jeździły tylko kontenerowce o - // rozkładowej 90 km/h. Pozostałe jeździły 70 km/h i były nastawione na G. - } - d = pVehicles[0]; // pojazd na czele składu - p = 0; // będziemy tu liczyć wagony od lokomotywy dla nastawy GP - while (d) - { // 3. Nastawianie - if( true == AIControllFlag - || d != pVehicle ) { + // 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did + auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist) : brake_setting::choose_legacy(consist)}; + // a light engine counts as a passenger train for the braking below + auto const passengertrain{brake_setting::passenger(brake_setting::choose_train_setting(consist))}; + // 3. Nastawianie + auto setting{settings.begin()}; + for (auto *d = pVehicles[0]; d != nullptr && setting != settings.end(); d = d->Next(), ++setting) { + if (false == AIControllFlag && d == pVehicle) { // don't touch human-controlled vehicle, but others are free game - switch( ustaw ) { - - case bdelay_P: { - // towarowy P - lokomotywa na G, reszta na P. - d->MoverParameters->BrakeDelaySwitch( - d->MoverParameters->Power > 1 ? - bdelay_G : - bdelay_P ); - break; - } - case bdelay_G: { - // towarowy G - wszystko na G, jeśli nie ma to P (powinno się wyłączyć hamulec) - d->MoverParameters->BrakeDelaySwitch( - TestFlag( d->MoverParameters->BrakeDelays, bdelay_G ) ? - bdelay_G : - bdelay_P ); - break; - } - case bdelay_R: { - // towarowy GP - lokomotywa oraz 5 pierwszych pojazdów przy niej na G, reszta na P - if( d->MoverParameters->Power > 1 ) { - d->MoverParameters->BrakeDelaySwitch( bdelay_G ); - p = 0; // a jak będzie druga w środku? - } - else { - d->MoverParameters->BrakeDelaySwitch( - ++p <= 5 ? - bdelay_G : - bdelay_P ); - } - break; - } - case 16 + bdelay_R: { - // pasażerski R - na R, jeśli nie ma to P - d->MoverParameters->BrakeDelaySwitch( - TestFlag( d->MoverParameters->BrakeDelays, bdelay_R ) ? - bdelay_R : - bdelay_P ); - break; - } - case 16 + bdelay_P: { - // pasażerski P - wszystko na P - d->MoverParameters->BrakeDelaySwitch( bdelay_P ); - break; - } - } - // potentially release manual brake - d->MoverParameters->DecManualBrakeLevel( ManualBrakePosNo ); - d->MoverParameters->SpringBrake.Activate = false; + continue; } - d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + if (*setting != 0) { + d->MoverParameters->BrakeDelaySwitch(*setting); + } + // potentially release manual brake + d->MoverParameters->DecManualBrakeLevel( ManualBrakePosNo ); + d->MoverParameters->SpringBrake.Activate = false; } //ustawianie trybu pracy zadajnika hamulca, wystarczy raz po inicjalizacji AI if( true == AIControllFlag ) { @@ -2218,7 +2143,7 @@ void TController::AutoRewident() if( OrderCurrentGet() & ( Obey_train | Bank ) ) { // 4. Przeliczanie siły hamowania double const velstep = mvOccupied->Vmax * 0.5 / BrakeAccTableSize; - d = pVehicles[0]; // pojazd na czele składu + auto *d = pVehicles[0]; // pojazd na czele składu while (d) { for( int i = 0; i < BrakeAccTableSize; ++i ) { fBrake_a0[ i + 1 ] += d->MoverParameters->BrakeForceR( 0.25, velstep*( 1 + 2 * i ) ); @@ -2257,7 +2182,7 @@ void TController::AutoRewident() fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - 8 * fBrake_a1[ BrakeAccTableSize ] ); fBrakeReaction = 0.25; } - else if (ustaw > 16) { + else if (passengertrain) { fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 4 * fBrake_a1[ BrakeAccTableSize ]; fBrakeReaction = 1.00 + fLength*0.004; } diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp new file mode 100644 index 000000000..785bfbd6d --- /dev/null +++ b/vehicle/brakesetting.cpp @@ -0,0 +1,216 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/brakesetting.h" + +#include "McZapkie/hamulce.h" + +#include + +namespace brake_setting { + +namespace { + +// the limits of Cw-1 §19.2 and §19.3 for the wagons of a freight train (the "skład pociągu", without +// the locomotives) +constexpr double freight_p_max_length{500.0}; // [m] +constexpr double freight_p_max_mass{1300000.0}; // [kg] +constexpr double freight_p_all_max_length{300.0}; // [m] +constexpr double freight_p_all_max_mass{600000.0}; // [kg] + +// the most P-braked vehicles a passenger train on R may carry (Cw-1 §18.3, §18.4) +constexpr int passenger_r_max_p_wagons{3}; + +bool has(int const Delays, int const Setting) { + return (Delays & Setting) == Setting; +} + +// Wanted when the vehicle has it, else Fallback when it has that, else 0 +int pick(int const Delays, int const Wanted, int const Fallback) { + if (has(Delays, Wanted)) { + return Wanted; + } + if (has(Delays, Fallback)) { + return Fallback; + } + return 0; +} + +// the wagons of the train by the fastest setting they have +struct wagon_counts { + int r{0}; // with R: passenger cars of fast trains + int g{0}; // with G but no R: freight wagons + int p{0}; // the rest: passenger cars with P only + double length{0.0}; // [m] + double mass{0.0}; // [kg] + + explicit wagon_counts(std::vector const &Consist) { + for (auto const &item : Consist) { + if (item.powered) { + continue; + } + length += item.length; + mass += item.mass; + if (has(item.delays, bdelay_R)) { + ++r; + } + else if (has(item.delays, bdelay_G)) { + ++g; + } + else { + ++p; + } + } + } + + int wagons() const { + return r + g + p; + } + // a train is a passenger one unless it has at least as many freight wagons as there are others, + // or four of them (the inspector's rule of the earlier releases, Cw-1 doesn't tell) + bool passenger() const { + return g < std::min(4, r + p); + } +}; + +int passenger_r_setting(vehicle const &Item) { + if (false == Item.powered && has(Item.delays, bdelay_R | bdelay_M)) { + return bdelay_R | bdelay_M; + } + return pick(Item.delays, bdelay_R, bdelay_P); +} + +} // namespace + +train_setting choose_train_setting(std::vector const &Consist) { + wagon_counts const counts{Consist}; + if (counts.wagons() == 0) { + return train_setting::light_engine; + } + if (counts.passenger()) { + // wagons without R run on P, and there may be no more than three of them, fewer than those on R + auto const pwagons{counts.g + counts.p}; + return pwagons <= passenger_r_max_p_wagons && counts.r > pwagons ? train_setting::passenger_r : train_setting::passenger_p; + } + if (counts.length > freight_p_max_length || counts.mass > freight_p_max_mass) { + return train_setting::freight_g; + } + if (counts.length > freight_p_all_max_length || counts.mass > freight_p_all_max_mass) { + return train_setting::freight_gp; + } + return train_setting::freight_p; +} + +std::vector choose(std::vector const &Consist) { + auto const setting{choose_train_setting(Consist)}; + std::vector settings; + settings.reserve(Consist.size()); + auto wagonsfromhead{0}; + for (auto const &item : Consist) { + if (false == item.powered) { + ++wagonsfromhead; + } + switch (setting) { + case train_setting::light_engine: { + settings.emplace_back(pick(item.delays, bdelay_R, bdelay_P)); + break; + } + case train_setting::passenger_r: { + settings.emplace_back(passenger_r_setting(item)); + break; + } + case train_setting::passenger_p: { + settings.emplace_back(pick(item.delays, bdelay_P, bdelay_P)); + break; + } + case train_setting::freight_p: { + settings.emplace_back(item.powered ? pick(item.delays, bdelay_G, bdelay_P) : pick(item.delays, bdelay_P, bdelay_G)); + break; + } + case train_setting::freight_gp: { + // the wagons are counted from the head of the train, past any locomotive in the middle of it + auto const ong{item.powered || wagonsfromhead <= freight_gp_wagons_on_g}; + settings.emplace_back(ong ? pick(item.delays, bdelay_G, bdelay_P) : pick(item.delays, bdelay_P, bdelay_G)); + break; + } + case train_setting::freight_g: + default: { + settings.emplace_back(pick(item.delays, bdelay_G, bdelay_P)); + break; + } + } + } + return settings; +} + +std::vector choose_legacy(std::vector const &Consist) { + wagon_counts const counts{Consist}; + auto length{0.0}; + auto mass{0.0}; + for (auto const &item : Consist) { + length += item.length; + mass += item.mass; + } + auto setting{train_setting::light_engine}; + if (counts.wagons() > 0) { + if (counts.passenger()) { + setting = counts.g && counts.r < counts.g + counts.p ? train_setting::passenger_p : train_setting::passenger_r; + } + else if (length < 300.0 && mass < 600000.0) { + setting = train_setting::freight_p; + } + else if (length < 500.0 && mass < 1300000.0) { + setting = train_setting::freight_gp; + } + else { + setting = train_setting::freight_g; + } + } + std::vector settings; + settings.reserve(Consist.size()); + auto wagonsfromloco{0}; + for (auto const &item : Consist) { + switch (setting) { + case train_setting::light_engine: + case train_setting::passenger_r: { + settings.emplace_back(has(item.delays, bdelay_R) ? bdelay_R : bdelay_P); + break; + } + case train_setting::passenger_p: { + settings.emplace_back(bdelay_P); + break; + } + case train_setting::freight_p: { + settings.emplace_back(item.powered ? bdelay_G : bdelay_P); + break; + } + case train_setting::freight_gp: { + // the count started anew at every locomotive + if (item.powered) { + wagonsfromloco = 0; + settings.emplace_back(bdelay_G); + } + else { + ++wagonsfromloco; + settings.emplace_back(wagonsfromloco <= freight_gp_wagons_on_g ? bdelay_G : bdelay_P); + } + break; + } + case train_setting::freight_g: + default: { + settings.emplace_back(has(item.delays, bdelay_G) ? bdelay_G : bdelay_P); + break; + } + } + } + return settings; +} + +} // namespace brake_setting diff --git a/vehicle/brakesetting.h b/vehicle/brakesetting.h new file mode 100644 index 000000000..cfb421d55 --- /dev/null +++ b/vehicle/brakesetting.h @@ -0,0 +1,57 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +// the brake setting (G/P/R/Mg) the virtual wagon inspector (TController::AutoRewident) chooses for every +// vehicle of a train, by the rules of the brake instruction Cw-1 (Mw56), §18 and §19 (eu07/maszyna#350) +namespace brake_setting { + +// what the inspector needs to know about a vehicle of the train +struct vehicle { + int delays{0}; // the settings the vehicle has (BrakeDelays, a combination of bdelay_*) + bool powered{false}; // a locomotive or a powered unit, as opposed to a wagon + double length{0.0}; // [m] + double mass{0.0}; // with its load [kg] +}; + +// the kind of train the inspector takes the consist for, and how it sets the brakes +enum class train_setting { + light_engine, // no wagons: R where there is one, else P + passenger_r, // passenger train on R, wagons with Mg on R+Mg (Cw-1 §18.2) + passenger_p, // passenger train on P (Cw-1 §18.3, §18.4) + freight_p, // freight train on P: locomotives on G, wagons on P (Cw-1 §19.3a) + freight_gp, // freight train on P: locomotives and the first five wagons on G, the rest on P (Cw-1 §19.3b) + freight_g // freight train on G (Cw-1 §19.1) +}; + +// how many wagons next to the locomotive stay on G in a freight_gp train +inline constexpr int freight_gp_wagons_on_g{5}; + +// the train setting by Cw-1. Consist runs from the head of the train to its rear +train_setting choose_train_setting(std::vector const &Consist); + +// a passenger train or a light engine, as opposed to a freight train. the inspector of the earlier +// releases tells them apart the same way +constexpr bool passenger(train_setting const Setting) { + return Setting == train_setting::light_engine || Setting == train_setting::passenger_r || Setting == train_setting::passenger_p; +} + +// the brake setting (bdelay_*) for every vehicle of Consist, in the same order, by Cw-1. a vehicle +// without the setting the train needs gets the other one of G and P it has, and 0 (left as it is) +// when it has neither. Cw-1 §19.9 would have the brake of such a vehicle cut out instead +std::vector choose(std::vector const &Consist); + +// the inspector of the releases before eu07/maszyna#350, kept for ai.brakesetting.cw1 no. the settings +// are requests: a vehicle which doesn't have the one asked for keeps its own +std::vector choose_legacy(std::vector const &Consist); + +} // namespace brake_setting From 6dc42e976fae695205c707fbbb4ec411eec12e61 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sat, 7 Nov 2026 22:08:42 +0100 Subject: [PATCH 03/37] feat: keep the vehicle odometers between the sessions (#72) Every vehicle gets an odometer (TMoverParameters::Odometer) counting along with the per-session DistCounter, starting from its state saved in eu07_odometers.txt in the user's settings directory, else from the file a python screen kept it in (kilometry/_przebieg.txt), else from a state made up from the vehicle name. The store is saved every minute of simulation time and on closing. The cab's distcounter: gauge shows the odometer; its .mmd offset seeds a vehicle with no known state. Python screens get it as state["odometer_total"]; state["odometer"] stays the session distance the logbook and mirror scripts count differences of. --- CMakeLists.txt | 1 + McZapkie/MOVER.h | 2 + McZapkie/Mover.cpp | 2 + application/application.cpp | 2 + tests/unit/test_odometer.cpp | 199 +++++++++++++++++++++++++++++++ vehicle/DynObj.cpp | 23 ++++ vehicle/DynObj.h | 5 + vehicle/Gauge.h | 7 ++ vehicle/Train.cpp | 10 +- vehicle/odometer.cpp | 225 +++++++++++++++++++++++++++++++++++ vehicle/odometer.h | 94 +++++++++++++++ 11 files changed, 568 insertions(+), 2 deletions(-) create mode 100644 tests/unit/test_odometer.cpp create mode 100644 vehicle/odometer.cpp create mode 100644 vehicle/odometer.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f34ad61f..d3152915e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -465,6 +465,7 @@ set(CORE_SOURCES "vehicle/handover.cpp" "vehicle/horn.cpp" "vehicle/smoke.cpp" +"vehicle/odometer.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 16bb207fa..1f7942e84 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include "hamulce.h" #include "scripting/ladderlogic.h" +#include "vehicle/odometer.h" class cParser; /* @@ -1963,6 +1964,7 @@ class TMoverParameters int SoundFlag = 0; /*!o patrz stale sound_ */ int AIFlag{0}; // HACK: events of interest for consist owner double DistCounter = 0.0; /*! licznik kilometrow */ + odometer::reading Odometer; // total distance run, kept between the sessions (eu07/maszyna#72) std::pair EnergyMeter; // energy from grid [kWh] double V = 0.0; // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) double Vel = 0.0; // moduł prędkości w [km/h], używany przez AI diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 20761bacb..48a36ccb6 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1510,6 +1510,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap dL)}; DistCounter += fabs(dL) / 1000.0; + Odometer.run(dL); dL = 0; // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze @@ -1576,6 +1577,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh dL)}; DistCounter += fabs(dL) / 1000.0; + Odometer.run(dL); dL = 0; // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze diff --git a/application/application.cpp b/application/application.cpp index 9b7b82853..bd0526269 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -708,6 +708,8 @@ void eu07_application::exit() m_network.reset(); // SafeDelete( simulation::Train ); + step("the odometers"); + simulation::Vehicles.save_odometers(); step("the scenery"); SafeDelete(simulation::Region); diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp new file mode 100644 index 000000000..8297d3167 --- /dev/null +++ b/tests/unit/test_odometer.cpp @@ -0,0 +1,199 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "vehicle/odometer.h" + +#include +#include +#include + +// the odometer of a vehicle, kept between the sessions (eu07/maszyna#72): one state the cab's counters and the +// python screens show, saved in one store, taking over the states the python screens kept in their own files + +namespace { + +odometer::reading started(double const Km, odometer::origin const Source = odometer::origin::saved) { + odometer::reading reading; + reading.begin(Km, Source); + return reading; +} + +odometer::reading run(double const Km, double const Metres) { + auto reading{started(Km)}; + reading.run(Metres); + return reading; +} + +// a directory of its own for a test, removed afterwards +struct scratch_directory { + std::filesystem::path path; + explicit scratch_directory(std::string const &Name) : path{std::filesystem::temp_directory_path() / ("eu07_unit_" + Name)} { + std::filesystem::remove_all(path); + std::filesystem::create_directories(path); + } + ~scratch_directory() { + std::error_code error; + std::filesystem::remove_all(path, error); + } +}; + +void write_file(std::filesystem::path const &Path, std::string const &Content) { + std::filesystem::create_directories(Path.parent_path()); + std::ofstream{Path, std::ios::binary} << Content; +} + +} // namespace + +TEST_CASE("odometer: a vehicle counts the distance it runs either way, as the session's counter does") { + for (auto const velocity : {40.0, -40.0}) { + CAPTURE(velocity); + test::vehicle vehicle{test::definition::load("wagon"), velocity}; + vehicle->Odometer.begin(123456.0, odometer::origin::saved); + vehicle.run(10.0); + CHECK(vehicle->DistCounter > 0.05); + CHECK(vehicle->Odometer.km - 123456.0 == doctest::Approx(vehicle->DistCounter)); + CHECK(vehicle->Odometer.start == 123456.0); + CHECK(vehicle->Odometer.moved()); + } +} + +TEST_CASE("odometer: the store reads back what it writes") { + odometer::store store; + store.record("EN76-012a", run(1361539.4283, 1000.0)); + store.record("loco with spaces", run(42.0, 500.0)); + CHECK(store.modified()); + + std::stringstream file; + store.write(file); + odometer::store read; + CHECK(read.read(file) == 2); + CHECK(read.find("EN76-012a").value() == doctest::Approx(1361540.4283)); + CHECK(read.find("loco with spaces").value() == doctest::Approx(42.5)); + CHECK_FALSE(read.find("EN76-012").has_value()); + CHECK_FALSE(read.modified()); +} + +TEST_CASE("odometer: the store skips the comments and the malformed lines") { + std::stringstream file{"# comment\r\n" + "100.5 good\r\n" + "\n" + "nonsense\n" + "abc name\n" + "-5 negative\n" + "nan notanumber\n" + "7 \n" + "200\ttabbed\n"}; + odometer::store store; + CHECK(store.read(file) == 2); + CHECK(store.find("good").value() == 100.5); + CHECK(store.find("tabbed").value() == 200.0); + CHECK(store.size() == 2); +} + +TEST_CASE("odometer: a vehicle gets in the store once it has run, then it's kept up to date") { + odometer::store store; + SUBCASE("a vehicle which only stood doesn't get in") { + store.record("standing", started(5000.0, odometer::origin::guessed)); + CHECK_FALSE(store.find("standing").has_value()); + CHECK_FALSE(store.modified()); + } + SUBCASE("one which ran does") { + store.record("running", run(5000.0, 250.0)); + CHECK(store.find("running").value() == doctest::Approx(5000.25)); + CHECK(store.modified()); + } + SUBCASE("one already in the store follows its state, and an unchanged one doesn't make the store modified") { + std::stringstream file{"300 known\n"}; + store.read(file); + store.record("known", started(300.0)); + CHECK_FALSE(store.modified()); + store.record("known", run(300.0, 1000.0)); + CHECK(store.find("known").value() == doctest::Approx(301.0)); + CHECK(store.modified()); + store.saved(); + CHECK_FALSE(store.modified()); + } + SUBCASE("a nameless vehicle doesn't") { + store.record("", run(1.0, 1000.0)); + CHECK(store.size() == 0); + } +} + +TEST_CASE("odometer: the state the python screens kept is read") { + auto const legacy = [](std::string const &Content) { + std::stringstream file{Content}; + return odometer::read_legacy(file); + }; + // written as python's str() of a float + CHECK(legacy("1361539.4283109533").value() == doctest::Approx(1361539.4283109533)); + CHECK(legacy("170650.0\n").value() == 170650.0); + CHECK(legacy(" 5000 ").value() == 5000.0); + CHECK_FALSE(legacy("").has_value()); + CHECK_FALSE(legacy("12 km").has_value()); + CHECK_FALSE(legacy("inf").has_value()); +} + +TEST_CASE("odometer: the state starts from the store, else the python screens' file, else a guess") { + scratch_directory directory{"odometer_legacy"}; + // the python screens dropped the last letter of the vehicle name: the units of the EN76 shared the file + write_file(directory.path / "kilometry" / "EN76-012_przebieg.txt", "1361539.5"); + std::stringstream file{"2000 EN76-012b\n"}; + odometer::store store; + store.read(file); + + auto const saved{odometer::starting_state(store, "EN76-012b", directory.path)}; + CHECK(saved.source == odometer::origin::saved); + CHECK(saved.km == 2000.0); + + auto const legacy{odometer::starting_state(store, "EN76-012a", directory.path)}; + CHECK(legacy.source == odometer::origin::legacy); + CHECK(legacy.km == 1361539.5); + CHECK(legacy.start == legacy.km); + + auto const guessed{odometer::starting_state(store, "SM42-001", directory.path)}; + CHECK(guessed.source == odometer::origin::guessed); + CHECK(guessed.km == odometer::guessed_state("SM42-001")); + CHECK_FALSE(guessed.moved()); + + // an unreadable legacy file is no state + write_file(directory.path / "kilometry" / "ET22-100_przebieg.txt", ""); + CHECK(odometer::starting_state(store, "ET22-100a", directory.path).source == odometer::origin::guessed); +} + +TEST_CASE("odometer: a guessed state is the same for the same vehicle, in range") { + for (auto const *name : {"", "a", "EN57-1001ra", "ET22-100", "SM42-001"}) { + CAPTURE(name); + auto const state{odometer::guessed_state(name)}; + CHECK(state == odometer::guessed_state(name)); + CHECK(state >= 10000.0); + CHECK(state < 500000.0); + } + CHECK(odometer::guessed_state("ET22-100") != odometer::guessed_state("ET22-101")); +} + +TEST_CASE("odometer: the cab's counter offset replaces only a guessed state, the distance run kept") { + CHECK(odometer::counter_seed(101532.f, 1.f).value() == 101532.0); + CHECK(odometer::counter_seed(1015320.f, 10.f).value() == doctest::Approx(101532.0)); + CHECK_FALSE(odometer::counter_seed(0.f, 1.f).has_value()); + CHECK_FALSE(odometer::counter_seed(100.f, 0.f).has_value()); + CHECK_FALSE(odometer::counter_seed(-100.f, 1.f).has_value()); + + SUBCASE("guessed") { + auto reading{started(33333.0, odometer::origin::guessed)}; + reading.run(2000.0); + reading.seed(101532.0); + CHECK(reading.source == odometer::origin::counter); + CHECK(reading.start == 101532.0); + CHECK(reading.km == doctest::Approx(101534.0)); + // the next cab load doesn't seed it again + reading.seed(5.0); + CHECK(reading.start == 101532.0); + } + for (auto const source : {odometer::origin::saved, odometer::origin::legacy}) { + CAPTURE(static_cast(source)); + auto reading{started(777.0, source)}; + reading.seed(101532.0); + CHECK(reading.km == 777.0); + CHECK(reading.source == source); + } +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index d5f60e332..ff7587169 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/lightarray.h" #include "vehicle/Camera.h" #include "vehicle/Train.h" +#include "vehicle/odometer.h" #include "vehicle/Driver.h" #include "utilities/Globals.h" #include "utilities/Timer.h" @@ -1983,6 +1984,8 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" */ // utworzenie parametrów fizyki MoverParameters = new TMoverParameters(iDirection ? fVel : -fVel, Type_Name, asName, Cab); + // the vehicle carries on with the odometer state of its earlier sessions (eu07/maszyna#72) + MoverParameters->Odometer = odometer::starting_state( odometer::states(), asName, asBaseDir ); // McZapkie: TypeName musi byc nazwą CHK/MMD pojazdu if (!MoverParameters->LoadFIZ(asBaseDir)) { // jak wczytanie CHK się nie uda, to błąd @@ -8721,6 +8724,26 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { // jeśli jest coś do usunięcia z listy, to trzeba na końcu erase_disabled(); + + // the odometers are saved now and then, a crash doesn't lose more than the last minute + m_odometersavetimer += totaltime; + if( m_odometersavetimer >= 60.0 ) { + save_odometers(); + } +} + +// records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) +void +vehicle_table::save_odometers() { + + m_odometersavetimer = 0.0; + auto &odometers { odometer::states() }; + for( auto const *vehicle : m_items ) { + if( vehicle->MoverParameters != nullptr ) { + odometers.record( vehicle->name(), vehicle->MoverParameters->Odometer ); + } + } + odometer::save(); } // legacy method, checks for presence and height of traction wire for specified vehicle diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 577f0f020..b8eec1031 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -901,11 +901,16 @@ public: // legacy method, sends list of vehicles over network void DynamicList( bool const Onlycontrolled = false ) const; + // records the odometer states of the vehicles and saves them for the next sessions + void + save_odometers(); private: // maintenance; removes from tracks consists with vehicles marked as disabled bool erase_disabled(); + + double m_odometersavetimer { 0.0 }; // simulation time since the odometers were last saved }; diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index fdef9c58e..9aa539f15 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -55,6 +55,13 @@ public: void AssignBool(bool *bValue); void UpdateValue(); void AssignState( bool const *State ); + // the value shown is value * scale + offset + float offset() const { + return m_offset; } + void offset( float const Offset ) { + m_offset = Offset; } + float scale() const { + return m_scale; } // returns offset of submodel associated with the button from the model centre glm::vec3 model_offset() const; TGaugeType type() const; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index e30635f4f..5a918809a 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -796,7 +796,8 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("tractionforce", std::abs(mvOccupied->Ft)); dict->insert("slipping_wheels", mvOccupied->SlippingWheels); dict->insert("sanding", mvOccupied->SandDose); - dict->insert("odometer", mvOccupied->DistCounter); + dict->insert("odometer", mvOccupied->DistCounter); // distance run in the session, km + dict->insert("odometer_total", mvOccupied->Odometer.km); // the vehicle's odometer, kept between the sessions // electric current data dict->insert("traction_voltage", std::abs(mvPantographUnit->PantographVoltage)); dict->insert("voltage", std::abs(mvControlled->EngineVoltage)); @@ -12320,7 +12321,12 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // Ra 2014-07: licznik kilometrów auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->DistCounter); + // the counter shows the odometer of the vehicle, kept between the sessions (eu07/maszyna#72). its offset + // was the state it started each session with, now it is that only for a vehicle with no known state + if (auto const seed{odometer::counter_seed(gauge.offset(), gauge.scale())}) + mvControlled->Odometer.seed(*seed); + gauge.offset(0.f); + gauge.AssignDouble(&mvControlled->Odometer.km); } else if (Label == "shuntmodepower:") { diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp new file mode 100644 index 000000000..5f2a185d1 --- /dev/null +++ b/vehicle/odometer.cpp @@ -0,0 +1,225 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/odometer.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" + +#include +#include +#include +#include +#include + +namespace odometer { + +namespace { + +bool valid(double const Km) { + return std::isfinite(Km) && Km >= 0.0; +} + +// number making up all of the text, surrounding whitespace aside +std::optional parse_number(std::string const &Text) { + auto const first{Text.find_first_not_of(" \t\r\n")}; + if (first == std::string::npos) + return std::nullopt; + auto const last{Text.find_last_not_of(" \t\r\n")}; + auto const number{Text.substr(first, last - first + 1)}; + try { + std::size_t used{0}; + auto const value{std::stod(number, &used)}; + if (used != number.size() || false == valid(value)) + return std::nullopt; + return value; + } catch (std::exception const &) { + return std::nullopt; + } +} + +} // namespace + +void reading::begin(double const Km, origin const Source) { + km = Km; + start = Km; + source = Source; +} + +void reading::seed(double const Km) { + if (source != origin::guessed || false == valid(Km)) + return; + km += Km - start; + start = Km; + source = origin::counter; +} + +void reading::run(double const Metres) { + km += std::abs(Metres) / 1000.0; +} + +bool reading::moved() const { + return km != start; +} + +std::size_t store::read(std::istream &Input) { + std::size_t count{0}; + std::string line; + while (std::getline(Input, line)) { + if (false == line.empty() && line.back() == '\r') + line.pop_back(); + if (line.empty() || line.front() == '#') + continue; + // the name goes last, it's the rest of the line after the separator + auto const separator{line.find_first_of(" \t")}; + if (separator == std::string::npos) + continue; + auto const km{parse_number(line.substr(0, separator))}; + auto const name{line.substr(separator + 1)}; + if (false == km.has_value() || name.empty()) + continue; + m_states[name] = *km; + ++count; + } + return count; +} + +void store::write(std::ostream &Output) const { + Output << "# odometer states of the vehicles: \n"; + Output << std::fixed << std::setprecision(4); + for (auto const &[name, km] : m_states) + Output << km << ' ' << name << '\n'; +} + +std::optional store::find(std::string const &Vehicle) const { + auto const lookup{m_states.find(Vehicle)}; + if (lookup == m_states.end()) + return std::nullopt; + return lookup->second; +} + +void store::record(std::string const &Vehicle, reading const &Odometer) { + if (Vehicle.empty() || false == valid(Odometer.km)) + return; + auto const lookup{m_states.find(Vehicle)}; + if (lookup == m_states.end()) { + if (false == Odometer.moved()) + return; + m_states.emplace(Vehicle, Odometer.km); + m_modified = true; + return; + } + if (lookup->second == Odometer.km) + return; + lookup->second = Odometer.km; + m_modified = true; +} + +std::optional read_legacy(std::istream &Input) { + std::stringstream content; + content << Input.rdbuf(); + return parse_number(content.str()); +} + +std::optional legacy_state(std::filesystem::path const &Vehicledirectory, std::string const &Vehicle) { + if (Vehicle.size() < 2) + return std::nullopt; + auto const path{Vehicledirectory / "kilometry" / (Vehicle.substr(0, Vehicle.size() - 1) + "_przebieg.txt")}; + std::error_code error; + if (false == std::filesystem::is_regular_file(path, error)) + return std::nullopt; + std::ifstream input{path, std::ios::binary}; + if (false == input.is_open()) + return std::nullopt; + return read_legacy(input); +} + +double guessed_state(std::string const &Vehicle) { + // FNV-1a, stable between the builds unlike std::hash + std::uint64_t hash{14695981039346656037ull}; + for (auto const character : Vehicle) { + hash ^= static_cast(character); + hash *= 1099511628211ull; + } + return 10000.0 + static_cast(hash % 490000ull); +} + +reading starting_state(store const &States, std::string const &Vehicle, std::filesystem::path const &Vehicledirectory) { + reading result; + if (auto const saved{States.find(Vehicle)}) { + result.begin(*saved, origin::saved); + } else if (auto const legacy{legacy_state(Vehicledirectory, Vehicle)}) { + result.begin(*legacy, origin::legacy); + } else { + result.begin(guessed_state(Vehicle), origin::guessed); + } + return result; +} + +std::optional counter_seed(float const Offset, float const Scale) { + if (Offset == 0.f || Scale == 0.f) + return std::nullopt; + auto const km{static_cast(Offset) / static_cast(Scale)}; + if (false == valid(km)) + return std::nullopt; + return km; +} + +std::filesystem::path file() { + auto path{user_config_path("eu07_odometers.txt")}; + return path.empty() ? std::filesystem::path{"eu07_odometers.txt"} : path; +} + +store &states() { + static store odometers = [] { + store result; + std::ifstream input{file(), std::ios::binary}; + if (input.is_open()) { + auto const count{result.read(input)}; + WriteLog("Odometer states of " + std::to_string(count) + " vehicles read from \"" + file().string() + "\""); + } + return result; + }(); + return odometers; +} + +bool save() { + auto &odometers{states()}; + if (false == odometers.modified()) + return true; + auto const path{file()}; + std::error_code error; + if (path.has_parent_path()) + std::filesystem::create_directories(path.parent_path(), error); + // written aside first, a crash in the middle of a write doesn't lose the states + auto temporary{path}; + temporary += ".tmp"; + { + std::ofstream output{temporary, std::ios::binary | std::ios::trunc}; + if (false == output.is_open()) { + ErrorLog("Failed to save the odometer states to \"" + temporary.string() + "\""); + return false; + } + odometers.write(output); + if (false == output.good()) { + ErrorLog("Failed to save the odometer states to \"" + temporary.string() + "\""); + return false; + } + } + std::filesystem::rename(temporary, path, error); + if (error) { + ErrorLog("Failed to save the odometer states to \"" + path.string() + "\": " + error.message()); + return false; + } + odometers.saved(); + return true; +} + +} // namespace odometer diff --git a/vehicle/odometer.h b/vehicle/odometer.h new file mode 100644 index 000000000..65313c34b --- /dev/null +++ b/vehicle/odometer.h @@ -0,0 +1,94 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include + +// the odometer of a vehicle: the total distance it has run, kept between the sessions (eu07/maszyna#72). +// the analog counters in the cab (distcounter:) and the python screens (state["odometer_total"]) show +// this one state, instead of the counters starting from their .mmd offset and the screens each keeping +// their own files +namespace odometer { + +// where the state of a vehicle came from +enum class origin { + saved, // the odometer store of the earlier sessions + legacy, // the file a python screen kept it in before + counter, // the offset of the cab's counter, which used to show it on top of the distance run in the session + guessed // nothing known, a made up state which the cab's counter can still replace +}; + +// odometer of one vehicle +struct reading { + double km{0.0}; // the state, km + double start{0.0}; // the state at the start of the session, km + origin source{origin::guessed}; + + // sets the state the vehicle starts the session with + void begin(double Km, origin Source); + // replaces a guessed state with the one the cab's counter showed at the start, the distance run kept. + // a known state stays + void seed(double Km); + // counts the distance run, in metres either way + void run(double Metres); + // the vehicle has run in this session + bool moved() const; +}; + +// the saved odometer states of the vehicles, km by vehicle name +class store { +public: + // reads the states written by write(). lines " ", '#' starts a comment line, a malformed + // line is skipped. returns the number of states read + std::size_t read(std::istream &Input); + void write(std::ostream &Output) const; + + std::optional find(std::string const &Vehicle) const; + // records the state of a vehicle. one not in the store yet gets in only once it has run, so the vehicles + // standing in the sceneries don't fill the file + void record(std::string const &Vehicle, reading const &Odometer); + + // there are states recorded since they were last saved + bool modified() const { return m_modified; } + void saved() { m_modified = false; } + std::size_t size() const { return m_states.size(); } + +private: + std::map m_states; + bool m_modified{false}; +}; + +// state kept in the file of the python screens before (/kilometry/_przebieg.txt, +// where the screens dropped the last character of the vehicle name), when it holds a number +std::optional read_legacy(std::istream &Input); +std::optional legacy_state(std::filesystem::path const &Vehicledirectory, std::string const &Vehicle); + +// made up state of a vehicle nothing is known about: a number from the name, in [10 000, 500 000) km, +// the same each session until the vehicle runs and gets its state saved +double guessed_state(std::string const &Vehicle); + +// state a vehicle starts the session with: the saved one, else the legacy one, else a guessed one +reading starting_state(store const &States, std::string const &Vehicle, std::filesystem::path const &Vehicledirectory); + +// state the cab's counter with offset Offset and scale Scale shows, once its offset no longer applies +// (the counter shows the odometer). nothing for a counter without an offset +std::optional counter_seed(float Offset, float Scale); + +// the odometer store of the simulation, read from the user's settings directory on the first use +store &states(); +std::filesystem::path file(); +// writes the store when anything was recorded since. returns false when the write failed +bool save(); + +} // namespace odometer From 1083f3cb5db56af9775d975852d14dbacc0848f3 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 8 Nov 2026 04:23:30 +0100 Subject: [PATCH 04/37] fix: make the odometer test's scratch directory in the build directory for CI Sonar (S5443) flags the shared temporary directory; the tests now use one in their working directory. Also makes the scratch directory non-copyable and spells out the optional checks Sonar asked about. --- tests/unit/test_odometer.cpp | 7 +++++-- vehicle/Train.cpp | 2 +- vehicle/odometer.cpp | 4 ++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 8297d3167..784fabaab 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -24,13 +24,16 @@ odometer::reading run(double const Km, double const Metres) { return reading; } -// a directory of its own for a test, removed afterwards +// a directory of its own for a test, removed afterwards. it's made in the working directory of the tests (the build +// directory), not in the shared temporary one struct scratch_directory { std::filesystem::path path; - explicit scratch_directory(std::string const &Name) : path{std::filesystem::temp_directory_path() / ("eu07_unit_" + Name)} { + explicit scratch_directory(std::string const &Name) : path{std::filesystem::current_path() / ("eu07_unit_" + Name)} { std::filesystem::remove_all(path); std::filesystem::create_directories(path); } + scratch_directory(scratch_directory const &) = delete; + scratch_directory &operator=(scratch_directory const &) = delete; ~scratch_directory() { std::error_code error; std::filesystem::remove_all(path, error); diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 5a918809a..c48ef69c6 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -12323,7 +12323,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con gauge.Load(Parser, DynamicObject); // the counter shows the odometer of the vehicle, kept between the sessions (eu07/maszyna#72). its offset // was the state it started each session with, now it is that only for a vehicle with no known state - if (auto const seed{odometer::counter_seed(gauge.offset(), gauge.scale())}) + if (auto const seed{odometer::counter_seed(gauge.offset(), gauge.scale())}; seed.has_value()) mvControlled->Odometer.seed(*seed); gauge.offset(0.f); gauge.AssignDouble(&mvControlled->Odometer.km); diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index 5f2a185d1..9d03462b2 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -153,9 +153,9 @@ double guessed_state(std::string const &Vehicle) { reading starting_state(store const &States, std::string const &Vehicle, std::filesystem::path const &Vehicledirectory) { reading result; - if (auto const saved{States.find(Vehicle)}) { + if (auto const saved{States.find(Vehicle)}; saved.has_value()) { result.begin(*saved, origin::saved); - } else if (auto const legacy{legacy_state(Vehicledirectory, Vehicle)}) { + } else if (auto const legacy{legacy_state(Vehicledirectory, Vehicle)}; legacy.has_value()) { result.begin(*legacy, origin::legacy); } else { result.begin(guessed_state(Vehicle), origin::guessed); From 1e650e375a72d03ed4c68cd6a2619ab1c7529589 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 8 Nov 2026 12:32:28 +0100 Subject: [PATCH 05/37] docs: why the inspector puts a vehicle without G on P in a train on G (eu07/maszyna#350) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cw-1 §19.9 cuts the brake of such a vehicle out; the inspector keeps the earlier P, as it has no record to put a cut out brake back with. --- vehicle/brakesetting.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index 785bfbd6d..a55d3d751 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -142,6 +142,10 @@ std::vector choose(std::vector const &Consist) { } case train_setting::freight_g: default: { + // NOTE: Cw-1 §19.9 wants the brake of a vehicle without G (a passenger car with P and R only) cut out in a + // train braked on G. It's put on P instead, as before: a brake cut out by the inspector would have to be + // remembered and put back when the train is made up again, and the simulator has no such record yet. + // The same goes for the vehicles kept on G in the long locomotive setting above (freight_gp) settings.emplace_back(pick(item.delays, bdelay_G, bdelay_P)); break; } From 81f10e4d901ff54ac40331216f32086e5ec6e115 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 8 Nov 2026 13:03:06 +0100 Subject: [PATCH 06/37] fix: AI wagon inspector cuts out the brake of wagons without G in a train on G (eu07/maszyna#350) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cw-1 §19.9: in a freight train braked on G, the brake of a vehicle that has no G setting (e.g. a passenger car with P and R) is cut out. The inspector put such wagons on P; now it cuts their brake out the way the scenery's '0' flag does (b_dmg, the distributor's reservoirs emptied), so the brake releases and stays off. - The vehicle remembers the inspector cut it out (TMoverParameters::BrakeCutOutByInspector); the next inspection puts such a brake back and sets it to what the new train needs. A brake cut out for any other reason (scenery, player, damage) is never put back; the cab's cut-out toggle hands an inspector's cut-out over to the player. - Locomotives and the vehicle the train is driven from keep a working brake (on P). In the long locomotive setting (§19.3b) the train runs on P, so a wagon without G stays on P there. - The braking tables after the settings leave cut-out brakes out. - §18.3: a car with R whose brake is cut out counts as one on P. - ai.brakesetting.cw1 no keeps the earlier behaviour: nothing cut out. The choice and the cutting out stay in vehicle/brakesetting.{h,cpp}, with unit tests on real wagons. --- McZapkie/MOVER.h | 3 + tests/unit/test_brake_setting.cpp | 170 +++++++++++++++++++++++++++++- vehicle/Driver.cpp | 14 +-- vehicle/Train.cpp | 2 + vehicle/brakesetting.cpp | 77 ++++++++++++-- vehicle/brakesetting.h | 26 ++++- 6 files changed, 273 insertions(+), 19 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 16bb207fa..77a122467 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2060,6 +2060,9 @@ class TMoverParameters bool UnlockPipe = false; /*unlockig brake pipe button pressed*/ int BrakeDelayFlag = 0; /*nastawa opoznienia ham. osob/towar/posp/exp 0/1/2/4*/ int BrakeDelays = 0; /*nastawy mozliwe do uzyskania*/ + // the AI wagon inspector cut the brake out (b_dmg) and puts it back when the train no longer needs it + // cut out (brake_setting::apply). Anyone else cutting it out or putting it back takes it over + bool BrakeCutOutByInspector = false; int BrakeOpModeFlag = 0; /*nastawa trybu pracy PS/PN/EP/MED 1/2/4/8*/ int BrakeOpModes = 0; /*nastawy mozliwe do uzyskania*/ bool DynamicBrakeFlag = false; /*czy wlaczony hamulec elektrodymiczny*/ diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index 7e598ad6e..aba1e80bb 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -1,7 +1,9 @@ #include "stdafx.h" #include "doctest.h" +#include "McZapkie/MOVER.h" #include "McZapkie/hamulce.h" +#include "vehicle.h" #include "vehicle/brakesetting.h" // the brake settings the AI wagon inspector (TController::AutoRewident) chooses for a train, by the @@ -91,18 +93,182 @@ TEST_CASE("brake setting: a locomotive in the middle of the train doesn't put fi CHECK(legacy[15] == P); } -TEST_CASE("brake setting: a heavy freight train runs on G, a vehicle without G on P") { +TEST_CASE("brake setting: a heavy freight train runs on G, a wagon without G has its brake cut out (Cw-1 §19.9)") { auto consist{train(locomotive(), 30, freight_wagon(15.0, 80.0))}; consist.emplace_back(passenger_car(P)); + consist.emplace_back(passenger_car()); REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_g); auto const settings{brake_setting::choose(consist)}; - for (std::size_t i = 0; i + 1 < settings.size(); ++i) { + for (std::size_t i = 0; i + 2 < settings.size(); ++i) { CAPTURE(i); CHECK(settings[i] == G); } + CHECK(settings[settings.size() - 2] == brake_setting::cut_out); + CHECK(settings.back() == brake_setting::cut_out); + + // the inspector of the earlier releases put them on P + auto const legacy{brake_setting::choose_legacy(consist)}; + CHECK(legacy[settings.size() - 2] == P); + CHECK(legacy.back() == P); +} + +TEST_CASE("brake setting: in a train on G a locomotive and the vehicle it's driven from keep a working brake") { + auto consist{train(locomotive(P | R), 30, freight_wagon(15.0, 80.0))}; + // a dead locomotive without G at the end, and a car which tells no settings at all + consist.emplace_back(locomotive(P | R)); + consist.emplace_back(0, false, 20.0, 40000.0); + REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_g); + auto settings{brake_setting::choose(consist)}; + CHECK(settings.front() == P); + CHECK(settings[settings.size() - 2] == P); + CHECK(settings.back() == 0); + + // a control car without G, the train driven from it, pushed by the locomotive at the rear + brake_setting::vehicle controlcar{P | R, false, 24.5, 45000.0}; + controlcar.driven = true; + consist.front() = controlcar; + consist.back() = locomotive(); + settings = brake_setting::choose(consist); + CHECK(settings.front() == P); + CHECK(settings.back() == G); +} + +TEST_CASE("brake setting: in the long locomotive setting a vehicle without G brakes on P, not cut out (Cw-1 §19.3b)") { + // the train runs on P, so §19.9 doesn't apply to it, among the first five wagons kept on G or behind them + auto consist{train(locomotive(), 2, freight_wagon(15.0, 60.0))}; + consist.emplace_back(passenger_car()); + consist.insert(consist.end(), 8, freight_wagon(15.0, 60.0)); + consist.emplace_back(passenger_car()); + REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_gp); + auto const settings{brake_setting::choose(consist)}; + CHECK(settings[2] == G); + CHECK(settings[3] == P); + CHECK(settings[4] == G); + CHECK(settings[6] == P); CHECK(settings.back() == P); } +TEST_CASE("brake setting: a car with its brake cut out counts as one on P in a passenger train (Cw-1 §18.3)") { + auto consist{train(locomotive(), 5, passenger_car())}; + consist.insert(consist.end(), 3, passenger_car(P)); + REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::passenger_r); + // one car with R cut out makes four on P + consist[1].cut_out = true; + CHECK(brake_setting::choose_train_setting(consist) == train_setting::passenger_p); + // with fewer P-only cars, three on P and four on R still run on R + consist.pop_back(); + CHECK(brake_setting::choose_train_setting(consist) == train_setting::passenger_r); + // a cut out brake changes nothing about a train being a passenger or a freight one + auto freight{train(locomotive(), 4, freight_wagon())}; + freight.emplace_back(passenger_car()); + freight.back().cut_out = true; + CHECK(brake_setting::choose_train_setting(freight) == train_setting::freight_p); +} + +namespace { + +// a passenger car with P and R, with the KE distributor of the test wagon +test::definition passenger_car_definition() { + return test::definition::load("wagon").set("Cntrl", "BrakeDelays", "PR"); +} + +// charges the brake of the vehicle from a brake pipe at 5 bar, then makes a full service application +void charge_and_apply(test::vehicle &Vehicle) { + Vehicle.hold_brake_pipe(5.0); + Vehicle.run(90.0); + Vehicle.hold_brake_pipe(3.5); + Vehicle.run(20.0); +} + +// the inspector at work on a heavy train on G with the vehicle at its end, as AutoRewident() does it +int inspect_heavy_train(test::vehicle &Vehicle) { + auto consist{train(locomotive(), 30, freight_wagon(15.0, 80.0))}; + consist.emplace_back(brake_setting::describe(Vehicle.mover(), false)); + auto const setting{brake_setting::choose(consist).back()}; + brake_setting::apply(Vehicle.mover(), setting); + return setting; +} + +// the same on a light train, which runs on P +int inspect_light_train(test::vehicle &Vehicle) { + auto consist{train(locomotive(), 4, freight_wagon())}; + consist.emplace_back(brake_setting::describe(Vehicle.mover(), false)); + auto const setting{brake_setting::choose(consist).back()}; + brake_setting::apply(Vehicle.mover(), setting); + return setting; +} + +} // namespace + +TEST_CASE("brake setting: the inspector cuts the brake out in a train on G and puts it back in a train on P") { + test::vehicle car{passenger_car_definition()}; + charge_and_apply(car); + REQUIRE(car->BrakePress > 1.0); + + // made up into a heavy train on G: the brake is cut out and released + REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); + CHECK(brake_setting::is_cut_out(car.mover())); + CHECK(car->BrakeCutOutByInspector); + car.run(30.0); + CHECK(car->BrakePress < 0.1); + // and it stays off whatever the brake pipe does + car.hold_brake_pipe(5.0); + car.run(60.0); + car.hold_brake_pipe(3.5); + car.run(20.0); + CHECK(car->BrakePress < 0.1); + car.hold_brake_pipe(0.0); + car.run(20.0); + CHECK(car->BrakePress < 0.1); + // to the inspector looking at the train again it's a car like any other, and the train needs it cut out still + CHECK(false == brake_setting::describe(car.mover(), false).cut_out); + REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); + CHECK(car->BrakeCutOutByInspector); + + // made up into a light train: the brake is back on P, charges and brakes again + CHECK(inspect_light_train(car) == P); + CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == car->BrakeCutOutByInspector); + CHECK(car->BrakeDelayFlag == P); + // the reservoirs emptied when it was cut out take some five minutes to charge from the brake pipe + car.hold_brake_pipe(5.0); + car.run(300.0); + CHECK(car->Hamulec->GetBRP() > 4.9); + charge_and_apply(car); + CHECK(car->BrakePress > 1.0); +} + +TEST_CASE("brake setting: the inspector never puts back a brake cut out for another reason") { + test::vehicle car{passenger_car_definition()}; + charge_and_apply(car); + // cut out the way the scenery's '0' does it + car->Hamulec->ForceEmptiness(); + car->Hamulec->SetBrakeStatus(car->Hamulec->GetBrakeStatus() | b_dmg); + CHECK(brake_setting::describe(car.mover(), false).cut_out); + + // a train on G wants it cut out anyway: it isn't the inspector's to put back + CHECK(inspect_heavy_train(car) == brake_setting::cut_out); + CHECK(false == car->BrakeCutOutByInspector); + // a train on P would want it working: it stays cut out + CHECK(inspect_light_train(car) == P); + CHECK(brake_setting::is_cut_out(car.mover())); + charge_and_apply(car); + CHECK(car->BrakePress < 0.1); + + // a brake the inspector cut out, which someone else puts back and cuts out again, is theirs from then on + test::vehicle other{passenger_car_definition()}; + REQUIRE(inspect_heavy_train(other) == brake_setting::cut_out); + other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() & ~b_dmg); + CHECK(inspect_heavy_train(other) == brake_setting::cut_out); // the inspector cuts it out again, and it's its own again + CHECK(other->BrakeCutOutByInspector); + other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() & ~b_dmg); + CHECK(inspect_light_train(other) == P); + CHECK(false == other->BrakeCutOutByInspector); + other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() | b_dmg); + CHECK(inspect_light_train(other) == P); + CHECK(brake_setting::is_cut_out(other.mover())); +} + TEST_CASE("brake setting: a vehicle without the setting the train needs gets the other one of G and P") { // a light freight train with a wagon which has G only auto consist{train(locomotive(), 4, freight_wagon(15.0, 20.0))}; diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index db6a8b7fd..0bb569c81 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2084,9 +2084,7 @@ void TController::AutoRewident() // 1. Zebranie informacji o składzie pociągu, od czoła do końca std::vector consist; for (auto const *d = pVehicles[0]; d != nullptr; d = d->Next()) { - auto const *mover{d->MoverParameters}; - // a locomotive has Power > 1, though it may be a dead one at the end of the train - consist.emplace_back(mover->BrakeDelays, mover->Power >= 1.0, mover->Dim.L, mover->TotalMass); + consist.emplace_back(brake_setting::describe(*d->MoverParameters, d == pVehicle)); } // 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist) : brake_setting::choose_legacy(consist)}; @@ -2099,9 +2097,8 @@ void TController::AutoRewident() // don't touch human-controlled vehicle, but others are free game continue; } - if (*setting != 0) { - d->MoverParameters->BrakeDelaySwitch(*setting); - } + // the setting, a brake cut out in a train on G (Cw-1 §19.9) or put back when the train no longer needs it cut out + brake_setting::apply(*d->MoverParameters, *setting); // potentially release manual brake d->MoverParameters->DecManualBrakeLevel( ManualBrakePosNo ); d->MoverParameters->SpringBrake.Activate = false; @@ -2145,7 +2142,10 @@ void TController::AutoRewident() double const velstep = mvOccupied->Vmax * 0.5 / BrakeAccTableSize; auto *d = pVehicles[0]; // pojazd na czele składu while (d) { - for( int i = 0; i < BrakeAccTableSize; ++i ) { + // a vehicle with its brake cut out (by the inspector above or for a reason of its own) adds its mass only; + // the inspector of the earlier releases counted its brake in + auto const brakes{false == Global.AIBrakeSettingCw1 || false == brake_setting::is_cut_out(*d->MoverParameters)}; + for( int i = 0; i < BrakeAccTableSize && brakes; ++i ) { fBrake_a0[ i + 1 ] += d->MoverParameters->BrakeForceR( 0.25, velstep*( 1 + 2 * i ) ); fBrake_a1[ i + 1 ] += d->MoverParameters->BrakeForceR( 1.00, velstep*( 1 + 2 * i ) ); } diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index e30635f4f..004e8092c 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -2114,6 +2114,8 @@ void TTrain::OnCommand_trainbrakeoperationtoggle(TTrain *Train, command_data con } vehicle->MoverParameters->Hamulec->SetBrakeStatus(vehicle->MoverParameters->Hamulec->GetBrakeStatus() ^ b_dmg); + // the brake is the player's now, the wagon inspector won't put it back on its own + vehicle->MoverParameters->BrakeCutOutByInspector = false; } } diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index a55d3d751..bf42f8ab4 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/brakesetting.h" +#include "McZapkie/MOVER.h" #include "McZapkie/hamulce.h" #include @@ -48,6 +49,7 @@ struct wagon_counts { int r{0}; // with R: passenger cars of fast trains int g{0}; // with G but no R: freight wagons int p{0}; // the rest: passenger cars with P only + int r_cut_out{0}; // of those with R, the ones with their brake cut out double length{0.0}; // [m] double mass{0.0}; // [kg] @@ -60,6 +62,9 @@ struct wagon_counts { mass += item.mass; if (has(item.delays, bdelay_R)) { ++r; + if (item.cut_out) { + ++r_cut_out; + } } else if (has(item.delays, bdelay_G)) { ++g; @@ -95,9 +100,11 @@ train_setting choose_train_setting(std::vector const &Consist) { return train_setting::light_engine; } if (counts.passenger()) { - // wagons without R run on P, and there may be no more than three of them, fewer than those on R - auto const pwagons{counts.g + counts.p}; - return pwagons <= passenger_r_max_p_wagons && counts.r > pwagons ? train_setting::passenger_r : train_setting::passenger_p; + // wagons without R run on P, and a wagon with its brake cut out counts as one on P (Cw-1 §18.3). there may + // be no more than three of them, fewer than those on R + auto const pwagons{counts.g + counts.p + counts.r_cut_out}; + auto const rwagons{counts.r - counts.r_cut_out}; + return pwagons <= passenger_r_max_p_wagons && rwagons > pwagons ? train_setting::passenger_r : train_setting::passenger_p; } if (counts.length > freight_p_max_length || counts.mass > freight_p_max_mass) { return train_setting::freight_g; @@ -135,18 +142,27 @@ std::vector choose(std::vector const &Consist) { break; } case train_setting::freight_gp: { - // the wagons are counted from the head of the train, past any locomotive in the middle of it + // the wagons are counted from the head of the train, past any locomotive in the middle of it. + // the train runs on P (Cw-1 §19.3b), so §19.9 doesn't apply: a vehicle without G among the ones + // kept on G brakes on P like the rest of the train, rather than being cut out auto const ong{item.powered || wagonsfromhead <= freight_gp_wagons_on_g}; settings.emplace_back(ong ? pick(item.delays, bdelay_G, bdelay_P) : pick(item.delays, bdelay_P, bdelay_G)); break; } case train_setting::freight_g: default: { - // NOTE: Cw-1 §19.9 wants the brake of a vehicle without G (a passenger car with P and R only) cut out in a - // train braked on G. It's put on P instead, as before: a brake cut out by the inspector would have to be - // remembered and put back when the train is made up again, and the simulator has no such record yet. - // The same goes for the vehicles kept on G in the long locomotive setting above (freight_gp) - settings.emplace_back(pick(item.delays, bdelay_G, bdelay_P)); + if (has(item.delays, bdelay_G)) { + settings.emplace_back(bdelay_G); + } + else if (item.powered || item.driven || item.delays == 0) { + // a locomotive, or the vehicle the train is driven from, keeps a working brake: on P. a vehicle + // which tells no settings at all is left alone + settings.emplace_back(pick(item.delays, bdelay_P, bdelay_P)); + } + else { + // a wagon without G (a passenger car with P and R) has its brake cut out (Cw-1 §19.9) + settings.emplace_back(cut_out); + } break; } } @@ -217,4 +233,47 @@ std::vector choose_legacy(std::vector const &Consist) { return settings; } +bool is_cut_out(TMoverParameters const &Vehicle) { + return (Vehicle.Hamulec->GetBrakeStatus() & b_dmg) == b_dmg; +} + +vehicle describe(TMoverParameters const &Vehicle, bool const Driven) { + vehicle described; + described.delays = Vehicle.BrakeDelays; + // a locomotive has Power > 1, though it may be a dead one at the end of the train + described.powered = Vehicle.Power >= 1.0; + described.length = Vehicle.Dim.L; + described.mass = Vehicle.TotalMass; + described.cut_out = is_cut_out(Vehicle) && false == Vehicle.BrakeCutOutByInspector; + described.driven = Driven; + return described; +} + +void apply(TMoverParameters &Vehicle, int const Setting) { + auto &brake{*Vehicle.Hamulec}; + if (Vehicle.BrakeCutOutByInspector && false == is_cut_out(Vehicle)) { + // someone put the brake back in the meantime, it's theirs now + Vehicle.BrakeCutOutByInspector = false; + } + if (Setting == cut_out) { + if (false == is_cut_out(Vehicle)) { + // close the cut-out cock and empty the brake with the releaser, as the scenery's '0' does: the + // distributor, cut off the brake pipe, has no air left to brake with and lets the cylinders go + brake.ForceEmptiness(); + brake.SetBrakeStatus(brake.GetBrakeStatus() | b_dmg); + Vehicle.BrakeCutOutByInspector = true; + } + // a brake cut out already, by the inspector or for a reason of its own, stays as it is + return; + } + if (Vehicle.BrakeCutOutByInspector) { + // open the cut-out cock: the distributor charges from the brake pipe again + brake.SetBrakeStatus(brake.GetBrakeStatus() & ~b_dmg); + Vehicle.BrakeCutOutByInspector = false; + } + if (Setting != 0) { + Vehicle.BrakeDelaySwitch(Setting); + } +} + } // namespace brake_setting diff --git a/vehicle/brakesetting.h b/vehicle/brakesetting.h index cfb421d55..cce2bbeb0 100644 --- a/vehicle/brakesetting.h +++ b/vehicle/brakesetting.h @@ -11,6 +11,8 @@ http://mozilla.org/MPL/2.0/. #include +class TMoverParameters; + // the brake setting (G/P/R/Mg) the virtual wagon inspector (TController::AutoRewident) chooses for every // vehicle of a train, by the rules of the brake instruction Cw-1 (Mw56), §18 and §19 (eu07/maszyna#350) namespace brake_setting { @@ -21,6 +23,8 @@ struct vehicle { bool powered{false}; // a locomotive or a powered unit, as opposed to a wagon double length{0.0}; // [m] double mass{0.0}; // with its load [kg] + bool cut_out{false}; // the brake is cut out for a reason of its own (damage, the scenario, the player) + bool driven{false}; // the vehicle the train is driven from: its brake is never cut out }; // the kind of train the inspector takes the consist for, and how it sets the brakes @@ -36,6 +40,9 @@ enum class train_setting { // how many wagons next to the locomotive stay on G in a freight_gp train inline constexpr int freight_gp_wagons_on_g{5}; +// the setting choose() gives a vehicle whose brake is to be cut out (Cw-1 §19.9) +inline constexpr int cut_out{-1}; + // the train setting by Cw-1. Consist runs from the head of the train to its rear train_setting choose_train_setting(std::vector const &Consist); @@ -47,11 +54,28 @@ constexpr bool passenger(train_setting const Setting) { // the brake setting (bdelay_*) for every vehicle of Consist, in the same order, by Cw-1. a vehicle // without the setting the train needs gets the other one of G and P it has, and 0 (left as it is) -// when it has neither. Cw-1 §19.9 would have the brake of such a vehicle cut out instead +// when it has neither. In a train on G (freight_g) a wagon without G gets cut_out instead: its brake +// is to be cut out (Cw-1 §19.9). A locomotive and the vehicle the train is driven from keep their +// brake working, on P std::vector choose(std::vector const &Consist); // the inspector of the releases before eu07/maszyna#350, kept for ai.brakesetting.cw1 no. the settings // are requests: a vehicle which doesn't have the one asked for keeps its own std::vector choose_legacy(std::vector const &Consist); +// the brake of the vehicle is cut out (b_dmg), whoever did it +bool is_cut_out(TMoverParameters const &Vehicle); + +// what choose() needs to know of the vehicle. a brake the inspector cut out itself doesn't count as +// cut out: the inspector decides about it anew +vehicle describe(TMoverParameters const &Vehicle, bool Driven); + +// the inspector puts the vehicle on Setting, as choose() gives it. cut_out cuts the brake out the way +// the scenery's '0' does: b_dmg, which cuts the distributor off the brake pipe (as the cab's cut-out, +// trainbrakeoperationtoggle, does), and its reservoirs emptied, so the brake releases and stays off. +// The vehicle remembers the inspector did it. Any other setting first puts back a brake the inspector +// cut out (it charges from the brake pipe again), then sets the vehicle to it (0: leaves the setting +// as it is). A brake cut out by anyone else stays cut out +void apply(TMoverParameters &Vehicle, int Setting); + } // namespace brake_setting From 7db67c3ce71caf1c8e5e3ff34992750cb856fbaf Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 8 Nov 2026 18:03:13 +0100 Subject: [PATCH 07/37] fix: the inspector cuts brakes out only in a train at a standstill, R+Mg keeps the rapid stage (review of #282) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - §19.9 cut-outs only when the AI runs the consist as a train (Obey_train); in shunting a wagon without G brakes on P, which also puts back a brake the inspector cut out before - no new cut-out while the consist moves: left to the next inspection at a standstill (putting back still happens) - ESt4R, LSt and EStED test the bit of R, so R+Mg keeps the high-speed stage of R as on the KE and Oerlikon valves --- McZapkie/hamulce.cpp | 6 +- tests/unit/test_brake_setting.cpp | 141 +++++++++++++++++++++++++----- vehicle/Driver.cpp | 10 ++- vehicle/brakesetting.cpp | 14 +-- vehicle/brakesetting.h | 16 ++-- 5 files changed, 148 insertions(+), 39 deletions(-) diff --git a/McZapkie/hamulce.cpp b/McZapkie/hamulce.cpp index c0a7d2a0e..b4441eac0 100644 --- a/McZapkie/hamulce.cpp +++ b/McZapkie/hamulce.cpp @@ -1449,7 +1449,7 @@ double TESt4R::GetPF(double const PP, double const dt, double const Vel) result = dv - dV1; - RapidStatus = BrakeDelayFlag == bdelay_R && ((Vel > 55 && RapidStatus == true) || Vel > 70); + RapidStatus = (BrakeDelayFlag & bdelay_R) == bdelay_R && ((Vel > 55 && RapidStatus == true) || Vel > 70); RapidTemp = RapidTemp + (0.9 * int(RapidStatus) - RapidTemp) * dt / 2; temp = 1.9 - RapidTemp; @@ -1752,7 +1752,7 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) // if Vel>55 then temp:=0.72 else // temp:=1;{R} // cisnienie PP - RapidTemp = RapidTemp + (RM * int(Vel > 55 && BrakeDelayFlag == bdelay_R) - RapidTemp) * dt / 2; + RapidTemp = RapidTemp + (RM * int(Vel > 55 && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; temp = 1 - RapidTemp; if (EDFlag > 0.2) temp = 10000; @@ -1971,7 +1971,7 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) dv = dv + PF(MPP, VVP, 0.02); Miedzypoj->Flow(dv * dt * 0.15); - RapidTemp = RapidTemp + (RM * int(Vel > RV && BrakeDelayFlag == bdelay_R) - RapidTemp) * dt / 2; + RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; temp = std::max(1 - RapidTemp, 0.001); // if EDFlag then temp:=1000; // temp:=temp/(1-); diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index aba1e80bb..2d5b02a41 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -18,6 +18,13 @@ constexpr int P{bdelay_P}; constexpr int R{bdelay_R}; constexpr int M{bdelay_M}; +// how the AI runs the consist the inspector looks at: as a train (Obey_train), or shunting it +constexpr bool as_train{true}; +constexpr bool shunting{false}; +// whether the train stands, as AutoRewident() tells the inspector +constexpr bool standstill{true}; +constexpr bool moving{false}; + brake_setting::vehicle locomotive(int const Delays = G | P | R) { return {Delays, true, 17.0, 80000.0}; } @@ -51,7 +58,7 @@ TEST_CASE("brake setting: the locomotives don't count into the length and mass o auto consist{train(locomotive(), 20, freight_wagon(15.0, 30.0))}; consist.insert(consist.begin(), locomotive()); CHECK(brake_setting::choose_train_setting(consist) == train_setting::freight_p); - auto const settings{brake_setting::choose(consist)}; + auto const settings{brake_setting::choose(consist, as_train)}; CHECK(settings[0] == G); CHECK(settings[1] == G); for (std::size_t i = 2; i < settings.size(); ++i) { @@ -66,7 +73,7 @@ TEST_CASE("brake setting: the locomotives don't count into the length and mass o TEST_CASE("brake setting: the locomotive and the first five wagons on G, the rest on P (Cw-1 §19.3b)") { auto const consist{train(locomotive(), 12, freight_wagon(15.0, 60.0))}; REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_gp); - auto const settings{brake_setting::choose(consist)}; + auto const settings{brake_setting::choose(consist, as_train)}; REQUIRE(settings.size() == consist.size()); for (std::size_t i = 0; i < settings.size(); ++i) { CAPTURE(i); @@ -79,7 +86,7 @@ TEST_CASE("brake setting: a locomotive in the middle of the train doesn't put fi consist.emplace_back(locomotive()); consist.insert(consist.end(), 8, freight_wagon(15.0, 60.0)); REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_gp); - auto const settings{brake_setting::choose(consist)}; + auto const settings{brake_setting::choose(consist, as_train)}; CHECK(settings[1] == G); CHECK(settings[5] == G); CHECK(settings[6] == P); @@ -98,7 +105,7 @@ TEST_CASE("brake setting: a heavy freight train runs on G, a wagon without G has consist.emplace_back(passenger_car(P)); consist.emplace_back(passenger_car()); REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_g); - auto const settings{brake_setting::choose(consist)}; + auto const settings{brake_setting::choose(consist, as_train)}; for (std::size_t i = 0; i + 2 < settings.size(); ++i) { CAPTURE(i); CHECK(settings[i] == G); @@ -118,7 +125,7 @@ TEST_CASE("brake setting: in a train on G a locomotive and the vehicle it's driv consist.emplace_back(locomotive(P | R)); consist.emplace_back(0, false, 20.0, 40000.0); REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_g); - auto settings{brake_setting::choose(consist)}; + auto settings{brake_setting::choose(consist, as_train)}; CHECK(settings.front() == P); CHECK(settings[settings.size() - 2] == P); CHECK(settings.back() == 0); @@ -128,7 +135,7 @@ TEST_CASE("brake setting: in a train on G a locomotive and the vehicle it's driv controlcar.driven = true; consist.front() = controlcar; consist.back() = locomotive(); - settings = brake_setting::choose(consist); + settings = brake_setting::choose(consist, as_train); CHECK(settings.front() == P); CHECK(settings.back() == G); } @@ -140,7 +147,7 @@ TEST_CASE("brake setting: in the long locomotive setting a vehicle without G bra consist.insert(consist.end(), 8, freight_wagon(15.0, 60.0)); consist.emplace_back(passenger_car()); REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_gp); - auto const settings{brake_setting::choose(consist)}; + auto const settings{brake_setting::choose(consist, as_train)}; CHECK(settings[2] == G); CHECK(settings[3] == P); CHECK(settings[4] == G); @@ -148,6 +155,23 @@ TEST_CASE("brake setting: in the long locomotive setting a vehicle without G bra CHECK(settings.back() == P); } +TEST_CASE("brake setting: a heavy consist being shunted has nothing cut out, a wagon without G brakes on P") { + // §19.9 is about trains: the same consist the AI shunts rather than runs as a train + auto consist{train(locomotive(), 30, freight_wagon(15.0, 80.0))}; + consist.emplace_back(passenger_car(P)); + consist.emplace_back(passenger_car()); + REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_g); + auto const settings{brake_setting::choose(consist, shunting)}; + for (std::size_t i = 0; i + 2 < settings.size(); ++i) { + CAPTURE(i); + CHECK(settings[i] == G); + } + CHECK(settings[settings.size() - 2] == P); + CHECK(settings.back() == P); + // as a train they're cut out + CHECK(brake_setting::choose(consist, as_train).back() == brake_setting::cut_out); +} + TEST_CASE("brake setting: a car with its brake cut out counts as one on P in a passenger train (Cw-1 §18.3)") { auto consist{train(locomotive(), 5, passenger_car())}; consist.insert(consist.end(), 3, passenger_car(P)); @@ -180,12 +204,13 @@ void charge_and_apply(test::vehicle &Vehicle) { Vehicle.run(20.0); } -// the inspector at work on a heavy train on G with the vehicle at its end, as AutoRewident() does it -int inspect_heavy_train(test::vehicle &Vehicle) { +// the inspector at work on a heavy train on G with the vehicle at its end, as AutoRewident() does it, the AI +// running it as a train or shunting it, standing or on the run +int inspect_heavy_train(test::vehicle &Vehicle, bool const Train = as_train, bool const Standstill = standstill) { auto consist{train(locomotive(), 30, freight_wagon(15.0, 80.0))}; consist.emplace_back(brake_setting::describe(Vehicle.mover(), false)); - auto const setting{brake_setting::choose(consist).back()}; - brake_setting::apply(Vehicle.mover(), setting); + auto const setting{brake_setting::choose(consist, Train).back()}; + brake_setting::apply(Vehicle.mover(), setting, Standstill); return setting; } @@ -193,8 +218,8 @@ int inspect_heavy_train(test::vehicle &Vehicle) { int inspect_light_train(test::vehicle &Vehicle) { auto consist{train(locomotive(), 4, freight_wagon())}; consist.emplace_back(brake_setting::describe(Vehicle.mover(), false)); - auto const setting{brake_setting::choose(consist).back()}; - brake_setting::apply(Vehicle.mover(), setting); + auto const setting{brake_setting::choose(consist, as_train).back()}; + brake_setting::apply(Vehicle.mover(), setting, standstill); return setting; } @@ -269,22 +294,96 @@ TEST_CASE("brake setting: the inspector never puts back a brake cut out for anot CHECK(brake_setting::is_cut_out(other.mover())); } +TEST_CASE("brake setting: shunting puts back a brake the inspector cut out, and cuts none out") { + test::vehicle car{passenger_car_definition()}; + charge_and_apply(car); + // shunted in a heavy consist: nothing is cut out, the car is on P and brakes + CHECK(inspect_heavy_train(car, shunting) == P); + CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(car->BrakeDelayFlag == P); + CHECK(car->BrakePress > 1.0); + + // cut out when the consist became a train, then shunted again (e.g. left in a yard): the brake is back + REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); + REQUIRE(car->BrakeCutOutByInspector); + CHECK(inspect_heavy_train(car, shunting) == P); + CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == car->BrakeCutOutByInspector); + car.hold_brake_pipe(5.0); + car.run(300.0); + charge_and_apply(car); + CHECK(car->BrakePress > 1.0); + + // a brake cut out for a reason of its own stays cut out in shunting too + test::vehicle other{passenger_car_definition()}; + other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() | b_dmg); + CHECK(inspect_heavy_train(other, shunting) == P); + CHECK(brake_setting::is_cut_out(other.mover())); +} + +TEST_CASE("brake setting: the inspector doesn't cut a brake out on the run, it waits for a standstill") { + test::vehicle car{passenger_car_definition()}; + charge_and_apply(car); + REQUIRE(car->BrakePress > 1.0); + // the train checked on the run (the order changed mid-run): the car keeps its brake and its setting + auto const setting{car->BrakeDelayFlag}; + CHECK(inspect_heavy_train(car, as_train, moving) == brake_setting::cut_out); + CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == car->BrakeCutOutByInspector); + CHECK(car->BrakeDelayFlag == setting); + car.run(5.0); + CHECK(car->BrakePress > 1.0); + // the next check, standing, cuts it out + CHECK(inspect_heavy_train(car) == brake_setting::cut_out); + CHECK(brake_setting::is_cut_out(car.mover())); + CHECK(car->BrakeCutOutByInspector); + // a brake cut out already stays cut out on the run, and one put back on the run is back + CHECK(inspect_heavy_train(car, as_train, moving) == brake_setting::cut_out); + CHECK(car->BrakeCutOutByInspector); + CHECK(inspect_heavy_train(car, shunting, moving) == P); + CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == car->BrakeCutOutByInspector); +} + +TEST_CASE("brake setting: R+Mg brakes as hard as R at speed, the rapid stage of an LSt kept") { + // the inspector sets R+Mg (Cw-1 §18.2), the bits of R and Mg together: the valves test the bit of R, not + // the whole setting, so the high stage of R at speed stays on with Mg. the EU07's LSt given an Mg here + auto const definition{test::definition::fiz("4e_v1/4e").set("Cntrl", "BrakeDelays", "GPR+Mg")}; + auto const service = [&](int const Setting) { + test::reseed_random(); + test::vehicle real{definition, 160.0}; + real->DecManualBrakeLevel(ManualBrakePosNo); + real->BrakeDelaySwitch(Setting); // false when already set + REQUIRE(real->BrakeDelayFlag == Setting); + real.hold_brake_pipe(5.0); + real.run(60.0); + real.hold_brake_pipe(3.5); + real.run(10.0); + REQUIRE(real->Vel > 100.0); + return real->BrakePress; + }; + auto const rapid{service(R)}; + CHECK(service(R | M) == doctest::Approx(rapid).epsilon(0.01)); + // and P has no high stage + CHECK(service(P) < rapid - 1.0); +} + TEST_CASE("brake setting: a vehicle without the setting the train needs gets the other one of G and P") { // a light freight train with a wagon which has G only auto consist{train(locomotive(), 4, freight_wagon(15.0, 20.0))}; consist.emplace_back(G, false, 15.0, 20000.0); REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::freight_p); - CHECK(brake_setting::choose(consist).back() == G); + CHECK(brake_setting::choose(consist, as_train).back() == G); // and a vehicle with neither is left alone consist.emplace_back(R, false, 15.0, 20000.0); - CHECK(brake_setting::choose(consist).back() == 0); + CHECK(brake_setting::choose(consist, as_train).back() == 0); } TEST_CASE("brake setting: a passenger train on R carries at most three cars on P, fewer than those on R (Cw-1 §18.3)") { auto consist{train(locomotive(), 4, passenger_car())}; consist.insert(consist.end(), 3, passenger_car(P)); CHECK(brake_setting::choose_train_setting(consist) == train_setting::passenger_r); - auto const settings{brake_setting::choose(consist)}; + auto const settings{brake_setting::choose(consist, as_train)}; CHECK(settings[0] == R); CHECK(settings[1] == R); CHECK(settings.back() == P); @@ -292,7 +391,7 @@ TEST_CASE("brake setting: a passenger train on R carries at most three cars on P // as many cars on P as on R: all on P consist.emplace_back(passenger_car(P)); CHECK(brake_setting::choose_train_setting(consist) == train_setting::passenger_p); - for (auto const setting : brake_setting::choose(consist)) { + for (auto const setting : brake_setting::choose(consist, as_train)) { CHECK(setting == P); } // the inspector of the earlier releases kept such a train on R @@ -307,14 +406,14 @@ TEST_CASE("brake setting: freight wagons in a passenger train on R count as cars auto consist{train(locomotive(), 6, passenger_car())}; consist.emplace_back(freight_wagon()); REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::passenger_r); - CHECK(brake_setting::choose(consist).back() == P); + CHECK(brake_setting::choose(consist, as_train).back() == P); } TEST_CASE("brake setting: cars with a magnetic rail brake run on R+Mg in a train on R (Cw-1 §18.2)") { auto consist{train(locomotive(G | P | R | M), 3, passenger_car(P | R | M))}; consist.emplace_back(passenger_car()); REQUIRE(brake_setting::choose_train_setting(consist) == train_setting::passenger_r); - auto const settings{brake_setting::choose(consist)}; + auto const settings{brake_setting::choose(consist, as_train)}; CHECK(settings[0] == R); // the locomotive stays on R CHECK(settings[1] == (R | M)); CHECK(settings.back() == R); @@ -323,7 +422,7 @@ TEST_CASE("brake setting: cars with a magnetic rail brake run on R+Mg in a train TEST_CASE("brake setting: a light engine runs on R where it has it") { std::vector const consist{locomotive(), locomotive(G | P)}; CHECK(brake_setting::choose_train_setting(consist) == train_setting::light_engine); - auto const settings{brake_setting::choose(consist)}; + auto const settings{brake_setting::choose(consist, as_train)}; CHECK(settings[0] == R); CHECK(settings[1] == P); } @@ -331,7 +430,7 @@ TEST_CASE("brake setting: a light engine runs on R where it has it") { TEST_CASE("brake setting: the inspector of the earlier releases counted the locomotives into the train's mass") { // 300 m and 600 t of wagons: P by Cw-1, the long locomotive setting before auto const consist{train(locomotive(), 20, freight_wagon(15.0, 30.0))}; - CHECK(brake_setting::choose(consist)[1] == P); + CHECK(brake_setting::choose(consist, as_train)[1] == P); CHECK(brake_setting::choose_legacy(consist)[1] == G); CHECK(brake_setting::choose_legacy(consist)[6] == P); } diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 0bb569c81..35856c412 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2086,8 +2086,12 @@ void TController::AutoRewident() for (auto const *d = pVehicles[0]; d != nullptr; d = d->Next()) { consist.emplace_back(brake_setting::describe(*d->MoverParameters, d == pVehicle)); } - // 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did - auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist) : brake_setting::choose_legacy(consist)}; + // 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did. + // brakes are cut out (Cw-1 §19.9) only in a train, not in a consist being shunted + auto const train{(OrderCurrentGet() & Obey_train) != 0}; + auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist, train) : brake_setting::choose_legacy(consist)}; + // and only at a standstill: a check on the run (the order changed mid-run) leaves them to the next one + auto const standstill{false == (mvOccupied->Vel > EU07_AI_NOMOVEMENT)}; // a light engine counts as a passenger train for the braking below auto const passengertrain{brake_setting::passenger(brake_setting::choose_train_setting(consist))}; // 3. Nastawianie @@ -2098,7 +2102,7 @@ void TController::AutoRewident() continue; } // the setting, a brake cut out in a train on G (Cw-1 §19.9) or put back when the train no longer needs it cut out - brake_setting::apply(*d->MoverParameters, *setting); + brake_setting::apply(*d->MoverParameters, *setting, standstill); // potentially release manual brake d->MoverParameters->DecManualBrakeLevel( ManualBrakePosNo ); d->MoverParameters->SpringBrake.Activate = false; diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index bf42f8ab4..bafe8a95b 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -115,7 +115,7 @@ train_setting choose_train_setting(std::vector const &Consist) { return train_setting::freight_p; } -std::vector choose(std::vector const &Consist) { +std::vector choose(std::vector const &Consist, bool const Train) { auto const setting{choose_train_setting(Consist)}; std::vector settings; settings.reserve(Consist.size()); @@ -154,9 +154,10 @@ std::vector choose(std::vector const &Consist) { if (has(item.delays, bdelay_G)) { settings.emplace_back(bdelay_G); } - else if (item.powered || item.driven || item.delays == 0) { + else if (item.powered || item.driven || item.delays == 0 || false == Train) { // a locomotive, or the vehicle the train is driven from, keeps a working brake: on P. a vehicle - // which tells no settings at all is left alone + // which tells no settings at all is left alone. a consist being shunted isn't a train and §19.9 + // doesn't apply to it: its wagons keep their brakes, on P settings.emplace_back(pick(item.delays, bdelay_P, bdelay_P)); } else { @@ -249,21 +250,22 @@ vehicle describe(TMoverParameters const &Vehicle, bool const Driven) { return described; } -void apply(TMoverParameters &Vehicle, int const Setting) { +void apply(TMoverParameters &Vehicle, int const Setting, bool const Standstill) { auto &brake{*Vehicle.Hamulec}; if (Vehicle.BrakeCutOutByInspector && false == is_cut_out(Vehicle)) { // someone put the brake back in the meantime, it's theirs now Vehicle.BrakeCutOutByInspector = false; } if (Setting == cut_out) { - if (false == is_cut_out(Vehicle)) { + if (false == is_cut_out(Vehicle) && Standstill) { // close the cut-out cock and empty the brake with the releaser, as the scenery's '0' does: the // distributor, cut off the brake pipe, has no air left to brake with and lets the cylinders go brake.ForceEmptiness(); brake.SetBrakeStatus(brake.GetBrakeStatus() | b_dmg); Vehicle.BrakeCutOutByInspector = true; } - // a brake cut out already, by the inspector or for a reason of its own, stays as it is + // a brake cut out already, by the inspector or for a reason of its own, stays as it is. on the run the + // vehicle is left alone, brake and setting, until the inspector looks at the train standing return; } if (Vehicle.BrakeCutOutByInspector) { diff --git a/vehicle/brakesetting.h b/vehicle/brakesetting.h index cce2bbeb0..789f52808 100644 --- a/vehicle/brakesetting.h +++ b/vehicle/brakesetting.h @@ -56,8 +56,10 @@ constexpr bool passenger(train_setting const Setting) { // without the setting the train needs gets the other one of G and P it has, and 0 (left as it is) // when it has neither. In a train on G (freight_g) a wagon without G gets cut_out instead: its brake // is to be cut out (Cw-1 §19.9). A locomotive and the vehicle the train is driven from keep their -// brake working, on P -std::vector choose(std::vector const &Consist); +// brake working, on P. Train tells the AI runs the consist as a train (Obey_train): §19.9 is about +// trains, so in shunting (or banking) nothing is cut out and a wagon without G brakes on P, which puts +// back a brake the inspector cut out before +std::vector choose(std::vector const &Consist, bool Train); // the inspector of the releases before eu07/maszyna#350, kept for ai.brakesetting.cw1 no. the settings // are requests: a vehicle which doesn't have the one asked for keeps its own @@ -73,9 +75,11 @@ vehicle describe(TMoverParameters const &Vehicle, bool Driven); // the inspector puts the vehicle on Setting, as choose() gives it. cut_out cuts the brake out the way // the scenery's '0' does: b_dmg, which cuts the distributor off the brake pipe (as the cab's cut-out, // trainbrakeoperationtoggle, does), and its reservoirs emptied, so the brake releases and stays off. -// The vehicle remembers the inspector did it. Any other setting first puts back a brake the inspector -// cut out (it charges from the brake pipe again), then sets the vehicle to it (0: leaves the setting -// as it is). A brake cut out by anyone else stays cut out -void apply(TMoverParameters &Vehicle, int Setting); +// The vehicle remembers the inspector did it. A brake is cut out only with the train at a standstill +// (Standstill): on the run the vehicle is left as it is until the inspector looks at the train again +// standing, rather than losing its brake while moving. Any other setting first puts back a brake the +// inspector cut out (it charges from the brake pipe again), then sets the vehicle to it (0: leaves the +// setting as it is). A brake cut out by anyone else stays cut out +void apply(TMoverParameters &Vehicle, int Setting, bool Standstill); } // namespace brake_setting From 97c483e827cb958f5f4d6c905b8f9e934285163f Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 8 Nov 2026 18:05:00 +0100 Subject: [PATCH 08/37] fix: Elf emergency brake position vents the pipe only from the driven vehicle, coupled units agree on the controller position The emergency position of the master controller vented the brake pipe from every vehicle whose controller stood there, and "MainCtrl" reached the coupled vehicles raw, so an Elf with EIMCtrlMainEmergency and one without it disagreed by one notch (the full braking of one was the emergency brake of the other, neutral of one a power position of the other). The pipe is now vented only from the vehicle driven from (IsCabMaster()), and the position goes to the coupled vehicles in the positions without the key (MainCtrlPosForCoupled(), the emergency one as the full braking), each adding its own shift on receiving it (MainCtrlPosFromCoupled()). The loader's fix-up for the old MCPN=4 raises DirChangeMaxPos by the same shift, so the reverser keeps working at the new neutral. --- McZapkie/MOVER.h | 5 ++ McZapkie/Mover.cpp | 35 +++++--- tests/unit/test_elf_controller.cpp | 136 +++++++++++++++++++++++++++-- 3 files changed, 158 insertions(+), 18 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index d96e0d10c..21c9ba7e4 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2373,6 +2373,11 @@ class TMoverParameters int EIMCtrlEmergencyPositions() const; // whether the master controller is in its emergency brake position (EIMCtrlType 2 with EIMCtrlMainEmergency) bool IsMainCtrlEmergencyPos() const; + // the master controller position sent to the coupled vehicles ("MainCtrl"), the same with and without + // EIMCtrlMainEmergency: the Elf's positions without the emergency brake one, which goes as the full braking + int MainCtrlPosForCoupled() const; + // the master controller position of this vehicle for one received from a coupled vehicle ("MainCtrl") + int MainCtrlPosFromCoupled(int Position) const; /*! pomocniczy nastawnik:*/ bool IncScndCtrl(int CtrlSpeed); bool DecScndCtrl(int CtrlSpeed); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 3499e16b3..cd4573ca0 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -2537,7 +2537,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) if (true == OK) { - SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //??? + SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } @@ -2662,7 +2662,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) if (OK) { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); // hmmmm...???!!! + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } } @@ -2745,6 +2745,17 @@ bool TMoverParameters::IsMainCtrlEmergencyPos() const return MainCtrlPos < EIMCtrlEmergencyPositions(); } +int TMoverParameters::MainCtrlPosForCoupled() const +{ + // the emergency brake itself reaches the train through the brake pipe, vented by the vehicle driven from + return std::max(0, MainCtrlPos - EIMCtrlEmergencyPositions()); +} + +int TMoverParameters::MainCtrlPosFromCoupled(int const Position) const +{ + return Position + EIMCtrlEmergencyPositions(); +} + // ************************************************************************************************* // Q: 20160710 // zwiększenie bocznika @@ -2786,7 +2797,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) OK = false; if (OK) { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //??? + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } } @@ -2848,7 +2859,7 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) OK = false; if (OK) { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //??? + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } } @@ -4586,8 +4597,9 @@ void TMoverParameters::UpdatePipePressure(double dt) // 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) - if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || IsMainCtrlEmergencyPos() || SecuritySystem.is_braking() || + // the emergency brake (a broken coupler sets AlarmChainFlag instead). the Elf's emergency brake position + // vents the pipe only from the vehicle driven from, whatever the controllers of the others show + if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)) { @@ -10915,8 +10927,10 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(EIMCtrlMainEmergency, "EIMCtrlMainEmergency", line, ""); if (auto const elfpositions{4 + EIMCtrlEmergencyPositions()}; EIMCtrlEmergencyPositions() > 0 && MainCtrlPosNo < elfpositions) { - // without it the controller would have no power position - ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}", elfpositions, TypeName)); + // the old positions in the file: without the fix-up the controller would have no power position, and the + // reverser would stop working at neutral (DirChangeMaxPos read before, in the old positions) + MainCtrlMaxDirChangePos += EIMCtrlEmergencyPositions(); + ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}, DirChangeMaxPos taken as {}", elfpositions, TypeName, MainCtrlMaxDirChangePos)); MainCtrlPosNo = elfpositions; } @@ -12256,9 +12270,10 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do if (Command == "MainCtrl") { - if (MainCtrlPosNo >= floor(CValue1)) + // sent as MainCtrlPosForCoupled(), passed on unchanged + if (auto const position{MainCtrlPosFromCoupled(static_cast(floor(CValue1)))}; MainCtrlPosNo >= position) { - MainCtrlPos = static_cast(floor(CValue1)); + MainCtrlPos = position; if (DelayCtrlFlag) { if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index 747a57630..212ed51d0 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -5,6 +5,9 @@ #include "McZapkie/hamulce.h" +#include +#include + // the master controller of the Elf (EIMCtrlType 2): its positions, and the emergency brake position below // them which EIMCtrlMainEmergency adds (eu07/maszyna#413) @@ -13,16 +16,32 @@ using test::vehicle; namespace { -// a three-car Elf ready to run, standing with its brakes released and the driver in the front cab of the -// head car, which also drives (the controller's eimic is worked out there) +// the data of an Elf: without the emergency brake position as now, with it in the files updated for it +// (EIMCtrlMainEmergency, MCPN=5, DirChangeMaxPos=4), or with the key alone added to the old files, which the +// loader fixes up +enum class data { plain, emergency, emergency_old_layout }; + +// three-car Elfs coupled into one train, of the given data each, ready to run, standing with their brakes +// released and the driver in the front cab of the head car of the first one, which also drives (the +// controller's eimic is worked out there) struct elf { - explicit elf(bool Emergency) { - for (auto const *car : {"elf_v1/21we-a", "elf_v1/21we-b", "elf_v1/21we-c"}) { - auto cardefinition{definition::fiz(car)}; - if (Emergency) { - cardefinition.set("Cntrl", "EIMCtrlMainEmergency", "Yes").set("Cntrl", "MCPN", 5); + explicit elf(bool Emergency) : elf({Emergency ? data::emergency : data::plain}) {} + explicit elf(std::initializer_list Units) { + for (auto const units : Units) { + for (auto const *car : {"elf_v1/21we-a", "elf_v1/21we-b", "elf_v1/21we-c"}) { + auto cardefinition{definition::fiz(car)}; + if (units != data::plain) { + cardefinition.set("Cntrl", "EIMCtrlMainEmergency", "Yes"); + } + if (units == data::emergency) { + cardefinition.set("Cntrl", "MCPN", 5); + if (std::string{car} != "elf_v1/21we-b") { + // the cars with a cab have it, at neutral: 3 before, one up with the key + cardefinition.set("Cntrl", "DirChangeMaxPos", 4); + } + } + unit.add(cardefinition, unit.size() == 0 ? 1 : 0); } - unit.add(cardefinition, unit.size() == 0 ? 1 : 0); } ready = test::start_up(test::driving(unit), line); // the start-up of the tests leaves the controller at its position 0 (close_line_breaker() in drive.cpp), @@ -48,6 +67,14 @@ struct elf { wait(30.0); } TMoverParameters &cab() { return unit[0].mover(); } + TMoverParameters &car(std::size_t Index) { return unit[Index].mover(); } + // the driver moves the controller notch by notch, which the cab sends on to the coupled vehicles + void set_controller(int Position) { + while (cab().MainCtrlPos < Position && cab().IncMainCtrl(1)) { + } + while (cab().MainCtrlPos > Position && cab().DecMainCtrl(1)) { + } + } void wait(double Seconds) { test::drive(test::driving(unit), line, Seconds); } test::consist unit; test::track line{0.15, 0.0, test::catenary_3kv}; @@ -124,6 +151,99 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency with the old MCPN gets its posit vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "EIMCtrlMainEmergency", "Yes")}; CHECK(car->MainCtrlPosNo == 5); CHECK(car->MainCtrlNoPowerPos() == 4); + // DirChangeMaxPos=3 of the file, the old neutral, moves up with the positions + CHECK(car->MainCtrlMaxDirChangePos == 4); +} + +TEST_CASE("elf controller: EIMCtrlMainEmergency leaves DirChangeMaxPos of the files updated for it alone") { + vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "EIMCtrlMainEmergency", "Yes").set("Cntrl", "MCPN", 5).set("Cntrl", "DirChangeMaxPos", 4)}; + CHECK(car->MainCtrlPosNo == 5); + CHECK(car->MainCtrlMaxDirChangePos == 4); +} + +TEST_CASE("elf controller: the reverser works at the neutral shifted by EIMCtrlMainEmergency") { + // the key added to the old files, DirChangeMaxPos=3 in them + elf unit{{data::emergency_old_layout}}; + REQUIRE(unit.ready); + auto &mover{unit.cab()}; + REQUIRE(mover.MainCtrlPos == mover.MainCtrlNoPowerPos()); + REQUIRE(mover.DirActive == 1); + CHECK(mover.DirectionBackward()); + CHECK(mover.DirActive == 0); + CHECK(mover.DirectionForward()); + CHECK(mover.DirActive == 1); + // not in the power position + unit.set_controller(mover.MainCtrlNoPowerPos() + 1); + REQUIRE(mover.MainCtrlPos == 5); + CHECK_FALSE(mover.DirectionBackward()); + CHECK(mover.DirActive == 1); +} + +TEST_CASE("elf controller: the emergency brake position vents the pipe only from the vehicle driven from") { + elf unit{true}; + REQUIRE(unit.ready); + REQUIRE(unit.charged); + // the rear car, with its own cab, has its controller in the emergency brake position, the driven one not + auto &rear{unit.car(2)}; + rear.MainCtrlPos = 0; + CHECK(rear.IsMainCtrlEmergencyPos()); + CHECK_FALSE(rear.IsCabMaster()); + unit.wait(10.0); + CHECK(unit.cab().PipePress > 4.5); + CHECK(rear.PipePress > 4.5); +} + +TEST_CASE("elf controller: an Elf with the emergency brake position leading one without it") { + elf unit{{data::emergency, data::plain}}; + REQUIRE(unit.ready); + REQUIRE(unit.charged); + auto &lead{unit.cab()}; + auto &other{unit.car(3)}; + REQUIRE_FALSE(other.EIMCtrlMainEmergency); + // neutral of the lead is neutral of the other + CHECK(lead.MainCtrlPos == 4); + CHECK(other.MainCtrlPos == other.MainCtrlNoPowerPos()); + SUBCASE("power") { + unit.set_controller(5); + CHECK(other.MainCtrlPos == 4); + } + SUBCASE("full braking") { + unit.set_controller(1); + CHECK(other.MainCtrlPos == 0); + unit.wait(10.0); + CHECK(lead.PipePress > 4.5); + } + SUBCASE("the emergency brake: the other one at its full braking, the pipe vented by the lead") { + unit.set_controller(0); + REQUIRE(lead.IsMainCtrlEmergencyPos()); + CHECK(other.MainCtrlPos == 0); + unit.wait(10.0); + CHECK(lead.PipePress < 0.5); + CHECK(other.PipePress < 0.5); + } +} + +TEST_CASE("elf controller: an Elf without the emergency brake position leading one with it") { + elf unit{{data::plain, data::emergency}}; + REQUIRE(unit.ready); + REQUIRE(unit.charged); + auto &lead{unit.cab()}; + auto &other{unit.car(3)}; + REQUIRE(other.EIMCtrlMainEmergency); + CHECK(lead.MainCtrlPos == 3); + CHECK(other.MainCtrlPos == other.MainCtrlNoPowerPos()); + SUBCASE("power") { + unit.set_controller(4); + CHECK(other.MainCtrlPos == 5); + } + SUBCASE("the full braking of the lead is the full braking of the other, not its emergency brake") { + unit.set_controller(0); + CHECK(other.MainCtrlPos == 1); + CHECK_FALSE(other.IsMainCtrlEmergencyPos()); + unit.wait(10.0); + CHECK(lead.PipePress > 4.5); + CHECK(other.PipePress > 4.5); + } } TEST_CASE("elf controller: EIMCtrlMainEmergency leaves the other controllers alone") { From a3ad30b72bbb071c73eb1ad19d3707641c654c50 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 8 Nov 2026 18:18:35 +0100 Subject: [PATCH 09/37] fix: the odometer store merges the file other simulations saved, keeps a made up state replaceable by the cab's counter - each process writes its own ..tmp and renames it in place; before writing it re-reads the file and merges it per vehicle (a known state beats a made up one, else the larger one, never the sum) - a state counted from a made up one is saved as ~ and the .mmd counter offset still replaces it later - a vehicle removed from the scenery has its odometer recorded right away --- tests/unit/test_odometer.cpp | 160 +++++++++++++++++++++++++++++++++++ vehicle/DynObj.cpp | 5 ++ vehicle/odometer.cpp | 123 +++++++++++++++++++++------ vehicle/odometer.h | 38 +++++++-- 4 files changed, 292 insertions(+), 34 deletions(-) diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 784fabaab..853072d33 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -200,3 +200,163 @@ TEST_CASE("odometer: the cab's counter offset replaces only a guessed state, the CHECK(reading.source == source); } } + +TEST_CASE("odometer: a state counted from a made up one is saved as such, the cab's counter still replaces it") { + scratch_directory directory{"odometer_guessed"}; + auto const guess{odometer::guessed_state("EU07-424")}; + // the vehicle runs 30 km with no cab loaded (the AI's, loose stock) + odometer::store first; + auto ai{odometer::starting_state(first, "EU07-424", directory.path)}; + REQUIRE(ai.source == odometer::origin::guessed); + ai.run(30000.0); + first.record("EU07-424", ai); + std::stringstream file; + first.write(file); + CHECK(file.str().find("\n~") != std::string::npos); + + odometer::store second; + REQUIRE(second.read(file) == 1); + CHECK(second.guessed("EU07-424")); + CHECK(second.find("EU07-424").value() == doctest::Approx(guess + 30.0)); + auto player{odometer::starting_state(second, "EU07-424", directory.path)}; + CHECK(player.source == odometer::origin::guessed); + CHECK(player.km == doctest::Approx(guess + 30.0)); + + SUBCASE("a cab whose counter has an offset loads it: the offset replaces the made up state, the 30 km kept") { + player.run(2000.0); + player.seed(101532.0); + CHECK(player.source == odometer::origin::counter); + CHECK(player.start == doctest::Approx(101562.0)); + CHECK(player.km == doctest::Approx(101564.0)); + // recorded as known, also when the counter shows less than the made up state did + second.record("EU07-424", player); + CHECK_FALSE(second.guessed("EU07-424")); + CHECK(second.find("EU07-424").value() == doctest::Approx(101564.0)); + odometer::reading low; + low.begin(10.0, odometer::origin::counter); + odometer::store replaced; + std::stringstream guessedfile{"~400000 SM42-001\n"}; + replaced.read(guessedfile); + replaced.record("SM42-001", low); + CHECK(replaced.find("SM42-001").value() == 10.0); + CHECK_FALSE(replaced.guessed("SM42-001")); + CHECK(replaced.modified()); + } + SUBCASE("it runs with no cab again: it stays guessed") { + player.run(1000.0); + second.record("EU07-424", player); + CHECK(second.guessed("EU07-424")); + CHECK(second.find("EU07-424").value() == doctest::Approx(guess + 31.0)); + } +} + +TEST_CASE("odometer: the store reads the marker of a made up state, and skips it malformed") { + std::stringstream file{"~300 guessed one\n" + "~ nothing\n" + "~abc name\n" + "~-5 negative\n" + "~~5 twice\n" + "400 known\n"}; + odometer::store store; + CHECK(store.read(file) == 2); + CHECK(store.find("guessed one").value() == 300.0); + CHECK(store.guessed("guessed one")); + CHECK_FALSE(store.guessed("known")); + CHECK_FALSE(store.guessed("missing")); +} + +TEST_CASE("odometer: a recorded state is replaced only by a newer one") { + std::stringstream file{"500 known\n~600 guessed\n"}; + odometer::store store; + store.read(file); + // a vehicle of this simulation counting from less than another simulation saved meanwhile + store.record("known", run(400.0, 50000.0)); + CHECK(store.find("known").value() == 500.0); + CHECK_FALSE(store.modified()); + // a larger one does, also when the vehicle hasn't run in this session + store.record("known", run(900.0, 0.0)); + CHECK(store.find("known").value() == 900.0); + CHECK(store.modified()); + // a guessed state doesn't replace a known one, even a larger one + odometer::reading guessed; + guessed.begin(5000.0, odometer::origin::guessed); + guessed.run(1000.0); + store.record("known", guessed); + CHECK(store.find("known").value() == 900.0); + CHECK_FALSE(store.guessed("known")); + // a larger guessed one replaces a guessed one + store.record("guessed", guessed); + CHECK(store.find("guessed").value() == doctest::Approx(5001.0)); + CHECK(store.guessed("guessed")); +} + +TEST_CASE("odometer: two simulations saving one file keep each other's states") { + scratch_directory directory{"odometer_merge"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "1000 shared\n~20000 both guessed\n50 untouched\n"); + auto const load = [&path]() { + odometer::store store; + std::ifstream input{path, std::ios::binary}; + store.read(input); + return store; + }; + auto first{load()}; + auto second{load()}; + auto const guessed = [](double const Km, double const Metres) { + odometer::reading reading; + reading.begin(Km, odometer::origin::guessed); + reading.run(Metres); + return reading; + }; + + // both run the shared vehicle, as two multiplayer simulations of the same train do, the first one further + first.record("shared", run(1000.0, 5000.0)); + first.record("first only", run(70.0, 1000.0)); + first.record("both guessed", guessed(20000.0, 3000.0)); + second.record("shared", run(1000.0, 2000.0)); + second.record("second only", run(80.0, 1000.0)); + second.record("both guessed", guessed(20000.0, 1000.0)); + + REQUIRE(odometer::save(first, path)); + CHECK_FALSE(first.modified()); + REQUIRE(odometer::save(second, path)); + + auto const saved{load()}; + CHECK(saved.size() == 5); + // the larger state of the shared vehicle, not the sum of the two: they counted the same run + CHECK(saved.find("shared").value() == doctest::Approx(1005.0)); + CHECK(saved.find("first only").value() == doctest::Approx(71.0)); + CHECK(saved.find("second only").value() == doctest::Approx(81.0)); + CHECK(saved.find("both guessed").value() == doctest::Approx(20003.0)); + CHECK(saved.guessed("both guessed")); + CHECK(saved.find("untouched").value() == 50.0); + // the second one now knows the states the first one saved, for the vehicles it loads later + CHECK(second.find("first only").value() == doctest::Approx(71.0)); + + SUBCASE("a known state saved by one replaces a guessed one of the other") { + odometer::reading seeded; + seeded.begin(100.0, odometer::origin::counter); + first.record("both guessed", seeded); + REQUIRE(odometer::save(first, path)); + second.record("both guessed", guessed(20003.0, 5000.0)); + REQUIRE(odometer::save(second, path)); + auto const after{load()}; + CHECK(after.find("both guessed").value() == 100.0); + CHECK_FALSE(after.guessed("both guessed")); + CHECK(after.find("second only").value() == doctest::Approx(81.0)); + } + SUBCASE("nothing but the file is left in the directory") { + std::size_t files{0}; + for (auto const &entry : std::filesystem::directory_iterator{directory.path}) { + CAPTURE(entry.path().string()); + CHECK(entry.path().filename() == path.filename()); + ++files; + } + CHECK(files == 1); + } + SUBCASE("a store with nothing recorded since doesn't write") { + write_file(path, "1 replaced by hand\n"); + REQUIRE(odometer::save(second, path)); + CHECK(load().size() == 1); + } +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index ff7587169..b30eabba5 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -8890,6 +8890,11 @@ vehicle_table::erase_disabled() { ++vehicleiter; } else { + // the distance the vehicle ran goes in the odometer store now, it doesn't depend on the vehicle being + // kept on the list until the next save (eu07/maszyna#72) + if( vehicle->MoverParameters != nullptr ) { + odometer::states().record( vehicle->name(), vehicle->MoverParameters->Odometer ); + } if( vehicle->MyTrack != nullptr && true == vehicle->MyTrack->RemoveDynamicObject(vehicle) ) { vehicle->MyTrack = nullptr; diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index 9d03462b2..3584253d3 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -13,11 +13,19 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" +#include +#include #include #include #include #include #include +#include +#ifdef _WIN32 +#include +#else +#include +#endif namespace odometer { @@ -27,6 +35,14 @@ bool valid(double const Km) { return std::isfinite(Km) && Km >= 0.0; } +int process_id() { +#ifdef _WIN32 + return _getpid(); +#else + return static_cast(getpid()); +#endif +} + // number making up all of the text, surrounding whitespace aside std::optional parse_number(std::string const &Text) { auto const first{Text.find_first_not_of(" \t\r\n")}; @@ -51,13 +67,16 @@ void reading::begin(double const Km, origin const Source) { km = Km; start = Km; source = Source; + guess = Km; } void reading::seed(double const Km) { if (source != origin::guessed || false == valid(Km)) return; - km += Km - start; - start = Km; + auto const shift{Km - guess}; + km += shift; + start += shift; + guess = Km; source = origin::counter; } @@ -81,47 +100,71 @@ std::size_t store::read(std::istream &Input) { auto const separator{line.find_first_of(" \t")}; if (separator == std::string::npos) continue; - auto const km{parse_number(line.substr(0, separator))}; + auto number{line.substr(0, separator)}; + auto const guessed{false == number.empty() && number.front() == '~'}; + if (guessed) + number.erase(0, 1); + auto const km{parse_number(number)}; auto const name{line.substr(separator + 1)}; if (false == km.has_value() || name.empty()) continue; - m_states[name] = *km; + m_states[name] = state{*km, guessed}; ++count; } return count; } void store::write(std::ostream &Output) const { - Output << "# odometer states of the vehicles: \n"; + Output << "# odometer states of the vehicles: , ~ for one counted from a made up state\n"; Output << std::fixed << std::setprecision(4); - for (auto const &[name, km] : m_states) - Output << km << ' ' << name << '\n'; + for (auto const &[name, state] : m_states) + Output << (state.guessed ? "~" : "") << state.km << ' ' << name << '\n'; } std::optional store::find(std::string const &Vehicle) const { auto const lookup{m_states.find(Vehicle)}; if (lookup == m_states.end()) return std::nullopt; - return lookup->second; + return lookup->second.km; +} + +bool store::guessed(std::string const &Vehicle) const { + auto const lookup{m_states.find(Vehicle)}; + return lookup != m_states.end() && lookup->second.guessed; +} + +bool store::newer(state const &Left, state const &Right) { + if (Left.guessed != Right.guessed) + return Right.guessed; + return Left.km > Right.km; } void store::record(std::string const &Vehicle, reading const &Odometer) { if (Vehicle.empty() || false == valid(Odometer.km)) return; + state const recorded{Odometer.km, Odometer.source == origin::guessed}; auto const lookup{m_states.find(Vehicle)}; if (lookup == m_states.end()) { if (false == Odometer.moved()) return; - m_states.emplace(Vehicle, Odometer.km); + m_states.emplace(Vehicle, recorded); m_modified = true; return; } - if (lookup->second == Odometer.km) + if (false == newer(recorded, lookup->second)) return; - lookup->second = Odometer.km; + lookup->second = recorded; m_modified = true; } +void store::merge(store const &Other) { + for (auto const &[name, other] : Other.m_states) { + auto const [lookup, added] {m_states.try_emplace(name, other)}; + if (false == added && newer(other, lookup->second)) + lookup->second = other; + } +} + std::optional read_legacy(std::istream &Input) { std::stringstream content; content << Input.rdbuf(); @@ -154,7 +197,14 @@ double guessed_state(std::string const &Vehicle) { reading starting_state(store const &States, std::string const &Vehicle, std::filesystem::path const &Vehicledirectory) { reading result; if (auto const saved{States.find(Vehicle)}; saved.has_value()) { - result.begin(*saved, origin::saved); + if (States.guessed(Vehicle)) { + // the vehicle ran with a made up state before any cab with a known one loaded it (as the AI's or loose + // stock); the made up part of it stays replaceable + result.begin(*saved, origin::guessed); + result.guess = std::min(*saved, guessed_state(Vehicle)); + } else { + result.begin(*saved, origin::saved); + } } else if (auto const legacy{legacy_state(Vehicledirectory, Vehicle)}; legacy.has_value()) { result.begin(*legacy, origin::legacy); } else { @@ -190,36 +240,59 @@ store &states() { return odometers; } -bool save() { - auto &odometers{states()}; - if (false == odometers.modified()) +bool save(store &States, std::filesystem::path const &File) { + if (false == States.modified()) return true; - auto const path{file()}; std::error_code error; - if (path.has_parent_path()) - std::filesystem::create_directories(path.parent_path(), error); - // written aside first, a crash in the middle of a write doesn't lose the states - auto temporary{path}; - temporary += ".tmp"; + if (File.has_parent_path()) + std::filesystem::create_directories(File.parent_path(), error); + // other simulations on the machine (multiplayer, parallel runs) keep their states in the same file: what they + // saved since this one read it is merged in, not overwritten + { + std::ifstream input{File, std::ios::binary}; + if (input.is_open()) { + store saved; + saved.read(input); + States.merge(saved); + } + } + // written aside first, a crash in the middle of a write doesn't lose the states. the file aside is this process' + // own, the other simulations write theirs + auto temporary{File}; + temporary += "." + std::to_string(process_id()) + ".tmp"; { std::ofstream output{temporary, std::ios::binary | std::ios::trunc}; if (false == output.is_open()) { ErrorLog("Failed to save the odometer states to \"" + temporary.string() + "\""); return false; } - odometers.write(output); + States.write(output); if (false == output.good()) { + output.close(); + std::filesystem::remove(temporary, error); ErrorLog("Failed to save the odometer states to \"" + temporary.string() + "\""); return false; } } - std::filesystem::rename(temporary, path, error); + // the file can't be replaced while another simulation is reading it, that takes a moment + for (auto attempt{0};; ++attempt) { + std::filesystem::rename(temporary, File, error); + if (false == static_cast(error) || attempt == 4) + break; + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } if (error) { - ErrorLog("Failed to save the odometer states to \"" + path.string() + "\": " + error.message()); + ErrorLog("Failed to save the odometer states to \"" + File.string() + "\": " + error.message()); + std::error_code ignored; + std::filesystem::remove(temporary, ignored); return false; } - odometers.saved(); + States.saved(); return true; } +bool save() { + return save(states(), file()); +} + } // namespace odometer diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 65313c34b..1414548c9 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -26,7 +26,7 @@ enum class origin { saved, // the odometer store of the earlier sessions legacy, // the file a python screen kept it in before counter, // the offset of the cab's counter, which used to show it on top of the distance run in the session - guessed // nothing known, a made up state which the cab's counter can still replace + guessed // counted from a made up state, which the cab's counter can still replace, also once it was saved }; // odometer of one vehicle @@ -34,11 +34,12 @@ struct reading { double km{0.0}; // the state, km double start{0.0}; // the state at the start of the session, km origin source{origin::guessed}; + double guess{0.0}; // the made up state a guessed one counts from, km // sets the state the vehicle starts the session with void begin(double Km, origin Source); - // replaces a guessed state with the one the cab's counter showed at the start, the distance run kept. - // a known state stays + // replaces the made up state a guessed one counts from with the one the cab's counter showed at the start, + // the distance run on top of it kept, in this session and the earlier ones. a known state stays void seed(double Km); // counts the distance run, in metres either way void run(double Metres); @@ -49,15 +50,22 @@ struct reading { // the saved odometer states of the vehicles, km by vehicle name class store { public: - // reads the states written by write(). lines " ", '#' starts a comment line, a malformed - // line is skipped. returns the number of states read + // reads the states written by write(). lines " ", "~ " for a state counted + // from a made up one, '#' starts a comment line, a malformed line is skipped. returns the number of states read std::size_t read(std::istream &Input); void write(std::ostream &Output) const; std::optional find(std::string const &Vehicle) const; + // the state of the vehicle is counted from a made up one, which the cab's counter can still replace + bool guessed(std::string const &Vehicle) const; // records the state of a vehicle. one not in the store yet gets in only once it has run, so the vehicles - // standing in the sceneries don't fill the file + // standing in the sceneries don't fill the file. a recorded state is replaced only by a newer one: a larger + // one, or a known one in place of a guessed one void record(std::string const &Vehicle, reading const &Odometer); + // takes the states of the other store (the file, as other simulations have saved it since) newer than these. + // the odometers only count up, so of two states of a vehicle the larger is the newer one. they aren't added + // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles + void merge(store const &Other); // there are states recorded since they were last saved bool modified() const { return m_modified; } @@ -65,7 +73,14 @@ public: std::size_t size() const { return m_states.size(); } private: - std::map m_states; + struct state { + double km{0.0}; + bool guessed{false}; + }; + // the first state is newer than the second one + static bool newer(state const &Left, state const &Right); + + std::map m_states; bool m_modified{false}; }; @@ -78,7 +93,8 @@ std::optional legacy_state(std::filesystem::path const &Vehicledirectory // the same each session until the vehicle runs and gets its state saved double guessed_state(std::string const &Vehicle); -// state a vehicle starts the session with: the saved one, else the legacy one, else a guessed one +// state a vehicle starts the session with: the saved one, else the legacy one, else a guessed one. a saved state +// counted from a guessed one stays guessed, so the cab's counter can still replace the made up part of it reading starting_state(store const &States, std::string const &Vehicle, std::filesystem::path const &Vehicledirectory); // state the cab's counter with offset Offset and scale Scale shows, once its offset no longer applies @@ -88,7 +104,11 @@ std::optional counter_seed(float Offset, float Scale); // the odometer store of the simulation, read from the user's settings directory on the first use store &states(); std::filesystem::path file(); -// writes the store when anything was recorded since. returns false when the write failed +// writes the store to the file when anything was recorded since, merged with what other simulations saved in the +// file meanwhile. it's written to a file of this process aside first, then put in place. returns false when the +// write failed +bool save(store &States, std::filesystem::path const &File); +// saves the store of the simulation to its file bool save(); } // namespace odometer From 64d1b7f8474e68f33cebf04759a2b94c82d27c69 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 8 Nov 2026 21:38:16 +0100 Subject: [PATCH 10/37] fix: the inspector takes a train below 1 km/h for standing and a bank run for a train (review of #282) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The AI inspects the train while it still creeps to a stop (W4, Shunt to Obey_train) and as it couples, so the 0.05 km/h threshold missed the §19.9 cut-out; it now uses EU07_AI_MOVEMENT. Bank counts as a train, as in the braking tables. --- tests/unit/test_brake_setting.cpp | 48 ++++++++++++++++++++++++++++++- vehicle/Driver.cpp | 9 +++--- vehicle/brakesetting.cpp | 14 +++++++-- vehicle/brakesetting.h | 16 +++++++++-- 4 files changed, 77 insertions(+), 10 deletions(-) diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index 2d5b02a41..93fb54a76 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -5,6 +5,7 @@ #include "McZapkie/hamulce.h" #include "vehicle.h" #include "vehicle/brakesetting.h" +#include "vehicle/Driver.h" // the brake settings the AI wagon inspector (TController::AutoRewident) chooses for a train, by the // brake instruction Cw-1 (Mw56) §18 and §19 (eu07/maszyna#350) @@ -18,7 +19,7 @@ constexpr int P{bdelay_P}; constexpr int R{bdelay_R}; constexpr int M{bdelay_M}; -// how the AI runs the consist the inspector looks at: as a train (Obey_train), or shunting it +// how the AI runs the consist the inspector looks at: as a train (Obey_train or Bank), or shunting it constexpr bool as_train{true}; constexpr bool shunting{false}; // whether the train stands, as AutoRewident() tells the inspector @@ -345,6 +346,51 @@ TEST_CASE("brake setting: the inspector doesn't cut a brake out on the run, it w CHECK(false == car->BrakeCutOutByInspector); } +TEST_CASE("brake setting: a train creeping to a stop or coupling counts as standing, one on the run doesn't") { + // the AI looks at the train at a W4 and when it switches from shunting to the train run below 1 km/h, and as it + // couples at the coupling speed: the inspector takes those for a standstill + CHECK(brake_setting::at_standstill(0.0)); + CHECK(brake_setting::at_standstill(0.04)); + CHECK(brake_setting::at_standstill(0.9)); + CHECK(brake_setting::at_standstill(-0.9)); + CHECK(false == brake_setting::at_standstill(EU07_AI_MOVEMENT)); + CHECK(false == brake_setting::at_standstill(30.0)); + + // checked at 0.9 km/h: the brake is cut out + test::vehicle creeping{passenger_car_definition()}; + charge_and_apply(creeping); + CHECK(inspect_heavy_train(creeping, as_train, brake_setting::at_standstill(0.9)) == brake_setting::cut_out); + CHECK(brake_setting::is_cut_out(creeping.mover())); + CHECK(creeping->BrakeCutOutByInspector); + // checked at 30 km/h: the car keeps its brake + test::vehicle running{passenger_car_definition()}; + charge_and_apply(running); + CHECK(inspect_heavy_train(running, as_train, brake_setting::at_standstill(30.0)) == brake_setting::cut_out); + CHECK(false == brake_setting::is_cut_out(running.mover())); + CHECK(false == running->BrakeCutOutByInspector); + running.run(5.0); + CHECK(running->BrakePress > 1.0); +} + +TEST_CASE("brake setting: a bank engine's run counts as a train, shunting doesn't") { + CHECK(brake_setting::runs_as_train(Obey_train)); + CHECK(brake_setting::runs_as_train(Bank)); + CHECK(brake_setting::runs_as_train(Obey_train | Connect)); + CHECK(false == brake_setting::runs_as_train(Shunt)); + CHECK(false == brake_setting::runs_as_train(Loose_shunt)); + CHECK(false == brake_setting::runs_as_train(Connect)); + CHECK(false == brake_setting::runs_as_train(Wait_for_orders)); + + // a heavy consist on G banked: the wagon without G has its brake cut out, as in a train + test::vehicle car{passenger_car_definition()}; + charge_and_apply(car); + CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(Bank)) == brake_setting::cut_out); + CHECK(brake_setting::is_cut_out(car.mover())); + // shunted: it's back on P + CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(Shunt)) == P); + CHECK(false == brake_setting::is_cut_out(car.mover())); +} + TEST_CASE("brake setting: R+Mg brakes as hard as R at speed, the rapid stage of an LSt kept") { // the inspector sets R+Mg (Cw-1 §18.2), the bits of R and Mg together: the valves test the bit of R, not // the whole setting, so the high stage of R at speed stays on with Mg. the EU07's LSt given an Mg here diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index b4f790768..0099c799c 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2167,11 +2167,12 @@ void TController::AutoRewident() consist.emplace_back(brake_setting::describe(*d->MoverParameters, d == pVehicle)); } // 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did. - // brakes are cut out (Cw-1 §19.9) only in a train, not in a consist being shunted - auto const train{(OrderCurrentGet() & Obey_train) != 0}; + // brakes are cut out (Cw-1 §19.9) only in a train (a bank engine's run included), not in a consist being shunted + auto const train{brake_setting::runs_as_train(OrderCurrentGet())}; auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist, train) : brake_setting::choose_legacy(consist)}; - // and only at a standstill: a check on the run (the order changed mid-run) leaves them to the next one - auto const standstill{false == (mvOccupied->Vel > EU07_AI_NOMOVEMENT)}; + // and only at a standstill, the train creeping to a stop or coupling included: a check on the run (the order changed + // mid-run) leaves them to the next one + auto const standstill{brake_setting::at_standstill(mvOccupied->Vel)}; // a light engine counts as a passenger train for the braking below auto const passengertrain{brake_setting::passenger(brake_setting::choose_train_setting(consist))}; // 3. Nastawianie diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index bafe8a95b..f27c136ca 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -12,8 +12,10 @@ http://mozilla.org/MPL/2.0/. #include "McZapkie/MOVER.h" #include "McZapkie/hamulce.h" +#include "vehicle/Driver.h" #include +#include namespace brake_setting { @@ -156,8 +158,8 @@ std::vector choose(std::vector const &Consist, bool const Train) { } else if (item.powered || item.driven || item.delays == 0 || false == Train) { // a locomotive, or the vehicle the train is driven from, keeps a working brake: on P. a vehicle - // which tells no settings at all is left alone. a consist being shunted isn't a train and §19.9 - // doesn't apply to it: its wagons keep their brakes, on P + // which tells no settings at all is left alone. a consist being shunted isn't a train (a bank + // engine's run is) and §19.9 doesn't apply to it: its wagons keep their brakes, on P settings.emplace_back(pick(item.delays, bdelay_P, bdelay_P)); } else { @@ -171,6 +173,14 @@ std::vector choose(std::vector const &Consist, bool const Train) { return settings; } +bool runs_as_train(int const Orders) { + return (Orders & (Obey_train | Bank)) != 0; +} + +bool at_standstill(double const Velocity) { + return std::abs(Velocity) < EU07_AI_MOVEMENT; +} + std::vector choose_legacy(std::vector const &Consist) { wagon_counts const counts{Consist}; auto length{0.0}; diff --git a/vehicle/brakesetting.h b/vehicle/brakesetting.h index 789f52808..b555850fb 100644 --- a/vehicle/brakesetting.h +++ b/vehicle/brakesetting.h @@ -56,11 +56,21 @@ constexpr bool passenger(train_setting const Setting) { // without the setting the train needs gets the other one of G and P it has, and 0 (left as it is) // when it has neither. In a train on G (freight_g) a wagon without G gets cut_out instead: its brake // is to be cut out (Cw-1 §19.9). A locomotive and the vehicle the train is driven from keep their -// brake working, on P. Train tells the AI runs the consist as a train (Obey_train): §19.9 is about -// trains, so in shunting (or banking) nothing is cut out and a wagon without G brakes on P, which puts -// back a brake the inspector cut out before +// brake working, on P. Train tells the AI runs the consist as a train (runs_as_train()): §19.9 is about +// trains, so in shunting nothing is cut out and a wagon without G brakes on P, which puts back a brake +// the inspector cut out before std::vector choose(std::vector const &Consist, bool Train); +// the AI runs the consist as a train, rather than shunting it: Obey_train, or Bank, which it drives as a +// train run too (with the braking of a train). Orders is the order of the AI (TOrders) +bool runs_as_train(int Orders); + +// the train stands for the inspector: slower than the AI takes for a deliberate movement (EU07_AI_MOVEMENT). +// the AI looks at the train while it still creeps to a stop (at a W4, or switching from shunting to the train +// run) and as it couples (at the coupling speed), so a stricter threshold would miss those checks; a train +// really on the run (an order changed mid-run) stays above it +bool at_standstill(double Velocity); + // the inspector of the releases before eu07/maszyna#350, kept for ai.brakesetting.cw1 no. the settings // are requests: a vehicle which doesn't have the one asked for keeps its own std::vector choose_legacy(std::vector const &Consist); From e8735f15648ca79a059ff7c4811513c2d24beaf4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 9 Nov 2026 15:54:10 +0100 Subject: [PATCH 11/37] fix: the copies of the odometer counter (duplicate: yes) drop their offset too the counter's offset no longer applies once it shows the odometer, the copies of the control which master added kept theirs and showed it on top --- vehicle/Gauge.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index 173c8a9f6..8d27c1144 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -58,11 +58,14 @@ public: // copies of the control animated along with it, from its definitions marked duplicate: yes std::vector const &mirrors() const { return m_mirrors; } - // the value shown is value * scale + offset + // the value shown is value * scale + offset. the copies of the control (mirrors()) show the same value, so they + // get the same offset float offset() const { return m_offset; } void offset( float const Offset ) { - m_offset = Offset; } + m_offset = Offset; + for( auto &mirror : m_mirrors ) { + mirror.m_offset = Offset; } } float scale() const { return m_scale; } // returns offset of submodel associated with the button from the model centre From 729f15e8787f649f362e9bc3c9c6f7d979010290 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 9 Nov 2026 16:01:16 +0100 Subject: [PATCH 12/37] fix: a test run neither reads nor saves the player's odometer store the autotests (--test, Global.test.enabled) run the vehicles of the player's game: their odometers count from the legacy or made up states in a store of their own, and nothing is written to eu07_odometers.txt --- tests/unit/test_odometer.cpp | 23 +++++++++++++++++++++++ vehicle/odometer.cpp | 13 +++++++++++++ vehicle/odometer.h | 8 ++++++-- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 853072d33..4ae5c454a 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #include "doctest.h" #include "vehicle.h" +#include "utilities/Globals.h" #include "vehicle/odometer.h" #include @@ -360,3 +361,25 @@ TEST_CASE("odometer: two simulations saving one file keep each other's states") CHECK(load().size() == 1); } } + +TEST_CASE("odometer: a test run neither reads nor saves the player's store") { + if (false == Global.test.enabled) + CHECK(odometer::persistent()); + // the autotests (--test) run the vehicles of the player's game, their runs aren't the player's + struct test_mode { + bool const was{Global.test.enabled}; + test_mode() { Global.test.enabled = true; } + test_mode(test_mode const &) = delete; + test_mode &operator=(test_mode const &) = delete; + ~test_mode() { Global.test.enabled = was; } + } const testmode; + // stops before the player's file is touched, if the gate is gone + REQUIRE_FALSE(odometer::persistent()); + + auto &states{odometer::states()}; + states.record("tested", run(1000.0, 5000.0)); + CHECK(states.find("tested").value() == doctest::Approx(1005.0)); + CHECK(odometer::save()); + // a save to the file would have cleared it + CHECK(states.modified()); +} diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index 3584253d3..e7e671d25 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/odometer.h" +#include "utilities/Globals.h" #include "utilities/Logs.h" #include "utilities/utilities.h" @@ -227,7 +228,17 @@ std::filesystem::path file() { return path.empty() ? std::filesystem::path{"eu07_odometers.txt"} : path; } +bool persistent() { + return false == Global.test.enabled; +} + store &states() { + if (false == persistent()) { + // the vehicles of a test run count their odometers as usual, from the guessed or legacy states, with nothing + // read from or saved to the player's file + static store scratch; + return scratch; + } static store odometers = [] { store result; std::ifstream input{file(), std::ios::binary}; @@ -292,6 +303,8 @@ bool save(store &States, std::filesystem::path const &File) { } bool save() { + if (false == persistent()) + return true; return save(states(), file()); } diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 1414548c9..110554ef6 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -101,14 +101,18 @@ reading starting_state(store const &States, std::string const &Vehicle, std::fil // (the counter shows the odometer). nothing for a counter without an offset std::optional counter_seed(float Offset, float Scale); -// the odometer store of the simulation, read from the user's settings directory on the first use +// the store of the simulation is the player's file: false in a test run (--test, Global.test.enabled), whose vehicles +// neither start from the player's states nor change them +bool persistent(); +// the odometer store of the simulation, read from the user's settings directory on the first use. in a test run an +// empty one, not read from anywhere store &states(); std::filesystem::path file(); // writes the store to the file when anything was recorded since, merged with what other simulations saved in the // file meanwhile. it's written to a file of this process aside first, then put in place. returns false when the // write failed bool save(store &States, std::filesystem::path const &File); -// saves the store of the simulation to its file +// saves the store of the simulation to its file. a test run doesn't save it bool save(); } // namespace odometer From acf0716a9ca1ee1f4459e4f69802f2d875a74146 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 9 Nov 2026 16:12:13 +0100 Subject: [PATCH 13/37] fix: keep the odometers of the vehicles with a driver's cab only every vehicle which ran got a line in the store, the wagons of the AI's trains in every scenario too. the store records a vehicle with a driver's brake valve (BrakeHandle in the .fiz), which can show its odometer; the locomotives and units the AI runs before a player's cab loads them still get in with their replaceable made up states. the states already in the file stay as they are --- McZapkie/MOVER.h | 7 +++++ tests/unit/test_odometer.cpp | 51 ++++++++++++++++++++++++++++++++++++ vehicle/DynObj.cpp | 4 +-- vehicle/odometer.cpp | 6 +++++ vehicle/odometer.h | 7 +++++ 5 files changed, 73 insertions(+), 2 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index f5de00931..d461269b1 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2566,6 +2566,13 @@ class TMoverParameters { return JointEngineStart ? range_t::consist : range_t::local; } + // whether the vehicle has a driver's cab: it has the driver's brake valve (BrakeHandle in the Cntrl. section of the + // .fiz), which the wagons and most cars of the units without a cab don't (a few copy the Cntrl. section of the cab + // car, as the EN57 s car does). it's the vehicle type's, unlike the cab the scenario puts a driver in + bool HasDriverCab() const + { + return BrakeHandle != TBrakeHandle::NoHandle; + } // whether the cab command opening the main circuit opens it where the only cab switch of the circuit is the button // closing it: on a diesel that's the starter button, and the command is the one way to stop an engine whose fuel pump // starts on its own (eu07/maszyna#427). the other vehicles with such a button keep ignoring the command diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 4ae5c454a..5e287116b 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -383,3 +383,54 @@ TEST_CASE("odometer: a test run neither reads nor saves the player's store") { // a save to the file would have cleared it CHECK(states.modified()); } + +TEST_CASE("odometer: the vehicles with a driver's cab are the ones with the driver's brake valve") { + // the definitions of the game: a locomotive, cab cars of units, a motor car of a unit without a cab, the wagons + struct expected { + char const *path; + bool cab; + }; + for (auto const &[path, cab] : {expected{"4e_v1/4e", true}, expected{"sm42_v1/6d1", true}, expected{"en57_v1/5bgb", true}, + expected{"21xm_v1/214ma", true}, expected{"impuls_v1/31we-a_pr", true}, + expected{"ed72_v1/6bs-sa", false}, expected{"impuls_v1/31we-b_pr", false}, + expected{"11xa_v2/93a", false}, expected{"bdhpumn_v3/bdhpumn", false}, + expected{"430w_v2/430w", false}}) { + CAPTURE(path); + test::vehicle vehicle{test::definition::fiz(path)}; + CHECK(vehicle->HasDriverCab() == cab); + } + test::vehicle wagon{test::definition::load("wagon")}; + CHECK_FALSE(wagon->HasDriverCab()); + test::vehicle locomotive{test::definition::load("wagon").set("Cntrl", "BrakeHandle", "FV4a")}; + CHECK(locomotive->HasDriverCab()); +} + +TEST_CASE("odometer: only the vehicles with a driver's cab are recorded") { + odometer::store store; + SUBCASE("a wagon which ran doesn't get in") { + odometer::record(store, "wagon", false, run(5000.0, 1000.0)); + CHECK_FALSE(store.find("wagon").has_value()); + CHECK_FALSE(store.modified()); + } + SUBCASE("a locomotive the AI ran before any cab loaded it gets in with its made up state, still replaceable") { + odometer::reading ai; + ai.begin(odometer::guessed_state("ET22-100"), odometer::origin::guessed); + ai.run(2000.0); + odometer::record(store, "ET22-100", true, ai); + CHECK(store.find("ET22-100").value() == doctest::Approx(ai.km)); + CHECK(store.guessed("ET22-100")); + CHECK(store.modified()); + } + SUBCASE("the state of a wagon already in the file stays as it was, and is written back") { + std::stringstream file{"300 old wagon\n"}; + store.read(file); + odometer::record(store, "old wagon", false, run(300.0, 1000.0)); + CHECK(store.find("old wagon").value() == 300.0); + CHECK_FALSE(store.modified()); + std::stringstream written; + store.write(written); + odometer::store read; + CHECK(read.read(written) == 1); + CHECK(read.find("old wagon").value() == 300.0); + } +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 46e634b9f..06955e694 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -8817,7 +8817,7 @@ vehicle_table::save_odometers() { auto &odometers { odometer::states() }; for( auto const *vehicle : m_items ) { if( vehicle->MoverParameters != nullptr ) { - odometers.record( vehicle->name(), vehicle->MoverParameters->Odometer ); + odometer::record( odometers, vehicle->name(), vehicle->MoverParameters->HasDriverCab(), vehicle->MoverParameters->Odometer ); } } odometer::save(); @@ -8970,7 +8970,7 @@ vehicle_table::erase_disabled() { // the distance the vehicle ran goes in the odometer store now, it doesn't depend on the vehicle being // kept on the list until the next save (eu07/maszyna#72) if( vehicle->MoverParameters != nullptr ) { - odometer::states().record( vehicle->name(), vehicle->MoverParameters->Odometer ); + odometer::record( odometer::states(), vehicle->name(), vehicle->MoverParameters->HasDriverCab(), vehicle->MoverParameters->Odometer ); } if( vehicle->MyTrack != nullptr && true == vehicle->MyTrack->RemoveDynamicObject(vehicle) ) { diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index e7e671d25..60c119f12 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -158,6 +158,12 @@ void store::record(std::string const &Vehicle, reading const &Odometer) { m_modified = true; } +void record(store &States, std::string const &Vehicle, bool const Drivercab, reading const &Odometer) { + if (false == Drivercab) + return; + States.record(Vehicle, Odometer); +} + void store::merge(store const &Other) { for (auto const &[name, other] : Other.m_states) { auto const [lookup, added] {m_states.try_emplace(name, other)}; diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 110554ef6..083d00d1a 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -84,6 +84,13 @@ private: bool m_modified{false}; }; +// records the state of a vehicle in the store when it's one the store keeps: a vehicle with a driver's cab +// (TMoverParameters::HasDriverCab()), which can show its odometer on the cab's counter or a python screen. that +// includes the locomotives and units the AI runs before a player's cab loads them, their made up states stay +// replaceable by the cab's counter. the wagons, which make most of the AI's trains, aren't recorded; the states the +// store already holds for any of them stay as they are +void record(store &States, std::string const &Vehicle, bool Drivercab, reading const &Odometer); + // state kept in the file of the python screens before (/kilometry/_przebieg.txt, // where the screens dropped the last character of the vehicle name), when it holds a number std::optional read_legacy(std::istream &Input); From ee42a801883b29b1cef7c59f46ed7811e9ba6ad3 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 9 Nov 2026 16:12:44 +0100 Subject: [PATCH 14/37] docs: the odometer store is keyed by the vehicle's name in the scenario --- vehicle/odometer.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 083d00d1a..84e18b1f1 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -47,7 +47,11 @@ struct reading { bool moved() const; }; -// the saved odometer states of the vehicles, km by vehicle name +// the saved odometer states of the vehicles, km by vehicle name. the name is the one the scenario gives the vehicle +// (the name of its node, TDynamicObject::name(), e.g. EU07-424), the only identity a vehicle has between the sessions: +// the vehicles of the same name in any scenarios share one state, whatever their type, and a vehicle the scenario +// names otherwise starts over, from the legacy or a made up state. the sceneries name the real vehicles by their +// numbers, so it's the same vehicle as a rule class store { public: // reads the states written by write(). lines " ", "~ " for a state counted From 8029740770593271d3b1523a50be21c5036a4a9b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 9 Nov 2026 16:27:45 +0100 Subject: [PATCH 15/37] fix: read the odometer files of the koliber screens too, say why the unit renderers' drop a letter the renderers of the units (elf_v1, impuls_v1) keep the unit's state, their cars are named after the unit and the letter of the car (EN76-022a .. EN76-022d), so they drop the last character. the koliber screens of scripts/ keep theirs in scripts/kilometry by the whole name, which wasn't read --- tests/unit/test_odometer.cpp | 19 +++++++++++++++++++ vehicle/odometer.cpp | 32 ++++++++++++++++++++++++-------- vehicle/odometer.h | 16 ++++++++++++---- 3 files changed, 55 insertions(+), 12 deletions(-) diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 5e287116b..5ec1b572f 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -434,3 +434,22 @@ TEST_CASE("odometer: only the vehicles with a driver's cab are recorded") { CHECK(read.find("old wagon").value() == 300.0); } } + +TEST_CASE("odometer: the files of both kinds of python screens are read, by the name each used") { + scratch_directory directory{"odometer_legacy_screens"}; + auto const vehicles{directory.path / "dynamic" / "elf_v1"}; + auto const scripts{directory.path / "scripts"}; + // the renderers of the units, next to the .mmd: state['name'][:-1], the cab cars of a unit share the file + write_file(vehicles / "kilometry" / "EN76-022_przebieg.txt", "250000.5"); + CHECK(odometer::legacy_state(vehicles, "EN76-022a", scripts).value() == 250000.5); + CHECK(odometer::legacy_state(vehicles, "EN76-022d", scripts).value() == 250000.5); + // the shared screens of scripts/ (koliber_*): the whole name + write_file(scripts / "kilometry" / "EU07-424_przebieg.txt", "123456.0"); + CHECK(odometer::legacy_state(vehicles, "EU07-424", scripts).value() == 123456.0); + auto const started{odometer::starting_state(odometer::store{}, "EU07-424", vehicles, scripts)}; + CHECK(started.source == odometer::origin::legacy); + CHECK(started.km == 123456.0); + // neither + CHECK_FALSE(odometer::legacy_state(vehicles, "EU07-425", scripts).has_value()); + CHECK_FALSE(odometer::legacy_state(vehicles, "", scripts).has_value()); +} diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index 60c119f12..8ecf9a9c1 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -178,19 +178,34 @@ std::optional read_legacy(std::istream &Input) { return parse_number(content.str()); } -std::optional legacy_state(std::filesystem::path const &Vehicledirectory, std::string const &Vehicle) { - if (Vehicle.size() < 2) - return std::nullopt; - auto const path{Vehicledirectory / "kilometry" / (Vehicle.substr(0, Vehicle.size() - 1) + "_przebieg.txt")}; +namespace { + +std::optional read_legacy_file(std::filesystem::path const &Path) { std::error_code error; - if (false == std::filesystem::is_regular_file(path, error)) + if (false == std::filesystem::is_regular_file(Path, error)) return std::nullopt; - std::ifstream input{path, std::ios::binary}; + std::ifstream input{Path, std::ios::binary}; if (false == input.is_open()) return std::nullopt; return read_legacy(input); } +} // namespace + +std::optional legacy_state(std::filesystem::path const &Vehicledirectory, std::string const &Vehicle, + std::filesystem::path const &Scriptsdirectory) { + if (Vehicle.empty()) + return std::nullopt; + // the renderers of the units drop the letter of the car, the file is the unit's (see the header) + if (Vehicle.size() > 1) { + auto const unit{read_legacy_file(Vehicledirectory / "kilometry" / (Vehicle.substr(0, Vehicle.size() - 1) + "_przebieg.txt"))}; + if (unit.has_value()) + return unit; + } + // the shared screens of scripts/ keep the whole name + return read_legacy_file(Scriptsdirectory / "kilometry" / (Vehicle + "_przebieg.txt")); +} + double guessed_state(std::string const &Vehicle) { // FNV-1a, stable between the builds unlike std::hash std::uint64_t hash{14695981039346656037ull}; @@ -201,7 +216,8 @@ double guessed_state(std::string const &Vehicle) { return 10000.0 + static_cast(hash % 490000ull); } -reading starting_state(store const &States, std::string const &Vehicle, std::filesystem::path const &Vehicledirectory) { +reading starting_state(store const &States, std::string const &Vehicle, std::filesystem::path const &Vehicledirectory, + std::filesystem::path const &Scriptsdirectory) { reading result; if (auto const saved{States.find(Vehicle)}; saved.has_value()) { if (States.guessed(Vehicle)) { @@ -212,7 +228,7 @@ reading starting_state(store const &States, std::string const &Vehicle, std::fil } else { result.begin(*saved, origin::saved); } - } else if (auto const legacy{legacy_state(Vehicledirectory, Vehicle)}; legacy.has_value()) { + } else if (auto const legacy{legacy_state(Vehicledirectory, Vehicle, Scriptsdirectory)}; legacy.has_value()) { result.begin(*legacy, origin::legacy); } else { result.begin(guessed_state(Vehicle), origin::guessed); diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 84e18b1f1..83396abfd 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -95,10 +95,17 @@ private: // store already holds for any of them stay as they are void record(store &States, std::string const &Vehicle, bool Drivercab, reading const &Odometer); -// state kept in the file of the python screens before (/kilometry/_przebieg.txt, -// where the screens dropped the last character of the vehicle name), when it holds a number +// state kept in the file of the python screens before, when it holds a number. the screens opened the file in the +// directory of their script (lookup_path), and two kinds of them kept one: +// - the renderers of the units, next to the .mmd (elf_v1: EN62, EN76, EN96, SKM; impuls_v1: EN63), in +// /kilometry/_przebieg.txt (state['name'][:-1]). the cars of +// these units are named after the unit and the letter of the car (EN76-022a .. EN76-022d, ED78-019A .. ED78-019D), +// so the cab cars at both ends of a unit share one file, the unit's odometer +// - the shared screens in scripts/ (koliber_hasler_elektroniczny, koliber_unicontrols_tramex[_ic]), in +// /kilometry/_przebieg.txt, the whole name std::optional read_legacy(std::istream &Input); -std::optional legacy_state(std::filesystem::path const &Vehicledirectory, std::string const &Vehicle); +std::optional legacy_state(std::filesystem::path const &Vehicledirectory, std::string const &Vehicle, + std::filesystem::path const &Scriptsdirectory = "scripts"); // made up state of a vehicle nothing is known about: a number from the name, in [10 000, 500 000) km, // the same each session until the vehicle runs and gets its state saved @@ -106,7 +113,8 @@ double guessed_state(std::string const &Vehicle); // state a vehicle starts the session with: the saved one, else the legacy one, else a guessed one. a saved state // counted from a guessed one stays guessed, so the cab's counter can still replace the made up part of it -reading starting_state(store const &States, std::string const &Vehicle, std::filesystem::path const &Vehicledirectory); +reading starting_state(store const &States, std::string const &Vehicle, std::filesystem::path const &Vehicledirectory, + std::filesystem::path const &Scriptsdirectory = "scripts"); // state the cab's counter with offset Offset and scale Scale shows, once its offset no longer applies // (the counter shows the odometer). nothing for a counter without an offset From b256c3efa9ea79f47e82052c078b9573bf3a16cd Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 9 Nov 2026 16:31:43 +0100 Subject: [PATCH 16/37] refactor: MOVER.h includes the odometer's plain data only odometer::reading moves to vehicle/odometerreading.h, the store with its files stays in vehicle/odometer.h, so the physics header doesn't pull in the filesystem and the streams --- McZapkie/MOVER.h | 2 +- vehicle/Train.cpp | 1 + vehicle/odometer.h | 28 ++------------------------ vehicle/odometerreading.h | 42 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 46 insertions(+), 27 deletions(-) create mode 100644 vehicle/odometerreading.h diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index d461269b1..aa64b1cf0 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -15,7 +15,7 @@ http://mozilla.org/MPL/2.0/. #include #include "hamulce.h" #include "scripting/ladderlogic.h" -#include "vehicle/odometer.h" +#include "vehicle/odometerreading.h" class cParser; /* diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 9987b66b3..128335d17 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/horn.h" #include "vehicle/linebreaker.h" #include "vehicle/holdcoillever.h" +#include "vehicle/odometer.h" #include "utilities/Globals.h" #include "simulation/simulation.h" diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 83396abfd..93685d281 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -15,38 +15,14 @@ http://mozilla.org/MPL/2.0/. #include #include +#include "vehicle/odometerreading.h" + // the odometer of a vehicle: the total distance it has run, kept between the sessions (eu07/maszyna#72). // the analog counters in the cab (distcounter:) and the python screens (state["odometer_total"]) show // this one state, instead of the counters starting from their .mmd offset and the screens each keeping // their own files namespace odometer { -// where the state of a vehicle came from -enum class origin { - saved, // the odometer store of the earlier sessions - legacy, // the file a python screen kept it in before - counter, // the offset of the cab's counter, which used to show it on top of the distance run in the session - guessed // counted from a made up state, which the cab's counter can still replace, also once it was saved -}; - -// odometer of one vehicle -struct reading { - double km{0.0}; // the state, km - double start{0.0}; // the state at the start of the session, km - origin source{origin::guessed}; - double guess{0.0}; // the made up state a guessed one counts from, km - - // sets the state the vehicle starts the session with - void begin(double Km, origin Source); - // replaces the made up state a guessed one counts from with the one the cab's counter showed at the start, - // the distance run on top of it kept, in this session and the earlier ones. a known state stays - void seed(double Km); - // counts the distance run, in metres either way - void run(double Metres); - // the vehicle has run in this session - bool moved() const; -}; - // the saved odometer states of the vehicles, km by vehicle name. the name is the one the scenario gives the vehicle // (the name of its node, TDynamicObject::name(), e.g. EU07-424), the only identity a vehicle has between the sessions: // the vehicles of the same name in any scenarios share one state, whatever their type, and a vehicle the scenario diff --git a/vehicle/odometerreading.h b/vehicle/odometerreading.h new file mode 100644 index 000000000..1b7d028da --- /dev/null +++ b/vehicle/odometerreading.h @@ -0,0 +1,42 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// the odometer of a vehicle (eu07/maszyna#72), the part the vehicle physics (TMoverParameters::Odometer) keeps: plain +// data, without the store and its files, which are in vehicle/odometer.h +namespace odometer { + +// where the state of a vehicle came from +enum class origin { + saved, // the odometer store of the earlier sessions + legacy, // the file a python screen kept it in before + counter, // the offset of the cab's counter, which used to show it on top of the distance run in the session + guessed // counted from a made up state, which the cab's counter can still replace, also once it was saved +}; + +// odometer of one vehicle +struct reading { + double km{0.0}; // the state, km + double start{0.0}; // the state at the start of the session, km + origin source{origin::guessed}; + double guess{0.0}; // the made up state a guessed one counts from, km + + // sets the state the vehicle starts the session with + void begin(double Km, origin Source); + // replaces the made up state a guessed one counts from with the one the cab's counter showed at the start, + // the distance run on top of it kept, in this session and the earlier ones. a known state stays + void seed(double Km); + // counts the distance run, in metres either way + void run(double Metres); + // the vehicle has run in this session + bool moved() const; +}; + +} // namespace odometer From c9792672c654eee57dc7709e7a5e1d9dbee74ed7 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Mon, 9 Nov 2026 23:41:14 +0000 Subject: [PATCH 17/37] fix(render): textures of a far vehicle no longer come back black with gfx.resource.move (#308) --- model/Texture.cpp | 90 ++++++++++++++++++++++++++++++++++++----------- model/Texture.h | 3 ++ 2 files changed, 73 insertions(+), 20 deletions(-) diff --git a/model/Texture.cpp b/model/Texture.cpp index 4a7b24792..29787ee8a 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -28,6 +28,8 @@ http://mozilla.org/MPL/2.0/. #include "dds-ktx/dds-ktx.h" #include "winheaders.h" +#include + #define EU07_DEFERRED_TEXTURE_UPLOAD #ifndef FOURCC_DX10 @@ -303,6 +305,20 @@ bool bptc_supported() { }(); return supported; } +// format of a compressed texture read back from the gpu, given as the image would have it: the driver tells the srgb variant +// of the format, which the mapping doesn't take. with the components hint of the texture the linear one gives the same gl +// format again on the next upload +GLint readback_format( GLint const Internalformat ) { + switch( Internalformat ) { + case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: { return GL_COMPRESSED_RGBA8_ETC2_EAC; } + case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; } + case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; } + case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; } + case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM: { return GL_COMPRESSED_RGBA_BPTC_UNORM; } + default: { return Internalformat; } + } +} + } // namespace std::array opengl_texture::units = { 0 }; @@ -1502,29 +1518,13 @@ opengl_texture::release() { } else { ::glBindTexture(target, id ); - GLint datasize {}; GLint iscompressed {}; ::glGetTexLevelParameteriv(target, 0, GL_TEXTURE_COMPRESSED, &iscompressed ); - if( iscompressed == GL_TRUE ) { - // texture is compressed on the gpu side - // query texture details needed to perform the backup... - ::glGetTexLevelParameteriv(target, 0, GL_TEXTURE_INTERNAL_FORMAT, &data_format ); - ::glGetTexLevelParameteriv(target, 0, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &datasize ); - data.resize( datasize ); - // ...fetch the data... - ::glGetCompressedTexImage(target, 0, &data[ 0 ] ); + if( ( iscompressed != GL_TRUE ) + || ( false == read_back_compressed() ) ) { + // the texture didn't get compressed during upload, or got a format the upload doesn't take + read_back_uncompressed(); } - else { - // for whatever reason texture didn't get compressed during upload - // fallback on plain rgba storage... - data_format = GL_RGBA; - data_type = GL_UNSIGNED_BYTE; - data.resize( data_width * data_height * 4 ); - // ...fetch the data... - ::glGetTexImage(target, 0, data_format, GL_UNSIGNED_BYTE, &data[ 0 ] ); - } - // ...and update texture object state - data_mapcount = 1; // we keep copy of only top mipmap level data_state = resource_state::good; } } @@ -1536,6 +1536,56 @@ opengl_texture::release() { return; } +// copies all mipmaps of the compressed gl texture into the data, in the layout of a dds file. returns false, leaving the data as +// it was, when the format can't be uploaded again as it is. all levels are kept since the driver may not generate mipmaps +// of a compressed format; without them the texture would be incomplete and drawn black +bool +opengl_texture::read_back_compressed() { + + GLint internalformat {}; + ::glGetTexLevelParameteriv( target, 0, GL_TEXTURE_INTERNAL_FORMAT, &internalformat ); + auto const format { readback_format( internalformat ) }; + if( ( false == precompressed_formats.contains( format ) ) + || ( false == mapping.contains( format ) ) ) { + return false; + } + auto const levelcount { static_cast( std::bit_width( std::max( data_width, data_height ) ) ) }; + std::vector leveldata; + auto mapcount { 0 }; + while( mapcount < levelcount ) { + GLint levelwidth {}; + GLint levelsize {}; + ::glGetTexLevelParameteriv( target, mapcount, GL_TEXTURE_WIDTH, &levelwidth ); + ::glGetTexLevelParameteriv( target, mapcount, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &levelsize ); + if( ( levelwidth <= 0 ) || ( levelsize <= 0 ) ) { + // the levels past the last one present weren't made + break; + } + auto const offset { leveldata.size() }; + leveldata.resize( offset + static_cast( levelsize ) ); + ::glGetCompressedTexImage( target, mapcount, &leveldata[ offset ] ); + ++mapcount; + } + if( mapcount == 0 ) { + return false; + } + data.swap( leveldata ); + data_format = format; + data_mapcount = static_cast( mapcount ); + return true; +} + +// copies the top level of the gl texture into the data as plain rgba, the mipmaps are generated again on upload +void +opengl_texture::read_back_uncompressed() { + + data_format = GL_RGBA; + data_type = GL_UNSIGNED_BYTE; + data.resize( data_width * data_height * 4 ); + ::glGetTexImage( target, 0, data_format, GL_UNSIGNED_BYTE, &data[ 0 ] ); + data_mapcount = 1; +} + void opengl_texture::alloc_rendertarget( GLint format, GLint components, int width, int height, int l, int s, GLint wrap ) { diff --git a/model/Texture.h b/model/Texture.h index 0a4ae62ec..313d0f6f4 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -117,6 +117,9 @@ public: // takes over the data read by a worker thread, waiting for it if needed void complete_data(); + // with gfx.resource.move, copies the gl texture back into the data before it's released. requires the texture bound + bool read_back_compressed(); + void read_back_uncompressed(); // members std::shared_ptr request; // data being read by a worker thread From 18c333b08952b537de6f6f4866ea0796769fb571 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Tue, 10 Nov 2026 00:57:37 +0100 Subject: [PATCH 18/37] wasm display support --- .gitmodules | 4 + CMakeLists.txt | 15 + CMake_modules/wamr/CMakeLists.txt | 67 +++ application/application.cpp | 7 + application/application.h | 6 + model/Texture.cpp | 4 + ref/wamr | 1 + scripting/wasmscreenkernels.cpp | 242 ++++++++ scripting/wasmscreenkernels.h | 36 ++ scripting/wasmscreenrules.cpp | 126 ++++ scripting/wasmscreenrules.h | 74 +++ scripting/wasmscreens.cpp | 942 ++++++++++++++++++++++++++++++ scripting/wasmscreens.h | 72 +++ scripting/wasmscreensstub.cpp | 51 ++ tests/unit/CMakeLists.txt | 5 + tests/unit/test_wasm_host.cpp | 288 +++++++++ tests/unit/test_wasm_kernels.cpp | 121 ++++ tests/unit/test_wasm_screens.cpp | 103 ++++ utilities/Globals.cpp | 33 ++ utilities/Globals.h | 4 + vehicle/DynObj.cpp | 77 ++- vehicle/DynObj.h | 13 + vehicle/Train.cpp | 110 +++- vehicle/Train.h | 14 + wasm_screens_doc.md | 129 ++++ 25 files changed, 2521 insertions(+), 23 deletions(-) create mode 100644 CMake_modules/wamr/CMakeLists.txt create mode 160000 ref/wamr create mode 100644 scripting/wasmscreenkernels.cpp create mode 100644 scripting/wasmscreenkernels.h create mode 100644 scripting/wasmscreenrules.cpp create mode 100644 scripting/wasmscreenrules.h create mode 100644 scripting/wasmscreens.cpp create mode 100644 scripting/wasmscreens.h create mode 100644 scripting/wasmscreensstub.cpp create mode 100644 tests/unit/test_wasm_host.cpp create mode 100644 tests/unit/test_wasm_kernels.cpp create mode 100644 tests/unit/test_wasm_screens.cpp create mode 100644 wasm_screens_doc.md diff --git a/.gitmodules b/.gitmodules index df7f5ddaa..55d108a70 100644 --- a/.gitmodules +++ b/.gitmodules @@ -32,3 +32,7 @@ [submodule "betterRenderer/thirdparty/bvh"] path = betterRenderer/thirdparty/bvh url = https://github.com/madmann91/bvh.git +[submodule "ref/wamr"] + path = ref/wamr + url = https://github.com/bytecodealliance/wasm-micro-runtime + shallow = true diff --git a/CMakeLists.txt b/CMakeLists.txt index 7137ab39a..b75f3295b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -72,6 +72,7 @@ option(WITH_OPENGL_LEGACY "Compile with OpenGL legacy renderer" ON) option(WITH_PYTHON "Python 3.14 embedded scripting" ON) option(WITH_UART "Compile with libserialport" ON) option(WITH_LUA "Compile with lua scripting support" ON) +option(WITH_WASM "WebAssembly screens (wasmscreen:, wasmdestinationsign:), run by the WAMR interpreter in ref/wamr" ON) option(WITH_OPENVR "Compile with OpenVR" OFF) option(WITH_ZMQ "Compile with cppzmq" OFF) option(WITH_CRASHPAD "Compile with crashpad" OFF) @@ -321,6 +322,13 @@ if (WITH_LUA) set(SOURCES ${SOURCES} "scripting/lua.cpp") endif() +if (WITH_WASM) + set(DEFINITIONS ${DEFINITIONS} "WITH_WASM") + set(SOURCES ${SOURCES} "scripting/wasmscreens.cpp") +else() + set(SOURCES ${SOURCES} "scripting/wasmscreensstub.cpp") +endif() + if (WITHDUMPGEN) set(DEFINITIONS ${DEFINITIONS} "WITHDUMPGEN") endif() @@ -463,6 +471,8 @@ set(CORE_SOURCES "utilities/parser.cpp" "utilities/utilities.cpp" "scripting/ladderlogic.cpp" +"scripting/wasmscreenrules.cpp" +"scripting/wasmscreenkernels.cpp" "simulation/simulationtestrules.cpp" "vehicle/enginestart.cpp" "vehicle/handover.cpp" @@ -677,6 +687,11 @@ if(WIN32 AND WITH_PYTHON) ) endif() +if (WITH_WASM) + add_subdirectory("CMake_modules/wamr" "${CMAKE_CURRENT_BINARY_DIR}/wamr") + target_link_libraries(${PROJECT_NAME} eu07_wamr) +endif () + if (WITH_BETTER_RENDERER) add_subdirectory("betterRenderer") set_target_properties(betterRenderer betterRenderer_fsr2 betterRenderer_shaders PROPERTIES FOLDER "renderers") diff --git a/CMake_modules/wamr/CMakeLists.txt b/CMake_modules/wamr/CMakeLists.txt new file mode 100644 index 000000000..74e82358d --- /dev/null +++ b/CMake_modules/wamr/CMakeLists.txt @@ -0,0 +1,67 @@ +# The WebAssembly Micro Runtime (ref/wamr) for the wasm screens (scripting/wasmscreens.cpp). +# +# Built here, in a directory of its own, because the WAMR build scripts set their configuration with +# add_definitions() and include_directories(): kept in this directory, none of it reaches the game's sources. +# Only the interpreter is built (see WAMR_BUILD_FAST_INTERP), with instruction metering so that a screen stuck in a loop +# can't hang the worker thread, and without the signal-based bounds checks, which would compete with the +# game's own crash handling. + +if (WIN32) + set(WAMR_BUILD_PLATFORM "windows") +elseif (APPLE) + set(WAMR_BUILD_PLATFORM "darwin") +else () + set(WAMR_BUILD_PLATFORM "linux") +endif () + +set(WAMR_ROOT_DIR "${CMAKE_SOURCE_DIR}/ref/wamr") + +set(WAMR_BUILD_INTERP 1) +# the fast interpreter counts the instructions only where it dispatches with computed gotos (GCC, Clang): built with +# MSVC it would let a screen stuck in a loop hang the worker. the classic interpreter counts them everywhere +if (MSVC) + set(WAMR_BUILD_FAST_INTERP 0) +else () + set(WAMR_BUILD_FAST_INTERP 1) +endif () +set(WAMR_BUILD_AOT 0) +set(WAMR_BUILD_JIT 0) +set(WAMR_BUILD_FAST_JIT 0) +set(WAMR_BUILD_LIBC_BUILTIN 0) +set(WAMR_BUILD_LIBC_WASI 0) +set(WAMR_BUILD_MULTI_MODULE 0) +set(WAMR_BUILD_LIB_PTHREAD 0) +set(WAMR_BUILD_LIB_WASI_THREADS 0) +set(WAMR_BUILD_THREAD_MGR 0) +set(WAMR_BUILD_SIMD 0) +set(WAMR_BUILD_BULK_MEMORY 1) +set(WAMR_BUILD_REF_TYPES 1) +set(WAMR_BUILD_MINI_LOADER 0) +set(WAMR_BUILD_INSTRUCTION_METERING 1) +# NOTE: the calls into the natives use WAMR's assembler invokeNative (MASM with MSVC). its C version +# (WAMR_BUILD_INVOKE_NATIVE_GENERAL) crashes on Windows x64 as soon as a module runs +set(WAMR_DISABLE_HW_BOUND_CHECK 1) +set(WAMR_DISABLE_STACK_HW_BOUND_CHECK 1) + +find_package(Threads REQUIRED) +include("${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake") + +add_library(eu07_wamr STATIC ${WAMR_RUNTIME_LIB_SOURCE}) +target_include_directories(eu07_wamr INTERFACE "${WAMR_ROOT_DIR}/core/iwasm/include") +# with MSVC the WAMR headers declare the API dllimport unless told otherwise; the library is linked statically +target_compile_definitions(eu07_wamr INTERFACE "WASM_RUNTIME_API_EXTERN=") +target_link_libraries(eu07_wamr PRIVATE Threads::Threads) +if (WIN32) + target_link_libraries(eu07_wamr PRIVATE ws2_32 ntdll) +else () + target_link_libraries(eu07_wamr PRIVATE m ${CMAKE_DL_LIBS}) +endif () +if (MSVC) + # third-party code: its warnings are not ours to fix + target_compile_options(eu07_wamr PRIVATE /W0) +else () + target_compile_options(eu07_wamr PRIVATE -w) +endif () +set_target_properties(eu07_wamr PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" + FOLDER "libraries") diff --git a/application/application.cpp b/application/application.cpp index a398117c7..98f004a92 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -425,6 +425,11 @@ int eu07_application::init(int Argc, char *Argv[]) { m_taskqueue.init(); } + crashreport_add_info("wasm_enabled", Global.wasm_enabled ? "yes" : "no"); + if (Global.wasm_enabled) + { + m_wasmqueue.init(); + } if ((result = init_modes()) != 0) { ErrorLog("Failed to initialize game modes"); @@ -635,6 +640,7 @@ int eu07_application::run() EditorTerrain.update(Global.pCamera.Pos); m_taskqueue.update(); + m_wasmqueue.update(); opengl_texture::reset_unit_cache(); if (!GfxRenderer->Render()) @@ -732,6 +738,7 @@ void eu07_application::exit() // the python workers detach their GL context on the way out, so they have to be done before the windows they use are destroyed m_taskqueue.exit(); + m_wasmqueue.exit(); step("the windows"); for (auto *window : m_windows) { diff --git a/application/application.h b/application/application.h index 11415603b..4a1d1ad1a 100644 --- a/application/application.h +++ b/application/application.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "application/applicationmode.h" #include "scripting/PyInt.h" +#include "scripting/wasmscreens.h" #include "network/manager.h" #include "utilities/headtrack.h" #ifdef WITH_UART @@ -49,6 +50,10 @@ public: // frees the python gil and swaps out the main thread void release_python_lock(); + // the screens drawn by WebAssembly modules + wasm_screen_queue & + wasm_screens() { + return m_wasmqueue; } void exit(); void @@ -122,6 +127,7 @@ private: modeptr_array m_modes { nullptr }; // collection of available application behaviour modes mode_stack m_modestack; // current behaviour mode python_taskqueue m_taskqueue; + wasm_screen_queue m_wasmqueue; std::vector m_windows; int m_glfwversion; diff --git a/model/Texture.cpp b/model/Texture.cpp index 4a7b24792..e9dc063de 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -722,6 +722,10 @@ void opengl_texture::make_request() { auto const components { Split( name, '?' ) }; + if( components.front().ends_with( ".wasm" ) ) { + // wasm destination signs are drawn by the vehicles showing them (wasm_screen_queue) + return; + } auto dictionary = std::make_shared( components.back() ); diff --git a/ref/wamr b/ref/wamr new file mode 160000 index 000000000..25bd7eb63 --- /dev/null +++ b/ref/wamr @@ -0,0 +1 @@ +Subproject commit 25bd7eb63e828e4bd242cc9b38d260b4b31c6605 diff --git a/scripting/wasmscreenkernels.cpp b/scripting/wasmscreenkernels.cpp new file mode 100644 index 000000000..4353f1894 --- /dev/null +++ b/scripting/wasmscreenkernels.cpp @@ -0,0 +1,242 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "scripting/wasmscreenkernels.h" + +#include +#include +#include +#include +#include + +namespace wasm_screens +{ + +namespace +{ + +constexpr int glow_radius{6}; +constexpr double glow_factor{0.08}; + +using light = std::array; + +// led_util's get_px_str: the light gathered from the diodes around, weighted 1 / (0.08 + distance squared), the sums +// taken in the same order as there to get the very same numbers +light glow_at(std::span const Source, int const Width, int const Height, int const X, int const Y) +{ + std::array sum{}; + auto const left{std::max(X - glow_radius, 0)}; + auto const right{std::min(X + glow_radius + 1, Width)}; + auto const top{std::max(Y - glow_radius, 0)}; + auto const bottom{std::min(Y + glow_radius + 1, Height)}; + for (auto i = left; i < right; ++i) + { + auto const m{glow_factor + static_cast((i - X) * (i - X))}; + if (m > 20.0) + { + continue; + } + for (auto j = top; j < bottom; ++j) + { + auto const s{m + static_cast((j - Y) * (j - Y))}; + if (s > 20.0) + { + continue; + } + auto const *pixel{&Source[(static_cast(j) * Width + i) * 4]}; + for (std::size_t channel = 0; channel < 3; ++channel) + { + sum[channel] += static_cast(pixel[channel]) / s; + } + } + } + return {static_cast(sum[0] * glow_factor), static_cast(sum[1] * glow_factor), static_cast(sum[2] * glow_factor)}; +} + +double sinc(double X) +{ + if (X == 0.0) + { + return 1.0; + } + X *= std::numbers::pi; + return std::sin(X) / X; +} + +double lanczos(double const X) +{ + if (X >= -3.0 && X < 3.0) + { + return sinc(X) * sinc(X / 3.0); + } + return 0.0; +} + +constexpr int precision_bits{32 - 8 - 2}; + +// the fixed-point weights of one pass, as Pillow's Resample.c (precompute_coeffs, normalize_coeffs_8bpc) makes them +struct coefficients +{ + int size{0}; + std::vector> bounds; // first input sample and the number of samples, per output sample + std::vector weights; + + coefficients(int const Input, int const Output) + { + auto const scale{static_cast(Input) / static_cast(Output)}; + auto const filterscale{std::max(scale, 1.0)}; + auto const support{3.0 * filterscale}; + size = static_cast(std::ceil(support)) * 2 + 1; + bounds.reserve(Output); + weights.assign(static_cast(Output) * size, 0); + std::vector prepared(size); + for (auto xx = 0; xx < Output; ++xx) + { + auto const center{(xx + 0.5) * scale}; + auto const ss{1.0 / filterscale}; + auto const xmin{std::max(static_cast(center - support + 0.5), 0)}; + auto const xmax{std::min(static_cast(center + support + 0.5), Input) - xmin}; + auto total{0.0}; + for (auto x = 0; x < xmax; ++x) + { + prepared[x] = lanczos((x + xmin - center + 0.5) * ss); + total += prepared[x]; + } + for (auto x = 0; x < xmax; ++x) + { + if (total != 0.0) + { + prepared[x] /= total; + } + auto const fixed{prepared[x] * static_cast(1 << precision_bits)}; + weights[static_cast(xx) * size + x] = static_cast(prepared[x] < 0.0 ? -0.5 + fixed : 0.5 + fixed); + } + bounds.emplace_back(xmin, xmax); + } + } + + static std::uint8_t clip(std::int64_t const Sum) + { + if (Sum >= (std::int64_t{1} << (precision_bits + 8))) + { + return 255; + } + if (Sum <= 0) + { + return 0; + } + return static_cast(Sum >> precision_bits); + } +}; + +constexpr std::int64_t rounding{std::int64_t{1} << (precision_bits - 1)}; + +// one pass of the resampling, along rows (Step 4: neighbouring pixels) or along columns (Step: a row) +struct pass +{ + coefficients const &weights; + std::size_t step; // bytes between the samples the pass mixes +}; + +std::uint8_t mix(std::uint8_t const *First, pass const &Pass, std::size_t const Index) +{ + auto const count{Pass.weights.bounds[Index].second}; + auto const offset{Index * static_cast(Pass.weights.size)}; + auto sum{rounding}; + for (auto sample = 0; sample < count; ++sample) + { + sum += static_cast(First[sample * Pass.step]) * Pass.weights.weights[offset + sample]; + } + return coefficients::clip(sum); +} + +} // namespace + +bool led_post(std::span const Source, int const Width, int const Height, std::span const Target, bool const Bloom) +{ + auto const targetwidth{Width * 2 + 2}; + auto const targetheight{Height * 2 + 2}; + if (Width <= 0 || Height <= 0 || Source.size() < image_size(Width, Height) || Target.size() < image_size(targetwidth, targetheight)) + { + return false; + } + // the light of every diode; above 255 it is clamped only in the final pixels, as led_util (Pillow) does + std::vector diodes(static_cast(Width) * Height); + for (auto y = 0; y < Height; ++y) + { + for (auto x = 0; x < Width; ++x) + { + auto const at{(static_cast(y) * Width + x) * 4}; + diodes[static_cast(y) * Width + x] = Bloom ? glow_at(Source, Width, Height, x, y) : light{Source[at], Source[at + 1], Source[at + 2]}; + } + } + // a black frame, then the diodes + for (std::size_t idx = 0; idx < image_size(targetwidth, targetheight); ++idx) + { + Target[idx] = idx % 4 == 3 ? 255 : 0; + } + for (auto i = 0; i < Width * 2; ++i) + { + for (auto j = 0; j < Height * 2; ++j) + { + auto const &diode{diodes[static_cast(j / 2) * Width + i / 2]}; + auto const shade{1.0 - static_cast(i % 2 + j % 2) * 0.15}; + auto *pixel{&Target[(static_cast(j + 1) * targetwidth + (i + 1)) * 4]}; + for (std::size_t channel = 0; channel < 3; ++channel) + { + pixel[channel] = static_cast(std::clamp(static_cast(static_cast(diode[channel]) * shade), 0, 255)); + } + } + } + return true; +} + +bool resize_lanczos(std::span const Source, int const Width, int const Height, std::span const Target, int const TargetWidth, + int const TargetHeight) +{ + if (Width <= 0 || Height <= 0 || TargetWidth <= 0 || TargetHeight <= 0 || Source.size() < image_size(Width, Height) || + Target.size() < image_size(TargetWidth, TargetHeight)) + { + return false; + } + coefficients const horizontal{Width, TargetWidth}; + coefficients const vertical{Height, TargetHeight}; + + std::vector temporary(image_size(TargetWidth, Height)); + pass const along_row{horizontal, 4}; + for (auto y = 0; y < Height; ++y) + { + for (auto x = 0; x < TargetWidth; ++x) + { + auto const *first{&Source[(static_cast(y) * Width + horizontal.bounds[x].first) * 4]}; + for (std::size_t channel = 0; channel < 3; ++channel) + { + temporary[(static_cast(y) * TargetWidth + x) * 4 + channel] = mix(first + channel, along_row, x); + } + } + } + pass const along_column{vertical, static_cast(TargetWidth) * 4}; + for (auto y = 0; y < TargetHeight; ++y) + { + for (auto x = 0; x < TargetWidth; ++x) + { + auto const *first{&temporary[(static_cast(vertical.bounds[y].first) * TargetWidth + x) * 4]}; + auto *pixel{&Target[(static_cast(y) * TargetWidth + x) * 4]}; + for (std::size_t channel = 0; channel < 3; ++channel) + { + pixel[channel] = mix(first + channel, along_column, y); + } + pixel[3] = 255; + } + } + return true; +} + +} // namespace wasm_screens diff --git a/scripting/wasmscreenkernels.h b/scripting/wasmscreenkernels.h new file mode 100644 index 000000000..15400e4b6 --- /dev/null +++ b/scripting/wasmscreenkernels.h @@ -0,0 +1,36 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +// image filters the wasm screens call through the host (eu07.led_post, eu07.resize_lanczos), run natively rather than +// in the interpreter. they give the very pixels of the Python screens: led_util.render_post() and Pillow's +// resize(..., Image.LANCZOS). the images are RGBA, 4 bytes a pixel, row by row; alpha is ignored and written as 255 +namespace wasm_screens +{ + +// the size in bytes of an RGBA image +constexpr std::size_t image_size(int const Width, int const Height) +{ + return static_cast(Width) * static_cast(Height) * 4; +} + +// led_util's render_post: every diode becomes 2x2 pixels with a darker grid between them, glowing into its neighbours +// (Bloom), in a 1 pixel black frame. Target takes (2 Width + 2) x (2 Height + 2) pixels. returns false for sizes that +// don't fit the spans +bool led_post(std::span Source, int Width, int Height, std::span Target, bool Bloom); + +// Pillow's resize with the Lanczos filter, horizontally then vertically, each pass rounded to 8 bits. returns false +// for sizes that don't fit the spans +bool resize_lanczos(std::span Source, int Width, int Height, std::span Target, int TargetWidth, int TargetHeight); + +} // namespace wasm_screens diff --git a/scripting/wasmscreenrules.cpp b/scripting/wasmscreenrules.cpp new file mode 100644 index 000000000..efd4bf424 --- /dev/null +++ b/scripting/wasmscreenrules.cpp @@ -0,0 +1,126 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "scripting/wasmscreenrules.h" + +#include "utilities/parser.h" + +#include + +namespace wasm_screens +{ + +void screen_config::deserialize(cParser &Input) +{ + while (deserialize_mapping(Input)) + { + // all work done by while() + } +} + +bool screen_config::deserialize_mapping(cParser &Input) +{ + // token can be a key or block end + auto const key{Input.getToken(true, "\n\r\t ,;[]")}; + + if (key.empty() || key == "}") + { + return false; + } + + if (key == "{") + { + script = Input.getToken(); + } + else if (key == "target:") + { + target = Input.getToken(); + } + else if (key == "frames:") + { + frames = Input.getToken(); + } + else if (key == "parameters:") + { + parameters = Input.getToken(); + } + else if (key == "instance:") + { + instancing = Input.getToken(); + } + else if (key == "background:") + { + background = Input.getToken(); + } + else + { + // a key of a later version: skip its value + Input.getToken(); + } + + return true; +} + +frame_schedule::frame_schedule(std::uint64_t const Start, int const Interval, int const Phase) + : m_interval{std::max(Interval, 1)}, m_next{Start + static_cast(std::max(Phase, 0))} +{ +} + +int frame_schedule::effective_interval(int const Configured, int const Requested) +{ + return std::max({Configured, Requested, 1}); +} + +int frame_schedule::phase(std::string_view const Key, int const Interval) +{ + if (Interval <= 1) + { + return 0; + } + // FNV-1a: the same offset for the same name on every compiler + std::uint32_t hash{2166136261u}; + for (auto const character : Key) + { + hash ^= static_cast(character); + hash *= 16777619u; + } + return static_cast(hash % static_cast(Interval)); +} + +bool frame_schedule::poll(std::uint64_t const Frame) +{ + if (Frame < m_next) + { + return false; + } + m_next = Frame + static_cast(m_interval); + return true; +} + +bool is_safe_relative_path(std::string_view const Path) +{ + if (Path.empty() || Path.front() == '/' || Path.front() == '\\' || Path.find(':') != std::string_view::npos) + { + return false; + } + std::size_t start{0}; + while (start <= Path.size()) + { + auto const end{std::min(Path.find_first_of("/\\", start), Path.size())}; + if (Path.substr(start, end - start) == "..") + { + return false; + } + start = end + 1; + } + return true; +} + +} // namespace wasm_screens diff --git a/scripting/wasmscreenrules.h b/scripting/wasmscreenrules.h new file mode 100644 index 000000000..923cf926e --- /dev/null +++ b/scripting/wasmscreenrules.h @@ -0,0 +1,74 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +class cParser; + +// the parts of the wasm screens that don't need the runtime: the .mmd entries, the frame schedule and the +// file access rules. kept apart from scripting/wasmscreens.cpp so the unit tests can check them +namespace wasm_screens +{ + +// a wasm screen as the .mmd file describes it: +// wasmscreen: { script.wasm target: submodel frames: 4 parameters: key=value&key=value } +// wasmdestinationsign: { script.wasm frames: 30 instance: name parameters: ... background: texture } +// every key but the script is optional, and an unknown key is skipped along with its value +struct screen_config +{ + std::string script; // the .wasm file, relative to the vehicle folder when it has no path of its own + std::string target{"none"}; // cab screens: the submodel the screen is drawn on + std::string parameters; // extra key=value pairs passed to the screen with the simulation state + std::string instancing; // destination signs: "name" or "type", one sign per vehicle or per vehicle type + std::string background; // destination signs: the texture shown while the sign is off + int frames{0}; // the screen's own refresh interval in frames, used when longer than the one set in eu07.ini + + void deserialize(cParser &Input); + + private: + bool deserialize_mapping(cParser &Input); +}; + +// how often a screen gets fresh data, counted in rendered frames +class frame_schedule +{ + public: + frame_schedule() = default; + // Start: the frame the screen was created on. the first refresh comes Phase frames later + frame_schedule(std::uint64_t Start, int Interval, int Phase); + + // the interval of a screen: the one set in eu07.ini, or the screen's own one when that is longer. at least 1 + static int effective_interval(int Configured, int Requested); + // a fixed offset in [0, Interval) taken from the screen's name, so that the screens sharing an interval + // don't all refresh on the same frame + static int phase(std::string_view Key, int Interval); + + // true when the screen is due on Frame, and then not again until Interval frames later. a screen that + // wasn't asked for a while (a vehicle out of sight) is due on the first frame it is asked again + bool poll(std::uint64_t Frame); + + int interval() const + { + return m_interval; + } + + private: + int m_interval{1}; + std::uint64_t m_next{0}; +}; + +// true for a file a screen may read: a relative path inside the screen's folder, without '..', without a +// drive or a leading separator +bool is_safe_relative_path(std::string_view Path); + +} // namespace wasm_screens diff --git a/scripting/wasmscreens.cpp b/scripting/wasmscreens.cpp new file mode 100644 index 000000000..26521435d --- /dev/null +++ b/scripting/wasmscreens.cpp @@ -0,0 +1,942 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "scripting/wasmscreens.h" +#include "scripting/wasmscreenkernels.h" + +#include "input/command.h" +#include "interfaces/ITexture.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/dictionary.h" +#include "utilities/utilities.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +// the wasm stack of a screen, in bytes +constexpr std::uint32_t stack_size{64 * 1024}; +// the most instructions one call into a screen may run, so that a screen stuck in a loop can't hang the worker +constexpr int instruction_limit{200'000'000}; +// the largest side of a screen image, in pixels +constexpr int max_image_side{4096}; +constexpr std::size_t no_texture{std::numeric_limits::max()}; + +// the type of a value in the input of a screen, as eu07.value_type() reports it +enum class value_type : std::int32_t +{ + none = 0, + floating = 1, + integer = 2, + boolean = 3, + string = 4, + vec2_list = 5 +}; + +// the input of one refresh, indexed by key. when two values share a key the later one counts, as it does for the +// python screens, which get the values in the same order +class input_view +{ + public: + struct entry + { + value_type type{value_type::none}; + std::size_t index{0}; + }; + + explicit input_view(dictionary_source const &Source) : m_source{Source} + { + index(Source.floats, value_type::floating); + index(Source.integers, value_type::integer); + index(Source.bools, value_type::boolean); + index(Source.strings, value_type::string); + index(Source.vec2_lists, value_type::vec2_list); + } + + entry find(std::string_view const Key) const + { + if (auto const lookup{m_entries.find(Key)}; lookup != m_entries.end()) + { + return lookup->second; + } + return {}; + } + + dictionary_source const &source() const + { + return m_source; + } + + private: + template void index(Sequence_ const &Values, value_type const Type) + { + for (std::size_t idx = 0; idx < Values.size(); ++idx) + { + m_entries.insert_or_assign(std::string_view{Values[idx].first}, entry{Type, idx}); + } + } + + dictionary_source const &m_source; + std::unordered_map m_entries; +}; + +struct pending_command +{ + std::string name; + std::int32_t param1{0}; + std::int32_t param2{0}; + std::uint32_t vehicle{0}; +}; + +// the length of the UTF-8 sequence starting with the byte, 0 for a byte that can't start one +std::size_t utf8_length(std::uint8_t const Lead) +{ + if (Lead < 0x80) + { + return 1; + } + if (Lead >= 0xC2 && Lead <= 0xDF) + { + return 2; + } + if (Lead >= 0xE0 && Lead <= 0xEF) + { + return 3; + } + if (Lead >= 0xF0 && Lead <= 0xF4) + { + return 4; + } + return 0; +} + +// true for text in valid UTF-8 +bool is_utf8(std::string_view const Text) +{ + std::size_t idx{0}; + while (idx < Text.size()) + { + auto const length{utf8_length(static_cast(Text[idx]))}; + if (length == 0 || idx + length > Text.size()) + { + return false; + } + auto const sequence{Text.substr(idx + 1, length - 1)}; + if (false == std::ranges::all_of(sequence, [](char const Byte) { return (static_cast(Byte) & 0xC0) == 0x80; })) + { + return false; + } + idx += length; + } + return true; +} + +std::int32_t to_int32(double const Value) +{ + if (std::isnan(Value)) + { + return 0; + } + return static_cast(std::clamp(Value, static_cast(std::numeric_limits::min()), static_cast(std::numeric_limits::max()))); +} + +std::int32_t to_int32(std::size_t const Value) +{ + return static_cast(std::min(Value, std::numeric_limits::max())); +} + +} // namespace + +class wasm_screen +{ + public: + wasm_screen(wasm_screen_queue::screen_request const &Request, wasm_screens::frame_schedule const &Schedule) + : kind{Request.kind}, script{Request.script}, folder{substr_path(Request.script)}, texture{Request.texture}, m_schedule{Schedule} + { + } + ~wasm_screen() + { + release_runtime(); + } + wasm_screen(wasm_screen const &) = delete; + wasm_screen &operator=(wasm_screen const &) = delete; + + bool poll(std::uint64_t const Frame) + { + std::scoped_lock lock{m_schedule_mutex}; + return m_schedule.poll(Frame); + } + + // frees the module instance. done by the queue when it stops, as the runtime goes with it + void release_runtime() + { + if (exec_env != nullptr) + { + wasm_runtime_destroy_exec_env(exec_env); + exec_env = nullptr; + } + if (instance != nullptr) + { + wasm_runtime_deinstantiate(instance); + instance = nullptr; + } + failed = true; + } + + // set when made, read-only afterwards + wasm_screen_kind const kind; + std::string const script; + std::string const folder; + ITexture *const texture; + + // set by the worker when the screen can't run (any more); a failed screen isn't refreshed + std::atomic failed{false}; + + // the worker's part + wasm_module_inst_t instance{nullptr}; + wasm_exec_env_t exec_env{nullptr}; + wasm_function_inst_t render{nullptr}; + wasm_function_inst_t width{nullptr}; + wasm_function_inst_t height{nullptr}; + bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged + // the call in progress + input_view const *input{nullptr}; + std::vector *commands{nullptr}; + std::uint32_t vehicle{0}; + + // the image, handed from the worker to the main thread + std::mutex image_mutex; + std::vector image; + int image_width{0}; + int image_height{0}; + bool image_pending{false}; // drawn and not yet uploaded + std::size_t uploaded_texture{no_texture}; // the gl texture the image went to, to upload it again when it's made anew + + private: + std::mutex m_schedule_mutex; + wasm_screens::frame_schedule m_schedule; +}; + +namespace +{ + +wasm_screen *screen_of(wasm_exec_env_t Env) +{ + return static_cast(wasm_runtime_get_custom_data(wasm_runtime_get_module_inst(Env))); +} + +struct lookup_result +{ + input_view const *view{nullptr}; + input_view::entry entry; +}; + +lookup_result lookup(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length) +{ + auto const *screen{screen_of(Env)}; + if (screen == nullptr || screen->input == nullptr || Key == nullptr) + { + return {}; + } + return {screen->input, screen->input->find(std::string_view{Key, Length})}; +} + +// the natives of the "eu07" module, which a screen imports. see wasm_screens_doc.md + +std::int32_t native_value_type(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length) +{ + return static_cast(lookup(Env, Key, Length).entry.type); +} + +double native_get_float(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length) +{ + auto const [view, entry]{lookup(Env, Key, Length)}; + using enum value_type; + switch (entry.type) + { + case floating: + return view->source().floats[entry.index].second; + case integer: + return view->source().integers[entry.index].second; + case boolean: + return view->source().bools[entry.index].second ? 1.0 : 0.0; + default: + return 0.0; + } +} + +std::int32_t native_get_int(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length) +{ + auto const [view, entry]{lookup(Env, Key, Length)}; + using enum value_type; + switch (entry.type) + { + case floating: + return to_int32(view->source().floats[entry.index].second); + case integer: + return view->source().integers[entry.index].second; + case boolean: + return view->source().bools[entry.index].second ? 1 : 0; + default: + return 0; + } +} + +std::int32_t native_get_bool(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length) +{ + auto const [view, entry]{lookup(Env, Key, Length)}; + using enum value_type; + switch (entry.type) + { + case floating: + return view->source().floats[entry.index].second != 0.0 ? 1 : 0; + case integer: + return view->source().integers[entry.index].second != 0 ? 1 : 0; + case boolean: + return view->source().bools[entry.index].second ? 1 : 0; + default: + return 0; + } +} + +// copies the string into the buffer, as UTF-8 (names of sceneries and vehicles may be in windows-1250). +// returns the length of the whole string, which may be more than the buffer took, or -1 when there is no such string +std::int32_t native_get_string(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length, char *Buffer, std::uint32_t const Capacity) +{ + auto const [view, entry]{lookup(Env, Key, Length)}; + if (entry.type != value_type::string) + { + return -1; + } + auto const &value{view->source().strings[entry.index].second}; + auto const text{is_utf8(value) ? value : win1250_to_utf8(value)}; + if (Buffer != nullptr) + { + std::memcpy(Buffer, text.data(), std::min(text.size(), Capacity)); + } + return to_int32(text.size()); +} + +std::int32_t native_get_vec2_count(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length) +{ + auto const [view, entry]{lookup(Env, Key, Length)}; + if (entry.type != value_type::vec2_list) + { + return 0; + } + return to_int32(view->source().vec2_lists[entry.index].second.size()); +} + +// writes the point as two f32 at Output. returns 1 on success, 0 when there is no such point +std::int32_t native_get_vec2(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length, std::int32_t const Index, std::uint32_t const Output) +{ + auto const [view, entry]{lookup(Env, Key, Length)}; + if (entry.type != value_type::vec2_list || Index < 0) + { + return 0; + } + auto const &points{view->source().vec2_lists[entry.index].second}; + if (static_cast(Index) >= points.size()) + { + return 0; + } + auto *instance{wasm_runtime_get_module_inst(Env)}; + std::array const point{points[Index].x, points[Index].y}; + if (false == wasm_runtime_validate_app_addr(instance, Output, sizeof(point))) + { + // the runtime has raised an exception, which ends the call + return 0; + } + std::memcpy(wasm_runtime_addr_app_to_native(instance, Output), point.data(), sizeof(point)); + return 1; +} + +void native_command(wasm_exec_env_t Env, char const *Name, std::uint32_t const Length, std::int32_t const Param1, std::int32_t const Param2) +{ + auto *screen{screen_of(Env)}; + if (screen == nullptr || screen->commands == nullptr || Name == nullptr) + { + return; + } + if (screen->kind != wasm_screen_kind::cab) + { + if (false == screen->commands_ignored) + { + screen->commands_ignored = true; + WriteLog(std::format("WASM screen \"{}\": commands are only taken from screens in the cab", screen->script)); + } + return; + } + screen->commands->emplace_back(std::string{Name, Length}, Param1, Param2, screen->vehicle); +} + +void native_log(wasm_exec_env_t Env, char const *Text, std::uint32_t const Length) +{ + auto const *screen{screen_of(Env)}; + if (screen == nullptr || Text == nullptr) + { + return; + } + WriteLog(std::format("WASM screen \"{}\": {}", screen->script, std::string_view{Text, Length})); +} + +// reads a file from the screen's folder into the buffer. returns the size of the whole file, which may be more +// than the buffer took, or -1 when there is no such file or the path leads outside the folder +std::int32_t native_file_read(wasm_exec_env_t Env, char const *Path, std::uint32_t const Length, char *Buffer, std::uint32_t const Capacity) +{ + auto const *screen{screen_of(Env)}; + if (screen == nullptr || Path == nullptr) + { + return -1; + } + std::string_view const path{Path, Length}; + if (false == wasm_screens::is_safe_relative_path(path)) + { + return -1; + } + std::ifstream file{screen->folder + std::string{path}, std::ios::binary | std::ios::ate}; + if (false == file.is_open()) + { + return -1; + } + auto const size{static_cast(std::max(file.tellg(), 0))}; + if (Buffer != nullptr && Capacity > 0) + { + file.seekg(0); + file.read(Buffer, static_cast(std::min(size, Capacity))); + } + return to_int32(size); +} + +// seconds of a steady clock, the same for every screen, for animations that don't depend on how often the +// screen is refreshed +double native_time(wasm_exec_env_t /*Env*/) +{ + static auto const start{std::chrono::steady_clock::now()}; + return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); +} + +// the bytes of an image in the module's memory; an empty span for one that lies outside (the runtime then raises an +// exception, which ends the call) +std::span module_image(wasm_exec_env_t Env, std::uint32_t const Offset, int const Width, int const Height) +{ + auto *instance{wasm_runtime_get_module_inst(Env)}; + auto const size{wasm_screens::image_size(Width, Height)}; + if (false == wasm_runtime_validate_app_addr(instance, Offset, size)) + { + return {}; + } + return {static_cast(wasm_runtime_addr_app_to_native(instance, Offset)), size}; +} + +bool valid_side(std::int32_t const Side) +{ + return Side > 0 && Side <= max_image_side; +} + +// led_util's render_post, natively: Target takes (2 Width + 2) x (2 Height + 2) pixels. returns 1, or 0 for an image +// that doesn't fit +std::int32_t native_led_post(wasm_exec_env_t Env, std::uint32_t const Source, std::int32_t const Width, std::int32_t const Height, std::uint32_t const Target, std::int32_t const Bloom) +{ + if (false == valid_side(Width) || false == valid_side(Height)) + { + return 0; + } + auto const source{module_image(Env, Source, Width, Height)}; + auto const target{module_image(Env, Target, Width * 2 + 2, Height * 2 + 2)}; + if (source.empty() || target.empty()) + { + return 0; + } + return wasm_screens::led_post(source, Width, Height, target, Bloom != 0) ? 1 : 0; +} + +// Pillow's resize(..., LANCZOS), natively. returns 1, or 0 for an image that doesn't fit +std::int32_t native_resize_lanczos(wasm_exec_env_t Env, std::uint32_t const Source, std::int32_t const Width, std::int32_t const Height, std::uint32_t const Target, + std::int32_t const TargetWidth, std::int32_t const TargetHeight) +{ + if (false == valid_side(Width) || false == valid_side(Height) || false == valid_side(TargetWidth) || false == valid_side(TargetHeight)) + { + return 0; + } + auto const source{module_image(Env, Source, Width, Height)}; + auto const target{module_image(Env, Target, TargetWidth, TargetHeight)}; + if (source.empty() || target.empty()) + { + return 0; + } + return wasm_screens::resize_lanczos(source, Width, Height, target, TargetWidth, TargetHeight) ? 1 : 0; +} + +template NativeSymbol native(char const *Name, Function_ *Function, char const *Signature) +{ + return NativeSymbol{Name, reinterpret_cast(Function), Signature, nullptr}; +} + +} // namespace + +struct wasm_screen_queue::implementation +{ + struct module_entry + { + std::vector bytes; // the runtime reads the module from here as long as it is loaded + wasm_module_t module{nullptr}; + }; + + struct task + { + std::shared_ptr screen; + std::shared_ptr input; + std::uint32_t vehicle{0}; + }; + + implementation() + : natives{native("value_type", &native_value_type, "(*~)i"), + native("get_float", &native_get_float, "(*~)F"), + native("get_int", &native_get_int, "(*~)i"), + native("get_bool", &native_get_bool, "(*~)i"), + native("get_string", &native_get_string, "(*~*~)i"), + native("get_vec2_count", &native_get_vec2_count, "(*~)i"), + native("get_vec2", &native_get_vec2, "(*~ii)i"), + native("command", &native_command, "(*~ii)"), + native("log", &native_log, "(*~)"), + native("file_read", &native_file_read, "(*~*~)i"), + native("time", &native_time, "()F"), + native("led_post", &native_led_post, "(iiiii)i"), + native("resize_lanczos", &native_resize_lanczos, "(iiiiii)i")} + { + } + + void run(std::stop_token const &Stop); + void process(task const &Task); + bool instantiate(wasm_screen &Screen); + wasm_module_t load_module(std::string const &Script); + bool call(wasm_screen &Screen, wasm_function_inst_t Function, std::string_view Name, std::int32_t &Result) const; + void present(wasm_screen &Screen, std::uint32_t Pixels) const; + static void upload(wasm_screen &Screen); + static void execute(pending_command const &Command); + + // the runtime keeps the array and sorts it, so it lives as long as the queue + std::array natives; + bool initialized{false}; + std::atomic frame{0}; + + std::mutex screens_mutex; + std::unordered_map> screens; + + std::mutex tasks_mutex; + std::condition_variable_any tasks_condition; + std::deque tasks; + std::jthread worker; + + std::mutex commands_mutex; + std::vector commands; + + // the worker's, and the queue's once the worker stopped + std::unordered_map modules; +}; + +void wasm_screen_queue::implementation::run(std::stop_token const &Stop) +{ + wasm_runtime_init_thread_env(); + while (false == Stop.stop_requested()) + { + task next; + { + std::unique_lock lock{tasks_mutex}; + if (false == tasks_condition.wait(lock, Stop, [this] { return false == tasks.empty(); })) + { + break; + } + next = std::move(tasks.front()); + tasks.pop_front(); + } + process(next); + } + wasm_runtime_destroy_thread_env(); +} + +void wasm_screen_queue::implementation::process(task const &Task) +{ + auto &screen{*Task.screen}; + if (screen.failed) + { + return; + } + if (screen.instance == nullptr && false == instantiate(screen)) + { + screen.failed = true; + return; + } + + input_view const view{*Task.input}; + std::vector sent; + screen.input = &view; + screen.commands = &sent; + screen.vehicle = Task.vehicle; + std::int32_t pixels{0}; + auto const rendered{call(screen, screen.render, "screen_render", pixels)}; + screen.input = nullptr; + screen.commands = nullptr; + if (false == rendered) + { + return; + } + // 0: the screen didn't change, keep the image there is + if (pixels != 0) + { + present(screen, static_cast(pixels)); + } + if (false == sent.empty()) + { + std::scoped_lock lock{commands_mutex}; + commands.insert(commands.end(), std::make_move_iterator(sent.begin()), std::make_move_iterator(sent.end())); + } +} + +bool wasm_screen_queue::implementation::instantiate(wasm_screen &Screen) +{ + auto *module{load_module(Screen.script)}; + if (module == nullptr) + { + return false; + } + std::array error{}; + Screen.instance = wasm_runtime_instantiate(module, stack_size, 0, error.data(), static_cast(error.size())); + if (Screen.instance == nullptr) + { + ErrorLog(std::format("WASM screen \"{}\": instantiation failed: {}", Screen.script, error.data())); + return false; + } + wasm_runtime_set_custom_data(Screen.instance, &Screen); + Screen.exec_env = wasm_runtime_create_exec_env(Screen.instance, stack_size); + if (Screen.exec_env == nullptr) + { + ErrorLog(std::format("WASM screen \"{}\": failed to create the execution environment", Screen.script)); + return false; + } + Screen.render = wasm_runtime_lookup_function(Screen.instance, "screen_render"); + Screen.width = wasm_runtime_lookup_function(Screen.instance, "screen_width"); + Screen.height = wasm_runtime_lookup_function(Screen.instance, "screen_height"); + if (Screen.render == nullptr || Screen.width == nullptr || Screen.height == nullptr) + { + ErrorLog(std::format("WASM screen \"{}\": the module has to export screen_render, screen_width and screen_height", Screen.script)); + return false; + } + if (auto *init{wasm_runtime_lookup_function(Screen.instance, "screen_init")}; init != nullptr) + { + std::int32_t result{0}; + if (false == call(Screen, init, "screen_init", result)) + { + return false; + } + if (result != 0) + { + ErrorLog(std::format("WASM screen \"{}\": screen_init returned {}", Screen.script, result)); + return false; + } + } + WriteLog(std::format("WASM screen \"{}\": ready", Screen.script)); + return true; +} + +wasm_module_t wasm_screen_queue::implementation::load_module(std::string const &Script) +{ + if (auto const lookup{modules.find(Script)}; lookup != modules.end()) + { + return lookup->second.module; + } + // a failure is kept as well, so the module isn't tried again for every screen using it + auto &entry{modules[Script]}; + std::ifstream file{Script, std::ios::binary}; + if (false == file.is_open()) + { + ErrorLog(std::format("WASM screen \"{}\": file not found", Script)); + return nullptr; + } + entry.bytes.assign(std::istreambuf_iterator{file}, std::istreambuf_iterator{}); + if (entry.bytes.empty() || entry.bytes.size() > std::numeric_limits::max()) + { + ErrorLog(std::format("WASM screen \"{}\": invalid module size", Script)); + return nullptr; + } + std::array error{}; + entry.module = wasm_runtime_load(entry.bytes.data(), static_cast(entry.bytes.size()), error.data(), static_cast(error.size())); + if (entry.module == nullptr) + { + ErrorLog(std::format("WASM screen \"{}\": failed to load the module: {}", Script, error.data())); + } + return entry.module; +} + +// calls a function of the screen that takes nothing and returns an i32. a failed call disables the screen +bool wasm_screen_queue::implementation::call(wasm_screen &Screen, wasm_function_inst_t Function, std::string_view const Name, std::int32_t &Result) const +{ + wasm_runtime_set_instruction_count_limit(Screen.exec_env, instruction_limit); + std::array cells{}; + if (false == wasm_runtime_call_wasm(Screen.exec_env, Function, 0, cells.data())) + { + auto const *exception{wasm_runtime_get_exception(Screen.instance)}; + ErrorLog(std::format("WASM screen \"{}\": {} failed: {}", Screen.script, Name, exception != nullptr ? exception : "unknown error")); + Screen.failed = true; + return false; + } + Result = static_cast(cells[0]); + return true; +} + +// copies the image the screen drew, Pixels being its address in the module's memory +void wasm_screen_queue::implementation::present(wasm_screen &Screen, std::uint32_t const Pixels) const +{ + std::int32_t width{0}; + std::int32_t height{0}; + if (false == call(Screen, Screen.width, "screen_width", width) || false == call(Screen, Screen.height, "screen_height", height)) + { + return; + } + if (width <= 0 || height <= 0 || width > max_image_side || height > max_image_side) + { + ErrorLog(std::format("WASM screen \"{}\": invalid image size {}x{}", Screen.script, width, height)); + Screen.failed = true; + return; + } + auto const size{static_cast(width) * static_cast(height) * 4}; + if (false == wasm_runtime_validate_app_addr(Screen.instance, Pixels, size)) + { + ErrorLog(std::format("WASM screen \"{}\": the image lies outside the module's memory", Screen.script)); + Screen.failed = true; + return; + } + auto const *pixels{static_cast(wasm_runtime_addr_app_to_native(Screen.instance, Pixels))}; + + std::scoped_lock lock{Screen.image_mutex}; + Screen.image.assign(pixels, pixels + size); + Screen.image_width = width; + Screen.image_height = height; + Screen.image_pending = true; +} + +void wasm_screen_queue::implementation::upload(wasm_screen &Screen) +{ + if (Screen.texture == nullptr) + { + return; + } + std::scoped_lock lock{Screen.image_mutex}; + if (Screen.image.empty() || false == Screen.texture->get_is_ready()) + { + // nothing drawn yet, or the texture isn't made yet or was released: the image goes up once it's there + return; + } + if (false == Screen.image_pending && Screen.texture->get_id() == Screen.uploaded_texture) + { + return; + } + Screen.texture->update_from_memory(Screen.image_width, Screen.image_height, Screen.image.data()); + Screen.uploaded_texture = Screen.texture->get_id(); + Screen.image_pending = false; +} + +void wasm_screen_queue::implementation::execute(pending_command const &Command) +{ + auto const lookup{simulation::commandMap.find(Command.name)}; + if (lookup == simulation::commandMap.end()) + { + ErrorLog(std::format("WASM screen: command [{}] not found", Command.name)); + return; + } + command_data data{}; + data.command = lookup->second; + data.action = GLFW_PRESS; + data.param1 = Command.param1; + data.param2 = Command.param2; + WriteLog(std::format("WASM screen: executing command [{}] with params: P1={} P2={} Target ID={}", Command.name, Command.param1, Command.param2, Command.vehicle)); + simulation::Commands.push(data, static_cast(command_target::vehicle) | Command.vehicle); +} + +wasm_screen_queue::wasm_screen_queue() : m_impl{std::make_unique()} {} + +wasm_screen_queue::~wasm_screen_queue() +{ + exit(); +} + +bool wasm_screen_queue::init() +{ + if (m_impl->initialized) + { + return true; + } + RuntimeInitArgs arguments{}; + arguments.mem_alloc_type = Alloc_With_System_Allocator; + arguments.native_module_name = "eu07"; + arguments.native_symbols = m_impl->natives.data(); + arguments.n_native_symbols = static_cast(m_impl->natives.size()); + arguments.running_mode = Mode_Interp; + if (false == wasm_runtime_full_init(&arguments)) + { + ErrorLog("WASM screens: failed to initialize the runtime"); + return false; + } + wasm_runtime_set_log_level(WASM_LOG_LEVEL_ERROR); + m_impl->initialized = true; + auto *impl{m_impl.get()}; + m_impl->worker = std::jthread([impl](std::stop_token const &Stop) { impl->run(Stop); }); + WriteLog(std::format("WASM screens: setup complete, refreshed every {} frames in the cab and every {} frames outside", Global.wasm_cabframes, Global.wasm_externalframes)); + return true; +} + +void wasm_screen_queue::exit() +{ + if (false == m_impl->initialized) + { + return; + } + if (m_impl->worker.joinable()) + { + m_impl->worker.request_stop(); + m_impl->worker.join(); + } + { + std::scoped_lock lock{m_impl->tasks_mutex}; + m_impl->tasks.clear(); + } + { + std::scoped_lock lock{m_impl->commands_mutex}; + m_impl->commands.clear(); + } + { + // the vehicles may hold their screens past this point, but the runtime goes now + std::scoped_lock lock{m_impl->screens_mutex}; + for (auto const &[key, screen] : m_impl->screens) + { + if (auto const live{screen.lock()}; live != nullptr) + { + live->release_runtime(); + } + } + m_impl->screens.clear(); + } + for (auto const &[script, entry] : m_impl->modules) + { + if (entry.module != nullptr) + { + wasm_runtime_unload(entry.module); + } + } + m_impl->modules.clear(); + wasm_runtime_destroy(); + m_impl->initialized = false; +} + +std::shared_ptr wasm_screen_queue::acquire(screen_request const &Request) +{ + if (false == m_impl->initialized || Request.script.empty()) + { + return nullptr; + } + auto const key{Request.key.empty() ? Request.script : Request.key}; + std::scoped_lock lock{m_impl->screens_mutex}; + if (auto const lookup{m_impl->screens.find(key)}; lookup != m_impl->screens.end()) + { + if (auto existing{lookup->second.lock()}; existing != nullptr) + { + return existing; + } + } + auto const configured{Request.kind == wasm_screen_kind::cab ? Global.wasm_cabframes : Global.wasm_externalframes}; + auto const interval{wasm_screens::frame_schedule::effective_interval(configured, Request.frames)}; + auto screen{std::make_shared(Request, wasm_screens::frame_schedule{m_impl->frame.load(), interval, wasm_screens::frame_schedule::phase(key, interval)})}; + m_impl->screens.insert_or_assign(key, screen); + return screen; +} + +bool wasm_screen_queue::due(wasm_screen &Screen) const +{ + if (false == m_impl->initialized || Screen.failed) + { + return false; + } + return Screen.poll(m_impl->frame.load()); +} + +void wasm_screen_queue::submit(std::shared_ptr const &Screen, std::shared_ptr Input, std::uint32_t const Vehicle) +{ + if (false == m_impl->initialized || Screen == nullptr || Input == nullptr || Screen->failed) + { + return; + } + { + std::scoped_lock lock{m_impl->tasks_mutex}; + auto const pending{std::ranges::find(m_impl->tasks, Screen, &implementation::task::screen)}; + if (pending != m_impl->tasks.end()) + { + // the refresh still waiting gets the newer input + pending->input = std::move(Input); + pending->vehicle = Vehicle; + } + else + { + m_impl->tasks.emplace_back(Screen, std::move(Input), Vehicle); + } + } + m_impl->tasks_condition.notify_one(); +} + +void wasm_screen_queue::update() +{ + if (false == m_impl->initialized) + { + return; + } + ++m_impl->frame; + { + std::scoped_lock lock{m_impl->screens_mutex}; + std::erase_if(m_impl->screens, [](auto const &Entry) { return Entry.second.expired(); }); + for (auto const &[key, screen] : m_impl->screens) + { + if (auto const live{screen.lock()}; live != nullptr) + { + implementation::upload(*live); + } + } + } + std::vector sent; + { + std::scoped_lock lock{m_impl->commands_mutex}; + sent.swap(m_impl->commands); + } + for (auto const &command : sent) + { + implementation::execute(command); + } +} diff --git a/scripting/wasmscreens.h b/scripting/wasmscreens.h new file mode 100644 index 000000000..a4933646a --- /dev/null +++ b/scripting/wasmscreens.h @@ -0,0 +1,72 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "scripting/wasmscreenrules.h" + +#include +#include +#include + +struct ITexture; +struct dictionary_source; + +// screens drawn by WebAssembly modules, the counterpart of the python screens (scripting/PyInt.h). +// a module gets the same state the python screens get, returns an RGBA image and may send commands. the +// interface between the two is described in wasm_screens_doc.md. +// unlike the python screens, which refresh after a time, a wasm screen refreshes every so many rendered +// frames: wasm.cabframes in eu07.ini for the screens in the cab, wasm.externalframes for the screens outside +// (destination signs) + +enum class wasm_screen_kind +{ + cab, // in the cab of the driven vehicle: may send commands to it + external // on the outside of a vehicle, such as a destination sign: shows only +}; + +// one screen: a module instance with its own memory, and the image it drew last +class wasm_screen; + +class wasm_screen_queue +{ + public: + struct screen_request + { + wasm_screen_kind kind{wasm_screen_kind::cab}; + std::string script; // the .wasm file + std::string key; // requests with the same key get the same screen, e.g. the destination signs of one train + ITexture *texture{nullptr}; // where the screen is drawn; none for a screen that only sends commands + int frames{0}; // the screen's own refresh interval from the .mmd, used when longer than the eu07.ini one + }; + + wasm_screen_queue(); + ~wasm_screen_queue(); + wasm_screen_queue(wasm_screen_queue const &) = delete; + wasm_screen_queue &operator=(wasm_screen_queue const &) = delete; + + // starts the runtime and its worker thread. returns true on success + bool init(); + // stops the worker and releases every screen, also the ones still held by vehicles + void exit(); + // the screen for the request, made on the first request with its key. nullptr when the wasm screens are off + std::shared_ptr acquire(screen_request const &Request); + // true once per refresh interval of the screen. the caller then gathers the screen's input and submit()s it + bool due(wasm_screen &Screen) const; + // queues a refresh of the screen with the given input, replacing a refresh of it still waiting. + // Vehicle: the vehicle that gets the commands the screen sends; cab screens only + void submit(std::shared_ptr const &Screen, std::shared_ptr Input, std::uint32_t Vehicle); + // main thread, once per rendered frame: uploads the finished images, runs the commands the screens sent and + // counts the frame + void update(); + + private: + struct implementation; + std::unique_ptr m_impl; +}; diff --git a/scripting/wasmscreensstub.cpp b/scripting/wasmscreensstub.cpp new file mode 100644 index 000000000..666b53f29 --- /dev/null +++ b/scripting/wasmscreensstub.cpp @@ -0,0 +1,51 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// the wasm screens of a build without WITH_WASM: there are none, and the vehicles fall back to what they had before + +#include "stdafx.h" +#include "scripting/wasmscreens.h" + +struct wasm_screen_queue::implementation +{ +}; + +wasm_screen_queue::wasm_screen_queue() : m_impl{std::make_unique()} {} + +wasm_screen_queue::~wasm_screen_queue() = default; + +bool wasm_screen_queue::init() +{ + return false; +} + +void wasm_screen_queue::exit() +{ + // nothing was started +} + +std::shared_ptr wasm_screen_queue::acquire(screen_request const & /*Request*/) +{ + return nullptr; +} + +bool wasm_screen_queue::due(wasm_screen & /*Screen*/) const +{ + return false; +} + +void wasm_screen_queue::submit(std::shared_ptr const & /*Screen*/, std::shared_ptr /*Input*/, std::uint32_t /*Vehicle*/) +{ + // nothing to refresh +} + +void wasm_screen_queue::update() +{ + // nothing to upload +} diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 17efffa7d..b620cc0ae 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -25,6 +25,11 @@ add_executable(${UNIT_TESTS_NAME} # the core library brings the game's build settings along target_link_libraries(${UNIT_TESTS_NAME} PRIVATE eu07_core) +# the wasm screen host, tested with the real runtime (test_wasm_host.cpp) +if (WITH_WASM) + target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/wasmscreens.cpp") + target_link_libraries(${UNIT_TESTS_NAME} PRIVATE eu07_wamr) +endif() target_include_directories(${UNIT_TESTS_NAME} PRIVATE "${DEPS_DIR}/doctest") # the names the tests CAPTURE are often C strings, shown as text rather than pointers target_compile_definitions(${UNIT_TESTS_NAME} PRIVATE EU07_UNIT_TESTS_DATA="${CMAKE_CURRENT_SOURCE_DIR}/data" DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING) diff --git a/tests/unit/test_wasm_host.cpp b/tests/unit/test_wasm_host.cpp new file mode 100644 index 000000000..d96ee716d --- /dev/null +++ b/tests/unit/test_wasm_host.cpp @@ -0,0 +1,288 @@ +#include "stdafx.h" +#include "doctest.h" + +// the wasm screen host (scripting/wasmscreens.cpp) with the real runtime: a module reads its input, draws an +// image that goes to the screen's texture and sends a command; a module stuck in a loop is stopped. built with +// WITH_WASM only + +#ifdef WITH_WASM + +#include "scripting/wasmscreens.h" +#include "input/command.h" +#include "interfaces/ITexture.h" +#include "utilities/Globals.h" +#include "utilities/dictionary.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +// the engine's command queue and command names, which the test build doesn't link: the commands the screens send +// are kept here instead + +namespace { + +std::vector> &sent_commands() { + static std::vector> commands; + return commands; +} + +} // namespace + +namespace simulation { +command_queue Commands; // NOSONAR the engine's extern global, input/command.h +std::unordered_map const commandMap{{"cmdtest", user_command::aidriverenable}}; // NOSONAR the engine's extern global, input/command.h +} // namespace simulation + +void command_queue::push(command_data const &Command, uint32_t const Recipient) { // NOSONAR signature from input/command.h + sent_commands().emplace_back(Command, Recipient); +} + +namespace { + +// the modules, encoded by hand. "paint": a 2x2 screen in the colour 0xFF0000vv, vv being the input value +// "speed", which sends the command "cmdtest" with the parameters (vv, 7): +// (import "eu07" "get_float" (func $get_float (param i32 i32) (result f64))) +// (import "eu07" "command" (func $command (param i32 i32 i32 i32))) +// (memory (export "memory") 1) +// (data (i32.const 0) "speed") (data (i32.const 16) "cmdtest") +// (func (export "screen_width") (result i32) i32.const 2) +// (func (export "screen_height") (result i32) i32.const 2) +// (func (export "screen_render") (result i32) (local $v i32) +// (local.set $v (i32.trunc_f64_s (call $get_float (i32.const 0) (i32.const 5)))) +// (i32.store (i32.const 1024) (i32.or (local.get $v) (i32.const 0xFF000000))) ... the same at 1028, 1032, 1036 +// (call $command (i32.const 16) (i32.const 7) (local.get $v) (i32.const 7)) +// (i32.const 1024)) +constexpr std::array paint_module{ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x12, 0x03, 0x60, 0x02, 0x7f, 0x7f, 0x01, + 0x7c, 0x60, 0x04, 0x7f, 0x7f, 0x7f, 0x7f, 0x00, 0x60, 0x00, 0x01, 0x7f, 0x02, 0x21, 0x02, 0x04, + 0x65, 0x75, 0x30, 0x37, 0x09, 0x67, 0x65, 0x74, 0x5f, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x00, 0x00, + 0x04, 0x65, 0x75, 0x30, 0x37, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x00, 0x01, 0x03, + 0x04, 0x03, 0x02, 0x02, 0x02, 0x05, 0x03, 0x01, 0x00, 0x01, 0x07, 0x39, 0x04, 0x06, 0x6d, 0x65, + 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x0c, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x77, 0x69, + 0x64, 0x74, 0x68, 0x00, 0x02, 0x0d, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x68, 0x65, 0x69, + 0x67, 0x68, 0x74, 0x00, 0x03, 0x0d, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x72, 0x65, 0x6e, + 0x64, 0x65, 0x72, 0x00, 0x04, 0x0a, 0x5e, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41, + 0x02, 0x0b, 0x52, 0x01, 0x01, 0x7f, 0x41, 0x00, 0x41, 0x05, 0x10, 0x00, 0xaa, 0x21, 0x00, 0x41, + 0x80, 0x08, 0x20, 0x00, 0x41, 0x80, 0x80, 0x80, 0x78, 0x72, 0x36, 0x02, 0x00, 0x41, 0x84, 0x08, + 0x20, 0x00, 0x41, 0x80, 0x80, 0x80, 0x78, 0x72, 0x36, 0x02, 0x00, 0x41, 0x88, 0x08, 0x20, 0x00, + 0x41, 0x80, 0x80, 0x80, 0x78, 0x72, 0x36, 0x02, 0x00, 0x41, 0x8c, 0x08, 0x20, 0x00, 0x41, 0x80, + 0x80, 0x80, 0x78, 0x72, 0x36, 0x02, 0x00, 0x41, 0x10, 0x41, 0x07, 0x20, 0x00, 0x41, 0x07, 0x10, + 0x01, 0x41, 0x80, 0x08, 0x0b, 0x0b, 0x17, 0x02, 0x00, 0x41, 0x00, 0x0b, 0x05, 0x73, 0x70, 0x65, + 0x65, 0x64, 0x00, 0x41, 0x10, 0x0b, 0x07, 0x63, 0x6d, 0x64, 0x74, 0x65, 0x73, 0x74}; + +// "spin": exports the same functions as "paint", but screen_render never returns: (loop $l (br $l)) +constexpr std::array spin_module{ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f, 0x03, + 0x04, 0x03, 0x00, 0x00, 0x00, 0x05, 0x03, 0x01, 0x00, 0x01, 0x07, 0x39, 0x04, 0x06, 0x6d, 0x65, + 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x0c, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x77, 0x69, + 0x64, 0x74, 0x68, 0x00, 0x00, 0x0d, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x68, 0x65, 0x69, + 0x67, 0x68, 0x74, 0x00, 0x01, 0x0d, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x72, 0x65, 0x6e, + 0x64, 0x65, 0x72, 0x00, 0x02, 0x0a, 0x15, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41, + 0x02, 0x0b, 0x09, 0x00, 0x03, 0x40, 0x0c, 0x00, 0x0b, 0x41, 0x00, 0x0b}; + +// a texture that keeps what was uploaded to it +struct recording_texture : ITexture { + bool create(bool) override { return true; } + int get_width() const override { return width; } + int get_height() const override { return height; } + size_t get_id() const override { return id; } + void release() override { /* nothing held */ } + void make_stub() override { /* nothing held */ } + std::string_view get_traits() const override { return ""; } + std::string_view get_name() const override { return "recording"; } + std::string_view get_type() const override { return "make:"; } + bool is_stub() const override { return false; } + bool get_has_alpha() const override { return true; } + bool get_is_ready() const override { return ready; } + void set_components_hint(int) override { /* not used */ } + void make_from_memory(size_t const Width, size_t const Height, const uint8_t *Data) override { update_from_memory(Width, Height, Data); } + void update_from_memory(size_t const Width, size_t const Height, const uint8_t *Data) override { + width = static_cast(Width); + height = static_cast(Height); + pixels.assign(Data, Data + Width * Height * 4); + ++uploads; + } + + bool ready{true}; + size_t id{1}; + int width{0}; + int height{0}; + int uploads{0}; + std::vector pixels; +}; + +// writes a module into a folder of its own, removed with the object +class module_file { + public: + template + module_file(std::string const &Name, std::array const &Bytes) + : m_folder{std::filesystem::temp_directory_path() / std::format("eu07_wasm_test_{}", Name)} { + std::filesystem::create_directories(m_folder); + m_path = (m_folder / (Name + ".wasm")).generic_string(); + std::ofstream file{m_path, std::ios::binary}; + file.write(reinterpret_cast(Bytes.data()), static_cast(Bytes.size())); + } + ~module_file() { + std::error_code error; + std::filesystem::remove_all(m_folder, error); + } + module_file(module_file const &) = delete; + module_file &operator=(module_file const &) = delete; + + std::string const &path() const { return m_path; } + + private: + std::filesystem::path m_folder; + std::string m_path; +}; + +// runs frames until the condition holds, or gives up after a few seconds +bool run_until(wasm_screen_queue &Queue, std::function const &Condition) { + auto const deadline{std::chrono::steady_clock::now() + std::chrono::seconds(10)}; + while (std::chrono::steady_clock::now() < deadline) { + Queue.update(); + if (Condition()) { + return true; + } + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + return false; +} + +std::shared_ptr speed(double const Value) { + auto input{std::make_shared()}; + input->insert("speed", Value); + return input; +} + +} // namespace + +TEST_CASE("wasm host: a cab screen draws from its input and sends commands to its vehicle") { + sent_commands().clear(); + module_file const module{"paint", paint_module}; + wasm_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire({.kind = wasm_screen_kind::cab, .script = module.path(), .key = "cab", .texture = &texture, .frames = 0})}; + REQUIRE(screen != nullptr); + // the same key, the same screen + CHECK(queue.acquire({.kind = wasm_screen_kind::cab, .script = module.path(), .key = "cab", .texture = &texture, .frames = 0}) == screen); + + REQUIRE(run_until(queue, [&queue, &screen] { return queue.due(*screen); })); + queue.submit(screen, speed(5.0), 42); + REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0 && false == sent_commands().empty(); })); + + CHECK(texture.width == 2); + CHECK(texture.height == 2); + REQUIRE(texture.pixels.size() == 16); + std::array const expected{0x05, 0x00, 0x00, 0xFF}; + for (std::size_t pixel = 0; pixel < 4; ++pixel) { + CAPTURE(pixel); + CHECK(std::equal(expected.begin(), expected.end(), texture.pixels.begin() + static_cast(pixel * 4))); + } + + REQUIRE(sent_commands().size() == 1); + auto const &[command, recipient]{sent_commands().front()}; + CHECK(command.command == user_command::aidriverenable); + CHECK(command.param1 == 5.0); + CHECK(command.param2 == 7.0); + CHECK(recipient == (static_cast(command_target::vehicle) | 42u)); + + queue.exit(); +} + +TEST_CASE("wasm host: the image goes up again when the texture is made anew, and waits while it isn't there") { + sent_commands().clear(); + module_file const module{"paint", paint_module}; + wasm_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + texture.ready = false; + auto const screen{queue.acquire({.kind = wasm_screen_kind::cab, .script = module.path(), .key = "cab", .texture = &texture, .frames = 0})}; + REQUIRE(run_until(queue, [&queue, &screen] { return queue.due(*screen); })); + queue.submit(screen, speed(9.0), 1); + REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); + queue.update(); + CHECK(texture.uploads == 0); + + texture.ready = true; + queue.update(); + CHECK(texture.uploads == 1); + queue.update(); + CHECK(texture.uploads == 1); + + // released and made again: a new gl texture + texture.id = 2; + queue.update(); + CHECK(texture.uploads == 2); + + queue.exit(); +} + +TEST_CASE("wasm host: a screen outside the cab draws, but its commands are dropped") { + sent_commands().clear(); + module_file const module{"paint", paint_module}; + wasm_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire({.kind = wasm_screen_kind::external, .script = module.path(), .key = "sign", .texture = &texture, .frames = 0})}; + REQUIRE(run_until(queue, [&queue, &screen] { return queue.due(*screen); })); + queue.submit(screen, speed(3.0), 0); + REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; })); + queue.update(); + CHECK(sent_commands().empty()); + + queue.exit(); +} + +TEST_CASE("wasm host: a screen stuck in a loop is stopped, and the others keep working") { + sent_commands().clear(); + module_file const spinning{"spin", spin_module}; + module_file const painting{"paint", paint_module}; + wasm_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture stuck; + recording_texture working; + auto const first{queue.acquire({.kind = wasm_screen_kind::cab, .script = spinning.path(), .key = "spin", .texture = &stuck, .frames = 0})}; + auto const second{queue.acquire({.kind = wasm_screen_kind::cab, .script = painting.path(), .key = "paint", .texture = &working, .frames = 0})}; + REQUIRE(run_until(queue, [&queue, &first] { return queue.due(*first); })); + REQUIRE(run_until(queue, [&queue, &second] { return queue.due(*second); })); + queue.submit(first, speed(1.0), 1); + queue.submit(second, speed(2.0), 1); + + REQUIRE(run_until(queue, [&working] { return working.uploads > 0; })); + CHECK(stuck.uploads == 0); + // the stuck screen ran first, into the instruction limit, and isn't due any more + CHECK_FALSE(queue.due(*first)); + + queue.exit(); +} + +TEST_CASE("wasm host: the screens outlive the queue without harm") { + module_file const module{"paint", paint_module}; + std::shared_ptr screen; + recording_texture texture; + { + wasm_screen_queue queue; + REQUIRE(queue.init()); + screen = queue.acquire({.kind = wasm_screen_kind::cab, .script = module.path(), .key = "cab", .texture = &texture, .frames = 0}); + REQUIRE(run_until(queue, [&queue, &screen] { return queue.due(*screen); })); + queue.submit(screen, speed(4.0), 1); + REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; })); + } + // the queue and the runtime are gone, the vehicle still holds its screen + CHECK(screen != nullptr); + screen.reset(); +} + +#endif diff --git a/tests/unit/test_wasm_kernels.cpp b/tests/unit/test_wasm_kernels.cpp new file mode 100644 index 000000000..618524c74 --- /dev/null +++ b/tests/unit/test_wasm_kernels.cpp @@ -0,0 +1,121 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "scripting/wasmscreenkernels.h" + +#include +#include +#include + +// the image filters the wasm screens call through the host give the pixels of the Python screens: led_util's +// render_post() and Pillow's resize(..., Image.LANCZOS). the expected images were made by them (Pillow 12.2) from a +// 5x3 image of (x*53 + y*97, x*31 + y*17 + 100, x*7 + y*151 + 40) mod 256 + +namespace { + +// RGB as Pillow gives it +constexpr std::array source{ + 0, 100, 40, 53, 131, 47, 106, 162, 54, 159, 193, 61, 212, 224, 68, 97, 117, 191, 150, 148, 198, 203, 179, 205, + 0, 210, 212, 53, 241, 219, 194, 134, 86, 247, 165, 93, 44, 196, 100, 97, 227, 107, 150, 2, 114, +}; +constexpr std::array posted{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 144, 77, 28, 122, 65, 99, 194, 97, + 84, 164, 82, 158, 236, 108, 134, 200, 91, 205, 255, 114, 174, 229, 96, 241, 255, 109, 204, 238, 92, 0, 0, 0, + 0, 0, 0, 28, 122, 65, 23, 100, 53, 84, 164, 82, 69, 135, 67, 134, 200, 91, 110, 165, 75, 174, 229, 96, + 143, 189, 79, 204, 238, 92, 168, 196, 76, 0, 0, 0, 0, 0, 0, 144, 173, 231, 122, 147, 196, 215, 229, 255, + 182, 194, 219, 255, 255, 255, 219, 232, 230, 67, 255, 255, 56, 255, 235, 101, 255, 255, 85, 255, 225, 0, 0, 0, + 0, 0, 0, 122, 147, 196, 100, 121, 161, 182, 194, 219, 150, 160, 180, 219, 232, 230, 180, 191, 189, 56, 255, 235, + 46, 213, 193, 85, 255, 225, 70, 212, 185, 0, 0, 0, 0, 0, 0, 234, 178, 126, 198, 151, 107, 255, 231, 148, + 251, 196, 125, 106, 255, 159, 90, 230, 135, 139, 255, 165, 118, 248, 140, 177, 65, 158, 150, 55, 134, 0, 0, 0, + 0, 0, 0, 198, 151, 107, 163, 124, 88, 251, 196, 125, 207, 161, 103, 90, 230, 135, 74, 189, 111, 118, 248, 140, + 97, 204, 115, 150, 55, 134, 123, 45, 110, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +}; +constexpr std::array enlarged{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 12, 46, 26, 22, 90, 53, 18, 71, 41, 50, 102, 55, 58, 108, 58, 53, 98, 52, + 88, 131, 65, 87, 128, 62, 84, 119, 58, 114, 144, 69, 102, 139, 63, 106, 133, 60, 136, 144, 67, 139, 144, 68, + 56, 71, 29, 0, 0, 0, 0, 0, 0, 16, 85, 39, 25, 165, 76, 21, 130, 59, 80, 188, 84, 94, 198, 89, + 86, 178, 78, 155, 246, 102, 150, 236, 97, 151, 221, 89, 232, 255, 112, 210, 255, 100, 213, 250, 94, 255, 255, 108, + 255, 255, 107, 113, 129, 44, 0, 0, 0, 0, 0, 0, 19, 67, 38, 31, 130, 74, 25, 100, 57, 72, 148, 78, + 83, 155, 82, 75, 137, 72, 128, 191, 92, 124, 181, 87, 119, 172, 81, 167, 225, 99, 146, 202, 89, 151, 197, 85, + 200, 238, 97, 198, 235, 95, 79, 96, 39, 0, 0, 0, 0, 0, 0, 70, 90, 108, 135, 177, 217, 108, 140, 171, + 172, 198, 208, 188, 211, 215, 167, 186, 192, 218, 235, 219, 227, 238, 214, 175, 222, 204, 95, 245, 222, 62, 245, 213, + 89, 240, 209, 122, 244, 224, 123, 243, 224, 49, 124, 99, 0, 0, 0, 0, 0, 0, 74, 89, 130, 139, 174, 255, + 110, 136, 201, 182, 194, 246, 197, 205, 253, 170, 182, 223, 244, 239, 255, 255, 234, 252, 186, 218, 236, 52, 255, 255, + 15, 245, 249, 49, 244, 240, 72, 255, 255, 73, 255, 255, 29, 130, 113, 0, 0, 0, 0, 0, 0, 76, 82, 96, + 147, 160, 188, 114, 123, 145, 166, 177, 183, 181, 187, 188, 163, 165, 163, 186, 224, 205, 188, 214, 191, 140, 200, 176, + 80, 251, 215, 54, 228, 190, 75, 211, 179, 105, 219, 206, 106, 217, 204, 42, 87, 82, 0, 0, 0, 0, 0, 0, + 124, 96, 69, 250, 189, 137, 195, 149, 108, 225, 207, 138, 250, 221, 143, 237, 195, 127, 134, 244, 156, 80, 245, 148, + 103, 228, 139, 135, 248, 165, 120, 252, 150, 129, 193, 143, 175, 68, 160, 178, 59, 161, 72, 34, 66, 0, 0, 0, + 0, 0, 0, 135, 101, 67, 255, 197, 133, 206, 153, 103, 255, 216, 134, 255, 228, 139, 247, 200, 122, 127, 255, 152, + 67, 255, 144, 98, 237, 134, 147, 255, 162, 131, 255, 146, 138, 187, 138, 189, 48, 157, 190, 37, 156, 76, 26, 64, + 0, 0, 0, 0, 0, 0, 57, 44, 32, 110, 85, 64, 84, 65, 48, 121, 94, 63, 140, 98, 65, 102, 86, 57, + 60, 120, 72, 39, 112, 68, 46, 103, 62, 61, 134, 76, 52, 133, 68, 56, 82, 64, 78, 34, 74, 77, 29, 73, + 31, 16, 29, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, +}; +constexpr std::array reduced{ + 2, 22, 10, 14, 58, 25, 35, 70, 30, 53, 83, 33, 74, 90, 34, 95, 99, 36, 37, 40, 13, 17, 60, 41, + 63, 155, 101, 115, 186, 110, 157, 217, 117, 161, 234, 120, 207, 255, 127, 81, 103, 47, 52, 64, 91, 142, 165, 218, + 186, 193, 220, 217, 219, 227, 58, 229, 227, 70, 251, 241, 32, 101, 90, 92, 72, 57, 230, 184, 137, 233, 214, 144, + 110, 238, 155, 114, 255, 157, 158, 131, 166, 64, 23, 60, 32, 24, 16, 84, 60, 38, 82, 70, 41, 27, 79, 44, + 40, 90, 45, 56, 29, 47, 22, 2, 17, +}; +constexpr std::array plain{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 40, 0, 85, 34, 53, 131, 47, + 45, 111, 39, 106, 162, 54, 90, 137, 45, 159, 193, 61, 135, 164, 51, 212, 224, 68, 180, 190, 57, 0, 0, 0, + 0, 0, 0, 0, 85, 34, 0, 70, 28, 45, 111, 39, 37, 91, 32, 90, 137, 45, 74, 113, 37, 135, 164, 51, + 111, 135, 42, 180, 190, 57, 148, 156, 47, 0, 0, 0, 0, 0, 0, 97, 117, 191, 82, 99, 162, 150, 148, 198, + 127, 125, 168, 203, 179, 205, 172, 152, 174, 0, 210, 212, 0, 178, 180, 53, 241, 219, 45, 204, 186, 0, 0, 0, + 0, 0, 0, 82, 99, 162, 67, 81, 133, 127, 125, 168, 105, 103, 138, 172, 152, 174, 142, 125, 143, 0, 178, 180, + 0, 147, 148, 45, 204, 186, 37, 168, 153, 0, 0, 0, 0, 0, 0, 194, 134, 86, 164, 113, 73, 247, 165, 93, + 209, 140, 79, 44, 196, 100, 37, 166, 85, 97, 227, 107, 82, 192, 90, 150, 2, 114, 127, 1, 96, 0, 0, 0, + 0, 0, 0, 164, 113, 73, 135, 93, 60, 209, 140, 79, 172, 115, 65, 37, 166, 85, 30, 137, 70, 82, 192, 90, + 67, 158, 74, 127, 1, 96, 105, 1, 79, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +}; + +std::vector rgba(std::span const Rgb) { + std::vector result; + for (std::size_t idx = 0; idx < Rgb.size(); idx += 3) { + result.insert(result.end(), {Rgb[idx], Rgb[idx + 1], Rgb[idx + 2], 255}); + } + return result; +} + +} // namespace + +TEST_CASE("wasm kernels: led_post gives the pixels of led_util.render_post") { + auto const input{rgba(source)}; + std::vector output(wasm_screens::image_size(12, 8), 7); + REQUIRE(wasm_screens::led_post(input, 5, 3, output, true)); + CHECK(output == rgba(posted)); + + REQUIRE(wasm_screens::led_post(input, 5, 3, output, false)); + CHECK(output == rgba(plain)); +} + +TEST_CASE("wasm kernels: resize_lanczos gives the pixels of Pillow's resize with LANCZOS") { + auto const input{rgba(posted)}; + std::vector larger(wasm_screens::image_size(17, 11)); + REQUIRE(wasm_screens::resize_lanczos(input, 12, 8, larger, 17, 11)); + CHECK(larger == rgba(enlarged)); + + std::vector smaller(wasm_screens::image_size(7, 5)); + REQUIRE(wasm_screens::resize_lanczos(input, 12, 8, smaller, 7, 5)); + CHECK(smaller == rgba(reduced)); +} + +TEST_CASE("wasm kernels: images that don't fit their buffers are refused") { + std::vector const input(wasm_screens::image_size(5, 3)); + std::vector output(wasm_screens::image_size(12, 8) - 1); + CHECK_FALSE(wasm_screens::led_post(input, 5, 3, output, true)); + CHECK_FALSE(wasm_screens::led_post(input, 0, 3, output, true)); + CHECK_FALSE(wasm_screens::resize_lanczos(input, 5, 3, output, 12, 8)); + CHECK_FALSE(wasm_screens::resize_lanczos(input, 6, 3, output, 2, 2)); +} diff --git a/tests/unit/test_wasm_screens.cpp b/tests/unit/test_wasm_screens.cpp new file mode 100644 index 000000000..5224f4b94 --- /dev/null +++ b/tests/unit/test_wasm_screens.cpp @@ -0,0 +1,103 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "scripting/wasmscreenrules.h" +#include "utilities/parser.h" + +// the parts of the wasm screens that don't need the runtime: the .mmd entries, the refresh schedule counted in +// frames and the files a screen may read + +using wasm_screens::frame_schedule; +using wasm_screens::screen_config; + +TEST_CASE("wasm screens: a cab screen entry with every key") { + cParser parser("{ ekran.wasm target: screen01 frames: 6 parameters: id=1&mode=full } next:", cParser::buffer_TEXT); + screen_config config; + config.deserialize(parser); + + CHECK(config.script == "ekran.wasm"); + CHECK(config.target == "screen01"); + CHECK(config.frames == 6); + CHECK(config.parameters == "id=1&mode=full"); + // the parser stops at the end of the block + CHECK(parser.getToken() == "next:"); +} + +TEST_CASE("wasm screens: the optional keys keep their defaults, an unknown key is skipped with its value") { + cParser parser("{ tablica.wasm later: 12 instance: name background: tablica_off }", cParser::buffer_TEXT); + screen_config config; + config.deserialize(parser); + + CHECK(config.script == "tablica.wasm"); + CHECK(config.target == "none"); + CHECK(config.frames == 0); + CHECK(config.parameters.empty()); + CHECK(config.instancing == "name"); + CHECK(config.background == "tablica_off"); +} + +TEST_CASE("wasm screens: the interval set in eu07.ini, or the screen's own when it is longer") { + CHECK(frame_schedule::effective_interval(4, 0) == 4); + CHECK(frame_schedule::effective_interval(4, 10) == 10); + CHECK(frame_schedule::effective_interval(4, 2) == 4); + // never less than every frame + CHECK(frame_schedule::effective_interval(0, 0) == 1); + CHECK(frame_schedule::effective_interval(-3, -1) == 1); +} + +TEST_CASE("wasm screens: a screen is due once per interval") { + frame_schedule schedule{100, 3, 0}; + CHECK(schedule.poll(100)); + // asked again in the same frame (the vehicle drawn in more than one pass) + CHECK_FALSE(schedule.poll(100)); + CHECK_FALSE(schedule.poll(101)); + CHECK_FALSE(schedule.poll(102)); + CHECK(schedule.poll(103)); + CHECK_FALSE(schedule.poll(105)); + CHECK(schedule.poll(106)); +} + +TEST_CASE("wasm screens: a screen out of sight for a while is due on the first frame it is asked again") { + frame_schedule schedule{0, 5, 0}; + CHECK(schedule.poll(0)); + CHECK(schedule.poll(42)); + CHECK_FALSE(schedule.poll(46)); + CHECK(schedule.poll(47)); +} + +TEST_CASE("wasm screens: the phase spreads the screens over the frames of an interval") { + auto const interval{30}; + auto const phase{frame_schedule::phase("make:dynamic/pkp/ed72/tablica.wasm?$timetable=ed72-001", interval)}; + CHECK(phase >= 0); + CHECK(phase < interval); + // the same name always gets the same phase + CHECK(phase == frame_schedule::phase("make:dynamic/pkp/ed72/tablica.wasm?$timetable=ed72-001", interval)); + // a screen refreshed every frame has no phase + CHECK(frame_schedule::phase("anything", 1) == 0); + + frame_schedule schedule{1000, interval, phase}; + auto first{std::uint64_t{0}}; + for (auto frame = std::uint64_t{1000}; frame < 1000 + interval; ++frame) { + if (schedule.poll(frame)) { + first = frame; + break; + } + } + CHECK(first == 1000 + static_cast(phase)); +} + +TEST_CASE("wasm screens: a screen reads files only below its own folder") { + CHECK(wasm_screens::is_safe_relative_path("font.png")); + CHECK(wasm_screens::is_safe_relative_path("data/font.png")); + CHECK(wasm_screens::is_safe_relative_path("data\\font.png")); + CHECK(wasm_screens::is_safe_relative_path("data/..font.png")); + + CHECK_FALSE(wasm_screens::is_safe_relative_path("")); + CHECK_FALSE(wasm_screens::is_safe_relative_path("../eu07.ini")); + CHECK_FALSE(wasm_screens::is_safe_relative_path("data/../../eu07.ini")); + CHECK_FALSE(wasm_screens::is_safe_relative_path("data\\..\\x")); + CHECK_FALSE(wasm_screens::is_safe_relative_path("..")); + CHECK_FALSE(wasm_screens::is_safe_relative_path("/etc/passwd")); + CHECK_FALSE(wasm_screens::is_safe_relative_path("\\windows")); + CHECK_FALSE(wasm_screens::is_safe_relative_path("c:/windows/win.ini")); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index ce299ce5d..6f27d6315 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -72,6 +72,10 @@ void global_settings::FinalizeConfig() python_enabled = false; #endif +#ifndef WITH_WASM + wasm_enabled = false; +#endif + #ifdef _WIN32 Console::ModeSet(iFeedbackMode, iFeedbackPort); #endif @@ -877,6 +881,29 @@ bool global_settings::ConfigParseUI(cParser& Parser, const std::string& token) return false; } +bool global_settings::ConfigParseWasm(cParser& Parser, std::string_view const token) +{ + if (token == "wasm.enabled") + { + ParseOne(Parser, wasm_enabled, 1); + return true; + } + + if (token == "wasm.cabframes") + { + ParseOneClamped(Parser, wasm_cabframes, 1, 1000); + return true; + } + + if (token == "wasm.externalframes") + { + ParseOneClamped(Parser, wasm_externalframes, 1, 1000); + return true; + } + + return false; +} + bool global_settings::ConfigParsePython(cParser& Parser, const std::string& token) { if (token == "python.enabled") @@ -1373,6 +1400,9 @@ void global_settings::ConfigParse(cParser& Parser) if (ConfigParsePython(Parser, token)) continue; + if (ConfigParseWasm(Parser, token)) + continue; + if (ConfigParseNetwork(Parser, token)) continue; @@ -1840,6 +1870,9 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "python.threadedupload", python_threadedupload ); export_as_text( Output, "python.uploadmain", python_uploadmain ); export_as_text( Output, "python.mipmaps", python_mipmaps ); + export_as_text( Output, "wasm.enabled", wasm_enabled ); + export_as_text( Output, "wasm.cabframes", wasm_cabframes ); + export_as_text( Output, "wasm.externalframes", wasm_externalframes ); export_as_text( Output, "async.trainThreads", trainThreads ); for( auto const &server : network_servers ) { Output diff --git a/utilities/Globals.h b/utilities/Globals.h index 872338b46..afa40e854 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -296,6 +296,9 @@ struct global_settings { bool python_sharectx = true; bool python_uploadmain = true; std::chrono::duration python_minframetime {0.01f}; + bool wasm_enabled{true}; // screens drawn by WebAssembly modules (wasmscreen:, wasmdestinationsign: in the .mmd) + int wasm_cabframes{4}; // the wasm screens in the cab are refreshed every so many rendered frames + int wasm_externalframes{30}; // the wasm screens outside the cab (destination signs) are refreshed every so many rendered frames bool gfx_skiprendering = false; int gfx_framebuffer_width = -1; @@ -390,6 +393,7 @@ struct global_settings { bool ConfigParseSimulation(cParser& Parser, const std::string& token); bool ConfigParseUI(cParser& Parser, const std::string& token); bool ConfigParsePython(cParser& Parser, const std::string& token); + bool ConfigParseWasm(cParser& Parser, std::string_view token); bool ConfigParseNetwork(cParser& Parser, const std::string& token); bool ConfigParseHardware(cParser& Parser, const std::string& token); bool ConfigParseDebug(cParser& Parser, const std::string& token); diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index b9c55bfac..4842e5b1a 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -35,6 +35,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/renderer.h" #include "application/uitranscripts.h" #include "input/messaging.h" +#include "application/application.h" #include "vehicle/Driver.h" // Ra: taki zapis funkcjonuje lepiej, ale może nie jest optymalny @@ -3139,6 +3140,20 @@ void TDynamicObject::update_destinations() { && ctOwner != nullptr)) ? // lcd signs are off for carriages without engine, potentially left on a siding DestinationSign.destination : DestinationSign.destination_off; + + update_wasm_destination(); +} + +void TDynamicObject::update_wasm_destination() { + + if( DestinationSign.wasm_sign == nullptr ) { return; } + // only while the sign shows the destination it draws + if( m_materialdata.replacable_skins[ 4 ] != DestinationSign.destination ) { return; } + + auto &queue { Application.wasm_screens() }; + if( false == queue.due( *DestinationSign.wasm_sign ) ) { return; } + // read anew on every refresh, so the sign follows the timetable + queue.submit( DestinationSign.wasm_sign, std::make_shared( DestinationSign.wasm_request ), 0 ); } bool TDynamicObject::Update(double dt, double dt1) @@ -7080,6 +7095,14 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co DestinationSign.script = asBaseDir + DestinationSign.script; } } + else if( token == "wasmdestinationsign:" ) { + DestinationSign.wasm.deserialize( parser ); + // supply vehicle folder as script path if none is provided + if( false == DestinationSign.wasm.script.empty() + && substr_path( DestinationSign.wasm.script ).empty() ) { + DestinationSign.wasm.script = asBaseDir + DestinationSign.wasm.script; + } + } // NOTE: legacy key, now expected as optional "background:" parameter in pydestinationsign: { parameter block } else if( token == "destinationsignbackground:" ) { parser.getTokens(); @@ -7099,7 +7122,9 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co if( ReplacableSkin != "none" ) { // potentially set blank destination texture - DestinationSign.destination_off = DestinationFind( DestinationSign.background.empty() ? "nowhere" : DestinationSign.background ); + auto const wasmbackground { Global.wasm_enabled && false == DestinationSign.wasm.script.empty() && false == DestinationSign.wasm.background.empty() }; + auto const &background { wasmbackground ? DestinationSign.wasm.background : DestinationSign.background }; + DestinationSign.destination_off = DestinationFind( background.empty() ? "nowhere" : background ); } // assign default samples to sound emitters which weren't included in the config file @@ -7920,6 +7945,7 @@ void TDynamicObject::DestinationClear() { if( false == DestinationSign.has_light ) { return; } // physical destination signs remain up until manually changed // update_destinations() shows the blank sign in place of the missing destination DestinationSign.destination = null_handle; + DestinationSign.wasm_sign.reset(); } void TDynamicObject::DestinationSet(std::string const &to, std::string const &numer) { @@ -7933,6 +7959,8 @@ void TDynamicObject::DestinationSet(std::string const &to, std::string const &nu if( std::abs( m_materialdata.multi_textures ) >= 4 ) { return; } // jak są 4 tekstury wymienne, to nie zmieniać rozkładem if( DestinationSign.sign == nullptr ) { return; } // no sign submodel, no problem + // a sign drawn for the previous destination + DestinationSign.wasm_sign.reset(); // now see if we can find any version of the destination texture std::vector const destinations = { @@ -7948,21 +7976,27 @@ void TDynamicObject::DestinationSet(std::string const &to, std::string const &nu } } // if we didn't get static texture we might be able to make one + if( true == destination_set_wasm( numer ) ) { return; } if( DestinationSign.script.empty() ) { return; } // no script so no way to make the texture if( numer == "none" ) { return; } // blank or incomplete/malformed timetable, don't bother + DestinationSign.destination = GfxRenderer->Fetch_Material( destination_request( DestinationSign.script, DestinationSign.instancing, DestinationSign.parameters ) ); +} + +std::string TDynamicObject::destination_request( std::string const &Script, std::string const &Instancing, std::string const &Parameters ) const { + auto const trainname { [this]() -> std::string { if( ctOwner != nullptr ) { return ctOwner->TrainName(); } if( Mechanik != nullptr ) { return Mechanik->TrainName(); } return "none"; } }; // shouldn't get here but, eh - auto const instance { [this]() -> std::string { - if( DestinationSign.instancing == "name" ) { return MoverParameters->Name; } - if( DestinationSign.instancing == "type" ) { return MoverParameters->TypeName; } + auto const instance { [this, &Instancing]() -> std::string { + if( Instancing == "name" ) { return MoverParameters->Name; } + if( Instancing == "type" ) { return MoverParameters->TypeName; } return "none"; } }; std::string signrequest { "make:" - + DestinationSign.script + + Script + "?" // timetable include + "$timetable=" + ( @@ -7973,15 +8007,40 @@ void TDynamicObject::DestinationSet(std::string const &to, std::string const &nu // NOTE: underscore doesn't have any magic meaning for the time being, it's just less likely to conflict with regular dictionary keys + "&_id1=" + trainname() }; // TBD, TODO: replace instancing with support for variables in extra parameters string? - if( false == DestinationSign.instancing.empty() ) { + if( false == Instancing.empty() ) { signrequest += "&_id2=" + instance(); } // optionl extra parameters - if( false == DestinationSign.parameters.empty() ) { - signrequest += "&" + DestinationSign.parameters; + if( false == Parameters.empty() ) { + signrequest += "&" + Parameters; } + return signrequest; +} - DestinationSign.destination = GfxRenderer->Fetch_Material( signrequest ); +bool TDynamicObject::destination_set_wasm( std::string const &Numer ) { + + if( false == Global.wasm_enabled ) { return false; } + if( DestinationSign.wasm.script.empty() ) { return false; } // no wasm sign, maybe a python one + if( Numer == "none" ) { return false; } // blank or incomplete/malformed timetable, don't bother + + auto const signrequest { destination_request( DestinationSign.wasm.script, DestinationSign.wasm.instancing, DestinationSign.wasm.parameters ) }; + auto const signmaterial { GfxRenderer->Fetch_Material( signrequest ) }; + if( signmaterial == null_handle ) { return false; } + auto &signtexture { GfxRenderer->Texture( GfxRenderer->Material( signmaterial )->GetTexture( 0 ) ) }; + + // vehicles showing the same request (one train, one instance) share the screen, as they share the texture + auto sign { Application.wasm_screens().acquire( { + .kind = wasm_screen_kind::external, + .script = DestinationSign.wasm.script, + .key = signrequest, + .texture = &signtexture, + .frames = DestinationSign.wasm.frames } ) }; + if( sign == nullptr ) { return false; } // the wasm screens are off + + DestinationSign.destination = signmaterial; + DestinationSign.wasm_sign = std::move( sign ); + DestinationSign.wasm_request = signrequest.substr( signrequest.find( '?' ) + 1 ); + return true; } material_handle TDynamicObject::DestinationFind( std::string Destination ) { diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index bfd477c4f..feaa548e8 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -22,8 +22,12 @@ http://mozilla.org/MPL/2.0/. #include "audio/sound.h" #include "world/Spring.h" #include "vehicle/mirrors.h" +#include "scripting/wasmscreenrules.h" #include +#include + +class wasm_screen; // scripting/wasmscreens.h #define EU07_SOUND_BOGIESOUNDS @@ -251,6 +255,9 @@ public: int update_rate { 0 }; // -1: per stop, 0: none, >0: fps // TBD, TODO: implement? std::string instancing; // potential method to generate more than one texture per timetable std::string parameters; // potential extra parameters supplied by mmd file + wasm_screens::screen_config wasm; // potential WebAssembly sign (wasmdestinationsign:), used in place of the python one while wasm screens are on + std::shared_ptr wasm_sign; // the wasm screen drawing the current destination + std::string wasm_request; // its input: the key=value pairs a python sign gets for its texture // methods void deserialize( cParser &Input ); private: @@ -726,6 +733,8 @@ private: void update_load_offset(); void shuffle_load_order(); void update_destinations(); + // feeds the wasm destination sign with fresh data, when it is shown and due + void update_wasm_destination(); bool Update(double dt, double dt1); bool FastUpdate(double dt); void Move(double fDistance); @@ -849,6 +858,10 @@ private: // blanks electronic destination sign at the end of the service; physical signs stay until changed void DestinationClear(); material_handle DestinationFind( std::string Destination ); + // the name of a generated destination sign texture: the script, the timetable, the instancing and the parameters + std::string destination_request( std::string const &Script, std::string const &Instancing, std::string const &Parameters ) const; + // makes the destination sign a wasm screen, when the vehicle has one and the wasm screens are on. returns true when it did + bool destination_set_wasm( std::string const &Numer ); void OverheadTrack(float o); glm::dvec3 get_future_movement() const; void move_set(double distance); diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index fb42c85fa..084e65d4d 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -38,6 +38,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include /* namespace input { @@ -10035,7 +10036,10 @@ bool TTrain::Update(double const Deltatime) // screens if (!FreeFlyModeFlag && simulation::Train == this) // don't bother if we're outside + { update_screens(Deltatime); + update_wasm_screens(); + } // update direction relay if (prevBatState != mvOccupied->Power24vIsAvailable) @@ -10564,6 +10568,92 @@ void TTrain::update_screens(double dt) } } +void TTrain::update_wasm_screens() +{ + auto &queue{Application.wasm_screens()}; + for (auto &entry : m_wasmscreens) + { + if (false == queue.due(*entry.screen)) + { + continue; + } + auto input{GetTrainState(entry.parameters)}; + input->insert("touches", *entry.touch_list); + entry.touch_list->clear(); + queue.submit(entry.screen, std::move(input), id()); + } +} + +bool TTrain::find_screen_surface(std::string const &Target, std::string_view const Kind, TSubModel *&Submodel, ITexture *&Texture) const +{ + Submodel = DynamicObject->mdKabina ? DynamicObject->mdKabina->GetFromName(Target) : + DynamicObject->mdLowPolyInt ? DynamicObject->mdLowPolyInt->GetFromName(Target) : + nullptr; + if (Submodel == nullptr) + { + WriteLog(std::format("{}: submodel {} not found - Ignoring screen", Kind, Target)); + return false; + } + auto const material{Submodel->GetMaterial()}; + if (material <= 0) + { + // sub model nie posiada tekstury lub tekstura wymienna - nie obslugiwana + WriteLog(std::format("{}: invalid texture id {} - Ignoring screen", Kind, material)); + return false; + } + + Texture = &GfxRenderer->Texture(GfxRenderer->Material(material)->GetTexture(0)); + return true; +} + +void TTrain::load_wasm_screen(cParser &Parser) +{ + wasm_screen_entry entry; + // the block is read whole even when the wasm screens are off + entry.config.deserialize(Parser); + if (entry.config.script.empty()) + { + return; + } + if (substr_path(entry.config.script).empty()) + { + entry.config.script = DynamicObject->asBaseDir + entry.config.script; + } + + TSubModel *submodel{nullptr}; + ITexture *texture{nullptr}; + if (entry.config.target != "none" && false == find_screen_surface(entry.config.target, "WASM Screen", submodel, texture)) + { + return; + } + + entry.screen = Application.wasm_screens().acquire({.kind = wasm_screen_kind::cab, + .script = entry.config.script, + .key = std::format("cab:{}:{}:{}", DynamicObject->name(), entry.config.target, entry.config.script), + .texture = texture, + .frames = entry.config.frames}); + if (entry.screen == nullptr) + { + // the wasm screens are off + return; + } + if (texture != nullptr) + { + // make the surface static so it doesn't get destroyed by garbage collector if the user spends long time outside cab + texture->create(true); + } + if (false == entry.config.parameters.empty()) + { + entry.parameters = dictionary_source(entry.config.parameters); + } + entry.touch_list = std::make_shared>(); + if (submodel != nullptr) + { + submodel->screen_touch_list = entry.touch_list; + } + m_wasmscreens.emplace_back(std::move(entry)); +} + void TTrain::add_distance(double const Distance) { @@ -10739,6 +10829,7 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) m_controlmapper.clear(); // clear python screens m_screens.clear(); + m_wasmscreens.clear(); // reset sound positions auto const nullvector{glm::vec3()}; std::vector>> sounds = { @@ -10930,23 +11021,10 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) TSubModel *submodel = nullptr; if (screen.target != "none") { - submodel = DynamicObject->mdKabina ? DynamicObject->mdKabina->GetFromName(screen.target) : - DynamicObject->mdLowPolyInt ? DynamicObject->mdLowPolyInt->GetFromName(screen.target) : - nullptr; - if (submodel == nullptr) + if (false == find_screen_surface(screen.target, "Python Screen", submodel, tex)) { - WriteLog("Python Screen: submodel " + screen.target + " not found - Ignoring screen"); continue; } - auto const material{submodel->GetMaterial()}; - if (material <= 0) - { - // sub model nie posiada tekstury lub tekstura wymienna - nie obslugiwana - WriteLog("Python Screen: invalid texture id " + std::to_string(material) + " - Ignoring screen"); - continue; - } - - tex = &GfxRenderer->Texture(GfxRenderer->Material(material)->GetTexture(0)); } else { @@ -10973,6 +11051,10 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) if (Global.python_displaywindows) m_screens.back().viewer = std::make_unique(rt, m_screens.back().touch_list, m_screens.back().script); } + else if (token == "wasmscreen:") + { + load_wasm_screen(parser); + } else if (token == "pyscreenupdatetime:") { parser.getTokens(); diff --git a/vehicle/Train.h b/vehicle/Train.h index dd077e366..1d7e032c6 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/PyInt.h" #include "input/command.h" #include "scripting/pythonscreenviewer.h" +#include "scripting/wasmscreens.h" #include "utilities/dictionary.h" #undef snprintf // pyint.h->python @@ -145,6 +146,14 @@ class TTrain { using screenentry_sequence = std::vector; + // a screen of the cab drawn by a WebAssembly module (wasmscreen: in the .mmd) + struct wasm_screen_entry { + wasm_screens::screen_config config; + dictionary_source parameters; // the config's parameters, pre-processed + std::shared_ptr screen; + std::shared_ptr> touch_list; + }; + // methods bool CabChange(int iDirection); bool ShowNextCurrent{false}; // pokaz przd w podlaczonej lokomotywie (ET41) @@ -233,6 +242,10 @@ class TTrain { end cab_to_end() const { return cab_to_end( iCabn ); } void update_screens(double dt); + void update_wasm_screens(); + // finds the submodel and the texture a cab screen is drawn on. returns false when the screen is to be ignored + bool find_screen_surface(std::string const &Target, std::string_view Kind, TSubModel *&Submodel, ITexture *&Texture) const; + void load_wasm_screen(cParser &Parser); // command handlers // NOTE: we're currently using universal handlers and static handler map but it may be beneficial to have these implemented on individual class instance basis @@ -935,6 +948,7 @@ private: bool m_mastercontrollerinuse { false }; float m_mastercontrollerreturndelay { 0.f }; screenentry_sequence m_screens; + std::vector m_wasmscreens; uint16_t vid { 0 }; // train network recipient id float m_distancecounter { -1.f }; // distance traveled since meter was activated or -1 if inactive double m_brakehandlecp{ 0.0 }; diff --git a/wasm_screens_doc.md b/wasm_screens_doc.md new file mode 100644 index 000000000..494d07c0d --- /dev/null +++ b/wasm_screens_doc.md @@ -0,0 +1,129 @@ +# WebAssembly screens + +Screens drawn by WebAssembly modules, alongside the Python screens (`pyscreen:`, `pydestinationsign:`). A module +gets the same input a Python screen gets (the table in `python_var_doc.md`), returns an RGBA image and, in the cab, +may send commands. The modules run in the WAMR interpreter (`ref/wamr`), in a sandbox: a module reaches nothing but +the functions of the `eu07` module below, and reads files only from its own folder. + +Unlike a Python screen, which refreshes after a time (`python.updatetime`, `updatetime:`), a WebAssembly screen +refreshes every so many rendered frames, set in `eu07.ini`. + +## eu07.ini + +| key | default | meaning | +|-----------------------|---------|--------------------------------------------------------------------------------| +| `wasm.enabled` | 1 | 0: no WebAssembly screens; the vehicles show what they did before | +| `wasm.cabframes` | 4 | a screen in the cab is refreshed every so many frames (1-1000) | +| `wasm.externalframes` | 30 | a screen outside the cab (destination sign) is refreshed every so many frames | + +A screen may ask for a longer interval of its own (`frames:` below); the longer of the two counts. Screens sharing +an interval are spread over its frames, so they don't all refresh on the same one. A screen in the cab is refreshed +only while the player sits in that cab, a screen outside only while its vehicle is drawn. + +## .mmd + +In the cab section, next to `pyscreen:`: + +``` +wasmscreen: { ekran.wasm target: screen01 frames: 6 parameters: id=1&mode=full } +``` + +| key | meaning | +|---------------|---------------------------------------------------------------------------------------------------| +| (first token) | the module, relative to the vehicle folder when it has no path of its own | +| `target:` | the submodel the screen is drawn on (its texture is replaced); `none` for a screen that only sends commands | +| `frames:` | the screen's own refresh interval, used when longer than `wasm.cabframes` | +| `parameters:` | extra `key=value` pairs, `&`-separated, added to the input | + +A touch on the screen's submodel comes in the input as the list of points `touches`, as for the Python screens. + +In `internaldata:`, next to `pydestinationsign:`: + +``` +wasmdestinationsign: { tablica.wasm frames: 60 instance: name background: tablica_off parameters: style=lcd } +``` + +The keys are those of `pydestinationsign:` (`instance:`, `parameters:`, `background:`) and `frames:`. The input is +what a Python sign gets: the timetable (`$timetable`), `_id1` (the train), `_id2` (the instance) and the +parameters, read anew on every refresh, so the sign can follow the journey. The vehicles of one train showing the +same request share one screen and one texture. A static destination texture, when there is one, still comes first. + +A vehicle may have both `pydestinationsign:` and `wasmdestinationsign:`: with the WebAssembly screens on, the +WebAssembly one is used; with them off (or in a release without them) the Python one. An unknown key in either block +is skipped together with its value. + +## The module + +Exports: + +| export | meaning | +|-------------------------------|------------------------------------------------------------------------------------------| +| `memory` | the linear memory | +| `screen_init() -> i32` | optional; called once after loading. anything but 0 disables the screen | +| `screen_render() -> i32` | called on every refresh. returns the address of the image, or 0 to keep the previous one | +| `screen_width() -> i32` | the width of the image, asked after every `screen_render` that returned an image | +| `screen_height() -> i32` | the height of the image, up to 4096 on either side | + +The image is `width * height` pixels of 4 bytes, R G B A, in sRGB, its rows in the order the Python screens give +them (PIL's `tobytes()`). + +Imports, module `eu07` (keys and texts are a pointer and a length in bytes, in the module's memory): + +| import | meaning | +|-----------------------------------------------------------------|-----------------------------------------------------------------| +| `value_type(key, key_len) -> i32` | 0 no such value, 1 float, 2 int, 3 bool, 4 string, 5 list of points | +| `get_float(key, key_len) -> f64` | the value as a number (int and bool too); 0 when there is none | +| `get_int(key, key_len) -> i32` | the value as an integer (a float is truncated) | +| `get_bool(key, key_len) -> i32` | 1 or 0 | +| `get_string(key, key_len, buffer, capacity) -> i32` | copies the text, in UTF-8; returns its whole length, -1 when there is none | +| `get_vec2_count(key, key_len) -> i32` | the number of points in a list (`touches`) | +| `get_vec2(key, key_len, index, out) -> i32` | writes the point as two f32 at `out`; returns 1, or 0 when there is none | +| `command(name, name_len, param1, param2)` | sends a command (the names of `simulation::commandMap`) to the vehicle of the cab; ignored outside the cab | +| `log(text, text_len)` | writes a line to the log | +| `time() -> f64` | seconds of a steady clock shared by all screens, for animations (scrolling) that keep their pace whatever the refresh interval | +| `led_post(source, width, height, target, bloom) -> i32` | `led_util.render_post()` of the Python screens, run natively: each diode of the `width x height` image becomes 2x2 pixels with a darker grid, glowing into its neighbours when `bloom` is not 0, in a 1 pixel black frame; `target` takes `(2 width + 2) x (2 height + 2)`. returns 1, or 0 for sizes over 4096 | +| `resize_lanczos(source, width, height, target, target_width, target_height) -> i32` | Pillow's `resize(..., Image.LANCZOS)`, run natively, giving the same pixels. returns 1, or 0 for sizes over 4096 | +| `file_read(path, path_len, buffer, capacity) -> i32` | reads a file from the module's folder or below; returns the file's whole size, -1 when there is none or the path leads outside | + +`led_post` and `resize_lanczos` take RGBA images in the module's memory and write alpha 255; the source and the +target may overlap. They are what makes LED boards fast enough: in the interpreter the same filters take some 30 +times longer. + +A call into the module may run at most 200 million instructions; a module that traps or runs over is disabled and +the reason goes to the log. The module gets 64 KiB of stack and no heap from the host: it manages its own memory. + +## Building a module + +With clang (any version with the `wasm32` target), no C library: + +```c +// ekran.c +#include + +#define IMPORT(name) __attribute__((import_module("eu07"), import_name(name))) +IMPORT("get_float") double get_float(const char *key, int key_len); +IMPORT("command") void command(const char *name, int name_len, int param1, int param2); + +#define WIDTH 256 +#define HEIGHT 128 +static uint32_t pixels[WIDTH * HEIGHT]; + +__attribute__((export_name("screen_width"))) int screen_width(void) { return WIDTH; } +__attribute__((export_name("screen_height"))) int screen_height(void) { return HEIGHT; } + +__attribute__((export_name("screen_render"))) int screen_render(void) { + double const velocity = get_float("velocity", 8); + int const filled = (int)(velocity * WIDTH / 160.0); + for (int y = 0; y < HEIGHT; ++y) + for (int x = 0; x < WIDTH; ++x) + pixels[y * WIDTH + x] = x < filled ? 0xFF00C000u : 0xFF202020u; // A B G R, little-endian + return (int)(uintptr_t)pixels; +} +``` + +``` +clang --target=wasm32 -O2 -nostdlib -Wl,--no-entry -o ekran.wasm ekran.c +``` + +Any language that compiles to WebAssembly works the same way (Rust `wasm32-unknown-unknown`, Zig, AssemblyScript), +as long as the module imports nothing but the `eu07` functions above. From a73585dca0a70b799cf8ed427edad122fbf4a939 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Tue, 10 Nov 2026 01:05:58 +0100 Subject: [PATCH 19/37] Dont copy entire python env when already present --- CMakeLists.txt | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b75f3295b..bfa580a32 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -678,13 +678,29 @@ if (WIN32) endif () if(WIN32 AND WITH_PYTHON) + # the Python runtime next to the game, copied when it isn't there yet or the Python install changed, rather + # than after every link of the game: the library alone is thousands of files. the folder is the game's + # RUNTIME_OUTPUT_DIRECTORY, spelled out: $ here would make this target depend on the game + get_property(EU07_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if (EU07_MULTI_CONFIG) + set(EU07_PY_TARGET_DIR "${CMAKE_BINARY_DIR}/bin/$") + else() + set(EU07_PY_TARGET_DIR "${CMAKE_BINARY_DIR}/bin") + endif() + set(EU07_PY_STAMP "${EU07_PY_TARGET_DIR}/python64/python_runtime.stamp") add_custom_command( - TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_DLL}" "$" - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_ZLIB}" "$" - COMMAND ${CMAKE_COMMAND} -E copy_directory "${EU07_PY_LIBDIR}" "$/python64/Lib" - COMMAND ${CMAKE_COMMAND} -E copy_directory "${EU07_PY_DLLSDIR}" "$/python64/DLLs" - ) + OUTPUT "${EU07_PY_STAMP}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_DLL}" "${EU07_PY_TARGET_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_ZLIB}" "${EU07_PY_TARGET_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${EU07_PY_LIBDIR}" "${EU07_PY_TARGET_DIR}/python64/Lib" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${EU07_PY_DLLSDIR}" "${EU07_PY_TARGET_DIR}/python64/DLLs" + COMMAND ${CMAKE_COMMAND} -E touch "${EU07_PY_STAMP}" + DEPENDS "${EU07_PY_DLL}" "${EU07_PY_ZLIB}" + COMMENT "Copying the Python runtime next to the game" + VERBATIM) + add_custom_target(eu07_python_runtime DEPENDS "${EU07_PY_STAMP}") + set_target_properties(eu07_python_runtime PROPERTIES FOLDER "libraries") + add_dependencies(${PROJECT_NAME} eu07_python_runtime) endif() if (WITH_WASM) From c4924f756da14cc4c3e47ebe5e11b70fdeccf8b4 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Tue, 10 Nov 2026 15:29:25 +0100 Subject: [PATCH 20/37] Lua script screens beside the WebAssembly ones --- CMakeLists.txt | 16 +- CMake_modules/wamr/CMakeLists.txt | 2 +- application/application.cpp | 9 +- application/application.h | 12 +- model/Texture.cpp | 4 +- script_screens_doc.md | 199 ++++ scripting/luaprogram.cpp | 847 ++++++++++++++++ scripting/scriptscreendrawing.cpp | 294 ++++++ scripting/scriptscreendrawing.h | 126 +++ ...eenkernels.cpp => scriptscreenkernels.cpp} | 6 +- ...mscreenkernels.h => scriptscreenkernels.h} | 6 +- scripting/scriptscreenprogram.h | 92 ++ ...mscreenrules.cpp => scriptscreenrules.cpp} | 6 +- ...{wasmscreenrules.h => scriptscreenrules.h} | 17 +- scripting/scriptscreens.cpp | 511 ++++++++++ scripting/scriptscreens.h | 98 ++ scripting/wasmprogram.cpp | 630 ++++++++++++ scripting/wasmscreens.cpp | 942 ------------------ scripting/wasmscreens.h | 72 -- scripting/wasmscreensstub.cpp | 51 - tests/unit/CMakeLists.txt | 12 +- tests/unit/run_tests.cmake | 8 + tests/unit/test_script_screen_drawing.cpp | 120 +++ tests/unit/test_script_screen_host.cpp | 596 +++++++++++ ...els.cpp => test_script_screen_kernels.cpp} | 36 +- ...sm_screens.cpp => test_script_screens.cpp} | 46 +- tests/unit/test_wasm_host.cpp | 288 ------ utilities/Globals.cpp | 28 +- utilities/Globals.h | 7 +- vehicle/DynObj.cpp | 116 ++- vehicle/DynObj.h | 25 +- vehicle/Train.cpp | 45 +- vehicle/Train.h | 16 +- wasm_screens_doc.md | 129 --- 34 files changed, 3777 insertions(+), 1635 deletions(-) create mode 100644 script_screens_doc.md create mode 100644 scripting/luaprogram.cpp create mode 100644 scripting/scriptscreendrawing.cpp create mode 100644 scripting/scriptscreendrawing.h rename scripting/{wasmscreenkernels.cpp => scriptscreenkernels.cpp} (98%) rename scripting/{wasmscreenkernels.h => scriptscreenkernels.h} (88%) create mode 100644 scripting/scriptscreenprogram.h rename scripting/{wasmscreenrules.cpp => scriptscreenrules.cpp} (96%) rename scripting/{wasmscreenrules.h => scriptscreenrules.h} (75%) create mode 100644 scripting/scriptscreens.cpp create mode 100644 scripting/scriptscreens.h create mode 100644 scripting/wasmprogram.cpp delete mode 100644 scripting/wasmscreens.cpp delete mode 100644 scripting/wasmscreens.h delete mode 100644 scripting/wasmscreensstub.cpp create mode 100644 tests/unit/test_script_screen_drawing.cpp create mode 100644 tests/unit/test_script_screen_host.cpp rename tests/unit/{test_wasm_kernels.cpp => test_script_screen_kernels.cpp} (82%) rename tests/unit/{test_wasm_screens.cpp => test_script_screens.cpp} (59%) delete mode 100644 tests/unit/test_wasm_host.cpp delete mode 100644 wasm_screens_doc.md diff --git a/CMakeLists.txt b/CMakeLists.txt index bfa580a32..cbcf185dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -72,7 +72,7 @@ option(WITH_OPENGL_LEGACY "Compile with OpenGL legacy renderer" ON) option(WITH_PYTHON "Python 3.14 embedded scripting" ON) option(WITH_UART "Compile with libserialport" ON) option(WITH_LUA "Compile with lua scripting support" ON) -option(WITH_WASM "WebAssembly screens (wasmscreen:, wasmdestinationsign:), run by the WAMR interpreter in ref/wamr" ON) +option(WITH_WASM "WebAssembly script screens (wasmscreen:, wasmdestinationsign:), run by the WAMR interpreter in ref/wamr" ON) option(WITH_OPENVR "Compile with OpenVR" OFF) option(WITH_ZMQ "Compile with cppzmq" OFF) option(WITH_CRASHPAD "Compile with crashpad" OFF) @@ -322,11 +322,14 @@ if (WITH_LUA) set(SOURCES ${SOURCES} "scripting/lua.cpp") endif() +# the script screens (scripting/scriptscreens.cpp), with the Lua and the WebAssembly runtime when they're built +set(SOURCES ${SOURCES} "scripting/scriptscreens.cpp") +if (WITH_LUA) + set(SOURCES ${SOURCES} "scripting/luaprogram.cpp") +endif() if (WITH_WASM) set(DEFINITIONS ${DEFINITIONS} "WITH_WASM") - set(SOURCES ${SOURCES} "scripting/wasmscreens.cpp") -else() - set(SOURCES ${SOURCES} "scripting/wasmscreensstub.cpp") + set(SOURCES ${SOURCES} "scripting/wasmprogram.cpp") endif() if (WITHDUMPGEN) @@ -471,8 +474,9 @@ set(CORE_SOURCES "utilities/parser.cpp" "utilities/utilities.cpp" "scripting/ladderlogic.cpp" -"scripting/wasmscreenrules.cpp" -"scripting/wasmscreenkernels.cpp" +"scripting/scriptscreenrules.cpp" +"scripting/scriptscreenkernels.cpp" +"scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" "vehicle/enginestart.cpp" "vehicle/handover.cpp" diff --git a/CMake_modules/wamr/CMakeLists.txt b/CMake_modules/wamr/CMakeLists.txt index 74e82358d..d12d48cd4 100644 --- a/CMake_modules/wamr/CMakeLists.txt +++ b/CMake_modules/wamr/CMakeLists.txt @@ -1,4 +1,4 @@ -# The WebAssembly Micro Runtime (ref/wamr) for the wasm screens (scripting/wasmscreens.cpp). +# The WebAssembly Micro Runtime (ref/wamr) for the WebAssembly script screens (scripting/wasmprogram.cpp). # # Built here, in a directory of its own, because the WAMR build scripts set their configuration with # add_definitions() and include_directories(): kept in this directory, none of it reaches the game's sources. diff --git a/application/application.cpp b/application/application.cpp index 98f004a92..136aa0600 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -425,10 +425,11 @@ int eu07_application::init(int Argc, char *Argv[]) { m_taskqueue.init(); } + crashreport_add_info("luascreens_enabled", Global.luascreens_enabled ? "yes" : "no"); crashreport_add_info("wasm_enabled", Global.wasm_enabled ? "yes" : "no"); - if (Global.wasm_enabled) + if (Global.luascreens_enabled || Global.wasm_enabled) { - m_wasmqueue.init(); + m_screenqueue.init(); } if ((result = init_modes()) != 0) { @@ -640,7 +641,7 @@ int eu07_application::run() EditorTerrain.update(Global.pCamera.Pos); m_taskqueue.update(); - m_wasmqueue.update(); + m_screenqueue.update(); opengl_texture::reset_unit_cache(); if (!GfxRenderer->Render()) @@ -738,7 +739,7 @@ void eu07_application::exit() // the python workers detach their GL context on the way out, so they have to be done before the windows they use are destroyed m_taskqueue.exit(); - m_wasmqueue.exit(); + m_screenqueue.exit(); step("the windows"); for (auto *window : m_windows) { diff --git a/application/application.h b/application/application.h index 4a1d1ad1a..850b66e1e 100644 --- a/application/application.h +++ b/application/application.h @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "application/applicationmode.h" #include "scripting/PyInt.h" -#include "scripting/wasmscreens.h" +#include "scripting/scriptscreens.h" #include "network/manager.h" #include "utilities/headtrack.h" #ifdef WITH_UART @@ -50,10 +50,10 @@ public: // frees the python gil and swaps out the main thread void release_python_lock(); - // the screens drawn by WebAssembly modules - wasm_screen_queue & - wasm_screens() { - return m_wasmqueue; } + // the screens drawn by scripts (Lua, WebAssembly) + script_screen_queue & + screens() { + return m_screenqueue; } void exit(); void @@ -127,7 +127,7 @@ private: modeptr_array m_modes { nullptr }; // collection of available application behaviour modes mode_stack m_modestack; // current behaviour mode python_taskqueue m_taskqueue; - wasm_screen_queue m_wasmqueue; + script_screen_queue m_screenqueue; std::vector m_windows; int m_glfwversion; diff --git a/model/Texture.cpp b/model/Texture.cpp index e9dc063de..67a33f44e 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -722,8 +722,8 @@ void opengl_texture::make_request() { auto const components { Split( name, '?' ) }; - if( components.front().ends_with( ".wasm" ) ) { - // wasm destination signs are drawn by the vehicles showing them (wasm_screen_queue) + if( components.front().ends_with( ".lua" ) || components.front().ends_with( ".wasm" ) ) { + // script destination signs are drawn by the vehicles showing them (script_screen_queue) return; } diff --git a/script_screens_doc.md b/script_screens_doc.md new file mode 100644 index 000000000..d8a6811b2 --- /dev/null +++ b/script_screens_doc.md @@ -0,0 +1,199 @@ +# Script screens + +Screens drawn by scripts, alongside the Python screens (`pyscreen:`, `pydestinationsign:`): Lua scripts, run by +LuaJIT, and WebAssembly modules, run by the WAMR interpreter (`ref/wamr`). A script gets the same input a Python +screen gets (the table in `python_var_doc.md`), returns an RGBA image and, in the cab, may send commands. + +A Lua script is text, kept with the vehicles and the `scripts/` folder like the Python screens, and changed with any +editor. A WebAssembly module is compiled from another language (Rust, C, Zig and the like). + +Both run sandboxed: a script reaches only the functions of `eu07` below, and reads files only from its own folder and +below. A Lua script gets no `io`, `os`, `ffi`, `debug` or `require`, and no precompiled code is loaded. + +Unlike a Python screen, which refreshes after a time (`python.updatetime`, `updatetime:`), a script screen refreshes +every so many rendered frames, set in `eu07.ini`. A call into a script may run at most 200 million instructions +(Lua runs without the JIT compiler so that the limit holds). A script that fails, or runs over, is switched off, and +the reason goes to the log. + +## eu07.ini + +| key | default | meaning | +|--------------------------|---------|--------------------------------------------------------------------------------| +| `luascreens.enabled` | 1 | 0: no Lua screens; the vehicles show what they did before | +| `wasm.enabled` | 1 | 0: no WebAssembly screens; the vehicles show what they did before | +| `screens.cabframes` | 4 | a screen in the cab is refreshed every so many frames (1-1000) | +| `screens.externalframes` | 30 | a screen outside the cab (destination sign) is refreshed every so many frames | + +`wasm.cabframes` and `wasm.externalframes`, the first names of the last two, are read as well. + +A screen may ask for a longer interval of its own (`frames:` below); the longer of the two counts. Screens sharing +an interval are spread over its frames, so they don't all refresh on the same one. A screen in the cab is refreshed +only while the player sits in that cab, a screen outside only while its vehicle is drawn. + +## .mmd + +In the cab section, next to `pyscreen:`: + +``` +luascreen: { ekran.lua target: screen01 frames: 6 parameters: id=1&mode=full } +wasmscreen: { ekran.wasm target: screen02 } +``` + +| key | meaning | +|---------------|---------------------------------------------------------------------------------------------------| +| (first token) | the script, relative to the vehicle folder when it has no path of its own | +| `target:` | the submodel the screen is drawn on (its texture is replaced); `none` for a screen that only sends commands | +| `frames:` | the screen's own refresh interval, used when longer than `screens.cabframes` | +| `parameters:` | extra `key=value` pairs, `&`-separated, added to the input | + +A touch on the screen's submodel comes in the input as the list of points `touches`, as for the Python screens. + +In `internaldata:`, next to `pydestinationsign:`: + +``` +luadestinationsign: { scripts/led_111a20.lua parameters: kod_e=IC&kod_p=TLK&kod_o=R instance: name } +destinationsignbackground: make:scripts/led_111a20.lua?dummy=1 +``` + +`luadestinationsign:` and `wasmdestinationsign:` take the keys of `pydestinationsign:` (`instance:`, `parameters:`, +`background:`) and `frames:`. The input is what a Python sign gets: the timetable (`$timetable`), `_id1` (the +train), `_id2` (the instance) and the parameters, read anew on every refresh, so the sign can follow the journey. The +vehicles of one train showing the same request share one screen and one texture. A static destination texture, when +there is one, still comes first. + +A blank sign (`background:`, or the older `destinationsignbackground:`) named `make: