ScriptInstance.cpp 27 KB

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