diff --git a/CMakeLists.txt b/CMakeLists.txt index 42587459b..12f27ab44 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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" diff --git a/simulation/simulationsnapshotdriver.cpp b/simulation/simulationsnapshotdriver.cpp new file mode 100644 index 000000000..f8461dcb5 --- /dev/null +++ b/simulation/simulationsnapshotdriver.cpp @@ -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 +#include +#include + +// 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 struct member { + std::string_view key; + Type_ TController::*variable; +}; + +template 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 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 const Orders) +{ + std::string text; + for (auto const order : Orders) + { + if (false == text.empty()) + text += ','; + text += std::to_string(static_cast(order)); + } + return text; +} + +std::vector split(std::string_view Text) +{ + std::vector 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(*number)); + Text.remove_prefix(comma == std::string_view::npos ? Text.size() : comma + 1); + } + return numbers; +} + +// an event under the keys "" (its name) and "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 "", 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(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(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{"accpreferred", &TController::AccPreferred}, + member{"accdesired", &TController::AccDesired}, + member{"veldesired", &TController::VelDesired}, + member{"accdesiredav", &TController::fAccDesiredAv}, + member{"accdesiredgravity", &TController::fAccDesiredGravity}, + member{"velfordriver", &TController::VelforDriver}, + member{"velsignal", &TController::VelSignal}, + member{"vellimit", &TController::VelLimit}, + member{"velsignallast", &TController::VelSignalLast}, + member{"velsignalnext", &TController::VelSignalNext}, + member{"vellimitlast", &TController::VelLimitLast}, + member{"velroad", &TController::VelRoad}, + member{"velnext", &TController::VelNext}, + member{"velrestricted", &TController::VelRestricted}, + member{"shuntvelocity", &TController::fShuntVelocity}, + member{"velmax", &TController::fVelMax}, + member{"velplus", &TController::fVelPlus}, + member{"velminus", &TController::fVelMinus}, + }; + static constexpr std::array distances{ + member{"firstsemaphordist", &TController::FirstSemaphorDist}, + member{"actualproximitydist", &TController::ActualProximityDist}, + member{"switchcleardist", &TController::SwitchClearDist}, + member{"signalareaenddist", &TController::SignalAreaEndDist}, + member{"minproximitydist", &TController::fMinProximityDist}, + member{"maxproximitydist", &TController::fMaxProximityDist}, + member{"laststopexpdist", &TController::fLastStopExpDist}, + member{"driverdist", &TController::fDriverDist}, + member{"brakedist", &TController::fBrakeDist}, + member{"movelen", &TController::dMoveLen}, + member{"length", &TController::fLength}, + member{"mass", &TController::fMass}, + }; + static constexpr std::array timers{ + member{"brakeheldtime", &TController::fBrakeHeldTime}, + member{"shortfall", &TController::fShortfall}, + member{"shortfalltime", &TController::fShortfallTime}, + member{"uphillstarttime", &TController::fUphillStartTime}, + member{"warningduration", &TController::fWarningDuration}, + member{"waitingtime", &TController::WaitingTime}, + member{"waitingexpiretime", &TController::WaitingExpireTime}, + member{"idletime", &TController::IdleTime}, + member{"stoptime", &TController::fStopTime}, + member{"reactiontime", &TController::ReactionTime}, + member{"lastreactiontime", &TController::LastReactionTime}, + member{"braketime", &TController::fBrakeTime}, + member{"actiontime", &TController::fActionTime}, + member{"radiocontroltime", &TController::m_radiocontroltime}, + member{"brakechargingcooldown", &TController::BrakeChargingCooldown}, + member{"brakechargingstart", &TController::BrakeChargingStart}, + member{"departblockedstart", &TController::DepartBlockedStart}, + member{"dbtvelocitybrake", &TController::DBT_VelocityBrake}, + member{"dbtvelocityrelease", &TController::DBT_VelocityRelease}, + member{"dbtvelocityfinish", &TController::DBT_VelocityFinish}, + member{"dbtbrakingtime", &TController::DBT_BrakingTime}, + member{"dbtreleasingtime", &TController::DBT_ReleasingTime}, + member{"dbtmidpointacc", &TController::DBT_MidPointAcc}, + member{"lastupdatedtime", &TController::LastUpdatedTime}, + member{"elapsedtime", &TController::ElapsedTime}, + }; + static constexpr std::array levels{ + member{"brakectrlposition", &TController::BrakeCtrlPosition}, + member{"overhead1", &TController::fOverhead1}, + member{"overhead2", &TController::fOverhead2}, + member{"voltage", &TController::fVoltage}, + member{"driverbraking", &TController::fDriverBraking}, + member{"brakereaction", &TController::fBrakeReaction}, + member{"nominalaccthreshold", &TController::fNominalAccThreshold}, + member{"accthreshold", &TController::fAccThreshold}, + member{"absaccs", &TController::AbsAccS}, + member{"brakinginitiallevel", &TController::BrakingInitialLevel}, + member{"brakinglevelincrease", &TController::BrakingLevelIncrease}, + member{"accgravity", &TController::fAccGravity}, + member{"ready", &TController::fReady}, + member{"consistshade", &TController::ConsistShade}, + member{"medamax", &TController::fMedAmax}, + }; + static constexpr std::array numbers{ + member{"flags", &TController::iDrivigFlags}, + member{"direction", &TController::iDirection}, + member{"directionorder", &TController::iDirectionOrder}, + member{"vehiclecount", &TController::iVehicleCount}, + member{"coupler", &TController::iCoupler}, + member{"failcount", &TController::iDriverFailCount}, + member{"overheadzero", &TController::iOverheadZero}, + member{"overheaddown", &TController::iOverheadDown}, + member{"universalbrakebuttons", &TController::UniversalBrakeButtons}, + member{"dizelpercentage", &TController::DizelPercentage}, + member{"dizelpercentagespeed", &TController::DizelPercentage_Speed}, + member{"helperstate", &TController::HelperState}, + member{"shortfallgrowth", &TController::iShortfallGrowth}, + member{"dynamicbraketest", &TController::DynamicBrakeTest}, + member{"staticbraketest", &TController::StaticBrakeTest}, + member{"radiochannel", &TController::iRadioChannel}, + member{"guardradio", &TController::iGuardRadio}, + member{"vehicles", &TController::iVehicles}, + member{"engines", &TController::ControlledEnginesCount}, + member{"lastexchangeplatforms", &TController::m_lastexchangeplatforms}, + member{"lastexchangedirection", &TController::m_lastexchangedirection}, + }; + static constexpr std::array flags{ + member{"stoptargetispassengerstop", &TController::bStopTargetIsPassengerStop}, + member{"uphillstart", &TController::bUphillStart}, + member{"needtryagain", &TController::Need_TryAgain}, + member{"heatingtemperatureok", &TController::IsHeatingTemperatureOK}, + member{"heatingtemperaturetoolow", &TController::IsHeatingTemperatureTooLow}, + member{"atpassengerstop", &TController::IsAtPassengerStop}, + member{"scheduledstopvisible", &TController::IsScheduledPassengerStopVisible}, + member{"forcepnbrake", &TController::ForcePNBrake}, + member{"brakereinspection", &TController::BrakeReinspectionPending}, + member{"engineactive", &TController::iEngineActive}, + member{"passengertrain", &TController::IsPassengerTrain}, + member{"cargotrain", &TController::IsCargoTrain}, + member{"heavycargotrain", &TController::IsHeavyCargoTrain}, + member{"isready", &TController::Ready}, + member{"consistbraked", &TController::IsConsistBraked}, + member{"nextstopannouncement", &TController::m_makenextstopannouncement}, + member{"doorneedsopening", &TController::DoesAnyDoorNeedOpening}, + }; + static constexpr std::array texts{ + member{"nextstop", &TController::asNextStop}, + member{"lastexchangestop", &TController::m_lastexchangestop}, + member{"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::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(m_stopflags.central_doors), static_cast(m_stopflags.doorstep), + static_cast(m_stopflags.conductor), static_cast(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 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(stopflags[0]); + m_stopflags.doorstep = static_cast(stopflags[1]); + m_stopflags.conductor = static_cast(stopflags[2]); + m_stopflags.brake_test = static_cast(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(orders.size()), maxorders); + for (auto index{0}; index < OrderTop; ++index) + OrderList[index] = static_cast(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(); +} diff --git a/simulation/simulationsnapshotworld.cpp b/simulation/simulationsnapshotworld.cpp index b5b50e266..7379bb899 100644 --- a/simulation/simulationsnapshotworld.cpp +++ b/simulation/simulationsnapshotworld.cpp @@ -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 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 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 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); diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 2ed51b6a1..8aabf06e1 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -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