Node.cpp 43 KB

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