18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-03 17:04:52 +01:00
Files
maszyna/physics/components/snapshot.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

1131 lines
48 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/.
*/
// the state of a running vehicle in a snapshot of the simulation (simulation/simulationsnapshot.h): what it carries, how it
// moves, what its machinery is set to and the air in its brakes. the list of what's kept is here; it's what a train needs
// to carry on as it was, not every variable of the physics. the keys and their order are those of the snapshots written
// before the state of the vehicle went private, so those still load
#include "stdafx.h"
#include "physics/vehicle.h"
#include "physics/brakes.h"
#include "simulation/simulationsnapshot.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <format>
#include <iterator>
#include <limits>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace snap = simulation::snapshot;
namespace
{
// keys of the parts a vehicle has two of, or a few: "pant0valve", "door1open"
std::string indexed(std::string_view const Part, int const Index, std::string_view const Key)
{
return std::format("{}{}{}", Part, Index, Key);
}
// the pressures a valve of the driver keeps, under the keys "<name>0", "<name>1"...
void capture_handle(snap::record &Entry, std::string_view const Name, TDriverHandle &Handle)
{
std::vector<double> values;
for (auto const *pressure : Handle.pressures())
values.emplace_back(*pressure);
Entry.set(Name, snap::numbers_text(values));
Entry.set(std::format("{}time", Name), (Handle.Time ? 1 : 0) | (Handle.TimeEP ? 2 : 0));
}
void apply_handle(snap::record const &Entry, std::string_view const Name, TDriverHandle &Handle)
{
auto const pressures{Handle.pressures()};
// the pressures of another kind of valve mean nothing to this one
if (auto const values{snap::text_numbers(Entry.text(Name))}; values.size() == pressures.size())
{
for (std::size_t index{0}; index < values.size(); ++index)
*pressures[index] = values[index];
}
if (auto time{0}; Entry.get(std::format("{}time", Name), time))
{
Handle.Time = (time & 1) != 0;
Handle.TimeEP = (time & 2) != 0;
}
}
// the three states of a device as one number: 1 allowed to run, 2 told to stop, 4 running
template <typename Device_> int device_state(Device_ const &Device)
{
return (Device.is_enabled ? 1 : 0) | (Device.is_disabled ? 2 : 0) | (Device.is_active ? 4 : 0);
}
template <typename Device_> void device_state(Device_ &Device, int const State)
{
Device.is_enabled = (State & 1) != 0;
Device.is_disabled = (State & 2) != 0;
Device.is_active = (State & 4) != 0;
}
template <typename Device_> void capture_device(snap::record &Entry, std::string_view const Key, Device_ const &Device)
{
Entry.set(Key, device_state(Device));
}
template <typename Device_> void apply_device(snap::record const &Entry, std::string_view const Key, Device_ &Device)
{
if (auto state{0}; Entry.get(Key, state))
device_state(Device, state);
}
// what a door is told to do, as one number: 1 permit, 2 local open, 4 local close, 8 remote open, 16 remote close
int door_inputs(physics::basic_door const &Door)
{
return (Door.open_permit ? 1 : 0) | (Door.local_open ? 2 : 0) | (Door.local_close ? 4 : 0) | (Door.remote_open ? 8 : 0) | (Door.remote_close ? 16 : 0);
}
// what a door does, as one number: 1 closed with its step, 2 the door itself closed, 4 closing, 8 opening, 16 open,
// 32 step folding, 64 step unfolding
int door_outputs(physics::basic_door const &Door)
{
return (Door.is_closed ? 1 : 0) | (Door.is_door_closed ? 2 : 0) | (Door.is_closing ? 4 : 0) | (Door.is_opening ? 8 : 0) | (Door.is_open ? 16 : 0) |
(Door.step_folding ? 32 : 0) | (Door.step_unfolding ? 64 : 0);
}
void apply_door(physics::basic_door &Door, snap::record const &Entry, int const Index)
{
if (auto inputs{0}; Entry.get(indexed("door", Index, "in"), inputs))
{
Door.open_permit = (inputs & 1) != 0;
Door.local_open = (inputs & 2) != 0;
Door.local_close = (inputs & 4) != 0;
Door.remote_open = (inputs & 8) != 0;
Door.remote_close = (inputs & 16) != 0;
}
if (auto outputs{0}; Entry.get(indexed("door", Index, "out"), outputs))
{
Door.is_closed = (outputs & 1) != 0;
Door.is_door_closed = (outputs & 2) != 0;
Door.is_closing = (outputs & 4) != 0;
Door.is_opening = (outputs & 8) != 0;
Door.is_open = (outputs & 16) != 0;
Door.step_folding = (outputs & 32) != 0;
Door.step_unfolding = (outputs & 64) != 0;
}
Entry.get(indexed("door", Index, "position"), Door.position);
Entry.get(indexed("door", Index, "step"), Door.step_position);
Entry.get(indexed("door", Index, "timer"), Door.auto_timer);
Entry.get(indexed("door", Index, "closedelay"), Door.close_delay);
Entry.get(indexed("door", Index, "opendelay"), Door.open_delay);
}
// the air of a reservoir: what it holds and, when there's any, the flow it has taken since it last acted. a flow
// added late in a step (the feed of the brake reservoir from the main pipe) waits there for the next one
void capture_reservoir(snap::record &Entry, std::string const &Key, TReservoir const &Reservoir)
{
Entry.set(Key, Reservoir.GetVol());
if (Reservoir.GetPendingFlow() != 0.0)
Entry.set(Key + "flow", Reservoir.GetPendingFlow());
}
bool apply_reservoir(TReservoir &Reservoir, snap::record const &Entry, std::string const &Key)
{
auto volume{0.0};
if (false == Entry.get(Key, volume))
return false;
Reservoir.SetVol(volume, Entry.value(Key + "flow", 0.0));
return true;
}
// the figures of an induction motor drive, which each step goes on from, in the order of the eimv table they were kept
// in before (eimv_FMAXMAX .. eimv_Fful), which is the order of the snapshot
template <typename State_> auto induction_motor_figures(State_ &State)
{
return std::array{&State.absoluteMaxForce, &State.maxForce, &State.slipShare, &State.slipFrequency, &State.supplyFrequency, &State.voltage,
&State.flux, &State.torqueCurrent, &State.fieldCurrent, &State.torque, &State.force, &State.lineCurrent,
&State.mechanicalPower, &State.electricalPower, &State.efficiency, &State.criticalFrequency, &State.linkVoltage,
&State.powerLimit, &State.forceDemand, &State.currentLimit, &State.fullForce};
}
} // namespace
struct physics::Vehicle::snapshot_members
{
// the state of the parts of the vehicle the snapshot keeps, as plain values: taken from the parts for a save and
// for a load, and put back into them once the load has set what the entry has
struct parts
{
LowVoltageSupply::Snapshot lowVoltage;
bool heating{false};
bool heatingAllow{false};
LineBreaker::Snapshot lineBreaker;
LineContactors::Snapshot lineContactors;
ProtectionRelays::Snapshot protection;
PowerConverter::Snapshot converter;
double pantographFrontVoltage{0.0};
double pantographRearVoltage{0.0};
double pantographSupplyVoltage{0.0};
bool pantographsAllDown{false};
PantographAir::Snapshot pantographAir;
AirCompressor::Snapshot compressor;
AirSupply::Snapshot air;
double brakePipePressure{0.0};
double mainPipePressure{0.0};
int handlePosition{0};
double handlePositionReal{0.0};
double handleCapPosition{0.0};
double handlePositionSmooth{0.0};
double independentPosition{0.0};
double independentPositionEim{0.0};
int handBrakePosition{0};
// the sets of flags, by their numbers
int damage{0};
int equipmentFaults{0};
};
static parts take(Vehicle const &V)
{
parts P;
P.lowVoltage = V.lowVoltage.TakeSnapshot();
P.heating = V.trainHeating.IsOn();
P.heatingAllow = V.trainHeating.IsAllowed();
P.lineBreaker = V.lineBreaker.TakeSnapshot();
P.lineContactors = V.lineContactors.TakeSnapshot();
P.protection = V.protection.TakeSnapshot();
P.converter = V.converter.TakeSnapshot();
P.pantographFrontVoltage = V.pantographCircuit.FrontVoltage();
P.pantographRearVoltage = V.pantographCircuit.RearVoltage();
P.pantographSupplyVoltage = V.pantographCircuit.SupplyVoltage();
P.pantographsAllDown = V.pantographCircuit.AllDown();
P.pantographAir = V.pantographAir.TakeSnapshot();
P.compressor = V.air.compressor.TakeSnapshot();
P.air = V.air.TakeSnapshot();
P.brakePipePressure = V.brakePipe.Pressure();
P.mainPipePressure = V.mainPipe.Pressure();
P.handlePosition = V.brakes.HandlePosition();
P.handlePositionReal = V.brakes.HandlePositionReal();
P.handleCapPosition = V.brakes.HandleCapPosition();
P.handlePositionSmooth = V.brakes.HandlePositionSmooth();
P.independentPosition = V.brakes.IndependentPosition();
P.independentPositionEim = V.brakes.IndependentPositionEim();
P.handBrakePosition = V.brakes.HandBrakePosition();
P.damage = V.DamageFlag.Bits();
P.equipmentFaults = V.equipmentFaults.Bits();
return P;
}
static void put(Vehicle &V, parts const &P)
{
V.lowVoltage.RestoreSnapshot(P.lowVoltage);
V.trainHeating.SetOn(P.heating);
V.trainHeating.Allow(P.heatingAllow);
V.lineBreaker.RestoreSnapshot(P.lineBreaker);
V.lineContactors.RestoreSnapshot(P.lineContactors);
V.protection.RestoreSnapshot(P.protection);
V.converter.RestoreSnapshot(P.converter);
V.pantographCircuit.SetFrontVoltage(P.pantographFrontVoltage);
V.pantographCircuit.SetRearVoltage(P.pantographRearVoltage);
V.pantographCircuit.SetSupplyVoltage(P.pantographSupplyVoltage);
V.pantographCircuit.SetAllDown(P.pantographsAllDown);
V.pantographAir.RestoreSnapshot(P.pantographAir);
V.air.compressor.RestoreSnapshot(P.compressor);
V.air.RestoreSnapshot(P.air);
V.brakePipe.SetPressure(P.brakePipePressure);
V.mainPipe.SetPressure(P.mainPipePressure);
V.brakes.SetHandlePosition(P.handlePosition);
V.brakes.SetHandlePositionReal(P.handlePositionReal);
V.brakes.SetHandleCapPosition(P.handleCapPosition);
V.brakes.SetHandlePositionSmooth(P.handlePositionSmooth);
V.brakes.SetIndependentPosition(P.independentPosition);
V.brakes.SetIndependentPositionEim(P.independentPositionEim);
V.brakes.SetHandBrakePosition(P.handBrakePosition);
// as the snapshot had them, without what setting them anew sets going (SetEquipmentFaults())
V.DamageFlag = DamageSet::FromBits(P.damage);
V.equipmentFaults = EquipmentFaultSet::FromBits(P.equipmentFaults);
}
// the plain values the snapshot keeps under a key each, by groups in the order of the entry. Vehicle_ and Parts_ are
// const for a save; Visit takes the key and the variable
// what the vehicle does: its movement, as the physics left it at the end of the step
template <typename Vehicle_, typename Parts_, typename Visit_> static void motion(Vehicle_ &V, Parts_ &, Visit_ const &Visit)
{
Visit("v", V.travelSpeed);
Visit("vel", V.Vel);
Visit("acc", V.accS);
Visit("accv", V.accSVBased);
Visit("nrot", V.nrotValue);
Visit("distance", V.distCounter);
Visit("movelen", V.moveLength);
}
// forces, moments and powers a step reads before it works them out anew, as it left them
template <typename Vehicle_, typename Parts_, typename Visit_> static void forces(Vehicle_ &V, Parts_ &, Visit_ const &Visit)
{
Visit("enginepower", V.EnginePower);
Visit("ft", V.ft);
Visit("fw", V.Fw);
Visit("mm", V.motorMoment);
Visit("mw", V.Mw);
Visit("fb", V.brakingForce);
Visit("ff", V.Ff);
Visit("ftrain", V.FTrain);
Visit("fstand", V.FStand);
Visit("ftotal", V.FTotal);
Visit("unitbrakeforce", V.brakes.unitForce);
Visit("ntotal", V.Ntotal);
Visit("totalcurrent", V.TotalCurrent);
Visit("dl", V.dL);
Visit("nroteps", V.nrot_eps);
Visit("accn", V.accN);
Visit("accvert", V.accVert);
Visit("dizeltorque", V.diesel.torque);
Visit("dizelpower", V.diesel.power);
Visit("dizeldeltaomega", V.diesel.clutchSlip);
Visit("dizelnold", V.diesel.previousRevolutions);
Visit("dizelnregmin", V.diesel.governorMinRevolutions);
Visit("dizelnregmax", V.diesel.governorMaxRevolutions);
Visit("hydrotorquein", V.torqueConverter.torqueIn);
Visit("hydrotorqueout", V.torqueConverter.torqueOut);
Visit("hydrotmratio", V.torqueConverter.torqueRatio);
Visit("hydrorequest", V.torqueConverter.request);
Visit("retarderfill", V.retarder.fill);
Visit("retardertorque", V.retarder.torque);
Visit("retarderrequest", V.retarder.request);
Visit("retardern", V.retarder.revolutions);
Visit("eimvpr", V.inductionMotor.forceShare);
Visit("eimicstep", V.eimic_step_progress);
Visit("eimicspeedctrl", V.eimicSpeedCtrlValue);
Visit("eimicspeedctrlintegral", V.eimicSpeedCtrlIntegral);
Visit("newspeed", V.newSpeed);
Visit("speedctrltimer", V.SpeedCtrlTimer);
Visit("vadd", V.Vadd);
Visit("medepvctime", V.brakes.blending.epCorrectionTimer);
Visit("mededdelay", V.brakes.blending.edDelayTimer);
// how long power has been asked for, which lets the holding brake of a unit go after its delay
Visit("stopbrakereleasetimer", V.brakes.holding.releaseTimer);
}
// positions of the controllers
template <typename Vehicle_, typename Parts_, typename Visit_> static void positions(Vehicle_ &V, Parts_ &P, Visit_ const &Visit)
{
Visit("mainctrl", V.mainCtrlPos);
Visit("scndctrl", V.scndCtrlPos);
Visit("mainctrlactual", V.MainCtrlActualPos);
Visit("scndctrlactual", V.ScndCtrlActualPos);
Visit("diractive", V.DirActive);
Visit("dirabsolute", V.DirAbsolute);
Visit("cabactive", V.CabActive);
Visit("caboccupied", V.cabOccupied);
Visit("lightspos", V.lightsPos);
Visit("compressorlistpos", P.compressor.listPosition);
Visit("wiperswitchpos", V.wiperSwitchPos);
Visit("pulseforcecount", V.PulseForceCount);
Visit("loadstatus", V.loadStatus);
Visit("brakectrl", P.handlePosition);
Visit("manualbrake", P.handBrakePosition);
Visit("brakedelay", V.brakes.delaySetting);
Visit("brakeopmode", V.brakes.operatingMode);
Visit("doubletr", V.DoubleTr);
Visit("damage", P.damage);
Visit("enginedamage", P.equipmentFaults);
Visit("warningsignal", V.warningSignal);
Visit("dimmer", V.modernDimmerPosition);
Visit("tuhexstage", V.TUHEX_StageActual);
}
// continuous settings, timers of the devices and the state of the engine
template <typename Vehicle_, typename Parts_, typename Visit_> static void levels(Vehicle_ &V, Parts_ &P, Visit_ const &Visit)
{
Visit("brakectrlr", P.handlePositionReal);
Visit("brakectrl2", P.handleCapPosition);
Visit("brakectrlf", P.handlePositionSmooth);
Visit("localbrake", P.independentPosition);
Visit("localbrakeeim", P.independentPositionEim);
Visit("dynamicbrakectrl", V.brakes.electrodynamic.controllerPosition);
Visit("eimic", V.eimic);
Visit("eimicanalog", V.eimicAnalog);
Visit("eimicreal", V.eimicReal);
Visit("eimlocalbrake", V.eim_localbrake);
Visit("anpos", V.anPos);
Visit("speedctrl", V.SpeedCtrlValue);
Visit("mainsinit", P.lineBreaker.initCountdown);
Visit("converterdelay", P.converter.startDelayTimer);
Visit("compressorpowertime", P.compressor.powerTime);
Visit("wheelflat", V.wheelFlat);
Visit("brakeslippingtimer", V.brakes.antiSlipTimer);
Visit("pulseforce", V.PulseForce);
Visit("pulseforcetimer", V.PulseForceTimer);
Visit("lastloadchangetime", V.LastLoadChangeTime);
Visit("brvtimer", V.brakes.electrodynamic.resistorFansTimer);
Visit("epforce", V.EpForce);
Visit("lastrelaytime", P.lineContactors.lastSwitchTime);
Visit("lastswitchingtime", V.LastSwitchingTime);
Visit("batteryvoltage", P.lowVoltage.batteryVoltage);
Visit("power24vvoltage", P.lowVoltage.power24vVoltage);
Visit("enginevoltage", V.EngineVoltage);
Visit("enrot", V.enrot);
Visit("im", V.Im);
Visit("itot", V.Itot);
Visit("rventrot", V.RventRot);
Visit("sand", V.Sand);
Visit("dizelfill", V.diesel.fill);
Visit("dizelengage", V.diesel.clutchPressure);
Visit("dizelengagestate", V.diesel.clutchState);
Visit("dizelgear", V.diesel.automaticGearShift);
Visit("dizelfiring", V.diesel.firingCountdown);
Visit("hydrofill", V.torqueConverter.fill);
Visit("hydronin", V.torqueConverter.revolutionsIn);
Visit("hydronout", V.torqueConverter.revolutionsOut);
Visit("hydrolockuprate", V.torqueConverter.lockupRate);
Visit("eangle", V.eAngleValue);
Visit("fuelrate", V.diesel.fuelConsumptionActual);
Visit("fuelused", V.diesel.fuelConsumedTotal);
}
// switches, levers and what they've set going
template <typename Vehicle_, typename Parts_, typename Visit_> static void switches(Vehicle_ &V, Parts_ &P, Visit_ const &Visit)
{
Visit("battery", P.lowVoltage.batteryOn);
Visit("mains", P.lineBreaker.closed);
Visit("converterallow", P.converter.allow);
Visit("converterallowlocal", P.converter.allowLocal);
Visit("converter", P.converter.running);
Visit("compressorallow", P.compressor.allow);
Visit("compressorallowlocal", P.compressor.allowLocal);
Visit("compressor", P.compressor.running);
Visit("compressorlock", P.compressor.governorLock);
Visit("pantcompressor", P.pantographAir.compressorRunning);
Visit("heatingallow", P.heatingAllow);
Visit("heating", P.heating);
Visit("cabmaster", V.cabMaster);
Visit("alarmchain", V.brakes.alarmChain);
Visit("radiostop", V.radioStopFlag);
Visit("radio", V.radio);
Visit("radiofuse", V.radioFuse);
Visit("signalling", V.signalling);
Visit("emergencyvalveopen", V.brakes.emergencyValve.open);
Visit("lockpipe", V.brakes.pipeLock.locked);
Visit("unlockpipe", V.brakes.pipeLock.unlockPressed);
Visit("departuresignal", V.departureSignalOn);
Visit("sanddoseauto", V.SandDoseAuto);
Visit("sanddoseautoallow", V.SandDoseAutoAllow);
Visit("inspectorcutout", V.brakes.cutOutByInspector);
Visit("physicactivation", V.physicActivation);
Visit("epfuse", V.epFuse);
Visit("shuntmode", V.ShuntMode);
Visit("pantkurek3", P.pantographAir.connectedToMainReservoir);
Visit("pantswitch", P.pantographAir.pressureSwitchActive);
Visit("pantlock", P.pantographAir.pressureLockActive);
Visit("pantalldown", P.pantographsAllDown);
Visit("sanddose", V.sandDose);
Visit("sanddosemanual", V.SandDoseManual);
Visit("dynamicbrake", V.brakes.electrodynamic.on);
Visit("stlinswitchoff", P.lineContactors.forcedOpen);
Visit("power110v", P.lowVoltage.power110vAvailable);
Visit("power24v", P.lowVoltage.power24vAvailable);
// prepared for being hauled dead: the scenery sets it, a switch of the physics can change it
Visit("pulleemode", V.pulleeMode);
}
// relays and contactors
template <typename Vehicle_, typename Parts_, typename Visit_> static void relays(Vehicle_ &V, Parts_ &P, Visit_ const &Visit)
{
Visit("fuse", V.FuseFlag);
Visit("convovld", P.converter.overloaded);
Visit("groundrelay", P.protection.ground);
Visit("stlin", P.lineContactors.closed);
Visit("resistors", V.ResistorsFlag);
Visit("novoltrelay", P.protection.noVoltage);
Visit("overvoltrelay", P.protection.overvoltage);
Visit("pressureswitch", P.protection.pressureSwitch);
Visit("delayctrl", V.delayCtrlFlag);
Visit("autorelay", V.autoRelayFlag);
Visit("slipping", V.slippingWheels);
Visit("dizelstartup", V.diesel.startupRequested);
Visit("dizelignition", V.diesel.ignitionRequested);
Visit("dizelspinup", V.diesel.spinningUp);
Visit("hydrolockup", V.torqueConverter.lockedUp);
Visit("retarderclutch", V.retarder.clutchActive);
Visit("dynamicbrakeemu", V.brakes.electrodynamic.emuWorking);
Visit("tuhexreschange", V.TUHEX_ResChange);
Visit("tuhexactive", V.TUHEX_Active);
}
// the air: pressures and volumes the physics keeps itself. the reservoirs of the brake valve come apart from these
template <typename Vehicle_, typename Parts_, typename Visit_> static void air(Vehicle_ &V, Parts_ &P, Visit_ const &Visit)
{
Visit("pipe", P.brakePipePressure);
Visit("pipeeqvt", V.brakes.equivalentPipePressure);
Visit("cntrlpipe", V.brakes.controlReservoirPressure);
Visit("scndpipe", P.mainPipePressure);
Visit("brakepress", V.brakes.cylinderPressure);
Visit("locbrakepress", V.brakes.independentCylinderPressure);
Visit("pipebrakepress", V.brakes.pipeCylinderPressure);
Visit("volume", V.brakes.reservoirAir);
Visit("compressedvolume", P.air.compressedVolume);
Visit("compressorpress", P.air.mainReservoirPressure);
Visit("limpipe", V.brakes.pipeLimiterPressure);
Visit("actflowspeed", V.actFlowSpeed);
Visit("pantvolume", P.pantographAir.volume);
Visit("pantpress", P.pantographAir.pressure);
}
// the positions a controller or a switch of the vehicle can take. they index tables of the vehicle (the resistors of
// the start by the master controller, the settings of the compressor, the lights, the wipers), so a position of the
// file past them is brought within them: a file edited by hand, or a vehicle definition with fewer positions since
static std::pair<int, int> position_range(Vehicle const &V, std::string_view const Key)
{
if (Key == "mainctrl")
return {0, std::clamp(V.MainCtrlPosNo, 0, ResArraySize)};
if (Key == "mainctrlactual")
return {0, std::clamp(std::max(V.MainCtrlPosNo, V.RlistSize), 0, ResArraySize - 1)};
if (Key == "scndctrl" || Key == "scndctrlactual")
return {0, std::max(V.scndCtrlPosNo, 0)};
if (Key == "diractive" || Key == "dirabsolute" || Key == "cabactive" || Key == "caboccupied")
return {-1, 1};
if (Key == "lightspos")
return {0, std::clamp(V.LightsPosNo, 0, static_cast<int>(std::size(V.Lights[0])))};
if (Key == "compressorlistpos")
return {0, std::clamp(V.air.compressor.config.listPositions, 0, static_cast<int>(std::size(V.air.compressor.config.list[0])) - 1)};
if (Key == "wiperswitchpos")
return {0, static_cast<int>(std::size(V.WiperList)) - 1};
if (Key == "brakectrl")
return {-2, std::max(V.brakes.config.handlePositions, 0)};
if (Key == "manualbrake")
return {0, ManualBrakePosNo};
if (Key == "dimmer")
return {0, std::max(static_cast<int>(V.dimPositions.size()) - 1, 0)};
return {std::numeric_limits<int>::min(), std::numeric_limits<int>::max()};
}
// the electric circuits of the vehicle, and what it gives and takes through its power couplings: each step starts
// from what the one before left there
static void capture_power(snap::record &Entry, Vehicle const &V)
{
std::vector<double> circuits;
for (auto const &[voltage, current] : V.PowerCircuits)
{
circuits.emplace_back(voltage);
circuits.emplace_back(current);
}
Entry.set("circuits", snap::numbers_text(circuits));
for (auto side{0}; side < 2; ++side)
{
auto const &joint{V.Couplers[side]};
std::vector<double> values;
for (auto const *power : {&joint.power_high, &joint.power_110v, &joint.power_24v})
{
values.emplace_back(power->current);
values.emplace_back(power->voltage);
values.emplace_back(power->is_local ? 1.0 : 0.0);
values.emplace_back(power->is_live ? 1.0 : 0.0);
}
Entry.set(indexed("couplerpower", side, ""), snap::numbers_text(values));
}
Entry.set("security", snap::numbers_text(V.SecuritySystem.state()));
// the figures of an induction motor drive, which each step goes on from
std::vector<double> drive;
for (auto const *figure : induction_motor_figures(V.inductionMotor.state))
drive.emplace_back(*figure);
Entry.set("eimv", snap::numbers_text(drive));
// the speed control: 1 active, 2 starting, 4 set by hand, 8 braking in, 16 braking, 32 releasing, 64 standby, 128 parking
auto const &speedctrl{V.SpeedCtrlUnit};
Entry.set("speedctrlstate", (speedctrl.IsActive ? 1 : 0) | (speedctrl.Start ? 2 : 0) | (speedctrl.ManualStateOverride ? 4 : 0) |
(speedctrl.BrakeIntervention ? 8 : 0) | (speedctrl.BrakeInterventionBraking ? 16 : 0) |
(speedctrl.BrakeInterventionUnbraking ? 32 : 0) | (speedctrl.Standby ? 64 : 0) | (speedctrl.Parking ? 128 : 0));
Entry.set("speedctrlvelocity", speedctrl.DesiredVelocity).set("speedctrlpower", speedctrl.DesiredPower);
}
static void apply_power(Vehicle &V, snap::record const &Entry)
{
if (auto const circuits{snap::text_numbers(Entry.text("circuits"))}; circuits.size() == 2 * V.PowerCircuits.size())
{
for (std::size_t index{0}; index < V.PowerCircuits.size(); ++index)
V.PowerCircuits[index] = {circuits[2 * index], circuits[2 * index + 1]};
}
for (auto side{0}; side < 2; ++side)
{
auto &joint{V.Couplers[side]};
auto const values{snap::text_numbers(Entry.text(indexed("couplerpower", side, "")))};
if (values.size() != 12)
continue;
std::size_t index{0};
for (auto *power : {&joint.power_high, &joint.power_110v, &joint.power_24v})
{
power->current = values[index];
power->voltage = values[index + 1];
power->is_local = values[index + 2] != 0.0;
power->is_live = values[index + 3] != 0.0;
index += 4;
}
}
if (Entry.has("security"))
{
// the last one is the cab it watches
if (auto const state{snap::text_numbers(Entry.text("security"))}; false == state.empty() && snap::whole_number(state.back(), -1, 1).has_value())
V.SecuritySystem.state(state);
else
Entry.refuse("security", "its cab isn't -1, 0 or 1");
}
if (auto const drive{snap::text_numbers(Entry.text("eimv"))}; drive.size() == induction_motor_figures(V.inductionMotor.state).size())
{
auto const figures{induction_motor_figures(V.inductionMotor.state)};
for (std::size_t index{0}; index < figures.size(); ++index)
*figures[index] = drive[index];
}
auto &speedctrl{V.SpeedCtrlUnit};
if (auto state{0}; Entry.get("speedctrlstate", state))
{
speedctrl.IsActive = (state & 1) != 0;
speedctrl.Start = (state & 2) != 0;
speedctrl.ManualStateOverride = (state & 4) != 0;
speedctrl.BrakeIntervention = (state & 8) != 0;
speedctrl.BrakeInterventionBraking = (state & 16) != 0;
speedctrl.BrakeInterventionUnbraking = (state & 32) != 0;
speedctrl.Standby = (state & 64) != 0;
speedctrl.Parking = (state & 128) != 0;
}
Entry.get("speedctrlvelocity", speedctrl.DesiredVelocity);
Entry.get("speedctrlpower", speedctrl.DesiredPower);
}
static void capture_devices(snap::record &Entry, Vehicle const &V, parts const &P)
{
capture_device(Entry, "pantsvalve", V.pantographAir.valve);
for (auto index{0}; index < static_cast<int>(V.pantographs.size()); ++index)
{
auto const &pantograph{V.pantographs[index]};
capture_device(Entry, indexed("pant", index, "valve"), pantograph.valve);
Entry.set(indexed("pant", index, "up"), pantograph.is_active);
Entry.set(indexed("pant", index, "voltage"), pantograph.voltage);
}
Entry.set("pantfrontvolt", P.pantographFrontVoltage);
Entry.set("pantrearvolt", P.pantographRearVoltage);
Entry.set("pantvoltage", P.pantographSupplyVoltage);
capture_device(Entry, "fuelpump", V.FuelPump);
capture_device(Entry, "oilpump", V.OilPump);
Entry.set("oilpressure", V.OilPump.pressure);
capture_device(Entry, "waterpump", V.WaterPump);
Entry.set("waterpumpbreaker", V.WaterPump.breaker);
Entry.set("waterheater", (V.WaterHeater.is_enabled ? 1 : 0) | (V.WaterHeater.is_active ? 4 : 0));
Entry.set("waterheaterbreaker", V.WaterHeater.breaker);
for (auto index{0}; index < static_cast<int>(V.MotorBlowers.size()); ++index)
{
capture_device(Entry, indexed("blower", index, ""), V.MotorBlowers[index]);
Entry.set(indexed("blower", index, "rpm"), V.MotorBlowers[index].revolutions);
}
capture_device(Entry, "compartmentlights", V.CompartmentLights);
Entry.set("lights0", V.litLights[VehicleEnd::front]);
Entry.set("lights1", V.litLights[VehicleEnd::rear]);
}
static void apply_devices(Vehicle &V, parts &P, snap::record const &Entry)
{
apply_device(Entry, "pantsvalve", V.pantographAir.valve);
for (auto index{0}; index < static_cast<int>(V.pantographs.size()); ++index)
{
auto &pantograph{V.pantographs[index]};
apply_device(Entry, indexed("pant", index, "valve"), pantograph.valve);
Entry.get(indexed("pant", index, "up"), pantograph.is_active);
Entry.get(indexed("pant", index, "voltage"), pantograph.voltage);
}
Entry.get("pantfrontvolt", P.pantographFrontVoltage);
Entry.get("pantrearvolt", P.pantographRearVoltage);
Entry.get("pantvoltage", P.pantographSupplyVoltage);
apply_device(Entry, "fuelpump", V.FuelPump);
apply_device(Entry, "oilpump", V.OilPump);
Entry.get("oilpressure", V.OilPump.pressure);
apply_device(Entry, "waterpump", V.WaterPump);
Entry.get("waterpumpbreaker", V.WaterPump.breaker);
if (auto state{0}; Entry.get("waterheater", state))
{
V.WaterHeater.is_enabled = (state & 1) != 0;
V.WaterHeater.is_active = (state & 4) != 0;
}
Entry.get("waterheaterbreaker", V.WaterHeater.breaker);
for (auto index{0}; index < static_cast<int>(V.MotorBlowers.size()); ++index)
{
apply_device(Entry, indexed("blower", index, ""), V.MotorBlowers[index]);
Entry.get(indexed("blower", index, "rpm"), V.MotorBlowers[index].revolutions);
}
apply_device(Entry, "compartmentlights", V.CompartmentLights);
Entry.get("lights0", V.litLights[VehicleEnd::front]);
Entry.get("lights1", V.litLights[VehicleEnd::rear]);
}
static void capture_doors(snap::record &Entry, Vehicle const &V)
{
Entry.set("doorlock", V.Doors.lock_enabled);
Entry.set("doorlocked", V.Doors.is_locked);
Entry.set("doorstep", V.Doors.step_enabled);
Entry.set("doorremoteonly", V.Doors.remote_only);
Entry.set("doorpreset", V.Doors.permit_preset);
for (auto index{0}; index < static_cast<int>(V.Doors.instances.size()); ++index)
{
auto const &door{V.Doors.instances[index]};
Entry.set(indexed("door", index, "in"), door_inputs(door));
Entry.set(indexed("door", index, "out"), door_outputs(door));
Entry.set(indexed("door", index, "position"), door.position);
Entry.set(indexed("door", index, "step"), door.step_position);
Entry.set(indexed("door", index, "timer"), door.auto_timer);
Entry.set(indexed("door", index, "closedelay"), door.close_delay);
Entry.set(indexed("door", index, "opendelay"), door.open_delay);
}
}
static void apply_doors(Vehicle &V, snap::record const &Entry)
{
Entry.get("doorlock", V.Doors.lock_enabled);
Entry.get("doorlocked", V.Doors.is_locked);
Entry.get("doorstep", V.Doors.step_enabled);
Entry.get("doorremoteonly", V.Doors.remote_only);
Entry.get("doorpreset", V.Doors.permit_preset);
for (auto index{0}; index < static_cast<int>(V.Doors.instances.size()); ++index)
apply_door(V.Doors.instances[index], Entry, index);
}
// the temperatures of a combustion engine and what its cooling is doing
static void capture_heat(snap::record &Entry, Vehicle const &V)
{
auto const &heat{V.diesel.heat};
Entry.set("heatts", heat.Ts).set("heatto", heat.To).set("heattsr", heat.Tsr).set("heattwy", heat.Twy).set("heattsr2", heat.Tsr2).set("heattwy2", heat.Twy2);
Entry.set("heatt1", heat.temperatura1).set("heatt2", heat.temperatura2).set("heatrpmw", heat.rpmw).set("heatrpmw2", heat.rpmw2);
Entry.set("heatshutters1", heat.zaluzje1).set("heatshutters2", heat.zaluzje2).set("heatfault", heat.PA);
Entry.set("heatrpmwz", heat.rpmwz).set("heatrpmwz2", heat.rpmwz2).set("heatenginehot", heat.engine_is_hot);
// what each circuit of the cooling tells of its fluid: 1 too cold, 2 too hot, 4 past the cooling point, 8 flowing
auto index{0};
for (auto const *circuit : {&heat.water, &heat.water_aux, &heat.oil, &heat.engine})
{
Entry.set(indexed("heatcircuit", index++, ""),
(circuit->is_cold ? 1 : 0) | (circuit->is_warm ? 2 : 0) | (circuit->is_hot ? 4 : 0) | (circuit->is_flowing ? 8 : 0));
}
}
static void apply_heat(Vehicle &V, snap::record const &Entry)
{
auto &heat{V.diesel.heat};
Entry.get("heatts", heat.Ts);
Entry.get("heatto", heat.To);
Entry.get("heattsr", heat.Tsr);
Entry.get("heattwy", heat.Twy);
Entry.get("heattsr2", heat.Tsr2);
Entry.get("heattwy2", heat.Twy2);
Entry.get("heatt1", heat.temperatura1);
Entry.get("heatt2", heat.temperatura2);
Entry.get("heatrpmw", heat.rpmw);
Entry.get("heatrpmw2", heat.rpmw2);
Entry.get("heatshutters1", heat.zaluzje1);
Entry.get("heatshutters2", heat.zaluzje2);
Entry.get("heatfault", heat.PA);
Entry.get("heatrpmwz", heat.rpmwz);
Entry.get("heatrpmwz2", heat.rpmwz2);
Entry.get("heatenginehot", heat.engine_is_hot);
auto index{0};
for (auto *circuit : {&heat.water, &heat.water_aux, &heat.oil, &heat.engine})
{
if (auto state{0}; Entry.get(indexed("heatcircuit", index++, ""), state))
{
circuit->is_cold = (state & 1) != 0;
circuit->is_warm = (state & 2) != 0;
circuit->is_hot = (state & 4) != 0;
circuit->is_flowing = (state & 8) != 0;
}
}
}
// the air of the brake: the pipes of the vehicle, the reservoirs of its valve, the valve of the driver, the spring brake
static void capture_brake(snap::record &Entry, Vehicle const &V)
{
if (V.brakePipe.reservoir != nullptr)
capture_reservoir(Entry, "pipeair", *V.brakePipe.reservoir);
if (V.mainPipe.reservoir != nullptr)
capture_reservoir(Entry, "scndpipeair", *V.mainPipe.reservoir);
// the brake set for an empty, a part loaded or a loaded vehicle
Entry.set("brakeload", V.brakes.loadSetting);
if (auto const *valve{V.brakes.distributor.get()}; valve != nullptr)
{
Entry.set("brakestatus", valve->GetBrakeStatus());
Entry.set("releaser", valve->Releaser());
// the latches of its inner valves, the step of its rapid relay
Entry.set("brakelatches", snap::numbers_text(valve->latches()));
auto index{0};
for (auto const *reservoir : valve->reservoirs())
{
if (reservoir != nullptr)
capture_reservoir(Entry, indexed("res", index, ""), *reservoir);
else
Entry.set(indexed("res", index, ""), 0.0);
++index;
}
}
if (V.brakes.driverValve != nullptr)
capture_handle(Entry, "handle", *V.brakes.driverValve);
if (V.brakes.independentValve != nullptr)
capture_handle(Entry, "lochandle", *V.brakes.independentValve);
auto const &spring{V.brakes.spring};
Entry.set("springbrake", spring.activate);
Entry.set("springbrakeshutoff", spring.shutOff);
Entry.set("springbrakerelease", spring.release);
Entry.set("springbrakeactive", spring.isActive);
Entry.set("springbrakeready", spring.isReady);
Entry.set("springbrakepress", spring.pressure);
if (spring.cylinder != nullptr)
capture_reservoir(Entry, "springbrakevolume", *spring.cylinder);
}
static void apply_brake_valve(TBrake &Valve, Vehicle const &V, snap::record const &Entry)
{
auto const reservoirs{Valve.reservoirs()};
// the air of each reservoir, when the entry has it for the reservoirs this kind of valve has; otherwise the valve
// is set as the scenery sets it at the start, to the pressures of the pipe and of the cylinders
if (auto const complete{false == reservoirs.empty() && Entry.has(indexed("res", static_cast<int>(reservoirs.size()) - 1, "")) &&
false == Entry.has(indexed("res", static_cast<int>(reservoirs.size()), ""))};
false == complete)
{
if (Entry.has("pipe"))
Valve.Init(V.brakePipe.Pressure(), V.brakes.config.pipeHighPressure, V.brakes.config.pipeLowPressure, V.brakes.cylinderPressure, V.brakes.delaySetting);
}
else
{
auto index{0};
for (auto *reservoir : reservoirs)
{
if (reservoir != nullptr)
apply_reservoir(*reservoir, Entry, indexed("res", index, ""));
++index;
}
}
if (Entry.has("brakedelay"))
Valve.SetBDF(V.brakes.delaySetting);
if (auto status{0}; Entry.get("brakestatus", status))
Valve.SetBrakeStatus(status);
// of the same kind of valve only: another kind has other latches
if (auto const latches{snap::text_numbers(Entry.text("brakelatches"))}; latches.size() == Valve.latches().size())
Valve.latches(latches);
if (auto releaser{false}; Entry.get("releaser", releaser) && releaser != Valve.Releaser())
Valve.Releaser(releaser ? 1 : 0);
}
static void apply_brake(Vehicle &V, snap::record const &Entry)
{
// the pipes of the vehicle hold the pressures the physics reads them from: by their air, or, for an entry which
// only gives the pressures, filled to those
if (V.brakePipe.reservoir != nullptr && false == apply_reservoir(*V.brakePipe.reservoir, Entry, "pipeair") && Entry.has("pipe"))
{
V.brakePipe.reservoir->CreatePress(V.brakePipe.Pressure());
V.brakePipe.reservoir->Act();
}
if (V.mainPipe.reservoir != nullptr && false == apply_reservoir(*V.mainPipe.reservoir, Entry, "scndpipeair") && Entry.has("scndpipe"))
{
V.mainPipe.reservoir->CreatePress(V.mainPipe.Pressure());
V.mainPipe.reservoir->Act();
}
if (auto setting{V.brakes.loadSetting}; Entry.get("brakeload", setting, 0, 3))
{
// by the steps of the lever, which change the ratio of the rigging with it
auto moved{true};
while (moved && V.brakes.loadSetting != setting)
moved = V.brakes.loadSetting < setting ? V.IncBrakeMult() : V.DecBrakeMult();
}
if (V.brakes.distributor != nullptr)
apply_brake_valve(*V.brakes.distributor, V, Entry);
if (V.brakes.driverValve != nullptr)
apply_handle(Entry, "handle", *V.brakes.driverValve);
if (V.brakes.independentValve != nullptr)
apply_handle(Entry, "lochandle", *V.brakes.independentValve);
auto &spring{V.brakes.spring};
Entry.get("springbrake", spring.activate);
Entry.get("springbrakeshutoff", spring.shutOff);
Entry.get("springbrakerelease", spring.release);
Entry.get("springbrakeactive", spring.isActive);
Entry.get("springbrakeready", spring.isReady);
Entry.get("springbrakepress", spring.pressure);
if (spring.cylinder != nullptr)
apply_reservoir(*spring.cylinder, Entry, "springbrakevolume");
}
// the load changes the mass, and with it what the brakes are set for
static void apply_load(Vehicle &V, snap::record const &Entry)
{
auto amount{V.loadAmount};
auto name{V.LoadType.name};
// the share of the load shown is worked out from it: what can be read as a load, up to a thousand times what the
// vehicle is rated for
auto const most{1000.f * std::max(V.maxLoad, 1.f)};
auto const given{Entry.get("load", amount, 0.f, most)};
if (Entry.has("load") && false == given)
return;
// the name of the load is that of its model, looked up in the folder of the vehicle
if (auto const *text{Entry.find("loadtype")};
text != nullptr && (text->find_first_of("/\\:") != std::string::npos || text->find("..") != std::string::npos))
{
Entry.refuse("loadtype", "a load is named by a name, not by a path");
return;
}
if (false == Entry.get("loadtype", name) && false == given)
return;
if (amount == V.loadAmount && name == V.LoadType.name)
return;
if (name == V.LoadType.name)
{
// more or less of what it carries
V.loadAmount = amount;
V.ComputeMass();
return;
}
// the vehicle is emptied first: it doesn't take a load of another kind on top of the one it has
V.AssignLoad("");
if (false == name.empty())
{
V.AssignLoad(name, amount);
// a load the vehicle isn't made for, as the scenery can give it one all the same, or one with nothing left of it
if (V.LoadType.name != name)
V.LoadType.name = name;
// AssignLoad() keeps the amount within what the vehicle is rated for, a vehicle loaded over that keeps what it had
V.loadAmount = amount;
}
V.ComputeMass();
}
// the track under the vehicle as the last step was given it. the next step works its constants out from this one
// (the resistance of a curve in ComputeConstans()) before it's given the track anew
static void capture_running(snap::record &Entry, Vehicle const &V)
{
auto const &shape{V.RunningShape};
Entry.set("runningshape", snap::numbers_text(std::array{shape.R, shape.Len, shape.dHtrack, shape.dHrail, shape.uneven_curvature, shape.uneven_cross,
shape.buckle_curvature}));
auto const &track{V.RunningTrack};
Entry.set("runningtrack", snap::numbers_text(std::array{track.Width, track.friction, static_cast<double>(track.CategoryFlag),
static_cast<double>(track.QualityFlag), static_cast<double>(track.DamageFlag),
std::isfinite(track.Velmax) ? track.Velmax : 0.0}));
auto const &traction{V.RunningTraction};
Entry.set("runningtraction",
snap::numbers_text(std::array{traction.TractionVoltage, traction.TractionFreq, traction.TractionMaxCurrent, traction.TractionResistivity}));
// where the physics has the vehicle: at the place it started the last step from, a frame behind its body. the gaps
// between the couplers are measured between these
auto const &location{V.location};
if (std::isfinite(location.X) && std::isfinite(location.Y) && std::isfinite(location.Z))
Entry.set("loc", snap::numbers_text(std::array{location.X, location.Y, location.Z}));
}
static void apply_running(Vehicle &V, snap::record const &Entry)
{
if (auto const numbers{snap::text_numbers(Entry.text("runningshape"))}; numbers.size() == 7)
{
auto &shape{V.RunningShape};
shape.R = numbers[0];
shape.Len = numbers[1];
shape.dHtrack = numbers[2];
shape.dHrail = numbers[3];
shape.uneven_curvature = numbers[4];
shape.uneven_cross = numbers[5];
shape.buckle_curvature = numbers[6];
}
if (auto const numbers{snap::text_numbers(Entry.text("runningtrack"))}; numbers.size() == 6)
{
constexpr auto lowest{std::numeric_limits<int>::min()};
constexpr auto highest{std::numeric_limits<int>::max()};
auto const category{snap::whole_number(numbers[2], lowest, highest)};
auto const quality{snap::whole_number(numbers[3], lowest, highest)};
auto const damage{snap::whole_number(numbers[4], lowest, highest)};
if (category.has_value() && quality.has_value() && damage.has_value())
{
auto &track{V.RunningTrack};
track.Width = numbers[0];
track.friction = numbers[1];
track.CategoryFlag = *category;
track.QualityFlag = *quality;
track.DamageFlag = *damage;
track.Velmax = numbers[5];
}
else
Entry.refuse("runningtrack", "its flags aren't whole numbers");
}
if (auto const numbers{snap::text_numbers(Entry.text("loc"))}; numbers.size() == 3)
V.location = {numbers[0], numbers[1], numbers[2]};
if (auto const numbers{snap::text_numbers(Entry.text("runningtraction"))}; numbers.size() == 4)
{
auto &traction{V.RunningTraction};
traction.TractionVoltage = numbers[0];
traction.TractionFreq = numbers[1];
traction.TractionMaxCurrent = numbers[2];
traction.TractionResistivity = numbers[3];
}
}
// how the vehicle left the rails, by any model of the derailment, written for a vehicle that did; and for every vehicle
// the distance its criteria of derailment were last checked over. an entry without them, written before they were
// kept, leaves the vehicle on the rails as the scenery put it
static void capture_derailment(snap::record &Entry, Vehicle const &V)
{
Entry.set("derailmentdistance", V.derailmentDistance);
if (V.derailOutcome == derailment::outcome::none && V.derailedBy == derailment::reason::none && V.collisionDerail == NONE)
return;
Entry.set("derailed", static_cast<int>(V.derailOutcome));
Entry.set("derailedby", static_cast<int>(V.derailedBy));
Entry.set("derailvelocity", V.derailVelocity);
Entry.set("derailcause", static_cast<int>(V.derailCause));
Entry.set("derailacceleration", V.derailAcceleration);
Entry.set("derailside", V.derailSide);
Entry.set("collisionderail", static_cast<int>(V.collisionDerail));
}
static void apply_derailment(Vehicle &V, snap::record const &Entry)
{
Entry.get("derailmentdistance", V.derailmentDistance);
if (auto outcome{0}; Entry.get("derailed", outcome, 0, static_cast<int>(derailment::outcome::overturned)))
V.derailOutcome = static_cast<derailment::outcome>(outcome);
if (auto reason{0}; Entry.get("derailedby", reason, 0, static_cast<int>(derailment::reason::other)))
V.derailedBy = static_cast<derailment::reason>(reason);
Entry.get("derailvelocity", V.derailVelocity);
if (auto cause{0}; Entry.get("derailcause", cause, 0, static_cast<int>(derail_motion::cause::collision)))
V.derailCause = static_cast<derail_motion::cause>(cause);
Entry.get("derailacceleration", V.derailAcceleration);
Entry.get("derailside", V.derailSide, -1, 1);
if (auto reason{0}; Entry.get("collisionderail", reason, 0, static_cast<int>(COLLISION_PUSHED_OFF)))
V.collisionDerail = static_cast<DerailReason>(reason);
}
// what the brake force came from when the physics fell asleep (physics.sleepheld): a change of it wakes the vehicle
static void capture_asleep(snap::record &Entry, Vehicle const &V)
{
auto const &brakes{V.sleep_brakes};
Entry.set("sleepbrakes", snap::numbers_text(std::array{brakes.cylinder, brakes.spring, static_cast<double>(brakes.manual), brakes.local}));
}
static void apply_asleep(Vehicle &V, snap::record const &Entry)
{
auto const numbers{snap::text_numbers(Entry.text("sleepbrakes"))};
if (numbers.size() != 4)
return;
auto const manual{snap::whole_number(numbers[2], 0, ManualBrakePosNo)};
if (false == manual.has_value())
{
Entry.refuse("sleepbrakes", "its hand brake position isn't one the vehicle has");
return;
}
auto &brakes{V.sleep_brakes};
brakes.cylinder = numbers[0];
brakes.spring = numbers[1];
brakes.manual = *manual;
brakes.local = numbers[3];
}
// what each coupler keeps from the step before: its force and the deflection of the buffers, how long it has been
// overstretched, the collision it's in, and the springs of the physical model of the pair, which give by where they were
static void capture_couplers(snap::record &Entry, Vehicle const &V)
{
for (auto side{0}; side < 2; ++side)
{
auto const &joint{V.Couplers[side]};
auto const &pair{joint.physics_state};
Entry.set(indexed("couplerstate", side, ""),
snap::numbers_text(std::array{joint.CForce, joint.Dist, static_cast<double>(joint.stretch_duration), joint.CheckCollision ? 1.0 : 0.0,
joint.crush, joint.closing, joint.hit_handled ? 1.0 : 0.0, joint.hit_force, joint.hit_duration,
pair.draw_gear.force, pair.draw_gear.deflection, pair.buffers.force, pair.buffers.deflection,
pair.elongation, pair.gap, static_cast<double>(pair.stop), pair.stop_force}));
}
}
static void apply_couplers(Vehicle &V, snap::record const &Entry)
{
for (auto side{0}; side < 2; ++side)
{
auto const values{snap::text_numbers(Entry.text(indexed("couplerstate", side, "")))};
if (values.size() != 17)
continue;
auto const stop{snap::whole_number(values[15], std::numeric_limits<int>::min(), std::numeric_limits<int>::max())};
if (false == stop.has_value())
{
Entry.refuse(indexed("couplerstate", side, ""), "the stop of the pair isn't a whole number");
continue;
}
auto &joint{V.Couplers[side]};
auto &pair{joint.physics_state};
joint.CForce = values[0];
joint.Dist = values[1];
joint.stretch_duration = static_cast<float>(values[2]);
joint.CheckCollision = values[3] != 0.0;
joint.crush = values[4];
joint.closing = values[5];
joint.hit_handled = values[6] != 0.0;
joint.hit_force = values[7];
joint.hit_duration = values[8];
pair.draw_gear.force = values[9];
pair.draw_gear.deflection = values[10];
pair.buffers.force = values[11];
pair.buffers.deflection = values[12];
pair.elongation = values[13];
pair.gap = values[14];
pair.stop = *stop;
pair.stop_force = values[16];
}
}
};
void physics::Vehicle::SnapshotSave(simulation::snapshot::record &Entry) const
{
using members = snapshot_members;
auto const parts{members::take(*this)};
auto const save{[&Entry](std::string_view const Key, auto const &Value) { Entry.set(Key, Value); }};
Entry.set("load", loadAmount);
Entry.set("loadtype", LoadType.name);
members::motion(*this, parts, save);
members::forces(*this, parts, save);
members::positions(*this, parts, save);
members::levels(*this, parts, save);
members::switches(*this, parts, save);
members::relays(*this, parts, save);
members::capture_devices(Entry, *this, parts);
members::capture_doors(Entry, *this);
members::capture_heat(Entry, *this);
members::air(*this, parts, save);
members::capture_brake(Entry, *this);
members::capture_power(Entry, *this);
members::capture_running(Entry, *this);
members::capture_couplers(Entry, *this);
members::capture_derailment(Entry, *this);
members::capture_asleep(Entry, *this);
}
void physics::Vehicle::SnapshotLoad(simulation::snapshot::record const &Entry)
{
using members = snapshot_members;
members::apply_load(*this, Entry);
// the parts as they are; what the entry has goes over it, and they get it back before the brake, which reads the pipes
auto parts{members::take(*this)};
auto const load{[&Entry](std::string_view const Key, auto &Value) { Entry.get(Key, Value); }};
members::motion(*this, parts, load);
members::forces(*this, parts, load);
members::positions(*this, parts, [this, &Entry](std::string_view const Key, int &Value) {
auto const [lowest, highest]{members::position_range(*this, Key)};
Entry.get_clamped(Key, Value, lowest, highest);
});
members::levels(*this, parts, load);
members::switches(*this, parts, load);
members::relays(*this, parts, load);
members::apply_devices(*this, parts, Entry);
members::apply_doors(*this, Entry);
members::apply_heat(*this, Entry);
members::air(*this, parts, load);
members::put(*this, parts);
members::apply_brake(*this, Entry);
members::apply_power(*this, Entry);
members::apply_running(*this, Entry);
members::apply_couplers(*this, Entry);
members::apply_derailment(*this, Entry);
members::apply_asleep(*this, Entry);
}