Node.cpp 47 KB

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