Node.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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. SceneResolver resolver;
  91. bool success = Load(source, resolver);
  92. if (success)
  93. {
  94. resolver.Resolve();
  95. ApplyAttributes();
  96. }
  97. return success;
  98. }
  99. bool Node::Save(Serializer& dest)
  100. {
  101. if (!Serializable::Save(dest))
  102. return false;
  103. dest.WriteVLE(components_.Size());
  104. for (unsigned i = 0; i < components_.Size(); ++i)
  105. {
  106. Component* component = components_[i];
  107. // Create a separate buffer to be able to skip unknown components during deserialization
  108. VectorBuffer compBuffer;
  109. compBuffer.WriteShortStringHash(component->GetType());
  110. compBuffer.WriteUInt(component->GetID());
  111. if (!component->Save(compBuffer))
  112. return false;
  113. dest.WriteVLE(compBuffer.GetSize());
  114. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  115. }
  116. dest.WriteVLE(children_.Size());
  117. for (unsigned i = 0; i < children_.Size(); ++i)
  118. {
  119. Node* node = children_[i];
  120. dest.WriteUInt(node->GetID());
  121. if (!node->Save(dest))
  122. return false;
  123. }
  124. return true;
  125. }
  126. bool Node::LoadXML(const XMLElement& source)
  127. {
  128. SceneResolver resolver;
  129. bool success = LoadXML(source, resolver);
  130. if (success)
  131. {
  132. resolver.Resolve();
  133. ApplyAttributes();
  134. }
  135. return success;
  136. }
  137. bool Node::SaveXML(XMLElement& dest)
  138. {
  139. if (!Serializable::SaveXML(dest))
  140. return false;
  141. for (unsigned i = 0; i < components_.Size(); ++i)
  142. {
  143. Component* component = components_[i];
  144. XMLElement compElem = dest.CreateChild("component");
  145. compElem.SetString("type", component->GetTypeName());
  146. compElem.SetInt("id", component->GetID());
  147. if (!component->SaveXML(compElem))
  148. return false;
  149. }
  150. for (unsigned i = 0; i < children_.Size(); ++i)
  151. {
  152. Node* node = children_[i];
  153. XMLElement childElem = dest.CreateChild("node");
  154. childElem.SetInt("id", node->GetID());
  155. if (!node->SaveXML(childElem))
  156. return false;
  157. }
  158. return true;
  159. }
  160. void Node::ApplyAttributes()
  161. {
  162. for (unsigned i = 0; i < components_.Size(); ++i)
  163. components_[i]->ApplyAttributes();
  164. for (unsigned i = 0; i < children_.Size(); ++i)
  165. children_[i]->ApplyAttributes();
  166. }
  167. void Node::SetName(const String& name)
  168. {
  169. name_ = name;
  170. nameHash_ = StringHash(name);
  171. }
  172. void Node::SetPosition(const Vector3& position)
  173. {
  174. if (!smoothed_)
  175. {
  176. position_ = position;
  177. if (!dirty_)
  178. MarkDirty();
  179. }
  180. else
  181. {
  182. targetPosition_ = position;
  183. smoothingMask_ |= SMOOTH_POSITION;
  184. }
  185. }
  186. void Node::SetRotation(const Quaternion& rotation)
  187. {
  188. if (!smoothed_)
  189. {
  190. rotation_ = rotation;
  191. if (!dirty_)
  192. MarkDirty();
  193. }
  194. else
  195. {
  196. targetRotation_ = rotation;
  197. smoothingMask_ |= SMOOTH_ROTATION;
  198. }
  199. rotateCount_ = 0;
  200. }
  201. void Node::SetDirection(const Vector3& direction)
  202. {
  203. SetRotation(Quaternion(Vector3::FORWARD, direction));
  204. }
  205. void Node::SetScale(float scale)
  206. {
  207. scale_ = Vector3(scale, scale, scale).Abs();
  208. if (!dirty_)
  209. MarkDirty();
  210. }
  211. void Node::SetScale(const Vector3& scale)
  212. {
  213. scale_ = scale.Abs();
  214. if (!dirty_)
  215. MarkDirty();
  216. }
  217. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  218. {
  219. if (!smoothed_)
  220. {
  221. position_ = position;
  222. rotation_ = rotation;
  223. if (!dirty_)
  224. MarkDirty();
  225. }
  226. else
  227. {
  228. targetPosition_ = position;
  229. targetRotation_ = rotation;
  230. smoothingMask_ |= SMOOTH_POSITION | SMOOTH_ROTATION;
  231. }
  232. rotateCount_ = 0;
  233. }
  234. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  235. {
  236. if (!smoothed_)
  237. {
  238. position_ = position;
  239. rotation_ = rotation;
  240. }
  241. else
  242. {
  243. targetPosition_ = position;
  244. targetRotation_ = rotation;
  245. smoothingMask_ |= SMOOTH_POSITION | SMOOTH_ROTATION;
  246. }
  247. rotateCount_ = 0;
  248. scale_ = Vector3(scale, scale, scale);
  249. if (!dirty_)
  250. MarkDirty();
  251. }
  252. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  253. {
  254. if (!smoothed_)
  255. {
  256. position_ = position;
  257. rotation_ = rotation;
  258. }
  259. else
  260. {
  261. targetPosition_ = position;
  262. targetRotation_ = rotation;
  263. smoothingMask_ |= SMOOTH_POSITION | SMOOTH_ROTATION;
  264. }
  265. rotateCount_ = 0;
  266. scale_ = scale;
  267. if (!dirty_)
  268. MarkDirty();
  269. }
  270. void Node::SnapPosition(const Vector3& position)
  271. {
  272. position_ = position;
  273. targetPosition_ = position;
  274. smoothingMask_ &= ~SMOOTH_POSITION;
  275. if (!dirty_)
  276. MarkDirty();
  277. }
  278. void Node::SnapRotation(const Quaternion& rotation)
  279. {
  280. rotation_ = rotation;
  281. targetRotation_ = rotation;
  282. smoothingMask_ &= ~SMOOTH_ROTATION;
  283. rotateCount_ = 0;
  284. if (!dirty_)
  285. MarkDirty();
  286. }
  287. void Node::SetWorldPosition(const Vector3& position)
  288. {
  289. if (!parent_)
  290. SetPosition(position);
  291. else
  292. SetPosition(parent_->GetWorldTransform().Inverse() * position);
  293. }
  294. void Node::SetWorldRotation(const Quaternion& rotation)
  295. {
  296. if (!parent_)
  297. SetRotation(rotation);
  298. else
  299. SetRotation(parent_->GetWorldRotation().Inverse() * rotation);
  300. }
  301. void Node::SetWorldDirection(const Vector3& direction)
  302. {
  303. Vector3 localDirection;
  304. if (!parent_)
  305. localDirection = direction;
  306. else
  307. localDirection = parent_->GetWorldTransform().Inverse() * direction;
  308. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  309. }
  310. void Node::SetWorldScale(float scale)
  311. {
  312. if (!parent_)
  313. SetScale(scale);
  314. else
  315. {
  316. Vector3 parentWorldScale = parent_->GetWorldScale();
  317. SetScale(Vector3(scale / parentWorldScale.x_, scale / parentWorldScale.y_, scale / parentWorldScale.z_));
  318. }
  319. }
  320. void Node::SetWorldScale(const Vector3& scale)
  321. {
  322. if (!parent_)
  323. SetScale(scale);
  324. else
  325. SetScale(scale / parent_->GetWorldScale());
  326. }
  327. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  328. {
  329. SetWorldPosition(position);
  330. SetWorldRotation(rotation);
  331. }
  332. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  333. {
  334. SetWorldPosition(position);
  335. SetWorldRotation(rotation);
  336. SetWorldScale(scale);
  337. }
  338. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  339. {
  340. SetWorldPosition(position);
  341. SetWorldRotation(rotation);
  342. SetWorldScale(scale);
  343. }
  344. void Node::SnapWorldPosition(const Vector3& position)
  345. {
  346. if (!parent_)
  347. SnapPosition(position);
  348. else
  349. SnapPosition(parent_->GetWorldTransform().Inverse() * position);
  350. }
  351. void Node::SnapWorldRotation(const Quaternion& rotation)
  352. {
  353. if (!parent_)
  354. SnapRotation(rotation);
  355. else
  356. SnapRotation(parent_->GetWorldRotation().Inverse() * rotation);
  357. }
  358. void Node::Translate(const Vector3& delta)
  359. {
  360. if (!smoothed_)
  361. {
  362. position_ += delta;
  363. if (!dirty_)
  364. MarkDirty();
  365. }
  366. else
  367. {
  368. targetPosition_ += delta;
  369. smoothingMask_ |= SMOOTH_POSITION;
  370. }
  371. }
  372. void Node::TranslateRelative(const Vector3& delta)
  373. {
  374. if (!smoothed_)
  375. {
  376. position_ += rotation_ * delta;
  377. if (!dirty_)
  378. MarkDirty();
  379. }
  380. else
  381. {
  382. targetPosition_ += targetRotation_ * delta;
  383. smoothingMask_ |= SMOOTH_POSITION;
  384. }
  385. }
  386. void Node::Rotate(const Quaternion& delta, bool fixedAxis)
  387. {
  388. if (!smoothed_)
  389. {
  390. if (!fixedAxis)
  391. rotation_ = rotation_ * delta;
  392. else
  393. rotation_ = delta * rotation_;
  394. }
  395. else
  396. {
  397. if (!fixedAxis)
  398. targetRotation_ = targetRotation_ * delta;
  399. else
  400. targetRotation_ = delta * targetRotation_;
  401. smoothingMask_ |= SMOOTH_ROTATION;
  402. }
  403. ++rotateCount_;
  404. if (rotateCount_ >= NORMALIZE_ROTATION_EVERY)
  405. {
  406. if (!smoothed_)
  407. rotation_.Normalize();
  408. else
  409. targetRotation_.Normalize();
  410. rotateCount_ = 0;
  411. }
  412. if (!dirty_)
  413. MarkDirty();
  414. }
  415. void Node::Yaw(float angle, bool fixedAxis)
  416. {
  417. Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
  418. }
  419. void Node::Pitch(float angle, bool fixedAxis)
  420. {
  421. Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
  422. }
  423. void Node::Roll(float angle, bool fixedAxis)
  424. {
  425. Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
  426. }
  427. void Node::LookAt(const Vector3& target, const Vector3& upAxis, bool worldSpace)
  428. {
  429. Vector3 targetZ;
  430. if (worldSpace)
  431. targetZ = (target - GetWorldPosition()).Normalized();
  432. else
  433. targetZ = (target - position_).Normalized();
  434. Vector3 targetX = upAxis.CrossProduct(targetZ).Normalized();
  435. Vector3 targetY = targetZ.CrossProduct(targetX).Normalized();
  436. if (!worldSpace || !parent_)
  437. SetRotation(Quaternion(targetX, targetY, targetZ));
  438. else
  439. SetRotation(parent_->GetWorldRotation().Inverse() * Quaternion(targetX, targetY, targetZ));
  440. }
  441. void Node::Scale(float scale)
  442. {
  443. scale_ *= scale;
  444. if (!dirty_)
  445. MarkDirty();
  446. }
  447. void Node::Scale(const Vector3& scale)
  448. {
  449. scale_ *= scale;
  450. if (!dirty_)
  451. MarkDirty();
  452. }
  453. void Node::SetOwner(Connection* owner)
  454. {
  455. owner_ = owner;
  456. }
  457. void Node::SetSmoothed(bool enable)
  458. {
  459. smoothed_ = enable;
  460. }
  461. void Node::MarkDirty()
  462. {
  463. dirty_ = true;
  464. // Notify listener components first, then mark child nodes
  465. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  466. {
  467. if (*i)
  468. {
  469. (*i)->OnMarkedDirty(this);
  470. ++i;
  471. }
  472. // If listener has expired, erase from list
  473. else
  474. i = listeners_.Erase(i);
  475. }
  476. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  477. (*i)->MarkDirty();
  478. }
  479. Node* Node::CreateChild(const String& name, CreateMode mode)
  480. {
  481. Node* newNode = CreateChild(0, mode);
  482. newNode->SetName(name);
  483. return newNode;
  484. }
  485. void Node::AddChild(Node* node)
  486. {
  487. // Check for illegal or redundant parent assignment
  488. if (!node || node == this || node->parent_ == this)
  489. return;
  490. // Check for possible cyclic parent assignment
  491. Node* parent = parent_;
  492. while (parent)
  493. {
  494. if (parent == node)
  495. return;
  496. parent = parent->parent_;
  497. }
  498. // Add first, then remove from old parent, to ensure the node does not get deleted
  499. children_.Push(SharedPtr<Node>(node));
  500. if (node->parent_)
  501. node->parent_->RemoveChild(node);
  502. // Add to the scene if not added yet
  503. if (scene_ && !node->GetScene())
  504. scene_->NodeAdded(node);
  505. node->parent_ = this;
  506. node->MarkDirty();
  507. }
  508. void Node::RemoveChild(Node* node)
  509. {
  510. if (!node)
  511. return;
  512. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  513. {
  514. if (*i == node)
  515. {
  516. RemoveChild(i);
  517. return;
  518. }
  519. }
  520. }
  521. void Node::RemoveAllChildren()
  522. {
  523. while (children_.Size())
  524. RemoveChild(children_.End() - 1);
  525. }
  526. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode)
  527. {
  528. return CreateComponent(type, 0, mode);
  529. }
  530. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode)
  531. {
  532. Component* oldComponent = GetComponent(type);
  533. if (oldComponent)
  534. return oldComponent;
  535. else
  536. return CreateComponent(type, 0, mode);
  537. }
  538. void Node::RemoveComponent(Component* component)
  539. {
  540. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  541. {
  542. if (*i == component)
  543. {
  544. WeakPtr<Component> componentWeak(*i);
  545. RemoveListener(*i);
  546. if (scene_)
  547. scene_->ComponentRemoved(*i);
  548. components_.Erase(i);
  549. // If the component is still referenced elsewhere, reset its node pointer now
  550. if (componentWeak)
  551. componentWeak->SetNode(0);
  552. return;
  553. }
  554. }
  555. }
  556. void Node::RemoveAllComponents()
  557. {
  558. while (components_.Size())
  559. {
  560. Vector<SharedPtr<Component> >::Iterator i = components_.End() - 1;
  561. WeakPtr<Component> componentWeak(*i);
  562. RemoveListener(*i);
  563. if (scene_)
  564. scene_->ComponentRemoved(*i);
  565. components_.Erase(i);
  566. // If the component is still referenced elsewhere, reset its node pointer now
  567. if (componentWeak)
  568. componentWeak->SetNode(0);
  569. }
  570. }
  571. void Node::AddListener(Component* component)
  572. {
  573. if (!component)
  574. return;
  575. // Check for not adding twice
  576. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  577. {
  578. if (*i == component)
  579. return;
  580. }
  581. listeners_.Push(WeakPtr<Component>(component));
  582. // If the node is currently dirty, notify immediately
  583. if (dirty_)
  584. component->OnMarkedDirty(this);
  585. }
  586. void Node::RemoveListener(Component* component)
  587. {
  588. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  589. {
  590. if (*i == component)
  591. {
  592. listeners_.Erase(i);
  593. return;
  594. }
  595. }
  596. }
  597. void Node::Remove()
  598. {
  599. if (parent_)
  600. parent_->RemoveChild(this);
  601. }
  602. void Node::SetParent(Node* parent)
  603. {
  604. if (parent)
  605. {
  606. Vector3 worldPosition;
  607. Quaternion worldRotation;
  608. Vector3 worldScale;
  609. GetWorldTransform().Decompose(worldPosition, worldRotation, worldScale);
  610. parent->AddChild(this);
  611. SetWorldTransform(worldPosition, worldRotation, worldScale);
  612. }
  613. }
  614. Matrix3x4 Node::GetWorldTargetTransform() const
  615. {
  616. if (!smoothed_)
  617. return GetWorldTransform();
  618. Matrix3x4 ret(targetPosition_, targetRotation_, scale_);
  619. Node* current = parent_;
  620. while (current)
  621. {
  622. ret = Matrix3x4(current->targetPosition_, current->targetRotation_, current->scale_) * ret;
  623. current = current->parent_;
  624. }
  625. return ret;
  626. }
  627. Vector3 Node::LocalToWorld(const Vector3& position) const
  628. {
  629. return GetWorldTransform() * position;
  630. }
  631. Vector3 Node::LocalToWorld(const Vector4& vector) const
  632. {
  633. return GetWorldTransform() * vector;
  634. }
  635. Vector3 Node::WorldToLocal(const Vector3& position) const
  636. {
  637. return GetWorldTransform().Inverse() * position;
  638. }
  639. Vector3 Node::WorldToLocal(const Vector4& vector) const
  640. {
  641. return GetWorldTransform().Inverse() * vector;
  642. }
  643. unsigned Node::GetNumChildren(bool recursive) const
  644. {
  645. if (!recursive)
  646. return children_.Size();
  647. else
  648. {
  649. unsigned allChildren = children_.Size();
  650. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  651. allChildren += (*i)->GetNumChildren(true);
  652. return allChildren;
  653. }
  654. }
  655. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  656. {
  657. dest.Clear();
  658. if (!recursive)
  659. {
  660. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  661. dest.Push(*i);
  662. }
  663. else
  664. GetChildrenRecursive(dest);
  665. }
  666. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  667. {
  668. dest.Clear();
  669. if (!recursive)
  670. {
  671. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  672. {
  673. if ((*i)->HasComponent(type))
  674. dest.Push(*i);
  675. }
  676. }
  677. else
  678. GetChildrenWithComponentRecursive(dest, type);
  679. }
  680. Node* Node::GetChild(unsigned index) const
  681. {
  682. return index < children_.Size() ? children_[index].Get() : 0;
  683. }
  684. Node* Node::GetChild(const String& name, bool recursive) const
  685. {
  686. return GetChild(StringHash(name), recursive);
  687. }
  688. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  689. {
  690. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  691. {
  692. if ((*i)->GetNameHash() == nameHash)
  693. return *i;
  694. if (recursive)
  695. {
  696. Node* node = (*i)->GetChild(nameHash, true);
  697. if (node)
  698. return node;
  699. }
  700. }
  701. return 0;
  702. }
  703. unsigned Node::GetNumNetworkComponents() const
  704. {
  705. unsigned num = 0;
  706. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  707. {
  708. if ((*i)->GetID() < FIRST_LOCAL_ID)
  709. ++num;
  710. }
  711. return num;
  712. }
  713. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
  714. {
  715. dest.Clear();
  716. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  717. {
  718. if ((*i)->GetType() == type)
  719. dest.Push(*i);
  720. }
  721. }
  722. bool Node::HasComponent(ShortStringHash type) const
  723. {
  724. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  725. {
  726. if ((*i)->GetType() == type)
  727. return true;
  728. }
  729. return false;
  730. }
  731. Component* Node::GetComponent(ShortStringHash type) const
  732. {
  733. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  734. {
  735. if ((*i)->GetType() == type)
  736. return *i;
  737. }
  738. return 0;
  739. }
  740. void Node::GetDependencyNodes(PODVector<Node*>& dest) const
  741. {
  742. // Add the parent node, but if it is local, traverse to the first non-local node
  743. if (parent_ && parent_ != scene_)
  744. {
  745. Node* current = parent_;
  746. while (current->id_ >= FIRST_LOCAL_ID)
  747. current = current->parent_;
  748. dest.Push(current);
  749. }
  750. // Then let the components add their dependencies
  751. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  752. (*i)->GetDependencyNodes(dest);
  753. }
  754. void Node::SetID(unsigned id)
  755. {
  756. id_ = id;
  757. }
  758. void Node::SetScene(Scene* scene)
  759. {
  760. scene_ = scene;
  761. }
  762. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  763. {
  764. MemoryBuffer buf(value);
  765. SetRotation(buf.ReadPackedQuaternion());
  766. }
  767. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  768. {
  769. Scene* scene = GetScene();
  770. if (!scene)
  771. return;
  772. MemoryBuffer buf(value);
  773. // If nothing in the buffer, parent is the root node
  774. if (buf.IsEof())
  775. {
  776. scene->AddChild(this);
  777. return;
  778. }
  779. unsigned baseNodeID = buf.ReadNetID();
  780. Node* baseNode = scene->GetNode(baseNodeID);
  781. if (!baseNode)
  782. {
  783. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  784. return;
  785. }
  786. // If buffer contains just an ID, the parent is replicated and we are done
  787. if (buf.IsEof())
  788. baseNode->AddChild(this);
  789. else
  790. {
  791. // Else the parent is local and we must find it recursively by name hash
  792. StringHash nameHash = buf.ReadStringHash();
  793. Node* parentNode = baseNode->GetChild(nameHash, true);
  794. if (!parentNode)
  795. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  796. else
  797. parentNode->AddChild(this);
  798. }
  799. }
  800. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  801. {
  802. attrBuffer_.Clear();
  803. attrBuffer_.WritePackedQuaternion(rotation_);
  804. return attrBuffer_.GetBuffer();
  805. }
  806. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  807. {
  808. attrBuffer_.Clear();
  809. Scene* scene = GetScene();
  810. if (scene && parent_ && parent_ != scene)
  811. {
  812. // If parent is replicated, can write the ID directly
  813. unsigned parentID = parent_->GetID();
  814. if (parentID < FIRST_LOCAL_ID)
  815. attrBuffer_.WriteNetID(parentID);
  816. else
  817. {
  818. // Parent is local: traverse hierarchy to find a non-local base node
  819. // This iteration always stops due to the scene (root) being non-local
  820. Node* current = parent_;
  821. while (current->GetID() >= FIRST_LOCAL_ID)
  822. current = current->GetParent();
  823. // Then write the base node ID and the parent's name hash
  824. attrBuffer_.WriteVLE(current->GetID());
  825. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  826. }
  827. }
  828. return attrBuffer_.GetBuffer();
  829. }
  830. void Node::UpdateSmoothing(float constant, float squaredSnapThreshold)
  831. {
  832. if (!smoothed_ || !smoothingMask_)
  833. return;
  834. if (smoothingMask_ & SMOOTH_POSITION)
  835. {
  836. // If position snaps, snap everything to the end
  837. float delta = (position_ - targetPosition_).LengthSquared();
  838. if (delta > squaredSnapThreshold)
  839. constant = 1.0f;
  840. if (delta < M_EPSILON || constant >= 1.0f)
  841. {
  842. position_ = targetPosition_;
  843. smoothingMask_ &= ~SMOOTH_POSITION;
  844. }
  845. else
  846. position_ = position_.Lerp(targetPosition_, constant);
  847. }
  848. if (smoothingMask_ & SMOOTH_ROTATION)
  849. {
  850. float delta = (rotation_ - targetRotation_).LengthSquared();
  851. if (delta < M_EPSILON || constant >= 1.0f)
  852. {
  853. rotation_ = targetRotation_;
  854. smoothingMask_ &= ~SMOOTH_ROTATION;
  855. }
  856. else
  857. rotation_ = rotation_.Slerp(targetRotation_, constant);
  858. }
  859. if (!dirty_)
  860. MarkDirty();
  861. }
  862. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren)
  863. {
  864. // Remove all children and components first in case this is not a fresh load
  865. RemoveAllChildren();
  866. RemoveAllComponents();
  867. // ID has been read at the parent level
  868. if (!Serializable::Load(source))
  869. return false;
  870. unsigned numComponents = source.ReadVLE();
  871. for (unsigned i = 0; i < numComponents; ++i)
  872. {
  873. VectorBuffer compBuffer(source, source.ReadVLE());
  874. ShortStringHash compType = compBuffer.ReadShortStringHash();
  875. unsigned compID = compBuffer.ReadUInt();
  876. Component* newComponent = CreateComponent(compType, compID, id_ < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  877. if (newComponent)
  878. {
  879. resolver.AddComponent(compID, newComponent);
  880. if (!newComponent->Load(compBuffer))
  881. return false;
  882. }
  883. }
  884. if (!readChildren)
  885. return true;
  886. unsigned numChildren = source.ReadVLE();
  887. for (unsigned i = 0; i < numChildren; ++i)
  888. {
  889. unsigned nodeID = source.ReadUInt();
  890. Node* newNode = CreateChild(nodeID, id_ < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  891. resolver.AddNode(nodeID, newNode);
  892. if (!newNode->Load(source, resolver))
  893. return false;
  894. }
  895. return true;
  896. }
  897. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren)
  898. {
  899. // Remove all children and components first in case this is not a fresh load
  900. RemoveAllChildren();
  901. RemoveAllComponents();
  902. if (!Serializable::LoadXML(source))
  903. return false;
  904. XMLElement compElem = source.GetChild("component");
  905. while (compElem)
  906. {
  907. String typeName = compElem.GetString("type");
  908. unsigned compID = compElem.GetInt("id");
  909. Component* newComponent = CreateComponent(ShortStringHash(typeName), compID, id_ < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  910. if (newComponent)
  911. {
  912. resolver.AddComponent(compID, newComponent);
  913. if (!newComponent->LoadXML(compElem))
  914. return false;
  915. }
  916. compElem = compElem.GetNext("component");
  917. }
  918. if (!readChildren)
  919. return true;
  920. XMLElement childElem = source.GetChild("node");
  921. while (childElem)
  922. {
  923. unsigned nodeID = childElem.GetInt("id");
  924. Node* newNode = CreateChild(nodeID, id_ < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  925. resolver.AddNode(nodeID, newNode);
  926. if (!newNode->LoadXML(childElem, resolver))
  927. return false;
  928. childElem = childElem.GetNext("node");
  929. }
  930. return true;
  931. }
  932. Component* Node::CreateComponent(ShortStringHash type, unsigned id, CreateMode mode)
  933. {
  934. // Check that creation succeeds and that the object in fact is a component
  935. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  936. if (!newComponent)
  937. {
  938. LOGERROR("Could not create unknown component type " + type.ToString());
  939. return 0;
  940. }
  941. components_.Push(newComponent);
  942. // If zero ID specified, or the ID is already taken, let the scene assign
  943. if (scene_)
  944. {
  945. if (!id || scene_->GetComponent(id))
  946. id = scene_->GetFreeComponentID(mode);
  947. newComponent->SetID(id);
  948. scene_->ComponentAdded(newComponent);
  949. }
  950. else
  951. newComponent->SetID(id);
  952. newComponent->SetNode(this);
  953. newComponent->OnMarkedDirty(this);
  954. return newComponent;
  955. }
  956. Node* Node::CreateChild(unsigned id, CreateMode mode)
  957. {
  958. SharedPtr<Node> newNode(new Node(context_));
  959. // If zero ID specified, or the ID is already taken, let the scene assign
  960. if (scene_)
  961. {
  962. if (!id || scene_->GetNode(id))
  963. id = scene_->GetFreeNodeID(mode);
  964. newNode->SetID(id);
  965. }
  966. else
  967. newNode->SetID(id);
  968. AddChild(newNode);
  969. return newNode;
  970. }
  971. void Node::UpdateWorldTransform() const
  972. {
  973. if (parent_)
  974. {
  975. if (parent_->dirty_)
  976. parent_->UpdateWorldTransform();
  977. worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
  978. }
  979. else
  980. worldTransform_ = Matrix3x4(position_, rotation_, scale_);
  981. dirty_ = false;
  982. }
  983. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  984. {
  985. (*i)->parent_ = 0;
  986. (*i)->MarkDirty();
  987. children_.Erase(i);
  988. }
  989. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  990. {
  991. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  992. {
  993. Node* node = *i;
  994. dest.Push(node);
  995. if (!node->children_.Empty())
  996. node->GetChildrenRecursive(dest);
  997. }
  998. }
  999. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  1000. {
  1001. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1002. {
  1003. Node* node = *i;
  1004. if (node->HasComponent(type))
  1005. dest.Push(node);
  1006. if (!node->children_.Empty())
  1007. node->GetChildrenRecursive(dest);
  1008. }
  1009. }