Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
Interface.h
Go to the documentation of this file.
1/* Copyright (C) 2026 Wildfire Games.
2 * This file is part of 0 A.D.
3 *
4 * 0 A.D. is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * 0 A.D. is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#ifndef INCLUDED_SCRIPT_INTERFACE
19#define INCLUDED_SCRIPT_INTERFACE
20
21#include "lib/code_annotation.h"
22#include "ps/Errors.h"
26
27#include <functional>
28#include <js/CallArgs.h>
29#include <js/Object.h>
30#include <js/RootingAPI.h>
31#include <js/TypeDecls.h>
32#include <js/Value.h>
33#include <js/ValueArray.h>
34#include <memory>
35#include <string>
36#include <string_view>
37#include <type_traits>
38#include <unordered_map>
39#include <utility>
40
41class JSObject;
42class Path;
43namespace Script { class Context; }
44namespace Script { class ModuleLoader; }
45namespace Script { struct Interface_impl; }
46namespace boost { namespace random { class rand48; } }
47struct JSClass;
48struct JSContext;
49struct JSFunctionSpec;
50struct JSPropertySpec;
51
52
53ERROR_GROUP(Scripting);
54ERROR_TYPE(Scripting, SetupFailed);
55
56ERROR_SUBGROUP(Scripting, LoadFile);
57ERROR_TYPE(Scripting_LoadFile, OpenFailed);
58ERROR_TYPE(Scripting_LoadFile, EvalErrors);
59
60ERROR_TYPE(Scripting, CallFunctionFailed);
61ERROR_TYPE(Scripting, DefineConstantFailed);
62ERROR_TYPE(Scripting, CreateObjectFailed);
63ERROR_TYPE(Scripting, TypeDoesNotExist);
64
65ERROR_SUBGROUP(Scripting, DefineType);
66ERROR_TYPE(Scripting_DefineType, AlreadyExists);
67ERROR_TYPE(Scripting_DefineType, CreationFailed);
68
69// Set the maximum number of function arguments that can be handled
70// (This should be as small as possible (for compiler efficiency),
71// but as large as necessary for all wrapped functions)
72#define SCRIPT_INTERFACE_MAX_ARGS 8
73
74using VfsPath = Path;
75
76// Using a global object for the context is a workaround until Simulation, AI, etc,
77// use their own threads and also their own contexts.
78extern thread_local std::shared_ptr<Script::Context> g_ScriptContext;
79
80/**
81 * Abstraction around a SpiderMonkey JS::Realm.
82 *
83 * Thread-safety:
84 * - May be used in non-main threads.
85 * - Each Script::Interface must be created, used, and destroyed, all in a single thread
86 * (it must never be shared between threads).
87 */
88
89namespace Script
90{
91
93{
95
96 friend class Request;
97
98public:
99
100 /**
101 * Constructor.
102 * @param nativeScopeName Name of global object that functions (via Script::Function::Register) will
103 * be placed into, as a scoping mechanism; typically "Engine"
104 * @param debugName Name of this interface for CScriptStats purposes.
105 * @param context ScriptContext to use when initializing this interface.
106 */
107 Interface(const char* nativeScopeName, const char* debugName, Context& context,
108 std::function<bool(const VfsPath&)> allowModule = {});
109
110 template<typename Context>
111 Interface(const char* nativeScopeName, const char* debugName, Context&& context,
112 std::function<bool(const VfsPath&)> allowModule = {}) :
113 Interface{nativeScopeName, debugName, *context, std::move(allowModule)}
114 {
115 static_assert(std::is_lvalue_reference_v<Context>, "`Interface` doesn't take ownership "
116 "of the context.");
117 }
118
119 /**
120 * Alternate constructor. This creates the new Realm in the same Compartment as the neighbor scriptInterface.
121 * This means that data can be freely exchanged between these two script interfaces without cloning.
122 * @param nativeScopeName Name of global object that functions (via Script::Function::Register) will
123 * be placed into, as a scoping mechanism; typically "Engine"
124 * @param debugName Name of this interface for CScriptStats purposes.
125 * @param scriptInterface 'Neighbor' scriptInterface to share a compartment with.
126 * @param allowModule A predicate deciding wheter to import the given
127 * module.
128 */
129 Interface(const char* nativeScopeName, const char* debugName, const Interface& neighbor,
130 std::function<bool(const VfsPath&)> allowModule = {});
131
132 ~Interface();
133
135 {
136 friend class Interface;
137 public:
138 static const Interface& GetScriptInterface(JSContext* cx);
139 static void* GetCBData(JSContext* cx);
140 protected:
141 Interface* pScriptInterface; // the Interface object the compartment belongs to
142 void* pCBData; // meant to be used as the "this" object for callback functions
143 };
144
145 void SetCallbackData(void* pCBData);
146
147 /**
148 * Convert the CmptPrivate callback data to T*
149 */
150 template <typename T>
151 static T* ObjectFromCBData(const Request& rq)
152 {
153 static_assert(!std::is_same_v<void, T>);
154 return static_cast<T*>(ObjectFromCBData<void>(rq));
155 }
156
157 /**
158 * Variant for the function wrapper.
159 */
160 template <typename T>
161 static T* ObjectFromCBData(const Request& rq, JS::CallArgs&)
162 {
163 return ObjectFromCBData<T>(rq);
164 }
165
167
168 /**
169 * GetGeneralJSContext returns the context without starting a GC request and without
170 * entering the Interface compartment. It should only be used in specific situations,
171 * for instance when initializing a persistent rooted.
172 * If you need the compartmented context of the Interface, you should create a
173 * Interface::Request and use the context from that.
174 */
175 JSContext* GetGeneralJSContext() const;
176 Context& GetContext() const;
177
178 /**
179 * Load global scripts that most script interfaces need,
180 * located in the /globalscripts directory. VFS must be initialized.
181 */
182 bool LoadGlobalScripts();
183
184 /**
185 * Replace the default JS random number generator with a seeded, network-synced one.
186 */
187 bool ReplaceNondeterministicRNG(boost::random::rand48& rng);
188
189 /**
190 * Call a constructor function, equivalent to JS "new ctor(arg)".
191 * @param ctor An object that can be used as constructor
192 * @param argv Constructor arguments
193 * @param out The new object; On error an error message gets logged and out is Null (out.isNull() == true).
194 */
195 void CallConstructor(JS::HandleValue ctor, JS::HandleValueArray argv, JS::MutableHandleValue out) const;
196
197 JSObject* CreateCustomObject(const std::string & typeName) const;
198 void DefineCustomObjectType(JSClass *clasp, JSNative constructor, unsigned int minArgs,
199 JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs);
200
201 /**
202 * Set the named property on the global object.
203 * Optionally makes it {ReadOnly, DontEnum}. We do not allow to make it DontDelete, so that it can be hotloaded
204 * by deleting it and re-creating it, which is done by setting @p replace to true.
205 */
206 template<typename T>
207 bool SetGlobal(const char* name, const T& value, bool replace = false, bool constant = true, bool enumerate = true);
208
209 /**
210 * Get an object from the global scope or any lexical scope.
211 * This can return globally accessible objects even if they are not properties
212 * of the global object (e.g. ES6 class definitions).
213 * @param name - Name of the property.
214 * @param out The object or null.
215 */
216 static bool GetGlobalProperty(const Request& rq, const std::string& name, JS::MutableHandleValue out);
217
218 bool SetPrototype(JS::HandleValue obj, JS::HandleValue proto);
219
220 /**
221 * Load and execute the given script in a new function scope.
222 * @param filename Name for debugging purposes (not used to load the file)
223 * @param code JS code to execute
224 * @return true on successful compilation and execution; false otherwise
225 */
226 bool LoadScript(const VfsPath& filename, const std::string& code) const;
227
228 /**
229 * Load and execute the given script in the global scope.
230 * @param filename Name for debugging purposes (not used to load the file)
231 * @param code JS code to execute
232 * @return true on successful compilation and execution; false otherwise
233 */
234 bool LoadGlobalScript(const VfsPath& filename, const std::string& code) const;
235
236 /**
237 * Load and execute the given script in the global scope.
238 * @return true on successful compilation and execution; false otherwise
239 */
240 bool LoadGlobalScriptFile(const VfsPath& path) const;
241
242 /**
243 * Evaluate some JS code in the global scope.
244 * @return true on successful compilation and execution; false otherwise
245 */
246 bool Eval(const std::string_view code) const;
247 bool Eval(const std::string_view code, JS::MutableHandleValue out) const;
248 template<typename T> bool Eval(const std::string_view code, T& out) const;
249
250 /**
251 * Calls the random number generator assigned to this Interface instance and returns the generated number.
252 */
253 bool MathRandom(double& nbr) const;
254
255 /**
256 * JSNative wrapper of the above.
257 */
258 static bool Math_random(JSContext* cx, unsigned int argc, JS::Value* vp);
259
260 /**
261 * Name the reserved slots we may need to use in custom JSObjects.
262 * When using JSCLASS_HAS_RESERVED_SLOTS in the definition of your JSClass, use the number
263 * of the highest slot you need plus 1.
264 */
266 PRIVATE = 0
267 };
268
269 /**
270 * Retrieve the private data field of a JSObject.
271 */
272 template <typename T>
273 static T* GetPrivate(const Request& rq, JS::HandleObject thisobj)
274 {
275 T* value = JS::GetMaybePtrFromReservedSlot<T>(thisobj, JSObjectReservedSlots::PRIVATE);
276
277 if (value == nullptr)
278 Exception::Raise(rq, "Private data of the given object is null!");
279
280 return value;
281 }
282
283 /**
284 * Retrieve the private data field of a JS Object.
285 * If an error occurs, GetPrivate will report it with the according stack.
286 */
287 template <typename T>
288 static T* GetPrivate(const Request& rq, JS::CallArgs& callArgs)
289 {
290 if (!callArgs.thisv().isObject())
291 {
292 Exception::Raise(rq, "Cannot retrieve private JS object data because from a non-object value!");
293 return nullptr;
294 }
295
296 JS::RootedObject thisObj(rq.cx, &callArgs.thisv().toObject());
297 T* value = JS::GetMaybePtrFromReservedSlot<T>(thisObj, JSObjectReservedSlots::PRIVATE);
298
299 if (value == nullptr)
300 Exception::Raise(rq, "Private data of the given object is null!");
301
302 return value;
303 }
304
305private:
306 bool SetGlobal_(const char* name, JS::HandleValue value, bool replace, bool constant, bool enumerate);
307
309 {
310 JS::PersistentRootedObject m_Prototype;
311 JSClass* m_Class;
313 };
314
316
317 // Take care to keep this declaration before heap rooted members. Destructors of heap rooted
318 // members have to be called before the custom destructor of Interface_impl.
319 std::unique_ptr<Interface_impl> m;
320
321 std::unordered_map<std::string, CustomType> m_CustomObjectTypes;
322};
323
324} // namespace Script
325
326// Explicitly instantiate void* as that is used for the generic template,
327// and we want to define it in the .cpp file.
328template <> void* Script::Interface::ObjectFromCBData(const Script::Request& rq);
329
330template<typename T>
331bool Script::Interface::SetGlobal(const char* name, const T& value, bool replace, bool constant, bool enumerate)
332{
333 Script::Request rq(this);
334 JS::RootedValue val(rq.cx);
335 Script::ToJSVal(rq, &val, value);
336 return SetGlobal_(name, val, replace, constant, enumerate);
337}
338
339template<typename T>
340bool Script::Interface::Eval(const std::string_view code, T& ret) const
341{
342 Script::Request rq(this);
343 JS::RootedValue rval(rq.cx);
344 if (!Eval(code, &rval))
345 return false;
346 return Script::FromJSVal(rq, rval, ret);
347}
348
349#endif // INCLUDED_SCRIPT_INTERFACE
Definition: path.h:84
Definition: Context.h:51
Definition: Interface.h:93
void DefineCustomObjectType(JSClass *clasp, JSNative constructor, unsigned int minArgs, JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs)
Definition: Interface.cpp:531
bool LoadGlobalScriptFile(const VfsPath &path) const
Load and execute the given script in the global scope.
Definition: Interface.cpp:715
bool SetPrototype(JS::HandleValue obj, JS::HandleValue proto)
Definition: Interface.cpp:649
bool SetGlobal_(const char *name, JS::HandleValue value, bool replace, bool constant, bool enumerate)
Definition: Interface.cpp:575
NONCOPYABLE(Interface)
bool ReplaceNondeterministicRNG(boost::random::rand48 &rng)
Replace the default JS random number generator with a seeded, network-synced one.
Definition: Interface.cpp:477
Context & GetContext() const
Definition: Interface.cpp:504
JSObject * CreateCustomObject(const std::string &typeName) const
Definition: Interface.cpp:563
bool SetGlobal(const char *name, const T &value, bool replace=false, bool constant=true, bool enumerate=true)
Set the named property on the global object.
Definition: Interface.h:331
bool MathRandom(double &nbr) const
Calls the random number generator assigned to this Interface instance and returns the generated numbe...
Definition: Interface.cpp:318
static bool Math_random(JSContext *cx, unsigned int argc, JS::Value *vp)
JSNative wrapper of the above.
Definition: Interface.cpp:326
static T * ObjectFromCBData(const Request &rq)
Convert the CmptPrivate callback data to T*.
Definition: Interface.h:151
JSContext * GetGeneralJSContext() const
GetGeneralJSContext returns the context without starting a GC request and without entering the Interf...
Definition: Interface.cpp:499
bool LoadGlobalScript(const VfsPath &filename, const std::string &code) const
Load and execute the given script in the global scope.
Definition: Interface.cpp:694
bool LoadGlobalScripts()
Load global scripts that most script interfaces need, located in the /globalscripts directory.
Definition: Interface.cpp:458
static T * GetPrivate(const Request &rq, JS::HandleObject thisobj)
Retrieve the private data field of a JSObject.
Definition: Interface.h:273
Interface(const char *nativeScopeName, const char *debugName, const Interface &neighbor, std::function< bool(const VfsPath &)> allowModule={})
Alternate constructor.
CmptPrivate m_CmptPrivate
Definition: Interface.h:315
static bool GetGlobalProperty(const Request &rq, const std::string &name, JS::MutableHandleValue out)
Get an object from the global scope or any lexical scope.
Definition: Interface.cpp:619
Interface(const char *nativeScopeName, const char *debugName, Context &context, std::function< bool(const VfsPath &)> allowModule={})
Constructor.
Definition: Interface.cpp:387
bool LoadScript(const VfsPath &filename, const std::string &code) const
Load and execute the given script in a new function scope.
Definition: Interface.cpp:659
std::unordered_map< std::string, CustomType > m_CustomObjectTypes
Definition: Interface.h:321
~Interface()
Definition: Interface.cpp:424
Interface(const char *nativeScopeName, const char *debugName, Context &&context, std::function< bool(const VfsPath &)> allowModule={})
Definition: Interface.h:111
std::unique_ptr< Interface_impl > m
Definition: Interface.h:319
ModuleLoader & GetModuleLoader() const
Definition: Interface.cpp:509
bool Eval(const std::string_view code) const
Evaluate some JS code in the global scope.
Definition: Interface.cpp:738
static T * GetPrivate(const Request &rq, JS::CallArgs &callArgs)
Retrieve the private data field of a JS Object.
Definition: Interface.h:288
static T * ObjectFromCBData(const Request &rq, JS::CallArgs &)
Variant for the function wrapper.
Definition: Interface.h:161
void SetCallbackData(void *pCBData)
Definition: Interface.cpp:447
void CallConstructor(JS::HandleValue ctor, JS::HandleValueArray argv, JS::MutableHandleValue out) const
Call a constructor function, equivalent to JS "new ctor(arg)".
Definition: Interface.cpp:514
JSObjectReservedSlots
Name the reserved slots we may need to use in custom JSObjects.
Definition: Interface.h:265
@ PRIVATE
Definition: Interface.h:266
Definition: ModuleLoader.h:46
Definition: Request.h:51
JSContext * cx
Definition: Request.h:83
void Raise(const Request &rq, const char *format,...)
Raise a JS exception from C++ code.
Definition: Exceptions.cpp:111
Abstraction around a SpiderMonkey JSContext.
Definition: DapInterface.h:32
bool FromJSVal(const Request &rq, const JS::HandleValue val, T &ret)
Convert a JS::Value to a C++ type.
void ToJSVal(const Request &rq, JS::MutableHandleValue ret, T const &val)
Convert a C++ type to a JS::Value.
Definition: Interface.h:46
ERROR_GROUP(Scripting)
ERROR_SUBGROUP(Scripting, LoadFile)
ERROR_TYPE(Scripting, SetupFailed)
thread_local std::shared_ptr< Script::Context > g_ScriptContext
Definition: GameSetup.cpp:133
#define T(string_literal)
Definition: secure_crt.cpp:81
Definition: Interface.h:135
void * pCBData
Definition: Interface.h:142
Interface * pScriptInterface
Definition: Interface.h:141
static void * GetCBData(JSContext *cx)
Definition: Interface.cpp:441
static const Interface & GetScriptInterface(JSContext *cx)
Definition: Interface.cpp:434
Definition: Interface.h:309
JSClass * m_Class
Definition: Interface.h:311
JSNative m_Constructor
Definition: Interface.h:312
JS::PersistentRootedObject m_Prototype
Definition: Interface.h:310
static void out(const wchar_t *fmt,...)
Definition: wdbg_sym.cpp:407