LuaScript.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/CoreEvents.h"
  5. #include "../Core/ProcessUtils.h"
  6. #include "../Core/Profiler.h"
  7. #include "../Engine/EngineEvents.h"
  8. #include "../IO/File.h"
  9. #include "../IO/FileSystem.h"
  10. #include "../IO/Log.h"
  11. #include "../LuaScript/LuaFile.h"
  12. #include "../LuaScript/LuaFunction.h"
  13. #include "../LuaScript/LuaScript.h"
  14. #include "../LuaScript/LuaScriptEventInvoker.h"
  15. #include "../LuaScript/LuaScriptInstance.h"
  16. #include "../Resource/ResourceCache.h"
  17. #include "../Scene/Scene.h"
  18. extern "C"
  19. {
  20. #include <lualib.h>
  21. }
  22. #include <toluapp/tolua++.h>
  23. #include "../LuaScript/ToluaUtils.h"
  24. #include "../DebugNew.h"
  25. extern int tolua_AudioLuaAPI_open(lua_State*);
  26. extern int tolua_CoreLuaAPI_open(lua_State*);
  27. extern int tolua_EngineLuaAPI_open(lua_State*);
  28. extern int tolua_GraphicsLuaAPI_open(lua_State*);
  29. extern int tolua_InputLuaAPI_open(lua_State*);
  30. extern int tolua_IOLuaAPI_open(lua_State*);
  31. extern int tolua_MathLuaAPI_open(lua_State*);
  32. #ifdef URHO3D_NAVIGATION
  33. extern int tolua_NavigationLuaAPI_open(lua_State*);
  34. #endif
  35. #ifdef URHO3D_NETWORK
  36. extern int tolua_NetworkLuaAPI_open(lua_State*);
  37. #endif
  38. #ifdef URHO3D_DATABASE
  39. extern int tolua_DatabaseLuaAPI_open(lua_State*);
  40. #endif
  41. #ifdef URHO3D_IK
  42. extern int tolua_IKLuaAPI_open(lua_State*);
  43. #endif
  44. #ifdef URHO3D_PHYSICS
  45. extern int tolua_PhysicsLuaAPI_open(lua_State*);
  46. #endif
  47. #ifdef URHO3D_PHYSICS2D
  48. extern int tolua_Physics2DLuaAPI_open(lua_State*);
  49. #endif
  50. extern int tolua_ResourceLuaAPI_open(lua_State*);
  51. extern int tolua_SceneLuaAPI_open(lua_State*);
  52. extern int tolua_UILuaAPI_open(lua_State*);
  53. #ifdef URHO3D_URHO2D
  54. extern int tolua_Urho2DLuaAPI_open(lua_State*);
  55. #endif
  56. extern int tolua_LuaScriptLuaAPI_open(lua_State*);
  57. namespace Urho3D
  58. {
  59. LuaScript::LuaScript(Context* context) :
  60. Object(context),
  61. luaState_(nullptr),
  62. executeConsoleCommands_(false)
  63. {
  64. RegisterLuaScriptLibrary(context_);
  65. luaState_ = luaL_newstate();
  66. if (!luaState_)
  67. {
  68. URHO3D_LOGERROR("Could not create Lua state");
  69. return;
  70. }
  71. lua_atpanic(luaState_, &LuaScript::AtPanic);
  72. luaL_openlibs(luaState_);
  73. RegisterLoader();
  74. ReplacePrint();
  75. tolua_MathLuaAPI_open(luaState_);
  76. tolua_CoreLuaAPI_open(luaState_);
  77. tolua_IOLuaAPI_open(luaState_);
  78. tolua_ResourceLuaAPI_open(luaState_);
  79. tolua_SceneLuaAPI_open(luaState_);
  80. tolua_AudioLuaAPI_open(luaState_);
  81. tolua_EngineLuaAPI_open(luaState_);
  82. tolua_GraphicsLuaAPI_open(luaState_);
  83. tolua_InputLuaAPI_open(luaState_);
  84. #ifdef URHO3D_NAVIGATION
  85. tolua_NavigationLuaAPI_open(luaState_);
  86. #endif
  87. #ifdef URHO3D_NETWORK
  88. tolua_NetworkLuaAPI_open(luaState_);
  89. #endif
  90. #ifdef URHO3D_DATABASE
  91. tolua_DatabaseLuaAPI_open(luaState_);
  92. #endif
  93. #ifdef URHO3D_IK
  94. tolua_IKLuaAPI_open(luaState_);
  95. #endif
  96. #ifdef URHO3D_PHYSICS
  97. tolua_PhysicsLuaAPI_open(luaState_);
  98. #endif
  99. #ifdef URHO3D_PHYSICS2D
  100. tolua_Physics2DLuaAPI_open(luaState_);
  101. #endif
  102. tolua_UILuaAPI_open(luaState_);
  103. #ifdef URHO3D_URHO2D
  104. tolua_Urho2DLuaAPI_open(luaState_);
  105. #endif
  106. tolua_LuaScriptLuaAPI_open(luaState_);
  107. SetContext(luaState_, context_);
  108. eventInvoker_ = new LuaScriptEventInvoker(context_);
  109. coroutineUpdate_ = GetFunction("coroutine.update");
  110. // Subscribe to post update
  111. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(LuaScript, HandlePostUpdate));
  112. // Subscribe to console commands
  113. SetExecuteConsoleCommands(true);
  114. }
  115. LuaScript::~LuaScript()
  116. {
  117. functionPointerToFunctionMap_.Clear();
  118. functionNameToFunctionMap_.Clear();
  119. lua_State* luaState = luaState_;
  120. luaState_ = nullptr;
  121. coroutineUpdate_ = nullptr;
  122. if (luaState)
  123. lua_close(luaState);
  124. }
  125. void LuaScript::AddEventHandler(const String& eventName, int index)
  126. {
  127. LuaFunction* function = GetFunction(index);
  128. if (function)
  129. eventInvoker_->AddEventHandler(nullptr, eventName, function);
  130. }
  131. void LuaScript::AddEventHandler(const String& eventName, const String& functionName)
  132. {
  133. LuaFunction* function = GetFunction(functionName);
  134. if (function)
  135. eventInvoker_->AddEventHandler(nullptr, eventName, function);
  136. }
  137. void LuaScript::AddEventHandler(Object* sender, const String& eventName, int index)
  138. {
  139. if (!sender)
  140. return;
  141. LuaFunction* function = GetFunction(index);
  142. if (function)
  143. eventInvoker_->AddEventHandler(sender, eventName, function);
  144. }
  145. void LuaScript::AddEventHandler(Object* sender, const String& eventName, const String& functionName)
  146. {
  147. if (!sender)
  148. return;
  149. LuaFunction* function = GetFunction(functionName);
  150. if (function)
  151. eventInvoker_->AddEventHandler(sender, eventName, function);
  152. }
  153. void LuaScript::RemoveEventHandler(const String& eventName)
  154. {
  155. eventInvoker_->UnsubscribeFromEvent(eventName);
  156. }
  157. void LuaScript::RemoveEventHandler(Object* sender, const String& eventName)
  158. {
  159. if (!sender)
  160. return;
  161. eventInvoker_->UnsubscribeFromEvent(sender, eventName);
  162. }
  163. void LuaScript::RemoveEventHandlers(Object* sender)
  164. {
  165. if (!sender)
  166. return;
  167. eventInvoker_->UnsubscribeFromEvents(sender);
  168. }
  169. void LuaScript::RemoveAllEventHandlers()
  170. {
  171. eventInvoker_->UnsubscribeFromAllEvents();
  172. }
  173. void LuaScript::RemoveEventHandlersExcept(const Vector<String>& exceptionNames)
  174. {
  175. PODVector<StringHash> exceptionTypes(exceptionNames.Size());
  176. for (unsigned i = 0; i < exceptionTypes.Size(); ++i)
  177. exceptionTypes[i] = StringHash(exceptionNames[i]);
  178. eventInvoker_->UnsubscribeFromAllEventsExcept(exceptionTypes, true);
  179. }
  180. bool LuaScript::HasEventHandler(const String& eventName) const
  181. {
  182. return eventInvoker_->HasSubscribedToEvent(eventName);
  183. }
  184. bool LuaScript::HasEventHandler(Object* sender, const String& eventName) const
  185. {
  186. return eventInvoker_->HasSubscribedToEvent(sender, eventName);
  187. }
  188. bool LuaScript::ExecuteFile(const String& fileName)
  189. {
  190. URHO3D_PROFILE(ExecuteFile);
  191. #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER
  192. if (ExecuteRawFile(fileName))
  193. return true;
  194. #endif
  195. auto* cache = GetSubsystem<ResourceCache>();
  196. auto* luaFile = cache->GetResource<LuaFile>(fileName);
  197. return luaFile && luaFile->LoadAndExecute(luaState_);
  198. }
  199. bool LuaScript::ExecuteString(const String& string)
  200. {
  201. URHO3D_PROFILE(ExecuteString);
  202. if (luaL_dostring(luaState_, string.CString()))
  203. {
  204. const char* message = lua_tostring(luaState_, -1);
  205. URHO3D_LOGERRORF("Execute Lua string failed: %s", message);
  206. lua_pop(luaState_, 1);
  207. return false;
  208. }
  209. return true;
  210. }
  211. bool LuaScript::LoadRawFile(const String& fileName)
  212. {
  213. URHO3D_PROFILE(LoadRawFile);
  214. URHO3D_LOGINFO("Finding Lua file on file system: " + fileName);
  215. auto* cache = GetSubsystem<ResourceCache>();
  216. String filePath = cache->GetResourceFileName(fileName);
  217. if (filePath.Empty())
  218. {
  219. URHO3D_LOGINFO("Lua file not found: " + fileName);
  220. return false;
  221. }
  222. filePath = GetNativePath(filePath);
  223. URHO3D_LOGINFO("Loading Lua file from file system: " + filePath);
  224. if (luaL_loadfile(luaState_, filePath.CString()))
  225. {
  226. const char* message = lua_tostring(luaState_, -1);
  227. URHO3D_LOGERRORF("Load Lua file failed: %s", message);
  228. lua_pop(luaState_, 1);
  229. return false;
  230. }
  231. URHO3D_LOGINFO("Lua file loaded: " + filePath);
  232. return true;
  233. }
  234. bool LuaScript::ExecuteRawFile(const String& fileName)
  235. {
  236. URHO3D_PROFILE(ExecuteRawFile);
  237. if (!LoadRawFile(fileName))
  238. return false;
  239. if (lua_pcall(luaState_, 0, 0, 0))
  240. {
  241. const char* message = lua_tostring(luaState_, -1);
  242. URHO3D_LOGERRORF("Execute Lua file failed: %s", message);
  243. lua_pop(luaState_, 1);
  244. return false;
  245. }
  246. return true;
  247. }
  248. bool LuaScript::ExecuteFunction(const String& functionName)
  249. {
  250. LuaFunction* function = GetFunction(functionName);
  251. return function && function->BeginCall() && function->EndCall();
  252. }
  253. void LuaScript::SetExecuteConsoleCommands(bool enable)
  254. {
  255. if (enable == executeConsoleCommands_)
  256. return;
  257. executeConsoleCommands_ = enable;
  258. if (enable)
  259. SubscribeToEvent(E_CONSOLECOMMAND, URHO3D_HANDLER(LuaScript, HandleConsoleCommand));
  260. else
  261. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  262. }
  263. void LuaScript::RegisterLoader()
  264. {
  265. // Get package.loaders table
  266. lua_getglobal(luaState_, "package");
  267. lua_getfield(luaState_, -1, "loaders");
  268. // Add LuaScript::Loader to the end of the table
  269. lua_pushinteger(luaState_, lua_objlen(luaState_, -1) + 1);
  270. lua_pushcfunction(luaState_, &LuaScript::Loader);
  271. lua_settable(luaState_, -3);
  272. lua_pop(luaState_, 2);
  273. }
  274. int LuaScript::AtPanic(lua_State* L)
  275. {
  276. String errorMessage = luaL_checkstring(L, -1);
  277. URHO3D_LOGERROR("Lua error: Error message = '" + errorMessage + "'");
  278. lua_pop(L, 1);
  279. return 0;
  280. }
  281. int LuaScript::Loader(lua_State* L)
  282. {
  283. // Get module name
  284. String fileName(luaL_checkstring(L, 1));
  285. #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER
  286. // First attempt to load lua script file from the file system
  287. // Attempt to load .luc file first, then fall back to .lua
  288. auto* lua = ::GetContext(L)->GetSubsystem<LuaScript>();
  289. if (lua->LoadRawFile(fileName + ".luc") || lua->LoadRawFile(fileName + ".lua"))
  290. return 1;
  291. #endif
  292. auto* cache = ::GetContext(L)->GetSubsystem<ResourceCache>();
  293. // Attempt to get .luc file first
  294. auto* lucFile = cache->GetResource<LuaFile>(fileName + ".luc", false);
  295. if (lucFile)
  296. return lucFile->LoadChunk(L) ? 1 : 0;
  297. // Then try to get .lua file. If this also fails, error is logged and
  298. // resource not found event is sent
  299. auto* luaFile = cache->GetResource<LuaFile>(fileName + ".lua");
  300. if (luaFile)
  301. return luaFile->LoadChunk(L) ? 1 : 0;
  302. return 0;
  303. }
  304. void LuaScript::ReplacePrint()
  305. {
  306. static const struct luaL_reg reg[] =
  307. {
  308. {"print", &LuaScript::Print},
  309. {nullptr, nullptr}
  310. };
  311. lua_getglobal(luaState_, "_G");
  312. luaL_register(luaState_, nullptr, reg);
  313. lua_pop(luaState_, 1);
  314. }
  315. int LuaScript::Print(lua_State* L)
  316. {
  317. int n = lua_gettop(L);
  318. Vector<String> strings((unsigned)n);
  319. // Call the tostring function repeatedly for each arguments in the stack
  320. lua_getglobal(L, "tostring");
  321. for (int i = 1; i <= n; ++i)
  322. {
  323. lua_pushvalue(L, -1);
  324. lua_pushvalue(L, i);
  325. lua_call(L, 1, 1);
  326. const char* s = lua_tostring(L, -1);
  327. lua_pop(L, 1);
  328. if (s)
  329. strings[i - 1] = s;
  330. else
  331. {
  332. lua_pop(L, 1);
  333. return luaL_error(L, LUA_QL("tostring") " failed at index %d to return a string to " LUA_QL("print"), i);
  334. }
  335. }
  336. lua_pop(L, 1);
  337. URHO3D_LOGRAWF("%s\n", String::Joined(strings, " ").CString());
  338. return 0;
  339. }
  340. LuaFunction* LuaScript::GetFunction(int index)
  341. {
  342. if (!lua_isfunction(luaState_, index))
  343. return nullptr;
  344. const void* functionPointer = lua_topointer(luaState_, index);
  345. if (!functionPointer)
  346. return nullptr;
  347. HashMap<const void*, SharedPtr<LuaFunction>>::Iterator i = functionPointerToFunctionMap_.Find(functionPointer);
  348. if (i != functionPointerToFunctionMap_.End())
  349. return i->second_;
  350. SharedPtr<LuaFunction> function(new LuaFunction(luaState_, index));
  351. functionPointerToFunctionMap_[functionPointer] = function;
  352. return function;
  353. }
  354. LuaFunction* LuaScript::GetFunction(const String& functionName, bool silentIfNotFound)
  355. {
  356. if (!luaState_)
  357. return nullptr;
  358. HashMap<String, SharedPtr<LuaFunction>>::Iterator i = functionNameToFunctionMap_.Find(functionName);
  359. if (i != functionNameToFunctionMap_.End())
  360. return i->second_;
  361. SharedPtr<LuaFunction> function;
  362. if (PushLuaFunction(luaState_, functionName))
  363. {
  364. function = GetFunction(-1);
  365. functionNameToFunctionMap_[functionName] = function;
  366. }
  367. else if (!silentIfNotFound)
  368. URHO3D_LOGERRORF("%s", lua_tostring(luaState_, -1));
  369. lua_pop(luaState_, 1);
  370. return function;
  371. }
  372. void LuaScript::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  373. {
  374. if (coroutineUpdate_ && coroutineUpdate_->BeginCall())
  375. {
  376. using namespace PostUpdate;
  377. float timeStep = eventData[P_TIMESTEP].GetFloat();
  378. coroutineUpdate_->PushFloat(timeStep);
  379. coroutineUpdate_->EndCall();
  380. }
  381. // Collect garbage
  382. {
  383. URHO3D_PROFILE(LuaCollectGarbage);
  384. lua_gc(luaState_, LUA_GCSTEP, 0);
  385. }
  386. }
  387. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  388. {
  389. using namespace ConsoleCommand;
  390. if (eventData[P_ID].GetString() == GetTypeName())
  391. ExecuteString(eventData[P_COMMAND].GetString());
  392. }
  393. bool LuaScript::PushLuaFunction(lua_State* L, const String& functionName)
  394. {
  395. Vector<String> splitNames = functionName.Split('.');
  396. String currentName = splitNames.Front();
  397. lua_getglobal(L, currentName.CString());
  398. if (splitNames.Size() > 1)
  399. {
  400. for (unsigned i = 0; i < splitNames.Size() - 1; ++i)
  401. {
  402. if (i)
  403. {
  404. currentName = currentName + "." + splitNames[i];
  405. lua_getfield(L, -1, splitNames[i].CString());
  406. lua_replace(L, -2);
  407. }
  408. if (!lua_istable(L, -1))
  409. {
  410. lua_pop(L, 1);
  411. lua_pushstring(L, ("Could not find Lua table: Table name = '" + currentName + "'").CString());
  412. return false;
  413. }
  414. }
  415. currentName = currentName + "." + splitNames.Back();
  416. lua_getfield(L, -1, splitNames.Back().CString());
  417. lua_replace(L, -2);
  418. }
  419. if (!lua_isfunction(L, -1))
  420. {
  421. lua_pop(L, 1);
  422. lua_pushstring(L, ("Could not find Lua function: Function name = '" + currentName + "'").CString());
  423. return false;
  424. }
  425. return true;
  426. }
  427. void RegisterLuaScriptLibrary(Context* context)
  428. {
  429. LuaFile::RegisterObject(context);
  430. LuaScriptInstance::RegisterObject(context);
  431. }
  432. }