18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-03 11:15:23 +01:00
Files
maszyna/simulation/simulationsnapshotdriver.cpp
T
jerrrrycho ed8708c5e2 feat(simulation): snapshots, save the state of a running scenery and load it back (stage A) (#420)
* feat(simulation): text format of simulation snapshots

A snapshot of a running simulation is a text file in the syntax of the scenery
files: entries of the form <type> <name> <key> <value> ... end<type>, the first
one a header which names the scenery. This is the text alone: entries, writer,
reader, the names of the things of a scenery, the plan of coupling changes and
the command line switches (--load-snapshot, --snapshot-at), in the core library
with unit tests. Nothing reads or writes a snapshot yet.

* feat(simulation): snapshot of time, weather, cells, switches and events (L1)

--snapshot-at <seconds> <file> writes a snapshot when the simulation has run
that long, --load-snapshot <file> puts one over the scenery once it has loaded,
before the first frame. This layer keeps the clock and the simulation timer,
the weather with the wind, the random engine, the memory cells, the switches,
the tracks an event can change and the ones made on the run, the traction
power sources, the event queue, the timers of the launchers and the lamps of
the signals.

While a snapshot is put back the event manager is suspended, so nothing in the
scenery reacts to it. Existing classes only get accessors for what was private
(the fraction of the second, launcher timers, the speed limit of a track, the
wind, the state of a power source, the event queue). Without the switches
nothing changes.

* feat(simulation): state of a vehicle's physics for snapshots (L3, core)

What TMoverParameters holds of a running vehicle, to and from an entry of a
snapshot: speed, load, controls, switches and relays, pantographs, doors,
engine and its cooling, the air of the pipes, of every reservoir of the brake
valve (with the flow it has yet to take in) and of the chambers of the driver's
valves, the vigilance device, the power circuits. In the core library, tested
on the real vehicle definitions: a
vehicle restored on a fresh one saves the same, and runs on next to the one it
was saved from.

The brake valves, the driver's valves and the vigilance device get accessors
for their private state (reservoirs(), latches(), pressures(), state()), a
reservoir one for the flow it has yet to take in; nothing else in the physics
changes. This comes before the vehicles of the scenery (L2), whose
speed and load are kept by it.

* feat(simulation): snapshot of vehicles and consists (L2)

Every vehicle is kept with the place of both its axles (track, distance,
direction, path of a switch, events still to set off), the way it faces, its
couplings with their flags, destination and, through its physics, speed and
load. Loaded, the vehicles are put straight where they were
(TTrackFollower::Place(), which trails no switch and fires no event), then
parted and joined until they are coupled as saved, whatever trainsets the
scenery made of them.

A vehicle of the snapshot the scenery does not have is skipped and reported,
one the snapshot does not know stays as the scenery made it, one which had left
the simulation is taken out again.

* feat(simulation): pantographs and passenger exchange in snapshots (L3)

What a vehicle keeps of its machinery beside its physics: the arms of the
pantographs as they stand under the wire, the time without voltage, the
passengers getting on and off, the lighting of the compartments, the headlight
toggles, the last force asked of the electrodynamic brake.

* feat(simulation): snapshot of the drivers and of the player's vehicle (L4)

A driver is kept with its orders and the one it is on, the name of its
timetable and its place in it, the consist it has, what it holds to (speeds of
signals and limits, the reason it stands, its timers and flags), its table of
what is ahead on the track with the point limits it has latched, its tables of
what the brake of the consist gives, and whether the AI drives. A driver who
had moved to another vehicle of its train is moved there.

A run loaded in ghost view (the test mode) is ready before its first frame, as
the run it goes on from was.

The snapshot also names the vehicle the player was in, which --load-snapshot
starts in unless -v says otherwise.

* feat(simulation): snapshotsave command, on [Ctrl]+[Shift]+[F9]

Writes a snapshot of the simulation to snapshots/<scenery>_<date>_<time>.snapshot
in the game folder. The command is the last one of the list, so the numbers of
the others stay.

* test: scenario cases which load a simulation snapshot and compare the run

A case with a "snapshot" section runs its scenery to a time, taking snapshots
on the way and at the end, then again from the first snapshot, and compares the
two ends: positions, speeds, pressures, couplings, cells, switches, drivers.
The snapshot saved right after loading has to be the one loaded.
tests/scenarios/snapshots.py reads the format and tells two snapshots apart.
The switches and the format are described in tests/scenarios/README.md.

* fix(simulation): a vehicle gone in the snapshot leaves its isolated sections

The scenery counts the axles of every vehicle in the isolated sections of
the tracks it puts it on. A vehicle the snapshot has as removed was only
taken off the list of its track, so its two axles stayed counted there and
the section never went free again: the next train on it went 4-6-4 axles
instead of 0-2-0, and its busy and free events never fired.

- A removed vehicle counts both axles out of the sections of their tracks,
  is taken off the list of its track only if it's on it, and has no owner.
- The drivers a snapshot doesn't have are deleted as before, and no
  vehicle keeps its owner pointing at one of them.
- The snapshot keeps the count of every isolated section and sets it after
  the vehicles are placed: the vehicles a consist leaves behind as it goes
  through a portal stay counted where they were, in the game too. A count
  the placing gives other than the snapshot has is told in the log.
- A vehicle with two entries is placed once.
- TIsolated::axles() reads and sets the count.
- The harness compares the counts of the sections; a new case,
  snapshot_td_portal_isolated, has a train leave through a portal from the
  track of a section before the snapshot.

* fix(simulation): every value of a snapshot file is checked before it's used

A damaged or edited snapshot could put an index past a table, a count
which takes forever or a number out of the range of its type into the
simulation, and a file cut short was put back half way.

- Reading a value: a whole number has to be whole and fit its type (an
  enum its underlying one), a float can't be past its largest value; what
  doesn't fit is refused. Every refusal names the entry, the key and the
  value, and goes to the log (errors.txt), up to 100 lines and a count.
- Ranges: coupler ends 0 or 1 and the flags of a coupling; couplings which
  would close a ring of vehicles; the count of the points of a driver's
  table and of its point limits (not past the keys of the entry), the
  indices into the table (tablelast, semnext, semnextstop); the order
  stack and its position, the timetable station, the driver's enums and
  directions; the path, events and distance of an axle, facing and first
  axle; the date and time; switch states, made track ends, crossing
  segments, event siblings and times, launcher timers, the weather; the
  load (amount, and a name which isn't a path); the whole numbers inside
  number lists (flags of a table point, the stop of a coupler pair, the
  track flags under a vehicle, the fuse count of a power source, the cab
  of the vigilance device).
- The positions of the controllers are brought within the ranges of the
  vehicle: master and secondary controller (set and actual), reverser,
  cabs, light, compressor and wiper switches, brake handle, hand brake,
  dimmer.
- A document with problems isn't loaded unless --load-snapshot-force says
  so; a test run ends with the error code then. The header counts the
  entries, so a file cut between two entries is found too. A file of a
  newer version is a warning, not a problem.
- A snapshot is written to <file>.tmp and renamed over the file only when
  the stream didn't fail.
- Unit tests of the reader on damaged input.

* feat(simulation): the pullee mode and the holding brake timer in snapshots

Of what #419 and #424 added to TMoverParameters, two are state: PulleeMode
(prepared for being hauled dead; the scenery sets it, PulleeModeSwitch()
can change it) and StopBrakeReleaseTimer (how long power has been asked
for, which lets the holding brake of a unit go after its delay). Both are
kept now, as "pulleemode" and "stopbrakereleasetimer". The others
(PressureSwitchBrakeCylinder, EmergencyBrakeMainOffPressure,
StopBrakeReleaseDelay) come from the vehicle definition and aren't.

* fix(simulation): the snapshot code without Sonar issues

No declaration shadows an enumerator, the variables used only by a
condition are declared in it, write_file takes its writer as a template,
the temporary file is a std::filesystem::path, the isolated sections are
looked up by a transparent hash, apply_couplings is split into helpers,
and the copies of the simulation's random engine are marked NOSONAR.
The test data has no http:// in it. No snapshot key or format changes.

* fix(brakes): TSt113 lists the control pressure once

TSt113::pressures() added CP on top of TH14K1::pressures(), which
already has it since #366 removed the CP of TSt113 that hid it. A
snapshot held the St113's control chamber twice. The second entry is
removed.

Tests: every driver's handle lists each pressure once, and the St113
pressures of an EN57 saved through a snapshot come back on a fresh one.

* fix(simulation): snapshots skip road traffic, refuse changed sceneries, keep misplaced vehicles apart

Cars of the road spawn points which a snapshot has on the road are no longer put back: the spawn point owns
them and the snapshot would leave them frozen on the track. They're counted in the log. The pooled cars keep
their AI drivers, which the snapshot used to delete.

A snapshot whose scenery fingerprint differs is refused unless --load-snapshot-force is given: tracks named
"#N" shift when a track is added. Each vehicle is checked against the x/y/z of its entry after placing. One
more than 1 m off, or one which can't be placed, goes back where the scenery put it, isn't coupled to the
placed vehicles, and keeps its scenery state and driver.

Couplings set from a snapshot keep to CompatibleCoupling, so no MU control between an electric and a diesel
loco (#520).

The snapshotsave key writes to snapshotsdir of eu07.ini (snapshots by default, ini only like screenshotsdir),
adds _2, _3... to a name that is taken, and shows where the file went.

* refactor(simulation): the snapshot reads and writes the private state of the vehicles through their own members

Since #552 the state of physics::Vehicle and of its parts is private, and since #531 the vehicle, the AI
and the cab live in other files under other names. The snapshot code is ported to that:

- the state of a vehicle's physics is saved and loaded by physics::Vehicle::SnapshotSave() and
  SnapshotLoad() (physics/components/snapshot.cpp), with the tables of the variables in a nested
  snapshot_members; capture_mover() and apply_mover() only hand it the entry. The parts with private
  state (low voltage, line breaker, line contactors, protective relays, converter, air of the
  pantographs, compressor, air supply) give a plain Snapshot of it and take it back
  (TakeSnapshot(), RestoreSnapshot()); the rest goes through their queries and setters
- the keys, their order and the numbers in them are unchanged, so the snapshots written before load:
  the fields that moved into the parts are mapped there (Mains to lineBreaker, PipePress to brakePipe,
  BrakeCtrlPos to brakes, dizel_* to diesel, hydro_* to torqueConverter and retarder, eimv to
  inductionMotor.state in the order of the old table, EngDmgFlag to equipmentFaults, ...)
- TDynamicObject: the machinery of a vehicle (sections, rail joints, the passenger exchange) is saved
  by members of its own, as these are private now; MED_oldFED is the last ED demand of the consist's
  brake blending (ConsistBrakeBlending::LastElectrodynamicDemand())
- TController: the driving flags are saved as the bits of iDrivigFlags they were, the running brake
  test as the number of its stage, the uphill start and the braking shortfall from their structs;
  StaticBrakeTest, which is gone, is written as 0 and not read
- the couplings take Coupling, CouplingSet and VehicleEnd; orders are DriverOrders
- the unit tests of the snapshot of a vehicle use the queries and the parts

* fix(simulation): carry the driver's coupling set in the snapshot as the bits of the set

iCoupler is a CouplingSet since 2098614f, which record::set()/get() can't take. It goes
through the converted values as a whole number, as the driving flags do: Bits() on save,
CouplingSet::FromBits() on load. The key and its values are the same as before.

* fix(simulation): a loaded snapshot counts the vehicles it left where they stand

apply_isolated() set every isolated section to the count of the snapshot, also where a
vehicle the load left at its scenery place (misplaced, forced load, road traffic not put
back) stands, or where the snapshot had it. The axles of those vehicles are now counted in
the sections they stand in and out of the ones the snapshot has them in, and the memory
cells of those sections say whether they are taken by that count.

An AI consist doesn't end on a vehicle the load left: the ends are then found along what is
coupled now, as CheckVehicles() finds them.

The player entry no longer writes the cab, which nothing read: the cab is the one the
vehicle has occupied (caboccupied of its entry).

* feat(simulation): the snapshot keeps a derailment and the brakes of a sleeping vehicle

A derailed vehicle came back on the rails. Its entry now keeps what derailed it (outcome,
cause, speed, the cause and side of the motion off the track, the acceleration, the
collision derailment) and the distance its criteria were last checked over; the
derailment the scenery and the test mode were told of (new_derailment()), so it isn't told
again; and with physics.derailment new the motion of the body off the track
(derail_motion::body::state()) with the timers of the vehicle off the track. The terrain
under it is gathered anew around it when it loads.

sleep_brakes, what a sleeping vehicle's brake force came from, is kept too.

All keys are new: an entry without them leaves the vehicle as the scenery made it, so files
written before still load. New scenario case snapshot_td_off_track.

* fix(simulation): the snapshot keeps the sanded start of an AI driver

#494 (in staging since the last runs of the snapshot cases) made a driver whose start
slipped keep sanding under power until the train is under way, and take the power down a
step at a time. Neither the flag nor the time of the last step down was kept, so on
linia61 the loaded run sanded one frame later than the run which went on and parted from
it 0.06 s after loading (suwnica2, 9 mm and 0.08 km/h at 600 s). Both are kept now
(sandedstart, sandedstarttime); an entry without them leaves the driver as it is.

* fix(simulation): the snapshot keeps a train running forked on a switch thrown under it

Staging's switch fork running (#496) gave the axles and the vehicles state of their own: the way of a
switch an axle ran onto (TTrackFollower::iPath, which it leaves the switch by after a throw), the ways it
remembers of the switches behind it (path_memory, read when the axle behind it comes onto one of them),
and per vehicle the switch its bogies or its coupled ends run forked on with whether that was told
(m_forkbogies, m_forkends). None of it was in a snapshot: a loaded train on a switch thrown under it
would have left it by the way it is set now and never derailed running forked.

- Place() sets the way of the switch from the path the axle is put on, as SetCurrentTrack() does, and
  clears the facing entry the vehicle hasn't looked at (there is none between frames).
- A vehicle entry has the remembered ways of each axle, oldest first (axle0switch0, axle0way0...),
  recorded again into an empty memory on load (path_memory::entries()), and the forked watches
  (forkbogies, fork0, fork1 with their "told"). A name which isn't a switch is refused.
- New case snapshot_td_switch_thrown: the snapshot is taken while the second coach of
  eu07_td_switch_thrown_facing_behind_derails runs forked and hasn't derailed yet; the loaded run derails
  it the same way and the two files at 150 s are identical.
2026-12-02 15:40:25 +01:00

623 lines
27 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "vehicle/Driver.h"
#include "simulation/simulation.h"
#include "simulation/simulationsnapshotworld.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "world/Event.h"
#include <array>
#include <format>
#include <limits>
#include <vector>
// the part of a simulation snapshot kept by the driver of a train (TController): the orders it has and which one it's
// on, where it is in its timetable, the consist it drives, and what it has made up its mind about: the speeds it
// holds to, why it stands, what it waits for, and its table of what's ahead on the track with the limits it latched
namespace {
namespace snapshot = simulation::snapshot;
// the most events sharing a name a snapshot looks among
constexpr int most_siblings{100000};
// every order the driver knows, as bits (DriverOrders)
constexpr int every_order{(static_cast<int>(DriverOrder::jumpToFirstOrder) << 1) - 1};
// the orders as their numbers joined with commas: "1,128,16,32"
std::string join(std::span<DriverOrders const> const Orders)
{
std::string text;
for (auto const order : Orders)
{
if (false == text.empty())
text += ',';
text += std::to_string(order.Bits());
}
return text;
}
// the whole numbers of a list between Min and Max. returns: empty if one of them isn't such a number
std::optional<std::vector<int>> split(std::string_view Text, int const Min, int const Max)
{
std::vector<int> numbers;
while (false == Text.empty())
{
auto const comma{Text.find(',')};
auto const number{snapshot::text_number(Text.substr(0, comma))};
auto const whole{number.has_value() ? snapshot::whole_number(*number, Min, Max) : std::nullopt};
if (false == whole.has_value())
return std::nullopt;
numbers.emplace_back(*whole);
Text.remove_prefix(comma == std::string_view::npos ? Text.size() : comma + 1);
}
return numbers;
}
// an event under the keys "<key>" (its name) and "<key>sibling" (its place among the events sharing the name)
void save_event(snapshot::record &Entry, std::string const &Key, basic_event const *Event)
{
if (Event == nullptr)
return;
Entry.set(Key, Event->m_name);
if (auto const sibling{snapshot::event_sibling(Event)}; sibling != 0)
Entry.set(Key + "sibling", sibling);
}
basic_event *load_event(snapshot::record const &Entry, std::string const &Key)
{
auto const name{Entry.text(Key)};
auto sibling{0};
if (name.empty() || (false == Entry.get(Key + "sibling", sibling, 0, most_siblings) && Entry.has(Key + "sibling")))
return nullptr;
return snapshot::find_event(name, sibling);
}
// a point of the table of what's ahead: its numbers under "<key>", its track and its event beside them
void save_point(snapshot::record &Entry, std::string const &Key, TSpeedPos const &Point)
{
std::array const numbers{Point.fDist, Point.fVelNext, Point.fSectionVelocityDist, Point.fPointDist, static_cast<double>(Point.LegacyFlagsValue()),
Point.bMoved ? 1.0 : 0.0, Point.fMoved, Point.vPos.x, Point.vPos.y, Point.vPos.z};
Entry.set(Key, snapshot::numbers_text(numbers));
if (Point.trTrack != nullptr)
Entry.set(Key + "track", snapshot::track_reference(Point.trTrack));
save_event(Entry, Key + "event", Point.evEvent);
}
// returns: false if the entry has no such point, or it's of another make
bool load_point(snapshot::record const &Entry, std::string const &Key, TSpeedPos &Point)
{
auto const numbers{snapshot::text_numbers(Entry.text(Key))};
if (numbers.size() != 10)
return false;
// the flags of a point are bits of a whole number
auto const flags{snapshot::whole_number(numbers[4], std::numeric_limits<int>::min(), std::numeric_limits<int>::max())};
if (false == flags.has_value())
{
Entry.refuse(Key, "its flags aren't a whole number");
return false;
}
Point.fDist = numbers[0];
Point.fVelNext = numbers[1];
Point.fSectionVelocityDist = numbers[2];
Point.fPointDist = numbers[3];
// the flags and, in their top 4 bits, the route through a crossing, -8..7
Point.flags = SpeedPointFlags::FromBits(static_cast<int>(static_cast<unsigned>(*flags) & 0x0fffffffu));
Point.crossRoute = *flags >> 28;
Point.bMoved = numbers[5] != 0.0;
Point.fMoved = numbers[6];
Point.vPos = {numbers[7], numbers[8], numbers[9]};
Point.trTrack = snapshot::find_track(Entry.text(Key + "track"));
Point.evEvent = load_event(Entry, Key + "event");
// a point whose track or event the scenery no longer has can't be told from one which had none
return (Point.trTrack != nullptr) == Entry.has(Key + "track") && (Point.evEvent != nullptr) == Entry.has(Key + "event");
}
} // namespace
// the variables kept one for one, by groups in the order of the entry. they're members so that they can name the private
// ones. Driver_ and Converted_ are const for a save; Visit takes the key, the variable and, for a whole number which has
// to be in a range, the range
struct TController::snapshot_members {
// what the driver keeps in another form than the snapshot has it, as the numbers of the snapshot: taken for a save and
// for a load, put back once the load has set what the entry has
struct converted {
int flags{0}; // the driving flags, as the bits of iDrivigFlags they were (TMovementStatus)
int brakeTest{0}; // the stage of the running brake test, as the number of DynamicBrakeTest it was
int staticBrakeTest{0}; // StaticBrakeTest, which nothing read or wrote and which is gone: 0, read and left
int coupler{0}; // the couplings to make when the driver couples next (iCoupler), as the bits of the set
bool uphillStart{false}; // starting uphill: the train brake holds the train until the power does, or is being released
};
// the driving flags in the order of their bits in iDrivigFlags (moveStopCloser 0x1 .. moveDepartureWarned 0x400000)
template <typename Flags_> static auto driving_flags(Flags_ &Flags)
{
return std::array{&Flags.stopCloser, &Flags.stopPoint, &Flags.active, &Flags.press, &Flags.connect, &Flags.primary,
&Flags.late, &Flags.stopHere, &Flags.startHorn, &Flags.startHornNow, &Flags.startHornDone, &Flags.oerlikons,
&Flags.incSpeed, &Flags.trackEnd, &Flags.switchFound, &Flags.guardSignal, &Flags.visibility, &Flags.doorOpened,
&Flags.pushPull, &Flags.signalFound, &Flags.stopPointFound, &Flags.guardOpenDoor, &Flags.departureWarned};
}
static converted take(TController const &Driver)
{
converted values;
auto bits{0u};
auto bit{1u};
for (auto const *flag : driving_flags(Driver.drivingFlags))
{
bits |= *flag ? bit : 0u;
bit <<= 1;
}
// the signals the map asked to show were bits Signal_Pc6 and Signal_A1 of the same number
bits |= Driver.drivingFlags.signalPc6 ? 1u << Signal_Pc6 : 0u;
bits |= Driver.drivingFlags.signalA1 ? 1u << Signal_A1 : 0u;
values.flags = static_cast<int>(bits);
values.brakeTest = static_cast<int>(Driver.brakeTest.stage);
values.coupler = Driver.iCoupler.Bits();
values.uphillStart = Driver.uphillStart.IsActive();
return values;
}
static void put(TController &Driver, converted const &Values)
{
auto const bits{static_cast<unsigned>(Values.flags)};
auto bit{1u};
for (auto *flag : driving_flags(Driver.drivingFlags))
{
*flag = (bits & bit) != 0;
bit <<= 1;
}
Driver.drivingFlags.signalPc6 = (bits & (1u << Signal_Pc6)) != 0;
Driver.drivingFlags.signalA1 = (bits & (1u << Signal_A1)) != 0;
Driver.brakeTest.stage = static_cast<RunningBrakeTest::Stage>(Values.brakeTest);
Driver.iCoupler = CouplingSet::FromBits(Values.coupler);
// a start uphill was kept as starting or not: one going on goes on, one given in the entry starts holding
if (false == Values.uphillStart)
Driver.uphillStart.phase = uphill_start::Phase::none;
else if (false == Driver.uphillStart.IsActive())
Driver.uphillStart.phase = uphill_start::Phase::holding;
}
template <typename Driver_, typename Converted_, typename Visit_> static void speeds(Driver_ &D, Converted_ &, Visit_ const &Visit)
{
Visit("accpreferred", D.AccPreferred);
Visit("accdesired", D.AccDesired);
Visit("veldesired", D.VelDesired);
Visit("accdesiredav", D.fAccDesiredAv);
Visit("accdesiredgravity", D.fAccDesiredGravity);
Visit("velfordriver", D.VelforDriver);
Visit("velsignal", D.VelSignal);
Visit("vellimit", D.VelLimit);
Visit("velsignallast", D.VelSignalLast);
Visit("velsignalnext", D.VelSignalNext);
Visit("vellimitlast", D.VelLimitLast);
Visit("velroad", D.VelRoad);
Visit("velnext", D.VelNext);
Visit("velrestricted", D.VelRestricted);
Visit("shuntvelocity", D.fShuntVelocity);
Visit("velmax", D.fVelMax);
Visit("velplus", D.fVelPlus);
Visit("velminus", D.fVelMinus);
}
template <typename Driver_, typename Converted_, typename Visit_> static void distances(Driver_ &D, Converted_ &, Visit_ const &Visit)
{
Visit("firstsemaphordist", D.FirstSemaphorDist);
Visit("actualproximitydist", D.ActualProximityDist);
Visit("switchcleardist", D.SwitchClearDist);
Visit("signalareaenddist", D.SignalAreaEndDist);
Visit("minproximitydist", D.fMinProximityDist);
Visit("maxproximitydist", D.fMaxProximityDist);
Visit("laststopexpdist", D.fLastStopExpDist);
Visit("driverdist", D.fDriverDist);
Visit("brakedist", D.fBrakeDist);
Visit("movelen", D.dMoveLen);
Visit("length", D.fLength);
Visit("mass", D.fMass);
}
template <typename Driver_, typename Converted_, typename Visit_> static void timers(Driver_ &D, Converted_ &, Visit_ const &Visit)
{
Visit("brakeheldtime", D.fBrakeHeldTime);
Visit("shortfall", D.brakingShortfall.value);
Visit("shortfalltime", D.brakingShortfall.time);
Visit("uphillstarttime", D.uphillStart.startTime);
Visit("warningduration", D.fWarningDuration);
Visit("waitingtime", D.WaitingTime);
Visit("waitingexpiretime", D.WaitingExpireTime);
Visit("idletime", D.IdleTime);
Visit("stoptime", D.fStopTime);
Visit("reactiontime", D.ReactionTime);
Visit("lastreactiontime", D.LastReactionTime);
Visit("braketime", D.fBrakeTime);
Visit("actiontime", D.fActionTime);
Visit("radiocontroltime", D.m_radiocontroltime);
Visit("brakechargingcooldown", D.BrakeChargingCooldown);
Visit("brakechargingstart", D.BrakeChargingStart);
Visit("departblockedstart", D.DepartBlockedStart);
Visit("dbtvelocitybrake", D.brakeTest.velocityBrake);
Visit("dbtvelocityrelease", D.brakeTest.velocityRelease);
Visit("dbtvelocityfinish", D.brakeTest.velocityFinish);
Visit("dbtbrakingtime", D.brakeTest.brakingTime);
Visit("dbtreleasingtime", D.brakeTest.releasingTime);
Visit("dbtmidpointacc", D.brakeTest.midPointAcc);
Visit("lastupdatedtime", D.LastUpdatedTime);
Visit("elapsedtime", D.ElapsedTime);
// when the power was last taken down a step for a slip while starting (#494)
Visit("sandedstarttime", D.sandedStart.decreaseTime);
}
template <typename Driver_, typename Converted_, typename Visit_> static void levels(Driver_ &D, Converted_ &, Visit_ const &Visit)
{
Visit("brakectrlposition", D.BrakeCtrlPosition);
Visit("overhead1", D.fOverhead1);
Visit("overhead2", D.fOverhead2);
Visit("voltage", D.fVoltage);
Visit("driverbraking", D.fDriverBraking);
Visit("brakereaction", D.fBrakeReaction);
Visit("nominalaccthreshold", D.fNominalAccThreshold);
Visit("accthreshold", D.fAccThreshold);
Visit("absaccs", D.AbsAccS);
Visit("brakinginitiallevel", D.BrakingInitialLevel);
Visit("brakinglevelincrease", D.BrakingLevelIncrease);
Visit("accgravity", D.fAccGravity);
Visit("ready", D.fReady);
Visit("consistshade", D.ConsistShade);
Visit("medamax", D.fMedAmax);
}
template <typename Driver_, typename Converted_, typename Visit_> static void numbers(Driver_ &D, Converted_ &C, Visit_ const &Visit)
{
Visit("flags", C.flags);
Visit("direction", D.iDirection, -1, 1);
Visit("directionorder", D.iDirectionOrder, -1, 1);
Visit("vehiclecount", D.iVehicleCount);
Visit("coupler", C.coupler);
Visit("failcount", D.iDriverFailCount);
Visit("overheadzero", D.iOverheadZero);
Visit("overheaddown", D.iOverheadDown);
Visit("universalbrakebuttons", D.UniversalBrakeButtons);
Visit("dizelpercentage", D.DizelPercentage);
Visit("dizelpercentagespeed", D.DizelPercentage_Speed);
Visit("helperstate", D.HelperState);
Visit("shortfallgrowth", D.brakingShortfall.growth);
Visit("dynamicbraketest", C.brakeTest, static_cast<int>(RunningBrakeTest::Stage::waiting), static_cast<int>(RunningBrakeTest::Stage::done));
Visit("staticbraketest", C.staticBrakeTest);
Visit("radiochannel", D.iRadioChannel);
Visit("guardradio", D.iGuardRadio);
Visit("vehicles", D.iVehicles);
Visit("engines", D.ControlledEnginesCount);
Visit("lastexchangeplatforms", D.m_lastexchangeplatforms);
Visit("lastexchangedirection", D.m_lastexchangedirection);
}
template <typename Driver_, typename Converted_, typename Visit_> static void flags(Driver_ &D, Converted_ &C, Visit_ const &Visit)
{
Visit("stoptargetispassengerstop", D.bStopTargetIsPassengerStop);
Visit("uphillstart", C.uphillStart);
Visit("needtryagain", D.Need_TryAgain);
Visit("heatingtemperatureok", D.IsHeatingTemperatureOK);
Visit("heatingtemperaturetoolow", D.IsHeatingTemperatureTooLow);
Visit("atpassengerstop", D.IsAtPassengerStop);
Visit("scheduledstopvisible", D.IsScheduledPassengerStopVisible);
Visit("forcepnbrake", D.ForcePNBrake);
Visit("brakereinspection", D.BrakeReinspectionPending);
Visit("engineactive", D.iEngineActive);
Visit("passengertrain", D.IsPassengerTrain);
Visit("cargotrain", D.IsCargoTrain);
Visit("heavycargotrain", D.IsHeavyCargoTrain);
Visit("isready", D.Ready);
Visit("consistbraked", D.IsConsistBraked);
Visit("nextstopannouncement", D.m_makenextstopannouncement);
Visit("doorneedsopening", D.DoesAnyDoorNeedOpening);
// a start that slipped: sanding under power until the train is under way (#494)
Visit("sandedstart", D.sandedStart.active);
}
template <typename Driver_, typename Converted_, typename Visit_> static void texts(Driver_ &D, Converted_ &, Visit_ const &Visit)
{
Visit("nextstop", D.asNextStop);
Visit("lastexchangestop", D.m_lastexchangestop);
Visit("assignment", D.m_assignment);
}
};
namespace {
// writes a variable of the driver to the entry
struct save_visit {
snapshot::record &entry;
template <typename Type_, typename... Range_> void operator()(std::string_view const Key, Type_ const &Value, Range_...) const { entry.set(Key, Value); }
};
// sets a variable of the driver from the entry: a whole number given a range only within it
struct load_visit {
snapshot::record const &entry;
template <typename Type_, typename... Range_> void operator()(std::string_view const Key, Type_ &Target, Range_... Range) const
{
if constexpr (sizeof...(Range) == 2)
entry.get(Key, Target, static_cast<Type_>(Range)...);
else
entry.get(Key, Target);
}
};
} // namespace
void TController::snapshot_save(simulation::snapshot::record &Entry) const
{
using members = snapshot_members;
auto const converted{members::take(*this)};
save_visit const save{Entry};
// who drives, and what
Entry.set("ai", aiControlled);
Entry.set("front", snapshot::vehicle_reference(pVehicles[VehicleEnd::front]));
Entry.set("rear", snapshot::vehicle_reference(pVehicles[VehicleEnd::rear]));
// the orders: the one it's on, in words for the reader of the file, then all of them
Entry.set("order", Order2Str(OrderCurrentGet()));
Entry.set("orderpos", OrderPos);
Entry.set("orders", join(std::span{OrderList}.first(static_cast<std::size_t>(std::clamp(OrderTop, 0, maxorders)))));
// the timetable
Entry.set("train", TrainParams.TrainName);
Entry.set("station", TrainParams.StationIndex);
Entry.set("stationstart", TrainParams.StationStart);
Entry.set("nextstation", TrainParams.NextStationName);
Entry.set("latency", TrainParams.LastStationLatency);
Entry.set("timetabledirection", TrainParams.Direction);
Entry.set("ttvmax", TrainParams.TTVmax);
// the service flags of the stop the train is at or left last: central doors, doorstep, conductor, brake test
Entry.set("stopflags", std::format("{},{},{},{}", static_cast<int>(m_stopflags.central_doors), static_cast<int>(m_stopflags.doorstep),
static_cast<int>(m_stopflags.conductor), static_cast<int>(m_stopflags.brake_test)));
members::texts(*this, converted, save);
// what it does and why
Entry.set("action", eAction);
Entry.set("stopreason", eStopReason);
members::numbers(*this, converted, save);
members::flags(*this, converted, save);
members::speeds(*this, converted, save);
members::distances(*this, converted, save);
members::timers(*this, converted, save);
members::levels(*this, converted, save);
Entry.set("exchangetime", ExchangeTime);
// what the brake of the consist gives at each speed, as worked out when the consist was last looked over
Entry.set("brakea0", snapshot::numbers_text(fBrake_a0));
Entry.set("brakea1", snapshot::numbers_text(fBrake_a1));
Entry.set("brakesystem", BrakeSystem);
Entry.set("doorclosure", DoorClosure);
Entry.set("lastannouncement", m_lastannouncement);
Entry.set("vellimitlastdist0", VelLimitLastDist.first).set("vellimitlastdist1", VelLimitLastDist.second);
Entry.set("lighthint0", m_lighthints[VehicleEnd::front]).set("lighthint1", m_lighthints[VehicleEnd::rear]);
if (iDirectionBackup.has_value())
Entry.set("directionbackup", *iDirectionBackup);
if (iCouplingVehicle.has_value() && iCouplingVehicle->first != nullptr)
Entry.set("couplingvehicle", snapshot::vehicle_reference(iCouplingVehicle->first)).set("couplingend", iCouplingVehicle->second);
save_event(Entry, "signskip", eSignSkip);
save_event(Entry, "signnext", eSignNext);
snapshot_save_table(Entry);
}
// what the driver sees ahead: the table of the tracks and signs on its way, and the speed limits of points it has
// passed the signs of
void TController::snapshot_save_table(simulation::snapshot::record &Entry) const
{
Entry.set("table", sSpeedTable.size());
Entry.set("tablelast", iLast).set("tabledirection", iTableDirection).set("tablelastvel", fLastVel);
if (tLast != nullptr)
Entry.set("tablelasttrack", snapshot::track_reference(tLast));
if (SemNextIndex != npos)
Entry.set("semnext", SemNextIndex);
if (SemNextStopIndex != npos)
Entry.set("semnextstop", SemNextStopIndex);
for (std::size_t index{0}; index < sSpeedTable.size(); ++index)
save_point(Entry, std::format("p{}", index), sSpeedTable[index]);
Entry.set("limits", m_pointlimits.size());
for (std::size_t index{0}; index < m_pointlimits.size(); ++index)
{
auto const &limit{m_pointlimits[index]};
auto const key{std::format("l{}", index)};
std::array const numbers{limit.velocity, limit.distance, limit.celldistance, limit.heading.x, limit.heading.y, limit.heading.z, limit.end, limit.endknown ? 1.0 : 0.0};
Entry.set(key, snapshot::numbers_text(numbers));
save_event(Entry, key + "event", limit.source);
}
if (m_pointlimitsvehicle != nullptr)
{
std::array const position{m_pointlimitsposition.x, m_pointlimitsposition.y, m_pointlimitsposition.z, m_pointlimitslength};
Entry.set("limitsvehicle", snapshot::vehicle_reference(m_pointlimitsvehicle)).set("limitsposition", snapshot::numbers_text(position));
Entry.set("limitsend0", snapshot::vehicle_reference(m_pointlimitsends[0])).set("limitsend1", snapshot::vehicle_reference(m_pointlimitsends[1]));
}
}
// returns: false if the table of the entry can't be put back whole; the driver then looks at the track again
bool TController::snapshot_load_table(simulation::snapshot::record const &Entry)
{
TableClear();
m_pointlimits.clear();
m_pointlimitsvehicle = nullptr;
// each point of the table has a key of its own: a count past the keys of the entry can't be the count of its points
auto const points{snapshot::read_count(Entry, "table")};
if (false == points.has_value())
return false;
auto const count{*points};
std::vector<TSpeedPos> table(count);
for (std::size_t index{0}; index < count; ++index)
{
if (false == load_point(Entry, std::format("p{}", index), table[index]))
return false;
}
// the indices into the table point at one of its points, or at none (-1 and npos, which the entry doesn't write)
auto last{-1};
auto const next{snapshot::read_index(Entry, "semnext", count)};
auto const nextstop{snapshot::read_index(Entry, "semnextstop", count)};
if ((false == Entry.get("tablelast", last, -1, static_cast<int>(count) - 1) && Entry.has("tablelast")) || (false == next.has_value() && Entry.has("semnext")) ||
(false == nextstop.has_value() && Entry.has("semnextstop")))
return false;
sSpeedTable = std::move(table);
iLast = last;
Entry.get("tabledirection", iTableDirection, -1, 1);
Entry.get("tablelastvel", fLastVel);
tLast = snapshot::find_track(Entry.text("tablelasttrack"));
SemNextIndex = next.value_or(npos);
SemNextStopIndex = nextstop.value_or(npos);
eSignNext = load_event(Entry, "signnext");
auto const limits{snapshot::read_count(Entry, "limits").value_or(0)};
for (std::size_t index{0}; index < limits; ++index)
{
auto const key{std::format("l{}", index)};
auto const numbers{snapshot::text_numbers(Entry.text(key))};
auto const *source{load_event(Entry, key + "event")};
if (numbers.size() != 8 || source == nullptr)
continue;
auto &limit{m_pointlimits.emplace_back()};
limit.source = source;
limit.velocity = numbers[0];
limit.distance = numbers[1];
limit.celldistance = numbers[2];
limit.heading = {numbers[3], numbers[4], numbers[5]};
limit.end = numbers[6];
limit.endknown = numbers[7] != 0.0;
}
if (auto const position{snapshot::text_numbers(Entry.text("limitsposition"))}; position.size() == 4)
{
m_pointlimitsvehicle = snapshot::find_vehicle(Entry.text("limitsvehicle"));
m_pointlimitsposition = {position[0], position[1], position[2]};
m_pointlimitslength = position[3];
m_pointlimitsends[0] = snapshot::find_vehicle(Entry.text("limitsend0"));
m_pointlimitsends[1] = snapshot::find_vehicle(Entry.text("limitsend1"));
}
return true;
}
void TController::snapshot_load(simulation::snapshot::record const &Entry, std::function<bool(TDynamicObject const *)> const &Left)
{
using members = snapshot_members;
auto converted{members::take(*this)};
load_visit const load{Entry};
// the timetable: the scenery gave the train the one it started with, which another may have replaced since
if (auto const train{Entry.text("train", TrainParams.TrainName)}; train != TrainParams.TrainName)
{
TrainParams = TTrainParameters(train);
if (train != "none" && false == TrainParams.LoadTTfile(Global.asCurrentSceneryPath, 0, Entry.value("ttvmax", 0.0)))
ErrorLog(std::format("snapshot: timetable \"{}\" of {} can't be loaded", train, OwnerName()));
}
// the stations are entries of the table of the timetable, 1..StationCount, and the one after the last
auto const laststation{std::clamp(TrainParams.StationCount + 1, 0, MaxTTableSize)};
Entry.get("station", TrainParams.StationIndex, 0, laststation);
Entry.get("stationstart", TrainParams.StationStart, 0, laststation);
Entry.get("nextstation", TrainParams.NextStationName);
Entry.get("latency", TrainParams.LastStationLatency);
Entry.get("timetabledirection", TrainParams.Direction, -1, 1);
Entry.get("ttvmax", TrainParams.TTVmax);
m_stopflags = TrainParams.stop_flags();
if (auto const stopflags{split(Entry.text("stopflags"), 0, static_cast<int>(timetable::tristate::no)).value_or(std::vector<int>{})}; stopflags.size() == 4)
{
using timetable::tristate;
m_stopflags.central_doors = static_cast<tristate>(stopflags[0]);
m_stopflags.doorstep = static_cast<tristate>(stopflags[1]);
m_stopflags.conductor = static_cast<tristate>(stopflags[2]);
m_stopflags.brake_test = static_cast<tristate>(stopflags[3]);
}
members::texts(*this, converted, load);
// the orders
if (Entry.has("orders"))
{
// the orders are bits, and the stack holds so many of them
if (auto const orders{split(Entry.text("orders"), 0, every_order)}; orders.has_value() && orders->size() <= static_cast<std::size_t>(maxorders))
{
OrdersClear();
OrderTop = static_cast<int>(orders->size());
for (auto index{0}; index < OrderTop; ++index)
OrderList[index] = DriverOrders::FromBits((*orders)[index]);
}
else
Entry.refuse("orders", std::format("they aren't up to {} numbers of orders", maxorders));
}
// the order the driver is on is an index into the stack
Entry.get("orderpos", OrderPos, 0, maxorders - 1);
Entry.get("action", eAction, TAction::actUnknown, TAction::actTrial);
Entry.get("stopreason", eStopReason, stopNone, stopError);
members::numbers(*this, converted, load);
members::flags(*this, converted, load);
members::speeds(*this, converted, load);
members::distances(*this, converted, load);
members::timers(*this, converted, load);
members::levels(*this, converted, load);
members::put(*this, converted);
Entry.get("exchangetime", ExchangeTime);
if (auto const numbers{snapshot::text_numbers(Entry.text("brakea0"))}; numbers.size() == std::size(fBrake_a0))
std::ranges::copy(numbers, fBrake_a0);
if (auto const numbers{snapshot::text_numbers(Entry.text("brakea1"))}; numbers.size() == std::size(fBrake_a1))
std::ranges::copy(numbers, fBrake_a1);
Entry.get("brakesystem", BrakeSystem, TBrakeSystem::Individual, TBrakeSystem::ElectroPneumatic);
Entry.get("doorclosure", DoorClosure, door_closure_t::none, door_closure_t::open);
Entry.get("lastannouncement", m_lastannouncement, announcement_t::idle, announcement_t::end);
Entry.get("vellimitlastdist0", VelLimitLastDist.first);
Entry.get("vellimitlastdist1", VelLimitLastDist.second);
Entry.get("lighthint0", m_lighthints[VehicleEnd::front]);
Entry.get("lighthint1", m_lighthints[VehicleEnd::rear]);
iDirectionBackup.reset();
if (auto direction{0}; Entry.get("directionbackup", direction, -1, 1))
iDirectionBackup = direction;
iCouplingVehicle.reset();
// the end of the vehicle to couple to is one of its two couplers
if (auto *vehicle{snapshot::find_vehicle(Entry.text("couplingvehicle"))}; vehicle != nullptr)
{
if (auto end{0}; Entry.get("couplingend", end, 0, 1) || false == Entry.has("couplingend"))
iCouplingVehicle = std::make_pair(vehicle, end);
}
// the consist: its ends as they were, the vehicles driven and braked found anew among what's coupled now. an end left
// where the scenery put it isn't coupled to the consist any more: the ends are then those of what's coupled now
auto *first{snapshot::find_vehicle(Entry.text("front"))};
auto *last{snapshot::find_vehicle(Entry.text("rear"))};
if ((first != nullptr && Left(first)) || (last != nullptr && Left(last)))
{
// as CheckVehicles() finds them, from the end the consist goes to
auto end{CheckDirection() >= 0 ? 0 : 1};
first = pVehicle->FirstFind(end);
if (first == nullptr)
first = pVehicle;
// from the head to the back, the coupler to go on through turned with each vehicle coupled the other way round;
// no further than FirstFind() looks, should the couplings close a ring
last = first;
auto side{1 - end};
for (auto count{0}; count < 300; ++count)
{
auto *next{last->Neighbour(side)};
if (next == nullptr)
break;
last = next;
}
}
if (first != nullptr)
pVehicles[VehicleEnd::front] = first;
if (last != nullptr)
pVehicles[VehicleEnd::rear] = last;
ControllingSet();
if (auto ai{aiControlled}; Entry.get("ai", ai))
{
aiControlled = ai;
pVehicle->Controller = ai;
}
// what's ahead on the track as the driver had it; without it the table is filled anew from where the train is now
if (false == snapshot_load_table(Entry))
TableClear();
eSignSkip = load_event(Entry, "signskip");
// the hints of what the driver is about to do are for the player, and made again as the driver goes on
m_hints.clear();
BrakeChargingPipeOverchargeStart.clear();
}