Node.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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 "Component.h"
  24. #include "Context.h"
  25. #include "Log.h"
  26. #include "MemoryBuffer.h"
  27. #include "Profiler.h"
  28. #include "ReplicationState.h"
  29. #include "Scene.h"
  30. #include "SmoothedTransform.h"
  31. #include "XMLFile.h"
  32. #include "DebugNew.h"
  33. namespace Urho3D
  34. {
  35. // Normalize rotation quaternion after this many incremental updates to prevent distortion
  36. static const int NORMALIZE_ROTATION_EVERY = 32;
  37. OBJECTTYPESTATIC(Node);
  38. Node::Node(Context* context) :
  39. Serializable(context),
  40. worldTransform_(Matrix3x4::IDENTITY),
  41. dirty_(false),
  42. networkUpdate_(false),
  43. rotateCount_(0),
  44. parent_(0),
  45. scene_(0),
  46. id_(0),
  47. position_(Vector3::ZERO),
  48. rotation_(Quaternion::IDENTITY),
  49. scale_(Vector3::ONE),
  50. owner_(0)
  51. {
  52. }
  53. Node::~Node()
  54. {
  55. RemoveAllChildren();
  56. RemoveAllComponents();
  57. // Remove from the scene
  58. if (scene_)
  59. scene_->NodeRemoved(this);
  60. }
  61. void Node::RegisterObject(Context* context)
  62. {
  63. context->RegisterFactory<Node>();
  64. /// \todo When position/rotation updates are received from the network, route to SmoothedTransform if exists
  65. REF_ACCESSOR_ATTRIBUTE(Node, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  66. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
  67. REF_ACCESSOR_ATTRIBUTE(Node, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  68. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  69. ATTRIBUTE(Node, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  70. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  71. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  72. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  73. }
  74. void Node::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  75. {
  76. Serializable::OnSetAttribute(attr, src);
  77. MarkNetworkUpdate();
  78. }
  79. bool Node::Load(Deserializer& source)
  80. {
  81. SceneResolver resolver;
  82. // Read own ID. Will not be applied, only stored for resolving possible references
  83. unsigned nodeID = source.ReadInt();
  84. resolver.AddNode(nodeID, this);
  85. // Read attributes, components and child nodes
  86. bool success = Load(source, resolver);
  87. if (success)
  88. {
  89. resolver.Resolve();
  90. ApplyAttributes();
  91. }
  92. return success;
  93. }
  94. bool Node::Save(Serializer& dest)
  95. {
  96. // Write node ID
  97. if (!dest.WriteUInt(id_))
  98. return false;
  99. // Write attributes
  100. if (!Serializable::Save(dest))
  101. return false;
  102. // Write components
  103. dest.WriteVLE(components_.Size());
  104. for (unsigned i = 0; i < components_.Size(); ++i)
  105. {
  106. Component* component = components_[i];
  107. // Create a separate buffer to be able to skip unknown components during deserialization
  108. VectorBuffer compBuffer;
  109. if (!component->Save(compBuffer))
  110. return false;
  111. dest.WriteVLE(compBuffer.GetSize());
  112. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  113. }
  114. // Write child nodes
  115. dest.WriteVLE(children_.Size());
  116. for (unsigned i = 0; i < children_.Size(); ++i)
  117. {
  118. Node* node = children_[i];
  119. if (!node->Save(dest))
  120. return false;
  121. }
  122. return true;
  123. }
  124. bool Node::LoadXML(const XMLElement& source)
  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)
  140. {
  141. // Write node ID
  142. if (!dest.SetInt("id", id_))
  143. return false;
  144. // Write attributes
  145. if (!Serializable::SaveXML(dest))
  146. return false;
  147. // Write components
  148. for (unsigned i = 0; i < components_.Size(); ++i)
  149. {
  150. Component* component = components_[i];
  151. XMLElement compElem = dest.CreateChild("component");
  152. if (!component->SaveXML(compElem))
  153. return false;
  154. }
  155. // Write child nodes
  156. for (unsigned i = 0; i < children_.Size(); ++i)
  157. {
  158. Node* node = children_[i];
  159. XMLElement childElem = dest.CreateChild("node");
  160. if (!node->SaveXML(childElem))
  161. return false;
  162. }
  163. return true;
  164. }
  165. void Node::ApplyAttributes()
  166. {
  167. for (unsigned i = 0; i < components_.Size(); ++i)
  168. components_[i]->ApplyAttributes();
  169. for (unsigned i = 0; i < children_.Size(); ++i)
  170. children_[i]->ApplyAttributes();
  171. }
  172. void Node::AddReplicationState(NodeReplicationState* state)
  173. {
  174. if (!networkState_)
  175. AllocateNetworkState();
  176. networkState_->replicationStates_.Push(state);
  177. }
  178. bool Node::SaveXML(Serializer& dest)
  179. {
  180. SharedPtr<XMLFile> xml(new XMLFile(context_));
  181. XMLElement rootElem = xml->CreateRoot("node");
  182. if (!SaveXML(rootElem))
  183. return false;
  184. return xml->Save(dest);
  185. }
  186. void Node::SetName(const String& name)
  187. {
  188. name_ = name;
  189. nameHash_ = StringHash(name);
  190. MarkNetworkUpdate();
  191. }
  192. void Node::SetPosition(const Vector3& position)
  193. {
  194. position_ = position;
  195. MarkDirty();
  196. MarkNetworkUpdate();
  197. }
  198. void Node::SetRotation(const Quaternion& rotation)
  199. {
  200. rotation_ = rotation;
  201. rotateCount_ = 0;
  202. MarkDirty();
  203. MarkNetworkUpdate();
  204. }
  205. void Node::SetDirection(const Vector3& direction)
  206. {
  207. SetRotation(Quaternion(Vector3::FORWARD, direction));
  208. }
  209. void Node::SetScale(float scale)
  210. {
  211. SetScale(Vector3(scale, scale, scale));
  212. }
  213. void Node::SetScale(const Vector3& scale)
  214. {
  215. scale_ = scale.Abs();
  216. MarkDirty();
  217. MarkNetworkUpdate();
  218. }
  219. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  220. {
  221. position_ = position;
  222. rotation_ = rotation;
  223. rotateCount_ = 0;
  224. MarkDirty();
  225. MarkNetworkUpdate();
  226. }
  227. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  228. {
  229. SetTransform(position, rotation, Vector3(scale, scale, scale));
  230. }
  231. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  232. {
  233. position_ = position;
  234. rotation_ = rotation;
  235. rotateCount_ = 0;
  236. scale_ = scale;
  237. MarkDirty();
  238. MarkNetworkUpdate();
  239. }
  240. void Node::SetWorldPosition(const Vector3& position)
  241. {
  242. if (!parent_)
  243. SetPosition(position);
  244. else
  245. SetPosition(parent_->GetWorldTransform().Inverse() * position);
  246. }
  247. void Node::SetWorldRotation(const Quaternion& rotation)
  248. {
  249. if (!parent_)
  250. SetRotation(rotation);
  251. else
  252. SetRotation(parent_->GetWorldRotation().Inverse() * rotation);
  253. }
  254. void Node::SetWorldDirection(const Vector3& direction)
  255. {
  256. Vector3 localDirection;
  257. if (!parent_)
  258. localDirection = direction;
  259. else
  260. localDirection = parent_->GetWorldTransform().Inverse() * direction;
  261. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  262. }
  263. void Node::SetWorldScale(float scale)
  264. {
  265. if (!parent_)
  266. SetScale(scale);
  267. else
  268. {
  269. Vector3 parentWorldScale = parent_->GetWorldScale();
  270. SetScale(Vector3(scale / parentWorldScale.x_, scale / parentWorldScale.y_, scale / parentWorldScale.z_));
  271. }
  272. }
  273. void Node::SetWorldScale(const Vector3& scale)
  274. {
  275. if (!parent_)
  276. SetScale(scale);
  277. else
  278. SetScale(scale / parent_->GetWorldScale());
  279. }
  280. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  281. {
  282. SetWorldPosition(position);
  283. SetWorldRotation(rotation);
  284. }
  285. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  286. {
  287. SetWorldPosition(position);
  288. SetWorldRotation(rotation);
  289. SetWorldScale(scale);
  290. }
  291. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  292. {
  293. SetWorldPosition(position);
  294. SetWorldRotation(rotation);
  295. SetWorldScale(scale);
  296. }
  297. void Node::Translate(const Vector3& delta)
  298. {
  299. position_ += delta;
  300. MarkDirty();
  301. MarkNetworkUpdate();
  302. }
  303. void Node::TranslateRelative(const Vector3& delta)
  304. {
  305. position_ += rotation_ * delta;
  306. MarkDirty();
  307. MarkNetworkUpdate();
  308. }
  309. void Node::Rotate(const Quaternion& delta, bool fixedAxis)
  310. {
  311. if (!fixedAxis)
  312. rotation_ = rotation_ * delta;
  313. else
  314. rotation_ = delta * rotation_;
  315. if (++rotateCount_ >= NORMALIZE_ROTATION_EVERY)
  316. {
  317. rotation_.Normalize();
  318. rotateCount_ = 0;
  319. }
  320. MarkDirty();
  321. MarkNetworkUpdate();
  322. }
  323. void Node::Yaw(float angle, bool fixedAxis)
  324. {
  325. Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
  326. }
  327. void Node::Pitch(float angle, bool fixedAxis)
  328. {
  329. Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
  330. }
  331. void Node::Roll(float angle, bool fixedAxis)
  332. {
  333. Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
  334. }
  335. void Node::LookAt(const Vector3& target, const Vector3& upAxis, bool worldSpace)
  336. {
  337. Vector3 targetZ;
  338. if (worldSpace)
  339. targetZ = (target - GetWorldPosition()).Normalized();
  340. else
  341. targetZ = (target - position_).Normalized();
  342. Vector3 targetX = upAxis.CrossProduct(targetZ).Normalized();
  343. Vector3 targetY = targetZ.CrossProduct(targetX).Normalized();
  344. if (!worldSpace || !parent_)
  345. SetRotation(Quaternion(targetX, targetY, targetZ));
  346. else
  347. SetRotation(parent_->GetWorldRotation().Inverse() * Quaternion(targetX, targetY, targetZ));
  348. }
  349. void Node::Scale(float scale)
  350. {
  351. Scale(Vector3(scale, scale, scale));
  352. }
  353. void Node::Scale(const Vector3& scale)
  354. {
  355. scale_ *= scale;
  356. MarkDirty();
  357. MarkNetworkUpdate();
  358. }
  359. void Node::SetOwner(Connection* owner)
  360. {
  361. owner_ = owner;
  362. }
  363. void Node::MarkDirty()
  364. {
  365. if (dirty_)
  366. return;
  367. dirty_ = true;
  368. // Notify listener components first, then mark child nodes
  369. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  370. {
  371. if (*i)
  372. {
  373. (*i)->OnMarkedDirty(this);
  374. ++i;
  375. }
  376. // If listener has expired, erase from list
  377. else
  378. i = listeners_.Erase(i);
  379. }
  380. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  381. (*i)->MarkDirty();
  382. }
  383. Node* Node::CreateChild(const String& name, CreateMode mode)
  384. {
  385. Node* newNode = CreateChild(0, mode);
  386. newNode->SetName(name);
  387. return newNode;
  388. }
  389. void Node::AddChild(Node* node)
  390. {
  391. // Check for illegal or redundant parent assignment
  392. if (!node || node == this || node->parent_ == this)
  393. return;
  394. // Check for possible cyclic parent assignment
  395. Node* parent = parent_;
  396. while (parent)
  397. {
  398. if (parent == node)
  399. return;
  400. parent = parent->parent_;
  401. }
  402. // Add first, then remove from old parent, to ensure the node does not get deleted
  403. children_.Push(SharedPtr<Node>(node));
  404. node->Remove();
  405. // Add to the scene if not added yet
  406. if (scene_ && !node->GetScene())
  407. scene_->NodeAdded(node);
  408. node->parent_ = this;
  409. node->MarkDirty();
  410. node->MarkNetworkUpdate();
  411. }
  412. void Node::RemoveChild(Node* node)
  413. {
  414. if (!node)
  415. return;
  416. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  417. {
  418. if (*i == node)
  419. {
  420. RemoveChild(i);
  421. return;
  422. }
  423. }
  424. }
  425. void Node::RemoveAllChildren()
  426. {
  427. while (children_.Size())
  428. RemoveChild(--children_.End());
  429. }
  430. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode, unsigned id)
  431. {
  432. // Check that creation succeeds and that the object in fact is a component
  433. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  434. if (!newComponent)
  435. {
  436. LOGERROR("Could not create unknown component type " + type.ToString());
  437. return 0;
  438. }
  439. AddComponent(newComponent, id, mode);
  440. return newComponent;
  441. }
  442. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode)
  443. {
  444. Component* oldComponent = GetComponent(type);
  445. if (oldComponent)
  446. return oldComponent;
  447. else
  448. return CreateComponent(type, mode);
  449. }
  450. void Node::RemoveComponent(Component* component)
  451. {
  452. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  453. {
  454. if (*i == component)
  455. {
  456. RemoveComponent(i);
  457. // Mark node dirty in all replication states
  458. MarkReplicationDirty();
  459. return;
  460. }
  461. }
  462. }
  463. void Node::RemoveComponent(ShortStringHash type)
  464. {
  465. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  466. {
  467. if ((*i)->GetType() == type)
  468. {
  469. RemoveComponent(i);
  470. // Mark node dirty in all replication states
  471. MarkReplicationDirty();
  472. return;
  473. }
  474. }
  475. }
  476. void Node::RemoveAllComponents()
  477. {
  478. if (components_.Empty())
  479. return;
  480. while (components_.Size())
  481. RemoveComponent(--components_.End());
  482. // Mark node dirty in all replication states
  483. MarkReplicationDirty();
  484. }
  485. Node* Node::Clone(CreateMode mode)
  486. {
  487. // The scene itself can not be cloned
  488. if (this == scene_ || !parent_)
  489. {
  490. LOGERROR("Can not clone node without a parent");
  491. return 0;
  492. }
  493. PROFILE(CloneNode);
  494. SceneResolver resolver;
  495. Node* clone = CloneRecursive(parent_, resolver, mode);
  496. resolver.Resolve();
  497. clone->ApplyAttributes();
  498. return clone;
  499. }
  500. void Node::Remove()
  501. {
  502. if (parent_)
  503. parent_->RemoveChild(this);
  504. }
  505. void Node::SetParent(Node* parent)
  506. {
  507. if (parent)
  508. {
  509. Vector3 worldPosition;
  510. Quaternion worldRotation;
  511. Vector3 worldScale;
  512. GetWorldTransform().Decompose(worldPosition, worldRotation, worldScale);
  513. parent->AddChild(this);
  514. SetWorldTransform(worldPosition, worldRotation, worldScale);
  515. }
  516. }
  517. void Node::SetVar(ShortStringHash key, const Variant& value)
  518. {
  519. vars_[key] = value;
  520. MarkNetworkUpdate();
  521. }
  522. void Node::AddListener(Component* component)
  523. {
  524. if (!component)
  525. return;
  526. // Check for not adding twice
  527. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  528. {
  529. if (*i == component)
  530. return;
  531. }
  532. listeners_.Push(WeakPtr<Component>(component));
  533. // If the node is currently dirty, notify immediately
  534. if (dirty_)
  535. component->OnMarkedDirty(this);
  536. }
  537. void Node::RemoveListener(Component* component)
  538. {
  539. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  540. {
  541. if (*i == component)
  542. {
  543. listeners_.Erase(i);
  544. return;
  545. }
  546. }
  547. }
  548. Vector3 Node::LocalToWorld(const Vector3& position) const
  549. {
  550. return GetWorldTransform() * position;
  551. }
  552. Vector3 Node::LocalToWorld(const Vector4& vector) const
  553. {
  554. return GetWorldTransform() * vector;
  555. }
  556. Vector3 Node::WorldToLocal(const Vector3& position) const
  557. {
  558. return GetWorldTransform().Inverse() * position;
  559. }
  560. Vector3 Node::WorldToLocal(const Vector4& vector) const
  561. {
  562. return GetWorldTransform().Inverse() * vector;
  563. }
  564. unsigned Node::GetNumChildren(bool recursive) const
  565. {
  566. if (!recursive)
  567. return children_.Size();
  568. else
  569. {
  570. unsigned allChildren = children_.Size();
  571. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  572. allChildren += (*i)->GetNumChildren(true);
  573. return allChildren;
  574. }
  575. }
  576. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  577. {
  578. dest.Clear();
  579. if (!recursive)
  580. {
  581. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  582. dest.Push(*i);
  583. }
  584. else
  585. GetChildrenRecursive(dest);
  586. }
  587. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  588. {
  589. dest.Clear();
  590. if (!recursive)
  591. {
  592. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  593. {
  594. if ((*i)->HasComponent(type))
  595. dest.Push(*i);
  596. }
  597. }
  598. else
  599. GetChildrenWithComponentRecursive(dest, type);
  600. }
  601. Node* Node::GetChild(unsigned index) const
  602. {
  603. return index < children_.Size() ? children_[index].Get() : 0;
  604. }
  605. Node* Node::GetChild(const String& name, bool recursive) const
  606. {
  607. return GetChild(StringHash(name), recursive);
  608. }
  609. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  610. {
  611. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  612. {
  613. if ((*i)->GetNameHash() == nameHash)
  614. return *i;
  615. if (recursive)
  616. {
  617. Node* node = (*i)->GetChild(nameHash, true);
  618. if (node)
  619. return node;
  620. }
  621. }
  622. return 0;
  623. }
  624. unsigned Node::GetNumNetworkComponents() const
  625. {
  626. unsigned num = 0;
  627. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  628. {
  629. if ((*i)->GetID() < FIRST_LOCAL_ID)
  630. ++num;
  631. }
  632. return num;
  633. }
  634. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
  635. {
  636. dest.Clear();
  637. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  638. {
  639. if ((*i)->GetType() == type)
  640. dest.Push(*i);
  641. }
  642. }
  643. bool Node::HasComponent(ShortStringHash type) const
  644. {
  645. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  646. {
  647. if ((*i)->GetType() == type)
  648. return true;
  649. }
  650. return false;
  651. }
  652. const Variant& Node::GetVar(ShortStringHash key) const
  653. {
  654. VariantMap::ConstIterator i = vars_.Find(key);
  655. if (i != vars_.End())
  656. return i->second_;
  657. else
  658. return Variant::EMPTY;
  659. }
  660. Component* Node::GetComponent(ShortStringHash type) const
  661. {
  662. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  663. {
  664. if ((*i)->GetType() == type)
  665. return *i;
  666. }
  667. return 0;
  668. }
  669. void Node::SetID(unsigned id)
  670. {
  671. id_ = id;
  672. }
  673. void Node::SetScene(Scene* scene)
  674. {
  675. scene_ = scene;
  676. }
  677. void Node::ResetScene()
  678. {
  679. SetID(0);
  680. SetScene(0);
  681. SetOwner(0);
  682. }
  683. void Node::SetNetPositionAttr(const Vector3& value)
  684. {
  685. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  686. if (transform)
  687. transform->SetTargetPosition(value);
  688. else
  689. SetPosition(value);
  690. }
  691. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  692. {
  693. MemoryBuffer buf(value);
  694. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  695. if (transform)
  696. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  697. else
  698. SetRotation(buf.ReadPackedQuaternion());
  699. }
  700. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  701. {
  702. Scene* scene = GetScene();
  703. if (!scene)
  704. return;
  705. MemoryBuffer buf(value);
  706. // If nothing in the buffer, parent is the root node
  707. if (buf.IsEof())
  708. {
  709. scene->AddChild(this);
  710. return;
  711. }
  712. unsigned baseNodeID = buf.ReadNetID();
  713. Node* baseNode = scene->GetNode(baseNodeID);
  714. if (!baseNode)
  715. {
  716. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  717. return;
  718. }
  719. // If buffer contains just an ID, the parent is replicated and we are done
  720. if (buf.IsEof())
  721. baseNode->AddChild(this);
  722. else
  723. {
  724. // Else the parent is local and we must find it recursively by name hash
  725. StringHash nameHash = buf.ReadStringHash();
  726. Node* parentNode = baseNode->GetChild(nameHash, true);
  727. if (!parentNode)
  728. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  729. else
  730. parentNode->AddChild(this);
  731. }
  732. }
  733. const Vector3& Node::GetNetPositionAttr() const
  734. {
  735. return position_;
  736. }
  737. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  738. {
  739. attrBuffer_.Clear();
  740. attrBuffer_.WritePackedQuaternion(rotation_);
  741. return attrBuffer_.GetBuffer();
  742. }
  743. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  744. {
  745. attrBuffer_.Clear();
  746. Scene* scene = GetScene();
  747. if (scene && parent_ && parent_ != scene)
  748. {
  749. // If parent is replicated, can write the ID directly
  750. unsigned parentID = parent_->GetID();
  751. if (parentID < FIRST_LOCAL_ID)
  752. attrBuffer_.WriteNetID(parentID);
  753. else
  754. {
  755. // Parent is local: traverse hierarchy to find a non-local base node
  756. // This iteration always stops due to the scene (root) being non-local
  757. Node* current = parent_;
  758. while (current->GetID() >= FIRST_LOCAL_ID)
  759. current = current->GetParent();
  760. // Then write the base node ID and the parent's name hash
  761. attrBuffer_.WriteNetID(current->GetID());
  762. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  763. }
  764. }
  765. return attrBuffer_.GetBuffer();
  766. }
  767. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  768. {
  769. // Remove all children and components first in case this is not a fresh load
  770. RemoveAllChildren();
  771. RemoveAllComponents();
  772. // ID has been read at the parent level
  773. if (!Serializable::Load(source))
  774. return false;
  775. unsigned numComponents = source.ReadVLE();
  776. for (unsigned i = 0; i < numComponents; ++i)
  777. {
  778. VectorBuffer compBuffer(source, source.ReadVLE());
  779. ShortStringHash compType = compBuffer.ReadShortStringHash();
  780. unsigned compID = compBuffer.ReadUInt();
  781. Component* newComponent = CreateComponent(compType,
  782. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  783. if (newComponent)
  784. {
  785. resolver.AddComponent(compID, newComponent);
  786. if (!newComponent->Load(compBuffer))
  787. return false;
  788. }
  789. }
  790. if (!readChildren)
  791. return true;
  792. unsigned numChildren = source.ReadVLE();
  793. for (unsigned i = 0; i < numChildren; ++i)
  794. {
  795. unsigned nodeID = source.ReadUInt();
  796. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  797. LOCAL);
  798. resolver.AddNode(nodeID, newNode);
  799. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  800. return false;
  801. }
  802. return true;
  803. }
  804. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  805. {
  806. // Remove all children and components first in case this is not a fresh load
  807. RemoveAllChildren();
  808. RemoveAllComponents();
  809. if (!Serializable::LoadXML(source))
  810. return false;
  811. XMLElement compElem = source.GetChild("component");
  812. while (compElem)
  813. {
  814. String typeName = compElem.GetAttribute("type");
  815. unsigned compID = compElem.GetInt("id");
  816. Component* newComponent = CreateComponent(ShortStringHash(typeName),
  817. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  818. if (newComponent)
  819. {
  820. resolver.AddComponent(compID, newComponent);
  821. if (!newComponent->LoadXML(compElem))
  822. return false;
  823. }
  824. compElem = compElem.GetNext("component");
  825. }
  826. if (!readChildren)
  827. return true;
  828. XMLElement childElem = source.GetChild("node");
  829. while (childElem)
  830. {
  831. unsigned nodeID = childElem.GetInt("id");
  832. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  833. LOCAL);
  834. resolver.AddNode(nodeID, newNode);
  835. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  836. return false;
  837. childElem = childElem.GetNext("node");
  838. }
  839. return true;
  840. }
  841. void Node::PrepareNetworkUpdate()
  842. {
  843. // Update dependency nodes list first
  844. dependencyNodes_.Clear();
  845. // Add the parent node, but if it is local, traverse to the first non-local node
  846. if (parent_ && parent_ != scene_)
  847. {
  848. Node* current = parent_;
  849. while (current->id_ >= FIRST_LOCAL_ID)
  850. current = current->parent_;
  851. if (current && current != scene_)
  852. dependencyNodes_.Push(current);
  853. }
  854. // Let the components add their dependencies
  855. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  856. {
  857. Component* component = *i;
  858. if (component->GetID() < FIRST_LOCAL_ID)
  859. component->GetDependencyNodes(dependencyNodes_);
  860. }
  861. // Then check for node attribute changes
  862. if (!networkState_)
  863. AllocateNetworkState();
  864. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  865. unsigned numAttributes = attributes->Size();
  866. if (networkState_->currentValues_.Size() != numAttributes)
  867. {
  868. networkState_->currentValues_.Resize(numAttributes);
  869. networkState_->previousValues_.Resize(numAttributes);
  870. // Copy the default attribute values to the previous state as a starting point
  871. for (unsigned i = 0; i < numAttributes; ++i)
  872. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  873. }
  874. // Check for attribute changes
  875. for (unsigned i = 0; i < numAttributes; ++i)
  876. {
  877. const AttributeInfo& attr = attributes->At(i);
  878. OnGetAttribute(attr, networkState_->currentValues_[i]);
  879. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  880. {
  881. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  882. // Mark the attribute dirty in all replication states that are tracking this node
  883. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  884. networkState_->replicationStates_.End();
  885. ++j)
  886. {
  887. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  888. nodeState->dirtyAttributes_.Set(i);
  889. // Add node to the dirty set if not added yet
  890. if (!nodeState->markedDirty_)
  891. {
  892. nodeState->markedDirty_ = true;
  893. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  894. }
  895. }
  896. }
  897. }
  898. // Finally check for user var changes
  899. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  900. {
  901. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  902. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  903. {
  904. networkState_->previousVars_[i->first_] = i->second_;
  905. // Mark the var dirty in all replication states that are tracking this node
  906. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  907. networkState_->replicationStates_.End(); ++j)
  908. {
  909. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  910. nodeState->dirtyVars_.Insert(i->first_);
  911. if (!nodeState->markedDirty_)
  912. {
  913. nodeState->markedDirty_ = true;
  914. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  915. }
  916. }
  917. }
  918. }
  919. networkUpdate_ = false;
  920. }
  921. void Node::CleanupConnection(Connection* connection)
  922. {
  923. if (owner_ == connection)
  924. owner_ = 0;
  925. if (networkState_)
  926. {
  927. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  928. {
  929. if (networkState_->replicationStates_[i]->connection_ == connection)
  930. networkState_->replicationStates_.Erase(i);
  931. }
  932. }
  933. }
  934. void Node::MarkNetworkUpdate()
  935. {
  936. if (!networkUpdate_ && scene_ && id_ < FIRST_LOCAL_ID)
  937. {
  938. scene_->MarkNetworkUpdate(this);
  939. networkUpdate_ = true;
  940. }
  941. }
  942. void Node::MarkReplicationDirty()
  943. {
  944. if (networkState_)
  945. {
  946. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  947. networkState_->replicationStates_.End(); ++j)
  948. {
  949. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  950. if (!nodeState->markedDirty_)
  951. {
  952. nodeState->markedDirty_ = true;
  953. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  954. }
  955. }
  956. }
  957. }
  958. Node* Node::CreateChild(unsigned id, CreateMode mode)
  959. {
  960. SharedPtr<Node> newNode(new Node(context_));
  961. // If zero ID specified, or the ID is already taken, let the scene assign
  962. if (scene_)
  963. {
  964. if (!id || scene_->GetNode(id))
  965. id = scene_->GetFreeNodeID(mode);
  966. newNode->SetID(id);
  967. }
  968. else
  969. newNode->SetID(id);
  970. AddChild(newNode);
  971. return newNode;
  972. }
  973. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  974. {
  975. if (!component)
  976. return;
  977. components_.Push(SharedPtr<Component>(component));
  978. // If zero ID specified, or the ID is already taken, let the scene assign
  979. if (scene_)
  980. {
  981. if (!id || scene_->GetComponent(id))
  982. id = scene_->GetFreeComponentID(mode);
  983. component->SetID(id);
  984. scene_->ComponentAdded(component);
  985. }
  986. else
  987. component->SetID(id);
  988. component->SetNode(this);
  989. component->OnMarkedDirty(this);
  990. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  991. component->MarkNetworkUpdate();
  992. MarkNetworkUpdate();
  993. MarkReplicationDirty();
  994. }
  995. void Node::UpdateWorldTransform() const
  996. {
  997. Matrix3x4 transform = GetTransform();
  998. if (parent_)
  999. worldTransform_ = parent_->GetWorldTransform() * transform;
  1000. else
  1001. worldTransform_ = transform;
  1002. dirty_ = false;
  1003. }
  1004. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1005. {
  1006. (*i)->parent_ = 0;
  1007. (*i)->MarkDirty();
  1008. (*i)->MarkNetworkUpdate();
  1009. children_.Erase(i);
  1010. }
  1011. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1012. {
  1013. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1014. {
  1015. Node* node = *i;
  1016. dest.Push(node);
  1017. if (!node->children_.Empty())
  1018. node->GetChildrenRecursive(dest);
  1019. }
  1020. }
  1021. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  1022. {
  1023. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1024. {
  1025. Node* node = *i;
  1026. if (node->HasComponent(type))
  1027. dest.Push(node);
  1028. if (!node->children_.Empty())
  1029. node->GetChildrenWithComponentRecursive(dest, type);
  1030. }
  1031. }
  1032. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1033. {
  1034. // Create clone node
  1035. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1036. resolver.AddNode(id_, cloneNode);
  1037. // Copy attributes
  1038. unsigned numAttributes = GetNumAttributes();
  1039. for (unsigned j = 0; j < numAttributes; ++j)
  1040. cloneNode->SetAttribute(j, GetAttribute(j));
  1041. // Clone components
  1042. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1043. {
  1044. Component* component = *i;
  1045. Component* cloneComponent = cloneNode->CreateComponent(component->GetType(), (mode == REPLICATED && component->GetID() <
  1046. FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1047. if (!cloneComponent)
  1048. {
  1049. LOGERROR("Could not clone component " + component->GetTypeName());
  1050. continue;
  1051. }
  1052. resolver.AddComponent(component->GetID(), cloneComponent);
  1053. numAttributes = component->GetNumAttributes();
  1054. for (unsigned j = 0; j < numAttributes; ++j)
  1055. cloneComponent->SetAttribute(j, component->GetAttribute(j));
  1056. }
  1057. // Clone child nodes recursively
  1058. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1059. {
  1060. Node* node = *i;
  1061. node->CloneRecursive(cloneNode, resolver, mode);
  1062. }
  1063. return cloneNode;
  1064. }
  1065. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1066. {
  1067. WeakPtr<Component> componentWeak(*i);
  1068. RemoveListener(*i);
  1069. if (scene_)
  1070. scene_->ComponentRemoved(*i);
  1071. components_.Erase(i);
  1072. // If the component is still referenced elsewhere, reset its node pointer now
  1073. if (componentWeak)
  1074. componentWeak->SetNode(0);
  1075. }
  1076. }