LuaScriptInstance.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. //
  2. // Copyright (c) 2008-2018 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 "../Core/CoreEvents.h"
  24. #include "../Core/Context.h"
  25. #include "../Core/ProcessUtils.h"
  26. #include "../IO/Log.h"
  27. #include "../IO/MemoryBuffer.h"
  28. #include "../LuaScript/LuaFile.h"
  29. #include "../LuaScript/LuaFunction.h"
  30. #include "../LuaScript/LuaScript.h"
  31. #include "../LuaScript/LuaScriptEventInvoker.h"
  32. #include "../LuaScript/LuaScriptInstance.h"
  33. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  34. #include "../Physics/PhysicsEvents.h"
  35. #endif
  36. #include "../Resource/ResourceCache.h"
  37. #include "../Scene/Scene.h"
  38. #include "../Scene/SceneEvents.h"
  39. #include <toluapp/tolua++.h>
  40. #include "../LuaScript/ToluaUtils.h"
  41. #include "../DebugNew.h"
  42. namespace Urho3D
  43. {
  44. static const char* scriptObjectMethodNames[] = {
  45. "Start",
  46. "Stop",
  47. "DelayedStart",
  48. "Update",
  49. "PostUpdate",
  50. "FixedUpdate",
  51. "FixedPostUpdate",
  52. "Load",
  53. "Save",
  54. "ReadNetworkUpdate",
  55. "WriteNetworkUpdate",
  56. "ApplyAttributes",
  57. "TransformChanged"
  58. };
  59. LuaScriptInstance::LuaScriptInstance(Context* context) :
  60. Component(context),
  61. luaScript_(GetSubsystem<LuaScript>()),
  62. eventInvoker_(new LuaScriptEventInvoker(this)),
  63. scriptObjectRef_(LUA_REFNIL)
  64. {
  65. luaState_ = luaScript_->GetState();
  66. attributeInfos_ = *context_->GetAttributes(GetTypeStatic());
  67. }
  68. LuaScriptInstance::~LuaScriptInstance()
  69. {
  70. ReleaseObject();
  71. }
  72. void LuaScriptInstance::RegisterObject(Context* context)
  73. {
  74. context->RegisterFactory<LuaScriptInstance>(LOGIC_CATEGORY);
  75. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  76. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script File", GetScriptFileAttr, SetScriptFileAttr, ResourceRef,
  77. ResourceRef(LuaFile::GetTypeStatic()), AM_DEFAULT);
  78. URHO3D_ACCESSOR_ATTRIBUTE("Script Object Type", GetScriptObjectType, SetScriptObjectType, String, String::EMPTY, AM_DEFAULT);
  79. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script Data", GetScriptDataAttr, SetScriptDataAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  80. AM_FILE | AM_NOEDIT);
  81. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script Network Data", GetScriptNetworkDataAttr, SetScriptNetworkDataAttr, PODVector<unsigned char>,
  82. Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  83. }
  84. void LuaScriptInstance::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  85. {
  86. if (attr.ptr_ != (void*)0xffffffff)
  87. {
  88. Serializable::OnSetAttribute(attr, src);
  89. return;
  90. }
  91. if (scriptObjectRef_ == LUA_REFNIL)
  92. return;
  93. String name = attr.name_;
  94. unsigned length = name.Length();
  95. if (name.Back() == '_')
  96. length -= 1;
  97. int top = lua_gettop(luaState_);
  98. String functionName = String("Set") + name.Substring(0, 1).ToUpper() + name.Substring(1, length - 1);
  99. LuaFunction* function = GetScriptObjectFunction(functionName);
  100. // If set function exist
  101. if (function)
  102. {
  103. if (function->BeginCall(this))
  104. {
  105. function->PushVariant(src);
  106. function->EndCall();
  107. }
  108. }
  109. else
  110. {
  111. lua_rawgeti(luaState_, LUA_REGISTRYINDEX, scriptObjectRef_);
  112. lua_pushstring(luaState_, name.CString());
  113. switch (attr.type_)
  114. {
  115. case VAR_BOOL:
  116. lua_pushboolean(luaState_, src.GetBool());
  117. break;
  118. case VAR_DOUBLE:
  119. lua_pushnumber(luaState_, src.GetDouble());
  120. break;
  121. case VAR_STRING:
  122. tolua_pushurho3dstring(luaState_, src.GetString());
  123. break;
  124. case VAR_VECTOR2:
  125. {
  126. auto* value = new Vector2(src.GetVector2());
  127. tolua_pushusertype(luaState_, value, "Vector2");
  128. tolua_register_gc(luaState_, lua_gettop(luaState_));
  129. }
  130. break;
  131. case VAR_VECTOR3:
  132. {
  133. auto* value = new Vector3(src.GetVector3());
  134. tolua_pushusertype(luaState_, value, "Vector3");
  135. tolua_register_gc(luaState_, lua_gettop(luaState_));
  136. }
  137. break;
  138. case VAR_VECTOR4:
  139. {
  140. auto* value = new Vector4(src.GetVector4());
  141. tolua_pushusertype(luaState_, value, "Vector4");
  142. tolua_register_gc(luaState_, lua_gettop(luaState_));
  143. }
  144. break;
  145. case VAR_QUATERNION:
  146. {
  147. auto* value = new Quaternion(src.GetQuaternion());
  148. tolua_pushusertype(luaState_, value, "Quaternion");
  149. tolua_register_gc(luaState_, lua_gettop(luaState_));
  150. }
  151. break;
  152. case VAR_COLOR:
  153. {
  154. auto* value = new Color(src.GetColor());
  155. tolua_pushusertype(luaState_, value, "Color");
  156. tolua_register_gc(luaState_, lua_gettop(luaState_));
  157. }
  158. break;
  159. case VAR_INTRECT:
  160. {
  161. auto* value = new IntRect(src.GetIntRect());
  162. tolua_pushusertype(luaState_, value, "IntRect");
  163. tolua_register_gc(luaState_, lua_gettop(luaState_));
  164. }
  165. break;
  166. case VAR_INTVECTOR2:
  167. {
  168. auto* value = new IntVector2(src.GetIntVector2());
  169. tolua_pushusertype(luaState_, value, "IntVector2");
  170. tolua_register_gc(luaState_, lua_gettop(luaState_));
  171. }
  172. break;
  173. case VAR_INTVECTOR3:
  174. {
  175. auto* value = new IntVector3(src.GetIntVector3());
  176. tolua_pushusertype(luaState_, value, "IntVector3");
  177. tolua_register_gc(luaState_, lua_gettop(luaState_));
  178. }
  179. break;
  180. default:
  181. URHO3D_LOGERROR("Unsupported data type");
  182. lua_settop(luaState_, top);
  183. return;
  184. }
  185. lua_settable(luaState_, -3);
  186. }
  187. lua_settop(luaState_, top);
  188. }
  189. void LuaScriptInstance::OnGetAttribute(const AttributeInfo& attr, Variant& dest) const
  190. {
  191. if (attr.ptr_ != (void*)0xffffffff)
  192. {
  193. Serializable::OnGetAttribute(attr, dest);
  194. return;
  195. }
  196. if (scriptObjectRef_ == LUA_REFNIL)
  197. return;
  198. String name = attr.name_;
  199. unsigned length = name.Length();
  200. if (name.Back() == '_')
  201. length -= 1;
  202. int top = lua_gettop(luaState_);
  203. String functionName = String("Get") + name.Substring(0, 1).ToUpper() + name.Substring(1, length - 1);
  204. LuaFunction* function = GetScriptObjectFunction(functionName);
  205. // If get function exist
  206. if (function)
  207. {
  208. if (function->BeginCall(this))
  209. function->EndCall(1);
  210. }
  211. else
  212. {
  213. lua_rawgeti(luaState_, LUA_REGISTRYINDEX, scriptObjectRef_);
  214. lua_pushstring(luaState_, name.CString());
  215. lua_gettable(luaState_, -2);
  216. }
  217. switch (attr.type_)
  218. {
  219. case VAR_BOOL:
  220. dest = lua_toboolean(luaState_, -1) != 0;
  221. break;
  222. case VAR_DOUBLE:
  223. dest = lua_tonumber(luaState_, -1);
  224. break;
  225. case VAR_STRING:
  226. dest = tolua_tourho3dstring(luaState_, -1, "");
  227. break;
  228. case VAR_VECTOR2:
  229. dest = *((Vector2*)tolua_tousertype(luaState_, -1, nullptr));
  230. break;
  231. case VAR_VECTOR3:
  232. dest = *((Vector3*)tolua_tousertype(luaState_, -1, nullptr));
  233. break;
  234. case VAR_VECTOR4:
  235. dest = *((Vector4*)tolua_tousertype(luaState_, -1, nullptr));
  236. break;
  237. case VAR_QUATERNION:
  238. dest = *((Quaternion*)tolua_tousertype(luaState_, -1, nullptr));
  239. break;
  240. case VAR_COLOR:
  241. dest = *((Color*)tolua_tousertype(luaState_, -1, nullptr));
  242. break;
  243. case VAR_INTRECT:
  244. dest = *((IntRect*)tolua_tousertype(luaState_, -1, nullptr));
  245. break;
  246. case VAR_INTVECTOR2:
  247. dest = *((IntVector2*)tolua_tousertype(luaState_, -1, nullptr));
  248. break;
  249. case VAR_INTVECTOR3:
  250. dest = *((IntVector3*)tolua_tousertype(luaState_, -1, nullptr));
  251. break;
  252. default:
  253. URHO3D_LOGERROR("Unsupported data type");
  254. return;
  255. }
  256. lua_settop(luaState_, top);
  257. }
  258. void LuaScriptInstance::ApplyAttributes()
  259. {
  260. LuaFunction* function = scriptObjectMethods_[LSOM_APPLYATTRIBUTES];
  261. if (function && function->BeginCall(this))
  262. function->EndCall();
  263. }
  264. void LuaScriptInstance::OnSetEnabled()
  265. {
  266. if (IsEnabledEffective())
  267. SubscribeToScriptMethodEvents();
  268. else
  269. UnsubscribeFromScriptMethodEvents();
  270. }
  271. void LuaScriptInstance::AddEventHandler(const String& eventName, int functionIndex)
  272. {
  273. LuaFunction* function = luaScript_->GetFunction(functionIndex);
  274. if (function)
  275. eventInvoker_->AddEventHandler(nullptr, eventName, function);
  276. }
  277. void LuaScriptInstance::AddEventHandler(const String& eventName, const String& functionName)
  278. {
  279. String realFunctionName = functionName.Replaced(":", ".");
  280. LuaFunction* function = luaScript_->GetFunction(realFunctionName);
  281. if (function)
  282. eventInvoker_->AddEventHandler(nullptr, eventName, function);
  283. }
  284. void LuaScriptInstance::AddEventHandler(Object* sender, const String& eventName, int functionIndex)
  285. {
  286. if (!sender)
  287. return;
  288. LuaFunction* function = luaScript_->GetFunction(functionIndex);
  289. if (function)
  290. eventInvoker_->AddEventHandler(sender, eventName, function);
  291. }
  292. void LuaScriptInstance::AddEventHandler(Object* sender, const String& eventName, const String& functionName)
  293. {
  294. if (!sender)
  295. return;
  296. String realFunctionName = functionName.Replaced(":", ".");
  297. LuaFunction* function = luaScript_->GetFunction(realFunctionName);
  298. if (function)
  299. eventInvoker_->AddEventHandler(sender, eventName, function);
  300. }
  301. void LuaScriptInstance::RemoveEventHandler(const String& eventName)
  302. {
  303. eventInvoker_->UnsubscribeFromEvent(eventName);
  304. }
  305. void LuaScriptInstance::RemoveEventHandler(Object* sender, const String& eventName)
  306. {
  307. if (!sender)
  308. return;
  309. eventInvoker_->UnsubscribeFromEvent(sender, eventName);
  310. }
  311. void LuaScriptInstance::RemoveEventHandlers(Object* sender)
  312. {
  313. if (!sender)
  314. return;
  315. eventInvoker_->UnsubscribeFromEvents(sender);
  316. }
  317. void LuaScriptInstance::RemoveAllEventHandlers()
  318. {
  319. eventInvoker_->UnsubscribeFromAllEvents();
  320. }
  321. void LuaScriptInstance::RemoveEventHandlersExcept(const Vector<String>& exceptionNames)
  322. {
  323. PODVector<StringHash> exceptionTypes(exceptionNames.Size());
  324. for (unsigned i = 0; i < exceptionTypes.Size(); ++i)
  325. exceptionTypes[i] = StringHash(exceptionNames[i]);
  326. eventInvoker_->UnsubscribeFromAllEventsExcept(exceptionTypes, true);
  327. }
  328. bool LuaScriptInstance::HasEventHandler(const String& eventName) const
  329. {
  330. return eventInvoker_->HasSubscribedToEvent(eventName);
  331. }
  332. bool LuaScriptInstance::HasEventHandler(Object* sender, const String& eventName) const
  333. {
  334. return eventInvoker_->HasSubscribedToEvent(sender, eventName);
  335. }
  336. bool LuaScriptInstance::CreateObject(const String& scriptObjectType)
  337. {
  338. SetScriptFile(nullptr);
  339. SetScriptObjectType(scriptObjectType);
  340. return scriptObjectRef_ != LUA_REFNIL;
  341. }
  342. bool LuaScriptInstance::CreateObject(LuaFile* scriptFile, const String& scriptObjectType)
  343. {
  344. SetScriptFile(scriptFile);
  345. SetScriptObjectType(scriptObjectType);
  346. return scriptObjectRef_ != LUA_REFNIL;
  347. }
  348. void LuaScriptInstance::SetScriptFile(LuaFile* scriptFile)
  349. {
  350. if (scriptFile == scriptFile_)
  351. return;
  352. scriptFile_ = scriptFile;
  353. if (!scriptFile_)
  354. return;
  355. if (!scriptFile_->LoadAndExecute(luaState_))
  356. URHO3D_LOGERROR("Execute Lua file failed: " + scriptFile_->GetName());
  357. }
  358. void LuaScriptInstance::SetScriptObjectType(const String& scriptObjectType)
  359. {
  360. if (scriptObjectType == scriptObjectType_)
  361. return;
  362. ReleaseObject();
  363. LuaFunction* function = luaScript_->GetFunction("CreateScriptObjectInstance");
  364. if (!function || !function->BeginCall())
  365. return;
  366. function->PushLuaTable(scriptObjectType);
  367. function->PushUserType((void*)this, "LuaScriptInstance");
  368. // Return script object and attribute names
  369. if (!function->EndCall(2))
  370. return;
  371. GetScriptAttributes();
  372. scriptObjectType_ = scriptObjectType;
  373. scriptObjectRef_ = luaL_ref(luaState_, LUA_REGISTRYINDEX);
  374. // Find script object method refs
  375. FindScriptObjectMethodRefs();
  376. }
  377. void LuaScriptInstance::SetScriptDataAttr(const PODVector<unsigned char>& data)
  378. {
  379. if (scriptObjectRef_ == LUA_REFNIL)
  380. return;
  381. LuaFunction* function = scriptObjectMethods_[LSOM_LOAD];
  382. if (function && function->BeginCall(this))
  383. {
  384. MemoryBuffer buf(data);
  385. function->PushUserType((Deserializer&)buf, "Deserializer");
  386. function->EndCall();
  387. }
  388. }
  389. void LuaScriptInstance::SetScriptNetworkDataAttr(const PODVector<unsigned char>& data)
  390. {
  391. if (scriptObjectRef_ == LUA_REFNIL)
  392. return;
  393. LuaFunction* function = scriptObjectMethods_[LSOM_READNETWORKUPDATE];
  394. if (function && function->BeginCall(this))
  395. {
  396. MemoryBuffer buf(data);
  397. function->PushUserType((Deserializer&)buf, "Deserializer");
  398. function->EndCall();
  399. }
  400. }
  401. LuaFile* LuaScriptInstance::GetScriptFile() const
  402. {
  403. return scriptFile_;
  404. }
  405. PODVector<unsigned char> LuaScriptInstance::GetScriptDataAttr() const
  406. {
  407. if (scriptObjectRef_ == LUA_REFNIL)
  408. return PODVector<unsigned char>();
  409. VectorBuffer buf;
  410. LuaFunction* function = scriptObjectMethods_[LSOM_SAVE];
  411. if (function && function->BeginCall(this))
  412. {
  413. function->PushUserType((Serializer&)buf, "Serializer");
  414. function->EndCall();
  415. }
  416. return buf.GetBuffer();
  417. }
  418. PODVector<unsigned char> LuaScriptInstance::GetScriptNetworkDataAttr() const
  419. {
  420. if (scriptObjectRef_ == LUA_REFNIL)
  421. return PODVector<unsigned char>();
  422. VectorBuffer buf;
  423. LuaFunction* function = scriptObjectMethods_[LSOM_WRITENETWORKUPDATE];
  424. if (function && function->BeginCall(this))
  425. {
  426. function->PushUserType((Serializer&)buf, "Serializer");
  427. function->EndCall();
  428. }
  429. return buf.GetBuffer();
  430. }
  431. void LuaScriptInstance::OnSceneSet(Scene* scene)
  432. {
  433. if (scene)
  434. SubscribeToScriptMethodEvents();
  435. else
  436. UnsubscribeFromScriptMethodEvents();
  437. }
  438. void LuaScriptInstance::OnMarkedDirty(Node* node)
  439. {
  440. // Script functions are not safe from worker threads
  441. Scene* scene = GetScene();
  442. if (scene && scene->IsThreadedUpdate())
  443. {
  444. scene->DelayedMarkedDirty(this);
  445. return;
  446. }
  447. LuaFunction* function = scriptObjectMethods_[LSOM_TRANSFORMCHANGED];
  448. if (function && function->BeginCall(this))
  449. function->EndCall();
  450. }
  451. void LuaScriptInstance::GetScriptAttributes()
  452. {
  453. // Get all attribute names
  454. Vector<String> names;
  455. if (lua_istable(luaState_, -1))
  456. {
  457. size_t length = lua_objlen(luaState_, -1);
  458. for (size_t i = 1; i <= length; ++i)
  459. {
  460. lua_pushinteger(luaState_, (int)i);
  461. lua_gettable(luaState_, -2);
  462. if (!lua_isstring(luaState_, -1))
  463. {
  464. lua_pop(luaState_, 1);
  465. continue;
  466. }
  467. String name = lua_tostring(luaState_, -1);
  468. names.Push(name);
  469. lua_pop(luaState_, 1);
  470. }
  471. }
  472. lua_pop(luaState_, 1);
  473. attributeInfos_ = *context_->GetAttributes(GetTypeStatic());
  474. for (unsigned i = 0; i < names.Size(); ++i)
  475. {
  476. lua_pushstring(luaState_, names[i].CString());
  477. lua_gettable(luaState_, -2);
  478. // Get attribute type
  479. int type = lua_type(luaState_, -1);
  480. AttributeInfo info;
  481. info.mode_ = AM_FILE;
  482. info.name_ = names[i];
  483. info.ptr_ = (void*)0xffffffff;
  484. switch (type)
  485. {
  486. case LUA_TBOOLEAN:
  487. info.type_ = VAR_BOOL;
  488. break;
  489. case LUA_TNUMBER:
  490. info.type_ = VAR_DOUBLE;
  491. break;
  492. case LUA_TSTRING:
  493. info.type_ = VAR_STRING;
  494. break;
  495. case LUA_TUSERDATA:
  496. {
  497. String typeName = tolua_typename(luaState_, -1);
  498. lua_pop(luaState_, 1);
  499. if (typeName == "Vector2")
  500. info.type_ = VAR_VECTOR2;
  501. else if (typeName == "Vector3")
  502. info.type_ = VAR_VECTOR3;
  503. else if (typeName == "Vector4")
  504. info.type_ = VAR_VECTOR4;
  505. else if (typeName == "Quaternion")
  506. info.type_ = VAR_QUATERNION;
  507. else if (typeName == "Color")
  508. info.type_ = VAR_COLOR;
  509. else if (typeName == "IntRect")
  510. info.type_ = VAR_INTRECT;
  511. else if (typeName == "IntVector2")
  512. info.type_ = VAR_INTVECTOR2;
  513. else if (typeName == "IntVector3")
  514. info.type_ = VAR_INTVECTOR3;
  515. }
  516. break;
  517. default:
  518. break;
  519. }
  520. lua_pop(luaState_, 1);
  521. if (info.type_ != VAR_NONE)
  522. attributeInfos_.Push(info);
  523. }
  524. }
  525. void LuaScriptInstance::FindScriptObjectMethodRefs()
  526. {
  527. for (unsigned i = 0; i < MAX_LUA_SCRIPT_OBJECT_METHODS; ++i)
  528. scriptObjectMethods_[i] = GetScriptObjectFunction(scriptObjectMethodNames[i]);
  529. if (IsEnabledEffective())
  530. SubscribeToScriptMethodEvents();
  531. }
  532. void LuaScriptInstance::SubscribeToScriptMethodEvents()
  533. {
  534. Scene* scene = GetScene();
  535. if (scene && (scriptObjectMethods_[LSOM_UPDATE] || scriptObjectMethods_[LSOM_DELAYEDSTART]))
  536. SubscribeToEvent(scene, E_SCENEUPDATE, URHO3D_HANDLER(LuaScriptInstance, HandleUpdate));
  537. if (scene && scriptObjectMethods_[LSOM_POSTUPDATE])
  538. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, URHO3D_HANDLER(LuaScriptInstance, HandlePostUpdate));
  539. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  540. Component* world = GetFixedUpdateSource();
  541. if (world && scriptObjectMethods_[LSOM_FIXEDUPDATE])
  542. SubscribeToEvent(world, E_PHYSICSPRESTEP, URHO3D_HANDLER(LuaScriptInstance, HandleFixedUpdate));
  543. if (world && scriptObjectMethods_[LSOM_FIXEDPOSTUPDATE])
  544. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, URHO3D_HANDLER(LuaScriptInstance, HandlePostFixedUpdate));
  545. #endif
  546. if (node_ && scriptObjectMethods_[LSOM_TRANSFORMCHANGED])
  547. node_->AddListener(this);
  548. }
  549. void LuaScriptInstance::UnsubscribeFromScriptMethodEvents()
  550. {
  551. UnsubscribeFromEvent(E_SCENEUPDATE);
  552. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  553. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  554. UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  555. UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
  556. #endif
  557. if (node_ && scriptObjectMethods_[LSOM_TRANSFORMCHANGED])
  558. node_->RemoveListener(this);
  559. }
  560. void LuaScriptInstance::HandleUpdate(StringHash eventType, VariantMap& eventData)
  561. {
  562. using namespace Update;
  563. float timeStep = eventData[P_TIMESTEP].GetFloat();
  564. // Execute delayed start before first update
  565. if (scriptObjectMethods_[LSOM_DELAYEDSTART])
  566. {
  567. if (scriptObjectMethods_[LSOM_DELAYEDSTART]->BeginCall(this))
  568. scriptObjectMethods_[LSOM_DELAYEDSTART]->EndCall();
  569. scriptObjectMethods_[LSOM_DELAYEDSTART] = nullptr; // Only execute once
  570. }
  571. LuaFunction* function = scriptObjectMethods_[LSOM_UPDATE];
  572. if (function && function->BeginCall(this))
  573. {
  574. function->PushFloat(timeStep);
  575. function->EndCall();
  576. }
  577. }
  578. void LuaScriptInstance::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  579. {
  580. using namespace PostUpdate;
  581. float timeStep = eventData[P_TIMESTEP].GetFloat();
  582. LuaFunction* function = scriptObjectMethods_[LSOM_POSTUPDATE];
  583. if (function && function->BeginCall(this))
  584. {
  585. function->PushFloat(timeStep);
  586. function->EndCall();
  587. }
  588. }
  589. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  590. void LuaScriptInstance::HandleFixedUpdate(StringHash eventType, VariantMap& eventData)
  591. {
  592. // Execute delayed start before first fixed update if not called yet
  593. if (scriptObjectMethods_[LSOM_DELAYEDSTART])
  594. {
  595. if (scriptObjectMethods_[LSOM_DELAYEDSTART]->BeginCall(this))
  596. scriptObjectMethods_[LSOM_DELAYEDSTART]->EndCall();
  597. scriptObjectMethods_[LSOM_DELAYEDSTART] = nullptr; // Only execute once
  598. }
  599. using namespace PhysicsPreStep;
  600. float timeStep = eventData[P_TIMESTEP].GetFloat();
  601. LuaFunction* function = scriptObjectMethods_[LSOM_FIXEDUPDATE];
  602. if (function && function->BeginCall(this))
  603. {
  604. function->PushFloat(timeStep);
  605. function->EndCall();
  606. }
  607. }
  608. void LuaScriptInstance::HandlePostFixedUpdate(StringHash eventType, VariantMap& eventData)
  609. {
  610. using namespace PhysicsPostStep;
  611. float timeStep = eventData[P_TIMESTEP].GetFloat();
  612. LuaFunction* function = scriptObjectMethods_[LSOM_FIXEDPOSTUPDATE];
  613. if (function && function->BeginCall(this))
  614. {
  615. function->PushFloat(timeStep);
  616. function->EndCall();
  617. }
  618. }
  619. #endif
  620. void LuaScriptInstance::ReleaseObject()
  621. {
  622. if (scriptObjectRef_ == LUA_REFNIL)
  623. return;
  624. attributeInfos_ = *context_->GetAttributes(GetTypeStatic());
  625. if (IsEnabledEffective())
  626. UnsubscribeFromScriptMethodEvents();
  627. // Unref script object
  628. luaL_unref(luaState_, LUA_REGISTRYINDEX, scriptObjectRef_);
  629. scriptObjectRef_ = LUA_REFNIL;
  630. LuaFunction* function = luaScript_->GetFunction("DestroyScriptObjectInstance");
  631. if (function && function->BeginCall())
  632. {
  633. function->PushUserType((void*)this, "LuaScriptInstance");
  634. function->EndCall();
  635. }
  636. for (auto& scriptObjectMethod : scriptObjectMethods_)
  637. scriptObjectMethod = nullptr;
  638. }
  639. LuaFunction* LuaScriptInstance::GetScriptObjectFunction(const String& functionName) const
  640. {
  641. return luaScript_->GetFunction(scriptObjectType_ + "." + functionName, true);
  642. }
  643. void LuaScriptInstance::SetScriptFileAttr(const ResourceRef& value)
  644. {
  645. auto* cache = GetSubsystem<ResourceCache>();
  646. SetScriptFile(cache->GetResource<LuaFile>(value.name_));
  647. }
  648. ResourceRef LuaScriptInstance::GetScriptFileAttr() const
  649. {
  650. return GetResourceRef(scriptFile_, LuaFile::GetTypeStatic());
  651. }
  652. }