From d19411ce4048a4027222cb66415017fac334ce38 Mon Sep 17 00:00:00 2001 From: jakubg1 <24206305+jakubg1@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:24:35 +0100 Subject: [PATCH] feat(lua): api.spawn_trainset() places trainsets from scenery scripts A scenery Lua script can place trainsets while the simulation runs, with spawn_trainset(definition) in eu07.events. The definition is written as in a scenery file, from "trainset" to "endtrainset", e.g. as copied from the scenario starter; it can hold more than one trainset. - The trainsets are queued and placed at the start of the next simulation update, ahead of everything that goes through the vehicles. A Lua event with no delay runs at once, also from a track event fired while the vehicles are being updated, and a vehicle added then would change the list being iterated. A call made while the scenery loads waits until it's loaded. - The whole definition is checked before anything is made: only trainset, reversed, assignment, vehicle nodes and endtrainset, each trainset on a track which exists, with vehicle names not in use and not repeated. Otherwise nothing is placed and the log says why. - The statements go through the same code as in a scenery file, so "reversed" and "assignment" work as there. The trainset header is read without the overrides of the scenario starter, which go by the line of the scenario file (open_trainset, split off deserialize_trainset; loading is unchanged). - The argument is checked with luaL_checkstring, a nil is a Lua error. Based on PR #159, without its move of the smoke sources and lights into TDynamicObject::Init (vehicles of road points would get their smoke twice) and without the velocity parameter of insert_trainset. Nothing changes for existing sceneries; no game data changes. Co-Authored-By: Claude Opus 5.5 --- scripting/lua.cpp | 9 ++ scripting/lua.h | 1 + simulation/simulation.cpp | 25 ++++ simulation/simulation.h | 9 ++ simulation/simulationstateserializer.cpp | 143 +++++++++++++++++++++++ simulation/simulationstateserializer.h | 6 + 6 files changed, 193 insertions(+) diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 14ecbb75d..76d55d346 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -30,6 +30,7 @@ lua::lua() {"isolated_isoccupied_n", scriptapi_isolated_isoccupied_n}, {"train_getname", scriptapi_train_getname}, {"dynobj_putvalues", scriptapi_dynobj_putvalues}, + {"spawn_trainset", scriptapi_spawn_trainset}, {"memcell_find", scriptapi_memcell_find}, {"memcell_read", scriptapi_memcell_read}, {"memcell_read_n", scriptapi_memcell_read_n}, @@ -296,6 +297,14 @@ int lua::scriptapi_dynobj_putvalues(lua_State *L) return 0; } +/// Places the trainsets of a definition written as in a scenery file (`trainset ... endtrainset`), for example one copied +/// from the scenario starter. They're placed at the start of the next simulation update, and the log says why if they can't be. +int lua::scriptapi_spawn_trainset(lua_State *L) +{ + simulation::State.queue_trainsets(luaL_checkstring(L, 1)); + return 0; +} + int lua::scriptapi_memcell_find(lua_State *L) { std::string str = lua_tostring(L, 1); diff --git a/scripting/lua.h b/scripting/lua.h index 07d729264..c852d456d 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -27,6 +27,7 @@ class lua static int scriptapi_isolated_isoccupied_n(lua_State *L); static int scriptapi_train_getname(lua_State *L); static int scriptapi_dynobj_putvalues(lua_State *L); + static int scriptapi_spawn_trainset(lua_State *L); static int scriptapi_memcell_find(lua_State *L); static int scriptapi_memcell_read(lua_State *L); static int scriptapi_memcell_read_n(lua_State *L); diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 87cce81b6..a809d60f8 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -36,6 +36,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "vehicle/Driver.h" +#include +#include + namespace simulation { state_manager State; @@ -121,6 +124,9 @@ state_manager::update( double const Deltatime, int Iterationcount ) { // aktualizacja animacji krokiem FPS: dt=krok czasu [s], dt*iter=czas od ostatnich przeliczeń if (Deltatime == 0.0) { return; } + // ahead of everything which goes through the vehicles, as the added ones change their list + place_queued_trainsets(); + auto const totaltime { Deltatime * Iterationcount }; // NOTE: we perform animations first, as they can determine factors like contact with powergrid TAnimModel::AnimUpdate( totaltime ); // wykonanie zakolejkowanych animacji @@ -132,6 +138,25 @@ state_manager::update( double const Deltatime, int Iterationcount ) { simulation::Vehicles.update( Deltatime, Iterationcount ); } +void +state_manager::queue_trainsets( std::string Definition ) { + + m_queuedtrainsets.emplace_back( std::move( Definition ) ); +} + +void +state_manager::place_queued_trainsets() { + + if( true == m_queuedtrainsets.empty() ) { return; } + // taken out of the queue first, so that what placing the vehicles leads to can queue more for the next update + auto const queued { std::exchange( m_queuedtrainsets, {} ) }; + for( auto const &definition : queued ) { + if( auto const vehicles { m_serializer.insert_trainsets( definition ) }; false == vehicles.empty() ) { + WriteLog( std::format( "Placed {} vehicle(s) of the trainsets given while the simulation runs, the first of them \"{}\"", vehicles.size(), vehicles.front()->name() ) ); + } + } +} + void state_manager::update_clocks() { diff --git a/simulation/simulation.h b/simulation/simulation.h index 0e96da68b..b2b5078d1 100644 --- a/simulation/simulation.h +++ b/simulation/simulation.h @@ -43,6 +43,10 @@ public: // places the vehicles, given as their node statements, as a trainset on the path. returns: the vehicles made std::vector insert_trainset(std::string const &Name, TTrack *Path, double const Offset, std::string const &Vehicles, bool const Reversed = false); + // places the trainsets of the definition, written as in a scenery file (trainset ... endtrainset), at the start of the next + // update of the simulation. a script can ask for it while the vehicles are being updated, or while the scenery loads + void + queue_trainsets(std::string Definition); // create eventlauncher from node string TEventLauncher * create_eventlauncher(const std::string &src, const std::string &name, const glm::dvec3 &position); @@ -74,8 +78,13 @@ public: export_as_text( std::string const &Scenariofile ) const; private: +// methods + // places the trainsets queued since the last update + void + place_queued_trainsets(); // members state_serializer m_serializer; + std::vector m_queuedtrainsets; // definitions of the trainsets to be placed at the next update struct { std::shared_ptr weather, time, date; } m_scriptinginterface; diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 0a8670c4e..7ca06cb65 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -37,7 +37,11 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include "editor/editorTerrainStreamer.hpp" +#include #include +#include +#include +#include namespace simulation { @@ -49,6 +53,113 @@ double vehicle_length( std::string const &Folder, std::string const &Type ) { return probe.LoadFIZ( paths::dynamic + Folder + "/" ) ? probe.Dim.L : 0.0; } +// checks the definition of trainsets to be placed while the simulation runs. it can hold only what a scenery file has +// from "trainset" to "endtrainset", each trainset on a track which exists, with vehicles of names not in use yet +class trainset_check { + +public: + explicit trainset_check( std::string const &Definition ) : + m_input( Definition, cParser::buffer_TEXT, Global.asCurrentSceneryPath, Global.bLoadTraction ) + {} + // returns: what keeps the definition from being placed, or nothing if it can be + std::string fault() { + auto token { m_input.getToken() }; + while( false == token.empty() && true == m_fault.empty() ) { + statement( token ); + token = m_input.getToken(); + } + if( false == m_fault.empty() ) { return m_fault; } + if( true == m_open ) { return "the last trainset doesn't end with \"endtrainset\""; } + if( m_trainsets == 0 ) { return "no trainset is defined"; } + return {}; + } + +private: + void statement( std::string const &Token ) { + if( Token == "trainset" ) { header(); } + else if( Token == "reversed" ) { reversed(); } + else if( Token == "assignment" ) { assignment(); } + else if( Token == "node" ) { vehicle(); } + else if( Token == "endtrainset" ) { close(); } + else { m_fault = std::format( "unexpected token \"{}\"", Token ); } + } + void header() { + if( true == m_open ) { + m_fault = "a trainset begins before the previous one ends"; + return; + } + std::string name; + std::string track; + m_input.getTokens( 4 ); + m_input >> name >> track; + if( simulation::Paths.find( track ) == nullptr ) { + m_fault = std::format( "track \"{}\" of trainset \"{}\" doesn't exist", track, name ); + return; + } + m_open = true; + m_vehicles = 0; + } + void reversed() { + if( false == m_open || m_vehicles > 0 ) { + m_fault = "\"reversed\" has to follow the trainset header, ahead of its vehicles"; + } + } + void assignment() { + if( false == m_open ) { + m_fault = "\"assignment\" outside of a trainset"; + return; + } + skip_until( "endassignment" ); + } + void vehicle() { + if( false == m_open ) { + m_fault = "a node outside of a trainset"; + return; + } + std::string rangemax; + std::string rangemin; + std::string name; + std::string type; + m_input.getTokens( 4 ); + m_input >> rangemax >> rangemin >> name >> type; + if( type != "dynamic" ) { + m_fault = std::format( "node \"{}\" of type \"{}\", only vehicles can be placed", name, type ); + return; + } + skip_until( "enddynamic" ); + ++m_vehicles; + if( name.empty() || name == "none" ) { return; } + if( simulation::Vehicles.find( name ) != nullptr || false == m_names.insert( name ).second ) { + m_fault = std::format( "vehicle name \"{}\" is in use", name ); + } + } + void close() { + if( false == m_open ) { + m_fault = "\"endtrainset\" outside of a trainset"; + return; + } + if( m_vehicles == 0 ) { + m_fault = "a trainset without vehicles"; + return; + } + m_open = false; + ++m_trainsets; + } + void skip_until( std::string_view Token ) { + auto token { m_input.getToken() }; + while( false == token.empty() && token != Token ) { + token = m_input.getToken(); + } + } + + cParser m_input; + std::string m_fault; + bool m_open { false }; + int m_vehicles { 0 }; + int m_trainsets { 0 }; + std::unordered_set m_names; +}; + } // namespace std::shared_ptr @@ -1095,6 +1206,12 @@ state_serializer::deserialize_trainset( cParser &Input, scene::scratch_data &Scr } } + open_trainset( Input, Scratchpad ); +} + +void +state_serializer::open_trainset( cParser &Input, scene::scratch_data &Scratchpad ) { + if( true == Scratchpad.trainset.is_open ) { // shouldn't happen but if it does wrap up currently open trainset and report an error deserialize_endtrainset( Input, Scratchpad ); @@ -1930,6 +2047,32 @@ std::vector state_serializer::insert_trainset(std::string cons return vehicles; } +std::vector state_serializer::insert_trainsets(std::string const &Definition) { + // checked in full first, so that nothing is placed when a part of it can't be + if (auto const fault { trainset_check(Definition).fault() }; false == fault.empty()) { + ErrorLog(std::format("Bad trainset: {}, the trainsets given while the simulation runs weren't placed", fault)); + return {}; + } + scene::scratch_data scratch; + cParser parser(Definition, cParser::buffer_TEXT, Global.asCurrentSceneryPath, Global.bLoadTraction); + std::vector vehicles; + auto token { parser.getToken() }; + while (false == token.empty()) { + // the check leaves nothing else to come across. the header is read without the overrides of the scenario + // starter, which go by the line of the scenario file + if (token == "trainset") { open_trainset(parser, scratch); } + else if (token == "reversed") { deserialize_reversed(parser, scratch); } + else if (token == "assignment") { deserialize_assignment(parser, scratch); } + else if (token == "node") { deserialize_node(parser, scratch); } + else if (token == "endtrainset") { + std::ranges::copy(scratch.trainset.vehicles, std::back_inserter(vehicles)); + deserialize_endtrainset(parser, scratch); + } + token = parser.getToken(); + } + return vehicles; +} + std::pair state_serializer::preview_include(std::string const &Directive, scene::layer_context const &Context, scene::layer_handle Layer, scene::instance_handle Instance) { // statements which take more than a single token, with the tokens ending them static std::unordered_map const nodeends { diff --git a/simulation/simulationstateserializer.h b/simulation/simulationstateserializer.h index 897749e7e..36222e57a 100644 --- a/simulation/simulationstateserializer.h +++ b/simulation/simulationstateserializer.h @@ -46,6 +46,10 @@ public: TAnimModel * create_model(std::string const &src, std::string const &name, const glm::dvec3 &position); // places the vehicles, given as their node statements, as a trainset on the path, while the simulation runs. returns: the vehicles made std::vector insert_trainset(std::string const &Name, TTrack *Path, double const Offset, std::string const &Vehicles, bool const Reversed = false); + // places the trainsets of the definition, written as in a scenery file (trainset ... endtrainset), while the simulation runs. + // nothing is placed if the definition holds anything else, or names a track which doesn't exist or a vehicle name in use. + // returns: the vehicles made + std::vector insert_trainsets(std::string const &Definition); // create new eventlauncher from node stirng TEventLauncher * create_eventlauncher(std::string const &src, std::string const &name, const glm::dvec3 &position); // creates model instances defined by an include directive placed or changed in the scenery editor, to show the outcome. @@ -79,6 +83,8 @@ private: void deserialize_test( cParser &Input, scene::scratch_data &Scratchpad ); void deserialize_time( cParser &Input, scene::scratch_data &Scratchpad ); void deserialize_trainset( cParser &Input, scene::scratch_data &Scratchpad ); + // opens the trainset whose header follows in the input + void open_trainset( cParser &Input, scene::scratch_data &Scratchpad ); void deserialize_terrain( cParser &Input, scene::scratch_data &Scratchpad ); void deserialize_heightmapterrain( cParser &Input, scene::scratch_data &Scratchpad ); void deserialize_editorterrain( cParser &Input, scene::scratch_data &Scratchpad );