RigsofRods
Soft-body Physics Simulation
ScriptEngine.h
Go to the documentation of this file.
1 /*
2  This source file is part of Rigs of Rods
3  Copyright 2005-2012 Pierre-Michel Ricordel
4  Copyright 2007-2012 Thomas Fischer
5  Copyright 2013-2020 Petr Ohlidal
6 
7  For more information, see http://www.rigsofrods.org/
8 
9  Rigs of Rods is free software: you can redistribute it and/or modify
10  it under the terms of the GNU General Public License version 3, as
11  published by the Free Software Foundation.
12 
13  Rigs of Rods is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  GNU General Public License for more details.
17 
18  You should have received a copy of the GNU General Public License
19  along with Rigs of Rods. If not, see <http://www.gnu.org/licenses/>.
20 */
21 
25 
26 #pragma once
27 
28 #ifdef USE_ANGELSCRIPT
29 
30 #define DEFAULT_TERRAIN_SCRIPT "default.as" // Used when map creator doesn't provide custom script.
31 
32 #include "AngelScriptBindings.h"
33 #include "Application.h"
34 #include "GameContext.h"
35 #include "GameScript.h"
36 #include "InterThreadStoreVector.h"
37 #include "ScriptEvents.h"
38 
39 #include <Ogre.h>
40 #include "scriptdictionary/scriptdictionary.h"
41 #include "scriptbuilder/scriptbuilder.h"
42 
43 #include <map>
44 
45 namespace RoR {
46 
49 
51 inline void TRIGGER_EVENT_ASYNC(scriptEvents type, int arg1, int arg2ex = 0, int arg3ex = 0, int arg4ex = 0, std::string arg5ex = "", std::string arg6ex = "", std::string arg7ex = "", std::string arg8ex = "")
52 {
53  ScriptEventArgs* args = new ScriptEventArgs{ type, arg1, arg2ex, arg3ex, arg4ex, arg5ex, arg6ex, arg7ex, arg8ex };
55 }
56 
58 enum class ScriptCategory
59 {
60  INVALID,
61  ACTOR,
62  TERRAIN,
63  CUSTOM
64 };
65 
67 
69 struct ScriptUnit
70 {
71  ScriptUnit();
72  ~ScriptUnit();
73 
76  unsigned int eventMask = 0;
77  AngelScript::asIScriptModule* scriptModule = nullptr;
78  AngelScript::asIScriptFunction* frameStepFunctionPtr = nullptr;
79  AngelScript::asIScriptFunction* eventCallbackFunctionPtr = nullptr;
80  AngelScript::asIScriptFunction* eventCallbackExFunctionPtr = nullptr;
81  AngelScript::asIScriptFunction* defaultEventCallbackFunctionPtr = nullptr;
83  Ogre::String scriptName;
84  Ogre::String scriptHash;
85  Ogre::String scriptBuffer;
86 };
87 
88 typedef std::map<ScriptUnitId_t, ScriptUnit> ScriptUnitMap;
89 
91 {
92  std::string lsr_filename;
93  std::string lsr_buffer;
96 };
97 
99 {
101 
104 };
105 
110 
111 // Params to `RoR::ScriptEngine::getFunctionByDeclAndLogCandidates()`
112 const std::string GETFUNC_DEFAULTEVENTCALLBACK_SIGFMT = "void {}(int, string, string, int)";
113 const std::string GETFUNC_DEFAULTEVENTCALLBACK_NAME = "defaultEventCallback";
114 
119 class ScriptEngine : public Ogre::LogListener
120 {
121  friend class GameScript;
122 
123 public:
124 
125  ScriptEngine();
126  ~ScriptEngine();
127 
136  ScriptUnitId_t loadScript(Ogre::String scriptname, ScriptCategory category = ScriptCategory::TERRAIN,
137  ActorPtr associatedActor = nullptr, std::string buffer = "");
138 
143  void unloadScript(ScriptUnitId_t unique_id);
144 
149  void framestep(Ogre::Real dt);
150 
151  void setForwardScriptLogToConsole(bool doForward);
152 
157  void triggerEvent(scriptEvents eventnum, int arg1=0, int arg2ex=0, int arg3ex=0, int arg4ex=0, std::string arg5ex="", std::string arg6ex="", std::string arg7ex="", std::string arg8ex="");
158 
159  void setEventsEnabled(bool val) { m_events_enabled = val; }
160 
165  int executeString(Ogre::String command);
166 
173  void queueStringForExecution(const Ogre::String command);
174 
179  int addFunction(const Ogre::String& arg);
180 
185  int functionExists(const Ogre::String& arg);
186 
191  int deleteFunction(const Ogre::String& arg);
192 
197  int addVariable(const Ogre::String& arg);
198 
203  int deleteVariable(const Ogre::String& arg);
204 
209  AngelScript::asIScriptFunction* getFunctionByDeclAndLogCandidates(ScriptUnitId_t nid, GetFuncFlags_t flags, const std::string& funcName, const std::string& fmtFuncDecl);
210 
211  int fireEvent(std::string instanceName, float intensity);
212 
213  void envokeCallback(int functionId, eventsource_t* source, NodeNum_t nodenum = NODENUM_INVALID, int type = 0);
214 
221  void forwardExceptionAsScriptEvent(const std::string& from);
222 
223  AngelScript::asIScriptEngine* getEngine() { return engine; };
224 
225  // method from Ogre::LogListener
226  void messageLogged(const Ogre::String& message, Ogre::LogMessageLevel lml, bool maskDebug, const Ogre::String& logName, bool& skipThisMessage);
227 
228  inline void SLOG(const char* msg) { this->scriptLog->logMessage(msg); }
229  inline void SLOG(std::string msg) { this->scriptLog->logMessage(msg); }
230 
231  bool scriptUnitExists(ScriptUnitId_t unique_id);
232  ScriptUnit& getScriptUnit(ScriptUnitId_t unique_id);
233  ScriptUnitId_t getTerrainScriptUnit() const { return m_terrain_script_unit; }
234  ScriptUnitId_t getCurrentlyExecutingScriptUnit() const { return m_currently_executing_script_unit; }
235  ScriptUnitMap const& getScriptUnits() const { return m_script_units; }
236 
237 protected:
238 
241 
245  void init();
246 
250  Ogre::String composeModuleName(Ogre::String const& scriptName, ScriptCategory origin, ScriptUnitId_t id);
251 
256  int setupScriptUnit(int unit_id);
257 
262  bool prepareContextAndHandleErrors(ScriptUnitId_t nid, int asFunctionID);
263 
269 
271 
274 
278  void msgCallback(const AngelScript::asSMessageInfo* msg);
279 
284  void lineCallback(AngelScript::asIScriptContext* ctx);
285 
290  void exceptionCallback(AngelScript::asIScriptContext* ctx);
291 
293 
294  AngelScript::asIScriptEngine* engine;
295  AngelScript::asIScriptContext* context;
302  bool m_events_enabled = true;
303 
305 };
306 
308 
309 } // namespace RoR
310 
311 #else // USE_ANGELSCRIPT
312 inline void TRIGGER_EVENT_ASYNC(scriptEvents type, int arg1, int arg2ex = 0, int arg3ex = 0, int arg4ex = 0, std::string arg5ex = "", std::string arg6ex = "", std::string arg7ex = "", std::string arg8ex = "")
313 {
314 }
315 #endif // USE_ANGELSCRIPT
RoR::ScriptUnit
Represents a loaded script and all associated resources/handles.
Definition: ScriptEngine.h:69
GameContext.h
Game state manager and message-queue provider.
RoR::ScriptUnit::frameStepFunctionPtr
AngelScript::asIScriptFunction * frameStepFunctionPtr
script function pointer to the frameStep function
Definition: ScriptEngine.h:78
RoR::ScriptEngine::getScriptUnits
ScriptUnitMap const & getScriptUnits() const
Definition: ScriptEngine.h:235
RoR::ScriptEngine::setEventsEnabled
void setEventsEnabled(bool val)
Definition: ScriptEngine.h:159
RoR::ScriptEngine::msgCallback
void msgCallback(const AngelScript::asSMessageInfo *msg)
Optional (but very recommended!) callback providing diagnostic info when things fail to start (most n...
Definition: ScriptEngine.cpp:196
RoR::ScriptEngine::exceptionCallback
void exceptionCallback(AngelScript::asIScriptContext *ctx)
Optional callback invoked when the script critically fails, allowing debugging.
Definition: ScriptEngine.cpp:233
RoR::ScriptEngine
This class represents the angelscript scripting interface.
Definition: ScriptEngine.h:119
RoR::LoadScriptRequest::lsr_filename
std::string lsr_filename
Load from resource (file). If buffer is supplied, use this as display name only.
Definition: ScriptEngine.h:92
RoR::ScriptEventArgs
Args for eventCallbackEx() queued via MSG_SIM_SCRIPT_EVENT_TRIGGERED See descriptions at enum RoR::sc...
Definition: ScriptEvents.h:103
RoR::ScriptEngine::scriptUnitExists
bool scriptUnitExists(ScriptUnitId_t unique_id)
Definition: ScriptEngine.cpp:994
RoR::ScriptEngine::composeModuleName
Ogre::String composeModuleName(Ogre::String const &scriptName, ScriptCategory origin, ScriptUnitId_t id)
Packs name + important info to one string, for logging and reporting purposes.
Definition: ScriptEngine.cpp:754
RoR::GETFUNCFLAG_OPTIONAL
const GetFuncFlags_t GETFUNCFLAG_OPTIONAL
Only logs warning if candidate is found, to help modder find a typo.
Definition: ScriptEngine.h:107
AngelScriptBindings.h
RoR::ScriptUnit::eventMask
unsigned int eventMask
filter mask for script events
Definition: ScriptEngine.h:76
RoR::ScriptEngine::setupScriptUnit
int setupScriptUnit(int unit_id)
Helper for loadScript(), does the actual building without worry about unit management.
Definition: ScriptEngine.cpp:808
RoR::eventsource_t
< Scripting
Definition: Collisions.h:40
RoR::NODENUM_INVALID
static const NodeNum_t NODENUM_INVALID
Definition: ForwardDeclarations.h:53
RoR::ScriptEngine::executeContextAndHandleErrors
int executeContextAndHandleErrors(ScriptUnitId_t nid)
Helper for executing any script function/snippet; registers Line/Exception callbacks (on demand) and ...
Definition: ScriptEngine.cpp:277
RoR::TRIGGER_EVENT_ASYNC
void TRIGGER_EVENT_ASYNC(scriptEvents type, int arg1, int arg2ex=0, int arg3ex=0, int arg4ex=0, std::string arg5ex="", std::string arg6ex="", std::string arg7ex="", std::string arg8ex="")
Asynchronously (via MSG_SIM_SCRIPT_EVENT_TRIGGERED) invoke script function eventCallbackEx(),...
Definition: ScriptEngine.h:51
RoR::ScriptCategoryToString
const char * ScriptCategoryToString(ScriptCategory c)
Definition: ScriptEngine.cpp:66
RoR::ScriptCategory::INVALID
@ INVALID
RoR::ScriptEngine::addVariable
int addVariable(const Ogre::String &arg)
Adds a global variable to the script.
Definition: ScriptEngine.cpp:639
RoR::ScriptEngine::executeString
int executeString(Ogre::String command)
executes a string (useful for the console)
Definition: ScriptEngine.cpp:483
RoR::ScriptEngine::getEngine
AngelScript::asIScriptEngine * getEngine()
Definition: ScriptEngine.h:223
RoR::LoadScriptRequest::lsr_buffer
std::string lsr_buffer
Load from memory buffer.
Definition: ScriptEngine.h:93
RoR::ScriptEngine::setForwardScriptLogToConsole
void setForwardScriptLogToConsole(bool doForward)
Definition: ScriptEngine.cpp:982
RoR::ScriptEngine::forwardExceptionAsScriptEvent
void forwardExceptionAsScriptEvent(const std::string &from)
Forwards useful info from C++ try{}catch{} exceptions to script in the form of game event.
Definition: ScriptEngine.cpp:246
RoR::GetFuncFlags_t
BitMask_t GetFuncFlags_t
Flags for RoR::ScriptEngine::getFunctionByDeclAndLogCandidates()
Definition: ScriptEngine.h:106
RoR::ScriptEngine::loadScript
ScriptUnitId_t loadScript(Ogre::String scriptname, ScriptCategory category=ScriptCategory::TERRAIN, ActorPtr associatedActor=nullptr, std::string buffer="")
Loads a script.
Definition: ScriptEngine.cpp:759
RoR::ScriptEngine::queueStringForExecution
void queueStringForExecution(const Ogre::String command)
Queues a string for execution.
Definition: ScriptEngine.cpp:478
BITMASK
#define BITMASK(OFFSET)
Definition: BitFlags.h:10
RoR::ScriptEngine::framestep
void framestep(Ogre::Real dt)
Calls the script's framestep function to be able to use timed things inside the script.
Definition: ScriptEngine.cpp:384
RefCountingObjectPtr< Actor >
RoR::ScriptEngine::deleteVariable
int deleteVariable(const Ogre::String &arg)
Deletes a global variable from the script.
Definition: ScriptEngine.cpp:659
RoR::GETFUNC_DEFAULTEVENTCALLBACK_NAME
const std::string GETFUNC_DEFAULTEVENTCALLBACK_NAME
Definition: ScriptEngine.h:113
RoR::SCRIPTUNITID_INVALID
static const ScriptUnitId_t SCRIPTUNITID_INVALID
Definition: ForwardDeclarations.h:41
RoR::LoadScriptRequest::lsr_category
ScriptCategory lsr_category
Definition: ScriptEngine.h:94
RoR::ScriptEngine::prepareContextAndHandleErrors
bool prepareContextAndHandleErrors(ScriptUnitId_t nid, int asFunctionID)
Helper for executing any script function/snippet; does asIScriptContext::Prepare() and reports any er...
Definition: ScriptEngine.cpp:364
RoR::ActorInstanceID_t
int ActorInstanceID_t
Unique sequentially generated ID of an actor in session. Use ActorManager::GetActorById()
Definition: ForwardDeclarations.h:37
RoR::ScriptEngine::init
void init()
This function initialzies the engine and registeres all types.
Definition: ScriptEngine.cpp:119
RoR::ScriptUnit::~ScriptUnit
~ScriptUnit()
Definition: ScriptEngine.cpp:83
RoR::NodeNum_t
uint16_t NodeNum_t
Node position within Actor::ar_nodes; use RoR::NODENUM_INVALID as empty value.
Definition: ForwardDeclarations.h:52
RoR::ScriptEngine::unloadScript
void unloadScript(ScriptUnitId_t unique_id)
Unloads a script.
Definition: ScriptEngine.cpp:964
RoR::ScriptUnit::scriptName
Ogre::String scriptName
Definition: ScriptEngine.h:83
InterThreadStoreVector< Ogre::String >
RoR::ACTORINSTANCEID_INVALID
static const ActorInstanceID_t ACTORINSTANCEID_INVALID
Definition: ForwardDeclarations.h:38
RoR::ScriptUnit::scriptCategory
ScriptCategory scriptCategory
Definition: ScriptEngine.h:75
RoR::GameContext::PushMessage
void PushMessage(Message m)
Doesn't guarantee order! Use ChainMessage() if order matters.
Definition: GameContext.cpp:65
RoR::ScriptUnitId_t
int ScriptUnitId_t
Unique sequentially generated ID of a loaded and running scriptin session. Use ScriptEngine::getScrip...
Definition: ForwardDeclarations.h:40
RoR::ScriptEngine::envokeCallback
void envokeCallback(int functionId, eventsource_t *source, NodeNum_t nodenum=NODENUM_INVALID, int type=0)
Definition: ScriptEngine.cpp:443
RoR::ScriptUnit::defaultEventCallbackFunctionPtr
AngelScript::asIScriptFunction * defaultEventCallbackFunctionPtr
script function pointer for spawner events
Definition: ScriptEngine.h:81
RoR::SE_NO_EVENTS
@ SE_NO_EVENTS
Definition: ScriptEvents.h:67
RoR::ScriptEngine::lineCallback
void lineCallback(AngelScript::asIScriptContext *ctx)
Optional callback which receives diagnostic info for every executed statement.
Definition: ScriptEngine.cpp:215
RoR::ScriptEngine::~ScriptEngine
~ScriptEngine()
Definition: ScriptEngine.cpp:106
RoR::LoadScriptRequest::lsr_associated_actor
ActorInstanceID_t lsr_associated_actor
For ScriptCategory::ACTOR.
Definition: ScriptEngine.h:95
RoR::ScriptEngine::scriptLog
Ogre::Log * scriptLog
Definition: ScriptEngine.h:296
Application.h
Central state/object manager and communications hub.
RoR::ScriptEngine::m_currently_executing_script_unit
ScriptUnitId_t m_currently_executing_script_unit
Definition: ScriptEngine.h:300
RoR::App::GetGameContext
GameContext * GetGameContext()
Definition: Application.cpp:280
GameScript.h
RoR::ScriptCallbackArgs
Definition: ScriptEngine.h:98
RoR::ScriptEngine::m_currently_executing_event_trigger
scriptEvents m_currently_executing_event_trigger
Definition: ScriptEngine.h:301
RoR::ScriptEngine::m_events_enabled
bool m_events_enabled
Hack to enable fast shutdown without cleanup.
Definition: ScriptEngine.h:302
RoR::ScriptEngine::triggerEvent
void triggerEvent(scriptEvents eventnum, int arg1=0, int arg2ex=0, int arg3ex=0, int arg4ex=0, std::string arg5ex="", std::string arg6ex="", std::string arg7ex="", std::string arg8ex="")
triggers an event; Not to be used by the end-user.
Definition: ScriptEngine.cpp:712
RoR::ScriptEngine::getFunctionByDeclAndLogCandidates
AngelScript::asIScriptFunction * getFunctionByDeclAndLogCandidates(ScriptUnitId_t nid, GetFuncFlags_t flags, const std::string &funcName, const std::string &fmtFuncDecl)
Finds a function by full declaration, and if not found, finds candidates by name and logs them to Ang...
Definition: ScriptEngine.cpp:690
RoR::LoadScriptRequest
Definition: ScriptEngine.h:90
RoR::ScriptEngine::engine
AngelScript::asIScriptEngine * engine
instance of the scripting engine
Definition: ScriptEngine.h:294
RoR::ScriptUnit::eventCallbackFunctionPtr
AngelScript::asIScriptFunction * eventCallbackFunctionPtr
script function pointer to the event callback function
Definition: ScriptEngine.h:79
RoR::ScriptCategory::TERRAIN
@ TERRAIN
Defined in terrn2 file under '[Scripts]', receives terrain eventbox notifications.
RoR::ScriptUnit::scriptHash
Ogre::String scriptHash
Definition: ScriptEngine.h:84
RoR::ScriptEngine::m_terrain_script_unit
ScriptUnitId_t m_terrain_script_unit
Definition: ScriptEngine.h:299
RoR::ScriptUnit::ScriptUnit
ScriptUnit()
Definition: ScriptEngine.cpp:78
RoR::GETFUNC_DEFAULTEVENTCALLBACK_SIGFMT
const std::string GETFUNC_DEFAULTEVENTCALLBACK_SIGFMT
Definition: ScriptEngine.h:112
RoR::ScriptUnit::associatedActor
ActorPtr associatedActor
For ScriptCategory::ACTOR.
Definition: ScriptEngine.h:82
RoR::GameScript
Proxy class that can be called by script functions.
Definition: GameScript.h:41
RoR::ScriptEngine::fireEvent
int fireEvent(std::string instanceName, float intensity)
Definition: ScriptEngine.cpp:413
RoR::GETFUNCFLAG_REQUIRED
const GetFuncFlags_t GETFUNCFLAG_REQUIRED
Always logs warning that function was not found.
Definition: ScriptEngine.h:108
RoR::ScriptUnitMap
std::map< ScriptUnitId_t, ScriptUnit > ScriptUnitMap
Definition: ScriptEngine.h:88
RoR::ScriptCallbackArgs::eventsource
eventsource_t * eventsource
Definition: ScriptEngine.h:102
RoR::Message
Unified game event system - all requests and state changes are reported using a message.
Definition: GameContext.h:51
RoR::ScriptUnit::eventCallbackExFunctionPtr
AngelScript::asIScriptFunction * eventCallbackExFunctionPtr
script function pointer to the event callback function
Definition: ScriptEngine.h:80
RoR::ScriptEngine::context
AngelScript::asIScriptContext * context
context in which all scripting happens
Definition: ScriptEngine.h:295
ScriptEvents.h
RoR::ScriptEngine::m_script_units
ScriptUnitMap m_script_units
Definition: ScriptEngine.h:298
InterThreadStoreVector.h
RoR::ScriptEngine::functionExists
int functionExists(const Ogre::String &arg)
Checks if a global function exists.
Definition: ScriptEngine.cpp:560
RoR::ScriptCategory::ACTOR
@ ACTOR
Defined in truck file under 'scripts', contains global variable BeamClass@ thisActor.
RoR::ScriptEngine::m_game_script
GameScript m_game_script
Definition: ScriptEngine.h:297
RoR::ScriptEngine::stringExecutionQueue
InterThreadStoreVector< Ogre::String > stringExecutionQueue
The string execution queue.
Definition: ScriptEngine.h:304
BitMask_t
uint32_t BitMask_t
Definition: BitFlags.h:7
RoR::ScriptCategory
ScriptCategory
Note: Either of these can be loaded from script using game.pushMessage(MSG_APP_LOAD_SCRIPT_REQUESTED....
Definition: ScriptEngine.h:58
RoR::ScriptCallbackArgs::node
NodeNum_t node
Definition: ScriptEngine.h:103
RoR::ScriptCallbackArgs::ScriptCallbackArgs
ScriptCallbackArgs(eventsource_t *evs, NodeNum_t nd)
Definition: ScriptEngine.h:100
RoR::ScriptUnit::scriptBuffer
Ogre::String scriptBuffer
Definition: ScriptEngine.h:85
RoR::ScriptUnit::scriptModule
AngelScript::asIScriptModule * scriptModule
Definition: ScriptEngine.h:77
RoR::scriptEvents
scriptEvents
This enum describes what events are existing. The script can register to receive events.
Definition: ScriptEvents.h:30
RoR::ScriptEngine::getScriptUnit
ScriptUnit & getScriptUnit(ScriptUnitId_t unique_id)
Definition: ScriptEngine.cpp:1000
RoR
Definition: AppContext.h:36
RoR::ScriptEngine::ScriptEngine
ScriptEngine()
Definition: ScriptEngine.cpp:97
RoR::ScriptCategory::CUSTOM
@ CUSTOM
Loaded by user via either: A) ingame console 'loadscript'; B) RoR.cfg 'app_custom_scripts'; C) comman...
RoR::ScriptUnit::uniqueId
ScriptUnitId_t uniqueId
Definition: ScriptEngine.h:74
Log
quaternion Log() const
RoR::ScriptEngine::deleteFunction
int deleteFunction(const Ogre::String &arg)
Deletes a global function from the script.
Definition: ScriptEngine.cpp:585
RoR::ScriptEngine::addFunction
int addFunction(const Ogre::String &arg)
Adds a global function to the script.
Definition: ScriptEngine.cpp:501
RoR::MSG_SIM_SCRIPT_EVENT_TRIGGERED
@ MSG_SIM_SCRIPT_EVENT_TRIGGERED
Payload = RoR::ScriptEventArgs* (owner)
Definition: Application.h:126
RoR::GETFUNCFLAG_SILENT
const GetFuncFlags_t GETFUNCFLAG_SILENT
Never logs.
Definition: ScriptEngine.h:109
RoR::ScriptEngine::messageLogged
void messageLogged(const Ogre::String &message, Ogre::LogMessageLevel lml, bool maskDebug, const Ogre::String &logName, bool &skipThisMessage)
Definition: ScriptEngine.cpp:113