Node.cpp 50 KB

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