LuaBinder.h 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. // Forward
  19. class LuaUserData;
  20. class SceneGraph;
  21. class MainRenderer;
  22. /// @addtogroup script
  23. /// @{
  24. /// @memberof LuaUserData
  25. using LuaUserDataSerializeCallback = void (*)(LuaUserData& self, void* data, PtrSize& size);
  26. /// @memberof LuaUserData
  27. using LuaUserDataDeserializeCallback = void (*)(const void* data, LuaUserData& self);
  28. /// @memberof LuaUserData
  29. class LuaUserDataTypeInfo
  30. {
  31. public:
  32. I64 m_signature;
  33. const char* m_typeName;
  34. PtrSize m_structureSize;
  35. LuaUserDataSerializeCallback m_serializeCallback;
  36. LuaUserDataDeserializeCallback m_deserializeCallback;
  37. };
  38. /// LUA userdata.
  39. class LuaUserData
  40. {
  41. public:
  42. /// @note NEVER ADD A DESTRUCTOR. LUA cannot call that.
  43. ~LuaUserData() = delete;
  44. I64 getSig() const
  45. {
  46. return m_sig;
  47. }
  48. void initGarbageCollected(const LuaUserDataTypeInfo* info)
  49. {
  50. ANKI_ASSERT(info);
  51. m_sig = info->m_signature;
  52. m_info = info;
  53. m_addressOrGarbageCollect = GC_MASK;
  54. }
  55. /// @note Accepting const void* is wrong because getData returns a mutable pointer. Fix that.
  56. void initPointed(const LuaUserDataTypeInfo* info, const void* ptrToObject)
  57. {
  58. ANKI_ASSERT(info);
  59. m_sig = info->m_signature;
  60. m_info = info;
  61. const 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
  127. {
  128. public:
  129. LuaBinder();
  130. LuaBinder(const LuaBinder&) = delete; // Non-copyable
  131. ~LuaBinder();
  132. LuaBinder& operator=(const LuaBinder&) = delete; // Non-copyable
  133. ANKI_USE_RESULT Error init(ScriptAllocator alloc, LuaBinderOtherSystems* otherSystems);
  134. lua_State* getLuaState()
  135. {
  136. ANKI_ASSERT(m_l);
  137. return m_l;
  138. }
  139. ScriptAllocator getAllocator() const
  140. {
  141. return m_alloc;
  142. }
  143. LuaBinderOtherSystems& getOtherSystems()
  144. {
  145. ANKI_ASSERT(m_otherSystems);
  146. return *m_otherSystems;
  147. }
  148. /// Expose a variable to the lua state
  149. template<typename T>
  150. static void exposeVariable(lua_State* state, CString name, T* y)
  151. {
  152. void* ptr = lua_newuserdata(state, sizeof(LuaUserData));
  153. LuaUserData* ud = static_cast<LuaUserData*>(ptr);
  154. ud->initPointed(&LuaUserData::getDataTypeInfoFor<T>(), y);
  155. luaL_setmetatable(state, LuaUserData::getDataTypeInfoFor<T>().m_typeName);
  156. lua_setglobal(state, name.cstr());
  157. }
  158. template<typename T>
  159. static void pushVariableToTheStack(lua_State* state, T* y)
  160. {
  161. void* ptr = lua_newuserdata(state, sizeof(LuaUserData));
  162. LuaUserData* ud = static_cast<LuaUserData*>(ptr);
  163. ud->initPointed(&LuaUserData::getDataTypeInfoFor<T>(), y);
  164. luaL_setmetatable(state, LuaUserData::getDataTypeInfoFor<T>().m_typeName);
  165. }
  166. /// Evaluate a string
  167. static Error evalString(lua_State* state, const CString& str);
  168. static void garbageCollect(lua_State* state)
  169. {
  170. lua_gc(state, LUA_GCCOLLECT, 0);
  171. }
  172. /// For debugging purposes
  173. static void stackDump(lua_State* l);
  174. /// Create a new LUA class
  175. static void createClass(lua_State* l, const LuaUserDataTypeInfo* typeInfo);
  176. /// Add new function in a class that it's already in the stack
  177. static void pushLuaCFuncMethod(lua_State* l, const char* name, lua_CFunction luafunc);
  178. /// Add a new static function in the class.
  179. static void pushLuaCFuncStaticMethod(lua_State* l, const char* className, const char* name, lua_CFunction luafunc);
  180. /// Add a new function.
  181. static void pushLuaCFunc(lua_State* l, const char* name, lua_CFunction luafunc);
  182. /// Dump global variables.
  183. static void serializeGlobals(lua_State* l, LuaBinderSerializeGlobalsCallback& callback);
  184. /// Deserialize global variables.
  185. static void deserializeGlobals(lua_State* l, const void* data, PtrSize dataSize);
  186. /// Make sure that the arguments match the argsCount number
  187. static ANKI_USE_RESULT Error checkArgsCount(lua_State* l, I argsCount);
  188. /// Get a number from the stack.
  189. template<typename TNumber>
  190. static ANKI_USE_RESULT Error checkNumber(lua_State* l, I32 stackIdx, TNumber& number)
  191. {
  192. lua_Number lnum;
  193. Error err = checkNumberInternal(l, stackIdx, lnum);
  194. if(!err)
  195. {
  196. number = TNumber(lnum);
  197. }
  198. return err;
  199. }
  200. /// Get a string from the stack.
  201. static ANKI_USE_RESULT Error checkString(lua_State* l, I32 stackIdx, const char*& out);
  202. /// Get some user data from the stack.
  203. /// The function uses the type signature to validate the type and not the
  204. /// typeName. That is supposed to be faster.
  205. static ANKI_USE_RESULT Error checkUserData(lua_State* l, I32 stackIdx, const LuaUserDataTypeInfo& typeInfo,
  206. LuaUserData*& out);
  207. /// Allocate memory.
  208. static void* luaAlloc(lua_State* l, size_t size, U32 alignment);
  209. /// Free memory.
  210. static void luaFree(lua_State* l, void* ptr);
  211. private:
  212. LuaBinderOtherSystems* m_otherSystems;
  213. ScriptAllocator m_alloc;
  214. lua_State* m_l = nullptr;
  215. HashMap<I64, const LuaUserDataTypeInfo*> m_userDataSigToDataInfo;
  216. static void* luaAllocCallback(void* userData, void* ptr, PtrSize osize, PtrSize nsize);
  217. static ANKI_USE_RESULT Error checkNumberInternal(lua_State* l, I32 stackIdx, lua_Number& number);
  218. };
  219. /// @}
  220. } // end namespace anki