2
0

LuaScript.cpp 15 KB

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