OpenTTD Source 20250924-master-gbec4e71d53
squirrel.hpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#ifndef SQUIRREL_HPP
11#define SQUIRREL_HPP
12
13#include <squirrel.h>
14#include "../core/convertible_through_base.hpp"
15
17enum class ScriptType : uint8_t {
18 AI,
19 GS,
20};
21
22struct ScriptAllocator;
23
24class Squirrel {
25 friend class ScriptAllocatorScope;
26 friend class ScriptInstance;
27
28private:
29 using SQPrintFunc = void (bool error_msg, std::string_view message);
30
31 HSQUIRRELVM vm;
33 SQPrintFunc *print_func;
34 bool crashed;
36 std::string_view api_name;
37 std::unique_ptr<ScriptAllocator> allocator;
38
42 static SQInteger _RunError(HSQUIRRELVM vm);
43
47 std::string_view GetAPIName() { return this->api_name; }
48
50 void Initialize();
52 void Uninitialize();
53
54protected:
58 static void CompileError(HSQUIRRELVM vm, std::string_view desc, std::string_view source, SQInteger line, SQInteger column);
59
63 static void RunError(HSQUIRRELVM vm, std::string_view error);
64
68 static void PrintFunc(HSQUIRRELVM vm, std::string_view s);
69
73 static void ErrorPrintFunc(HSQUIRRELVM vm, std::string_view s);
74
75public:
76 Squirrel(std::string_view api_name);
77 ~Squirrel();
78
82 HSQUIRRELVM GetVM() { return this->vm; }
83
89 bool LoadScript(const std::string &script);
90 bool LoadScript(HSQUIRRELVM vm, const std::string &script, bool in_root = true);
91
95 SQRESULT LoadFile(HSQUIRRELVM vm, const std::string &filename, SQBool printerror);
96
101 void AddMethod(std::string_view method_name, SQFUNCTION proc, std::string_view params = {}, void *userdata = nullptr, int size = 0);
102
107 void AddConst(std::string_view var_name, SQInteger value);
108
113 void AddConst(std::string_view var_name, uint value) { this->AddConst(var_name, (SQInteger)value); }
114
119 void AddConst(std::string_view var_name, int value) { this->AddConst(var_name, (SQInteger)value); }
120
121 void AddConst(std::string_view var_name, const ConvertibleThroughBase auto &value) { this->AddConst(var_name, static_cast<SQInteger>(value.base())); }
122
127 void AddConst(std::string_view var_name, bool value);
128
133 void AddClassBegin(std::string_view class_name);
134
139 void AddClassBegin(std::string_view class_name, std::string_view parent_class);
140
145 void AddClassEnd();
146
150 bool Resume(int suspend = -1);
151
155 void ResumeError();
156
160 void CollectGarbage();
161
162 void InsertResult(bool result);
163 void InsertResult(int result);
164 void InsertResult(uint result) { this->InsertResult((int)result); }
165 void InsertResult(ConvertibleThroughBase auto result) { this->InsertResult(static_cast<int>(result.base())); }
166
171 bool CallMethod(HSQOBJECT instance, std::string_view method_name, HSQOBJECT *ret, int suspend);
172 bool CallMethod(HSQOBJECT instance, std::string_view method_name, int suspend) { return this->CallMethod(instance, method_name, nullptr, suspend); }
173 bool CallStringMethod(HSQOBJECT instance, std::string_view method_name, std::string *res, int suspend);
174 bool CallIntegerMethod(HSQOBJECT instance, std::string_view method_name, int *res, int suspend);
175 bool CallBoolMethod(HSQOBJECT instance, std::string_view method_name, bool *res, int suspend);
176
180 bool MethodExists(HSQOBJECT instance, std::string_view method_name);
181
192 static bool CreateClassInstanceVM(HSQUIRRELVM vm, const std::string &class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name = false);
193
197 bool CreateClassInstance(const std::string &class_name, void *real_instance, HSQOBJECT *instance);
198
204 static SQUserPointer GetRealInstance(HSQUIRRELVM vm, int index, std::string_view tag);
205
211 static bool GetInstance(HSQUIRRELVM vm, HSQOBJECT *ptr, int pos = 1) { sq_getclass(vm, pos); sq_getstackobj(vm, pos, ptr); sq_pop(vm, 1); return true; }
212
216 static std::optional<std::string_view> ObjectToString(HSQOBJECT *ptr) { return sq_objtostring(ptr); }
217
221 static int ObjectToInteger(HSQOBJECT *ptr) { return sq_objtointeger(ptr); }
222
226 static bool ObjectToBool(HSQOBJECT *ptr) { return sq_objtobool(ptr) == 1; }
227
232 void SetGlobalPointer(void *ptr) { this->global_pointer = ptr; }
233
237 static void *GetGlobalPointer(HSQUIRRELVM vm) { return ((Squirrel *)sq_getforeignptr(vm))->global_pointer; }
238
242 void SetPrintFunction(SQPrintFunc *func) { this->print_func = func; }
243
247 void ThrowError(std::string_view error) { sq_throwerror(this->vm, error); }
248
252 void ReleaseObject(HSQOBJECT *ptr) { sq_release(this->vm, ptr); }
253
257 static void DecreaseOps(HSQUIRRELVM vm, int amount);
258
263 bool IsSuspended();
264
268 bool HasScriptCrashed();
269
273 void CrashOccurred();
274
278 bool CanSuspend();
279
283 SQInteger GetOpsTillSuspend();
284
288 void Reset();
289
293 size_t GetAllocatedMemory() const noexcept;
294};
295
296
297extern ScriptAllocator *_squirrel_allocator;
298
300 ScriptAllocator *old_allocator;
301
302public:
303 ScriptAllocatorScope(const Squirrel *engine)
304 {
305 this->old_allocator = _squirrel_allocator;
306 /* This may get called with a nullptr engine, in case of a crashed script */
307 _squirrel_allocator = engine != nullptr ? engine->allocator.get() : nullptr;
308 }
309
311 {
312 _squirrel_allocator = this->old_allocator;
313 }
314};
315
316#endif /* SQUIRREL_HPP */
Runtime information about a script like a pointer to the squirrel vm and the current state.
void AddClassEnd()
Finishes adding a class to the global scope.
Definition squirrel.cpp:315
bool Resume(int suspend=-1)
Resume a VM when it was suspended via a throw.
Definition squirrel.cpp:341
static void * GetGlobalPointer(HSQUIRRELVM vm)
Get the pointer as set by SetGlobalPointer.
Definition squirrel.hpp:237
static SQUserPointer GetRealInstance(HSQUIRRELVM vm, int index, std::string_view tag)
Get the real-instance pointer.
Definition squirrel.cpp:493
void AddConst(std::string_view var_name, SQInteger value)
Adds a const to the stack.
Definition squirrel.cpp:273
void * global_pointer
Can be set by who ever initializes Squirrel.
Definition squirrel.hpp:32
void SetPrintFunction(SQPrintFunc *func)
Set a custom print function, so you can handle outputs from SQ yourself.
Definition squirrel.hpp:242
void CollectGarbage()
Tell the VM to do a garbage collection run.
Definition squirrel.cpp:370
HSQUIRRELVM vm
The VirtualMachine instance for squirrel.
Definition squirrel.hpp:31
void Reset()
Completely reset the engine; start from scratch.
Definition squirrel.cpp:741
SQInteger GetOpsTillSuspend()
How many operations can we execute till suspension?
Definition squirrel.cpp:795
bool LoadScript(const std::string &script)
Load a script.
Definition squirrel.cpp:713
bool IsSuspended()
Did the squirrel code suspend or return normally.
Definition squirrel.cpp:774
void ReleaseObject(HSQOBJECT *ptr)
Release a SQ object.
Definition squirrel.hpp:252
bool CanSuspend()
Are we allowed to suspend the squirrel script at this moment?
Definition squirrel.cpp:789
std::string_view api_name
Name of the API used for this squirrel.
Definition squirrel.hpp:36
SQPrintFunc * print_func
Points to either nullptr, or a custom print handler.
Definition squirrel.hpp:33
void AddClassBegin(std::string_view class_name)
Adds a class to the global scope.
Definition squirrel.cpp:291
void ThrowError(std::string_view error)
Throw a Squirrel error that will be nicely displayed to the user.
Definition squirrel.hpp:247
static SQInteger _RunError(HSQUIRRELVM vm)
The internal RunError handler.
Definition squirrel.cpp:230
size_t GetAllocatedMemory() const noexcept
Get number of bytes allocated by this VM.
Definition squirrel.cpp:175
void SetGlobalPointer(void *ptr)
Sets a pointer in the VM that is reachable from where ever you are in SQ.
Definition squirrel.hpp:232
static void DecreaseOps(HSQUIRRELVM vm, int amount)
Tell the VM to remove amount ops from the number of ops till suspend.
Definition squirrel.cpp:769
bool HasScriptCrashed()
Find out if the squirrel script made an error before.
Definition squirrel.cpp:779
void CrashOccurred()
Set the script status to crashed.
Definition squirrel.cpp:784
SQRESULT LoadFile(HSQUIRRELVM vm, const std::string &filename, SQBool printerror)
Load a file to a given VM.
Definition squirrel.cpp:622
HSQUIRRELVM GetVM()
Get the squirrel VM.
Definition squirrel.hpp:82
static void CompileError(HSQUIRRELVM vm, std::string_view desc, std::string_view source, SQInteger line, SQInteger column)
The CompileError handler.
Definition squirrel.cpp:182
static bool GetInstance(HSQUIRRELVM vm, HSQOBJECT *ptr, int pos=1)
Get the Squirrel-instance pointer.
Definition squirrel.hpp:211
static void RunError(HSQUIRRELVM vm, std::string_view error)
The RunError handler.
Definition squirrel.cpp:208
void Initialize()
Perform all initialization steps to create the engine.
Definition squirrel.cpp:516
bool crashed
True if the squirrel script made an error.
Definition squirrel.hpp:34
static void PrintFunc(HSQUIRRELVM vm, std::string_view s)
If a user runs 'print' inside a script, this function gets the params.
Definition squirrel.cpp:245
static bool ObjectToBool(HSQOBJECT *ptr)
Convert a Squirrel-object to a bool.
Definition squirrel.hpp:226
int overdrawn_ops
The amount of operations we have overdrawn.
Definition squirrel.hpp:35
static std::optional< std::string_view > ObjectToString(HSQOBJECT *ptr)
Convert a Squirrel-object to a string.
Definition squirrel.hpp:216
void Uninitialize()
Perform all the cleanups for the engine.
Definition squirrel.cpp:723
std::string_view GetAPIName()
Get the API name.
Definition squirrel.hpp:47
void AddMethod(std::string_view method_name, SQFUNCTION proc, std::string_view params={}, void *userdata=nullptr, int size=0)
Adds a function to the stack.
Definition squirrel.cpp:256
bool CallMethod(HSQOBJECT instance, std::string_view method_name, HSQOBJECT *ret, int suspend)
Call a method of an instance, in various flavors.
Definition squirrel.cpp:376
void AddConst(std::string_view var_name, uint value)
Adds a const to the stack.
Definition squirrel.hpp:113
bool MethodExists(HSQOBJECT instance, std::string_view method_name)
Check if a method exists in an instance.
Definition squirrel.cpp:323
void ResumeError()
Resume the VM with an error so it prints a stack trace.
Definition squirrel.cpp:363
static bool CreateClassInstanceVM(HSQUIRRELVM vm, const std::string &class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name=false)
Creates a class instance.
Definition squirrel.cpp:440
bool CreateClassInstance(const std::string &class_name, void *real_instance, HSQOBJECT *instance)
Exactly the same as CreateClassInstanceVM, only callable without instance of Squirrel.
Definition squirrel.cpp:487
static void ErrorPrintFunc(HSQUIRRELVM vm, std::string_view s)
If an error has to be print, this function is called.
Definition squirrel.cpp:197
void AddConst(std::string_view var_name, int value)
Adds a const to the stack.
Definition squirrel.hpp:119
static int ObjectToInteger(HSQOBJECT *ptr)
Convert a Squirrel-object to an integer.
Definition squirrel.hpp:221
std::unique_ptr< ScriptAllocator > allocator
Allocator object used by this script.
Definition squirrel.hpp:37
A type is considered 'convertible through base()' when it has a 'base()' function that returns someth...
ScriptType
The type of script we're working with, i.e.
Definition squirrel.hpp:17
@ AI
The script is for AI scripts.
@ GS
The script is for Game scripts.