Node.cpp 34 KB

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