LuaScript.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. //
  2. // Copyright (c) 2008-2013 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 "EngineEvents.h"
  24. #include "File.h"
  25. #include "Log.h"
  26. #include "LuaFile.h"
  27. #include "LuaScript.h"
  28. #include "LuaScriptInstance.h"
  29. #include "ProcessUtils.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "Scene.h"
  33. #include "ToluaUrho3DEx.h"
  34. extern "C"
  35. {
  36. #include <lua.h>
  37. #include <lualib.h>
  38. #include <lauxlib.h>
  39. }
  40. #include "tolua++.h"
  41. #include "DebugNew.h"
  42. extern int tolua_AudioLuaAPI_open(lua_State*);
  43. extern int tolua_ContainerLuaAPI_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. extern int tolua_NavigationLuaAPI_open(lua_State*);
  51. extern int tolua_NetworkLuaAPI_open(lua_State*);
  52. extern int tolua_PhysicsLuaAPI_open(lua_State*);
  53. extern int tolua_ResourceLuaAPI_open(lua_State*);
  54. extern int tolua_SceneLuaAPI_open(lua_State*);
  55. extern int tolua_UILuaAPI_open(lua_State*);
  56. extern int tolua_LuaScriptLuaAPI_open(lua_State*);
  57. namespace Urho3D
  58. {
  59. static Context* currentContext_ = 0;
  60. LuaScript::LuaScript(Context* context) :
  61. Object(context),
  62. luaState_(0)
  63. {
  64. currentContext_ = context_;
  65. RegisterLuaScriptLibrary(context_);
  66. luaState_ = luaL_newstate();
  67. if (!luaState_)
  68. {
  69. LOGERROR("Could not create Lua state");
  70. return;
  71. }
  72. luaL_openlibs(luaState_);
  73. RegisterLoader();
  74. ReplacePrint();
  75. tolua_AudioLuaAPI_open(luaState_);
  76. tolua_ContainerLuaAPI_open(luaState_);
  77. tolua_CoreLuaAPI_open(luaState_);
  78. tolua_EngineLuaAPI_open(luaState_);
  79. tolua_GraphicsLuaAPI_open(luaState_);
  80. tolua_InputLuaAPI_open(luaState_);
  81. tolua_IOLuaAPI_open(luaState_);
  82. tolua_MathLuaAPI_open(luaState_);
  83. tolua_NavigationLuaAPI_open(luaState_);
  84. tolua_NetworkLuaAPI_open(luaState_);
  85. tolua_PhysicsLuaAPI_open(luaState_);
  86. tolua_ResourceLuaAPI_open(luaState_);
  87. tolua_SceneLuaAPI_open(luaState_);
  88. tolua_UILuaAPI_open(luaState_);
  89. tolua_LuaScriptLuaAPI_open(luaState_);
  90. // Subscribe to console commands
  91. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
  92. }
  93. LuaScript::~LuaScript()
  94. {
  95. for (HashMap<String, int>::Iterator i = functionNameToFunctionRefMap_.Begin(); i != functionNameToFunctionRefMap_.End(); ++i)
  96. {
  97. if (i->second_ != LUA_REFNIL)
  98. luaL_unref(luaState_, LUA_REGISTRYINDEX, i->second_);
  99. }
  100. if (luaState_)
  101. lua_close(luaState_);
  102. }
  103. bool LuaScript::ExecuteFile(const String& fileName)
  104. {
  105. PROFILE(ExecuteFile);
  106. ResourceCache* cache = GetSubsystem<ResourceCache>();
  107. if (!cache)
  108. return false;
  109. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName);
  110. if (!luaFile)
  111. return false;
  112. return luaFile->LoadAndExecute(luaState_);
  113. }
  114. bool LuaScript::ExecuteString(const String& string)
  115. {
  116. PROFILE(ExecuteString);
  117. int top = lua_gettop(luaState_);
  118. if (luaL_dostring(luaState_, string.CString()) != 0)
  119. {
  120. const char* message = lua_tostring(luaState_, -1);
  121. LOGERROR("Execute Lua string failed: " + String(message));
  122. lua_settop(luaState_, top);
  123. return false;
  124. }
  125. return true;
  126. }
  127. bool LuaScript::ExecuteFunction(const String& functionName, const VariantVector& parameters)
  128. {
  129. PROFILE(ExecuteFunction);
  130. int top = lua_gettop(luaState_);
  131. if (!PushScriptFunction(functionName))
  132. {
  133. lua_settop(luaState_, top);
  134. return false;
  135. }
  136. // Push parameters.
  137. if (!tolua_pushurho3dvariantvector(luaState_, parameters))
  138. {
  139. lua_settop(luaState_, top);
  140. return false;
  141. }
  142. if (lua_pcall(luaState_, parameters.Size(), 0, 0))
  143. {
  144. const char* message = lua_tostring(luaState_, -1);
  145. LOGERROR("Execute Lua function failed: " + String(message));
  146. lua_settop(luaState_, top);
  147. return false;
  148. }
  149. return true;
  150. }
  151. void LuaScript::ScriptSendEvent(const String& eventName, VariantMap& eventData)
  152. {
  153. SendEvent(StringHash(eventName), eventData);
  154. }
  155. void LuaScript::ScriptSubscribeToEvent(const String& eventName, const String& functionName)
  156. {
  157. StringHash eventType(eventName);
  158. int functionRef = GetScriptFunctionRef(functionName);
  159. if (functionRef != LUA_REFNIL)
  160. {
  161. SubscribeToEvent(eventType, HANDLER(LuaScript, HandleEvent));
  162. eventTypeToFunctionRefMap_[eventType] = functionRef;
  163. }
  164. }
  165. void LuaScript::ScriptUnsubscribeFromEvent(const String& eventName)
  166. {
  167. StringHash eventType(eventName);
  168. HashMap<StringHash, int>::Iterator i = eventTypeToFunctionRefMap_.Find(eventType);
  169. if (i != eventTypeToFunctionRefMap_.End())
  170. {
  171. UnsubscribeFromEvent(eventType);
  172. eventTypeToFunctionRefMap_.Erase(i);
  173. }
  174. }
  175. void LuaScript::ScriptUnsubscribeFromAllEvents()
  176. {
  177. if (eventTypeToFunctionRefMap_.Empty())
  178. return;
  179. UnsubscribeFromAllEvents();
  180. eventTypeToFunctionRefMap_.Clear();
  181. }
  182. void LuaScript::ScriptSubscribeToEvent(void* sender, const String& eventName, const String& functionName)
  183. {
  184. StringHash eventType(eventName);
  185. Object* object = (Object*)sender;
  186. int functionRef = GetScriptFunctionRef(functionName);
  187. if (functionRef != LUA_REFNIL)
  188. {
  189. SubscribeToEvent(object, eventType, HANDLER(LuaScript, HandleObjectEvent));
  190. objectToEventTypeToFunctionRefMap_[object][eventType] = functionRef;
  191. }
  192. }
  193. void LuaScript::ScriptUnsubscribeFromEvent(void* sender, const String& eventName)
  194. {
  195. StringHash eventType(eventName);
  196. Object* object = (Object*)sender;
  197. HashMap<StringHash, int>::Iterator i = objectToEventTypeToFunctionRefMap_[object].Find(eventType);
  198. if (i != objectToEventTypeToFunctionRefMap_[object].End())
  199. {
  200. UnsubscribeFromEvent(object, eventType);
  201. objectToEventTypeToFunctionRefMap_[object].Erase(i);
  202. }
  203. }
  204. void LuaScript::ScriptUnsubscribeFromEvents(void* sender)
  205. {
  206. Object* object = (Object*)sender;
  207. HashMap<Object*, HashMap<StringHash, int> >::Iterator it = objectToEventTypeToFunctionRefMap_.Find(object);
  208. if (it == objectToEventTypeToFunctionRefMap_.End())
  209. return;
  210. UnsubscribeFromEvents(object);
  211. objectToEventTypeToFunctionRefMap_.Erase(it);
  212. }
  213. void LuaScript::RegisterLoader()
  214. {
  215. // Get package.loaders table.
  216. lua_getglobal(luaState_, "package");
  217. lua_getfield(luaState_, -1, "loaders");
  218. // Add our loader to the end of the table
  219. lua_pushinteger(luaState_, lua_objlen(luaState_, -1) + 1);
  220. lua_pushcfunction(luaState_, &LuaScript::Loader);
  221. lua_settable(luaState_, -3);
  222. lua_pop(luaState_, 2);
  223. }
  224. int LuaScript::Loader(lua_State* L)
  225. {
  226. ResourceCache* cache = currentContext_->GetSubsystem<ResourceCache>();
  227. if (!cache)
  228. return 0;
  229. // Get module name.
  230. const char* name = luaL_checkstring(L, 1);
  231. // Get Lua file from module name.
  232. LuaFile* luaFile = cache->GetResource<LuaFile>(String(name) + ".lua");
  233. if (!luaFile)
  234. return false;
  235. // Load Lua file to Lua chunk.
  236. return luaFile->LoadChunk(L) ? 1 : 0;
  237. }
  238. void LuaScript::ReplacePrint()
  239. {
  240. static const struct luaL_reg reg[] =
  241. {
  242. {"print", &LuaScript::Print},
  243. { NULL, NULL}
  244. };
  245. lua_getglobal(luaState_, "_G");
  246. luaL_register(luaState_, NULL, reg);
  247. lua_pop(luaState_, 1);
  248. }
  249. int LuaScript::Print(lua_State *L)
  250. {
  251. String string;
  252. int n = lua_gettop(L);
  253. lua_getglobal(L, "tostring");
  254. for (int i = 1; i <= n; i++)
  255. {
  256. const char *s;
  257. lua_pushvalue(L, -1); /* function to be called */
  258. lua_pushvalue(L, i); /* value to print */
  259. lua_call(L, 1, 1);
  260. s = lua_tostring(L, -1); /* get result */
  261. if (s == NULL)
  262. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  263. if (i > 1)
  264. string.Append(" "); // fputs("\t", stdout);
  265. string.Append(s); // fputs(s, stdout);
  266. lua_pop(L, 1); /* pop result */
  267. }
  268. LOGRAW("Lua: " + string); // fputs("\n", stdout);
  269. return 0;
  270. }
  271. int LuaScript::GetScriptFunctionRef(const String& functionName, bool silentIfNotFound)
  272. {
  273. HashMap<String, int>::Iterator i = functionNameToFunctionRefMap_.Find(functionName);
  274. if (i != functionNameToFunctionRefMap_.End())
  275. return i->second_;
  276. int top = lua_gettop(luaState_);
  277. int functionRef = LUA_REFNIL;
  278. if (PushScriptFunction(functionName, silentIfNotFound))
  279. functionRef = luaL_ref(luaState_, LUA_REGISTRYINDEX);
  280. lua_settop(luaState_, top);
  281. functionNameToFunctionRefMap_[functionName] = functionRef;
  282. return functionRef;
  283. }
  284. void LuaScript::HandleEvent(StringHash eventType, VariantMap& eventData)
  285. {
  286. int functionRef = eventTypeToFunctionRefMap_[eventType];
  287. if (functionRef == LUA_REFNIL)
  288. return;
  289. CallScriptFunction(functionRef, eventType, eventData);
  290. }
  291. void LuaScript::HandleObjectEvent(StringHash eventType, VariantMap& eventData)
  292. {
  293. Object* object = GetEventSender();
  294. int functionRef = objectToEventTypeToFunctionRefMap_[object][eventType];
  295. if (functionRef == LUA_REFNIL)
  296. return;
  297. CallScriptFunction(functionRef, eventType, eventData);
  298. }
  299. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  300. {
  301. using namespace ConsoleCommand;
  302. ExecuteString(eventData[P_COMMAND].GetString());
  303. }
  304. bool LuaScript::PushScriptFunction(const String& functionName, bool silentIfNotFound)
  305. {
  306. Vector<String> splitedNames = functionName.Split('.');
  307. String currentName = splitedNames.Front();
  308. lua_getglobal(luaState_, currentName.CString());
  309. if (splitedNames.Size() > 1)
  310. {
  311. if (!lua_istable(luaState_, -1))
  312. {
  313. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  314. return false;
  315. }
  316. for (unsigned i = 1; i < splitedNames.Size() - 1; ++i)
  317. {
  318. currentName = currentName + "." + splitedNames[i];
  319. lua_getfield(luaState_, -1, splitedNames[i].CString());
  320. if (!lua_istable(luaState_, -1))
  321. {
  322. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  323. return false;
  324. }
  325. }
  326. currentName = currentName + "." + splitedNames.Back().CString();
  327. lua_getfield(luaState_, -1, splitedNames.Back().CString());
  328. }
  329. if (!lua_isfunction(luaState_, -1))
  330. {
  331. if (!silentIfNotFound)
  332. LOGERROR("Could not find Lua function: Function name = '" + currentName + "'");
  333. return false;
  334. }
  335. return true;
  336. }
  337. void LuaScript::CallScriptFunction(int functionRef, StringHash eventType, VariantMap& eventData )
  338. {
  339. int top = lua_gettop(luaState_);
  340. lua_rawgeti(luaState_, LUA_REGISTRYINDEX, functionRef);
  341. if (!lua_isfunction(luaState_, -1))
  342. {
  343. LOGERROR("Could not find function");
  344. lua_settop(luaState_, top);
  345. return;
  346. }
  347. tolua_pushusertype(luaState_, (void*)&eventType, "StringHash");
  348. tolua_pushusertype(luaState_, (void*)&eventData, "VariantMap");
  349. if (lua_pcall(luaState_, 2, 0, 0) != 0)
  350. {
  351. const char* message = lua_tostring(luaState_, -1);
  352. LOGERROR("Execute Lua function failed: " + String(message));
  353. lua_settop(luaState_, top);
  354. return;
  355. }
  356. }
  357. void RegisterLuaScriptLibrary(Context* context)
  358. {
  359. LuaFile::RegisterObject(context);
  360. LuaScriptInstance::RegisterObject(context);
  361. }
  362. Context* GetContext()
  363. {
  364. return currentContext_;
  365. }
  366. }