LuaScript.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 "../Core/CoreEvents.h"
  23. #include "../Engine/EngineEvents.h"
  24. #include "../IO/File.h"
  25. #include "../IO/FileSystem.h"
  26. #include "../IO/Log.h"
  27. #include "../LuaScript/LuaFile.h"
  28. #include "../LuaScript/LuaFunction.h"
  29. #include "../LuaScript/LuaScript.h"
  30. #include "../LuaScript/LuaScriptEventInvoker.h"
  31. #include "../LuaScript/LuaScriptInstance.h"
  32. #include "../Core/ProcessUtils.h"
  33. #include "../Core/Profiler.h"
  34. #include "../Resource/ResourceCache.h"
  35. #include "../Scene/Scene.h"
  36. extern "C"
  37. {
  38. #include <lualib.h>
  39. }
  40. #include <toluapp/tolua++.h>
  41. #include "../LuaScript/ToluaUtils.h"
  42. #include "../DebugNew.h"
  43. extern int tolua_AudioLuaAPI_open(lua_State*);
  44. extern int tolua_CoreLuaAPI_open(lua_State*);
  45. extern int tolua_EngineLuaAPI_open(lua_State*);
  46. extern int tolua_GraphicsLuaAPI_open(lua_State*);
  47. extern int tolua_InputLuaAPI_open(lua_State*);
  48. extern int tolua_IOLuaAPI_open(lua_State*);
  49. extern int tolua_MathLuaAPI_open(lua_State*);
  50. #ifdef URHO3D_NAVIGATION
  51. extern int tolua_NavigationLuaAPI_open(lua_State*);
  52. #endif
  53. #ifdef URHO3D_NETWORK
  54. extern int tolua_NetworkLuaAPI_open(lua_State*);
  55. #endif
  56. #ifdef URHO3D_PHYSICS
  57. extern int tolua_PhysicsLuaAPI_open(lua_State*);
  58. #endif
  59. extern int tolua_ResourceLuaAPI_open(lua_State*);
  60. extern int tolua_SceneLuaAPI_open(lua_State*);
  61. extern int tolua_UILuaAPI_open(lua_State*);
  62. #ifdef URHO3D_URHO2D
  63. extern int tolua_Urho2DLuaAPI_open(lua_State*);
  64. #endif
  65. extern int tolua_LuaScriptLuaAPI_open(lua_State*);
  66. namespace Urho3D
  67. {
  68. LuaScript::LuaScript(Context* context) :
  69. Object(context),
  70. luaState_(0),
  71. executeConsoleCommands_(false)
  72. {
  73. RegisterLuaScriptLibrary(context_);
  74. luaState_ = luaL_newstate();
  75. if (!luaState_)
  76. {
  77. LOGERROR("Could not create Lua state");
  78. return;
  79. }
  80. SetContext(luaState_, context_);
  81. lua_atpanic(luaState_, &LuaScript::AtPanic);
  82. luaL_openlibs(luaState_);
  83. RegisterLoader();
  84. ReplacePrint();
  85. tolua_MathLuaAPI_open(luaState_);
  86. tolua_CoreLuaAPI_open(luaState_);
  87. tolua_IOLuaAPI_open(luaState_);
  88. tolua_ResourceLuaAPI_open(luaState_);
  89. tolua_SceneLuaAPI_open(luaState_);
  90. tolua_AudioLuaAPI_open(luaState_);
  91. tolua_EngineLuaAPI_open(luaState_);
  92. tolua_GraphicsLuaAPI_open(luaState_);
  93. tolua_InputLuaAPI_open(luaState_);
  94. #ifdef URHO3D_NAVIGATION
  95. tolua_NavigationLuaAPI_open(luaState_);
  96. #endif
  97. #ifdef URHO3D_NETWORK
  98. tolua_NetworkLuaAPI_open(luaState_);
  99. #endif
  100. #ifdef URHO3D_PHYSICS
  101. tolua_PhysicsLuaAPI_open(luaState_);
  102. #endif
  103. tolua_UILuaAPI_open(luaState_);
  104. #ifdef URHO3D_URHO2D
  105. tolua_Urho2DLuaAPI_open(luaState_);
  106. #endif
  107. tolua_LuaScriptLuaAPI_open(luaState_);
  108. eventInvoker_ = new LuaScriptEventInvoker(context_);
  109. coroutineUpdate_ = GetFunction("coroutine.update");
  110. // Subscribe to post update
  111. SubscribeToEvent(E_POSTUPDATE, 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_ = 0;
  121. SetContext(luaState_, 0);
  122. if (luaState)
  123. lua_close(luaState);
  124. }
  125. void LuaScript::AddEventHandler(const String& eventName, int functionIndex)
  126. {
  127. LuaFunction* function = GetFunction(functionIndex);
  128. if (function)
  129. eventInvoker_->AddEventHandler(0, 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(0, eventName, function);
  136. }
  137. void LuaScript::AddEventHandler(Object* sender, const String& eventName, int functionIndex)
  138. {
  139. if (!sender)
  140. return;
  141. LuaFunction* function = GetFunction(functionIndex);
  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::ExecuteFile(const String& fileName)
  181. {
  182. PROFILE(ExecuteFile);
  183. #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER
  184. if (ExecuteRawFile(fileName))
  185. return true;
  186. #endif
  187. ResourceCache* cache = GetSubsystem<ResourceCache>();
  188. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName);
  189. return luaFile && luaFile->LoadAndExecute(luaState_);
  190. }
  191. bool LuaScript::ExecuteString(const String& string)
  192. {
  193. PROFILE(ExecuteString);
  194. int top = lua_gettop(luaState_);
  195. if (luaL_dostring(luaState_, string.CString()) != 0)
  196. {
  197. const char* message = lua_tostring(luaState_, -1);
  198. LOGERROR("Execute Lua string failed: " + String(message));
  199. lua_settop(luaState_, top);
  200. return false;
  201. }
  202. return true;
  203. }
  204. bool LuaScript::LoadRawFile(const String& fileName)
  205. {
  206. PROFILE(LoadRawFile);
  207. LOGINFO("Finding Lua file on file system: " + fileName);
  208. ResourceCache* cache = GetSubsystem<ResourceCache>();
  209. String filePath = cache->GetResourceFileName(fileName);
  210. if (filePath.Empty())
  211. {
  212. LOGINFO("Lua file not found: " + fileName);
  213. return false;
  214. }
  215. filePath = GetNativePath(filePath);
  216. LOGINFO("Loading Lua file from file system: " + filePath);
  217. int top = lua_gettop(luaState_);
  218. if (luaL_loadfile (luaState_, filePath.CString()))
  219. {
  220. const char* message = lua_tostring(luaState_, -1);
  221. LOGERROR("Load Lua file failed: " + String(message));
  222. lua_settop(luaState_, top);
  223. return false;
  224. }
  225. LOGINFO("Lua file loaded: " + filePath);
  226. return true;
  227. }
  228. bool LuaScript::ExecuteRawFile(const String& fileName)
  229. {
  230. PROFILE(ExecuteRawFile);
  231. int top = lua_gettop(luaState_);
  232. if (!LoadRawFile(fileName))
  233. return false;
  234. if (lua_pcall(luaState_, 0, 0, 0))
  235. {
  236. const char* message = lua_tostring(luaState_, -1);
  237. LOGERROR("Execute Lua file failed: " + String(message));
  238. lua_settop(luaState_, top);
  239. return false;
  240. }
  241. return true;
  242. }
  243. bool LuaScript::ExecuteFunction(const String& functionName)
  244. {
  245. LuaFunction* function = GetFunction(functionName);
  246. return function && function->BeginCall() && function->EndCall();
  247. }
  248. void LuaScript::SendEvent(const String& eventName, VariantMap& eventData)
  249. {
  250. Object::SendEvent(StringHash(eventName), eventData);
  251. }
  252. void LuaScript::SetExecuteConsoleCommands(bool enable)
  253. {
  254. if (enable == executeConsoleCommands_)
  255. return;
  256. executeConsoleCommands_ = enable;
  257. if (enable)
  258. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
  259. else
  260. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  261. }
  262. void LuaScript::RegisterLoader()
  263. {
  264. // Get package.loaders table
  265. lua_getglobal(luaState_, "package");
  266. lua_getfield(luaState_, -1, "loaders");
  267. // Add LuaScript::Loader to the end of the table
  268. lua_pushinteger(luaState_, lua_objlen(luaState_, -1) + 1);
  269. lua_pushcfunction(luaState_, &LuaScript::Loader);
  270. lua_settable(luaState_, -3);
  271. lua_pop(luaState_, 2);
  272. }
  273. int LuaScript::AtPanic(lua_State* L)
  274. {
  275. String errorMessage = luaL_checkstring(L, -1);
  276. LOGERROR("Lua error: Error message = '" + errorMessage + "'");
  277. lua_pop(L, 1);
  278. return 0;
  279. }
  280. int LuaScript::Loader(lua_State* L)
  281. {
  282. LuaScript* lua = ::GetContext(L)->GetSubsystem<LuaScript>();
  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. if (
  289. lua->LoadRawFile(fileName + ".luc")
  290. || lua->LoadRawFile(fileName + ".lua")
  291. ) return 1;
  292. #endif
  293. ResourceCache* cache = ::GetContext(L)->GetSubsystem<ResourceCache>();
  294. // Attempt to get .luc file first.
  295. LuaFile* lucFile = cache->GetResource<LuaFile>(fileName + ".luc", false);
  296. if (lucFile)
  297. return lucFile->LoadChunk(L) ? 1 : 0;
  298. // Then try to get .lua file. If this also fails, error is logged and
  299. // resource not found event is sent
  300. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName + ".lua");
  301. if (luaFile)
  302. return luaFile->LoadChunk(L) ? 1 : 0;
  303. return 0;
  304. }
  305. void LuaScript::ReplacePrint()
  306. {
  307. static const struct luaL_reg reg[] =
  308. {
  309. {"print", &LuaScript::Print},
  310. { NULL, NULL}
  311. };
  312. lua_getglobal(luaState_, "_G");
  313. luaL_register(luaState_, NULL, reg);
  314. lua_pop(luaState_, 1);
  315. }
  316. int LuaScript::Print(lua_State *L)
  317. {
  318. String string;
  319. int n = lua_gettop(L);
  320. lua_getglobal(L, "tostring");
  321. for (int i = 1; i <= n; i++)
  322. {
  323. const char *s;
  324. // Function to be called
  325. lua_pushvalue(L, -1);
  326. // Value to print
  327. lua_pushvalue(L, i);
  328. lua_call(L, 1, 1);
  329. // Get result
  330. s = lua_tostring(L, -1);
  331. if (s == NULL)
  332. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  333. if (i > 1)
  334. string.Append(" ");
  335. string.Append(s);
  336. // Pop result
  337. lua_pop(L, 1);
  338. }
  339. LOGRAW(string + "\n");
  340. return 0;
  341. }
  342. LuaFunction* LuaScript::GetFunction(int functionIndex)
  343. {
  344. if (!lua_isfunction(luaState_, functionIndex))
  345. return 0;
  346. const void* functionPointer = lua_topointer(luaState_, functionIndex);
  347. if (!functionPointer)
  348. return 0;
  349. HashMap<const void*, SharedPtr<LuaFunction> >::Iterator i = functionPointerToFunctionMap_.Find(functionPointer);
  350. if (i != functionPointerToFunctionMap_.End())
  351. return i->second_;
  352. lua_pushvalue(luaState_, functionIndex);
  353. int functionRef = luaL_ref(luaState_, LUA_REGISTRYINDEX);
  354. SharedPtr<LuaFunction> function(new LuaFunction(luaState_, functionRef, false));
  355. functionPointerToFunctionMap_[functionPointer] = function;
  356. return function;
  357. }
  358. LuaFunction* LuaScript::GetFunction(const String& functionName, bool silentIfNotFound)
  359. {
  360. if (!luaState_)
  361. return 0;
  362. HashMap<String, SharedPtr<LuaFunction> >::Iterator i = functionNameToFunctionMap_.Find(functionName);
  363. if (i != functionNameToFunctionMap_.End())
  364. return i->second_;
  365. int top = lua_gettop(luaState_);
  366. SharedPtr<LuaFunction> function;
  367. if (PushScriptFunction(functionName, silentIfNotFound))
  368. function = GetFunction(-1);
  369. lua_settop(luaState_, top);
  370. functionNameToFunctionMap_[functionName] = function;
  371. return function;
  372. }
  373. void LuaScript::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  374. {
  375. if (coroutineUpdate_ && coroutineUpdate_->BeginCall())
  376. {
  377. using namespace PostUpdate;
  378. float timeStep = eventData[P_TIMESTEP].GetFloat();
  379. coroutineUpdate_->PushFloat(timeStep);
  380. coroutineUpdate_->EndCall();
  381. }
  382. // Collect garbage
  383. {
  384. PROFILE(LuaCollectGarbage);
  385. lua_gc(luaState_, LUA_GCCOLLECT, 0);
  386. }
  387. }
  388. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  389. {
  390. using namespace ConsoleCommand;
  391. if (eventData[P_ID].GetString() == GetTypeName())
  392. ExecuteString(eventData[P_COMMAND].GetString());
  393. }
  394. bool LuaScript::PushScriptFunction(const String& functionName, bool silentIfNotFound)
  395. {
  396. Vector<String> splitedNames = functionName.Split('.');
  397. String currentName = splitedNames.Front();
  398. lua_getglobal(luaState_, currentName.CString());
  399. if (splitedNames.Size() > 1)
  400. {
  401. if (!lua_istable(luaState_, -1))
  402. {
  403. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  404. return false;
  405. }
  406. for (unsigned i = 1; i < splitedNames.Size() - 1; ++i)
  407. {
  408. currentName = currentName + "." + splitedNames[i];
  409. lua_getfield(luaState_, -1, splitedNames[i].CString());
  410. if (!lua_istable(luaState_, -1))
  411. {
  412. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  413. return false;
  414. }
  415. }
  416. currentName = currentName + "." + splitedNames.Back().CString();
  417. lua_getfield(luaState_, -1, splitedNames.Back().CString());
  418. }
  419. if (!lua_isfunction(luaState_, -1))
  420. {
  421. if (!silentIfNotFound)
  422. LOGERROR("Could not find Lua function: Function name = '" + currentName + "'");
  423. return false;
  424. }
  425. return true;
  426. }
  427. void RegisterLuaScriptLibrary(Context* context)
  428. {
  429. LuaFile::RegisterObject(context);
  430. LuaScriptInstance::RegisterObject(context);
  431. }
  432. }