LuaScript.cpp 15 KB

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