LuaBinder.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Script/Common.h>
  7. #include <AnKi/Util/Assert.h>
  8. #include <AnKi/Util/StdTypes.h>
  9. #include <AnKi/Util/Allocator.h>
  10. #include <AnKi/Util/String.h>
  11. #include <AnKi/Util/Functions.h>
  12. #include <AnKi/Util/HashMap.h>
  13. #include <Lua/lua.hpp>
  14. #ifndef ANKI_LUA_HPP
  15. # error "Wrong LUA header included"
  16. #endif
  17. namespace anki
  18. {
  19. // Forward
  20. class LuaUserData;
  21. class SceneGraph;
  22. class MainRenderer;
  23. /// @addtogroup script
  24. /// @{
  25. /// @memberof LuaUserData
  26. using LuaUserDataSerializeCallback = void (*)(LuaUserData& self, void* data, PtrSize& size);
  27. /// @memberof LuaUserData
  28. using LuaUserDataDeserializeCallback = void (*)(const void* data, LuaUserData& self);
  29. /// @memberof LuaUserData
  30. class LuaUserDataTypeInfo
  31. {
  32. public:
  33. I64 m_signature;
  34. const char* m_typeName;
  35. PtrSize m_structureSize;
  36. LuaUserDataSerializeCallback m_serializeCallback;
  37. LuaUserDataDeserializeCallback m_deserializeCallback;
  38. };
  39. /// LUA userdata.
  40. class LuaUserData
  41. {
  42. public:
  43. /// @note NEVER ADD A DESTRUCTOR. LUA cannot call that.
  44. ~LuaUserData() = delete;
  45. I64 getSig() const
  46. {
  47. return m_sig;
  48. }
  49. void initGarbageCollected(const LuaUserDataTypeInfo* info)
  50. {
  51. ANKI_ASSERT(info);
  52. m_sig = info->m_signature;
  53. m_info = info;
  54. m_addressOrGarbageCollect = GC_MASK;
  55. }
  56. void initPointed(const LuaUserDataTypeInfo* info, void* ptrToObject)
  57. {
  58. ANKI_ASSERT(info);
  59. m_sig = info->m_signature;
  60. m_info = info;
  61. U64 addr = ptrToNumber(ptrToObject);
  62. ANKI_ASSERT((addr & GC_MASK) == 0 && "Address too high, cannot encode a flag");
  63. m_addressOrGarbageCollect = addr;
  64. }
  65. Bool isGarbageCollected() const
  66. {
  67. ANKI_ASSERT(m_addressOrGarbageCollect != 0);
  68. return m_addressOrGarbageCollect == GC_MASK;
  69. }
  70. template<typename T>
  71. T* getData()
  72. {
  73. ANKI_ASSERT(m_addressOrGarbageCollect != 0);
  74. ANKI_ASSERT(getDataTypeInfoFor<T>().m_signature == m_sig);
  75. T* out = nullptr;
  76. if(isGarbageCollected())
  77. {
  78. // Garbage collected, the data -in memory- are after this object
  79. PtrSize mem = ptrToNumber(this);
  80. mem += getAlignedRoundUp(alignof(T), sizeof(LuaUserData));
  81. out = numberToPtr<T*>(mem);
  82. }
  83. else
  84. {
  85. // Pointed
  86. PtrSize mem = static_cast<PtrSize>(m_addressOrGarbageCollect);
  87. out = numberToPtr<T*>(mem);
  88. }
  89. ANKI_ASSERT(out);
  90. ANKI_ASSERT(isAligned(alignof(T), out));
  91. return out;
  92. }
  93. template<typename T>
  94. static PtrSize computeSizeForGarbageCollected()
  95. {
  96. return getAlignedRoundUp(alignof(T), sizeof(LuaUserData)) + sizeof(T);
  97. }
  98. const LuaUserDataTypeInfo& getDataTypeInfo() const
  99. {
  100. ANKI_ASSERT(m_info);
  101. return *m_info;
  102. }
  103. template<typename TWrapedType>
  104. static const LuaUserDataTypeInfo& getDataTypeInfoFor();
  105. private:
  106. static constexpr U64 GC_MASK = U64(1) << U64(63);
  107. I64 m_sig = 0; ///< Signature to identify the user data.
  108. U64 m_addressOrGarbageCollect = 0; ///< Encodes an address or a flag if it's for garbage collection.
  109. const LuaUserDataTypeInfo* m_info = nullptr;
  110. };
  111. /// @memberof LuaBinder
  112. class LuaBinderSerializeGlobalsCallback
  113. {
  114. public:
  115. virtual void write(const void* data, PtrSize dataSize) = 0;
  116. };
  117. /// A list of systems that the LuaBinder should be aware of.
  118. /// @memberof LuaBinder
  119. class LuaBinderOtherSystems
  120. {
  121. public:
  122. SceneGraph* m_sceneGraph;
  123. MainRenderer* m_renderer;
  124. };
  125. /// Lua binder class. A wrapper on top of LUA
  126. class LuaBinder : public NonCopyable
  127. {
  128. public:
  129. LuaBinder();
  130. ~LuaBinder();
  131. ANKI_USE_RESULT Error init(ScriptAllocator alloc, LuaBinderOtherSystems* otherSystems);
  132. lua_State* getLuaState()
  133. {
  134. ANKI_ASSERT(m_l);
  135. return m_l;
  136. }
  137. ScriptAllocator getAllocator() const
  138. {
  139. return m_alloc;
  140. }
  141. LuaBinderOtherSystems& getOtherSystems()
  142. {
  143. ANKI_ASSERT(m_otherSystems);
  144. return *m_otherSystems;
  145. }
  146. /// Expose a variable to the lua state
  147. template<typename T>
  148. static void exposeVariable(lua_State* state, CString name, T* y)
  149. {
  150. void* ptr = lua_newuserdata(state, sizeof(LuaUserData));
  151. LuaUserData* ud = static_cast<LuaUserData*>(ptr);
  152. ud->initPointed(&LuaUserData::getDataTypeInfoFor<T>(), y);
  153. luaL_setmetatable(state, LuaUserData::getDataTypeInfoFor<T>().m_typeName);
  154. lua_setglobal(state, name.cstr());
  155. }
  156. template<typename T>
  157. static void pushVariableToTheStack(lua_State* state, T* y)
  158. {
  159. void* ptr = lua_newuserdata(state, sizeof(LuaUserData));
  160. LuaUserData* ud = static_cast<LuaUserData*>(ptr);
  161. ud->initPointed(&LuaUserData::getDataTypeInfoFor<T>(), y);
  162. luaL_setmetatable(state, LuaUserData::getDataTypeInfoFor<T>().m_typeName);
  163. }
  164. /// Evaluate a string
  165. static Error evalString(lua_State* state, const CString& str);
  166. static void garbageCollect(lua_State* state)
  167. {
  168. lua_gc(state, LUA_GCCOLLECT, 0);
  169. }
  170. /// For debugging purposes
  171. static void stackDump(lua_State* l);
  172. /// Create a new LUA class
  173. static void createClass(lua_State* l, const LuaUserDataTypeInfo* typeInfo);
  174. /// Add new function in a class that it's already in the stack
  175. static void pushLuaCFuncMethod(lua_State* l, const char* name, lua_CFunction luafunc);
  176. /// Add a new static function in the class.
  177. static void pushLuaCFuncStaticMethod(lua_State* l, const char* className, const char* name, lua_CFunction luafunc);
  178. /// Add a new function.
  179. static void pushLuaCFunc(lua_State* l, const char* name, lua_CFunction luafunc);
  180. /// Dump global variables.
  181. static void serializeGlobals(lua_State* l, LuaBinderSerializeGlobalsCallback& callback);
  182. /// Deserialize global variables.
  183. static void deserializeGlobals(lua_State* l, const void* data, PtrSize dataSize);
  184. /// Make sure that the arguments match the argsCount number
  185. static ANKI_USE_RESULT Error checkArgsCount(lua_State* l, I argsCount);
  186. /// Get a number from the stack.
  187. template<typename TNumber>
  188. static ANKI_USE_RESULT Error checkNumber(lua_State* l, I32 stackIdx, TNumber& number)
  189. {
  190. lua_Number lnum;
  191. Error err = checkNumberInternal(l, stackIdx, lnum);
  192. if(!err)
  193. {
  194. number = TNumber(lnum);
  195. }
  196. return err;
  197. }
  198. /// Get a string from the stack.
  199. static ANKI_USE_RESULT Error checkString(lua_State* l, I32 stackIdx, const char*& out);
  200. /// Get some user data from the stack.
  201. /// The function uses the type signature to validate the type and not the
  202. /// typeName. That is supposed to be faster.
  203. static ANKI_USE_RESULT Error checkUserData(lua_State* l, I32 stackIdx, const LuaUserDataTypeInfo& typeInfo,
  204. LuaUserData*& out);
  205. /// Allocate memory.
  206. static void* luaAlloc(lua_State* l, size_t size, U32 alignment);
  207. /// Free memory.
  208. static void luaFree(lua_State* l, void* ptr);
  209. private:
  210. LuaBinderOtherSystems* m_otherSystems;
  211. ScriptAllocator m_alloc;
  212. lua_State* m_l = nullptr;
  213. HashMap<I64, const LuaUserDataTypeInfo*> m_userDataSigToDataInfo;
  214. static void* luaAllocCallback(void* userData, void* ptr, PtrSize osize, PtrSize nsize);
  215. static ANKI_USE_RESULT Error checkNumberInternal(lua_State* l, I32 stackIdx, lua_Number& number);
  216. };
  217. /// @}
  218. } // end namespace anki