Node.cpp 47 KB

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