LuaScript.cpp 12 KB

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