ScriptInstance.cpp 29 KB

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