Node.cpp 53 KB

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