LuaBinder.cpp 9.7 KB

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