LuaBinder.cpp 9.4 KB

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