Node.cpp 45 KB

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