ScriptInstance.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. //
  2. // Copyright (c) 2008-2017 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 "../AngelScript/Script.h"
  24. #include "../AngelScript/ScriptFile.h"
  25. #include "../AngelScript/ScriptInstance.h"
  26. #include "../Core/Context.h"
  27. #include "../Core/Profiler.h"
  28. #include "../IO/Log.h"
  29. #include "../IO/MemoryBuffer.h"
  30. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  31. #include "../Physics/PhysicsEvents.h"
  32. #endif
  33. #include "../Resource/ResourceCache.h"
  34. #include "../Resource/ResourceEvents.h"
  35. #include "../Scene/Scene.h"
  36. #include "../Scene/SceneEvents.h"
  37. #include <AngelScript/angelscript.h>
  38. #include "../DebugNew.h"
  39. namespace Urho3D
  40. {
  41. static const char* methodDeclarations[] = {
  42. "void Start()",
  43. "void Stop()",
  44. "void DelayedStart()",
  45. "void Update(float)",
  46. "void PostUpdate(float)",
  47. "void FixedUpdate(float)",
  48. "void FixedPostUpdate(float)",
  49. "void Load(Deserializer&)",
  50. "void Save(Serializer&)",
  51. "void ReadNetworkUpdate(Deserializer&)",
  52. "void WriteNetworkUpdate(Serializer&)",
  53. "void ApplyAttributes()",
  54. "void TransformChanged()"
  55. };
  56. ScriptInstance::ScriptInstance(Context* context) :
  57. Component(context),
  58. scriptObject_(0),
  59. subscribed_(false),
  60. subscribedPostFixed_(false)
  61. {
  62. ClearScriptMethods();
  63. ClearScriptAttributes();
  64. }
  65. ScriptInstance::~ScriptInstance()
  66. {
  67. ReleaseObject();
  68. }
  69. void ScriptInstance::RegisterObject(Context* context)
  70. {
  71. context->RegisterFactory<ScriptInstance>(LOGIC_CATEGORY);
  72. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  73. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Delayed Method Calls", GetDelayedCallsAttr, SetDelayedCallsAttr, PODVector<unsigned char>,
  74. Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  75. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script File", GetScriptFileAttr, SetScriptFileAttr, ResourceRef,
  76. ResourceRef(ScriptFile::GetTypeStatic()), AM_DEFAULT);
  77. URHO3D_ACCESSOR_ATTRIBUTE("Class Name", GetClassName, SetClassName, String, String::EMPTY, AM_DEFAULT);
  78. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script Data", GetScriptDataAttr, SetScriptDataAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  79. AM_FILE | AM_NOEDIT);
  80. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script Network Data", GetScriptNetworkDataAttr, SetScriptNetworkDataAttr, PODVector<unsigned char>,
  81. Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  82. }
  83. void ScriptInstance::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  84. {
  85. // Update stored script attributes if being manipulated while the actual object doesn't exist
  86. if (!scriptObject_ && storedAttributes_.Size())
  87. {
  88. HashMap<String, Variant>::Iterator i = storedAttributes_.Find(attr.name_);
  89. if (i != storedAttributes_.End())
  90. i->second_ = src;
  91. }
  92. if (attr.mode_ & (AM_NODEID | AM_COMPONENTID))
  93. {
  94. // The component / node to which the ID refers to may not be in the scene yet, and furthermore the ID must go through the
  95. // SceneResolver first. Delay searching for the object to ApplyAttributes
  96. AttributeInfo* attrPtr = const_cast<AttributeInfo*>(&attr);
  97. idAttributes_[attrPtr] = src.GetUInt();
  98. }
  99. else if (attr.type_ == VAR_RESOURCEREF && attr.ptr_)
  100. {
  101. Resource*& resourcePtr = *(reinterpret_cast<Resource**>(attr.ptr_));
  102. // Decrease reference count of the old object if any, then increment the new
  103. if (resourcePtr)
  104. resourcePtr->ReleaseRef();
  105. const ResourceRef& ref = src.GetResourceRef();
  106. resourcePtr = GetSubsystem<ResourceCache>()->GetResource(ref.type_, ref.name_);
  107. if (resourcePtr)
  108. resourcePtr->AddRef();
  109. }
  110. else
  111. Serializable::OnSetAttribute(attr, src);
  112. }
  113. void ScriptInstance::OnGetAttribute(const AttributeInfo& attr, Variant& dest) const
  114. {
  115. AttributeInfo* attrPtr = const_cast<AttributeInfo*>(&attr);
  116. // Get ID's for node / component handle attributes
  117. if (attr.mode_ & (AM_NODEID | AM_COMPONENTID))
  118. {
  119. // If a cached ID value has been stored, return it instead of querying from the actual object
  120. // (the object handle is likely null at that point)
  121. HashMap<AttributeInfo*, unsigned>::ConstIterator i = idAttributes_.Find(attrPtr);
  122. if (i != idAttributes_.End())
  123. dest = i->second_;
  124. else if (attr.mode_ & AM_NODEID)
  125. {
  126. Node* node = *(reinterpret_cast<Node**>(attr.ptr_));
  127. unsigned nodeID = node ? node->GetID() : 0;
  128. dest = nodeID;
  129. }
  130. else
  131. {
  132. Component* component = *(reinterpret_cast<Component**>(attr.ptr_));
  133. unsigned componentID = component ? component->GetID() : 0;
  134. dest = componentID;
  135. }
  136. }
  137. else if (attr.type_ == VAR_RESOURCEREF && attr.ptr_)
  138. {
  139. Resource* resource = *(reinterpret_cast<Resource**>(attr.ptr_));
  140. // If resource is non-null get its type and name hash. Otherwise get type from the default value
  141. dest = GetResourceRef(resource, attr.defaultValue_.GetResourceRef().type_);
  142. }
  143. else
  144. Serializable::OnGetAttribute(attr, dest);
  145. }
  146. void ScriptInstance::ApplyAttributes()
  147. {
  148. // Apply node / component ID attributes now (find objects from the scene and assign to the object handles)
  149. for (HashMap<AttributeInfo*, unsigned>::Iterator i = idAttributes_.Begin(); i != idAttributes_.End(); ++i)
  150. {
  151. AttributeInfo& attr = *i->first_;
  152. if (attr.mode_ & AM_NODEID)
  153. {
  154. Node*& nodePtr = *(reinterpret_cast<Node**>(attr.ptr_));
  155. // Decrease reference count of the old object if any, then increment the new
  156. if (nodePtr)
  157. nodePtr->ReleaseRef();
  158. nodePtr = GetScene()->GetNode(i->second_);
  159. if (nodePtr)
  160. nodePtr->AddRef();
  161. }
  162. else if (attr.mode_ & AM_COMPONENTID)
  163. {
  164. Component*& componentPtr = *(reinterpret_cast<Component**>(attr.ptr_));
  165. if (componentPtr)
  166. componentPtr->ReleaseRef();
  167. componentPtr = GetScene()->GetComponent(i->second_);
  168. if (componentPtr)
  169. componentPtr->AddRef();
  170. }
  171. }
  172. idAttributes_.Clear();
  173. if (scriptObject_ && methods_[METHOD_APPLYATTRIBUTES])
  174. scriptFile_->Execute(scriptObject_, methods_[METHOD_APPLYATTRIBUTES]);
  175. }
  176. void ScriptInstance::OnSetEnabled()
  177. {
  178. UpdateEventSubscription();
  179. }
  180. bool ScriptInstance::CreateObject(ScriptFile* scriptFile, const String& className)
  181. {
  182. className_ = String::EMPTY; // Do not create object during SetScriptFile()
  183. SetScriptFile(scriptFile);
  184. SetClassName(className);
  185. return scriptObject_ != 0;
  186. }
  187. void ScriptInstance::SetScriptFile(ScriptFile* scriptFile)
  188. {
  189. if (scriptFile == scriptFile_ && scriptObject_)
  190. return;
  191. ReleaseObject();
  192. // Unsubscribe from the reload event of previous script file (if any), then subscribe to the new
  193. if (scriptFile_)
  194. {
  195. UnsubscribeFromEvent(scriptFile_, E_RELOADSTARTED);
  196. UnsubscribeFromEvent(scriptFile_, E_RELOADFINISHED);
  197. }
  198. if (scriptFile)
  199. {
  200. SubscribeToEvent(scriptFile, E_RELOADSTARTED, URHO3D_HANDLER(ScriptInstance, HandleScriptFileReload));
  201. SubscribeToEvent(scriptFile, E_RELOADFINISHED, URHO3D_HANDLER(ScriptInstance, HandleScriptFileReloadFinished));
  202. }
  203. scriptFile_ = scriptFile;
  204. CreateObject();
  205. MarkNetworkUpdate();
  206. }
  207. void ScriptInstance::SetClassName(const String& className)
  208. {
  209. if (className == className_ && scriptObject_)
  210. return;
  211. ReleaseObject();
  212. className_ = className;
  213. CreateObject();
  214. MarkNetworkUpdate();
  215. }
  216. bool ScriptInstance::Execute(const String& declaration, const VariantVector& parameters)
  217. {
  218. if (!scriptObject_)
  219. return false;
  220. asIScriptFunction* method = scriptFile_->GetMethod(scriptObject_, declaration);
  221. if (!method)
  222. {
  223. URHO3D_LOGERROR("Method " + declaration + " not found in class " + className_);
  224. return false;
  225. }
  226. return scriptFile_->Execute(scriptObject_, method, parameters);
  227. }
  228. bool ScriptInstance::Execute(asIScriptFunction* method, const VariantVector& parameters)
  229. {
  230. if (!method || !scriptObject_)
  231. return false;
  232. return scriptFile_->Execute(scriptObject_, method, parameters);
  233. }
  234. void ScriptInstance::DelayedExecute(float delay, bool repeat, const String& declaration, const VariantVector& parameters)
  235. {
  236. if (!scriptObject_)
  237. return;
  238. DelayedCall call;
  239. call.period_ = call.delay_ = Max(delay, 0.0f);
  240. call.repeat_ = repeat;
  241. call.declaration_ = declaration;
  242. call.parameters_ = parameters;
  243. delayedCalls_.Push(call);
  244. // Make sure we are registered to the scene update event, because delayed calls are executed there
  245. if (!subscribed_)
  246. UpdateEventSubscription();
  247. }
  248. void ScriptInstance::ClearDelayedExecute(const String& declaration)
  249. {
  250. if (declaration.Empty())
  251. delayedCalls_.Clear();
  252. else
  253. {
  254. for (Vector<DelayedCall>::Iterator i = delayedCalls_.Begin(); i != delayedCalls_.End();)
  255. {
  256. if (declaration == i->declaration_)
  257. i = delayedCalls_.Erase(i);
  258. else
  259. ++i;
  260. }
  261. }
  262. }
  263. void ScriptInstance::AddEventHandler(StringHash eventType, const String& handlerName)
  264. {
  265. if (!scriptObject_)
  266. return;
  267. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  268. asIScriptFunction* method = scriptFile_->GetMethod(scriptObject_, declaration);
  269. if (!method)
  270. {
  271. // Retry with parameterless signature
  272. method = scriptFile_->GetMethod(scriptObject_, handlerName);
  273. if (!method)
  274. {
  275. URHO3D_LOGERROR("Event handler method " + handlerName + " not found in " + scriptFile_->GetName());
  276. return;
  277. }
  278. }
  279. SubscribeToEvent(eventType, URHO3D_HANDLER_USERDATA(ScriptInstance, HandleScriptEvent, (void*)method));
  280. }
  281. void ScriptInstance::AddEventHandler(Object* sender, StringHash eventType, const String& handlerName)
  282. {
  283. if (!scriptObject_)
  284. return;
  285. if (!sender)
  286. {
  287. URHO3D_LOGERROR("Null event sender for event " + String(eventType) + ", handler " + handlerName);
  288. return;
  289. }
  290. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  291. asIScriptFunction* method = scriptFile_->GetMethod(scriptObject_, declaration);
  292. if (!method)
  293. {
  294. // Retry with parameterless signature
  295. method = scriptFile_->GetMethod(scriptObject_, handlerName);
  296. if (!method)
  297. {
  298. URHO3D_LOGERROR("Event handler method " + handlerName + " not found in " + scriptFile_->GetName());
  299. return;
  300. }
  301. }
  302. SubscribeToEvent(sender, eventType, URHO3D_HANDLER_USERDATA(ScriptInstance, HandleScriptEvent, (void*)method));
  303. }
  304. void ScriptInstance::RemoveEventHandler(StringHash eventType)
  305. {
  306. UnsubscribeFromEvent(eventType);
  307. }
  308. void ScriptInstance::RemoveEventHandler(Object* sender, StringHash eventType)
  309. {
  310. UnsubscribeFromEvent(sender, eventType);
  311. }
  312. void ScriptInstance::RemoveEventHandlers(Object* sender)
  313. {
  314. UnsubscribeFromEvents(sender);
  315. }
  316. void ScriptInstance::RemoveEventHandlers()
  317. {
  318. UnsubscribeFromAllEventsExcept(PODVector<StringHash>(), true);
  319. }
  320. void ScriptInstance::RemoveEventHandlersExcept(const PODVector<StringHash>& exceptions)
  321. {
  322. UnsubscribeFromAllEventsExcept(exceptions, true);
  323. }
  324. bool ScriptInstance::HasEventHandler(StringHash eventType) const
  325. {
  326. return HasSubscribedToEvent(eventType);
  327. }
  328. bool ScriptInstance::HasEventHandler(Object* sender, StringHash eventType) const
  329. {
  330. return HasSubscribedToEvent(sender, eventType);
  331. }
  332. bool ScriptInstance::IsA(const String& className) const
  333. {
  334. // Early out for the easiest case where that's what we are
  335. if (className_ == className)
  336. return true;
  337. if (scriptObject_)
  338. {
  339. // Start immediately at the first base class because we already checked the early out
  340. asITypeInfo* currentType = scriptObject_->GetObjectType()->GetBaseType();
  341. while (currentType)
  342. {
  343. if (className == currentType->GetName())
  344. return true;
  345. currentType = currentType->GetBaseType();
  346. }
  347. }
  348. return false;
  349. }
  350. bool ScriptInstance::HasMethod(const String& declaration) const
  351. {
  352. if (!scriptFile_ || !scriptObject_)
  353. return false;
  354. else
  355. return scriptFile_->GetMethod(scriptObject_, declaration) != 0;
  356. }
  357. void ScriptInstance::SetScriptFileAttr(const ResourceRef& value)
  358. {
  359. ResourceCache* cache = GetSubsystem<ResourceCache>();
  360. SetScriptFile(cache->GetResource<ScriptFile>(value.name_));
  361. }
  362. void ScriptInstance::SetDelayedCallsAttr(const PODVector<unsigned char>& value)
  363. {
  364. MemoryBuffer buf(value);
  365. delayedCalls_.Resize(buf.ReadVLE());
  366. for (Vector<DelayedCall>::Iterator i = delayedCalls_.Begin(); i != delayedCalls_.End(); ++i)
  367. {
  368. i->period_ = buf.ReadFloat();
  369. i->delay_ = buf.ReadFloat();
  370. i->repeat_ = buf.ReadBool();
  371. i->declaration_ = buf.ReadString();
  372. i->parameters_ = buf.ReadVariantVector();
  373. }
  374. if (scriptObject_ && delayedCalls_.Size() && !subscribed_)
  375. UpdateEventSubscription();
  376. }
  377. void ScriptInstance::SetScriptDataAttr(const PODVector<unsigned char>& data)
  378. {
  379. if (scriptObject_ && methods_[METHOD_LOAD])
  380. {
  381. MemoryBuffer buf(data);
  382. VariantVector parameters;
  383. parameters.Push(Variant((void*)static_cast<Deserializer*>(&buf)));
  384. scriptFile_->Execute(scriptObject_, methods_[METHOD_LOAD], parameters);
  385. }
  386. }
  387. void ScriptInstance::SetScriptNetworkDataAttr(const PODVector<unsigned char>& data)
  388. {
  389. if (scriptObject_ && methods_[METHOD_READNETWORKUPDATE])
  390. {
  391. MemoryBuffer buf(data);
  392. VariantVector parameters;
  393. parameters.Push(Variant((void*)static_cast<Deserializer*>(&buf)));
  394. scriptFile_->Execute(scriptObject_, methods_[METHOD_READNETWORKUPDATE], parameters);
  395. }
  396. }
  397. ResourceRef ScriptInstance::GetScriptFileAttr() const
  398. {
  399. return GetResourceRef(scriptFile_, ScriptFile::GetTypeStatic());
  400. }
  401. PODVector<unsigned char> ScriptInstance::GetDelayedCallsAttr() const
  402. {
  403. VectorBuffer buf;
  404. buf.WriteVLE(delayedCalls_.Size());
  405. for (Vector<DelayedCall>::ConstIterator i = delayedCalls_.Begin(); i != delayedCalls_.End(); ++i)
  406. {
  407. buf.WriteFloat(i->period_);
  408. buf.WriteFloat(i->delay_);
  409. buf.WriteBool(i->repeat_);
  410. buf.WriteString(i->declaration_);
  411. buf.WriteVariantVector(i->parameters_);
  412. }
  413. return buf.GetBuffer();
  414. }
  415. PODVector<unsigned char> ScriptInstance::GetScriptDataAttr() const
  416. {
  417. if (!scriptObject_ || !methods_[METHOD_SAVE])
  418. return PODVector<unsigned char>();
  419. else
  420. {
  421. VectorBuffer buf;
  422. VariantVector parameters;
  423. parameters.Push(Variant((void*)static_cast<Serializer*>(&buf)));
  424. scriptFile_->Execute(scriptObject_, methods_[METHOD_SAVE], parameters);
  425. return buf.GetBuffer();
  426. }
  427. }
  428. PODVector<unsigned char> ScriptInstance::GetScriptNetworkDataAttr() const
  429. {
  430. if (!scriptObject_ || !methods_[METHOD_WRITENETWORKUPDATE])
  431. return PODVector<unsigned char>();
  432. else
  433. {
  434. VectorBuffer buf;
  435. VariantVector parameters;
  436. parameters.Push(Variant((void*)static_cast<Serializer*>(&buf)));
  437. scriptFile_->Execute(scriptObject_, methods_[METHOD_WRITENETWORKUPDATE], parameters);
  438. return buf.GetBuffer();
  439. }
  440. }
  441. void ScriptInstance::OnSceneSet(Scene* scene)
  442. {
  443. if (scene)
  444. UpdateEventSubscription();
  445. else
  446. {
  447. UnsubscribeFromEvent(E_SCENEUPDATE);
  448. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  449. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  450. UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  451. UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
  452. #endif
  453. subscribed_ = false;
  454. subscribedPostFixed_ = false;
  455. }
  456. }
  457. void ScriptInstance::OnMarkedDirty(Node* node)
  458. {
  459. // Script functions are not safe from worker threads
  460. Scene* scene = GetScene();
  461. if (scene && scene->IsThreadedUpdate())
  462. {
  463. scene->DelayedMarkedDirty(this);
  464. return;
  465. }
  466. if (scriptObject_ && methods_[METHOD_TRANSFORMCHANGED])
  467. scriptFile_->Execute(scriptObject_, methods_[METHOD_TRANSFORMCHANGED]);
  468. }
  469. void ScriptInstance::CreateObject()
  470. {
  471. if (!scriptFile_ || className_.Empty())
  472. return;
  473. URHO3D_PROFILE(CreateScriptObject);
  474. scriptObject_ = scriptFile_->CreateObject(className_);
  475. if (scriptObject_)
  476. {
  477. // Map script object to script instance with userdata
  478. scriptObject_->SetUserData(this);
  479. GetScriptMethods();
  480. GetScriptAttributes();
  481. UpdateEventSubscription();
  482. if (methods_[METHOD_START])
  483. scriptFile_->Execute(scriptObject_, methods_[METHOD_START]);
  484. }
  485. else
  486. URHO3D_LOGERROR("Failed to create object of class " + className_ + " from " + scriptFile_->GetName());
  487. }
  488. void ScriptInstance::ReleaseObject()
  489. {
  490. if (scriptObject_)
  491. {
  492. if (methods_[METHOD_STOP])
  493. scriptFile_->Execute(scriptObject_, methods_[METHOD_STOP]);
  494. PODVector<StringHash> exceptions;
  495. exceptions.Push(E_RELOADSTARTED);
  496. exceptions.Push(E_RELOADFINISHED);
  497. UnsubscribeFromAllEventsExcept(exceptions, false);
  498. if (node_)
  499. node_->RemoveListener(this);
  500. subscribed_ = false;
  501. subscribedPostFixed_ = false;
  502. ClearScriptMethods();
  503. ClearScriptAttributes();
  504. scriptObject_->SetUserData(0);
  505. scriptObject_->Release();
  506. scriptObject_ = 0;
  507. }
  508. }
  509. void ScriptInstance::ClearScriptMethods()
  510. {
  511. for (unsigned i = 0; i < MAX_SCRIPT_METHODS; ++i)
  512. methods_[i] = 0;
  513. delayedCalls_.Clear();
  514. }
  515. void ScriptInstance::ClearScriptAttributes()
  516. {
  517. attributeInfos_ = *context_->GetAttributes(GetTypeStatic());
  518. idAttributes_.Clear();
  519. }
  520. void ScriptInstance::GetScriptMethods()
  521. {
  522. for (unsigned i = 0; i < MAX_SCRIPT_METHODS; ++i)
  523. methods_[i] = scriptFile_->GetMethod(scriptObject_, methodDeclarations[i]);
  524. }
  525. void ScriptInstance::GetScriptAttributes()
  526. {
  527. asIScriptEngine* engine = GetSubsystem<Script>()->GetScriptEngine();
  528. attributeInfos_ = *context_->GetAttributes(GetTypeStatic());
  529. unsigned numProperties = scriptObject_->GetPropertyCount();
  530. for (unsigned i = 0; i < numProperties; ++i)
  531. {
  532. const char* name;
  533. int typeId;
  534. bool isPrivate, isProtected, isHandle;
  535. scriptObject_->GetObjectType()->GetProperty(i, &name, &typeId, &isPrivate, &isProtected);
  536. // Hide private variables or ones that begin with an underscore
  537. if (isPrivate || isProtected || name[0] == '_')
  538. continue;
  539. String typeName = engine->GetTypeDeclaration(typeId);
  540. isHandle = typeName.EndsWith("@");
  541. if (isHandle)
  542. typeName = typeName.Substring(0, typeName.Length() - 1);
  543. AttributeInfo info;
  544. info.mode_ = AM_FILE;
  545. info.name_ = name;
  546. info.ptr_ = scriptObject_->GetAddressOfProperty(i);
  547. if (!isHandle)
  548. {
  549. switch (typeId)
  550. {
  551. case asTYPEID_BOOL:
  552. info.type_ = VAR_BOOL;
  553. break;
  554. case asTYPEID_INT32:
  555. case asTYPEID_UINT32:
  556. info.type_ = VAR_INT;
  557. break;
  558. case asTYPEID_FLOAT:
  559. info.type_ = VAR_FLOAT;
  560. break;
  561. default:
  562. info.type_ = Variant::GetTypeFromName(typeName);
  563. break;
  564. }
  565. }
  566. else
  567. {
  568. // For a handle type, check if it's an Object subclass with a registered factory
  569. StringHash typeHash(typeName);
  570. const HashMap<StringHash, SharedPtr<ObjectFactory> >& factories = context_->GetObjectFactories();
  571. HashMap<StringHash, SharedPtr<ObjectFactory> >::ConstIterator j = factories.Find(typeHash);
  572. if (j != factories.End())
  573. {
  574. // Check base class type. Node & Component are supported as ID attributes, Resource as a resource reference
  575. const TypeInfo* typeInfo = j->second_->GetTypeInfo();
  576. if (typeInfo->IsTypeOf<Node>())
  577. {
  578. info.mode_ |= AM_NODEID;
  579. info.type_ = VAR_INT;
  580. }
  581. else if (typeInfo->IsTypeOf<Component>())
  582. {
  583. info.mode_ |= AM_COMPONENTID;
  584. info.type_ = VAR_INT;
  585. }
  586. else if (typeInfo->IsTypeOf<Resource>())
  587. {
  588. info.type_ = VAR_RESOURCEREF;
  589. info.defaultValue_ = ResourceRef(typeHash);
  590. }
  591. }
  592. }
  593. if (info.type_ != VAR_NONE)
  594. attributeInfos_.Push(info);
  595. }
  596. }
  597. void ScriptInstance::StoreScriptAttributes()
  598. {
  599. if (!scriptObject_)
  600. return;
  601. storedAttributes_.Clear();
  602. for (unsigned i = 0; i < attributeInfos_.Size(); ++i)
  603. {
  604. const AttributeInfo& attr = attributeInfos_[i];
  605. if (attr.ptr_)
  606. storedAttributes_[attr.name_] = GetAttribute(i);
  607. }
  608. }
  609. void ScriptInstance::RestoreScriptAttributes()
  610. {
  611. if (!scriptObject_)
  612. return;
  613. for (unsigned i = 0; i < attributeInfos_.Size(); ++i)
  614. {
  615. const AttributeInfo& attr = attributeInfos_[i];
  616. if (attr.ptr_)
  617. {
  618. HashMap<String, Variant>::ConstIterator j = storedAttributes_.Find(attr.name_);
  619. if (j != storedAttributes_.End())
  620. SetAttribute(i, j->second_);
  621. }
  622. }
  623. // Clear after restoring once. If the attributes are no longer in use (script code has changed) they are forgotten now
  624. storedAttributes_.Clear();
  625. }
  626. void ScriptInstance::UpdateEventSubscription()
  627. {
  628. Scene* scene = GetScene();
  629. if (!scene)
  630. {
  631. URHO3D_LOGWARNING("Node is detached from scene, can not subscribe script object to update events");
  632. return;
  633. }
  634. bool enabled = scriptObject_ && IsEnabledEffective();
  635. if (enabled)
  636. {
  637. if (!subscribed_ && (methods_[METHOD_UPDATE] || methods_[METHOD_DELAYEDSTART] || delayedCalls_.Size()))
  638. {
  639. SubscribeToEvent(scene, E_SCENEUPDATE, URHO3D_HANDLER(ScriptInstance, HandleSceneUpdate));
  640. subscribed_ = true;
  641. }
  642. if (!subscribedPostFixed_)
  643. {
  644. if (methods_[METHOD_POSTUPDATE])
  645. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, URHO3D_HANDLER(ScriptInstance, HandleScenePostUpdate));
  646. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  647. if (methods_[METHOD_FIXEDUPDATE] || methods_[METHOD_FIXEDPOSTUPDATE])
  648. {
  649. Component* world = GetFixedUpdateSource();
  650. if (world)
  651. {
  652. if (methods_[METHOD_FIXEDUPDATE])
  653. SubscribeToEvent(world, E_PHYSICSPRESTEP, URHO3D_HANDLER(ScriptInstance, HandlePhysicsPreStep));
  654. if (methods_[METHOD_FIXEDPOSTUPDATE])
  655. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, URHO3D_HANDLER(ScriptInstance, HandlePhysicsPostStep));
  656. }
  657. else
  658. URHO3D_LOGERROR("No physics world, can not subscribe script object to fixed update events");
  659. }
  660. #endif
  661. subscribedPostFixed_ = true;
  662. }
  663. if (methods_[METHOD_TRANSFORMCHANGED])
  664. node_->AddListener(this);
  665. }
  666. else
  667. {
  668. if (subscribed_)
  669. {
  670. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  671. subscribed_ = false;
  672. }
  673. if (subscribedPostFixed_)
  674. {
  675. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  676. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  677. Component* world = GetFixedUpdateSource();
  678. if (world)
  679. {
  680. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  681. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  682. }
  683. #endif
  684. subscribedPostFixed_ = false;
  685. }
  686. if (methods_[METHOD_TRANSFORMCHANGED])
  687. node_->RemoveListener(this);
  688. }
  689. }
  690. void ScriptInstance::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  691. {
  692. if (!scriptObject_)
  693. return;
  694. using namespace SceneUpdate;
  695. float timeStep = eventData[P_TIMESTEP].GetFloat();
  696. // Execute delayed calls
  697. for (unsigned i = 0; i < delayedCalls_.Size();)
  698. {
  699. DelayedCall& call = delayedCalls_[i];
  700. bool remove = false;
  701. call.delay_ -= timeStep;
  702. if (call.delay_ <= 0.0f)
  703. {
  704. if (!call.repeat_)
  705. remove = true;
  706. else
  707. call.delay_ += call.period_;
  708. Execute(call.declaration_, call.parameters_);
  709. }
  710. if (remove)
  711. delayedCalls_.Erase(i);
  712. else
  713. ++i;
  714. }
  715. // Execute delayed start before first update
  716. if (methods_[METHOD_DELAYEDSTART])
  717. {
  718. scriptFile_->Execute(scriptObject_, methods_[METHOD_DELAYEDSTART]);
  719. methods_[METHOD_DELAYEDSTART] = 0; // Only execute once
  720. }
  721. if (methods_[METHOD_UPDATE])
  722. {
  723. VariantVector parameters;
  724. parameters.Push(timeStep);
  725. scriptFile_->Execute(scriptObject_, methods_[METHOD_UPDATE], parameters);
  726. }
  727. }
  728. void ScriptInstance::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  729. {
  730. if (!scriptObject_)
  731. return;
  732. using namespace ScenePostUpdate;
  733. VariantVector parameters;
  734. parameters.Push(eventData[P_TIMESTEP]);
  735. scriptFile_->Execute(scriptObject_, methods_[METHOD_POSTUPDATE], parameters);
  736. }
  737. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  738. void ScriptInstance::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  739. {
  740. if (!scriptObject_)
  741. return;
  742. // Execute delayed start before first fixed update if not called yet
  743. if (methods_[METHOD_DELAYEDSTART])
  744. {
  745. scriptFile_->Execute(scriptObject_, methods_[METHOD_DELAYEDSTART]);
  746. methods_[METHOD_DELAYEDSTART] = 0; // Only execute once
  747. }
  748. using namespace PhysicsPreStep;
  749. VariantVector parameters;
  750. parameters.Push(eventData[P_TIMESTEP]);
  751. scriptFile_->Execute(scriptObject_, methods_[METHOD_FIXEDUPDATE], parameters);
  752. }
  753. void ScriptInstance::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  754. {
  755. if (!scriptObject_)
  756. return;
  757. using namespace PhysicsPostStep;
  758. VariantVector parameters;
  759. parameters.Push(eventData[P_TIMESTEP]);
  760. scriptFile_->Execute(scriptObject_, methods_[METHOD_FIXEDPOSTUPDATE], parameters);
  761. }
  762. #endif
  763. void ScriptInstance::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  764. {
  765. if (!IsEnabledEffective() || !scriptFile_ || !scriptObject_)
  766. return;
  767. asIScriptFunction* method = static_cast<asIScriptFunction*>(GetEventHandler()->GetUserData());
  768. VariantVector parameters;
  769. if (method->GetParamCount() > 0)
  770. {
  771. parameters.Push(Variant((void*)&eventType));
  772. parameters.Push(Variant((void*)&eventData));
  773. }
  774. scriptFile_->Execute(scriptObject_, method, parameters);
  775. }
  776. void ScriptInstance::HandleScriptFileReload(StringHash eventType, VariantMap& eventData)
  777. {
  778. StoreScriptAttributes();
  779. ReleaseObject();
  780. }
  781. void ScriptInstance::HandleScriptFileReloadFinished(StringHash eventType, VariantMap& eventData)
  782. {
  783. if (!className_.Empty())
  784. {
  785. CreateObject();
  786. RestoreScriptAttributes();
  787. }
  788. }
  789. asIScriptContext* GetActiveASContext()
  790. {
  791. return asGetActiveContext();
  792. }
  793. Context* GetScriptContext()
  794. {
  795. asIScriptContext* context = asGetActiveContext();
  796. if (context)
  797. return static_cast<Script*>(context->GetEngine()->GetUserData())->GetContext();
  798. else
  799. return 0;
  800. }
  801. ScriptInstance* GetScriptContextInstance()
  802. {
  803. asIScriptContext* context = asGetActiveContext();
  804. asIScriptObject* object = context ? static_cast<asIScriptObject*>(context->GetThisPointer()) : 0;
  805. if (object)
  806. return static_cast<ScriptInstance*>(object->GetUserData());
  807. else
  808. return 0;
  809. }
  810. Node* GetScriptContextNode()
  811. {
  812. ScriptInstance* instance = GetScriptContextInstance();
  813. return instance ? instance->GetNode() : 0;
  814. }
  815. Scene* GetScriptContextScene()
  816. {
  817. Scene* scene = 0;
  818. Node* node = GetScriptContextNode();
  819. if (node)
  820. scene = node->GetScene();
  821. // If null, try to get the default scene
  822. if (!scene)
  823. scene = GetScriptContext()->GetSubsystem<Script>()->GetDefaultScene();
  824. return scene;
  825. }
  826. ScriptEventListener* GetScriptContextEventListener()
  827. {
  828. // If the context has an object and that object has user data set, try and get the ScriptInstance, otherwise try and get a ScriptFile.
  829. asIScriptContext* context = asGetActiveContext();
  830. if (context)
  831. {
  832. asIScriptObject* object = static_cast<asIScriptObject*>(context->GetThisPointer());
  833. if (object && object->GetUserData())
  834. return GetScriptContextInstance();
  835. else
  836. return GetScriptContextFile();
  837. }
  838. else
  839. return 0;
  840. }
  841. Object* GetScriptContextEventListenerObject()
  842. {
  843. return dynamic_cast<Object*>(GetScriptContextEventListener());
  844. }
  845. }