Node.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  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 "../Scene/Component.h"
  23. #include "../Core/Context.h"
  24. #include "../IO/Log.h"
  25. #include "../IO/MemoryBuffer.h"
  26. #include "../Scene/ObjectAnimation.h"
  27. #include "../Core/Profiler.h"
  28. #include "../Scene/ReplicationState.h"
  29. #include "../Scene/Scene.h"
  30. #include "../Scene/SceneEvents.h"
  31. #include "../Scene/SmoothedTransform.h"
  32. #include "../Scene/UnknownComponent.h"
  33. #include "../Resource/XMLFile.h"
  34. #include "../DebugNew.h"
  35. namespace Atomic
  36. {
  37. Node::Node(Context* context) :
  38. Animatable(context),
  39. networkUpdate_(false),
  40. worldTransform_(Matrix3x4::IDENTITY),
  41. dirty_(false),
  42. enabled_(true),
  43. enabledPrev_(true),
  44. parent_(0),
  45. scene_(0),
  46. id_(0),
  47. position_(Vector3::ZERO),
  48. rotation_(Quaternion::IDENTITY),
  49. scale_(Vector3::ONE),
  50. worldRotation_(Quaternion::IDENTITY),
  51. owner_(0)
  52. {
  53. }
  54. Node::~Node()
  55. {
  56. RemoveAllChildren();
  57. RemoveAllComponents();
  58. // Remove from the scene
  59. if (scene_)
  60. scene_->NodeRemoved(this);
  61. }
  62. void Node::RegisterObject(Context* context)
  63. {
  64. context->RegisterFactory<Node>();
  65. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  66. ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  67. ACCESSOR_ATTRIBUTE("Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
  68. ACCESSOR_ATTRIBUTE("Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  69. ACCESSOR_ATTRIBUTE("Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  70. ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  71. ACCESSOR_ATTRIBUTE("Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  72. ACCESSOR_ATTRIBUTE("Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  73. ACCESSOR_ATTRIBUTE("Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  74. }
  75. bool Node::Load(Deserializer& source, bool setInstanceDefault)
  76. {
  77. SceneResolver resolver;
  78. // Read own ID. Will not be applied, only stored for resolving possible references
  79. unsigned nodeID = source.ReadInt();
  80. resolver.AddNode(nodeID, this);
  81. // Read attributes, components and child nodes
  82. bool success = Load(source, resolver);
  83. if (success)
  84. {
  85. resolver.Resolve();
  86. ApplyAttributes();
  87. }
  88. return success;
  89. }
  90. bool Node::Save(Serializer& dest) const
  91. {
  92. // Write node ID
  93. if (!dest.WriteUInt(id_))
  94. return false;
  95. // Write attributes
  96. if (!Animatable::Save(dest))
  97. return false;
  98. // Write components
  99. dest.WriteVLE(GetNumPersistentComponents());
  100. for (unsigned i = 0; i < components_.Size(); ++i)
  101. {
  102. Component* component = components_[i];
  103. if (component->IsTemporary())
  104. continue;
  105. // Create a separate buffer to be able to skip failing components during deserialization
  106. VectorBuffer compBuffer;
  107. if (!component->Save(compBuffer))
  108. return false;
  109. dest.WriteVLE(compBuffer.GetSize());
  110. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  111. }
  112. // Write child nodes
  113. dest.WriteVLE(GetNumPersistentChildren());
  114. for (unsigned i = 0; i < children_.Size(); ++i)
  115. {
  116. Node* node = children_[i];
  117. if (node->IsTemporary())
  118. continue;
  119. if (!node->Save(dest))
  120. return false;
  121. }
  122. return true;
  123. }
  124. bool Node::LoadXML(const XMLElement& source, bool setInstanceDefault)
  125. {
  126. SceneResolver resolver;
  127. // Read own ID. Will not be applied, only stored for resolving possible references
  128. unsigned nodeID = source.GetInt("id");
  129. resolver.AddNode(nodeID, this);
  130. // Read attributes, components and child nodes
  131. bool success = LoadXML(source, resolver);
  132. if (success)
  133. {
  134. resolver.Resolve();
  135. ApplyAttributes();
  136. }
  137. return success;
  138. }
  139. bool Node::SaveXML(XMLElement& dest) const
  140. {
  141. // Write node ID
  142. if (!dest.SetInt("id", id_))
  143. return false;
  144. // Write attributes
  145. if (!Animatable::SaveXML(dest))
  146. return false;
  147. // Write components
  148. for (unsigned i = 0; i < components_.Size(); ++i)
  149. {
  150. Component* component = components_[i];
  151. if (component->IsTemporary())
  152. continue;
  153. XMLElement compElem = dest.CreateChild("component");
  154. if (!component->SaveXML(compElem))
  155. return false;
  156. }
  157. // Write child nodes
  158. for (unsigned i = 0; i < children_.Size(); ++i)
  159. {
  160. Node* node = children_[i];
  161. if (node->IsTemporary())
  162. continue;
  163. XMLElement childElem = dest.CreateChild("node");
  164. if (!node->SaveXML(childElem))
  165. return false;
  166. }
  167. return true;
  168. }
  169. void Node::ApplyAttributes()
  170. {
  171. for (unsigned i = 0; i < components_.Size(); ++i)
  172. components_[i]->ApplyAttributes();
  173. for (unsigned i = 0; i < children_.Size(); ++i)
  174. children_[i]->ApplyAttributes();
  175. }
  176. void Node::MarkNetworkUpdate()
  177. {
  178. if (!networkUpdate_ && scene_ && id_ < FIRST_LOCAL_ID)
  179. {
  180. scene_->MarkNetworkUpdate(this);
  181. networkUpdate_ = true;
  182. }
  183. }
  184. void Node::AddReplicationState(NodeReplicationState* state)
  185. {
  186. if (!networkState_)
  187. AllocateNetworkState();
  188. networkState_->replicationStates_.Push(state);
  189. }
  190. bool Node::SaveXML(Serializer& dest, const String& indentation) const
  191. {
  192. SharedPtr<XMLFile> xml(new XMLFile(context_));
  193. XMLElement rootElem = xml->CreateRoot("node");
  194. if (!SaveXML(rootElem))
  195. return false;
  196. return xml->Save(dest, indentation);
  197. }
  198. void Node::SetName(const String& name)
  199. {
  200. if (name != name_)
  201. {
  202. name_ = name;
  203. nameHash_ = name_;
  204. MarkNetworkUpdate();
  205. // Send change event
  206. if (scene_)
  207. {
  208. using namespace NodeNameChanged;
  209. VariantMap& eventData = GetEventDataMap();
  210. eventData[P_SCENE] = scene_;
  211. eventData[P_NODE] = this;
  212. scene_->SendEvent(E_NODENAMECHANGED, eventData);
  213. }
  214. }
  215. }
  216. void Node::SetPosition(const Vector3& position)
  217. {
  218. position_ = position;
  219. MarkDirty();
  220. MarkNetworkUpdate();
  221. }
  222. void Node::SetRotation(const Quaternion& rotation)
  223. {
  224. rotation_ = rotation;
  225. MarkDirty();
  226. MarkNetworkUpdate();
  227. }
  228. void Node::SetDirection(const Vector3& direction)
  229. {
  230. SetRotation(Quaternion(Vector3::FORWARD, direction));
  231. }
  232. void Node::SetScale(float scale)
  233. {
  234. SetScale(Vector3(scale, scale, scale));
  235. }
  236. void Node::SetScale(const Vector3& scale)
  237. {
  238. scale_ = scale.Abs();
  239. MarkDirty();
  240. MarkNetworkUpdate();
  241. }
  242. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  243. {
  244. position_ = position;
  245. rotation_ = rotation;
  246. MarkDirty();
  247. MarkNetworkUpdate();
  248. }
  249. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  250. {
  251. SetTransform(position, rotation, Vector3(scale, scale, scale));
  252. }
  253. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  254. {
  255. position_ = position;
  256. rotation_ = rotation;
  257. scale_ = scale;
  258. MarkDirty();
  259. MarkNetworkUpdate();
  260. }
  261. void Node::SetWorldPosition(const Vector3& position)
  262. {
  263. SetPosition((parent_ == scene_ || !parent_) ? position : parent_->GetWorldTransform().Inverse() * position);
  264. }
  265. void Node::SetWorldRotation(const Quaternion& rotation)
  266. {
  267. SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation);
  268. }
  269. void Node::SetWorldDirection(const Vector3& direction)
  270. {
  271. Vector3 localDirection = (parent_ == scene_ || !parent_) ? direction : parent_->GetWorldRotation().Inverse() * direction;
  272. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  273. }
  274. void Node::SetWorldScale(float scale)
  275. {
  276. SetWorldScale(Vector3(scale, scale, scale));
  277. }
  278. void Node::SetWorldScale(const Vector3& scale)
  279. {
  280. SetScale((parent_ == scene_ || !parent_) ? scale : scale / parent_->GetWorldScale());
  281. }
  282. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  283. {
  284. SetWorldPosition(position);
  285. SetWorldRotation(rotation);
  286. }
  287. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  288. {
  289. SetWorldPosition(position);
  290. SetWorldRotation(rotation);
  291. SetWorldScale(scale);
  292. }
  293. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  294. {
  295. SetWorldPosition(position);
  296. SetWorldRotation(rotation);
  297. SetWorldScale(scale);
  298. }
  299. void Node::Translate(const Vector3& delta, TransformSpace space)
  300. {
  301. switch (space)
  302. {
  303. case TS_LOCAL:
  304. // Note: local space translation disregards local scale for scale-independent movement speed
  305. position_ += rotation_ * delta;
  306. break;
  307. case TS_PARENT:
  308. position_ += delta;
  309. break;
  310. case TS_WORLD:
  311. position_ += (parent_ == scene_ || !parent_) ? delta : parent_->GetWorldTransform().Inverse() * Vector4(delta, 0.0f);
  312. break;
  313. }
  314. MarkDirty();
  315. MarkNetworkUpdate();
  316. }
  317. void Node::Rotate(const Quaternion& delta, TransformSpace space)
  318. {
  319. switch (space)
  320. {
  321. case TS_LOCAL:
  322. rotation_ = (rotation_ * delta).Normalized();
  323. break;
  324. case TS_PARENT:
  325. rotation_ = (delta * rotation_).Normalized();
  326. break;
  327. case TS_WORLD:
  328. if (parent_ == scene_ || !parent_)
  329. rotation_ = (delta * rotation_).Normalized();
  330. else
  331. {
  332. Quaternion worldRotation = GetWorldRotation();
  333. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  334. }
  335. break;
  336. }
  337. MarkDirty();
  338. MarkNetworkUpdate();
  339. }
  340. void Node::RotateAround(const Vector3& point, const Quaternion& delta, TransformSpace space)
  341. {
  342. Vector3 parentSpacePoint;
  343. Quaternion oldRotation = rotation_;
  344. switch (space)
  345. {
  346. case TS_LOCAL:
  347. parentSpacePoint = GetTransform() * point;
  348. rotation_ = (rotation_ * delta).Normalized();
  349. break;
  350. case TS_PARENT:
  351. parentSpacePoint = point;
  352. rotation_ = (delta * rotation_).Normalized();
  353. break;
  354. case TS_WORLD:
  355. if (parent_ == scene_ || !parent_)
  356. {
  357. parentSpacePoint = point;
  358. rotation_ = (delta * rotation_).Normalized();
  359. }
  360. else
  361. {
  362. parentSpacePoint = parent_->GetWorldTransform().Inverse() * point;
  363. Quaternion worldRotation = GetWorldRotation();
  364. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  365. }
  366. break;
  367. }
  368. Vector3 oldRelativePos = oldRotation.Inverse() * (position_ - parentSpacePoint);
  369. position_ = rotation_ * oldRelativePos + parentSpacePoint;
  370. MarkDirty();
  371. MarkNetworkUpdate();
  372. }
  373. void Node::Yaw(float angle, TransformSpace space)
  374. {
  375. Rotate(Quaternion(angle, Vector3::UP), space);
  376. }
  377. void Node::Pitch(float angle, TransformSpace space)
  378. {
  379. Rotate(Quaternion(angle, Vector3::RIGHT), space);
  380. }
  381. void Node::Roll(float angle, TransformSpace space)
  382. {
  383. Rotate(Quaternion(angle, Vector3::FORWARD), space);
  384. }
  385. bool Node::LookAt(const Vector3& target, const Vector3& up, TransformSpace space)
  386. {
  387. Vector3 worldSpaceTarget;
  388. switch (space)
  389. {
  390. case TS_LOCAL:
  391. worldSpaceTarget = GetWorldTransform() * target;
  392. break;
  393. case TS_PARENT:
  394. worldSpaceTarget = (parent_ == scene_ || !parent_) ? target : parent_->GetWorldTransform() * target;
  395. break;
  396. case TS_WORLD:
  397. worldSpaceTarget = target;
  398. break;
  399. }
  400. Vector3 lookDir = worldSpaceTarget - GetWorldPosition();
  401. // Check if target is very close, in that case can not reliably calculate lookat direction
  402. if (lookDir.Equals(Vector3::ZERO))
  403. return false;
  404. Quaternion newRotation;
  405. // Do nothing if setting look rotation failed
  406. if (!newRotation.FromLookRotation(lookDir, up))
  407. return false;
  408. SetWorldRotation(newRotation);
  409. return true;
  410. }
  411. void Node::Scale(float scale)
  412. {
  413. Scale(Vector3(scale, scale, scale));
  414. }
  415. void Node::Scale(const Vector3& scale)
  416. {
  417. scale_ *= scale;
  418. MarkDirty();
  419. MarkNetworkUpdate();
  420. }
  421. void Node::SetEnabled(bool enable)
  422. {
  423. SetEnabled(enable, false, true);
  424. }
  425. void Node::SetDeepEnabled(bool enable)
  426. {
  427. SetEnabled(enable, true, false);
  428. }
  429. void Node::ResetDeepEnabled()
  430. {
  431. SetEnabled(enabledPrev_, false, false);
  432. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  433. (*i)->ResetDeepEnabled();
  434. }
  435. void Node::SetEnabledRecursive(bool enable)
  436. {
  437. SetEnabled(enable, true, true);
  438. }
  439. void Node::SetOwner(Connection* owner)
  440. {
  441. owner_ = owner;
  442. }
  443. void Node::MarkDirty()
  444. {
  445. dirty_ = true;
  446. // Notify listener components first, then mark child nodes
  447. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  448. {
  449. if (*i)
  450. {
  451. (*i)->OnMarkedDirty(this);
  452. ++i;
  453. }
  454. // If listener has expired, erase from list
  455. else
  456. i = listeners_.Erase(i);
  457. }
  458. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  459. (*i)->MarkDirty();
  460. }
  461. Node* Node::CreateChild(const String& name, CreateMode mode, unsigned id)
  462. {
  463. Node* newNode = CreateChild(id, mode);
  464. newNode->SetName(name);
  465. return newNode;
  466. }
  467. void Node::AddChild(Node* node, unsigned index)
  468. {
  469. // Check for illegal or redundant parent assignment
  470. if (!node || node == this || node->parent_ == this)
  471. return;
  472. // Check for possible cyclic parent assignment
  473. Node* parent = parent_;
  474. while (parent)
  475. {
  476. if (parent == node)
  477. return;
  478. parent = parent->parent_;
  479. }
  480. // Keep a shared ptr to the node while transfering
  481. SharedPtr<Node> nodeShared(node);
  482. Node* oldParent = node->parent_;
  483. if (oldParent)
  484. {
  485. // If old parent is in different scene, perform the full removal
  486. if (oldParent->GetScene() != scene_)
  487. oldParent->RemoveChild(node);
  488. else
  489. {
  490. if (scene_)
  491. {
  492. // Otherwise do not remove from the scene during reparenting, just send the necessary change event
  493. using namespace NodeRemoved;
  494. VariantMap& eventData = GetEventDataMap();
  495. eventData[P_SCENE] = scene_;
  496. eventData[P_PARENT] = oldParent;
  497. eventData[P_NODE] = node;
  498. scene_->SendEvent(E_NODEREMOVED, eventData);
  499. }
  500. oldParent->children_.Remove(nodeShared);
  501. }
  502. }
  503. // Add to the child vector, then add to the scene if not added yet
  504. children_.Insert(index, nodeShared);
  505. if (scene_ && node->GetScene() != scene_)
  506. scene_->NodeAdded(node);
  507. node->parent_ = this;
  508. node->MarkDirty();
  509. node->MarkNetworkUpdate();
  510. // Send change event
  511. if (scene_)
  512. {
  513. using namespace NodeAdded;
  514. VariantMap& eventData = GetEventDataMap();
  515. eventData[P_SCENE] = scene_;
  516. eventData[P_PARENT] = this;
  517. eventData[P_NODE] = node;
  518. scene_->SendEvent(E_NODEADDED, eventData);
  519. }
  520. }
  521. void Node::RemoveChild(Node* node)
  522. {
  523. if (!node)
  524. return;
  525. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  526. {
  527. if (*i == node)
  528. {
  529. RemoveChild(i);
  530. return;
  531. }
  532. }
  533. }
  534. void Node::RemoveAllChildren()
  535. {
  536. RemoveChildren(true, true, true);
  537. }
  538. void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
  539. {
  540. unsigned numRemoved = 0;
  541. for (unsigned i = children_.Size() - 1; i < children_.Size(); --i)
  542. {
  543. bool remove = false;
  544. Node* childNode = children_[i];
  545. if (recursive)
  546. childNode->RemoveChildren(removeReplicated, removeLocal, true);
  547. if (childNode->GetID() < FIRST_LOCAL_ID && removeReplicated)
  548. remove = true;
  549. else if (childNode->GetID() >= FIRST_LOCAL_ID && removeLocal)
  550. remove = true;
  551. if (remove)
  552. {
  553. RemoveChild(children_.Begin() + i);
  554. ++numRemoved;
  555. }
  556. }
  557. // Mark node dirty in all replication states
  558. if (numRemoved)
  559. MarkReplicationDirty();
  560. }
  561. Component* Node::CreateComponent(StringHash type, CreateMode mode, unsigned id)
  562. {
  563. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  564. // as replicated components are synced over
  565. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  566. mode = LOCAL;
  567. // Check that creation succeeds and that the object in fact is a component
  568. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  569. if (!newComponent)
  570. {
  571. LOGERROR("Could not create unknown component type " + type.ToString());
  572. return 0;
  573. }
  574. AddComponent(newComponent, id, mode);
  575. return newComponent;
  576. }
  577. Component* Node::GetOrCreateComponent(StringHash type, CreateMode mode, unsigned id)
  578. {
  579. Component* oldComponent = GetComponent(type);
  580. if (oldComponent)
  581. return oldComponent;
  582. else
  583. return CreateComponent(type, mode, id);
  584. }
  585. Component* Node::CloneComponent(Component* component, unsigned id)
  586. {
  587. if (!component)
  588. {
  589. LOGERROR("Null source component given for CloneComponent");
  590. return 0;
  591. }
  592. return CloneComponent(component, component->GetID() < FIRST_LOCAL_ID ? REPLICATED : LOCAL, id);
  593. }
  594. Component* Node::CloneComponent(Component* component, CreateMode mode, unsigned id)
  595. {
  596. if (!component)
  597. {
  598. LOGERROR("Null source component given for CloneComponent");
  599. return 0;
  600. }
  601. Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0);
  602. if (!cloneComponent)
  603. {
  604. LOGERROR("Could not clone component " + component->GetTypeName());
  605. return 0;
  606. }
  607. const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
  608. const Vector<AttributeInfo>* cloneAttributes = cloneComponent->GetAttributes();
  609. if (compAttributes)
  610. {
  611. for (unsigned i = 0; i < compAttributes->Size() && i < cloneAttributes->Size(); ++i)
  612. {
  613. const AttributeInfo& attr = compAttributes->At(i);
  614. const AttributeInfo& cloneAttr = cloneAttributes->At(i);
  615. if (attr.mode_ & AM_FILE)
  616. {
  617. Variant value;
  618. component->OnGetAttribute(attr, value);
  619. // Note: when eg. a ScriptInstance component is cloned, its script object attributes are unique and therefore we
  620. // can not simply refer to the source component's AttributeInfo
  621. cloneComponent->OnSetAttribute(cloneAttr, value);
  622. }
  623. }
  624. cloneComponent->ApplyAttributes();
  625. }
  626. return cloneComponent;
  627. }
  628. void Node::RemoveComponent(Component* component)
  629. {
  630. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  631. {
  632. if (*i == component)
  633. {
  634. RemoveComponent(i);
  635. // Mark node dirty in all replication states
  636. MarkReplicationDirty();
  637. return;
  638. }
  639. }
  640. }
  641. void Node::RemoveComponent(StringHash type)
  642. {
  643. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  644. {
  645. if ((*i)->GetType() == type)
  646. {
  647. RemoveComponent(i);
  648. // Mark node dirty in all replication states
  649. MarkReplicationDirty();
  650. return;
  651. }
  652. }
  653. }
  654. void Node::RemoveAllComponents()
  655. {
  656. RemoveComponents(true, true);
  657. }
  658. void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
  659. {
  660. unsigned numRemoved = 0;
  661. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  662. {
  663. bool remove = false;
  664. Component* component = components_[i];
  665. if (component->GetID() < FIRST_LOCAL_ID && removeReplicated)
  666. remove = true;
  667. else if (component->GetID() >= FIRST_LOCAL_ID && removeLocal)
  668. remove = true;
  669. if (remove)
  670. {
  671. RemoveComponent(components_.Begin() + i);
  672. ++numRemoved;
  673. }
  674. }
  675. // Mark node dirty in all replication states
  676. if (numRemoved)
  677. MarkReplicationDirty();
  678. }
  679. Node* Node::Clone(CreateMode mode)
  680. {
  681. // The scene itself can not be cloned
  682. if (this == scene_ || !parent_)
  683. {
  684. LOGERROR("Can not clone node without a parent");
  685. return 0;
  686. }
  687. PROFILE(CloneNode);
  688. SceneResolver resolver;
  689. Node* clone = CloneRecursive(parent_, resolver, mode);
  690. resolver.Resolve();
  691. clone->ApplyAttributes();
  692. return clone;
  693. }
  694. void Node::Remove()
  695. {
  696. if (parent_)
  697. parent_->RemoveChild(this);
  698. }
  699. void Node::SetParent(Node* parent)
  700. {
  701. if (parent)
  702. {
  703. Matrix3x4 oldWorldTransform = GetWorldTransform();
  704. parent->AddChild(this);
  705. if (parent != scene_)
  706. {
  707. Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
  708. SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
  709. }
  710. else
  711. {
  712. // The root node is assumed to have identity transform, so can disregard it
  713. SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
  714. }
  715. }
  716. }
  717. void Node::SetVar(StringHash key, const Variant& value)
  718. {
  719. vars_[key] = value;
  720. MarkNetworkUpdate();
  721. }
  722. void Node::AddListener(Component* component)
  723. {
  724. if (!component)
  725. return;
  726. // Check for not adding twice
  727. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  728. {
  729. if (*i == component)
  730. return;
  731. }
  732. listeners_.Push(WeakPtr<Component>(component));
  733. // If the node is currently dirty, notify immediately
  734. if (dirty_)
  735. component->OnMarkedDirty(this);
  736. }
  737. void Node::RemoveListener(Component* component)
  738. {
  739. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  740. {
  741. if (*i == component)
  742. {
  743. listeners_.Erase(i);
  744. return;
  745. }
  746. }
  747. }
  748. Vector3 Node::LocalToWorld(const Vector3& position) const
  749. {
  750. return GetWorldTransform() * position;
  751. }
  752. Vector3 Node::LocalToWorld(const Vector4& vector) const
  753. {
  754. return GetWorldTransform() * vector;
  755. }
  756. Vector2 Node::LocalToWorld2D(const Vector2& vector) const
  757. {
  758. Vector3 result = LocalToWorld(Vector3(vector));
  759. return Vector2(result.x_, result.y_);
  760. }
  761. Vector3 Node::WorldToLocal(const Vector3& position) const
  762. {
  763. return GetWorldTransform().Inverse() * position;
  764. }
  765. Vector3 Node::WorldToLocal(const Vector4& vector) const
  766. {
  767. return GetWorldTransform().Inverse() * vector;
  768. }
  769. Vector2 Node::WorldToLocal2D(const Vector2& vector) const
  770. {
  771. Vector3 result = WorldToLocal(Vector3(vector));
  772. return Vector2(result.x_, result.y_);
  773. }
  774. unsigned Node::GetNumChildren(bool recursive) const
  775. {
  776. if (!recursive)
  777. return children_.Size();
  778. else
  779. {
  780. unsigned allChildren = children_.Size();
  781. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  782. allChildren += (*i)->GetNumChildren(true);
  783. return allChildren;
  784. }
  785. }
  786. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  787. {
  788. dest.Clear();
  789. if (!recursive)
  790. {
  791. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  792. dest.Push(*i);
  793. }
  794. else
  795. GetChildrenRecursive(dest);
  796. }
  797. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, StringHash type, bool recursive) const
  798. {
  799. dest.Clear();
  800. if (!recursive)
  801. {
  802. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  803. {
  804. if ((*i)->HasComponent(type))
  805. dest.Push(*i);
  806. }
  807. }
  808. else
  809. GetChildrenWithComponentRecursive(dest, type);
  810. }
  811. Node* Node::GetChild(unsigned index) const
  812. {
  813. return index < children_.Size() ? children_[index].Get() : 0;
  814. }
  815. Node* Node::GetChild(const String& name, bool recursive) const
  816. {
  817. return GetChild(StringHash(name), recursive);
  818. }
  819. Node* Node::GetChild(const char* name, bool recursive) const
  820. {
  821. return GetChild(StringHash(name), recursive);
  822. }
  823. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  824. {
  825. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  826. {
  827. if ((*i)->GetNameHash() == nameHash)
  828. return *i;
  829. if (recursive)
  830. {
  831. Node* node = (*i)->GetChild(nameHash, true);
  832. if (node)
  833. return node;
  834. }
  835. }
  836. return 0;
  837. }
  838. unsigned Node::GetNumNetworkComponents() const
  839. {
  840. unsigned num = 0;
  841. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  842. {
  843. if ((*i)->GetID() < FIRST_LOCAL_ID)
  844. ++num;
  845. }
  846. return num;
  847. }
  848. void Node::GetComponents(PODVector<Component*>& dest, StringHash type, bool recursive) const
  849. {
  850. dest.Clear();
  851. bool all = type == Component::GetTypeStatic();
  852. if (!recursive)
  853. {
  854. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  855. {
  856. if (all || ((*i)->GetType() == type))
  857. dest.Push(*i);
  858. }
  859. }
  860. else
  861. GetComponentsRecursive(dest, type);
  862. }
  863. bool Node::HasComponent(StringHash type) const
  864. {
  865. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  866. {
  867. if ((*i)->GetType() == type)
  868. return true;
  869. }
  870. return false;
  871. }
  872. const Variant& Node::GetVar(StringHash key) const
  873. {
  874. VariantMap::ConstIterator i = vars_.Find(key);
  875. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  876. }
  877. Component* Node::GetComponent(StringHash type) const
  878. {
  879. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  880. {
  881. if ((*i)->GetType() == type)
  882. return *i;
  883. }
  884. return 0;
  885. }
  886. void Node::SetID(unsigned id)
  887. {
  888. id_ = id;
  889. }
  890. void Node::SetScene(Scene* scene)
  891. {
  892. scene_ = scene;
  893. }
  894. void Node::ResetScene()
  895. {
  896. SetID(0);
  897. SetScene(0);
  898. SetOwner(0);
  899. }
  900. void Node::SetNetPositionAttr(const Vector3& value)
  901. {
  902. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  903. if (transform)
  904. transform->SetTargetPosition(value);
  905. else
  906. SetPosition(value);
  907. }
  908. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  909. {
  910. MemoryBuffer buf(value);
  911. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  912. if (transform)
  913. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  914. else
  915. SetRotation(buf.ReadPackedQuaternion());
  916. }
  917. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  918. {
  919. Scene* scene = GetScene();
  920. if (!scene)
  921. return;
  922. MemoryBuffer buf(value);
  923. // If nothing in the buffer, parent is the root node
  924. if (buf.IsEof())
  925. {
  926. scene->AddChild(this);
  927. return;
  928. }
  929. unsigned baseNodeID = buf.ReadNetID();
  930. Node* baseNode = scene->GetNode(baseNodeID);
  931. if (!baseNode)
  932. {
  933. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  934. return;
  935. }
  936. // If buffer contains just an ID, the parent is replicated and we are done
  937. if (buf.IsEof())
  938. baseNode->AddChild(this);
  939. else
  940. {
  941. // Else the parent is local and we must find it recursively by name hash
  942. StringHash nameHash = buf.ReadStringHash();
  943. Node* parentNode = baseNode->GetChild(nameHash, true);
  944. if (!parentNode)
  945. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  946. else
  947. parentNode->AddChild(this);
  948. }
  949. }
  950. const Vector3& Node::GetNetPositionAttr() const
  951. {
  952. return position_;
  953. }
  954. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  955. {
  956. attrBuffer_.Clear();
  957. attrBuffer_.WritePackedQuaternion(rotation_);
  958. return attrBuffer_.GetBuffer();
  959. }
  960. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  961. {
  962. attrBuffer_.Clear();
  963. Scene* scene = GetScene();
  964. if (scene && parent_ && parent_ != scene)
  965. {
  966. // If parent is replicated, can write the ID directly
  967. unsigned parentID = parent_->GetID();
  968. if (parentID < FIRST_LOCAL_ID)
  969. attrBuffer_.WriteNetID(parentID);
  970. else
  971. {
  972. // Parent is local: traverse hierarchy to find a non-local base node
  973. // This iteration always stops due to the scene (root) being non-local
  974. Node* current = parent_;
  975. while (current->GetID() >= FIRST_LOCAL_ID)
  976. current = current->GetParent();
  977. // Then write the base node ID and the parent's name hash
  978. attrBuffer_.WriteNetID(current->GetID());
  979. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  980. }
  981. }
  982. return attrBuffer_.GetBuffer();
  983. }
  984. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  985. {
  986. // Remove all children and components first in case this is not a fresh load
  987. RemoveAllChildren();
  988. RemoveAllComponents();
  989. // ID has been read at the parent level
  990. if (!Animatable::Load(source))
  991. return false;
  992. unsigned numComponents = source.ReadVLE();
  993. for (unsigned i = 0; i < numComponents; ++i)
  994. {
  995. VectorBuffer compBuffer(source, source.ReadVLE());
  996. StringHash compType = compBuffer.ReadStringHash();
  997. unsigned compID = compBuffer.ReadUInt();
  998. Component* newComponent = SafeCreateComponent(String::EMPTY, compType,
  999. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1000. if (newComponent)
  1001. {
  1002. resolver.AddComponent(compID, newComponent);
  1003. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  1004. newComponent->Load(compBuffer);
  1005. }
  1006. }
  1007. if (!readChildren)
  1008. return true;
  1009. unsigned numChildren = source.ReadVLE();
  1010. for (unsigned i = 0; i < numChildren; ++i)
  1011. {
  1012. unsigned nodeID = source.ReadUInt();
  1013. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1014. LOCAL);
  1015. resolver.AddNode(nodeID, newNode);
  1016. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  1017. return false;
  1018. }
  1019. return true;
  1020. }
  1021. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1022. {
  1023. // Remove all children and components first in case this is not a fresh load
  1024. RemoveAllChildren();
  1025. RemoveAllComponents();
  1026. if (!Animatable::LoadXML(source))
  1027. return false;
  1028. XMLElement compElem = source.GetChild("component");
  1029. while (compElem)
  1030. {
  1031. String typeName = compElem.GetAttribute("type");
  1032. unsigned compID = compElem.GetInt("id");
  1033. // ATOMIC BEGIN
  1034. // At runtime, a XML JSComponent may refer to a "scriptClass"
  1035. // component which is new'd in JS and creates the component itself
  1036. // we peek ahead here to see if we have a JSComponentFile and store
  1037. // it off in the Context vars, for the specialized JSComponent object factory to use
  1038. // when creating the component
  1039. if (!context_->GetEditorContext())
  1040. {
  1041. // at runtime peek ahead to see if we have a ComponentFile attr
  1042. if (typeName == "JSComponent")
  1043. {
  1044. XMLElement attrElem = compElem.GetChild("attribute");
  1045. while (attrElem)
  1046. {
  1047. if (attrElem.GetAttribute("name") == "ComponentFile")
  1048. {
  1049. String componentFile = attrElem.GetAttribute("value");
  1050. if (componentFile.Length())
  1051. {
  1052. // store in context vars
  1053. context_->GetVars()["__JSComponent_ComponentFile"] = componentFile;
  1054. break;
  1055. }
  1056. }
  1057. attrElem = attrElem.GetNext("attribute");
  1058. }
  1059. }
  1060. }
  1061. // ATOMIC END
  1062. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1063. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1064. // ATOMIC BEGIN
  1065. // ensure component file, if any, is cleared
  1066. context_->GetVars()["__JSComponent_ComponentFile"] = Variant::EMPTY;
  1067. // ATOMIC END
  1068. if (newComponent)
  1069. {
  1070. resolver.AddComponent(compID, newComponent);
  1071. if (!newComponent->LoadXML(compElem))
  1072. return false;
  1073. }
  1074. compElem = compElem.GetNext("component");
  1075. }
  1076. if (!readChildren)
  1077. return true;
  1078. XMLElement childElem = source.GetChild("node");
  1079. while (childElem)
  1080. {
  1081. unsigned nodeID = childElem.GetInt("id");
  1082. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1083. LOCAL);
  1084. resolver.AddNode(nodeID, newNode);
  1085. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  1086. return false;
  1087. childElem = childElem.GetNext("node");
  1088. }
  1089. return true;
  1090. }
  1091. void Node::PrepareNetworkUpdate()
  1092. {
  1093. // Update dependency nodes list first
  1094. dependencyNodes_.Clear();
  1095. // Add the parent node, but if it is local, traverse to the first non-local node
  1096. if (parent_ && parent_ != scene_)
  1097. {
  1098. Node* current = parent_;
  1099. while (current->id_ >= FIRST_LOCAL_ID)
  1100. current = current->parent_;
  1101. if (current && current != scene_)
  1102. dependencyNodes_.Push(current);
  1103. }
  1104. // Let the components add their dependencies
  1105. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1106. {
  1107. Component* component = *i;
  1108. if (component->GetID() < FIRST_LOCAL_ID)
  1109. component->GetDependencyNodes(dependencyNodes_);
  1110. }
  1111. // Then check for node attribute changes
  1112. if (!networkState_)
  1113. AllocateNetworkState();
  1114. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  1115. unsigned numAttributes = attributes->Size();
  1116. if (networkState_->currentValues_.Size() != numAttributes)
  1117. {
  1118. networkState_->currentValues_.Resize(numAttributes);
  1119. networkState_->previousValues_.Resize(numAttributes);
  1120. // Copy the default attribute values to the previous state as a starting point
  1121. for (unsigned i = 0; i < numAttributes; ++i)
  1122. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  1123. }
  1124. // Check for attribute changes
  1125. for (unsigned i = 0; i < numAttributes; ++i)
  1126. {
  1127. const AttributeInfo& attr = attributes->At(i);
  1128. if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
  1129. continue;
  1130. OnGetAttribute(attr, networkState_->currentValues_[i]);
  1131. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  1132. {
  1133. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  1134. // Mark the attribute dirty in all replication states that are tracking this node
  1135. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  1136. networkState_->replicationStates_.End();
  1137. ++j)
  1138. {
  1139. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1140. nodeState->dirtyAttributes_.Set(i);
  1141. // Add node to the dirty set if not added yet
  1142. if (!nodeState->markedDirty_)
  1143. {
  1144. nodeState->markedDirty_ = true;
  1145. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1146. }
  1147. }
  1148. }
  1149. }
  1150. // Finally check for user var changes
  1151. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  1152. {
  1153. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  1154. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  1155. {
  1156. networkState_->previousVars_[i->first_] = i->second_;
  1157. // Mark the var dirty in all replication states that are tracking this node
  1158. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  1159. networkState_->replicationStates_.End(); ++j)
  1160. {
  1161. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1162. nodeState->dirtyVars_.Insert(i->first_);
  1163. if (!nodeState->markedDirty_)
  1164. {
  1165. nodeState->markedDirty_ = true;
  1166. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1167. }
  1168. }
  1169. }
  1170. }
  1171. networkUpdate_ = false;
  1172. }
  1173. void Node::CleanupConnection(Connection* connection)
  1174. {
  1175. if (owner_ == connection)
  1176. owner_ = 0;
  1177. if (networkState_)
  1178. {
  1179. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  1180. {
  1181. if (networkState_->replicationStates_[i]->connection_ == connection)
  1182. networkState_->replicationStates_.Erase(i);
  1183. }
  1184. }
  1185. }
  1186. void Node::MarkReplicationDirty()
  1187. {
  1188. if (networkState_)
  1189. {
  1190. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  1191. networkState_->replicationStates_.End(); ++j)
  1192. {
  1193. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1194. if (!nodeState->markedDirty_)
  1195. {
  1196. nodeState->markedDirty_ = true;
  1197. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1198. }
  1199. }
  1200. }
  1201. }
  1202. Node* Node::CreateChild(unsigned id, CreateMode mode)
  1203. {
  1204. SharedPtr<Node> newNode(new Node(context_));
  1205. // If zero ID specified, or the ID is already taken, let the scene assign
  1206. if (scene_)
  1207. {
  1208. if (!id || scene_->GetNode(id))
  1209. id = scene_->GetFreeNodeID(mode);
  1210. newNode->SetID(id);
  1211. }
  1212. else
  1213. newNode->SetID(id);
  1214. AddChild(newNode);
  1215. return newNode;
  1216. }
  1217. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1218. {
  1219. if (!component)
  1220. return;
  1221. components_.Push(SharedPtr<Component>(component));
  1222. // If zero ID specified, or the ID is already taken, let the scene assign
  1223. if (scene_)
  1224. {
  1225. if (!id || scene_->GetComponent(id))
  1226. id = scene_->GetFreeComponentID(mode);
  1227. component->SetID(id);
  1228. scene_->ComponentAdded(component);
  1229. }
  1230. else
  1231. component->SetID(id);
  1232. if(component->GetNode())
  1233. LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!");
  1234. component->SetNode(this);
  1235. component->OnMarkedDirty(this);
  1236. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1237. component->MarkNetworkUpdate();
  1238. MarkNetworkUpdate();
  1239. MarkReplicationDirty();
  1240. // Send change event
  1241. if (scene_)
  1242. {
  1243. using namespace ComponentAdded;
  1244. VariantMap& eventData = GetEventDataMap();
  1245. eventData[P_SCENE] = scene_;
  1246. eventData[P_NODE] = this;
  1247. eventData[P_COMPONENT] = component;
  1248. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1249. }
  1250. }
  1251. unsigned Node::GetNumPersistentChildren() const
  1252. {
  1253. unsigned ret = 0;
  1254. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1255. {
  1256. if (!(*i)->IsTemporary())
  1257. ++ret;
  1258. }
  1259. return ret;
  1260. }
  1261. unsigned Node::GetNumPersistentComponents() const
  1262. {
  1263. unsigned ret = 0;
  1264. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1265. {
  1266. if (!(*i)->IsTemporary())
  1267. ++ret;
  1268. }
  1269. return ret;
  1270. }
  1271. void Node::SetTransformSilent(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  1272. {
  1273. position_ = position;
  1274. rotation_ = rotation;
  1275. scale_ = scale;
  1276. }
  1277. void Node::OnAttributeAnimationAdded()
  1278. {
  1279. if (attributeAnimationInfos_.Size() == 1)
  1280. SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, HANDLER(Node, HandleAttributeAnimationUpdate));
  1281. }
  1282. void Node::OnAttributeAnimationRemoved()
  1283. {
  1284. if (attributeAnimationInfos_.Empty())
  1285. UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
  1286. }
  1287. void Node::SetObjectAttributeAnimation(const String& name, ValueAnimation* attributeAnimation, WrapMode wrapMode, float speed)
  1288. {
  1289. Vector<String> names = name.Split('/');
  1290. // Only attribute name
  1291. if (names.Size() == 1)
  1292. SetAttributeAnimation(name, attributeAnimation, wrapMode, speed);
  1293. else
  1294. {
  1295. // Name must in following format: "#0/#1/@component#0/attribute"
  1296. Node* node = this;
  1297. unsigned i = 0;
  1298. for (; i < names.Size() - 1; ++i)
  1299. {
  1300. if (names[i].Front() != '#')
  1301. break;
  1302. unsigned index = ToInt(names[i].Substring(1, names[i].Length() - 1));
  1303. node = node->GetChild(index);
  1304. if (!node)
  1305. {
  1306. LOGERROR("Could not find node by name " + name);
  1307. return;
  1308. }
  1309. }
  1310. if (i == names.Size() - 1)
  1311. {
  1312. node->SetAttributeAnimation(names.Back(), attributeAnimation, wrapMode, speed);
  1313. return;
  1314. }
  1315. if (i != names.Size() - 2 || names[i].Front() != '@')
  1316. {
  1317. LOGERROR("Invalid name " + name);
  1318. return;
  1319. }
  1320. String componentName = names[i].Substring(1, names[i].Length() - 1);
  1321. Vector<String> componentNames = componentName.Split('#');
  1322. if (componentNames.Size() == 1)
  1323. {
  1324. Component* component = node->GetComponent(StringHash(componentNames.Front()));
  1325. if (!component)
  1326. {
  1327. LOGERROR("Could not find component by name " + name);
  1328. return;
  1329. }
  1330. component->SetAttributeAnimation(names.Back(), attributeAnimation, wrapMode, speed);
  1331. }
  1332. else
  1333. {
  1334. unsigned index = ToInt(componentNames[1]);
  1335. PODVector<Component*> components;
  1336. node->GetComponents(components, StringHash(componentNames.Front()));
  1337. if (index >= components.Size())
  1338. {
  1339. LOGERROR("Could not find component by name " + name);
  1340. return;
  1341. }
  1342. components[index]->SetAttributeAnimation(names.Back(), attributeAnimation, wrapMode, speed);
  1343. }
  1344. }
  1345. }
  1346. void Node::SetEnabled(bool enable, bool recursive, bool storeSelf)
  1347. {
  1348. // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
  1349. if (GetType() == Scene::GetTypeStatic())
  1350. {
  1351. LOGERROR("Can not change enabled state of the Scene");
  1352. return;
  1353. }
  1354. if (storeSelf)
  1355. enabledPrev_ = enable;
  1356. if (enable != enabled_)
  1357. {
  1358. enabled_ = enable;
  1359. MarkNetworkUpdate();
  1360. // Notify listener components of the state change
  1361. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  1362. {
  1363. if (*i)
  1364. {
  1365. (*i)->OnNodeSetEnabled(this);
  1366. ++i;
  1367. }
  1368. // If listener has expired, erase from list
  1369. else
  1370. i = listeners_.Erase(i);
  1371. }
  1372. // Send change event
  1373. if (scene_)
  1374. {
  1375. using namespace NodeEnabledChanged;
  1376. VariantMap& eventData = GetEventDataMap();
  1377. eventData[P_SCENE] = scene_;
  1378. eventData[P_NODE] = this;
  1379. scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
  1380. }
  1381. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  1382. {
  1383. (*i)->OnSetEnabled();
  1384. // Send change event for the component
  1385. if (scene_)
  1386. {
  1387. using namespace ComponentEnabledChanged;
  1388. VariantMap& eventData = GetEventDataMap();
  1389. eventData[P_SCENE] = scene_;
  1390. eventData[P_NODE] = this;
  1391. eventData[P_COMPONENT] = (*i);
  1392. scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
  1393. }
  1394. }
  1395. }
  1396. if (recursive)
  1397. {
  1398. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1399. (*i)->SetEnabled(enable, recursive, storeSelf);
  1400. }
  1401. }
  1402. Component* Node::SafeCreateComponent(const String& typeName, StringHash type, CreateMode mode, unsigned id)
  1403. {
  1404. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  1405. // as replicated components are synced over
  1406. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  1407. mode = LOCAL;
  1408. // First check if factory for type exists
  1409. if (!context_->GetTypeName(type).Empty())
  1410. return CreateComponent(type, mode, id);
  1411. else
  1412. {
  1413. LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder");
  1414. // Else create as UnknownComponent
  1415. SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
  1416. if (typeName.Empty() || typeName.StartsWith("Unknown", false))
  1417. newComponent->SetType(type);
  1418. else
  1419. newComponent->SetTypeName(typeName);
  1420. AddComponent(newComponent, id, mode);
  1421. return newComponent;
  1422. }
  1423. }
  1424. void Node::UpdateWorldTransform() const
  1425. {
  1426. Matrix3x4 transform = GetTransform();
  1427. // Assume the root node (scene) has identity transform
  1428. if (parent_ == scene_ || !parent_)
  1429. {
  1430. worldTransform_ = transform;
  1431. worldRotation_ = rotation_;
  1432. }
  1433. else
  1434. {
  1435. worldTransform_ = parent_->GetWorldTransform() * transform;
  1436. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1437. }
  1438. dirty_ = false;
  1439. }
  1440. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1441. {
  1442. // Send change event. Do not send when already being destroyed
  1443. Node* child = *i;
  1444. if (Refs() > 0 && scene_)
  1445. {
  1446. using namespace NodeRemoved;
  1447. VariantMap& eventData = GetEventDataMap();
  1448. eventData[P_SCENE] = scene_;
  1449. eventData[P_PARENT] = this;
  1450. eventData[P_NODE] = child;
  1451. scene_->SendEvent(E_NODEREMOVED, eventData);
  1452. }
  1453. child->parent_ = 0;
  1454. child->MarkDirty();
  1455. child->MarkNetworkUpdate();
  1456. // Remove the child from the scene already at this point, in case it is not destroyed immediately
  1457. if (scene_)
  1458. scene_->NodeRemoved(child);
  1459. children_.Erase(i);
  1460. }
  1461. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1462. {
  1463. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1464. {
  1465. Node* node = *i;
  1466. dest.Push(node);
  1467. if (!node->children_.Empty())
  1468. node->GetChildrenRecursive(dest);
  1469. }
  1470. }
  1471. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, StringHash type) const
  1472. {
  1473. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1474. {
  1475. Node* node = *i;
  1476. if (node->HasComponent(type))
  1477. dest.Push(node);
  1478. if (!node->children_.Empty())
  1479. node->GetChildrenWithComponentRecursive(dest, type);
  1480. }
  1481. }
  1482. void Node::GetComponentsRecursive(PODVector<Component*>& dest, StringHash type) const
  1483. {
  1484. bool all = type == Component::GetTypeStatic();
  1485. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1486. {
  1487. if (all || (*i)->GetType() == type)
  1488. dest.Push(*i);
  1489. }
  1490. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1491. (*i)->GetComponentsRecursive(dest, type);
  1492. }
  1493. void Node::GetChildrenWithName(PODVector<Node*>& dest, const String& name, bool recursive) const
  1494. {
  1495. GetChildrenWithName(dest, StringHash(name), recursive);
  1496. }
  1497. void Node::GetChildrenWithName(PODVector<Node*>& dest, const char* name, bool recursive) const
  1498. {
  1499. GetChildrenWithName(dest, StringHash(name), recursive);
  1500. }
  1501. void Node::GetChildrenWithName(PODVector<Node*>& dest, StringHash nameHash, bool recursive) const
  1502. {
  1503. dest.Clear();
  1504. if (!recursive)
  1505. {
  1506. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1507. {
  1508. if ((*i)->GetNameHash() == nameHash)
  1509. dest.Push(*i);
  1510. }
  1511. }
  1512. else
  1513. GetChildrenWithNameRecursive(dest, nameHash);
  1514. }
  1515. void Node::GetChildrenWithNameRecursive(PODVector<Node*>& dest, StringHash nameHash) const
  1516. {
  1517. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1518. {
  1519. Node* node = *i;
  1520. if (node->GetNameHash() == nameHash)
  1521. dest.Push(node);
  1522. if (!node->children_.Empty())
  1523. node->GetChildrenWithNameRecursive(dest, nameHash);
  1524. }
  1525. }
  1526. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1527. {
  1528. // Create clone node
  1529. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1530. resolver.AddNode(id_, cloneNode);
  1531. // Copy attributes
  1532. const Vector<AttributeInfo>* attributes = GetAttributes();
  1533. for (unsigned j = 0; j < attributes->Size(); ++j)
  1534. {
  1535. const AttributeInfo& attr = attributes->At(j);
  1536. // Do not copy network-only attributes, as they may have unintended side effects
  1537. if (attr.mode_ & AM_FILE)
  1538. {
  1539. Variant value;
  1540. OnGetAttribute(attr, value);
  1541. cloneNode->OnSetAttribute(attr, value);
  1542. }
  1543. }
  1544. // Clone components
  1545. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1546. {
  1547. Component* component = *i;
  1548. if (component->IsTemporary())
  1549. continue;
  1550. Component* cloneComponent = cloneNode->CloneComponent(component,
  1551. (mode == REPLICATED && component->GetID() < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, 0);
  1552. if (cloneComponent)
  1553. resolver.AddComponent(component->GetID(), cloneComponent);
  1554. }
  1555. // Clone child nodes recursively
  1556. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1557. {
  1558. Node* node = *i;
  1559. if (node->IsTemporary())
  1560. continue;
  1561. node->CloneRecursive(cloneNode, resolver, mode);
  1562. }
  1563. return cloneNode;
  1564. }
  1565. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1566. {
  1567. // Send node change event. Do not send when already being destroyed
  1568. if (Refs() > 0 && scene_)
  1569. {
  1570. using namespace ComponentRemoved;
  1571. VariantMap& eventData = GetEventDataMap();
  1572. eventData[P_SCENE] = scene_;
  1573. eventData[P_NODE] = this;
  1574. eventData[P_COMPONENT] = (*i).Get();
  1575. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1576. }
  1577. RemoveListener(*i);
  1578. if (scene_)
  1579. scene_->ComponentRemoved(*i);
  1580. (*i)->SetNode(0);
  1581. components_.Erase(i);
  1582. }
  1583. void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1584. {
  1585. using namespace AttributeAnimationUpdate;
  1586. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1587. }
  1588. }