LuaBinder.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // Copyright (C) 2009-2023, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Script/LuaBinder.h>
  6. #include <AnKi/Util/Logger.h>
  7. #include <AnKi/Util/Tracer.h>
  8. namespace anki {
  9. // Forward
  10. #define ANKI_SCRIPT_CALL_WRAP(x_) void wrapModule##x_(lua_State*)
  11. ANKI_SCRIPT_CALL_WRAP(Logger);
  12. ANKI_SCRIPT_CALL_WRAP(Math);
  13. ANKI_SCRIPT_CALL_WRAP(Renderer);
  14. ANKI_SCRIPT_CALL_WRAP(Scene);
  15. #undef ANKI_SCRIPT_CALL_WRAP
  16. static void wrapModules(lua_State* l)
  17. {
  18. #define ANKI_SCRIPT_CALL_WRAP(x_) wrapModule##x_(l)
  19. ANKI_SCRIPT_CALL_WRAP(Logger);
  20. ANKI_SCRIPT_CALL_WRAP(Math);
  21. ANKI_SCRIPT_CALL_WRAP(Renderer);
  22. ANKI_SCRIPT_CALL_WRAP(Scene);
  23. #undef ANKI_SCRIPT_CALL_WRAP
  24. }
  25. static int luaPanic(lua_State* l)
  26. {
  27. ANKI_SCRIPT_LOGF("Lua panic attack: %s", lua_tostring(l, -1));
  28. return 0;
  29. }
  30. LuaBinder::LuaBinder()
  31. {
  32. m_l = lua_newstate(luaAllocCallback, this);
  33. luaL_openlibs(m_l);
  34. lua_atpanic(m_l, &luaPanic);
  35. wrapModules(m_l);
  36. }
  37. LuaBinder::~LuaBinder()
  38. {
  39. if(m_l)
  40. {
  41. lua_close(m_l);
  42. }
  43. }
  44. void* LuaBinder::luaAllocCallback([[maybe_unused]] void* userData, void* ptr, PtrSize osize, PtrSize nsize)
  45. {
  46. ANKI_ASSERT(userData);
  47. #if 1
  48. void* out = nullptr;
  49. if(nsize == 0)
  50. {
  51. if(ptr != nullptr)
  52. {
  53. ScriptMemoryPool::getSingleton().free(ptr);
  54. }
  55. }
  56. else
  57. {
  58. // Should be doing something like realloc
  59. if(ptr == nullptr)
  60. {
  61. out = ScriptMemoryPool::getSingleton().allocate(nsize, 16);
  62. }
  63. else if(nsize <= osize)
  64. {
  65. out = ptr;
  66. }
  67. else
  68. {
  69. // realloc
  70. out = ScriptMemoryPool::getSingleton().allocate(nsize, 16);
  71. memcpy(out, ptr, osize);
  72. ScriptMemoryPool::getSingleton().free(ptr);
  73. }
  74. }
  75. #else
  76. void* out = nullptr;
  77. if(nsize == 0)
  78. {
  79. free(ptr);
  80. }
  81. else
  82. {
  83. out = realloc(ptr, nsize);
  84. }
  85. #endif
  86. return out;
  87. }
  88. Error LuaBinder::evalString(lua_State* state, const CString& str)
  89. {
  90. ANKI_TRACE_SCOPED_EVENT(LuaExec);
  91. Error err = Error::kNone;
  92. int e = luaL_dostring(state, &str[0]);
  93. if(e)
  94. {
  95. ANKI_SCRIPT_LOGE("%s", lua_tostring(state, -1));
  96. lua_pop(state, 1);
  97. err = Error::kUserData;
  98. }
  99. garbageCollect(state);
  100. return err;
  101. }
  102. void LuaBinder::createClass(lua_State* l, const LuaUserDataTypeInfo* typeInfo)
  103. {
  104. ANKI_ASSERT(typeInfo);
  105. lua_newtable(l); // push new table
  106. lua_setglobal(l, typeInfo->m_typeName); // pop and make global
  107. luaL_newmetatable(l, typeInfo->m_typeName); // push
  108. lua_pushstring(l, "__index"); // push
  109. lua_pushvalue(l, -2); // pushes copy of the metatable
  110. lua_settable(l, -3); // pop*2: metatable.__index = metatable
  111. // After all these the metatable is in the top of tha stack
  112. // Now, store the typeInfo
  113. void* ud;
  114. lua_getallocf(l, &ud);
  115. ANKI_ASSERT(ud);
  116. LuaBinder& binder = *static_cast<LuaBinder*>(ud);
  117. binder.m_userDataSigToDataInfo.emplace(typeInfo->m_signature, typeInfo);
  118. }
  119. void LuaBinder::pushLuaCFuncMethod(lua_State* l, const char* name, lua_CFunction luafunc)
  120. {
  121. lua_pushstring(l, name);
  122. lua_pushcfunction(l, luafunc);
  123. lua_settable(l, -3);
  124. }
  125. void LuaBinder::pushLuaCFuncStaticMethod(lua_State* l, const char* className, const char* name, lua_CFunction luafunc)
  126. {
  127. lua_getglobal(l, className); // push
  128. lua_pushcfunction(l, luafunc); // push
  129. lua_setfield(l, -2, name); // pop global
  130. lua_pop(l, 1); // pop cfunc
  131. }
  132. void LuaBinder::pushLuaCFunc(lua_State* l, const char* name, lua_CFunction luafunc)
  133. {
  134. lua_register(l, name, luafunc);
  135. }
  136. Error LuaBinder::checkNumberInternal(lua_State* l, I32 stackIdx, lua_Number& number)
  137. {
  138. Error err = Error::kNone;
  139. lua_Number lnum;
  140. int isnum;
  141. lnum = lua_tonumberx(l, stackIdx, &isnum);
  142. if(isnum)
  143. {
  144. number = lnum;
  145. }
  146. else
  147. {
  148. err = Error::kUserData;
  149. lua_pushfstring(l, "Number expected. Got %s", luaL_typename(l, stackIdx));
  150. }
  151. return err;
  152. }
  153. Error LuaBinder::checkString(lua_State* l, I32 stackIdx, const char*& out)
  154. {
  155. Error err = Error::kNone;
  156. const char* s = lua_tolstring(l, stackIdx, nullptr);
  157. if(s != nullptr)
  158. {
  159. out = s;
  160. }
  161. else
  162. {
  163. err = Error::kUserData;
  164. lua_pushfstring(l, "String expected. Got %s", luaL_typename(l, stackIdx));
  165. }
  166. return err;
  167. }
  168. Error LuaBinder::checkUserData(lua_State* l, I32 stackIdx, const LuaUserDataTypeInfo& typeInfo, LuaUserData*& out)
  169. {
  170. Error err = Error::kNone;
  171. void* p = lua_touserdata(l, stackIdx);
  172. if(p != nullptr)
  173. {
  174. out = reinterpret_cast<LuaUserData*>(p);
  175. if(out->getSig() == typeInfo.m_signature)
  176. {
  177. // Check using a LUA method again
  178. ANKI_ASSERT(luaL_testudata(l, stackIdx, typeInfo.m_typeName) != nullptr && "ANKI type check passes but LUA's type check failed");
  179. }
  180. else
  181. {
  182. // It's not the correct user data
  183. err = Error::kUserData;
  184. }
  185. }
  186. else
  187. {
  188. // It's not user data
  189. err = Error::kUserData;
  190. }
  191. if(err)
  192. {
  193. lua_pushfstring(l, "Userdata of %s expected. Got %s", typeInfo.m_typeName, luaL_typename(l, stackIdx));
  194. }
  195. return err;
  196. }
  197. Error LuaBinder::checkArgsCount(lua_State* l, I argsCount)
  198. {
  199. const I actualArgsCount = lua_gettop(l);
  200. if(argsCount != actualArgsCount)
  201. {
  202. lua_pushfstring(l, "Expecting %d arguments, got %d", argsCount, actualArgsCount);
  203. return Error::kUserData;
  204. }
  205. return Error::kNone;
  206. }
  207. void LuaBinder::serializeGlobals(lua_State* l, LuaBinderSerializeGlobalsCallback& callback)
  208. {
  209. ANKI_ASSERT(l);
  210. lua_pushglobaltable(l);
  211. lua_pushnil(l);
  212. while(lua_next(l, -2) != 0)
  213. {
  214. // Get type of key and value
  215. I keyType = lua_type(l, -2);
  216. I valueType = lua_type(l, -1);
  217. // Only string keys
  218. if(keyType != LUA_TSTRING)
  219. {
  220. lua_pop(l, 1);
  221. continue;
  222. }
  223. CString keyString = lua_tostring(l, -2);
  224. if(keyString.isEmpty() || keyString.getLength() == 0 || keyString[0] == '_')
  225. {
  226. lua_pop(l, 1);
  227. continue;
  228. }
  229. switch(valueType)
  230. {
  231. case LUA_TNUMBER:
  232. {
  233. // Write name
  234. callback.write(keyString.cstr(), keyString.getLength() + 1);
  235. // Write type
  236. U32 type = LUA_TNUMBER;
  237. callback.write(&type, sizeof(type));
  238. // Write value
  239. F64 val = lua_tonumber(l, -1);
  240. callback.write(&val, sizeof(val));
  241. break;
  242. }
  243. case LUA_TSTRING:
  244. {
  245. // Write name
  246. callback.write(keyString.cstr(), keyString.getLength() + 1);
  247. // Write type
  248. U32 type = LUA_TSTRING;
  249. callback.write(&type, sizeof(type));
  250. // Write str len
  251. CString val = lua_tostring(l, -1);
  252. callback.write(val.cstr(), val.getLength() + 1);
  253. break;
  254. }
  255. case LUA_TUSERDATA:
  256. {
  257. LuaUserData* ud = static_cast<LuaUserData*>(lua_touserdata(l, -1));
  258. ANKI_ASSERT(ud);
  259. LuaUserDataSerializeCallback cb = ud->getDataTypeInfo().m_serializeCallback;
  260. if(cb)
  261. {
  262. Array<U8, 256> buff;
  263. PtrSize dumpSize;
  264. cb(*ud, nullptr, dumpSize);
  265. if(dumpSize <= buff.getSize())
  266. {
  267. cb(*ud, &buff[0], dumpSize);
  268. }
  269. else
  270. {
  271. ANKI_ASSERT(!"TODO");
  272. }
  273. // Write name
  274. callback.write(keyString.cstr(), keyString.getLength() + 1);
  275. // Write type
  276. U32 type = LUA_TUSERDATA;
  277. callback.write(&type, sizeof(type));
  278. // Write sig
  279. callback.write(&ud->getDataTypeInfo().m_signature, sizeof(ud->getDataTypeInfo().m_signature));
  280. // Write data
  281. PtrSize size = dumpSize;
  282. callback.write(&size, sizeof(size));
  283. callback.write(&buff[0], dumpSize);
  284. }
  285. else
  286. {
  287. ANKI_SCRIPT_LOGW("Can't serialize variable %s. No callback provided", keyString.cstr());
  288. }
  289. break;
  290. }
  291. }
  292. lua_pop(l, 1);
  293. }
  294. }
  295. void LuaBinder::deserializeGlobals(lua_State* l, const void* data, PtrSize dataSize)
  296. {
  297. ANKI_ASSERT(dataSize > 0 && data);
  298. const U8* ptr = static_cast<const U8*>(data);
  299. const U8* end = ptr + dataSize;
  300. while(ptr < end)
  301. {
  302. // Get name
  303. CString name = reinterpret_cast<const char*>(ptr);
  304. U32 len = name.getLength();
  305. ANKI_ASSERT(len > 0);
  306. ptr += len + 1;
  307. // Get type
  308. I type = *reinterpret_cast<const U32*>(ptr);
  309. ptr += sizeof(U32);
  310. switch(type)
  311. {
  312. case LUA_TNUMBER:
  313. {
  314. const F64 val = *reinterpret_cast<const F64*>(ptr);
  315. ptr += sizeof(F64);
  316. lua_pushnumber(l, val);
  317. lua_setglobal(l, name.cstr());
  318. break;
  319. }
  320. case LUA_TSTRING:
  321. {
  322. CString val = reinterpret_cast<const char*>(ptr);
  323. const U len = val.getLength();
  324. ptr += len + 1;
  325. ANKI_ASSERT(len > 0);
  326. lua_pushstring(l, val.cstr());
  327. lua_setglobal(l, name.cstr());
  328. break;
  329. }
  330. case LUA_TUSERDATA:
  331. {
  332. // Get sig
  333. const I64 sig = *reinterpret_cast<const I64*>(ptr);
  334. ptr += sizeof(sig);
  335. // Get input data size
  336. const PtrSize dataSize = *reinterpret_cast<const PtrSize*>(ptr);
  337. ptr += sizeof(dataSize);
  338. // Get the type info
  339. void* ud;
  340. lua_getallocf(l, &ud);
  341. ANKI_ASSERT(ud);
  342. LuaBinder& binder = *static_cast<LuaBinder*>(ud);
  343. auto it = binder.m_userDataSigToDataInfo.find(sig);
  344. ANKI_ASSERT(it != binder.m_userDataSigToDataInfo.getEnd());
  345. const LuaUserDataTypeInfo* typeInfo = *it;
  346. // Create user data
  347. LuaUserData* userData = static_cast<LuaUserData*>(lua_newuserdata(l, typeInfo->m_structureSize));
  348. userData->initGarbageCollected(typeInfo);
  349. ANKI_ASSERT(typeInfo->m_deserializeCallback);
  350. typeInfo->m_deserializeCallback(ptr, *userData);
  351. ptr += dataSize;
  352. luaL_setmetatable(l, typeInfo->m_typeName);
  353. lua_setglobal(l, name.cstr());
  354. break;
  355. }
  356. }
  357. }
  358. }
  359. } // end namespace anki