Node.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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::ONE),
  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::ONE, 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::LookAt(const Vector3& target, const Vector3& upAxis, bool worldSpace)
  343. {
  344. Vector3 targetZ;
  345. if (worldSpace)
  346. targetZ = (target - GetWorldPosition()).Normalized();
  347. else
  348. targetZ = (target - position_).Normalized();
  349. Vector3 targetX = upAxis.CrossProduct(targetZ).Normalized();
  350. Vector3 targetY = targetZ.CrossProduct(targetX).Normalized();
  351. if (!worldSpace || !parent_)
  352. SetRotation(Quaternion(targetX, targetY, targetZ));
  353. else
  354. SetRotation(parent_->GetWorldRotation().Inverse() * Quaternion(targetX, targetY, targetZ));
  355. }
  356. void Node::Scale(float scale)
  357. {
  358. scale_ *= scale;
  359. if (!dirty_)
  360. MarkDirty();
  361. }
  362. void Node::Scale(const Vector3& scale)
  363. {
  364. scale_ *= scale;
  365. if (!dirty_)
  366. MarkDirty();
  367. }
  368. void Node::SetOwner(Connection* owner)
  369. {
  370. owner_ = owner;
  371. }
  372. void Node::SetSmoothed(bool enable)
  373. {
  374. smoothed_ = enable;
  375. }
  376. void Node::MarkDirty()
  377. {
  378. dirty_ = true;
  379. // Notify listener components first, then mark child nodes
  380. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  381. {
  382. if (*i)
  383. {
  384. (*i)->OnMarkedDirty(this);
  385. ++i;
  386. }
  387. // If listener has expired, erase from list
  388. else
  389. i = listeners_.Erase(i);
  390. }
  391. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  392. (*i)->MarkDirty();
  393. }
  394. Node* Node::CreateChild(const String& name, CreateMode mode)
  395. {
  396. Node* newNode = CreateChild(0, mode);
  397. newNode->SetName(name);
  398. return newNode;
  399. }
  400. void Node::AddChild(Node* node)
  401. {
  402. // Check for illegal or redundant parent assignment
  403. if (!node || node == this || node->parent_ == this)
  404. return;
  405. // Check for possible cyclic parent assignment
  406. Node* parent = parent_;
  407. while (parent)
  408. {
  409. if (parent == node)
  410. return;
  411. parent = parent->parent_;
  412. }
  413. // Add first, then remove from old parent, to ensure the node does not get deleted
  414. children_.Push(SharedPtr<Node>(node));
  415. if (node->parent_)
  416. node->parent_->RemoveChild(node);
  417. // Add to the scene if not added yet
  418. if (scene_ && !node->GetScene())
  419. scene_->NodeAdded(node);
  420. node->parent_ = this;
  421. node->MarkDirty();
  422. }
  423. void Node::RemoveChild(Node* node)
  424. {
  425. if (!node)
  426. return;
  427. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  428. {
  429. if (*i == node)
  430. {
  431. RemoveChild(i);
  432. return;
  433. }
  434. }
  435. }
  436. void Node::RemoveAllChildren()
  437. {
  438. while (children_.Size())
  439. RemoveChild(children_.End() - 1);
  440. }
  441. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode)
  442. {
  443. return CreateComponent(type, 0, mode);
  444. }
  445. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode)
  446. {
  447. Component* oldComponent = GetComponent(type);
  448. if (oldComponent)
  449. return oldComponent;
  450. else
  451. return CreateComponent(type, 0, mode);
  452. }
  453. void Node::RemoveComponent(Component* component)
  454. {
  455. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  456. {
  457. if (*i == component)
  458. {
  459. WeakPtr<Component> componentWeak(*i);
  460. RemoveListener(*i);
  461. if (scene_)
  462. scene_->ComponentRemoved(*i);
  463. components_.Erase(i);
  464. // If the component is still referenced elsewhere, reset its node pointer now
  465. if (componentWeak)
  466. componentWeak->SetNode(0);
  467. return;
  468. }
  469. }
  470. }
  471. void Node::RemoveAllComponents()
  472. {
  473. while (components_.Size())
  474. {
  475. Vector<SharedPtr<Component> >::Iterator i = components_.End() - 1;
  476. WeakPtr<Component> componentWeak(*i);
  477. RemoveListener(*i);
  478. if (scene_)
  479. scene_->ComponentRemoved(*i);
  480. components_.Erase(i);
  481. // If the component is still referenced elsewhere, reset its node pointer now
  482. if (componentWeak)
  483. componentWeak->SetNode(0);
  484. }
  485. }
  486. void Node::AddListener(Component* component)
  487. {
  488. if (!component)
  489. return;
  490. // Check for not adding twice
  491. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  492. {
  493. if (*i == component)
  494. return;
  495. }
  496. listeners_.Push(WeakPtr<Component>(component));
  497. // If the node is currently dirty, notify immediately
  498. if (dirty_)
  499. component->OnMarkedDirty(this);
  500. }
  501. void Node::RemoveListener(Component* component)
  502. {
  503. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  504. {
  505. if (*i == component)
  506. {
  507. listeners_.Erase(i);
  508. return;
  509. }
  510. }
  511. }
  512. void Node::Remove()
  513. {
  514. if (parent_)
  515. parent_->RemoveChild(this);
  516. }
  517. void Node::SetParent(Node* parent)
  518. {
  519. if (parent)
  520. parent->AddChild(this);
  521. }
  522. Matrix3x4 Node::GetWorldTargetTransform() const
  523. {
  524. if (!smoothed_)
  525. return GetWorldTransform();
  526. Matrix3x4 ret(targetPosition_, targetRotation_, scale_);
  527. Node* current = parent_;
  528. while (current)
  529. {
  530. ret = Matrix3x4(current->targetPosition_, current->targetRotation_, current->scale_) * ret;
  531. current = current->parent_;
  532. }
  533. return ret;
  534. }
  535. Vector3 Node::LocalToWorld(const Vector3& position) const
  536. {
  537. return GetWorldTransform() * position;
  538. }
  539. Vector3 Node::LocalToWorld(const Vector4& vector) const
  540. {
  541. return GetWorldTransform() * vector;
  542. }
  543. Vector3 Node::WorldToLocal(const Vector3& position) const
  544. {
  545. return GetWorldTransform().Inverse() * position;
  546. }
  547. Vector3 Node::WorldToLocal(const Vector4& vector) const
  548. {
  549. return GetWorldTransform().Inverse() * vector;
  550. }
  551. unsigned Node::GetNumChildren(bool recursive) const
  552. {
  553. if (!recursive)
  554. return children_.Size();
  555. else
  556. {
  557. unsigned allChildren = children_.Size();
  558. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  559. allChildren += (*i)->GetNumChildren(true);
  560. return allChildren;
  561. }
  562. }
  563. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  564. {
  565. dest.Clear();
  566. if (!recursive)
  567. {
  568. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  569. dest.Push(*i);
  570. }
  571. else
  572. GetChildrenRecursive(dest);
  573. }
  574. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  575. {
  576. dest.Clear();
  577. if (!recursive)
  578. {
  579. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  580. {
  581. if ((*i)->HasComponent(type))
  582. dest.Push(*i);
  583. }
  584. }
  585. else
  586. GetChildrenWithComponentRecursive(dest, type);
  587. }
  588. Node* Node::GetChild(unsigned index) const
  589. {
  590. return index < children_.Size() ? children_[index].Get() : 0;
  591. }
  592. Node* Node::GetChild(const String& name, bool recursive) const
  593. {
  594. return GetChild(StringHash(name), recursive);
  595. }
  596. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  597. {
  598. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  599. {
  600. if ((*i)->GetNameHash() == nameHash)
  601. return *i;
  602. if (recursive)
  603. {
  604. Node* node = (*i)->GetChild(nameHash, true);
  605. if (node)
  606. return node;
  607. }
  608. }
  609. return 0;
  610. }
  611. unsigned Node::GetNumNetworkComponents() const
  612. {
  613. unsigned num = 0;
  614. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  615. {
  616. if ((*i)->GetID() < FIRST_LOCAL_ID)
  617. ++num;
  618. }
  619. return num;
  620. }
  621. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
  622. {
  623. dest.Clear();
  624. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  625. {
  626. if ((*i)->GetType() == type)
  627. dest.Push(*i);
  628. }
  629. }
  630. bool Node::HasComponent(ShortStringHash type) const
  631. {
  632. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  633. {
  634. if ((*i)->GetType() == type)
  635. return true;
  636. }
  637. return false;
  638. }
  639. Component* Node::GetComponent(ShortStringHash type) const
  640. {
  641. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  642. {
  643. if ((*i)->GetType() == type)
  644. return *i;
  645. }
  646. return 0;
  647. }
  648. void Node::GetDependencyNodes(PODVector<Node*>& dest) const
  649. {
  650. // Add the parent node, but if it is local, traverse to the first non-local node
  651. if (parent_ && parent_ != scene_)
  652. {
  653. Node* current = parent_;
  654. while (current->id_ >= FIRST_LOCAL_ID)
  655. current = current->parent_;
  656. dest.Push(current);
  657. }
  658. // Then let the components add their dependencies
  659. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  660. (*i)->GetDependencyNodes(dest);
  661. }
  662. void Node::SetID(unsigned id)
  663. {
  664. id_ = id;
  665. }
  666. void Node::SetScene(Scene* scene)
  667. {
  668. scene_ = scene;
  669. }
  670. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  671. {
  672. MemoryBuffer buf(value);
  673. SetRotation(buf.ReadPackedQuaternion());
  674. }
  675. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  676. {
  677. Scene* scene = GetScene();
  678. if (!scene)
  679. return;
  680. MemoryBuffer buf(value);
  681. // If nothing in the buffer, parent is the root node
  682. if (buf.IsEof())
  683. {
  684. SetParent(scene);
  685. return;
  686. }
  687. unsigned baseNodeID = buf.ReadNetID();
  688. Node* baseNode = scene->GetNode(baseNodeID);
  689. if (!baseNode)
  690. {
  691. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  692. return;
  693. }
  694. // If buffer contains just an ID, the parent is replicated and we are done
  695. if (buf.IsEof())
  696. SetParent(baseNode);
  697. else
  698. {
  699. // Else the parent is local and we must find it recursively by name hash
  700. StringHash nameHash = buf.ReadStringHash();
  701. Node* parentNode = baseNode->GetChild(nameHash, true);
  702. if (!parentNode)
  703. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  704. else
  705. SetParent(parentNode);
  706. }
  707. }
  708. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  709. {
  710. attrBuffer_.Clear();
  711. attrBuffer_.WritePackedQuaternion(rotation_);
  712. return attrBuffer_.GetBuffer();
  713. }
  714. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  715. {
  716. attrBuffer_.Clear();
  717. Scene* scene = GetScene();
  718. if (scene && parent_ && parent_ != scene)
  719. {
  720. // If parent is replicated, can write the ID directly
  721. unsigned parentID = parent_->GetID();
  722. if (parentID < FIRST_LOCAL_ID)
  723. attrBuffer_.WriteNetID(parentID);
  724. else
  725. {
  726. // Parent is local: traverse hierarchy to find a non-local base node
  727. // This iteration always stops due to the scene (root) being non-local
  728. Node* current = parent_;
  729. while (current->GetID() >= FIRST_LOCAL_ID)
  730. current = current->GetParent();
  731. // Then write the base node ID and the parent's name hash
  732. attrBuffer_.WriteVLE(current->GetID());
  733. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  734. }
  735. }
  736. return attrBuffer_.GetBuffer();
  737. }
  738. void Node::UpdateSmoothing(float constant, float squaredSnapThreshold)
  739. {
  740. if (!smoothed_ || !smoothingMask_)
  741. return;
  742. if (smoothingMask_ & SMOOTH_POSITION)
  743. {
  744. // If position snaps, snap everything to the end
  745. float delta = (position_ - targetPosition_).LengthSquared();
  746. if (delta > squaredSnapThreshold)
  747. constant = 1.0f;
  748. if (delta < M_EPSILON || constant >= 1.0f)
  749. {
  750. position_ = targetPosition_;
  751. smoothingMask_ &= ~SMOOTH_POSITION;
  752. }
  753. else
  754. position_ = position_.Lerp(targetPosition_, constant);
  755. }
  756. if (smoothingMask_ & SMOOTH_ROTATION)
  757. {
  758. float delta = (rotation_ - targetRotation_).LengthSquared();
  759. if (delta < M_EPSILON || constant >= 1.0f)
  760. {
  761. rotation_ = targetRotation_;
  762. smoothingMask_ &= ~SMOOTH_ROTATION;
  763. }
  764. else
  765. rotation_ = rotation_.Slerp(targetRotation_, constant);
  766. }
  767. if (!dirty_)
  768. MarkDirty();
  769. }
  770. bool Node::Load(Deserializer& source, bool readChildren)
  771. {
  772. // Remove all children and components first in case this is not a fresh load
  773. RemoveAllChildren();
  774. RemoveAllComponents();
  775. // ID has been read at the parent level
  776. if (!Serializable::Load(source))
  777. return false;
  778. unsigned numComponents = source.ReadVLE();
  779. for (unsigned i = 0; i < numComponents; ++i)
  780. {
  781. VectorBuffer compBuffer(source, source.ReadVLE());
  782. ShortStringHash newType = compBuffer.ReadShortStringHash();
  783. Component* newComponent = CreateComponent(newType, compBuffer.ReadUInt(), id_ < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  784. if (newComponent)
  785. {
  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. Node* newNode = CreateChild(source.ReadUInt(), id_ < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  796. if (!newNode->Load(source))
  797. return false;
  798. }
  799. return true;
  800. }
  801. bool Node::LoadXML(const XMLElement& source, bool readChildren)
  802. {
  803. // Remove all children and components first in case this is not a fresh load
  804. RemoveAllChildren();
  805. RemoveAllComponents();
  806. if (!Serializable::LoadXML(source))
  807. return false;
  808. XMLElement compElem = source.GetChild("component");
  809. while (compElem)
  810. {
  811. String typeName = compElem.GetString("type");
  812. Component* newComponent = CreateComponent(ShortStringHash(compElem.GetString("type")), compElem.GetInt("id"),
  813. id_ < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  814. if (newComponent)
  815. {
  816. if (!newComponent->LoadXML(compElem))
  817. return false;
  818. }
  819. compElem = compElem.GetNext("component");
  820. }
  821. if (!readChildren)
  822. return true;
  823. XMLElement childElem = source.GetChild("node");
  824. while (childElem)
  825. {
  826. Node* newNode = CreateChild(childElem.GetInt("id"), id_ < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  827. if (!newNode->LoadXML(childElem))
  828. return false;
  829. childElem = childElem.GetNext("node");
  830. }
  831. return true;
  832. }
  833. Component* Node::CreateComponent(ShortStringHash type, unsigned id, CreateMode mode)
  834. {
  835. // Check that creation succeeds and that the object in fact is a component
  836. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  837. if (!newComponent)
  838. {
  839. LOGERROR("Could not create unknown component type " + type.ToString());
  840. return 0;
  841. }
  842. components_.Push(newComponent);
  843. // If zero ID specified, or the ID is already taken, let the scene assign
  844. if (scene_)
  845. {
  846. if (!id || scene_->GetComponent(id))
  847. id = scene_->GetFreeComponentID(mode);
  848. newComponent->SetID(id);
  849. scene_->ComponentAdded(newComponent);
  850. }
  851. else
  852. newComponent->SetID(id);
  853. newComponent->SetNode(this);
  854. newComponent->OnMarkedDirty(this);
  855. return newComponent;
  856. }
  857. Node* Node::CreateChild(unsigned id, CreateMode mode)
  858. {
  859. SharedPtr<Node> newNode(new Node(context_));
  860. // If zero ID specified, or the ID is already taken, let the scene assign
  861. if (scene_)
  862. {
  863. if (!id || scene_->GetNode(id))
  864. id = scene_->GetFreeNodeID(mode);
  865. newNode->SetID(id);
  866. }
  867. else
  868. newNode->SetID(id);
  869. AddChild(newNode);
  870. return newNode;
  871. }
  872. void Node::UpdateWorldTransform() const
  873. {
  874. if (parent_)
  875. {
  876. if (parent_->dirty_)
  877. parent_->UpdateWorldTransform();
  878. worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
  879. }
  880. else
  881. worldTransform_ = Matrix3x4(position_, rotation_, scale_);
  882. dirty_ = false;
  883. }
  884. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  885. {
  886. (*i)->parent_ = 0;
  887. (*i)->MarkDirty();
  888. children_.Erase(i);
  889. }
  890. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  891. {
  892. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  893. {
  894. Node* node = *i;
  895. dest.Push(node);
  896. if (!node->children_.Empty())
  897. node->GetChildrenRecursive(dest);
  898. }
  899. }
  900. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  901. {
  902. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  903. {
  904. Node* node = *i;
  905. if (node->HasComponent(type))
  906. dest.Push(node);
  907. if (!node->children_.Empty())
  908. node->GetChildrenRecursive(dest);
  909. }
  910. }