Node.cpp 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Context.h"
  26. #include "Log.h"
  27. #include "MemoryBuffer.h"
  28. #include "Scene.h"
  29. #include "XMLElement.h"
  30. #include "DebugNew.h"
  31. // Normalize rotation quaternion after this many incremental updates to prevent distortion
  32. static const int NORMALIZE_ROTATION_EVERY = 32;
  33. OBJECTTYPESTATIC(Node);
  34. Node::Node(Context* context) :
  35. Serializable(context),
  36. id_(0),
  37. parent_(0),
  38. scene_(0),
  39. owner_(0),
  40. position_(Vector3::ZERO),
  41. rotation_(Quaternion::IDENTITY),
  42. scale_(Vector3::UNITY),
  43. worldTransform_(Matrix3x4::IDENTITY),
  44. targetPosition_(Vector3::ZERO),
  45. targetRotation_(Quaternion::IDENTITY),
  46. rotateCount_(0),
  47. smoothingMask_(SMOOTH_NONE),
  48. dirty_(false),
  49. smoothed_(false)
  50. {
  51. }
  52. Node::~Node()
  53. {
  54. RemoveAllChildren();
  55. RemoveAllComponents();
  56. // Remove from the scene
  57. if (scene_)
  58. scene_->NodeRemoved(this);
  59. }
  60. void Node::RegisterObject(Context* context)
  61. {
  62. context->RegisterFactory<Node>();
  63. REF_ACCESSOR_ATTRIBUTE(Node, VAR_STRING, "Name", GetName, SetName, String, String(), AM_DEFAULT);
  64. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  65. REF_ACCESSOR_ATTRIBUTE(Node, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  66. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::UNITY, AM_DEFAULT);
  67. ATTRIBUTE(Node, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE); // Network replication of vars uses custom data
  68. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
  69. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_NOEDIT);
  70. }
  71. void Node::OnEvent(Object* sender, bool broadcast, StringHash eventType, VariantMap& eventData)
  72. {
  73. // Make a weak pointer to self to check for destruction during event handling
  74. WeakPtr<Node> self(this);
  75. // If this is a targeted event, forward it to all components
  76. if (!broadcast)
  77. {
  78. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  79. {
  80. components_[i]->OnEvent(sender, broadcast, eventType, eventData);
  81. if (self.Expired())
  82. return;
  83. }
  84. }
  85. else
  86. Object::OnEvent(sender, broadcast, eventType, eventData);
  87. }
  88. bool Node::Load(Deserializer& source)
  89. {
  90. return Load(source, true);
  91. }
  92. bool Node::Save(Serializer& dest)
  93. {
  94. if (!Serializable::Save(dest))
  95. return false;
  96. dest.WriteVLE(components_.Size());
  97. for (unsigned i = 0; i < components_.Size(); ++i)
  98. {
  99. Component* component = components_[i];
  100. // Create a separate buffer to be able to skip unknown components during deserialization
  101. VectorBuffer compBuffer;
  102. compBuffer.WriteShortStringHash(component->GetType());
  103. compBuffer.WriteUInt(component->GetID());
  104. if (!component->Save(compBuffer))
  105. return false;
  106. dest.WriteVLE(compBuffer.GetSize());
  107. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  108. }
  109. dest.WriteVLE(children_.Size());
  110. for (unsigned i = 0; i < children_.Size(); ++i)
  111. {
  112. Node* node = children_[i];
  113. dest.WriteUInt(node->GetID());
  114. if (!node->Save(dest))
  115. return false;
  116. }
  117. return true;
  118. }
  119. bool Node::LoadXML(const XMLElement& source)
  120. {
  121. return LoadXML(source, true);
  122. }
  123. bool Node::SaveXML(XMLElement& dest)
  124. {
  125. if (!Serializable::SaveXML(dest))
  126. return false;
  127. for (unsigned i = 0; i < components_.Size(); ++i)
  128. {
  129. Component* component = components_[i];
  130. XMLElement compElem = dest.CreateChild("component");
  131. compElem.SetString("type", component->GetTypeName());
  132. compElem.SetInt("id", component->GetID());
  133. if (!component->SaveXML(compElem))
  134. return false;
  135. }
  136. for (unsigned i = 0; i < children_.Size(); ++i)
  137. {
  138. Node* node = children_[i];
  139. XMLElement childElem = dest.CreateChild("node");
  140. childElem.SetInt("id", node->GetID());
  141. if (!node->SaveXML(childElem))
  142. return false;
  143. }
  144. return true;
  145. }
  146. void Node::ApplyAttributes()
  147. {
  148. for (unsigned i = 0; i < components_.Size(); ++i)
  149. components_[i]->ApplyAttributes();
  150. for (unsigned i = 0; i < children_.Size(); ++i)
  151. children_[i]->ApplyAttributes();
  152. }
  153. void Node::SetName(const String& name)
  154. {
  155. name_ = name;
  156. nameHash_ = StringHash(name);
  157. }
  158. void Node::SetPosition(const Vector3& position)
  159. {
  160. if (!smoothed_)
  161. {
  162. position_ = position;
  163. if (!dirty_)
  164. MarkDirty();
  165. }
  166. else
  167. {
  168. targetPosition_ = position;
  169. smoothingMask_ |= SMOOTH_POSITION;
  170. }
  171. }
  172. void Node::SetRotation(const Quaternion& rotation)
  173. {
  174. if (!smoothed_)
  175. {
  176. rotation_ = rotation;
  177. if (!dirty_)
  178. MarkDirty();
  179. }
  180. else
  181. {
  182. targetRotation_ = rotation;
  183. smoothingMask_ |= SMOOTH_ROTATION;
  184. }
  185. rotateCount_ = 0;
  186. }
  187. void Node::SetDirection(const Vector3& direction)
  188. {
  189. SetRotation(Quaternion(Vector3::FORWARD, direction));
  190. }
  191. void Node::SetScale(float scale)
  192. {
  193. scale_ = Vector3(scale, scale, scale).Abs();
  194. if (!dirty_)
  195. MarkDirty();
  196. }
  197. void Node::SetScale(const Vector3& scale)
  198. {
  199. scale_ = scale.Abs();
  200. if (!dirty_)
  201. MarkDirty();
  202. }
  203. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  204. {
  205. if (!smoothed_)
  206. {
  207. position_ = position;
  208. rotation_ = rotation;
  209. if (!dirty_)
  210. MarkDirty();
  211. }
  212. else
  213. {
  214. targetPosition_ = position;
  215. targetRotation_ = rotation;
  216. smoothingMask_ |= SMOOTH_POSITION | SMOOTH_ROTATION;
  217. }
  218. rotateCount_ = 0;
  219. }
  220. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  221. {
  222. if (!smoothed_)
  223. {
  224. position_ = position;
  225. rotation_ = rotation;
  226. }
  227. else
  228. {
  229. targetPosition_ = position;
  230. targetRotation_ = rotation;
  231. smoothingMask_ |= SMOOTH_POSITION | SMOOTH_ROTATION;
  232. }
  233. rotateCount_ = 0;
  234. scale_ = Vector3(scale, scale, scale);
  235. if (!dirty_)
  236. MarkDirty();
  237. }
  238. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  239. {
  240. if (!smoothed_)
  241. {
  242. position_ = position;
  243. rotation_ = rotation;
  244. }
  245. else
  246. {
  247. targetPosition_ = position;
  248. targetRotation_ = rotation;
  249. smoothingMask_ |= SMOOTH_POSITION | SMOOTH_ROTATION;
  250. }
  251. rotateCount_ = 0;
  252. scale_ = scale;
  253. if (!dirty_)
  254. MarkDirty();
  255. }
  256. void Node::SnapPosition(const Vector3& position)
  257. {
  258. position_ = position;
  259. targetPosition_ = position;
  260. smoothingMask_ &= ~SMOOTH_POSITION;
  261. if (!dirty_)
  262. MarkDirty();
  263. }
  264. void Node::SnapRotation(const Quaternion& rotation)
  265. {
  266. rotation_ = rotation;
  267. targetRotation_ = rotation;
  268. smoothingMask_ &= ~SMOOTH_ROTATION;
  269. rotateCount_ = 0;
  270. if (!dirty_)
  271. MarkDirty();
  272. }
  273. void Node::Translate(const Vector3& delta)
  274. {
  275. if (!smoothed_)
  276. {
  277. position_ += delta;
  278. if (!dirty_)
  279. MarkDirty();
  280. }
  281. else
  282. {
  283. targetPosition_ += delta;
  284. smoothingMask_ |= SMOOTH_POSITION;
  285. }
  286. }
  287. void Node::TranslateRelative(const Vector3& delta)
  288. {
  289. if (!smoothed_)
  290. {
  291. position_ += rotation_ * delta;
  292. if (!dirty_)
  293. MarkDirty();
  294. }
  295. else
  296. {
  297. targetPosition_ += targetRotation_ * delta;
  298. smoothingMask_ |= SMOOTH_POSITION;
  299. }
  300. }
  301. void Node::Rotate(const Quaternion& delta, bool fixedAxis)
  302. {
  303. if (!smoothed_)
  304. {
  305. if (!fixedAxis)
  306. rotation_ = rotation_ * delta;
  307. else
  308. rotation_ = delta * rotation_;
  309. }
  310. else
  311. {
  312. if (!fixedAxis)
  313. targetRotation_ = targetRotation_ * delta;
  314. else
  315. targetRotation_ = delta * targetRotation_;
  316. smoothingMask_ |= SMOOTH_ROTATION;
  317. }
  318. ++rotateCount_;
  319. if (rotateCount_ >= NORMALIZE_ROTATION_EVERY)
  320. {
  321. if (!smoothed_)
  322. rotation_.Normalize();
  323. else
  324. targetRotation_.Normalize();
  325. rotateCount_ = 0;
  326. }
  327. if (!dirty_)
  328. MarkDirty();
  329. }
  330. void Node::Yaw(float angle, bool fixedAxis)
  331. {
  332. Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
  333. }
  334. void Node::Pitch(float angle, bool fixedAxis)
  335. {
  336. Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
  337. }
  338. void Node::Roll(float angle, bool fixedAxis)
  339. {
  340. Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
  341. }
  342. void Node::Scale(float scale)
  343. {
  344. scale_ *= scale;
  345. if (!dirty_)
  346. MarkDirty();
  347. }
  348. void Node::Scale(const Vector3& scale)
  349. {
  350. scale_ *= scale;
  351. if (!dirty_)
  352. MarkDirty();
  353. }
  354. void Node::SetOwner(Connection* owner)
  355. {
  356. owner_ = owner;
  357. }
  358. void Node::SetSmoothed(bool enable)
  359. {
  360. smoothed_ = enable;
  361. }
  362. void Node::MarkDirty()
  363. {
  364. dirty_ = true;
  365. // Notify listener components first, then mark child nodes
  366. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  367. {
  368. if (*i)
  369. {
  370. (*i)->OnMarkedDirty(this);
  371. ++i;
  372. }
  373. // If listener has expired, erase from list
  374. else
  375. i = listeners_.Erase(i);
  376. }
  377. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  378. (*i)->MarkDirty();
  379. }
  380. Node* Node::CreateChild(const String& name, CreateMode mode)
  381. {
  382. Node* newNode = CreateChild(0, mode);
  383. newNode->SetName(name);
  384. return newNode;
  385. }
  386. void Node::AddChild(Node* node)
  387. {
  388. // Check for illegal or redundant parent assignment
  389. if (!node || node == this || node->parent_ == this)
  390. return;
  391. // Check for possible cyclic parent assignment
  392. Node* parent = parent_;
  393. while (parent)
  394. {
  395. if (parent == node)
  396. return;
  397. parent = parent->parent_;
  398. }
  399. // Add first, then remove from old parent, to ensure the node does not get deleted
  400. children_.Push(SharedPtr<Node>(node));
  401. if (node->parent_)
  402. node->parent_->RemoveChild(node);
  403. // Add to the scene if not added yet
  404. if (scene_ && !node->GetScene())
  405. scene_->NodeAdded(node);
  406. node->parent_ = this;
  407. node->MarkDirty();
  408. }
  409. void Node::RemoveChild(Node* node)
  410. {
  411. if (!node)
  412. return;
  413. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  414. {
  415. if (*i == node)
  416. {
  417. RemoveChild(i);
  418. return;
  419. }
  420. }
  421. }
  422. void Node::RemoveAllChildren()
  423. {
  424. while (children_.Size())
  425. RemoveChild(children_.End() - 1);
  426. }
  427. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode)
  428. {
  429. return CreateComponent(type, 0, mode);
  430. }
  431. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode)
  432. {
  433. Component* oldComponent = GetComponent(type);
  434. if (oldComponent)
  435. return oldComponent;
  436. else
  437. return CreateComponent(type, 0, mode);
  438. }
  439. void Node::RemoveComponent(Component* component)
  440. {
  441. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  442. {
  443. if (*i == component)
  444. {
  445. WeakPtr<Component> componentWeak(*i);
  446. RemoveListener(*i);
  447. if (scene_)
  448. scene_->ComponentRemoved(*i);
  449. components_.Erase(i);
  450. // If the component is still referenced elsewhere, reset its node pointer now
  451. if (componentWeak)
  452. componentWeak->SetNode(0);
  453. return;
  454. }
  455. }
  456. }
  457. void Node::RemoveAllComponents()
  458. {
  459. while (components_.Size())
  460. {
  461. Vector<SharedPtr<Component> >::Iterator i = components_.End() - 1;
  462. WeakPtr<Component> componentWeak(*i);
  463. RemoveListener(*i);
  464. if (scene_)
  465. scene_->ComponentRemoved(*i);
  466. components_.Erase(i);
  467. // If the component is still referenced elsewhere, reset its node pointer now
  468. if (componentWeak)
  469. componentWeak->SetNode(0);
  470. }
  471. }
  472. void Node::AddListener(Component* component)
  473. {
  474. if (!component)
  475. return;
  476. // Check for not adding twice
  477. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  478. {
  479. if (*i == component)
  480. return;
  481. }
  482. listeners_.Push(WeakPtr<Component>(component));
  483. // If the node is currently dirty, notify immediately
  484. if (dirty_)
  485. component->OnMarkedDirty(this);
  486. }
  487. void Node::RemoveListener(Component* component)
  488. {
  489. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  490. {
  491. if (*i == component)
  492. {
  493. listeners_.Erase(i);
  494. return;
  495. }
  496. }
  497. }
  498. void Node::Remove()
  499. {
  500. if (parent_)
  501. parent_->RemoveChild(this);
  502. }
  503. void Node::SetParent(Node* parent)
  504. {
  505. if (parent)
  506. parent->AddChild(this);
  507. }
  508. Matrix3x4 Node::GetWorldTargetTransform() const
  509. {
  510. if (!smoothed_)
  511. return GetWorldTransform();
  512. Matrix3x4 ret(targetPosition_, targetRotation_, scale_);
  513. Node* current = parent_;
  514. while (current)
  515. {
  516. ret = Matrix3x4(current->targetPosition_, current->targetRotation_, current->scale_) * ret;
  517. current = current->parent_;
  518. }
  519. return ret;
  520. }
  521. unsigned Node::GetNumChildren(bool recursive) const
  522. {
  523. if (!recursive)
  524. return children_.Size();
  525. else
  526. {
  527. unsigned allChildren = children_.Size();
  528. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  529. allChildren += (*i)->GetNumChildren(true);
  530. return allChildren;
  531. }
  532. }
  533. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  534. {
  535. dest.Clear();
  536. if (!recursive)
  537. {
  538. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  539. dest.Push(*i);
  540. }
  541. else
  542. GetChildrenRecursive(dest);
  543. }
  544. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  545. {
  546. dest.Clear();
  547. if (!recursive)
  548. {
  549. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  550. {
  551. if ((*i)->HasComponent(type))
  552. dest.Push(*i);
  553. }
  554. }
  555. else
  556. GetChildrenWithComponentRecursive(dest, type);
  557. }
  558. Node* Node::GetChild(unsigned index) const
  559. {
  560. return index < children_.Size() ? children_[index].Get() : 0;
  561. }
  562. Node* Node::GetChild(const String& name, bool recursive) const
  563. {
  564. return GetChild(StringHash(name), recursive);
  565. }
  566. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  567. {
  568. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  569. {
  570. if ((*i)->GetNameHash() == nameHash)
  571. return *i;
  572. if (recursive)
  573. {
  574. Node* node = (*i)->GetChild(nameHash, true);
  575. if (node)
  576. return node;
  577. }
  578. }
  579. return 0;
  580. }
  581. unsigned Node::GetNumNetworkComponents() const
  582. {
  583. unsigned num = 0;
  584. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  585. {
  586. if ((*i)->GetID() < FIRST_LOCAL_ID)
  587. ++num;
  588. }
  589. return num;
  590. }
  591. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
  592. {
  593. dest.Clear();
  594. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  595. {
  596. if ((*i)->GetType() == type)
  597. dest.Push(*i);
  598. }
  599. }
  600. bool Node::HasComponent(ShortStringHash type) const
  601. {
  602. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  603. {
  604. if ((*i)->GetType() == type)
  605. return true;
  606. }
  607. return false;
  608. }
  609. Component* Node::GetComponent(ShortStringHash type) const
  610. {
  611. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  612. {
  613. if ((*i)->GetType() == type)
  614. return *i;
  615. }
  616. return 0;
  617. }
  618. void Node::GetDependencyNodes(PODVector<Node*>& dest) const
  619. {
  620. // Add the parent node, but if it is local, traverse to the first non-local node
  621. if (parent_ && parent_ != scene_)
  622. {
  623. Node* current = parent_;
  624. while (current->id_ >= FIRST_LOCAL_ID)
  625. current = current->parent_;
  626. dest.Push(current);
  627. }
  628. // Then let the components add their dependencies
  629. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  630. (*i)->GetDependencyNodes(dest);
  631. }
  632. void Node::SetID(unsigned id)
  633. {
  634. id_ = id;
  635. }
  636. void Node::SetScene(Scene* scene)
  637. {
  638. scene_ = scene;
  639. }
  640. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  641. {
  642. MemoryBuffer buf(value);
  643. SetRotation(buf.ReadPackedQuaternion());
  644. }
  645. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  646. {
  647. Scene* scene = GetScene();
  648. if (!scene)
  649. return;
  650. MemoryBuffer buf(value);
  651. // If nothing in the buffer, parent is the root node
  652. if (buf.IsEof())
  653. {
  654. SetParent(scene);
  655. return;
  656. }
  657. unsigned baseNodeID = buf.ReadNetID();
  658. Node* baseNode = scene->GetNode(baseNodeID);
  659. if (!baseNode)
  660. {
  661. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  662. return;
  663. }
  664. // If buffer contains just an ID, the parent is replicated and we are done
  665. if (buf.IsEof())
  666. SetParent(baseNode);
  667. else
  668. {
  669. // Else the parent is local and we must find it recursively by name hash
  670. StringHash nameHash = buf.ReadStringHash();
  671. Node* parentNode = baseNode->GetChild(nameHash, true);
  672. if (!parentNode)
  673. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  674. else
  675. SetParent(parentNode);
  676. }
  677. }
  678. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  679. {
  680. attrBuffer_.Clear();
  681. attrBuffer_.WritePackedQuaternion(rotation_);
  682. return attrBuffer_.GetBuffer();
  683. }
  684. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  685. {
  686. attrBuffer_.Clear();
  687. Scene* scene = GetScene();
  688. if (scene && parent_ && parent_ != scene)
  689. {
  690. // If parent is replicated, can write the ID directly
  691. unsigned parentID = parent_->GetID();
  692. if (parentID < FIRST_LOCAL_ID)
  693. attrBuffer_.WriteNetID(parentID);
  694. else
  695. {
  696. // Parent is local: traverse hierarchy to find a non-local base node
  697. // This iteration always stops due to the scene (root) being non-local
  698. Node* current = parent_;
  699. while (current->GetID() >= FIRST_LOCAL_ID)
  700. current = current->GetParent();
  701. // Then write the base node ID and the parent's name hash
  702. attrBuffer_.WriteVLE(current->GetID());
  703. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  704. }
  705. }
  706. return attrBuffer_.GetBuffer();
  707. }
  708. void Node::UpdateSmoothing(float constant, float squaredSnapThreshold)
  709. {
  710. if (!smoothed_ || !smoothingMask_)
  711. return;
  712. if (smoothingMask_ & SMOOTH_POSITION)
  713. {
  714. // If position snaps, snap everything to the end
  715. float delta = (position_ - targetPosition_).LengthSquared();
  716. if (delta > squaredSnapThreshold)
  717. constant = 1.0f;
  718. if (delta < M_EPSILON || constant >= 1.0f)
  719. {
  720. position_ = targetPosition_;
  721. smoothingMask_ &= ~SMOOTH_POSITION;
  722. }
  723. else
  724. position_ = position_.Lerp(targetPosition_, constant);
  725. }
  726. if (smoothingMask_ & SMOOTH_ROTATION)
  727. {
  728. float delta = (rotation_ - targetRotation_).LengthSquared();
  729. if (delta < M_EPSILON || constant >= 1.0f)
  730. {
  731. rotation_ = targetRotation_;
  732. smoothingMask_ &= ~SMOOTH_ROTATION;
  733. }
  734. else
  735. rotation_ = rotation_.Slerp(targetRotation_, constant);
  736. }
  737. if (!dirty_)
  738. MarkDirty();
  739. }
  740. bool Node::Load(Deserializer& source, bool readChildren)
  741. {
  742. // Remove all children and components first in case this is not a fresh load
  743. RemoveAllChildren();
  744. RemoveAllComponents();
  745. // ID has been read at the parent level
  746. if (!Serializable::Load(source))
  747. return false;
  748. unsigned numComponents = source.ReadVLE();
  749. for (unsigned i = 0; i < numComponents; ++i)
  750. {
  751. VectorBuffer compBuffer(source, source.ReadVLE());
  752. ShortStringHash newType = compBuffer.ReadShortStringHash();
  753. Component* newComponent = CreateComponent(newType, compBuffer.ReadUInt(), REPLICATED);
  754. if (newComponent)
  755. {
  756. if (!newComponent->Load(compBuffer))
  757. return false;
  758. }
  759. }
  760. if (!readChildren)
  761. return true;
  762. unsigned numChildren = source.ReadVLE();
  763. for (unsigned i = 0; i < numChildren; ++i)
  764. {
  765. Node* newNode = CreateChild(source.ReadUInt(), REPLICATED);
  766. if (!newNode->Load(source))
  767. return false;
  768. }
  769. return true;
  770. }
  771. bool Node::LoadXML(const XMLElement& source, bool readChildren)
  772. {
  773. // Remove all children and components first in case this is not a fresh load
  774. RemoveAllChildren();
  775. RemoveAllComponents();
  776. if (!Serializable::LoadXML(source))
  777. return false;
  778. XMLElement compElem = source.GetChild("component");
  779. while (compElem)
  780. {
  781. String typeName = compElem.GetString("type");
  782. Component* newComponent = CreateComponent(ShortStringHash(compElem.GetString("type")), compElem.GetInt("id"), REPLICATED);
  783. if (newComponent)
  784. {
  785. if (!newComponent->LoadXML(compElem))
  786. return false;
  787. }
  788. compElem = compElem.GetNext("component");
  789. }
  790. if (!readChildren)
  791. return true;
  792. XMLElement childElem = source.GetChild("node");
  793. while (childElem)
  794. {
  795. Node* newNode = CreateChild(childElem.GetInt("id"), REPLICATED);
  796. if (!newNode->LoadXML(childElem))
  797. return false;
  798. childElem = childElem.GetNext("node");
  799. }
  800. return true;
  801. }
  802. Component* Node::CreateComponent(ShortStringHash type, unsigned id, CreateMode mode)
  803. {
  804. // Check that creation succeeds and that the object in fact is a component
  805. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  806. if (!newComponent)
  807. {
  808. LOGERROR("Could not create unknown component type " + type.ToString());
  809. return 0;
  810. }
  811. components_.Push(newComponent);
  812. // If zero ID specified, or the ID is already taken, let the scene assign
  813. if (scene_)
  814. {
  815. if (!id || scene_->GetComponent(id))
  816. id = scene_->GetFreeComponentID(mode);
  817. newComponent->SetID(id);
  818. scene_->ComponentAdded(newComponent);
  819. }
  820. else
  821. newComponent->SetID(id);
  822. newComponent->SetNode(this);
  823. newComponent->OnMarkedDirty(this);
  824. return newComponent;
  825. }
  826. Node* Node::CreateChild(unsigned id, CreateMode mode)
  827. {
  828. SharedPtr<Node> newNode(new Node(context_));
  829. // If zero ID specified, or the ID is already taken, let the scene assign
  830. if (scene_)
  831. {
  832. if (!id || scene_->GetComponent(id))
  833. id = scene_->GetFreeNodeID(mode);
  834. newNode->SetID(id);
  835. }
  836. else
  837. newNode->SetID(id);
  838. AddChild(newNode);
  839. return newNode;
  840. }
  841. void Node::UpdateWorldTransform() const
  842. {
  843. if (parent_)
  844. {
  845. if (parent_->dirty_)
  846. parent_->UpdateWorldTransform();
  847. worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
  848. }
  849. else
  850. worldTransform_ = Matrix3x4(position_, rotation_, scale_);
  851. dirty_ = false;
  852. }
  853. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  854. {
  855. (*i)->parent_ = 0;
  856. (*i)->MarkDirty();
  857. children_.Erase(i);
  858. }
  859. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  860. {
  861. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  862. {
  863. Node* node = *i;
  864. dest.Push(node);
  865. if (!node->children_.Empty())
  866. node->GetChildrenRecursive(dest);
  867. }
  868. }
  869. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  870. {
  871. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  872. {
  873. Node* node = *i;
  874. if (node->HasComponent(type))
  875. dest.Push(node);
  876. if (!node->children_.Empty())
  877. node->GetChildrenRecursive(dest);
  878. }
  879. }