Node.cpp 53 KB

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