LuaScript.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. extern "C"
  34. {
  35. #include <lua.h>
  36. #include <lualib.h>
  37. #include <lauxlib.h>
  38. }
  39. #include "tolua++.h"
  40. #include "DebugNew.h"
  41. extern int tolua_AudioLuaAPI_open(lua_State*);
  42. extern int tolua_ContainerLuaAPI_open(lua_State*);
  43. extern int tolua_CoreLuaAPI_open(lua_State*);
  44. extern int tolua_EngineLuaAPI_open(lua_State*);
  45. extern int tolua_GraphicsLuaAPI_open(lua_State*);
  46. extern int tolua_InputLuaAPI_open(lua_State*);
  47. extern int tolua_IOLuaAPI_open(lua_State*);
  48. extern int tolua_MathLuaAPI_open(lua_State*);
  49. extern int tolua_NavigationLuaAPI_open(lua_State*);
  50. extern int tolua_NetworkLuaAPI_open(lua_State*);
  51. extern int tolua_PhysicsLuaAPI_open(lua_State*);
  52. extern int tolua_ResourceLuaAPI_open(lua_State*);
  53. extern int tolua_SceneLuaAPI_open(lua_State*);
  54. extern int tolua_UILuaAPI_open(lua_State*);
  55. extern int tolua_LuaScriptLuaAPI_open(lua_State*);
  56. namespace Urho3D
  57. {
  58. static Context* currentContext_ = 0;
  59. LuaScript::LuaScript(Context* context) :
  60. Object(context),
  61. luaState_(0)
  62. {
  63. currentContext_ = context_;
  64. RegisterLuaScriptLibrary(context_);
  65. luaState_ = luaL_newstate();
  66. if (!luaState_)
  67. {
  68. LOGERROR("Could not create Lua state");
  69. return;
  70. }
  71. luaL_openlibs(luaState_);
  72. RegisterLoader();
  73. ReplacePrint();
  74. tolua_AudioLuaAPI_open(luaState_);
  75. tolua_ContainerLuaAPI_open(luaState_);
  76. tolua_CoreLuaAPI_open(luaState_);
  77. tolua_EngineLuaAPI_open(luaState_);
  78. tolua_GraphicsLuaAPI_open(luaState_);
  79. tolua_InputLuaAPI_open(luaState_);
  80. tolua_IOLuaAPI_open(luaState_);
  81. tolua_MathLuaAPI_open(luaState_);
  82. tolua_NavigationLuaAPI_open(luaState_);
  83. tolua_NetworkLuaAPI_open(luaState_);
  84. tolua_PhysicsLuaAPI_open(luaState_);
  85. tolua_ResourceLuaAPI_open(luaState_);
  86. tolua_SceneLuaAPI_open(luaState_);
  87. tolua_UILuaAPI_open(luaState_);
  88. tolua_LuaScriptLuaAPI_open(luaState_);
  89. // Subscribe to console commands
  90. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
  91. }
  92. LuaScript::~LuaScript()
  93. {
  94. if (luaState_)
  95. lua_close(luaState_);
  96. }
  97. bool LuaScript::ExecuteFile(const String& fileName)
  98. {
  99. PROFILE(ExecuteFile);
  100. ResourceCache* cache = GetSubsystem<ResourceCache>();
  101. if (!cache)
  102. return false;
  103. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName);
  104. if (!luaFile)
  105. return false;
  106. return luaFile->LoadAndExecute(luaState_);
  107. }
  108. bool LuaScript::ExecuteString(const String& string)
  109. {
  110. PROFILE(ExecuteString);
  111. int top = lua_gettop(luaState_);
  112. if (luaL_dostring(luaState_, string.CString()) != 0)
  113. {
  114. const char* message = lua_tostring(luaState_, -1);
  115. LOGERROR("Execute Lua string failed: " + String(message));
  116. lua_settop(luaState_, top);
  117. return false;
  118. }
  119. return true;
  120. }
  121. bool LuaScript::ExecuteFunction(const String& functionName)
  122. {
  123. PROFILE(ExecuteFunction);
  124. int top = lua_gettop(luaState_);
  125. if (!FindFunction(functionName))
  126. {
  127. lua_settop(luaState_, top);
  128. return false;
  129. }
  130. if (lua_pcall(luaState_, 0, 0, 0))
  131. {
  132. const char* message = lua_tostring(luaState_, -1);
  133. LOGERROR("Execute Lua function failed: " + String(message));
  134. lua_settop(luaState_, top);
  135. return false;
  136. }
  137. return true;
  138. }
  139. void LuaScript::ScriptSendEvent(const String& eventName, VariantMap& eventData)
  140. {
  141. SendEvent(StringHash(eventName), eventData);
  142. }
  143. void LuaScript::ScriptSubscribeToEvent(const String& eventName, const String& functionName)
  144. {
  145. StringHash eventType(eventName);
  146. HashSet<Object*>* receivers = context_->GetEventReceivers(eventType);
  147. if (!receivers || !receivers->Contains(this))
  148. SubscribeToEvent(eventType, HANDLER(LuaScript, HandleEvent));
  149. eventTypeToFunctionNameMap_[eventType].Insert(functionName);
  150. }
  151. void LuaScript::ScriptSubscribeToEvent(Object* object, const String& eventName, const String& functionName)
  152. {
  153. StringHash eventType(eventName);
  154. HashSet<Object*>* receivers = context_->GetEventReceivers(object, eventType);
  155. if (!receivers || !receivers->Contains(this))
  156. SubscribeToEvent(object, eventType, HANDLER(LuaScript, HandleObjectEvent));
  157. objectToEventTypeToFunctionNameMap_[object][eventType].Insert(functionName);
  158. }
  159. void LuaScript::RegisterLoader()
  160. {
  161. // Get package.loaders table.
  162. lua_getglobal(luaState_, "package");
  163. lua_getfield(luaState_, -1, "loaders");
  164. // Set package.loaders[1] = LuaScript::Loader.
  165. lua_pushnumber(luaState_, 1);
  166. lua_pushcfunction(luaState_, &LuaScript::Loader);
  167. lua_settable(luaState_, -3);
  168. }
  169. int LuaScript::Loader(lua_State* L)
  170. {
  171. ResourceCache* cache = currentContext_->GetSubsystem<ResourceCache>();
  172. if (!cache)
  173. return 0;
  174. // Get module name.
  175. const char* name = luaL_checkstring(L, 1);
  176. // Get Lua file from module name.
  177. LuaFile* luaFile = cache->GetResource<LuaFile>(String(name) + ".lua");
  178. if (!luaFile)
  179. return false;
  180. // Load Lua file to Lua chunk.
  181. return luaFile->LoadChunk(L) ? 1 : 0;
  182. }
  183. void LuaScript::ReplacePrint()
  184. {
  185. static const struct luaL_reg reg[] =
  186. {
  187. {"print", &LuaScript::Print},
  188. { NULL, NULL}
  189. };
  190. lua_getglobal(luaState_, "_G");
  191. luaL_register(luaState_, NULL, reg);
  192. lua_pop(luaState_, 1);
  193. }
  194. int LuaScript::Print(lua_State *L)
  195. {
  196. String string;
  197. int n = lua_gettop(L);
  198. lua_getglobal(L, "tostring");
  199. for (int i = 1; i <= n; i++)
  200. {
  201. const char *s;
  202. lua_pushvalue(L, -1); /* function to be called */
  203. lua_pushvalue(L, i); /* value to print */
  204. lua_call(L, 1, 1);
  205. s = lua_tostring(L, -1); /* get result */
  206. if (s == NULL)
  207. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  208. if (i > 1)
  209. string.Append(" "); // fputs("\t", stdout);
  210. string.Append(s); // fputs(s, stdout);
  211. lua_pop(L, 1); /* pop result */
  212. }
  213. LOGRAW(String("Lua: ") + string); // fputs("\n", stdout);
  214. return 0;
  215. }
  216. bool LuaScript::FindFunction(const String& functionName)
  217. {
  218. Vector<String> splitedNames = functionName.Split('.');
  219. String currentName = splitedNames.Front();
  220. lua_getglobal(luaState_, currentName.CString());
  221. if (splitedNames.Size() > 1)
  222. {
  223. if (!lua_istable(luaState_, -1))
  224. {
  225. LOGERROR("Can not find Lua table: " + String("Table name = '") + currentName + "'.");
  226. return false;
  227. }
  228. for (unsigned i = 1; i < splitedNames.Size() - 1; ++i)
  229. {
  230. currentName = currentName + "." + splitedNames[i];
  231. lua_getfield(luaState_, -1, splitedNames[i].CString());
  232. if (!lua_istable(luaState_, -1))
  233. {
  234. LOGERROR("Can not find Lua table: " + String("Table name = '") + currentName + "'.");
  235. return false;
  236. }
  237. }
  238. currentName = currentName + "." + splitedNames.Back().CString();
  239. lua_getfield(luaState_, -1, splitedNames.Back().CString());
  240. }
  241. if (!lua_isfunction(luaState_, -1))
  242. {
  243. LOGERROR("Can not find Lua function: " + String("Function name = '") + currentName + "'.");
  244. return false;
  245. }
  246. return true;
  247. }
  248. void LuaScript::HandleEvent(StringHash eventType, VariantMap& eventData)
  249. {
  250. const HashSet<String>& functionNames = eventTypeToFunctionNameMap_[eventType];
  251. for (HashSet<String>::ConstIterator i = functionNames.Begin(); i != functionNames.End(); ++i)
  252. CallEventHandler(*i, eventType, eventData);
  253. }
  254. void LuaScript::HandleObjectEvent(StringHash eventType, VariantMap& eventData)
  255. {
  256. Object* object = GetEventSender();
  257. const HashSet<String>& functionNames = objectToEventTypeToFunctionNameMap_[object][eventType];
  258. for (HashSet<String>::ConstIterator i = functionNames.Begin(); i != functionNames.End(); ++i)
  259. CallEventHandler(*i, eventType, eventData);
  260. }
  261. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  262. {
  263. using namespace ConsoleCommand;
  264. ExecuteString(eventData[P_COMMAND].GetString());
  265. }
  266. void LuaScript::CallEventHandler(const String& functionName, StringHash eventType, VariantMap& eventData )
  267. {
  268. int top = lua_gettop(luaState_);
  269. if (!FindFunction(functionName))
  270. {
  271. lua_settop(luaState_, top);
  272. return;
  273. }
  274. tolua_pushusertype(luaState_, (void*)&eventType, "StringHash");
  275. tolua_pushusertype(luaState_, (void*)&eventData, "VariantMap");
  276. if (lua_pcall(luaState_, 2, 0, 0) != 0)
  277. {
  278. const char* message = lua_tostring(luaState_, -1);
  279. LOGERROR("Execute Lua function failed: " + String(message));
  280. lua_settop(luaState_, top);
  281. return;
  282. }
  283. }
  284. void RegisterLuaScriptLibrary(Context* context)
  285. {
  286. LuaFile::RegisterObject(context);
  287. LuaScriptInstance::RegisterObject(context);
  288. }
  289. Context* GetContext()
  290. {
  291. return currentContext_;
  292. }
  293. }