ScriptInstance.cpp 27 KB

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