diff --git a/CMakeLists.txt b/CMakeLists.txt index 90b42cf1f..fc9869111 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -289,6 +289,9 @@ set(SOURCES "application/application.cpp" "simulation/simulationtime.cpp" "simulation/simulationtest.cpp" +"simulation/simulationsnapshotworld.cpp" +"simulation/simulationsnapshotvehicle.cpp" +"simulation/simulationsnapshotdriver.cpp" "scene/sceneeditor.cpp" "rendering/screenshot.cpp" "input/driverkeyboardinput.cpp" @@ -821,6 +824,7 @@ set(CORE_SOURCES "physics/components/fizsections.cpp" "physics/components/pneumatics.cpp" "physics/components/securitysystem.cpp" +"physics/components/snapshot.cpp" "physics/components/setup.cpp" "physics/components/traction.cpp" "physics/couplerphysics.cpp" @@ -845,6 +849,8 @@ set(CORE_SOURCES "scripting/scriptscreenkernels.cpp" "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" +"simulation/simulationsnapshot.cpp" +"simulation/simulationsnapshotmover.cpp" "vehicle/aipower.cpp" "vehicle/aiwire.cpp" "vehicle/blackbox.cpp" diff --git a/application/application.cpp b/application/application.cpp index 22293bb3c..36133c53c 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -37,6 +37,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/dictionary.h" #include "version_info.h" #include "simulation/simulationtest.h" +#include "simulation/simulationsnapshotworld.h" #include "utilities/physicslog.h" #include #include @@ -1403,7 +1404,8 @@ int eu07_application::init_settings(int Argc, char *Argv[]) // a test run is known before the rest of the command line is read (Global.test.enabled, see init()), so a // command line it can't take ends with the error code of the test, not with 0, which would pass it - auto const testcommandline{simulation::parse_test_command_line(std::vector(Argv, Argv + Argc))}; + std::vector const arguments(Argv, Argv + Argc); + auto const testcommandline{simulation::parse_test_command_line(arguments)}; if (false == testcommandline.error.empty()) { simulation::test().conclude(simulation::test_result::error, testcommandline.error); @@ -1420,6 +1422,15 @@ int eu07_application::init_settings(int Argc, char *Argv[]) Global.test.wall_timeout_from_command_line = true; } + // the simulation snapshots to load and to take (--load-snapshot, --snapshot-at) + auto const snapshotcommandline{simulation::snapshot::parse_command_line(arguments)}; + if (false == snapshotcommandline.error.empty()) + { + std::cerr << snapshotcommandline.error << std::endl; + simulation::test().conclude(simulation::test_result::error, snapshotcommandline.error); + return -1; + } + fs::path iniPath = user_config_path("eu07.ini"); // a test reads the settings of the game folder only (and those given with -ini), not the player's own @@ -1440,6 +1451,8 @@ int eu07_application::init_settings(int Argc, char *Argv[]) // process command line arguments bool sceneryfromcommandline{false}; bool editwithoutscenery{false}; + bool seedfromcommandline{false}; + bool vehiclefromcommandline{false}; for (int i = 1; i < Argc; ++i) { @@ -1458,6 +1471,7 @@ int eu07_application::init_settings(int Argc, char *Argv[]) if (i + 1 < Argc) { Global.local_start_vehicle = ToLower(Argv[++i]); + vehiclefromcommandline = true; } } else if (token == "-edit") @@ -1484,6 +1498,7 @@ int eu07_application::init_settings(int Argc, char *Argv[]) { Global.random_seed = *seed; Global.random_seed_given = true; + seedfromcommandline = true; WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); } } @@ -1498,6 +1513,11 @@ int eu07_application::init_settings(int Argc, char *Argv[]) // taken from the command line above, with its value ++i; } + else if (token == "--load-snapshot" || token == "--snapshot-at" || token == "--load-snapshot-force") + { + // taken from the command line above, with their values + i += simulation::snapshot::option_value_count(token); + } else if (token == "-ini") { // extra settings file read on top of eu07.ini, so a run can override a few keys @@ -1515,7 +1535,8 @@ int eu07_application::init_settings(int Argc, char *Argv[]) << " [-edit [sceneryfilepath]]" << " [-seed number|word]" << " [-ini settingsfile]" - << " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" << std::endl; + << " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" + << " [--load-snapshot file [--load-snapshot-force]] [--snapshot-at seconds file]" << std::endl; simulation::test().conclude(simulation::test_result::error, std::format("unknown command line argument {}", token)); return -1; } @@ -1523,6 +1544,18 @@ int eu07_application::init_settings(int Argc, char *Argv[]) if (editwithoutscenery && false == sceneryfromcommandline) Global.SceneryFile.clear(); + simulation::snapshot::request(snapshotcommandline); + // the scenery of a snapshot loads the way it did when the snapshot was taken only with the seed it had then + if (auto const seed{simulation::snapshot::requested_seed()}; seed.has_value() && false == seedfromcommandline) + { + Global.random_seed = *seed; + Global.random_seed_given = true; + WriteLog(std::format("seed taken from the snapshot to load: {}", Global.random_seed)); + } + // and the player goes on in the vehicle they were in + if (auto const vehicle{simulation::snapshot::requested_player_vehicle()}; false == vehicle.empty() && false == vehiclefromcommandline) + Global.local_start_vehicle = vehicle; + if (Global.test.enabled) { if (false == sceneryfromcommandline || Global.SceneryFile.empty()) diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 79186a4cd..8853a5e15 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" #include "simulation/simulationtest.h" +#include "simulation/simulationsnapshotworld.h" #include "simulation/blackboxrecorder.h" #include "scene/scene.h" #include "rendering/lightarray.h" @@ -365,6 +366,8 @@ bool driver_mode::update() { simulation::test().update(deltatime); } + // the frame is complete: the snapshots asked for at this time are taken (--snapshot-at) + simulation::snapshot::update(); } // render time routines follow: @@ -560,6 +563,9 @@ void driver_mode::enter() Timer::ResetTimers(); + // the scenery is loaded and nothing runs yet: the state saved in a snapshot goes over it (--load-snapshot) + simulation::snapshot::start(); + if (Global.test.enabled) { // the test runs as fast as it can compute, in steps of fixed length, so that runs on different machines agree diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index bfe1a4716..5a4a30669 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -78,7 +78,7 @@ void gl::glsl_common_setup() "#define ENVMAP_GGX_LEVELS " + std::to_string(ENVMAP_GGX_LEVELS) + "\n" + "#define ENVMAP_GGX_ROUGHNESS_MIN " + std::to_string(ENVMAP_GGX_ROUGHNESS_MIN) + "\n" + "#define ENVMAP_GGX_GROUP_SIZE " + std::to_string(ENVMAP_GGX_GROUP_SIZE) + "\n" + - "#define SKY_SSBO_BINDING " + std::to_string(SKY_SSBO_BINDING) + "\n" + + "#define SKY_UBO_BINDING " + std::to_string(SKY_UBO_BINDING) + "\n" + "#define EXPOSURE_SSBO_BINDING " + std::to_string(EXPOSURE_SSBO_BINDING) + "\n" + "#define EXPOSURE_HISTOGRAM_BINS " + std::to_string(EXPOSURE_HISTOGRAM_BINS) + "\n" + "#define EXPOSURE_HISTOGRAM_GROUP_SIZE " + std::to_string(EXPOSURE_HISTOGRAM_GROUP_SIZE) + "\n" + @@ -115,6 +115,7 @@ void gl::glsl_common_setup() "#define CAB_PROBE_MASK_TEX " + std::to_string(CAB_PROBE_MASK_TEX) + "\n" + "#define SKY_OCCLUSION_HEIGHT_TEX " + std::to_string(SKY_OCCLUSION_HEIGHT_TEX) + "\n" + "#define SKY_OCCLUSION_TEX " + std::to_string(SKY_OCCLUSION_TEX) + "\n" + + "#define CAB_PROBE_UBO_BINDING " + std::to_string(CAB_PROBE_UBO_BINDING) + "\n" + "#define CAB_PROBE_SSBO_BINDING " + std::to_string(CAB_PROBE_SSBO_BINDING) + "\n" + "#define CAB_PROBE_SH_SIZE " + std::to_string(CAB_PROBE_SH_SIZE) + "\n" + "#define CAB_PROBE_SH_GROUP_SIZE " + std::to_string(CAB_PROBE_SH_GROUP_SIZE) + "\n" + diff --git a/gl/ssbo.cpp b/gl/ssbo.cpp index 387fddc69..9b9d8b419 100644 --- a/gl/ssbo.cpp +++ b/gl/ssbo.cpp @@ -24,6 +24,11 @@ void gl::ssbo::bind_base() const glBindBuffersBase(GL_SHADER_STORAGE_BUFFER, m_index, 1, *this); } +void gl::ssbo::bind_uniform(GLuint const Index) const +{ + glBindBuffersBase(GL_UNIFORM_BUFFER, Index, 1, *this); +} + void gl::ssbo::resize(GLsizeiptr size) { if (size == m_size) diff --git a/gl/ssbo.h b/gl/ssbo.h index f8e5f9645..14857634f 100644 --- a/gl/ssbo.h +++ b/gl/ssbo.h @@ -19,6 +19,9 @@ namespace gl ~ssbo(); void bind_base() const; + // the same buffer as the uniform block of Index, for data a compute pass writes and the shading reads uniformly + // (std140 and std430 lay it out alike, e.g. vec4 arrays). glBindBuffersBase, like bind_base() + void bind_uniform(GLuint Index) const; void resize(GLsizeiptr size); GLsizeiptr size() const { diff --git a/gl/ubo.h b/gl/ubo.h index 6ee7d5d9a..b37d20474 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -357,7 +357,7 @@ namespace gl // 1 if the shading takes the lights of a fragment from the list of its cluster (lights_count is not used then), 0 if not. // set per pass: the cluster grid exists only for the color pass of a perspective view uint32_t lights_clustered; - // scale of the directional part of the sky ambient light (sky_ssbo): the factor the ambient light of the object + // scale of the directional part of the sky ambient light (sky_ubo): the factor the ambient light of the object // is scaled with (tunnels), 0 where the ambient light is not the sky's (model previews) float sky_ambient_factor; // 1 if the shading reads rough reflections from the prefiltered environment map, 0 if from the mipmaps of the plain one @@ -466,10 +466,13 @@ namespace gl static_assert(offsetof(cluster_counters, index_count) == 0, "bad layout of cluster_counters"); static_assert(offsetof(cluster_counters, overflow_count) == 4, "bad layout of cluster_counters"); - // binding points of the sky, exposure and atmosphere buffers: layout(binding = ...) in glsl_common - const GLuint SKY_SSBO_BINDING = 5; + // binding points of the sky, exposure and atmosphere buffers: layout(binding = ...) in glsl_common. the sky is a uniform + // block: 9 vec4 every fragment reads the same of, which keeps a storage buffer point free (see MAX_SSBO_BINDINGS). the + // result of the atmosphere is written by one compute pass only, which binds it right before its dispatch, so it shares + // a point with the other compute passes + const GLuint SKY_UBO_BINDING = 3; const GLuint EXPOSURE_SSBO_BINDING = 6; - const GLuint ATMOSPHERE_RESULT_SSBO_BINDING = 7; + const GLuint ATMOSPHERE_RESULT_SSBO_BINDING = 9; const GLuint ATMOSPHERE_UBO_BINDING = 4; // binding point of the per-instance modelview matrices of instanced draws (glsl: instance_ssbo, mat4 per instance). @@ -479,7 +482,7 @@ namespace gl // number of coefficients of the spherical harmonics of order 2 (bands 0..2) const size_t SKY_SH_COEFFICIENTS = 9; - // layout std430: directional part of the sky ambient light (GLSL: sky_ssbo). the coefficients of the real spherical + // layout std140 and std430 alike: directional part of the sky ambient light (GLSL: sky_ubo). the coefficients of the real spherical // harmonics of the light a surface facing a world space direction gets, in units of light_data.ambient, without the // constant band (that one is light_data.ambient itself); rgb used, w is padding struct sky_data @@ -487,15 +490,18 @@ namespace gl glm::vec4 ambient_sh[SKY_SH_COEFFICIENTS]; }; - // layout std430: the light of the lamps the occupied cab reflects, which lights the cab again (GLSL: cab_probe_ssbo, written by - // cabprobe_sh.comp from the probe of the cab): the coefficients of the real spherical harmonics of the light a surface facing a + // layout std140 and std430 alike: the light of the lamps the occupied cab reflects, which lights the cab again (GLSL: + // cab_probe_ubo, written by cabprobe_sh.comp from the probe of the cab as cab_probe_result_ssbo): the coefficients of the real spherical harmonics of the light a surface facing a // direction of the space of the probe gets, bands 0..2, in units of light_data.ambient; rgb used, w is padding struct cab_probe_data { glm::vec4 bounce_sh[SKY_SH_COEFFICIENTS]; }; - // binding point of the opengl renderer, bound with the colour passes - const GLuint CAB_PROBE_SSBO_BINDING = 17; + // binding points of the opengl renderer: the shading reads the buffer as a uniform block, bound with the colour passes; + // cabprobe_sh.comp writes it as a storage buffer, bound right before its dispatch, so it shares that point with the other + // compute passes + const GLuint CAB_PROBE_UBO_BINDING = 7; + const GLuint CAB_PROBE_SSBO_BINDING = 9; // the face of the level of the probe the spherical harmonics are taken from, at most, and the work group of cabprobe_sh.comp const size_t CAB_PROBE_SH_SIZE = 16; // the face of the level of the probe CAB_PROBE_MASK_TEX is a copy of, at most @@ -743,10 +749,10 @@ namespace gl // the binding points of the opengl renderer: the storage of the water (read by the glasses, written by the passes), the block // of the step of the simulation (water_ubs) and the texture unit of the mask of the wipers the map is baked from. the storage // point is used by nothing else, bound with the colour passes - const GLuint WATER_SSBO_BINDING = 16; + const GLuint WATER_SSBO_BINDING = 5; // the drops and the rivulets of the cells of the glasses with rain (mat_rain_windscreen, rain_cells.comp, rain_cells.glsl): worked // out once a frame for every cell, so a glass only reads them. RAIN_CELLS_COUNT uvec4, as rain_cells.glsl lays them out - const GLuint RAIN_CELLS_SSBO_BINDING = 18; + const GLuint RAIN_CELLS_SSBO_BINDING = 7; const size_t RAIN_DROP_CELLS = 512; const size_t RAIN_RIV_CELLS = 128; const size_t RAIN_RIV_LAYERS = 5; @@ -927,5 +933,20 @@ namespace gl static_assert(offsetof(shadow_fit_data, bounds) == 48, "bad layout of shadow_fit_data"); static_assert(sizeof(shadow_fit_data) == 48 + 32 * MAX_CASCADES, "bad size of shadow_fit_data"); + // the storage buffer binding points the renderer may use: GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS of the drivers of integrated + // Intel graphics, which is 16. a shader with a point past it doesn't compile there, and the material falls back to pink. what + // the shading reads uniformly and is small goes into a uniform block instead (sky_ubo, cab_probe_ubo); a point a compute pass + // binds right before its dispatch is shared by such passes + const GLuint MAX_SSBO_BINDINGS = 16; + static_assert(std::max({LIGHT_SSBO_BINDING, CLUSTER_AABB_SSBO_BINDING, CLUSTER_RANGE_SSBO_BINDING, CLUSTER_INDEX_SSBO_BINDING, + CLUSTER_COUNTER_SSBO_BINDING, EXPOSURE_SSBO_BINDING, ATMOSPHERE_RESULT_SSBO_BINDING, INSTANCE_SSBO_BINDING, + CAB_PROBE_SSBO_BINDING, WEATHER_SCRATCH_SSBO_BINDING, INSTANCE_RECORD_SSBO_BINDING, INSTANCE_JOB_SSBO_BINDING, + INSTANCE_GROUP_SSBO_BINDING, INSTANCE_LOD_SSBO_BINDING, INSTANCE_COUNTER_SSBO_BINDING, INSTANCE_OUTPUT_SSBO_BINDING, + INSTANCE_COMMAND_SSBO_BINDING, MODEL_DRAW_SSBO_BINDING, SHADOW_FIT_SSBO_BINDING, PARTICLE_SSBO_BINDING, + PARTICLE_SOURCE_SSBO_BINDING, PARTICLE_OWNER_SSBO_BINDING, PARTICLE_OUTPUT_SSBO_BINDING, PARTICLE_COMMAND_SSBO_BINDING, + TIMBER_LOCAL_SSBO_BINDING, TIMBER_RANGE_SSBO_BINDING, TIMBER_OUTPUT_SSBO_BINDING, TIMBER_ORIGIN_SSBO_BINDING, + WATER_SSBO_BINDING, RAIN_CELLS_SSBO_BINDING}) < MAX_SSBO_BINDINGS, + "a storage buffer binding point past what integrated Intel graphics offer"); + #pragma pack(pop) } diff --git a/input/command.cpp b/input/command.cpp index 5e52edf30..8b52d8ad6 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -461,6 +461,7 @@ commanddescription_sequence Commands_descriptions = { {"gensetdisable", command_target::vehicle, command_mode::oneoff}, // the flashlight is the player's own: an entity command, which stays on the machine it was given on (command_queue::is_network_target()) {"flashlighttoggle", command_target::entity, command_mode::oneoff}, + {"snapshotsave", command_target::simulation, command_mode::oneoff}, }; // Maps of command and coresponding strings @@ -900,6 +901,7 @@ std::unordered_map const commandMap = { {"gensetenable", user_command::gensetenable}, {"gensetdisable", user_command::gensetdisable}, {"flashlighttoggle", user_command::flashlighttoggle}, + {"snapshotsave", user_command::snapshotsave}, {"none", user_command::none}}; } // namespace simulation diff --git a/input/command.h b/input/command.h index f8460fdd4..daa46d908 100644 --- a/input/command.h +++ b/input/command.h @@ -462,6 +462,7 @@ enum class user_command // the flashlight of the player (Global.flashlight), at the end so the numbers of the commands before it stay as they were. // an entity command, taken by the camera of the player (TCamera::OnCommand()): it isn't sent to the other machines of a network game flashlighttoggle, + snapshotsave, // writes a snapshot of the simulation to the snapshots folder (simulation/simulationsnapshotworld.h) none = -1 }; diff --git a/input/driverkeyboardinput.cpp b/input/driverkeyboardinput.cpp index 6119adf30..5aa8635d7 100644 --- a/input/driverkeyboardinput.cpp +++ b/input/driverkeyboardinput.cpp @@ -338,7 +338,8 @@ driverkeyboard_input::default_bindings() { { vehiclemovebackwards, {GLFW_KEY_RIGHT_BRACKET | keymodifier::control, "Move the train backwards (Debug Mode only)"} }, { vehicleboost, {GLFW_KEY_TAB | keymodifier::control, "Boost the train (Debug Mode only)"} }, { debugtoggle, {GLFW_KEY_F12 | keymodifier::control | keymodifier::shift, "Toggle Debug Mode"} }, - { pausetoggle, {GLFW_KEY_ESCAPE, "Pause the game"} } + { pausetoggle, {GLFW_KEY_ESCAPE, "Pause the game"} }, + { snapshotsave, {GLFW_KEY_F9 | keymodifier::control | keymodifier::shift, "Save a snapshot of the simulation"} } }; } diff --git a/physics/brakes.cpp b/physics/brakes.cpp index 7cd66b1d5..7a33c01b4 100644 --- a/physics/brakes.cpp +++ b/physics/brakes.cpp @@ -479,6 +479,229 @@ double TBrake::GetCRP() return GetBRP(); } +/// +/// The reservoirs every valve has. The kinds of valve with more reservoirs add theirs after these. +/// +std::vector TBrake::reservoirs() const +{ + return {BrakeCyl.get(), BrakeRes.get(), ValveRes.get()}; +} + +/// +/// What every valve keeps: whether the double check valve is over to the auxiliary brake, the anti-slip pressure. +/// +std::vector TBrake::latches() const +{ + return {DCV ? 1.0 : 0.0, ASBP}; +} + +void TBrake::latches(std::vector const &State) +{ + if (State.size() < 2) + return; + DCV = State[0] != 0.0; + ASBP = State[1]; +} + +std::vector TWest::latches() const +{ + auto state{TBrake::latches()}; + state.emplace_back(LBP); + state.emplace_back(dVP); + state.emplace_back(EPS); + state.emplace_back(LoadC); + return state; +} + +void TWest::latches(std::vector const &State) +{ + auto const first{TBrake::latches().size()}; + if (State.size() < first + 4) + return; + TBrake::latches(State); + LBP = State[first + 0]; + dVP = State[first + 1]; + EPS = State[first + 2]; + LoadC = State[first + 3]; +} + +std::vector TESt3AL2::latches() const +{ + auto state{TESt3::latches()}; + state.emplace_back(LoadC); + return state; +} + +void TESt3AL2::latches(std::vector const &State) +{ + auto const first{TESt3::latches().size()}; + if (State.size() < first + 1) + return; + TESt3::latches(State); + LoadC = State[first + 0]; +} + +std::vector TESt4R::latches() const +{ + auto state{TESt::latches()}; + state.emplace_back(RapidStatus ? 1.0 : 0.0); + state.emplace_back(RapidTemp); + return state; +} + +void TESt4R::latches(std::vector const &State) +{ + auto const first{TESt::latches().size()}; + if (State.size() < first + 2) + return; + TESt::latches(State); + RapidStatus = State[first + 0] != 0.0; + RapidTemp = State[first + 1]; +} + +std::vector TLSt::latches() const +{ + auto state{TESt4R::latches()}; + state.emplace_back(LBP); + state.emplace_back(EDFlag); + return state; +} + +void TLSt::latches(std::vector const &State) +{ + auto const first{TESt4R::latches().size()}; + if (State.size() < first + 2) + return; + TESt4R::latches(State); + LBP = State[first + 0]; + EDFlag = State[first + 1]; +} + +std::vector TEStED::latches() const +{ + auto state{TLSt::latches()}; + state.emplace_back(Zamykajacy ? 1.0 : 0.0); + state.emplace_back(Przys_blok ? 1.0 : 0.0); + state.emplace_back(LoadC); + return state; +} + +void TEStED::latches(std::vector const &State) +{ + auto const first{TLSt::latches().size()}; + if (State.size() < first + 3) + return; + TLSt::latches(State); + Zamykajacy = State[first + 0] != 0.0; + Przys_blok = State[first + 1] != 0.0; + LoadC = State[first + 2]; +} + +std::vector TEStEP2::latches() const +{ + auto state{TLSt::latches()}; + state.emplace_back(LoadC); + state.emplace_back(EPS); + return state; +} + +void TEStEP2::latches(std::vector const &State) +{ + auto const first{TLSt::latches().size()}; + if (State.size() < first + 2) + return; + TLSt::latches(State); + LoadC = State[first + 0]; + EPS = State[first + 1]; +} + +std::vector TCV1L_TR::latches() const +{ + auto state{TCV1::latches()}; + state.emplace_back(LBP); + return state; +} + +void TCV1L_TR::latches(std::vector const &State) +{ + auto const first{TCV1::latches().size()}; + if (State.size() < first + 1) + return; + TCV1::latches(State); + LBP = State[first + 0]; +} + +std::vector TKE::latches() const +{ + auto state{TBrake::latches()}; + state.emplace_back(RapidStatus ? 1.0 : 0.0); + state.emplace_back(LoadC); + state.emplace_back(LBP); + return state; +} + +void TKE::latches(std::vector const &State) +{ + auto const first{TBrake::latches().size()}; + if (State.size() < first + 3) + return; + TBrake::latches(State); + RapidStatus = State[first + 0] != 0.0; + LoadC = State[first + 1]; + LBP = State[first + 2]; +} + +std::vector TESt::reservoirs() const +{ + auto list{TBrake::reservoirs()}; + list.emplace_back(CntrlRes.get()); + return list; +} + +std::vector TESt3AL2::reservoirs() const +{ + auto list{TESt::reservoirs()}; + list.emplace_back(ImplsRes.get()); + return list; +} + +std::vector TESt4R::reservoirs() const +{ + auto list{TESt::reservoirs()}; + list.emplace_back(ImplsRes.get()); + return list; +} + +std::vector TEStED::reservoirs() const +{ + auto list{TLSt::reservoirs()}; + list.emplace_back(Miedzypoj.get()); + return list; +} + +std::vector TCV1::reservoirs() const +{ + auto list{TBrake::reservoirs()}; + list.emplace_back(CntrlRes.get()); + return list; +} + +std::vector TCV1L_TR::reservoirs() const +{ + auto list{TCV1::reservoirs()}; + list.emplace_back(ImplsRes.get()); + return list; +} + +std::vector TKE::reservoirs() const +{ + auto list{TBrake::reservoirs()}; + list.emplace_back(CntrlRes.get()); + list.emplace_back(ImplsRes.get()); + list.emplace_back(Brak2Res.get()); + return list; +} + /// /// Default per-step distributor advance — commits any pending flows on the /// reservoirs and reports zero brake-pipe exchange. Concrete distributors override. @@ -2941,6 +3164,79 @@ double TDriverHandle::GetCP() return 0; } +/// A valve with no pressures of its own. +std::vector TDriverHandle::pressures() +{ + return {}; +} + +std::vector TFV4a::pressures() +{ + return {&CP, &TP, &RP}; +} + +std::vector TFV4aM::pressures() +{ + return {&CP, &TP, &RP, &XP, &RedAdj}; +} + +std::vector TMHZ_EN57::pressures() +{ + return {&CP, &TP, &RP, &RedAdj, &UnbrakeOverPressure}; +} + +std::vector TMHZ_K5P::pressures() +{ + return {&CP, &TP, &RedAdj, &UnbrakeOverPressure}; +} + +std::vector TMHZ_6P::pressures() +{ + return {&CP, &TP, &RedAdj, &UnbrakeOverPressure}; +} + +std::vector TM394::pressures() +{ + return {&CP, &RedAdj}; +} + +std::vector TH14K1::pressures() +{ + return {&CP, &RedAdj}; +} + +std::vector TSt113::pressures() +{ + auto list{TH14K1::pressures()}; // the control chamber and the reductor are inherited + list.emplace_back(&EPS); + return list; +} + +std::vector Ttest::pressures() +{ + return {&CP}; +} + +std::vector TFD1::pressures() +{ + return {&BP}; +} + +std::vector TH1405::pressures() +{ + return {&BP}; +} + +std::vector TFVel6::pressures() +{ + return {&CP, &EPS}; +} + +std::vector TFVE408::pressures() +{ + return {&CP, &EPS}; +} + /// Default EP intensity — 0. double TDriverHandle::GetEP() { diff --git a/physics/brakes.h b/physics/brakes.h index 4fb4b7f9f..f719d3216 100644 --- a/physics/brakes.h +++ b/physics/brakes.h @@ -35,6 +35,9 @@ Knorr/West EP - żeby był #include "physics/friction.h" // Pascal unit +#include +#include + /// Number of positions of the local (auxiliary/manual) brake handle. static int const LocalBrakePosNo = 10; /*ilosc nastaw hamulca recznego lub pomocniczego*/ /// Maximum number of positions of the main (train) brake handle. @@ -251,6 +254,16 @@ class TReservoir void CreatePress(double Press); /// Returns reservoir capacity in liters. double GetCap() const { return Cap; } + /// Returns the air volume contained; with the capacity it gives the pressure. + double GetVol() const { return Vol; } + /// Returns the flow accumulated since the last , which isn't in the volume yet. + double GetPendingFlow() const { return dVol; } + /// Sets the air volume contained and the flow still to be applied to it, for a restored state. + void SetVol(double const Volume, double const Pendingflow = 0.0) + { + Vol = Volume; + dVol = Pendingflow; + } /// /// Returns absolute (atmospheric) pressure inside the reservoir. /// @@ -438,6 +451,18 @@ class TBrake double GetVRP() const; // cisnienie komory wstepnej rozdzielacza /// Returns control reservoir (ZS) pressure [bar]; defaults to the auxiliary reservoir for valves without a dedicated ZS. virtual double GetCRP(); // cisnienie zbiornika sterujacego + /// + /// The reservoirs of the valve: brake cylinder, auxiliary reservoir, pre-chamber, then the ones the kind of valve adds, + /// always in the same order for a kind. For a snapshot of the simulation, which keeps the air in them. + /// + virtual std::vector reservoirs() const; + /// + /// What the valve keeps from one step to the next beside the air in its reservoirs: the latches of its inner valves, the + /// step of its rapid relay, the pressures it was last told. Always in the same order for a kind of valve. For a snapshot of + /// the simulation, which puts them back with the other overload; a list too short for the kind of valve is left alone. + /// + virtual std::vector latches() const; + virtual void latches(std::vector const &State); /// Share of the full cylinder pressure the distributor settles at for the given share /// of the full service pipe drop. Used only to predict the brake force; the default is proportional. /// Share of the full service brake pipe drop. @@ -559,6 +584,9 @@ class TWest : public TBrake double LoadC = 0.0; // wspolczynnik przystawki wazacej public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises pressures: PP into ValveRes, BP into BrakeCyl, average of PP/HPP into BrakeRes. /// Brake pipe pressure. /// High pressure. @@ -604,6 +632,7 @@ class TESt : public TBrake public: /// Initialises the ESt distributor; sizes the control reservoir (15 l) and computes BVM. void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for the ESt baseline. /// Net flow exchanged with the brake pipe. double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG @@ -696,8 +725,12 @@ class TESt3AL2 : public TESt3 double LoadC = 0.0; public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the impulse chamber on top of the ESt initialisation. void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for ESt3/AL2 with load-weighing relay. double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Recomputes LoadC for the current vehicle mass. @@ -731,8 +764,12 @@ class TESt4R : public TESt double RapidTemp = 0.0; // aktualne, zmienne przelozenie public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the ESt4R; sizes the impulse chamber and selects the R delay. void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for ESt4R (rapid step active above velocity threshold). double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG @@ -761,6 +798,9 @@ class TLSt : public TESt4R double EDFlag = 0.0; // luzowanie hamulca z powodu zalaczonego ED public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the LSt; resizes the valve and impulse reservoirs and presets pressures. void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// Sets the auxiliary brake target pressure for the DCV. @@ -815,8 +855,12 @@ class TEStED : public TLSt double LoadC = 0.0; public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the EStED — sets up Miedzypoj, ImplsRes and the nozzle characteristics. void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for EStED (full EP09 logic with intermediate reservoir). double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Returns ED-brake reference pressure (ImplsRes pressure scaled by load coefficient). @@ -864,6 +908,9 @@ class TEStEP2 : public TLSt void UpdateStatusEP2(double BCP, double VVP, double CVP); public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the EP2-equipped distributor (impulse chamber, P delay). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; // inicjalizacja /// One-step distributor advance with EP2 EP brake logic. @@ -919,6 +966,7 @@ class TCV1 : public TBrake public: /// Initialises the CV1 distributor (sizes ZS, sets pressures, computes BVM). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for the CV1 baseline. double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Returns the control reservoir (ZS) pressure. @@ -972,8 +1020,12 @@ class TCV1L_TR : public TCV1 double LBP = 0.0; // cisnienie hamulca pomocniczego public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the CV1-L-TR (sizes the impulse chamber on top of CV1::Init). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for CV1-L-TR (impulse chamber + DCV). double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Sets the auxiliary brake target pressure for the DCV. @@ -1025,8 +1077,12 @@ class TKE : public TBrake void CheckStateHeld(double BCP, double VVP, double CVP); public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the KE distributor (control / impulse / auxiliary reservoirs and BVM). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// Sets the rapid step ratio (RM = 1 - RMR). void SetRM(double const RMR) override; // ustalenie przelozenia rapida /// One-step distributor advance for the KE distributor. @@ -1104,6 +1160,11 @@ class TDriverHandle /// Initialises internal pressures from the supplied reference. /// Initial pressure [bar]. virtual void Init(double Press); + /// + /// The pressures the valve keeps from one step to the next, in an order of its own kind. + /// For a snapshot of the simulation, which reads them and puts them back. + /// + virtual std::vector pressures(); /// Returns the control-reservoir / equalising pressure displayed on the cab gauge. virtual double GetCP(); /// Returns the EP brake intensity reported by the handle (0 by default). @@ -1166,6 +1227,7 @@ class TFV4a : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and RP to the supplied pressure. void Init(double Press) override; + std::vector pressures() override; /// Default constructor. using TDriverHandle::TDriverHandle; @@ -1212,6 +1274,7 @@ class TFV4aM : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and RP. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). @@ -1266,6 +1329,7 @@ class TMHZ_EN57 : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). @@ -1318,6 +1382,7 @@ class TMHZ_K5P : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). @@ -1369,6 +1434,7 @@ class TMHZ_6P : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). @@ -1434,6 +1500,7 @@ class TM394 : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chamber. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns CP. @@ -1473,6 +1540,7 @@ class TH14K1 : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns CP. @@ -1518,6 +1586,7 @@ class TSt113 : public TH14K1 double GetPos(int i) override; /// Enables the time chambers (no pressure init). void Init(double Press) override; + std::vector pressures() override; /// Default constructor. using TH14K1::TH14K1;}; @@ -1538,6 +1607,7 @@ class Ttest : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP. void Init(double Press) override; + std::vector pressures() override; /// Default constructor. using TDriverHandle::TDriverHandle;}; @@ -1563,6 +1633,7 @@ class TFD1 : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises MaxBP and the action speed. void Init(double Press) override; + std::vector pressures() override; /// Returns the currently commanded cylinder pressure (BP). double GetCP() override; /// Sets the action speed multiplier. @@ -1589,6 +1660,7 @@ class TH1405 : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises MaxBP and enables the time chamber. void Init(double Press) override; + std::vector pressures() override; /// Returns the currently commanded cylinder pressure (BP). double GetCP() override; // procedure Init(press: real; MaxBP: real); overload; @@ -1625,6 +1697,7 @@ class TFVel6 : public TDriverHandle double GetSound(int i) override; /// Enables the time chambers. void Init(double Press) override; + std::vector pressures() override; /// Default constructor. using TDriverHandle::TDriverHandle;}; @@ -1659,6 +1732,7 @@ class TFVE408 : public TDriverHandle double GetSound(int i) override; /// Enables the time chamber, disables the EP-time chamber. void Init(double Press) override; + std::vector pressures() override; /// Default constructor. using TDriverHandle::TDriverHandle;}; diff --git a/physics/components/airsupply.h b/physics/components/airsupply.h index b5a04460b..acf237ee8 100644 --- a/physics/components/airsupply.h +++ b/physics/components/airsupply.h @@ -254,6 +254,30 @@ class AirCompressor return step; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool running{false}; + bool allow{false}; + bool allowLocal{true}; + bool governorLock{false}; + double powerTime{0.0}; + int listPosition{0}; + }; + Snapshot TakeSnapshot() const + { + return {running, allow, allowLocal, governorLock, powerTime, listPosition}; + } + void RestoreSnapshot(Snapshot const &State) + { + running = State.running; + allow = State.allow; + allowLocal = State.allowLocal; + governorLock = State.governorLock; + powerTime = State.powerTime; + listPosition = State.listPosition; + } + private: bool running{false}; bool allow{false}; @@ -318,6 +342,22 @@ class AirSupply // for the tests: the pressure in the reservoir as given, whatever its air void SetPressureForTest(double const Value) { mainReservoirPressure = Value; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + double mainReservoirPressure{0.0}; + double compressedVolume{0.0}; + }; + Snapshot TakeSnapshot() const + { + return {mainReservoirPressure, compressedVolume}; + } + void RestoreSnapshot(Snapshot const &State) + { + mainReservoirPressure = State.mainReservoirPressure; + compressedVolume = State.compressedVolume; + } + private: double mainReservoirPressure{0.0}; double compressedVolume{0.0}; diff --git a/physics/components/lowvoltage.h b/physics/components/lowvoltage.h index a3c4b1332..50a01fc73 100644 --- a/physics/components/lowvoltage.h +++ b/physics/components/lowvoltage.h @@ -95,6 +95,28 @@ class LowVoltageSupply void Set24vAvailableForTest(bool const State) { power24vAvailable = State; } void Set110vAvailableForTest(bool const State) { power110vAvailable = State; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool batteryOn{false}; + double batteryVoltage{0.0}; + bool power110vAvailable{false}; + bool power24vAvailable{false}; + double power24vVoltage{0.0}; + }; + Snapshot TakeSnapshot() const + { + return {batteryOn, batteryVoltage, power110vAvailable, power24vAvailable, power24vVoltage}; + } + void RestoreSnapshot(Snapshot const &State) + { + batteryOn = State.batteryOn; + batteryVoltage = State.batteryVoltage; + power110vAvailable = State.power110vAvailable; + power24vAvailable = State.power24vAvailable; + power24vVoltage = State.power24vVoltage; + } + private: bool batteryOn{false}; double batteryVoltage{0.0}; diff --git a/physics/components/maincircuit.h b/physics/components/maincircuit.h index 39f083687..d96a957f6 100644 --- a/physics/components/maincircuit.h +++ b/physics/components/maincircuit.h @@ -75,6 +75,22 @@ class LineBreaker return true; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool closed{false}; + double initCountdown{0.0}; + }; + Snapshot TakeSnapshot() const + { + return {closed, initCountdown}; + } + void RestoreSnapshot(Snapshot const &State) + { + closed = State.closed; + initCountdown = State.initCountdown; + } + private: bool closed{false}; double initCountdown{0.0}; // how long it still initialises [s] @@ -104,6 +120,24 @@ class LineContactors void RestartSwitchTimer() { lastSwitchTime = 0.0; } void AdvanceSwitchTimer(double const dt) { lastSwitchTime += dt; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool closed{false}; + bool forcedOpen{false}; + double lastSwitchTime{0.0}; + }; + Snapshot TakeSnapshot() const + { + return {closed, forcedOpen, lastSwitchTime}; + } + void RestoreSnapshot(Snapshot const &State) + { + closed = State.closed; + forcedOpen = State.forcedOpen; + lastSwitchTime = State.lastSwitchTime; + } + private: bool closed{false}; bool forcedOpen{false}; @@ -169,6 +203,26 @@ class ProtectionRelays pressureSwitch = config.hasPressureSwitch && ((config.pressureSwitchWatchesCylinders && cylinderPressure > 2.0) || pipePressure < 3.6); } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool noVoltage{true}; + bool overvoltage{true}; + bool ground{true}; + bool pressureSwitch{false}; + }; + Snapshot TakeSnapshot() const + { + return {noVoltage, overvoltage, ground, pressureSwitch}; + } + void RestoreSnapshot(Snapshot const &State) + { + noVoltage = State.noVoltage; + overvoltage = State.overvoltage; + ground = State.ground; + pressureSwitch = State.pressureSwitch; + } + private: bool noVoltage{true}; bool overvoltage{true}; @@ -278,6 +332,28 @@ class PowerConverter // for the tests of the parts it feeds: the converter running, or not, whatever its conditions void SetRunningForTest(bool const State) { running = State; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool allow{false}; + bool allowLocal{true}; + bool running{false}; + bool overloaded{false}; + double startDelayTimer{0.0}; + }; + Snapshot TakeSnapshot() const + { + return {allow, allowLocal, running, overloaded, startDelayTimer}; + } + void RestoreSnapshot(Snapshot const &State) + { + allow = State.allow; + allowLocal = State.allowLocal; + running = State.running; + overloaded = State.overloaded; + startDelayTimer = State.startDelayTimer; + } + private: bool allow{false}; bool allowLocal{true}; diff --git a/physics/components/pantographs.h b/physics/components/pantographs.h index be7ab5688..7783d8c90 100644 --- a/physics/components/pantographs.h +++ b/physics/components/pantographs.h @@ -201,6 +201,30 @@ class PantographAir pressureSwitchActive = PressureSwitchPrimed; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + double volume{0.48}; + double pressure{0.0}; + bool compressorRunning{false}; + bool connectedToMainReservoir{true}; + bool pressureSwitchActive{false}; + bool pressureLockActive{false}; + }; + Snapshot TakeSnapshot() const + { + return {volume, pressure, compressorRunning, connectedToMainReservoir, pressureSwitchActive, pressureLockActive}; + } + void RestoreSnapshot(Snapshot const &State) + { + volume = State.volume; + pressure = State.pressure; + compressorRunning = State.compressorRunning; + connectedToMainReservoir = State.connectedToMainReservoir; + pressureSwitchActive = State.pressureSwitchActive; + pressureLockActive = State.pressureLockActive; + } + private: double volume{0.48}; // so that the raised pantographs drop soon with the compressor off double pressure{0.0}; diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp index 3605d6810..45e415a2a 100644 --- a/physics/components/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -30,6 +30,39 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/internal.h" +std::vector TSecuritySystem::state() const +{ + return {vigilance_timer, + alert_timer, + press_timer, + velocity, + cabsignal_active ? 1.0 : 0.0, + pressed ? 1.0 : 0.0, + enabled ? 1.0 : 0.0, + cabsignal_lock ? 1.0 : 0.0, + vigilance_suspended ? 1.0 : 0.0, + power ? 1.0 : 0.0, + static_cast(cabactive)}; +} + +void TSecuritySystem::state(std::vector const &State) +{ + // a list of another length comes from a build which keeps other things + if (State.size() != 11) + return; + vigilance_timer = State[0]; + alert_timer = State[1]; + press_timer = State[2]; + velocity = State[3]; + cabsignal_active = State[4] != 0.0; + pressed = State[5] != 0.0; + enabled = State[6] != 0.0; + cabsignal_lock = State[7] != 0.0; + vigilance_suspended = State[8] != 0.0; + power = State[9] != 0.0; + cabactive = static_cast(State[10]); +} + void TSecuritySystem::set_enabled(bool e) { if (vigilance_enabled || cabsignal_enabled || radiostop_enabled) diff --git a/physics/components/snapshot.cpp b/physics/components/snapshot.cpp new file mode 100644 index 000000000..ed0b85430 --- /dev/null +++ b/physics/components/snapshot.cpp @@ -0,0 +1,1130 @@ +/* +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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 "0", "1"... +void capture_handle(snap::record &Entry, std::string_view const Name, TDriverHandle &Handle) +{ + std::vector 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 int device_state(Device_ const &Device) +{ + return (Device.is_enabled ? 1 : 0) | (Device.is_disabled ? 2 : 0) | (Device.is_active ? 4 : 0); +} + +template 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 void capture_device(snap::record &Entry, std::string_view const Key, Device_ const &Device) +{ + Entry.set(Key, device_state(Device)); +} + +template 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 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 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 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 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 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 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 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 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 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(std::size(V.Lights[0])))}; + if (Key == "compressorlistpos") + return {0, std::clamp(V.air.compressor.config.listPositions, 0, static_cast(std::size(V.air.compressor.config.list[0])) - 1)}; + if (Key == "wiperswitchpos") + return {0, static_cast(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(V.dimPositions.size()) - 1, 0)}; + return {std::numeric_limits::min(), std::numeric_limits::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 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 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 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(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(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(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(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(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(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(reservoirs.size()) - 1, "")) && + false == Entry.has(indexed("res", static_cast(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(track.CategoryFlag), + static_cast(track.QualityFlag), static_cast(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::min()}; + constexpr auto highest{std::numeric_limits::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(V.derailOutcome)); + Entry.set("derailedby", static_cast(V.derailedBy)); + Entry.set("derailvelocity", V.derailVelocity); + Entry.set("derailcause", static_cast(V.derailCause)); + Entry.set("derailacceleration", V.derailAcceleration); + Entry.set("derailside", V.derailSide); + Entry.set("collisionderail", static_cast(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(derailment::outcome::overturned))) + V.derailOutcome = static_cast(outcome); + if (auto reason{0}; Entry.get("derailedby", reason, 0, static_cast(derailment::reason::other))) + V.derailedBy = static_cast(reason); + Entry.get("derailvelocity", V.derailVelocity); + if (auto cause{0}; Entry.get("derailcause", cause, 0, static_cast(derail_motion::cause::collision))) + V.derailCause = static_cast(cause); + Entry.get("derailacceleration", V.derailAcceleration); + Entry.get("derailside", V.derailSide, -1, 1); + if (auto reason{0}; Entry.get("collisionderail", reason, 0, static_cast(COLLISION_PUSHED_OFF))) + V.collisionDerail = static_cast(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(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(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(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::min(), std::numeric_limits::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(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); +} diff --git a/physics/consistbraking.h b/physics/consistbraking.h index 78794864a..c7e9a3109 100644 --- a/physics/consistbraking.h +++ b/physics/consistbraking.h @@ -42,6 +42,10 @@ class ConsistBrakeBlending // the figures of the last step for the debug screen, in the order of Labels static constexpr std::array Labels{"masa: ", "amax: ", "Fzad: ", "FmPN: ", "FmED: ", "FrED: ", "FzPN: ", "nPrF: "}; std::array const &Figures() const { return figures; } + // the demand of the ED brake of the step before [N], which the next one is held to: read and put back by a snapshot of the + // simulation + double LastElectrodynamicDemand() const { return lastEdDemand; } + void RestoreLastElectrodynamicDemand(double const Demand) { lastEdDemand = Demand; } private: struct Step; diff --git a/physics/oerlikonest.cpp b/physics/oerlikonest.cpp index 524624a21..c5dad80b9 100644 --- a/physics/oerlikonest.cpp +++ b/physics/oerlikonest.cpp @@ -309,6 +309,42 @@ void TNESt3::EStParams( double const /*i_crc*/ ) const // parametry charakteryst // no effect for this device type } +std::vector TNESt3::latches() const +{ + auto state{TBrake::latches()}; + state.emplace_back(Zamykajacy ? 1.0 : 0.0); + state.emplace_back(Przys_blok ? 1.0 : 0.0); + state.emplace_back(RapidStatus ? 1.0 : 0.0); + state.emplace_back(LBP); + state.emplace_back(LoadC); + return state; +} + +void TNESt3::latches(std::vector const &State) +{ + auto const first{TBrake::latches().size()}; + if (State.size() < first + 5) + return; + TBrake::latches(State); + Zamykajacy = State[first + 0] != 0.0; + Przys_blok = State[first + 1] != 0.0; + RapidStatus = State[first + 2] != 0.0; + LBP = State[first + 3]; + LoadC = State[first + 4]; +} + +std::vector TNESt3::reservoirs() const +{ + auto list { TBrake::reservoirs() }; + list.emplace_back( CntrlRes.get() ); + list.emplace_back( Miedzypoj.get() ); + // the relays hold air of their own; a slot without a relay keeps its place in the list + for( auto const &relay : Przekladniki ) { + list.emplace_back( relay.get() ); + } + return list; +} + void TNESt3::Init( double const PP, double const HPP, double const LPP, double const BP, int const BDF ) { TBrake::Init(PP, HPP, LPP, BP, BDF); diff --git a/physics/oerlikonest.h b/physics/oerlikonest.h index eedf80dc9..6ff49cbd6 100644 --- a/physics/oerlikonest.h +++ b/physics/oerlikonest.h @@ -192,6 +192,9 @@ class TNESt3 : public TBrake { public: using TBrake::TBrake; void Init( double const PP, double const HPP, double const LPP, double const BP, int const BDF ) override; + std::vector reservoirs() const override; // with the control reservoir, the intermediate volume and the relays + std::vector latches() const override; // the closing valve, the lock of the accelerator, the rapid step, the pressures last told + void latches( std::vector const &State ) override; double GetPF( double const PP, double const dt, double const Vel ) override; // przeplyw miedzy komora wstepna i PG void EStParams(double i_crc) const; // parametry charakterystyczne dla ESt double GetCRP() override; diff --git a/physics/vehicle.h b/physics/vehicle.h index c3ed63725..1210439d7 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -34,6 +34,10 @@ http://mozilla.org/MPL/2.0/. class TractionDrive; class cParser; +namespace simulation::snapshot +{ +class record; // simulation/simulationsnapshot.h +} namespace physics { class Vehicle; @@ -450,6 +454,9 @@ class TSecuritySystem bool radiostop_available() const; bool has_separate_acknowledge() const; void load(std::string const &line, double vmax); + // what the device keeps from one step to the next, its timers and latches: read and put back by a snapshot of the simulation + std::vector state() const; + void state(std::vector const &State); double MagnetLocation = 0.0; }; @@ -1807,8 +1814,15 @@ class Vehicle // the cab interior light the light preset at given position (1-based, as lightsPos) sets, if it sets one std::optional LightsPresetCabLight(int Position) const; + // the state of the running vehicle in an entry of a snapshot of the simulation (physics/components/snapshot.cpp): what it + // carries, how it moves, what its machinery is set to and the air in its brakes. Load sets what the entry has and leaves + // the rest as the vehicle has it; the couplings belong to the pair of vehicles and aren't touched + void SnapshotSave(simulation::snapshot::record &Entry) const; + void SnapshotLoad(simulation::snapshot::record const &Entry); + private: // the state and the definition no code outside the vehicle uses + struct snapshot_members; // what a snapshot keeps of the vehicle and of its parts, physics/components/snapshot.cpp // the vehicle derails now, by the Reason, at the speed it has (DerailedBy(), DerailVelocity()) void noteDerailment(derailment::reason Reason); double eimicReal = 0; diff --git a/rendering/opengl46/opengl46cabprobe.cpp b/rendering/opengl46/opengl46cabprobe.cpp index 67148a31e..db059a812 100644 --- a/rendering/opengl46/opengl46cabprobe.cpp +++ b/rendering/opengl46/opengl46cabprobe.cpp @@ -97,7 +97,7 @@ void opengl46_cab_probe::bind() glBindTextureUnit(gl::CAB_PROBE_ALBEDO_TEX, (m_albedo != 0) ? m_albedo : m_empty); glBindTextureUnit(gl::CAB_PROBE_MASK_TEX, (m_mask != 0) ? m_mask : m_empty); if (m_sh) - m_sh->bind_base(); + m_sh->bind_uniform(gl::CAB_PROBE_UBO_BINDING); } bool opengl46_cab_probe::gpu_allocate(int const Size) @@ -174,7 +174,8 @@ void opengl46_cab_probe::gpu_end() glProgramUniform2i(*m_sh_program, SH_LEVEL_LOCATION, sh_level(), sh_size()); m_sh->bind_base(); m_sh_program->dispatch(1); - glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + // the shading reads it as a uniform block + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT | GL_UNIFORM_BARRIER_BIT); opengl_texture::reset_unit_cache(); m_timer.end(); } diff --git a/rendering/opengl46/opengl46cabprobe.h b/rendering/opengl46/opengl46cabprobe.h index c920b34de..bbf6da7d5 100644 --- a/rendering/opengl46/opengl46cabprobe.h +++ b/rendering/opengl46/opengl46cabprobe.h @@ -30,7 +30,8 @@ class opengl46_cab_probe : public gfx::cab_probe // doesn't compile) there is no probe: logged, and gfx.cabprobe switched off void init(); // puts the maps (or the stand-ins) on their texture units, gl::CAB_PROBE_TEX, gl::CAB_PROBE_ALBEDO_TEX and the mask on - // gl::CAB_PROBE_MASK_TEX, and the spherical harmonics on gl::CAB_PROBE_SSBO_BINDING. once per context and frame + // gl::CAB_PROBE_MASK_TEX, and the spherical harmonics on the uniform block of + // gl::CAB_PROBE_UBO_BINDING. once per context and frame void bind(); // program of the probe, of the alpha tested materials when Alpha gl::program &program(bool const Alpha) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index d7b1cb24f..ba76b6a21 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -7502,6 +7502,15 @@ bool opengl46_renderer::Init_caps() WriteLog("shadows map size capped at " + std::to_string(m_shadowbuffersize) + "p"); } + // the storage buffer binding points the shaders use (gl::MAX_SSBO_BINDINGS); with fewer, the materials don't compile + { + GLint ssbobindings{0}; + ::glGetIntegerv(GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS, &ssbobindings); + WriteLog(std::format("shader storage buffer binding points: {}", ssbobindings)); + if (ssbobindings < static_cast(gl::MAX_SSBO_BINDINGS)) + ErrorLog(std::format("the shaders need {} shader storage buffer binding points, the driver offers {}", gl::MAX_SSBO_BINDINGS, ssbobindings)); + } + clamp_multisampling(); if (Global.iMultisampling) { diff --git a/rendering/opengl46/opengl46sky.cpp b/rendering/opengl46/opengl46sky.cpp index 9f87800a5..548d045d0 100644 --- a/rendering/opengl46/opengl46sky.cpp +++ b/rendering/opengl46/opengl46sky.cpp @@ -77,8 +77,8 @@ void opengl46_sky::init() Global.gfx_envmap_ggx = false; } - m_sky_ssbo = std::make_unique(sizeof(gl::sky_data), gl::SKY_SSBO_BINDING); - m_sky_ssbo->update(m_sky_data); + m_sky_ubo = std::make_unique(sizeof(gl::sky_data), gl::SKY_UBO_BINDING); + m_sky_ubo->update(m_sky_data); m_atmosphere_ubo = std::make_unique(sizeof(gl::atmosphere_ubs), gl::ATMOSPHERE_UBO_BINDING); m_atmosphere_result_ssbo = std::make_unique(sizeof(gl::atmosphere_result), gl::ATMOSPHERE_RESULT_SSBO_BINDING); @@ -92,9 +92,9 @@ void opengl46_sky::init() void opengl46_sky::bind() { - m_sky_ssbo->bind_base(); + m_sky_ubo->bind_uniform(); m_atmosphere_ubo->bind_uniform(); - m_atmosphere_result_ssbo->bind_base(); + // the result of the atmosphere is bound by its pass only (update_atmosphere()): its point is shared by the compute passes } void opengl46_sky::update_atmosphere(glm::vec3 const &Sundirection) @@ -159,7 +159,7 @@ void opengl46_sky::update(opengl46_light &Sunlight, glm::vec3 &Fogcolor, CSkyDom if (!m_sky_data_uploaded || std::memcmp(&skydata, &m_sky_data, sizeof(skydata)) != 0) { m_sky_data = skydata; - m_sky_ssbo->update(m_sky_data); + m_sky_ubo->update(m_sky_data); m_sky_data_uploaded = true; } } diff --git a/rendering/opengl46/opengl46sky.h b/rendering/opengl46/opengl46sky.h index c5fbba8c1..bbc1c63e3 100644 --- a/rendering/opengl46/opengl46sky.h +++ b/rendering/opengl46/opengl46sky.h @@ -26,7 +26,7 @@ http://mozilla.org/MPL/2.0/. class CSkyDome; // light of the sky for the opengl 4.6 renderer: -// - the directional part of the ambient light, as spherical harmonics in sky_ssbo, worked out from the colours of the sky +// - the directional part of the ambient light, as spherical harmonics in sky_ubo, worked out from the colours of the sky // dome or from the physical atmosphere. the shading adds it to the uniform ambient light (light_common.glsl), so the // average of the ambient light stays what the rest of the renderer sets // - the physical atmosphere (Hillaire 2020, atmosphere_*.comp): look-up tables made in compute passes, the sky drawn from @@ -104,7 +104,7 @@ class opengl46_sky static GLuint create_table(GLsizei Width, GLsizei Height); // buffers the shaders read - std::unique_ptr m_sky_ssbo; + std::unique_ptr m_sky_ubo; std::unique_ptr m_atmosphere_ubo; std::unique_ptr m_atmosphere_result_ssbo; gl::sky_data m_sky_data{}; diff --git a/script_screens_doc.md b/script_screens_doc.md index 3e9248d11..793cc1233 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -308,6 +308,6 @@ again: Only `eu07.ini` turns it on: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set the other keys that would take a scenery out of its sandbox or reach the computer: `execonexit`, `extcam.cmd`, -`extcam.rec`, `screenshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, +`extcam.rec`, `screenshotsdir`, `snapshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, `feedbackmode`, `feedbackport`, nor does it switch on `python.enabled`, `luascreens.enabled` or `wasm.enabled` when `eu07.ini` has them off. A scenery may still switch those three off, or `lua.fulllibraries` off, as it always could. diff --git a/shaders/ogl46/clouds_march.comp b/shaders/ogl46/clouds_march.comp index a2d85c24e..05ed1b1fa 100644 --- a/shaders/ogl46/clouds_march.comp +++ b/shaders/ogl46/clouds_march.comp @@ -71,7 +71,7 @@ float cloud_phase(float cosangle, float scale) } // the light of the sky a face looking straight up (Up 1) or down (-1) gets: the uniform ambient light and the directional part of -// the sky light (sky_ssbo, light_common.glsl: sky_ambient_directional) along the vertical. with the physical atmosphere it is bluer +// the sky light (sky_ubo, light_common.glsl: sky_ambient_directional) along the vertical. with the physical atmosphere it is bluer // and brighter from above than from the sides, so the shaded sides of the clouds take the colour of the sky above them vec3 cloud_sky_light(float up) { diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index 0e727e3a1..d09a15dbb 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -61,8 +61,8 @@ #define WATER_TRAIL 1024 #define WATER_MAP 256 #define WATER_GROUP_SIZE 64 -#define WATER_SSBO_BINDING 16 -#define RAIN_CELLS_SSBO_BINDING 18 +#define WATER_SSBO_BINDING 5 +#define RAIN_CELLS_SSBO_BINDING 7 #define WATER_UBO_BINDING 6 #define WATER_MASK_TEX 25 #define WATER_LAYER_TEXELS 2097152 @@ -87,12 +87,12 @@ #define ENVMAP_GGX_LEVELS 7 #define ENVMAP_GGX_ROUGHNESS_MIN 0.200000 #define ENVMAP_GGX_GROUP_SIZE 8 -#define SKY_SSBO_BINDING 5 +#define SKY_UBO_BINDING 3 #define EXPOSURE_SSBO_BINDING 6 #define EXPOSURE_HISTOGRAM_BINS 256 #define EXPOSURE_HISTOGRAM_GROUP_SIZE 16 #define ATMOSPHERE_UBO_BINDING 4 -#define ATMOSPHERE_RESULT_SSBO_BINDING 7 +#define ATMOSPHERE_RESULT_SSBO_BINDING 9 #define ATMOSPHERE_TRANSMITTANCE_WIDTH 256 #define ATMOSPHERE_TRANSMITTANCE_HEIGHT 64 #define ATMOSPHERE_MULTISCATTERING_SIZE 32 @@ -123,7 +123,8 @@ #define SKY_OCCLUSION_HEIGHT_TEX 29 #define SKY_OCCLUSION_TEX 30 #define CAB_PROBE_MASK_TEX 31 -#define CAB_PROBE_SSBO_BINDING 17 +#define CAB_PROBE_UBO_BINDING 7 +#define CAB_PROBE_SSBO_BINDING 9 #define CAB_PROBE_SH_SIZE 16 #define CAB_PROBE_SH_GROUP_SIZE 64 #define WEATHER_UBO_BINDING 5 @@ -197,7 +198,7 @@ layout(std430, binding = LIGHT_SSBO_BINDING) readonly buffer light_ssbo uint lights_count; // 1 if the shading takes the lights from the list of the cluster of a fragment, see cluster_ubo uint lights_clustered; - // scale of the directional part of the sky ambient light, see sky_ssbo + // scale of the directional part of the sky ambient light, see sky_ubo float sky_ambient_factor; // 1 if rough reflections come from the prefiltered environment map uint env_ggx; @@ -207,7 +208,7 @@ layout(std430, binding = LIGHT_SSBO_BINDING) readonly buffer light_ssbo // directional part of the sky ambient light: real spherical harmonics (bands 1 and 2, band 0 is ambient) of the light // a surface facing a world space direction gets, in units of ambient. see gl::sky_data -layout(std430, binding = SKY_SSBO_BINDING) readonly buffer sky_ssbo +layout(std140, binding = SKY_UBO_BINDING) uniform sky_ubo { vec4 sky_ambient_sh[9]; }; diff --git a/shaders/ogl46/light_common.glsl b/shaders/ogl46/light_common.glsl index a49006820..cfb10758a 100644 --- a/shaders/ogl46/light_common.glsl +++ b/shaders/ogl46/light_common.glsl @@ -15,7 +15,7 @@ layout(binding = SCENE_AO_TEX) uniform sampler2D scene_ao; // itself with again (gl::cab_probe_data) layout(binding = CAB_PROBE_TEX) uniform samplerCube cab_probe_light; layout(binding = CAB_PROBE_ALBEDO_TEX) uniform samplerCube cab_probe_albedo; -layout(std430, binding = CAB_PROBE_SSBO_BINDING) readonly buffer cab_probe_ssbo +layout(std140, binding = CAB_PROBE_UBO_BINDING) uniform cab_probe_ubo { vec4 cab_probe_sh[9]; }; @@ -725,7 +725,7 @@ vec3 material_diffuse() return (value > 0.0 ? diffusecolor * (param[1].x / value) : vec3(0.0)); } -// directional part of the sky ambient light (sky_ssbo, bands 1 and 2 of the spherical harmonics) for a world space direction +// directional part of the sky ambient light (sky_ubo, bands 1 and 2 of the spherical harmonics) for a world space direction vec3 sky_ambient_directional(vec3 n) { return sky_ambient_sh[1].rgb * (0.488603 * n.y) diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 60c6679c3..4bb2c7d7b 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" #include "simulation/simulationtest.h" +#include "simulation/simulationsnapshotworld.h" #include "simulation/blackboxrecorder.h" #include "utilities/Globals.h" @@ -568,6 +569,10 @@ void state_manager::process_commands() { vehicle->Mechanik->PutCommand(command, commanddata.param1, commanddata.param2, &location); } + if (commanddata.command == user_command::snapshotsave && commanddata.action == GLFW_PRESS) { + snapshot::save_now(); + } + if (commanddata.command == user_command::quitsimulation) { // TBD: allow clients to go into offline mode? Application.queue_quit(true); diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index ba12ee4f7..2b3a9f399 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -255,6 +255,23 @@ world_environment::update_moon() { m_moon.update( true ); } +std::array +world_environment::wind_state() const { + + return { m_wind.azimuth, m_wind.azimuth_change, m_wind.velocity, m_wind.velocity_change, m_wind.change_time, m_wind.vector.x, m_wind.vector.y, m_wind.vector.z }; +} + +void +world_environment::wind_state( std::array const &State ) { + + m_wind.azimuth = State[ 0 ]; + m_wind.azimuth_change = State[ 1 ]; + m_wind.velocity = State[ 2 ]; + m_wind.velocity_change = State[ 3 ]; + m_wind.change_time = State[ 4 ]; + m_wind.vector = { State[ 5 ], State[ 6 ], State[ 7 ] }; +} + void world_environment::update_wind() { diff --git a/simulation/simulationenvironment.h b/simulation/simulationenvironment.h index 249d706e7..8d67e94ca 100644 --- a/simulation/simulationenvironment.h +++ b/simulation/simulationenvironment.h @@ -18,6 +18,8 @@ http://mozilla.org/MPL/2.0/. #include "rendering/precipitation.h" #include "audio/sound.h" +#include + class opengl46_renderer; // wrapper for environment elements -- sky, sun, stars, clouds etc @@ -63,6 +65,12 @@ public: inline auto const & wind_azimuth() const { return m_wind.azimuth; } + // the wind as it blows and as it is about to change, for a snapshot of the simulation, which puts it back: + // azimuth and its change, velocity and its change, the time to the next change, the vector + std::array + wind_state() const; + void + wind_state( std::array const &State ); // clouds, fog and precipitation of the scenery, see environment/weather.h inline auto const & weather() const { diff --git a/simulation/simulationsnapshot.cpp b/simulation/simulationsnapshot.cpp new file mode 100644 index 000000000..e5ac33f60 --- /dev/null +++ b/simulation/simulationsnapshot.cpp @@ -0,0 +1,758 @@ +/* +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 "simulation/simulationsnapshot.h" + +#include "utilities/parser.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace simulation::snapshot { + +namespace { + +// a value which is no text at all is written as this, there's no way to write an empty token +constexpr std::string_view empty_mark{"<>"}; +// lines of the file are kept shorter than this, where the tokens allow +constexpr std::size_t line_width{110}; + +// characters a token can hold without quotes around it: nothing which ends a token, starts a comment or a quoted text +bool is_plain(std::string_view const Text) +{ + if (Text.find("//") != std::string_view::npos || Text.find("/*") != std::string_view::npos) + return false; + return std::ranges::none_of(Text, [](char const Character) { + auto const code{static_cast(Character)}; + return code <= ' ' || Character == ';' || Character == '"' || Character == '\\' || code == 127; + }); +} + +// the value as a token of the file; Terminator is the word which ends the entry the value is written in +std::string encode(std::string_view const Value, std::string_view const Terminator) +{ + if (Value.empty()) + return std::string(empty_mark); + std::string text; + if (Value.front() == '<' || Value == Terminator) + { + // one more '<' in front keeps the value apart from the mark of an empty one, and from the end of its entry + text += '<'; + } + text += Value; + if (is_plain(text)) + return text; + std::string quoted{"\""}; + for (auto const character : text) + { + if (character == '"' || character == '\\') + quoted += '\\'; + quoted += character; + } + quoted += '"'; + return quoted; +} + +// the value a token of the file stands for; the parser has taken the quotes off already +std::string decode(std::string const &Token) +{ + if (Token == empty_mark) + return {}; + if (Token.starts_with('<')) + return Token.substr(1); + return Token; +} + +std::string next_token(cParser &Input) +{ + return Input.getToken(false); +} + +// the headings put before the entries of a type, for a reader of the file +std::string_view heading(std::string_view const Type) +{ + using entry = std::pair; + static constexpr std::array headings{ + entry{"time", "date and time of the simulation"}, + entry{"weather", "weather"}, + entry{"random", "random number engine"}, + entry{"memcell", "memory cells: text, value 1, value 2"}, + entry{"switch", "switches: the path set"}, + entry{"track", "tracks changed by events: speed limit, damage"}, + entry{"crossing", "road crossings: the way through which was taken last"}, + entry{"madetrack", "tracks made on the run where a track of the scenery ends: turning loops, derailing tracks"}, + entry{"powersource", "traction power sources: voltage, current, admittance now and before, output, fuses, their timer and count"}, + entry{"isolated", "isolated sections: axles counted in"}, + entry{"event", "queued events: seconds left, the vehicle which set them off"}, + entry{"launcher", "event launchers: their timers"}, + entry{"model", "lights of the models which events switch: the signals"}, + entry{"vehicle", "vehicles: place, speed, couplings, load, machinery"}, + entry{"driver", "drivers: orders, timetable"}, + entry{"player", "the vehicle of the player"}, + }; + auto const lookup{std::ranges::find(headings, Type, &entry::first)}; + return lookup != headings.end() ? lookup->second : std::string_view{}; +} + +void write_record(std::ostream &Output, record const &Record) +{ + auto const terminator{"end" + Record.type}; + std::string line{Record.type + ' ' + encode(Record.name, terminator)}; + for (auto const &[key, value] : Record.fields) + { + auto const token{key + ' ' + encode(value, terminator)}; + if (line.size() + 1 + token.size() > line_width) + { + Output << line << '\n'; + line = " "; + } + line += ' '; + line += token; + } + if (line.size() + 1 + terminator.size() > line_width) + { + Output << line << '\n'; + line = " "; + } + Output << line << ' ' << terminator << '\n'; +} + +// reads the keys and values of an entry, up to its end. returns: what went wrong, if anything +std::string read_fields(cParser &Input, record &Record) +{ + auto const terminator{"end" + Record.type}; + while (true) + { + auto key{next_token(Input)}; + if (key == terminator) + return {}; + if (key.empty()) + return std::format("entry \"{} {}\" isn't closed with {}", Record.type, Record.name, terminator); + auto const value{next_token(Input)}; + if (value.empty() || value == terminator) + return std::format("entry \"{} {}\" has key {} without a value", Record.type, Record.name, key); + Record.fields.emplace_back(std::move(key), decode(value)); + } +} + +using coupler_key = std::pair; + +struct coupler_link { + std::string other; + int otherend{0}; + int flags{0}; +}; + +using coupler_map = std::map>; + +// the links by each of their ends; a link to nothing is the vehicle's end standing free +coupler_map by_coupler(std::vector const &Links) +{ + coupler_map map; + for (auto const &link : Links) + { + auto const linked{false == link.other.empty() && link.flags != 0}; + map[coupler_key{link.vehicle, link.end}] = linked ? coupler_link{link.other, link.otherend, link.flags} : coupler_link{}; + if (linked) + map[coupler_key{link.other, link.otherend}] = coupler_link{link.vehicle, link.end, link.flags}; + } + return map; +} + +bool same_partner(coupler_link const &Left, coupler_link const &Right) +{ + return Left.other == Right.other && Left.otherend == Right.otherend; +} + +// each link once: the end it's listed by first is the one which comes first in the list +std::vector unique_links(std::vector const &Links) +{ + std::vector unique; + std::set> seen; + for (auto const &link : Links) + { + if (link.other.empty() || link.flags == 0) + continue; + if (seen.contains(coupler_key{link.vehicle, link.end}) || seen.contains(coupler_key{link.other, link.otherend})) + continue; + seen.emplace(link.vehicle, link.end); + seen.emplace(link.other, link.otherend); + unique.emplace_back(link); + } + return unique; +} + +// what the snapshot wants of a coupler, if it says anything of it +coupler_link const *wanted_link(coupler_map const &Wanted, std::string const &Vehicle, int const End) +{ + auto const lookup{Wanted.find(coupler_key{Vehicle, End})}; + return lookup != Wanted.end() ? &lookup->second : nullptr; +} + +// the consists the links make, as sets of vehicles: two vehicles are of one consist if a chain of links joins them +class consists { + +public: + // joins the consists of the two vehicles. returns: false if they're of one consist already, which the link would + // make into a ring + bool join(std::string const &Left, std::string const &Right) + { + auto const left{root(Left)}; + auto const right{root(Right)}; + if (left == right) + return false; + m_parents[left] = right; + return true; + } + +private: + std::string root(std::string const &Vehicle) const + { + auto current{Vehicle}; + for (auto lookup{m_parents.find(current)}; lookup != m_parents.end(); lookup = m_parents.find(current)) + current = lookup->second; + return current; + } + + std::map> m_parents; +}; + +// what's refused is kept in the order it came, up to this many lines +constexpr std::size_t refusals_kept{100}; + +struct refusal_list { + std::vector lines; + std::size_t more{0}; +}; + +refusal_list &refusals() +{ + static refusal_list list; + return list; +} + +// a value of the file in what's told of it: a damaged file can have anything in a value, a whole other file too +std::string shortened(std::string_view const Text) +{ + constexpr std::size_t length{40}; + return Text.size() <= length ? std::string(Text) : std::string(Text.substr(0, length)) + "..."; +} + +} // namespace + +std::string number_text(double const Value) +{ + if (std::isnan(Value)) + return "nan"; + if (std::isinf(Value)) + return Value > 0.0 ? "inf" : "-inf"; + // the shortest text which reads back as the same value + return std::format("{}", Value); +} + +std::string number_text(float const Value) +{ + if (std::isnan(Value) || std::isinf(Value)) + return number_text(static_cast(Value)); + return std::format("{}", Value); +} + +std::optional text_number(std::string_view Text) +{ + if (Text.empty()) + return std::nullopt; + if (Text == "nan") + return std::nan(""); + if (Text == "inf") + return HUGE_VAL; + if (Text == "-inf") + return -HUGE_VAL; + if (Text.front() == '+') + Text.remove_prefix(1); + double value{0.0}; + auto const *const end{Text.data() + Text.size()}; + if (auto const [parsed, error]{std::from_chars(Text.data(), end, value)}; error == std::errc{} && parsed == end) + return value; + return std::nullopt; +} + +std::string numbers_text(std::span const Numbers) +{ + std::string text; + for (auto const number : Numbers) + { + if (false == text.empty()) + text += ','; + text += number_text(number); + } + return text; +} + +std::optional whole_number(double const Value, int const Min, int const Max) +{ + if (false == detail::fits_integer(Value) || Value < Min || Value > Max) + return std::nullopt; + return static_cast(Value); +} + +void refuse(std::string Text) +{ + auto &list{refusals()}; + if (list.lines.size() < refusals_kept) + list.lines.emplace_back(std::move(Text)); + else + ++list.more; +} + +std::vector take_refusals() +{ + auto list{std::move(refusals())}; + refusals() = {}; + if (list.more != 0) + list.lines.emplace_back(std::format("and {} more values refused", list.more)); + return std::move(list.lines); +} + +std::vector text_numbers(std::string_view Text) +{ + std::vector numbers; + while (false == Text.empty()) + { + auto const comma{Text.find(',')}; + if (auto const number{text_number(Text.substr(0, comma))}; number.has_value()) + numbers.emplace_back(*number); + Text.remove_prefix(comma == std::string_view::npos ? Text.size() : comma + 1); + } + return numbers; +} + +std::string const *record::find(std::string_view const Key) const +{ + auto const lookup{std::ranges::find(fields, Key, &std::pair::first)}; + return lookup != fields.end() ? &lookup->second : nullptr; +} + +std::string record::text(std::string_view const Key, std::string_view const Fallback) const +{ + auto const *value{find(Key)}; + return value != nullptr ? *value : std::string(Fallback); +} + +void record::refuse(std::string_view const Key, std::string_view const Why) const +{ + snapshot::refuse(std::format("{} {}: {} \"{}\" refused, {}", type, shortened(name), Key, shortened(text(Key)), Why)); +} + +void record::set_text(std::string_view const Key, std::string Value) +{ + if (auto const lookup{std::ranges::find(fields, Key, &std::pair::first)}; lookup != fields.end()) + { + lookup->second = std::move(Value); + return; + } + fields.emplace_back(std::string(Key), std::move(Value)); +} + +std::optional read_count(record const &Entry, std::string_view const Key) +{ + if (std::size_t count{0}; Entry.get(Key, count, std::size_t{0}, Entry.fields.size())) + return count; + return std::nullopt; +} + +std::optional read_index(record const &Entry, std::string_view const Key, std::size_t const Size) +{ + std::size_t index{0}; + if (false == Entry.get(Key, index)) + return std::nullopt; + if (index >= Size) + { + Entry.refuse(Key, std::format("it's past the end of a table of {}", Size)); + return std::nullopt; + } + return index; +} + +record &document::add(std::string_view const Type, std::string_view const Name) +{ + return records.emplace_back(Type, Name); +} + +std::vector document::of(std::string_view const Type) const +{ + std::vector found; + for (auto const &entry : records) + { + if (entry.type == Type) + found.emplace_back(&entry); + } + return found; +} + +record const *document::find(std::string_view const Type, std::string_view const Name) const +{ + auto const lookup{std::ranges::find_if(records, [&](record const &Entry) { return Entry.type == Type && Entry.name == Name; })}; + return lookup != records.end() ? std::to_address(lookup) : nullptr; +} + +record *document::find(std::string_view const Type, std::string_view const Name) +{ + auto const lookup{std::ranges::find_if(records, [&](record const &Entry) { return Entry.type == Type && Entry.name == Name; })}; + return lookup != records.end() ? std::to_address(lookup) : nullptr; +} + +record const *document::header() const +{ + return false == records.empty() && records.front().type == "snapshot" ? &records.front() : nullptr; +} + +int document::version() const +{ + auto const *first{header()}; + if (first == nullptr) + return 0; + // a version which isn't a whole number is no version this build knows + return whole_number(text_number(first->name).value_or(0.0), 0, std::numeric_limits::max()).value_or(0); +} + +void write(std::ostream &Output, document const &Document) +{ + Output << "// MaSzyna simulation snapshot: the state of a running scenery, loaded over it with --load-snapshot\n"; + std::string lasttype; + for (auto const &entry : Document.records) + { + if (entry.type != lasttype) + { + lasttype = entry.type; + if (auto const text{heading(entry.type)}; false == text.empty()) + Output << "\n// " << text << '\n'; + } + write_record(Output, entry); + } +} + +std::string to_text(document const &Document) +{ + std::ostringstream output; + write(output, Document); + return output.str(); +} + +document read(cParser &Input) +{ + // a value can be any word, "include" among them + Input.expandIncludes = false; + document result; + auto type{next_token(Input)}; + while (false == type.empty()) + { + auto name{next_token(Input)}; + if (name.empty()) + { + result.problems.emplace_back(std::format("the file ends after \"{}\"", type)); + break; + } + auto &entry{result.records.emplace_back(type, decode(name))}; + if (auto problem{read_fields(Input, entry)}; false == problem.empty()) + result.problems.emplace_back(std::move(problem)); + type = next_token(Input); + } + auto const *header{result.header()}; + if (header == nullptr) + { + result.problems.emplace_back("the file doesn't start with a \"snapshot\" entry"); + return result; + } + if (result.version() > format_version) + result.warnings.emplace_back(std::format("the file is of version {}, newer than {} which this build writes", result.version(), format_version)); + // the header counts the entries of the file: a file cut short between two entries reads without a fault otherwise + if (auto const *entries{header->find("entries")}; entries != nullptr) + { + if (auto const count{text_number(*entries)}; false == count.has_value() || *count != static_cast(result.records.size())) + { + result.problems.emplace_back(std::format("the header says the file has {} entries, it has {}: it's cut short, or it was put together from pieces", + shortened(*entries), result.records.size())); + } + } + return result; +} + +document parse(std::string const &Text) +{ + cParser parser(Text, cParser::buffer_TEXT); + return read(parser); +} + +bool accepted(document const &Document, bool const Force) +{ + return Document.header() != nullptr && (Document.problems.empty() || Force); +} + +namespace { + +std::filesystem::path temporary_file(std::string const &File) +{ + std::filesystem::path temporary{File}; + temporary += ".tmp"; + return temporary; +} + +} // namespace + +std::string open_temporary(std::string const &File, std::ofstream &Output) +{ + Output.open(temporary_file(File), std::ios::binary | std::ios::trunc); + if (false == Output.is_open()) + return std::format("file \"{}.tmp\" can't be written", File); + return {}; +} + +std::string put_in_place(std::string const &File, std::ofstream &Output) +{ + auto const temporary{temporary_file(File)}; + std::error_code error; + Output.flush(); + Output.close(); + if (Output.fail()) + { + std::filesystem::remove(temporary, error); + return std::format("writing file \"{}.tmp\" failed", File); + } + // the whole text is there: it takes the place of the file at once + std::filesystem::rename(temporary, File, error); + if (error) + { + std::filesystem::remove(temporary, error); + return std::format(R"(file "{0}.tmp" can't be put in place of "{0}")", File); + } + return {}; +} + +std::string write_file(std::string const &File, document const &Document) +{ + return write_file(File, [&Document](std::ostream &Output) { write(Output, Document); }); +} + +document load(std::string const &File) +{ + std::ifstream input(File, std::ios::binary); + if (false == input.is_open()) + { + document result; + result.problems.emplace_back(std::format("file \"{}\" can't be opened", File)); + return result; + } + std::ostringstream text; + text << input.rdbuf(); + return parse(text.str()); +} + +std::string reference(std::string_view const Name, std::size_t const Index, bool const Foundbyname) +{ + if (Foundbyname && false == Name.empty() && Name.front() != '#') + return std::string(Name); + return std::format("#{}", Index); +} + +std::optional reference_index(std::string_view const Reference) +{ + if (Reference.size() < 2 || Reference.front() != '#') + return std::nullopt; + std::size_t index{0}; + auto const *const begin{Reference.data() + 1}; + auto const *const end{Reference.data() + Reference.size()}; + if (auto const [parsed, error]{std::from_chars(begin, end, index)}; error == std::errc{} && parsed == end) + return index; + return std::nullopt; +} + +void name_hash::add(std::string_view const Name) +{ + constexpr std::uint64_t prime{1099511628211ULL}; + for (auto const character : Name) + { + m_hash ^= static_cast(character); + m_hash *= prime; + } + // the end of the name counts too: "ab", "c" isn't "a", "bc" + m_hash ^= 0xffU; + m_hash *= prime; +} + +std::string name_hash::text() const +{ + return std::format("{:016x}", m_hash); +} + +int option_value_count(std::string_view const Option) +{ + if (Option == "--snapshot-at") + return 2; + if (Option == "-s" || Option == "-v" || Option == "-seed" || Option == "-ini" || Option == "--test-timeout" || Option == "--test-wall-timeout" || + Option == "--load-snapshot") + return 1; + return 0; +} + +command_line parse_command_line(std::span const Arguments) +{ + command_line result; + std::size_t index{1}; + while (index < Arguments.size()) + { + std::string_view const option{Arguments[index]}; + auto const values{static_cast(option_value_count(option))}; + auto const complete{index + values < Arguments.size()}; + if (option == "--load-snapshot-force") + { + result.force = true; + } + else if (option == "--load-snapshot") + { + if (complete) + result.load = Arguments[index + 1]; + else if (result.error.empty()) + result.error = "--load-snapshot needs the name of a snapshot file"; + } + else if (option == "--snapshot-at") + { + auto const seconds{complete ? text_number(Arguments[index + 1]) : std::nullopt}; + if (seconds.has_value() && std::isfinite(*seconds) && *seconds >= 0.0) + result.saves.emplace_back(*seconds, Arguments[index + 2]); + else if (result.error.empty()) + result.error = "--snapshot-at needs a number of seconds and the name of a file"; + } + index += 1 + values; + } + return result; +} + +coupling_plan plan_couplings(std::vector const &Current, std::vector const &Wanted, std::vector const &Present) +{ + coupling_plan plan; + auto const current{by_coupler(Current)}; + auto const wanted{by_coupler(Wanted)}; + std::set> const present(Present.begin(), Present.end()); + + // what's coupled and shouldn't be, or should be another way + for (auto const &link : unique_links(Current)) + { + auto const *here{wanted_link(wanted, link.vehicle, link.end)}; + if (auto const *there{wanted_link(wanted, link.other, link.otherend)}; here == nullptr && there == nullptr) + continue; + // a vehicle which stays where the scenery put it isn't coupled to one put where the snapshot has it + if (auto const kept{here != nullptr && present.contains(link.vehicle) && present.contains(link.other) && + same_partner(*here, coupler_link{link.other, link.otherend, link.flags})}; + false == kept) + { + plan.part.emplace_back(link); + continue; + } + if (here->flags != link.flags) + plan.change.emplace_back(link.vehicle, link.end, link.other, link.otherend, here->flags); + } + // what should be coupled and isn't + for (auto const &link : unique_links(Wanted)) + { + if (false == present.contains(link.vehicle) || false == present.contains(link.other)) + { + plan.missing.emplace_back(link); + continue; + } + if (auto const lookup{current.find(coupler_key{link.vehicle, link.end})}; lookup != current.end() && same_partner(lookup->second, coupler_link{link.other, link.otherend, link.flags})) + continue; + plan.join.emplace_back(link); + } + // the links which stay and the ones to make mustn't close a ring of vehicles + consists joined; + for (auto const &link : unique_links(Current)) + { + if (std::ranges::find(plan.part, link) == plan.part.end()) + joined.join(link.vehicle, link.other); + } + std::erase_if(plan.join, [&joined, &plan](coupling_link const &Link) { + if (Link.vehicle != Link.other && joined.join(Link.vehicle, Link.other)) + return false; + plan.refused.emplace_back(Link); + return true; + }); + return plan; +} + +std::vector read_couplings(std::vector const &Entries) +{ + std::vector links; + for (auto const *entry : Entries) + { + for (auto const side : {0, 1}) + { + auto const key{std::format("coupler{}", side)}; + if (false == entry->has(key + "flags")) + continue; + // the end of the coupler on the other side is the index of one of the two couplers of a vehicle + auto otherend{0}; + auto flags{0}; + if (false == entry->get(key + "end", otherend, 0, 1) || false == entry->get(key + "flags", flags, 0, coupling_flags_mask)) + continue; + links.emplace_back(entry->name, side, entry->text(key), otherend, flags); + } + } + return links; +} + +bool placed_where_saved(record const &Entry, double const X, double const Y, double const Z) +{ + auto const x{text_number(Entry.text("x"))}; + auto const y{text_number(Entry.text("y"))}; + auto const z{text_number(Entry.text("z"))}; + if (false == x.has_value() || false == y.has_value() || false == z.has_value() || false == std::isfinite(*x + *y + *z)) + return true; + // written so that a vehicle put at a place which isn't a number is off + return std::hypot(X - *x, Y - *y, Z - *z) <= misplaced_distance; +} + +std::string fingerprint_changes(record const &Saved, record const &Now) +{ + std::string changed; + for (auto const &[key, value] : Now.fields) + { + if (auto const saved{Saved.text(key, value)}; saved != value) + changed += std::format("{}{} {} (snapshot {})", changed.empty() ? "" : ", ", key, value, shortened(saved)); + } + return changed; +} + +std::string free_file(std::string const &File) +{ + std::error_code error; + if (false == std::filesystem::exists(File, error)) + return File; + // the number goes before the extension of the name, the folder is written as it was given + auto const extension{std::filesystem::path{File}.extension().string()}; + auto const stem{File.substr(0, File.size() - extension.size())}; + auto number{2}; + auto file{std::format("{}_{}{}", stem, number, extension)}; + while (std::filesystem::exists(file, error)) + { + ++number; + file = std::format("{}_{}{}", stem, number, extension); + } + return file; +} + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshot.h b/simulation/simulationsnapshot.h new file mode 100644 index 000000000..d5dbcc709 --- /dev/null +++ b/simulation/simulationsnapshot.h @@ -0,0 +1,402 @@ +/* +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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 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 Numbers); +std::vector 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 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 take_refusals(); + +// one entry of a snapshot: " ... end". 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 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 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 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 bool get_clamped(std::string_view Key, Type_ &Target, Type_ Min, Type_ Max) const; + // the value of the key, or Fallback + template Type_ value(std::string_view Key, Type_ Fallback) const; + // the value of the key between Min and Max, or Fallback + template 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> 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 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 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 ... endsnapshot" +struct document { + std::vector 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 problems; + // what a reader should know, but which doesn't keep the document from being used: a file of a newer version + std::vector warnings; + + record &add(std::string_view Type, std::string_view Name); + // the entries of the type, in the order of the file + std::vector 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 ".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 ".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 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 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 part; + std::vector join; + // the links to set other flags on: joined to the same vehicle and end already, but by other means + std::vector change; + // the links of the snapshot to vehicles which aren't in Present + std::vector 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 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 const &Current, std::vector const &Wanted, std::vector 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 read_couplings(std::vector 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: "_2", "_3"... 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 : 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 saves; // --snapshot-at , 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 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 std::string value_text(Type_ const &Value) +{ + using type = std::remove_cvref_t; + if constexpr (std::is_same_v) + return Value ? "1" : "0"; + else if constexpr (std::is_enum_v) + return std::to_string(static_cast(Value)); + else if constexpr (std::is_integral_v) + return std::to_string(Value); + else if constexpr (std::is_same_v) + return number_text(Value); + else if constexpr (std::is_floating_point_v) + return number_text(static_cast(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 bool fits_integer(double const Number) +{ + using limits = std::numeric_limits; + // 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 bool text_value(std::string const &Text, Type_ &Target) +{ + using type = std::remove_cvref_t; + if constexpr (std::is_same_v) + { + Target = Text; + return true; + } + else + { + auto const number{text_number(Text)}; + if (false == number.has_value()) + return false; + if constexpr (std::is_same_v) + { + if (std::isnan(*number)) + return false; + Target = *number != 0.0; + } + else if constexpr (std::is_enum_v || std::is_integral_v) + { + // 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::underlying_type, std::type_identity>::type; + if (false == fits_integer(*number)) + return false; + Target = static_cast(static_cast(*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(std::numeric_limits::max())}; + if (auto const step{top - static_cast(std::nextafter(std::numeric_limits::max(), type{0}))}; + std::isfinite(*number) && std::abs(*number) >= top + step / 2) + return false; + Target = static_cast(*number); + } + return true; + } +} + +// the text of a bound, for what's told of a value out of its range +template std::string bound_text(Type_ const Value) +{ + if constexpr (std::is_enum_v) + return std::to_string(static_cast(Value)); + else + return value_text(Value); +} + +} // namespace detail + +template record &record::set(std::string_view const Key, Type_ const &Value) +{ + set_text(Key, detail::value_text(Value)); + return *this; +} + +template 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 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 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) + { + 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 Type_ record::value(std::string_view const Key, Type_ Fallback) const +{ + get(Key, Fallback); + return Fallback; +} + +template 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 diff --git a/simulation/simulationsnapshotdriver.cpp b/simulation/simulationsnapshotdriver.cpp new file mode 100644 index 000000000..e2c7fefa7 --- /dev/null +++ b/simulation/simulationsnapshotdriver.cpp @@ -0,0 +1,622 @@ +/* +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 +#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; + +// the most events sharing a name a snapshot looks among +constexpr int most_siblings{100000}; +// every order the driver knows, as bits (DriverOrders) +constexpr int every_order{(static_cast(DriverOrder::jumpToFirstOrder) << 1) - 1}; + +// 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(order.Bits()); + } + return text; +} + +// the whole numbers of a list between Min and Max. returns: empty if one of them isn't such a number +std::optional> split(std::string_view Text, int const Min, int const Max) +{ + std::vector numbers; + while (false == Text.empty()) + { + auto const comma{Text.find(',')}; + auto const number{snapshot::text_number(Text.substr(0, comma))}; + auto const whole{number.has_value() ? snapshot::whole_number(*number, Min, Max) : std::nullopt}; + if (false == whole.has_value()) + return std::nullopt; + numbers.emplace_back(*whole); + Text.remove_prefix(comma == std::string_view::npos ? Text.size() : comma + 1); + } + return numbers; +} + +// an event under the keys "" (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)}; + auto sibling{0}; + if (name.empty() || (false == Entry.get(Key + "sibling", sibling, 0, most_siblings) && Entry.has(Key + "sibling"))) + return nullptr; + return snapshot::find_event(name, sibling); +} + +// a point of the table of what's ahead: its numbers under "", 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.LegacyFlagsValue()), + Point.bMoved ? 1.0 : 0.0, Point.fMoved, Point.vPos.x, Point.vPos.y, Point.vPos.z}; + Entry.set(Key, snapshot::numbers_text(numbers)); + if (Point.trTrack != nullptr) + Entry.set(Key + "track", snapshot::track_reference(Point.trTrack)); + save_event(Entry, Key + "event", Point.evEvent); +} + +// returns: false if the entry has no such point, or it's of another make +bool load_point(snapshot::record const &Entry, std::string const &Key, TSpeedPos &Point) +{ + auto const numbers{snapshot::text_numbers(Entry.text(Key))}; + if (numbers.size() != 10) + return false; + // the flags of a point are bits of a whole number + auto const flags{snapshot::whole_number(numbers[4], std::numeric_limits::min(), std::numeric_limits::max())}; + if (false == flags.has_value()) + { + Entry.refuse(Key, "its flags aren't a whole number"); + return false; + } + Point.fDist = numbers[0]; + Point.fVelNext = numbers[1]; + Point.fSectionVelocityDist = numbers[2]; + Point.fPointDist = numbers[3]; + // the flags and, in their top 4 bits, the route through a crossing, -8..7 + Point.flags = SpeedPointFlags::FromBits(static_cast(static_cast(*flags) & 0x0fffffffu)); + Point.crossRoute = *flags >> 28; + Point.bMoved = numbers[5] != 0.0; + Point.fMoved = numbers[6]; + Point.vPos = {numbers[7], numbers[8], numbers[9]}; + Point.trTrack = snapshot::find_track(Entry.text(Key + "track")); + Point.evEvent = load_event(Entry, Key + "event"); + // a point whose track or event the scenery no longer has can't be told from one which had none + return (Point.trTrack != nullptr) == Entry.has(Key + "track") && (Point.evEvent != nullptr) == Entry.has(Key + "event"); +} + +} // namespace + +// the variables kept one for one, by groups in the order of the entry. they're members so that they can name the private +// ones. Driver_ and Converted_ are const for a save; Visit takes the key, the variable and, for a whole number which has +// to be in a range, the range +struct TController::snapshot_members { + // what the driver keeps in another form than the snapshot has it, as the numbers of the snapshot: taken for a save and + // for a load, put back once the load has set what the entry has + struct converted { + int flags{0}; // the driving flags, as the bits of iDrivigFlags they were (TMovementStatus) + int brakeTest{0}; // the stage of the running brake test, as the number of DynamicBrakeTest it was + int staticBrakeTest{0}; // StaticBrakeTest, which nothing read or wrote and which is gone: 0, read and left + int coupler{0}; // the couplings to make when the driver couples next (iCoupler), as the bits of the set + bool uphillStart{false}; // starting uphill: the train brake holds the train until the power does, or is being released + }; + + // the driving flags in the order of their bits in iDrivigFlags (moveStopCloser 0x1 .. moveDepartureWarned 0x400000) + template static auto driving_flags(Flags_ &Flags) + { + return std::array{&Flags.stopCloser, &Flags.stopPoint, &Flags.active, &Flags.press, &Flags.connect, &Flags.primary, + &Flags.late, &Flags.stopHere, &Flags.startHorn, &Flags.startHornNow, &Flags.startHornDone, &Flags.oerlikons, + &Flags.incSpeed, &Flags.trackEnd, &Flags.switchFound, &Flags.guardSignal, &Flags.visibility, &Flags.doorOpened, + &Flags.pushPull, &Flags.signalFound, &Flags.stopPointFound, &Flags.guardOpenDoor, &Flags.departureWarned}; + } + + static converted take(TController const &Driver) + { + converted values; + auto bits{0u}; + auto bit{1u}; + for (auto const *flag : driving_flags(Driver.drivingFlags)) + { + bits |= *flag ? bit : 0u; + bit <<= 1; + } + // the signals the map asked to show were bits Signal_Pc6 and Signal_A1 of the same number + bits |= Driver.drivingFlags.signalPc6 ? 1u << Signal_Pc6 : 0u; + bits |= Driver.drivingFlags.signalA1 ? 1u << Signal_A1 : 0u; + values.flags = static_cast(bits); + values.brakeTest = static_cast(Driver.brakeTest.stage); + values.coupler = Driver.iCoupler.Bits(); + values.uphillStart = Driver.uphillStart.IsActive(); + return values; + } + + static void put(TController &Driver, converted const &Values) + { + auto const bits{static_cast(Values.flags)}; + auto bit{1u}; + for (auto *flag : driving_flags(Driver.drivingFlags)) + { + *flag = (bits & bit) != 0; + bit <<= 1; + } + Driver.drivingFlags.signalPc6 = (bits & (1u << Signal_Pc6)) != 0; + Driver.drivingFlags.signalA1 = (bits & (1u << Signal_A1)) != 0; + Driver.brakeTest.stage = static_cast(Values.brakeTest); + Driver.iCoupler = CouplingSet::FromBits(Values.coupler); + // a start uphill was kept as starting or not: one going on goes on, one given in the entry starts holding + if (false == Values.uphillStart) + Driver.uphillStart.phase = uphill_start::Phase::none; + else if (false == Driver.uphillStart.IsActive()) + Driver.uphillStart.phase = uphill_start::Phase::holding; + } + + template static void speeds(Driver_ &D, Converted_ &, Visit_ const &Visit) + { + Visit("accpreferred", D.AccPreferred); + Visit("accdesired", D.AccDesired); + Visit("veldesired", D.VelDesired); + Visit("accdesiredav", D.fAccDesiredAv); + Visit("accdesiredgravity", D.fAccDesiredGravity); + Visit("velfordriver", D.VelforDriver); + Visit("velsignal", D.VelSignal); + Visit("vellimit", D.VelLimit); + Visit("velsignallast", D.VelSignalLast); + Visit("velsignalnext", D.VelSignalNext); + Visit("vellimitlast", D.VelLimitLast); + Visit("velroad", D.VelRoad); + Visit("velnext", D.VelNext); + Visit("velrestricted", D.VelRestricted); + Visit("shuntvelocity", D.fShuntVelocity); + Visit("velmax", D.fVelMax); + Visit("velplus", D.fVelPlus); + Visit("velminus", D.fVelMinus); + } + + template static void distances(Driver_ &D, Converted_ &, Visit_ const &Visit) + { + Visit("firstsemaphordist", D.FirstSemaphorDist); + Visit("actualproximitydist", D.ActualProximityDist); + Visit("switchcleardist", D.SwitchClearDist); + Visit("signalareaenddist", D.SignalAreaEndDist); + Visit("minproximitydist", D.fMinProximityDist); + Visit("maxproximitydist", D.fMaxProximityDist); + Visit("laststopexpdist", D.fLastStopExpDist); + Visit("driverdist", D.fDriverDist); + Visit("brakedist", D.fBrakeDist); + Visit("movelen", D.dMoveLen); + Visit("length", D.fLength); + Visit("mass", D.fMass); + } + + template static void timers(Driver_ &D, Converted_ &, Visit_ const &Visit) + { + Visit("brakeheldtime", D.fBrakeHeldTime); + Visit("shortfall", D.brakingShortfall.value); + Visit("shortfalltime", D.brakingShortfall.time); + Visit("uphillstarttime", D.uphillStart.startTime); + Visit("warningduration", D.fWarningDuration); + Visit("waitingtime", D.WaitingTime); + Visit("waitingexpiretime", D.WaitingExpireTime); + Visit("idletime", D.IdleTime); + Visit("stoptime", D.fStopTime); + Visit("reactiontime", D.ReactionTime); + Visit("lastreactiontime", D.LastReactionTime); + Visit("braketime", D.fBrakeTime); + Visit("actiontime", D.fActionTime); + Visit("radiocontroltime", D.m_radiocontroltime); + Visit("brakechargingcooldown", D.BrakeChargingCooldown); + Visit("brakechargingstart", D.BrakeChargingStart); + Visit("departblockedstart", D.DepartBlockedStart); + Visit("dbtvelocitybrake", D.brakeTest.velocityBrake); + Visit("dbtvelocityrelease", D.brakeTest.velocityRelease); + Visit("dbtvelocityfinish", D.brakeTest.velocityFinish); + Visit("dbtbrakingtime", D.brakeTest.brakingTime); + Visit("dbtreleasingtime", D.brakeTest.releasingTime); + Visit("dbtmidpointacc", D.brakeTest.midPointAcc); + Visit("lastupdatedtime", D.LastUpdatedTime); + Visit("elapsedtime", D.ElapsedTime); + // when the power was last taken down a step for a slip while starting (#494) + Visit("sandedstarttime", D.sandedStart.decreaseTime); + } + + template static void levels(Driver_ &D, Converted_ &, Visit_ const &Visit) + { + Visit("brakectrlposition", D.BrakeCtrlPosition); + Visit("overhead1", D.fOverhead1); + Visit("overhead2", D.fOverhead2); + Visit("voltage", D.fVoltage); + Visit("driverbraking", D.fDriverBraking); + Visit("brakereaction", D.fBrakeReaction); + Visit("nominalaccthreshold", D.fNominalAccThreshold); + Visit("accthreshold", D.fAccThreshold); + Visit("absaccs", D.AbsAccS); + Visit("brakinginitiallevel", D.BrakingInitialLevel); + Visit("brakinglevelincrease", D.BrakingLevelIncrease); + Visit("accgravity", D.fAccGravity); + Visit("ready", D.fReady); + Visit("consistshade", D.ConsistShade); + Visit("medamax", D.fMedAmax); + } + + template static void numbers(Driver_ &D, Converted_ &C, Visit_ const &Visit) + { + Visit("flags", C.flags); + Visit("direction", D.iDirection, -1, 1); + Visit("directionorder", D.iDirectionOrder, -1, 1); + Visit("vehiclecount", D.iVehicleCount); + Visit("coupler", C.coupler); + Visit("failcount", D.iDriverFailCount); + Visit("overheadzero", D.iOverheadZero); + Visit("overheaddown", D.iOverheadDown); + Visit("universalbrakebuttons", D.UniversalBrakeButtons); + Visit("dizelpercentage", D.DizelPercentage); + Visit("dizelpercentagespeed", D.DizelPercentage_Speed); + Visit("helperstate", D.HelperState); + Visit("shortfallgrowth", D.brakingShortfall.growth); + Visit("dynamicbraketest", C.brakeTest, static_cast(RunningBrakeTest::Stage::waiting), static_cast(RunningBrakeTest::Stage::done)); + Visit("staticbraketest", C.staticBrakeTest); + Visit("radiochannel", D.iRadioChannel); + Visit("guardradio", D.iGuardRadio); + Visit("vehicles", D.iVehicles); + Visit("engines", D.ControlledEnginesCount); + Visit("lastexchangeplatforms", D.m_lastexchangeplatforms); + Visit("lastexchangedirection", D.m_lastexchangedirection); + } + + template static void flags(Driver_ &D, Converted_ &C, Visit_ const &Visit) + { + Visit("stoptargetispassengerstop", D.bStopTargetIsPassengerStop); + Visit("uphillstart", C.uphillStart); + Visit("needtryagain", D.Need_TryAgain); + Visit("heatingtemperatureok", D.IsHeatingTemperatureOK); + Visit("heatingtemperaturetoolow", D.IsHeatingTemperatureTooLow); + Visit("atpassengerstop", D.IsAtPassengerStop); + Visit("scheduledstopvisible", D.IsScheduledPassengerStopVisible); + Visit("forcepnbrake", D.ForcePNBrake); + Visit("brakereinspection", D.BrakeReinspectionPending); + Visit("engineactive", D.iEngineActive); + Visit("passengertrain", D.IsPassengerTrain); + Visit("cargotrain", D.IsCargoTrain); + Visit("heavycargotrain", D.IsHeavyCargoTrain); + Visit("isready", D.Ready); + Visit("consistbraked", D.IsConsistBraked); + Visit("nextstopannouncement", D.m_makenextstopannouncement); + Visit("doorneedsopening", D.DoesAnyDoorNeedOpening); + // a start that slipped: sanding under power until the train is under way (#494) + Visit("sandedstart", D.sandedStart.active); + } + + template static void texts(Driver_ &D, Converted_ &, Visit_ const &Visit) + { + Visit("nextstop", D.asNextStop); + Visit("lastexchangestop", D.m_lastexchangestop); + Visit("assignment", D.m_assignment); + } +}; + +namespace { + +// writes a variable of the driver to the entry +struct save_visit { + snapshot::record &entry; + template void operator()(std::string_view const Key, Type_ const &Value, Range_...) const { entry.set(Key, Value); } +}; + +// sets a variable of the driver from the entry: a whole number given a range only within it +struct load_visit { + snapshot::record const &entry; + template void operator()(std::string_view const Key, Type_ &Target, Range_... Range) const + { + if constexpr (sizeof...(Range) == 2) + entry.get(Key, Target, static_cast(Range)...); + else + entry.get(Key, Target); + } +}; + +} // namespace + +void TController::snapshot_save(simulation::snapshot::record &Entry) const +{ + using members = snapshot_members; + auto const converted{members::take(*this)}; + save_visit const save{Entry}; + // who drives, and what + Entry.set("ai", aiControlled); + Entry.set("front", snapshot::vehicle_reference(pVehicles[VehicleEnd::front])); + Entry.set("rear", snapshot::vehicle_reference(pVehicles[VehicleEnd::rear])); + // the orders: the one it's on, in words for the reader of the file, then all of them + Entry.set("order", Order2Str(OrderCurrentGet())); + Entry.set("orderpos", OrderPos); + Entry.set("orders", join(std::span{OrderList}.first(static_cast(std::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))); + members::texts(*this, converted, save); + // what it does and why + Entry.set("action", eAction); + Entry.set("stopreason", eStopReason); + members::numbers(*this, converted, save); + members::flags(*this, converted, save); + members::speeds(*this, converted, save); + members::distances(*this, converted, save); + members::timers(*this, converted, save); + members::levels(*this, converted, save); + Entry.set("exchangetime", ExchangeTime); + // what the brake of the consist gives at each speed, as worked out when the consist was last looked over + Entry.set("brakea0", snapshot::numbers_text(fBrake_a0)); + Entry.set("brakea1", snapshot::numbers_text(fBrake_a1)); + Entry.set("brakesystem", BrakeSystem); + Entry.set("doorclosure", DoorClosure); + Entry.set("lastannouncement", m_lastannouncement); + Entry.set("vellimitlastdist0", VelLimitLastDist.first).set("vellimitlastdist1", VelLimitLastDist.second); + Entry.set("lighthint0", m_lighthints[VehicleEnd::front]).set("lighthint1", m_lighthints[VehicleEnd::rear]); + if (iDirectionBackup.has_value()) + Entry.set("directionbackup", *iDirectionBackup); + if (iCouplingVehicle.has_value() && iCouplingVehicle->first != nullptr) + Entry.set("couplingvehicle", snapshot::vehicle_reference(iCouplingVehicle->first)).set("couplingend", iCouplingVehicle->second); + save_event(Entry, "signskip", eSignSkip); + save_event(Entry, "signnext", eSignNext); + snapshot_save_table(Entry); +} + +// what the driver sees ahead: the table of the tracks and signs on its way, and the speed limits of points it has +// passed the signs of +void TController::snapshot_save_table(simulation::snapshot::record &Entry) const +{ + Entry.set("table", sSpeedTable.size()); + Entry.set("tablelast", iLast).set("tabledirection", iTableDirection).set("tablelastvel", fLastVel); + if (tLast != nullptr) + Entry.set("tablelasttrack", snapshot::track_reference(tLast)); + if (SemNextIndex != npos) + Entry.set("semnext", SemNextIndex); + if (SemNextStopIndex != npos) + Entry.set("semnextstop", SemNextStopIndex); + for (std::size_t index{0}; index < sSpeedTable.size(); ++index) + save_point(Entry, std::format("p{}", index), sSpeedTable[index]); + + Entry.set("limits", m_pointlimits.size()); + for (std::size_t index{0}; index < m_pointlimits.size(); ++index) + { + auto const &limit{m_pointlimits[index]}; + auto const key{std::format("l{}", index)}; + std::array const numbers{limit.velocity, limit.distance, limit.celldistance, limit.heading.x, limit.heading.y, limit.heading.z, limit.end, limit.endknown ? 1.0 : 0.0}; + Entry.set(key, snapshot::numbers_text(numbers)); + save_event(Entry, key + "event", limit.source); + } + if (m_pointlimitsvehicle != nullptr) + { + std::array const position{m_pointlimitsposition.x, m_pointlimitsposition.y, m_pointlimitsposition.z, m_pointlimitslength}; + Entry.set("limitsvehicle", snapshot::vehicle_reference(m_pointlimitsvehicle)).set("limitsposition", snapshot::numbers_text(position)); + Entry.set("limitsend0", snapshot::vehicle_reference(m_pointlimitsends[0])).set("limitsend1", snapshot::vehicle_reference(m_pointlimitsends[1])); + } +} + +// returns: false if the table of the entry can't be put back whole; the driver then looks at the track again +bool TController::snapshot_load_table(simulation::snapshot::record const &Entry) +{ + TableClear(); + m_pointlimits.clear(); + m_pointlimitsvehicle = nullptr; + // each point of the table has a key of its own: a count past the keys of the entry can't be the count of its points + auto const points{snapshot::read_count(Entry, "table")}; + if (false == points.has_value()) + return false; + auto const count{*points}; + std::vector table(count); + for (std::size_t index{0}; index < count; ++index) + { + if (false == load_point(Entry, std::format("p{}", index), table[index])) + return false; + } + // the indices into the table point at one of its points, or at none (-1 and npos, which the entry doesn't write) + auto last{-1}; + auto const next{snapshot::read_index(Entry, "semnext", count)}; + auto const nextstop{snapshot::read_index(Entry, "semnextstop", count)}; + if ((false == Entry.get("tablelast", last, -1, static_cast(count) - 1) && Entry.has("tablelast")) || (false == next.has_value() && Entry.has("semnext")) || + (false == nextstop.has_value() && Entry.has("semnextstop"))) + return false; + sSpeedTable = std::move(table); + iLast = last; + Entry.get("tabledirection", iTableDirection, -1, 1); + Entry.get("tablelastvel", fLastVel); + tLast = snapshot::find_track(Entry.text("tablelasttrack")); + SemNextIndex = next.value_or(npos); + SemNextStopIndex = nextstop.value_or(npos); + eSignNext = load_event(Entry, "signnext"); + + auto const limits{snapshot::read_count(Entry, "limits").value_or(0)}; + for (std::size_t index{0}; index < limits; ++index) + { + auto const key{std::format("l{}", index)}; + auto const numbers{snapshot::text_numbers(Entry.text(key))}; + auto const *source{load_event(Entry, key + "event")}; + if (numbers.size() != 8 || source == nullptr) + continue; + auto &limit{m_pointlimits.emplace_back()}; + limit.source = source; + limit.velocity = numbers[0]; + limit.distance = numbers[1]; + limit.celldistance = numbers[2]; + limit.heading = {numbers[3], numbers[4], numbers[5]}; + limit.end = numbers[6]; + limit.endknown = numbers[7] != 0.0; + } + if (auto const position{snapshot::text_numbers(Entry.text("limitsposition"))}; position.size() == 4) + { + m_pointlimitsvehicle = snapshot::find_vehicle(Entry.text("limitsvehicle")); + m_pointlimitsposition = {position[0], position[1], position[2]}; + m_pointlimitslength = position[3]; + m_pointlimitsends[0] = snapshot::find_vehicle(Entry.text("limitsend0")); + m_pointlimitsends[1] = snapshot::find_vehicle(Entry.text("limitsend1")); + } + return true; +} + +void TController::snapshot_load(simulation::snapshot::record const &Entry, std::function const &Left) +{ + using members = snapshot_members; + auto converted{members::take(*this)}; + load_visit const load{Entry}; + // the timetable: the scenery gave the train the one it started with, which another may have replaced since + if (auto const train{Entry.text("train", TrainParams.TrainName)}; train != TrainParams.TrainName) + { + TrainParams = TTrainParameters(train); + if (train != "none" && false == TrainParams.LoadTTfile(Global.asCurrentSceneryPath, 0, Entry.value("ttvmax", 0.0))) + ErrorLog(std::format("snapshot: timetable \"{}\" of {} can't be loaded", train, OwnerName())); + } + // the stations are entries of the table of the timetable, 1..StationCount, and the one after the last + auto const laststation{std::clamp(TrainParams.StationCount + 1, 0, MaxTTableSize)}; + Entry.get("station", TrainParams.StationIndex, 0, laststation); + Entry.get("stationstart", TrainParams.StationStart, 0, laststation); + Entry.get("nextstation", TrainParams.NextStationName); + Entry.get("latency", TrainParams.LastStationLatency); + Entry.get("timetabledirection", TrainParams.Direction, -1, 1); + Entry.get("ttvmax", TrainParams.TTVmax); + m_stopflags = TrainParams.stop_flags(); + if (auto const stopflags{split(Entry.text("stopflags"), 0, static_cast(timetable::tristate::no)).value_or(std::vector{})}; 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]); + } + members::texts(*this, converted, load); + + // the orders + if (Entry.has("orders")) + { + // the orders are bits, and the stack holds so many of them + if (auto const orders{split(Entry.text("orders"), 0, every_order)}; orders.has_value() && orders->size() <= static_cast(maxorders)) + { + OrdersClear(); + OrderTop = static_cast(orders->size()); + for (auto index{0}; index < OrderTop; ++index) + OrderList[index] = DriverOrders::FromBits((*orders)[index]); + } + else + Entry.refuse("orders", std::format("they aren't up to {} numbers of orders", maxorders)); + } + // the order the driver is on is an index into the stack + Entry.get("orderpos", OrderPos, 0, maxorders - 1); + + Entry.get("action", eAction, TAction::actUnknown, TAction::actTrial); + Entry.get("stopreason", eStopReason, stopNone, stopError); + members::numbers(*this, converted, load); + members::flags(*this, converted, load); + members::speeds(*this, converted, load); + members::distances(*this, converted, load); + members::timers(*this, converted, load); + members::levels(*this, converted, load); + members::put(*this, converted); + Entry.get("exchangetime", ExchangeTime); + if (auto const numbers{snapshot::text_numbers(Entry.text("brakea0"))}; numbers.size() == std::size(fBrake_a0)) + std::ranges::copy(numbers, fBrake_a0); + if (auto const numbers{snapshot::text_numbers(Entry.text("brakea1"))}; numbers.size() == std::size(fBrake_a1)) + std::ranges::copy(numbers, fBrake_a1); + Entry.get("brakesystem", BrakeSystem, TBrakeSystem::Individual, TBrakeSystem::ElectroPneumatic); + Entry.get("doorclosure", DoorClosure, door_closure_t::none, door_closure_t::open); + Entry.get("lastannouncement", m_lastannouncement, announcement_t::idle, announcement_t::end); + Entry.get("vellimitlastdist0", VelLimitLastDist.first); + Entry.get("vellimitlastdist1", VelLimitLastDist.second); + Entry.get("lighthint0", m_lighthints[VehicleEnd::front]); + Entry.get("lighthint1", m_lighthints[VehicleEnd::rear]); + iDirectionBackup.reset(); + if (auto direction{0}; Entry.get("directionbackup", direction, -1, 1)) + iDirectionBackup = direction; + iCouplingVehicle.reset(); + // the end of the vehicle to couple to is one of its two couplers + if (auto *vehicle{snapshot::find_vehicle(Entry.text("couplingvehicle"))}; vehicle != nullptr) + { + if (auto end{0}; Entry.get("couplingend", end, 0, 1) || false == Entry.has("couplingend")) + iCouplingVehicle = std::make_pair(vehicle, end); + } + + // the consist: its ends as they were, the vehicles driven and braked found anew among what's coupled now. an end left + // where the scenery put it isn't coupled to the consist any more: the ends are then those of what's coupled now + auto *first{snapshot::find_vehicle(Entry.text("front"))}; + auto *last{snapshot::find_vehicle(Entry.text("rear"))}; + if ((first != nullptr && Left(first)) || (last != nullptr && Left(last))) + { + // as CheckVehicles() finds them, from the end the consist goes to + auto end{CheckDirection() >= 0 ? 0 : 1}; + first = pVehicle->FirstFind(end); + if (first == nullptr) + first = pVehicle; + // from the head to the back, the coupler to go on through turned with each vehicle coupled the other way round; + // no further than FirstFind() looks, should the couplings close a ring + last = first; + auto side{1 - end}; + for (auto count{0}; count < 300; ++count) + { + auto *next{last->Neighbour(side)}; + if (next == nullptr) + break; + last = next; + } + } + if (first != nullptr) + pVehicles[VehicleEnd::front] = first; + if (last != nullptr) + pVehicles[VehicleEnd::rear] = last; + ControllingSet(); + if (auto ai{aiControlled}; Entry.get("ai", ai)) + { + aiControlled = ai; + pVehicle->Controller = ai; + } + // what's ahead on the track as the driver had it; without it the table is filled anew from where the train is now + if (false == snapshot_load_table(Entry)) + TableClear(); + eSignSkip = load_event(Entry, "signskip"); + // the hints of what the driver is about to do are for the player, and made again as the driver goes on + m_hints.clear(); + BrakeChargingPipeOverchargeStart.clear(); +} diff --git a/simulation/simulationsnapshotmover.cpp b/simulation/simulationsnapshotmover.cpp new file mode 100644 index 000000000..acdcaaab6 --- /dev/null +++ b/simulation/simulationsnapshotmover.cpp @@ -0,0 +1,27 @@ +/* +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 "simulation/simulationsnapshotmover.h" + +#include "physics/vehicle.h" + +namespace simulation::snapshot { + +void capture_mover(record &Entry, physics::Vehicle const &Mover) +{ + Mover.SnapshotSave(Entry); +} + +void apply_mover(physics::Vehicle &Mover, record const &Entry) +{ + Mover.SnapshotLoad(Entry); +} + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshotmover.h b/simulation/simulationsnapshotmover.h new file mode 100644 index 000000000..c621d3788 --- /dev/null +++ b/simulation/simulationsnapshotmover.h @@ -0,0 +1,26 @@ +/* +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 "simulation/simulationsnapshot.h" +#include "utilities/Classes.h" + +// the part of a simulation snapshot held by the physics of a vehicle (physics::Vehicle): what it carries, how it moves, +// what its machinery is set to and the air in its brakes. the vehicle reads and writes its own state +// (physics::Vehicle::SnapshotSave(), SnapshotLoad(), physics/components/snapshot.cpp); these hand it the entry +namespace simulation::snapshot { + +// adds the state of the vehicle to its entry +void capture_mover(record &Entry, physics::Vehicle const &Mover); +// sets the vehicle to the state of the entry; what the entry doesn't have stays as the vehicle has it. +// the couplings aren't touched, they belong to the pair of vehicles (see plan_couplings()) +void apply_mover(physics::Vehicle &Mover, record const &Entry); + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshotvehicle.cpp b/simulation/simulationsnapshotvehicle.cpp new file mode 100644 index 000000000..24d5ad8f6 --- /dev/null +++ b/simulation/simulationsnapshotvehicle.cpp @@ -0,0 +1,443 @@ +/* +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/DynObj.h" + +#include "physics/vehicle.h" +#include "simulation/simulation.h" +#include "simulation/simulationsnapshotmover.h" +#include "simulation/simulationsnapshotworld.h" +#include "vehicle/Driver.h" +#include "world/Track.h" + +#include +#include +#include + +// the part of a simulation snapshot kept by a vehicle of the scenery: where its axles are on the tracks, which way it +// faces, what it's coupled to, where it's bound for, and through its physics (simulationsnapshotmover.cpp) how fast +// it goes, what it carries and what its machinery is doing + +namespace { + +namespace snapshot = simulation::snapshot; + +// keys of the two axles and the two couplers: "track0", "coupler1flags" +std::string indexed(std::string_view const Part, int const Index, std::string_view const Key = {}) +{ + return std::format("{}{}{}", Part, Index, Key); +} + +void save_axle(snapshot::record &Entry, int const Index, TTrackFollower const &Axle) +{ + Entry.set(indexed("track", Index), snapshot::track_reference(Axle.GetTrack())); + Entry.set(indexed("at", Index), Axle.GetTranslation()); + Entry.set(indexed("dir", Index), Axle.GetDirection()); + if (auto const path{Axle.Path()}; path != 0) + Entry.set(indexed("path", Index), path); + // which events of the track the axle has yet to set off: of the trains with a driver, and of any vehicle + Entry.set(indexed("events", Index), Axle.EventFlags() | (Axle.EventallFlags() << 2)); + // the ways of the switches the axle ran over last, the oldest first: the axle behind it coming onto one of them + // after a throw is checked against them for running forked (world/switchfork.h) + auto const paths{Axle.Paths().entries()}; + for (std::size_t index{0}; index < paths.size(); ++index) + { + Entry.set(indexed("axle", Index, std::format("switch{}", index)), snapshot::track_reference(static_cast(paths[index].first))); + Entry.set(indexed("axle", Index, std::format("way{}", index)), paths[index].second); + } +} + +// the ways of the switches the axle ran over last as the entry has them; an entry without them leaves none +void load_paths(snapshot::record const &Entry, int const Index, TTrackFollower &Axle) +{ + switch_fork::path_memory paths; + for (std::size_t index{0}; index < switch_fork::path_memory::size; ++index) + { + auto const key{indexed("axle", Index, std::format("switch{}", index))}; + if (false == Entry.has(key)) + break; + auto const *track{snapshot::find_track(Entry.text(key))}; + if (track == nullptr || track->eType != tt_Switch) + { + Entry.refuse(key, "it isn't a switch of the scenery"); + continue; + } + if (auto way{0}; Entry.get(indexed("axle", Index, std::format("way{}", index)), way, 0, 1)) + paths.record(track, way); + } + Axle.SetPaths(paths); +} + +// where an entry has an axle +struct axle_place { + TTrack *track{nullptr}; + int path{0}; + double distance{0.0}; + double direction{1.0}; + int events{15}; + + bool put(TTrackFollower &Axle, double const Inset) const + { + // Inset keeps the axle off the very ends of the track + auto const length{track->Length()}; + auto const place{Inset > 0.0 && length > 2.0 * Inset ? std::clamp(distance, Inset, length - Inset) : distance}; + return Axle.Place(track, path, place, direction, events & 3, (events >> 2) & 3); + } +}; + +// returns: the place, without its track if the entry doesn't give one which can be used +axle_place read_axle(snapshot::record const &Entry, int const Index) +{ + axle_place place; + place.track = snapshot::find_track(Entry.text(indexed("track", Index))); + // the path is a segment of a switch (0, 1) or of a crossing (1..6, the sign the way through it), the events two + // pairs of flags. the axle is put at a distance along its track, which has to be a number + if (auto const usable{(Entry.get(indexed("path", Index), place.path, -6, 6) || false == Entry.has(indexed("path", Index))) && + (Entry.get(indexed("at", Index), place.distance, -1e7, 1e7) || false == Entry.has(indexed("at", Index))) && + (Entry.get(indexed("dir", Index), place.direction, -1e7, 1e7) || false == Entry.has(indexed("dir", Index))) && + (Entry.get(indexed("events", Index), place.events, 0, 15) || false == Entry.has(indexed("events", Index)))}; + false == usable) + place.track = nullptr; + return place; +} + +// where the axle is now +axle_place axle_at(TTrackFollower const &Axle) +{ + return {Axle.GetTrack(), Axle.Path(), Axle.GetTranslation(), Axle.GetDirection(), Axle.EventFlags() | (Axle.EventallFlags() << 2)}; +} + +// takes the vehicle off the list of the track it's on, if it's on it +void leave_track(TDynamicObject &Vehicle) +{ + if (Vehicle.MyTrack != nullptr && Vehicle.MyTrack->CheckDynamicObject(&Vehicle)) + Vehicle.MyTrack->RemoveDynamicObject(&Vehicle); + Vehicle.MyTrack = nullptr; +} + +// puts the axles of the vehicle at the places, and its body after them. returns: false if an axle can't be put there +bool put_axles(TDynamicObject &Vehicle, std::array const &Places) +{ + // the axles a hair off the ends of their tracks first, for the body of the vehicle to be worked out from them: + // Move() does that, and takes an axle standing at the very end of a track over to the next one + if (constexpr double inset{1e-6}; false == Places[0].put(Vehicle.Axle0, inset) || false == Places[1].put(Vehicle.Axle1, inset)) + return false; + // too short a way for the axles to move at all + Vehicle.Move(1e-300); + // then exactly where they were + Places[0].put(Vehicle.Axle0, 0.0); + Places[1].put(Vehicle.Axle1, 0.0); + return true; +} + +// the vehicle is on the list of the track its leading axle is on, and its physics where its body is +void settle(TDynamicObject &Vehicle) +{ + if (auto *track{Vehicle.iAxleFirst != 0 ? Vehicle.Axle1.GetTrack() : Vehicle.Axle0.GetTrack()}; track != nullptr && track != Vehicle.MyTrack) + { + leave_track(Vehicle); + track->AddDynamicObject(&Vehicle); + } + Vehicle.physics->SetLoc({-Vehicle.vPosition.x, Vehicle.vPosition.z, Vehicle.vPosition.y}); +} + +// the vehicle whose physics a coupler is joined to: the neighbour at that end as a rule, otherwise looked up +TDynamicObject const *coupled_vehicle(TCoupling const &Coupler, TDynamicObject const *Neighbour) +{ + if (Coupler.Connected == nullptr || Coupler.CouplingFlag.Empty()) + return nullptr; + if (Neighbour != nullptr && Neighbour->physics == Coupler.Connected) + return Neighbour; + auto const &vehicles{simulation::Vehicles.sequence()}; + auto const lookup{std::ranges::find_if(vehicles, [&](TDynamicObject const *Vehicle) { return Vehicle != nullptr && Vehicle->physics == Coupler.Connected; })}; + return lookup != vehicles.end() ? *lookup : nullptr; +} + +void save_coupler(snapshot::record &Entry, int const Index, TCoupling const &Coupler, TDynamicObject const *Neighbour) +{ + Neighbour = coupled_vehicle(Coupler, Neighbour); + auto const coupled{Neighbour != nullptr}; + // an end with nothing coupled says so too: the snapshot knows the vehicle stands free there + Entry.set(indexed("coupler", Index), coupled ? snapshot::vehicle_reference(Neighbour) : std::string{}); + Entry.set(indexed("coupler", Index, "end"), coupled ? Coupler.ConnectedNr : 0); + Entry.set(indexed("coupler", Index, "flags"), coupled ? Coupler.CouplingFlag.Bits() : 0); +} + +} // namespace + +// what the vehicle keeps of its machinery beside its physics: the pantographs as they stand, the passengers getting on and off +void TDynamicObject::snapshot_save_machinery(simulation::snapshot::record &Entry) const +{ + Entry.set("overheadmask", iOverheadMask); + Entry.set("novolttime", NoVoltTime); + for (auto index{0}; index < iAnimType[ANIM_PANTS] && pants != nullptr; ++index) + { + auto const *pantograph{pants[index].fParamPants}; + if (pantograph == nullptr) + continue; + Entry.set(indexed("pant", index, "anglel"), pantograph->fAngleL); + Entry.set(indexed("pant", index, "angleu"), pantograph->fAngleU); + Entry.set(indexed("pant", index, "height"), pantograph->PantWys); + Entry.set(indexed("pant", index, "wire"), pantograph->PantTraction); + Entry.set(indexed("pant", index, "novolttime"), pantograph->NoVoltTime); + } + if (auto const &exchange{m_exchange}; exchange.unload_count != 0.f || exchange.load_count != 0.f) + { + Entry.set("exchangeunload", exchange.unload_count).set("exchangeload", exchange.load_count); + Entry.set("exchangeplatforms", exchange.platforms).set("exchangetime", exchange.time); + } + // the rails under the wheel sets: the length of a rail, and for each wheel set how far along its rail it is and + // whether that's by the joints of the track. a joint of a worn track jolts the vehicle + Entry.set("raillength", dRailLength); + if (false == m_axlesounds.empty()) + { + std::vector joints; + for (auto const &axle : m_axlesounds) + { + joints.emplace_back(axle.distance); + joints.emplace_back(axle.atjoints ? 1.0 : 0.0); + } + Entry.set("railjoints", snapshot::numbers_text(joints)); + } + // the lighting of the compartments: which of them are lit is drawn at random when it comes on + Entry.set("sectionlights", SectionLightsActive); + if (false == Sections.empty()) + { + std::vector levels; + for (auto const §ion : Sections) + levels.emplace_back(section.light_level); + Entry.set("sectionlightlevels", snapshot::numbers_text(levels)); + } + Entry.set("dimheadlights", DimHeadlights).set("highbeamlights", HighBeamLights); + Entry.set("headlightsaoff", HeadlightsAoff).set("headlightsboff", HeadlightsBoff); + // the force the electrodynamic brake of a unit was asked for in the step before, which the next one is held to + if (brakeBlending.LastElectrodynamicDemand() != 0.0) + Entry.set("medoldfed", brakeBlending.LastElectrodynamicDemand()); + // the derailment the scenery and the test mode were told of (new_derailment()): told once, it isn't told again + if (m_derailment.has_value()) + { + Entry.set("derailtold", static_cast(m_derailment->why)).set("derailtoldtrack", m_derailment->track); + Entry.set("derailtoldvelocity", m_derailment->velocity); + } + // off the track: how long, when it's told of in the log next, the move along the track its axles haven't made yet and + // where its body was when they last did + if (physics->OffTrack.active()) + { + Entry.set("offtracktime", m_offtracktotal).set("offtracklog", m_offtracklogdue).set("offtrackaxles", m_offtrackaxles); + Entry.set("offtrackfrom", snapshot::numbers_text(std::array{m_offtrackfrom.x, m_offtrackfrom.y, m_offtrackfrom.z})); + } + // a switch thrown under the train (world/switchfork.h): the switch the bogies of the vehicle, or an end of it and + // the vehicle coupled there, run forked on, and whether that came past what the vehicle takes and was told of + auto const save_fork = [&Entry](std::string const &Key, fork_watch const &Watch) { + if (Watch.Switch != nullptr) + Entry.set(Key, snapshot::track_reference(Watch.Switch)).set(Key + "told", Watch.told); + }; + save_fork("forkbogies", m_forkbogies); + for (auto const end : VehicleEnds) + save_fork(indexed("fork", NumberOf(end)), m_forkends[end]); +} + +void TDynamicObject::snapshot_load_machinery(simulation::snapshot::record const &Entry) +{ + Entry.get("overheadmask", iOverheadMask); + Entry.get("novolttime", NoVoltTime); + for (auto index{0}; index < iAnimType[ANIM_PANTS] && pants != nullptr; ++index) + { + auto *pantograph{pants[index].fParamPants}; + if (pantograph == nullptr) + continue; + Entry.get(indexed("pant", index, "anglel"), pantograph->fAngleL); + Entry.get(indexed("pant", index, "angleu"), pantograph->fAngleU); + Entry.get(indexed("pant", index, "height"), pantograph->PantWys); + Entry.get(indexed("pant", index, "wire"), pantograph->PantTraction); + Entry.get(indexed("pant", index, "novolttime"), pantograph->NoVoltTime); + } + auto &exchange{m_exchange}; + exchange = {}; + // the counts of the passengers getting off and on are counted down step by step + constexpr auto most_passengers{1e6f}; + Entry.get("exchangeunload", exchange.unload_count, -most_passengers, most_passengers); + Entry.get("exchangeload", exchange.load_count, -most_passengers, most_passengers); + Entry.get("exchangeplatforms", exchange.platforms); + Entry.get("exchangetime", exchange.time); + Entry.get("raillength", dRailLength, -1.0, 1e6); + if (auto const joints{snapshot::text_numbers(Entry.text("railjoints"))}; joints.size() == 2 * m_axlesounds.size()) + { + for (std::size_t index{0}; index < m_axlesounds.size(); ++index) + { + m_axlesounds[index].distance = joints[2 * index]; + m_axlesounds[index].atjoints = joints[2 * index + 1] != 0.0; + } + } + Entry.get("sectionlights", SectionLightsActive); + if (auto const levels{snapshot::text_numbers(Entry.text("sectionlightlevels"))}; levels.size() == Sections.size()) + { + for (std::size_t index{0}; index < levels.size(); ++index) + Sections[index].light_level = static_cast(levels[index]); + } + Entry.get("dimheadlights", DimHeadlights); + Entry.get("highbeamlights", HighBeamLights); + Entry.get("headlightsaoff", HeadlightsAoff); + Entry.get("headlightsboff", HeadlightsBoff); + brakeBlending.RestoreLastElectrodynamicDemand(Entry.value("medoldfed", 0.0, -1e9, 1e9)); + m_derailment.reset(); + if (auto why{0}; Entry.get("derailtold", why, 1, static_cast(derailment::reason::other))) + { + std::string track; + Entry.get("derailtoldtrack", track); + m_derailment = derailment::notice{asName, static_cast(why), track, Entry.value("derailtoldvelocity", 0.0)}; + } + else if (false == Entry.has("derailtold") && physics->DamageFlag.HasAll(VehicleDamage::derailed)) + { + // a snapshot written before this was kept: a vehicle derailed then isn't told of again + new_derailment(); + } + if (physics->OffTrack.active()) + { + Entry.get("offtracktime", m_offtracktotal); + Entry.get("offtracklog", m_offtracklogdue); + Entry.get("offtrackaxles", m_offtrackaxles); + if (auto const from{snapshot::text_numbers(Entry.text("offtrackfrom"))}; from.size() == 3) + m_offtrackfrom = {from[0], from[1], from[2]}; + else + m_offtrackfrom = physics->OffTrack.current().position; + // the terrain it slides over, gathered anew around where it is, as when it left the rails + gather_off_track_terrain(); + m_offtracksite = derail_motion::site{m_offtrackterrain.get(), track_bed()}; + if (physics->OffTrack.at_rest()) + crop_off_track_terrain(); + } + auto const load_fork = [&Entry](std::string const &Key, fork_watch &Watch) { + Watch = {}; + if (false == Entry.has(Key)) + return; + auto const *track{snapshot::find_track(Entry.text(Key))}; + if (track == nullptr || track->eType != tt_Switch) + { + Entry.refuse(Key, "it isn't a switch of the scenery"); + return; + } + Watch.Switch = track; + Entry.get(Key + "told", Watch.told); + }; + load_fork("forkbogies", m_forkbogies); + for (auto const end : VehicleEnds) + load_fork(indexed("fork", NumberOf(end)), m_forkends[end]); +} + +void TDynamicObject::snapshot_save(simulation::snapshot::record &Entry) const +{ + if (false == bEnabled) + { + // gone from the simulation, through a portal say + Entry.set("removed", true); + return; + } + // place + save_axle(Entry, 0, Axle0); + save_axle(Entry, 1, Axle1); + Entry.set("first", iAxleFirst); + Entry.set("facing", iDirection); + // where that is in the world: the reader of the file sees it, and a loaded snapshot is checked against it + Entry.set("x", vPosition.x).set("y", vPosition.y).set("z", vPosition.z); + // physics.derailment new, off the track: its body on the ground, which the place above is the place of + if (physics->OffTrack.active()) + Entry.set("offtrack", snapshot::numbers_text(physics->OffTrack.state())); + // consist + for (auto const side : VehicleEnds) + save_coupler(Entry, NumberOf(side), physics->Couplers[side], physics->Neighbours[side].vehicle); + if (ctOwner != nullptr && ctOwner->Vehicle() != nullptr) + Entry.set("owner", snapshot::vehicle_reference(ctOwner->Vehicle())); + Entry.set("destination", asDestination); + // the physics + snapshot::capture_mover(Entry, *physics); + snapshot_save_machinery(Entry); +} + +bool TDynamicObject::snapshot_place(simulation::snapshot::record const &Entry) +{ + if (Entry.value("removed", false)) + { + if (false == bEnabled) + return true; + // the vehicle left the simulation before the snapshot was taken: off the track, and off the list at the next update + leave_track(*this); + // the scenery counted its axles in the isolated sections of the tracks it put it on, the run the snapshot comes + // from counted them out as the train drove off. the events are held while a snapshot is put back, and the saved + // cells and queue carry what followed from it + for (auto const *axle : {&Axle0, &Axle1}) + { + if (auto *track{axle->GetTrack()}; track != nullptr) + track->AxleCounter(-1, this); + } + // nobody's in charge of it: its driver, if it had one, doesn't go on (apply_drivers()) + ctOwner = nullptr; + bEnabled = false; + bDynamicRemove = true; + return true; + } + auto const places{std::array{read_axle(Entry, 0), read_axle(Entry, 1)}}; + if (places[0].track == nullptr || places[1].track == nullptr) + return false; + + // where the scenery put the vehicle, for it to stay there if it can't be put where the snapshot has it + auto const scenery{std::array{axle_at(Axle0), axle_at(Axle1)}}; + auto const facing{iDirection}; + auto const first{iAxleFirst}; + // which of the ends of the vehicle leads in its consist, which of its axles is the first: 0 or 1 + Entry.get("facing", iDirection, 0, 1); + if (put_axles(*this, places)) + { + Entry.get("first", iAxleFirst, 0, 1); + // a vehicle off the track: its axles go along the track beside it, its body is where its motion on the ground has it + if (Entry.has("offtrack")) + { + if (physics->OffTrack.state(snapshot::text_numbers(Entry.text("offtrack"))) && physics->OffTrack.active()) + place_off_track(); + else + Entry.refuse("offtrack", "it isn't the motion of a vehicle off the track"); + } + // a track named by its place in the scenery ("#12") is another one after a track was added before it: the + // place in the world the entry gives tells + if (snapshot::placed_where_saved(Entry, vPosition.x, vPosition.y, vPosition.z)) + { + load_paths(Entry, 0, Axle0); + load_paths(Entry, 1, Axle1); + settle(*this); + return true; + } + Entry.refuse("x", std::format("the vehicle put on track {} is more than {} m from there", Entry.text("track0"), snapshot::misplaced_distance)); + } + // back where the scenery put it, on the rails + physics->OffTrack.reset(); + m_offtrackplaced = false; + iDirection = facing; + iAxleFirst = first; + if (scenery[0].track != nullptr && scenery[1].track != nullptr) + put_axles(*this, scenery); + settle(*this); + return false; +} + +void TDynamicObject::snapshot_load(simulation::snapshot::record const &Entry) +{ + if (false == bEnabled) + return; + Entry.get("destination", asDestination); + + snapshot::apply_mover(*physics, Entry); + // a load of another kind than the scenery gave comes with its model. it's loaded here and not by the first frame: + // laying the load out in the vehicle draws at random, which doesn't count while a snapshot is put back + if (physics->LoadTypeChange()) + LoadUpdate(); + update_load_visibility(); + + snapshot_load_machinery(Entry); +} diff --git a/simulation/simulationsnapshotworld.cpp b/simulation/simulationsnapshotworld.cpp new file mode 100644 index 000000000..d17ebadda --- /dev/null +++ b/simulation/simulationsnapshotworld.cpp @@ -0,0 +1,1416 @@ +/* +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 "simulation/simulationsnapshotworld.h" + +#include "physics/vehicle.h" +#include "application/uitranscripts.h" +#include "model/AnimModel.h" +#include "simulation/simulation.h" +#include "simulation/simulationenvironment.h" +#include "simulation/simulationtest.h" +#include "simulation/simulationtime.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/utilities.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/EvLaunch.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/Track.h" +#include "world/TractionPower.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace simulation::snapshot { + +namespace { + +// the cells the simulation itself writes each frame: the weather, the time and the date for the scripts +constexpr std::string_view scripting_cells{"__simulation."}; +// a speed limit beyond any a track has: a value of the file past it is refused +constexpr double big_velocity{1e6}; +// the most events sharing a name a snapshot looks among, the most seconds an event waits in the queue +constexpr int most_siblings{100000}; +constexpr double longest_wait{1e9}; + +// the place of each thing of a table, to name the ones without a name of their own +template class table_index { + +public: + // the place of the item in the sequence, or the size of the sequence for an item which isn't there + template std::size_t of(Sequence_ const &Sequence, Item_ const *Item) + { + if (auto const place{known(Sequence, Item)}; place < Sequence.size()) + return place; + // the table has grown, or it's the table of another scenery now + m_places.clear(); + std::size_t place{0}; + for (auto const *item : Sequence) + m_places.emplace(item, place++); + return known(Sequence, Item); + } + +private: + template std::size_t known(Sequence_ const &Sequence, Item_ const *Item) const + { + auto const lookup{m_places.find(Item)}; + return lookup != m_places.end() && lookup->second < Sequence.size() && Sequence[lookup->second] == Item ? lookup->second : Sequence.size(); + } + + std::unordered_map m_places; +}; + +// a thing of a table by its reference: its name, or its place +template auto find_in(Table_ const &Table, std::string const &Reference) -> decltype(Table.find(Reference)) +{ + if (auto const index{reference_index(Reference)}; index.has_value()) + return *index < Table.sequence().size() ? Table.sequence()[*index] : nullptr; + return Table.find(Reference); +} + +template std::string reference_in(Table_ const &Table, table_index &Index, Item_ const *Item) +{ + if (Item == nullptr) + return {}; + auto const place{Index.of(Table.sequence(), Item)}; + if (place >= Table.sequence().size()) + return {}; + return reference(Item->name(), place, Table.find(Item->name()) == Item); +} + +table_index &track_index() +{ + static table_index index; + return index; +} + +table_index &vehicle_index() +{ + static table_index index; + return index; +} + +table_index &powersource_index() +{ + static table_index index; + return index; +} + +table_index &model_index() +{ + static table_index index; + return index; +} + +// a track the simulation made on the run, where a track of the scenery ends: the loop a road vehicle turns back on, +// the track a train runs off the rails along (TTrack::NullCreate()) +bool made_on_the_run(TTrack const &Track) +{ + return (Track.iCategoryFlag & 0x80) != 0; +} + +// what the scenery is made of, by which a snapshot tells whether it's put over the scenery it was taken in +void capture_fingerprint(record &Header) +{ + name_hash names; + auto switches{0}; + auto tracks{0}; + for (auto const *track : Paths.sequence()) + { + // the tracks made on the run aren't the scenery's + if (track == nullptr || made_on_the_run(*track)) + continue; + ++tracks; + names.add(track->name()); + if (track->eType == tt_Switch) + ++switches; + } + for (auto const *cell : Memory.sequence()) + names.add(cell != nullptr ? cell->name() : std::string{}); + for (auto const *scenery_event : Events.sequence()) + names.add(scenery_event != nullptr ? scenery_event->m_name : std::string{}); + for (auto const *vehicle : Vehicles.sequence()) + names.add(vehicle != nullptr ? vehicle->name() : std::string{}); + Header.set("tracks", tracks); + Header.set("switches", switches); + Header.set("memcells", Memory.sequence().size()); + Header.set("events", Events.sequence().size()); + Header.set("launchers", Events.launchers().size()); + Header.set("vehicles", Vehicles.sequence().size()); + Header.set("names", names.text()); +} + +void capture_header(document &Document) +{ + auto &header{Document.add("snapshot", std::to_string(format_version))}; + header.set("scenery", Global.SceneryFile); + header.set("seed", Global.random_seed); + header.set("timer", Timer::GetTime()); + capture_fingerprint(header); +} + +void capture_time(document &Document) +{ + auto const &time{Time.data()}; + auto &entry{Document.add("time", "now")}; + entry.set("year", time.wYear).set("month", time.wMonth).set("day", time.wDay).set("weekday", time.wDayOfWeek); + entry.set("hour", time.wHour).set("minute", time.wMinute).set("second", time.wSecond).set("milliseconds", Time.milliseconds()); +} + +bool apply_time(record const &Entry) +{ + // the month and the day pick entries of the tables of the clock: a date which isn't one is refused whole + auto time{Time.data()}; + if (false == Entry.get("year", time.wYear, WORD{1}, WORD{9999}) && Entry.has("year")) + return false; + if (false == Entry.get("month", time.wMonth, WORD{1}, WORD{12}) && Entry.has("month")) + return false; + if (constexpr std::array days{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + false == Entry.get("day", time.wDay, WORD{1}, days[time.wMonth]) && Entry.has("day")) + return false; + if (time.wMonth == 2 && time.wDay == 29 && false == ((time.wYear % 4 == 0 && time.wYear % 100 != 0) || time.wYear % 400 == 0)) + { + Entry.refuse("day", "the year isn't a leap one"); + return false; + } + auto milliseconds{Time.milliseconds()}; + if ((false == Entry.get("weekday", time.wDayOfWeek, WORD{0}, WORD{6}) && Entry.has("weekday")) || + (false == Entry.get("hour", time.wHour, WORD{0}, WORD{23}) && Entry.has("hour")) || + (false == Entry.get("minute", time.wMinute, WORD{0}, WORD{59}) && Entry.has("minute")) || + (false == Entry.get("second", time.wSecond, WORD{0}, WORD{59}) && Entry.has("second")) || + (false == Entry.get("milliseconds", milliseconds, 0.0, 999.999999) && Entry.has("milliseconds"))) + return false; + Time.restore(time, milliseconds); + // the season goes by the date, and the weather by the season + Environment.compute_season(Time.year_day()); + return true; +} + +void capture_weather(document &Document) +{ + auto &entry{Document.add("weather", "now")}; + entry.set("overcast", Global.Overcast).set("fog", Global.fFogEnd).set("temperature", Global.AirTemperature); + // the wind: it changes now and then, by numbers drawn at random + std::vector wind; + for (auto const value : Environment.wind_state()) + wind.emplace_back(value); + entry.set("wind", numbers_text(wind)); +} + +void apply_weather(record const &Entry) +{ + // the weather is drawn from these: a number which isn't one has no place in it + constexpr auto big{1e9f}; + Entry.get("overcast", Global.Overcast, 0.f, 10.f); + Entry.get("fog", Global.fFogEnd, 0.f, big); + Entry.get("temperature", Global.AirTemperature, -100.f, 100.f); + Environment.compute_weather(); + auto state{Environment.wind_state()}; + if (auto const wind{text_numbers(Entry.text("wind"))}; wind.size() == state.size()) + { + if (std::ranges::all_of(wind, [](double const Value) { return std::isfinite(Value) && std::abs(Value) < 1e9; })) + { + std::ranges::transform(wind, state.begin(), [](double const Value) { return static_cast(Value); }); + Environment.wind_state(state); + } + else + Entry.refuse("wind", "a number of it isn't finite"); + } +} + +// the sources of the traction power: the voltage an event may have set, the load of the step before, the fuses +void capture_power(document &Document) +{ + // what a source which has fed nothing yet says of itself, but for its voltage + std::vector const idle{0.0, 1e-10, 1e-10, 0.0, 0.0, 0.0, 0.0, 0.0}; + for (auto const *source : Powergrid.sequence()) + { + if (source == nullptr) + continue; + auto const state{source->state()}; + // the sources made for single wires are many, and most of them idle + if (source->IsAutogenerated && std::ranges::equal(state.begin() + 1, state.end(), idle.begin(), idle.end())) + continue; + if (auto const name{reference_in(Powergrid, powersource_index(), source)}; false == name.empty()) + Document.add("powersource", name).set("state", numbers_text(state)); + } +} + +bool apply_power(record const &Entry) +{ + auto *source{find_in(Powergrid, Entry.name)}; + if (source == nullptr) + return false; + auto const state{text_numbers(Entry.text("state"))}; + // the last one counts the times the fuse blew + if (false == state.empty() && false == whole_number(state.back(), 0, std::numeric_limits::max()).has_value()) + { + Entry.refuse("state", "the count of its fuse isn't a whole number"); + return true; + } + source->state(state); + return true; +} + +// the engine the simulation draws its random numbers from, as the numbers of its state, eight to a line +void capture_random(document &Document) +{ + std::ostringstream state; + state << Global.random_engine; + std::istringstream numbers{state.str()}; + std::string text; + std::string number; + auto count{0}; + while (numbers >> number) + { + if (false == text.empty()) + text += (count % 8 == 0 ? "\n " : " "); + text += number; + ++count; + } + Document.add("random", "engine").set("state", text); +} + +bool apply_random(record const &Entry) +{ + std::istringstream state{Entry.text("state")}; + auto engine{Global.random_engine}; // NOSONAR: a copy of the simulation's reproducible engine, which nothing secure uses + state >> engine; + if (state.fail()) + return false; + Global.random_engine = engine; + return true; +} + +void capture_memcells(document &Document) +{ + auto const &cells{Memory.sequence()}; + for (std::size_t index{0}; index < cells.size(); ++index) + { + auto const *cell{cells[index]}; + if (cell == nullptr || cell->name().starts_with(scripting_cells)) + continue; + auto &entry{Document.add("memcell", reference(cell->name(), index, Memory.find(cell->name()) == cell))}; + entry.set("text", cell->Text()).set("value1", cell->Value1()).set("value2", cell->Value2()); + if (false == cell->StopCommand()) + { + // the command of the cell isn't waiting to be sent to a train: it's not a command, or it was sent already + entry.set("sent", true); + } + } +} + +bool apply_memcell(record const &Entry) +{ + auto *cell{find_in(Memory, Entry.name)}; + if (cell == nullptr) + return false; + cell->UpdateValues(Entry.text("text", cell->Text()), Entry.value("value1", cell->Value1()), Entry.value("value2", cell->Value2()), + basic_event::flags::text | basic_event::flags::value1 | basic_event::flags::value2); + if (Entry.value("sent", false)) + cell->StopCommandSent(); + return true; +} + +void capture_tracks(document &Document) +{ + // what an event can change of a track: bit 0x100 of iAction marks the damage, 0x200 the speed limit + constexpr int changedbyevents{0x100 | 0x200}; + for (auto *track : Paths.sequence()) + { + if (track != nullptr && track->eType == tt_Switch) + Document.add("switch", track_reference(track)).set("state", track->GetSwitchState()).set("velocity", track->velocity_limit()); + } + for (auto const *track : Paths.sequence()) + { + if (track != nullptr && track->eType != tt_Switch && (track->iAction & changedbyevents) != 0) + Document.add("track", track_reference(track)).set("velocity", track->velocity_limit()).set("damage", track->iDamageFlag); + } +} + +// the crossings of roads: which of the ways through was taken last. the crossing has it as its current segment, by +// which a driver looking ahead measures it +void capture_crossings(document &Document) +{ + for (auto const *track : Paths.sequence()) + { + if (track == nullptr || track->eType != tt_Cross || track->SwitchExtension == nullptr) + continue; + auto const &segments{track->SwitchExtension->Segments}; + for (auto index{0}; index < 6; ++index) + { + if (segments[index] != nullptr && segments[index] == track->Segment) + { + Document.add("crossing", track_reference(track)).set("segment", index); + break; + } + } + } +} + +bool apply_crossing(record const &Entry) +{ + auto *track{find_track(Entry.name)}; + if (track == nullptr || track->eType != tt_Cross || track->SwitchExtension == nullptr) + return false; + auto const index{Entry.value("segment", -1, 0, 5)}; + if (index < 0 || track->SwitchExtension->Segments[index] == nullptr) + return false; + track->Segment = track->SwitchExtension->Segments[index]; + return true; +} + +// the tracks made on the run, each by the track of the scenery it was made at and the end of it. they come back in +// the order they were made in, which gives them their places in the table again +void capture_made_tracks(document &Document) +{ + for (auto const *made : Paths.sequence()) + { + if (made == nullptr || false == made_on_the_run(*made)) + continue; + for (auto const *track : Paths.sequence()) + { + if (track == nullptr || made_on_the_run(*track) || (track->trPrev != made && track->trNext != made)) + continue; + Document.add("madetrack", track_reference(track)).set("end", track->trPrev == made ? 0 : 1); + break; + } + } +} + +bool apply_made_track(record const &Entry) +{ + auto *track{find_track(Entry.name)}; + if (track == nullptr) + return false; + auto end{0}; + if (false == Entry.get("end", end, 0, 1) && Entry.has("end")) + return false; + // made anew unless the scenery has something there by now + if ((end == 0 ? track->trPrev : track->trNext) == nullptr) + track->NullCreate(end); + return true; +} + +bool apply_switch(record const &Entry) +{ + auto *track{find_track(Entry.name)}; + if (track == nullptr || track->eType != tt_Switch) + return false; + if (auto state{0}; Entry.get("state", state, 0, 1) && state != track->GetSwitchState()) + track->Switch(state); + if (auto velocity{0.0}; Entry.get("velocity", velocity, -big_velocity, big_velocity)) + track->velocity_limit(velocity); + return true; +} + +bool apply_track(record const &Entry) +{ + auto *track{find_track(Entry.name)}; + if (track == nullptr) + return false; + if (auto velocity{0.0}; Entry.get("velocity", velocity, -big_velocity, big_velocity)) + track->velocity_limit(velocity); + Entry.get("damage", track->iDamageFlag); + return true; +} + +void capture_events(document &Document) +{ + auto const now{Timer::GetTime()}; + for (auto const *queued{Events.begin()}; queued != nullptr; queued = queued->m_next) + { + auto &entry{Document.add("event", queued->m_name)}; + if (auto const sibling{event_sibling(queued)}; sibling != 0) + entry.set("sibling", sibling); + // when it runs, by the clock of the simulation; the seconds left are for the reader of the file + entry.set("at", queued->m_launchtime).set("left", queued->m_launchtime - now); + if (queued->m_activator != nullptr) + entry.set("activator", vehicle_reference(queued->m_activator)); + } +} + +bool apply_event(record const &Entry) +{ + auto sibling{0}; + if (false == Entry.get("sibling", sibling, 0, most_siblings) && Entry.has("sibling")) + return false; + auto *found{find_event(Entry.name, sibling)}; + if (found == nullptr) + return false; + // without the time it ran at, the seconds it had left count from now. the queue is kept in the order of the times, + // which a time that isn't a number has none in + auto const now{Timer::GetTime()}; + auto launchtime{now + Entry.value("left", 0.0, -longest_wait, longest_wait)}; + if (false == Entry.get("at", launchtime, now - longest_wait, now + longest_wait) && Entry.has("at")) + return false; + auto const *activator{Entry.has("activator") ? find_vehicle(Entry.text("activator")) : nullptr}; + return Events.restore_queued(found, activator, launchtime); +} + +void capture_launchers(document &Document) +{ + auto const launchers{Events.launchers()}; + std::map> named; + for (auto const *launcher : launchers) + { + if (launcher != nullptr) + ++named[launcher->name()]; + } + for (std::size_t index{0}; index < launchers.size(); ++index) + { + auto const *launcher{launchers[index]}; + // a launcher which hasn't counted any time yet is as the scenery makes it + if (launcher == nullptr || launcher->timer() == 0.0) + continue; + Document.add("launcher", reference(launcher->name(), index, named[launcher->name()] == 1 && launcher->name() != "none")).set("timer", launcher->timer()); + } +} + +bool apply_launcher(record const &Entry, std::vector const &Launchers) +{ + TEventLauncher *launcher{nullptr}; + if (auto const index{reference_index(Entry.name)}; index.has_value()) + launcher = (*index < Launchers.size() ? Launchers[*index] : nullptr); + else if (auto const lookup{std::ranges::find_if(Launchers, [&](TEventLauncher const *Item) { return Item != nullptr && Item->name() == Entry.name; })}; + lookup != Launchers.end()) + launcher = *lookup; + if (launcher == nullptr) + return false; + launcher->timer(Entry.value("timer", launcher->timer(), 0.0, longest_wait)); + return true; +} + +// the models whose lights the events of the scenery switch: the signals, mostly +std::vector switched_models() +{ + std::vector models; + std::unordered_set seen; + for (auto const *scenery_event : Events.sequence()) + { + if (dynamic_cast(scenery_event) == nullptr) + continue; + for (auto *node : scenery_event->target_nodes()) + { + if (seen.emplace(node).second) + models.emplace_back(static_cast(node)); + } + } + return models; +} + +void capture_lights(document &Document) +{ + for (auto *model : switched_models()) + { + auto const name{reference_in(Instances, model_index(), static_cast(model))}; + if (name.empty()) + continue; + record entry{"model", name}; + for (auto light{0}; light < iMaxNumLights; ++light) + { + if (auto const state{model->LightGet(light)}; state.has_value()) + entry.set(std::format("light{}", light), std::get<0>(*state)); + } + if (false == entry.fields.empty()) + Document.records.emplace_back(std::move(entry)); + } +} + +bool apply_lights(record const &Entry) +{ + auto *model{find_in(Instances, Entry.name)}; + if (model == nullptr) + return false; + for (auto light{0}; light < iMaxNumLights; ++light) + { + if (auto state{0.f}; Entry.get(std::format("light{}", light), state, -1e6f, 1e6f)) + model->LightSet(light, state); + } + return true; +} + +void capture_vehicles(document &Document) +{ + for (auto const *vehicle : Vehicles.sequence()) + { + if (vehicle == nullptr || vehicle->physics == nullptr) + continue; + vehicle->snapshot_save(Document.add("vehicle", vehicle_reference(vehicle))); + } +} + +// the couplings as the vehicles have them now +std::vector current_couplings(std::unordered_map const &Owners) +{ + std::vector links; + for (auto const *vehicle : Vehicles.sequence()) + { + if (vehicle == nullptr || vehicle->physics == nullptr) + continue; + for (auto const side : VehicleEnds) + { + auto const &joint{vehicle->physics->Couplers[side]}; + auto const owner{joint.Connected != nullptr ? Owners.find(joint.Connected) : Owners.end()}; + if (owner == Owners.end() || joint.CouplingFlag.Empty()) + continue; + links.emplace_back(vehicle_reference(vehicle), NumberOf(side), vehicle_reference(owner->second), joint.ConnectedNr, joint.CouplingFlag.Bits()); + } + } + return links; +} + +static_assert(coupling_flags_mask == (static_cast(Coupling::power3x400v) << 1) - 1, "the flags a snapshot takes are every bit of the coupling enum"); + +void part(TDynamicObject &Vehicle, int const End) +{ + auto &joint{Vehicle.physics->Couplers[End]}; + if (joint.Connected != nullptr && joint.ConnectedNr >= 0 && joint.ConnectedNr < 2) + { + auto &other{joint.Connected->Couplers[joint.ConnectedNr]}; + other.Connected = nullptr; + other.ConnectedNr = -1; + other.CouplingFlag = CouplingSet{}; + } + joint.Connected = nullptr; + joint.ConnectedNr = -1; + joint.CouplingFlag = CouplingSet{}; +} + +// whether the vehicle is there, with its physics +bool with_physics(TDynamicObject const *Vehicle) +{ + return Vehicle != nullptr && Vehicle->physics != nullptr; +} + +// the flags of the link as the two vehicles can have them now: no control between an electric and a diesel locomotive +// (eu07/maszyna#520), whatever an edited file or a vehicle definition changed since the snapshot says +int compatible_flags(TDynamicObject const &Vehicle, TDynamicObject const &Other, coupling_link const &Link) +{ + return Vehicle.physics->CompatibleCoupling(EndOf(Link.end), *Other.physics, EndOf(Link.otherend), CouplingSet::FromBits(Link.flags)).Bits(); +} + +// the links of the plan which change the kind of a coupling the vehicles keep +void change_couplings(std::vector const &Links) +{ + for (auto const &link : Links) + { + auto const *vehicle{find_vehicle(link.vehicle)}; + auto const *other{find_vehicle(link.other)}; + if (false == with_physics(vehicle) || false == with_physics(other)) + continue; + auto const flags{compatible_flags(*vehicle, *other, link)}; + if (flags == 0) + continue; + vehicle->physics->Couplers[link.end].CouplingFlag = CouplingSet::FromBits(flags); + other->physics->Couplers[link.otherend].CouplingFlag = CouplingSet::FromBits(flags); + } +} + +// the links of the plan to make. returns: how many couldn't be made +int join_couplings(std::vector const &Links) +{ + auto failed{0}; + for (auto const &link : Links) + { + auto *vehicle{find_vehicle(link.vehicle)}; + auto *other{find_vehicle(link.other)}; + if (false == with_physics(vehicle) || false == with_physics(other) || + false == vehicle->physics->Attach(link.end, link.otherend, other->physics, CouplingSet::FromBits(link.flags), true, false)) + { + ++failed; + continue; + } + // the vehicles joined in the snapshot, whatever the scenery made of their couplers, as far as they can be + auto const flags{compatible_flags(*vehicle, *other, link)}; + vehicle->physics->Couplers[link.end].CouplingFlag = CouplingSet::FromBits(flags); + other->physics->Couplers[link.otherend].CouplingFlag = CouplingSet::FromBits(flags); + } + return failed; +} + +void report_couplings(coupling_plan const &Plan, int const Failed, apply_summary &Summary) +{ + if (false == Plan.part.empty() || false == Plan.join.empty() || false == Plan.change.empty()) + Summary.remarks.emplace_back(std::format("couplings: {} parted, {} joined, {} changed", Plan.part.size(), static_cast(Plan.join.size()) - Failed, Plan.change.size())); + if (Failed != 0 || false == Plan.missing.empty()) + Summary.notes.emplace_back(std::format("couplings: {} of the snapshot couldn't be made, {} are to vehicles the scenery doesn't have or which stay where it put them", + Failed, Plan.missing.size())); + if (false == Plan.refused.empty()) + { + Summary.notes.emplace_back(std::format("couplings: {} of the snapshot refused, they'd close a ring of vehicles; the first one {} {} to {} {}", Plan.refused.size(), + Plan.refused.front().vehicle, Plan.refused.front().end, Plan.refused.front().other, Plan.refused.front().otherend)); + } +} + +// each vehicle knows the one coupled to it as its neighbour at that end +void find_neighbours(std::unordered_map const &Owners) +{ + for (auto *vehicle : Vehicles.sequence()) + { + if (vehicle == nullptr || vehicle->physics == nullptr) + continue; + for (auto const side : VehicleEnds) + { + auto const &joint{vehicle->physics->Couplers[side]}; + auto &neighbour{vehicle->physics->Neighbours[side]}; + neighbour = neighbour_data(); + if (auto const owner{joint.Connected != nullptr ? Owners.find(joint.Connected) : Owners.end()}; owner != Owners.end()) + { + neighbour.vehicle = owner->second; + neighbour.vehicle_end = joint.ConnectedNr; + } + } + } + for (auto *vehicle : Vehicles.sequence()) + { + if (vehicle != nullptr && vehicle->physics != nullptr && vehicle->bEnabled) + vehicle->update_neighbours(); + } +} + +// the vehicles of the snapshot which stay as the scenery made them: the ones it couldn't put where the snapshot has +// them, and the road traffic waiting at its spawn point +using vehicle_set = std::unordered_set; + +// parts and joins the vehicles of the scenery until they're coupled the way the snapshot has them. the vehicles Left +// aren't coupled to the ones put where the snapshot has them: the links to them are missing +void apply_couplings(std::vector const &Entries, vehicle_set const &Left, apply_summary &Summary) +{ + std::unordered_map owners; + std::vector present; + for (auto *vehicle : Vehicles.sequence()) + { + if (vehicle == nullptr || vehicle->physics == nullptr) + continue; + owners.emplace(vehicle->physics, vehicle); + if (false == Left.contains(vehicle)) + present.emplace_back(vehicle_reference(vehicle)); + } + std::vector entries; + std::ranges::copy_if(Entries, std::back_inserter(entries), [&Left](record const *Entry) { return false == Left.contains(find_vehicle(Entry->name)); }); + auto const plan{plan_couplings(current_couplings(owners), read_couplings(entries), present)}; + + // the vehicles of the links are of the scenery (Present), with their physics + for (auto const &link : plan.part) + { + if (auto *vehicle{find_vehicle(link.vehicle)}; with_physics(vehicle)) + part(*vehicle, link.end); + } + change_couplings(plan.change); + auto const failed{join_couplings(plan.join)}; + report_couplings(plan, failed, Summary); + find_neighbours(owners); +} + +// a vehicle the scenery keeps out of the simulation until its time comes: a car a road spawn point (roadpoint_node) made +// as the scenery loaded, which waits off the road to be put on it. the snapshot doesn't bring one which was on the +// road back: the spawn point puts its cars on the road and takes them back to its set, and a car put there by the +// snapshot would be one the point doesn't know is out +bool waits_off_the_road(TDynamicObject const &Vehicle) +{ + return false == Vehicle.bEnabled && Vehicle.MyTrack == nullptr; +} + +// the vehicles of the snapshot's entries +struct vehicle_entries { + std::vector> known; // to put where the snapshot has them + vehicle_set listed; // every vehicle of the scenery the snapshot has + vehicle_set left; // the ones of them left as the scenery made them +}; + +vehicle_entries read_vehicles(std::vector const &Entries, apply_summary &Summary) +{ + vehicle_entries result; + auto traffic{0}; + for (auto const *entry : Entries) + { + auto *vehicle{find_vehicle(entry->name)}; + if (vehicle == nullptr || vehicle->physics == nullptr) + { + ++Summary.skipped; + Summary.notes.emplace_back(std::format("vehicle {} of the snapshot isn't in the scenery", entry->name)); + continue; + } + // a vehicle placed twice would have its axles counted out of their sections twice + if (false == result.listed.emplace(vehicle).second) + { + ++Summary.skipped; + Summary.notes.emplace_back(std::format("vehicle {} has more than one entry in the snapshot, the first one is taken", entry->name)); + continue; + } + if (false == waits_off_the_road(*vehicle)) + { + result.known.emplace_back(vehicle, entry); + continue; + } + // off the road in the snapshot too, or a car of the road traffic which isn't brought back + result.left.emplace(vehicle); + if (entry->value("removed", false)) + { + ++Summary.entries; + continue; + } + ++Summary.skipped; + ++traffic; + } + if (traffic != 0) + Summary.notes.emplace_back(std::format("{} cars of the road traffic of the snapshot aren't put back, their spawn points send cars anew", traffic)); + return result; +} + +// puts the vehicles of the snapshot in place. returns: the vehicles of the snapshot left as the scenery made them +vehicle_set apply_vehicles(document const &Document, apply_summary &Summary) +{ + auto const entries{Document.of("vehicle")}; + auto vehicles{read_vehicles(entries, Summary)}; + auto const &known{vehicles.known}; + auto const &listed{vehicles.listed}; + auto &left{vehicles.left}; + // where the vehicles are, then what they're coupled to, then what they're doing. a vehicle which can't be put where + // the snapshot has it is left out of the rest: coupled to vehicles put elsewhere, it'd be torn off them + auto misplaced{0}; + for (auto const &[vehicle, entry] : known) + { + if (false == vehicle->snapshot_place(*entry)) + { + ++misplaced; + left.emplace(vehicle); + } + } + if (misplaced != 0) + Summary.notes.emplace_back(std::format("{} vehicles of the snapshot couldn't be put where it has them, they stay as the scenery made them", misplaced)); + apply_couplings(entries, left, Summary); + for (auto const &[vehicle, entry] : known) + { + if (left.contains(vehicle)) + { + ++Summary.skipped; + continue; + } + vehicle->snapshot_load(*entry); + ++Summary.entries; + } + // the vehicles the snapshot doesn't know stay as the scenery made them + if (auto const unknown{std::ranges::count_if(Vehicles.sequence(), [&](TDynamicObject const *Vehicle) { return Vehicle != nullptr && false == listed.contains(Vehicle); })}; + unknown != 0) + Summary.notes.emplace_back(std::format("{} vehicles of the scenery aren't in the snapshot, they stay as the scenery made them", unknown)); + return std::move(left); +} + +// a hash of the text of a name, which finds a string key by any kind of string +struct name_hash { + using is_transparent = void; + std::size_t operator()(std::string_view const Name) const noexcept { return std::hash{}(Name); } +}; + +using isolated_map = std::unordered_map>; + +// the isolated sections, by their names: the scenery makes one for each name (TIsolated::Find()) +isolated_map isolated_sections() +{ + isolated_map sections; + for (auto *section{TIsolated::Root()}; section != nullptr; section = section->Next()) + sections.try_emplace(section->asName, section); + return sections; +} + +// how many axles each isolated section counts. in a running simulation it's the vehicles on its tracks, but not only: +// the vehicles of a consist which follow its first one out through a portal leave the simulation where they are, and +// stay counted there. a snapshot keeps the counts as they are +void capture_isolated(document &Document) +{ + for (auto *section{TIsolated::Root()}; section != nullptr; section = section->Next()) + Document.add("isolated", section->asName).set("axles", section->axles()); +} + +// how many axles more or fewer each isolated section counts than the snapshot has, for the axles of the vehicles left as +// the scenery made them: they stand where the scenery put them, not where the snapshot has them +using section_counts = std::unordered_map; + +// counts Axles in every section of the Track and in the sections those pass their counts to (TIsolated::Modify()) +void count_axles(TTrack const *Track, int const Axles, section_counts &Counts) +{ + if (Track == nullptr) + return; + for (auto *section : Track->Isolated) + { + for (; section != nullptr; section = section->parent()) + Counts[section] += Axles; + } +} + +// the axles of the Left vehicles: counted in the sections they stand in now, and out of the ones the snapshot has them in +section_counts left_axles(document const &Document, vehicle_set const &Left) +{ + section_counts counts; + if (Left.empty()) + return counts; + vehicle_set seen; + for (auto const *entry : Document.of("vehicle")) + { + // the first entry of a vehicle is the one taken (read_vehicles()) + auto const *vehicle{find_vehicle(entry->name)}; + if (vehicle == nullptr || false == Left.contains(vehicle) || false == seen.emplace(vehicle).second) + continue; + // a car off the road waits in its spawn point's set, on no track + if (vehicle->MyTrack != nullptr) + { + count_axles(vehicle->Axle0.GetTrack(), 1, counts); + count_axles(vehicle->Axle1.GetTrack(), 1, counts); + } + if (false == entry->value("removed", false)) + { + count_axles(find_track(entry->text("track0")), -1, counts); + count_axles(find_track(entry->text("track1")), -1, counts); + } + } + std::erase_if(counts, [](auto const &Count) { return Count.second == 0; }); + return counts; +} + +// sets the counts of the isolated sections to those of the snapshot, after the vehicles are put on their tracks: which +// counts them anew. a section whose count comes out other than the snapshot has is told of. the axles of the vehicles +// left as the scenery made them (Left) are counted where they stand instead of where the snapshot has them. returns: +// the sections whose counts that changed +std::vector apply_isolated(document const &Document, section_counts const &Left, apply_summary &Summary) +{ + std::vector moved; + auto const entries{Document.of("isolated")}; + if (entries.empty()) + return moved; + auto const sections{isolated_sections()}; + auto missing{0}; + auto differing{0}; + std::string example; + for (auto const *entry : entries) + { + auto const lookup{sections.find(entry->name)}; + if (lookup == sections.end()) + { + ++Summary.skipped; + ++missing; + continue; + } + // a count beyond any the vehicles of a scenery make + auto axles{0}; + if (false == entry->get("axles", axles, -1000000, 1000000)) + { + ++Summary.skipped; + continue; + } + auto *section{lookup->second}; + if (auto const left{Left.find(section)}; left != Left.end()) + { + // no fewer than none: a snapshot taken in another scenery can name a track the vehicle wasn't on + axles = std::max(axles + left->second, 0); + moved.emplace_back(section); + } + if (section->axles() != axles) + { + if (differing++ == 0) + example = std::format("{}: {} axles, the snapshot has {}", section->asName, section->axles(), axles); + section->axles(axles); + } + ++Summary.entries; + } + if (missing != 0) + Summary.notes.emplace_back(std::format("{} isolated sections of the snapshot aren't in the scenery", missing)); + if (false == moved.empty()) + Summary.notes.emplace_back(std::format("{} isolated sections count the axles of vehicles left where the scenery put them instead of where the snapshot has them; the first one {}", + moved.size(), moved.front()->asName)); + // not a fault as such: the vehicles a consist leaves behind as it goes through a portal stay counted where they were + if (differing != 0) + Summary.remarks.emplace_back(std::format("{} isolated sections counted other axles with the vehicles placed than the snapshot has, set to its counts; the first one {}", + differing, example)); + return moved; +} + +// the cells of the sections whose counts the left vehicles changed say whether they're taken by the count, not by the +// snapshot: as TIsolated::Modify() writes them, the lowest bits of the second value +void apply_isolated_cells(std::vector const &Sections) +{ + for (auto const *section : Sections) + { + if (section->pMemCell == nullptr) + continue; + auto const value{static_cast(section->pMemCell->Value2())}; + auto const busy{section->axles() > 0}; + if (busy != ((value & 1) != 0)) + section->pMemCell->UpdateValues("", 0, busy ? value | 1 : value & ~0xFF, basic_event::flags::value2); + } +} + +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; +} + +// the drivers of the snapshot, in the vehicles it has them in. the vehicles Left keep the drivers the scenery gave them +void apply_drivers(document const &Document, vehicle_set const &Left, 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 (Left.contains(vehicle)) + { + ++Summary.skipped; + continue; + } + if (vehicle == nullptr) + { + ++Summary.skipped; + ++missing; + continue; + } + if (vehicle->Mechanik == nullptr) + { + if (auto *spare{spare_driver(vehicle, taken)}; spare != nullptr) + spare->MoveTo(vehicle); + } + if (vehicle->Mechanik == nullptr) + { + ++Summary.skipped; + ++missing; + continue; + } + vehicle->Mechanik->snapshot_load(*entry, [&Left](TDynamicObject const *Vehicle) { return Left.contains(Vehicle); }); + ++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)); + std::unordered_set deleted; + for (auto *vehicle : Vehicles.sequence()) + { + if (vehicle == nullptr || vehicle->Mechanik == nullptr || taken.contains(vehicle) || false == known.contains(vehicle) || Left.contains(vehicle)) + continue; + if (vehicle->Mechanik->AIControllFlag()) + { + deleted.emplace(vehicle->Mechanik); + SafeDelete(vehicle->Mechanik); + } + } + // the other vehicles of their consists had them in charge: those the snapshot has get their owners anew + // (apply_owners()), but no vehicle is left pointing at a driver who's no more + for (auto *vehicle : Vehicles.sequence()) + { + if (vehicle != nullptr && deleted.contains(vehicle->ctOwner)) + vehicle->ctOwner = nullptr; + } +} + +// the driver in charge of each vehicle; after the drivers are where the snapshot has them. the vehicles Left keep +// theirs +void apply_owners(document const &Document, vehicle_set const &Left) +{ + for (auto const *entry : Document.of("vehicle")) + { + auto *vehicle{find_vehicle(entry->name)}; + if (vehicle == nullptr || Left.contains(vehicle)) + continue; + // a vehicle gone from the simulation has nobody in charge + if (entry->value("removed", false)) + { + vehicle->ctOwner = nullptr; + continue; + } + if (false == entry->has("first")) + continue; + auto const *owner{find_vehicle(entry->text("owner"))}; + vehicle->ctOwner = (owner != nullptr ? owner->Mechanik : nullptr); + } +} + +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. the cab the player is in is the one the + // vehicle has occupied, which its entry keeps (caboccupied); a file written before has it here too, as cab, unread + Document.add("player", vehicle->name()); +} + +// tells whether the snapshot was taken in the scenery it's being put over. returns: false if the scenery isn't what it +// was then, which the snapshot isn't put over unless that's forced +bool check_scenery(record const &Header, bool const Force, apply_summary &Summary) +{ + if (auto const scenery{Header.text("scenery")}; scenery != Global.SceneryFile) + Summary.notes.emplace_back(std::format(R"(the snapshot was taken in scenery "{}", this one is "{}")", scenery, Global.SceneryFile)); + if (auto const seed{Header.value("seed", Global.random_seed)}; seed != Global.random_seed) + { + Summary.notes.emplace_back( + std::format("the snapshot was taken with random seed {}, the scenery was loaded with {}: what it draws at random while it loads may differ", seed, + Global.random_seed)); + } + record now; + capture_fingerprint(now); + auto const changed{fingerprint_changes(Header, now)}; + if (changed.empty()) + return true; + // most tracks have no name and are named by their place: a track added early in a file of the scenery moves the + // places of all after it, and the vehicles would be put on other tracks than they were on + Summary.notes.emplace_back(std::format("the scenery isn't what it was when the snapshot was taken: {}. things named by their place in the scenery " + "(\"#12\") may be other ones now", + changed)); + if (Force) + return true; + Summary.notes.emplace_back("the snapshot isn't loaded (--load-snapshot-force loads it all the same)"); + return false; +} + +// applies the entries of a type, each by the function given, and counts how it went +template void apply_each(document const &Document, std::string_view const Type, apply_summary &Summary, Function_ const Function) +{ + auto missing{0}; + std::string example; + for (auto const *entry : Document.of(Type)) + { + if (Function(*entry)) + { + ++Summary.entries; + continue; + } + ++Summary.skipped; + if (missing++ == 0) + example = entry->name; + } + if (missing != 0) + Summary.notes.emplace_back(std::format("{} {} entries of the snapshot have nothing in the scenery to go to, the first one is {}", missing, Type, example)); +} + +// the snapshots asked for on the command line +struct schedule { + command_line requests; + std::optional pending; // the one to load, read ahead for its header + std::size_t written{0}; // how many of the saves are done +}; + +schedule &requested() +{ + static schedule instance; + return instance; +} + +} // namespace + +std::string track_reference(TTrack const *Track) +{ + return reference_in(Paths, track_index(), Track); +} + +TTrack *find_track(std::string const &Reference) +{ + return Reference.empty() ? nullptr : find_in(Paths, Reference); +} + +std::string vehicle_reference(TDynamicObject const *Vehicle) +{ + return reference_in(Vehicles, vehicle_index(), Vehicle); +} + +TDynamicObject *find_vehicle(std::string const &Reference) +{ + return Reference.empty() ? nullptr : find_in(Vehicles, Reference); +} + +int event_sibling(basic_event const *Event) +{ + auto index{0}; + for (auto const *sibling{Events.FindEvent(Event->m_name)}; sibling != nullptr && sibling != Event; sibling = sibling->m_sibling) + ++index; + return index; +} + +basic_event *find_event(std::string const &Name, int const Sibling) +{ + auto *found{Events.FindEvent(Name)}; + auto index{0}; + while (index < Sibling && found != nullptr) + { + found = found->m_sibling; + ++index; + } + return found; +} + +document capture() +{ + document result; + capture_header(result); + capture_time(result); + capture_weather(result); + capture_memcells(result); + capture_tracks(result); + capture_crossings(result); + capture_made_tracks(result); + capture_power(result); + capture_events(result); + capture_launchers(result); + capture_lights(result); + capture_vehicles(result); + capture_isolated(result); + capture_drivers(result); + capture_player(result); + // the long one last, out of the way of whoever reads the file + capture_random(result); + // a file cut short between two entries is told by this + result.records.front().set("entries", result.records.size()); + return result; +} + +apply_summary apply(document const &Document, bool const Force) +{ + apply_summary summary; + auto const *header{Document.header()}; + if (header == nullptr) + { + summary.refused = true; + summary.notes.emplace_back("not a snapshot, nothing was loaded from it"); + return summary; + } + if (false == check_scenery(*header, Force, summary)) + { + summary.refused = true; + return summary; + } + + // nothing in the scenery reacts to the saved state being put back: the vehicles moved to their places don't + // set off the events of the tracks, the sections they free and take don't change their signals + Events.suspend(true); + + if (auto timer{0.0}; header->get("timer", timer, 0.0, longest_wait)) + Timer::set_time(timer); + apply_each(Document, "time", summary, apply_time); + apply_each(Document, "weather", summary, [](record const &Entry) { + apply_weather(Entry); + return true; + }); + // the switches first: a vehicle is put on the path a switch is set to + apply_each(Document, "switch", summary, apply_switch); + apply_each(Document, "track", summary, apply_track); + apply_each(Document, "crossing", summary, apply_crossing); + apply_each(Document, "madetrack", summary, apply_made_track); + apply_each(Document, "powersource", summary, apply_power); + auto const left{apply_vehicles(Document, summary)}; + // the sections the vehicles were counted in and out of as they were put on their tracks + auto const moved{apply_isolated(Document, left_axles(Document, left), summary)}; + apply_drivers(Document, left, summary); + apply_owners(Document, left); + // the cells after the vehicles, whose sections write to their cells as they're taken and freed + apply_each(Document, "memcell", summary, apply_memcell); + apply_isolated_cells(moved); + auto const launchers{Events.launchers()}; + apply_each(Document, "launcher", summary, [&launchers](record const &Entry) { return apply_launcher(Entry, launchers); }); + apply_each(Document, "model", summary, apply_lights); + + Events.suspend(false); + // the queue of the scenery just loaded gives way to the saved one + if (false == Document.of("event").empty() || header->has("timer")) + { + Events.clear_queue(); + apply_each(Document, "event", summary, apply_event); + } + // last, whatever was drawn at random on the way here doesn't count + apply_each(Document, "random", summary, apply_random); + // the values of the file which weren't taken + for (auto &refusal : take_refusals()) + summary.notes.emplace_back(std::move(refusal)); + return summary; +} + +bool save(std::string const &File) +{ + auto const document{capture()}; + // to a file of its own first, which takes the place of the one asked for once it's whole + if (auto const error{write_file(File, document)}; false == error.empty()) + { + ErrorLog(std::format("snapshot: {}", error)); + return false; + } + WriteLog(std::format("snapshot: the simulation at {:.2f} s saved to \"{}\", {} entries", Timer::GetTime(), File, document.records.size())); + return true; +} + +std::string save_now() +{ + auto const &time{Time.data()}; + auto scenery{Global.SceneryFile}; + if (auto const extension{scenery.rfind('.')}; extension != std::string::npos) + scenery.erase(extension); + std::ranges::replace_if(scenery, [](char const Character) { return Character == '/' || Character == '\\' || Character == ':'; }, '_'); + // the folder eu07.ini names; the game folder may be one the game can't write to + auto const folder{Global.snapshot_dir.empty() ? std::string{"snapshots"} : Global.snapshot_dir}; + std::error_code error; + std::filesystem::create_directories(folder, error); + // two saves in the same second of the simulation (while it's paused, say) don't write over each other + auto const file{free_file(std::format("{}/{}_{:04}-{:02}-{:02}_{:02}-{:02}-{:02}.snapshot", folder, scenery, time.wYear, time.wMonth, time.wDay, time.wHour, + time.wMinute, time.wSecond))}; + auto const saved{save(file)}; + ui::Transcripts.AddLine(saved ? std::format("Snapshot saved: {}", file) : std::format("Snapshot not saved, {} can't be written (see errors.txt)", file), 0.f, 10.f, + false); + return saved ? file : std::string{}; +} + +void request(command_line const &Requests) +{ + auto &schedule{requested()}; + schedule.requests = Requests; + // the earliest first + std::ranges::stable_sort(schedule.requests.saves, {}, &command_line::save_request::time); + schedule.written = 0; + schedule.pending.reset(); + if (false == Requests.load.empty()) + schedule.pending = load(Requests.load); +} + +// the snapshot to load, if it's to be used +document const *accepted_pending() +{ + auto const &schedule{requested()}; + return schedule.pending.has_value() && accepted(*schedule.pending, schedule.requests.force) ? &*schedule.pending : nullptr; +} + +std::optional requested_seed() +{ + auto const *pending{accepted_pending()}; + auto const *header{pending != nullptr ? pending->header() : nullptr}; + if (std::uint32_t seed{0}; header != nullptr && header->get("seed", seed)) + return seed; + return std::nullopt; +} + +std::string requested_player_vehicle() +{ + auto const *pending{accepted_pending()}; + if (pending == nullptr) + return {}; + auto const players{pending->of("player")}; + return players.empty() ? std::string{} : players.front()->name; +} + +void start() +{ + auto &schedule{requested()}; + auto loaded{false}; + if (schedule.pending.has_value()) + { + auto const document{std::move(*schedule.pending)}; + schedule.pending.reset(); + for (auto const &problem : document.problems) + ErrorLog(std::format("snapshot: \"{}\": {}", schedule.requests.load, problem)); + for (auto const &warning : document.warnings) + ErrorLog(std::format("snapshot: \"{}\": {}", schedule.requests.load, warning)); + // a damaged file would put back part of the world, and leave the rest as the scenery makes it + apply_summary summary; + if (accepted(document, schedule.requests.force)) + { + if (false == document.problems.empty()) + ErrorLog(std::format("snapshot: \"{}\" is loaded as far as it could be read, --load-snapshot-force says so", schedule.requests.load)); + summary = apply(document, schedule.requests.force); + } + else + { + summary.refused = true; + summary.notes.emplace_back(std::format("\"{}\" isn't loaded: it's damaged (--load-snapshot-force loads what can be read of it)", schedule.requests.load)); + } + for (auto const ¬e : summary.notes) + ErrorLog(std::format("snapshot: {}", note)); + for (auto const &remark : summary.remarks) + WriteLog(std::format("snapshot: {}", remark)); + loaded = (false == summary.refused); + if (false == loaded && Global.test.enabled) + { + // a test run from a snapshot is no test without it + test().finish(test_result::error, "the snapshot to load is damaged, missing or of another scenery"); + } + if (loaded) + { + // the simulation goes on, it doesn't start: with nobody to wait for in a cab the drivers and the scenery + // take the first frame as any other, the way they took it in the run the snapshot comes from + if (Global.local_start_vehicle == "ghostview") + { + // the cells the scripts read the weather and the time from are made by the first, not yet ready, pass. + // the run the snapshot comes from made them in its first frame; made here, the numbers their making + // draws at random don't count + auto const engine{Global.random_engine}; // NOSONAR: a copy of the simulation's reproducible engine, which nothing secure uses + State.update_scripting_interface(); + Global.random_engine = engine; + is_ready = true; + } + WriteLog(std::format("snapshot: \"{}\" loaded, the simulation goes on from {:.2f} s: {} entries put in place, {} left out", schedule.requests.load, + Timer::GetTime(), summary.entries, summary.skipped)); + } + } + // a snapshot asked for at the very time the simulation starts from + update(); + if (loaded && Timer::GetDeltaTime() == 0.0) + { + // the main loop draws a number after every frame of the simulation (eu07_application::generate_sync()), but + // not after this start. the snapshot was taken at the end of a frame, before that draw: it's made up for here + Random(1.0, 100.0); + } +} + +void update() +{ + auto &schedule{requested()}; + auto const &saves{schedule.requests.saves}; + // a frame is never short of the time asked for by the rounding of its steps alone + constexpr double margin{1e-6}; + while (schedule.written < saves.size() && Timer::GetTime() >= saves[schedule.written].time - margin) + { + save(saves[schedule.written].file); + ++schedule.written; + } +} + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshotworld.h b/simulation/simulationsnapshotworld.h new file mode 100644 index 000000000..d2df9ecbd --- /dev/null +++ b/simulation/simulationsnapshotworld.h @@ -0,0 +1,73 @@ +/* +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 "simulation/simulationsnapshot.h" + +#include +#include + +class TDynamicObject; +class TTrack; +class basic_event; + +// the simulation snapshot of the running game: taken from the scenery as it is, and put over a scenery just loaded. +// the text of the file is in simulationsnapshot.h; the parts kept by a vehicle and by its driver are with those classes +// (TDynamicObject::snapshot_save() and the like, defined in simulationsnapshotvehicle.cpp and simulationsnapshotdriver.cpp) +namespace simulation::snapshot { + +// the state of the simulation as a document +document capture(); + +// how putting a snapshot over the scenery went +struct apply_summary { + int entries{0}; // put in place + int skipped{0}; // of the snapshot, with nothing in the scenery to put them on + std::vector notes; // what went other than the snapshot has it, for the user to know of + std::vector remarks; // what was done on the way, for the log + bool refused{false}; // the snapshot wasn't used at all +}; + +// puts the state of the document over the scenery, which is expected to be loaded and initialized, with the simulation +// not yet running. what the snapshot doesn't hold stays as the scenery made it. a snapshot taken in a scenery which +// isn't the same as this one (its fingerprint differs) is refused, unless Force says to put it over it all the same +apply_summary apply(document const &Document, bool Force = false); + +// writes a snapshot of the simulation to the file. returns: true on success +bool save(std::string const &File); +// writes one to the folder of the snapshots (snapshotsdir of eu07.ini, "snapshots" by default), named after the scenery +// and the time of the simulation, with a number added if that file is there already; for the player, who asks for it +// with a key (the snapshotsave command), and is told on the screen where it went. returns: the file written, empty if +// it couldn't be +std::string save_now(); + +// the snapshots asked for on the command line (parse_command_line()): one to load when the simulation starts, and the +// ones to write when its time comes +void request(command_line const &Requests); +// the seed the snapshot to be loaded was taken with, if there's one to load and it tells: the scenery loads the same +// way again only with the seed it was loaded with then +std::optional requested_seed(); +// the vehicle the player was in when the snapshot to be loaded was taken, if it tells +std::string requested_player_vehicle(); +// called when the simulation is about to start: loads the snapshot asked for +void start(); +// called at the end of each frame of the simulation: writes the snapshots due +void update(); + +// names of the things of the scenery, as the entries of a snapshot give them (reference()) +std::string track_reference(TTrack const *Track); +TTrack *find_track(std::string const &Reference); +std::string vehicle_reference(TDynamicObject const *Vehicle); +TDynamicObject *find_vehicle(std::string const &Reference); +// an event is named by its name and, among the events sharing that name, its place +int event_sibling(basic_event const *Event); +basic_event *find_event(std::string const &Name, int Sibling); + +} // namespace simulation::snapshot diff --git a/simulation/simulationtestrules.cpp b/simulation/simulationtestrules.cpp index 6635d0808..f5d39071e 100644 --- a/simulation/simulationtestrules.cpp +++ b/simulation/simulationtestrules.cpp @@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "simulation/simulationtestrules.h" +#include "simulation/simulationsnapshot.h" + #include #include #include @@ -28,11 +30,6 @@ std::string reason_suffix(std::string_view const Reason) return Reason.empty() ? std::string() : std::format(" ({})", Reason); } -// options of the simulator which take a value, see eu07_application::init_settings() -bool takes_value(std::string_view const Option) -{ - return Option == "-s" || Option == "-v" || Option == "-seed" || Option == "-ini"; -} // a number of seconds given to Option, at Index of Arguments; the index is moved past the value std::optional option_seconds(std::span const Arguments, std::size_t &Index) @@ -97,9 +94,10 @@ test_command_line parse_test_command_line(std::span const Arg else result.wall_timeout = seconds; } - else if (takes_value(option)) + else { - ++i; + // the values of the other options, see eu07_application::init_settings() + i += static_cast(snapshot::option_value_count(option)); } } return result; diff --git a/simulation/simulationtime.cpp b/simulation/simulationtime.cpp index 6f9f87a5f..14099b714 100644 --- a/simulation/simulationtime.cpp +++ b/simulation/simulationtime.cpp @@ -193,6 +193,13 @@ void scenario_time::set_time(int yearday, int minute) { m_time.wMinute = minute % 60; } +void scenario_time::restore( SYSTEMTIME const &Time, double const Milliseconds ) { + m_time = Time; + m_milliseconds = Milliseconds; + m_time.wMilliseconds = static_cast( std::floor( m_milliseconds ) ); + m_yearday = year_day( m_time.wDay, m_time.wMonth, m_time.wYear ); +} + // calculates day of week for provided date int scenario_time::day_of_week( int const Day, int const Month, int const Year ) const { diff --git a/simulation/simulationtime.h b/simulation/simulationtime.h index aae98ee82..eec227e99 100644 --- a/simulation/simulationtime.h +++ b/simulation/simulationtime.h @@ -47,6 +47,14 @@ public: return m_timezonebias; } void set_time(int yearday, int minute); + // the part of the running second gone by [ms], with its fraction + inline + double + milliseconds() const { + return m_milliseconds; } + // sets the clock to a saved moment: the date and time of Time, Milliseconds into its second (simulation snapshot) + void + restore( SYSTEMTIME const &Time, double const Milliseconds ); /** Returns std::string in format: `"mm:ss"`. */ operator std::string(); diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index f207a05a2..178798a22 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -212,6 +212,68 @@ a driver isn't watched, and neither is a signal the driver never scanned (a trai 100 km/h 150 m before a signal at stop got past it before its AI first looked ahead; at 60 km/h it was caught). Outside the test mode the same is written to the log, nothing more. +## Simulation snapshots + +A snapshot is a text file with the state of a running simulation: the clock, the weather, the memory cells, +the switches, the queued events, where every vehicle is, how it is coupled and what its machinery and brakes +are doing, what the drivers are up to. Loading one means loading its scenery the usual way and putting that +state over it before the first frame, so a run can go on from the middle of a scenario: + +``` +eu07 -s [--snapshot-at ]... [--load-snapshot [--load-snapshot-force]] +``` + +- `--snapshot-at ` writes a snapshot once the simulation has run that long and goes on. The + time is the simulation time since the scenery started, which a run loaded from a snapshot carries on with + (a snapshot taken at 600 s and loaded starts at 600 s, so `--snapshot-at 900` is written 300 s later). The + switch can be given several times. +- `--load-snapshot ` puts the snapshot over the scenery given with `-s` once it has loaded. Without + `-seed` the random seed is taken from the snapshot, so the scenery loads the way it did then; without + `-v` the player starts in the vehicle they were in. A file the reader finds damaged (an entry cut short, or + fewer entries than its header counts), or one taken in a scenery which isn't the same as this one (see + below), isn't loaded: the scenery starts as it is, the log says why, and a test run ends with the error code. + `--load-snapshot-force` loads what can be read of it all the same. +- Both work with and without `--test`. In the game the `snapshotsave` command ([Ctrl]+[Shift]+[F9], or + whatever `eu07_input-keyboard.ini` binds it to) writes one to `__