LuaScript.cpp 15 KB

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