Node.cpp 51 KB

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