Node.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  1. //
  2. // Copyright (c) 2008-2015 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 "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../IO/Log.h"
  26. #include "../IO/MemoryBuffer.h"
  27. #include "../Resource/XMLFile.h"
  28. #include "../Scene/Component.h"
  29. #include "../Scene/ObjectAnimation.h"
  30. #include "../Scene/ReplicationState.h"
  31. #include "../Scene/Scene.h"
  32. #include "../Scene/SceneEvents.h"
  33. #include "../Scene/SmoothedTransform.h"
  34. #include "../Scene/UnknownComponent.h"
  35. #include "../DebugNew.h"
  36. #ifdef _MSC_VER
  37. #pragma warning(disable:6293)
  38. #endif
  39. namespace Atomic
  40. {
  41. Node::Node(Context* context) :
  42. Animatable(context),
  43. networkUpdate_(false),
  44. worldTransform_(Matrix3x4::IDENTITY),
  45. dirty_(false),
  46. enabled_(true),
  47. enabledPrev_(true),
  48. parent_(0),
  49. scene_(0),
  50. id_(0),
  51. position_(Vector3::ZERO),
  52. rotation_(Quaternion::IDENTITY),
  53. scale_(Vector3::ONE),
  54. worldRotation_(Quaternion::IDENTITY),
  55. owner_(0)
  56. {
  57. }
  58. Node::~Node()
  59. {
  60. RemoveAllChildren();
  61. RemoveAllComponents();
  62. // Remove from the scene
  63. if (scene_)
  64. scene_->NodeRemoved(this);
  65. }
  66. void Node::RegisterObject(Context* context)
  67. {
  68. context->RegisterFactory<Node>();
  69. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  70. ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  71. ACCESSOR_ATTRIBUTE("Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
  72. ACCESSOR_ATTRIBUTE("Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  73. ACCESSOR_ATTRIBUTE("Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  74. ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  75. ACCESSOR_ATTRIBUTE("Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO,
  76. AM_NET | AM_LATESTDATA | AM_NOEDIT);
  77. ACCESSOR_ATTRIBUTE("Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  78. AM_NET | AM_LATESTDATA | AM_NOEDIT);
  79. ACCESSOR_ATTRIBUTE("Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  80. AM_NET | AM_NOEDIT);
  81. }
  82. bool Node::Load(Deserializer& source, bool setInstanceDefault)
  83. {
  84. SceneResolver resolver;
  85. // Read own ID. Will not be applied, only stored for resolving possible references
  86. unsigned nodeID = source.ReadUInt();
  87. resolver.AddNode(nodeID, this);
  88. // Read attributes, components and child nodes
  89. bool success = Load(source, resolver);
  90. if (success)
  91. {
  92. resolver.Resolve();
  93. ApplyAttributes();
  94. }
  95. return success;
  96. }
  97. bool Node::Save(Serializer& dest) const
  98. {
  99. // Write node ID
  100. if (!dest.WriteUInt(id_))
  101. return false;
  102. // Write attributes
  103. if (!Animatable::Save(dest))
  104. return false;
  105. // Write components
  106. dest.WriteVLE(GetNumPersistentComponents());
  107. for (unsigned i = 0; i < components_.Size(); ++i)
  108. {
  109. Component* component = components_[i];
  110. if (component->IsTemporary())
  111. continue;
  112. // Create a separate buffer to be able to skip failing components during deserialization
  113. VectorBuffer compBuffer;
  114. if (!component->Save(compBuffer))
  115. return false;
  116. dest.WriteVLE(compBuffer.GetSize());
  117. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  118. }
  119. // Write child nodes
  120. dest.WriteVLE(GetNumPersistentChildren());
  121. for (unsigned i = 0; i < children_.Size(); ++i)
  122. {
  123. Node* node = children_[i];
  124. if (node->IsTemporary())
  125. continue;
  126. if (!node->Save(dest))
  127. return false;
  128. }
  129. return true;
  130. }
  131. bool Node::LoadXML(const XMLElement& source, bool setInstanceDefault)
  132. {
  133. SceneResolver resolver;
  134. // Read own ID. Will not be applied, only stored for resolving possible references
  135. unsigned nodeID = source.GetUInt("id");
  136. resolver.AddNode(nodeID, this);
  137. // Read attributes, components and child nodes
  138. bool success = LoadXML(source, resolver);
  139. if (success)
  140. {
  141. resolver.Resolve();
  142. ApplyAttributes();
  143. }
  144. return success;
  145. }
  146. bool Node::SaveXML(XMLElement& dest) const
  147. {
  148. // Write node ID
  149. if (!dest.SetUInt("id", id_))
  150. return false;
  151. // Write attributes
  152. if (!Animatable::SaveXML(dest))
  153. return false;
  154. // Write components
  155. for (unsigned i = 0; i < components_.Size(); ++i)
  156. {
  157. Component* component = components_[i];
  158. if (component->IsTemporary())
  159. continue;
  160. XMLElement compElem = dest.CreateChild("component");
  161. if (!component->SaveXML(compElem))
  162. return false;
  163. }
  164. // Write child nodes
  165. for (unsigned i = 0; i < children_.Size(); ++i)
  166. {
  167. Node* node = children_[i];
  168. if (node->IsTemporary())
  169. continue;
  170. XMLElement childElem = dest.CreateChild("node");
  171. if (!node->SaveXML(childElem))
  172. return false;
  173. }
  174. return true;
  175. }
  176. void Node::ApplyAttributes()
  177. {
  178. for (unsigned i = 0; i < components_.Size(); ++i)
  179. components_[i]->ApplyAttributes();
  180. for (unsigned i = 0; i < children_.Size(); ++i)
  181. children_[i]->ApplyAttributes();
  182. }
  183. void Node::MarkNetworkUpdate()
  184. {
  185. if (!networkUpdate_ && scene_ && id_ < FIRST_LOCAL_ID)
  186. {
  187. scene_->MarkNetworkUpdate(this);
  188. networkUpdate_ = true;
  189. }
  190. }
  191. void Node::AddReplicationState(NodeReplicationState* state)
  192. {
  193. if (!networkState_)
  194. AllocateNetworkState();
  195. networkState_->replicationStates_.Push(state);
  196. }
  197. bool Node::SaveXML(Serializer& dest, const String& indentation) const
  198. {
  199. SharedPtr<XMLFile> xml(new XMLFile(context_));
  200. XMLElement rootElem = xml->CreateRoot("node");
  201. if (!SaveXML(rootElem))
  202. return false;
  203. return xml->Save(dest, indentation);
  204. }
  205. void Node::SetName(const String& name)
  206. {
  207. if (name != name_)
  208. {
  209. name_ = name;
  210. nameHash_ = name_;
  211. MarkNetworkUpdate();
  212. // Send change event
  213. if (scene_)
  214. {
  215. using namespace NodeNameChanged;
  216. VariantMap& eventData = GetEventDataMap();
  217. eventData[P_SCENE] = scene_;
  218. eventData[P_NODE] = this;
  219. scene_->SendEvent(E_NODENAMECHANGED, eventData);
  220. }
  221. }
  222. }
  223. void Node::SetPosition(const Vector3& position)
  224. {
  225. position_ = position;
  226. MarkDirty();
  227. MarkNetworkUpdate();
  228. }
  229. void Node::SetRotation(const Quaternion& rotation)
  230. {
  231. rotation_ = rotation;
  232. MarkDirty();
  233. MarkNetworkUpdate();
  234. }
  235. void Node::SetDirection(const Vector3& direction)
  236. {
  237. SetRotation(Quaternion(Vector3::FORWARD, direction));
  238. }
  239. void Node::SetScale(float scale)
  240. {
  241. SetScale(Vector3(scale, scale, scale));
  242. }
  243. void Node::SetScale(const Vector3& scale)
  244. {
  245. scale_ = scale;
  246. // Prevent exact zero scale e.g. from momentary edits as this may cause division by zero
  247. // when decomposing the world transform matrix
  248. if (scale_.x_ == 0.0f)
  249. scale_.x_ = M_EPSILON;
  250. if (scale_.y_ == 0.0f)
  251. scale_.y_ = M_EPSILON;
  252. if (scale_.z_ == 0.0f)
  253. scale_.z_ = M_EPSILON;
  254. MarkDirty();
  255. MarkNetworkUpdate();
  256. }
  257. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  258. {
  259. position_ = position;
  260. rotation_ = rotation;
  261. MarkDirty();
  262. MarkNetworkUpdate();
  263. }
  264. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  265. {
  266. SetTransform(position, rotation, Vector3(scale, scale, scale));
  267. }
  268. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  269. {
  270. position_ = position;
  271. rotation_ = rotation;
  272. scale_ = scale;
  273. MarkDirty();
  274. MarkNetworkUpdate();
  275. }
  276. void Node::SetWorldPosition(const Vector3& position)
  277. {
  278. SetPosition((parent_ == scene_ || !parent_) ? position : parent_->GetWorldTransform().Inverse() * position);
  279. }
  280. void Node::SetWorldRotation(const Quaternion& rotation)
  281. {
  282. SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation);
  283. }
  284. void Node::SetWorldDirection(const Vector3& direction)
  285. {
  286. Vector3 localDirection = (parent_ == scene_ || !parent_) ? direction : parent_->GetWorldRotation().Inverse() * direction;
  287. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  288. }
  289. void Node::SetWorldScale(float scale)
  290. {
  291. SetWorldScale(Vector3(scale, scale, scale));
  292. }
  293. void Node::SetWorldScale(const Vector3& scale)
  294. {
  295. SetScale((parent_ == scene_ || !parent_) ? scale : scale / parent_->GetWorldScale());
  296. }
  297. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  298. {
  299. SetWorldPosition(position);
  300. SetWorldRotation(rotation);
  301. }
  302. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  303. {
  304. SetWorldPosition(position);
  305. SetWorldRotation(rotation);
  306. SetWorldScale(scale);
  307. }
  308. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  309. {
  310. SetWorldPosition(position);
  311. SetWorldRotation(rotation);
  312. SetWorldScale(scale);
  313. }
  314. void Node::Translate(const Vector3& delta, TransformSpace space)
  315. {
  316. switch (space)
  317. {
  318. case TS_LOCAL:
  319. // Note: local space translation disregards local scale for scale-independent movement speed
  320. position_ += rotation_ * delta;
  321. break;
  322. case TS_PARENT:
  323. position_ += delta;
  324. break;
  325. case TS_WORLD:
  326. position_ += (parent_ == scene_ || !parent_) ? delta : parent_->GetWorldTransform().Inverse() * Vector4(delta, 0.0f);
  327. break;
  328. }
  329. MarkDirty();
  330. MarkNetworkUpdate();
  331. }
  332. void Node::Rotate(const Quaternion& delta, TransformSpace space)
  333. {
  334. switch (space)
  335. {
  336. case TS_LOCAL:
  337. rotation_ = (rotation_ * delta).Normalized();
  338. break;
  339. case TS_PARENT:
  340. rotation_ = (delta * rotation_).Normalized();
  341. break;
  342. case TS_WORLD:
  343. if (parent_ == scene_ || !parent_)
  344. rotation_ = (delta * rotation_).Normalized();
  345. else
  346. {
  347. Quaternion worldRotation = GetWorldRotation();
  348. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  349. }
  350. break;
  351. }
  352. MarkDirty();
  353. MarkNetworkUpdate();
  354. }
  355. void Node::RotateAround(const Vector3& point, const Quaternion& delta, TransformSpace space)
  356. {
  357. Vector3 parentSpacePoint;
  358. Quaternion oldRotation = rotation_;
  359. switch (space)
  360. {
  361. case TS_LOCAL:
  362. parentSpacePoint = GetTransform() * point;
  363. rotation_ = (rotation_ * delta).Normalized();
  364. break;
  365. case TS_PARENT:
  366. parentSpacePoint = point;
  367. rotation_ = (delta * rotation_).Normalized();
  368. break;
  369. case TS_WORLD:
  370. if (parent_ == scene_ || !parent_)
  371. {
  372. parentSpacePoint = point;
  373. rotation_ = (delta * rotation_).Normalized();
  374. }
  375. else
  376. {
  377. parentSpacePoint = parent_->GetWorldTransform().Inverse() * point;
  378. Quaternion worldRotation = GetWorldRotation();
  379. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  380. }
  381. break;
  382. }
  383. Vector3 oldRelativePos = oldRotation.Inverse() * (position_ - parentSpacePoint);
  384. position_ = rotation_ * oldRelativePos + parentSpacePoint;
  385. MarkDirty();
  386. MarkNetworkUpdate();
  387. }
  388. void Node::Yaw(float angle, TransformSpace space)
  389. {
  390. Rotate(Quaternion(angle, Vector3::UP), space);
  391. }
  392. void Node::Pitch(float angle, TransformSpace space)
  393. {
  394. Rotate(Quaternion(angle, Vector3::RIGHT), space);
  395. }
  396. void Node::Roll(float angle, TransformSpace space)
  397. {
  398. Rotate(Quaternion(angle, Vector3::FORWARD), space);
  399. }
  400. bool Node::LookAt(const Vector3& target, const Vector3& up, TransformSpace space)
  401. {
  402. Vector3 worldSpaceTarget;
  403. switch (space)
  404. {
  405. case TS_LOCAL:
  406. worldSpaceTarget = GetWorldTransform() * target;
  407. break;
  408. case TS_PARENT:
  409. worldSpaceTarget = (parent_ == scene_ || !parent_) ? target : parent_->GetWorldTransform() * target;
  410. break;
  411. case TS_WORLD:
  412. worldSpaceTarget = target;
  413. break;
  414. }
  415. Vector3 lookDir = worldSpaceTarget - GetWorldPosition();
  416. // Check if target is very close, in that case can not reliably calculate lookat direction
  417. if (lookDir.Equals(Vector3::ZERO))
  418. return false;
  419. Quaternion newRotation;
  420. // Do nothing if setting look rotation failed
  421. if (!newRotation.FromLookRotation(lookDir, up))
  422. return false;
  423. SetWorldRotation(newRotation);
  424. return true;
  425. }
  426. void Node::Scale(float scale)
  427. {
  428. Scale(Vector3(scale, scale, scale));
  429. }
  430. void Node::Scale(const Vector3& scale)
  431. {
  432. scale_ *= scale;
  433. MarkDirty();
  434. MarkNetworkUpdate();
  435. }
  436. void Node::SetEnabled(bool enable)
  437. {
  438. SetEnabled(enable, false, true);
  439. }
  440. void Node::SetDeepEnabled(bool enable)
  441. {
  442. SetEnabled(enable, true, false);
  443. }
  444. void Node::ResetDeepEnabled()
  445. {
  446. SetEnabled(enabledPrev_, false, false);
  447. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  448. (*i)->ResetDeepEnabled();
  449. }
  450. void Node::SetEnabledRecursive(bool enable)
  451. {
  452. SetEnabled(enable, true, true);
  453. }
  454. void Node::SetOwner(Connection* owner)
  455. {
  456. owner_ = owner;
  457. }
  458. void Node::MarkDirty()
  459. {
  460. dirty_ = true;
  461. // Notify listener components first, then mark child nodes
  462. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  463. {
  464. if (*i)
  465. {
  466. (*i)->OnMarkedDirty(this);
  467. ++i;
  468. }
  469. // If listener has expired, erase from list
  470. else
  471. i = listeners_.Erase(i);
  472. }
  473. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  474. (*i)->MarkDirty();
  475. }
  476. Node* Node::CreateChild(const String& name, CreateMode mode, unsigned id)
  477. {
  478. Node* newNode = CreateChild(id, mode);
  479. newNode->SetName(name);
  480. return newNode;
  481. }
  482. void Node::AddChild(Node* node, unsigned index)
  483. {
  484. // Check for illegal or redundant parent assignment
  485. if (!node || node == this || node->parent_ == this)
  486. return;
  487. // Check for possible cyclic parent assignment
  488. Node* parent = parent_;
  489. while (parent)
  490. {
  491. if (parent == node)
  492. return;
  493. parent = parent->parent_;
  494. }
  495. // Keep a shared ptr to the node while transfering
  496. SharedPtr<Node> nodeShared(node);
  497. Node* oldParent = node->parent_;
  498. if (oldParent)
  499. {
  500. // If old parent is in different scene, perform the full removal
  501. if (oldParent->GetScene() != scene_)
  502. oldParent->RemoveChild(node);
  503. else
  504. {
  505. if (scene_)
  506. {
  507. // Otherwise do not remove from the scene during reparenting, just send the necessary change event
  508. using namespace NodeRemoved;
  509. VariantMap& eventData = GetEventDataMap();
  510. eventData[P_SCENE] = scene_;
  511. eventData[P_PARENT] = oldParent;
  512. eventData[P_NODE] = node;
  513. scene_->SendEvent(E_NODEREMOVED, eventData);
  514. }
  515. oldParent->children_.Remove(nodeShared);
  516. }
  517. }
  518. // Add to the child vector, then add to the scene if not added yet
  519. children_.Insert(index, nodeShared);
  520. if (scene_ && node->GetScene() != scene_)
  521. scene_->NodeAdded(node);
  522. node->parent_ = this;
  523. node->MarkDirty();
  524. node->MarkNetworkUpdate();
  525. // Send change event
  526. if (scene_)
  527. {
  528. using namespace NodeAdded;
  529. VariantMap& eventData = GetEventDataMap();
  530. eventData[P_SCENE] = scene_;
  531. eventData[P_PARENT] = this;
  532. eventData[P_NODE] = node;
  533. scene_->SendEvent(E_NODEADDED, eventData);
  534. }
  535. }
  536. void Node::RemoveChild(Node* node)
  537. {
  538. if (!node)
  539. return;
  540. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  541. {
  542. if (*i == node)
  543. {
  544. RemoveChild(i);
  545. return;
  546. }
  547. }
  548. }
  549. void Node::RemoveAllChildren()
  550. {
  551. RemoveChildren(true, true, true);
  552. }
  553. void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
  554. {
  555. unsigned numRemoved = 0;
  556. for (unsigned i = children_.Size() - 1; i < children_.Size(); --i)
  557. {
  558. bool remove = false;
  559. Node* childNode = children_[i];
  560. if (recursive)
  561. childNode->RemoveChildren(removeReplicated, removeLocal, true);
  562. if (childNode->GetID() < FIRST_LOCAL_ID && removeReplicated)
  563. remove = true;
  564. else if (childNode->GetID() >= FIRST_LOCAL_ID && removeLocal)
  565. remove = true;
  566. if (remove)
  567. {
  568. RemoveChild(children_.Begin() + i);
  569. ++numRemoved;
  570. }
  571. }
  572. // Mark node dirty in all replication states
  573. if (numRemoved)
  574. MarkReplicationDirty();
  575. }
  576. Component* Node::CreateComponent(StringHash type, CreateMode mode, unsigned id)
  577. {
  578. return CreateComponentInternal(type, mode, id);
  579. }
  580. Component* Node::CreateComponentInternal(StringHash type, CreateMode mode, unsigned id, const XMLElement& source)
  581. {
  582. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  583. // as replicated components are synced over
  584. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  585. mode = LOCAL;
  586. // Check that creation succeeds and that the object in fact is a component
  587. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type, source));
  588. if (!newComponent)
  589. {
  590. LOGERROR("Could not create unknown component type " + type.ToString());
  591. return 0;
  592. }
  593. AddComponent(newComponent, id, mode);
  594. return newComponent;
  595. }
  596. Component* Node::GetOrCreateComponent(StringHash type, CreateMode mode, unsigned id)
  597. {
  598. Component* oldComponent = GetComponent(type);
  599. if (oldComponent)
  600. return oldComponent;
  601. else
  602. return CreateComponent(type, mode, id);
  603. }
  604. Component* Node::CloneComponent(Component* component, unsigned id)
  605. {
  606. if (!component)
  607. {
  608. LOGERROR("Null source component given for CloneComponent");
  609. return 0;
  610. }
  611. return CloneComponent(component, component->GetID() < FIRST_LOCAL_ID ? REPLICATED : LOCAL, id);
  612. }
  613. Component* Node::CloneComponent(Component* component, CreateMode mode, unsigned id)
  614. {
  615. if (!component)
  616. {
  617. LOGERROR("Null source component given for CloneComponent");
  618. return 0;
  619. }
  620. Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0);
  621. if (!cloneComponent)
  622. {
  623. LOGERROR("Could not clone component " + component->GetTypeName());
  624. return 0;
  625. }
  626. const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
  627. const Vector<AttributeInfo>* cloneAttributes = cloneComponent->GetAttributes();
  628. if (compAttributes)
  629. {
  630. for (unsigned i = 0; i < compAttributes->Size() && i < cloneAttributes->Size(); ++i)
  631. {
  632. const AttributeInfo& attr = compAttributes->At(i);
  633. const AttributeInfo& cloneAttr = cloneAttributes->At(i);
  634. if (attr.mode_ & AM_FILE)
  635. {
  636. Variant value;
  637. component->OnGetAttribute(attr, value);
  638. // Note: when eg. a ScriptInstance component is cloned, its script object attributes are unique and therefore we
  639. // can not simply refer to the source component's AttributeInfo
  640. cloneComponent->OnSetAttribute(cloneAttr, value);
  641. }
  642. }
  643. cloneComponent->ApplyAttributes();
  644. }
  645. return cloneComponent;
  646. }
  647. void Node::RemoveComponent(Component* component)
  648. {
  649. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  650. {
  651. if (*i == component)
  652. {
  653. RemoveComponent(i);
  654. // Mark node dirty in all replication states
  655. MarkReplicationDirty();
  656. return;
  657. }
  658. }
  659. }
  660. void Node::RemoveComponent(StringHash type)
  661. {
  662. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  663. {
  664. if ((*i)->GetType() == type)
  665. {
  666. RemoveComponent(i);
  667. // Mark node dirty in all replication states
  668. MarkReplicationDirty();
  669. return;
  670. }
  671. }
  672. }
  673. void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
  674. {
  675. unsigned numRemoved = 0;
  676. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  677. {
  678. bool remove = false;
  679. Component* component = components_[i];
  680. if (component->GetID() < FIRST_LOCAL_ID && removeReplicated)
  681. remove = true;
  682. else if (component->GetID() >= FIRST_LOCAL_ID && removeLocal)
  683. remove = true;
  684. if (remove)
  685. {
  686. RemoveComponent(components_.Begin() + i);
  687. ++numRemoved;
  688. }
  689. }
  690. // Mark node dirty in all replication states
  691. if (numRemoved)
  692. MarkReplicationDirty();
  693. }
  694. void Node::RemoveComponents(StringHash type)
  695. {
  696. unsigned numRemoved = 0;
  697. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  698. {
  699. if (components_[i]->GetType() == type)
  700. {
  701. RemoveComponent(components_.Begin() + i);
  702. ++numRemoved;
  703. }
  704. }
  705. // Mark node dirty in all replication states
  706. if (numRemoved)
  707. MarkReplicationDirty();
  708. }
  709. void Node::RemoveAllComponents()
  710. {
  711. RemoveComponents(true, true);
  712. }
  713. Node* Node::Clone(CreateMode mode)
  714. {
  715. // The scene itself can not be cloned
  716. if (this == scene_ || !parent_)
  717. {
  718. LOGERROR("Can not clone node without a parent");
  719. return 0;
  720. }
  721. PROFILE(CloneNode);
  722. SceneResolver resolver;
  723. Node* clone = CloneRecursive(parent_, resolver, mode);
  724. resolver.Resolve();
  725. clone->ApplyAttributes();
  726. return clone;
  727. }
  728. void Node::Remove()
  729. {
  730. if (parent_)
  731. parent_->RemoveChild(this);
  732. }
  733. void Node::SetParent(Node* parent)
  734. {
  735. if (parent)
  736. {
  737. Matrix3x4 oldWorldTransform = GetWorldTransform();
  738. parent->AddChild(this);
  739. if (parent != scene_)
  740. {
  741. Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
  742. SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
  743. }
  744. else
  745. {
  746. // The root node is assumed to have identity transform, so can disregard it
  747. SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
  748. }
  749. }
  750. }
  751. void Node::SetVar(StringHash key, const Variant& value)
  752. {
  753. vars_[key] = value;
  754. MarkNetworkUpdate();
  755. }
  756. void Node::AddListener(Component* component)
  757. {
  758. if (!component)
  759. return;
  760. // Check for not adding twice
  761. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  762. {
  763. if (*i == component)
  764. return;
  765. }
  766. listeners_.Push(WeakPtr<Component>(component));
  767. // If the node is currently dirty, notify immediately
  768. if (dirty_)
  769. component->OnMarkedDirty(this);
  770. }
  771. void Node::RemoveListener(Component* component)
  772. {
  773. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  774. {
  775. if (*i == component)
  776. {
  777. listeners_.Erase(i);
  778. return;
  779. }
  780. }
  781. }
  782. Vector3 Node::LocalToWorld(const Vector3& position) const
  783. {
  784. return GetWorldTransform() * position;
  785. }
  786. Vector3 Node::LocalToWorld(const Vector4& vector) const
  787. {
  788. return GetWorldTransform() * vector;
  789. }
  790. Vector2 Node::LocalToWorld2D(const Vector2& vector) const
  791. {
  792. Vector3 result = LocalToWorld(Vector3(vector));
  793. return Vector2(result.x_, result.y_);
  794. }
  795. Vector3 Node::WorldToLocal(const Vector3& position) const
  796. {
  797. return GetWorldTransform().Inverse() * position;
  798. }
  799. Vector3 Node::WorldToLocal(const Vector4& vector) const
  800. {
  801. return GetWorldTransform().Inverse() * vector;
  802. }
  803. Vector2 Node::WorldToLocal2D(const Vector2& vector) const
  804. {
  805. Vector3 result = WorldToLocal(Vector3(vector));
  806. return Vector2(result.x_, result.y_);
  807. }
  808. unsigned Node::GetNumChildren(bool recursive) const
  809. {
  810. if (!recursive)
  811. return children_.Size();
  812. else
  813. {
  814. unsigned allChildren = children_.Size();
  815. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  816. allChildren += (*i)->GetNumChildren(true);
  817. return allChildren;
  818. }
  819. }
  820. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  821. {
  822. dest.Clear();
  823. if (!recursive)
  824. {
  825. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  826. dest.Push(*i);
  827. }
  828. else
  829. GetChildrenRecursive(dest);
  830. }
  831. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, StringHash type, bool recursive) const
  832. {
  833. dest.Clear();
  834. if (!recursive)
  835. {
  836. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  837. {
  838. if ((*i)->HasComponent(type))
  839. dest.Push(*i);
  840. }
  841. }
  842. else
  843. GetChildrenWithComponentRecursive(dest, type);
  844. }
  845. Node* Node::GetChild(unsigned index) const
  846. {
  847. return index < children_.Size() ? children_[index].Get() : 0;
  848. }
  849. Node* Node::GetChild(const String& name, bool recursive) const
  850. {
  851. return GetChild(StringHash(name), recursive);
  852. }
  853. Node* Node::GetChild(const char* name, bool recursive) const
  854. {
  855. return GetChild(StringHash(name), recursive);
  856. }
  857. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  858. {
  859. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  860. {
  861. if ((*i)->GetNameHash() == nameHash)
  862. return *i;
  863. if (recursive)
  864. {
  865. Node* node = (*i)->GetChild(nameHash, true);
  866. if (node)
  867. return node;
  868. }
  869. }
  870. return 0;
  871. }
  872. unsigned Node::GetNumNetworkComponents() const
  873. {
  874. unsigned num = 0;
  875. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  876. {
  877. if ((*i)->GetID() < FIRST_LOCAL_ID)
  878. ++num;
  879. }
  880. return num;
  881. }
  882. void Node::GetComponents(PODVector<Component*>& dest, StringHash type, bool recursive) const
  883. {
  884. dest.Clear();
  885. bool all = type == Component::GetTypeStatic();
  886. if (!recursive)
  887. {
  888. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  889. {
  890. if (all || ((*i)->GetType() == type))
  891. dest.Push(*i);
  892. }
  893. }
  894. else
  895. GetComponentsRecursive(dest, type);
  896. }
  897. bool Node::HasComponent(StringHash type) const
  898. {
  899. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  900. {
  901. if ((*i)->GetType() == type)
  902. return true;
  903. }
  904. return false;
  905. }
  906. const Variant& Node::GetVar(StringHash key) const
  907. {
  908. VariantMap::ConstIterator i = vars_.Find(key);
  909. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  910. }
  911. Component* Node::GetComponent(StringHash type, bool recursive) const
  912. {
  913. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  914. {
  915. if ((*i)->GetType() == type)
  916. return *i;
  917. }
  918. if (recursive)
  919. {
  920. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  921. {
  922. Component* component = (*i)->GetComponent(type, true);
  923. if (component)
  924. return component;
  925. }
  926. }
  927. return 0;
  928. }
  929. void Node::SetID(unsigned id)
  930. {
  931. id_ = id;
  932. }
  933. void Node::SetScene(Scene* scene)
  934. {
  935. scene_ = scene;
  936. }
  937. void Node::ResetScene()
  938. {
  939. SetID(0);
  940. SetScene(0);
  941. SetOwner(0);
  942. }
  943. void Node::SetNetPositionAttr(const Vector3& value)
  944. {
  945. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  946. if (transform)
  947. transform->SetTargetPosition(value);
  948. else
  949. SetPosition(value);
  950. }
  951. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  952. {
  953. MemoryBuffer buf(value);
  954. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  955. if (transform)
  956. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  957. else
  958. SetRotation(buf.ReadPackedQuaternion());
  959. }
  960. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  961. {
  962. Scene* scene = GetScene();
  963. if (!scene)
  964. return;
  965. MemoryBuffer buf(value);
  966. // If nothing in the buffer, parent is the root node
  967. if (buf.IsEof())
  968. {
  969. scene->AddChild(this);
  970. return;
  971. }
  972. unsigned baseNodeID = buf.ReadNetID();
  973. Node* baseNode = scene->GetNode(baseNodeID);
  974. if (!baseNode)
  975. {
  976. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  977. return;
  978. }
  979. // If buffer contains just an ID, the parent is replicated and we are done
  980. if (buf.IsEof())
  981. baseNode->AddChild(this);
  982. else
  983. {
  984. // Else the parent is local and we must find it recursively by name hash
  985. StringHash nameHash = buf.ReadStringHash();
  986. Node* parentNode = baseNode->GetChild(nameHash, true);
  987. if (!parentNode)
  988. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  989. else
  990. parentNode->AddChild(this);
  991. }
  992. }
  993. const Vector3& Node::GetNetPositionAttr() const
  994. {
  995. return position_;
  996. }
  997. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  998. {
  999. attrBuffer_.Clear();
  1000. attrBuffer_.WritePackedQuaternion(rotation_);
  1001. return attrBuffer_.GetBuffer();
  1002. }
  1003. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  1004. {
  1005. attrBuffer_.Clear();
  1006. Scene* scene = GetScene();
  1007. if (scene && parent_ && parent_ != scene)
  1008. {
  1009. // If parent is replicated, can write the ID directly
  1010. unsigned parentID = parent_->GetID();
  1011. if (parentID < FIRST_LOCAL_ID)
  1012. attrBuffer_.WriteNetID(parentID);
  1013. else
  1014. {
  1015. // Parent is local: traverse hierarchy to find a non-local base node
  1016. // This iteration always stops due to the scene (root) being non-local
  1017. Node* current = parent_;
  1018. while (current->GetID() >= FIRST_LOCAL_ID)
  1019. current = current->GetParent();
  1020. // Then write the base node ID and the parent's name hash
  1021. attrBuffer_.WriteNetID(current->GetID());
  1022. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  1023. }
  1024. }
  1025. return attrBuffer_.GetBuffer();
  1026. }
  1027. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1028. {
  1029. // Remove all children and components first in case this is not a fresh load
  1030. RemoveAllChildren();
  1031. RemoveAllComponents();
  1032. // ID has been read at the parent level
  1033. if (!Animatable::Load(source))
  1034. return false;
  1035. unsigned numComponents = source.ReadVLE();
  1036. for (unsigned i = 0; i < numComponents; ++i)
  1037. {
  1038. VectorBuffer compBuffer(source, source.ReadVLE());
  1039. StringHash compType = compBuffer.ReadStringHash();
  1040. unsigned compID = compBuffer.ReadUInt();
  1041. Component* newComponent = SafeCreateComponent(String::EMPTY, compType,
  1042. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1043. if (newComponent)
  1044. {
  1045. resolver.AddComponent(compID, newComponent);
  1046. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  1047. newComponent->Load(compBuffer);
  1048. }
  1049. }
  1050. if (!readChildren)
  1051. return true;
  1052. unsigned numChildren = source.ReadVLE();
  1053. for (unsigned i = 0; i < numChildren; ++i)
  1054. {
  1055. unsigned nodeID = source.ReadUInt();
  1056. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1057. LOCAL);
  1058. resolver.AddNode(nodeID, newNode);
  1059. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  1060. return false;
  1061. }
  1062. return true;
  1063. }
  1064. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1065. {
  1066. // Remove all children and components first in case this is not a fresh load
  1067. RemoveAllChildren();
  1068. RemoveAllComponents();
  1069. if (!Animatable::LoadXML(source))
  1070. return false;
  1071. XMLElement compElem = source.GetChild("component");
  1072. while (compElem)
  1073. {
  1074. String typeName = compElem.GetAttribute("type");
  1075. unsigned compID = compElem.GetInt("id");
  1076. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1077. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID, compElem);
  1078. if (newComponent)
  1079. {
  1080. resolver.AddComponent(compID, newComponent);
  1081. if (!newComponent->LoadXML(compElem))
  1082. return false;
  1083. }
  1084. compElem = compElem.GetNext("component");
  1085. }
  1086. if (!readChildren)
  1087. return true;
  1088. XMLElement childElem = source.GetChild("node");
  1089. while (childElem)
  1090. {
  1091. unsigned nodeID = childElem.GetUInt("id");
  1092. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1093. LOCAL);
  1094. resolver.AddNode(nodeID, newNode);
  1095. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  1096. return false;
  1097. childElem = childElem.GetNext("node");
  1098. }
  1099. return true;
  1100. }
  1101. void Node::PrepareNetworkUpdate()
  1102. {
  1103. // Update dependency nodes list first
  1104. dependencyNodes_.Clear();
  1105. // Add the parent node, but if it is local, traverse to the first non-local node
  1106. if (parent_ && parent_ != scene_)
  1107. {
  1108. Node* current = parent_;
  1109. while (current->id_ >= FIRST_LOCAL_ID)
  1110. current = current->parent_;
  1111. if (current && current != scene_)
  1112. dependencyNodes_.Push(current);
  1113. }
  1114. // Let the components add their dependencies
  1115. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1116. {
  1117. Component* component = *i;
  1118. if (component->GetID() < FIRST_LOCAL_ID)
  1119. component->GetDependencyNodes(dependencyNodes_);
  1120. }
  1121. // Then check for node attribute changes
  1122. if (!networkState_)
  1123. AllocateNetworkState();
  1124. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  1125. unsigned numAttributes = attributes->Size();
  1126. if (networkState_->currentValues_.Size() != numAttributes)
  1127. {
  1128. networkState_->currentValues_.Resize(numAttributes);
  1129. networkState_->previousValues_.Resize(numAttributes);
  1130. // Copy the default attribute values to the previous state as a starting point
  1131. for (unsigned i = 0; i < numAttributes; ++i)
  1132. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  1133. }
  1134. // Check for attribute changes
  1135. for (unsigned i = 0; i < numAttributes; ++i)
  1136. {
  1137. const AttributeInfo& attr = attributes->At(i);
  1138. if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
  1139. continue;
  1140. OnGetAttribute(attr, networkState_->currentValues_[i]);
  1141. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  1142. {
  1143. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  1144. // Mark the attribute dirty in all replication states that are tracking this node
  1145. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1146. j != networkState_->replicationStates_.End(); ++j)
  1147. {
  1148. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1149. nodeState->dirtyAttributes_.Set(i);
  1150. // Add node to the dirty set if not added yet
  1151. if (!nodeState->markedDirty_)
  1152. {
  1153. nodeState->markedDirty_ = true;
  1154. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1155. }
  1156. }
  1157. }
  1158. }
  1159. // Finally check for user var changes
  1160. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  1161. {
  1162. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  1163. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  1164. {
  1165. networkState_->previousVars_[i->first_] = i->second_;
  1166. // Mark the var dirty in all replication states that are tracking this node
  1167. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1168. j != networkState_->replicationStates_.End(); ++j)
  1169. {
  1170. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1171. nodeState->dirtyVars_.Insert(i->first_);
  1172. if (!nodeState->markedDirty_)
  1173. {
  1174. nodeState->markedDirty_ = true;
  1175. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1176. }
  1177. }
  1178. }
  1179. }
  1180. networkUpdate_ = false;
  1181. }
  1182. void Node::CleanupConnection(Connection* connection)
  1183. {
  1184. if (owner_ == connection)
  1185. owner_ = 0;
  1186. if (networkState_)
  1187. {
  1188. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  1189. {
  1190. if (networkState_->replicationStates_[i]->connection_ == connection)
  1191. networkState_->replicationStates_.Erase(i);
  1192. }
  1193. }
  1194. }
  1195. void Node::MarkReplicationDirty()
  1196. {
  1197. if (networkState_)
  1198. {
  1199. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1200. j != networkState_->replicationStates_.End(); ++j)
  1201. {
  1202. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1203. if (!nodeState->markedDirty_)
  1204. {
  1205. nodeState->markedDirty_ = true;
  1206. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1207. }
  1208. }
  1209. }
  1210. }
  1211. Node* Node::CreateChild(unsigned id, CreateMode mode)
  1212. {
  1213. SharedPtr<Node> newNode(new Node(context_));
  1214. // If zero ID specified, or the ID is already taken, let the scene assign
  1215. if (scene_)
  1216. {
  1217. if (!id || scene_->GetNode(id))
  1218. id = scene_->GetFreeNodeID(mode);
  1219. newNode->SetID(id);
  1220. }
  1221. else
  1222. newNode->SetID(id);
  1223. AddChild(newNode);
  1224. return newNode;
  1225. }
  1226. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1227. {
  1228. if (!component)
  1229. return;
  1230. components_.Push(SharedPtr<Component>(component));
  1231. if (component->GetNode())
  1232. LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!");
  1233. component->SetNode(this);
  1234. // If zero ID specified, or the ID is already taken, let the scene assign
  1235. if (scene_)
  1236. {
  1237. if (!id || scene_->GetComponent(id))
  1238. id = scene_->GetFreeComponentID(mode);
  1239. component->SetID(id);
  1240. scene_->ComponentAdded(component);
  1241. }
  1242. else
  1243. component->SetID(id);
  1244. component->OnMarkedDirty(this);
  1245. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1246. component->MarkNetworkUpdate();
  1247. MarkNetworkUpdate();
  1248. MarkReplicationDirty();
  1249. // Send change event
  1250. if (scene_)
  1251. {
  1252. using namespace ComponentAdded;
  1253. VariantMap& eventData = GetEventDataMap();
  1254. eventData[P_SCENE] = scene_;
  1255. eventData[P_NODE] = this;
  1256. eventData[P_COMPONENT] = component;
  1257. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1258. }
  1259. }
  1260. unsigned Node::GetNumPersistentChildren() const
  1261. {
  1262. unsigned ret = 0;
  1263. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1264. {
  1265. if (!(*i)->IsTemporary())
  1266. ++ret;
  1267. }
  1268. return ret;
  1269. }
  1270. unsigned Node::GetNumPersistentComponents() const
  1271. {
  1272. unsigned ret = 0;
  1273. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1274. {
  1275. if (!(*i)->IsTemporary())
  1276. ++ret;
  1277. }
  1278. return ret;
  1279. }
  1280. void Node::SetTransformSilent(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  1281. {
  1282. position_ = position;
  1283. rotation_ = rotation;
  1284. scale_ = scale;
  1285. }
  1286. void Node::OnAttributeAnimationAdded()
  1287. {
  1288. if (attributeAnimationInfos_.Size() == 1)
  1289. SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, HANDLER(Node, HandleAttributeAnimationUpdate));
  1290. }
  1291. void Node::OnAttributeAnimationRemoved()
  1292. {
  1293. if (attributeAnimationInfos_.Empty())
  1294. UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
  1295. }
  1296. void Node::SetObjectAttributeAnimation(const String& name, ValueAnimation* attributeAnimation, WrapMode wrapMode, float speed)
  1297. {
  1298. Vector<String> names = name.Split('/');
  1299. // Only attribute name
  1300. if (names.Size() == 1)
  1301. SetAttributeAnimation(name, attributeAnimation, wrapMode, speed);
  1302. else
  1303. {
  1304. // Name must in following format: "#0/#1/@component#0/attribute"
  1305. Node* node = this;
  1306. unsigned i = 0;
  1307. for (; i < names.Size() - 1; ++i)
  1308. {
  1309. if (names[i].Front() != '#')
  1310. break;
  1311. unsigned index = ToUInt(names[i].Substring(1, names[i].Length() - 1));
  1312. node = node->GetChild(index);
  1313. if (!node)
  1314. {
  1315. LOGERROR("Could not find node by name " + name);
  1316. return;
  1317. }
  1318. }
  1319. if (i == names.Size() - 1)
  1320. {
  1321. node->SetAttributeAnimation(names.Back(), attributeAnimation, wrapMode, speed);
  1322. return;
  1323. }
  1324. if (i != names.Size() - 2 || names[i].Front() != '@')
  1325. {
  1326. LOGERROR("Invalid name " + name);
  1327. return;
  1328. }
  1329. String componentName = names[i].Substring(1, names[i].Length() - 1);
  1330. Vector<String> componentNames = componentName.Split('#');
  1331. if (componentNames.Size() == 1)
  1332. {
  1333. Component* component = node->GetComponent(StringHash(componentNames.Front()));
  1334. if (!component)
  1335. {
  1336. LOGERROR("Could not find component by name " + name);
  1337. return;
  1338. }
  1339. component->SetAttributeAnimation(names.Back(), attributeAnimation, wrapMode, speed);
  1340. }
  1341. else
  1342. {
  1343. unsigned index = ToUInt(componentNames[1]);
  1344. PODVector<Component*> components;
  1345. node->GetComponents(components, StringHash(componentNames.Front()));
  1346. if (index >= components.Size())
  1347. {
  1348. LOGERROR("Could not find component by name " + name);
  1349. return;
  1350. }
  1351. components[index]->SetAttributeAnimation(names.Back(), attributeAnimation, wrapMode, speed);
  1352. }
  1353. }
  1354. }
  1355. void Node::SetEnabled(bool enable, bool recursive, bool storeSelf)
  1356. {
  1357. // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
  1358. if (GetType() == Scene::GetTypeStatic())
  1359. {
  1360. LOGERROR("Can not change enabled state of the Scene");
  1361. return;
  1362. }
  1363. if (storeSelf)
  1364. enabledPrev_ = enable;
  1365. if (enable != enabled_)
  1366. {
  1367. enabled_ = enable;
  1368. MarkNetworkUpdate();
  1369. // Notify listener components of the state change
  1370. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  1371. {
  1372. if (*i)
  1373. {
  1374. (*i)->OnNodeSetEnabled(this);
  1375. ++i;
  1376. }
  1377. // If listener has expired, erase from list
  1378. else
  1379. i = listeners_.Erase(i);
  1380. }
  1381. // Send change event
  1382. if (scene_)
  1383. {
  1384. using namespace NodeEnabledChanged;
  1385. VariantMap& eventData = GetEventDataMap();
  1386. eventData[P_SCENE] = scene_;
  1387. eventData[P_NODE] = this;
  1388. scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
  1389. }
  1390. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  1391. {
  1392. (*i)->OnSetEnabled();
  1393. // Send change event for the component
  1394. if (scene_)
  1395. {
  1396. using namespace ComponentEnabledChanged;
  1397. VariantMap& eventData = GetEventDataMap();
  1398. eventData[P_SCENE] = scene_;
  1399. eventData[P_NODE] = this;
  1400. eventData[P_COMPONENT] = (*i);
  1401. scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
  1402. }
  1403. }
  1404. }
  1405. if (recursive)
  1406. {
  1407. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1408. (*i)->SetEnabled(enable, recursive, storeSelf);
  1409. }
  1410. }
  1411. Component* Node::SafeCreateComponent(const String& typeName, StringHash type, CreateMode mode, unsigned id, const Atomic::XMLElement &source)
  1412. {
  1413. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  1414. // as replicated components are synced over
  1415. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  1416. mode = LOCAL;
  1417. // First check if factory for type exists
  1418. if (!context_->GetTypeName(type).Empty())
  1419. return CreateComponentInternal(type, mode, id, source);
  1420. else
  1421. {
  1422. LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder");
  1423. // Else create as UnknownComponent
  1424. SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
  1425. if (typeName.Empty() || typeName.StartsWith("Unknown", false))
  1426. newComponent->SetType(type);
  1427. else
  1428. newComponent->SetTypeName(typeName);
  1429. AddComponent(newComponent, id, mode);
  1430. return newComponent;
  1431. }
  1432. }
  1433. void Node::UpdateWorldTransform() const
  1434. {
  1435. Matrix3x4 transform = GetTransform();
  1436. // Assume the root node (scene) has identity transform
  1437. if (parent_ == scene_ || !parent_)
  1438. {
  1439. worldTransform_ = transform;
  1440. worldRotation_ = rotation_;
  1441. }
  1442. else
  1443. {
  1444. worldTransform_ = parent_->GetWorldTransform() * transform;
  1445. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1446. }
  1447. dirty_ = false;
  1448. }
  1449. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1450. {
  1451. // Send change event. Do not send when already being destroyed
  1452. Node* child = *i;
  1453. if (Refs() > 0 && scene_)
  1454. {
  1455. using namespace NodeRemoved;
  1456. VariantMap& eventData = GetEventDataMap();
  1457. eventData[P_SCENE] = scene_;
  1458. eventData[P_PARENT] = this;
  1459. eventData[P_NODE] = child;
  1460. scene_->SendEvent(E_NODEREMOVED, eventData);
  1461. }
  1462. child->parent_ = 0;
  1463. child->MarkDirty();
  1464. child->MarkNetworkUpdate();
  1465. if (scene_)
  1466. scene_->NodeRemoved(child);
  1467. children_.Erase(i);
  1468. }
  1469. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1470. {
  1471. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1472. {
  1473. Node* node = *i;
  1474. dest.Push(node);
  1475. if (!node->children_.Empty())
  1476. node->GetChildrenRecursive(dest);
  1477. }
  1478. }
  1479. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, StringHash type) const
  1480. {
  1481. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1482. {
  1483. Node* node = *i;
  1484. if (node->HasComponent(type))
  1485. dest.Push(node);
  1486. if (!node->children_.Empty())
  1487. node->GetChildrenWithComponentRecursive(dest, type);
  1488. }
  1489. }
  1490. void Node::GetComponentsRecursive(PODVector<Component*>& dest, StringHash type) const
  1491. {
  1492. bool all = type == Component::GetTypeStatic();
  1493. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1494. {
  1495. if (all || (*i)->GetType() == type)
  1496. dest.Push(*i);
  1497. }
  1498. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1499. (*i)->GetComponentsRecursive(dest, type);
  1500. }
  1501. void Node::GetChildrenWithName(PODVector<Node*>& dest, const String& name, bool recursive) const
  1502. {
  1503. GetChildrenWithName(dest, StringHash(name), recursive);
  1504. }
  1505. void Node::GetChildrenWithName(PODVector<Node*>& dest, const char* name, bool recursive) const
  1506. {
  1507. GetChildrenWithName(dest, StringHash(name), recursive);
  1508. }
  1509. void Node::GetChildrenWithName(PODVector<Node*>& dest, StringHash nameHash, bool recursive) const
  1510. {
  1511. dest.Clear();
  1512. if (!recursive)
  1513. {
  1514. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1515. {
  1516. if ((*i)->GetNameHash() == nameHash)
  1517. dest.Push(*i);
  1518. }
  1519. }
  1520. else
  1521. GetChildrenWithNameRecursive(dest, nameHash);
  1522. }
  1523. void Node::GetChildrenWithNameRecursive(PODVector<Node*>& dest, StringHash nameHash) const
  1524. {
  1525. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1526. {
  1527. Node* node = *i;
  1528. if (node->GetNameHash() == nameHash)
  1529. dest.Push(node);
  1530. if (!node->children_.Empty())
  1531. node->GetChildrenWithNameRecursive(dest, nameHash);
  1532. }
  1533. }
  1534. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1535. {
  1536. // Create clone node
  1537. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1538. resolver.AddNode(id_, cloneNode);
  1539. // Copy attributes
  1540. const Vector<AttributeInfo>* attributes = GetAttributes();
  1541. for (unsigned j = 0; j < attributes->Size(); ++j)
  1542. {
  1543. const AttributeInfo& attr = attributes->At(j);
  1544. // Do not copy network-only attributes, as they may have unintended side effects
  1545. if (attr.mode_ & AM_FILE)
  1546. {
  1547. Variant value;
  1548. OnGetAttribute(attr, value);
  1549. cloneNode->OnSetAttribute(attr, value);
  1550. }
  1551. }
  1552. // Clone components
  1553. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1554. {
  1555. Component* component = *i;
  1556. if (component->IsTemporary())
  1557. continue;
  1558. Component* cloneComponent = cloneNode->CloneComponent(component,
  1559. (mode == REPLICATED && component->GetID() < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, 0);
  1560. if (cloneComponent)
  1561. resolver.AddComponent(component->GetID(), cloneComponent);
  1562. }
  1563. // Clone child nodes recursively
  1564. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1565. {
  1566. Node* node = *i;
  1567. if (node->IsTemporary())
  1568. continue;
  1569. node->CloneRecursive(cloneNode, resolver, mode);
  1570. }
  1571. return cloneNode;
  1572. }
  1573. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1574. {
  1575. // Send node change event. Do not send when already being destroyed
  1576. if (Refs() > 0 && scene_)
  1577. {
  1578. using namespace ComponentRemoved;
  1579. VariantMap& eventData = GetEventDataMap();
  1580. eventData[P_SCENE] = scene_;
  1581. eventData[P_NODE] = this;
  1582. eventData[P_COMPONENT] = (*i).Get();
  1583. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1584. }
  1585. RemoveListener(*i);
  1586. if (scene_)
  1587. scene_->ComponentRemoved(*i);
  1588. (*i)->SetNode(0);
  1589. components_.Erase(i);
  1590. }
  1591. void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1592. {
  1593. using namespace AttributeAnimationUpdate;
  1594. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1595. }
  1596. }