Pioneer
LuaObject.h
Go to the documentation of this file.
1 // Copyright © 2008-2022 Pioneer Developers. See AUTHORS.txt for details
2 // Licensed under the terms of the GPL v3. See licenses/GPL-3.txt
3 
4 #ifndef _LUAOBJECT_H
5 #define _LUAOBJECT_H
6 
7 #include "DeleteEmitter.h"
8 #include "Lua.h"
9 #include "LuaPushPull.h"
10 #include "LuaRef.h"
11 #include "LuaUtils.h"
12 #include "LuaWrappable.h"
13 #include "RefCounted.h"
14 #include "galaxy/SystemPath.h"
15 #include <tuple>
16 #include <typeinfo>
17 
18 //
19 // LuaObject provides proxy objects and tracking facilities to safely get
20 // objects in and out of lua. the basic idea is that for every class you want
21 // to expose to lua, you define LuaObject wrapper class that defines the
22 // lua name lua name, methods and metamethods for that class. you then call
23 // methods on this class to push and pull objects to and from the lua stack
24 //
25 // Push an object to the Lua stack:
26 //
27 // // C++-owned, still responsible for deletion
28 // Ship *s = new Ship("wave");
29 // LuaObject<Ship>::PushToLua(s);
30 //
31 // // RefCounted, Lua will take a reference
32 // StarSystem *s = Pi::GetGalaxy()->GetStarSystem(SystemPath(0,0,0,0));
33 // LuaObject<StarSystem>::PushToLua(s);
34 //
35 // // Stack-allocated, Lua will get a copy
36 // SystemPath path(0,0,0,0,1);
37 // LuaObject<SystemPath>::PushToLua(path);
38 //
39 // // Create an object, fully owned by lua
40 // // WARNING! the lifetime of an object will be determined by the lua garbage
41 // // collector, so a pointer to it should not be stored in any form on the C++ side
42 // LuaObject<Ship>::CreateInLua(ship_id); // constructor arguments are passed
43 //
44 // Get an object from the Lua stack at index n. Causes a Lua exception if the
45 // object doesn't exist or the types don't match.
46 //
47 // Ship *s = LuaObject<Ship>::CheckFromLua(1);
48 //
49 // Or alternatively, get it and return 0 on failure.
50 //
51 // Ship *s = LuaObject<Ship>::GetFromLua(1);
52 //
53 //
54 // If you need to expose a new class to Lua:
55 //
56 // - Have it inherit from LuaWrappable
57 //
58 // - Have it either:
59 // - inherit from DeleteEmitter
60 // - inherit from RefCounted
61 // - implement a copy constructor
62 //
63 // - Arrange for the wrapper class RegisterClass() method to be called in
64 // LuaInit in Pi.cpp
65 //
66 // - Make a new file LuaWhatever.cpp implement RegisterClass() and any
67 // methods, metamethods and attribute methods you want. Copy from one of the
68 // other files to get the idea
69 //
70 // - Add the new file to the build system
71 //
72 
73 // type for promotion test callbacks
74 typedef bool (*PromotionTest)(LuaWrappable *o);
75 
76 /*
77  * SerializerPair stores object hooks for serializing and deserializing objects
78  * into and out of json. The serialization mechanism functions in a type-erased
79  * manner; the hook is responsible for loading the serialized object from the
80  * Lua stack and in turn pushing the deserialized object on the stack as well.
81  */
83  // Serializer takes a lua object on the top of the stack and writes it to `out`
84  using Serializer = bool (*)(lua_State *l, Json &out);
85  // Deserializer takes `obj` and creates a lua object on the top of the stack
86  using Deserializer = bool (*)(lua_State *l, const Json &obj);
87 
89  serialize(nullptr),
90  deserialize(nullptr)
91  {}
92 
93  SerializerPair(Serializer serialize_, Deserializer deserialize_) :
94  serialize(serialize_),
95  deserialize(deserialize_)
96  {}
97 
100 };
101 
102 class PropertyMap;
103 class LuaMetaTypeBase;
104 
105 // wrapper baseclass, and extra bits for getting at certain parts of the
106 // LuaObject layer
108  friend class LuaSerializer;
109 
110 public:
111  // creates a single "typeless" object and attaches the listed methods,
112  // attributes and metamethods to it. leaves the created object on the
113  // stack
114  static void CreateObject(const luaL_Reg *methods, const luaL_Reg *attrs, const luaL_Reg *meta, bool protect = false);
115 
116  // Creates a single "typeless" object and attaches the given metatype
117  // to it. Leaves the created object on the stack.
118  static void CreateObject(LuaMetaTypeBase *metaType);
119 
120  // Checks if the object at the stack position is a PropertiedObject and returns a pointer to
121  // its PropertyMap. Returns nullptr on failure.
122  static PropertyMap *GetPropertiesFromObject(lua_State *l, int object);
123 
124  // register a serializer pair for a given type
125  static void RegisterSerializer(const char *type, SerializerPair pair);
126 
127 protected:
128  // base class constructor, called by the wrapper Push* methods
129  LuaObjectBase(const char *type) :
130  m_type(type){};
131  virtual ~LuaObjectBase() {}
132 
133  // creates a class in the lua vm with the given name and attaches the
134  // listed methods to it and the listed metamethods to its metaclass. if
135  // attributes extra magic is added to the metaclass to make them work as
136  // expected
137  static void CreateClass(const char *type, const char *parent, const luaL_Reg *methods, const luaL_Reg *attrs, const luaL_Reg *meta);
138 
139  // Creates a class in the lua vm with the given name and attaches the
140  // listed metatype to it. All method, attribute, and metamethod handling
141  // is contained in the metatype.
142  static void CreateClass(LuaMetaTypeBase *metaType);
143 
144  // push an already-registered object onto the lua stack. the object is
145  // looked up in the lua registry, if it exists its userdata its userdata
146  // is pushed onto the lua stack. returns true if the object exists and was
147  // pushed, false otherwise
148  static bool PushRegistered(LuaWrappable *o);
149 
150  // adds an object->wrapper mapping to the registry for the given wrapper
151  // object. the wrapper's corresponding userdata should be on the top of
152  // the stack
153  static void Register(LuaObjectBase *lo);
154 
155  // remove the object->wrapper from the registry. checks to make sure the
156  // the mapping matches first, to protect against memory being reused
157  static void Deregister(LuaObjectBase *lo);
158 
159  // pulls an object off the lua stack and returns its associated c++
160  // object. type is the lua type string of the object. a lua exception is
161  // triggered if the object on the stack is not of this type
162  static LuaWrappable *CheckFromLua(int index, const char *type);
163 
164  // does exactly the same as Check without triggering exceptions
165  static LuaWrappable *GetFromLua(int index, const char *type);
166 
167  // register a promotion test. when an object with lua type base_type is
168  // pushed, test_fn will be called. if it returns true then the created lua
169  // object will be of target_type
170  static void RegisterPromotion(const char *base_type, const char *target_type, PromotionTest test_fn);
171 
172  // Take a lua object at the top of the stack and serialize it to Json
173  static bool SerializeToJson(lua_State *l, Json &out);
174 
175  // Take a json object and deserialize it to a lua object
176  static bool DeserializeFromJson(lua_State *l, const Json &obj);
177 
178  // allocate n bytes from Lua memory and leave it an associated userdata on
179  // the stack. this is a wrapper around lua_newuserdata
180  static void *Allocate(size_t n);
181 
182  // get a pointer to the underlying object
183  virtual LuaWrappable *GetObject() const = 0;
184 
185  const char *GetType() const { return m_type; }
186 
187 private:
188  LuaObjectBase() {}
189  LuaObjectBase(const LuaObjectBase &) {}
190 
191  // Lua-side helper functionality, declared in LuaObject.cpp
192  friend class LuaObjectHelpers;
193 
194  // determine if the object has a class in its ancestry
195  bool Isa(const char *base) const;
196 
197  // lua type (ie method/metatable name)
198  const char *m_type;
199 };
200 
201 // templated portion of the wrapper baseclass
202 template <typename T>
203 class LuaObject : public LuaObjectBase {
204 public:
205  // registers the class with the lua vm
206  static void RegisterClass();
207 
208  // wrap an object and push it onto the stack. these create a wrapper
209  // object that knows how to deal with the type of object
210  static inline void PushToLua(DeleteEmitter *o); // LuaCoreObject
211  static inline void PushToLua(RefCounted *o); // LuaSharedObject
212  static inline void PushToLua(const T &o); // LuaCopyObject
213  template <typename... Args>
214  static inline void CreateInLua(Args &&... args);
215 
216  template <typename Ret, typename Key, typename... Args>
217  static inline Ret CallMethod(T *o, const Key &key, const Args &... args);
218  template <typename Key, typename... Args>
219  static inline void CallMethod(T *o, const Key &key, const Args &... args)
220  {
221  CallMethod<bool>(o, key, args...);
222  }
223 
224  template <typename Ret1, typename Ret2, typename... Ret, typename Key, typename... Args>
225  static inline std::tuple<Ret1, Ret2, Ret...> CallMethod(T *o, const Key &key, const Args &... args);
226 
227  // pull an object off the stack, unwrap and return it
228  // if not found or doesn't match the type, throws a lua exception
229  static inline T *CheckFromLua(int idx)
230  {
231 #ifdef __clang__
232 #pragma clang diagnostic push
233 #pragma clang diagnostic ignored "-Wundefined-var-template"
234 #endif
235  return dynamic_cast<T *>(LuaObjectBase::CheckFromLua(idx, s_type));
236 #ifdef __clang__
237 #pragma clang diagnostic pop
238 #endif
239  }
240 
241  // same but without error checks. returns 0 on failure
242  static inline T *GetFromLua(int idx)
243  {
244 #ifdef __clang__
245 #pragma clang diagnostic push
246 #pragma clang diagnostic ignored "-Wundefined-var-template"
247 #endif
248  return dynamic_cast<T *>(LuaObjectBase::GetFromLua(idx, s_type));
249 #ifdef __clang__
250 #pragma clang diagnostic pop
251 #endif
252  }
253 
254  // standard cast promotion test for convenience
255  static inline bool DynamicCastPromotionTest(LuaWrappable *o)
256  {
257  return dynamic_cast<T *>(o);
258  }
259 
260 protected:
261 #ifdef __clang__
262 #pragma clang diagnostic push
263 #pragma clang diagnostic ignored "-Wundefined-var-template"
264 #endif
266  LuaObjectBase(s_type)
267  {}
268 #ifdef __clang__
269 #pragma clang diagnostic pop
270 #endif
271 
272 private:
273  // initial lua type string. defined in a specialisation in the appropriate
274  // .cpp file
275  static const char *s_type;
276 };
277 
278 // wrapper for a "core" object - one owned by c++ (eg Body).
279 // Lua needs to know when the object is deleted so that it can handle
280 // requests for it appropriately (ie with an exception, or exists())
281 template <typename T>
282 class LuaCoreObject : public LuaObject<T> {
283 public:
285  m_object(o)
286  {
287  m_deleteConnection = m_object->DeleteEmitter::onDelete.connect(sigc::mem_fun(this, &LuaCoreObject::OnDelete));
288  }
289 
291  {
292  if (m_deleteConnection.connected())
293  m_deleteConnection.disconnect();
294  }
295 
297  {
298  return m_object;
299  }
300 
301 private:
302  void OnDelete()
303  {
305  m_object = 0;
306  }
307 
308  T *m_object;
309  sigc::connection m_deleteConnection;
310 };
311 
312 // wrapper for a "shared" object - one that can comfortably exist in both
313 // environments. usually for long-lived (StarSystem) or standalone (UI
314 // widget) objects
315 // Lua simply needs to keep a reference to these
316 template <typename T>
317 class LuaSharedObject : public LuaObject<T> {
318 public:
320  m_object(o) {}
321 
323  {
324  return m_object.Get();
325  }
326 
327 private:
328  RefCountedPtr<T> m_object;
329 };
330 
331 // wrapper for a "copied" object. a new one is created via the copy
332 // constructor and fully owned by Lua. good for lightweight POD-style objects
333 // (eg SystemPath)
334 template <typename T>
335 class LuaCopyObject : public LuaObject<T> {
336 public:
337  LuaCopyObject(const T &o)
338  {
339  lua_State *l = Lua::manager->GetLuaState();
340  m_object = new (LuaObjectBase::Allocate(sizeof(T))) T(o);
341  m_ref = LuaRef(l, -1);
342  lua_pop(l, 1);
343  }
344 
346  {
347  m_object->~T();
348  m_object = 0;
349  }
350 
352  {
353  return m_object;
354  }
355 
356 private:
357  T *m_object;
358  LuaRef m_ref;
359 };
360 
361 // wrapper for a "lua-owned" object.
362 // the wrapper is deleted by lua gc, and when it is deleted, it also deletes the wrapped object
363 template <typename T>
364 class LuaOwnObject : public LuaObject<T> {
365 public:
367  {
368  m_object = o;
369  }
370 
372  {
373  delete (m_object);
374  }
375 
377  {
378  return m_object;
379  }
380 
381 private:
382  T *m_object;
383 };
384 
385 // push methods, create wrappers if necessary
386 // wrappers are allocated from Lua memory
387 template <typename T>
389 {
390  if (!PushRegistered(o))
391  Register(new (LuaObjectBase::Allocate(sizeof(LuaCoreObject<T>))) LuaCoreObject<T>(static_cast<T *>(o)));
392 }
393 
394 template <typename T>
396 {
397  if (!PushRegistered(o))
398  Register(new (LuaObjectBase::Allocate(sizeof(LuaSharedObject<T>))) LuaSharedObject<T>(static_cast<T *>(o)));
399 }
400 
401 template <typename T>
402 inline void LuaObject<T>::PushToLua(const T &o)
403 {
405 }
406 
407 template <typename T>
408 template <typename... Args>
409 inline void LuaObject<T>::CreateInLua(Args &&... args)
410 {
411  T *p(new T(std::forward<Args>(args)...));
412  Register(new (LuaObjectBase::Allocate(sizeof(LuaOwnObject<T>))) LuaOwnObject<T>(static_cast<T *>(p)));
413 }
414 
415 template <typename T>
416 template <typename Ret, typename Key, typename... Args>
417 inline Ret LuaObject<T>::CallMethod(T *o, const Key &key, const Args &... args)
418 {
419  lua_State *l = Lua::manager->GetLuaState();
420  LUA_DEBUG_START(l);
421  Ret return_value;
422 
423  lua_checkstack(l, sizeof...(args) + 5);
424  PushToLua(o);
425  pi_lua_generic_push(l, key);
426  lua_gettable(l, -2);
427  lua_pushvalue(l, -2);
428  lua_remove(l, -3);
429  pi_lua_multiple_push(l, args...);
430  pi_lua_protected_call(l, sizeof...(args) + 1, 1);
431  pi_lua_generic_pull(l, -1, return_value);
432  lua_pop(l, 1);
433  LUA_DEBUG_END(l, 0);
434  return return_value;
435 }
436 
437 template <typename T>
438 template <typename Ret1, typename Ret2, typename... Ret, typename Key, typename... Args>
439 inline std::tuple<Ret1, Ret2, Ret...> LuaObject<T>::CallMethod(T *o, const Key &key, const Args &... args)
440 {
441  lua_State *l = Lua::manager->GetLuaState();
442 
443  LUA_DEBUG_START(l);
444  lua_checkstack(l, sizeof...(args) + 5);
445  PushToLua(o);
446  pi_lua_generic_push(l, key);
447  lua_gettable(l, -2);
448  lua_pushvalue(l, -2);
449  lua_remove(l, -3);
450  pi_lua_multiple_push(l, args...);
451  pi_lua_protected_call(l, sizeof...(args) + 1, 2 + sizeof...(Ret));
452  auto ret_values = pi_lua_multiple_pull<Ret1, Ret2, Ret...>(l, -2 - static_cast<int>(sizeof...(Ret)));
453  lua_pop(l, 2 + static_cast<int>(sizeof...(Ret)));
454  LUA_DEBUG_END(l, 0);
455  return ret_values;
456 }
457 
458 // specialise for SystemPath, which needs custom machinery to deduplicate system paths
459 class SystemPath;
460 template <>
462 
463 inline void pi_lua_generic_pull(lua_State *l, int index, SystemPath &out)
464 {
465  assert(l == Lua::manager->GetLuaState());
467 }
468 
469 inline void pi_lua_generic_push(lua_State *l, const SystemPath &value)
470 {
471  assert(l == Lua::manager->GetLuaState());
473 }
474 
475 // LuaPushPull stuff.
476 template <class T>
477 void pi_lua_generic_pull(lua_State *l, int index, T *&out)
478 {
479  assert(l == Lua::manager->GetLuaState());
481 }
482 
483 template <class T>
484 bool pi_lua_strict_pull(lua_State *l, int index, T *&out)
485 {
486  assert(l == Lua::manager->GetLuaState());
488  return out != 0;
489 }
490 
491 template <class T>
492 void pi_lua_generic_push(lua_State *l, T *value)
493 {
494  assert(l == Lua::manager->GetLuaState());
495  if (value)
497  else
498  lua_pushnil(l);
499 }
500 
501 // LuaPushPull stuff.
502 template <class T>
503 void pi_lua_generic_pull(lua_State *l, int index, RefCountedPtr<T> &out)
504 {
505  assert(l == Lua::manager->GetLuaState());
507 }
508 
509 template <class T>
510 bool pi_lua_strict_pull(lua_State *l, int index, RefCountedPtr<T> &out)
511 {
512  assert(l == Lua::manager->GetLuaState());
514  return out != 0;
515 }
516 
517 template <class T>
518 void pi_lua_generic_push(lua_State *l, RefCountedPtr<T> value)
519 {
520  assert(l == Lua::manager->GetLuaState());
521  if (value)
523  else
524  lua_pushnil(l);
525 }
526 
527 #endif
nlohmann::json Json
Definition: Json.h:8
void pi_lua_generic_pull(lua_State *l, int index, SystemPath &out)
Definition: LuaObject.h:463
bool(* PromotionTest)(LuaWrappable *o)
Definition: LuaObject.h:74
void pi_lua_generic_push(lua_State *l, const SystemPath &value)
Definition: LuaObject.h:469
bool pi_lua_strict_pull(lua_State *l, int index, T *&out)
Definition: LuaObject.h:484
std::tuple< Types... > pi_lua_multiple_pull(lua_State *l, int beg)
Definition: LuaPushPull.h:217
void pi_lua_multiple_push(lua_State *l, Types... args)
#define LUA_DEBUG_START(luaptr)
Definition: LuaUtils.h:100
#define LUA_DEBUG_END(luaptr, expectedStackDiff)
Definition: LuaUtils.h:101
void pi_lua_protected_call(lua_State *L, int nargs, int nresults)
Definition: Sandbox.cpp:172
Definition: DeleteEmitter.h:16
Definition: LuaObject.h:335
LuaCopyObject(const T &o)
Definition: LuaObject.h:337
LuaWrappable * GetObject() const
Definition: LuaObject.h:351
~LuaCopyObject()
Definition: LuaObject.h:345
Definition: LuaObject.h:282
LuaCoreObject(T *o)
Definition: LuaObject.h:284
~LuaCoreObject()
Definition: LuaObject.h:290
LuaWrappable * GetObject() const
Definition: LuaObject.h:296
lua_State * GetLuaState()
Definition: LuaManager.h:14
Definition: LuaMetaType.h:44
Definition: LuaObject.h:107
static void CreateObject(const luaL_Reg *methods, const luaL_Reg *attrs, const luaL_Reg *meta, bool protect=false)
Definition: LuaObject.cpp:287
static void * Allocate(size_t n)
Definition: LuaObject.cpp:745
const char * GetType() const
Definition: LuaObject.h:185
virtual LuaWrappable * GetObject() const =0
static LuaWrappable * CheckFromLua(int index, const char *type)
Definition: LuaObject.cpp:589
LuaObjectBase(const char *type)
Definition: LuaObject.h:129
static PropertyMap * GetPropertiesFromObject(lua_State *l, int object)
Definition: LuaObject.cpp:238
static LuaWrappable * GetFromLua(int index, const char *type)
Definition: LuaObject.cpp:609
static void RegisterPromotion(const char *base_type, const char *target_type, PromotionTest test_fn)
Definition: LuaObject.cpp:665
static bool SerializeToJson(lua_State *l, Json &out)
Definition: LuaObject.cpp:692
static void CreateClass(const char *type, const char *parent, const luaL_Reg *methods, const luaL_Reg *attrs, const luaL_Reg *meta)
Definition: LuaObject.cpp:346
virtual ~LuaObjectBase()
Definition: LuaObject.h:131
static bool PushRegistered(LuaWrappable *o)
Definition: LuaObject.cpp:453
static void Register(LuaObjectBase *lo)
Definition: LuaObject.cpp:487
static void RegisterSerializer(const char *type, SerializerPair pair)
Definition: LuaObject.cpp:670
static void Deregister(LuaObjectBase *lo)
Definition: LuaObject.cpp:567
static bool DeserializeFromJson(lua_State *l, const Json &obj)
Definition: LuaObject.cpp:723
Definition: LuaObject.cpp:95
Definition: LuaObject.h:203
static void CreateInLua(Args &&... args)
Definition: LuaObject.h:409
static void CallMethod(T *o, const Key &key, const Args &... args)
Definition: LuaObject.h:219
static void PushToLua(DeleteEmitter *o)
Definition: LuaObject.h:388
static T * CheckFromLua(int idx)
Definition: LuaObject.h:229
LuaObject()
Definition: LuaObject.h:265
static bool DynamicCastPromotionTest(LuaWrappable *o)
Definition: LuaObject.h:255
static T * GetFromLua(int idx)
Definition: LuaObject.h:242
static Ret CallMethod(T *o, const Key &key, const Args &... args)
Definition: LuaObject.h:417
static void RegisterClass()
Definition: LuaObject.h:364
LuaWrappable * GetObject() const
Definition: LuaObject.h:376
~LuaOwnObject()
Definition: LuaObject.h:371
LuaOwnObject(T *o)
Definition: LuaObject.h:366
Definition: LuaRef.h:12
Definition: LuaSerializer.h:12
Definition: LuaObject.h:317
LuaSharedObject(T *o)
Definition: LuaObject.h:319
LuaWrappable * GetObject() const
Definition: LuaObject.h:322
Definition: LuaWrappable.h:13
Definition: PropertyMap.h:11
Definition: RefCounted.h:36
Definition: RefCounted.h:11
T * Get() const
Definition: SmartPtr.h:37
Definition: SystemPath.h:13
const Color4ub * GetFromLua(lua_State *L, int idx)
Definition: LuaColor.cpp:290
void PushToLua(lua_State *L, const Color4ub &v)
Definition: LuaColor.h:14
Color4ub * CheckFromLua(lua_State *L, int idx)
Definition: LuaColor.cpp:295
void Register(lua_State *L)
Definition: LuaColor.cpp:253
LuaManager * manager
Definition: Lua.cpp:43
Definition: GeomTree.h:9
Definition: LuaObject.h:82
SerializerPair(Serializer serialize_, Deserializer deserialize_)
Definition: LuaObject.h:93
bool(*)(lua_State *l, const Json &obj) Deserializer
Definition: LuaObject.h:86
SerializerPair()
Definition: LuaObject.h:88
Serializer serialize
Definition: LuaObject.h:98
Deserializer deserialize
Definition: LuaObject.h:99