Node.cpp 53 KB

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