LuaScript.cpp 15 KB

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