-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathScriptEngine.h
More file actions
406 lines (347 loc) · 14.3 KB
/
Copy pathScriptEngine.h
File metadata and controls
406 lines (347 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*****************************************************************************
* Copyright (c) 2014-2026 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#pragma once
#ifdef ENABLE_SCRIPTING
#include "../actions/general/CustomAction.h"
#include "../management/Finance.h"
#include "HookEngine.h"
#include "Plugin.h"
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <quickjs.h>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace OpenRCT2::GameActions
{
class GameAction;
class Result;
} // namespace OpenRCT2::GameActions
class FileWatcher;
class InteractiveConsole;
namespace OpenRCT2
{
struct IPlatformEnvironment;
}
namespace OpenRCT2::Scripting
{
// Grepped from CI (.github/workflows/publish-plugin-types.yml); keep the format `kPluginApiVersion = N`.
static constexpr int32_t kPluginApiVersion = 114;
// Versions marking breaking changes.
static constexpr int32_t kApiVersionPeepDeprecation = 33;
static constexpr int32_t kApiVersionG2Reorder = 63;
static constexpr int32_t kApiVersionCustomActionArgs = 68;
static constexpr int32_t kApiVersionNetworkIDs = 77;
// This stack limit is not precise as quickjs-ng just sets a hard boundary offset from the stack frame
// where the limit is updated. The actual limit available to quickjs will be more or less depending on
// how big the native stack is relative to its size when the limit was first set.
// Calculating a precise limit is possible but requires platform specifc code for all possible platforms
// to get the end of the reserved stack space.
static constexpr size_t kJsStackSize = 1024 * 1024 * 7;
#ifndef DISABLE_NETWORK
struct SocketDataBase;
#endif
class ScriptExecutionInfo
{
private:
std::shared_ptr<Plugin> _plugin;
bool _isGameStateMutable{};
public:
class PluginScope
{
private:
ScriptExecutionInfo& _execInfo;
std::shared_ptr<Plugin> _plugin;
std::shared_ptr<Plugin> _backupPlugin;
bool _backupIsGameStateMutable;
public:
PluginScope(ScriptExecutionInfo& execInfo, std::shared_ptr<Plugin> plugin, bool isGameStateMutable)
: _execInfo(execInfo)
, _plugin(plugin)
{
_backupPlugin = _execInfo._plugin;
_backupIsGameStateMutable = _execInfo._isGameStateMutable;
_execInfo._plugin = std::move(plugin);
_execInfo._isGameStateMutable = isGameStateMutable;
}
PluginScope(const PluginScope&) = delete;
~PluginScope()
{
_execInfo._plugin = _backupPlugin;
_execInfo._isGameStateMutable = _backupIsGameStateMutable;
}
};
std::shared_ptr<Plugin> GetCurrentPlugin()
{
return _plugin;
}
bool IsGameStateMutable()
{
return _isGameStateMutable;
}
};
using IntervalHandle = uint32_t;
struct ScriptInterval
{
std::shared_ptr<Plugin> Owner;
uint32_t Delay{};
int64_t LastTimestamp{};
JSCallback Callback;
bool Repeat{};
bool Deleted{};
};
class ScriptEngine
{
private:
InteractiveConsole& _console;
IPlatformEnvironment& _env;
static JSRuntime* _runtime;
JSContext* _replContext = nullptr;
bool _initialised{};
bool _hotReloadingInitialised{};
bool _transientPluginsEnabled{};
bool _transientPluginsStarted{};
bool _intransientPluginsStarted{};
std::queue<std::tuple<std::promise<void>, std::string>> _evalQueue;
std::vector<std::shared_ptr<Plugin>> _plugins;
uint32_t _lastHotReloadCheckTick{};
HookEngine _hookEngine;
ScriptExecutionInfo _execInfo;
JSValue _sharedStorage = JS_UNDEFINED;
JSValue _parkStorage = JS_UNDEFINED;
uint32_t _lastIntervalTimestamp{};
std::map<IntervalHandle, ScriptInterval> _intervals;
IntervalHandle _nextIntervalHandle = 1;
std::unique_ptr<FileWatcher> _pluginFileWatcher;
std::unordered_set<std::string> _changedPluginFiles;
std::mutex _changedPluginFilesMutex;
std::vector<std::function<void(std::shared_ptr<Plugin>)>> _pluginStoppedSubscriptions;
struct ExtensionCallbacks
{
std::function<void(JSContext*)> newContext;
std::function<void()> unregister;
};
std::vector<ExtensionCallbacks> _extensions;
struct CustomActionInfo
{
std::shared_ptr<Plugin> Owner;
std::string Name;
JSCallback Query;
JSCallback Execute;
};
std::unordered_map<std::string, CustomActionInfo> _customActions;
#ifndef DISABLE_NETWORK
std::vector<std::shared_ptr<SocketDataBase>> _sockets;
#endif
void InitialiseContext(JSContext* ctx) const;
public:
ScriptEngine(InteractiveConsole& console, IPlatformEnvironment& env);
ScriptEngine(ScriptEngine&) = delete;
~ScriptEngine();
JSContext* GetContext() const
{
return _replContext;
}
static JSRuntime* GetRuntime()
{
return _runtime;
}
HookEngine& GetHookEngine()
{
return _hookEngine;
}
ScriptExecutionInfo& GetExecInfo()
{
return _execInfo;
}
JSValue GetSharedStorage()
{
return _sharedStorage;
}
JSValue GetParkStorage()
{
return _parkStorage;
}
std::vector<std::shared_ptr<Plugin>>& GetPlugins()
{
return _plugins;
}
std::vector<std::shared_ptr<Plugin>> GetRemotePlugins()
{
std::vector<std::shared_ptr<Plugin>> res;
for (const auto& plugin : _plugins)
{
const auto& metadata = plugin->GetMetadata();
if (metadata.Type == PluginType::Remote)
{
res.push_back(plugin);
}
}
return res;
}
void ClearParkStorage();
std::string GetParkStorageAsJSON();
void SetParkStorageFromJSON(const std::string& value, const std::string& filename);
void Initialise();
JSContext* CreateContext() const;
void LoadTransientPlugins();
void UnloadTransientPlugins();
void StopUnloadRegisterAllPlugins();
void Tick();
std::future<void> Eval(const std::string& s);
void ExecutePluginCall(
const std::shared_ptr<Plugin>& plugin, JSValue func, const std::vector<JSValue>& args, bool isGameStateMutable,
bool keepArgsAlive = false);
JSValue ExecutePluginCall(
const std::shared_ptr<Plugin>& plugin, JSValue func, JSValue thisValue, const std::vector<JSValue>& args,
bool isGameStateMutable, bool keepArgsAlive = false, bool keepRetValueAlive = false);
void LogPluginInfo(std::string_view message);
void LogPluginInfo(const std::shared_ptr<Plugin>& plugin, std::string_view message);
void SubscribeToPluginStoppedEvent(std::function<void(std::shared_ptr<Plugin>)> callback)
{
_pluginStoppedSubscriptions.push_back(callback);
}
void RegisterExtension(std::function<void(JSContext*)> newContext, std::function<void()> unregister)
{
_extensions.emplace_back(newContext, unregister);
newContext(_replContext);
}
void AddNetworkPlugin(std::string_view code);
void RemoveNetworkPlugins();
[[nodiscard]] GameActions::Result QueryOrExecuteCustomGameAction(
const GameActions::CustomAction& action, bool isExecute);
bool RegisterCustomAction(
const std::shared_ptr<Plugin>& plugin, std::string_view action, const JSCallback& query, const JSCallback& execute);
void RunGameActionHooks(const GameActions::GameAction& action, GameActions::Result& result, bool isExecute);
[[nodiscard]] std::pair<std::unique_ptr<GameActions::GameAction>, bool> CreateGameAction(
JSContext* ctx, const std::string& actionid, JSValue args, const std::string& pluginName);
[[nodiscard]] JSValue GameActionResultToJS(
JSContext* ctx, const GameActions::GameAction& action, const GameActions::Result& result);
void SaveSharedStorage();
IntervalHandle AddInterval(
const std::shared_ptr<Plugin>& plugin, int32_t delay, bool repeat, const JSCallback& callback);
void RemoveInterval(const std::shared_ptr<Plugin>& plugin, IntervalHandle handle);
static std::string_view ExpenditureTypeToString(ExpenditureType expenditureType);
static ExpenditureType StringToExpenditureType(std::string_view expenditureType);
#ifndef DISABLE_NETWORK
void AddSocket(const std::shared_ptr<SocketDataBase>& data);
#endif
private:
static void RegisterClasses(JSContext* ctx);
static void UnregisterClasses();
static void RegisterConstants(JSContext* ctx);
void RefreshPlugins();
std::vector<std::string> GetPluginFiles() const;
void UnregisterPlugin(std::string_view path);
void RegisterPlugin(std::string_view path);
void CheckAndStartPlugins();
void StartIntransientPlugins();
void StartTransientPlugins();
void LoadPlugin(const std::string& path);
void LoadPlugin(std::shared_ptr<Plugin>& plugin);
void UnloadPlugin(std::shared_ptr<Plugin>& plugin);
void StartPlugin(std::shared_ptr<Plugin> plugin);
void StopPlugin(std::shared_ptr<Plugin> plugin, bool unregistering = false);
void ReloadPlugin(std::shared_ptr<Plugin> plugin);
static bool ShouldLoadScript(std::string_view path);
bool ShouldStartPlugin(const std::shared_ptr<Plugin>& plugin);
void SetupHotReloading();
void DoAutoReloadPluginCheck();
void AutoReloadPlugins();
void ProcessREPL();
void RemoveCustomGameActions(const std::shared_ptr<Plugin>& plugin);
[[nodiscard]] static GameActions::Result JSToGameActionResult(JSContext* ctx, JSValue d);
void InitSharedStorage();
void LoadSharedStorage();
IntervalHandle AllocateHandle();
void UpdateIntervals();
void RemoveIntervals(const std::shared_ptr<Plugin>& plugin);
void UpdateSockets();
void RemoveSockets(const std::shared_ptr<Plugin>& plugin);
};
bool IsGameStateMutable();
int32_t GetTargetAPIVersion();
std::string Stringify(JSContext* context, JSValue value);
class ScBase
{
private:
JSValue proto = JS_NULL;
JSContext* protoCtx = nullptr;
JSClassID classId = JS_INVALID_CLASS_ID;
bool hasFinalizer = false;
public:
void Unregister()
{
classId = JS_INVALID_CLASS_ID;
if (protoCtx != nullptr)
JS_FreeValue(protoCtx, proto);
}
[[nodiscard]] JSValue GetProto() const
{
return proto;
}
void RegisterDerived(JSContext* ctx, const ScBase& parent, std::span<const JSCFunctionListEntry> classFuncs)
{
proto = JS_NewObject(ctx);
protoCtx = ctx;
JS_SetPrototype(ctx, proto, parent.GetProto());
JS_SetPropertyFunctionList(ctx, proto, classFuncs.data(), static_cast<int>(classFuncs.size()));
}
protected:
[[nodiscard]] JSValue MakeWithOpaqueAndProto(JSContext* ctx, void* opaque, JSValue customProto) const
{
assert(opaque == nullptr || hasFinalizer);
JSValue obj = JS_NewObjectProtoClass(ctx, customProto, classId);
if (JS_IsException(obj))
throw std::runtime_error("Failed to create new object for class.");
JS_SetOpaque(obj, opaque);
return obj;
}
[[nodiscard]] JSValue MakeWithOpaque(JSContext* ctx, void* opaque) const
{
// If you fail this assert you probably need a finalizer to free the opaque ptr.
assert(opaque == nullptr || hasFinalizer);
// TODO: the class proto could be set once per context rather than here on every object creation.
JS_SetClassProto(ctx, classId, JS_DupValue(ctx, proto));
JSValue obj = JS_NewObjectClass(ctx, classId);
if (JS_IsException(obj))
throw std::runtime_error("Failed to create new object for class.");
JS_SetOpaque(obj, opaque);
return obj;
}
template<typename T>
[[nodiscard]] T GetOpaque(JSValue obj) const
{
return static_cast<T>(JS_GetOpaque(obj, classId));
}
void RegisterBase(
JSContext* ctx, const char* className, JSClassFinalizer* finalizer,
std::span<const JSCFunctionListEntry> classFuncs)
{
assert(classId == JS_INVALID_CLASS_ID);
// Note: Technically JS_NewClassID is meant to be called once during the lifetime of the program
// whereas JS_NewClass is meant to be called for each runtime.
// If we ever have any more runtimes, this flow would be wrong.
// More runtimes would also require refactoring the way values are passed to the JS code when
// calling callbacks.
JSRuntime* rt = JS_GetRuntime(ctx);
JS_NewClassID(rt, &classId);
JSClassDef classDef = { className, finalizer, nullptr, nullptr, nullptr };
JS_NewClass(rt, classId, &classDef);
proto = JS_NewObject(ctx);
protoCtx = ctx;
JS_SetPropertyFunctionList(ctx, proto, classFuncs.data(), static_cast<int>(classFuncs.size()));
hasFinalizer = finalizer != nullptr;
}
};
} // namespace OpenRCT2::Scripting
#endif