ScriptInstance.cpp 29 KB

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