Node.cpp 45 KB

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