Node.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522
  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 "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;
  206. eventData[P_SCENE] = (void*)scene_;
  207. eventData[P_NODE] = (void*)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;
  378. eventData[P_SCENE] = (void*)scene_;
  379. eventData[P_NODE] = (void*)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;
  390. eventData[P_SCENE] = (void*)scene_;
  391. eventData[P_NODE] = (void*)this;
  392. eventData[P_COMPONENT] = (void*)(*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;
  460. eventData[P_SCENE] = (void*)scene_;
  461. eventData[P_PARENT] = (void*)this;
  462. eventData[P_NODE] = (void*)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;
  1103. eventData[P_SCENE] = (void*)scene_;
  1104. eventData[P_NODE] = (void*)this;
  1105. eventData[P_COMPONENT] = (void*)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. // Else create as UnknownComponent
  1137. SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
  1138. if (typeName.Empty() || typeName.StartsWith("Unknown", false))
  1139. newComponent->SetType(type);
  1140. else
  1141. newComponent->SetTypeName(typeName);
  1142. AddComponent(newComponent, id, mode);
  1143. return newComponent;
  1144. }
  1145. }
  1146. void Node::UpdateWorldTransform() const
  1147. {
  1148. Matrix3x4 transform = GetTransform();
  1149. // Assume the root node (scene) has identity transform
  1150. if (parent_ == scene_ || !parent_)
  1151. {
  1152. worldTransform_ = transform;
  1153. worldRotation_ = rotation_;
  1154. }
  1155. else
  1156. {
  1157. worldTransform_ = parent_->GetWorldTransform() * transform;
  1158. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1159. }
  1160. dirty_ = false;
  1161. }
  1162. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1163. {
  1164. // Send change event. Do not send when already being destroyed
  1165. if (Refs() > 0 && scene_)
  1166. {
  1167. using namespace NodeRemoved;
  1168. VariantMap eventData;
  1169. eventData[P_SCENE] = (void*)scene_;
  1170. eventData[P_PARENT] = (void*)this;
  1171. eventData[P_NODE] = (void*)(*i).Get();
  1172. scene_->SendEvent(E_NODEREMOVED, eventData);
  1173. }
  1174. (*i)->parent_ = 0;
  1175. (*i)->MarkDirty();
  1176. (*i)->MarkNetworkUpdate();
  1177. children_.Erase(i);
  1178. }
  1179. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1180. {
  1181. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1182. {
  1183. Node* node = *i;
  1184. dest.Push(node);
  1185. if (!node->children_.Empty())
  1186. node->GetChildrenRecursive(dest);
  1187. }
  1188. }
  1189. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  1190. {
  1191. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1192. {
  1193. Node* node = *i;
  1194. if (node->HasComponent(type))
  1195. dest.Push(node);
  1196. if (!node->children_.Empty())
  1197. node->GetChildrenWithComponentRecursive(dest, type);
  1198. }
  1199. }
  1200. void Node::GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const
  1201. {
  1202. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1203. {
  1204. if ((*i)->GetType() == type)
  1205. dest.Push(*i);
  1206. }
  1207. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1208. (*i)->GetComponentsRecursive(dest, type);
  1209. }
  1210. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1211. {
  1212. // Create clone node
  1213. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1214. resolver.AddNode(id_, cloneNode);
  1215. // Copy attributes
  1216. const Vector<AttributeInfo>* attributes = GetAttributes();
  1217. for (unsigned j = 0; j < attributes->Size(); ++j)
  1218. {
  1219. const AttributeInfo& attr = attributes->At(j);
  1220. // Do not copy network-only attributes, as they may have unintended side effects
  1221. if (attr.mode_ & AM_FILE)
  1222. cloneNode->SetAttribute(j, GetAttribute(j));
  1223. }
  1224. // Clone components
  1225. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1226. {
  1227. Component* component = *i;
  1228. Component* cloneComponent = cloneNode->SafeCreateComponent(component->GetTypeName(), component->GetType(),
  1229. (mode == REPLICATED && component->GetID() < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, 0);
  1230. if (!cloneComponent)
  1231. {
  1232. LOGERROR("Could not clone component " + component->GetTypeName());
  1233. continue;
  1234. }
  1235. resolver.AddComponent(component->GetID(), cloneComponent);
  1236. const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
  1237. for (unsigned j = 0; j < compAttributes->Size(); ++j)
  1238. {
  1239. const AttributeInfo& attr = compAttributes->At(j);
  1240. if (attr.mode_ & AM_FILE)
  1241. cloneComponent->SetAttribute(j, component->GetAttribute(j));
  1242. }
  1243. }
  1244. // Clone child nodes recursively
  1245. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1246. {
  1247. Node* node = *i;
  1248. node->CloneRecursive(cloneNode, resolver, mode);
  1249. }
  1250. return cloneNode;
  1251. }
  1252. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1253. {
  1254. WeakPtr<Component> componentWeak(*i);
  1255. // Send node change event. Do not send when already being destroyed
  1256. if (Refs() > 0 && scene_)
  1257. {
  1258. using namespace ComponentRemoved;
  1259. VariantMap eventData;
  1260. eventData[P_SCENE] = (void*)scene_;
  1261. eventData[P_NODE] = (void*)this;
  1262. eventData[P_COMPONENT] = (void*)(*i).Get();
  1263. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1264. }
  1265. RemoveListener(*i);
  1266. if (scene_)
  1267. scene_->ComponentRemoved(*i);
  1268. components_.Erase(i);
  1269. // If the component is still referenced elsewhere, reset its node pointer now
  1270. if (componentWeak)
  1271. componentWeak->SetNode(0);
  1272. }
  1273. }