Node.cpp 41 KB

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