Node.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  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 Urho3D
  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. Node *cur = this;
  461. for (;;)
  462. {
  463. // Precondition:
  464. // a) whenever a node is marked dirty, all its children are marked dirty as well.
  465. // b) whenever a node is cleared from being dirty, all its parents must have been
  466. // cleared as well.
  467. // Therefore if we are recursing here to mark this node dirty, and it already was,
  468. // then all children of this node must also be already dirty, and we don't need to
  469. // reflag them again.
  470. if (cur->dirty_)
  471. return;
  472. cur->dirty_ = true;
  473. // Notify listener components first, then mark child nodes
  474. for (Vector<WeakPtr<Component> >::Iterator i = cur->listeners_.Begin(); i != cur->listeners_.End();)
  475. {
  476. Component *c = *i;
  477. if (c)
  478. {
  479. c->OnMarkedDirty(cur);
  480. ++i;
  481. }
  482. // If listener has expired, erase from list (swap with the last element to avoid O(n^2) behavior)
  483. else
  484. {
  485. *i = cur->listeners_.Back();
  486. cur->listeners_.Pop();
  487. }
  488. }
  489. // Tail call optimization: Don't recurse to mark the first child dirty, but
  490. // instead process it in the context of the current function. If there are more
  491. // than one child, then recurse to the excess children.
  492. Vector<SharedPtr<Node> >::Iterator i = cur->children_.Begin();
  493. if (i != cur->children_.End())
  494. {
  495. Node *next = *i;
  496. for (++i; i != cur->children_.End(); ++i)
  497. (*i)->MarkDirty();
  498. cur = next;
  499. }
  500. else
  501. return;
  502. }
  503. }
  504. Node* Node::CreateChild(const String& name, CreateMode mode, unsigned id)
  505. {
  506. Node* newNode = CreateChild(id, mode);
  507. newNode->SetName(name);
  508. return newNode;
  509. }
  510. void Node::AddChild(Node* node, unsigned index)
  511. {
  512. // Check for illegal or redundant parent assignment
  513. if (!node || node == this || node->parent_ == this)
  514. return;
  515. // Check for possible cyclic parent assignment
  516. Node* parent = parent_;
  517. while (parent)
  518. {
  519. if (parent == node)
  520. return;
  521. parent = parent->parent_;
  522. }
  523. // Keep a shared ptr to the node while transfering
  524. SharedPtr<Node> nodeShared(node);
  525. Node* oldParent = node->parent_;
  526. if (oldParent)
  527. {
  528. // If old parent is in different scene, perform the full removal
  529. if (oldParent->GetScene() != scene_)
  530. oldParent->RemoveChild(node);
  531. else
  532. {
  533. if (scene_)
  534. {
  535. // Otherwise do not remove from the scene during reparenting, just send the necessary change event
  536. using namespace NodeRemoved;
  537. VariantMap& eventData = GetEventDataMap();
  538. eventData[P_SCENE] = scene_;
  539. eventData[P_PARENT] = oldParent;
  540. eventData[P_NODE] = node;
  541. scene_->SendEvent(E_NODEREMOVED, eventData);
  542. }
  543. oldParent->children_.Remove(nodeShared);
  544. }
  545. }
  546. // Add to the child vector, then add to the scene if not added yet
  547. children_.Insert(index, nodeShared);
  548. if (scene_ && node->GetScene() != scene_)
  549. scene_->NodeAdded(node);
  550. node->parent_ = this;
  551. node->MarkDirty();
  552. node->MarkNetworkUpdate();
  553. // Send change event
  554. if (scene_)
  555. {
  556. using namespace NodeAdded;
  557. VariantMap& eventData = GetEventDataMap();
  558. eventData[P_SCENE] = scene_;
  559. eventData[P_PARENT] = this;
  560. eventData[P_NODE] = node;
  561. scene_->SendEvent(E_NODEADDED, eventData);
  562. }
  563. }
  564. void Node::RemoveChild(Node* node)
  565. {
  566. if (!node)
  567. return;
  568. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  569. {
  570. if (*i == node)
  571. {
  572. RemoveChild(i);
  573. return;
  574. }
  575. }
  576. }
  577. void Node::RemoveAllChildren()
  578. {
  579. RemoveChildren(true, true, true);
  580. }
  581. void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
  582. {
  583. unsigned numRemoved = 0;
  584. for (unsigned i = children_.Size() - 1; i < children_.Size(); --i)
  585. {
  586. bool remove = false;
  587. Node* childNode = children_[i];
  588. if (recursive)
  589. childNode->RemoveChildren(removeReplicated, removeLocal, true);
  590. if (childNode->GetID() < FIRST_LOCAL_ID && removeReplicated)
  591. remove = true;
  592. else if (childNode->GetID() >= FIRST_LOCAL_ID && removeLocal)
  593. remove = true;
  594. if (remove)
  595. {
  596. RemoveChild(children_.Begin() + i);
  597. ++numRemoved;
  598. }
  599. }
  600. // Mark node dirty in all replication states
  601. if (numRemoved)
  602. MarkReplicationDirty();
  603. }
  604. Component* Node::CreateComponent(StringHash type, CreateMode mode, unsigned id)
  605. {
  606. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  607. // as replicated components are synced over
  608. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  609. mode = LOCAL;
  610. // Check that creation succeeds and that the object in fact is a component
  611. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  612. if (!newComponent)
  613. {
  614. LOGERROR("Could not create unknown component type " + type.ToString());
  615. return 0;
  616. }
  617. AddComponent(newComponent, id, mode);
  618. return newComponent;
  619. }
  620. Component* Node::GetOrCreateComponent(StringHash type, CreateMode mode, unsigned id)
  621. {
  622. Component* oldComponent = GetComponent(type);
  623. if (oldComponent)
  624. return oldComponent;
  625. else
  626. return CreateComponent(type, mode, id);
  627. }
  628. Component* Node::CloneComponent(Component* component, unsigned id)
  629. {
  630. if (!component)
  631. {
  632. LOGERROR("Null source component given for CloneComponent");
  633. return 0;
  634. }
  635. return CloneComponent(component, component->GetID() < FIRST_LOCAL_ID ? REPLICATED : LOCAL, id);
  636. }
  637. Component* Node::CloneComponent(Component* component, CreateMode mode, unsigned id)
  638. {
  639. if (!component)
  640. {
  641. LOGERROR("Null source component given for CloneComponent");
  642. return 0;
  643. }
  644. Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0);
  645. if (!cloneComponent)
  646. {
  647. LOGERROR("Could not clone component " + component->GetTypeName());
  648. return 0;
  649. }
  650. const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
  651. const Vector<AttributeInfo>* cloneAttributes = cloneComponent->GetAttributes();
  652. if (compAttributes)
  653. {
  654. for (unsigned i = 0; i < compAttributes->Size() && i < cloneAttributes->Size(); ++i)
  655. {
  656. const AttributeInfo& attr = compAttributes->At(i);
  657. const AttributeInfo& cloneAttr = cloneAttributes->At(i);
  658. if (attr.mode_ & AM_FILE)
  659. {
  660. Variant value;
  661. component->OnGetAttribute(attr, value);
  662. // Note: when eg. a ScriptInstance component is cloned, its script object attributes are unique and therefore we
  663. // can not simply refer to the source component's AttributeInfo
  664. cloneComponent->OnSetAttribute(cloneAttr, value);
  665. }
  666. }
  667. cloneComponent->ApplyAttributes();
  668. }
  669. return cloneComponent;
  670. }
  671. void Node::RemoveComponent(Component* component)
  672. {
  673. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  674. {
  675. if (*i == component)
  676. {
  677. RemoveComponent(i);
  678. // Mark node dirty in all replication states
  679. MarkReplicationDirty();
  680. return;
  681. }
  682. }
  683. }
  684. void Node::RemoveComponent(StringHash type)
  685. {
  686. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  687. {
  688. if ((*i)->GetType() == type)
  689. {
  690. RemoveComponent(i);
  691. // Mark node dirty in all replication states
  692. MarkReplicationDirty();
  693. return;
  694. }
  695. }
  696. }
  697. void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
  698. {
  699. unsigned numRemoved = 0;
  700. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  701. {
  702. bool remove = false;
  703. Component* component = components_[i];
  704. if (component->GetID() < FIRST_LOCAL_ID && removeReplicated)
  705. remove = true;
  706. else if (component->GetID() >= FIRST_LOCAL_ID && removeLocal)
  707. remove = true;
  708. if (remove)
  709. {
  710. RemoveComponent(components_.Begin() + i);
  711. ++numRemoved;
  712. }
  713. }
  714. // Mark node dirty in all replication states
  715. if (numRemoved)
  716. MarkReplicationDirty();
  717. }
  718. void Node::RemoveComponents(StringHash type)
  719. {
  720. unsigned numRemoved = 0;
  721. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  722. {
  723. if (components_[i]->GetType() == type)
  724. {
  725. RemoveComponent(components_.Begin() + i);
  726. ++numRemoved;
  727. }
  728. }
  729. // Mark node dirty in all replication states
  730. if (numRemoved)
  731. MarkReplicationDirty();
  732. }
  733. void Node::RemoveAllComponents()
  734. {
  735. RemoveComponents(true, true);
  736. }
  737. Node* Node::Clone(CreateMode mode)
  738. {
  739. // The scene itself can not be cloned
  740. if (this == scene_ || !parent_)
  741. {
  742. LOGERROR("Can not clone node without a parent");
  743. return 0;
  744. }
  745. PROFILE(CloneNode);
  746. SceneResolver resolver;
  747. Node* clone = CloneRecursive(parent_, resolver, mode);
  748. resolver.Resolve();
  749. clone->ApplyAttributes();
  750. return clone;
  751. }
  752. void Node::Remove()
  753. {
  754. if (parent_)
  755. parent_->RemoveChild(this);
  756. }
  757. void Node::SetParent(Node* parent)
  758. {
  759. if (parent)
  760. {
  761. Matrix3x4 oldWorldTransform = GetWorldTransform();
  762. parent->AddChild(this);
  763. if (parent != scene_)
  764. {
  765. Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
  766. SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
  767. }
  768. else
  769. {
  770. // The root node is assumed to have identity transform, so can disregard it
  771. SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
  772. }
  773. }
  774. }
  775. void Node::SetVar(StringHash key, const Variant& value)
  776. {
  777. vars_[key] = value;
  778. MarkNetworkUpdate();
  779. }
  780. void Node::AddListener(Component* component)
  781. {
  782. if (!component)
  783. return;
  784. // Check for not adding twice
  785. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  786. {
  787. if (*i == component)
  788. return;
  789. }
  790. listeners_.Push(WeakPtr<Component>(component));
  791. // If the node is currently dirty, notify immediately
  792. if (dirty_)
  793. component->OnMarkedDirty(this);
  794. }
  795. void Node::RemoveListener(Component* component)
  796. {
  797. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  798. {
  799. if (*i == component)
  800. {
  801. listeners_.Erase(i);
  802. return;
  803. }
  804. }
  805. }
  806. Vector3 Node::LocalToWorld(const Vector3& position) const
  807. {
  808. return GetWorldTransform() * position;
  809. }
  810. Vector3 Node::LocalToWorld(const Vector4& vector) const
  811. {
  812. return GetWorldTransform() * vector;
  813. }
  814. Vector2 Node::LocalToWorld2D(const Vector2& vector) const
  815. {
  816. Vector3 result = LocalToWorld(Vector3(vector));
  817. return Vector2(result.x_, result.y_);
  818. }
  819. Vector3 Node::WorldToLocal(const Vector3& position) const
  820. {
  821. return GetWorldTransform().Inverse() * position;
  822. }
  823. Vector3 Node::WorldToLocal(const Vector4& vector) const
  824. {
  825. return GetWorldTransform().Inverse() * vector;
  826. }
  827. Vector2 Node::WorldToLocal2D(const Vector2& vector) const
  828. {
  829. Vector3 result = WorldToLocal(Vector3(vector));
  830. return Vector2(result.x_, result.y_);
  831. }
  832. unsigned Node::GetNumChildren(bool recursive) const
  833. {
  834. if (!recursive)
  835. return children_.Size();
  836. else
  837. {
  838. unsigned allChildren = children_.Size();
  839. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  840. allChildren += (*i)->GetNumChildren(true);
  841. return allChildren;
  842. }
  843. }
  844. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  845. {
  846. dest.Clear();
  847. if (!recursive)
  848. {
  849. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  850. dest.Push(*i);
  851. }
  852. else
  853. GetChildrenRecursive(dest);
  854. }
  855. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, StringHash type, bool recursive) const
  856. {
  857. dest.Clear();
  858. if (!recursive)
  859. {
  860. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  861. {
  862. if ((*i)->HasComponent(type))
  863. dest.Push(*i);
  864. }
  865. }
  866. else
  867. GetChildrenWithComponentRecursive(dest, type);
  868. }
  869. Node* Node::GetChild(unsigned index) const
  870. {
  871. return index < children_.Size() ? children_[index].Get() : 0;
  872. }
  873. Node* Node::GetChild(const String& name, bool recursive) const
  874. {
  875. return GetChild(StringHash(name), recursive);
  876. }
  877. Node* Node::GetChild(const char* name, bool recursive) const
  878. {
  879. return GetChild(StringHash(name), recursive);
  880. }
  881. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  882. {
  883. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  884. {
  885. if ((*i)->GetNameHash() == nameHash)
  886. return *i;
  887. if (recursive)
  888. {
  889. Node* node = (*i)->GetChild(nameHash, true);
  890. if (node)
  891. return node;
  892. }
  893. }
  894. return 0;
  895. }
  896. unsigned Node::GetNumNetworkComponents() const
  897. {
  898. unsigned num = 0;
  899. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  900. {
  901. if ((*i)->GetID() < FIRST_LOCAL_ID)
  902. ++num;
  903. }
  904. return num;
  905. }
  906. void Node::GetComponents(PODVector<Component*>& dest, StringHash type, bool recursive) const
  907. {
  908. dest.Clear();
  909. if (!recursive)
  910. {
  911. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  912. {
  913. if ((*i)->GetType() == type)
  914. dest.Push(*i);
  915. }
  916. }
  917. else
  918. GetComponentsRecursive(dest, type);
  919. }
  920. bool Node::HasComponent(StringHash type) const
  921. {
  922. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  923. {
  924. if ((*i)->GetType() == type)
  925. return true;
  926. }
  927. return false;
  928. }
  929. const Variant& Node::GetVar(StringHash key) const
  930. {
  931. VariantMap::ConstIterator i = vars_.Find(key);
  932. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  933. }
  934. Component* Node::GetComponent(StringHash type, bool recursive) const
  935. {
  936. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  937. {
  938. if ((*i)->GetType() == type)
  939. return *i;
  940. }
  941. if (recursive)
  942. {
  943. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  944. {
  945. Component* component = (*i)->GetComponent(type, true);
  946. if (component)
  947. return component;
  948. }
  949. }
  950. return 0;
  951. }
  952. Component* Node::GetParentComponent(StringHash type, bool fullTraversal) const
  953. {
  954. Node* current = GetParent();
  955. while (current)
  956. {
  957. Component* soughtComponent = current->GetComponent(type);
  958. if (soughtComponent)
  959. return soughtComponent;
  960. if (fullTraversal)
  961. current = current->GetParent();
  962. else
  963. break;
  964. }
  965. return 0;
  966. }
  967. void Node::SetID(unsigned id)
  968. {
  969. id_ = id;
  970. }
  971. void Node::SetScene(Scene* scene)
  972. {
  973. scene_ = scene;
  974. }
  975. void Node::ResetScene()
  976. {
  977. SetID(0);
  978. SetScene(0);
  979. SetOwner(0);
  980. }
  981. void Node::SetNetPositionAttr(const Vector3& value)
  982. {
  983. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  984. if (transform)
  985. transform->SetTargetPosition(value);
  986. else
  987. SetPosition(value);
  988. }
  989. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  990. {
  991. MemoryBuffer buf(value);
  992. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  993. if (transform)
  994. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  995. else
  996. SetRotation(buf.ReadPackedQuaternion());
  997. }
  998. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  999. {
  1000. Scene* scene = GetScene();
  1001. if (!scene)
  1002. return;
  1003. MemoryBuffer buf(value);
  1004. // If nothing in the buffer, parent is the root node
  1005. if (buf.IsEof())
  1006. {
  1007. scene->AddChild(this);
  1008. return;
  1009. }
  1010. unsigned baseNodeID = buf.ReadNetID();
  1011. Node* baseNode = scene->GetNode(baseNodeID);
  1012. if (!baseNode)
  1013. {
  1014. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  1015. return;
  1016. }
  1017. // If buffer contains just an ID, the parent is replicated and we are done
  1018. if (buf.IsEof())
  1019. baseNode->AddChild(this);
  1020. else
  1021. {
  1022. // Else the parent is local and we must find it recursively by name hash
  1023. StringHash nameHash = buf.ReadStringHash();
  1024. Node* parentNode = baseNode->GetChild(nameHash, true);
  1025. if (!parentNode)
  1026. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  1027. else
  1028. parentNode->AddChild(this);
  1029. }
  1030. }
  1031. const Vector3& Node::GetNetPositionAttr() const
  1032. {
  1033. return position_;
  1034. }
  1035. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  1036. {
  1037. attrBuffer_.Clear();
  1038. attrBuffer_.WritePackedQuaternion(rotation_);
  1039. return attrBuffer_.GetBuffer();
  1040. }
  1041. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  1042. {
  1043. attrBuffer_.Clear();
  1044. Scene* scene = GetScene();
  1045. if (scene && parent_ && parent_ != scene)
  1046. {
  1047. // If parent is replicated, can write the ID directly
  1048. unsigned parentID = parent_->GetID();
  1049. if (parentID < FIRST_LOCAL_ID)
  1050. attrBuffer_.WriteNetID(parentID);
  1051. else
  1052. {
  1053. // Parent is local: traverse hierarchy to find a non-local base node
  1054. // This iteration always stops due to the scene (root) being non-local
  1055. Node* current = parent_;
  1056. while (current->GetID() >= FIRST_LOCAL_ID)
  1057. current = current->GetParent();
  1058. // Then write the base node ID and the parent's name hash
  1059. attrBuffer_.WriteNetID(current->GetID());
  1060. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  1061. }
  1062. }
  1063. return attrBuffer_.GetBuffer();
  1064. }
  1065. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1066. {
  1067. // Remove all children and components first in case this is not a fresh load
  1068. RemoveAllChildren();
  1069. RemoveAllComponents();
  1070. // ID has been read at the parent level
  1071. if (!Animatable::Load(source))
  1072. return false;
  1073. unsigned numComponents = source.ReadVLE();
  1074. for (unsigned i = 0; i < numComponents; ++i)
  1075. {
  1076. VectorBuffer compBuffer(source, source.ReadVLE());
  1077. StringHash compType = compBuffer.ReadStringHash();
  1078. unsigned compID = compBuffer.ReadUInt();
  1079. Component* newComponent = SafeCreateComponent(String::EMPTY, compType,
  1080. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1081. if (newComponent)
  1082. {
  1083. resolver.AddComponent(compID, newComponent);
  1084. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  1085. newComponent->Load(compBuffer);
  1086. }
  1087. }
  1088. if (!readChildren)
  1089. return true;
  1090. unsigned numChildren = source.ReadVLE();
  1091. for (unsigned i = 0; i < numChildren; ++i)
  1092. {
  1093. unsigned nodeID = source.ReadUInt();
  1094. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1095. LOCAL);
  1096. resolver.AddNode(nodeID, newNode);
  1097. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  1098. return false;
  1099. }
  1100. return true;
  1101. }
  1102. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1103. {
  1104. // Remove all children and components first in case this is not a fresh load
  1105. RemoveAllChildren();
  1106. RemoveAllComponents();
  1107. if (!Animatable::LoadXML(source))
  1108. return false;
  1109. XMLElement compElem = source.GetChild("component");
  1110. while (compElem)
  1111. {
  1112. String typeName = compElem.GetAttribute("type");
  1113. unsigned compID = compElem.GetUInt("id");
  1114. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1115. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1116. if (newComponent)
  1117. {
  1118. resolver.AddComponent(compID, newComponent);
  1119. if (!newComponent->LoadXML(compElem))
  1120. return false;
  1121. }
  1122. compElem = compElem.GetNext("component");
  1123. }
  1124. if (!readChildren)
  1125. return true;
  1126. XMLElement childElem = source.GetChild("node");
  1127. while (childElem)
  1128. {
  1129. unsigned nodeID = childElem.GetUInt("id");
  1130. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1131. LOCAL);
  1132. resolver.AddNode(nodeID, newNode);
  1133. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  1134. return false;
  1135. childElem = childElem.GetNext("node");
  1136. }
  1137. return true;
  1138. }
  1139. void Node::PrepareNetworkUpdate()
  1140. {
  1141. // Update dependency nodes list first
  1142. dependencyNodes_.Clear();
  1143. // Add the parent node, but if it is local, traverse to the first non-local node
  1144. if (parent_ && parent_ != scene_)
  1145. {
  1146. Node* current = parent_;
  1147. while (current->id_ >= FIRST_LOCAL_ID)
  1148. current = current->parent_;
  1149. if (current && current != scene_)
  1150. dependencyNodes_.Push(current);
  1151. }
  1152. // Let the components add their dependencies
  1153. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1154. {
  1155. Component* component = *i;
  1156. if (component->GetID() < FIRST_LOCAL_ID)
  1157. component->GetDependencyNodes(dependencyNodes_);
  1158. }
  1159. // Then check for node attribute changes
  1160. if (!networkState_)
  1161. AllocateNetworkState();
  1162. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  1163. unsigned numAttributes = attributes->Size();
  1164. if (networkState_->currentValues_.Size() != numAttributes)
  1165. {
  1166. networkState_->currentValues_.Resize(numAttributes);
  1167. networkState_->previousValues_.Resize(numAttributes);
  1168. // Copy the default attribute values to the previous state as a starting point
  1169. for (unsigned i = 0; i < numAttributes; ++i)
  1170. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  1171. }
  1172. // Check for attribute changes
  1173. for (unsigned i = 0; i < numAttributes; ++i)
  1174. {
  1175. const AttributeInfo& attr = attributes->At(i);
  1176. if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
  1177. continue;
  1178. OnGetAttribute(attr, networkState_->currentValues_[i]);
  1179. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  1180. {
  1181. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  1182. // Mark the attribute dirty in all replication states that are tracking this node
  1183. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1184. j != networkState_->replicationStates_.End(); ++j)
  1185. {
  1186. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1187. nodeState->dirtyAttributes_.Set(i);
  1188. // Add node to the dirty set if not added yet
  1189. if (!nodeState->markedDirty_)
  1190. {
  1191. nodeState->markedDirty_ = true;
  1192. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1193. }
  1194. }
  1195. }
  1196. }
  1197. // Finally check for user var changes
  1198. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  1199. {
  1200. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  1201. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  1202. {
  1203. networkState_->previousVars_[i->first_] = i->second_;
  1204. // Mark the var dirty in all replication states that are tracking this node
  1205. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1206. j != networkState_->replicationStates_.End(); ++j)
  1207. {
  1208. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1209. nodeState->dirtyVars_.Insert(i->first_);
  1210. if (!nodeState->markedDirty_)
  1211. {
  1212. nodeState->markedDirty_ = true;
  1213. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1214. }
  1215. }
  1216. }
  1217. }
  1218. networkUpdate_ = false;
  1219. }
  1220. void Node::CleanupConnection(Connection* connection)
  1221. {
  1222. if (owner_ == connection)
  1223. owner_ = 0;
  1224. if (networkState_)
  1225. {
  1226. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  1227. {
  1228. if (networkState_->replicationStates_[i]->connection_ == connection)
  1229. networkState_->replicationStates_.Erase(i);
  1230. }
  1231. }
  1232. }
  1233. void Node::MarkReplicationDirty()
  1234. {
  1235. if (networkState_)
  1236. {
  1237. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1238. j != networkState_->replicationStates_.End(); ++j)
  1239. {
  1240. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1241. if (!nodeState->markedDirty_)
  1242. {
  1243. nodeState->markedDirty_ = true;
  1244. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1245. }
  1246. }
  1247. }
  1248. }
  1249. Node* Node::CreateChild(unsigned id, CreateMode mode)
  1250. {
  1251. SharedPtr<Node> newNode(new Node(context_));
  1252. // If zero ID specified, or the ID is already taken, let the scene assign
  1253. if (scene_)
  1254. {
  1255. if (!id || scene_->GetNode(id))
  1256. id = scene_->GetFreeNodeID(mode);
  1257. newNode->SetID(id);
  1258. }
  1259. else
  1260. newNode->SetID(id);
  1261. AddChild(newNode);
  1262. return newNode;
  1263. }
  1264. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1265. {
  1266. if (!component)
  1267. return;
  1268. components_.Push(SharedPtr<Component>(component));
  1269. if (component->GetNode())
  1270. LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!");
  1271. component->SetNode(this);
  1272. // If zero ID specified, or the ID is already taken, let the scene assign
  1273. if (scene_)
  1274. {
  1275. if (!id || scene_->GetComponent(id))
  1276. id = scene_->GetFreeComponentID(mode);
  1277. component->SetID(id);
  1278. scene_->ComponentAdded(component);
  1279. }
  1280. else
  1281. component->SetID(id);
  1282. component->OnMarkedDirty(this);
  1283. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1284. component->MarkNetworkUpdate();
  1285. MarkNetworkUpdate();
  1286. MarkReplicationDirty();
  1287. // Send change event
  1288. if (scene_)
  1289. {
  1290. using namespace ComponentAdded;
  1291. VariantMap& eventData = GetEventDataMap();
  1292. eventData[P_SCENE] = scene_;
  1293. eventData[P_NODE] = this;
  1294. eventData[P_COMPONENT] = component;
  1295. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1296. }
  1297. }
  1298. unsigned Node::GetNumPersistentChildren() const
  1299. {
  1300. unsigned ret = 0;
  1301. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1302. {
  1303. if (!(*i)->IsTemporary())
  1304. ++ret;
  1305. }
  1306. return ret;
  1307. }
  1308. unsigned Node::GetNumPersistentComponents() const
  1309. {
  1310. unsigned ret = 0;
  1311. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1312. {
  1313. if (!(*i)->IsTemporary())
  1314. ++ret;
  1315. }
  1316. return ret;
  1317. }
  1318. void Node::SetTransformSilent(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  1319. {
  1320. position_ = position;
  1321. rotation_ = rotation;
  1322. scale_ = scale;
  1323. }
  1324. void Node::OnAttributeAnimationAdded()
  1325. {
  1326. if (attributeAnimationInfos_.Size() == 1)
  1327. SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Node, HandleAttributeAnimationUpdate));
  1328. }
  1329. void Node::OnAttributeAnimationRemoved()
  1330. {
  1331. if (attributeAnimationInfos_.Empty())
  1332. UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
  1333. }
  1334. Animatable* Node::FindAttributeAnimationTarget(const String& name, String& outName)
  1335. {
  1336. Vector<String> names = name.Split('/');
  1337. // Only attribute name
  1338. if (names.Size() == 1)
  1339. {
  1340. outName = name;
  1341. return this;
  1342. }
  1343. else
  1344. {
  1345. // Name must in following format: "#0/#1/@component#0/attribute"
  1346. Node* node = this;
  1347. unsigned i = 0;
  1348. for (; i < names.Size() - 1; ++i)
  1349. {
  1350. if (names[i].Front() != '#')
  1351. break;
  1352. unsigned index = ToUInt(names[i].Substring(1, names[i].Length() - 1));
  1353. node = node->GetChild(index);
  1354. if (!node)
  1355. {
  1356. LOGERROR("Could not find node by name " + name);
  1357. return 0;
  1358. }
  1359. }
  1360. if (i == names.Size() - 1)
  1361. {
  1362. outName = names.Back();
  1363. return node;
  1364. }
  1365. if (i != names.Size() - 2 || names[i].Front() != '@')
  1366. {
  1367. LOGERROR("Invalid name " + name);
  1368. return 0;
  1369. }
  1370. String componentName = names[i].Substring(1, names[i].Length() - 1);
  1371. Vector<String> componentNames = componentName.Split('#');
  1372. if (componentNames.Size() == 1)
  1373. {
  1374. Component* component = node->GetComponent(StringHash(componentNames.Front()));
  1375. if (!component)
  1376. {
  1377. LOGERROR("Could not find component by name " + name);
  1378. return 0;
  1379. }
  1380. outName = names.Back();
  1381. return component;
  1382. }
  1383. else
  1384. {
  1385. unsigned index = ToUInt(componentNames[1]);
  1386. PODVector<Component*> components;
  1387. node->GetComponents(components, StringHash(componentNames.Front()));
  1388. if (index >= components.Size())
  1389. {
  1390. LOGERROR("Could not find component by name " + name);
  1391. return 0;
  1392. }
  1393. outName = names.Back();
  1394. return components[index];
  1395. }
  1396. }
  1397. }
  1398. void Node::SetEnabled(bool enable, bool recursive, bool storeSelf)
  1399. {
  1400. // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
  1401. if (GetType() == Scene::GetTypeStatic())
  1402. {
  1403. LOGERROR("Can not change enabled state of the Scene");
  1404. return;
  1405. }
  1406. if (storeSelf)
  1407. enabledPrev_ = enable;
  1408. if (enable != enabled_)
  1409. {
  1410. enabled_ = enable;
  1411. MarkNetworkUpdate();
  1412. // Notify listener components of the state change
  1413. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  1414. {
  1415. if (*i)
  1416. {
  1417. (*i)->OnNodeSetEnabled(this);
  1418. ++i;
  1419. }
  1420. // If listener has expired, erase from list
  1421. else
  1422. i = listeners_.Erase(i);
  1423. }
  1424. // Send change event
  1425. if (scene_)
  1426. {
  1427. using namespace NodeEnabledChanged;
  1428. VariantMap& eventData = GetEventDataMap();
  1429. eventData[P_SCENE] = scene_;
  1430. eventData[P_NODE] = this;
  1431. scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
  1432. }
  1433. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  1434. {
  1435. (*i)->OnSetEnabled();
  1436. // Send change event for the component
  1437. if (scene_)
  1438. {
  1439. using namespace ComponentEnabledChanged;
  1440. VariantMap& eventData = GetEventDataMap();
  1441. eventData[P_SCENE] = scene_;
  1442. eventData[P_NODE] = this;
  1443. eventData[P_COMPONENT] = (*i);
  1444. scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
  1445. }
  1446. }
  1447. }
  1448. if (recursive)
  1449. {
  1450. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1451. (*i)->SetEnabled(enable, recursive, storeSelf);
  1452. }
  1453. }
  1454. Component* Node::SafeCreateComponent(const String& typeName, StringHash type, CreateMode mode, unsigned id)
  1455. {
  1456. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  1457. // as replicated components are synced over
  1458. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  1459. mode = LOCAL;
  1460. // First check if factory for type exists
  1461. if (!context_->GetTypeName(type).Empty())
  1462. return CreateComponent(type, mode, id);
  1463. else
  1464. {
  1465. LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder");
  1466. // Else create as UnknownComponent
  1467. SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
  1468. if (typeName.Empty() || typeName.StartsWith("Unknown", false))
  1469. newComponent->SetType(type);
  1470. else
  1471. newComponent->SetTypeName(typeName);
  1472. AddComponent(newComponent, id, mode);
  1473. return newComponent;
  1474. }
  1475. }
  1476. void Node::UpdateWorldTransform() const
  1477. {
  1478. Matrix3x4 transform = GetTransform();
  1479. // Assume the root node (scene) has identity transform
  1480. if (parent_ == scene_ || !parent_)
  1481. {
  1482. worldTransform_ = transform;
  1483. worldRotation_ = rotation_;
  1484. }
  1485. else
  1486. {
  1487. worldTransform_ = parent_->GetWorldTransform() * transform;
  1488. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1489. }
  1490. dirty_ = false;
  1491. }
  1492. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1493. {
  1494. // Send change event. Do not send when already being destroyed
  1495. Node* child = *i;
  1496. if (Refs() > 0 && scene_)
  1497. {
  1498. using namespace NodeRemoved;
  1499. VariantMap& eventData = GetEventDataMap();
  1500. eventData[P_SCENE] = scene_;
  1501. eventData[P_PARENT] = this;
  1502. eventData[P_NODE] = child;
  1503. scene_->SendEvent(E_NODEREMOVED, eventData);
  1504. }
  1505. child->parent_ = 0;
  1506. child->MarkDirty();
  1507. child->MarkNetworkUpdate();
  1508. if (scene_)
  1509. scene_->NodeRemoved(child);
  1510. children_.Erase(i);
  1511. }
  1512. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1513. {
  1514. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1515. {
  1516. Node* node = *i;
  1517. dest.Push(node);
  1518. if (!node->children_.Empty())
  1519. node->GetChildrenRecursive(dest);
  1520. }
  1521. }
  1522. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, StringHash type) const
  1523. {
  1524. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1525. {
  1526. Node* node = *i;
  1527. if (node->HasComponent(type))
  1528. dest.Push(node);
  1529. if (!node->children_.Empty())
  1530. node->GetChildrenWithComponentRecursive(dest, type);
  1531. }
  1532. }
  1533. void Node::GetComponentsRecursive(PODVector<Component*>& dest, StringHash type) const
  1534. {
  1535. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1536. {
  1537. if ((*i)->GetType() == type)
  1538. dest.Push(*i);
  1539. }
  1540. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1541. (*i)->GetComponentsRecursive(dest, type);
  1542. }
  1543. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1544. {
  1545. // Create clone node
  1546. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1547. resolver.AddNode(id_, cloneNode);
  1548. // Copy attributes
  1549. const Vector<AttributeInfo>* attributes = GetAttributes();
  1550. for (unsigned j = 0; j < attributes->Size(); ++j)
  1551. {
  1552. const AttributeInfo& attr = attributes->At(j);
  1553. // Do not copy network-only attributes, as they may have unintended side effects
  1554. if (attr.mode_ & AM_FILE)
  1555. {
  1556. Variant value;
  1557. OnGetAttribute(attr, value);
  1558. cloneNode->OnSetAttribute(attr, value);
  1559. }
  1560. }
  1561. // Clone components
  1562. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1563. {
  1564. Component* component = *i;
  1565. if (component->IsTemporary())
  1566. continue;
  1567. Component* cloneComponent = cloneNode->CloneComponent(component,
  1568. (mode == REPLICATED && component->GetID() < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, 0);
  1569. if (cloneComponent)
  1570. resolver.AddComponent(component->GetID(), cloneComponent);
  1571. }
  1572. // Clone child nodes recursively
  1573. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1574. {
  1575. Node* node = *i;
  1576. if (node->IsTemporary())
  1577. continue;
  1578. node->CloneRecursive(cloneNode, resolver, mode);
  1579. }
  1580. return cloneNode;
  1581. }
  1582. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1583. {
  1584. // Send node change event. Do not send when already being destroyed
  1585. if (Refs() > 0 && scene_)
  1586. {
  1587. using namespace ComponentRemoved;
  1588. VariantMap& eventData = GetEventDataMap();
  1589. eventData[P_SCENE] = scene_;
  1590. eventData[P_NODE] = this;
  1591. eventData[P_COMPONENT] = (*i).Get();
  1592. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1593. }
  1594. RemoveListener(*i);
  1595. if (scene_)
  1596. scene_->ComponentRemoved(*i);
  1597. (*i)->SetNode(0);
  1598. components_.Erase(i);
  1599. }
  1600. void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1601. {
  1602. using namespace AttributeAnimationUpdate;
  1603. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1604. }
  1605. }