mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-12-03 13:35:26 +01:00
ed8708c5e2
* 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.
403 lines
18 KiB
C++
403 lines
18 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/.
|
|
*/
|
|
|
|
#pragma once
|
|
|
|
#include <charconv>
|
|
#include <cmath>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <format>
|
|
#include <fstream>
|
|
#include <functional>
|
|
#include <limits>
|
|
#include <optional>
|
|
#include <span>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <type_traits>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
class cParser;
|
|
|
|
// snapshot of a running simulation (stage A of the saved game): a text file in the syntax of the scenery files, which
|
|
// names the scenery it was taken in and holds what changed since that scenery was loaded. loading one means loading the
|
|
// scenery the usual way and then putting the saved state over it.
|
|
// this file is the text itself: the entries, how they're written and read. what goes into them is in
|
|
// simulationsnapshotmover.cpp (the state of a vehicle's machinery) and simulationsnapshotworld.cpp (the rest)
|
|
namespace simulation::snapshot {
|
|
|
|
// version of the format, the name of the "snapshot" entry which starts the file. a reader takes the files of its own
|
|
// version and older ones, and of a newer file what it knows: unknown entries and keys are skipped
|
|
inline constexpr int format_version{1};
|
|
|
|
// writes a number so that reading it back gives the very same value
|
|
std::string number_text(double Value);
|
|
// a single precision value takes fewer digits to come back the same
|
|
std::string number_text(float Value);
|
|
// reads a number written by number_text(), or any other the standard reads. returns: empty if the text isn't a number
|
|
std::optional<double> text_number(std::string_view Text);
|
|
// a few numbers as one value, with commas between them, and back; what isn't a number is left out
|
|
std::string numbers_text(std::span<double const> Numbers);
|
|
std::vector<double> text_numbers(std::string_view Text);
|
|
// a number of the file as a whole number between Min and Max. returns: empty if it isn't one (not finite, a fraction,
|
|
// out of the range)
|
|
std::optional<int> whole_number(double Value, int Min, int Max);
|
|
|
|
// the values of the file the reader doesn't take: a number out of the range of what it's put into, a count past what
|
|
// the entry can hold, a text where a number is needed. a snapshot from a damaged or edited file mustn't put an index
|
|
// past the end of a table nor a count which takes forever, so each such value is left out (or brought into its range,
|
|
// where that's said) and told of here; the simulation collects them while a snapshot is put back, for the log
|
|
void refuse(std::string Text);
|
|
// the refusals told of since the last call, in their order. a damaged file can give a great many: past the first
|
|
// hundred only their number is kept, given as the last line
|
|
std::vector<std::string> take_refusals();
|
|
|
|
// one entry of a snapshot: "<type> <name> <key> <value> <key> <value> ... end<type>". the values are single tokens,
|
|
// kept as text in the order of the file, so an entry read and written back comes out the same, whatever it holds
|
|
class record {
|
|
|
|
public:
|
|
record() = default;
|
|
record(std::string_view Type, std::string_view Name) : type(Type), name(Name) {}
|
|
|
|
// adds the value, or replaces the one the key has
|
|
template <typename Type_> record &set(std::string_view Key, Type_ const &Value);
|
|
// the value of the key, or nullptr
|
|
std::string const *find(std::string_view Key) const;
|
|
bool has(std::string_view Key) const { return find(Key) != nullptr; }
|
|
// the value of the key in the type of Target, which stays as it is when the entry has no such key or the value
|
|
// can't be read as that type (a whole number for a whole one, within the range of the type). a value which can't
|
|
// be read is refused (refuse()). returns: true if Target was set
|
|
template <typename Type_> bool get(std::string_view Key, Type_ &Target) const;
|
|
// the same, for a value which has to be between Min and Max: one past them is refused
|
|
template <typename Type_> bool get(std::string_view Key, Type_ &Target, Type_ Min, Type_ Max) const;
|
|
// the same, but a value past Min or Max is brought to it, and that's told of (refuse())
|
|
template <typename Type_> bool get_clamped(std::string_view Key, Type_ &Target, Type_ Min, Type_ Max) const;
|
|
// the value of the key, or Fallback
|
|
template <typename Type_> Type_ value(std::string_view Key, Type_ Fallback) const;
|
|
// the value of the key between Min and Max, or Fallback
|
|
template <typename Type_> Type_ value(std::string_view Key, Type_ Fallback, Type_ Min, Type_ Max) const;
|
|
std::string text(std::string_view Key, std::string_view Fallback = {}) const;
|
|
// tells of a value of the entry the reader didn't take, and why (refuse())
|
|
void refuse(std::string_view Key, std::string_view Why) const;
|
|
|
|
bool operator==(record const &) const = default;
|
|
|
|
std::string type;
|
|
std::string name;
|
|
std::vector<std::pair<std::string, std::string>> fields;
|
|
|
|
private:
|
|
void set_text(std::string_view Key, std::string Value);
|
|
};
|
|
|
|
// a count the entry gives of things it lists, each under a key of its own (the points of a table of a driver: "table"
|
|
// and "p0", "p1"...): a count past the number of keys of the entry can't be the count of what it lists, and is refused,
|
|
// as is one which isn't a whole number. returns: empty if the entry hasn't the key or its value is refused
|
|
std::optional<std::size_t> read_count(record const &Entry, std::string_view Key);
|
|
// an index the entry gives into a table of Size things: one past the end of the table is refused.
|
|
// returns: empty if the entry hasn't the key or its value is refused
|
|
std::optional<std::size_t> read_index(record const &Entry, std::string_view Key, std::size_t Size);
|
|
|
|
// the whole file: the entries in their order. the first one is the header, "snapshot <version> ... endsnapshot"
|
|
struct document {
|
|
std::vector<record> records;
|
|
// what the reader couldn't make sense of: the file is damaged or cut short. a document with problems isn't put
|
|
// over a scenery unless that's forced (accepted())
|
|
std::vector<std::string> problems;
|
|
// what a reader should know, but which doesn't keep the document from being used: a file of a newer version
|
|
std::vector<std::string> warnings;
|
|
|
|
record &add(std::string_view Type, std::string_view Name);
|
|
// the entries of the type, in the order of the file
|
|
std::vector<record const *> of(std::string_view Type) const;
|
|
// the first entry of the type with the name, or nullptr
|
|
record const *find(std::string_view Type, std::string_view Name) const;
|
|
record *find(std::string_view Type, std::string_view Name);
|
|
// the header, or nullptr if the document doesn't start with one
|
|
record const *header() const;
|
|
// the version the header gives, 0 without a header
|
|
int version() const;
|
|
};
|
|
|
|
// the document as text
|
|
void write(std::ostream &Output, document const &Document);
|
|
std::string to_text(document const &Document);
|
|
// reads the entries until the input ends
|
|
document read(cParser &Input);
|
|
document parse(std::string const &Text);
|
|
// reads the file; a file which can't be opened gives a document with that as its problem
|
|
document load(std::string const &File);
|
|
// whether the document is to be put over the scenery: it has to start with a header, and to have no problems unless
|
|
// Force says to use what could be read of it all the same (--load-snapshot-force)
|
|
bool accepted(document const &Document, bool Force);
|
|
// the steps of write_file(): opens "<file>.tmp" for Output, and puts it in place of the file once it's written.
|
|
// returns: what went wrong, empty if nothing did
|
|
std::string open_temporary(std::string const &File, std::ofstream &Output);
|
|
std::string put_in_place(std::string const &File, std::ofstream &Output);
|
|
// writes the text Writer gives to the file, whole or not at all: to "<file>.tmp" first, which takes the place of the
|
|
// file only once it's all written. a write which fails leaves the file as it was, and no .tmp behind.
|
|
// returns: what went wrong, empty if nothing did
|
|
template <typename Writer_> std::string write_file(std::string const &File, Writer_ const &Writer)
|
|
{
|
|
std::ofstream output;
|
|
if (auto error{open_temporary(File, output)}; false == error.empty())
|
|
return error;
|
|
Writer(output);
|
|
return put_in_place(File, output);
|
|
}
|
|
std::string write_file(std::string const &File, document const &Document);
|
|
|
|
// a thing of the scenery is named in a snapshot by its name where it has one of its own, which is the one the tables
|
|
// of the simulation find it by, and by its place in the table otherwise ("#12"): the tables are filled in the order
|
|
// of the scenery files, so the same scenery gives the same places
|
|
std::string reference(std::string_view Name, std::size_t Index, bool Foundbyname);
|
|
// the place in the table a reference gives, if it's of the "#12" kind
|
|
std::optional<std::size_t> reference_index(std::string_view Reference);
|
|
|
|
// a hash of names (FNV-1a, 64 bits), for the fingerprint of the scenery in the header: the snapshot remembers how many
|
|
// tracks, memory cells, events and vehicles the scenery had and a hash of their names, and a scenery which gives
|
|
// other numbers when the snapshot is loaded isn't the one it was taken in
|
|
class name_hash {
|
|
|
|
public:
|
|
void add(std::string_view Name);
|
|
std::uint64_t value() const { return m_hash; }
|
|
// as text, 16 hexadecimal digits
|
|
std::string text() const;
|
|
|
|
private:
|
|
std::uint64_t m_hash{14695981039346656037ULL};
|
|
};
|
|
|
|
// the flags of a coupling a snapshot can give: every bit of the Coupling enum of the physics (physics/vehicletypes.h), from coupler
|
|
// (0x1) to power3x400v (0x400)
|
|
inline constexpr int coupling_flags_mask{0x7ff};
|
|
|
|
// what the vehicles of a snapshot are coupled to: for a vehicle and its end (0 front, 1 rear) the vehicle and the end
|
|
// on the other side, and the Coupling flags of what's joined
|
|
struct coupling_link {
|
|
std::string vehicle;
|
|
int end{0};
|
|
std::string other;
|
|
int otherend{0};
|
|
int flags{0};
|
|
|
|
bool operator==(coupling_link const &) const = default;
|
|
};
|
|
|
|
// what has to be done to the couplings of the scenery to get the ones of the snapshot: the links to part first, then
|
|
// the links to make. a link is listed once, by the vehicle and end which come first in the given lists
|
|
struct coupling_plan {
|
|
std::vector<coupling_link> part;
|
|
std::vector<coupling_link> join;
|
|
// the links to set other flags on: joined to the same vehicle and end already, but by other means
|
|
std::vector<coupling_link> change;
|
|
// the links of the snapshot to vehicles which aren't in Present
|
|
std::vector<coupling_link> missing;
|
|
// the links of the snapshot which would close a ring of vehicles (a vehicle coupled to itself, or the last vehicle
|
|
// of a consist to its first): a consist is a line, and the code which walks along one would never get to its end
|
|
std::vector<coupling_link> refused;
|
|
};
|
|
// Current: the links as they are, each given from both of its ends or from one. Wanted: the same for the snapshot.
|
|
// Present: the names of the vehicles of the scenery which can be coupled as the snapshot has them. links of vehicles the
|
|
// snapshot says nothing of stay as they are, unless a vehicle of the snapshot needs the coupler at their other end. a
|
|
// vehicle left out of Present (one which stays where the scenery put it) is parted from the vehicles of the snapshot,
|
|
// and the links of the snapshot to it are missing
|
|
coupling_plan plan_couplings(std::vector<coupling_link> const &Current, std::vector<coupling_link> const &Wanted, std::vector<std::string> const &Present);
|
|
// the couplings of the vehicle entries ("coupler0", "coupler0end", "coupler0flags" and the same for 1), for
|
|
// plan_couplings(). an end other than 0 or 1, or flags which aren't those of a coupling, are refused (refuse()): that
|
|
// coupler is left out, as if the entry said nothing of it
|
|
std::vector<coupling_link> read_couplings(std::vector<record const *> const &Entries);
|
|
|
|
// how far a vehicle may be put from the place in the world its entry gives ("x", "y", "z") to be where the snapshot has
|
|
// it. further off, the track the entry names is another one now: the scenery changed since the snapshot was taken
|
|
inline constexpr double misplaced_distance{1.0};
|
|
// whether the vehicle, put at X Y Z, is where the entry has it. an entry without its place in the world can't tell, and
|
|
// is taken at its word
|
|
bool placed_where_saved(record const &Entry, double X, double Y, double Z);
|
|
// what differs between the fingerprint of the scenery in the header of a snapshot (Saved) and the one of the scenery
|
|
// it's put over (Now): "tracks 812 (snapshot 811), names ...". returns: empty if they're the same
|
|
std::string fingerprint_changes(record const &Saved, record const &Now);
|
|
// the file to write in place of File, which is taken already: "<stem>_2<extension>", "<stem>_3<extension>"... the first
|
|
// one which isn't. returns: File itself if it isn't taken
|
|
std::string free_file(std::string const &File);
|
|
|
|
// the snapshots asked for on the command line of the simulator
|
|
struct command_line {
|
|
struct save_request {
|
|
double time{0.0}; // of the simulation, seconds since the scenery started (Timer::GetTime())
|
|
std::string file;
|
|
};
|
|
std::string load; // --load-snapshot <file>: put over the scenery once it's loaded
|
|
bool force{false}; // --load-snapshot-force: a damaged file is put over the scenery as far as it could be read
|
|
std::vector<save_request> saves; // --snapshot-at <seconds> <file>, any number of them: written when the time comes
|
|
std::string error; // what's wrong with the options; empty if nothing
|
|
};
|
|
// picks the snapshot options out of a command line (the first argument is the program), skipping the values of the
|
|
// other options the simulator takes
|
|
command_line parse_command_line(std::span<char const *const> Arguments);
|
|
// how many values follow an option of the simulator on its command line, for the parsers which pick out their own
|
|
int option_value_count(std::string_view Option);
|
|
|
|
// implementation of the templates
|
|
|
|
namespace detail {
|
|
|
|
template <typename Type_> std::string value_text(Type_ const &Value)
|
|
{
|
|
using type = std::remove_cvref_t<Type_>;
|
|
if constexpr (std::is_same_v<type, bool>)
|
|
return Value ? "1" : "0";
|
|
else if constexpr (std::is_enum_v<type>)
|
|
return std::to_string(static_cast<long long>(Value));
|
|
else if constexpr (std::is_integral_v<type>)
|
|
return std::to_string(Value);
|
|
else if constexpr (std::is_same_v<type, float>)
|
|
return number_text(Value);
|
|
else if constexpr (std::is_floating_point_v<type>)
|
|
return number_text(static_cast<double>(Value));
|
|
else
|
|
return std::string(std::string_view(Value));
|
|
}
|
|
|
|
// whether the number fits a variable of the integer type: whole, and within its range
|
|
template <typename Integer_> bool fits_integer(double const Number)
|
|
{
|
|
using limits = std::numeric_limits<Integer_>;
|
|
// the bounds as exact doubles: -2^63 .. 2^63 for a 64 bit signed type, 0 .. 2^64 for an unsigned one; the upper one
|
|
// is past the range
|
|
auto const lowest{limits::is_signed ? -std::ldexp(1.0, limits::digits) : 0.0};
|
|
auto const past{std::ldexp(1.0, limits::digits)};
|
|
return std::isfinite(Number) && std::trunc(Number) == Number && Number >= lowest && Number < past;
|
|
}
|
|
|
|
template <typename Type_> bool text_value(std::string const &Text, Type_ &Target)
|
|
{
|
|
using type = std::remove_cvref_t<Type_>;
|
|
if constexpr (std::is_same_v<type, std::string>)
|
|
{
|
|
Target = Text;
|
|
return true;
|
|
}
|
|
else
|
|
{
|
|
auto const number{text_number(Text)};
|
|
if (false == number.has_value())
|
|
return false;
|
|
if constexpr (std::is_same_v<type, bool>)
|
|
{
|
|
if (std::isnan(*number))
|
|
return false;
|
|
Target = *number != 0.0;
|
|
}
|
|
else if constexpr (std::is_enum_v<type> || std::is_integral_v<type>)
|
|
{
|
|
// an integer out of the range of its type is undefined, a fraction isn't what was written
|
|
using integer = typename std::conditional_t<std::is_enum_v<type>, std::underlying_type<type>, std::type_identity<type>>::type;
|
|
if (false == fits_integer<integer>(*number))
|
|
return false;
|
|
Target = static_cast<type>(static_cast<integer>(*number));
|
|
}
|
|
else
|
|
{
|
|
// not a number and the infinities are values like any other, a finite number too big for the type isn't: one
|
|
// which rounds past its largest value
|
|
auto const top{static_cast<double>(std::numeric_limits<type>::max())};
|
|
if (auto const step{top - static_cast<double>(std::nextafter(std::numeric_limits<type>::max(), type{0}))};
|
|
std::isfinite(*number) && std::abs(*number) >= top + step / 2)
|
|
return false;
|
|
Target = static_cast<type>(*number);
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
|
|
// the text of a bound, for what's told of a value out of its range
|
|
template <typename Type_> std::string bound_text(Type_ const Value)
|
|
{
|
|
if constexpr (std::is_enum_v<Type_>)
|
|
return std::to_string(static_cast<long long>(Value));
|
|
else
|
|
return value_text(Value);
|
|
}
|
|
|
|
} // namespace detail
|
|
|
|
template <typename Type_> record &record::set(std::string_view const Key, Type_ const &Value)
|
|
{
|
|
set_text(Key, detail::value_text(Value));
|
|
return *this;
|
|
}
|
|
|
|
template <typename Type_> bool record::get(std::string_view const Key, Type_ &Target) const
|
|
{
|
|
auto const *text{find(Key)};
|
|
if (text == nullptr)
|
|
return false;
|
|
if (detail::text_value(*text, Target))
|
|
return true;
|
|
refuse(Key, "it can't be read as a value of its kind");
|
|
return false;
|
|
}
|
|
|
|
template <typename Type_> bool record::get(std::string_view const Key, Type_ &Target, Type_ const Min, Type_ const Max) const
|
|
{
|
|
auto value{Target};
|
|
if (false == get(Key, value))
|
|
return false;
|
|
// written so that not a number fails too
|
|
if (false == (value >= Min && value <= Max))
|
|
{
|
|
refuse(Key, std::format("it's out of the range {} .. {}", detail::bound_text(Min), detail::bound_text(Max)));
|
|
return false;
|
|
}
|
|
Target = value;
|
|
return true;
|
|
}
|
|
|
|
template <typename Type_> bool record::get_clamped(std::string_view const Key, Type_ &Target, Type_ const Min, Type_ const Max) const
|
|
{
|
|
auto value{Target};
|
|
if (false == get(Key, value))
|
|
return false;
|
|
if constexpr (std::is_floating_point_v<Type_>)
|
|
{
|
|
if (std::isnan(value))
|
|
{
|
|
refuse(Key, "it's not a number");
|
|
return false;
|
|
}
|
|
}
|
|
if (value < Min || value > Max)
|
|
{
|
|
auto const clamped{value < Min ? Min : Max};
|
|
refuse(Key, std::format("it's out of the range {} .. {}, {} is taken", detail::bound_text(Min), detail::bound_text(Max), detail::bound_text(clamped)));
|
|
value = clamped;
|
|
}
|
|
Target = value;
|
|
return true;
|
|
}
|
|
|
|
template <typename Type_> Type_ record::value(std::string_view const Key, Type_ Fallback) const
|
|
{
|
|
get(Key, Fallback);
|
|
return Fallback;
|
|
}
|
|
|
|
template <typename Type_> Type_ record::value(std::string_view const Key, Type_ Fallback, Type_ const Min, Type_ const Max) const
|
|
{
|
|
get(Key, Fallback, Min, Max);
|
|
return Fallback;
|
|
}
|
|
|
|
} // namespace simulation::snapshot
|