Node.cpp 36 KB

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