LuaScript.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. for (HashMap<String, int>::Iterator i = functionNameToFunctionRefMap_.Begin(); i != functionNameToFunctionRefMap_.End(); ++i)
  95. {
  96. if (i->second_ != LUA_REFNIL)
  97. luaL_unref(luaState_, LUA_REGISTRYINDEX, i->second_);
  98. }
  99. if (luaState_)
  100. lua_close(luaState_);
  101. }
  102. bool LuaScript::ExecuteFile(const String& fileName)
  103. {
  104. PROFILE(ExecuteFile);
  105. ResourceCache* cache = GetSubsystem<ResourceCache>();
  106. if (!cache)
  107. return false;
  108. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName);
  109. if (!luaFile)
  110. return false;
  111. return luaFile->LoadAndExecute(luaState_);
  112. }
  113. bool LuaScript::ExecuteString(const String& string)
  114. {
  115. PROFILE(ExecuteString);
  116. int top = lua_gettop(luaState_);
  117. if (luaL_dostring(luaState_, string.CString()) != 0)
  118. {
  119. const char* message = lua_tostring(luaState_, -1);
  120. LOGERROR("Execute Lua string failed: " + String(message));
  121. lua_settop(luaState_, top);
  122. return false;
  123. }
  124. return true;
  125. }
  126. bool LuaScript::ExecuteFunction(const String& functionName, const VariantVector& parameters)
  127. {
  128. PROFILE(ExecuteFunction);
  129. int top = lua_gettop(luaState_);
  130. if (!PushScriptFunction(functionName))
  131. {
  132. lua_settop(luaState_, top);
  133. return false;
  134. }
  135. unsigned numParams = PushParameters(luaState_, parameters);
  136. if (lua_pcall(luaState_, numParams, 0, 0))
  137. {
  138. const char* message = lua_tostring(luaState_, -1);
  139. LOGERROR("Execute Lua function failed: " + String(message));
  140. lua_settop(luaState_, top);
  141. return false;
  142. }
  143. return true;
  144. }
  145. void LuaScript::ScriptSendEvent(const String& eventName, VariantMap& eventData)
  146. {
  147. SendEvent(StringHash(eventName), eventData);
  148. }
  149. void LuaScript::ScriptSubscribeToEvent(const String& eventName, const String& functionName)
  150. {
  151. StringHash eventType(eventName);
  152. int functionRef = GetScriptFunctionRef(functionName);
  153. if (functionRef != LUA_REFNIL)
  154. {
  155. SubscribeToEvent(eventType, HANDLER(LuaScript, HandleEvent));
  156. eventTypeToFunctionRefMap_[eventType] = functionRef;
  157. }
  158. }
  159. void LuaScript::ScriptUnsubscribeFromEvent(const String& eventName)
  160. {
  161. StringHash eventType(eventName);
  162. HashMap<StringHash, int>::Iterator i = eventTypeToFunctionRefMap_.Find(eventType);
  163. if (i != eventTypeToFunctionRefMap_.End())
  164. {
  165. UnsubscribeFromEvent(eventType);
  166. eventTypeToFunctionRefMap_.Erase(i);
  167. }
  168. }
  169. void LuaScript::ScriptUnsubscribeFromAllEvents()
  170. {
  171. if (eventTypeToFunctionRefMap_.Empty())
  172. return;
  173. UnsubscribeFromAllEvents();
  174. eventTypeToFunctionRefMap_.Clear();
  175. }
  176. void LuaScript::ScriptSubscribeToEvent(void* sender, const String& eventName, const String& functionName)
  177. {
  178. StringHash eventType(eventName);
  179. Object* object = (Object*)sender;
  180. int functionRef = GetScriptFunctionRef(functionName);
  181. if (functionRef != LUA_REFNIL)
  182. {
  183. SubscribeToEvent(object, eventType, HANDLER(LuaScript, HandleObjectEvent));
  184. objectToEventTypeToFunctionRefMap_[object][eventType] = functionRef;
  185. }
  186. }
  187. void LuaScript::ScriptUnsubscribeFromEvent(void* sender, const String& eventName)
  188. {
  189. StringHash eventType(eventName);
  190. Object* object = (Object*)sender;
  191. HashMap<StringHash, int>::Iterator i = objectToEventTypeToFunctionRefMap_[object].Find(eventType);
  192. if (i != objectToEventTypeToFunctionRefMap_[object].End())
  193. {
  194. UnsubscribeFromEvent(object, eventType);
  195. objectToEventTypeToFunctionRefMap_[object].Erase(i);
  196. }
  197. }
  198. void LuaScript::ScriptUnsubscribeFromEvents(void* sender)
  199. {
  200. Object* object = (Object*)sender;
  201. HashMap<Object*, HashMap<StringHash, int> >::Iterator it = objectToEventTypeToFunctionRefMap_.Find(object);
  202. if (it == objectToEventTypeToFunctionRefMap_.End())
  203. return;
  204. UnsubscribeFromEvents(object);
  205. objectToEventTypeToFunctionRefMap_.Erase(it);
  206. }
  207. void LuaScript::RegisterLoader()
  208. {
  209. // Get package.loaders table.
  210. lua_getglobal(luaState_, "package");
  211. lua_getfield(luaState_, -1, "loaders");
  212. // Set package.loaders[1] = LuaScript::Loader.
  213. lua_pushnumber(luaState_, 1);
  214. lua_pushcfunction(luaState_, &LuaScript::Loader);
  215. lua_settable(luaState_, -3);
  216. }
  217. int LuaScript::Loader(lua_State* L)
  218. {
  219. ResourceCache* cache = currentContext_->GetSubsystem<ResourceCache>();
  220. if (!cache)
  221. return 0;
  222. // Get module name.
  223. const char* name = luaL_checkstring(L, 1);
  224. // Get Lua file from module name.
  225. LuaFile* luaFile = cache->GetResource<LuaFile>(String(name) + ".lua");
  226. if (!luaFile)
  227. return false;
  228. // Load Lua file to Lua chunk.
  229. return luaFile->LoadChunk(L) ? 1 : 0;
  230. }
  231. void LuaScript::ReplacePrint()
  232. {
  233. static const struct luaL_reg reg[] =
  234. {
  235. {"print", &LuaScript::Print},
  236. { NULL, NULL}
  237. };
  238. lua_getglobal(luaState_, "_G");
  239. luaL_register(luaState_, NULL, reg);
  240. lua_pop(luaState_, 1);
  241. }
  242. int LuaScript::Print(lua_State *L)
  243. {
  244. String string;
  245. int n = lua_gettop(L);
  246. lua_getglobal(L, "tostring");
  247. for (int i = 1; i <= n; i++)
  248. {
  249. const char *s;
  250. lua_pushvalue(L, -1); /* function to be called */
  251. lua_pushvalue(L, i); /* value to print */
  252. lua_call(L, 1, 1);
  253. s = lua_tostring(L, -1); /* get result */
  254. if (s == NULL)
  255. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  256. if (i > 1)
  257. string.Append(" "); // fputs("\t", stdout);
  258. string.Append(s); // fputs(s, stdout);
  259. lua_pop(L, 1); /* pop result */
  260. }
  261. LOGRAW("Lua: " + string); // fputs("\n", stdout);
  262. return 0;
  263. }
  264. unsigned LuaScript::PushParameters(lua_State* state, const VariantVector& parameters)
  265. {
  266. unsigned numParams = 0;
  267. for (unsigned i = 0; i < parameters.Size(); ++i)
  268. {
  269. switch (parameters[i].GetType())
  270. {
  271. case VAR_BOOL:
  272. tolua_pushboolean(luaState_, parameters[i].GetBool() ? 1 : 0);
  273. ++numParams;
  274. break;
  275. case VAR_INT:
  276. tolua_pushnumber(luaState_, (double)parameters[i].GetInt());
  277. ++numParams;
  278. break;
  279. case VAR_FLOAT:
  280. tolua_pushnumber(luaState_, parameters[i].GetFloat());
  281. ++numParams;
  282. break;
  283. case VAR_STRING:
  284. tolua_pushstring(luaState_, parameters[i].GetString().CString());
  285. ++numParams;
  286. break;
  287. case VAR_VECTOR2:
  288. tolua_pushusertype(luaState_, &const_cast<Vector2&>(parameters[i].GetVector2()), parameters[i].GetTypeName().CString());
  289. ++numParams;
  290. break;
  291. case VAR_VECTOR3:
  292. tolua_pushusertype(luaState_, &const_cast<Vector3&>(parameters[i].GetVector3()), parameters[i].GetTypeName().CString());
  293. ++numParams;
  294. break;
  295. case VAR_VECTOR4:
  296. tolua_pushusertype(luaState_, &const_cast<Vector4&>(parameters[i].GetVector4()), parameters[i].GetTypeName().CString());
  297. ++numParams;
  298. break;
  299. case VAR_QUATERNION:
  300. tolua_pushusertype(luaState_, &const_cast<Quaternion&>(parameters[i].GetQuaternion()), parameters[i].GetTypeName().CString());
  301. ++numParams;
  302. break;
  303. case VAR_COLOR:
  304. tolua_pushusertype(luaState_, &const_cast<Color&>(parameters[i].GetColor()), parameters[i].GetTypeName().CString());
  305. ++numParams;
  306. break;
  307. }
  308. }
  309. return numParams;
  310. }
  311. int LuaScript::GetScriptFunctionRef(const String& functionName, bool silentIfNotFound)
  312. {
  313. HashMap<String, int>::Iterator i = functionNameToFunctionRefMap_.Find(functionName);
  314. if (i != functionNameToFunctionRefMap_.End())
  315. return i->second_;
  316. int top = lua_gettop(luaState_);
  317. int functionRef = LUA_REFNIL;
  318. if (PushScriptFunction(functionName, silentIfNotFound))
  319. functionRef = luaL_ref(luaState_, LUA_REGISTRYINDEX);
  320. lua_settop(luaState_, top);
  321. functionNameToFunctionRefMap_[functionName] = functionRef;
  322. return functionRef;
  323. }
  324. void LuaScript::HandleEvent(StringHash eventType, VariantMap& eventData)
  325. {
  326. int functionRef = eventTypeToFunctionRefMap_[eventType];
  327. if (functionRef == LUA_REFNIL)
  328. return;
  329. CallScriptFunction(functionRef, eventType, eventData);
  330. }
  331. void LuaScript::HandleObjectEvent(StringHash eventType, VariantMap& eventData)
  332. {
  333. Object* object = GetEventSender();
  334. int functionRef = objectToEventTypeToFunctionRefMap_[object][eventType];
  335. if (functionRef == LUA_REFNIL)
  336. return;
  337. CallScriptFunction(functionRef, eventType, eventData);
  338. }
  339. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  340. {
  341. using namespace ConsoleCommand;
  342. ExecuteString(eventData[P_COMMAND].GetString());
  343. }
  344. bool LuaScript::PushScriptFunction(const String& functionName, bool silentIfNotFound)
  345. {
  346. Vector<String> splitedNames = functionName.Split('.');
  347. String currentName = splitedNames.Front();
  348. lua_getglobal(luaState_, currentName.CString());
  349. if (splitedNames.Size() > 1)
  350. {
  351. if (!lua_istable(luaState_, -1))
  352. {
  353. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  354. return false;
  355. }
  356. for (unsigned i = 1; i < splitedNames.Size() - 1; ++i)
  357. {
  358. currentName = currentName + "." + splitedNames[i];
  359. lua_getfield(luaState_, -1, splitedNames[i].CString());
  360. if (!lua_istable(luaState_, -1))
  361. {
  362. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  363. return false;
  364. }
  365. }
  366. currentName = currentName + "." + splitedNames.Back().CString();
  367. lua_getfield(luaState_, -1, splitedNames.Back().CString());
  368. }
  369. if (!lua_isfunction(luaState_, -1))
  370. {
  371. if (!silentIfNotFound)
  372. LOGERROR("Could not find Lua function: Function name = '" + currentName + "'");
  373. return false;
  374. }
  375. return true;
  376. }
  377. void LuaScript::CallScriptFunction(int functionRef, StringHash eventType, VariantMap& eventData )
  378. {
  379. int top = lua_gettop(luaState_);
  380. lua_rawgeti(luaState_, LUA_REGISTRYINDEX, functionRef);
  381. if (!lua_isfunction(luaState_, -1))
  382. {
  383. LOGERROR("Could not find function");
  384. lua_settop(luaState_, top);
  385. return;
  386. }
  387. tolua_pushusertype(luaState_, (void*)&eventType, "StringHash");
  388. tolua_pushusertype(luaState_, (void*)&eventData, "VariantMap");
  389. if (lua_pcall(luaState_, 2, 0, 0) != 0)
  390. {
  391. const char* message = lua_tostring(luaState_, -1);
  392. LOGERROR("Execute Lua function failed: " + String(message));
  393. lua_settop(luaState_, top);
  394. return;
  395. }
  396. }
  397. void RegisterLuaScriptLibrary(Context* context)
  398. {
  399. LuaFile::RegisterObject(context);
  400. LuaScriptInstance::RegisterObject(context);
  401. }
  402. Context* GetContext()
  403. {
  404. return currentContext_;
  405. }
  406. }