18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-04 07:04:42 +01:00

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.
This commit is contained in:
jerrrrycho
2026-11-19 06:49:17 +01:00
parent e6e177cb06
commit 021b281085
4 changed files with 558 additions and 0 deletions
+1
View File
@@ -181,6 +181,7 @@ set(SOURCES
"simulation/simulationtest.cpp"
"simulation/simulationsnapshotworld.cpp"
"simulation/simulationsnapshotvehicle.cpp"
"simulation/simulationsnapshotdriver.cpp"
"scene/sceneeditor.cpp"
"rendering/screenshot.cpp"
"input/driverkeyboardinput.cpp"
+469
View File
@@ -0,0 +1,469 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "vehicle/Driver.h"
#include "simulation/simulation.h"
#include "simulation/simulationsnapshotworld.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "world/Event.h"
#include <array>
#include <format>
#include <vector>
// the part of a simulation snapshot kept by the driver of a train (TController): the orders it has and which one it's
// on, where it is in its timetable, the consist it drives, and what it has made up its mind about: the speeds it
// holds to, why it stands, what it waits for, and its table of what's ahead on the track with the limits it latched
namespace {
namespace snapshot = simulation::snapshot;
// a variable of the driver kept under a key of the entry
template <typename Type_> struct member {
std::string_view key;
Type_ TController::*variable;
};
template <typename Table_> void save_members(snapshot::record &Entry, TController const &Driver, Table_ const &Table)
{
for (auto const &item : Table)
Entry.set(item.key, Driver.*(item.variable));
}
template <typename Table_> void load_members(TController &Driver, snapshot::record const &Entry, Table_ const &Table)
{
for (auto const &item : Table)
Entry.get(item.key, Driver.*(item.variable));
}
// the orders as their numbers joined with commas: "1,128,16,32"
std::string join(std::span<TOrders const> const Orders)
{
std::string text;
for (auto const order : Orders)
{
if (false == text.empty())
text += ',';
text += std::to_string(static_cast<int>(order));
}
return text;
}
std::vector<int> split(std::string_view Text)
{
std::vector<int> numbers;
while (false == Text.empty())
{
auto const comma{Text.find(',')};
if (auto const number{snapshot::text_number(Text.substr(0, comma))}; number.has_value())
numbers.emplace_back(static_cast<int>(*number));
Text.remove_prefix(comma == std::string_view::npos ? Text.size() : comma + 1);
}
return numbers;
}
// an event under the keys "<key>" (its name) and "<key>sibling" (its place among the events sharing the name)
void save_event(snapshot::record &Entry, std::string const &Key, basic_event const *Event)
{
if (Event == nullptr)
return;
Entry.set(Key, Event->m_name);
if (auto const sibling{snapshot::event_sibling(Event)}; sibling != 0)
Entry.set(Key + "sibling", sibling);
}
basic_event *load_event(snapshot::record const &Entry, std::string const &Key)
{
auto const name{Entry.text(Key)};
return name.empty() ? nullptr : snapshot::find_event(name, Entry.value(Key + "sibling", 0));
}
// a point of the table of what's ahead: its numbers under "<key>", its track and its event beside them
void save_point(snapshot::record &Entry, std::string const &Key, TSpeedPos const &Point)
{
std::array const numbers{Point.fDist, Point.fVelNext, Point.fSectionVelocityDist, Point.fPointDist, static_cast<double>(Point.iFlags),
Point.bMoved ? 1.0 : 0.0, Point.fMoved, Point.vPos.x, Point.vPos.y, Point.vPos.z};
Entry.set(Key, snapshot::numbers_text(numbers));
if (Point.trTrack != nullptr)
Entry.set(Key + "track", snapshot::track_reference(Point.trTrack));
save_event(Entry, Key + "event", Point.evEvent);
}
// returns: false if the entry has no such point, or it's of another make
bool load_point(snapshot::record const &Entry, std::string const &Key, TSpeedPos &Point)
{
auto const numbers{snapshot::text_numbers(Entry.text(Key))};
if (numbers.size() != 10)
return false;
Point.fDist = numbers[0];
Point.fVelNext = numbers[1];
Point.fSectionVelocityDist = numbers[2];
Point.fPointDist = numbers[3];
Point.iFlags = static_cast<int>(numbers[4]);
Point.bMoved = numbers[5] != 0.0;
Point.fMoved = numbers[6];
Point.vPos = {numbers[7], numbers[8], numbers[9]};
Point.trTrack = snapshot::find_track(Entry.text(Key + "track"));
Point.evEvent = load_event(Entry, Key + "event");
// a point whose track or event the scenery no longer has can't be told from one which had none
return (Point.trTrack != nullptr) == Entry.has(Key + "track") && (Point.evEvent != nullptr) == Entry.has(Key + "event");
}
} // namespace
// the variables kept one for one. the tables are members so that they can name the private ones
struct TController::snapshot_members {
static constexpr std::array speeds{
member<double>{"accpreferred", &TController::AccPreferred},
member<double>{"accdesired", &TController::AccDesired},
member<double>{"veldesired", &TController::VelDesired},
member<double>{"accdesiredav", &TController::fAccDesiredAv},
member<double>{"accdesiredgravity", &TController::fAccDesiredGravity},
member<double>{"velfordriver", &TController::VelforDriver},
member<double>{"velsignal", &TController::VelSignal},
member<double>{"vellimit", &TController::VelLimit},
member<double>{"velsignallast", &TController::VelSignalLast},
member<double>{"velsignalnext", &TController::VelSignalNext},
member<double>{"vellimitlast", &TController::VelLimitLast},
member<double>{"velroad", &TController::VelRoad},
member<double>{"velnext", &TController::VelNext},
member<double>{"velrestricted", &TController::VelRestricted},
member<double>{"shuntvelocity", &TController::fShuntVelocity},
member<double>{"velmax", &TController::fVelMax},
member<double>{"velplus", &TController::fVelPlus},
member<double>{"velminus", &TController::fVelMinus},
};
static constexpr std::array distances{
member<double>{"firstsemaphordist", &TController::FirstSemaphorDist},
member<double>{"actualproximitydist", &TController::ActualProximityDist},
member<double>{"switchcleardist", &TController::SwitchClearDist},
member<double>{"signalareaenddist", &TController::SignalAreaEndDist},
member<double>{"minproximitydist", &TController::fMinProximityDist},
member<double>{"maxproximitydist", &TController::fMaxProximityDist},
member<double>{"laststopexpdist", &TController::fLastStopExpDist},
member<double>{"driverdist", &TController::fDriverDist},
member<double>{"brakedist", &TController::fBrakeDist},
member<double>{"movelen", &TController::dMoveLen},
member<double>{"length", &TController::fLength},
member<double>{"mass", &TController::fMass},
};
static constexpr std::array timers{
member<double>{"brakeheldtime", &TController::fBrakeHeldTime},
member<double>{"shortfall", &TController::fShortfall},
member<double>{"shortfalltime", &TController::fShortfallTime},
member<double>{"uphillstarttime", &TController::fUphillStartTime},
member<double>{"warningduration", &TController::fWarningDuration},
member<double>{"waitingtime", &TController::WaitingTime},
member<double>{"waitingexpiretime", &TController::WaitingExpireTime},
member<double>{"idletime", &TController::IdleTime},
member<double>{"stoptime", &TController::fStopTime},
member<double>{"reactiontime", &TController::ReactionTime},
member<double>{"lastreactiontime", &TController::LastReactionTime},
member<double>{"braketime", &TController::fBrakeTime},
member<double>{"actiontime", &TController::fActionTime},
member<double>{"radiocontroltime", &TController::m_radiocontroltime},
member<double>{"brakechargingcooldown", &TController::BrakeChargingCooldown},
member<double>{"brakechargingstart", &TController::BrakeChargingStart},
member<double>{"departblockedstart", &TController::DepartBlockedStart},
member<double>{"dbtvelocitybrake", &TController::DBT_VelocityBrake},
member<double>{"dbtvelocityrelease", &TController::DBT_VelocityRelease},
member<double>{"dbtvelocityfinish", &TController::DBT_VelocityFinish},
member<double>{"dbtbrakingtime", &TController::DBT_BrakingTime},
member<double>{"dbtreleasingtime", &TController::DBT_ReleasingTime},
member<double>{"dbtmidpointacc", &TController::DBT_MidPointAcc},
member<double>{"lastupdatedtime", &TController::LastUpdatedTime},
member<double>{"elapsedtime", &TController::ElapsedTime},
};
static constexpr std::array levels{
member<double>{"brakectrlposition", &TController::BrakeCtrlPosition},
member<double>{"overhead1", &TController::fOverhead1},
member<double>{"overhead2", &TController::fOverhead2},
member<double>{"voltage", &TController::fVoltage},
member<double>{"driverbraking", &TController::fDriverBraking},
member<double>{"brakereaction", &TController::fBrakeReaction},
member<double>{"nominalaccthreshold", &TController::fNominalAccThreshold},
member<double>{"accthreshold", &TController::fAccThreshold},
member<double>{"absaccs", &TController::AbsAccS},
member<double>{"brakinginitiallevel", &TController::BrakingInitialLevel},
member<double>{"brakinglevelincrease", &TController::BrakingLevelIncrease},
member<double>{"accgravity", &TController::fAccGravity},
member<double>{"ready", &TController::fReady},
member<double>{"consistshade", &TController::ConsistShade},
member<double>{"medamax", &TController::fMedAmax},
};
static constexpr std::array numbers{
member<int>{"flags", &TController::iDrivigFlags},
member<int>{"direction", &TController::iDirection},
member<int>{"directionorder", &TController::iDirectionOrder},
member<int>{"vehiclecount", &TController::iVehicleCount},
member<int>{"coupler", &TController::iCoupler},
member<int>{"failcount", &TController::iDriverFailCount},
member<int>{"overheadzero", &TController::iOverheadZero},
member<int>{"overheaddown", &TController::iOverheadDown},
member<int>{"universalbrakebuttons", &TController::UniversalBrakeButtons},
member<int>{"dizelpercentage", &TController::DizelPercentage},
member<int>{"dizelpercentagespeed", &TController::DizelPercentage_Speed},
member<int>{"helperstate", &TController::HelperState},
member<int>{"shortfallgrowth", &TController::iShortfallGrowth},
member<int>{"dynamicbraketest", &TController::DynamicBrakeTest},
member<int>{"staticbraketest", &TController::StaticBrakeTest},
member<int>{"radiochannel", &TController::iRadioChannel},
member<int>{"guardradio", &TController::iGuardRadio},
member<int>{"vehicles", &TController::iVehicles},
member<int>{"engines", &TController::ControlledEnginesCount},
member<int>{"lastexchangeplatforms", &TController::m_lastexchangeplatforms},
member<int>{"lastexchangedirection", &TController::m_lastexchangedirection},
};
static constexpr std::array flags{
member<bool>{"stoptargetispassengerstop", &TController::bStopTargetIsPassengerStop},
member<bool>{"uphillstart", &TController::bUphillStart},
member<bool>{"needtryagain", &TController::Need_TryAgain},
member<bool>{"heatingtemperatureok", &TController::IsHeatingTemperatureOK},
member<bool>{"heatingtemperaturetoolow", &TController::IsHeatingTemperatureTooLow},
member<bool>{"atpassengerstop", &TController::IsAtPassengerStop},
member<bool>{"scheduledstopvisible", &TController::IsScheduledPassengerStopVisible},
member<bool>{"forcepnbrake", &TController::ForcePNBrake},
member<bool>{"brakereinspection", &TController::BrakeReinspectionPending},
member<bool>{"engineactive", &TController::iEngineActive},
member<bool>{"passengertrain", &TController::IsPassengerTrain},
member<bool>{"cargotrain", &TController::IsCargoTrain},
member<bool>{"heavycargotrain", &TController::IsHeavyCargoTrain},
member<bool>{"isready", &TController::Ready},
member<bool>{"consistbraked", &TController::IsConsistBraked},
member<bool>{"nextstopannouncement", &TController::m_makenextstopannouncement},
member<bool>{"doorneedsopening", &TController::DoesAnyDoorNeedOpening},
};
static constexpr std::array texts{
member<std::string>{"nextstop", &TController::asNextStop},
member<std::string>{"lastexchangestop", &TController::m_lastexchangestop},
member<std::string>{"assignment", &TController::m_assignment},
};
};
void TController::snapshot_save(simulation::snapshot::record &Entry) const
{
// who drives, and what
Entry.set("ai", AIControllFlag);
Entry.set("front", snapshot::vehicle_reference(pVehicles[end::front]));
Entry.set("rear", snapshot::vehicle_reference(pVehicles[end::rear]));
// the orders: the one it's on, in words for the reader of the file, then all of them
Entry.set("order", Order2Str(OrderCurrentGet()));
Entry.set("orderpos", OrderPos);
Entry.set("orders", join(std::span{OrderList}.first(static_cast<std::size_t>(std::clamp(OrderTop, 0, maxorders)))));
// the timetable
Entry.set("train", TrainParams.TrainName);
Entry.set("station", TrainParams.StationIndex);
Entry.set("stationstart", TrainParams.StationStart);
Entry.set("nextstation", TrainParams.NextStationName);
Entry.set("latency", TrainParams.LastStationLatency);
Entry.set("timetabledirection", TrainParams.Direction);
Entry.set("ttvmax", TrainParams.TTVmax);
// the service flags of the stop the train is at or left last: central doors, doorstep, conductor, brake test
Entry.set("stopflags", std::format("{},{},{},{}", static_cast<int>(m_stopflags.central_doors), static_cast<int>(m_stopflags.doorstep),
static_cast<int>(m_stopflags.conductor), static_cast<int>(m_stopflags.brake_test)));
save_members(Entry, *this, snapshot_members::texts);
// what it does and why
Entry.set("action", eAction);
Entry.set("stopreason", eStopReason);
save_members(Entry, *this, snapshot_members::numbers);
save_members(Entry, *this, snapshot_members::flags);
save_members(Entry, *this, snapshot_members::speeds);
save_members(Entry, *this, snapshot_members::distances);
save_members(Entry, *this, snapshot_members::timers);
save_members(Entry, *this, snapshot_members::levels);
Entry.set("exchangetime", ExchangeTime);
// what the brake of the consist gives at each speed, as worked out when the consist was last looked over
Entry.set("brakea0", snapshot::numbers_text(fBrake_a0));
Entry.set("brakea1", snapshot::numbers_text(fBrake_a1));
Entry.set("brakesystem", BrakeSystem);
Entry.set("doorclosure", DoorClosure);
Entry.set("lastannouncement", m_lastannouncement);
Entry.set("vellimitlastdist0", VelLimitLastDist.first).set("vellimitlastdist1", VelLimitLastDist.second);
Entry.set("lighthint0", m_lighthints[end::front]).set("lighthint1", m_lighthints[end::rear]);
if (iDirectionBackup.has_value())
Entry.set("directionbackup", *iDirectionBackup);
if (iCouplingVehicle.has_value() && iCouplingVehicle->first != nullptr)
Entry.set("couplingvehicle", snapshot::vehicle_reference(iCouplingVehicle->first)).set("couplingend", iCouplingVehicle->second);
save_event(Entry, "signskip", eSignSkip);
save_event(Entry, "signnext", eSignNext);
snapshot_save_table(Entry);
}
// what the driver sees ahead: the table of the tracks and signs on its way, and the speed limits of points it has
// passed the signs of
void TController::snapshot_save_table(simulation::snapshot::record &Entry) const
{
Entry.set("table", sSpeedTable.size());
Entry.set("tablelast", iLast).set("tabledirection", iTableDirection).set("tablelastvel", fLastVel);
if (tLast != nullptr)
Entry.set("tablelasttrack", snapshot::track_reference(tLast));
if (SemNextIndex != npos)
Entry.set("semnext", SemNextIndex);
if (SemNextStopIndex != npos)
Entry.set("semnextstop", SemNextStopIndex);
for (std::size_t index{0}; index < sSpeedTable.size(); ++index)
save_point(Entry, std::format("p{}", index), sSpeedTable[index]);
Entry.set("limits", m_pointlimits.size());
for (std::size_t index{0}; index < m_pointlimits.size(); ++index)
{
auto const &limit{m_pointlimits[index]};
auto const key{std::format("l{}", index)};
std::array const numbers{limit.velocity, limit.distance, limit.celldistance, limit.heading.x, limit.heading.y, limit.heading.z, limit.end, limit.endknown ? 1.0 : 0.0};
Entry.set(key, snapshot::numbers_text(numbers));
save_event(Entry, key + "event", limit.source);
}
if (m_pointlimitsvehicle != nullptr)
{
std::array const position{m_pointlimitsposition.x, m_pointlimitsposition.y, m_pointlimitsposition.z, m_pointlimitslength};
Entry.set("limitsvehicle", snapshot::vehicle_reference(m_pointlimitsvehicle)).set("limitsposition", snapshot::numbers_text(position));
Entry.set("limitsend0", snapshot::vehicle_reference(m_pointlimitsends[0])).set("limitsend1", snapshot::vehicle_reference(m_pointlimitsends[1]));
}
}
// returns: false if the table of the entry can't be put back whole; the driver then looks at the track again
bool TController::snapshot_load_table(simulation::snapshot::record const &Entry)
{
TableClear();
m_pointlimits.clear();
m_pointlimitsvehicle = nullptr;
std::size_t count{0};
if (false == Entry.get("table", count))
return false;
std::vector<TSpeedPos> table(count);
for (std::size_t index{0}; index < count; ++index)
{
if (false == load_point(Entry, std::format("p{}", index), table[index]))
return false;
}
sSpeedTable = std::move(table);
Entry.get("tablelast", iLast);
Entry.get("tabledirection", iTableDirection);
Entry.get("tablelastvel", fLastVel);
tLast = snapshot::find_track(Entry.text("tablelasttrack"));
SemNextIndex = Entry.value("semnext", npos);
SemNextStopIndex = Entry.value("semnextstop", npos);
eSignNext = load_event(Entry, "signnext");
std::size_t limits{0};
Entry.get("limits", limits);
for (std::size_t index{0}; index < limits; ++index)
{
auto const key{std::format("l{}", index)};
auto const numbers{snapshot::text_numbers(Entry.text(key))};
auto const *source{load_event(Entry, key + "event")};
if (numbers.size() != 8 || source == nullptr)
continue;
auto &limit{m_pointlimits.emplace_back()};
limit.source = source;
limit.velocity = numbers[0];
limit.distance = numbers[1];
limit.celldistance = numbers[2];
limit.heading = {numbers[3], numbers[4], numbers[5]};
limit.end = numbers[6];
limit.endknown = numbers[7] != 0.0;
}
if (auto const position{snapshot::text_numbers(Entry.text("limitsposition"))}; position.size() == 4)
{
m_pointlimitsvehicle = snapshot::find_vehicle(Entry.text("limitsvehicle"));
m_pointlimitsposition = {position[0], position[1], position[2]};
m_pointlimitslength = position[3];
m_pointlimitsends[0] = snapshot::find_vehicle(Entry.text("limitsend0"));
m_pointlimitsends[1] = snapshot::find_vehicle(Entry.text("limitsend1"));
}
return true;
}
void TController::snapshot_load(simulation::snapshot::record const &Entry)
{
// the timetable: the scenery gave the train the one it started with, which another may have replaced since
if (auto const train{Entry.text("train", TrainParams.TrainName)}; train != TrainParams.TrainName)
{
TrainParams = TTrainParameters(train);
if (train != "none" && false == TrainParams.LoadTTfile(Global.asCurrentSceneryPath, 0, Entry.value("ttvmax", 0.0)))
ErrorLog(std::format("snapshot: timetable \"{}\" of {} can't be loaded", train, OwnerName()));
}
Entry.get("station", TrainParams.StationIndex);
Entry.get("stationstart", TrainParams.StationStart);
Entry.get("nextstation", TrainParams.NextStationName);
Entry.get("latency", TrainParams.LastStationLatency);
Entry.get("timetabledirection", TrainParams.Direction);
Entry.get("ttvmax", TrainParams.TTVmax);
m_stopflags = TrainParams.stop_flags();
if (auto const stopflags{split(Entry.text("stopflags"))}; stopflags.size() == 4)
{
using timetable::tristate;
m_stopflags.central_doors = static_cast<tristate>(stopflags[0]);
m_stopflags.doorstep = static_cast<tristate>(stopflags[1]);
m_stopflags.conductor = static_cast<tristate>(stopflags[2]);
m_stopflags.brake_test = static_cast<tristate>(stopflags[3]);
}
load_members(*this, Entry, snapshot_members::texts);
// the orders
if (Entry.has("orders"))
{
auto const orders{split(Entry.text("orders"))};
OrdersClear();
OrderTop = std::min(static_cast<int>(orders.size()), maxorders);
for (auto index{0}; index < OrderTop; ++index)
OrderList[index] = static_cast<TOrders>(orders[index]);
}
Entry.get("orderpos", OrderPos);
Entry.get("action", eAction);
Entry.get("stopreason", eStopReason);
load_members(*this, Entry, snapshot_members::numbers);
load_members(*this, Entry, snapshot_members::flags);
load_members(*this, Entry, snapshot_members::speeds);
load_members(*this, Entry, snapshot_members::distances);
load_members(*this, Entry, snapshot_members::timers);
load_members(*this, Entry, snapshot_members::levels);
Entry.get("exchangetime", ExchangeTime);
if (auto const numbers{snapshot::text_numbers(Entry.text("brakea0"))}; numbers.size() == std::size(fBrake_a0))
std::ranges::copy(numbers, fBrake_a0);
if (auto const numbers{snapshot::text_numbers(Entry.text("brakea1"))}; numbers.size() == std::size(fBrake_a1))
std::ranges::copy(numbers, fBrake_a1);
Entry.get("brakesystem", BrakeSystem);
Entry.get("doorclosure", DoorClosure);
Entry.get("lastannouncement", m_lastannouncement);
Entry.get("vellimitlastdist0", VelLimitLastDist.first);
Entry.get("vellimitlastdist1", VelLimitLastDist.second);
Entry.get("lighthint0", m_lighthints[end::front]);
Entry.get("lighthint1", m_lighthints[end::rear]);
iDirectionBackup.reset();
if (auto direction{0}; Entry.get("directionbackup", direction))
iDirectionBackup = direction;
iCouplingVehicle.reset();
if (auto *vehicle{snapshot::find_vehicle(Entry.text("couplingvehicle"))}; vehicle != nullptr)
iCouplingVehicle = std::make_pair(vehicle, Entry.value("couplingend", 0));
// the consist: its ends as they were, the vehicles driven and braked found anew among what's coupled now
if (auto *front{snapshot::find_vehicle(Entry.text("front"))}; front != nullptr)
pVehicles[end::front] = front;
if (auto *rear{snapshot::find_vehicle(Entry.text("rear"))}; rear != nullptr)
pVehicles[end::rear] = rear;
ControllingSet();
if (auto ai{AIControllFlag}; Entry.get("ai", ai))
{
AIControllFlag = ai;
pVehicle->Controller = ai;
}
// what's ahead on the track as the driver had it; without it the table is filled anew from where the train is now
if (false == snapshot_load_table(Entry))
TableClear();
eSignSkip = load_event(Entry, "signskip");
// the hints of what the driver is about to do are for the player, and made again as the driver goes on
m_hints.clear();
BrakeChargingPipeOverchargeStart.clear();
}
+81
View File
@@ -673,6 +673,75 @@ void apply_vehicles(document const &Document, apply_summary &Summary)
Summary.notes.emplace_back(std::format("{} vehicles of the scenery aren't in the snapshot, they stay as the scenery made them", unknown));
}
void capture_drivers(document &Document)
{
for (auto const *vehicle : Vehicles.sequence())
{
if (vehicle != nullptr && vehicle->bEnabled && vehicle->Mechanik != nullptr)
vehicle->Mechanik->snapshot_save(Document.add("driver", vehicle_reference(vehicle)));
}
}
// a driver of the consist of the vehicle whom the snapshot doesn't have where the scenery put them: the one to move
// to the vehicle, where the snapshot has a driver and the scenery none (a driver changes ends of a train)
TController *spare_driver(TDynamicObject *Vehicle, std::unordered_set<TDynamicObject const *> const &Taken)
{
TController *found{nullptr};
Vehicle->for_each(coupling::coupler, [&found, &Taken](TDynamicObject const *Coupled) {
if (found == nullptr && Coupled->Mechanik != nullptr && false == Taken.contains(Coupled))
found = Coupled->Mechanik;
});
return found;
}
void apply_drivers(document const &Document, apply_summary &Summary)
{
auto const entries{Document.of("driver")};
if (entries.empty())
return;
// the vehicles the snapshot has drivers in
std::unordered_set<TDynamicObject const *> taken;
for (auto const *entry : entries)
taken.emplace(find_vehicle(entry->name));
auto missing{0};
for (auto const *entry : entries)
{
auto *vehicle{find_vehicle(entry->name)};
if (vehicle == nullptr)
{
++Summary.skipped;
++missing;
continue;
}
if (vehicle->Mechanik == nullptr)
{
if (auto *driver{spare_driver(vehicle, taken)}; driver != nullptr)
driver->MoveTo(vehicle);
}
if (vehicle->Mechanik == nullptr)
{
++Summary.skipped;
++missing;
continue;
}
vehicle->Mechanik->snapshot_load(*entry);
++Summary.entries;
}
if (missing != 0)
Summary.notes.emplace_back(std::format("{} drivers of the snapshot have no driver in the scenery to become", missing));
// the drivers of the scenery the snapshot has no word of, in vehicles it does know, were gone when it was taken
std::unordered_set<TDynamicObject const *> known;
for (auto const *entry : Document.of("vehicle"))
known.emplace(find_vehicle(entry->name));
for (auto *vehicle : Vehicles.sequence())
{
if (vehicle == nullptr || vehicle->Mechanik == nullptr || taken.contains(vehicle) || false == known.contains(vehicle))
continue;
if (vehicle->Mechanik->AIControllFlag)
SafeDelete(vehicle->Mechanik);
}
}
// the driver in charge of each vehicle; after the drivers are where the snapshot has them
void apply_owners(document const &Document)
{
@@ -686,6 +755,15 @@ void apply_owners(document const &Document)
}
}
void capture_player(document &Document)
{
if (Train == nullptr || Train->Dynamic() == nullptr)
return;
auto const *vehicle{Train->Dynamic()};
// by its name, which is what the simulator is started in a vehicle with
Document.add("player", vehicle->name()).set("cab", vehicle->MoverParameters->CabOccupied);
}
// tells whether the snapshot was taken in the scenery it's being put over
void check_scenery(record const &Header, apply_summary &Summary)
{
@@ -799,6 +877,8 @@ document capture()
capture_launchers(result);
capture_lights(result);
capture_vehicles(result);
capture_drivers(result);
capture_player(result);
// the long one last, out of the way of whoever reads the file
capture_random(result);
return result;
@@ -837,6 +917,7 @@ apply_summary apply(document const &Document)
apply_each(Document, "madetrack", summary, apply_made_track);
apply_each(Document, "powersource", summary, apply_power);
apply_vehicles(Document, summary);
apply_drivers(Document, summary);
apply_owners(Document);
// the cells after the vehicles, whose sections write to their cells as they're taken and freed
apply_each(Document, "memcell", summary, apply_memcell);
+7
View File
@@ -281,7 +281,14 @@ public:
int light_hint( int const End ) const { return m_lighthints[ End ]; }
// the order the driver goes by now: a train run, shunting and the like
TOrders order_current() const { return OrderCurrentGet(); }
// the driver's part of a simulation snapshot (simulation/simulationsnapshotdriver.cpp): its orders, its place in the
// timetable and what it has made up its mind about, written to an entry of the snapshot and set from one
void snapshot_save( simulation::snapshot::record &Entry ) const;
void snapshot_load( simulation::snapshot::record const &Entry );
private:
void snapshot_save_table( simulation::snapshot::record &Entry ) const;
bool snapshot_load_table( simulation::snapshot::record const &Entry );
struct snapshot_members; // the variables the snapshot keeps one for one
// tells the black box of the train at the station of its timetable it makes for, at the stop point given
void record_station( TSpeedPos const &Point, std::uint8_t Kind ) const;
void Activation(); // umieszczenie obsady w odpowiednim członie