From 4575f61cc8d8919571a72c9023b7cd584c81cba1 Mon Sep 17 00:00:00 2001
From: Piotr Warszawski
Date: Fri, 4 Sep 2026 15:52:38 +0200
Subject: [PATCH 01/60] whois: add lookahead mode for the timetable entry after
the next stop
Dispatcher scripts that route trains at a station based on where they
go afterwards (e.g. a big terminal throat with several outbound
directions) have no way to read that: whois +40 only exposes the
current/next timetable entry (NextStop()/IsStop()), which while the
train is at that very station is that station itself.
Adds flags::whois_ahead (bit 6, previously unused) plus
TTrainParameters::StationNameAhead(Offset)/StationIsStopAhead(Offset),
returning the raw TimeTable[] entry Offset positions past StationIndex
(name and whether it's a booked stop, "none"/false past the end of the
timetable). The new whois branch calls both with Offset=1, mirroring
the existing +40 branch's UpdateValues()/WriteLog() shape.
Logic-verified with an isolated harness mirroring the touched types
(TTrainParameters/TController/TMemCell shapes and the exact function
bodies); not yet build-tested against the full engine locally - relying
on CI for that.
---
world/Event.cpp | 31 ++++++++++++++++++++++++++++++-
world/Event.h | 1 +
world/mtable.cpp | 16 ++++++++++++++++
world/mtable.h | 4 ++++
4 files changed, 51 insertions(+), 1 deletion(-)
diff --git a/world/Event.cpp b/world/Event.cpp
index eb679e720..e47dbea23 100644
--- a/world/Event.cpp
+++ b/world/Event.cpp
@@ -1018,13 +1018,42 @@ whois_event::run_() {
auto *targetcell { static_cast( std::get( target ) ) };
if( targetcell == nullptr ) { continue; }
// event effect code
+ // +64: station after the next one, unused, stop there or passthrough
// +40: next station name, unused, stop at next station (duplicate of +0 2nd numeric value)
// +32: vehicle name
// +24: vehicle type, consist brake level, obstacle distance
// +16: load type, load amount, max load amount
// +8: destination, direction, engine power
// +0: train name, station count, stop on next station
- if( m_input.flags & flags::whois_name ) {
+ if( m_input.flags & flags::whois_ahead ) {
+ // +64
+ // the timetable entry one past the next stop, and whether the train stops there
+ auto const *owner { (
+ m_activator->Mechanik != nullptr && m_activator->Mechanik->primary() ?
+ m_activator->Mechanik :
+ m_activator->ctOwner ) };
+ auto const aheadname { (
+ owner != nullptr ?
+ owner->TrainTimetable().StationNameAhead( 1 ) :
+ "none" ) };
+ auto const aheadstop { (
+ owner != nullptr && owner->TrainTimetable().StationIsStopAhead( 1 ) ?
+ 1 :
+ 0 ) };
+
+ targetcell->UpdateValues(
+ aheadname, // station after the next one
+ 0, // unused
+ aheadstop, // stop there or passthrough
+ m_input.flags & ( flags::text | flags::value1 | flags::value2 ) );
+
+ WriteLog(
+ "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - "
+ + "[station after next: " + aheadname + "], "
+ + "[X], "
+ + "[stop there: " + ( aheadstop != 0 ? "yes" : "no" ) + "]" );
+ }
+ else if( m_input.flags & flags::whois_name ) {
// +32 or +40
// next station name
if( m_input.flags & flags::mode_alt ) {
diff --git a/world/Event.h b/world/Event.h
index 52ee3468d..55be65de1 100644
--- a/world/Event.h
+++ b/world/Event.h
@@ -37,6 +37,7 @@ public:
mode_alt = 1 << 3,
whois_load = 1 << 4,
whois_name = 1 << 5,
+ whois_ahead = 1 << 6,
// condition values
track_busy = 1 << 3,
track_free = 1 << 4,
diff --git a/world/mtable.cpp b/world/mtable.cpp
index cec54f870..75e6c8ad0 100644
--- a/world/mtable.cpp
+++ b/world/mtable.cpp
@@ -77,6 +77,22 @@ bool TTrainParameters::IsLastStop() const {
return StationIndex >= StationCount;
}
+std::string TTrainParameters::StationNameAhead( int Offset ) const
+{ // nazwa wpisu rozkladu Offset pozycji za aktualnym (bez pomijania przelotow)
+ int const idx { StationIndex + Offset };
+ if( ( idx < 1 ) || ( idx > StationCount ) )
+ return "none";
+ return TimeTable[idx].StationName;
+}
+
+bool TTrainParameters::StationIsStopAhead( int Offset ) const
+{ // czy wpis Offset pozycji za aktualnym to zaplanowany postoj
+ int const idx { StationIndex + Offset };
+ if( ( idx < 1 ) || ( idx > StationCount ) )
+ return false;
+ return TimeTable[idx].Ah >= 0; //-1 to brak postoju
+}
+
bool TTrainParameters::IsMaintenance() const {
if( StationIndex <= StationCount )
diff --git a/world/mtable.h b/world/mtable.h
index c58d120ff..701b0c6ca 100644
--- a/world/mtable.h
+++ b/world/mtable.h
@@ -70,6 +70,10 @@ class TTrainParameters
std::string ShowRelation() const;
double WatchMTable(double DistCounter);
std::string NextStop() const;
+ // nazwa wpisu rozkladu Offset pozycji za StationIndex (Offset>=1); "none" poza koncem rozkladu
+ std::string StationNameAhead( int Offset ) const;
+ // true, gdy ten wpis to zaplanowany postoj (ma godzine przyjazdu), false dla przelotu / poza koncem
+ bool StationIsStopAhead( int Offset ) const;
sound_source next_stop_sound() const;
sound_source last_stop_sound() const;
bool IsStop() const;
From 5705062cd29826b9bb1386eb2ccfa5be258a3204 Mon Sep 17 00:00:00 2001
From: Piotr Warszawski
Date: Fri, 4 Sep 2026 20:28:28 +0200
Subject: [PATCH 02/60] whois: select the lookahead mode via +48 instead of a
new bit
Per review: +48 (whois_name | whois_load, mode_alt clear) was an
unused combination of the existing mode bits - use that instead of
claiming a new bit 6. +56 (same, with mode_alt set) stays free for a
future mode. No new flags::* entry needed; mtable.h/.cpp unchanged.
---
world/Event.cpp | 8 +++++---
world/Event.h | 1 -
2 files changed, 5 insertions(+), 4 deletions(-)
diff --git a/world/Event.cpp b/world/Event.cpp
index e47dbea23..ebfc73958 100644
--- a/world/Event.cpp
+++ b/world/Event.cpp
@@ -1018,15 +1018,17 @@ whois_event::run_() {
auto *targetcell { static_cast( std::get( target ) ) };
if( targetcell == nullptr ) { continue; }
// event effect code
- // +64: station after the next one, unused, stop there or passthrough
+ // +48: station after the next one, unused, stop there or passthrough
// +40: next station name, unused, stop at next station (duplicate of +0 2nd numeric value)
// +32: vehicle name
// +24: vehicle type, consist brake level, obstacle distance
// +16: load type, load amount, max load amount
// +8: destination, direction, engine power
// +0: train name, station count, stop on next station
- if( m_input.flags & flags::whois_ahead ) {
- // +64
+ if( ( m_input.flags & ( flags::whois_name | flags::whois_load | flags::mode_alt ) )
+ == ( flags::whois_name | flags::whois_load ) ) {
+ // +48 (the whois_name | whois_load combination was unused; +56, same with mode_alt
+ // set, stays free for a future mode)
// the timetable entry one past the next stop, and whether the train stops there
auto const *owner { (
m_activator->Mechanik != nullptr && m_activator->Mechanik->primary() ?
diff --git a/world/Event.h b/world/Event.h
index 55be65de1..52ee3468d 100644
--- a/world/Event.h
+++ b/world/Event.h
@@ -37,7 +37,6 @@ public:
mode_alt = 1 << 3,
whois_load = 1 << 4,
whois_name = 1 << 5,
- whois_ahead = 1 << 6,
// condition values
track_busy = 1 << 3,
track_free = 1 << 4,
From 93463a3850e50f8818d12c042a6ef7e3639b84f3 Mon Sep 17 00:00:00 2001
From: Piotr Warszawski
Date: Fri, 4 Sep 2026 21:24:01 +0200
Subject: [PATCH 03/60] whois: consolidate the two lookahead accessors into one
Per review: StationNameAhead()/StationIsStopAhead() duplicated the same
bounds check for no reason. Replaced with a single
TimeTableEntryAhead(Offset) returning the TMTableLine itself; the whois
branch reads .StationName/.Ah off it directly.
---
world/Event.cpp | 12 +++++-------
world/mtable.cpp | 17 +++++------------
world/mtable.h | 7 +++----
3 files changed, 13 insertions(+), 23 deletions(-)
diff --git a/world/Event.cpp b/world/Event.cpp
index ebfc73958..319ad0591 100644
--- a/world/Event.cpp
+++ b/world/Event.cpp
@@ -1034,14 +1034,12 @@ whois_event::run_() {
m_activator->Mechanik != nullptr && m_activator->Mechanik->primary() ?
m_activator->Mechanik :
m_activator->ctOwner ) };
- auto const aheadname { (
+ auto const *entry { (
owner != nullptr ?
- owner->TrainTimetable().StationNameAhead( 1 ) :
- "none" ) };
- auto const aheadstop { (
- owner != nullptr && owner->TrainTimetable().StationIsStopAhead( 1 ) ?
- 1 :
- 0 ) };
+ &owner->TrainTimetable().TimeTableEntryAhead( 1 ) :
+ nullptr ) };
+ auto const aheadname { ( entry != nullptr ? entry->StationName : "none" ) };
+ auto const aheadstop { ( entry != nullptr && entry->Ah >= 0 ? 1 : 0 ) };
targetcell->UpdateValues(
aheadname, // station after the next one
diff --git a/world/mtable.cpp b/world/mtable.cpp
index 75e6c8ad0..dd84b6c23 100644
--- a/world/mtable.cpp
+++ b/world/mtable.cpp
@@ -77,20 +77,13 @@ bool TTrainParameters::IsLastStop() const {
return StationIndex >= StationCount;
}
-std::string TTrainParameters::StationNameAhead( int Offset ) const
-{ // nazwa wpisu rozkladu Offset pozycji za aktualnym (bez pomijania przelotow)
+TMTableLine const &TTrainParameters::TimeTableEntryAhead( int Offset ) const
+{ // wpis rozkladu Offset pozycji za aktualnym (bez pomijania przelotow);
+ // poza zakresem 1..StationCount zwraca techniczny wpis zerowy
int const idx { StationIndex + Offset };
if( ( idx < 1 ) || ( idx > StationCount ) )
- return "none";
- return TimeTable[idx].StationName;
-}
-
-bool TTrainParameters::StationIsStopAhead( int Offset ) const
-{ // czy wpis Offset pozycji za aktualnym to zaplanowany postoj
- int const idx { StationIndex + Offset };
- if( ( idx < 1 ) || ( idx > StationCount ) )
- return false;
- return TimeTable[idx].Ah >= 0; //-1 to brak postoju
+ return TimeTable[0];
+ return TimeTable[idx];
}
diff --git a/world/mtable.h b/world/mtable.h
index 701b0c6ca..2d20a27bb 100644
--- a/world/mtable.h
+++ b/world/mtable.h
@@ -70,10 +70,9 @@ class TTrainParameters
std::string ShowRelation() const;
double WatchMTable(double DistCounter);
std::string NextStop() const;
- // nazwa wpisu rozkladu Offset pozycji za StationIndex (Offset>=1); "none" poza koncem rozkladu
- std::string StationNameAhead( int Offset ) const;
- // true, gdy ten wpis to zaplanowany postoj (ma godzine przyjazdu), false dla przelotu / poza koncem
- bool StationIsStopAhead( int Offset ) const;
+ // wpis rozkladu Offset pozycji za StationIndex (Offset>=1); poza zakresem 1..StationCount
+ // zwraca techniczny wpis zerowy (TimeTable[0], StationName=="nowhere", Ah==-1)
+ TMTableLine const &TimeTableEntryAhead( int Offset ) const;
sound_source next_stop_sound() const;
sound_source last_stop_sound() const;
bool IsStop() const;
From 36d4f16c01abd9404c7e3b59547260f33191b0ba Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sun, 27 Sep 2026 17:50:07 +0200
Subject: [PATCH 04/60] Brake force table: take the rapid step threshold from
the distributor
TMoverParameters::BrakeForceR() halves the force of a vehicle set to R
below 40 km/h. That is one approximation for every distributor, but a
NESt3/ESt4 distributor with a rapid relay engages the step above 70 km/h
and keeps it down to 50 km/h (TNESt3::GetPF, RapidStatus), and below
that its cylinder pressure is divided by the relay's own multiplier
(TRapid, RapidMult). For a vehicle braking from speed the full force
therefore lasts down to 50 km/h, not 40. The AI builds its consist brake
table (fBrake_a0/a1) from BrakeForceR(), so between 40 and 50 km/h it
expected twice the force the wagons actually deliver.
Add TBrake::GetRapidRatio(), which keeps the old approximation as the
default, and override it in TNESt3 with the relay's threshold and
multiplier. The brake itself is unchanged; only the prediction is.
---
McZapkie/Mover.cpp | 4 ++--
McZapkie/Oerlikon_ESt.cpp | 11 +++++++++++
McZapkie/Oerlikon_ESt.h | 2 ++
McZapkie/hamulce.h | 5 +++++
4 files changed, 20 insertions(+), 2 deletions(-)
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 83c918e24..a58878ab4 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -5166,8 +5166,8 @@ double TMoverParameters::BrakeForceR(double ratio, double velocity)
press = MaxBrakePress[3];
if (DynamicBrakeType == dbrake_automatic)
ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02);
- if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1 && velocity < 40)
- ratio = ratio / 2;
+ if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1)
+ ratio *= Hamulec->GetRapidRatio(velocity);
if (TrainType == dt_DMU && velocity < 30.0)
{
ratio -= 0.3;
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index 9559d3052..d8d5b3da8 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -324,6 +324,17 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c
RapidStaly = false;
}
+double TNESt3::GetRapidRatio(double const Vel) const
+{
+ // ESt3 has no rapid relay, and with disc brakes the rapid step stays engaged at all speeds
+ if( ( PrzekRapid == nullptr ) || ( true == RapidStaly ) ) {
+ return 1.0;
+ }
+ // a braking vehicle comes from above, so the step is still engaged down to the speed
+ // at which GetPF() drops it, not the one at which it engages
+ return ( Vel < 50.0 ? 1.0 / PrzekRapid->GetRapidMult() : 1.0 );
+}
+
double TNESt3::GetCRP()
{
return CntrlRes->P();
diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h
index c12691851..180c47206 100644
--- a/McZapkie/Oerlikon_ESt.h
+++ b/McZapkie/Oerlikon_ESt.h
@@ -117,6 +117,7 @@ class TRapid : public TPrzekladnik {
public:
void SetRapidParams(double mult, double size);
void SetRapidStatus(bool rs);
+ double GetRapidMult() const { return RapidMult; }
void Update(double dt) /*override*/;
inline TRapid() :
TPrzekladnik()
@@ -213,6 +214,7 @@ class TNESt3 : public TBrake {
virtual double GetPF( double const PP, double const dt, double const Vel ) /*override*/; // przeplyw miedzy komora wstepna i PG
void EStParams(double i_crc); // parametry charakterystyczne dla ESt
virtual double GetCRP() /*override*/;
+ double GetRapidRatio(double const Vel) const override;
void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy
void CheckReleaser(double const dt); // odluzniacz
double CVs(double const BP); // napelniacz sterujacego
diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h
index a05a36359..11b8bdfb3 100644
--- a/McZapkie/hamulce.h
+++ b/McZapkie/hamulce.h
@@ -442,6 +442,11 @@ class TBrake
/// Sets the rapid step ratio. Default no-op; overridden where supported.
/// Rapid ratio.
virtual void SetRM(double const RMR) {}; // ustalenie przelozenia rapida
+ /// Share of the full cylinder pressure the distributor delivers at the given speed
+ /// while the vehicle is slowing down through it, for a vehicle set to R. Used only to predict
+ /// the brake force; the default is the approximation BrakeForceR() has always used.
+ /// Vehicle velocity [km/h].
+ virtual double GetRapidRatio(double const Vel) const { return Vel < 40.0 ? 0.5 : 1.0; }
/// Sets the velocity threshold for the rapid step.
/// Velocity threshold (same unit as Vel passed to GetPF).
virtual void SetRV(double const RVR)
From 92bd7ef827196e0ae7f3dfa6e5cbabf93eb87390 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 28 Sep 2026 15:45:10 +0200
Subject: [PATCH 05/60] AI braking: hold the speed on a descent
Two changes that only work together: the first on its own lets a heavy
freight train brake less on a descent than it needs (in testing an
ET42 with 30 loaded wagons overran the stop signal by 16-48 m at 20 per
mille), the second makes the hold on a descent what it should be.
The comparison that decides whether the AI may skip its reaction time
between two brake steps stays on the brake-only demand, as before: it
is about how much brake is asked for, and a heavy train in G approaching
a stop on a descent needs its brake built up at once. Compared in the
resultant frame, that train built up its brake one step per reaction
time and overran the signal (16 copies of the ET42 train, x20:
22 of 32 overruns with the comparison moved, 0 of 48 with it kept).
1. Compare the measured deceleration in the same frame.
Going downhill, adjust_desired_speed_for_current_speed() subtracts the
gravity component from AccDesired, so that IncBrake() sizes the handle
position for what the brake alone has to deliver. control_braking_force()
then compares that brake-only value with AbsAccS, which is the resultant
acceleration and already contains the gravity. On a 20 per mille descent
the two differ by about 0.2 m/s2, so the AI asked for more braking than
the target needed and then released, and repeated that.
Keep the subtracted part in fAccDesiredGravity and add it back wherever
AccDesired is compared with AbsAccS. It is zero everywhere else (flat,
uphill, braking test), so the behaviour there does not change.
2. Hold the speed with one continuous law.
On a descent the AI looks ahead to decide whether it will exceed the
target speed. The look-ahead was (1 - a0) * 30 / 3.6 s, a few seconds,
while a pneumatic brake in G takes tens of seconds to apply or to
release; the AI therefore acted on an estimate the train had already
left behind. The demand then jumped between the braking threshold above
the target and a lerp towards full acceleration below it, and with the
brake that slow this turned into long alternating applications and
releases.
- look ahead for half the brake application time while the train is
speeding up and half the release time while it is slowing down
(brake_response_horizon), never less than before;
- use one law on both sides of the target, proportional to the
predicted difference, and hold a band just below the limit that widens
with the gradient (pneumatic up to 3 km/h, EP/electric up to 1.5 km/h);
- once below a lower limit ahead, hold that limit instead of speeding up
towards the line speed and braking again.
---
vehicle/Driver.cpp | 101 ++++++++++++++++++++++++++++++++++-----------
vehicle/Driver.h | 1 +
2 files changed, 77 insertions(+), 25 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 9a6de8596..5b61b6dd1 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -7483,6 +7483,25 @@ TController::adjust_desired_speed_for_limits() {
}
}
+// how long the present acceleration of a consist lasts whatever is done with the handle now: half the time
+// its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G
+// is tens of seconds; never shorter than the look-ahead the AI has always used
+static double
+brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) {
+
+ auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 };
+ if( Brakesystem == TBrakeSystem::Pneumatic ) {
+ auto const isrelease { Acceleration < 0.0 };
+ horizon = std::max(
+ horizon,
+ 0.5 * (
+ Vehicle->BrakeDelayFlag > bdelay_G ?
+ Vehicle->BrakeDelay[ isrelease ? 0 : 1 ] :
+ Vehicle->BrakeDelay[ isrelease ? 2 : 3 ] ) );
+ }
+ return horizon;
+}
+
void
TController::adjust_desired_speed_for_target_speed( double const Range ) {
// ustalanie zadanego przyspieszenia
@@ -7496,6 +7515,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
// gdy jedzie wolniej niż potrzeba, albo nie ma przeszkód na drodze
// normalna jazda
AccDesired = VelDesired != 0.0 ? AccPreferred : -0.01;
+ fAccDesiredGravity = 0.0;
auto const vel { DirectionalVel() };
@@ -7654,35 +7674,57 @@ TController::adjust_desired_speed_for_current_speed() {
if( fAccGravity > 0.025 ) {
// going sharply downhill we may need to start braking sooner than usual
// try to estimate increase of current velocity before engaged brakes start working
- auto const speedestimate = vel + ( 1.0 - fBrake_a0[ 0 ] ) * 30.0 * AbsAccS;
- if( speedestimate > VelDesired ) {
- // jesli jedzie za szybko do AKTUALNEGO
- if( VelDesired == 0.0 ) {
- // jesli stoj, to hamuj, ale i tak juz za pozno :)
- AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie
- }
- else {
- // if it looks like we'll exceed maximum speed start thinking about slight slowing down
- AccDesired = std::min( AccDesired, -0.05 + fAccThreshold );
- // HACK: for cargo trains with high braking threshold ensure we cross that threshold
- if( true == IsCargoTrain
- && fBrake_a0[0] > 0.2 ) {
- AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 );
- }
- }
+ // look ahead for as long as the brake takes to respond, since that is how long the
+ // present acceleration will last whatever is done with the handle now; a pneumatic
+ // brake applies and releases on its own time scale, which in G is tens of seconds
+ auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) };
+ auto const speedestimate = vel + 3.6 * horizon * AbsAccS;
+ // already below a lower limit ahead, the train has no business speeding up towards it
+ auto holdlimit { VelDesired };
+ if( ( VelNext > 0.0 )
+ && ( VelNext < holdlimit )
+ && ( vel <= VelNext + fVelPlus )
+ && ( ActualProximityDist < std::max( 2.0 * fBrakeDist, 500.0 ) ) ) {
+ holdlimit = VelNext;
+ }
+ // hold a band just below the limit; the steeper the descent the harder the train pulls
+ // away once the brake eases, so the band widens with the gradient (about 3 km/h at 20 per mille)
+ // an electro-pneumatic or electric brake responds at once and needs far less room
+ auto const holdspeed { holdlimit - (
+ BrakeSystem == TBrakeSystem::Pneumatic ?
+ std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) :
+ std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) };
+ if( ( speedestimate > VelDesired )
+ && ( VelDesired == 0.0 ) ) {
+ // jesli stoj, to hamuj, ale i tak juz za pozno :)
+ AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie
}
else {
- // stop accelerating when close enough to target speed
+ // one continuous law on both sides of the target, proportional to the predicted
+ // difference: a demand that jumps to the braking threshold above the target and to
+ // full acceleration below it alternates, with a brake that responds in seconds,
+ // between a hard application and a full release
AccDesired = std::min(
AccDesired, // but don't override decceleration for VelNext
- std::lerp( // ease off as you close to the target velocity
- EU07_AI_NOACCELERATION, AccPreferred,
- std::clamp( VelDesired - speedestimate, 0.0, fVelMinus ) / fVelMinus ) );
+ std::clamp(
+ EU07_AI_NOACCELERATION - 0.04 * ( speedestimate - holdspeed ),
+ -0.05 + fAccThreshold,
+ std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) );
+ // HACK: for cargo trains with high braking threshold ensure we cross that threshold
+ if( true == IsCargoTrain
+ && fBrake_a0[0] > 0.2
+ && speedestimate > holdlimit ) {
+ AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 );
+ }
}
// final tweaks
if( vel > EU07_AI_NOMOVEMENT ) {
// going downhill also take into account impact of gravity
AccDesired -= fAccGravity;
+ // from here on AccDesired is what the brake alone has to deliver, which is what
+ // IncBrake() sizes the handle position for; AbsAccS already contains the gravity,
+ // so the comparisons with it have to add this part back
+ fAccDesiredGravity = fAccGravity;
// HACK: if the max allowed speed was exceeded something went wrong; brake harder
AccDesired -= 0.15 * std::clamp( vel - VelDesired, 0.0, 5.0 );
}
@@ -7773,6 +7815,7 @@ TController::adjust_desired_speed_for_braking_test() {
}
case 1: {
AccDesired = EU07_AI_BRAKINGTESTACCELERATION;
+ fAccDesiredGravity = 0.0;
VelDesired = DBT_VelocityBrake;
if( ElapsedTime - DBT_BrakingTime > 1 ) {
ForcePNBrake = true;
@@ -7783,6 +7826,7 @@ TController::adjust_desired_speed_for_braking_test() {
}
case 2: {
AccDesired = EU07_AI_BRAKINGTESTACCELERATION;
+ fAccDesiredGravity = 0.0;
VelDesired = DBT_VelocityBrake;
if( ElapsedTime - DBT_BrakingTime > 2 ) {
DBT_BrakingTime = ElapsedTime;
@@ -7794,6 +7838,7 @@ TController::adjust_desired_speed_for_braking_test() {
}
case 3: {
AccDesired = safe_clamp( -AbsAccS, fAccThreshold * 1.01, fAccThreshold * 1.21 );
+ fAccDesiredGravity = 0.0;
VelDesired = DBT_VelocityBrake;
if( vel <= DBT_VelocityRelease ) {
DynamicBrakeTest = 4;
@@ -7980,6 +8025,10 @@ void TController::control_braking_force() {
}
}
+ // AbsAccS is the resultant acceleration, gravity included, so it is compared with the
+ // resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent
+ auto const accdesiredresultant { AccDesired + fAccDesiredGravity };
+
if( is_emu() && !ForcePNBrake ) {
// właściwie, to warunek powinien być na działający EP
// Ra: to dobrze hamuje EP w EZT
@@ -7991,13 +8040,13 @@ void TController::control_braking_force() {
auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ?
0.05 : 0.0;
if( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold
- && ( AbsAccS > AccDesired + accmargin
+ && ( AbsAccS > accdesiredresultant + accmargin
|| BrakeCtrlPosition < 0 ) ) {
// hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired)
cue_action( driver_hint::brakingforceincrease );
}
else if( OrderCurrentGet() != Disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca
- if( AbsAccS < AccDesired - 0.05 ) {
+ if( AbsAccS < accdesiredresultant - 0.05 ) {
// jeśli opóźnienie większe od wymaganego (z histerezą) luzowanie, gdy za dużo
// TBD: check if the condition isn't redundant with the DecBrake() code
if( BrakeCtrlPosition >= 0 ) {
@@ -8013,10 +8062,12 @@ void TController::control_braking_force() {
} // type & dt_ezt
else {
// a stara wersja w miarę dobrze działa na składy wagonowe
- if( ( AccDesired < fAccGravity - 0.1 && AbsAccS > AccDesired + fBrake_a1[0] ) // regular braking
+ if( ( accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + fBrake_a1[0] ) // regular braking
|| ( fAccGravity < -0.05 && velocity < -0.1 ) ) { // also brake if uphill and slipping back
// u góry ustawia się hamowanie na fAccThreshold
if( fBrakeTime < 0.0
+ // the size of the brake demand decides whether to skip the reaction time, so the brake-only part
+ // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow)
|| AccDesired < fAccGravity - 0.5
|| BrakeCtrlPosition <= 0 ) {
// jeśli upłynął czas reakcji hamulca, chyba że nagłe albo luzował
@@ -8033,8 +8084,8 @@ void TController::control_braking_force() {
* 0.5 ); // Ra: tymczasowo, bo przeżyna S1
}
}
- if ( AccDesired < fAccGravity - 0.05
- && AccDesired - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 ) {
+ if ( accdesiredresultant < fAccGravity - 0.05
+ && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 ) {
// jak hamuje, to nie tykaj kranu za często
// yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2
if( OrderCurrentGet() != Disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index e7c4fac00..c493afc8a 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -387,6 +387,7 @@ private:
double AccDesired = 0.0; // przyspieszenie, jakie ma utrzymywać (<0:nie przyspieszaj,<-0.1:hamuj)
double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal
double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie
+ double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam
double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?)
double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie
double VelLimit = -1.0; // predkość zadawana przez event jednokierunkowego ograniczenia prędkości // -1: brak ograniczenia prędkości
From ce87aa0e090d4b5fba7042588df6e5e71895d5a1 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 28 Sep 2026 15:45:10 +0200
Subject: [PATCH 06/60] AI braking: plan approaches from the consist brake,
stop 8-15 m short
The new braking curve below plans the stop at the signal itself unless
the stopping point moves with it (in testing, trains stopped 0-3 m past
the signal), so both go in one change.
1. The braking curve.
The braking curve towards a lower speed or a stop assumed a constant
deceleration from the present speed over the whole distance. A pneumatic
brake does not work like that:
- it acts on the state the train is in once it has applied; while the
train is still speeding up (downhill), plan from the speed it will have
reached by then, over the distance left by then;
- cast iron blocks grip harder as the train slows, so a constant
deceleration plan asks for too much at the start and then releases;
follow the shape of the consist brake table (fBrake_a0/a1) over speed
instead (shaped_braking_demand), over the distance left once the brake
has had its fill time;
- no power while the train is still above the speed it is braking for.
IncBrake() only adds braking when the brake table says the present
position is not enough. When the table overestimates the consist (see
the previous rapid step fix, or a descent), the train keeps slowing too
little with the handle held. After the full fill time with the handle
unchanged, believe the train rather than the table (fBrakeHeldTime).
When the AI asks for no braking and the train is still slowing down more
than that, release. With the gentler plan above the demand eases off
early, and without this a heavy freight train in G came to a stand a few
hundred metres before a W4 with its brake still on (seen in testing).
2. The stopping window.
In train running the final approach to a stop signal began at
fMaxProximityDist (15-40 m, cargo 25-50 m), aimed at half of
fMinProximityDist (10-15 m, cargo 20-25 m), and set VelDesired = 0,
which asks for hard braking whatever the distance left. Where a train
came to a stand depended on how it entered that phase: on the test
sceneries anywhere from 1 to 45 m short of the signal on the flat and
25-42 m uphill for heavy freight.
For train running only (a W4 stop point, shunting and coupling keep the
old margins and the old final approach):
- stop 8-15 m short of the signal whatever the length of the train, aim
at the middle of that window (stopping_margin) both with the braking
curve and in the final approach, and ask there only for what the
distance left takes, following the consist brake table;
- start the final approach 50 m out (cargo 60 m) whether the train is
moving or standing; it used to be 15-40 m while moving and 50 m once
stopped, and with the gentler final approach above a train that came
to a stand between the two released to creep closer and, uphill,
rolled back and tried again;
- uphill, while the gradient alone would bring the train to a stand short
of the window, keep it rolling at no more than the speed the gradient
can take off by then, with power if needed;
- uphill, put the train brake on as the train comes to a stand, keep it
on while it stands, and apply it for real if the train rolls back. This
is done at the very end of pick_optimal_speed(): the adjustments made
before it assume a train moving forward and can raise the demand back
to "no braking" (with the rule placed earlier, EMUs rolled back up to
90 m in testing). The EMU branch of
control_braking_force() gets the "slipping back" condition the wagon
branch has always had.
3. Known limitation.
Heavy trains of wagons with the ESt3AL2 distributor (413S, 601W and
alike) respond more slowly than the AI expects: with the present brake
model the distributor fills the AL2 relay chamber, whose capacity is set
to 2 in TNESt3::SetSize (Przekladniki[i]->CreateCap(i)), through
orifices sized for about 1 l, so these wagons need 34 s to reach 95 %
cylinder pressure in G against 21 s for a plain ESt3. On a 20 per mille
descent an ET22 with 20 loaded 413S wagons overran the stop signal by up
to 6.5 m in 6 of 24 runs at x20 with this change. With the relay chamber
at 1 l and the release orifices at about 80 % of their diameter, as the
author of the brake model suggested, none of them did (0 of 16).
---
vehicle/Driver.cpp | 217 ++++++++++++++++++++++++++++++++++++++++-----
vehicle/Driver.h | 7 ++
2 files changed, 200 insertions(+), 24 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 5b61b6dd1..09b607b69 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -3122,6 +3122,17 @@ bool TController::IncBrake()
}
}
}
+ else if( BrakeCtrlPosition > 0.0
+ && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting
+ && fBrakeHeldTime > (
+ mvOccupied->BrakeDelayFlag > bdelay_G ?
+ mvOccupied->BrakeDelay[ 1 ] :
+ mvOccupied->BrakeDelay[ 3 ] ) ) {
+ // the table says the present position is enough, but the brake has had its full fill
+ // time since the handle last moved and the train is still not slowing down as asked:
+ // believe the train rather than the table
+ OK = BrakeLevelAdd( BrakingLevelIncrease );
+ }
else
OK = false;
}
@@ -3781,6 +3792,7 @@ void TController::BrakeLevelSet(double b)
if (BrakeCtrlPosition == b)
return; // nie przeliczać, jak nie ma zmiany
BrakeCtrlPosition = std::clamp(b, (double)gbh_MIN, (double)gbh_MAX);
+ fBrakeHeldTime = 0.0;
}
bool TController::BrakeLevelAdd(double b)
@@ -5911,6 +5923,7 @@ TController::update_timers( double dt ) {
ElapsedTime += dt;
WaitingTime += dt;
fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca
+ fBrakeHeldTime += dt;
if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_FS ) ) {
// brake charging timeout starts after charging ends
BrakeChargingCooldown += dt;
@@ -6659,12 +6672,27 @@ TController::determine_proximity_ranges() {
// na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody
// jeśli pociąg
if( is_train() ) {
- fMinProximityDist = std::clamp( 5 + iVehicles, 10, 15 );
- fMaxProximityDist = std::clamp( 10 + iVehicles, 15, 40 );
+ if( true == IsAtPassengerStop ) {
+ // a stop point keeps the margins its W4 parameters (head or middle of the consist,
+ // platform length) were set up against
+ fMinProximityDist = std::clamp( 5 + iVehicles, 10, 15 );
+ fMaxProximityDist = std::clamp( 10 + iVehicles, 15, 40 );
+ if( IsCargoTrain ) {
+ fMinProximityDist += 10.0;
+ }
+ }
+ else {
+ // a train stops 8-15 m short of the signal whatever its length; closer than the lower
+ // edge it stops at once, the braking aims at the middle of the window, 3.5 m further out
+ fMinProximityDist = 8.0;
+ // the final approach begins far enough out to slow from the coasting speed down to the window,
+ // and at the same distance whether the train is moving or standing, so it does not flip
+ // between creeping closer and holding still when it comes to a stand short of the window
+ fMaxProximityDist = 50.0;
+ }
if( IsCargoTrain ) {
- // increase distances for cargo trains to take into account slower reaction to brakes
- fMinProximityDist += 10.0;
+ // start the final approach earlier for cargo trains, their brakes react more slowly
fMaxProximityDist += 10.0;
/*
if( IsHeavyCargoTrain ) {
@@ -6683,7 +6711,7 @@ TController::determine_proximity_ranges() {
if( mvOccupied->Vel < 0.1 ) {
// jak stanie za daleko, to niech nie dociąga paru metrów
- fMaxProximityDist = 50.0;
+ fMaxProximityDist = std::max( fMaxProximityDist, 50.0 );
}
if( iDrivigFlags & moveLate ) {
@@ -7314,6 +7342,26 @@ TController::pick_optimal_speed( double const Range ) {
is_car() ? -2.0 : -0.9,
is_car() ? 2.0 : 0.9 );
+ if( ( true == is_train() )
+ && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( VelNext == 0.0 )
+ && ( ActualProximityDist <= fMaxProximityDist )
+ && ( fAccGravity < -0.025 ) ) {
+ // uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released
+ // brake applies; so the train brake goes on while the train is coming to a stand, stays on while it
+ // stands, and is applied for real if the train has started to roll back. done last, so that none of
+ // the adjustments above, made for a train moving forward, can undo it
+ auto const vel { DirectionalVel() };
+ if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) {
+ VelDesired = 0.0;
+ AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
+ }
+ else if( ( vel < 0.0 )
+ || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) ) ) {
+ AccDesired = std::min( AccDesired, fAccGravity - 0.15 );
+ }
+ }
+
// if the route ahead is blocked we might need to head the other way
check_route_behind( 1000 ); // NOTE: legacy scan range value
}
@@ -7502,6 +7550,55 @@ brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brak
return horizon;
}
+// distance [m] in which the gradient alone, with no brake and no power, brings a train rolling uphill at Velocity [km/h] to a stand
+static double
+uphill_stopping_distance( double const Velocity, double const Gravity ) {
+ return ( Velocity / 3.6 ) * ( Velocity / 3.6 ) / ( 2.0 * std::max( 0.01, -Gravity ) );
+}
+
+// speed [km/h] from which the gradient alone brings a train rolling uphill to a stand in Distance [m]
+static double
+uphill_coasting_speed( double const Distance, double const Gravity ) {
+ return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) );
+}
+
+// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train
+// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the
+// consist brake table says it does (cast iron blocks grip harder as the train slows)
+static double
+shaped_braking_demand(
+ double const Velocity, double const Target, double const Distance, double const Gravity,
+ double const Vmax, double const *Brakea0, double const *Brakea1, int const Tablesize ) {
+
+ auto const fullbraking = [&]( double const Kmh ) {
+ auto const index { std::clamp( static_cast( Tablesize * Kmh / std::max( 1.0, Vmax ) ), 1, Tablesize ) };
+ return std::max( 0.01, Brakea0[ index ] + 12.0 * Brakea1[ index ] ); };
+ auto const travel = [&]( double const Ratio ) {
+ auto const steps { 24 };
+ auto const step { ( Velocity - Target ) / steps };
+ auto distance { 0.0 };
+ for( auto i { 0 }; i < steps; ++i ) {
+ auto const kmh { Target + ( i + 0.5 ) * step };
+ auto const deceleration { Ratio * fullbraking( kmh ) - Gravity };
+ if( deceleration <= 0.001 ) {
+ return std::numeric_limits::max();
+ }
+ distance += ( kmh / 3.6 ) * ( step / 3.6 ) / deceleration;
+ }
+ return distance; };
+
+ auto low { 0.0 };
+ auto high { 3.0 };
+ if( travel( high ) > Distance ) {
+ return Gravity - high * fullbraking( Velocity );
+ }
+ for( auto i { 0 }; i < 30; ++i ) {
+ auto const middle { 0.5 * ( low + high ) };
+ ( travel( middle ) > Distance ? low : high ) = middle;
+ }
+ return Gravity - high * fullbraking( Velocity );
+}
+
void
TController::adjust_desired_speed_for_target_speed( double const Range ) {
// ustalanie zadanego przyspieszenia
@@ -7552,9 +7649,33 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
}
else {
// hamowanie tak, aby stanąć
- VelDesired = VelNext;
- AccDesired = ( VelNext * VelNext - vel * vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) );
- AccDesired = std::min( AccDesired, fAccThreshold );
+ if( ( OrderCurrentGet() & Obey_train ) == 0 ) {
+ VelDesired = VelNext;
+ AccDesired = ( VelNext * VelNext - vel * vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) );
+ AccDesired = std::min( AccDesired, fAccThreshold );
+ }
+ else {
+ // a train keeps its desired speed until the lower edge of the stopping window (a desired
+ // speed of 0 here asks for hard braking whatever the distance left), aims at the middle
+ // of the window, and asks only for what that takes
+ auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) };
+ AccDesired = (
+ BrakeSystem == TBrakeSystem::Pneumatic ?
+ // cast iron blocks grip harder as the train comes to a stand
+ shaped_braking_demand(
+ vel, VelNext, stoppingroom, fAccGravity,
+ mvOccupied->Vmax, fBrake_a0, fBrake_a1, BrakeAccTableSize ) :
+ ( VelNext * VelNext - vel * vel ) / ( 25.92 * stoppingroom ) );
+ if( ( fAccGravity < -0.025 )
+ && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all
+ && ( ActualProximityDist - uphill_stopping_distance( vel, fAccGravity ) > stopping_margin() ) ) {
+ // uphill the gradient alone would bring the train to a stand short of the
+ // middle of the stopping window; keep it rolling at the present speed until that changes,
+ // but no faster than the gradient alone can take off by the middle of the window
+ AccDesired = std::min( 0.0, AccPreferred );
+ VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) );
+ }
+ }
}
}
else {
@@ -7578,17 +7699,57 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
if( brakingdistance + std::max(slowdowndistance, fMaxProximityDist) >= ActualProximityDist - fMaxProximityDist ) {
// don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good
// ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever
- auto const brakingpointoffset = VelNext * braking_distance_multiplier( VelNext );
- AccDesired = std::min(
- AccDesired,
- ( VelNext * VelNext - vel * vel )
- / ( 25.92
- * std::max(
- ActualProximityDist - brakingpointoffset,
- std::min(
- ActualProximityDist,
- brakingpointoffset ) )
- + 0.1 ) ); // najpierw hamuje mocniej, potem zluzuje
+ auto const brakingpointoffset = (
+ ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ?
+ stopping_margin() : // the same stopping point as the final approach
+ VelNext * braking_distance_multiplier( VelNext ) );
+ // a pneumatic brake acts on the state the train will be in once it has responded; while the
+ // train is still speeding up, plan the deceleration from there, so more is asked for at once
+ auto velocity { vel };
+ auto distance { ActualProximityDist };
+ if( ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( AbsAccS > 0.0 ) ) {
+ auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) };
+ velocity = vel + 3.6 * horizon * AbsAccS;
+ distance = std::max( 0.5 * ActualProximityDist, ActualProximityDist - ( vel + velocity ) * 0.5 / 3.6 * horizon );
+ }
+ auto const brakingroom {
+ std::max(
+ distance - brakingpointoffset,
+ std::min(
+ distance,
+ brakingpointoffset ) ) };
+ auto deceleration { ( VelNext * VelNext - velocity * velocity ) / ( 25.92 * brakingroom + 0.1 ) };
+ if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( velocity > VelNext ) ) {
+ // follow the shape of the consist brake force over speed rather than assume a constant
+ // deceleration, over the distance left once the brake has had time to fill (while the
+ // train is still speeding up, the prediction above has taken that off already)
+ auto room { brakingroom };
+ if( ( AbsAccS <= 0.0 )
+ && ( ( VelNext > 0.0 ) || ( BrakeCtrlPosition <= 0.0 ) ) ) { // for a stop, only while the brake is still to be applied
+ room = std::max(
+ 0.5 * brakingroom,
+ brakingroom - vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) );
+ }
+ deceleration = shaped_braking_demand(
+ velocity, VelNext, room + 0.1 / 25.92, fAccGravity,
+ mvOccupied->Vmax, fBrake_a0, fBrake_a1, BrakeAccTableSize );
+ }
+ AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje
+ if( vel > VelNext ) {
+ if( deceleration < fAccGravity - 0.001 ) {
+ // no power while still above the speed being braked for
+ AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
+ }
+ else if( ( fAccGravity < -0.025 )
+ && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( ActualProximityDist - uphill_stopping_distance( vel, fAccGravity ) > brakingpointoffset ) ) {
+ // uphill the gradient alone slows the train down more than it is asked to;
+ // keep it rolling at the present speed until that changes
+ AccDesired = std::min( 0.0, AccPreferred );
+ VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) );
+ }
+ }
}
}
}
@@ -7959,7 +8120,13 @@ void TController::control_tractive_force() {
if( ActualProximityDist > (is_car() ? fMinProximityDist : // cars are allowed to move within min proximity distance
fMaxProximityDist) ? // other vehicle types keep wider margin
true :
- velocity + 1.0 < VelNext ) {
+ ( velocity + 1.0 < VelNext )
+ // uphill, a train told to hold its speed on the way to a stop needs the power to do it
+ || ( ( VelNext == 0.0 )
+ && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( AccDesired >= 0.0 )
+ && ( fAccGravity < -0.025 )
+ && ( ActualProximityDist > fMinProximityDist ) ) ) {
// ...to można przyspieszyć
increase_tractive_force();
}
@@ -8039,9 +8206,10 @@ void TController::control_braking_force() {
auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], mvOccupied->MED_amax) };
auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ?
0.05 : 0.0;
- if( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold
- && ( AbsAccS > accdesiredresultant + accmargin
- || BrakeCtrlPosition < 0 ) ) {
+ if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold
+ && ( AbsAccS > accdesiredresultant + accmargin
+ || BrakeCtrlPosition < 0 ) )
+ || ( fAccGravity < -0.05 && velocity < -0.1 && AccDesired < 0.0 ) ) { // also brake if uphill and slipping back
// hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired)
cue_action( driver_hint::brakingforceincrease );
}
@@ -8084,7 +8252,8 @@ void TController::control_braking_force() {
* 0.5 ); // Ra: tymczasowo, bo przeżyna S1
}
}
- if ( accdesiredresultant < fAccGravity - 0.05
+ if ( ( accdesiredresultant < fAccGravity - 0.05
+ || AccDesired >= EU07_AI_NOACCELERATION ) // no braking asked for, yet the train is slowing down more than that
&& accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 ) {
// jak hamuje, to nie tykaj kranu za często
// yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index c493afc8a..0e65a4b94 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -353,6 +353,12 @@ private:
void control_tractive_force();
void increase_tractive_force();
void control_braking_force();
+ // how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal,
+ // otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before
+ double stopping_margin() const {
+ return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && ( false == IsAtPassengerStop ) ?
+ fMinProximityDist + 3.5 :
+ 0.5 * fMinProximityDist; }
void apply_independent_brake_only();
void check_route_ahead( double const Range );
void check_route_behind( double const Range );
@@ -387,6 +393,7 @@ private:
double AccDesired = 0.0; // przyspieszenie, jakie ma utrzymywać (<0:nie przyspieszaj,<-0.1:hamuj)
double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal
double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie
+ double fBrakeHeldTime = 0.0; // czas od ostatniego przestawienia kranu hamulca zasadniczego
double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam
double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?)
double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie
From 4f2dfd93186f218f20c499ef20572b9fa5b30b83 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Tue, 29 Sep 2026 09:47:51 +0200
Subject: [PATCH 07/60] Drop redundant comparisons with true/false
In the conditions this PR adds; no change in behaviour.
---
McZapkie/Oerlikon_ESt.cpp | 2 +-
vehicle/Driver.cpp | 6 +++---
vehicle/Driver.h | 2 +-
3 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index d8d5b3da8..8705000a4 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -327,7 +327,7 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c
double TNESt3::GetRapidRatio(double const Vel) const
{
// ESt3 has no rapid relay, and with disc brakes the rapid step stays engaged at all speeds
- if( ( PrzekRapid == nullptr ) || ( true == RapidStaly ) ) {
+ if( ( PrzekRapid == nullptr ) || RapidStaly ) {
return 1.0;
}
// a braking vehicle comes from above, so the step is still engaged down to the speed
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 09b607b69..d75500dbe 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -6672,7 +6672,7 @@ TController::determine_proximity_ranges() {
// na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody
// jeśli pociąg
if( is_train() ) {
- if( true == IsAtPassengerStop ) {
+ if( IsAtPassengerStop ) {
// a stop point keeps the margins its W4 parameters (head or middle of the consist,
// platform length) were set up against
fMinProximityDist = std::clamp( 5 + iVehicles, 10, 15 );
@@ -7342,7 +7342,7 @@ TController::pick_optimal_speed( double const Range ) {
is_car() ? -2.0 : -0.9,
is_car() ? 2.0 : 0.9 );
- if( ( true == is_train() )
+ if( is_train()
&& ( ( OrderCurrentGet() & Obey_train ) != 0 )
&& ( VelNext == 0.0 )
&& ( ActualProximityDist <= fMaxProximityDist )
@@ -7872,7 +7872,7 @@ TController::adjust_desired_speed_for_current_speed() {
-0.05 + fAccThreshold,
std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) );
// HACK: for cargo trains with high braking threshold ensure we cross that threshold
- if( true == IsCargoTrain
+ if( IsCargoTrain
&& fBrake_a0[0] > 0.2
&& speedestimate > holdlimit ) {
AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 );
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 0e65a4b94..fefa950ca 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -356,7 +356,7 @@ private:
// how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal,
// otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before
double stopping_margin() const {
- return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && ( false == IsAtPassengerStop ) ?
+ return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && !IsAtPassengerStop ?
fMinProximityDist + 3.5 :
0.5 * fMinProximityDist; }
void apply_independent_brake_only();
From 504d69b26a1be53aa4e6121685eda395ff10e47c Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 10 Oct 2026 23:39:19 +0200
Subject: [PATCH 08/60] AI braking: keep braking for a lower speed inside the
proximity range
Inside the proximity range only a stop had a final approach of its own;
for a lower speed ahead that branch set nothing, so AccDesired stayed at
the preferred acceleration. With the range at 50 m, which this PR uses so
that trains stop 8-15 m short of a signal, the AI stopped braking within
the last 50 m before a speed restriction and even took power: EMUs reached
a 20 km/h restriction at 25 km/h. On master the range is 15-40 m, which
kept this mostly out of sight.
A lower speed ahead now keeps the braking curve right up to where it
begins. Stops are unchanged.
Measured in real time on current master (with #199), with a 20 km/h
restriction one coach long, two runs of 32 consists each: over 22 km/h in
the restriction on the flat 9 on master, 15 before this change, 1 after
(a 36WEa at 22.1 km/h); on the 20 per mille descent 15, 0 and 0. Stops
8-15 m short of the signal stay as they were (flat 57 and 55 of 64,
descent 44 and 42), no overruns.
---
vehicle/Driver.cpp | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index c0e78b7cd..a5272b392 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -7518,7 +7518,10 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
}
else if (ActualProximityDist > fMinProximityDist) {
// jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko
- if (ActualProximityDist < fMaxProximityDist) {
+ // only a stop has a final approach of its own inside the proximity range; a lower speed ahead
+ // keeps the braking curve below right up to where it begins, or the train would stop braking
+ // (and even take power) that far out
+ if( ( VelNext == 0.0 ) && ( ActualProximityDist < fMaxProximityDist ) ) {
// jak minął już maksymalny dystans po prostu hamuj (niski stopień)
// ma stanąć, a jest w drodze hamowania albo ma jechać
/*
From 86069c5eaba8700ff7f8b38bf4ee562421e85889 Mon Sep 17 00:00:00 2001
From: Sebastian Krzyszkowiak
Date: Tue, 7 Jul 2026 01:45:05 +0200
Subject: [PATCH 09/60] utilities: XYZtoRGB: Use sRGB colorspace
It used Adobe RGB matrix depite of nothing else using Adobe RGB in
the pipeline.
---
utilities/color.h | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/utilities/color.h b/utilities/color.h
index be853a3d4..bbf17e096 100644
--- a/utilities/color.h
+++ b/utilities/color.h
@@ -15,9 +15,9 @@ glm::vec3
XYZtoRGB( glm::vec3 const &XYZ ) {
// M^-1 for Adobe RGB from http://www.brucelindbloom.com/Eqn_RGB_XYZ_Matrix.html
- float const mi[ 3 ][ 3 ] = { 2.041369f, -0.969266f, 0.0134474f, -0.5649464f, 1.8760108f, -0.1183897f, -0.3446944f, 0.041556f, 1.0154096f };
+// float const mi[ 3 ][ 3 ] = { 2.041369f, -0.969266f, 0.0134474f, -0.5649464f, 1.8760108f, -0.1183897f, -0.3446944f, 0.041556f, 1.0154096f };
// m^-1 for sRGB:
-// float const mi[ 3 ][ 3 ] = { 3.240479f, -0.969256f, 0.055648f, -1.53715f, 1.875991f, -0.204043f, -0.49853f, 0.041556f, 1.057311f };
+ float const mi[ 3 ][ 3 ] = { 3.240479f, -0.969256f, 0.055648f, -1.53715f, 1.875991f, -0.204043f, -0.49853f, 0.041556f, 1.057311f };
return glm::vec3{
XYZ.x*mi[ 0 ][ 0 ] + XYZ.y*mi[ 1 ][ 0 ] + XYZ.z*mi[ 2 ][ 0 ],
From 842b768803c0499048360680ae5f6d6437c98609 Mon Sep 17 00:00:00 2001
From: Sebastian Krzyszkowiak
Date: Tue, 7 Jul 2026 01:45:59 +0200
Subject: [PATCH 10/60] simulationenvironment: Adjust turbidity values
Turbidity 3 breaks the model at night. Adjust the values to have them
work well all the time and to maximize variation between cloud states.
---
simulation/simulationenvironment.cpp | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp
index 14ad2353c..0c1ec44b4 100644
--- a/simulation/simulationenvironment.cpp
+++ b/simulation/simulationenvironment.cpp
@@ -68,15 +68,15 @@ world_environment::compute_weather() const {
Global.AirTemperature > 1 ? "rain:" :
"snow:";
- Global.fTurbidity = Global.Overcast <= 0.10 ? 3 :
+ Global.fTurbidity = Global.Overcast <= 0.10 ? 4 :
Global.Overcast <= 0.20 ? 4 :
Global.Overcast <= 0.30 ? 5 :
Global.Overcast <= 0.40 ? 5 :
- Global.Overcast <= 0.50 ? 5 :
- Global.Overcast <= 0.60 ? 5 :
- Global.Overcast <= 0.70 ? 6 :
- Global.Overcast <= 0.80 ? 7 :
- Global.Overcast <= 0.90 ? 8 :
+ Global.Overcast <= 0.50 ? 6 :
+ Global.Overcast <= 0.60 ? 6 :
+ Global.Overcast <= 0.70 ? 7 :
+ Global.Overcast <= 0.80 ? 8 :
+ Global.Overcast <= 0.90 ? 9 :
9;
}
From ba405858e16a88ec5c0c9acb4dc0086dad13bfdd Mon Sep 17 00:00:00 2001
From: Sebastian Krzyszkowiak
Date: Tue, 27 Oct 2026 01:00:52 +0100
Subject: [PATCH 11/60] opengl33renderer: Fix up the sizes of Sun and Moon
Although the used value makes some physical sense, it fails to take
FoV effect into account, leading to both Sun and Moon becoming
comically tiny. Revert the sizes to the ones used by the legacy
renderer, which makes them appear much more plausible.
---
rendering/opengl33renderer.cpp | 11 +++++------
1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp
index d20454c35..9d4318981 100644
--- a/rendering/opengl33renderer.cpp
+++ b/rendering/opengl33renderer.cpp
@@ -2028,12 +2028,12 @@ bool opengl33_renderer::Render(world_environment *Environment)
glm::vec4 color(suncolor.x, suncolor.y, suncolor.z, std::clamp(1.5f - Global.Overcast, 0.f, 1.f) * fogfactor);
auto const sunvector = Environment->m_sun.getDirection();
- /*float const size = std::lerp( // TODO: expose distance/scale factor from the moon object
+ float const size = std::lerp( // TODO: expose distance/scale factor from the moon object
0.0325f,
0.0275f,
- std::clamp( Environment->m_sun.getAngle(), 0.f, 90.f ) / 90.f );*/
+ std::clamp( Environment->m_sun.getAngle(), 0.f, 90.f ) / 90.f );
model_ubs.param[0] = color;
- model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(sunvector, 1.0f)), 0.00463f /* size */);
+ model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(sunvector, 1.0f)), size);
model_ubs.param[2] = glm::vec4(0.0f, 1.0f, 1.0f, 0.0f);
model_ubo->update(model_ubs);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
@@ -2104,14 +2104,13 @@ bool opengl33_renderer::Render(world_environment *Environment)
moonu = 0.0f;
}
- /*
float const size = std::lerp( // TODO: expose distance/scale factor from the moon object
0.0160f,
0.0135f,
- std::clamp( Environment->m_moon.getAngle(), 0.f, 90.f ) / 90.f );*/
+ std::clamp( Environment->m_moon.getAngle(), 0.f, 90.f ) / 90.f );
model_ubs.param[0] = color;
- model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(moonvector, 1.0f)), 0.00451f /* size */);
+ model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(moonvector, 1.0f)), size);
model_ubs.param[2] = glm::vec4(moonu, moonv, 0.333f, 0.0f);
model_ubo->update(model_ubs);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
From 6b82f1471aaf38b7417f28c018aa3e1e958416fc Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 2 Nov 2026 12:36:11 +0100
Subject: [PATCH 12/60] AI braking: take power off when holding the speed
uphill near a stop
Within fMaxProximityDist of a stop, going uphill, the AI holds its speed
with AccDesired = min(0, AccPreferred). control_tractive_force only cut
the power uphill when AccDesired < 0, so an AccDesired of exactly 0 kept
the controller where it was. A consist that came into that range under
power kept full power and crept up to the signal.
Holding the speed uphill on the way to a stop now asks for no speeding
up: power comes off once the train is faster than AccDesired allows.
With the current brake valves this rarely shows: on a 10 per mille climb,
four real-time runs of 32 consists each, the E186 with 25 empty 408W drew
power in 0-14 samples of the last 50 m before and 0-8 after, no overruns
either way. It surfaced once the AI predicted the ESt3 brake closer to
what the valve delivers, where the same train crept to 12 km/h from 40 m
out and overran the signal; with this change it stopped short in all runs.
---
vehicle/Driver.cpp | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 2c59ddcda..436cdb7f6 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -8099,7 +8099,9 @@ void TController::control_tractive_force() {
}
else if( velocity > VelDesired + SpeedCtrlMargin
|| ( fAccGravity < -0.01 ?
- AccDesired < 0.0 :
+ AccDesired < 0.0
+ // holding the speed uphill on the way to a stop asks for no speeding up
+ || ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 ) :
AbsAccS > AccDesired + 10.05 )
|| IsAnyCouplerStretched ) {
// jak za bardzo przyspiesza albo prędkość przekroczona
From 1f3cf4fe56ee33fe38accd7903eaee401cd2d2a7 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 2 Nov 2026 16:02:06 +0100
Subject: [PATCH 13/60] AI braking: don't let the running brake test override a
stop ahead
adjust_desired_speed_for_braking_test runs after the target speed was
worked out and overwrites AccDesired. In its third phase it holds the
deceleration near fAccThreshold until the speed has dropped by 8 km/h.
On a 20 per mille descent that application barely holds the speed, so
the phase can last minutes, and a stop signal coming up meanwhile is
ignored. In one real-time run an E186 with 19 container wagons started
the test 1290 m before a stop signal, lost 7 km/h by the signal and
overran it by 274 m after the emergency application.
While the test runs the AI now uses whichever of the two asks for the
harder braking: the test may brake harder than the route needs, never
softer.
Measured in real time, four runs of 32 consists each on a 20 per mille
descent, on the flat and on the descent with half the rail adhesion:
the test no longer runs within 600 m of a stop signal (before: down to
414 m on this branch, and 14 m with the overrun above in a build with
other brake changes), no overruns, stops 8-15 m short of the signal 86,
117 and 83 of 128 (before 90, 117 and 78).
---
vehicle/Driver.cpp | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 436cdb7f6..6d6c1532e 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -7927,6 +7927,10 @@ TController::adjust_desired_speed_for_braking_test() {
if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well?
auto const vel { DirectionalVel() };
+ // what the route ahead asks for; the test may brake harder than that, never softer
+ auto const routeaccdesired { AccDesired };
+ auto const routeaccdesiredgravity { fAccDesiredGravity };
+ auto const routeveldesired { VelDesired };
switch( DynamicBrakeTest ) {
case 0: {
@@ -7993,6 +7997,14 @@ TController::adjust_desired_speed_for_braking_test() {
break;
}
}
+ // a stop or a restriction coming up while the test runs takes precedence
+ if( ( DynamicBrakeTest >= 1 )
+ && ( DynamicBrakeTest <= 3 )
+ && ( routeaccdesired < AccDesired ) ) {
+ AccDesired = routeaccdesired;
+ fAccDesiredGravity = routeaccdesiredgravity;
+ VelDesired = std::min( VelDesired, routeveldesired );
+ }
}
void
From 18bc7e06bfe58a4efff593dc3245a27289605ed3 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 2 Nov 2026 16:43:16 +0100
Subject: [PATCH 14/60] AI braking: move the uphill power-off check into its
own function
The condition added for holding the speed uphill near a stop pushed the
cognitive complexity of control_tractive_force() to 26, over the 25
SonarCloud allows. It now lives in is_too_fast_uphill(); the behaviour
is unchanged.
---
vehicle/Driver.cpp | 13 ++++++++-----
vehicle/Driver.h | 1 +
2 files changed, 9 insertions(+), 5 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 6d6c1532e..2311ffacf 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -8110,11 +8110,7 @@ void TController::control_tractive_force() {
cue_action( driver_hint::mastercontrollersetzerospeed );
}
else if( velocity > VelDesired + SpeedCtrlMargin
- || ( fAccGravity < -0.01 ?
- AccDesired < 0.0
- // holding the speed uphill on the way to a stop asks for no speeding up
- || ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 ) :
- AbsAccS > AccDesired + 10.05 )
+ || ( fAccGravity < -0.01 ? is_too_fast_uphill() : AbsAccS > AccDesired + 10.05 )
|| IsAnyCouplerStretched ) {
// jak za bardzo przyspiesza albo prędkość przekroczona
// dodany wyjatek na "pelna w przod"
@@ -8126,6 +8122,13 @@ void TController::control_tractive_force() {
SpeedSet(); // ciągla regulacja prędkości
}
+bool TController::is_too_fast_uphill() const {
+
+ if( AccDesired < 0.0 ) { return true; }
+ // holding the speed uphill on the way to a stop asks for no speeding up
+ return ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 );
+}
+
void TController::increase_tractive_force() {
if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index af97b4a1e..11a01517f 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -358,6 +358,7 @@ private:
void control_motor_connectors();
void control_tractive_force();
void increase_tractive_force();
+ bool is_too_fast_uphill() const;
void control_braking_force();
// how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal,
// otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before
From bb43f559e8ede590142d5383e4686e8d3d563f6c Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 2 Nov 2026 17:01:21 +0100
Subject: [PATCH 15/60] ESt3: spring preload, minimum stage, releaser time and
AL2 timing
Corrections to the TNESt3 distributor, checked against the ESt3 data
and acceptance requirements (orange book tables 3-5, 3-7 and 3-9) and
discussed with youBy:
- The main control device settles at (control reservoir - pipe - 0.21)
times the ratio instead of using a 0.05 bar offset. The 0.21 bar is the
spring preload; without it the first stage came 0.2 bar of pipe drop
too early. BVM is derived from the same offset, so a full service drop
still gives MaxBP.
- When the valve brakes it gives at least the minimum stage of 0.28 bar
(acceptance tests 12 and 22 require 0.25-0.30 bar); when the target
drops to zero the cylinder vents completely.
- The automatic releaser vents the 15 l control reservoir from 5.0 to
0.4 bar in about 23 s (test 27: 23 +/- 3 s) instead of 5.6 s.
- 12" cylinder fill nozzle dTN is 1.62, not 1.65 (typo).
- With the AL2 relay the impulse chamber is 1 l and the cylinder nozzles
are scaled so that the fill and release times meet table 3-9; before,
the AL2 timings had been set by eye.
On a valve test bench running the acceptance procedures, the number of
results out of tolerance drops from 77 to 40. The remaining ones need
parts that are not modelled yet (accelerator venting, ZP/ZS filling,
intermediate chamber).
---
McZapkie/Oerlikon_ESt.cpp | 44 +++++++++++++++++++++++++++++----------
McZapkie/Oerlikon_ESt.h | 1 +
2 files changed, 34 insertions(+), 11 deletions(-)
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index eb3a9ad4b..f37dc69f9 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -16,6 +16,11 @@ Copyright (C) 2007-2014 Maciej Cierniak
#include "Oerlikon_ESt.h"
#include "utilities/utilities.h"
+// wstepny nacisk sprezyn na glowny przyrzad rozrzadczy, wyrazony jako roznica cisnien ZS - PG [bar]
+static double const dPSprezyny = 0.21;
+// najmniejszy stopien hamowania w cylindrze [bar] (tablica 3-9, proby 12 i 22: 0,25-0,30)
+static double const pStopnia = 0.28;
+
double d2A( double const d )
{
return d * d * 0.7854 / 1000.0;
@@ -218,10 +223,11 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr
CheckReleaser(dt);
// luzowanie
+ double const cel{ CelBCP( CVP, VVP ) };
if ((BrakeStatus & b_hld) == b_off)
dV =
PF(0.0, BCP, Nozzles[dTO] * nastG + (1.0 - nastG) * Nozzles[dOO])
- * dt * (0.1 + 4.9 * std::min(0.2, BCP - ((CVP - 0.05 - VVP) * BVM + 0.1)));
+ * dt * (0.1 + 4.9 * std::min(0.2, BCP - (cel > 0.0 ? cel + 0.1 : 0.0))); // bez stopnia luzuje do zera
else
dV = 0.0;
// BrakeCyl.Flow(-dV);
@@ -229,7 +235,7 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr
if ( (BrakeStatus & b_on) == b_on && Przekladniki[1]->P() * HBG300 < MaxBP )
dV =
PF( BVP, BCP, Nozzles[dTN] * (nastG + 2.0 * (BCP < Podskok ? 1.0 : 0.0)) + Nozzles[dON] * (1.0 - nastG) )
- * dt * (0.1 + 4.9 * std::min( 0.2, (CVP - 0.05 - VVP) * BVM - BCP ) );
+ * dt * (0.1 + 4.9 * std::min( 0.2, cel - BCP ) );
else
dV = 0;
// BrakeCyl.Flow(-dV);
@@ -313,7 +319,7 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c
Miedzypoj->CreateCap(5.0);
Miedzypoj->CreatePress(PP);
- BVM = 1.0 / (HPP - 0.05 - LPP) * MaxBP;
+ BVM = 1.0 / (HPP - dPSprezyny - LPP) * MaxBP;
BrakeDelayFlag = BDF;
@@ -345,6 +351,13 @@ double TNESt3::GetCRP()
// return Miedzypoj.P;
}
+double TNESt3::CelBCP( double const CVP, double const VVP ) const // docelowe cisnienie w cylindrze
+{
+ double const cel{ ( CVP - dPSprezyny - VVP ) * BVM };
+ // gdy zawor hamuje, nie daje mniej niz najmniejszy stopien
+ return ( cel > 0.0 ? std::max( cel, pStopnia ) : cel );
+}
+
void TNESt3::CheckState(double const BCP, double & /*dV1*/) // glowny przyrzad rozrzadczy
{
double const VVP{ ValveRes->P() };
@@ -355,14 +368,14 @@ void TNESt3::CheckState(double const BCP, double & /*dV1*/) // glowny przyrzad r
Przys_blok = false;
// sprawdzanie stanu
- // if ((BrakeStatus and 1)=1)and(BCP>0.25)then
- if (VVP + 0.01 + BCP / BVM < CVP - 0.05 && Przys_blok)
+ double const cel{ CelBCP( CVP, VVP ) };
+ if (BCP < cel - 0.01 * BVM && Przys_blok)
BrakeStatus |= b_on | b_hld; // hamowanie stopniowe;
- else if (VVP - 0.01 + (BCP - 0.1) / BVM > CVP - 0.05)
+ else if (BCP - 0.1 > cel + 0.01 * BVM)
BrakeStatus &= ~( b_on | b_hld ); // luzowanie;
- else if (VVP + BCP / BVM > CVP - 0.05)
+ else if (BCP > cel)
BrakeStatus &= ~b_on; // zatrzymanie napelaniania;
- else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania
+ else if (BCP - 0.1 < cel && BCP > 0.25) // zatrzymanie luzowania
BrakeStatus |= b_hld;
if( ( BrakeStatus & b_hld ) == 0 )
@@ -391,7 +404,7 @@ void TNESt3::CheckReleaser(double const dt) // odluzniacz
// odluzniacz automatyczny
if ((BrakeStatus & b_rls) == b_rls)
{
- CntrlRes->Flow(PF(CVP, 0, 0.02) * dt);
+ CntrlRes->Flow(PF(CVP, 0, 0.0049) * dt); // ZS 15 l z 5,0 do 0,4 bar w 23 s (proba odbioru nr 27)
if (CVP < VVP + 0.3 || false == autom)
BrakeStatus &= ~b_rls;
}
@@ -560,7 +573,7 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie
{ // dON,dOO,dTN,dTO,dP,dS
Nozzles[dON] = 3.7;
Nozzles[dOO] = 2.50;
- Nozzles[dTN] = 1.65;
+ Nozzles[dTN] = 1.62;
Nozzles[dTO] = 1.39;
Nozzles[dP] = 2.65;
Nozzles[dPd] = 1.80;
@@ -649,6 +662,14 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie
Nozzles[dSd] = 1.1;
Nozzles[dSm] = 0.9;
+ if( PrzekCiagly != nullptr ) {
+ // dysze cylindra skalibrowane na komore impulsowa przekladnika AL2 (1 l) wg czasow z tablicy 3-9
+ Nozzles[dON] *= 0.914;
+ Nozzles[dTN] *= 0.885;
+ Nozzles[dOO] *= 0.82;
+ Nozzles[dTO] *= 0.8;
+ }
+
// przeliczanie z mm^2 na l/m
for (auto &nozzle : Nozzles)
{
@@ -657,7 +678,8 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie
for (int i = 1; i < 4; ++i)
{
Przekladniki[i]->BrakeRes = BrakeRes;
- Przekladniki[i]->CreateCap(i);
+ // komora impulsowa przekladnika AL2 ma 1 l
+ Przekladniki[i]->CreateCap( ( Przekladniki[i] == PrzekCiagly ) ? 1.0 : i );
Przekladniki[i]->CreatePress(BrakeCyl->P());
if (i < 3)
Przekladniki[i]->Next = Przekladniki[i + 1];
diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h
index 9cdffe7bc..01aefb7f2 100644
--- a/McZapkie/Oerlikon_ESt.h
+++ b/McZapkie/Oerlikon_ESt.h
@@ -196,6 +196,7 @@ class TNESt3 : public TBrake {
void EStParams(double i_crc) const; // parametry charakterystyczne dla ESt
double GetCRP() override;
double GetRapidRatio(double const Vel) const override;
+ double CelBCP(double const CVP, double const VVP) const; // docelowe cisnienie w cylindrze
void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy
void CheckReleaser(double const dt); // odluzniacz
double CVs(double const BP) const; // napelniacz sterujacego
From 6374e2d32e7ef00bb938d7b79763b1aae1d57779 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 2 Nov 2026 17:01:32 +0100
Subject: [PATCH 16/60] AI braking: predict the ESt3 brake force from the
distributor characteristic
---
McZapkie/Mover.cpp | 1 +
McZapkie/Oerlikon_ESt.cpp | 11 +++++++++++
McZapkie/Oerlikon_ESt.h | 1 +
McZapkie/hamulce.h | 4 ++++
4 files changed, 17 insertions(+)
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 429c2df17..2b2275112 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -5091,6 +5091,7 @@ void TMoverParameters::ComputeTotalForce(double dt)
double TMoverParameters::BrakeForceR(double ratio, double velocity)
{
double press = 0;
+ ratio = Hamulec->GetBrakeRatio(ratio);
if (MBPM > 2)
{
press = MaxBrakePress[1] + (MaxBrakePress[3] - MaxBrakePress[1]) * std::min(1.0, (TotalMass - Mass) / (MBPM - Mass));
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index f37dc69f9..1e7a5be66 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -351,6 +351,17 @@ double TNESt3::GetCRP()
// return Miedzypoj.P;
}
+double TNESt3::GetBrakeRatio( double const Ratio ) const // udzial cisnienia w cylindrze dla udzialu spadku w PG
+{
+ if( MaxBP <= 0.0 || BVM <= 0.0 ) {
+ return Ratio;
+ }
+ // pelny spadek sluzbowy w PG (HPP - LPP), odtworzony z przelozenia
+ double const spadek{ MaxBP / BVM + dPSprezyny };
+ double const cel{ ( Ratio * spadek - dPSprezyny ) * BVM };
+ return ( cel > 0.0 ? std::max( cel, pStopnia ) / MaxBP : 0.0 );
+}
+
double TNESt3::CelBCP( double const CVP, double const VVP ) const // docelowe cisnienie w cylindrze
{
double const cel{ ( CVP - dPSprezyny - VVP ) * BVM };
diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h
index 01aefb7f2..02d65a285 100644
--- a/McZapkie/Oerlikon_ESt.h
+++ b/McZapkie/Oerlikon_ESt.h
@@ -197,6 +197,7 @@ class TNESt3 : public TBrake {
double GetCRP() override;
double GetRapidRatio(double const Vel) const override;
double CelBCP(double const CVP, double const VVP) const; // docelowe cisnienie w cylindrze
+ double GetBrakeRatio(double const Ratio) const override; // udzial cisnienia w cylindrze dla udzialu spadku w PG
void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy
void CheckReleaser(double const dt); // odluzniacz
double CVs(double const BP) const; // napelniacz sterujacego
diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h
index 5b5f8933c..37b9b6a4d 100644
--- a/McZapkie/hamulce.h
+++ b/McZapkie/hamulce.h
@@ -421,6 +421,10 @@ class TBrake
double GetVRP() const; // cisnienie komory wstepnej rozdzielacza
/// Returns control reservoir (ZS) pressure [bar]; defaults to the auxiliary reservoir for valves without a dedicated ZS.
virtual double GetCRP(); // cisnienie zbiornika sterujacego
+ /// Share of the full cylinder pressure the distributor settles at for the given share
+ /// of the full service pipe drop. Used only to predict the brake force; the default is proportional.
+ /// Share of the full service brake pipe drop.
+ virtual double GetBrakeRatio(double const Ratio) const { return Ratio; }
///
/// Sets the brake delay (G/P/R/M) selector if requested mode is supported.
///
From 4a256477e0d5b8be8685d7e9944af530b6584136 Mon Sep 17 00:00:00 2001
From: Sebastian Krzyszkowiak
Date: Wed, 28 Oct 2026 03:33:33 +0100
Subject: [PATCH 17/60] Train: Handle 3-way light switches in headlighttoggle
actions
This lets them be fully operated with mouse and VR pointers.
---
vehicle/Train.cpp | 76 +++++++++++++++++++++++++++++++++++++----------
1 file changed, 60 insertions(+), 16 deletions(-)
diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp
index 201b8972f..e2f8fa86e 100644
--- a/vehicle/Train.cpp
+++ b/vehicle/Train.cpp
@@ -5234,15 +5234,37 @@ void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Co
if (Command.action == GLFW_PRESS)
{
// only reacting to press, so the switch doesn't flip back and forth if key is held down
- if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0)
+
+ if (Train->ggLeftEndLightButton.SubModel != nullptr || Train->ggLeftLightButton.SubModel == nullptr)
{
- // turn on
- OnCommand_headlightenableleft(Train, Command);
- }
- else
- {
- // turn off
- OnCommand_headlightdisableleft(Train, Command);
+ if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0)
+ {
+ // turn on
+ OnCommand_headlightenableleft(Train, Command);
+ }
+ else
+ {
+ // turn off
+ OnCommand_headlightdisableleft(Train, Command);
+ }
+ } else {
+ // if the light is controlled by 3-way switch, handle both headlight and redmarker
+ if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0 &&
+ (Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0)
+ {
+ // turn on
+ OnCommand_headlightenableleft(Train, Command);
+ }
+ else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_left)
+ {
+ // switch to red
+ OnCommand_redmarkerenableleft(Train, Command);
+ }
+ else
+ {
+ // disable
+ OnCommand_redmarkerdisableleft(Train, Command);
+ }
}
}
}
@@ -5317,15 +5339,37 @@ void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &C
if (Command.action == GLFW_PRESS)
{
// only reacting to press, so the switch doesn't flip back and forth if key is held down
- if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0)
+
+ if (Train->ggRightEndLightButton.SubModel != nullptr || Train->ggRightLightButton.SubModel == nullptr)
{
- // turn on
- OnCommand_headlightenableright(Train, Command);
- }
- else
- {
- // turn off
- OnCommand_headlightdisableright(Train, Command);
+ if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0)
+ {
+ // turn on
+ OnCommand_headlightenableright(Train, Command);
+ }
+ else
+ {
+ // turn off
+ OnCommand_headlightdisableright(Train, Command);
+ }
+ } else {
+ // if the light is controlled by 3-way switch, handle both headlight and redmarker
+ if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0 &&
+ (Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0)
+ {
+ // turn on
+ OnCommand_headlightenableright(Train, Command);
+ }
+ else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_right)
+ {
+ // switch to red
+ OnCommand_redmarkerenableright(Train, Command);
+ }
+ else
+ {
+ // disable
+ OnCommand_redmarkerdisableright(Train, Command);
+ }
}
}
}
From 7e426192b7962f0e2d0c1610e4639fe746b67fd9 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 10:05:10 +0100
Subject: [PATCH 18/60] fix(cab): a diesel with only the starter button stops
its engine with the main switch off command (eu07/maszyna#427)
The SM03 had no way to stop its engine. Its fuel pump starts on its own, so the fuel pump switch is ignored; the
engine runs the converter feeding the low voltage circuit, so the battery switch doesn't starve the fuel pump either;
and its cab has only the starter button, for which TTrain::OnCommand_linebreakeropen() kept a legacy branch which
animated the button and returned without opening the circuit. MainSwitch(false) itself stops the engine fine.
The command now opens the circuit on diesels whose cab has only the starter button
(TMoverParameters::MainCircuitOpensWithStarterOnly()), without animating the button, which held down would start
the engine again. Other vehicles with only the button closing the circuit keep ignoring the command.
Tests: tests/unit/test_engine_shutdown.cpp, on a shunter made after the SM03.
---
McZapkie/MOVER.h | 7 +++
tests/unit/data/diesel_shunter.json | 53 +++++++++++++++++++++
tests/unit/test_engine_shutdown.cpp | 74 +++++++++++++++++++++++++++++
vehicle/Train.cpp | 3 +-
4 files changed, 136 insertions(+), 1 deletion(-)
create mode 100644 tests/unit/data/diesel_shunter.json
create mode 100644 tests/unit/test_engine_shutdown.cpp
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..79a73f1a0 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -2466,6 +2466,13 @@ class TMoverParameters
{
return false == StLinFlag && MainCircuitLampsEnabled();
}
+ // 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
+ bool MainCircuitOpensWithStarterOnly() const
+ {
+ return EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric;
+ }
// whether the pumps a joint oil and fuel pump switch works, those not started automatically, are all switched on
bool OilFuelPumpsEnabled() const
{
diff --git a/tests/unit/data/diesel_shunter.json b/tests/unit/data/diesel_shunter.json
new file mode 100644
index 000000000..3cbcdb992
--- /dev/null
+++ b/tests/unit/data/diesel_shunter.json
@@ -0,0 +1,53 @@
+{
+ "_comment": "Diesel shunter with a mechanical gearbox, made after the SM03 (Ls150): the fuel pump starts on its own with the engine, a converter run by the engine feeds the low voltage circuit, the only cab control of the engine is the starter button.",
+ "Param": { "Category": "train", "M": 23200, "Vmax": 25.68, "PWR": 111.855, "SandCap": 200 },
+ "Dimensions": { "L": 6.94, "H": 3.21, "W": 2.97, "Cx": 0.3 },
+ "Wheels": { "D": 0.94, "Tw": 1.435, "AIM": 250, "Axle": "B", "Ad": 2.5, "Bd": 2.5, "Rmin": 50, "BearingType": "Roll" },
+ "Brake": {
+ "BrakeValve": "K", "NBpA": 2, "MBF": 85.0, "MaxBP": 3.5, "LocMaxBP": 5.0, "BCN": 1, "BCR": 0.114, "BCD": 0.12, "BCM": 10.0,
+ "HiPP": 5, "LoPP": 3.5, "Vv": 0.3, "MinCP": 7.0, "MaxCP": 8.0, "CompressorSpeed": 0.0125, "CompressorPower": "Main",
+ "BCS": 0.8, "BSA": 0, "BM": "P10-Bg", "BVV": 40, "BRE": 0.9
+ },
+ "BuffCoupl": { "CType": "Screw", "kB": 9200, "DmaxB": 0.15, "FmaxB": 740, "kC": 4800, "DmaxC": 0.15, "FmaxC": 780, "beta": 0.58, "AllowedFlag": 3 },
+ "Cntrl": {
+ "BrakeSystem": "Pneumatic", "BDelay1": 15, "BDelay2": 4, "ASB": "Manual", "LocalBrake": "PneumaticBrake", "ManualBrake": "Yes",
+ "DynamicBrake": "Passive", "MCPN": 9, "SCPN": 7, "AutoRelay": "No", "IniCDelay": 0.5, "SCDelay": 0.1, "BrakeDelays": "P",
+ "BrakeHandle": "Knorr", "LocBrakeHandle": "Knorr", "FuelStart": "Automatic", "ConverterStart": "Automatic"
+ },
+ "Light": { "Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": 24, "LMaxCurrent": 100 },
+ "Engine": {
+ "EngineType": "DieselEngine", "Trans": "1:1", "nmin": 900, "nmax": 1500, "nmax_cutoff": 1550, "AIM": 100,
+ "OilMinPressure": 0.343, "OilMaxPressure": 0.686, "WaterCoolingTemperature": 80, "WaterShutters": "yes", "WaterAuxCircuit": "no",
+ "HeatKFO": 160, "HeatKFO2": 180, "HeatKFS": 160, "HeatKFE": 7, "HeatKW": 2, "HeatKV": 0.3, "IsTC": "No", "EUS": 0.35, "EDS": 1.0
+ },
+ "_gears": "rows: gear, ratio, engagement speed, top speed; the even ones neutral",
+ "MotorParamTable": {
+ "minVelfullengage": 3.8, "engageDia": 1, "engageMaxForce": 800, "engagefriction": 1,
+ "rows": [
+ [0, 0, 0, -1],
+ [1, 46.88, -1, 5.73],
+ [2, 0, 0, -1],
+ [3, 28.65, 2.9, 9.42],
+ [4, 0, 0, -1],
+ [5, 17.12, 4.7, 15.69],
+ [6, 0, 0, -1],
+ [7, 10.46, 10.6, 100]
+ ]
+ },
+ "_throttle": "rows: position, fill, speed governor mode; position 0 idles",
+ "DList": {
+ "Size": 9, "Mmax": 784.5, "nMmax": 15, "Mnmax": 686.4, "nmax": 25, "nominalfill": 1, "Mstand": 200.0,
+ "rows": [
+ [0, 0.1, 0],
+ [1, 0.2, 2],
+ [2, 0.3, 2],
+ [3, 0.4, 2],
+ [4, 0.5, 2],
+ [5, 0.6, 2],
+ [6, 0.7, 2],
+ [7, 0.8, 2],
+ [8, 0.9, 2],
+ [9, 1.0, 2]
+ ]
+ }
+}
diff --git a/tests/unit/test_engine_shutdown.cpp b/tests/unit/test_engine_shutdown.cpp
new file mode 100644
index 000000000..9230330f4
--- /dev/null
+++ b/tests/unit/test_engine_shutdown.cpp
@@ -0,0 +1,74 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "vehicle.h"
+
+// stopping the engine of a diesel shunter like the SM03 (eu07/maszyna#427): its fuel pump starts on its own with the
+// engine and the engine runs the converter which feeds the low voltage circuit, so neither the fuel pump switch nor the
+// battery switch stop it. the cab has only the starter button, and the command opening the main circuit has to stop it
+
+namespace {
+
+// the shunter with its engine started from the cab and idling
+test::vehicle running_shunter() {
+ test::vehicle shunter{test::definition::load("diesel_shunter")};
+ shunter->CabOccupied = 1;
+ shunter->CabActivisation();
+ shunter->BatterySwitch(true);
+ shunter->OilPumpSwitch(true);
+ shunter.run(20.0); // the oil pressure builds up
+ shunter->MainSwitch(true);
+ shunter.run(15.0);
+ return shunter;
+}
+
+} // namespace
+
+TEST_CASE("engine shutdown: the shunter starts with the starter button") {
+ auto shunter{running_shunter()};
+ REQUIRE(shunter->EngineType == TEngineType::DieselEngine);
+ REQUIRE(shunter->FuelPump.start_type == start_t::automatic);
+ CHECK(shunter->Mains);
+ CHECK(shunter->FuelPump.is_active);
+ CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin);
+}
+
+TEST_CASE("engine shutdown: neither the fuel pump switch nor the battery switch stop the engine") {
+ auto shunter{running_shunter()};
+ shunter->FuelPumpSwitchOff(true, range_t::local); // the pump started automatically ignores its switch
+ shunter.run(10.0);
+ CHECK(shunter->Mains);
+ shunter->BatterySwitch(false);
+ shunter.run(10.0);
+ CHECK(shunter->Power110vIsAvailable); // the converter run by the engine keeps feeding the fuel pump
+ CHECK(shunter->Mains);
+ CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin);
+}
+
+TEST_CASE("engine shutdown: the command opening the main circuit stops the engine and it stays stopped") {
+ auto shunter{running_shunter()};
+ REQUIRE(shunter->MainCircuitOpensWithStarterOnly()); // the cab passes the command on with only the starter button
+ CHECK(shunter->MainSwitch(false));
+ shunter.run(20.0);
+ CHECK_FALSE(shunter->Mains);
+ CHECK_FALSE(shunter->FuelPump.is_active);
+ CHECK(shunter->enrot == 0.0);
+}
+
+TEST_CASE("engine shutdown: the engine starts again after it was stopped") {
+ auto shunter{running_shunter()};
+ shunter->MainSwitch(false);
+ shunter.run(20.0);
+ REQUIRE(shunter->enrot == 0.0);
+ shunter->MainSwitch(true);
+ shunter.run(15.0);
+ CHECK(shunter->Mains);
+ CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin);
+}
+
+TEST_CASE("engine shutdown: vehicles without a diesel keep ignoring the command with only the button closing the circuit") {
+ test::vehicle wagon{test::definition::load("wagon")};
+ CHECK_FALSE(wagon->MainCircuitOpensWithStarterOnly());
+ test::vehicle electric{test::definition::load("wagon").set("Engine", "EngineType", "ElectricSeriesMotor")};
+ REQUIRE(electric->EngineType == TEngineType::ElectricSeriesMotor);
+ CHECK_FALSE(electric->MainCircuitOpensWithStarterOnly());
+}
diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp
index 201b8972f..1b7d06a8f 100644
--- a/vehicle/Train.cpp
+++ b/vehicle/Train.cpp
@@ -3702,13 +3702,14 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman
{
Train->ggMainButton.UpdateValue(0.0, Train->dsbSwitch);
}
- else if (Train->ggMainOnButton.SubModel != nullptr)
+ else if (Train->ggMainOnButton.SubModel != nullptr && false == Train->mvControlled->MainCircuitOpensWithStarterOnly())
{
// NOTE: legacy behaviour, for vehicles equipped only with impulse close switch
// it doesn't make any real sense to animate this one, but some people can't get over how there's no visual reaction to their keypress
Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch);
return;
}
+ // a diesel with only the starter button gets its engine stopped. the button stays put: held down, it would start the engine again
// play sound immediately when the switch is hit, not after release
Train->fMainRelayTimer = 0.0f;
From d90edb698033c66ccc93e1c447c53269dbeaa9e9 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 14:06:58 +0100
Subject: [PATCH 19/60] fix(cab): on the SU45 and SU46 the open line contactors
lamp lights with the contactors opened by the pressure switch
(eu07/maszyna#263)
On the electric locomotives the lamp of the open line contactors tells the start can be made, so it goes out with the
start cut off by the pressure switch. The diesel-electric SU45 and SU46 (the only diesel-electrics with the lamp) use
it just to show the contactors are open, but it went out the same way: with too low a pressure in the main pipe the
contactors were open and the lamp out. Once the pressure came back with the master controller past the first
position, the contactors stayed open, as they should, and the lamp lit up on a power position, which looked like
the lamp working the other way round.
On the diesel-electrics TMoverParameters::LineContactorsLampLit() now follows the contactors alone; the electric
locomotives and the other main circuit lamps are unchanged.
Tests: tests/unit/test_line_contactors.cpp, on a locomotive made after the SU46.
---
McZapkie/MOVER.h | 8 +++-
tests/unit/data/diesel_electric.json | 46 ++++++++++++++++++
tests/unit/test_line_contactors.cpp | 71 ++++++++++++++++++++++++++++
3 files changed, 124 insertions(+), 1 deletion(-)
create mode 100644 tests/unit/data/diesel_electric.json
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 199c65a0c..a34d537f4 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -2461,9 +2461,15 @@ class TMoverParameters
{
return false == ControlPressureSwitch && (HasControlPressureSwitch || BrakePress < 1.0);
}
- // whether the lamp of the open line contactors is lit, telling the start can be made
+ // whether the lamp of the open line contactors is lit. on the electric locomotives it tells the start can be made, so
+ // it goes out with the start cut off; on the diesel-electric ones (the SU45 and SU46 family) it just tells the
+ // contactors are open, whatever opened them: the master controller at 0, or the pressure switch (eu07/maszyna#263)
bool LineContactorsLampLit() const
{
+ if (EngineType == TEngineType::DieselElectric)
+ {
+ return false == StLinFlag;
+ }
return false == StLinFlag && MainCircuitLampsEnabled();
}
// whether the pumps a joint oil and fuel pump switch works, those not started automatically, are all switched on
diff --git a/tests/unit/data/diesel_electric.json b/tests/unit/data/diesel_electric.json
new file mode 100644
index 000000000..bef605880
--- /dev/null
+++ b/tests/unit/data/diesel_electric.json
@@ -0,0 +1,46 @@
+{
+ "_comment": "Diesel-electric locomotive made after the SU46 (303D): the line contactors close on the first power position of the master controller, the pressure switch (on by default) opens them with too low a pressure in the main pipe or the brakes applied.",
+ "Param": { "Category": "train", "M": 105000, "Mred": 15000, "Vmax": 120, "PWR": 1400, "SandCap": 400 },
+ "Dimensions": { "L": 18.99, "H": 4.292, "W": 2.904, "Cx": 0.3 },
+ "Wheels": { "D": 1.1, "AIM": 4000, "Tw": 1.435, "Axle": "Co'Co'", "Ad": 1.75, "Bd": 10.3, "Rmin": 100 },
+ "Brake": {
+ "BrakeValve": "LSt", "NBpA": 4, "MBF": 85.0, "MaxBP": 4.4, "LocMaxBP": 4.4, "MaxASBP": 1.3, "RM": 0.71, "BCN": 12, "BCR": 0.114,
+ "BCD": 0.06, "BCM": 5.84, "HiPP": 5, "LoPP": 3.5, "Vv": 0.9, "MinCP": 7, "MaxCP": 8.5, "CompressorSpeed": 0.05, "BCS": 1, "BSA": 2,
+ "BM": "P10-Bgu", "CompressorPower": "Converter", "BVV": 200, "BRE": 0.8
+ },
+ "BuffCoupl": { "CType": "Screw", "kB": 9200, "DmaxB": 0.15, "FmaxB": 740, "kC": 4800, "DmaxC": 0.15, "FmaxC": 780, "beta": 0.58, "AllowedFlag": 103 },
+ "Cntrl": {
+ "BrakeHandle": "FV4a", "LocBrakeHandle": "FD1", "BrakeSystem": "Pneumatic", "BDelay1": 15, "BDelay2": 6, "BDelay3": 36, "BDelay4": 32,
+ "ASB": "Manual", "LocalBrake": "PneumaticBrake", "MCPN": 15, "SCPN": 4, "AutoRelay": "Yes", "IniCDelay": 0.5, "SCDelay": 0.1,
+ "BrakeDelays": "GPR", "ConverterStart": "Automatic", "ConverterStartDelay": 10
+ },
+ "Light": { "Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": 110, "LMaxCurrent": 100 },
+ "Engine": {
+ "AIM": 1.6, "EngineType": "DumbDE", "Trans": "18:62", "Ftmax": 317000, "Flat": 0, "Vhyp": 15.0, "Vadd": 3.8, "Cr": 1.0, "RelayType": 46,
+ "OilMinPressure": 0.055, "OilMaxPressure": 0.6, "WaterMinTemperature": 40, "WaterMaxTemperature": 92, "WaterCoolingTemperature": 76,
+ "HeatKW": 0.068599, "HeatKV": 0.3, "HeatKFE": 1, "HeatKFS": 87.76269, "HeatKFO": 26.72716, "HeatKFO2": 57.72
+ },
+ "Circuit": { "CircuitRes": 0.01, "ImaxLo": 3300, "IminLo": 2500 },
+ "_power": "rows: engine speed [rpm], power [kW], generator voltage limit, current limit, one per master controller position",
+ "WWList": {
+ "Size": 15,
+ "rows": [
+ [696, 0, 0, 0],
+ [696, 0, 0, 0],
+ [696, 80, 350, 1000],
+ [696, 80, 350, 1000],
+ [763, 214, 455, 1400],
+ [830, 321, 500, 1600],
+ [897, 428, 545, 1800],
+ [964, 535, 590, 2000],
+ [1031, 642, 635, 2200],
+ [1098, 748, 680, 2400],
+ [1165, 855, 725, 2600],
+ [1232, 962, 770, 2800],
+ [1299, 1069, 815, 3000],
+ [1366, 1176, 865, 3200],
+ [1433, 1283, 910, 3400],
+ [1500, 1390, 960, 3600]
+ ]
+ }
+}
diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp
index 79c419edf..fd7e24f08 100644
--- a/tests/unit/test_line_contactors.cpp
+++ b/tests/unit/test_line_contactors.cpp
@@ -57,3 +57,74 @@ TEST_CASE("line contactors: the ground relay and overload lamps follow the same
vehicle->MotorConnectorsCheck();
CHECK_FALSE(vehicle->MainCircuitLampsEnabled());
}
+
+// on the diesel-electric SU45 and SU46 (eu07/maszyna#263) the lamp tells just the line contactors are open: lit with the
+// master controller at 0 and with the start cut off by too low a pressure in the main pipe, out on the power positions
+
+namespace {
+
+// the diesel-electric locomotive with its engine running and the brakes released, the master controller at 0
+test::vehicle diesel_electric() {
+ test::vehicle vehicle{test::definition::load("diesel_electric")};
+ vehicle->CabOccupied = 1;
+ vehicle->CabActivisation();
+ vehicle->BatterySwitch(true);
+ vehicle->OilPumpSwitch(true);
+ vehicle->FuelPumpSwitch(true);
+ vehicle.run(20.0); // the oil pressure builds up
+ vehicle.hold_brake_pipe(5.0); // bar
+ vehicle->MainSwitch(true);
+ vehicle.run(30.0);
+ vehicle->DirectionForward();
+ vehicle.run(60.0); // the brakes release
+ return vehicle;
+}
+
+} // namespace
+
+TEST_CASE("line contactors: on a diesel-electric the lamp is lit at 0 and goes out on a power position") {
+ auto vehicle{diesel_electric()};
+ REQUIRE(vehicle->EngineType == TEngineType::DieselElectric);
+ REQUIRE(vehicle->Mains);
+ REQUIRE_FALSE(vehicle->ControlPressureSwitch);
+ CHECK_FALSE(vehicle->StLinFlag);
+ CHECK(vehicle->LineContactorsLampLit());
+
+ vehicle->IncMainCtrl(1);
+ vehicle.run(3.0);
+ CHECK(vehicle->StLinFlag);
+ CHECK_FALSE(vehicle->LineContactorsLampLit());
+
+ vehicle->DecMainCtrl(1);
+ vehicle.run(3.0);
+ CHECK_FALSE(vehicle->StLinFlag);
+ CHECK(vehicle->LineContactorsLampLit());
+}
+
+TEST_CASE("line contactors: on a diesel-electric the lamp lights with the contactors opened by too low a main pipe pressure") {
+ auto vehicle{diesel_electric()};
+ vehicle->IncMainCtrl(1);
+ vehicle.run(1.0);
+ vehicle->IncMainCtrl(1);
+ vehicle.run(2.0);
+ REQUIRE(vehicle->StLinFlag);
+
+ vehicle.hold_brake_pipe(2.5); // bar, below the 3.6 bar of the pressure switch
+ vehicle.run(10.0);
+ REQUIRE(vehicle->ControlPressureSwitch);
+ CHECK_FALSE(vehicle->StLinFlag);
+ CHECK(vehicle->LineContactorsLampLit()); // it went out here
+ CHECK_FALSE(vehicle->MainCircuitLampsEnabled()); // the ground relay and overload lamps still go out with the start cut off
+
+ // the pressure back, the contactors stay open on the second position and the lamp stays lit, as it should;
+ // they close again only on the first one
+ vehicle.hold_brake_pipe(5.0);
+ vehicle.run(60.0);
+ REQUIRE_FALSE(vehicle->ControlPressureSwitch);
+ CHECK_FALSE(vehicle->StLinFlag);
+ CHECK(vehicle->LineContactorsLampLit());
+ vehicle->DecMainCtrl(1);
+ vehicle.run(3.0);
+ CHECK(vehicle->StLinFlag);
+ CHECK_FALSE(vehicle->LineContactorsLampLit());
+}
From 439e892abdaeac36bb76f3df2c8f926f76791477 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 15:35:35 +0100
Subject: [PATCH 20/60] AI: use the locomotive releaser only when starting off
The rule "wyluzuj lokomotywe, to szybciej ruszymy" released the
locomotive's own brake whenever power was asked for and the locomotive
cylinder held more than 0.4 bar. It had no speed condition, so it also
fired in motion, at 50-75 km/h, right after an application. On a
locomotive with the EStED distributor (E186) this vented the control
reservoir; with the pipe not yet recharged the locomotive brake then
faded to nothing at the next application.
The rule is meant for starting off, so it now applies only below
1 km/h.
---
vehicle/Driver.cpp | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 2311ffacf..8d2a3fac6 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -8292,8 +8292,11 @@ void TController::control_releaser() {
}
}
// wyluzuj lokomotywę, to szybciej ruszymy
+ // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent
+ // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it
if( mvOccupied->BrakePress > 0.4
- && mvOccupied->Hamulec->GetCRP() > 4.9 ) {
+ && mvOccupied->Hamulec->GetCRP() > 4.9
+ && mvOccupied->Vel < 1.0 ) {
actuate = true;
}
// keep engine brakes released during coupling/uncoupling
From fddeea8b0e48e3bda81c3da5c90cb729eb8d3e31 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 15:35:35 +0100
Subject: [PATCH 21/60] AI: use the locomotive releaser only when starting off
The rule "wyluzuj lokomotywe, to szybciej ruszymy" released the
locomotive's own brake whenever power was asked for and the locomotive
cylinder held more than 0.4 bar. It had no speed condition, so it also
fired in motion, at 50-75 km/h, right after an application. On a
locomotive with the EStED distributor (E186) this vented the control
reservoir; with the pipe not yet recharged the locomotive brake then
faded to nothing at the next application.
The rule is meant for starting off, so it now applies only below
1 km/h.
---
vehicle/Driver.cpp | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 08f0c0d24..97ec36470 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -8057,8 +8057,11 @@ void TController::control_releaser() {
}
}
// wyluzuj lokomotywę, to szybciej ruszymy
+ // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent
+ // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it
if( mvOccupied->BrakePress > 0.4
- && mvOccupied->Hamulec->GetCRP() > 4.9 ) {
+ && mvOccupied->Hamulec->GetCRP() > 4.9
+ && mvOccupied->Vel < 1.0 ) {
actuate = true;
}
// keep engine brakes released during coupling/uncoupling
From 798fd89dd0fc616967485a06530f9b40a88791e9 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 30 Sep 2026 19:16:46 +0200
Subject: [PATCH 22/60] test: scenario tests that run the simulator and check a
vehicle's physicslog
tests/scenarios/run.py builds a test scenery from a game install's scenery
(own trainsets removed, case fragment added), runs eu07 in ghostview with
physicslog on, and checks what the vehicle did: starts, max speed, brakes,
stops. First case: EU07 on td.scn driven by AI on the td/rozklad timetable,
with the Stacja1 exit route set by an event launcher instead of shift+4.
eu07 gets a -ini option: an extra settings file read after eu07.ini,
so a test run can switch to a window and turn on physicslog without touching
the user's config.
Local only: scenery and vehicle data are not in the repo.
---
application/application.cpp | 12 +-
tests/scenarios/.gitignore | 2 +
tests/scenarios/README.md | 66 ++++
tests/scenarios/cases/eu07_td_timetable.json | 15 +
tests/scenarios/cases/eu07_td_timetable.scn | 11 +
tests/scenarios/run.py | 330 +++++++++++++++++++
6 files changed, 435 insertions(+), 1 deletion(-)
create mode 100644 tests/scenarios/.gitignore
create mode 100644 tests/scenarios/README.md
create mode 100644 tests/scenarios/cases/eu07_td_timetable.json
create mode 100644 tests/scenarios/cases/eu07_td_timetable.scn
create mode 100644 tests/scenarios/run.py
diff --git a/application/application.cpp b/application/application.cpp
index 9b7b82853..ee381f98b 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -1195,12 +1195,22 @@ int eu07_application::init_settings(int Argc, char *Argv[])
WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed));
}
}
+ else if (token == "-ini")
+ {
+ // extra settings file read on top of eu07.ini, so a run can override a few keys
+ // (window size, physicslog...) without touching the user's own config
+ if (i + 1 < Argc)
+ {
+ Global.LoadIniFile(Argv[++i]);
+ }
+ }
else
{
std::cout << "usage: " << std::string(Argv[0]) << " [-s sceneryfilepath]"
<< " [-v vehiclename]"
<< " [-edit [sceneryfilepath]]"
- << " [-seed number|word]" << std::endl;
+ << " [-seed number|word]"
+ << " [-ini settingsfile]" << std::endl;
return -1;
}
}
diff --git a/tests/scenarios/.gitignore b/tests/scenarios/.gitignore
new file mode 100644
index 000000000..ea93687fe
--- /dev/null
+++ b/tests/scenarios/.gitignore
@@ -0,0 +1,2 @@
+out/
+__pycache__/
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
new file mode 100644
index 000000000..77edb5a93
--- /dev/null
+++ b/tests/scenarios/README.md
@@ -0,0 +1,66 @@
+# Scenario tests
+
+End-to-end checks that run the real simulator on a scenery and look at what a vehicle
+did: did it start, did it keep to the speed limit, did it brake and stop.
+
+Scenery and vehicle data are not in this repo, so these run against a local game install
+only, not in CI.
+
+## Running
+
+```
+python tests/scenarios/run.py --game-dir "E:/Program Files (x86)/Steam/steamapps/common/MaSzyna"
+```
+
+Python 3.10+, no extra packages. Options:
+
+- `EU07_GAME_DIR` can replace `--game-dir`.
+- `--exe path/to/eu07.exe` picks the build to test; the default is the newest
+ `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `-ini` command line option.
+- name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`.
+- `--timespeed 4` runs the simulation faster than real time.
+
+Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`,
+the vehicle's physicslog) land in `tests/scenarios/out//`.
+
+## How it works
+
+For each case the runner:
+
+1. writes `scenery/autotest_.scn` into the game dir: the base scenery with its own
+ trainsets removed, the start time changed if the case says so, and the case's `.scn`
+ fragment added: its trainsets after `FirstInit`, everything else (event launchers standing
+ in for keys the scenery expects a player to press, extra events) before it,
+2. starts the simulator with `-s autotest_.scn -v ghostview -ini out//autotest.ini`;
+ ghostview leaves every train to the AI, and the extra ini turns on `physicslog`,
+ runs in a 1280x720 window and does not pause when the window loses focus,
+3. waits until `physicslog/.dat` covers `duration` seconds, then closes the simulator,
+4. runs the checks on the physicslog.
+
+## Writing a case
+
+`cases/.json`:
+
+| key | meaning |
+| --- | --- |
+| `base_scenery` | scenery file in the game's `scenery/` dir |
+| `strip_trainsets` | drop the base scenery's trainsets (default `true`) |
+| `time` | replace the scenery start time, `HH:MM` |
+| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) |
+| `vehicle` | node name of the vehicle whose physicslog is checked |
+| `duration` | seconds of simulation to record |
+| `timeout` | wall-clock seconds before giving up, loading included |
+| `fail_on_errors` | fail when `errors.txt` is not empty (default `false`) |
+| `checks` | list of checks, below |
+
+Checks (speeds in km/h, times in seconds of physicslog time):
+
+- `starts` `min_speed`, `within`: reaches `min_speed` within `within` seconds.
+- `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`.
+- `brakes` `min_pressure`: after moving off, brake cylinder pressure reaches `min_pressure` bar
+ (physicslog pressures are in bar whatever its header says; the brake pipe runs at 5.0).
+- `stops` `moving_speed`, `stop_speed`, `hold`: after reaching `moving_speed`, stays at or
+ below `stop_speed` for `hold` seconds.
+
+New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's
+parameters and returns `(passed, detail)`.
diff --git a/tests/scenarios/cases/eu07_td_timetable.json b/tests/scenarios/cases/eu07_td_timetable.json
new file mode 100644
index 000000000..c12b8ae71
--- /dev/null
+++ b/tests/scenarios/cases/eu07_td_timetable.json
@@ -0,0 +1,15 @@
+{
+ "description": "EU07 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "eu07_td_timetable.scn",
+ "vehicle": "autotest_eu07",
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/eu07_td_timetable.scn b/tests/scenarios/cases/eu07_td_timetable.scn
new file mode 100644
index 000000000..c8044e467
--- /dev/null
+++ b/tests/scenarios/cases/eu07_td_timetable.scn
@@ -0,0 +1,11 @@
+// added by tests/scenarios/run.py to the base scenery, whose own trainsets were removed:
+// the trainset goes after FirstInit, the launcher before it.
+// the EU07 stands where td.scn keeps its timetable train and gets the same timetable.
+trainset td/rozklad tdo_n1734 0.0 0.1
+node -1 0 autotest_eu07 dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic
+endtrainset
+
+// td.scn sets routes from the keyboard (shift+1..4 run events keyctrl01..04). keyctrl04 is the
+// way out of the track the train stands on: switch zwr02 and the exit signal stacja1_j at 40.
+// a launcher with a positive time fires once at that hour (HHMM), radius -1 means anywhere.
+node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
new file mode 100644
index 000000000..ad1f51ee7
--- /dev/null
+++ b/tests/scenarios/run.py
@@ -0,0 +1,330 @@
+#!/usr/bin/env python3
+"""Scenario tests: run the real simulator on a scenery and check what a vehicle did.
+
+A case (cases/.json) names a base scenery from the game install, a fragment
+appended to it (usually a trainset with an AI driver), and checks on the vehicle's
+physics log. The runner:
+
+ 1. builds scenery/autotest_.scn in the game dir: the base scenery with its own
+ trainsets removed, optionally a different start time, and the case fragment appended,
+ 2. starts eu07 with that scenery in ghostview (every train driven by AI) and an extra
+ settings file (-ini) that turns on physicslog and runs in a window,
+ 3. waits until the vehicle's physicslog covers `duration` seconds of simulation,
+ then closes the simulator,
+ 4. evaluates the checks on the log and prints PASS/FAIL per check.
+
+Scenery and vehicle data are not part of this repo, so this runs against a local game
+install only (--game-dir or EU07_GAME_DIR), not in CI.
+
+Usage:
+ python tests/scenarios/run.py --game-dir "E:/.../MaSzyna" # all cases
+ python tests/scenarios/run.py --game-dir ... eu07_td_timetable # chosen cases
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+REPO = HERE.parents[1]
+CASES_DIR = HERE / "cases"
+OUT_DIR = HERE / "out"
+
+# physicslog columns, see TController::PhysicsLog() in vehicle/Driver.cpp.
+# Velocity is in km/h and pressures in bar, despite the header saying m/s and MPa.
+COL_TIME = 0
+COL_VELOCITY = 1
+COL_BRAKE_PRESS = 8
+
+# settings layered over the user's eu07.ini for a test run
+TEST_INI = """\
+fullscreen no
+fullscreenwindowed no
+width 1280
+height 720
+inactivepause no
+soundenabled no
+physicslog yes
+multiplelogs no
+timespeed {timespeed}
+"""
+
+
+# ---------------------------------------------------------------- scenery
+
+
+def split_trainsets(text: str) -> tuple[str, str]:
+ """Splits text into (everything else, the trainset ... endtrainset blocks)."""
+ rest, trainsets = [], []
+ inside = False
+ for line in text.splitlines(keepends=True):
+ tokens = line.split("//", 1)[0].split()
+ if not inside and tokens and tokens[0].lower() == "trainset":
+ inside = True
+ if inside:
+ trainsets.append(line)
+ if any(t.lower() == "endtrainset" for t in tokens):
+ inside = False
+ continue
+ rest.append(line)
+ return "".join(rest), "".join(trainsets)
+
+
+def set_start_time(text: str, hhmm: str) -> str:
+ return re.sub(r"(?im)^(\s*time\s+)\d{1,2}:\d{2}", lambda m: m.group(1) + hhmm, text, count=1)
+
+
+def build_scenery(case: dict, game_dir: Path, case_name: str) -> str:
+ """Writes the case scenery into the game's scenery dir and returns its file name."""
+ scenery_dir = game_dir / "scenery"
+ # sceneries are cp1250; latin-1 round-trips every byte, so nothing gets mangled
+ text = (scenery_dir / case["base_scenery"]).read_bytes().decode("latin-1")
+ if case.get("strip_trainsets", True):
+ text, _ = split_trainsets(text)
+ if "time" in case:
+ text = set_start_time(text, case["time"])
+ fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1")
+ # FirstInit binds event launchers to their events and links the tracks. so launchers and
+ # events of the case go in before it (read after it they never fire), trainsets after it
+ # (placed before it they stand on unlinked track and derail at once)
+ before, trainsets = split_trainsets(fragment)
+ header = f"\n// ---- autotest: {case_name} ----\n"
+ firstinit = re.search(r"(?im)^\s*firstinit\b", text)
+ if firstinit:
+ text = text[: firstinit.start()] + header + before + "\n" + text[firstinit.start():]
+ else:
+ text += header + before + "\n"
+ text += header + trainsets + "\n"
+ name = f"autotest_{case_name}.scn"
+ (scenery_dir / name).write_bytes(text.encode("latin-1"))
+ return name
+
+
+# ---------------------------------------------------------------- run
+
+
+def read_physicslog(path: Path) -> list[list[float]]:
+ """Returns rows of numeric columns up to BrakePress; skips the header and partial lines."""
+ rows = []
+ try:
+ lines = path.read_text(errors="replace").splitlines()
+ except FileNotFoundError:
+ return rows
+ for line in lines[1:]:
+ parts = line.split()
+ if len(parts) <= COL_BRAKE_PRESS:
+ continue # line still being written
+ try:
+ rows.append([float(p) for p in parts[: COL_BRAKE_PRESS + 1]])
+ except ValueError:
+ continue
+ return rows
+
+
+@dataclass
+class RunResult:
+ rows: list[list[float]] = field(default_factory=list)
+ exit_code: int | None = None # None: still running when we closed it (the normal end)
+ timed_out: bool = False
+ wall_seconds: float = 0.0
+
+
+def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog: Path,
+ duration: float, timeout: float) -> RunResult:
+ physicslog.unlink(missing_ok=True)
+ cmd = [str(exe), "-s", scenery, "-v", "ghostview", "-ini", str(ini)]
+ print(" $", " ".join(f'"{c}"' if " " in c else c for c in cmd))
+ started = time.monotonic()
+ proc = subprocess.Popen(cmd, cwd=game_dir)
+ result = RunResult()
+ last_report = 0.0
+ try:
+ while True:
+ time.sleep(1.0)
+ result.rows = read_physicslog(physicslog)
+ sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
+ wall = time.monotonic() - started
+ if wall - last_report >= 15:
+ v = result.rows[-1][COL_VELOCITY] if result.rows else 0.0
+ print(f" ... {wall:5.0f}s wall, sim {sim_t:6.1f}s, v={v:6.1f} km/h")
+ last_report = wall
+ if proc.poll() is not None:
+ result.exit_code = proc.returncode
+ break
+ if sim_t >= duration:
+ break
+ if wall > timeout:
+ result.timed_out = True
+ break
+ finally:
+ if proc.poll() is None:
+ proc.terminate()
+ try:
+ proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ result.wall_seconds = time.monotonic() - started
+ result.rows = read_physicslog(physicslog)
+ return result
+
+
+# ---------------------------------------------------------------- checks
+
+
+def check_starts(rows, min_speed, within):
+ for r in rows:
+ if r[COL_TIME] > within:
+ break
+ if r[COL_VELOCITY] >= min_speed:
+ return True, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s"
+ top = max((r[COL_VELOCITY] for r in rows if r[COL_TIME] <= within), default=0.0)
+ return False, f"top speed in the first {within}s was {top:.1f} km/h, wanted {min_speed}"
+
+
+def check_max_speed(rows, limit, tolerance=0.0):
+ worst = max(rows, key=lambda r: r[COL_VELOCITY])
+ v, t = worst[COL_VELOCITY], worst[COL_TIME]
+ ok = v <= limit + tolerance
+ return ok, f"top speed {v:.1f} km/h at t={t:.1f}s (limit {limit} +{tolerance})"
+
+
+def _first_moving(rows, moving_speed):
+ return next((i for i, r in enumerate(rows) if r[COL_VELOCITY] >= moving_speed), None)
+
+
+def check_brakes(rows, min_pressure, moving_speed=20):
+ start = _first_moving(rows, moving_speed)
+ if start is None:
+ return False, "never moved, so never braked"
+ for r in rows[start:]:
+ if r[COL_BRAKE_PRESS] >= min_pressure:
+ return True, f"brake cylinder {r[COL_BRAKE_PRESS]:.2f} bar at t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h"
+ return False, f"brake cylinder pressure never reached {min_pressure} bar after moving off"
+
+
+def check_stops(rows, moving_speed, stop_speed, hold):
+ start = _first_moving(rows, moving_speed)
+ if start is None:
+ return False, f"never reached {moving_speed} km/h"
+ stopped_at = None
+ for r in rows[start:]:
+ if r[COL_VELOCITY] <= stop_speed:
+ if stopped_at is None:
+ stopped_at = r[COL_TIME]
+ if r[COL_TIME] - stopped_at >= hold:
+ return True, f"came to a stop at t={stopped_at:.1f}s"
+ else:
+ stopped_at = None
+ return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off"
+
+
+CHECKS = {
+ "starts": check_starts,
+ "max_speed": check_max_speed,
+ "brakes": check_brakes,
+ "stops": check_stops,
+}
+
+
+# ---------------------------------------------------------------- main
+
+
+def find_exe(explicit: str | None) -> Path:
+ if explicit:
+ return Path(explicit).resolve()
+ candidates = sorted(REPO.glob("cmake-build-*/bin/Release/eu07*.exe"), key=lambda p: p.stat().st_mtime)
+ if not candidates:
+ sys.exit("no eu07 executable found under cmake-build-*/bin/Release, pass --exe")
+ return candidates[-1]
+
+
+def count_lines(path: Path) -> int:
+ try:
+ return sum(1 for line in path.read_text(errors="replace").splitlines() if line.strip())
+ except FileNotFoundError:
+ return 0
+
+
+def run_case(name: str, exe: Path, game_dir: Path, timespeed: float) -> bool:
+ case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8"))
+ print(f"\n=== {name}: {case.get('description', '')}")
+ out = OUT_DIR / name
+ shutil.rmtree(out, ignore_errors=True)
+ out.mkdir(parents=True)
+
+ scenery = build_scenery(case, game_dir, name)
+ ini = out / "autotest.ini"
+ ini.write_text(TEST_INI.format(timespeed=timespeed), encoding="ascii")
+ physicslog = game_dir / "physicslog" / f"{case['vehicle']}.dat"
+
+ result = run_simulator(exe, game_dir, scenery, ini, physicslog,
+ float(case["duration"]), float(case.get("timeout", 600)))
+
+ for f in ("log.txt", "errors.txt"):
+ if (game_dir / f).exists():
+ shutil.copy2(game_dir / f, out / f)
+ if physicslog.exists():
+ shutil.copy2(physicslog, out / physicslog.name)
+
+ ok = True
+ sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
+ print(f" ran {result.wall_seconds:.0f}s wall, {sim_t:.1f}s of physicslog, results in {out.relative_to(REPO)}")
+ if result.exit_code is not None:
+ print(f" FAIL simulator exited on its own with code {result.exit_code} (crash?)")
+ ok = False
+ if result.timed_out:
+ print(f" FAIL timed out before {case['duration']}s of simulation")
+ ok = False
+ if not result.rows:
+ print(f" FAIL no physicslog for '{case['vehicle']}' ({physicslog})")
+ return False
+
+ for check in case["checks"]:
+ params = {k: v for k, v in check.items() if k != "type"}
+ passed, detail = CHECKS[check["type"]](result.rows, **params)
+ print(f" {'PASS' if passed else 'FAIL'} {check['type']}: {detail}")
+ ok &= passed
+
+ errors = count_lines(out / "errors.txt")
+ if errors:
+ print(f" note errors.txt has {errors} line(s)")
+ if case.get("fail_on_errors") and errors:
+ ok = False
+ return ok
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("cases", nargs="*", help="case names from cases/ (default: all)")
+ ap.add_argument("--game-dir", default=os.environ.get("EU07_GAME_DIR"),
+ help="game install with scenery/ and dynamic/ (or EU07_GAME_DIR)")
+ ap.add_argument("--exe", help="simulator executable (default: newest cmake-build-*/bin/Release/eu07*.exe)")
+ ap.add_argument("--timespeed", type=float, default=1.0, help="simulation time multiplier")
+ args = ap.parse_args()
+
+ if not args.game_dir:
+ sys.exit("pass --game-dir or set EU07_GAME_DIR")
+ game_dir = Path(args.game_dir).resolve()
+ exe = find_exe(args.exe)
+ print(f"exe: {exe}\ngame: {game_dir}")
+
+ names = args.cases or sorted(p.stem for p in CASES_DIR.glob("*.json"))
+ results = {n: run_case(n, exe, game_dir, args.timespeed) for n in names}
+
+ print("\n=== summary")
+ for n, ok in results.items():
+ print(f" {'PASS' if ok else 'FAIL'} {n}")
+ return 0 if all(results.values()) else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
From 6cf8934acb65aec779aea3d0f7a9604f9ef7ec15 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 30 Sep 2026 19:29:10 +0200
Subject: [PATCH 23/60] test: run scenario tests at timespeed 20 by default
eu07_td_timetable now takes about 20 s instead of 4 min. Its speed profile
at 20 and 60 matched a real-time run within a few km/h and seconds; the
physicslog keeps its 0.05 s rows. The runner polls the log every 0.25 s so
it does not overshoot the case duration by a minute of simulation.
---
tests/scenarios/README.md | 5 ++++-
tests/scenarios/run.py | 7 +++++--
2 files changed, 9 insertions(+), 3 deletions(-)
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 77edb5a93..c233154d6 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -18,7 +18,10 @@ Python 3.10+, no extra packages. Options:
- `--exe path/to/eu07.exe` picks the build to test; the default is the newest
`cmake-build-*/bin/Release/eu07*.exe`. The build needs the `-ini` command line option.
- name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`.
-- `--timespeed 4` runs the simulation faster than real time.
+- `--timespeed N` sets the simulation time multiplier, default 20: a 4-minute case runs in
+ about 20 s. Physics still steps finely (the physicslog keeps its 0.05 s rows) and the speed
+ profile at 20 and 60 matched a real-time run within a few km/h and seconds. Use
+ `--timespeed 1` to watch a run.
Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`,
the vehicle's physicslog) land in `tests/scenarios/out//`.
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index ad1f51ee7..b3736a929 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -149,7 +149,7 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
last_report = 0.0
try:
while True:
- time.sleep(1.0)
+ time.sleep(0.25) # at timespeed 20 that is 5 s of simulation
result.rows = read_physicslog(physicslog)
sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
wall = time.monotonic() - started
@@ -308,7 +308,10 @@ def main() -> int:
ap.add_argument("--game-dir", default=os.environ.get("EU07_GAME_DIR"),
help="game install with scenery/ and dynamic/ (or EU07_GAME_DIR)")
ap.add_argument("--exe", help="simulator executable (default: newest cmake-build-*/bin/Release/eu07*.exe)")
- ap.add_argument("--timespeed", type=float, default=1.0, help="simulation time multiplier")
+ # 20 gave the same speed profile as 1 within a few km/h and seconds on eu07_td_timetable,
+ # in 20 s instead of 4 min; 1 is for watching a run
+ ap.add_argument("--timespeed", type=float, default=20.0,
+ help="simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 20)")
args = ap.parse_args()
if not args.game_dir:
From cb0a1223835009fa8e82726170d4cc0afe992a41 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 30 Sep 2026 21:55:16 +0200
Subject: [PATCH 24/60] test: red signal case, seven vehicles on the td.scn
timetable, parallel runs
- eu07_td_red_signal: no route set, the train has to stop before the exit
signal and stay there (new checks stays_stopped and distance; distance
is integrated from the speed, the physicslog has no position)
- en57/ep09/et22/sm42/sn61/vectron/eu07_td_timetable share one fragment
template, td_timetable.scn; a case sets vars.consist and the lead vehicle
is named {{vehicle}} = autotest_
- -j N runs cases in parallel: each case has its own physicslog and, with
multiplelogs, its own log files, which are moved to out//
- a run stops at once on Bad vehicle / Bad trainset instead of waiting for
the timeout, and fails after 120 s without physicslog rows
- the .sbt geometry cache of a test scenery is dropped when the base
scenery is newer
All 8 cases pass in about a minute with -j 4.
---
tests/scenarios/README.md | 35 ++-
tests/scenarios/cases/en57_td_timetable.json | 21 ++
tests/scenarios/cases/ep09_td_timetable.json | 17 ++
tests/scenarios/cases/et22_td_timetable.json | 17 ++
tests/scenarios/cases/eu07_td_red_signal.json | 18 ++
tests/scenarios/cases/eu07_td_timetable.json | 6 +-
tests/scenarios/cases/sm42_td_timetable.json | 17 ++
tests/scenarios/cases/sn61_td_timetable.json | 17 ++
tests/scenarios/cases/td_red_signal.scn | 6 +
...eu07_td_timetable.scn => td_timetable.scn} | 9 +-
.../scenarios/cases/vectron_td_timetable.json | 17 ++
tests/scenarios/run.py | 201 ++++++++++++++----
12 files changed, 332 insertions(+), 49 deletions(-)
create mode 100644 tests/scenarios/cases/en57_td_timetable.json
create mode 100644 tests/scenarios/cases/ep09_td_timetable.json
create mode 100644 tests/scenarios/cases/et22_td_timetable.json
create mode 100644 tests/scenarios/cases/eu07_td_red_signal.json
create mode 100644 tests/scenarios/cases/sm42_td_timetable.json
create mode 100644 tests/scenarios/cases/sn61_td_timetable.json
create mode 100644 tests/scenarios/cases/td_red_signal.scn
rename tests/scenarios/cases/{eu07_td_timetable.scn => td_timetable.scn} (51%)
create mode 100644 tests/scenarios/cases/vectron_td_timetable.json
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index c233154d6..23f793018 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -9,7 +9,7 @@ only, not in CI.
## Running
```
-python tests/scenarios/run.py --game-dir "E:/Program Files (x86)/Steam/steamapps/common/MaSzyna"
+python tests/scenarios/run.py --game-dir "E:/Program Files (x86)/Steam/steamapps/common/MaSzyna" -j 4
```
Python 3.10+, no extra packages. Options:
@@ -18,13 +18,15 @@ Python 3.10+, no extra packages. Options:
- `--exe path/to/eu07.exe` picks the build to test; the default is the newest
`cmake-build-*/bin/Release/eu07*.exe`. The build needs the `-ini` command line option.
- name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`.
+- `-j N` runs N cases at once, each in its own simulator window. Each case prints its
+ results when it is done. All 8 cases take about a minute with `-j 4`.
- `--timespeed N` sets the simulation time multiplier, default 20: a 4-minute case runs in
about 20 s. Physics still steps finely (the physicslog keeps its 0.05 s rows) and the speed
profile at 20 and 60 matched a real-time run within a few km/h and seconds. Use
`--timespeed 1` to watch a run.
Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`,
-the vehicle's physicslog) land in `tests/scenarios/out//`.
+the vehicle's physicslog) are moved to `tests/scenarios/out//`.
## How it works
@@ -35,11 +37,19 @@ For each case the runner:
fragment added: its trainsets after `FirstInit`, everything else (event launchers standing
in for keys the scenery expects a player to press, extra events) before it,
2. starts the simulator with `-s autotest_.scn -v ghostview -ini out//autotest.ini`;
- ghostview leaves every train to the AI, and the extra ini turns on `physicslog`,
- runs in a 1280x720 window and does not pause when the window loses focus,
-3. waits until `physicslog/.dat` covers `duration` seconds, then closes the simulator,
+ ghostview leaves every train to the AI, and the extra ini turns on `physicslog`, runs in a
+ 1280x720 window, does not pause when the window loses focus, and writes the logs to
+ `logs/log (autotest_) .txt` rather than the shared `log.txt` (`multiplelogs`),
+3. waits until `physicslog/autotest_.dat` covers `duration` seconds, then closes the
+ simulator. It gives up early when the log reports `Bad vehicle` / `Bad trainset`, or when
+ the scenario has loaded and no physicslog appeared,
4. runs the checks on the physicslog.
+The lead vehicle is named `autotest_`, so every case has its own physicslog and log
+files and cases can run in parallel. The `autotest_*` sceneries (and the simulator's `.sbt`
+geometry cache of them) stay in the game's `scenery/` dir; the cache is dropped when the base
+scenery is newer.
+
## Writing a case
`cases/.json`:
@@ -50,13 +60,19 @@ For each case the runner:
| `strip_trainsets` | drop the base scenery's trainsets (default `true`) |
| `time` | replace the scenery start time, `HH:MM` |
| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) |
-| `vehicle` | node name of the vehicle whose physicslog is checked |
+| `vars` | values for `{{name}}` in the fragment; a list becomes one line per item |
| `duration` | seconds of simulation to record |
| `timeout` | wall-clock seconds before giving up, loading included |
| `fail_on_errors` | fail when `errors.txt` is not empty (default `false`) |
| `checks` | list of checks, below |
-Checks (speeds in km/h, times in seconds of physicslog time):
+`{{vehicle}}` is always set, also inside `vars` values: the node name of the lead vehicle,
+the one whose physicslog is checked. Other vehicles of the consist take names made from it,
+e.g. `{{vehicle}}_s`. The td.scn cases share two fragments, `td_timetable.scn` (route set,
+train runs to Przystanek) and `td_red_signal.scn` (no route, exit signal at stop), and differ
+only in `vars.consist`.
+
+Checks (speeds in km/h, times in seconds of physicslog time, distances in metres):
- `starts` `min_speed`, `within`: reaches `min_speed` within `within` seconds.
- `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`.
@@ -64,6 +80,11 @@ Checks (speeds in km/h, times in seconds of physicslog time):
(physicslog pressures are in bar whatever its header says; the brake pipe runs at 5.0).
- `stops` `moving_speed`, `stop_speed`, `hold`: after reaching `moving_speed`, stays at or
below `stop_speed` for `hold` seconds.
+- `stays_stopped` `moving_speed`, `stop_speed`: after moving off and stopping, never goes
+ above `stop_speed` again.
+- `distance` `min`, `max`: total distance travelled. The physicslog has no position, so the
+ distance comes from integrating the speed; on td.scn every vehicle's first stop after
+ Stacja1 came out at 1400 m (+-3), and the red signal stop at 140 m.
New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's
parameters and returns `(passed, detail)`.
diff --git a/tests/scenarios/cases/en57_td_timetable.json b/tests/scenarios/cases/en57_td_timetable.json
new file mode 100644
index 000000000..ddd52af37
--- /dev/null
+++ b/tests/scenarios/cases/en57_td_timetable.json
@@ -0,0 +1,21 @@
+{
+ "description": "EN57 EMU (three cars) on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": [
+ "node -1 0 {{vehicle}} dynamic pkp\\en57_v2 EN57-1000ra EN57RA_GSO_WKM1_KM_NS_N 0 headdriver 255 0 enddynamic",
+ "node -1 0 {{vehicle}}_s dynamic pkp\\en57_v2 EN57-1000s EN57S_WKM1_KM_NS_S 0 nobody 255 0 enddynamic",
+ "node -1 0 {{vehicle}}_rb dynamic pkp\\en57_v2 EN57-1000rb EN57RB_GSO_WKM1_KM_NS 0 nobody 0 0 enddynamic"
+ ]
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/ep09_td_timetable.json b/tests/scenarios/cases/ep09_td_timetable.json
new file mode 100644
index 000000000..dd130be3c
--- /dev/null
+++ b/tests/scenarios/cases/ep09_td_timetable.json
@@ -0,0 +1,17 @@
+{
+ "description": "EP09 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\ep09_v1 104e-005 104e_3 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/et22_td_timetable.json b/tests/scenarios/cases/et22_td_timetable.json
new file mode 100644
index 000000000..004f5354d
--- /dev/null
+++ b/tests/scenarios/cases/et22_td_timetable.json
@@ -0,0 +1,17 @@
+{
+ "description": "ET22 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\et22_v3 201E-1150 201E 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/eu07_td_red_signal.json b/tests/scenarios/cases/eu07_td_red_signal.json
new file mode 100644
index 000000000..b02acdc81
--- /dev/null
+++ b/tests/scenarios/cases/eu07_td_red_signal.json
@@ -0,0 +1,18 @@
+{
+ "description": "EU07 on td.scn with no route set: pulls off, stops before the exit signal stacja1_j at stop, and stays there.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 5, "within": 150 },
+ { "type": "max_speed", "limit": 40 },
+ { "type": "stops", "moving_speed": 5, "stop_speed": 0.5, "hold": 5 },
+ { "type": "stays_stopped", "moving_speed": 5, "stop_speed": 0.5 },
+ { "type": "distance", "max": 150 }
+ ]
+}
diff --git a/tests/scenarios/cases/eu07_td_timetable.json b/tests/scenarios/cases/eu07_td_timetable.json
index c12b8ae71..2f23019fe 100644
--- a/tests/scenarios/cases/eu07_td_timetable.json
+++ b/tests/scenarios/cases/eu07_td_timetable.json
@@ -2,8 +2,10 @@
"description": "EU07 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
"base_scenery": "td.scn",
"time": "10:34",
- "fragment": "eu07_td_timetable.scn",
- "vehicle": "autotest_eu07",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
"duration": 240,
"timeout": 600,
"checks": [
diff --git a/tests/scenarios/cases/sm42_td_timetable.json b/tests/scenarios/cases/sm42_td_timetable.json
new file mode 100644
index 000000000..fc89be0fa
--- /dev/null
+++ b/tests/scenarios/cases/sm42_td_timetable.json
@@ -0,0 +1,17 @@
+{
+ "description": "SM42 diesel shunter on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\sm42_v1 6D-468 6D 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/sn61_td_timetable.json b/tests/scenarios/cases/sn61_td_timetable.json
new file mode 100644
index 000000000..1db425c80
--- /dev/null
+++ b/tests/scenarios/cases/sn61_td_timetable.json
@@ -0,0 +1,17 @@
+{
+ "description": "SN61 diesel railcar on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\sn61_v2 SN61-13 SN61_v1 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/cases/td_red_signal.scn b/tests/scenarios/cases/td_red_signal.scn
new file mode 100644
index 000000000..981707085
--- /dev/null
+++ b/tests/scenarios/cases/td_red_signal.scn
@@ -0,0 +1,6 @@
+// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed.
+// same start as td_timetable.scn, but nobody sets the route: the exit signal stacja1_j,
+// about 150 m ahead of the train, stays at stop.
+trainset td/rozklad tdo_n1734 0.0 0.1
+{{consist}}
+endtrainset
diff --git a/tests/scenarios/cases/eu07_td_timetable.scn b/tests/scenarios/cases/td_timetable.scn
similarity index 51%
rename from tests/scenarios/cases/eu07_td_timetable.scn
rename to tests/scenarios/cases/td_timetable.scn
index c8044e467..e67dcf9ad 100644
--- a/tests/scenarios/cases/eu07_td_timetable.scn
+++ b/tests/scenarios/cases/td_timetable.scn
@@ -1,11 +1,12 @@
-// added by tests/scenarios/run.py to the base scenery, whose own trainsets were removed:
+// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed:
// the trainset goes after FirstInit, the launcher before it.
-// the EU07 stands where td.scn keeps its timetable train and gets the same timetable.
+// the case's consist stands where td.scn keeps its timetable train (track 1 of Stacja1)
+// and gets the same timetable: Stacja1 10:35 -> Przystanek -> Stacja2.
trainset td/rozklad tdo_n1734 0.0 0.1
-node -1 0 autotest_eu07 dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic
+{{consist}}
endtrainset
// td.scn sets routes from the keyboard (shift+1..4 run events keyctrl01..04). keyctrl04 is the
-// way out of the track the train stands on: switch zwr02 and the exit signal stacja1_j at 40.
+// way out of track 1: switch zwr02 and the exit signal stacja1_j at 40.
// a launcher with a positive time fires once at that hour (HHMM), radius -1 means anywhere.
node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end
diff --git a/tests/scenarios/cases/vectron_td_timetable.json b/tests/scenarios/cases/vectron_td_timetable.json
new file mode 100644
index 000000000..9948a09ef
--- /dev/null
+++ b/tests/scenarios/cases/vectron_td_timetable.json
@@ -0,0 +1,17 @@
+{
+ "description": "Vectron 1293-107 on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_timetable.scn",
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\vectron_v1 1293-107 wariant_7w 0 headdriver 0 0 enddynamic"
+ },
+ "duration": 240,
+ "timeout": 600,
+ "checks": [
+ { "type": "starts", "min_speed": 20, "within": 150 },
+ { "type": "max_speed", "limit": 90, "tolerance": 3 },
+ { "type": "brakes", "min_pressure": 0.5 },
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ ]
+}
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index b3736a929..419906700 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -2,11 +2,11 @@
"""Scenario tests: run the real simulator on a scenery and check what a vehicle did.
A case (cases/.json) names a base scenery from the game install, a fragment
-appended to it (usually a trainset with an AI driver), and checks on the vehicle's
+added to it (usually a trainset with an AI driver), and checks on the vehicle's
physics log. The runner:
1. builds scenery/autotest_.scn in the game dir: the base scenery with its own
- trainsets removed, optionally a different start time, and the case fragment appended,
+ trainsets removed, optionally a different start time, and the case fragment added,
2. starts eu07 with that scenery in ghostview (every train driven by AI) and an extra
settings file (-ini) that turns on physicslog and runs in a window,
3. waits until the vehicle's physicslog covers `duration` seconds of simulation,
@@ -14,10 +14,10 @@ physics log. The runner:
4. evaluates the checks on the log and prints PASS/FAIL per check.
Scenery and vehicle data are not part of this repo, so this runs against a local game
-install only (--game-dir or EU07_GAME_DIR), not in CI.
+install only (--game-dir or EU07_GAME_DIR), not in CI. See README.md.
Usage:
- python tests/scenarios/run.py --game-dir "E:/.../MaSzyna" # all cases
+ python tests/scenarios/run.py --game-dir "E:/.../MaSzyna" -j 4 # all cases
python tests/scenarios/run.py --game-dir ... eu07_td_timetable # chosen cases
"""
@@ -31,6 +31,7 @@ import shutil
import subprocess
import sys
import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from pathlib import Path
@@ -54,9 +55,11 @@ height 720
inactivepause no
soundenabled no
physicslog yes
-multiplelogs no
+multiplelogs yes
timespeed {timespeed}
"""
+# multiplelogs: log and errors go to logs/log () .txt instead of the shared
+# log.txt, so runs of different cases can go in parallel
# ---------------------------------------------------------------- scenery
@@ -83,7 +86,19 @@ def set_start_time(text: str, hhmm: str) -> str:
return re.sub(r"(?im)^(\s*time\s+)\d{1,2}:\d{2}", lambda m: m.group(1) + hhmm, text, count=1)
-def build_scenery(case: dict, game_dir: Path, case_name: str) -> str:
+def fill_vars(fragment: str, values: dict, keep=frozenset()) -> str:
+ """Replaces {{name}} with the case's value; a list value becomes one line per item."""
+ def value(m):
+ if m.group(1) in keep:
+ return m.group(0)
+ v = values.get(m.group(1))
+ if v is None:
+ sys.exit(f"fragment uses {{{{{m.group(1)}}}}} but the case sets no such var")
+ return "\n".join(v) if isinstance(v, list) else str(v)
+ return re.sub(r"\{\{(\w+)\}\}", value, fragment)
+
+
+def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> str:
"""Writes the case scenery into the game's scenery dir and returns its file name."""
scenery_dir = game_dir / "scenery"
# sceneries are cp1250; latin-1 round-trips every byte, so nothing gets mangled
@@ -93,6 +108,9 @@ def build_scenery(case: dict, game_dir: Path, case_name: str) -> str:
if "time" in case:
text = set_start_time(text, case["time"])
fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1")
+ # vars first: {{vehicle}} inside a var's value gets filled in the second pass
+ fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"})
+ fragment = fill_vars(fragment, {"vehicle": vehicle})
# FirstInit binds event launchers to their events and links the tracks. so launchers and
# events of the case go in before it (read after it they never fire), trainsets after it
# (placed before it they stand on unlinked track and derail at once)
@@ -106,6 +124,12 @@ def build_scenery(case: dict, game_dir: Path, case_name: str) -> str:
text += header + trainsets + "\n"
name = f"autotest_{case_name}.scn"
(scenery_dir / name).write_bytes(text.encode("latin-1"))
+ # the simulator caches the scenery's static geometry in .sbt and reads it instead of
+ # the terrain in the .scn (tracks, events and trainsets always come from the .scn), so
+ # drop the cache once the base scenery has changed
+ cache = scenery_dir / f"autotest_{case_name}.sbt"
+ if cache.exists() and cache.stat().st_mtime < (scenery_dir / case["base_scenery"]).stat().st_mtime:
+ cache.unlink()
return name
@@ -130,19 +154,47 @@ def read_physicslog(path: Path) -> list[list[float]]:
return rows
+def find_logs(game_dir: Path, scenery: str, since: float) -> dict[str, Path]:
+ """The log.txt / errors.txt of one run; with multiplelogs each scenery gets its own files."""
+ stem = scenery.rsplit(".", 1)[0]
+ found = {}
+ for kind in ("log", "errors"):
+ files = [p for p in (game_dir / "logs").glob(f"{kind} ({stem}) *.txt") if p.stat().st_mtime >= since]
+ if files:
+ found[kind] = max(files, key=lambda p: p.stat().st_mtime)
+ return found
+
+
+def read_text(path: Path | None) -> str:
+ try:
+ return path.read_text(errors="replace") if path else ""
+ except FileNotFoundError:
+ return ""
+
+
+# load problems that leave the case without its vehicle; no point waiting for the timeout
+FATAL_LOG_LINES = ("Bad vehicle:", "Bad trainset:")
+# wall seconds from start to the first physicslog row before giving up. "Scenario loading
+# time" in the log is not the end of loading (the trainsets after FirstInit still follow),
+# and with several simulators loading at once the first rows took well over 15 s
+STARTUP_TIMEOUT = 120.0
+
+
@dataclass
class RunResult:
rows: list[list[float]] = field(default_factory=list)
exit_code: int | None = None # None: still running when we closed it (the normal end)
- timed_out: bool = False
+ failure: str = "" # why the run was cut short
wall_seconds: float = 0.0
+ logs: dict[str, Path] = field(default_factory=dict)
def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog: Path,
- duration: float, timeout: float) -> RunResult:
+ duration: float, timeout: float, say) -> RunResult:
physicslog.unlink(missing_ok=True)
cmd = [str(exe), "-s", scenery, "-v", "ghostview", "-ini", str(ini)]
- print(" $", " ".join(f'"{c}"' if " " in c else c for c in cmd))
+ say(" $ " + " ".join(f'"{c}"' if " " in c else c for c in cmd), progress=True)
+ since = time.time() - 1
started = time.monotonic()
proc = subprocess.Popen(cmd, cwd=game_dir)
result = RunResult()
@@ -150,12 +202,12 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
try:
while True:
time.sleep(0.25) # at timespeed 20 that is 5 s of simulation
+ wall = time.monotonic() - started
result.rows = read_physicslog(physicslog)
sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
- wall = time.monotonic() - started
if wall - last_report >= 15:
v = result.rows[-1][COL_VELOCITY] if result.rows else 0.0
- print(f" ... {wall:5.0f}s wall, sim {sim_t:6.1f}s, v={v:6.1f} km/h")
+ say(f" ... {wall:5.0f}s wall, sim {sim_t:6.1f}s, v={v:6.1f} km/h", progress=True)
last_report = wall
if proc.poll() is not None:
result.exit_code = proc.returncode
@@ -163,8 +215,18 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
if sim_t >= duration:
break
if wall > timeout:
- result.timed_out = True
+ result.failure = f"timed out after {timeout:.0f}s before {duration}s of simulation"
break
+ if not result.rows:
+ result.logs = find_logs(game_dir, scenery, since)
+ fatal = [l.strip() for l in read_text(result.logs.get("errors")).splitlines()
+ if any(k in l for k in FATAL_LOG_LINES)]
+ if fatal:
+ result.failure = "vehicle failed to load: " + " | ".join(fatal)
+ break
+ if wall > STARTUP_TIMEOUT:
+ result.failure = f"no physicslog rows after {STARTUP_TIMEOUT:.0f}s"
+ break
finally:
if proc.poll() is None:
proc.terminate()
@@ -174,6 +236,7 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
proc.kill()
result.wall_seconds = time.monotonic() - started
result.rows = read_physicslog(physicslog)
+ result.logs = find_logs(game_dir, scenery, since)
return result
@@ -201,6 +264,15 @@ def _first_moving(rows, moving_speed):
return next((i for i, r in enumerate(rows) if r[COL_VELOCITY] >= moving_speed), None)
+def _distances(rows):
+ """Metres travelled up to each row, from the speed; the physicslog has no position."""
+ out, d = [0.0], 0.0
+ for a, b in zip(rows, rows[1:]):
+ d += (a[COL_VELOCITY] + b[COL_VELOCITY]) / 2 / 3.6 * (b[COL_TIME] - a[COL_TIME])
+ out.append(d)
+ return out
+
+
def check_brakes(rows, min_pressure, moving_speed=20):
start = _first_moving(rows, moving_speed)
if start is None:
@@ -215,23 +287,49 @@ def check_stops(rows, moving_speed, stop_speed, hold):
start = _first_moving(rows, moving_speed)
if start is None:
return False, f"never reached {moving_speed} km/h"
+ dist = _distances(rows)
stopped_at = None
- for r in rows[start:]:
+ for i in range(start, len(rows)):
+ r = rows[i]
if r[COL_VELOCITY] <= stop_speed:
if stopped_at is None:
- stopped_at = r[COL_TIME]
- if r[COL_TIME] - stopped_at >= hold:
- return True, f"came to a stop at t={stopped_at:.1f}s"
+ stopped_at = i
+ if r[COL_TIME] - rows[stopped_at][COL_TIME] >= hold:
+ return True, f"came to a stop at t={rows[stopped_at][COL_TIME]:.1f}s after {dist[stopped_at]:.0f} m"
else:
stopped_at = None
return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off"
+def check_stays_stopped(rows, moving_speed, stop_speed):
+ """Once stopped after moving off, never moves again (e.g. waiting at a red signal)."""
+ start = _first_moving(rows, moving_speed)
+ if start is None:
+ return False, f"never reached {moving_speed} km/h"
+ stop = next((i for i in range(start, len(rows)) if rows[i][COL_VELOCITY] <= stop_speed), None)
+ if stop is None:
+ return False, f"never came down to {stop_speed} km/h"
+ moved = next((r for r in rows[stop:] if r[COL_VELOCITY] > stop_speed), None)
+ if moved is not None:
+ return False, f"stopped at t={rows[stop][COL_TIME]:.1f}s but moved again at t={moved[COL_TIME]:.1f}s, v={moved[COL_VELOCITY]:.1f} km/h"
+ return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s and stayed until t={rows[-1][COL_TIME]:.1f}s"
+
+
+def check_distance(rows, max=None, min=None):
+ """Total distance travelled, in metres."""
+ d = _distances(rows)[-1]
+ ok = (max is None or d <= max) and (min is None or d >= min)
+ bounds = " ".join(s for s in (f">= {min}" if min is not None else "", f"<= {max}" if max is not None else "") if s)
+ return ok, f"travelled {d:.0f} m (wanted {bounds})"
+
+
CHECKS = {
"starts": check_starts,
"max_speed": check_max_speed,
"brakes": check_brakes,
"stops": check_stops,
+ "stays_stopped": check_stays_stopped,
+ "distance": check_distance,
}
@@ -254,49 +352,52 @@ def count_lines(path: Path) -> int:
return 0
-def run_case(name: str, exe: Path, game_dir: Path, timespeed: float) -> bool:
+def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, say) -> bool:
case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8"))
- print(f"\n=== {name}: {case.get('description', '')}")
+ say(f"\n=== {name}: {case.get('description', '')}")
out = OUT_DIR / name
shutil.rmtree(out, ignore_errors=True)
out.mkdir(parents=True)
- scenery = build_scenery(case, game_dir, name)
+ # the lead vehicle is named after the case, so parallel runs never share a physicslog
+ vehicle = f"autotest_{name}"
+ scenery = build_scenery(case, game_dir, name, vehicle)
ini = out / "autotest.ini"
ini.write_text(TEST_INI.format(timespeed=timespeed), encoding="ascii")
- physicslog = game_dir / "physicslog" / f"{case['vehicle']}.dat"
+ physicslog = game_dir / "physicslog" / f"{vehicle}.dat"
result = run_simulator(exe, game_dir, scenery, ini, physicslog,
- float(case["duration"]), float(case.get("timeout", 600)))
+ float(case["duration"]), float(case.get("timeout", 600)), say)
- for f in ("log.txt", "errors.txt"):
- if (game_dir / f).exists():
- shutil.copy2(game_dir / f, out / f)
+ # the logs are ours alone (named after the case scenery), move them out of the game dir
+ for kind, path in result.logs.items():
+ shutil.move(path, out / f"{kind}.txt")
if physicslog.exists():
- shutil.copy2(physicslog, out / physicslog.name)
+ shutil.move(physicslog, out / physicslog.name)
ok = True
sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
- print(f" ran {result.wall_seconds:.0f}s wall, {sim_t:.1f}s of physicslog, results in {out.relative_to(REPO)}")
+ say(f" ran {result.wall_seconds:.0f}s wall, {sim_t:.1f}s of physicslog, results in {out.relative_to(REPO)}")
if result.exit_code is not None:
- print(f" FAIL simulator exited on its own with code {result.exit_code} (crash?)")
+ say(f" FAIL simulator exited on its own with code {result.exit_code}")
ok = False
- if result.timed_out:
- print(f" FAIL timed out before {case['duration']}s of simulation")
+ if result.failure:
+ say(f" FAIL {result.failure}")
ok = False
if not result.rows:
- print(f" FAIL no physicslog for '{case['vehicle']}' ({physicslog})")
+ if not result.failure:
+ say(f" FAIL no physicslog for '{vehicle}'")
return False
for check in case["checks"]:
params = {k: v for k, v in check.items() if k != "type"}
passed, detail = CHECKS[check["type"]](result.rows, **params)
- print(f" {'PASS' if passed else 'FAIL'} {check['type']}: {detail}")
+ say(f" {'PASS' if passed else 'FAIL'} {check['type']}: {detail}")
ok &= passed
errors = count_lines(out / "errors.txt")
if errors:
- print(f" note errors.txt has {errors} line(s)")
+ say(f" note errors.txt has {errors} line(s)")
if case.get("fail_on_errors") and errors:
ok = False
return ok
@@ -312,6 +413,8 @@ def main() -> int:
# in 20 s instead of 4 min; 1 is for watching a run
ap.add_argument("--timespeed", type=float, default=20.0,
help="simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 20)")
+ ap.add_argument("-j", "--jobs", type=int, default=1,
+ help="cases run at once, each in its own simulator window (default 1)")
args = ap.parse_args()
if not args.game_dir:
@@ -321,11 +424,37 @@ def main() -> int:
print(f"exe: {exe}\ngame: {game_dir}")
names = args.cases or sorted(p.stem for p in CASES_DIR.glob("*.json"))
- results = {n: run_case(n, exe, game_dir, args.timespeed) for n in names}
+ missing = [n for n in names if not (CASES_DIR / f"{n}.json").exists()]
+ if missing:
+ sys.exit("no such case: " + ", ".join(missing))
- print("\n=== summary")
- for n, ok in results.items():
- print(f" {'PASS' if ok else 'FAIL'} {n}")
+ started = time.monotonic()
+ results = {}
+ if args.jobs <= 1:
+ def say(line, progress=False):
+ print(line, flush=True)
+ for n in names:
+ results[n] = run_case(n, exe, game_dir, args.timespeed, say)
+ else:
+ # each case prints its block when it is done, so parallel output does not interleave
+ def job(n):
+ lines = []
+ def say(line, progress=False):
+ if not progress:
+ lines.append(line)
+ ok = run_case(n, exe, game_dir, args.timespeed, say)
+ return n, ok, lines
+ with ThreadPoolExecutor(max_workers=args.jobs) as pool:
+ for n in names:
+ print(f"started {n}", flush=True)
+ for fut in as_completed([pool.submit(job, n) for n in names]):
+ n, ok, lines = fut.result()
+ print("\n".join(lines), flush=True)
+ results[n] = ok
+
+ print(f"\n=== summary ({time.monotonic() - started:.0f}s)")
+ for n in names:
+ print(f" {'PASS' if results[n] else 'FAIL'} {n}")
return 0 if all(results.values()) else 1
From 219836b4648020de36f1ccf7dc7d7edc71b8e2a6 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 14 Oct 2026 13:55:06 +0200
Subject: [PATCH 25/60] test: track_friction case key for slippery rail
scenarios
---
tests/scenarios/README.md | 1 +
tests/scenarios/run.py | 8 ++++++++
2 files changed, 9 insertions(+)
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 23f793018..463086cc5 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -59,6 +59,7 @@ scenery is newer.
| `base_scenery` | scenery file in the game's `scenery/` dir |
| `strip_trainsets` | drop the base scenery's trainsets (default `true`) |
| `time` | replace the scenery start time, `HH:MM` |
+| `track_friction` | set the friction of every track of the base scenery (default in the sceneries is 0.15), e.g. for slippery rail |
| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) |
| `vars` | values for `{{name}}` in the fragment; a list becomes one line per item |
| `duration` | seconds of simulation to record |
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 419906700..32be5dfc0 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -86,6 +86,12 @@ def set_start_time(text: str, hhmm: str) -> str:
return re.sub(r"(?im)^(\s*time\s+)\d{1,2}:\d{2}", lambda m: m.group(1) + hhmm, text, count=1)
+def set_track_friction(text: str, friction: float) -> str:
+ """Sets the friction of every track: node track ..."""
+ return re.sub(r"(?im)^(\s*node\s+\S+\s+\S+\s+\S+\s+track\s+\S+\s+\S+\s+\S+\s+)[-\d.]+",
+ lambda m: m.group(1) + f"{friction}", text)
+
+
def fill_vars(fragment: str, values: dict, keep=frozenset()) -> str:
"""Replaces {{name}} with the case's value; a list value becomes one line per item."""
def value(m):
@@ -107,6 +113,8 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s
text, _ = split_trainsets(text)
if "time" in case:
text = set_start_time(text, case["time"])
+ if "track_friction" in case:
+ text = set_track_friction(text, case["track_friction"])
fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1")
# vars first: {{vehicle}} inside a var's value gets filled in the second pass
fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"})
From fe9e2f77c24f71d965fd3d6c11478840c6f659e8 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 14 Oct 2026 14:11:54 +0200
Subject: [PATCH 26/60] feat(log): vehicle speed column in the physicslog
The Velocity column is the wheel speed, which stays at 0 while the wheels
are locked in a skid, so a vehicle sliding on locked wheels looked as if
it stood still. Add the signed vehicle speed in km/h as the last column.
---
vehicle/Driver.cpp | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 08f0c0d24..c5f5f51e9 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -1880,7 +1880,8 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche,
<< "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] "
<< "MCP SCP BCP LBP Direction Command CVal1 CVal2 "
<< "Security Wheelslip "
- << "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]"
+ << "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] "
+ << "VehicleVelocity[km/h]"
<< "\r\n";
LogFile << std::fixed << std::setprecision( 4 );
#endif
@@ -4817,7 +4818,9 @@ void TController::PhysicsLog()
<< mvControlling->dizel_heat.Ts << " "
<< mvControlling->dizel_heat.To << " "
<< mvControlling->dizel_heat.temperatura1 << " "
- << mvControlling->dizel_heat.temperatura2
+ << mvControlling->dizel_heat.temperatura2 << " "
+ // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid
+ << mvOccupied->V * 3.6
<< "\r\n";
#endif
#if LOGPRESS == 1
From 6209e165583b841b61d4ec9a99b2d69b2e0db5c2 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Wed, 14 Oct 2026 14:11:54 +0200
Subject: [PATCH 27/60] test: slippery rail skid cases, wheelslip and vehicle
speed checks
- physicslog rows keep all columns (text ones as None), checks can read
the wheelslip flag and the new vehicle speed column
- slips: the lead vehicle's wheels slip at some point (makes sure a
slippery rail case does what it's meant to)
- slip_clears: once stopped, the wheels stop slipping within N seconds
- holds_still: once stopped, the vehicle doesn't creep, by vehicle speed
- td_red_signal_moving.scn: the red signal case starting already moving
- eu07_slippery_red_signal / eu07_slippery_push_red_signal: skid on
braking for the red signal with track friction 0.03; the pushing one
fails without the fix for eu07/maszyna#479 (stays skidding, creeps)
- sn61_td_timetable: stop hold 5 -> 2 s, the railcar arrives 5-7 s
before its departure time, so 5 s made the case flaky
---
tests/scenarios/README.md | 14 +++-
.../cases/eu07_slippery_push_red_signal.json | 36 ++++++++++
.../cases/eu07_slippery_red_signal.json | 36 ++++++++++
tests/scenarios/cases/sn61_td_timetable.json | 2 +-
.../scenarios/cases/td_red_signal_moving.scn | 6 ++
tests/scenarios/run.py | 68 ++++++++++++++++++-
6 files changed, 156 insertions(+), 6 deletions(-)
create mode 100644 tests/scenarios/cases/eu07_slippery_push_red_signal.json
create mode 100644 tests/scenarios/cases/eu07_slippery_red_signal.json
create mode 100644 tests/scenarios/cases/td_red_signal_moving.scn
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 463086cc5..4600a3577 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -71,9 +71,13 @@ scenery is newer.
the one whose physicslog is checked. Other vehicles of the consist take names made from it,
e.g. `{{vehicle}}_s`. The td.scn cases share two fragments, `td_timetable.scn` (route set,
train runs to Przystanek) and `td_red_signal.scn` (no route, exit signal at stop), and differ
-only in `vars.consist`.
+only in `vars.consist`. `td_red_signal_moving.scn` is the red signal one with the train
+starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels when braking.
-Checks (speeds in km/h, times in seconds of physicslog time, distances in metres):
+Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use
+the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are
+locked in a skid. The ones marked *vehicle speed* use the vehicle speed column at the end of
+the row instead, logged by builds from this branch on.
- `starts` `min_speed`, `within`: reaches `min_speed` within `within` seconds.
- `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`.
@@ -86,6 +90,12 @@ Checks (speeds in km/h, times in seconds of physicslog time, distances in metres
- `distance` `min`, `max`: total distance travelled. The physicslog has no position, so the
distance comes from integrating the speed; on td.scn every vehicle's first stop after
Stacja1 came out at 1400 m (+-3), and the red signal stop at 140 m.
+- `slips` `within`: the lead vehicle's wheels slip or lock at some point (within `within`
+ seconds if given), so a slippery rail case does what it's meant to.
+- `slip_clears` `moving_speed`, `stop_speed`, `within` (*vehicle speed*): once stopped after
+ moving off, the wheels stop slipping within `within` seconds.
+- `holds_still` `moving_speed`, `stop_speed`, `max_distance` (*vehicle speed*): once stopped
+ after moving off, moves no more than `max_distance` metres, e.g. no creeping on locked wheels.
New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's
parameters and returns `(passed, detail)`.
diff --git a/tests/scenarios/cases/eu07_slippery_push_red_signal.json b/tests/scenarios/cases/eu07_slippery_push_red_signal.json
new file mode 100644
index 000000000..f7ae10bb7
--- /dev/null
+++ b/tests/scenarios/cases/eu07_slippery_push_red_signal.json
@@ -0,0 +1,36 @@
+{
+ "description": "EU07 pushing three coaches on td.scn with slippery rail and no route set, starting at 30 km/h: brakes for the exit signal at stop and skids. Pushed by the train it doesn't roll back at the stop, so it used to stay skidding on locked wheels with the brakes capped by the sliding adhesion and creep (eu07/maszyna#479).",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "track_friction": 0.03,
+ "fragment": "td_red_signal_moving.scn",
+ "vars": {
+ "velocity": "30",
+ "consist": [
+ "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic",
+ "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic",
+ "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic",
+ "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ ]
+ },
+ "duration": 240,
+ "timeout": 900,
+ "checks": [
+ {
+ "type": "slips",
+ "within": 60
+ },
+ {
+ "type": "slip_clears",
+ "moving_speed": 5,
+ "stop_speed": 0.05,
+ "within": 5
+ },
+ {
+ "type": "holds_still",
+ "moving_speed": 5,
+ "stop_speed": 0.05,
+ "max_distance": 0.01
+ }
+ ]
+}
diff --git a/tests/scenarios/cases/eu07_slippery_red_signal.json b/tests/scenarios/cases/eu07_slippery_red_signal.json
new file mode 100644
index 000000000..40b5944eb
--- /dev/null
+++ b/tests/scenarios/cases/eu07_slippery_red_signal.json
@@ -0,0 +1,36 @@
+{
+ "description": "EU07 with three coaches on td.scn with slippery rail and no route set, starting at 30 km/h: brakes for the exit signal at stop and skids, then the skid ends and the train holds still.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "track_friction": 0.03,
+ "fragment": "td_red_signal_moving.scn",
+ "vars": {
+ "velocity": "30",
+ "consist": [
+ "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic",
+ "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic",
+ "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic",
+ "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic"
+ ]
+ },
+ "duration": 240,
+ "timeout": 900,
+ "checks": [
+ {
+ "type": "slips",
+ "within": 60
+ },
+ {
+ "type": "slip_clears",
+ "moving_speed": 5,
+ "stop_speed": 0.05,
+ "within": 5
+ },
+ {
+ "type": "holds_still",
+ "moving_speed": 5,
+ "stop_speed": 0.05,
+ "max_distance": 0.01
+ }
+ ]
+}
diff --git a/tests/scenarios/cases/sn61_td_timetable.json b/tests/scenarios/cases/sn61_td_timetable.json
index 1db425c80..9fa4b18d8 100644
--- a/tests/scenarios/cases/sn61_td_timetable.json
+++ b/tests/scenarios/cases/sn61_td_timetable.json
@@ -12,6 +12,6 @@
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "max_speed", "limit": 90, "tolerance": 3 },
{ "type": "brakes", "min_pressure": 0.5 },
- { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 2 }
]
}
diff --git a/tests/scenarios/cases/td_red_signal_moving.scn b/tests/scenarios/cases/td_red_signal_moving.scn
new file mode 100644
index 000000000..648e5d90a
--- /dev/null
+++ b/tests/scenarios/cases/td_red_signal_moving.scn
@@ -0,0 +1,6 @@
+// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed.
+// like td_red_signal.scn (no route, the exit signal stacja1_j about 150 m ahead stays at stop),
+// but the train starts already moving at {{velocity}} km/h, so it has to brake right away.
+trainset td/rozklad tdo_n1734 0.0 {{velocity}}
+{{consist}}
+endtrainset
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 32be5dfc0..2cd754a06 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -43,8 +43,11 @@ OUT_DIR = HERE / "out"
# physicslog columns, see TController::PhysicsLog() in vehicle/Driver.cpp.
# Velocity is in km/h and pressures in bar, despite the header saying m/s and MPa.
COL_TIME = 0
-COL_VELOCITY = 1
+COL_VELOCITY = 1 # wheel speed: stays at 0 while the wheels are locked in a skid
COL_BRAKE_PRESS = 8
+COL_COMMAND = 16 # text, read as None
+COL_WHEELSLIP = 20
+COL_VEHICLE_VELOCITY = 25 # signed vehicle speed, km/h; only in builds which log it
# settings layered over the user's eu07.ini for a test run
TEST_INI = """\
@@ -145,7 +148,7 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s
def read_physicslog(path: Path) -> list[list[float]]:
- """Returns rows of numeric columns up to BrakePress; skips the header and partial lines."""
+ """Returns rows of columns, None for the text ones; skips the header and partial lines."""
rows = []
try:
lines = path.read_text(errors="replace").splitlines()
@@ -156,9 +159,15 @@ def read_physicslog(path: Path) -> list[list[float]]:
if len(parts) <= COL_BRAKE_PRESS:
continue # line still being written
try:
- rows.append([float(p) for p in parts[: COL_BRAKE_PRESS + 1]])
+ row = [float(p) for p in parts[: COL_BRAKE_PRESS + 1]]
except ValueError:
continue
+ for p in parts[COL_BRAKE_PRESS + 1:]:
+ try:
+ row.append(float(p))
+ except ValueError:
+ row.append(None)
+ rows.append(row)
return rows
@@ -331,7 +340,60 @@ def check_distance(rows, max=None, min=None):
return ok, f"travelled {d:.0f} m (wanted {bounds})"
+def check_slips(rows, within=None):
+ """The lead vehicle's wheels slip (or lock in a skid) at some point, e.g. to make sure a slippery rail case does what it's meant to."""
+ for r in rows:
+ if within is not None and r[COL_TIME] > within:
+ break
+ if len(r) > COL_WHEELSLIP and r[COL_WHEELSLIP]:
+ return True, f"wheels slipping at t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h"
+ return False, "the wheels never slipped"
+
+
+def check_holds_still(rows, moving_speed, stop_speed, max_distance):
+ """Once stopped after moving off, the vehicle doesn't creep. Uses the vehicle speed rather than the
+ wheel speed, so it also catches a vehicle sliding on locked wheels."""
+ if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None:
+ return False, "the physicslog has no vehicle speed column, the build is too old"
+ speed = [abs(r[COL_VEHICLE_VELOCITY]) for r in rows]
+ start = next((i for i, v in enumerate(speed) if v >= moving_speed), None)
+ if start is None:
+ return False, f"never reached {moving_speed} km/h"
+ stop = next((i for i in range(start, len(rows)) if speed[i] <= stop_speed), None)
+ if stop is None:
+ return False, f"never came down to {stop_speed} km/h"
+ d, top, top_t = 0.0, 0.0, rows[stop][COL_TIME]
+ for i in range(stop + 1, len(rows)):
+ d += (speed[i - 1] + speed[i]) / 2 / 3.6 * (rows[i][COL_TIME] - rows[i - 1][COL_TIME])
+ if speed[i] > top:
+ top, top_t = speed[i], rows[i][COL_TIME]
+ held = rows[-1][COL_TIME] - rows[stop][COL_TIME]
+ detail = f"stopped at t={rows[stop][COL_TIME]:.1f}s, then moved {d:.3f} m in {held:.0f}s, top {top:.4f} km/h at t={top_t:.1f}s"
+ return d <= max_distance, detail
+
+
+def check_slip_clears(rows, moving_speed, stop_speed, within):
+ """Once the vehicle has stopped after moving off, its wheels stop slipping within `within` seconds
+ (a vehicle left skidding on locked wheels keeps its brakes capped by the sliding adhesion)."""
+ if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None:
+ return False, "the physicslog has no vehicle speed column, the build is too old"
+ start = next((i for i, r in enumerate(rows) if abs(r[COL_VEHICLE_VELOCITY]) >= moving_speed), None)
+ if start is None:
+ return False, f"never reached {moving_speed} km/h"
+ stop = next((i for i in range(start, len(rows)) if abs(rows[i][COL_VEHICLE_VELOCITY]) <= stop_speed), None)
+ if stop is None:
+ return False, f"never came down to {stop_speed} km/h"
+ deadline = rows[stop][COL_TIME] + within
+ late = [r for r in rows[stop:] if r[COL_TIME] > deadline and r[COL_WHEELSLIP]]
+ if late:
+ return False, f"stopped at t={rows[stop][COL_TIME]:.1f}s, wheels still slipping at t={late[0][COL_TIME]:.1f}s ({len(late)} rows after the {within}s grace)"
+ return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s, no slipping after t={deadline:.1f}s"
+
+
CHECKS = {
+ "slips": check_slips,
+ "slip_clears": check_slip_clears,
+ "holds_still": check_holds_still,
"starts": check_starts,
"max_speed": check_max_speed,
"brakes": check_brakes,
From 02e29f69712d1e02e960c14eba32feb1a3245ab3 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 13:17:26 +0100
Subject: [PATCH 28/60] feat(simulation): test mode, --test runs a scenery
unattended and exits with the result (eu07/maszyna#541)
eu07 --test -s [--test-timeout ] runs the scenery in ghostview with
the null renderer (models loaded, no textures), a hidden window, no sound,
network or python, and in fixed steps of 0.03 s of simulation time per frame
(three 10 ms physics steps) as fast as it can. Without -seed it uses a fixed
seed, so two runs give byte-identical physicslogs.
The scenery reports its result to the __test.result memory cell, which the
simulator always creates: value 1 passes once every vehicle has stood still for
1 s, value 0 fails at once. The run ends with exit code
0 pass, 1 fail,
2 a train passed a signal at stop (SetVelocity 0 0, as seen in its driver's
speed table; SetVelocity 0 x on automatic block doesn't count),
3 timeout (test.timeout, default 3600 s of simulation time),
4 standstill (every vehicle still for test.standstill s, default 300, with no
result; a pass with test.pass_on_standstill yes),
5 error (no -s, the scenery didn't load or has no vehicles, an exception).
The test.* keys go in the scenery's config block; test.fail_if_stop_overran no
only logs a signal passed at danger. Outside the test mode a signal passed at
danger is logged.
The null renderer gets a ui backend which draws nothing, hands out the null
texture and material instead of throwing, and ends the ui frame. A GL context
is still made for the hidden window, without asking for a version, as parts
of the ui create textures with gl calls of their own. No crash dialog or
message box in test mode; the window code no longer needs a monitor.
---
CMakeLists.txt | 1 +
EU07.cpp | 17 +++-
application/application.cpp | 82 +++++++++++++---
application/drivermode.cpp | 13 +++
application/scenarioloadermode.cpp | 10 ++
rendering/nullrenderer.cpp | 19 ++++
rendering/nullrenderer.h | 30 ++++--
simulation/simulation.cpp | 3 +
simulation/simulationtest.cpp | 149 +++++++++++++++++++++++++++++
simulation/simulationtest.h | 66 +++++++++++++
utilities/Globals.cpp | 37 +++++++
utilities/Globals.h | 10 ++
utilities/Timer.cpp | 13 ++-
utilities/Timer.h | 3 +
vehicle/Driver.cpp | 29 +++++-
vehicle/Driver.h | 2 +
16 files changed, 458 insertions(+), 26 deletions(-)
create mode 100644 simulation/simulationtest.cpp
create mode 100644 simulation/simulationtest.h
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 6f34ad61f..8a4e1d6ea 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -160,6 +160,7 @@ set(SOURCES
"world/station.cpp"
"application/application.cpp"
"simulation/simulationtime.cpp"
+"simulation/simulationtest.cpp"
"scene/sceneeditor.cpp"
"rendering/screenshot.cpp"
"input/driverkeyboardinput.cpp"
diff --git a/EU07.cpp b/EU07.cpp
index e03618297..aac7cae11 100644
--- a/EU07.cpp
+++ b/EU07.cpp
@@ -19,6 +19,8 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others
#include "stdafx.h"
#include "application/application.h"
+#include "simulation/simulationtest.h"
+#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include
#ifdef WITHDUMPGEN
@@ -148,9 +150,14 @@ int main(int argc, char *argv[])
#ifdef _WIN32
catch (std::runtime_error const &Error)
{
- std::string msg = "Simulator crash occured :(\n";
- msg += Error.what();
- MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR);
+ ErrorLog("Critical error: " + std::string(Error.what()));
+ // in test mode nobody is there to close the box, the exit code tells of the error
+ if (false == Global.test.enabled)
+ {
+ std::string msg = "Simulator crash occured :(\n";
+ msg += Error.what();
+ MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR);
+ }
}
#endif
}
@@ -158,5 +165,7 @@ int main(int argc, char *argv[])
fflush(stdout);
fflush(stderr);
#endif
- std::_Exit(0); // skip destructors, there are ordering errors which causes segfaults
+ // skip destructors, there are ordering errors which causes segfaults
+ // a test run (--test) says its result in the exit code
+ std::_Exit(Global.test.enabled ? simulation::Test.exit_code() : 0);
}
diff --git a/application/application.cpp b/application/application.cpp
index ee381f98b..37afff67f 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -378,7 +378,7 @@ int eu07_application::init(int Argc, char *Argv[])
return result;
}
- if (crashreport_is_pending())
+ if (crashreport_is_pending() && false == Global.test.enabled)
{ // run crashgui as early as possible
if ((result = run_crashgui()) != 0)
{
@@ -951,14 +951,17 @@ GLFWwindow *eu07_application::window(int const Windowindex, bool visible, int wi
}
// for index -1 create a new child window
- auto const *vmode{glfwGetVideoMode(monitor ? monitor : glfwGetPrimaryMonitor())};
-
- // match requested video mode to current to allow for
- // fullwindow creation when resolution is the same
- glfwWindowHint(GLFW_RED_BITS, vmode->redBits);
- glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits);
- glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits);
- glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate);
+ auto *videomonitor{monitor ? monitor : glfwGetPrimaryMonitor()};
+ // a machine without a display (e.g. a test runner) has no monitor to match
+ if (auto const *vmode{videomonitor ? glfwGetVideoMode(videomonitor) : nullptr})
+ {
+ // match requested video mode to current to allow for
+ // fullwindow creation when resolution is the same
+ glfwWindowHint(GLFW_RED_BITS, vmode->redBits);
+ glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits);
+ glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits);
+ glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate);
+ }
glfwWindowHint(GLFW_VISIBLE, visible);
@@ -1195,6 +1198,19 @@ int eu07_application::init_settings(int Argc, char *Argv[])
WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed));
}
}
+ else if (token == "--test")
+ {
+ // integration test: the scenery runs unattended and the exit code is the result (eu07/maszyna#541)
+ Global.test.enabled = true;
+ }
+ else if (token == "--test-timeout")
+ {
+ if (i + 1 < Argc)
+ {
+ Global.test.timeout = std::max(0.0, std::atof(Argv[++i]));
+ Global.test.timeout_from_command_line = true;
+ }
+ }
else if (token == "-ini")
{
// extra settings file read on top of eu07.ini, so a run can override a few keys
@@ -1210,13 +1226,45 @@ int eu07_application::init_settings(int Argc, char *Argv[])
<< " [-v vehiclename]"
<< " [-edit [sceneryfilepath]]"
<< " [-seed number|word]"
- << " [-ini settingsfile]" << std::endl;
+ << " [-ini settingsfile]"
+ << " [--test [--test-timeout seconds]]" << std::endl;
return -1;
}
}
if (editwithoutscenery && false == sceneryfromcommandline)
Global.SceneryFile.clear();
+ if (Global.test.enabled)
+ {
+ if (false == sceneryfromcommandline || Global.SceneryFile.empty())
+ {
+ ErrorLog("test: --test needs a scenery given with -s");
+ return -1;
+ }
+ // nobody watches nor listens: no player vehicle, nothing drawn, no sound, no window in the way
+ Global.editor_session = false;
+ Global.local_start_vehicle = "ghostview";
+ Global.GfxRenderer = "null";
+ Global.NvRenderer = false;
+ Global.bSoundEnabled = false;
+ Global.python_enabled = false;
+ Global.bInactivePause = false;
+ Global.bFullScreen = false;
+ Global.fullscreen_windowed = false;
+ Global.VSync = false;
+ Global.iMultisampling = 0;
+ Global.gfx_usegles = false;
+ Global.minframetime = std::chrono::duration(0.0f);
+ Global.extra_viewports.clear();
+ Global.headtrack_conf.joy.clear();
+ // a test runs on its own
+ Global.network_servers.clear();
+ Global.network_client.reset();
+ // and the same way every time, unless given another seed (-seed, or randomseed in the settings)
+ if (!Global.random_seed)
+ Global.random_seed = seed_of("test");
+ }
+
return 0;
}
@@ -1290,6 +1338,12 @@ int eu07_application::init_glfw()
{
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
}
+ else if (Global.test.enabled)
+ {
+ // the null renderer draws nothing, but parts of the ui make textures with gl calls of their own.
+ // any context will do for them, so none is asked for in particular: a machine without a graphics
+ // driver (a test runner) has only the basic one of the system
+ }
else
{
if (!Global.LegacyRenderer)
@@ -1341,7 +1395,8 @@ int eu07_application::init_glfw()
Global.bFullScreen = true;
}
- auto *mainwindow = window(-1, true, Global.window_size.x, Global.window_size.y, Global.bFullScreen ? monitor : nullptr, true, false);
+ // test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it
+ auto *mainwindow = window(-1, false == Global.test.enabled, Global.window_size.x, Global.window_size.y, Global.bFullScreen ? monitor : nullptr, true, false);
if (mainwindow == nullptr)
{
@@ -1428,6 +1483,11 @@ int eu07_application::init_gfx()
// default render path
GfxRenderer = gfx_renderer_factory::get_instance()->create("modern");
}
+ else if (Global.GfxRenderer == "null")
+ {
+ // draws nothing and loads no textures (test mode)
+ GfxRenderer = gfx_renderer_factory::get_instance()->create("null");
+ }
else if (Global.GfxRenderer == "experimental")
{
GfxRenderer = gfx_renderer_factory::get_instance()->create(Global.GfxRenderer);
diff --git a/application/drivermode.cpp b/application/drivermode.cpp
index b55d09c2b..1b3a44d63 100644
--- a/application/drivermode.cpp
+++ b/application/drivermode.cpp
@@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulation.h"
#include "simulation/simulationtime.h"
#include "simulation/simulationenvironment.h"
+#include "simulation/simulationtest.h"
#include "scene/scene.h"
#include "rendering/lightarray.h"
#include "rendering/particles.h"
@@ -305,6 +306,11 @@ bool driver_mode::update()
simulation::Events.update();
simulation::Region->update_events();
simulation::Lights.update();
+
+ if (Global.test.enabled && simulation::is_ready)
+ {
+ simulation::Test.update(deltatime);
+ }
}
// render time routines follow:
@@ -478,6 +484,13 @@ void driver_mode::enter()
Timer::ResetTimers();
+ if (Global.test.enabled)
+ {
+ // the test runs as fast as it can compute, in steps of fixed length, so that runs on different machines agree
+ Timer::set_fixed_step(simulation::test_manager::frame_step);
+ simulation::Test.start();
+ }
+
set_picking(!Global.captureonstart);
m_editorpending = Global.editor_session;
diff --git a/application/scenarioloadermode.cpp b/application/scenarioloadermode.cpp
index f8f06ac93..b84c1912f 100644
--- a/application/scenarioloadermode.cpp
+++ b/application/scenarioloadermode.cpp
@@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulation.h"
#include "simulation/simulationtime.h"
#include "simulation/simulationenvironment.h"
+#include "simulation/simulationtest.h"
#include "application/application.h"
#include "application/scenarioloaderuilayer.h"
#include "rendering/renderer.h"
@@ -58,6 +59,10 @@ bool scenarioloader_mode::update() {
catch (std::runtime_error const &e) {
ErrorLog(std::format("Bad init: scenario \"{}\" couldn't be opened ({})", Global.SceneryFile, e.what()));
state.reset();
+ if (Global.test.enabled) {
+ simulation::Test.finish(simulation::test_result::error, "scenario couldn't be opened");
+ return true;
+ }
Global.SceneryFile.clear();
Application.pop_mode();
Application.push_mode(eu07_application::mode::launcher);
@@ -73,6 +78,11 @@ bool scenarioloader_mode::update() {
// back to the launcher as when the scenario can't be opened, not on to the driver mode with the scenery half loaded
ErrorLog( "Bad init: scenario loading failed" );
state.reset();
+ if( Global.test.enabled ) {
+ // there's nothing to test; the exit code says the run went wrong
+ simulation::Test.finish( simulation::test_result::error, "scenario loading failed" );
+ return true;
+ }
Global.SceneryFile.clear();
Application.pop_mode();
Application.push_mode(eu07_application::mode::launcher);
diff --git a/rendering/nullrenderer.cpp b/rendering/nullrenderer.cpp
index 332d357c7..f193ad3e4 100644
--- a/rendering/nullrenderer.cpp
+++ b/rendering/nullrenderer.cpp
@@ -1,6 +1,25 @@
#include "stdafx.h"
#include "rendering/nullrenderer.h"
+#include "application/application.h"
+
+void null_imgui_renderer::BeginFrame()
+{
+ auto &io { ImGui::GetIO() };
+ if( false == io.Fonts->IsBuilt() ) {
+ unsigned char *pixels;
+ int width, height;
+ io.Fonts->GetTexDataAsAlpha8( &pixels, &width, &height );
+ }
+}
+
+bool null_renderer::Render()
+{
+ // the ui frame begun by the application has to be ended, or imgui won't start the next one
+ Application.render_ui();
+ return true;
+}
+
std::unique_ptr null_renderer::create_func()
{
return std::make_unique();
diff --git a/rendering/nullrenderer.h b/rendering/nullrenderer.h
index 0b21580b9..2a7ef0398 100644
--- a/rendering/nullrenderer.h
+++ b/rendering/nullrenderer.h
@@ -35,7 +35,18 @@ private:
release_() override { /* null implementation, nothing to do */ }
};
+// user interface backend which draws nothing: imgui still builds its frames, so the ui code runs as usual
+class null_imgui_renderer : public imgui_renderer {
+public:
+ bool Init() override { return true; }
+ void Shutdown() override { /* null implementation, nothing to do */ }
+ // imgui wants its font atlas built before a frame starts; that's done on the cpu, no texture is made of it
+ void BeginFrame() override;
+ void Render() override { /* null implementation, nothing to do */ }
+};
+
// bare-bones render controller, in lack of anything better yet
+// it's the renderer of the test mode (--test): models are loaded for the physics, textures aren't
class null_renderer : public gfx_renderer {
public:
@@ -49,7 +60,7 @@ public:
Init( GLFWwindow *Window ) override { return true; }
// main draw call. returns false on error
bool
- Render() override { return true; }
+ Render() override;
void
SwapBuffers() override { /* null implementation, nothing to do */ }
inline
@@ -105,20 +116,22 @@ public:
void
Bind_Material( material_handle const Material, TSubModel const *sm = nullptr, lighting_data const *lighting = nullptr ) override { /* null implementation, nothing to do */ }
IMaterial const *
- Material( material_handle const Material ) const override { return m_materials.at(Material - 1).get(); }
+ Material( material_handle const Material ) const override {
+ return ( Material > 0 && static_cast( Material ) <= m_materials.size() ? m_materials[ Material - 1 ].get() : IMaterial::null_material() ); }
// shader methods
auto Fetch_Shader( std::string const &name ) -> std::shared_ptr override { throw std::runtime_error("not impl"); }
// texture methods
+ // no textures are loaded; whoever asks gets the null texture
texture_handle
- Fetch_Texture( std::string const &Filename, bool const Loadnow = true, GLint format_hint = GL_SRGB_ALPHA ) override { throw std::runtime_error("not impl"); }
+ Fetch_Texture( std::string const &Filename, bool const Loadnow = true, GLint format_hint = GL_SRGB_ALPHA ) override { return null_handle; }
void
Bind_Texture( texture_handle const Texture ) override { /* null implementation, nothing to do */ }
void
Bind_Texture( std::size_t const Unit, texture_handle const Texture ) override { /* null implementation, nothing to do */ }
- opengl_texture &
- Texture( texture_handle const Texture ) override { throw std::runtime_error("not impl"); }
- opengl_texture const &
- Texture( texture_handle const Texture ) const override { throw std::runtime_error("not impl"); }
+ ITexture &
+ Texture( texture_handle const Texture ) override { return *ITexture::null_texture(); }
+ ITexture const &
+ Texture( texture_handle const Texture ) const override { return *ITexture::null_texture(); }
// utility methods
void
Pick_Control_Callback( std::function Callback ) override { /* null implementation, nothing to do */ }
@@ -152,11 +165,12 @@ public:
imgui_renderer *GetImguiRenderer() override
{
- return nullptr;
+ return &m_imgui;
}
private:
std::string empty_str;
+ null_imgui_renderer m_imgui;
gfx::geometrybank_manager m_geometry;
std::vector> m_materials;
};
diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp
index ea2177170..59635c38c 100644
--- a/simulation/simulation.cpp
+++ b/simulation/simulation.cpp
@@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulation.h"
#include "simulation/simulationtime.h"
#include "simulation/simulationenvironment.h"
+#include "simulation/simulationtest.h"
#include "utilities/Globals.h"
#include "world/Event.h"
@@ -109,6 +110,8 @@ state_manager::init_scripting_interface() {
simulation::Memory.insert( memorycell );
simulation::Region->insert( memorycell );
}
+ // the cell a test scenery reports its result to
+ simulation::Test.init_result_cell();
}
// legacy method, calculates changes in simulation state over specified time
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
new file mode 100644
index 000000000..4dbe4c24f
--- /dev/null
+++ b/simulation/simulationtest.cpp
@@ -0,0 +1,149 @@
+/*
+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 "simulation/simulationtest.h"
+
+#include "application/application.h"
+#include "scene/scene.h"
+#include "simulation/simulation.h"
+#include "utilities/Globals.h"
+#include "utilities/Logs.h"
+#include "vehicle/DynObj.h"
+#include "world/Event.h"
+#include "world/MemCell.h"
+
+namespace simulation {
+
+test_manager Test;
+
+std::string_view to_string(test_result const Result)
+{
+ switch (Result)
+ {
+ case test_result::pass: return "pass";
+ case test_result::fail: return "fail";
+ case test_result::signal_passed_at_danger: return "signal passed at danger";
+ case test_result::timeout: return "timeout";
+ case test_result::standstill: return "standstill";
+ case test_result::error: return "error";
+ }
+ return "unknown";
+}
+
+void test_manager::init_result_cell()
+{
+ auto *cell = new TMemCell({0, -1, std::string(result_cell), "memcell"});
+ // neither of the reported values, so that a cell nobody wrote to says nothing
+ cell->UpdateValues("", -1.0, 0.0, basic_event::flags::value1 | basic_event::flags::value2);
+ simulation::Memory.insert(cell);
+ simulation::Region->insert(cell);
+}
+
+void test_manager::start()
+{
+ if (m_started)
+ return;
+ m_started = true;
+ m_time = 0.0;
+ m_resttime = 0.0;
+ if (simulation::Vehicles.sequence().empty())
+ {
+ // most likely the scenery wasn't found, or it isn't a test scenery
+ finish(test_result::error, "the scenery has no vehicles");
+ return;
+ }
+ // a pause set by the scenery or the settings would never be lifted, nobody is there to press the key
+ Global.iPause = 0;
+ WriteLog(std::format("test: started, timeout {:.0f} s, standstill {:.0f} s{}{}", Global.test.timeout, Global.test.standstill,
+ Global.test.pass_on_standstill ? ", standstill passes" : "",
+ Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed"));
+}
+
+void test_manager::update(double const Deltatime)
+{
+ if (false == m_started || m_finished)
+ return;
+
+ m_time += Deltatime;
+
+ if (auto const *cell = simulation::Memory.find(std::string(result_cell)))
+ {
+ auto const value { cell->Value1() };
+ auto const reason { cell->Text().empty() ? std::string() : " (" + cell->Text() + ")" };
+ if (value == 0.0)
+ {
+ finish(test_result::fail, "__test.result set to 0" + reason);
+ return;
+ }
+ if (value == 1.0 && false == m_passrequested)
+ {
+ m_passrequested = true;
+ WriteLog(std::format("test: pass requested at {:.1f} s{}, waiting for every vehicle to stop", m_time, reason));
+ }
+ }
+
+ auto const atrest = std::none_of(simulation::Vehicles.sequence().begin(), simulation::Vehicles.sequence().end(),
+ [](TDynamicObject const *Vehicle) { return std::abs(Vehicle->GetVelocity()) > 0.01; });
+ m_resttime = atrest ? m_resttime + Deltatime : 0.0;
+
+ if (m_passrequested && m_resttime >= pass_settle_time)
+ {
+ finish(test_result::pass, "__test.result set to 1 and every vehicle stopped");
+ return;
+ }
+ if (Global.test.standstill > 0.0 && m_resttime >= Global.test.standstill)
+ {
+ auto const reason { std::format("every vehicle stood still for {:.0f} s", Global.test.standstill) };
+ finish(Global.test.pass_on_standstill ? test_result::pass : test_result::standstill, reason);
+ return;
+ }
+ if (Global.test.timeout > 0.0 && m_time >= Global.test.timeout)
+ {
+ finish(test_result::timeout, std::format("no result after {:.0f} s", Global.test.timeout));
+ return;
+ }
+}
+
+void test_manager::signal_passed_at_danger(std::string const &Vehicle, std::string const &Signal)
+{
+ auto const reason { Vehicle + " passed signal " + Signal + " at danger" };
+ if (false == Global.test.enabled)
+ {
+ WriteLog(reason, logtype::generic);
+ return;
+ }
+ if (false == Global.test.fail_if_stop_overran)
+ {
+ WriteLog(std::format("test: {} at {:.1f} s, allowed by test.fail_if_stop_overran", reason, m_time));
+ return;
+ }
+ finish(test_result::signal_passed_at_danger, reason);
+}
+
+void test_manager::finish(test_result const Result, std::string const &Reason)
+{
+ if (m_finished || false == Global.test.enabled)
+ return;
+ m_finished = true;
+ m_result = Result;
+
+ auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast(Result), m_time, Reason) };
+ if (Result == test_result::pass)
+ WriteLog(line);
+ else
+ ErrorLog(line);
+ // the process has no console of its own; whoever started it with a redirected output gets the verdict there too
+ std::fprintf(stdout, "%s\n", line.c_str());
+ std::fflush(stdout);
+
+ Application.queue_quit(true);
+}
+
+} // namespace simulation
diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h
new file mode 100644
index 000000000..c9bc5437e
--- /dev/null
+++ b/simulation/simulationtest.h
@@ -0,0 +1,66 @@
+/*
+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
+
+// integration test mode (eu07 --test -s , eu07/maszyna#541): the scenery runs unattended in a tight
+// fixed-step loop and the simulator quits with an exit code saying how the test went
+namespace simulation {
+
+// exit codes of a test run; public, scripts and CI read them
+enum class test_result : int {
+ pass = 0, // __test.result set to 1, then every vehicle came to rest (or test.pass_on_standstill)
+ fail = 1, // __test.result set to 0
+ signal_passed_at_danger = 2, // a train went past a stop signal (SetVelocity 0 0), unless test.fail_if_stop_overran no
+ timeout = 3, // test.timeout seconds of simulation time went by without a result
+ standstill = 4, // every vehicle stood still for test.standstill seconds without a result
+ error = 5, // the run could not start (no -s, the scenery failed to load) or the simulator threw
+};
+
+std::string_view to_string(test_result Result);
+
+class test_manager {
+
+public:
+ // name of the memory cell a scenery reports its result to
+ static constexpr std::string_view result_cell { "__test.result" };
+ // how long everything has to stand before a requested pass is granted [s]
+ static constexpr double pass_settle_time { 1.0 };
+ // fixed simulation time step of one frame in test mode [s]: 3 physics steps of 10 ms
+ static constexpr double frame_step { 0.03 };
+
+ // creates the result cell; called with the other scripting interface cells, before the scenery is read
+ void init_result_cell();
+ // the simulation is ready: start the clocks
+ void start();
+ // checks the end conditions after a simulation frame of Deltatime seconds
+ void update(double Deltatime);
+ // reported by a driver whose train went past a signal showing stop
+ void signal_passed_at_danger(std::string const &Vehicle, std::string const &Signal);
+ // ends the test with given result; the first call wins
+ void finish(test_result Result, std::string const &Reason);
+
+ bool finished() const { return m_finished; }
+ // exit code of the process: the result, or error while the test hasn't finished
+ int exit_code() const { return static_cast(m_finished ? m_result : test_result::error); }
+
+private:
+ bool m_started { false };
+ bool m_finished { false };
+ test_result m_result { test_result::error };
+ bool m_passrequested { false };
+ double m_time { 0.0 }; // simulation time since the start [s]
+ double m_resttime { 0.0 }; // how long every vehicle has been standing [s]
+};
+
+extern test_manager Test;
+
+} // namespace simulation
diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp
index b4f2e14be..e36223174 100644
--- a/utilities/Globals.cpp
+++ b/utilities/Globals.cpp
@@ -456,6 +456,40 @@ bool global_settings::ConfigParseInput(cParser& Parser, const std::string& token
return false;
}
+bool global_settings::ConfigParseTest(cParser& Parser, const std::string& token)
+{
+ // integration test limits, usually given in the config block of a test scenery
+ if (token == "test.timeout")
+ {
+ double value{ test.timeout };
+ ParseOne(Parser, value);
+ if (false == test.timeout_from_command_line)
+ test.timeout = std::max(0.0, value);
+ return true;
+ }
+
+ if (token == "test.standstill")
+ {
+ ParseOne(Parser, test.standstill);
+ test.standstill = std::max(0.0, test.standstill);
+ return true;
+ }
+
+ if (token == "test.pass_on_standstill")
+ {
+ ParseOne(Parser, test.pass_on_standstill);
+ return true;
+ }
+
+ if (token == "test.fail_if_stop_overran")
+ {
+ ParseOne(Parser, test.fail_if_stop_overran);
+ return true;
+ }
+
+ return false;
+}
+
bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& token)
{
if (token == "async.trainThreads")
@@ -1316,6 +1350,9 @@ void global_settings::ConfigParse(cParser& Parser)
if (ConfigParseDebug(Parser, token))
continue;
+ if (ConfigParseTest(Parser, token))
+ continue;
+
// WriteLog(std::format("Unknown config token: {}", token), logtype::warning, false);
} while (true);
diff --git a/utilities/Globals.h b/utilities/Globals.h
index ad216cd96..8fa04e9ce 100644
--- a/utilities/Globals.h
+++ b/utilities/Globals.h
@@ -86,6 +86,15 @@ struct global_settings {
std::string local_start_vehicle{ "EU07-424" };
std::string editor_enter_vehicle; // vehicle placed in the editor, to be entered when the driving goes on
bool editor_session{ false }; // scenery was opened for editing (-edit): loader keeps track of scenery layers and hands over to the editor
+ // integration test mode (--test, eu07/maszyna#541); the limits can be set in the scenery's config block (test.*)
+ struct test_settings {
+ bool enabled{ false };
+ double timeout{ 3600.0 }; // [s] of simulation time; no result by then fails the test
+ double standstill{ 300.0 }; // [s] every vehicle standing still this long ends the test; 0 = never
+ bool pass_on_standstill{ false }; // the standstill end passes the test instead of failing it
+ bool fail_if_stop_overran{ true }; // a train passing a signal at stop ends the test as failed; with false it's only logged
+ bool timeout_from_command_line{ false }; // --test-timeout given, the scenery doesn't override it
+ } test;
bool editor_tracks{ false }; // F3 track workspace: draw and pick tracks without the scenery draw-range cap
int iConvertModels{ 0 }; // tworzenie plików binarnych
int iConvertIndexRange{ 1000 }; // range of duplicate vertex scan
@@ -377,6 +386,7 @@ struct global_settings {
bool ConfigParseNetwork(cParser& Parser, const std::string& token);
bool ConfigParseHardware(cParser& Parser, const std::string& token);
bool ConfigParseDebug(cParser& Parser, const std::string& token);
+ bool ConfigParseTest(cParser& Parser, const std::string& token);
bool ConfigParse_gfx( cParser &parser, std::string_view const Token );
// sends basic content of the class in legacy (text) format to provided stream
void
diff --git a/utilities/Timer.cpp b/utilities/Timer.cpp
index 0b877f2b4..388330bbe 100644
--- a/utilities/Timer.cpp
+++ b/utilities/Timer.cpp
@@ -26,6 +26,7 @@ double fRenderTime{ 0.0 };
double fSoundTimer{ 0.0 };
double fSinceStart{ 0.0 };
double override_delta = -1.0f;
+double fixed_step = 0.0;
double GetTime()
{
@@ -53,6 +54,11 @@ void set_delta_override(double t)
override_delta = t;
}
+void set_fixed_step(double t)
+{
+ fixed_step = t;
+}
+
void ResetTimers()
{
UpdateTimers( Global.iPause != 0 );
@@ -76,10 +82,15 @@ void UpdateTimers(bool pause)
fr = 1000000000;
#endif
DeltaRenderTime = double(count - oldCount) / double(fr);
+ if (fixed_step > 0.0)
+ {
+ // the frame lasts exactly as long as said, however long it took to compute; the time speed doesn't apply
+ DeltaRenderTime = fixed_step;
+ }
fRenderTime += DeltaRenderTime;
if (!pause)
{
- DeltaTime = Global.fTimeSpeed * DeltaRenderTime;
+ DeltaTime = (fixed_step > 0.0 ? 1.0 : Global.fTimeSpeed) * DeltaRenderTime;
fSoundTimer += DeltaTime;
if (fSoundTimer > 0.1)
fSoundTimer = 0.0;
diff --git a/utilities/Timer.h b/utilities/Timer.h
index 32e170a46..15fdd4f6b 100644
--- a/utilities/Timer.h
+++ b/utilities/Timer.h
@@ -19,6 +19,9 @@ double GetDeltaRenderTime();
void set_delta_override(double v);
+// every frame advances the clocks by this many seconds, whatever the real time; 0 = real time (test mode)
+void set_fixed_step(double v);
+
void ResetTimers();
void UpdateTimers(bool pause);
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index c5f5f51e9..5f1bde20c 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/.
#include "world/MemCell.h"
#include "simulation/simulation.h"
#include "simulation/simulationtime.h"
+#include "simulation/simulationtest.h"
#include "world/Track.h"
#include "world/station.h"
#include "input/keyboardinput.h"
@@ -767,7 +768,12 @@ void TController::TableCheck(double fDistance)
{ // aktualizacja rekordów z wyjątkiem ostatniego
if (sSpeedTable[i].iFlags & spEnabled) // jeśli pozycja istotna
{
- if (sSpeedTable[i].Update())
+ auto const waspassed { TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) };
+ auto const switchchanged { sSpeedTable[ i ].Update() };
+ if( false == waspassed ) {
+ CheckSignalPassedAtDanger( sSpeedTable[ i ] );
+ }
+ if (switchchanged)
{
if( Global.iWriteLogEnabled & 8 ) {
WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" );
@@ -816,7 +822,12 @@ void TController::TableCheck(double fDistance)
}
}
}
- sSpeedTable[iLast].Update(); // aktualizacja ostatniego
+ // aktualizacja ostatniego; a signal at stop often is the last, the scan doesn't go past it
+ auto const lastwaspassed { TestFlag( sSpeedTable[ iLast ].iFlags, spElapsed ) };
+ sSpeedTable[iLast].Update();
+ if( false == lastwaspassed ) {
+ CheckSignalPassedAtDanger( sSpeedTable[ iLast ] );
+ }
// WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist));
if( sSpeedTable[ iLast ].fDist < fDistance ) {
TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka
@@ -827,6 +838,20 @@ void TController::TableCheck(double fDistance)
}
};
+void TController::CheckSignalPassedAtDanger( TSpeedPos const &Point ) const
+{
+ if( false == TestFlag( Point.iFlags, spElapsed )
+ || false == TestFlag( Point.iFlags, spEvent )
+ || false == TestFlag( Point.iFlags, spSemaphor )
+ || true == TestFlag( Point.iFlags, spStopOnSBL ) // SetVelocity 0 x on automatic block: may go on after a stop
+ || Point.fVelNext != 0.0
+ || Point.evEvent == nullptr
+ || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only
+ return;
+ }
+ simulation::Test.signal_passed_at_danger( OwnerName(), Point.evEvent->m_name );
+}
+
auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head
TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fNext, double &fAcc)
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index f88e115ac..8c12087f9 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -519,6 +519,8 @@ private:
bool TableNotFound( basic_event const *Event, double const Distance ) const;
void TableTraceRoute( double fDistance, TDynamicObject *pVehicle );
void TableCheck( double fDistance );
+ // reports the train going past a signal showing stop (SetVelocity 0 0); called once the head passed Point
+ void CheckSignalPassedAtDanger( TSpeedPos const &Point ) const;
TCommandType TableUpdate( double &fVelDes, double &fDist, double &fNext, double &fAcc );
bool TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance );
bool TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex );
From 6a538d202b6437e27e189e7c63a0fa413da65167 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 13:17:27 +0100
Subject: [PATCH 29/60] test: scenario tests run in the simulator's test mode
and check its exit code
run.py starts eu07 with --test (and --test-timeout for cases that
record a fixed time) and compares the result from the exit code with the
case's expect key, before the physicslog checks. The 14 cases take about 30 s
with -j 4 instead of minutes. --watch keeps the old windowed run.
New case keys: expect, test_config (lines of a config block), track_events
(lines added to a track of the base scenery, e.g. event0 test_pass). New cases
show each end of the test mode: test_mode_pass, _signal_passed_at_danger,
_timeout and _standstill. The slippery rail cases slide past the red signal,
which now ends a test, so they set test.fail_if_stop_overran no.
README documents the test mode for scenery authors.
---
tests/scenarios/README.md | 130 ++++++++++++++----
.../cases/eu07_slippery_push_red_signal.json | 3 +
.../cases/eu07_slippery_red_signal.json | 3 +
tests/scenarios/cases/td_red_signal_pass.scn | 8 ++
tests/scenarios/cases/test_mode_pass.json | 31 +++++
.../test_mode_signal_passed_at_danger.json | 22 +++
.../scenarios/cases/test_mode_standstill.json | 26 ++++
tests/scenarios/cases/test_mode_timeout.json | 21 +++
tests/scenarios/run.py | 122 ++++++++++++----
9 files changed, 315 insertions(+), 51 deletions(-)
create mode 100644 tests/scenarios/cases/td_red_signal_pass.scn
create mode 100644 tests/scenarios/cases/test_mode_pass.json
create mode 100644 tests/scenarios/cases/test_mode_signal_passed_at_danger.json
create mode 100644 tests/scenarios/cases/test_mode_standstill.json
create mode 100644 tests/scenarios/cases/test_mode_timeout.json
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 4600a3577..1ebd84c75 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -1,49 +1,121 @@
# Scenario tests
-End-to-end checks that run the real simulator on a scenery and look at what a vehicle
-did: did it start, did it keep to the speed limit, did it brake and stop.
+End-to-end checks that run the real simulator on a scenery and look at how the run ended
+and what a vehicle did: did it start, did it keep to the speed limit, did it brake and stop,
+did it pass a signal at stop.
Scenery and vehicle data are not in this repo, so these run against a local game install
only, not in CI.
+## The simulator's test mode
+
+The runner drives the simulator's test mode (eu07/maszyna#541), which works without the
+runner too and is meant for scenery authors as well:
+
+```
+eu07 --test -s [--test-timeout ] [-seed ] [-ini ]
+```
+
+With `--test` the simulator:
+
+- needs `-s`; `-v` is ignored and every train is driven by AI (ghostview),
+- draws nothing: the null renderer loads the 3D models (the physics needs some of their
+ data) but no textures, and the window stays hidden,
+- has no sound, no network, no python, no pause (not even one set by the scenery), and
+ no crash dialog,
+- runs the simulation as fast as it can in fixed steps of 0.03 s of simulation time per
+ frame (three 10 ms physics steps), whatever the real time, the time speed or the machine,
+- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so two
+ runs of a scenery come out the same (the physicslogs of two runs are byte for byte equal),
+- quits when the test ends, and says how it ended in the exit code and in a `test: ...`
+ line on stdout and in the log.
+
+A scenery reports its result to the memory cell `__test.result`, which the simulator creates
+(in every run, so a test scenery loads normally too). Write value 1 to it for a pass and 0
+for a failure, with an `UpdateValues` event; other values are ignored, and the text, if
+given, goes to the log as the reason:
+
+```
+event test_pass UpdateValues 0 __test.result reached_the_stop 1 * endevent
+event test_fail UpdateValues 0 __test.result wrong_track 0 * endevent
+```
+
+(`PutValues` isn't the event for it: it hands a command to a vehicle, it doesn't write a cell.)
+A good place for the pass event is `event0` of a track the train should stop on: it runs
+while a train stands there, and the length of the track is the margin of the stop.
+
+The test ends with the first of these:
+
+| exit code | result | when |
+| --- | --- | --- |
+| 0 | pass | `__test.result` was set to 1 and then every vehicle stood still for 1 s, so a train still moving towards a signal at stop has to stop first. Also the standstill end with `test.pass_on_standstill yes` |
+| 1 | fail | `__test.result` was set to 0; ends at once |
+| 2 | signal passed at danger | a train went past a signal showing stop (`SetVelocity 0 0`; `SetVelocity 0 x` on automatic block, which may be passed after a stop, doesn't count); ends at once, unless `test.fail_if_stop_overran no` |
+| 3 | timeout | `test.timeout` seconds of simulation time went by (default 3600) |
+| 4 | standstill | every vehicle stood still for `test.standstill` seconds (default 300) and nothing reported a result. Trains waiting at a station or for a signal count as standing, so the limit has to be longer than such waits |
+| 5 | error | the run could not start: no `-s`, the scenery failed to load or has no vehicles, or the simulator threw |
+
+A crash ends with the system's code instead (on Windows e.g. `0xC0000005`, -1073741819).
+
+The limits go in a `config` block of the scenery:
+
+```
+config
+test.timeout 600
+test.standstill 120
+test.pass_on_standstill no
+test.fail_if_stop_overran yes
+endconfig
+```
+
+`--test-timeout` on the command line wins over `test.timeout` of the scenery.
+
+A signal is passed at danger when the head of a train goes past a signal which its driver
+has in its speed table, showing stop. So it's the driver's view that counts: a train without
+a driver isn't watched, and neither is a signal the driver never scanned (a train placed at
+100 km/h 150 m before a signal at stop got past it before its AI first looked ahead; at
+60 km/h it was caught). Outside the test mode the same is written to the log, nothing more.
+
## Running
```
-python tests/scenarios/run.py --game-dir "E:/Program Files (x86)/Steam/steamapps/common/MaSzyna" -j 4
+python tests/scenarios/run.py --game-dir "C:/Steam/steamapps/common/MaSzyna" -j 4
```
Python 3.10+, no extra packages. Options:
- `EU07_GAME_DIR` can replace `--game-dir`.
- `--exe path/to/eu07.exe` picks the build to test; the default is the newest
- `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `-ini` command line option.
+ `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `--test` and `-ini` command
+ line options.
- name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`.
-- `-j N` runs N cases at once, each in its own simulator window. Each case prints its
- results when it is done. All 8 cases take about a minute with `-j 4`.
-- `--timespeed N` sets the simulation time multiplier, default 20: a 4-minute case runs in
- about 20 s. Physics still steps finely (the physicslog keeps its 0.05 s rows) and the speed
- profile at 20 and 60 matched a real-time run within a few km/h and seconds. Use
- `--timespeed 1` to watch a run.
+- `-j N` runs N cases at once. Each case prints its results when it is done. All 14 cases
+ take about 30 s with `-j 4`, loading included.
+- `--watch` runs a case the old way, in a visible window in real time (or faster with
+ `--timespeed N`), closed after the case's `duration`; the exit code isn't checked then. For
+ watching what a case does.
Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`,
-the vehicle's physicslog) are moved to `tests/scenarios/out//`.
+`stdout.txt`, the vehicle's physicslog) are moved to `tests/scenarios/out//`.
## How it works
For each case the runner:
1. writes `scenery/autotest_.scn` into the game dir: the base scenery with its own
- trainsets removed, the start time changed if the case says so, and the case's `.scn`
- fragment added: its trainsets after `FirstInit`, everything else (event launchers standing
- in for keys the scenery expects a player to press, extra events) before it,
-2. starts the simulator with `-s autotest_.scn -v ghostview -ini out//autotest.ini`;
- ghostview leaves every train to the AI, and the extra ini turns on `physicslog`, runs in a
- 1280x720 window, does not pause when the window loses focus, and writes the logs to
- `logs/log (autotest_) .txt` rather than the shared `log.txt` (`multiplelogs`),
-3. waits until `physicslog/autotest_.dat` covers `duration` seconds, then closes the
- simulator. It gives up early when the log reports `Bad vehicle` / `Bad trainset`, or when
- the scenario has loaded and no physicslog appeared,
-4. runs the checks on the physicslog.
+ trainsets removed, the start time changed if the case says so, the case's track events
+ added, and the case's `.scn` fragment added: its trainsets after `FirstInit`, everything
+ else (the case's `test_config`, event launchers standing in for keys the scenery expects a
+ player to press, extra events) before it,
+2. starts the simulator with `--test -s autotest_.scn -ini out//autotest.ini`,
+ plus `--test-timeout ` when the case gives a `duration`; the extra ini turns on
+ `physicslog` and writes the logs to `logs/log (autotest_) .txt` rather than the
+ shared `log.txt` (`multiplelogs`),
+3. waits until the simulator quits by itself. It gives up early when the log reports
+ `Bad vehicle` / `Bad trainset`, when the scenario has loaded and no physicslog appeared, or
+ after the case's `timeout` of wall-clock time,
+4. compares the result from the exit code with the case's `expect`, then runs the checks on
+ the physicslog.
The lead vehicle is named `autotest_`, so every case has its own physicslog and log
files and cases can run in parallel. The `autotest_*` sceneries (and the simulator's `.sbt`
@@ -60,9 +132,12 @@ scenery is newer.
| `strip_trainsets` | drop the base scenery's trainsets (default `true`) |
| `time` | replace the scenery start time, `HH:MM` |
| `track_friction` | set the friction of every track of the base scenery (default in the sceneries is 0.15), e.g. for slippery rail |
+| `track_events` | lines added to tracks of the base scenery, by track name, e.g. `{ "tor1k": "event0 test_pass" }`; only tracks in the scenery file itself, not in its includes |
+| `test_config` | lines of a `config` block added to the scenery, e.g. `["test.timeout 90"]` |
| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) |
| `vars` | values for `{{name}}` in the fragment; a list becomes one line per item |
-| `duration` | seconds of simulation to record |
+| `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`. Default `timeout` for a case with `duration`, else `pass` |
+| `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) |
| `timeout` | wall-clock seconds before giving up, loading included |
| `fail_on_errors` | fail when `errors.txt` is not empty (default `false`) |
| `checks` | list of checks, below |
@@ -72,7 +147,14 @@ the one whose physicslog is checked. Other vehicles of the consist take names ma
e.g. `{{vehicle}}_s`. The td.scn cases share two fragments, `td_timetable.scn` (route set,
train runs to Przystanek) and `td_red_signal.scn` (no route, exit signal at stop), and differ
only in `vars.consist`. `td_red_signal_moving.scn` is the red signal one with the train
-starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels when braking.
+starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels when braking
+and slides past the signal, so those cases set `test.fail_if_stop_overran no`.
+`td_red_signal_pass.scn` adds the `test_pass` event, which `test_mode_pass` puts as `event0`
+on `tor1k`, the track in front of the signal.
+
+The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass
+event), `test_mode_signal_passed_at_danger` (exit 2), `test_mode_timeout` (exit 3, from
+`test.timeout`) and `test_mode_standstill` (exit 4, from `test.standstill`).
Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use
the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are
diff --git a/tests/scenarios/cases/eu07_slippery_push_red_signal.json b/tests/scenarios/cases/eu07_slippery_push_red_signal.json
index f7ae10bb7..64d6ba884 100644
--- a/tests/scenarios/cases/eu07_slippery_push_red_signal.json
+++ b/tests/scenarios/cases/eu07_slippery_push_red_signal.json
@@ -4,6 +4,9 @@
"time": "10:34",
"track_friction": 0.03,
"fragment": "td_red_signal_moving.scn",
+ "test_config": [
+ "test.fail_if_stop_overran no"
+ ],
"vars": {
"velocity": "30",
"consist": [
diff --git a/tests/scenarios/cases/eu07_slippery_red_signal.json b/tests/scenarios/cases/eu07_slippery_red_signal.json
index 40b5944eb..c2f60f22d 100644
--- a/tests/scenarios/cases/eu07_slippery_red_signal.json
+++ b/tests/scenarios/cases/eu07_slippery_red_signal.json
@@ -4,6 +4,9 @@
"time": "10:34",
"track_friction": 0.03,
"fragment": "td_red_signal_moving.scn",
+ "test_config": [
+ "test.fail_if_stop_overran no"
+ ],
"vars": {
"velocity": "30",
"consist": [
diff --git a/tests/scenarios/cases/td_red_signal_pass.scn b/tests/scenarios/cases/td_red_signal_pass.scn
new file mode 100644
index 000000000..724050322
--- /dev/null
+++ b/tests/scenarios/cases/td_red_signal_pass.scn
@@ -0,0 +1,8 @@
+// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed.
+// like td_red_signal.scn (no route, the exit signal stacja1_j about 150 m ahead stays at stop),
+// with the test mode's pass event: the case puts it as event0 on tor1k, the track in front of
+// the signal, so it runs once the train stands there. the test passes when every vehicle stopped.
+event test_pass UpdateValues 0 __test.result stopped_before_stacja1_j 1 * endevent
+trainset td/rozklad tdo_n1734 0.0 0.1
+{{consist}}
+endtrainset
diff --git a/tests/scenarios/cases/test_mode_pass.json b/tests/scenarios/cases/test_mode_pass.json
new file mode 100644
index 000000000..686b7d160
--- /dev/null
+++ b/tests/scenarios/cases/test_mode_pass.json
@@ -0,0 +1,31 @@
+{
+ "description": "Test mode, pass: EU07 on td.scn with no route set stops before the exit signal stacja1_j; event0 of the track there reports the pass, and the test ends as passed once the train stands.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal_pass.scn",
+ "track_events": {
+ "tor1k": "event0 test_pass"
+ },
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "expect": "pass",
+ "timeout": 600,
+ "checks": [
+ {
+ "type": "starts",
+ "min_speed": 5,
+ "within": 150
+ },
+ {
+ "type": "stops",
+ "moving_speed": 5,
+ "stop_speed": 0.5,
+ "hold": 0.5
+ },
+ {
+ "type": "distance",
+ "max": 150
+ }
+ ]
+}
diff --git a/tests/scenarios/cases/test_mode_signal_passed_at_danger.json b/tests/scenarios/cases/test_mode_signal_passed_at_danger.json
new file mode 100644
index 000000000..338e7e6ea
--- /dev/null
+++ b/tests/scenarios/cases/test_mode_signal_passed_at_danger.json
@@ -0,0 +1,22 @@
+{
+ "description": "Test mode, signal passed at danger: EU07 on td.scn with no route set starts at 60 km/h about 150 m before the exit signal stacja1_j at stop. Its AI driver is still preparing the engine and doesn't brake, and the run ends when the train passes the signal.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal_moving.scn",
+ "vars": {
+ "velocity": "60",
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "expect": "signal_passed_at_danger",
+ "timeout": 600,
+ "checks": [
+ {
+ "type": "max_speed",
+ "limit": 61
+ },
+ {
+ "type": "distance",
+ "min": 140
+ }
+ ]
+}
diff --git a/tests/scenarios/cases/test_mode_standstill.json b/tests/scenarios/cases/test_mode_standstill.json
new file mode 100644
index 000000000..0d96585ee
--- /dev/null
+++ b/tests/scenarios/cases/test_mode_standstill.json
@@ -0,0 +1,26 @@
+{
+ "description": "Test mode, standstill: EU07 on td.scn with no route set stops before the exit signal stacja1_j at stop and stays; nothing reports a result, so the test ends once every vehicle stood still for test.standstill 120 seconds (the train waits about 70 s before it pulls off, so less would end it before the start).",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal.scn",
+ "test_config": [
+ "test.standstill 120"
+ ],
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "expect": "standstill",
+ "timeout": 600,
+ "checks": [
+ {
+ "type": "stops",
+ "moving_speed": 5,
+ "stop_speed": 0.5,
+ "hold": 5
+ },
+ {
+ "type": "distance",
+ "max": 150
+ }
+ ]
+}
diff --git a/tests/scenarios/cases/test_mode_timeout.json b/tests/scenarios/cases/test_mode_timeout.json
new file mode 100644
index 000000000..46899e89c
--- /dev/null
+++ b/tests/scenarios/cases/test_mode_timeout.json
@@ -0,0 +1,21 @@
+{
+ "description": "Test mode, timeout: EU07 on td.scn with no route set pulls off towards the exit signal stacja1_j at stop; nothing reports a result and test.timeout 90 from the scenery's config block runs out first.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal.scn",
+ "test_config": [
+ "test.timeout 90"
+ ],
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "expect": "timeout",
+ "timeout": 600,
+ "checks": [
+ {
+ "type": "starts",
+ "min_speed": 5,
+ "within": 90
+ }
+ ]
+}
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 2cd754a06..770069d12 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -2,16 +2,19 @@
"""Scenario tests: run the real simulator on a scenery and check what a vehicle did.
A case (cases/.json) names a base scenery from the game install, a fragment
-added to it (usually a trainset with an AI driver), and checks on the vehicle's
-physics log. The runner:
+added to it (usually a trainset with an AI driver), the result the simulator's test
+mode should end with, and checks on the vehicle's physics log. The runner:
1. builds scenery/autotest_.scn in the game dir: the base scenery with its own
trainsets removed, optionally a different start time, and the case fragment added,
- 2. starts eu07 with that scenery in ghostview (every train driven by AI) and an extra
- settings file (-ini) that turns on physicslog and runs in a window,
- 3. waits until the vehicle's physicslog covers `duration` seconds of simulation,
- then closes the simulator,
- 4. evaluates the checks on the log and prints PASS/FAIL per check.
+ 2. starts eu07 in test mode (--test: every train driven by AI, nothing drawn, fixed
+ time steps as fast as it can) with that scenery and an extra settings file (-ini)
+ that turns on physicslog,
+ 3. waits until the simulator quits by itself and reads the test result from its exit
+ code: pass, fail, signal passed at danger, timeout (after `duration` seconds of
+ simulation, if the case gives one), standstill or error,
+ 4. compares the result with the one the case expects, evaluates the checks on the
+ physicslog and prints PASS/FAIL per check.
Scenery and vehicle data are not part of this repo, so this runs against a local game
install only (--game-dir or EU07_GAME_DIR), not in CI. See README.md.
@@ -49,7 +52,18 @@ COL_COMMAND = 16 # text, read as None
COL_WHEELSLIP = 20
COL_VEHICLE_VELOCITY = 25 # signed vehicle speed, km/h; only in builds which log it
-# settings layered over the user's eu07.ini for a test run
+# exit codes of the simulator's test mode (eu07 --test), see simulation/simulationtest.h
+EXIT_RESULTS = {
+ 0: "pass",
+ 1: "fail",
+ 2: "signal_passed_at_danger",
+ 3: "timeout",
+ 4: "standstill",
+ 5: "error",
+}
+
+# settings layered over the user's eu07.ini for a test run; the window ones only matter
+# with --watch, test mode keeps its window hidden and turns the sound off by itself
TEST_INI = """\
fullscreen no
fullscreenwindowed no
@@ -89,6 +103,17 @@ def set_start_time(text: str, hhmm: str) -> str:
return re.sub(r"(?im)^(\s*time\s+)\d{1,2}:\d{2}", lambda m: m.group(1) + hhmm, text, count=1)
+def add_track_events(text: str, events: dict) -> str:
+ """Adds lines (e.g. "event0 test_pass") to tracks named in events, before their endtrack."""
+ for track, lines in events.items():
+ lines = [lines] if isinstance(lines, str) else lines
+ m = re.search(rf"(?im)^\s*node\s+\S+\s+\S+\s+{re.escape(track)}\s+track\b.*?^(\s*endtrack\b)", text, re.S)
+ if not m:
+ sys.exit(f"track_events: no track {track} in the base scenery itself (not in its includes)")
+ text = text[: m.start(1)] + "".join(line + "\n" for line in lines) + text[m.start(1):]
+ return text
+
+
def set_track_friction(text: str, friction: float) -> str:
"""Sets the friction of every track: node track ..."""
return re.sub(r"(?im)^(\s*node\s+\S+\s+\S+\s+\S+\s+track\s+\S+\s+\S+\s+\S+\s+)[-\d.]+",
@@ -118,6 +143,8 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s
text = set_start_time(text, case["time"])
if "track_friction" in case:
text = set_track_friction(text, case["track_friction"])
+ if "track_events" in case:
+ text = add_track_events(text, case["track_events"])
fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1")
# vars first: {{vehicle}} inside a var's value gets filled in the second pass
fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"})
@@ -126,6 +153,9 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s
# events of the case go in before it (read after it they never fire), trainsets after it
# (placed before it they stand on unlinked track and derail at once)
before, trainsets = split_trainsets(fragment)
+ if case.get("test_config"):
+ # settings of the test mode (test.timeout and so on), read like any other config block
+ before = "config\n" + "".join(line + "\n" for line in case["test_config"]) + "endconfig\n" + before
header = f"\n// ---- autotest: {case_name} ----\n"
firstinit = re.search(r"(?im)^\s*firstinit\b", text)
if firstinit:
@@ -200,20 +230,30 @@ STARTUP_TIMEOUT = 120.0
@dataclass
class RunResult:
rows: list[list[float]] = field(default_factory=list)
- exit_code: int | None = None # None: still running when we closed it (the normal end)
+ exit_code: int | None = None # None: still running when we closed it (the normal end with --watch)
+ verdict: str = "" # the simulator's own line about the test result
failure: str = "" # why the run was cut short
wall_seconds: float = 0.0
logs: dict[str, Path] = field(default_factory=dict)
def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog: Path,
- duration: float, timeout: float, say) -> RunResult:
+ duration: float | None, timeout: float, watch: bool, say) -> RunResult:
+ """Runs the simulator on the scenery. In test mode it quits by itself and the exit code
+ is the result; with watch it runs in a window and gets closed after `duration`."""
physicslog.unlink(missing_ok=True)
- cmd = [str(exe), "-s", scenery, "-v", "ghostview", "-ini", str(ini)]
+ if watch:
+ cmd = [str(exe), "-s", scenery, "-v", "ghostview", "-ini", str(ini)]
+ else:
+ cmd = [str(exe), "--test", "-s", scenery, "-ini", str(ini)]
+ if duration is not None:
+ cmd += ["--test-timeout", f"{duration:g}"]
say(" $ " + " ".join(f'"{c}"' if " " in c else c for c in cmd), progress=True)
since = time.time() - 1
started = time.monotonic()
- proc = subprocess.Popen(cmd, cwd=game_dir)
+ # the test result line goes to stdout; a file, not a pipe, so a chatty run can't block on it
+ stdout = (ini.parent / "stdout.txt").open("w+b")
+ proc = subprocess.Popen(cmd, cwd=game_dir, stdout=stdout, stderr=subprocess.STDOUT)
result = RunResult()
last_report = 0.0
try:
@@ -229,7 +269,7 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
if proc.poll() is not None:
result.exit_code = proc.returncode
break
- if sim_t >= duration:
+ if watch and sim_t >= duration:
break
if wall > timeout:
result.failure = f"timed out after {timeout:.0f}s before {duration}s of simulation"
@@ -252,6 +292,10 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog
except subprocess.TimeoutExpired:
proc.kill()
result.wall_seconds = time.monotonic() - started
+ stdout.seek(0)
+ result.verdict = next((line.strip() for line in stdout.read().decode(errors="replace").splitlines()
+ if line.startswith("test:")), "")
+ stdout.close()
result.rows = read_physicslog(physicslog)
result.logs = find_logs(game_dir, scenery, since)
return result
@@ -422,7 +466,14 @@ def count_lines(path: Path) -> int:
return 0
-def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, say) -> bool:
+def describe_exit(code: int | None) -> str:
+ if code is None:
+ return "none, still running"
+ name = EXIT_RESULTS.get(code)
+ return f"{code} ({name})" if name else f"{code} (0x{code & 0xFFFFFFFF:08X}, a crash?)"
+
+
+def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say) -> bool:
case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8"))
say(f"\n=== {name}: {case.get('description', '')}")
out = OUT_DIR / name
@@ -436,8 +487,16 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, say) -> boo
ini.write_text(TEST_INI.format(timespeed=timespeed), encoding="ascii")
physicslog = game_dir / "physicslog" / f"{vehicle}.dat"
+ duration = float(case["duration"]) if "duration" in case else None
+ # a case that only records `duration` seconds ends on the test timeout; one that says
+ # how the test ends (a pass event, a signal passed at danger...) expects that result
+ expect = case.get("expect", "timeout" if duration is not None else "pass")
+ if expect not in EXIT_RESULTS.values():
+ sys.exit(f"{name}: expect must be one of {', '.join(EXIT_RESULTS.values())}")
+ if watch and duration is None:
+ sys.exit(f"{name}: --watch needs a case with duration")
result = run_simulator(exe, game_dir, scenery, ini, physicslog,
- float(case["duration"]), float(case.get("timeout", 600)), say)
+ duration, float(case.get("timeout", 600)), watch, say)
# the logs are ours alone (named after the case scenery), move them out of the game dir
for kind, path in result.logs.items():
@@ -448,18 +507,26 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, say) -> boo
ok = True
sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
say(f" ran {result.wall_seconds:.0f}s wall, {sim_t:.1f}s of physicslog, results in {out.relative_to(REPO)}")
- if result.exit_code is not None:
- say(f" FAIL simulator exited on its own with code {result.exit_code}")
- ok = False
+ if watch:
+ if result.exit_code is not None:
+ say(f" FAIL simulator exited on its own with code {result.exit_code}")
+ ok = False
+ else:
+ if result.verdict:
+ say(f" {result.verdict}")
+ got = EXIT_RESULTS.get(result.exit_code) if result.exit_code is not None else None
+ passed = got == expect
+ say(f" {'PASS' if passed else 'FAIL'} exit code {describe_exit(result.exit_code)}, expected {expect}")
+ ok &= passed
if result.failure:
say(f" FAIL {result.failure}")
ok = False
- if not result.rows:
+ if not result.rows and case.get("checks"):
if not result.failure:
say(f" FAIL no physicslog for '{vehicle}'")
return False
- for check in case["checks"]:
+ for check in case.get("checks", []):
params = {k: v for k, v in check.items() if k != "type"}
passed, detail = CHECKS[check["type"]](result.rows, **params)
say(f" {'PASS' if passed else 'FAIL'} {check['type']}: {detail}")
@@ -479,12 +546,13 @@ def main() -> int:
ap.add_argument("--game-dir", default=os.environ.get("EU07_GAME_DIR"),
help="game install with scenery/ and dynamic/ (or EU07_GAME_DIR)")
ap.add_argument("--exe", help="simulator executable (default: newest cmake-build-*/bin/Release/eu07*.exe)")
- # 20 gave the same speed profile as 1 within a few km/h and seconds on eu07_td_timetable,
- # in 20 s instead of 4 min; 1 is for watching a run
- ap.add_argument("--timespeed", type=float, default=20.0,
- help="simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 20)")
+ ap.add_argument("--watch", action="store_true",
+ help="run in a visible window in real time (see --timespeed) instead of the test mode, "
+ "closed after the case's duration; the exit code isn't checked")
+ ap.add_argument("--timespeed", type=float, default=1.0,
+ help="with --watch: simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 1)")
ap.add_argument("-j", "--jobs", type=int, default=1,
- help="cases run at once, each in its own simulator window (default 1)")
+ help="cases run at once, each in a simulator of its own (default 1)")
args = ap.parse_args()
if not args.game_dir:
@@ -504,7 +572,7 @@ def main() -> int:
def say(line, progress=False):
print(line, flush=True)
for n in names:
- results[n] = run_case(n, exe, game_dir, args.timespeed, say)
+ results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say)
else:
# each case prints its block when it is done, so parallel output does not interleave
def job(n):
@@ -512,7 +580,7 @@ def main() -> int:
def say(line, progress=False):
if not progress:
lines.append(line)
- ok = run_case(n, exe, game_dir, args.timespeed, say)
+ ok = run_case(n, exe, game_dir, args.timespeed, args.watch, say)
return n, ok, lines
with ThreadPoolExecutor(max_workers=args.jobs) as pool:
for n in names:
From 441caeed641b1a2257b382916f5dd6431b3369bc Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 17:12:11 +0100
Subject: [PATCH 30/60] refactor(simulation): tidy the test mode code
The test manager is reached through simulation::test() instead of a global,
the result cell is owned by a unique_ptr until the memory table takes it, the
cell value is compared with a margin, strings are built with std::format and
the --test settings moved to apply_test_mode_settings(). The driver's signal
check is folded into UpdateSpeedPosition(), which updates a speed table entry
and reports a signal at stop the head of the train just passed. The test.*
keys are listed with the other settings at the start of the log.
---
EU07.cpp | 5 +--
application/application.cpp | 55 ++++++++++++++++++------------
application/drivermode.cpp | 4 +--
application/scenarioloadermode.cpp | 4 +--
rendering/nullrenderer.cpp | 5 +--
simulation/simulation.cpp | 2 +-
simulation/simulationtest.cpp | 47 ++++++++++++++++++-------
simulation/simulationtest.h | 8 +++--
utilities/Globals.cpp | 4 +++
utilities/Timer.cpp | 21 +++++++++---
vehicle/Driver.cpp | 46 +++++++++++++------------
vehicle/Driver.h | 5 +--
12 files changed, 131 insertions(+), 75 deletions(-)
diff --git a/EU07.cpp b/EU07.cpp
index aac7cae11..ec3e972e7 100644
--- a/EU07.cpp
+++ b/EU07.cpp
@@ -23,6 +23,7 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include
+#include
#ifdef WITHDUMPGEN
#ifdef _WIN32
#include
@@ -150,7 +151,7 @@ int main(int argc, char *argv[])
#ifdef _WIN32
catch (std::runtime_error const &Error)
{
- ErrorLog("Critical error: " + std::string(Error.what()));
+ ErrorLog(std::format("Critical error: {}", Error.what()));
// in test mode nobody is there to close the box, the exit code tells of the error
if (false == Global.test.enabled)
{
@@ -167,5 +168,5 @@ int main(int argc, char *argv[])
#endif
// skip destructors, there are ordering errors which causes segfaults
// a test run (--test) says its result in the exit code
- std::_Exit(Global.test.enabled ? simulation::Test.exit_code() : 0);
+ std::_Exit(Global.test.enabled ? simulation::test().exit_code() : 0);
}
diff --git a/application/application.cpp b/application/application.cpp
index 37afff67f..439c01d97 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -1137,6 +1137,38 @@ void eu07_application::init_files()
}
namespace fs = std::filesystem;
+namespace
+{
+
+// the settings of the test mode (--test), over whatever the settings files say
+void apply_test_mode_settings()
+{
+ // nobody watches nor listens: no player vehicle, nothing drawn, no sound, no window in the way
+ Global.editor_session = false;
+ Global.local_start_vehicle = "ghostview";
+ Global.GfxRenderer = "null";
+ Global.NvRenderer = false;
+ Global.bSoundEnabled = false;
+ Global.python_enabled = false;
+ Global.bInactivePause = false;
+ Global.bFullScreen = false;
+ Global.fullscreen_windowed = false;
+ Global.VSync = false;
+ Global.iMultisampling = 0;
+ Global.gfx_usegles = false;
+ Global.minframetime = std::chrono::duration(0.0f);
+ Global.extra_viewports.clear();
+ Global.headtrack_conf.joy.clear();
+ // a test runs on its own
+ Global.network_servers.clear();
+ Global.network_client.reset();
+ // and the same way every time, unless given another seed (-seed, or randomseed in the settings)
+ if (!Global.random_seed)
+ Global.random_seed = seed_of("test");
+}
+
+} // namespace
+
int eu07_application::init_settings(int Argc, char *Argv[])
{
Global.asVersion = VERSION_INFO;
@@ -1241,28 +1273,7 @@ int eu07_application::init_settings(int Argc, char *Argv[])
ErrorLog("test: --test needs a scenery given with -s");
return -1;
}
- // nobody watches nor listens: no player vehicle, nothing drawn, no sound, no window in the way
- Global.editor_session = false;
- Global.local_start_vehicle = "ghostview";
- Global.GfxRenderer = "null";
- Global.NvRenderer = false;
- Global.bSoundEnabled = false;
- Global.python_enabled = false;
- Global.bInactivePause = false;
- Global.bFullScreen = false;
- Global.fullscreen_windowed = false;
- Global.VSync = false;
- Global.iMultisampling = 0;
- Global.gfx_usegles = false;
- Global.minframetime = std::chrono::duration(0.0f);
- Global.extra_viewports.clear();
- Global.headtrack_conf.joy.clear();
- // a test runs on its own
- Global.network_servers.clear();
- Global.network_client.reset();
- // and the same way every time, unless given another seed (-seed, or randomseed in the settings)
- if (!Global.random_seed)
- Global.random_seed = seed_of("test");
+ apply_test_mode_settings();
}
return 0;
diff --git a/application/drivermode.cpp b/application/drivermode.cpp
index 1b3a44d63..deb906a4a 100644
--- a/application/drivermode.cpp
+++ b/application/drivermode.cpp
@@ -309,7 +309,7 @@ bool driver_mode::update()
if (Global.test.enabled && simulation::is_ready)
{
- simulation::Test.update(deltatime);
+ simulation::test().update(deltatime);
}
}
@@ -488,7 +488,7 @@ void driver_mode::enter()
{
// the test runs as fast as it can compute, in steps of fixed length, so that runs on different machines agree
Timer::set_fixed_step(simulation::test_manager::frame_step);
- simulation::Test.start();
+ simulation::test().start();
}
set_picking(!Global.captureonstart);
diff --git a/application/scenarioloadermode.cpp b/application/scenarioloadermode.cpp
index b84c1912f..20fa46d3d 100644
--- a/application/scenarioloadermode.cpp
+++ b/application/scenarioloadermode.cpp
@@ -60,7 +60,7 @@ bool scenarioloader_mode::update() {
ErrorLog(std::format("Bad init: scenario \"{}\" couldn't be opened ({})", Global.SceneryFile, e.what()));
state.reset();
if (Global.test.enabled) {
- simulation::Test.finish(simulation::test_result::error, "scenario couldn't be opened");
+ simulation::test().finish(simulation::test_result::error, "scenario couldn't be opened");
return true;
}
Global.SceneryFile.clear();
@@ -80,7 +80,7 @@ bool scenarioloader_mode::update() {
state.reset();
if( Global.test.enabled ) {
// there's nothing to test; the exit code says the run went wrong
- simulation::Test.finish( simulation::test_result::error, "scenario loading failed" );
+ simulation::test().finish( simulation::test_result::error, "scenario loading failed" );
return true;
}
Global.SceneryFile.clear();
diff --git a/rendering/nullrenderer.cpp b/rendering/nullrenderer.cpp
index f193ad3e4..bc466e977 100644
--- a/rendering/nullrenderer.cpp
+++ b/rendering/nullrenderer.cpp
@@ -7,8 +7,9 @@ void null_imgui_renderer::BeginFrame()
{
auto &io { ImGui::GetIO() };
if( false == io.Fonts->IsBuilt() ) {
- unsigned char *pixels;
- int width, height;
+ unsigned char *pixels { nullptr };
+ int width { 0 };
+ int height { 0 };
io.Fonts->GetTexDataAsAlpha8( &pixels, &width, &height );
}
}
diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp
index 59635c38c..d10d555a3 100644
--- a/simulation/simulation.cpp
+++ b/simulation/simulation.cpp
@@ -111,7 +111,7 @@ state_manager::init_scripting_interface() {
simulation::Region->insert( memorycell );
}
// the cell a test scenery reports its result to
- simulation::Test.init_result_cell();
+ simulation::test().init_result_cell();
}
// legacy method, calculates changes in simulation state over specified time
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
index 4dbe4c24f..439f295fe 100644
--- a/simulation/simulationtest.cpp
+++ b/simulation/simulationtest.cpp
@@ -19,9 +19,29 @@ http://mozilla.org/MPL/2.0/.
#include "world/Event.h"
#include "world/MemCell.h"
+#include
+#include
+#include
+#include
+#include
+
+namespace {
+
+// the cell holds what the scenery wrote, so the values are whole numbers; the margin only keeps a stray fraction out
+bool holds(double const Value, double const Expected)
+{
+ return std::abs(Value - Expected) < 1e-6;
+}
+
+} // namespace
+
namespace simulation {
-test_manager Test;
+test_manager &test()
+{
+ static test_manager instance;
+ return instance;
+}
std::string_view to_string(test_result const Result)
{
@@ -39,11 +59,12 @@ std::string_view to_string(test_result const Result)
void test_manager::init_result_cell()
{
- auto *cell = new TMemCell({0, -1, std::string(result_cell), "memcell"});
+ auto cell { std::make_unique(scene::node_data{0, -1, std::string(result_cell), "memcell"}) };
// neither of the reported values, so that a cell nobody wrote to says nothing
cell->UpdateValues("", -1.0, 0.0, basic_event::flags::value1 | basic_event::flags::value2);
- simulation::Memory.insert(cell);
- simulation::Region->insert(cell);
+ simulation::Region->insert(cell.get());
+ // the table owns its cells
+ simulation::Memory.insert(cell.release());
}
void test_manager::start()
@@ -76,21 +97,21 @@ void test_manager::update(double const Deltatime)
if (auto const *cell = simulation::Memory.find(std::string(result_cell)))
{
auto const value { cell->Value1() };
- auto const reason { cell->Text().empty() ? std::string() : " (" + cell->Text() + ")" };
- if (value == 0.0)
+ auto const reason { cell->Text().empty() ? std::string() : std::format(" ({})", cell->Text()) };
+ if (holds(value, 0.0))
{
- finish(test_result::fail, "__test.result set to 0" + reason);
+ finish(test_result::fail, std::format("__test.result set to 0{}", reason));
return;
}
- if (value == 1.0 && false == m_passrequested)
+ if (holds(value, 1.0) && false == m_passrequested)
{
m_passrequested = true;
WriteLog(std::format("test: pass requested at {:.1f} s{}, waiting for every vehicle to stop", m_time, reason));
}
}
- auto const atrest = std::none_of(simulation::Vehicles.sequence().begin(), simulation::Vehicles.sequence().end(),
- [](TDynamicObject const *Vehicle) { return std::abs(Vehicle->GetVelocity()) > 0.01; });
+ auto const atrest { std::ranges::none_of(simulation::Vehicles.sequence(),
+ [](TDynamicObject const *Vehicle) { return std::abs(Vehicle->GetVelocity()) > 0.01; }) };
m_resttime = atrest ? m_resttime + Deltatime : 0.0;
if (m_passrequested && m_resttime >= pass_settle_time)
@@ -111,9 +132,9 @@ void test_manager::update(double const Deltatime)
}
}
-void test_manager::signal_passed_at_danger(std::string const &Vehicle, std::string const &Signal)
+void test_manager::signal_passed_at_danger(std::string_view const Vehicle, std::string_view const Signal)
{
- auto const reason { Vehicle + " passed signal " + Signal + " at danger" };
+ auto const reason { std::format("{} passed signal {} at danger", Vehicle, Signal) };
if (false == Global.test.enabled)
{
WriteLog(reason, logtype::generic);
@@ -127,7 +148,7 @@ void test_manager::signal_passed_at_danger(std::string const &Vehicle, std::stri
finish(test_result::signal_passed_at_danger, reason);
}
-void test_manager::finish(test_result const Result, std::string const &Reason)
+void test_manager::finish(test_result const Result, std::string_view const Reason)
{
if (m_finished || false == Global.test.enabled)
return;
diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h
index c9bc5437e..f47f408b7 100644
--- a/simulation/simulationtest.h
+++ b/simulation/simulationtest.h
@@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/.
#pragma once
#include
+#include
// integration test mode (eu07 --test -s , eu07/maszyna#541): the scenery runs unattended in a tight
// fixed-step loop and the simulator quits with an exit code saying how the test went
@@ -44,9 +45,9 @@ public:
// checks the end conditions after a simulation frame of Deltatime seconds
void update(double Deltatime);
// reported by a driver whose train went past a signal showing stop
- void signal_passed_at_danger(std::string const &Vehicle, std::string const &Signal);
+ void signal_passed_at_danger(std::string_view Vehicle, std::string_view Signal);
// ends the test with given result; the first call wins
- void finish(test_result Result, std::string const &Reason);
+ void finish(test_result Result, std::string_view Reason);
bool finished() const { return m_finished; }
// exit code of the process: the result, or error while the test hasn't finished
@@ -61,6 +62,7 @@ private:
double m_resttime { 0.0 }; // how long every vehicle has been standing [s]
};
-extern test_manager Test;
+// the test of the run
+test_manager &test();
} // namespace simulation
diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp
index e36223174..5cdb3ef25 100644
--- a/utilities/Globals.cpp
+++ b/utilities/Globals.cpp
@@ -1779,6 +1779,10 @@ global_settings::export_as_text( std::ostream &Output ) const {
export_as_text( Output, "gfx.shadowmap.enabled", gfx_shadowmap_enabled );
// TODO: export fpslimit
export_as_text( Output, "randomseed", Global.random_seed );
+ export_as_text( Output, "test.timeout", test.timeout );
+ export_as_text( Output, "test.standstill", test.standstill );
+ export_as_text( Output, "test.pass_on_standstill", test.pass_on_standstill );
+ export_as_text( Output, "test.fail_if_stop_overran", test.fail_if_stop_overran );
export_as_text( Output, "gfx.envmap.enabled", gfx_envmap_enabled );
export_as_text( Output, "gfx.postfx.motionblur.enabled", gfx_postfx_motionblur_enabled );
export_as_text( Output, "gfx.postfx.motionblur.shutter", gfx_postfx_motionblur_shutter );
diff --git a/utilities/Timer.cpp b/utilities/Timer.cpp
index 388330bbe..eacd2ba0a 100644
--- a/utilities/Timer.cpp
+++ b/utilities/Timer.cpp
@@ -26,7 +26,17 @@ double fRenderTime{ 0.0 };
double fSoundTimer{ 0.0 };
double fSinceStart{ 0.0 };
double override_delta = -1.0f;
-double fixed_step = 0.0;
+
+namespace {
+
+// when set (test mode), every frame lasts this long, see set_fixed_step()
+double &fixed_step()
+{
+ static double step{0.0};
+ return step;
+}
+
+} // namespace
double GetTime()
{
@@ -56,7 +66,7 @@ void set_delta_override(double t)
void set_fixed_step(double t)
{
- fixed_step = t;
+ fixed_step() = t;
}
void ResetTimers()
@@ -82,15 +92,16 @@ void UpdateTimers(bool pause)
fr = 1000000000;
#endif
DeltaRenderTime = double(count - oldCount) / double(fr);
- if (fixed_step > 0.0)
+ auto const fixedstep{fixed_step()};
+ if (fixedstep > 0.0)
{
// the frame lasts exactly as long as said, however long it took to compute; the time speed doesn't apply
- DeltaRenderTime = fixed_step;
+ DeltaRenderTime = fixedstep;
}
fRenderTime += DeltaRenderTime;
if (!pause)
{
- DeltaTime = (fixed_step > 0.0 ? 1.0 : Global.fTimeSpeed) * DeltaRenderTime;
+ DeltaTime = (fixedstep > 0.0 ? 1.0 : Global.fTimeSpeed) * DeltaRenderTime;
fSoundTimer += DeltaTime;
if (fSoundTimer > 0.1)
fSoundTimer = 0.0;
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 5f1bde20c..c0614923c 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -768,12 +768,7 @@ void TController::TableCheck(double fDistance)
{ // aktualizacja rekordów z wyjątkiem ostatniego
if (sSpeedTable[i].iFlags & spEnabled) // jeśli pozycja istotna
{
- auto const waspassed { TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) };
- auto const switchchanged { sSpeedTable[ i ].Update() };
- if( false == waspassed ) {
- CheckSignalPassedAtDanger( sSpeedTable[ i ] );
- }
- if (switchchanged)
+ if (UpdateSpeedPosition(sSpeedTable[i]))
{
if( Global.iWriteLogEnabled & 8 ) {
WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" );
@@ -823,11 +818,7 @@ void TController::TableCheck(double fDistance)
}
}
// aktualizacja ostatniego; a signal at stop often is the last, the scan doesn't go past it
- auto const lastwaspassed { TestFlag( sSpeedTable[ iLast ].iFlags, spElapsed ) };
- sSpeedTable[iLast].Update();
- if( false == lastwaspassed ) {
- CheckSignalPassedAtDanger( sSpeedTable[ iLast ] );
- }
+ UpdateSpeedPosition(sSpeedTable[iLast]);
// WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist));
if( sSpeedTable[ iLast ].fDist < fDistance ) {
TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka
@@ -838,18 +829,31 @@ void TController::TableCheck(double fDistance)
}
};
-void TController::CheckSignalPassedAtDanger( TSpeedPos const &Point ) const
+namespace {
+
+// the position is a signal showing stop (SetVelocity 0 0). SetVelocity 0 x on automatic block isn't: it may be passed after a stop
+bool is_signal_at_stop( TSpeedPos const &Point )
{
- if( false == TestFlag( Point.iFlags, spElapsed )
- || false == TestFlag( Point.iFlags, spEvent )
- || false == TestFlag( Point.iFlags, spSemaphor )
- || true == TestFlag( Point.iFlags, spStopOnSBL ) // SetVelocity 0 x on automatic block: may go on after a stop
- || Point.fVelNext != 0.0
- || Point.evEvent == nullptr
- || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only
- return;
+ return TestFlag( Point.iFlags, spEvent )
+ && TestFlag( Point.iFlags, spSemaphor )
+ && false == TestFlag( Point.iFlags, spStopOnSBL )
+ && std::abs( Point.fVelNext ) <= 0.0
+ && Point.evEvent != nullptr;
+}
+
+} // namespace
+
+bool TController::UpdateSpeedPosition( TSpeedPos &Point ) const
+{
+ auto const passedbefore { TestFlag( Point.iFlags, spElapsed ) };
+ auto const switchchanged { Point.Update() };
+ if( false == passedbefore
+ && TestFlag( Point.iFlags, spElapsed )
+ && is_signal_at_stop( Point )
+ && ( mvOccupied->CategoryFlag & 1 ) != 0 ) { // railway only
+ simulation::test().signal_passed_at_danger( OwnerName(), Point.evEvent->m_name );
}
- simulation::Test.signal_passed_at_danger( OwnerName(), Point.evEvent->m_name );
+ return switchchanged;
}
auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 8c12087f9..8f2015f2f 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -519,8 +519,9 @@ private:
bool TableNotFound( basic_event const *Event, double const Distance ) const;
void TableTraceRoute( double fDistance, TDynamicObject *pVehicle );
void TableCheck( double fDistance );
- // reports the train going past a signal showing stop (SetVelocity 0 0); called once the head passed Point
- void CheckSignalPassedAtDanger( TSpeedPos const &Point ) const;
+ // updates a position of the speed table, returns true when a switch on it changed (TSpeedPos::Update).
+ // reports the head of the train going past it, if it's a signal showing stop
+ bool UpdateSpeedPosition( TSpeedPos &Point ) const;
TCommandType TableUpdate( double &fVelDes, double &fDist, double &fNext, double &fAcc );
bool TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance );
bool TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex );
From dd019d88ba4f45c711e37abe00782c27207ed5be Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 17:38:37 +0100
Subject: [PATCH 31/60] feat(simulation): the test mode takes no input from
outside (eu07/maszyna#541)
With --test the gamepad, mouse picking, UART, ZeroMQ and motion telemetry are
off, the hidden window gets no key, mouse, scroll or char callbacks, and the
window procedure that takes WM_COPYDATA commands from other programs isn't
installed, so nothing but the scenery drives a test run.
---
application/application.cpp | 22 ++++++++++++++++++----
1 file changed, 18 insertions(+), 4 deletions(-)
diff --git a/application/application.cpp b/application/application.cpp
index 439c01d97..eaf60c7cd 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -1159,9 +1159,16 @@ void apply_test_mode_settings()
Global.minframetime = std::chrono::duration(0.0f);
Global.extra_viewports.clear();
Global.headtrack_conf.joy.clear();
- // a test runs on its own
+ // a test runs on its own: no network, and no input from outside (eu07/maszyna#541)
Global.network_servers.clear();
Global.network_client.reset();
+ Global.InputGamepad = false;
+ Global.InputMouse = false;
+ Global.uart_conf.enable = false;
+ Global.motiontelemetry_conf.enable = false;
+#ifdef WITH_ZMQ
+ Global.zmq_address.clear();
+#endif
// and the same way every time, unless given another seed (-seed, or randomseed in the settings)
if (!Global.random_seed)
Global.random_seed = seed_of("test");
@@ -1431,7 +1438,9 @@ int eu07_application::init_glfw()
#ifdef _WIN32
// setup wrapper for base glfw window proc, to handle copydata messages
Hwnd = glfwGetWin32Window(mainwindow);
- BaseWindowProc = (WNDPROC)::SetWindowLongPtr(Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc);
+ // commands sent by other programs are input from outside, which a test doesn't take
+ if (false == Global.test.enabled)
+ BaseWindowProc = (WNDPROC)::SetWindowLongPtr(Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc);
// switch off the topmost flag
::SetWindowPos(Hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
#endif
@@ -1445,13 +1454,18 @@ void eu07_application::init_callbacks()
auto *window{m_windows.front()};
glfwSetWindowSizeCallback(window, window_resize_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_resize_callback);
+ glfwSetWindowFocusCallback(window, focus_callback);
+ glfwSetCursorEnterCallback(window, cursor_enter_callback);
+ if (Global.test.enabled)
+ {
+ // a test takes no input: keys and clicks sent to its hidden window would change the run
+ return;
+ }
glfwSetCursorPosCallback(window, cursor_pos_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetKeyCallback(window, key_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetCharCallback(window, char_callback);
- glfwSetWindowFocusCallback(window, focus_callback);
- glfwSetCursorEnterCallback(window, cursor_enter_callback);
}
int eu07_application::init_ogl()
From 6ccf4b14bf8a02fb7835dd20837db54ed5a5edcb Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sat, 7 Nov 2026 17:38:38 +0100
Subject: [PATCH 32/60] feat(simulation): test.no_movement_before_pass, a pass
that doesn't wait for a stop
The config key from eu07/maszyna#541. By default (yes) a pass reported to
__test.result waits until every vehicle has stood still for 1 s; with no it
ends the test at once. The key is listed with the other test.* settings in the
log and in the test start line.
Scenario tests: new case test_mode_pass_while_moving reports the pass from
event2 of tor1k as the train runs onto it and checks the run ended with the
train still moving (new check ends_moving). The README lists the test.* keys
with their defaults and the input the test mode ignores.
---
simulation/simulationtest.cpp | 10 +++++--
tests/scenarios/README.md | 18 +++++++++++-
.../cases/test_mode_pass_while_moving.json | 28 +++++++++++++++++++
tests/scenarios/run.py | 10 +++++++
utilities/Globals.cpp | 7 +++++
utilities/Globals.h | 1 +
6 files changed, 71 insertions(+), 3 deletions(-)
create mode 100644 tests/scenarios/cases/test_mode_pass_while_moving.json
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
index 439f295fe..8d57505ff 100644
--- a/simulation/simulationtest.cpp
+++ b/simulation/simulationtest.cpp
@@ -82,9 +82,10 @@ void test_manager::start()
}
// a pause set by the scenery or the settings would never be lifted, nobody is there to press the key
Global.iPause = 0;
- WriteLog(std::format("test: started, timeout {:.0f} s, standstill {:.0f} s{}{}", Global.test.timeout, Global.test.standstill,
+ WriteLog(std::format("test: started, timeout {:.0f} s, standstill {:.0f} s{}{}{}", Global.test.timeout, Global.test.standstill,
Global.test.pass_on_standstill ? ", standstill passes" : "",
- Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed"));
+ Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed",
+ Global.test.no_movement_before_pass ? "" : ", pass without waiting for a stop"));
}
void test_manager::update(double const Deltatime)
@@ -103,6 +104,11 @@ void test_manager::update(double const Deltatime)
finish(test_result::fail, std::format("__test.result set to 0{}", reason));
return;
}
+ if (holds(value, 1.0) && false == Global.test.no_movement_before_pass)
+ {
+ finish(test_result::pass, std::format("__test.result set to 1{}", reason));
+ return;
+ }
if (holds(value, 1.0) && false == m_passrequested)
{
m_passrequested = true;
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 1ebd84c75..b57fc4a05 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -23,6 +23,9 @@ With `--test` the simulator:
data) but no textures, and the window stays hidden,
- has no sound, no network, no python, no pause (not even one set by the scenery), and
no crash dialog,
+- takes no input from outside: keys and mouse sent to its window, gamepad, UART (a cab
+ desk), ZeroMQ and commands sent by other programs (`WM_COPYDATA`) are all ignored, and
+ motion telemetry is off,
- runs the simulation as fast as it can in fixed steps of 0.03 s of simulation time per
frame (three 10 ms physics steps), whatever the real time, the time speed or the machine,
- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so two
@@ -48,7 +51,7 @@ The test ends with the first of these:
| exit code | result | when |
| --- | --- | --- |
-| 0 | pass | `__test.result` was set to 1 and then every vehicle stood still for 1 s, so a train still moving towards a signal at stop has to stop first. Also the standstill end with `test.pass_on_standstill yes` |
+| 0 | pass | `__test.result` was set to 1 and then every vehicle stood still for 1 s, so a train still moving towards a signal at stop has to stop first (with `test.no_movement_before_pass no` the pass ends the test at once). Also the standstill end with `test.pass_on_standstill yes` |
| 1 | fail | `__test.result` was set to 0; ends at once |
| 2 | signal passed at danger | a train went past a signal showing stop (`SetVelocity 0 0`; `SetVelocity 0 x` on automatic block, which may be passed after a stop, doesn't count); ends at once, unless `test.fail_if_stop_overran no` |
| 3 | timeout | `test.timeout` seconds of simulation time went by (default 3600) |
@@ -65,9 +68,18 @@ test.timeout 600
test.standstill 120
test.pass_on_standstill no
test.fail_if_stop_overran yes
+test.no_movement_before_pass yes
endconfig
```
+| key | default | meaning |
+| --- | --- | --- |
+| `test.timeout` | 3600 | seconds of simulation time before the test ends as `timeout`; 0 = never |
+| `test.standstill` | 300 | seconds with every vehicle still and no result before the test ends as `standstill`; 0 = never |
+| `test.pass_on_standstill` | no | the standstill end passes the test instead |
+| `test.fail_if_stop_overran` | yes | a signal passed at danger ends the test; with `no` it's only logged |
+| `test.no_movement_before_pass` | yes | a pass waits until every vehicle stands still; with `no` it ends the test at once |
+
`--test-timeout` on the command line wins over `test.timeout` of the scenery.
A signal is passed at danger when the head of a train goes past a signal which its driver
@@ -155,6 +167,8 @@ on `tor1k`, the track in front of the signal.
The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass
event), `test_mode_signal_passed_at_danger` (exit 2), `test_mode_timeout` (exit 3, from
`test.timeout`) and `test_mode_standstill` (exit 4, from `test.standstill`).
+`test_mode_pass_while_moving` reports the pass from `event2` of `tor1k` (the direction the train runs), as the train runs onto
+it, with `test.no_movement_before_pass no`, so the test ends with the train still moving.
Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use
the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are
@@ -178,6 +192,8 @@ the row instead, logged by builds from this branch on.
moving off, the wheels stop slipping within `within` seconds.
- `holds_still` `moving_speed`, `stop_speed`, `max_distance` (*vehicle speed*): once stopped
after moving off, moves no more than `max_distance` metres, e.g. no creeping on locked wheels.
+- `ends_moving` `min_speed`: the last row of the physicslog is at `min_speed` or faster, e.g.
+ the test ended without waiting for the train to stop.
New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's
parameters and returns `(passed, detail)`.
diff --git a/tests/scenarios/cases/test_mode_pass_while_moving.json b/tests/scenarios/cases/test_mode_pass_while_moving.json
new file mode 100644
index 000000000..cdf798f16
--- /dev/null
+++ b/tests/scenarios/cases/test_mode_pass_while_moving.json
@@ -0,0 +1,28 @@
+{
+ "description": "Test mode, pass without waiting for a stop: like test_mode_pass, but event2 of the track in front of the exit signal reports the pass as the train runs onto it, and with test.no_movement_before_pass no the test ends at once, the train still moving.",
+ "base_scenery": "td.scn",
+ "time": "10:34",
+ "fragment": "td_red_signal_pass.scn",
+ "track_events": {
+ "tor1k": "event2 test_pass"
+ },
+ "test_config": [
+ "test.no_movement_before_pass no"
+ ],
+ "vars": {
+ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic"
+ },
+ "expect": "pass",
+ "timeout": 600,
+ "checks": [
+ {
+ "type": "starts",
+ "min_speed": 5,
+ "within": 150
+ },
+ {
+ "type": "ends_moving",
+ "min_speed": 3
+ }
+ ]
+}
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 770069d12..4c3383081 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -416,6 +416,15 @@ def check_holds_still(rows, moving_speed, stop_speed, max_distance):
return d <= max_distance, detail
+def check_ends_moving(rows, min_speed):
+ """The run ended with the vehicle still moving, e.g. a pass that didn't wait for the trains to stop."""
+ if not rows:
+ return False, "the physicslog is empty"
+ last = rows[-1]
+ ok = last[COL_VELOCITY] >= min_speed
+ return ok, f"last row t={last[COL_TIME]:.1f}s, v={last[COL_VELOCITY]:.1f} km/h (wanted >= {min_speed})"
+
+
def check_slip_clears(rows, moving_speed, stop_speed, within):
"""Once the vehicle has stopped after moving off, its wheels stop slipping within `within` seconds
(a vehicle left skidding on locked wheels keeps its brakes capped by the sliding adhesion)."""
@@ -444,6 +453,7 @@ CHECKS = {
"stops": check_stops,
"stays_stopped": check_stays_stopped,
"distance": check_distance,
+ "ends_moving": check_ends_moving,
}
diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp
index 5cdb3ef25..2516da29e 100644
--- a/utilities/Globals.cpp
+++ b/utilities/Globals.cpp
@@ -487,6 +487,12 @@ bool global_settings::ConfigParseTest(cParser& Parser, const std::string& token)
return true;
}
+ if (token == "test.no_movement_before_pass")
+ {
+ ParseOne(Parser, test.no_movement_before_pass);
+ return true;
+ }
+
return false;
}
@@ -1783,6 +1789,7 @@ global_settings::export_as_text( std::ostream &Output ) const {
export_as_text( Output, "test.standstill", test.standstill );
export_as_text( Output, "test.pass_on_standstill", test.pass_on_standstill );
export_as_text( Output, "test.fail_if_stop_overran", test.fail_if_stop_overran );
+ export_as_text( Output, "test.no_movement_before_pass", test.no_movement_before_pass );
export_as_text( Output, "gfx.envmap.enabled", gfx_envmap_enabled );
export_as_text( Output, "gfx.postfx.motionblur.enabled", gfx_postfx_motionblur_enabled );
export_as_text( Output, "gfx.postfx.motionblur.shutter", gfx_postfx_motionblur_shutter );
diff --git a/utilities/Globals.h b/utilities/Globals.h
index 8fa04e9ce..a6a9e1226 100644
--- a/utilities/Globals.h
+++ b/utilities/Globals.h
@@ -93,6 +93,7 @@ struct global_settings {
double standstill{ 300.0 }; // [s] every vehicle standing still this long ends the test; 0 = never
bool pass_on_standstill{ false }; // the standstill end passes the test instead of failing it
bool fail_if_stop_overran{ true }; // a train passing a signal at stop ends the test as failed; with false it's only logged
+ bool no_movement_before_pass{ true }; // a pass waits until every vehicle stands still; with false it ends the test at once
bool timeout_from_command_line{ false }; // --test-timeout given, the scenery doesn't override it
} test;
bool editor_tracks{ false }; // F3 track workspace: draw and pick tracks without the scenery draw-range cap
From 8d1d9eec9b2f2e0ae15dc20f21c943e7f9693c89 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 18:10:47 +0100
Subject: [PATCH 33/60] AI braking: smaller steps, earlier, while approaching a
stop or a lower speed
Changes to how the AI works the train brake on the way to a lower speed
or a stop, so that it uses few, early applications instead of a late
deep one:
- Approaching a lower speed, the deceleration may fall short of the
demand by only half of a step (fBrake_a1) before the brake is applied
harder. With a full step the demand crept up meanwhile and a long G
train got its next step many seconds too late.
- The shortfall is checked every 3 s. If it keeps growing at a handle
left alone for longer than the brake takes to respond, the AI adds a
small step at once instead of waiting until the margin calls for a
deep one. A shortfall that shrinks on its own (brake still filling,
blocks gripping harder at lower speed) does not trigger it.
- Releasing, a position short of the first one counts as giving the
minimum stage of the distributor, not less.
- Holding the speed on a descent, the predicted excess speed is taken
off over the time the brake takes to respond, not at once, so a slow
brake does not get a deep application that then takes as long to
release.
---
vehicle/Driver.cpp | 69 ++++++++++++++++++++++++++++++++++++++++------
vehicle/Driver.h | 5 ++++
2 files changed, 65 insertions(+), 9 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 8d2a3fac6..ea78e655c 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -2928,6 +2928,9 @@ bool TController::ReleaseEngine() {
return OK;
}
+// defined further down, with the braking demand it is used for
+static double brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 );
+
bool TController::IncBrake()
{ // zwiększenie hamowania
auto OK { false };
@@ -3040,7 +3043,7 @@ bool TController::IncBrake()
}
double deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]);
- if( deltaAcc > fBrake_a1[0])
+ if( deltaAcc > brake_increase_margin() )
{
if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) {
OK = /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ); //GBH
@@ -3069,10 +3072,13 @@ bool TController::IncBrake()
}
else if( BrakeCtrlPosition > 0.0
&& AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting
- && fBrakeHeldTime > (
- mvOccupied->BrakeDelayFlag > bdelay_G ?
- mvOccupied->BrakeDelay[ 1 ] :
- mvOccupied->BrakeDelay[ 3 ] ) ) {
+ && ( fBrakeHeldTime > (
+ mvOccupied->BrakeDelayFlag > bdelay_G ?
+ mvOccupied->BrakeDelay[ 1 ] :
+ mvOccupied->BrakeDelay[ 3 ] )
+ // a train falling further behind needs no full fill time to be seen not to get enough
+ || ( ( fShortfall > 0.02 )
+ && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) {
// the table says the present position is enough, but the brake has had its full fill
// time since the handle last moved and the train is still not slowing down as asked:
// believe the train rather than the table
@@ -3194,7 +3200,9 @@ bool TController::DecBrake() {
if( fBrake_a0[0] != 0.0
|| fBrake_a1[0] != 0.0 ) {
auto const pos_diff { ( is_dmu() ? 0.25 : 1.0 ) };
- deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - pos_diff )*fBrake_a1[ 0 ] );
+ // a distributor applied at all gives at least its minimum stage, about what the first position does, so
+ // a position short of the first one brakes no weaker than that
+ deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] );
}
if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) {
OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25);
@@ -7701,7 +7709,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
// train is still speeding up, the prediction above has taken that off already)
auto room { brakingroom };
if( ( AbsAccS <= 0.0 )
- && ( ( VelNext > 0.0 ) || ( BrakeCtrlPosition <= 0.0 ) ) ) { // for a stop, only while the brake is still to be applied
+ && ( BrakeCtrlPosition <= 0.0 ) ) { // only while the brake is still to be applied: once it acts, the room it needs to respond is behind
room = std::max(
0.5 * brakingroom,
brakingroom - vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) );
@@ -7830,6 +7838,10 @@ TController::adjust_desired_speed_for_current_speed() {
BrakeSystem == TBrakeSystem::Pneumatic ?
std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) :
std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) };
+ // the predicted difference is to be made up over the time the brake takes to respond, not at once: with a
+ // slow brake, a demand sized to remove it at once comes on as a deep application, which then takes as
+ // long to let go, and the train ends up well below the speed it was to hold
+ auto const holdgain { std::min( 0.04, 1.0 / ( 3.6 * std::max( 1.0, horizon ) ) ) };
if( ( speedestimate > VelDesired )
&& ( VelDesired == 0.0 ) ) {
// jesli stoj, to hamuj, ale i tak juz za pozno :)
@@ -7843,7 +7855,7 @@ TController::adjust_desired_speed_for_current_speed() {
AccDesired = std::min(
AccDesired, // but don't override decceleration for VelNext
std::clamp(
- EU07_AI_NOACCELERATION - 0.04 * ( speedestimate - holdspeed ),
+ EU07_AI_NOACCELERATION - holdgain * ( speedestimate - holdspeed ),
-0.05 + fAccThreshold,
std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) );
// HACK: for cargo trains with high braking threshold ensure we cross that threshold
@@ -8151,6 +8163,20 @@ void TController::increase_tractive_force() {
cue_action( driver_hint::tractiveforceincrease );
}
+// how far the deceleration may fall short of the demand before the brake is applied harder. approaching a lower
+// speed, a pneumatic brake given a full step only once that much is missing acts too late: the demand
+// creeps up meanwhile, and in a long G train the next step takes many seconds to act, so half a step is enough
+double
+TController::brake_increase_margin() const {
+
+ if( ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( VelNext > 0.0 )
+ && ( VelNext < DirectionalVel() ) ) {
+ return 0.5 * fBrake_a1[ 0 ];
+ }
+ return fBrake_a1[ 0 ];
+}
+
void TController::control_braking_force() {
// don't touch the brakes when compressing buffers during coupling/uncoupling
@@ -8168,6 +8194,19 @@ void TController::control_braking_force() {
// resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent
auto const accdesiredresultant { AccDesired + fAccDesiredGravity };
+ // every few seconds, note how far the train falls short of the demand and whether that is getting worse: a brake
+ // still filling, or blocks gripping harder as the train slows down, make up a shortfall on their own, but a
+ // shortfall that keeps growing at a constant handle means the train is falling further behind its braking curve
+ if( ElapsedTime - fShortfallTime >= 3.0 ) {
+ auto const shortfall { AbsAccS - accdesiredresultant };
+ iShortfallGrowth = (
+ ( ( AccDesired < 0.0 ) && ( shortfall > fShortfall + 0.005 ) ) ?
+ iShortfallGrowth + 1 :
+ 0 );
+ fShortfall = shortfall;
+ fShortfallTime = ElapsedTime;
+ }
+
if( is_emu() && !ForcePNBrake ) {
// właściwie, to warunek powinien być na działający EP
// Ra: to dobrze hamuje EP w EZT
@@ -8201,7 +8240,7 @@ void TController::control_braking_force() {
} // type & dt_ezt
else {
// a stara wersja w miarę dobrze działa na składy wagonowe
- if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + fBrake_a1[0] // regular braking
+ if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking
|| fAccGravity < -0.05 && velocity < -0.1) && // also brake if uphill and slipping back
(fBrakeTime < 0.0
// the size of the brake demand decides whether to skip the reaction time, so the brake-only part
@@ -8214,6 +8253,18 @@ void TController::control_braking_force() {
// Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy
(3.0 + 0.5 * ((mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[1] : mvOccupied->BrakeDelay[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1
}
+ else if( ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( AccDesired < 0.0 )
+ && ( BrakeCtrlPosition > 0.0 )
+ && ( fShortfall > 0.02 )
+ && ( iShortfallGrowth >= 2 )
+ && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) {
+ // the train has been falling further behind the demand for a while at a handle left alone for longer than
+ // the brake takes to respond: a small step now, while it still is small, rather than the deep one the
+ // margin above would allow only once the train is far behind
+ cue_action( driver_hint::brakingforceincrease );
+ iShortfallGrowth = 0;
+ }
if ( (accdesiredresultant < fAccGravity - 0.05
|| AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that
&& accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 ) {
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 11a01517f..f1975fca6 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -311,6 +311,8 @@ private:
double DirectionalVel() const {
return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); }
+ double brake_increase_margin() const;
+
void update_timers( double const dt );
void update_logs( double const dt );
void determine_consist_state();
@@ -401,6 +403,9 @@ private:
double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal
double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie
double fBrakeHeldTime = 0.0; // czas od ostatniego przestawienia kranu hamulca zasadniczego
+ double fShortfall = 0.0; // how far the train fell short of the braking demand at the last check [m/s2]
+ double fShortfallTime = 0.0; // when that was checked
+ int iShortfallGrowth = 0; // how many checks in a row the shortfall has grown
double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam
double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?)
double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie
From 39244a88a500d51ada0f8c33ccc3056848466d22 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sat, 7 Nov 2026 21:17:12 +0100
Subject: [PATCH 34/60] tests: wait for the pressure switches before notching
up
full_power() notched up as soon as the controlling half had closed its line
contactors. In the ET42 test the locomotive brake is still at about 2.0 bar
then, right at the pressure switch threshold, so whether the second half
starts as well depended on thousandths of a bar in its cylinder: a half whose
switch is on when the controller leaves zero doesn't close its line
contactors until the controller is back at zero. Any change to the air
brakes could tip it either way (with the corrected ESt3 the second half
stayed off and the train reached 88.7 instead of 106 km/h).
The helper now waits, as a driver does, until no pressure switch in the
train cuts the start off.
---
tests/unit/scenario.cpp | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/tests/unit/scenario.cpp b/tests/unit/scenario.cpp
index b933a0ab5..4af8be18a 100644
--- a/tests/unit/scenario.cpp
+++ b/tests/unit/scenario.cpp
@@ -5,6 +5,21 @@
namespace test {
+namespace {
+
+// whether the pressure switch of a vehicle in the train still cuts the start off: a half of a locomotive whose
+// switch is on when the controller leaves zero doesn't close its line contactors until the controller is back at zero
+bool start_cut_off(consist &Train) {
+ for (std::size_t i = 0; i < Train.size(); ++i) {
+ if (Train[i].mover().ControlPressureSwitch) {
+ return true;
+ }
+ }
+ return false;
+}
+
+} // namespace
+
scenario::scenario(std::string Name, std::vector Channels, track const &Track) : m_name(std::move(Name)), m_channels(std::move(Channels)), m_track(Track) {
reseed_random();
}
@@ -53,6 +68,11 @@ void scenario::get_going() {
void scenario::full_power(double Seconds) {
auto &controlling{driver().controlling};
+ // as a driver does, wait for the brakes to let go far enough for every pressure switch of the train to allow the
+ // start; otherwise whether all the halves of a locomotive start hangs on thousandths of a bar of their cylinders
+ for (int i = 0; i < 120 && start_cut_off(m_train); ++i) {
+ wait(1.0);
+ }
controlling.IncMainCtrl(1);
for (int i = 0; i < 90 && false == controlling.StLinFlag; ++i) {
wait(1.0);
From aecc73e89337c8cc73054285a660d6cefd8c91b9 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 01:34:35 +0100
Subject: [PATCH 35/60] fix(render): antialias alpha tested edges with
multisampling (eu07/maszyna#449)
The sides of the trackbed (and grass, fences, foliage) are cut out of their
textures by the alpha test, which keeps or drops whole pixels, so their edges
stayed jagged at any multisampling level; only geometry edges got smoothed.
With multisampling on, the alpha tested materials of the opaque colour pass
now draw with GL_SAMPLE_ALPHA_TO_COVERAGE. Their shaders do the alpha test
with alpha_test_fail() of glsl_common and write as alpha the coverage of the
test edge: the alpha sharpened around the opacity threshold to go from 0 to 1
over about a pixel, so the edge keeps the place it had and gets the samples
it covers. The renderer turns alpha to coverage on per material, only for
shaders which use the helper and only in the opaque pass with a positive
opacity, so translucent, water, terrain and the other shaders are unchanged.
Without multisampling the shaders work as before.
---
ci_shadervalidator/Globals.h | 1 +
gl/glsl_common.cpp | 30 +++++++++++++++++++
gl/shader.cpp | 3 ++
gl/shader.h | 4 +++
rendering/opengl33renderer.cpp | 24 +++++++++++++++
rendering/opengl33renderer.h | 3 ++
shaders/mat_default.frag | 5 ++--
shaders/mat_default_detail.frag | 5 ++--
shaders/mat_default_specgloss.frag | 5 ++--
shaders/mat_detail_normalmap.frag | 5 ++--
shaders/mat_detail_normalmap_specgloss.frag | 5 ++--
shaders/mat_detail_parallax.frag | 5 ++--
shaders/mat_detail_parallax_specgloss.frag | 5 ++--
shaders/mat_normalmap.frag | 5 ++--
shaders/mat_normalmap_specgloss.frag | 5 ++--
shaders/mat_parallax.frag | 5 ++--
shaders/mat_parallax_specgloss.frag | 5 ++--
shaders/mat_reflmap.frag | 5 ++--
shaders/mat_reflmap_specgloss.frag | 5 ++--
shaders/mat_shadowlessnormalmap.frag | 5 ++--
.../mat_shadowlessnormalmap_specgloss.frag | 5 ++--
shaders/mat_sunlessnormalmap.frag | 5 ++--
shaders/mat_sunlessnormalmap_specgloss.frag | 5 ++--
23 files changed, 116 insertions(+), 34 deletions(-)
diff --git a/ci_shadervalidator/Globals.h b/ci_shadervalidator/Globals.h
index 16f85e802..e8f548dc3 100644
--- a/ci_shadervalidator/Globals.h
+++ b/ci_shadervalidator/Globals.h
@@ -8,6 +8,7 @@ struct _global
bool gfx_extraeffects;
bool gfx_shadergamma;
bool gfx_usegles;
+ int iMultisampling;
};
extern _global Global;
diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp
index 26c310000..a0d38de63 100644
--- a/gl/glsl_common.cpp
+++ b/gl/glsl_common.cpp
@@ -11,6 +11,7 @@ void gl::glsl_common_setup()
"#define MOTIONBLUR_ENABLED " + std::to_string((int)Global.gfx_postfx_motionblur_enabled) + "\n" +
"#define POSTFX_ENABLED " + std::to_string((int)!Global.gfx_skippipeline) + "\n" +
"#define EXTRAEFFECTS_ENABLED " + std::to_string((int)Global.gfx_extraeffects) + "\n" +
+ "#define ALPHA_TO_COVERAGE_ENABLED " + std::to_string((int)(Global.iMultisampling > 0)) + "\n" +
"#define MAX_LIGHTS " + std::to_string(MAX_LIGHTS) + "U\n" +
"#define MAX_CASCADES " + std::to_string(MAX_CASCADES) + "U\n" +
"#define MAX_PARAMS " + std::to_string(MAX_PARAMS) + "U\n" +
@@ -110,5 +111,34 @@ void gl::glsl_common_setup()
}
#endif
+ #ifdef STAGE_FRAGMENT
+ // alpha tested surfaces (positive opacity, the opaque pass) get the coverage of their alpha
+ // test edge from GL_SAMPLE_ALPHA_TO_COVERAGE, which the renderer turns on for them with
+ // multisampling; otherwise the alpha test keeps or drops whole pixels and its edges stay
+ // jagged whatever the multisampling. the alpha is sharpened to go from 0 to 1 over about
+ // a pixel around the test threshold, so the edge keeps the place and sharpness the alpha
+ // test gave it. computed before any discard, which leaves the derivatives undefined
+ float alpha_coverage(float alpha)
+ {
+ #if ALPHA_TO_COVERAGE_ENABLED
+ if (opacity > 0.0)
+ return clamp((alpha - opacity) / max(fwidth(alpha), 0.0001) + 0.5, 0.0, 1.0);
+ #endif
+ return alpha;
+ }
+
+ // true for the fragments the alpha test drops: below the opacity threshold in the opaque
+ // pass, at or above it (negative opacity) in the translucent pass. with alpha to coverage
+ // only the fragments which cover no sample at all
+ bool alpha_test_fail(float alpha, float coverage)
+ {
+ #if ALPHA_TO_COVERAGE_ENABLED
+ if (opacity > 0.0)
+ return coverage <= 0.0;
+ #endif
+ return (opacity >= 0.0 ? (alpha < opacity) : (alpha >= -opacity));
+ }
+ #endif
+
)STRING";
}
diff --git a/gl/shader.cpp b/gl/shader.cpp
index 9160a2c97..31a3e6a87 100644
--- a/gl/shader.cpp
+++ b/gl/shader.cpp
@@ -175,6 +175,8 @@ std::pair gl::shader::process_source(const std::string &fil
str += "vec4 FBOUT(vec4 x) { return " + (Global.gfx_shadergamma ? std::string("vec4(pow(x.rgb, vec3(1.0 / 2.2)), x.a)") : std::string("x")) + "; }\n";
str += read_file(basedir + filename);
+ // checked before the includes are expanded, since glsl_common defines the function
+ alpha_to_coverage = ( str.find( "alpha_test_fail(" ) != std::string::npos );
expand_includes(str, basedir);
parse_texture_entries(str);
@@ -381,6 +383,7 @@ void gl::program::attach(const gl::shader &s)
texture_conf.try_emplace(texturename, std::move(textureentry));
for (auto [paramname, paramentry] : s.param_conf)
param_conf.try_emplace(paramname, std::move(paramentry));
+ alpha_to_coverage = alpha_to_coverage || s.alpha_to_coverage;
glAttachShader(*this, *s);
}
diff --git a/gl/shader.h b/gl/shader.h
index f1735a0e9..e46c14273 100644
--- a/gl/shader.h
+++ b/gl/shader.h
@@ -63,6 +63,9 @@ namespace gl
std::unordered_map texture_conf;
std::unordered_map param_conf;
std::string name;
+ // the shader does its alpha test with alpha_test_fail() of glsl_common, so its alpha
+ // output can drive GL_SAMPLE_ALPHA_TO_COVERAGE in the opaque pass
+ bool alpha_to_coverage{ false };
#ifndef SHADERVALIDATOR_STANDALONE
private:
@@ -96,6 +99,7 @@ namespace gl
std::unordered_map texture_conf;
std::unordered_map param_conf;
+ bool alpha_to_coverage{ false };
private:
void init();
diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp
index 932ac31f2..d577312b5 100644
--- a/rendering/opengl33renderer.cpp
+++ b/rendering/opengl33renderer.cpp
@@ -1820,6 +1820,18 @@ void opengl33_renderer::setup_matrices()
OpenGLMatrices.load_matrix(glm::mat4{glm::mat3{m_renderpass.pass_camera.modelview()}});
}
+void opengl33_renderer::setup_alpha_to_coverage(bool const Enable)
+{
+ if (Enable == m_alphatocoverageenabled)
+ return;
+
+ if (Enable)
+ glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
+ else
+ glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
+ m_alphatocoverageenabled = Enable;
+}
+
void opengl33_renderer::setup_drawing(bool const Alpha)
{
if (Alpha)
@@ -1834,6 +1846,8 @@ void opengl33_renderer::setup_drawing(bool const Alpha)
glDepthMask(GL_TRUE);
m_blendingenabled = false;
}
+ // turned on again per material, by the ones which need it
+ setup_alpha_to_coverage(false);
switch (m_renderpass.draw_mode)
{
@@ -2374,6 +2388,16 @@ void opengl33_renderer::Bind_Material( material_handle const Material, TSubModel
else
model_ubs.alpha_mult = 1.0f;
+ // the alpha test drops or keeps whole pixels, so multisampling alone leaves its edges (e.g. sides
+ // of the trackbed textures) jagged. the alpha tested materials of the opaque colour pass get them
+ // antialiased with alpha to coverage instead; their shaders give the coverage as the alpha
+ setup_alpha_to_coverage(
+ Global.iMultisampling > 0
+ && false == m_blendingenabled
+ && m_renderpass.draw_mode == rendermode::color
+ && model_ubs.opacity > 0.f
+ && material.shader->alpha_to_coverage );
+
// materials which declare texture variants provide a different texture set per model instance,
// picked from the seed of the rendered instance and the variant group of the submodel
auto const &materialtextures{
diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h
index 1b4897386..0e84761e1 100644
--- a/rendering/opengl33renderer.h
+++ b/rendering/opengl33renderer.h
@@ -277,6 +277,8 @@ class opengl33_renderer : public gfx_renderer {
void setup_pass(viewport_config &Viewport, renderpass_config &Config, rendermode const Mode, float const Znear = 0.f, float const Zfar = 1.f, bool const Ignoredebug = false);
void setup_matrices();
void setup_drawing(bool const Alpha = false);
+ // alpha to coverage for the alpha tested materials of the opaque colour pass, when multisampled
+ void setup_alpha_to_coverage(bool const Enable);
void setup_shadow_unbind_map();
void setup_shadow_bind_map();
void setup_shadow_color( glm::vec4 const &Shadowcolor );
@@ -560,6 +562,7 @@ class opengl33_renderer : public gfx_renderer {
material_handle m_invalid_material;
bool m_blendingenabled;
+ bool m_alphatocoverageenabled{ false };
bool m_widelines_supported;
diff --git a/shaders/mat_default.frag b/shaders/mat_default.frag
index bc48d939c..5459f1d21 100644
--- a/shaders/mat_default.frag
+++ b/shaders/mat_default.frag
@@ -29,7 +29,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -42,7 +43,7 @@ void main()
glossiness = abs(param[1].w);
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, 0.0, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
/*
float distance = dot(f_pos.xyz, f_pos.xyz);
if( distance <= cascade_end.x ) { color.r += 0.25; }
diff --git a/shaders/mat_default_detail.frag b/shaders/mat_default_detail.frag
index 63d15c7ce..0f8ad7d5a 100644
--- a/shaders/mat_default_detail.frag
+++ b/shaders/mat_default_detail.frag
@@ -35,7 +35,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -52,7 +53,7 @@ void main()
glossiness = abs(param[1].w);
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_default_specgloss.frag b/shaders/mat_default_specgloss.frag
index 254a0cc7f..52d94aec0 100644
--- a/shaders/mat_default_specgloss.frag
+++ b/shaders/mat_default_specgloss.frag
@@ -32,7 +32,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -46,7 +47,7 @@ void main()
metalic = texture(specgloss, f_coord).b;
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
/*
float distance = dot(f_pos.xyz, f_pos.xyz);
if( distance <= cascade_end.x ) { color.r += 0.25; }
diff --git a/shaders/mat_detail_normalmap.frag b/shaders/mat_detail_normalmap.frag
index 85f552899..debfe3bab 100644
--- a/shaders/mat_detail_normalmap.frag
+++ b/shaders/mat_detail_normalmap.frag
@@ -39,7 +39,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
@@ -64,7 +65,7 @@ void main()
float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5;
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_detail_normalmap_specgloss.frag b/shaders/mat_detail_normalmap_specgloss.frag
index a3799ce1e..0fa9ea2ee 100644
--- a/shaders/mat_detail_normalmap_specgloss.frag
+++ b/shaders/mat_detail_normalmap_specgloss.frag
@@ -42,7 +42,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -72,7 +73,7 @@ void main()
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_detail_parallax.frag b/shaders/mat_detail_parallax.frag
index 75919b13f..28de25095 100644
--- a/shaders/mat_detail_parallax.frag
+++ b/shaders/mat_detail_parallax.frag
@@ -49,7 +49,8 @@ void main()
vec4 detailnormal_map = texture(detailnormalmap, f_coord_p * param[2].x);
vec4 tex_color = texture(diffuse, f_coord_p);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -72,7 +73,7 @@ void main()
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_detail_parallax_specgloss.frag b/shaders/mat_detail_parallax_specgloss.frag
index fcc33ac34..8d1b86457 100644
--- a/shaders/mat_detail_parallax_specgloss.frag
+++ b/shaders/mat_detail_parallax_specgloss.frag
@@ -55,7 +55,8 @@ void main()
vec4 tex_color = texture(diffuse, f_coord_p);
vec4 specgloss_map = texture(specgloss, f_coord_p);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
@@ -78,7 +79,7 @@ void main()
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_normalmap.frag b/shaders/mat_normalmap.frag
index 3ef505eba..9757324d8 100644
--- a/shaders/mat_normalmap.frag
+++ b/shaders/mat_normalmap.frag
@@ -34,7 +34,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -51,7 +52,7 @@ void main()
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_normalmap_specgloss.frag b/shaders/mat_normalmap_specgloss.frag
index a4b184627..3f043b51a 100644
--- a/shaders/mat_normalmap_specgloss.frag
+++ b/shaders/mat_normalmap_specgloss.frag
@@ -38,7 +38,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -57,7 +58,7 @@ void main()
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_parallax.frag b/shaders/mat_parallax.frag
index 7adac0549..49e8eb2a0 100644
--- a/shaders/mat_parallax.frag
+++ b/shaders/mat_parallax.frag
@@ -42,7 +42,8 @@ void main()
vec4 tex_color = texture(diffuse, f_coord_p);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -59,7 +60,7 @@ void main()
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_parallax_specgloss.frag b/shaders/mat_parallax_specgloss.frag
index 8b590fae1..04349ef2c 100644
--- a/shaders/mat_parallax_specgloss.frag
+++ b/shaders/mat_parallax_specgloss.frag
@@ -46,7 +46,8 @@ void main()
vec4 tex_color = texture(diffuse, f_coord_p);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -65,7 +66,7 @@ void main()
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_reflmap.frag b/shaders/mat_reflmap.frag
index bd4c4ae79..1ffdd822f 100644
--- a/shaders/mat_reflmap.frag
+++ b/shaders/mat_reflmap.frag
@@ -32,7 +32,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -49,7 +50,7 @@ void main()
if(alphatestfail)
fragcolor.r = 1.0;
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
diff --git a/shaders/mat_reflmap_specgloss.frag b/shaders/mat_reflmap_specgloss.frag
index 4c89083c7..71ebbac24 100644
--- a/shaders/mat_reflmap_specgloss.frag
+++ b/shaders/mat_reflmap_specgloss.frag
@@ -36,7 +36,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -54,7 +55,7 @@ void main()
if(alphatestfail)
fragcolor.r = 1.0;
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
diff --git a/shaders/mat_shadowlessnormalmap.frag b/shaders/mat_shadowlessnormalmap.frag
index cb2c040e9..ebf135ba1 100644
--- a/shaders/mat_shadowlessnormalmap.frag
+++ b/shaders/mat_shadowlessnormalmap.frag
@@ -34,7 +34,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -51,7 +52,7 @@ void main()
glossiness = abs(param[1].w);
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, 1.0);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_shadowlessnormalmap_specgloss.frag b/shaders/mat_shadowlessnormalmap_specgloss.frag
index adc473ff6..2bd6d215f 100644
--- a/shaders/mat_shadowlessnormalmap_specgloss.frag
+++ b/shaders/mat_shadowlessnormalmap_specgloss.frag
@@ -38,7 +38,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -56,7 +57,7 @@ void main()
metalic = texture(specgloss, f_coord).b;
fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, 1.0);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_sunlessnormalmap.frag b/shaders/mat_sunlessnormalmap.frag
index 0b3fc7f67..a5e97d30c 100644
--- a/shaders/mat_sunlessnormalmap.frag
+++ b/shaders/mat_sunlessnormalmap.frag
@@ -99,7 +99,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -115,7 +116,7 @@ void main()
float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5;
fragcolor = apply_lights_sunless(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
diff --git a/shaders/mat_sunlessnormalmap_specgloss.frag b/shaders/mat_sunlessnormalmap_specgloss.frag
index 21cc9f6e9..4e2abe1d9 100644
--- a/shaders/mat_sunlessnormalmap_specgloss.frag
+++ b/shaders/mat_sunlessnormalmap_specgloss.frag
@@ -113,7 +113,8 @@ void main()
{
vec4 tex_color = texture(diffuse, f_coord);
- bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) );
+ float alphacoverage = alpha_coverage(tex_color.a);
+ bool alphatestfail = alpha_test_fail(tex_color.a, alphacoverage);
if(alphatestfail)
discard;
// if (tex_color.a < opacity)
@@ -131,7 +132,7 @@ void main()
metalic = texture(specgloss, f_coord).b;
fragcolor = apply_lights_sunless(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone);
- vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult);
+ vec4 color = vec4(apply_fog(fragcolor), alphacoverage * alpha_mult);
#if POSTFX_ENABLED
out_color = color;
#else
From 4b769d95c1588e13acd8e9e6fea02efdae2336ca Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 02:05:45 +0100
Subject: [PATCH 36/60] fix: SOD lamp shows the doors of the whole consist in
three states (eu07/maszyna#288)
The door closure signalling lamp (i-door_blocked) showed only Doors.is_locked
of the occupied vehicle, so a door open in another car or a coupled unit
didn't show on it.
TMoverParameters::door_closure() gives the state of one vehicle (none, locked,
released, open), the driver gathers the most severe one of the train in
determine_consist_state(), next to IsAnyDoorOpen, and the lamp is lit for
locked doors, blinks for closed but released ones (a permit given, or no lock
engaged on doors that need no permit) and is dark with a door open.
doorclosuresignal in eu07.ini (default yes) switches it; with no the lamp
shows is_locked of the occupied vehicle as before. No data change needed.
---
McZapkie/MOVER.h | 17 +++++
McZapkie/Mover.cpp | 37 +++++++++++
tests/unit/test_door_closure.cpp | 110 +++++++++++++++++++++++++++++++
utilities/Globals.cpp | 7 ++
utilities/Globals.h | 2 +
vehicle/Driver.cpp | 3 +
vehicle/Driver.h | 1 +
vehicle/Train.cpp | 11 +++-
8 files changed, 187 insertions(+), 1 deletion(-)
create mode 100644 tests/unit/test_door_closure.cpp
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 16bb207fa..45e3305c0 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -261,6 +261,22 @@ enum class range_t
/// Affects the entire consist.
consist
};
+/// State of the door closure signalling (SOD) of a vehicle or a consist, ordered from the least to the most
+/// severe: the state of a consist is the most severe state of its vehicles.
+enum class door_closure_t
+{
+ /// No doors worked by the crew: the vehicle doesn't take part in the signalling.
+ none,
+ /// All doors closed and locked: they can't be opened.
+ locked,
+ /// All doors closed, but released: a permit is given, or no lock holds them shut.
+ released,
+ /// A door is open, or not fully closed yet.
+ open
+};
+/// Whether the door closure signalling lamp is lit: steadily for locked doors, in the lit phase of the
+/// blinking for released ones, never with a door open or with no doors signalled.
+bool door_closure_lamp(door_closure_t const State, bool const BlinkLit);
/// Possible settings for an enable/disable input pair (mutually exclusive).
enum class operation_t
{
@@ -2593,6 +2609,7 @@ class TMoverParameters
bool LockDoors(bool const State, range_t const Notify = range_t::consist);
bool signal_departure(bool const State, range_t const Notify = range_t::consist); // toggles departure warning
void update_doors(double const Deltatime); // door controller update
+ door_closure_t door_closure() const; // state of the door closure signalling of this vehicle
/* funkcje dla samochodow*/
bool ChangeOffsetH(double DeltaOffset);
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 20761bacb..03fa3e6db 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -8699,6 +8699,43 @@ bool TMoverParameters::signal_departure(bool const State, range_t const Notify)
return true;
}
+// state of the door closure signalling (SOD) of this vehicle: open while a door isn't fully closed, released while
+// the closed doors can be opened (a permit given, or, for doors that need none, no lock engaged), locked otherwise.
+// doors the crew doesn't close (autonomous) aren't signalled, the same as for the door lights of the consist
+door_closure_t TMoverParameters::door_closure() const
+{
+ if (Doors.range == 0.f || Doors.close_control == control_t::autonomous)
+ {
+ return door_closure_t::none;
+ }
+ if (std::ranges::any_of(Doors.instances, [](basic_door const &Door) { return false == Door.is_closed; }))
+ {
+ return door_closure_t::open;
+ }
+ if (Doors.is_locked)
+ {
+ return door_closure_t::locked;
+ }
+ if (Doors.permit_needed && std::ranges::none_of(Doors.instances, [](basic_door const &Door) { return Door.open_permit; }))
+ {
+ return door_closure_t::locked;
+ }
+ return door_closure_t::released;
+}
+
+bool door_closure_lamp(door_closure_t const State, bool const BlinkLit)
+{
+ switch (State)
+ {
+ case door_closure_t::locked:
+ return true;
+ case door_closure_t::released:
+ return BlinkLit;
+ default:
+ return false;
+ }
+}
+
// automatic door controller update
void TMoverParameters::update_doors(double const Deltatime)
{
diff --git a/tests/unit/test_door_closure.cpp b/tests/unit/test_door_closure.cpp
new file mode 100644
index 000000000..abfa5a7e1
--- /dev/null
+++ b/tests/unit/test_door_closure.cpp
@@ -0,0 +1,110 @@
+#include "stdafx.h"
+#include "doctest.h"
+#include "scenario.h"
+
+// the door closure signalling (SOD, the i-door_blocked lamp of a cab): the state of each vehicle's doors and of the
+// whole train, the most severe of its vehicles, as the driver gathers it for the lamp (eu07/maszyna#288)
+
+using test::scenario;
+using namespace test::channels;
+
+namespace {
+
+// the state of the whole train, the way TController::determine_consist_state() gathers it
+door_closure_t consist_closure(scenario &Scenario) {
+ auto closure{door_closure_t::none};
+ for (std::size_t i = 0; i < Scenario.train().size(); ++i) {
+ closure = std::max(closure, Scenario.vehicle(i).door_closure());
+ }
+ return closure;
+}
+
+} // namespace
+
+TEST_CASE("door closure: the lamp is lit for locked doors, blinks for released ones and is dark for open ones") {
+ for (auto const lit : {true, false}) {
+ CAPTURE(lit);
+ CHECK(door_closure_lamp(door_closure_t::locked, lit));
+ CHECK(door_closure_lamp(door_closure_t::released, lit) == lit);
+ CHECK_FALSE(door_closure_lamp(door_closure_t::open, lit));
+ CHECK_FALSE(door_closure_lamp(door_closure_t::none, lit));
+ }
+ // a consist takes the most severe state of its vehicles
+ CHECK(std::max(door_closure_t::none, door_closure_t::locked) == door_closure_t::locked);
+ CHECK(std::max(door_closure_t::locked, door_closure_t::released) == door_closure_t::released);
+ CHECK(std::max(door_closure_t::released, door_closure_t::open) == door_closure_t::open);
+}
+
+TEST_CASE("door closure: a unit with permits, locked, released by the permit and open, in any of its cars") {
+ scenario scenario{"door closure/elf", motion() + doors()};
+ scenario.add("elf_v1/21we-a", 1).add("elf_v1/21we-b").add("elf_v1/21we-c");
+ scenario.start_up();
+ auto &cab{scenario.cab()};
+ auto &last{scenario.vehicle(scenario.train().size() - 1)};
+ // closed with no permit: no door can be opened
+ CHECK(cab.door_closure() == door_closure_t::locked);
+ CHECK(last.door_closure() == door_closure_t::locked);
+ CHECK(consist_closure(scenario) == door_closure_t::locked);
+
+ scenario.act("permit left");
+ cab.PermitDoors(side::left, true);
+ scenario.wait(2.0);
+ CHECK(last.door_closure() == door_closure_t::released);
+ CHECK(consist_closure(scenario) == door_closure_t::released);
+
+ scenario.act("the last car opens its own door");
+ last.OperateDoors(side::left, true, range_t::local);
+ scenario.wait(5.0);
+ // the cab's own doors stay closed, the train is open all the same
+ CHECK(cab.door_closure() == door_closure_t::released);
+ CHECK(last.door_closure() == door_closure_t::open);
+ CHECK(consist_closure(scenario) == door_closure_t::open);
+
+ scenario.act("close, the steps stay out under the permit");
+ last.OperateDoors(side::left, false, range_t::local);
+ cab.OperateDoors(side::left, false);
+ scenario.wait(10.0);
+ CHECK(last.Doors.instances[side::left].position <= 0.f);
+ // a step out isn't a closed door
+ CHECK(consist_closure(scenario) == door_closure_t::open);
+
+ scenario.act("revoke the permit");
+ cab.PermitDoors(side::left, false);
+ scenario.wait(10.0);
+ CHECK(consist_closure(scenario) == door_closure_t::locked);
+}
+
+TEST_CASE("door closure: the doors of a unit without permits are released at a standstill") {
+ scenario scenario{"door closure/en57", motion() + doors()};
+ scenario.add("en57_v1/5bgaiii_led_spot", 1).add("en57_v1/6ba_840").add("en57_v1/5bgb");
+ scenario.start_up();
+ auto &cab{scenario.cab()};
+ auto &middle{scenario.vehicle(1)};
+ REQUIRE_FALSE(cab.Doors.permit_needed);
+ REQUIRE(middle.Doors.permit_needed);
+ // the door lock engages only once the train runs (DoorLockSpeed), till then the end cars' doors can be opened
+ CHECK(cab.door_closure() == door_closure_t::released);
+ CHECK(middle.door_closure() == door_closure_t::locked);
+ CHECK(consist_closure(scenario) == door_closure_t::released);
+ scenario.act("open right");
+ cab.OperateDoors(side::right, true);
+ scenario.wait(10.0);
+ CHECK(consist_closure(scenario) == door_closure_t::open);
+ scenario.act("close right");
+ cab.OperateDoors(side::right, false);
+ scenario.wait(10.0);
+ CHECK(consist_closure(scenario) == door_closure_t::released);
+}
+
+TEST_CASE("door closure: a locomotive has no doors to signal, its coach does") {
+ scenario scenario{"door closure/eu07 with a coach", motion() + doors()};
+ scenario.add("4e_v1/4e", 1).add("bdhpumn_v3/bdhpumn");
+ scenario.start_up();
+ CHECK(scenario.cab().door_closure() == door_closure_t::none);
+ scenario.act("open right");
+ scenario.cab().PermitDoors(side::right, true);
+ scenario.cab().OperateDoors(side::right, true);
+ scenario.wait(10.0);
+ CHECK(scenario.vehicle(1).door_closure() == door_closure_t::open);
+ CHECK(consist_closure(scenario) == door_closure_t::open);
+}
diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp
index b4f2e14be..a8aadec22 100644
--- a/utilities/Globals.cpp
+++ b/utilities/Globals.cpp
@@ -506,6 +506,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string&
return true;
}
+ if (token == "doorclosuresignal")
+ {
+ ParseOne(Parser, DoorClosureSignal);
+ return true;
+ }
+
if (token == "movelight")
{
ParseOne(Parser, fMoveLight, 1, false);
@@ -1573,6 +1579,7 @@ global_settings::export_as_text( std::ostream &Output ) const {
export_as_text( Output, "skyenabled", asSky );
export_as_text( Output, "defaultext", szDefaultExt );
export_as_text( Output, "newaircouplers", bnewAirCouplers );
+ export_as_text( Output, "doorclosuresignal", DoorClosureSignal );
export_as_text( Output, "anisotropicfiltering", AnisotropicFiltering );
export_as_text( Output, "usevbo", bUseVBO );
export_as_text( Output, "feedbackmode", iFeedbackMode );
diff --git a/utilities/Globals.h b/utilities/Globals.h
index ad216cd96..971f8495a 100644
--- a/utilities/Globals.h
+++ b/utilities/Globals.h
@@ -115,6 +115,8 @@ struct global_settings {
std::string Period{}; // time of the day, based on sun position
bool FullPhysics{ true }; // full calculations performed for each simulation step
bool bnewAirCouplers{ true };
+ bool DoorClosureSignal{ true }; // door closure signalling lamp (i-door_blocked) shows the doors of the whole consist in three states
+
float fMoveLight{ 0.f }; // numer dnia w roku albo -1
bool FakeLight{ false }; // toggle between fixed and dynamic daylight
double fTimeSpeed{ 1.0 }; // przyspieszenie czasu, zmienna do testów
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 9f83b6d53..778b97004 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -5937,6 +5937,7 @@ TController::determine_consist_state() {
IsAnyDoorOnlyOpen[ side::right ] = IsAnyDoorOnlyOpen[ side::left ] = false;
IsAnyDoorOpen[ side::right ] = IsAnyDoorOpen[ side::left ] = false;
IsAnyDoorPermitActive[ side::right ] = IsAnyDoorPermitActive[ side::left ] = false;
+ auto doorclosure { door_closure_t::none };
ConsistShade = 0.0;
auto *p { pVehicles[ end::front ] }; // pojazd na czole składu
double dy; // składowa styczna grawitacji, w przedziale <0,1>
@@ -5998,12 +5999,14 @@ TController::determine_consist_state() {
IsAnyDoorPermitActive[ side::right ] |= rightdoor.open_permit;
IsAnyDoorPermitActive[ side::left ] |= leftdoor.open_permit;
}
+ doorclosure = std::max( doorclosure, vehicle->door_closure() );
}
// measure lighting level
// TBD: apply weight (multiplier) to partially lit vehicles?
ConsistShade += p->fShade > 0.0 ? p->fShade : 1.0;
p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła)
}
+ DoorClosure = doorclosure;
// calculate average amount of received sunlight
ConsistShade /= iVehicles;
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index f1975fca6..d750fc398 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -632,6 +632,7 @@ private:
bool IsAnyDoorOpen[ 2 ]; // state of door in the consist
bool IsAnyDoorOnlyOpen[ 2 ]; // state of door in the consist regardless of step
bool IsAnyDoorPermitActive[ 2 ]; // state of door permit in the consist
+ door_closure_t DoorClosure{ door_closure_t::none }; // state of the door closure signalling (SOD) of the consist
bool IsAnyLineBreakerOpen{ false }; // state of line breaker in all powered vehicles under control
bool IsAnyConverterOverloadRelayOpen{ false }; // state of converter overload relays in all vehicles under control
bool IsAnyMotorOverloadRelayOpen{ false }; // state of motor overload relays in all vehicles under control
diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp
index e30635f4f..3a4c42db1 100644
--- a/vehicle/Train.cpp
+++ b/vehicle/Train.cpp
@@ -9108,7 +9108,16 @@ bool TTrain::Update(double const Deltatime)
btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right]);
btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left]);
}
- btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked);
+ if (Global.DoorClosureSignal && DynamicObject->Mechanik != nullptr)
+ {
+ // door closure signalling (SOD) of the whole consist: lit with all doors closed and locked, blinking with
+ // them closed but released, dark with a door open
+ btLampkaBlokadaDrzwi.Turn(door_closure_lamp(DynamicObject->Mechanik->DoorClosure, simulation::Time.data().wSecond % 2 < 1));
+ }
+ else
+ {
+ btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked);
+ }
btLampkaDoorLockOff.Turn(false == mvOccupied->Doors.lock_enabled);
btLampkaDepartureSignal.Turn(mvControlled->DepartureSignal);
btLampkaNapNastHam.Turn(mvControlled->DirActive != 0 && mvOccupied->EpFuse); // napiecie na nastawniku hamulcowym
From 547706b54d769865bc9fb8239cdbdbe64f292dc8 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 09:35:59 +0100
Subject: [PATCH 37/60] refactor(simulation): fix the Sonar remarks on the test
mode code
- TController::TableCheck() calls TSpeedPos::Update() as it did before the
test mode: the check for a signal passed at danger is a call of its own
after it (CheckSignalPassedAtDanger), so the update lines nest no deeper
than on master (S134). A switch is a track, so a signal's update never
takes the switch-change branch and the check runs in the same place as
before; the physicslogs of all 15 scenario cases are byte for byte the
same.
- null_imgui_renderer is final (S1235), to_string(test_result) uses
`using enum` (S6177), init_result_cell() is const (S5817),
ConfigParseTest() takes a std::string_view (S6009) and the test settings
struct is declared apart from its member (S3646).
---
rendering/nullrenderer.h | 2 +-
simulation/simulationtest.cpp | 15 ++++++++-------
simulation/simulationtest.h | 2 +-
utilities/Globals.cpp | 12 ++++++------
utilities/Globals.h | 5 +++--
vehicle/Driver.cpp | 18 ++++++++++--------
vehicle/Driver.h | 4 ++--
7 files changed, 31 insertions(+), 27 deletions(-)
diff --git a/rendering/nullrenderer.h b/rendering/nullrenderer.h
index 2a7ef0398..7ecb57bf8 100644
--- a/rendering/nullrenderer.h
+++ b/rendering/nullrenderer.h
@@ -36,7 +36,7 @@ private:
};
// user interface backend which draws nothing: imgui still builds its frames, so the ui code runs as usual
-class null_imgui_renderer : public imgui_renderer {
+class null_imgui_renderer final : public imgui_renderer {
public:
bool Init() override { return true; }
void Shutdown() override { /* null implementation, nothing to do */ }
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
index 8d57505ff..45aa513f8 100644
--- a/simulation/simulationtest.cpp
+++ b/simulation/simulationtest.cpp
@@ -45,19 +45,20 @@ test_manager &test()
std::string_view to_string(test_result const Result)
{
+ using enum test_result;
switch (Result)
{
- case test_result::pass: return "pass";
- case test_result::fail: return "fail";
- case test_result::signal_passed_at_danger: return "signal passed at danger";
- case test_result::timeout: return "timeout";
- case test_result::standstill: return "standstill";
- case test_result::error: return "error";
+ case pass: return "pass";
+ case fail: return "fail";
+ case signal_passed_at_danger: return "signal passed at danger";
+ case timeout: return "timeout";
+ case standstill: return "standstill";
+ case error: return "error";
}
return "unknown";
}
-void test_manager::init_result_cell()
+void test_manager::init_result_cell() const
{
auto cell { std::make_unique(scene::node_data{0, -1, std::string(result_cell), "memcell"}) };
// neither of the reported values, so that a cell nobody wrote to says nothing
diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h
index f47f408b7..a58e9ae2f 100644
--- a/simulation/simulationtest.h
+++ b/simulation/simulationtest.h
@@ -39,7 +39,7 @@ public:
static constexpr double frame_step { 0.03 };
// creates the result cell; called with the other scripting interface cells, before the scenery is read
- void init_result_cell();
+ void init_result_cell() const;
// the simulation is ready: start the clocks
void start();
// checks the end conditions after a simulation frame of Deltatime seconds
diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp
index 2516da29e..3a9e10145 100644
--- a/utilities/Globals.cpp
+++ b/utilities/Globals.cpp
@@ -456,10 +456,10 @@ bool global_settings::ConfigParseInput(cParser& Parser, const std::string& token
return false;
}
-bool global_settings::ConfigParseTest(cParser& Parser, const std::string& token)
+bool global_settings::ConfigParseTest(cParser& Parser, std::string_view const Token)
{
// integration test limits, usually given in the config block of a test scenery
- if (token == "test.timeout")
+ if (Token == "test.timeout")
{
double value{ test.timeout };
ParseOne(Parser, value);
@@ -468,26 +468,26 @@ bool global_settings::ConfigParseTest(cParser& Parser, const std::string& token)
return true;
}
- if (token == "test.standstill")
+ if (Token == "test.standstill")
{
ParseOne(Parser, test.standstill);
test.standstill = std::max(0.0, test.standstill);
return true;
}
- if (token == "test.pass_on_standstill")
+ if (Token == "test.pass_on_standstill")
{
ParseOne(Parser, test.pass_on_standstill);
return true;
}
- if (token == "test.fail_if_stop_overran")
+ if (Token == "test.fail_if_stop_overran")
{
ParseOne(Parser, test.fail_if_stop_overran);
return true;
}
- if (token == "test.no_movement_before_pass")
+ if (Token == "test.no_movement_before_pass")
{
ParseOne(Parser, test.no_movement_before_pass);
return true;
diff --git a/utilities/Globals.h b/utilities/Globals.h
index a6a9e1226..11d14e34f 100644
--- a/utilities/Globals.h
+++ b/utilities/Globals.h
@@ -95,7 +95,8 @@ struct global_settings {
bool fail_if_stop_overran{ true }; // a train passing a signal at stop ends the test as failed; with false it's only logged
bool no_movement_before_pass{ true }; // a pass waits until every vehicle stands still; with false it ends the test at once
bool timeout_from_command_line{ false }; // --test-timeout given, the scenery doesn't override it
- } test;
+ };
+ test_settings test;
bool editor_tracks{ false }; // F3 track workspace: draw and pick tracks without the scenery draw-range cap
int iConvertModels{ 0 }; // tworzenie plików binarnych
int iConvertIndexRange{ 1000 }; // range of duplicate vertex scan
@@ -387,7 +388,7 @@ struct global_settings {
bool ConfigParseNetwork(cParser& Parser, const std::string& token);
bool ConfigParseHardware(cParser& Parser, const std::string& token);
bool ConfigParseDebug(cParser& Parser, const std::string& token);
- bool ConfigParseTest(cParser& Parser, const std::string& token);
+ bool ConfigParseTest(cParser& Parser, std::string_view Token);
bool ConfigParse_gfx( cParser &parser, std::string_view const Token );
// sends basic content of the class in legacy (text) format to provided stream
void
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index c0614923c..fe09fb240 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -768,7 +768,8 @@ void TController::TableCheck(double fDistance)
{ // aktualizacja rekordów z wyjątkiem ostatniego
if (sSpeedTable[i].iFlags & spEnabled) // jeśli pozycja istotna
{
- if (UpdateSpeedPosition(sSpeedTable[i]))
+ auto const passedbefore { TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) };
+ if (sSpeedTable[i].Update())
{
if( Global.iWriteLogEnabled & 8 ) {
WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" );
@@ -794,6 +795,8 @@ void TController::TableCheck(double fDistance)
// nie kontynuujemy pętli, trzeba doskanować ciąg dalszy
break;
}
+ // a switch is a track, the update of a signal never ends the loop above
+ CheckSignalPassedAtDanger( sSpeedTable[ i ], passedbefore );
if (sSpeedTable[i].iFlags & spTrack) // jeśli odcinek
{
if( sSpeedTable[ i ].fDist + sSpeedTable[ i ].trTrack->Length() < -fLength ) // a skład wyjechał całą długością poza
@@ -817,8 +820,10 @@ void TController::TableCheck(double fDistance)
}
}
}
- // aktualizacja ostatniego; a signal at stop often is the last, the scan doesn't go past it
- UpdateSpeedPosition(sSpeedTable[iLast]);
+ auto const lastpassedbefore { TestFlag( sSpeedTable[ iLast ].iFlags, spElapsed ) };
+ sSpeedTable[iLast].Update(); // aktualizacja ostatniego
+ // a signal at stop often is the last, the scan doesn't go past it
+ CheckSignalPassedAtDanger( sSpeedTable[ iLast ], lastpassedbefore );
// WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist));
if( sSpeedTable[ iLast ].fDist < fDistance ) {
TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka
@@ -843,17 +848,14 @@ bool is_signal_at_stop( TSpeedPos const &Point )
} // namespace
-bool TController::UpdateSpeedPosition( TSpeedPos &Point ) const
+void TController::CheckSignalPassedAtDanger( TSpeedPos const &Point, bool const Passedbefore ) const
{
- auto const passedbefore { TestFlag( Point.iFlags, spElapsed ) };
- auto const switchchanged { Point.Update() };
- if( false == passedbefore
+ if( false == Passedbefore
&& TestFlag( Point.iFlags, spElapsed )
&& is_signal_at_stop( Point )
&& ( mvOccupied->CategoryFlag & 1 ) != 0 ) { // railway only
simulation::test().signal_passed_at_danger( OwnerName(), Point.evEvent->m_name );
}
- return switchchanged;
}
auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 8f2015f2f..dfa63c088 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -519,9 +519,9 @@ private:
bool TableNotFound( basic_event const *Event, double const Distance ) const;
void TableTraceRoute( double fDistance, TDynamicObject *pVehicle );
void TableCheck( double fDistance );
- // updates a position of the speed table, returns true when a switch on it changed (TSpeedPos::Update).
+ // called after TSpeedPos::Update() of a position of the speed table, with its spElapsed flag from before it:
// reports the head of the train going past it, if it's a signal showing stop
- bool UpdateSpeedPosition( TSpeedPos &Point ) const;
+ void CheckSignalPassedAtDanger( TSpeedPos const &Point, bool Passedbefore ) const;
TCommandType TableUpdate( double &fVelDes, double &fDist, double &fNext, double &fAcc );
bool TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance );
bool TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex );
From 4356e7c3fd8beb83c9c22e0ae55b0ac34df7705e Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 09:36:28 +0100
Subject: [PATCH 38/60] fix(simulation): a test run that can't start ends with
the error code and says why
- `--test` is looked for before the rest of the command line is read. An
unknown option before it (e.g. `-s x.scn --test-timout 90 --test`) used
to end the run with exit code 0, which a caller reads as a pass.
- `--test-timeout` without a value, or with one that isn't a number of
seconds, fails the run instead of leaving the default or, through atof,
turning the timeout off.
- These, a missing -s, a failed start and an exception caught in main()
end the test through test_manager::conclude(), which writes the usual
`test: error (exit code 5) ... : ` line to stdout and the log.
Before, `eu07 --test` alone exited with 5 and nothing anywhere: the
error went to the log queue and the process ended before the log
thread wrote it. In test mode main() now stops the log thread and
waits for it before _Exit().
Outside the test mode nothing changes: conclude() does nothing there.
---
EU07.cpp | 21 +++++++++++++++++++++
application/application.cpp | 34 ++++++++++++++++++++++++++++++----
simulation/simulationtest.cpp | 11 ++++++++---
simulation/simulationtest.h | 5 ++++-
4 files changed, 63 insertions(+), 8 deletions(-)
diff --git a/EU07.cpp b/EU07.cpp
index ec3e972e7..790f6ffb9 100644
--- a/EU07.cpp
+++ b/EU07.cpp
@@ -84,6 +84,20 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo)
#endif
+namespace
+{
+
+// the log is written by a thread of its own, which the closing of the application stops and waits for. on the ways
+// out that skip the closing (a failed start, an exception) what was logged last would be lost with the process
+void finish_log()
+{
+ StopLogService();
+ if (auto const logservice{Global.threads.find("LogService")}; logservice != Global.threads.end() && logservice->second.joinable())
+ logservice->second.join();
+}
+
+} // namespace
+
int main(int argc, char *argv[])
{
#ifdef WITHDUMPGEN
@@ -153,6 +167,7 @@ int main(int argc, char *argv[])
{
ErrorLog(std::format("Critical error: {}", Error.what()));
// in test mode nobody is there to close the box, the exit code tells of the error
+ simulation::test().conclude(simulation::test_result::error, std::format("critical error: {}", Error.what()));
if (false == Global.test.enabled)
{
std::string msg = "Simulator crash occured :(\n";
@@ -166,6 +181,12 @@ int main(int argc, char *argv[])
fflush(stdout);
fflush(stderr);
#endif
+ if (Global.test.enabled)
+ {
+ // a run that stopped before its test ended (a failed start, an exception) says so like any other end
+ simulation::test().conclude(simulation::test_result::error, "the simulator stopped before the test ended");
+ finish_log();
+ }
// skip destructors, there are ordering errors which causes segfaults
// a test run (--test) says its result in the exit code
std::_Exit(Global.test.enabled ? simulation::test().exit_code() : 0);
diff --git a/application/application.cpp b/application/application.cpp
index eaf60c7cd..f8e20bed4 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -30,8 +30,15 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/Timer.h"
#include "utilities/dictionary.h"
#include "version_info.h"
+#include "simulation/simulationtest.h"
+#include
+#include
#include
+#include
#include
+#include
+#include
+#include
#include "utilities/translation.h"
#if WITH_DISCORD_RPC
@@ -1174,6 +1181,16 @@ void apply_test_mode_settings()
Global.random_seed = seed_of("test");
}
+// seconds given on the command line: a number, not negative. returns nothing for anything else
+std::optional parse_seconds(std::string_view const Text)
+{
+ auto const *const last{Text.data() + Text.size()};
+ double value{0.0};
+ if (auto const [parsed, status]{std::from_chars(Text.data(), last, value)}; status != std::errc{} || parsed != last || false == std::isfinite(value) || value < 0.0)
+ return std::nullopt;
+ return value;
+}
+
} // namespace
int eu07_application::init_settings(int Argc, char *Argv[])
@@ -1191,6 +1208,10 @@ int eu07_application::init_settings(int Argc, char *Argv[])
Global.LoadIniFile("eu07.ini");
}
+ // a test run is known before the rest of the command line is read, so a command line it can't take
+ // ends with the error code of the test, not with 0, which would pass it
+ Global.test.enabled = std::ranges::any_of(std::span(Argv, static_cast(Argc)), [](char const *Argument) { return std::string_view(Argument) == "--test"; });
+
// process command line arguments
bool sceneryfromcommandline{false};
bool editwithoutscenery{false};
@@ -1244,11 +1265,15 @@ int eu07_application::init_settings(int Argc, char *Argv[])
}
else if (token == "--test-timeout")
{
- if (i + 1 < Argc)
+ auto const timeout{i + 1 < Argc ? parse_seconds(Argv[++i]) : std::nullopt};
+ if (false == timeout.has_value())
{
- Global.test.timeout = std::max(0.0, std::atof(Argv[++i]));
- Global.test.timeout_from_command_line = true;
+ // a typo would otherwise turn the timeout off
+ simulation::test().conclude(simulation::test_result::error, "--test-timeout needs a number of seconds");
+ return -1;
}
+ Global.test.timeout = *timeout;
+ Global.test.timeout_from_command_line = true;
}
else if (token == "-ini")
{
@@ -1267,6 +1292,7 @@ int eu07_application::init_settings(int Argc, char *Argv[])
<< " [-seed number|word]"
<< " [-ini settingsfile]"
<< " [--test [--test-timeout seconds]]" << std::endl;
+ simulation::test().conclude(simulation::test_result::error, std::format("unknown command line argument {}", token));
return -1;
}
}
@@ -1277,7 +1303,7 @@ int eu07_application::init_settings(int Argc, char *Argv[])
{
if (false == sceneryfromcommandline || Global.SceneryFile.empty())
{
- ErrorLog("test: --test needs a scenery given with -s");
+ simulation::test().conclude(simulation::test_result::error, "--test needs a scenery given with -s");
return -1;
}
apply_test_mode_settings();
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
index 45aa513f8..214d7e463 100644
--- a/simulation/simulationtest.cpp
+++ b/simulation/simulationtest.cpp
@@ -156,9 +156,15 @@ void test_manager::signal_passed_at_danger(std::string_view const Vehicle, std::
}
void test_manager::finish(test_result const Result, std::string_view const Reason)
+{
+ if (conclude(Result, Reason))
+ Application.queue_quit(true);
+}
+
+bool test_manager::conclude(test_result const Result, std::string_view const Reason)
{
if (m_finished || false == Global.test.enabled)
- return;
+ return false;
m_finished = true;
m_result = Result;
@@ -170,8 +176,7 @@ void test_manager::finish(test_result const Result, std::string_view const Reaso
// the process has no console of its own; whoever started it with a redirected output gets the verdict there too
std::fprintf(stdout, "%s\n", line.c_str());
std::fflush(stdout);
-
- Application.queue_quit(true);
+ return true;
}
} // namespace simulation
diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h
index a58e9ae2f..2b5012e9f 100644
--- a/simulation/simulationtest.h
+++ b/simulation/simulationtest.h
@@ -46,8 +46,11 @@ public:
void update(double Deltatime);
// reported by a driver whose train went past a signal showing stop
void signal_passed_at_danger(std::string_view Vehicle, std::string_view Signal);
- // ends the test with given result; the first call wins
+ // ends the test with given result and closes the application; the first call wins
void finish(test_result Result, std::string_view Reason);
+ // ends the test with given result, without closing the application: for the ways out that close it anyway
+ // (a bad command line, a failed start, an exception). returns false if the test had already ended
+ bool conclude(test_result Result, std::string_view Reason);
bool finished() const { return m_finished; }
// exit code of the process: the result, or error while the test hasn't finished
From ced4e06b35b7945789460efed5af22c205fa0b98 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 09:36:35 +0100
Subject: [PATCH 39/60] fix(simulation): no crash message box in test mode
The crash handler of WITHDUMPGEN builds (on by default) shows a message
box before it writes the dump. It also gets the C++ exceptions nothing
catches, since it replaces the CRT's unhandled exception filter. In test
mode nobody is there to close the box, so a crashing test waited for it
until whatever started it gave up (run.py after the case's timeout,
600 s by default). The dump is still written, the exit code is the
exception's.
---
EU07.cpp | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/EU07.cpp b/EU07.cpp
index 790f6ffb9..0fbabba5b 100644
--- a/EU07.cpp
+++ b/EU07.cpp
@@ -73,7 +73,9 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo)
MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory |
MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation);
- MessageBoxA(nullptr, "Simulator crash occured :(\n", "Simulator crashed :(", MB_ICONERROR);
+ // in test mode nobody is there to close the box, and the run would wait for it until killed
+ if (false == Global.test.enabled)
+ MessageBoxA(nullptr, "Simulator crash occured :(\n", "Simulator crashed :(", MB_ICONERROR);
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, dumpType, &dumpInfo, nullptr, nullptr);
CloseHandle(hFile);
From 93e2b85d08cca5d4d374a3965c747292d59656d9 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 09:36:51 +0100
Subject: [PATCH 40/60] fix(simulation): the test mode gives nothing to the
outside and leaves the player's files alone
The test mode turned off what comes in from outside, but a few settings
of the user's eu07.ini still reached out of a test run:
- feedbackmode: 1 and 2 toggle Caps Lock / Scroll Lock by injecting key
events into the whole system, 3 and 4 drive an LPT port or a PoKeys
desk (and 4 reads the desk's switches);
- multiplayer: events are reported to a multiplayer server, and some
events are held back for it;
- execonexit: a program is run with system() at the end of each run,
which also waits for it;
- showsystemconsole: a console of the run's own pops up and stdout is
reopened on it, so whoever started the test with a redirected output
doesn't get the `test:` line (and a console the run was started from
would be hidden without it);
- imgui.ini in the game folder was written by every run, and by several
at once with run.py -j.
All of these are off in test mode. Nothing changes outside it.
---
application/application.cpp | 18 ++++++++++++++++++
application/uilayer.cpp | 5 +++++
2 files changed, 23 insertions(+)
diff --git a/application/application.cpp b/application/application.cpp
index f8e20bed4..d4aed9d8a 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -31,6 +31,9 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/dictionary.h"
#include "version_info.h"
#include "simulation/simulationtest.h"
+#ifdef _WIN32
+#include "Console.h"
+#endif
#include
#include
#include
@@ -1048,6 +1051,13 @@ void eu07_application::init_debug()
void eu07_application::init_console()
{
#ifdef _WIN32
+ if (Global.test.enabled)
+ {
+ // a test is started by whoever waits for its result, often reading its output: no console of its own
+ // (showsystemconsole) pops up and takes stdout away from them, and a console it was started from isn't hidden
+ return;
+ }
+
HWND consoleWnd = ::GetConsoleWindow();
const bool hadConsole = consoleWnd != nullptr;
@@ -1176,6 +1186,14 @@ void apply_test_mode_settings()
#ifdef WITH_ZMQ
Global.zmq_address.clear();
#endif
+ // nor anything to the outside: no keyboard leds, LPT or PoKeys desk (feedbackmode), no messages to a
+ // multiplayer server (multiplayer, which also holds some events back for it), no program run at the end
+ Global.iFeedbackMode = 0;
+#ifdef _WIN32
+ Console::ModeSet(Global.iFeedbackMode, Global.iFeedbackPort);
+#endif
+ Global.iMultiplayer = 0;
+ Global.exec_on_exit.clear();
// and the same way every time, unless given another seed (-seed, or randomseed in the settings)
if (!Global.random_seed)
Global.random_seed = seed_of("test");
diff --git a/application/uilayer.cpp b/application/uilayer.cpp
index 5443d158c..855bfbadc 100644
--- a/application/uilayer.cpp
+++ b/application/uilayer.cpp
@@ -288,6 +288,11 @@ bool ui_layer::init(GLFWwindow *Window)
IMGUI_CHECKVERSION();
ImGui::CreateContext();
m_imguiio = &ImGui::GetIO();
+ if (Global.test.enabled)
+ {
+ // a test leaves the player's window layout alone (imgui.ini in the game folder), runs in parallel included
+ m_imguiio->IniFilename = nullptr;
+ }
ImGui::GetCurrentContext()->ConfigNavWindowingKeyNext = ImGuiKey_None;
ImGui::GetCurrentContext()->ConfigNavWindowingKeyPrev = ImGuiKey_None;
// imgui.ini is read with the first frame, which may be of another mode than the editor
From 1b373bcc385e800e3a6717fc37f1fbda75f5de7c Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 09:36:56 +0100
Subject: [PATCH 41/60] docs(test): the test mode README on the new ends,
outside settings and Windows shells
- what the test mode turns off towards the outside (feedbackmode,
multiplayer, execonexit, showsystemconsole, imgui.ini),
- a command line it can't take or a failed start ends with `error`,
- cmd and PowerShell don't wait for the (windowed) simulator nor show its
output: start /wait, Start-Process -Wait,
- 15 cases, not 14.
---
tests/scenarios/README.md | 13 +++++++++++--
1 file changed, 11 insertions(+), 2 deletions(-)
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index b57fc4a05..1d63ebefe 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -26,12 +26,21 @@ With `--test` the simulator:
- takes no input from outside: keys and mouse sent to its window, gamepad, UART (a cab
desk), ZeroMQ and commands sent by other programs (`WM_COPYDATA`) are all ignored, and
motion telemetry is off,
+- gives nothing to the outside either: no keyboard leds, LPT or PoKeys (`feedbackmode`), no
+ messages to a multiplayer server (`multiplayer`), no program run at the end (`execonexit`),
+ no console window of its own (`showsystemconsole`), and the game's `imgui.ini` stays as it is,
- runs the simulation as fast as it can in fixed steps of 0.03 s of simulation time per
frame (three 10 ms physics steps), whatever the real time, the time speed or the machine,
- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so two
runs of a scenery come out the same (the physicslogs of two runs are byte for byte equal),
- quits when the test ends, and says how it ended in the exit code and in a `test: ...`
- line on stdout and in the log.
+ line on stdout and in the log. A command line it can't take, or a start that fails, ends
+ the same way with the `error` code.
+
+On Windows the simulator is a windowed program, so `cmd` and PowerShell don't wait for it nor
+show its output by themselves: run it with `start /wait eu07 --test ... > result.txt` and read
+`%errorlevel%` in `cmd`, or `(Start-Process eu07 '--test ...' -Wait -PassThru -RedirectStandardOutput result.txt).ExitCode`
+in PowerShell. Scripts (Python's `subprocess`, bash) wait for it as for any other program.
A scenery reports its result to the memory cell `__test.result`, which the simulator creates
(in every run, so a test scenery loads normally too). Write value 1 to it for a pass and 0
@@ -101,7 +110,7 @@ Python 3.10+, no extra packages. Options:
`cmake-build-*/bin/Release/eu07*.exe`. The build needs the `--test` and `-ini` command
line options.
- name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`.
-- `-j N` runs N cases at once. Each case prints its results when it is done. All 14 cases
+- `-j N` runs N cases at once. Each case prints its results when it is done. All 15 cases
take about 30 s with `-j 4`, loading included.
- `--watch` runs a case the old way, in a visible window in real time (or faster with
`--timespeed N`), closed after the case's `duration`; the exit code isn't checked then. For
From b2331ad2d185a2b4e52529b1900e90eeeecf4be7 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 09:37:32 +0100
Subject: [PATCH 42/60] docs(test): what waits for a test run in cmd, checked
start /wait gives the exit code but not the output; a .bat file waits
for the windowed simulator and passes its output on.
---
tests/scenarios/README.md | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 1d63ebefe..8ad7e7470 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -37,10 +37,11 @@ With `--test` the simulator:
line on stdout and in the log. A command line it can't take, or a start that fails, ends
the same way with the `error` code.
-On Windows the simulator is a windowed program, so `cmd` and PowerShell don't wait for it nor
-show its output by themselves: run it with `start /wait eu07 --test ... > result.txt` and read
-`%errorlevel%` in `cmd`, or `(Start-Process eu07 '--test ...' -Wait -PassThru -RedirectStandardOutput result.txt).ExitCode`
-in PowerShell. Scripts (Python's `subprocess`, bash) wait for it as for any other program.
+On Windows the simulator is a windowed program, which the `cmd` prompt and PowerShell don't wait
+for. In a `.bat` file `eu07 --test ... > result.txt` waits and sets `%errorlevel%`; at the prompt
+`start /wait eu07 --test ...` waits too but doesn't pass the output on. In PowerShell use
+`(Start-Process eu07 '--test ...' -Wait -PassThru -RedirectStandardOutput result.txt).ExitCode`.
+Scripts (Python's `subprocess`, bash) wait for it as for any other program.
A scenery reports its result to the memory cell `__test.result`, which the simulator creates
(in every run, so a test scenery loads normally too). Write value 1 to it for a pass and 0
From 62526e9d6a1b87fcb0f67cb36ba674a91da94f9c Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 11:16:33 +0100
Subject: [PATCH 43/60] test(scenarios): the timetable cases check where the
train stops, not how long
Przystanek on td.scn is a technical stop of the td/rozklad timetable (pt): the AI
doesn't wait there for the departure time but sets off as soon as it counts the
train as standing at the W4, below 1 km/h. How long the speed then stays under
0.5 km/h is only how fast the brake releases. With the AI braking of #264 the
trains creep up to the W4 at about 10 km/h on a light application and stood there
for 1-5 s; the SN61 turns back at 0.36 km/h without stopping. The hold of 5 s
(2 s for the SN61) failed for EP09, SN61 and Vectron and had well under a second
to spare for others.
The cases now check that the train comes down to 1 km/h, the AI's own standstill
at a W4, 1380-1420 m from the start; every vehicle stops at 1397-1401 m, before
and after #264. `stops` takes min_distance and max_distance for that.
---
tests/scenarios/README.md | 14 ++++++++++----
tests/scenarios/cases/en57_td_timetable.json | 2 +-
tests/scenarios/cases/ep09_td_timetable.json | 2 +-
tests/scenarios/cases/et22_td_timetable.json | 2 +-
tests/scenarios/cases/eu07_td_timetable.json | 2 +-
tests/scenarios/cases/sm42_td_timetable.json | 2 +-
tests/scenarios/cases/sn61_td_timetable.json | 2 +-
tests/scenarios/cases/vectron_td_timetable.json | 2 +-
tests/scenarios/run.py | 8 ++++++--
9 files changed, 23 insertions(+), 13 deletions(-)
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 8ad7e7470..8bd6f1a4a 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -168,7 +168,12 @@ scenery is newer.
the one whose physicslog is checked. Other vehicles of the consist take names made from it,
e.g. `{{vehicle}}_s`. The td.scn cases share two fragments, `td_timetable.scn` (route set,
train runs to Przystanek) and `td_red_signal.scn` (no route, exit signal at stop), and differ
-only in `vars.consist`. `td_red_signal_moving.scn` is the red signal one with the train
+only in `vars.consist`. Przystanek is a technical stop in that timetable (`pt`), where the AI
+doesn't wait for the departure time: it sets off as soon as it counts the train as standing at
+the W4, which is below 1 km/h, so the train stands there for a few seconds at most, or doesn't
+quite stop (since the AI braking of #264 the SN61 turns back at 0.4 km/h). The
+timetable cases therefore check that the train comes down to 1 km/h, with no hold, 1380-1420 m
+from the start (every vehicle stops at 1397-1401 m). `td_red_signal_moving.scn` is the red signal one with the train
starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels when braking
and slides past the signal, so those cases set `test.fail_if_stop_overran no`.
`td_red_signal_pass.scn` adds the `test_pass` event, which `test_mode_pass` puts as `event0`
@@ -189,13 +194,14 @@ the row instead, logged by builds from this branch on.
- `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`.
- `brakes` `min_pressure`: after moving off, brake cylinder pressure reaches `min_pressure` bar
(physicslog pressures are in bar whatever its header says; the brake pipe runs at 5.0).
-- `stops` `moving_speed`, `stop_speed`, `hold`: after reaching `moving_speed`, stays at or
- below `stop_speed` for `hold` seconds.
+- `stops` `moving_speed`, `stop_speed`, `hold`, optional `min_distance`, `max_distance`: after
+ reaching `moving_speed`, stays at or below `stop_speed` for `hold` seconds; with the distances,
+ that stop has to be between them (metres travelled, as in `distance`).
- `stays_stopped` `moving_speed`, `stop_speed`: after moving off and stopping, never goes
above `stop_speed` again.
- `distance` `min`, `max`: total distance travelled. The physicslog has no position, so the
distance comes from integrating the speed; on td.scn every vehicle's first stop after
- Stacja1 came out at 1400 m (+-3), and the red signal stop at 140 m.
+ Stacja1 came out at 1400 m (+-4), and the red signal stop at 140 m.
- `slips` `within`: the lead vehicle's wheels slip or lock at some point (within `within`
seconds if given), so a slippery rail case does what it's meant to.
- `slip_clears` `moving_speed`, `stop_speed`, `within` (*vehicle speed*): once stopped after
diff --git a/tests/scenarios/cases/en57_td_timetable.json b/tests/scenarios/cases/en57_td_timetable.json
index ddd52af37..d4c4f26fa 100644
--- a/tests/scenarios/cases/en57_td_timetable.json
+++ b/tests/scenarios/cases/en57_td_timetable.json
@@ -16,6 +16,6 @@
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "max_speed", "limit": 90, "tolerance": 3 },
{ "type": "brakes", "min_pressure": 0.5 },
- { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }
]
}
diff --git a/tests/scenarios/cases/ep09_td_timetable.json b/tests/scenarios/cases/ep09_td_timetable.json
index dd130be3c..851b4dbfe 100644
--- a/tests/scenarios/cases/ep09_td_timetable.json
+++ b/tests/scenarios/cases/ep09_td_timetable.json
@@ -12,6 +12,6 @@
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "max_speed", "limit": 90, "tolerance": 3 },
{ "type": "brakes", "min_pressure": 0.5 },
- { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }
]
}
diff --git a/tests/scenarios/cases/et22_td_timetable.json b/tests/scenarios/cases/et22_td_timetable.json
index 004f5354d..47622c622 100644
--- a/tests/scenarios/cases/et22_td_timetable.json
+++ b/tests/scenarios/cases/et22_td_timetable.json
@@ -12,6 +12,6 @@
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "max_speed", "limit": 90, "tolerance": 3 },
{ "type": "brakes", "min_pressure": 0.5 },
- { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }
]
}
diff --git a/tests/scenarios/cases/eu07_td_timetable.json b/tests/scenarios/cases/eu07_td_timetable.json
index 2f23019fe..3774242cd 100644
--- a/tests/scenarios/cases/eu07_td_timetable.json
+++ b/tests/scenarios/cases/eu07_td_timetable.json
@@ -12,6 +12,6 @@
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "max_speed", "limit": 90, "tolerance": 3 },
{ "type": "brakes", "min_pressure": 0.5 },
- { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }
]
}
diff --git a/tests/scenarios/cases/sm42_td_timetable.json b/tests/scenarios/cases/sm42_td_timetable.json
index fc89be0fa..994f94c0e 100644
--- a/tests/scenarios/cases/sm42_td_timetable.json
+++ b/tests/scenarios/cases/sm42_td_timetable.json
@@ -12,6 +12,6 @@
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "max_speed", "limit": 90, "tolerance": 3 },
{ "type": "brakes", "min_pressure": 0.5 },
- { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }
]
}
diff --git a/tests/scenarios/cases/sn61_td_timetable.json b/tests/scenarios/cases/sn61_td_timetable.json
index 9fa4b18d8..1a03c31f8 100644
--- a/tests/scenarios/cases/sn61_td_timetable.json
+++ b/tests/scenarios/cases/sn61_td_timetable.json
@@ -12,6 +12,6 @@
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "max_speed", "limit": 90, "tolerance": 3 },
{ "type": "brakes", "min_pressure": 0.5 },
- { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 2 }
+ { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }
]
}
diff --git a/tests/scenarios/cases/vectron_td_timetable.json b/tests/scenarios/cases/vectron_td_timetable.json
index 9948a09ef..04656a00f 100644
--- a/tests/scenarios/cases/vectron_td_timetable.json
+++ b/tests/scenarios/cases/vectron_td_timetable.json
@@ -12,6 +12,6 @@
{ "type": "starts", "min_speed": 20, "within": 150 },
{ "type": "max_speed", "limit": 90, "tolerance": 3 },
{ "type": "brakes", "min_pressure": 0.5 },
- { "type": "stops", "moving_speed": 20, "stop_speed": 0.5, "hold": 5 }
+ { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }
]
}
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 4c3383081..210d6c013 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -344,7 +344,7 @@ def check_brakes(rows, min_pressure, moving_speed=20):
return False, f"brake cylinder pressure never reached {min_pressure} bar after moving off"
-def check_stops(rows, moving_speed, stop_speed, hold):
+def check_stops(rows, moving_speed, stop_speed, hold, min_distance=None, max_distance=None):
start = _first_moving(rows, moving_speed)
if start is None:
return False, f"never reached {moving_speed} km/h"
@@ -356,7 +356,11 @@ def check_stops(rows, moving_speed, stop_speed, hold):
if stopped_at is None:
stopped_at = i
if r[COL_TIME] - rows[stopped_at][COL_TIME] >= hold:
- return True, f"came to a stop at t={rows[stopped_at][COL_TIME]:.1f}s after {dist[stopped_at]:.0f} m"
+ where = dist[stopped_at]
+ detail = f"came to a stop at t={rows[stopped_at][COL_TIME]:.1f}s after {where:.0f} m"
+ if (min_distance is not None and where < min_distance) or (max_distance is not None and where > max_distance):
+ return False, f"{detail}, wanted between {min_distance} and {max_distance} m"
+ return True, detail
else:
stopped_at = None
return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off"
From 486a714f521ce6d28aca9f9adc475f03817306dc Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 11:20:52 +0100
Subject: [PATCH 44/60] refactor(simulation): the rules of the test mode in a
file of their own, with unit tests
The command line options of the test mode and the end conditions checked after
each frame are now plain functions in simulation/simulationtestrules.cpp, which
needs nothing of the running simulation: parse_test_command_line() and
evaluate_frame(). The file is part of the core library, so the unit tests check
them (tests/unit/test_test_mode.cpp): the --test-timeout value, values of other
options not taken for options, a pass that waits for the stop, the standstill,
the timeout. test_manager only gathers what a frame brought and acts on the
verdict. No change in behaviour.
---
CMakeLists.txt | 3 +-
application/application.cpp | 45 +++----
simulation/simulationtest.cpp | 77 +++---------
simulation/simulationtest.h | 21 +---
simulation/simulationtestrules.cpp | 139 ++++++++++++++++++++
simulation/simulationtestrules.h | 82 ++++++++++++
tests/unit/test_test_mode.cpp | 195 +++++++++++++++++++++++++++++
7 files changed, 452 insertions(+), 110 deletions(-)
create mode 100644 simulation/simulationtestrules.cpp
create mode 100644 simulation/simulationtestrules.h
create mode 100644 tests/unit/test_test_mode.cpp
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8a4e1d6ea..483dbc146 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -454,7 +454,7 @@ endif()
add_library(eu07_settings INTERFACE)
# the parts of the simulation the game shares with the unit tests: the vehicle physics, the vehicle
-# definition parser and the helpers they use. built once, and tested as the game uses them
+# definition parser, the helpers they use and the rules of the test mode. built once, and tested as the game uses them
set(CORE_SOURCES
"McZapkie/friction.cpp"
"McZapkie/hamulce.cpp"
@@ -463,6 +463,7 @@ set(CORE_SOURCES
"utilities/parser.cpp"
"utilities/utilities.cpp"
"scripting/ladderlogic.cpp"
+"simulation/simulationtestrules.cpp"
"vehicle/handover.cpp"
"vehicle/horn.cpp"
"vehicle/smoke.cpp"
diff --git a/application/application.cpp b/application/application.cpp
index d4aed9d8a..f3c3fe46d 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -34,14 +34,9 @@ http://mozilla.org/MPL/2.0/.
#ifdef _WIN32
#include "Console.h"
#endif
-#include
-#include
#include
-#include
#include
-#include
-#include
-#include
+#include
#include "utilities/translation.h"
#if WITH_DISCORD_RPC
@@ -1199,16 +1194,6 @@ void apply_test_mode_settings()
Global.random_seed = seed_of("test");
}
-// seconds given on the command line: a number, not negative. returns nothing for anything else
-std::optional parse_seconds(std::string_view const Text)
-{
- auto const *const last{Text.data() + Text.size()};
- double value{0.0};
- if (auto const [parsed, status]{std::from_chars(Text.data(), last, value)}; status != std::errc{} || parsed != last || false == std::isfinite(value) || value < 0.0)
- return std::nullopt;
- return value;
-}
-
} // namespace
int eu07_application::init_settings(int Argc, char *Argv[])
@@ -1228,7 +1213,18 @@ int eu07_application::init_settings(int Argc, char *Argv[])
// a test run is known before the rest of the command line is read, so a command line it can't take
// ends with the error code of the test, not with 0, which would pass it
- Global.test.enabled = std::ranges::any_of(std::span(Argv, static_cast(Argc)), [](char const *Argument) { return std::string_view(Argument) == "--test"; });
+ auto const testcommandline{simulation::parse_test_command_line(std::vector(Argv, Argv + Argc))};
+ Global.test.enabled = testcommandline.enabled;
+ if (false == testcommandline.error.empty())
+ {
+ simulation::test().conclude(simulation::test_result::error, testcommandline.error);
+ return -1;
+ }
+ if (testcommandline.timeout.has_value())
+ {
+ Global.test.timeout = *testcommandline.timeout;
+ Global.test.timeout_from_command_line = true;
+ }
// process command line arguments
bool sceneryfromcommandline{false};
@@ -1278,20 +1274,13 @@ int eu07_application::init_settings(int Argc, char *Argv[])
}
else if (token == "--test")
{
- // integration test: the scenery runs unattended and the exit code is the result (eu07/maszyna#541)
- Global.test.enabled = true;
+ // integration test: the scenery runs unattended and the exit code is the result (eu07/maszyna#541),
+ // taken from the command line above
}
else if (token == "--test-timeout")
{
- auto const timeout{i + 1 < Argc ? parse_seconds(Argv[++i]) : std::nullopt};
- if (false == timeout.has_value())
- {
- // a typo would otherwise turn the timeout off
- simulation::test().conclude(simulation::test_result::error, "--test-timeout needs a number of seconds");
- return -1;
- }
- Global.test.timeout = *timeout;
- Global.test.timeout_from_command_line = true;
+ // taken from the command line above, with its value
+ ++i;
}
else if (token == "-ini")
{
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
index 214d7e463..76aa1be30 100644
--- a/simulation/simulationtest.cpp
+++ b/simulation/simulationtest.cpp
@@ -25,16 +25,6 @@ http://mozilla.org/MPL/2.0/.
#include
#include
-namespace {
-
-// the cell holds what the scenery wrote, so the values are whole numbers; the margin only keeps a stray fraction out
-bool holds(double const Value, double const Expected)
-{
- return std::abs(Value - Expected) < 1e-6;
-}
-
-} // namespace
-
namespace simulation {
test_manager &test()
@@ -43,21 +33,6 @@ test_manager &test()
return instance;
}
-std::string_view to_string(test_result const Result)
-{
- using enum test_result;
- switch (Result)
- {
- case pass: return "pass";
- case fail: return "fail";
- case signal_passed_at_danger: return "signal passed at danger";
- case timeout: return "timeout";
- case standstill: return "standstill";
- case error: return "error";
- }
- return "unknown";
-}
-
void test_manager::init_result_cell() const
{
auto cell { std::make_unique(scene::node_data{0, -1, std::string(result_cell), "memcell"}) };
@@ -73,8 +48,7 @@ void test_manager::start()
if (m_started)
return;
m_started = true;
- m_time = 0.0;
- m_resttime = 0.0;
+ m_progress = test_progress {};
if (simulation::Vehicles.sequence().empty())
{
// most likely the scenery wasn't found, or it isn't a test scenery
@@ -94,48 +68,25 @@ void test_manager::update(double const Deltatime)
if (false == m_started || m_finished)
return;
- m_time += Deltatime;
-
+ test_frame frame { Deltatime, std::nullopt, {},
+ std::ranges::none_of(simulation::Vehicles.sequence(), [](TDynamicObject const *Vehicle) { return std::abs(Vehicle->GetVelocity()) > 0.01; }) };
if (auto const *cell = simulation::Memory.find(std::string(result_cell)))
{
- auto const value { cell->Value1() };
- auto const reason { cell->Text().empty() ? std::string() : std::format(" ({})", cell->Text()) };
- if (holds(value, 0.0))
- {
- finish(test_result::fail, std::format("__test.result set to 0{}", reason));
- return;
- }
- if (holds(value, 1.0) && false == Global.test.no_movement_before_pass)
- {
- finish(test_result::pass, std::format("__test.result set to 1{}", reason));
- return;
- }
- if (holds(value, 1.0) && false == m_passrequested)
- {
- m_passrequested = true;
- WriteLog(std::format("test: pass requested at {:.1f} s{}, waiting for every vehicle to stop", m_time, reason));
- }
+ frame.reported = cell->Value1();
+ frame.reason = cell->Text();
}
- auto const atrest { std::ranges::none_of(simulation::Vehicles.sequence(),
- [](TDynamicObject const *Vehicle) { return std::abs(Vehicle->GetVelocity()) > 0.01; }) };
- m_resttime = atrest ? m_resttime + Deltatime : 0.0;
-
- if (m_passrequested && m_resttime >= pass_settle_time)
+ auto const requestedbefore { m_progress.passrequested };
+ auto const verdict { evaluate_frame(m_progress, frame, test_limits { Global.test.timeout, Global.test.standstill, Global.test.pass_on_standstill, Global.test.no_movement_before_pass }) };
+ if (verdict.has_value())
{
- finish(test_result::pass, "__test.result set to 1 and every vehicle stopped");
+ finish(verdict->result, verdict->reason);
return;
}
- if (Global.test.standstill > 0.0 && m_resttime >= Global.test.standstill)
+ if (m_progress.passrequested && false == requestedbefore)
{
- auto const reason { std::format("every vehicle stood still for {:.0f} s", Global.test.standstill) };
- finish(Global.test.pass_on_standstill ? test_result::pass : test_result::standstill, reason);
- return;
- }
- if (Global.test.timeout > 0.0 && m_time >= Global.test.timeout)
- {
- finish(test_result::timeout, std::format("no result after {:.0f} s", Global.test.timeout));
- return;
+ WriteLog(std::format("test: pass requested at {:.1f} s{}, waiting for every vehicle to stop", m_progress.time,
+ frame.reason.empty() ? std::string() : std::format(" ({})", frame.reason)));
}
}
@@ -149,7 +100,7 @@ void test_manager::signal_passed_at_danger(std::string_view const Vehicle, std::
}
if (false == Global.test.fail_if_stop_overran)
{
- WriteLog(std::format("test: {} at {:.1f} s, allowed by test.fail_if_stop_overran", reason, m_time));
+ WriteLog(std::format("test: {} at {:.1f} s, allowed by test.fail_if_stop_overran", reason, m_progress.time));
return;
}
finish(test_result::signal_passed_at_danger, reason);
@@ -168,7 +119,7 @@ bool test_manager::conclude(test_result const Result, std::string_view const Rea
m_finished = true;
m_result = Result;
- auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast(Result), m_time, Reason) };
+ auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast(Result), m_progress.time, Reason) };
if (Result == test_result::pass)
WriteLog(line);
else
diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h
index 2b5012e9f..66384b6ed 100644
--- a/simulation/simulationtest.h
+++ b/simulation/simulationtest.h
@@ -9,32 +9,19 @@ http://mozilla.org/MPL/2.0/.
#pragma once
-#include
+#include "simulation/simulationtestrules.h"
+
#include
// integration test mode (eu07 --test -s , eu07/maszyna#541): the scenery runs unattended in a tight
// fixed-step loop and the simulator quits with an exit code saying how the test went
namespace simulation {
-// exit codes of a test run; public, scripts and CI read them
-enum class test_result : int {
- pass = 0, // __test.result set to 1, then every vehicle came to rest (or test.pass_on_standstill)
- fail = 1, // __test.result set to 0
- signal_passed_at_danger = 2, // a train went past a stop signal (SetVelocity 0 0), unless test.fail_if_stop_overran no
- timeout = 3, // test.timeout seconds of simulation time went by without a result
- standstill = 4, // every vehicle stood still for test.standstill seconds without a result
- error = 5, // the run could not start (no -s, the scenery failed to load) or the simulator threw
-};
-
-std::string_view to_string(test_result Result);
-
class test_manager {
public:
// name of the memory cell a scenery reports its result to
static constexpr std::string_view result_cell { "__test.result" };
- // how long everything has to stand before a requested pass is granted [s]
- static constexpr double pass_settle_time { 1.0 };
// fixed simulation time step of one frame in test mode [s]: 3 physics steps of 10 ms
static constexpr double frame_step { 0.03 };
@@ -60,9 +47,7 @@ private:
bool m_started { false };
bool m_finished { false };
test_result m_result { test_result::error };
- bool m_passrequested { false };
- double m_time { 0.0 }; // simulation time since the start [s]
- double m_resttime { 0.0 }; // how long every vehicle has been standing [s]
+ test_progress m_progress;
};
// the test of the run
diff --git a/simulation/simulationtestrules.cpp b/simulation/simulationtestrules.cpp
new file mode 100644
index 000000000..44f740f13
--- /dev/null
+++ b/simulation/simulationtestrules.cpp
@@ -0,0 +1,139 @@
+/*
+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 "simulation/simulationtestrules.h"
+
+#include
+#include
+#include
+
+namespace {
+
+// the cell holds what the scenery wrote, so the values are whole numbers; the margin only keeps a stray fraction out
+bool holds(double const Value, double const Expected)
+{
+ return std::abs(Value - Expected) < 1e-6;
+}
+
+// the text of the result cell, as said after the result
+std::string reason_suffix(std::string_view const Reason)
+{
+ return Reason.empty() ? std::string() : std::format(" ({})", Reason);
+}
+
+// options of the simulator which take a value, see eu07_application::init_settings()
+bool takes_value(std::string_view const Option)
+{
+ return Option == "-s" || Option == "-v" || Option == "-seed" || Option == "-ini";
+}
+
+// a number of seconds given to Option, at Index of Arguments; the index is moved past the value
+std::optional option_seconds(std::span const Arguments, std::size_t &Index)
+{
+ if (Index + 1 >= Arguments.size())
+ return std::nullopt;
+ ++Index;
+ return simulation::parse_seconds(Arguments[Index]);
+}
+
+} // namespace
+
+namespace simulation {
+
+std::string_view to_string(test_result const Result)
+{
+ using enum test_result;
+ switch (Result)
+ {
+ case pass: return "pass";
+ case fail: return "fail";
+ case signal_passed_at_danger: return "signal passed at danger";
+ case timeout: return "timeout";
+ case standstill: return "standstill";
+ case error: return "error";
+ }
+ return "unknown";
+}
+
+std::optional parse_seconds(std::string_view const Text)
+{
+ auto const *const last{Text.data() + Text.size()};
+ double value{0.0};
+ if (auto const [parsed, status]{std::from_chars(Text.data(), last, value)}; status != std::errc{} || parsed != last || false == std::isfinite(value) || value < 0.0)
+ return std::nullopt;
+ return value;
+}
+
+test_command_line parse_test_command_line(std::span const Arguments)
+{
+ test_command_line result;
+ for (std::size_t i = 1; i < Arguments.size(); ++i)
+ {
+ std::string_view const option{Arguments[i]};
+ if (option == "--test")
+ {
+ result.enabled = true;
+ }
+ else if (option == "--test-timeout")
+ {
+ auto const seconds{option_seconds(Arguments, i)};
+ if (false == seconds.has_value())
+ {
+ // a typo would otherwise turn the limit off
+ if (result.error.empty())
+ result.error = std::format("{} needs a number of seconds", option);
+ continue;
+ }
+ result.timeout = seconds;
+ }
+ else if (takes_value(option))
+ {
+ ++i;
+ }
+ else if (option == "-edit" && i + 1 < Arguments.size() && Arguments[i + 1][0] != '-')
+ {
+ // the scenery to edit is optional
+ ++i;
+ }
+ }
+ return result;
+}
+
+std::optional evaluate_frame(test_progress &Progress, test_frame const &Frame, test_limits const &Limits)
+{
+ using enum test_result;
+
+ Progress.time += Frame.deltatime;
+
+ if (Frame.reported.has_value())
+ {
+ auto const value{*Frame.reported};
+ if (holds(value, 0.0))
+ return test_verdict{fail, std::format("__test.result set to 0{}", reason_suffix(Frame.reason))};
+ if (holds(value, 1.0))
+ {
+ if (false == Limits.no_movement_before_pass)
+ return test_verdict{pass, std::format("__test.result set to 1{}", reason_suffix(Frame.reason))};
+ Progress.passrequested = true;
+ }
+ }
+
+ Progress.resttime = Frame.atrest ? Progress.resttime + Frame.deltatime : 0.0;
+
+ if (Progress.passrequested && Progress.resttime >= pass_settle_time)
+ return test_verdict{pass, "__test.result set to 1 and every vehicle stopped"};
+ if (Limits.standstill > 0.0 && Progress.resttime >= Limits.standstill)
+ return test_verdict{Limits.pass_on_standstill ? pass : standstill, std::format("every vehicle stood still for {:.0f} s", Limits.standstill)};
+ if (Limits.timeout > 0.0 && Progress.time >= Limits.timeout)
+ return test_verdict{timeout, std::format("no result after {:.0f} s", Limits.timeout)};
+ return std::nullopt;
+}
+
+} // namespace simulation
diff --git a/simulation/simulationtestrules.h b/simulation/simulationtestrules.h
new file mode 100644
index 000000000..5d966c3c2
--- /dev/null
+++ b/simulation/simulationtestrules.h
@@ -0,0 +1,82 @@
+/*
+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
+
+// the rules of the test mode (eu07 --test, eu07/maszyna#541) which need nothing of the running simulation: the exit
+// codes, the command line and the end conditions. kept apart so the unit tests can check them
+namespace simulation {
+
+// exit codes of a test run; public, scripts and CI read them
+enum class test_result : int {
+ pass = 0, // __test.result set to 1, then every vehicle came to rest (or test.pass_on_standstill)
+ fail = 1, // __test.result set to 0
+ signal_passed_at_danger = 2, // a train went past a stop signal (SetVelocity 0 0), unless test.fail_if_stop_overran no
+ timeout = 3, // test.timeout seconds of simulation time went by without a result
+ standstill = 4, // every vehicle stood still for test.standstill seconds without a result
+ error = 5, // the run could not start (a bad command line, the scenery failed to load) or the simulator threw
+};
+
+std::string_view to_string(test_result Result);
+
+// how a test ended, and why
+struct test_verdict {
+ test_result result{test_result::error};
+ std::string reason;
+};
+
+// the test mode options of the command line
+struct test_command_line {
+ bool enabled{false}; // --test
+ std::optional timeout; // --test-timeout
+ std::string error; // what's wrong with them; empty if nothing
+};
+
+// seconds given on the command line: a number, not negative. nothing for anything else
+std::optional parse_seconds(std::string_view Text);
+
+// picks the test mode options out of a command line (the first argument is the program). the values of the other
+// options are skipped, so a scenery named like an option isn't taken for one; options it doesn't know are left alone
+test_command_line parse_test_command_line(std::span Arguments);
+
+// the limits and switches the end conditions go by
+struct test_limits {
+ double timeout{3600.0}; // [s] of simulation time; 0 = never
+ double standstill{300.0}; // [s] of every vehicle standing without a result; 0 = never
+ bool pass_on_standstill{false};
+ bool no_movement_before_pass{true};
+};
+
+// what a frame of the simulation brought
+struct test_frame {
+ double deltatime{0.0}; // [s] of simulation time
+ std::optional reported; // value of the result cell, if there is one
+ std::string_view reason; // text of the result cell
+ bool atrest{false}; // every vehicle stands
+};
+
+// the state of a test between frames
+struct test_progress {
+ double time{0.0}; // simulation time since the start [s]
+ double resttime{0.0}; // how long every vehicle has been standing [s]
+ bool passrequested{false}; // __test.result was set to 1, the pass waits for the vehicles to stop
+};
+
+// how long everything has to stand before a requested pass is granted [s]
+inline constexpr double pass_settle_time{1.0};
+
+// checks the end conditions after a frame and moves the progress on. returns the verdict once the test is over
+std::optional evaluate_frame(test_progress &Progress, test_frame const &Frame, test_limits const &Limits);
+
+} // namespace simulation
diff --git a/tests/unit/test_test_mode.cpp b/tests/unit/test_test_mode.cpp
new file mode 100644
index 000000000..fec475c5c
--- /dev/null
+++ b/tests/unit/test_test_mode.cpp
@@ -0,0 +1,195 @@
+#include "stdafx.h"
+#include "doctest.h"
+
+#include "simulation/simulationtestrules.h"
+
+#include
+
+// the test mode of the simulator (eu07 --test, eu07/maszyna#541): its command line and end conditions
+
+namespace {
+
+using simulation::test_result;
+
+simulation::test_command_line parse(std::vector Arguments)
+{
+ Arguments.insert(Arguments.begin(), "eu07");
+ return simulation::parse_test_command_line(Arguments);
+}
+
+// a frame of the default 0.03 s
+simulation::test_frame frame(bool const Atrest, std::optional const Reported = std::nullopt, std::string_view const Reason = {})
+{
+ return simulation::test_frame{0.03, Reported, Reason, Atrest};
+}
+
+// runs frames until the test ends or Seconds of simulation time go by
+std::optional run(simulation::test_progress &Progress, simulation::test_limits const &Limits, double const Seconds,
+ simulation::test_frame const &Frame)
+{
+ while (Progress.time < Seconds)
+ {
+ if (auto verdict{simulation::evaluate_frame(Progress, Frame, Limits)})
+ return verdict;
+ }
+ return std::nullopt;
+}
+
+} // namespace
+
+TEST_CASE("test mode: seconds on the command line are a number, not negative")
+{
+ CHECK(simulation::parse_seconds("240") == 240.0);
+ CHECK(simulation::parse_seconds("0.5") == 0.5);
+ CHECK(simulation::parse_seconds("0") == 0.0);
+ CHECK_FALSE(simulation::parse_seconds("").has_value());
+ CHECK_FALSE(simulation::parse_seconds("-1").has_value());
+ CHECK_FALSE(simulation::parse_seconds("60s").has_value());
+ CHECK_FALSE(simulation::parse_seconds("abc").has_value());
+ CHECK_FALSE(simulation::parse_seconds("inf").has_value());
+ CHECK_FALSE(simulation::parse_seconds("nan").has_value());
+}
+
+TEST_CASE("test mode: the command line")
+{
+ SUBCASE("without --test there is no test")
+ {
+ auto const commandline{parse({"-s", "td.scn", "-v", "ep07-424"})};
+ CHECK_FALSE(commandline.enabled);
+ CHECK(commandline.error.empty());
+ }
+ SUBCASE("--test and its limit, in any order")
+ {
+ auto const commandline{parse({"-s", "td.scn", "--test-timeout", "240", "--test"})};
+ CHECK(commandline.enabled);
+ CHECK(commandline.timeout == 240.0);
+ CHECK(commandline.error.empty());
+ }
+ SUBCASE("a limit not given stays unset")
+ {
+ auto const commandline{parse({"--test", "-s", "td.scn"})};
+ CHECK_FALSE(commandline.timeout.has_value());
+ }
+ SUBCASE("a limit which isn't a number is an error, not a limit turned off")
+ {
+ auto const commandline{parse({"--test", "-s", "td.scn", "--test-timeout", "4m"})};
+ CHECK(commandline.enabled);
+ CHECK_FALSE(commandline.timeout.has_value());
+ CHECK(commandline.error == "--test-timeout needs a number of seconds");
+ }
+ SUBCASE("a limit without its value is an error")
+ {
+ auto const commandline{parse({"--test", "-s", "td.scn", "--test-timeout"})};
+ CHECK(commandline.error == "--test-timeout needs a number of seconds");
+ }
+ SUBCASE("values of other options aren't taken for options")
+ {
+ auto const commandline{parse({"-s", "--test", "-ini", "--test-timeout", "-v", "--test", "-seed", "--test"})};
+ CHECK_FALSE(commandline.enabled);
+ CHECK(commandline.error.empty());
+ }
+ SUBCASE("the scenery of -edit is optional")
+ {
+ CHECK(parse({"-edit", "--test", "-s", "td.scn"}).enabled);
+ CHECK_FALSE(parse({"-edit", "td.scn"}).enabled);
+ }
+}
+
+TEST_CASE("test mode: the end conditions")
+{
+ simulation::test_limits limits;
+ simulation::test_progress progress;
+
+ SUBCASE("nothing happens, nothing ends")
+ {
+ CHECK_FALSE(simulation::evaluate_frame(progress, frame(false), limits).has_value());
+ CHECK(progress.time == doctest::Approx(0.03));
+ CHECK(progress.resttime == 0.0);
+ }
+ SUBCASE("a cell nobody wrote to says nothing")
+ {
+ CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, -1.0), limits).has_value());
+ CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, 2.0), limits).has_value());
+ CHECK_FALSE(progress.passrequested);
+ }
+ SUBCASE("0 fails at once, with the text of the cell")
+ {
+ auto const verdict{simulation::evaluate_frame(progress, frame(false, 0.0, "wrong_track"), limits)};
+ REQUIRE(verdict.has_value());
+ CHECK(verdict->result == test_result::fail);
+ CHECK(verdict->reason == "__test.result set to 0 (wrong_track)");
+ }
+ SUBCASE("1 passes once every vehicle has stood for a second")
+ {
+ CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, 1.0), limits).has_value());
+ CHECK(progress.passrequested);
+ // still moving: the pass waits
+ CHECK_FALSE(run(progress, limits, 30.0, frame(false, 1.0)).has_value());
+ auto const stoppedat{progress.time};
+ auto const verdict{run(progress, limits, 60.0, frame(true, 1.0))};
+ REQUIRE(verdict.has_value());
+ CHECK(verdict->result == test_result::pass);
+ CHECK(progress.time - stoppedat == doctest::Approx(simulation::pass_settle_time).epsilon(0.05));
+ }
+ SUBCASE("the pass stays requested when the cell changes back")
+ {
+ CHECK_FALSE(simulation::evaluate_frame(progress, frame(false, 1.0), limits).has_value());
+ auto const verdict{run(progress, limits, 60.0, frame(true, -1.0))};
+ REQUIRE(verdict.has_value());
+ CHECK(verdict->result == test_result::pass);
+ }
+ SUBCASE("1 with test.no_movement_before_pass no passes at once")
+ {
+ limits.no_movement_before_pass = false;
+ auto const verdict{simulation::evaluate_frame(progress, frame(false, 1.0, "reached_the_stop"), limits)};
+ REQUIRE(verdict.has_value());
+ CHECK(verdict->result == test_result::pass);
+ CHECK(verdict->reason == "__test.result set to 1 (reached_the_stop)");
+ }
+ SUBCASE("standing still without a result ends after test.standstill")
+ {
+ limits.standstill = 120.0;
+ auto const verdict{run(progress, limits, 1000.0, frame(true))};
+ REQUIRE(verdict.has_value());
+ CHECK(verdict->result == test_result::standstill);
+ CHECK(progress.time == doctest::Approx(120.0).epsilon(0.001));
+ }
+ SUBCASE("a move starts the standstill over")
+ {
+ limits.standstill = 120.0;
+ CHECK_FALSE(run(progress, limits, 100.0, frame(true)).has_value());
+ CHECK_FALSE(simulation::evaluate_frame(progress, frame(false), limits).has_value());
+ CHECK(progress.resttime == 0.0);
+ CHECK_FALSE(run(progress, limits, 200.0, frame(true)).has_value());
+ }
+ SUBCASE("test.pass_on_standstill makes the standstill a pass")
+ {
+ limits.standstill = 10.0;
+ limits.pass_on_standstill = true;
+ auto const verdict{run(progress, limits, 1000.0, frame(true))};
+ REQUIRE(verdict.has_value());
+ CHECK(verdict->result == test_result::pass);
+ }
+ SUBCASE("test.standstill 0 never ends the test")
+ {
+ limits.standstill = 0.0;
+ limits.timeout = 0.0;
+ CHECK_FALSE(run(progress, limits, 5000.0, frame(true)).has_value());
+ }
+ SUBCASE("no result by test.timeout")
+ {
+ limits.timeout = 240.0;
+ auto const verdict{run(progress, limits, 1000.0, frame(false))};
+ REQUIRE(verdict.has_value());
+ CHECK(verdict->result == test_result::timeout);
+ CHECK(verdict->reason == "no result after 240 s");
+ CHECK(progress.time == doctest::Approx(240.0).epsilon(0.001));
+ }
+ SUBCASE("a result in the last frame wins over the timeout")
+ {
+ limits.timeout = 0.03;
+ auto const verdict{simulation::evaluate_frame(progress, frame(false, 0.0), limits)};
+ REQUIRE(verdict.has_value());
+ CHECK(verdict->result == test_result::fail);
+ }
+}
From baf6bc2a2080a2c6a691b4e0e119e346a15d6603 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 11:21:30 +0100
Subject: [PATCH 45/60] feat(simulation): the test mode's exit codes keep clear
of 1 and 3
1 is what a process killed with TerminateProcess (and the plain failure of most
programs) ends with, 3 what abort() ends with on Windows, so a fail or a timeout
couldn't be told from a run that was killed or blew up. The codes other than
pass now are 10 fail, 11 signal passed at danger, 12 timeout, 13 standstill and
14 error: none of them a code a process gets on its own, neither the shells'
126-127 nor 128 + a signal number on Linux. pass stays 0.
---
simulation/simulationtestrules.h | 14 ++++++++------
tests/scenarios/README.md | 19 +++++++++++--------
tests/scenarios/run.py | 12 ++++++------
tests/unit/test_test_mode.cpp | 24 +++++++++++++++++++++++-
4 files changed, 48 insertions(+), 21 deletions(-)
diff --git a/simulation/simulationtestrules.h b/simulation/simulationtestrules.h
index 5d966c3c2..99d35db7b 100644
--- a/simulation/simulationtestrules.h
+++ b/simulation/simulationtestrules.h
@@ -18,14 +18,16 @@ http://mozilla.org/MPL/2.0/.
// codes, the command line and the end conditions. kept apart so the unit tests can check them
namespace simulation {
-// exit codes of a test run; public, scripts and CI read them
+// exit codes of a test run; public, scripts and CI read them. none of them is a code a process commonly ends with
+// when it goes wrong on its own: 1 (killed with TerminateProcess, or a plain failure of most programs), 3 (abort()
+// on Windows), 126-127 (a shell that can't run the program) or 128 + a signal number (killed, on Linux)
enum class test_result : int {
pass = 0, // __test.result set to 1, then every vehicle came to rest (or test.pass_on_standstill)
- fail = 1, // __test.result set to 0
- signal_passed_at_danger = 2, // a train went past a stop signal (SetVelocity 0 0), unless test.fail_if_stop_overran no
- timeout = 3, // test.timeout seconds of simulation time went by without a result
- standstill = 4, // every vehicle stood still for test.standstill seconds without a result
- error = 5, // the run could not start (a bad command line, the scenery failed to load) or the simulator threw
+ fail = 10, // __test.result set to 0
+ signal_passed_at_danger = 11, // a train went past a stop signal (SetVelocity 0 0), unless test.fail_if_stop_overran no
+ timeout = 12, // test.timeout seconds of simulation time went by without a result
+ standstill = 13, // every vehicle stood still for test.standstill seconds without a result
+ error = 14, // the run could not start (a bad command line, the scenery failed to load) or the simulator threw
};
std::string_view to_string(test_result Result);
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 8bd6f1a4a..acab07e79 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -62,13 +62,16 @@ The test ends with the first of these:
| exit code | result | when |
| --- | --- | --- |
| 0 | pass | `__test.result` was set to 1 and then every vehicle stood still for 1 s, so a train still moving towards a signal at stop has to stop first (with `test.no_movement_before_pass no` the pass ends the test at once). Also the standstill end with `test.pass_on_standstill yes` |
-| 1 | fail | `__test.result` was set to 0; ends at once |
-| 2 | signal passed at danger | a train went past a signal showing stop (`SetVelocity 0 0`; `SetVelocity 0 x` on automatic block, which may be passed after a stop, doesn't count); ends at once, unless `test.fail_if_stop_overran no` |
-| 3 | timeout | `test.timeout` seconds of simulation time went by (default 3600) |
-| 4 | standstill | every vehicle stood still for `test.standstill` seconds (default 300) and nothing reported a result. Trains waiting at a station or for a signal count as standing, so the limit has to be longer than such waits |
-| 5 | error | the run could not start: no `-s`, the scenery failed to load or has no vehicles, or the simulator threw |
+| 10 | fail | `__test.result` was set to 0; ends at once |
+| 11 | signal passed at danger | a train went past a signal showing stop (`SetVelocity 0 0`; `SetVelocity 0 x` on automatic block, which may be passed after a stop, doesn't count); ends at once, unless `test.fail_if_stop_overran no` |
+| 12 | timeout | `test.timeout` seconds of simulation time went by (default 3600) |
+| 13 | standstill | every vehicle stood still for `test.standstill` seconds (default 300) and nothing reported a result. Trains waiting at a station or for a signal count as standing, so the limit has to be longer than such waits |
+| 14 | error | the run could not start: no `-s`, the scenery failed to load or has no vehicles, or the simulator threw |
-A crash ends with the system's code instead (on Windows e.g. `0xC0000005`, -1073741819).
+A crash ends with the system's code instead (on Windows e.g. `0xC0000005`, -1073741819). The
+codes of the test mode keep clear of the ones a process gets when it goes wrong on its own: 1
+(killed with `TerminateProcess`, or a plain failure of most programs), 3 (`abort()` on Windows),
+126-127 (a shell that can't run the program) and 128 + a signal number (killed, on Linux).
The limits go in a `config` block of the scenery:
@@ -180,8 +183,8 @@ and slides past the signal, so those cases set `test.fail_if_stop_overran no`.
on `tor1k`, the track in front of the signal.
The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass
-event), `test_mode_signal_passed_at_danger` (exit 2), `test_mode_timeout` (exit 3, from
-`test.timeout`) and `test_mode_standstill` (exit 4, from `test.standstill`).
+event), `test_mode_signal_passed_at_danger` (exit 11), `test_mode_timeout` (exit 12, from
+`test.timeout`) and `test_mode_standstill` (exit 13, from `test.standstill`).
`test_mode_pass_while_moving` reports the pass from `event2` of `tor1k` (the direction the train runs), as the train runs onto
it, with `test.no_movement_before_pass no`, so the test ends with the train still moving.
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 210d6c013..886e2e90d 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -52,14 +52,14 @@ COL_COMMAND = 16 # text, read as None
COL_WHEELSLIP = 20
COL_VEHICLE_VELOCITY = 25 # signed vehicle speed, km/h; only in builds which log it
-# exit codes of the simulator's test mode (eu07 --test), see simulation/simulationtest.h
+# exit codes of the simulator's test mode (eu07 --test), see simulation/simulationtestrules.h
EXIT_RESULTS = {
0: "pass",
- 1: "fail",
- 2: "signal_passed_at_danger",
- 3: "timeout",
- 4: "standstill",
- 5: "error",
+ 10: "fail",
+ 11: "signal_passed_at_danger",
+ 12: "timeout",
+ 13: "standstill",
+ 14: "error",
}
# settings layered over the user's eu07.ini for a test run; the window ones only matter
diff --git a/tests/unit/test_test_mode.cpp b/tests/unit/test_test_mode.cpp
index fec475c5c..609b16ff0 100644
--- a/tests/unit/test_test_mode.cpp
+++ b/tests/unit/test_test_mode.cpp
@@ -3,9 +3,10 @@
#include "simulation/simulationtestrules.h"
+#include
#include
-// the test mode of the simulator (eu07 --test, eu07/maszyna#541): its command line and end conditions
+// the test mode of the simulator (eu07 --test, eu07/maszyna#541): its exit codes, command line and end conditions
namespace {
@@ -37,6 +38,27 @@ std::optional run(simulation::test_progress &Progress,
} // namespace
+TEST_CASE("test mode: the exit codes keep clear of the ones of a killed or aborted process")
+{
+ std::array const results{test_result::pass, test_result::fail, test_result::signal_passed_at_danger, test_result::timeout, test_result::standstill, test_result::error};
+ for (auto const result : results)
+ {
+ auto const code{static_cast(result)};
+ CAPTURE(code);
+ CHECK(code != 1); // TerminateProcess, most programs' failure
+ CHECK(code != 3); // abort() on Windows
+ CHECK(code < 126); // shells, signals on Linux
+ CHECK(simulation::to_string(result) != "unknown");
+ }
+ // the codes are public: scripts and CI read them
+ CHECK(static_cast(test_result::pass) == 0);
+ CHECK(static_cast(test_result::fail) == 10);
+ CHECK(static_cast(test_result::signal_passed_at_danger) == 11);
+ CHECK(static_cast(test_result::timeout) == 12);
+ CHECK(static_cast(test_result::standstill) == 13);
+ CHECK(static_cast(test_result::error) == 14);
+}
+
TEST_CASE("test mode: seconds on the command line are a number, not negative")
{
CHECK(simulation::parse_seconds("240") == 240.0);
From 7f8892cda6f02facd364d093992c48060bd1db09 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 11:21:57 +0100
Subject: [PATCH 46/60] fix(simulation): a test doesn't read the player's own
eu07.ini
The simulator reads eu07.ini from %APPDATA%/MaSzyna (~/.config/MaSzyna on Linux)
when there is one, in place of the game folder's. A test run then depended on
whose machine it ran on. With --test only the game folder's eu07.ini is read,
then the files given with -ini. The test mode options are taken from the command
line before the settings for that; --test-timeout still wins over test.timeout
of any settings file.
---
application/application.cpp | 24 +++++++++++++-----------
tests/scenarios/README.md | 3 +++
tests/scenarios/run.py | 3 ++-
3 files changed, 18 insertions(+), 12 deletions(-)
diff --git a/application/application.cpp b/application/application.cpp
index f3c3fe46d..638eacdce 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -1200,17 +1200,6 @@ int eu07_application::init_settings(int Argc, char *Argv[])
{
Global.asVersion = VERSION_INFO;
- fs::path iniPath = user_config_path("eu07.ini");
-
- if (!iniPath.empty() && fs::exists(iniPath))
- {
- Global.LoadIniFile(iniPath.string().c_str());
- }
- else
- {
- Global.LoadIniFile("eu07.ini");
- }
-
// a test run is known before the rest of the command line is read, so a command line it can't take
// ends with the error code of the test, not with 0, which would pass it
auto const testcommandline{simulation::parse_test_command_line(std::vector(Argv, Argv + Argc))};
@@ -1226,6 +1215,19 @@ int eu07_application::init_settings(int Argc, char *Argv[])
Global.test.timeout_from_command_line = true;
}
+ fs::path iniPath = user_config_path("eu07.ini");
+
+ // a test reads the settings of the game folder only (and those given with -ini), not the player's own
+ // (%APPDATA%/MaSzyna, ~/.config/MaSzyna), so it runs the same for whoever runs it
+ if (false == Global.test.enabled && !iniPath.empty() && fs::exists(iniPath))
+ {
+ Global.LoadIniFile(iniPath.string().c_str());
+ }
+ else
+ {
+ Global.LoadIniFile("eu07.ini");
+ }
+
// process command line arguments
bool sceneryfromcommandline{false};
bool editwithoutscenery{false};
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index acab07e79..ca45dc34d 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -19,6 +19,9 @@ eu07 --test -s [--test-timeout ] [-seed ] [-
With `--test` the simulator:
- needs `-s`; `-v` is ignored and every train is driven by AI (ghostview),
+- reads the settings of the game folder's `eu07.ini` and of the files given with `-ini` (in that
+ order), not the player's own `eu07.ini` in `%APPDATA%\MaSzyna` (`~/.config/MaSzyna` on Linux),
+ so a test runs the same for whoever runs it,
- draws nothing: the null renderer loads the 3D models (the physics needs some of their
data) but no textures, and the window stays hidden,
- has no sound, no network, no python, no pause (not even one set by the scenery), and
diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py
index 886e2e90d..9cc6f84a9 100644
--- a/tests/scenarios/run.py
+++ b/tests/scenarios/run.py
@@ -62,7 +62,8 @@ EXIT_RESULTS = {
14: "error",
}
-# settings layered over the user's eu07.ini for a test run; the window ones only matter
+# settings layered over the game's eu07.ini for a test run (test mode doesn't read the player's own
+# in %APPDATA%); the window ones only matter
# with --watch, test mode keeps its window hidden and turns the sound off by itself
TEST_INI = """\
fullscreen no
From 1626df2bc49945680f596395f06f81256edd2130 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 11:22:37 +0100
Subject: [PATCH 47/60] fix(simulation): a scenery's config block can't turn
back on what a test keeps off
The config block of a scenery is read like the settings files, after the test
mode settings were applied, so a scenery with soundenabled, multiplayer,
execonexit, feedbackmode or the like in it got them back in a test run. The test
mode settings now are applied again after each config block of the scenery;
apply_test_mode_settings() moved to simulationtest.cpp for that.
---
application/application.cpp | 52 +-----------------------
simulation/simulationstateserializer.cpp | 5 +++
simulation/simulationtest.cpp | 46 +++++++++++++++++++++
simulation/simulationtest.h | 5 +++
tests/scenarios/README.md | 2 +
5 files changed, 59 insertions(+), 51 deletions(-)
diff --git a/application/application.cpp b/application/application.cpp
index 638eacdce..d0ef6a01a 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -31,9 +31,6 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/dictionary.h"
#include "version_info.h"
#include "simulation/simulationtest.h"
-#ifdef _WIN32
-#include "Console.h"
-#endif
#include
#include
#include
@@ -1149,53 +1146,6 @@ void eu07_application::init_files()
}
namespace fs = std::filesystem;
-namespace
-{
-
-// the settings of the test mode (--test), over whatever the settings files say
-void apply_test_mode_settings()
-{
- // nobody watches nor listens: no player vehicle, nothing drawn, no sound, no window in the way
- Global.editor_session = false;
- Global.local_start_vehicle = "ghostview";
- Global.GfxRenderer = "null";
- Global.NvRenderer = false;
- Global.bSoundEnabled = false;
- Global.python_enabled = false;
- Global.bInactivePause = false;
- Global.bFullScreen = false;
- Global.fullscreen_windowed = false;
- Global.VSync = false;
- Global.iMultisampling = 0;
- Global.gfx_usegles = false;
- Global.minframetime = std::chrono::duration(0.0f);
- Global.extra_viewports.clear();
- Global.headtrack_conf.joy.clear();
- // a test runs on its own: no network, and no input from outside (eu07/maszyna#541)
- Global.network_servers.clear();
- Global.network_client.reset();
- Global.InputGamepad = false;
- Global.InputMouse = false;
- Global.uart_conf.enable = false;
- Global.motiontelemetry_conf.enable = false;
-#ifdef WITH_ZMQ
- Global.zmq_address.clear();
-#endif
- // nor anything to the outside: no keyboard leds, LPT or PoKeys desk (feedbackmode), no messages to a
- // multiplayer server (multiplayer, which also holds some events back for it), no program run at the end
- Global.iFeedbackMode = 0;
-#ifdef _WIN32
- Console::ModeSet(Global.iFeedbackMode, Global.iFeedbackPort);
-#endif
- Global.iMultiplayer = 0;
- Global.exec_on_exit.clear();
- // and the same way every time, unless given another seed (-seed, or randomseed in the settings)
- if (!Global.random_seed)
- Global.random_seed = seed_of("test");
-}
-
-} // namespace
-
int eu07_application::init_settings(int Argc, char *Argv[])
{
Global.asVersion = VERSION_INFO;
@@ -1315,7 +1265,7 @@ int eu07_application::init_settings(int Argc, char *Argv[])
simulation::test().conclude(simulation::test_result::error, "--test needs a scenery given with -s");
return -1;
}
- apply_test_mode_settings();
+ simulation::apply_test_mode_settings();
}
return 0;
diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp
index 664f3b955..244700070 100644
--- a/simulation/simulationstateserializer.cpp
+++ b/simulation/simulationstateserializer.cpp
@@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulationtime.h"
#include "simulation/simulationsounds.h"
#include "simulation/simulationenvironment.h"
+#include "simulation/simulationtest.h"
#include "scene/scenenodegroups.h"
#include "scene/scenelayers.h"
#include "scene/sceneterrain.h"
@@ -363,6 +364,10 @@ state_serializer::deserialize_config( cParser &Input, scene::scratch_data &Scrat
// config parameters (re)definition
Global.ConfigParse( Input );
+ if( Global.test.enabled ) {
+ // a scenery doesn't get to turn on what a test keeps off
+ simulation::apply_test_mode_settings();
+ }
}
void
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
index 76aa1be30..67e05ad31 100644
--- a/simulation/simulationtest.cpp
+++ b/simulation/simulationtest.cpp
@@ -15,11 +15,16 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulation.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
+#include "utilities/utilities.h"
#include "vehicle/DynObj.h"
#include "world/Event.h"
#include "world/MemCell.h"
+#ifdef _WIN32
+#include "Console.h"
+#endif
#include
+#include
#include
#include
#include
@@ -33,6 +38,47 @@ test_manager &test()
return instance;
}
+void apply_test_mode_settings()
+{
+ // nobody watches nor listens: no player vehicle, nothing drawn, no sound, no window in the way
+ Global.editor_session = false;
+ Global.local_start_vehicle = "ghostview";
+ Global.GfxRenderer = "null";
+ Global.NvRenderer = false;
+ Global.bSoundEnabled = false;
+ Global.python_enabled = false;
+ Global.bInactivePause = false;
+ Global.bFullScreen = false;
+ Global.fullscreen_windowed = false;
+ Global.VSync = false;
+ Global.iMultisampling = 0;
+ Global.gfx_usegles = false;
+ Global.minframetime = std::chrono::duration(0.0f);
+ Global.extra_viewports.clear();
+ Global.headtrack_conf.joy.clear();
+ // a test runs on its own: no network, and no input from outside (eu07/maszyna#541)
+ Global.network_servers.clear();
+ Global.network_client.reset();
+ Global.InputGamepad = false;
+ Global.InputMouse = false;
+ Global.uart_conf.enable = false;
+ Global.motiontelemetry_conf.enable = false;
+#ifdef WITH_ZMQ
+ Global.zmq_address.clear();
+#endif
+ // nor anything to the outside: no keyboard leds, LPT or PoKeys desk (feedbackmode), no messages to a
+ // multiplayer server (multiplayer, which also holds some events back for it), no program run at the end
+ Global.iFeedbackMode = 0;
+#ifdef _WIN32
+ Console::ModeSet(Global.iFeedbackMode, Global.iFeedbackPort);
+#endif
+ Global.iMultiplayer = 0;
+ Global.exec_on_exit.clear();
+ // and the same way every time, unless given another seed (-seed, or randomseed in the settings)
+ if (!Global.random_seed)
+ Global.random_seed = seed_of("test");
+}
+
void test_manager::init_result_cell() const
{
auto cell { std::make_unique(scene::node_data{0, -1, std::string(result_cell), "memcell"}) };
diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h
index 66384b6ed..e67b2adaf 100644
--- a/simulation/simulationtest.h
+++ b/simulation/simulationtest.h
@@ -53,4 +53,9 @@ private:
// the test of the run
test_manager &test();
+// the settings of the test mode, over whatever the settings files and the scenery say: applied once the command
+// line is read, and again after each config block of the scenery, which could turn the sound, the network or the
+// program run at the end back on
+void apply_test_mode_settings();
+
} // namespace simulation
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index ca45dc34d..006a0fc69 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -32,6 +32,8 @@ With `--test` the simulator:
- gives nothing to the outside either: no keyboard leds, LPT or PoKeys (`feedbackmode`), no
messages to a multiplayer server (`multiplayer`), no program run at the end (`execonexit`),
no console window of its own (`showsystemconsole`), and the game's `imgui.ini` stays as it is,
+- keeps all of the above whatever the `config` block of the scenery says: the settings of the
+ test mode are applied again after it,
- runs the simulation as fast as it can in fixed steps of 0.03 s of simulation time per
frame (three 10 ms physics steps), whatever the real time, the time speed or the machine,
- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so two
From 14d25520f3e056b9279c0458e7a1487bc4fb2bea Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 11:23:02 +0100
Subject: [PATCH 48/60] fix(simulation): a test's standard output carries its
result only
The log was printed in colour to stdout too (debuglog bit 2), so a script reading
the verdict of a test got the whole log with it. In test mode the log goes to the
log file only and stdout has the `test: ...` line alone; the usage text of a bad
command line goes to stderr. Whether the run is a test is now known before the
log service starts.
---
application/application.cpp | 11 +++++++----
tests/scenarios/README.md | 3 ++-
utilities/Logs.cpp | 4 ++--
3 files changed, 11 insertions(+), 7 deletions(-)
diff --git a/application/application.cpp b/application/application.cpp
index d0ef6a01a..4fe0911ac 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -322,6 +322,9 @@ int eu07_application::init(int Argc, char *Argv[])
{
int result{0};
+ // a test run is known before anything is logged: whoever started it reads its result on the standard output,
+ // which the log isn't written to then (eu07/maszyna#541)
+ Global.test.enabled = simulation::parse_test_command_line(std::vector(Argv, Argv + Argc)).enabled;
// start logging service
std::thread sLoggingService(LogService);
Global.threads.emplace("LogService", std::move(sLoggingService));
@@ -1150,10 +1153,9 @@ int eu07_application::init_settings(int Argc, char *Argv[])
{
Global.asVersion = VERSION_INFO;
- // a test run is known before the rest of the command line is read, so a command line it can't take
- // ends with the error code of the test, not with 0, which would pass it
+ // a test run is known before the rest of the command line is read (Global.test.enabled, see init()), so a
+ // command line it can't take ends with the error code of the test, not with 0, which would pass it
auto const testcommandline{simulation::parse_test_command_line(std::vector(Argv, Argv + Argc))};
- Global.test.enabled = testcommandline.enabled;
if (false == testcommandline.error.empty())
{
simulation::test().conclude(simulation::test_result::error, testcommandline.error);
@@ -1245,7 +1247,8 @@ int eu07_application::init_settings(int Argc, char *Argv[])
}
else
{
- std::cout << "usage: " << std::string(Argv[0]) << " [-s sceneryfilepath]"
+ // a test's standard output carries its result only
+ (Global.test.enabled ? std::cerr : std::cout) << "usage: " << std::string(Argv[0]) << " [-s sceneryfilepath]"
<< " [-v vehiclename]"
<< " [-edit [sceneryfilepath]]"
<< " [-seed number|word]"
diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md
index 006a0fc69..d3f256782 100644
--- a/tests/scenarios/README.md
+++ b/tests/scenarios/README.md
@@ -40,7 +40,8 @@ With `--test` the simulator:
runs of a scenery come out the same (the physicslogs of two runs are byte for byte equal),
- quits when the test ends, and says how it ended in the exit code and in a `test: ...`
line on stdout and in the log. A command line it can't take, or a start that fails, ends
- the same way with the `error` code.
+ the same way with the `error` code. That line is all there is on stdout: the log goes to
+ the log file only (`debuglog` doesn't print it on the console in test mode).
On Windows the simulator is a windowed program, which the `cmd` prompt and PowerShell don't wait
for. In a `.bat` file `eu07 --test ... > result.txt` waits and sets `%errorlevel%`; at the prompt
diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp
index 38094d72e..e0949aba6 100644
--- a/utilities/Logs.cpp
+++ b/utilities/Logs.cpp
@@ -125,8 +125,8 @@ void LogService()
if (log_scrollback.size() > 200)
log_scrollback.pop_front();
- // log to console
- if (Global.iWriteLogEnabled & 2)
+ // log to console; not in test mode, where the standard output carries the result of the test only
+ if ((Global.iWriteLogEnabled & 2) && false == Global.test.enabled)
{
if (isError)
printf("\033[1;37;41m%s\033[0m\n", msg.c_str());
From 03a417c7b0b4307546bec78a9cf0321abd573f17 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 8 Nov 2026 11:33:36 +0100
Subject: [PATCH 49/60] feat(simulation): a real time watchdog ends a test run
that hangs
A test run that hung, in the loading or anywhere else, waited until whoever
started it killed it. A watchdog thread now ends a run still going test.wall_timeout
seconds of real time after the start of the simulator, loading included: it says
`test: timeout ... still running after N s of real time` and quits with the
timeout code, whatever the main thread is doing, with no dialog. A test that has
ended but whose simulator doesn't close ends with its own result.
The limit is test.wall_timeout (settings, the scenery's config block) or
--test-wall-timeout, which wins. Not given, it is test.timeout + 600 s: ten
minutes for the loading, and a simulation that runs at least as fast as real
time is never cut short. test.timeout 0 means no watchdog unless the limit is
given; test.wall_timeout 0 turns it off.
run.py passes the case's timeout as --test-wall-timeout and kills a simulator
only 30 s after it. A timeout from the watchdog counts as wall_timeout there, so
a run that hung doesn't pass a case expecting the simulation time to run out;
test_mode_wall_timeout ends while loading on a limit of 2 s.
---
application/application.cpp | 9 ++-
simulation/simulationtest.cpp | 73 +++++++++++++++++--
simulation/simulationtest.h | 17 ++++-
simulation/simulationtestrules.cpp | 14 +++-
simulation/simulationtestrules.h | 13 +++-
tests/scenarios/README.md | 36 ++++++---
.../cases/test_mode_wall_timeout.json | 11 +++
tests/scenarios/run.py | 23 ++++--
tests/unit/test_test_mode.cpp | 34 ++++++++-
utilities/Globals.cpp | 12 +++
utilities/Globals.h | 3 +
11 files changed, 210 insertions(+), 35 deletions(-)
create mode 100644 tests/scenarios/cases/test_mode_wall_timeout.json
diff --git a/application/application.cpp b/application/application.cpp
index 4fe0911ac..860b8a235 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -1166,6 +1166,11 @@ int eu07_application::init_settings(int Argc, char *Argv[])
Global.test.timeout = *testcommandline.timeout;
Global.test.timeout_from_command_line = true;
}
+ if (testcommandline.wall_timeout.has_value())
+ {
+ Global.test.wall_timeout = testcommandline.wall_timeout;
+ Global.test.wall_timeout_from_command_line = true;
+ }
fs::path iniPath = user_config_path("eu07.ini");
@@ -1231,7 +1236,7 @@ int eu07_application::init_settings(int Argc, char *Argv[])
// integration test: the scenery runs unattended and the exit code is the result (eu07/maszyna#541),
// taken from the command line above
}
- else if (token == "--test-timeout")
+ else if (token == "--test-timeout" || token == "--test-wall-timeout")
{
// taken from the command line above, with its value
++i;
@@ -1253,7 +1258,7 @@ int eu07_application::init_settings(int Argc, char *Argv[])
<< " [-edit [sceneryfilepath]]"
<< " [-seed number|word]"
<< " [-ini settingsfile]"
- << " [--test [--test-timeout seconds]]" << std::endl;
+ << " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" << std::endl;
simulation::test().conclude(simulation::test_result::error, std::format("unknown command line argument {}", token));
return -1;
}
diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp
index 67e05ad31..15cdf0e3f 100644
--- a/simulation/simulationtest.cpp
+++ b/simulation/simulationtest.cpp
@@ -27,9 +27,20 @@ http://mozilla.org/MPL/2.0/.
#include
#include
#include
+#include
#include
#include
+namespace {
+
+// [s] of real time since the start of the simulator
+double elapsed_wall_time()
+{
+ return std::chrono::duration(std::chrono::steady_clock::now() - Global.startTimestamp).count();
+}
+
+} // namespace
+
namespace simulation {
test_manager &test()
@@ -77,6 +88,8 @@ void apply_test_mode_settings()
// and the same way every time, unless given another seed (-seed, or randomseed in the settings)
if (!Global.random_seed)
Global.random_seed = seed_of("test");
+ // the real time limit, which the scenery may set too
+ test().watch_wall_clock(wall_clock_limit(Global.test.wall_timeout, Global.test.timeout));
}
void test_manager::init_result_cell() const
@@ -94,7 +107,10 @@ void test_manager::start()
if (m_started)
return;
m_started = true;
- m_progress = test_progress {};
+ {
+ std::scoped_lock lock { m_lock };
+ m_progress = test_progress {};
+ }
if (simulation::Vehicles.sequence().empty())
{
// most likely the scenery wasn't found, or it isn't a test scenery
@@ -103,7 +119,9 @@ void test_manager::start()
}
// a pause set by the scenery or the settings would never be lifted, nobody is there to press the key
Global.iPause = 0;
- WriteLog(std::format("test: started, timeout {:.0f} s, standstill {:.0f} s{}{}{}", Global.test.timeout, Global.test.standstill,
+ auto const walllimit { m_walllimit.load() };
+ WriteLog(std::format("test: started, timeout {:.0f} s, real time limit {}, standstill {:.0f} s{}{}{}", Global.test.timeout,
+ walllimit > 0.0 ? std::format("{:.0f} s", walllimit) : std::string("none"), Global.test.standstill,
Global.test.pass_on_standstill ? ", standstill passes" : "",
Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed",
Global.test.no_movement_before_pass ? "" : ", pass without waiting for a stop"));
@@ -122,14 +140,21 @@ void test_manager::update(double const Deltatime)
frame.reason = cell->Text();
}
- auto const requestedbefore { m_progress.passrequested };
- auto const verdict { evaluate_frame(m_progress, frame, test_limits { Global.test.timeout, Global.test.standstill, Global.test.pass_on_standstill, Global.test.no_movement_before_pass }) };
+ auto const limits { test_limits { Global.test.timeout, Global.test.standstill, Global.test.pass_on_standstill, Global.test.no_movement_before_pass } };
+ std::optional verdict;
+ auto passrequested { false };
+ {
+ std::scoped_lock lock { m_lock };
+ auto const requestedbefore { m_progress.passrequested };
+ verdict = evaluate_frame(m_progress, frame, limits);
+ passrequested = m_progress.passrequested && false == requestedbefore;
+ }
if (verdict.has_value())
{
finish(verdict->result, verdict->reason);
return;
}
- if (m_progress.passrequested && false == requestedbefore)
+ if (passrequested)
{
WriteLog(std::format("test: pass requested at {:.1f} s{}, waiting for every vehicle to stop", m_progress.time,
frame.reason.empty() ? std::string() : std::format(" ({})", frame.reason)));
@@ -160,10 +185,11 @@ void test_manager::finish(test_result const Result, std::string_view const Reaso
bool test_manager::conclude(test_result const Result, std::string_view const Reason)
{
+ std::scoped_lock lock { m_lock };
if (m_finished || false == Global.test.enabled)
return false;
- m_finished = true;
m_result = Result;
+ m_finished = true;
auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast(Result), m_progress.time, Reason) };
if (Result == test_result::pass)
@@ -176,4 +202,39 @@ bool test_manager::conclude(test_result const Result, std::string_view const Rea
return true;
}
+int test_manager::exit_code() const
+{
+ std::scoped_lock lock { m_lock };
+ return static_cast(m_finished ? m_result : test_result::error);
+}
+
+void test_manager::watch_wall_clock(double const Limit)
+{
+ m_walllimit = Limit;
+ if (Limit <= 0.0 || m_watchdog.joinable())
+ return;
+ m_watchdog = std::jthread([this](std::stop_token const &Stop) {
+ while (false == Stop.stop_requested())
+ {
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ check_wall_clock(elapsed_wall_time());
+ }
+ });
+}
+
+void test_manager::check_wall_clock(double const Elapsed)
+{
+ auto const limit { m_walllimit.load() };
+ if (limit <= 0.0 || Elapsed < limit)
+ return;
+ // the run hangs, or is too slow: it ends here, whatever the main thread is doing. a run whose test has ended
+ // but which doesn't close ends with its result
+ if (false == conclude(test_result::timeout, std::format("still running after {:.0f} s of real time (test.wall_timeout)", limit)))
+ ErrorLog(std::format("test: the simulator was still running {:.0f} s of real time after the start, ended", limit));
+ // what was logged last gets written, unless the log is held up by a hung thread
+ StopLogService();
+ std::this_thread::sleep_for(std::chrono::milliseconds(250));
+ std::_Exit(exit_code());
+}
+
} // namespace simulation
diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h
index e67b2adaf..a59ec87bf 100644
--- a/simulation/simulationtest.h
+++ b/simulation/simulationtest.h
@@ -11,7 +11,10 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulationtestrules.h"
+#include
+#include
#include
+#include
// integration test mode (eu07 --test -s , eu07/maszyna#541): the scenery runs unattended in a tight
// fixed-step loop and the simulator quits with an exit code saying how the test went
@@ -38,16 +41,26 @@ public:
// ends the test with given result, without closing the application: for the ways out that close it anyway
// (a bad command line, a failed start, an exception). returns false if the test had already ended
bool conclude(test_result Result, std::string_view Reason);
+ // (re)sets the real time limit of the run [s] since the start of the simulator, 0 = none. the first limit
+ // starts the watchdog, which ends a run still going at the limit with the timeout code, whatever it's doing
+ void watch_wall_clock(double Limit);
bool finished() const { return m_finished; }
// exit code of the process: the result, or error while the test hasn't finished
- int exit_code() const { return static_cast(m_finished ? m_result : test_result::error); }
+ int exit_code() const;
private:
+ // the watchdog's check, at Elapsed seconds of real time since the start of the simulator
+ void check_wall_clock(double Elapsed);
+
+ // the watchdog may end the test from its own thread
+ mutable std::mutex m_lock;
bool m_started { false };
- bool m_finished { false };
+ std::atomic m_finished { false };
test_result m_result { test_result::error };
test_progress m_progress;
+ std::atomic