Node.cpp 43 KB

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