Node.cpp 27 KB

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