2
0

Node.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270
  1. //
  2. // Copyright (c) 2008-2022 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 "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../IO/Log.h"
  26. #include "../IO/MemoryBuffer.h"
  27. #include "../Resource/XMLFile.h"
  28. #include "../Resource/JSONFile.h"
  29. #include "../Scene/Component.h"
  30. #include "../Scene/ObjectAnimation.h"
  31. #include "../Scene/ReplicationState.h"
  32. #include "../Scene/Scene.h"
  33. #include "../Scene/SceneEvents.h"
  34. #include "../Scene/SmoothedTransform.h"
  35. #include "../Scene/UnknownComponent.h"
  36. #include "../DebugNew.h"
  37. using namespace std;
  38. #ifdef _MSC_VER
  39. #pragma warning(disable:6293)
  40. #endif
  41. namespace Urho3D
  42. {
  43. Node::Node(Context* context) :
  44. Animatable(context),
  45. worldTransform_(Matrix3x4::IDENTITY),
  46. dirty_(false),
  47. enabled_(true),
  48. enabledPrev_(true),
  49. networkUpdate_(false),
  50. parent_(nullptr),
  51. scene_(nullptr),
  52. id_(0),
  53. position_(Vector3::ZERO),
  54. rotation_(Quaternion::IDENTITY),
  55. scale_(Vector3::ONE),
  56. worldRotation_(Quaternion::IDENTITY)
  57. {
  58. impl_ = make_unique<NodeImpl>();
  59. impl_->owner_ = nullptr;
  60. }
  61. Node::~Node()
  62. {
  63. RemoveAllChildren();
  64. RemoveAllComponents();
  65. // Remove from the scene
  66. if (scene_)
  67. scene_->NodeRemoved(this);
  68. }
  69. void Node::RegisterObject(Context* context)
  70. {
  71. context->RegisterFactory<Node>();
  72. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  73. URHO3D_ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  74. URHO3D_ACCESSOR_ATTRIBUTE("Tags", GetTags, SetTags, StringVector, Variant::emptyStringVector, AM_DEFAULT);
  75. URHO3D_ACCESSOR_ATTRIBUTE("Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
  76. URHO3D_ACCESSOR_ATTRIBUTE("Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  77. URHO3D_ACCESSOR_ATTRIBUTE("Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  78. URHO3D_ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  79. URHO3D_ACCESSOR_ATTRIBUTE("Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO,
  80. AM_NET | AM_LATESTDATA | AM_NOEDIT);
  81. URHO3D_ACCESSOR_ATTRIBUTE("Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  82. AM_NET | AM_LATESTDATA | AM_NOEDIT);
  83. URHO3D_ACCESSOR_ATTRIBUTE("Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  84. AM_NET | AM_NOEDIT);
  85. }
  86. bool Node::Load(Deserializer& source)
  87. {
  88. SceneResolver resolver;
  89. // Read own ID. Will not be applied, only stored for resolving possible references
  90. unsigned nodeID = source.ReadUInt();
  91. resolver.AddNode(nodeID, this);
  92. // Read attributes, components and child nodes
  93. bool success = Load(source, resolver);
  94. if (success)
  95. {
  96. resolver.Resolve();
  97. ApplyAttributes();
  98. }
  99. return success;
  100. }
  101. bool Node::Save(Serializer& dest) const
  102. {
  103. // Write node ID
  104. if (!dest.WriteUInt(id_))
  105. return false;
  106. // Write attributes
  107. if (!Animatable::Save(dest))
  108. return false;
  109. // Write components
  110. dest.WriteVLE(GetNumPersistentComponents());
  111. for (unsigned i = 0; i < components_.Size(); ++i)
  112. {
  113. Component* component = components_[i];
  114. if (component->IsTemporary())
  115. continue;
  116. // Create a separate buffer to be able to skip failing components during deserialization
  117. VectorBuffer compBuffer;
  118. if (!component->Save(compBuffer))
  119. return false;
  120. dest.WriteVLE(compBuffer.GetSize());
  121. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  122. }
  123. // Write child nodes
  124. dest.WriteVLE(GetNumPersistentChildren());
  125. for (unsigned i = 0; i < children_.Size(); ++i)
  126. {
  127. Node* node = children_[i];
  128. if (node->IsTemporary())
  129. continue;
  130. if (!node->Save(dest))
  131. return false;
  132. }
  133. return true;
  134. }
  135. bool Node::LoadXML(const XMLElement& source)
  136. {
  137. SceneResolver resolver;
  138. // Read own ID. Will not be applied, only stored for resolving possible references
  139. unsigned nodeID = source.GetUInt("id");
  140. resolver.AddNode(nodeID, this);
  141. // Read attributes, components and child nodes
  142. bool success = LoadXML(source, resolver);
  143. if (success)
  144. {
  145. resolver.Resolve();
  146. ApplyAttributes();
  147. }
  148. return success;
  149. }
  150. bool Node::LoadJSON(const JSONValue& source)
  151. {
  152. SceneResolver resolver;
  153. // Read own ID. Will not be applied, only stored for resolving possible references
  154. unsigned nodeID = source.Get("id").GetUInt();
  155. resolver.AddNode(nodeID, this);
  156. // Read attributes, components and child nodes
  157. bool success = LoadJSON(source, resolver);
  158. if (success)
  159. {
  160. resolver.Resolve();
  161. ApplyAttributes();
  162. }
  163. return success;
  164. }
  165. bool Node::SaveXML(XMLElement& dest) const
  166. {
  167. // Write node ID
  168. if (!dest.SetUInt("id", id_))
  169. return false;
  170. // Write attributes
  171. if (!Animatable::SaveXML(dest))
  172. return false;
  173. // Write components
  174. for (unsigned i = 0; i < components_.Size(); ++i)
  175. {
  176. Component* component = components_[i];
  177. if (component->IsTemporary())
  178. continue;
  179. XMLElement compElem = dest.CreateChild("component");
  180. if (!component->SaveXML(compElem))
  181. return false;
  182. }
  183. // Write child nodes
  184. for (unsigned i = 0; i < children_.Size(); ++i)
  185. {
  186. Node* node = children_[i];
  187. if (node->IsTemporary())
  188. continue;
  189. XMLElement childElem = dest.CreateChild("node");
  190. if (!node->SaveXML(childElem))
  191. return false;
  192. }
  193. return true;
  194. }
  195. bool Node::SaveJSON(JSONValue& dest) const
  196. {
  197. // Write node ID
  198. dest.Set("id", id_);
  199. // Write attributes
  200. if (!Animatable::SaveJSON(dest))
  201. return false;
  202. // Write components
  203. JSONArray componentsArray;
  204. componentsArray.Reserve(components_.Size());
  205. for (unsigned i = 0; i < components_.Size(); ++i)
  206. {
  207. Component* component = components_[i];
  208. if (component->IsTemporary())
  209. continue;
  210. JSONValue compVal;
  211. if (!component->SaveJSON(compVal))
  212. return false;
  213. componentsArray.Push(compVal);
  214. }
  215. dest.Set("components", componentsArray);
  216. // Write child nodes
  217. JSONArray childrenArray;
  218. childrenArray.Reserve(children_.Size());
  219. for (unsigned i = 0; i < children_.Size(); ++i)
  220. {
  221. Node* node = children_[i];
  222. if (node->IsTemporary())
  223. continue;
  224. JSONValue childVal;
  225. if (!node->SaveJSON(childVal))
  226. return false;
  227. childrenArray.Push(childVal);
  228. }
  229. dest.Set("children", childrenArray);
  230. return true;
  231. }
  232. void Node::ApplyAttributes()
  233. {
  234. for (unsigned i = 0; i < components_.Size(); ++i)
  235. components_[i]->ApplyAttributes();
  236. for (unsigned i = 0; i < children_.Size(); ++i)
  237. children_[i]->ApplyAttributes();
  238. }
  239. void Node::MarkNetworkUpdate()
  240. {
  241. if (!networkUpdate_ && scene_ && IsReplicated())
  242. {
  243. scene_->MarkNetworkUpdate(this);
  244. networkUpdate_ = true;
  245. }
  246. }
  247. void Node::AddReplicationState(NodeReplicationState* state)
  248. {
  249. if (!networkState_)
  250. AllocateNetworkState();
  251. networkState_->replicationStates_.Push(state);
  252. }
  253. bool Node::SaveXML(Serializer& dest, const String& indentation) const
  254. {
  255. SharedPtr<XMLFile> xml(new XMLFile(context_));
  256. XMLElement rootElem = xml->CreateRoot("node");
  257. if (!SaveXML(rootElem))
  258. return false;
  259. return xml->Save(dest, indentation);
  260. }
  261. bool Node::SaveJSON(Serializer& dest, const String& indentation) const
  262. {
  263. SharedPtr<JSONFile> json(new JSONFile(context_));
  264. JSONValue& rootElem = json->GetRoot();
  265. if (!SaveJSON(rootElem))
  266. return false;
  267. return json->Save(dest, indentation);
  268. }
  269. void Node::SetName(const String& name)
  270. {
  271. if (name != impl_->name_)
  272. {
  273. impl_->name_ = name;
  274. impl_->nameHash_ = name;
  275. MarkNetworkUpdate();
  276. // Send change event
  277. if (scene_)
  278. {
  279. using namespace NodeNameChanged;
  280. VariantMap& eventData = GetEventDataMap();
  281. eventData[P_SCENE] = scene_;
  282. eventData[P_NODE] = this;
  283. scene_->SendEvent(E_NODENAMECHANGED, eventData);
  284. }
  285. }
  286. }
  287. void Node::SetTags(const StringVector& tags)
  288. {
  289. RemoveAllTags();
  290. AddTags(tags);
  291. // MarkNetworkUpdate() already called in RemoveAllTags() / AddTags()
  292. }
  293. void Node::AddTag(const String& tag)
  294. {
  295. // Check if tag empty or already added
  296. if (tag.Empty() || HasTag(tag))
  297. return;
  298. // Add tag
  299. impl_->tags_.Push(tag);
  300. // Cache
  301. if (scene_)
  302. {
  303. scene_->NodeTagAdded(this, tag);
  304. // Send event
  305. using namespace NodeTagAdded;
  306. VariantMap& eventData = GetEventDataMap();
  307. eventData[P_SCENE] = scene_;
  308. eventData[P_NODE] = this;
  309. eventData[P_TAG] = tag;
  310. scene_->SendEvent(E_NODETAGADDED, eventData);
  311. }
  312. // Sync
  313. MarkNetworkUpdate();
  314. }
  315. void Node::AddTags(const String& tags, char separator)
  316. {
  317. StringVector tagVector = tags.Split(separator);
  318. AddTags(tagVector);
  319. }
  320. void Node::AddTags(const StringVector& tags)
  321. {
  322. // This is OK, as MarkNetworkUpdate() early-outs when called multiple times
  323. for (unsigned i = 0; i < tags.Size(); ++i)
  324. AddTag(tags[i]);
  325. }
  326. bool Node::RemoveTag(const String& tag)
  327. {
  328. bool removed = impl_->tags_.Remove(tag);
  329. // Nothing to do
  330. if (!removed)
  331. return false;
  332. // Scene cache update
  333. if (scene_)
  334. {
  335. scene_->NodeTagRemoved(this, tag);
  336. // Send event
  337. using namespace NodeTagRemoved;
  338. VariantMap& eventData = GetEventDataMap();
  339. eventData[P_SCENE] = scene_;
  340. eventData[P_NODE] = this;
  341. eventData[P_TAG] = tag;
  342. scene_->SendEvent(E_NODETAGREMOVED, eventData);
  343. }
  344. // Sync
  345. MarkNetworkUpdate();
  346. return true;
  347. }
  348. void Node::RemoveAllTags()
  349. {
  350. // Clear old scene cache
  351. if (scene_)
  352. {
  353. for (unsigned i = 0; i < impl_->tags_.Size(); ++i)
  354. {
  355. scene_->NodeTagRemoved(this, impl_->tags_[i]);
  356. // Send event
  357. using namespace NodeTagRemoved;
  358. VariantMap& eventData = GetEventDataMap();
  359. eventData[P_SCENE] = scene_;
  360. eventData[P_NODE] = this;
  361. eventData[P_TAG] = impl_->tags_[i];
  362. scene_->SendEvent(E_NODETAGREMOVED, eventData);
  363. }
  364. }
  365. impl_->tags_.Clear();
  366. // Sync
  367. MarkNetworkUpdate();
  368. }
  369. void Node::SetPosition(const Vector3& position)
  370. {
  371. position_ = position;
  372. MarkDirty();
  373. MarkNetworkUpdate();
  374. }
  375. void Node::SetRotation(const Quaternion& rotation)
  376. {
  377. rotation_ = rotation;
  378. MarkDirty();
  379. MarkNetworkUpdate();
  380. }
  381. void Node::SetDirection(const Vector3& direction)
  382. {
  383. SetRotation(Quaternion(Vector3::FORWARD, direction));
  384. }
  385. void Node::SetScale(float scale)
  386. {
  387. SetScale(Vector3(scale, scale, scale));
  388. }
  389. void Node::SetScale(const Vector3& scale)
  390. {
  391. scale_ = scale;
  392. // Prevent exact zero scale e.g. from momentary edits as this may cause division by zero
  393. // when decomposing the world transform matrix
  394. if (scale_.x_ == 0.0f)
  395. scale_.x_ = M_EPSILON;
  396. if (scale_.y_ == 0.0f)
  397. scale_.y_ = M_EPSILON;
  398. if (scale_.z_ == 0.0f)
  399. scale_.z_ = M_EPSILON;
  400. MarkDirty();
  401. MarkNetworkUpdate();
  402. }
  403. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  404. {
  405. position_ = position;
  406. rotation_ = rotation;
  407. MarkDirty();
  408. MarkNetworkUpdate();
  409. }
  410. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  411. {
  412. SetTransform(position, rotation, Vector3(scale, scale, scale));
  413. }
  414. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  415. {
  416. position_ = position;
  417. rotation_ = rotation;
  418. scale_ = scale;
  419. MarkDirty();
  420. MarkNetworkUpdate();
  421. }
  422. void Node::SetTransform(const Matrix3x4& matrix)
  423. {
  424. SetTransform(matrix.Translation(), matrix.Rotation(), matrix.Scale());
  425. }
  426. void Node::SetWorldPosition(const Vector3& position)
  427. {
  428. SetPosition((parent_ == scene_ || !parent_) ? position : parent_->GetWorldTransform().Inverse() * position);
  429. }
  430. void Node::SetWorldRotation(const Quaternion& rotation)
  431. {
  432. SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation);
  433. }
  434. void Node::SetWorldDirection(const Vector3& direction)
  435. {
  436. Vector3 localDirection = (parent_ == scene_ || !parent_) ? direction : parent_->GetWorldRotation().Inverse() * direction;
  437. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  438. }
  439. void Node::SetWorldScale(float scale)
  440. {
  441. SetWorldScale(Vector3(scale, scale, scale));
  442. }
  443. void Node::SetWorldScale(const Vector3& scale)
  444. {
  445. SetScale((parent_ == scene_ || !parent_) ? scale : scale / parent_->GetWorldScale());
  446. }
  447. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  448. {
  449. SetWorldPosition(position);
  450. SetWorldRotation(rotation);
  451. }
  452. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  453. {
  454. SetWorldPosition(position);
  455. SetWorldRotation(rotation);
  456. SetWorldScale(scale);
  457. }
  458. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  459. {
  460. SetWorldPosition(position);
  461. SetWorldRotation(rotation);
  462. SetWorldScale(scale);
  463. }
  464. void Node::SetWorldTransform(const Matrix3x4& worldTransform)
  465. {
  466. SetWorldTransform(worldTransform.Translation(), worldTransform.Rotation(), worldTransform.Scale());
  467. }
  468. void Node::Translate(const Vector3& delta, TransformSpace space)
  469. {
  470. switch (space)
  471. {
  472. case TS_LOCAL:
  473. // Note: local space translation disregards local scale for scale-independent movement speed
  474. position_ += rotation_ * delta;
  475. break;
  476. case TS_PARENT:
  477. position_ += delta;
  478. break;
  479. case TS_WORLD:
  480. position_ += (parent_ == scene_ || !parent_) ? delta : parent_->GetWorldTransform().Inverse() * Vector4(delta, 0.0f);
  481. break;
  482. }
  483. MarkDirty();
  484. MarkNetworkUpdate();
  485. }
  486. void Node::Rotate(const Quaternion& delta, TransformSpace space)
  487. {
  488. switch (space)
  489. {
  490. case TS_LOCAL:
  491. rotation_ = (rotation_ * delta).Normalized();
  492. break;
  493. case TS_PARENT:
  494. rotation_ = (delta * rotation_).Normalized();
  495. break;
  496. case TS_WORLD:
  497. if (parent_ == scene_ || !parent_)
  498. rotation_ = (delta * rotation_).Normalized();
  499. else
  500. {
  501. Quaternion worldRotation = GetWorldRotation();
  502. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  503. }
  504. break;
  505. }
  506. MarkDirty();
  507. MarkNetworkUpdate();
  508. }
  509. void Node::RotateAround(const Vector3& point, const Quaternion& delta, TransformSpace space)
  510. {
  511. Vector3 parentSpacePoint;
  512. Quaternion oldRotation = rotation_;
  513. switch (space)
  514. {
  515. case TS_LOCAL:
  516. parentSpacePoint = GetTransform() * point;
  517. rotation_ = (rotation_ * delta).Normalized();
  518. break;
  519. case TS_PARENT:
  520. parentSpacePoint = point;
  521. rotation_ = (delta * rotation_).Normalized();
  522. break;
  523. case TS_WORLD:
  524. if (parent_ == scene_ || !parent_)
  525. {
  526. parentSpacePoint = point;
  527. rotation_ = (delta * rotation_).Normalized();
  528. }
  529. else
  530. {
  531. parentSpacePoint = parent_->GetWorldTransform().Inverse() * point;
  532. Quaternion worldRotation = GetWorldRotation();
  533. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  534. }
  535. break;
  536. }
  537. Vector3 oldRelativePos = oldRotation.Inverse() * (position_ - parentSpacePoint);
  538. position_ = rotation_ * oldRelativePos + parentSpacePoint;
  539. MarkDirty();
  540. MarkNetworkUpdate();
  541. }
  542. void Node::Yaw(float angle, TransformSpace space)
  543. {
  544. Rotate(Quaternion(angle, Vector3::UP), space);
  545. }
  546. void Node::Pitch(float angle, TransformSpace space)
  547. {
  548. Rotate(Quaternion(angle, Vector3::RIGHT), space);
  549. }
  550. void Node::Roll(float angle, TransformSpace space)
  551. {
  552. Rotate(Quaternion(angle, Vector3::FORWARD), space);
  553. }
  554. bool Node::LookAt(const Vector3& target, const Vector3& up, TransformSpace space)
  555. {
  556. Vector3 worldSpaceTarget;
  557. switch (space)
  558. {
  559. case TS_LOCAL:
  560. worldSpaceTarget = GetWorldTransform() * target;
  561. break;
  562. case TS_PARENT:
  563. worldSpaceTarget = (parent_ == scene_ || !parent_) ? target : parent_->GetWorldTransform() * target;
  564. break;
  565. case TS_WORLD:
  566. worldSpaceTarget = target;
  567. break;
  568. }
  569. Vector3 lookDir = worldSpaceTarget - GetWorldPosition();
  570. // Check if target is very close, in that case can not reliably calculate lookat direction
  571. if (lookDir.Equals(Vector3::ZERO))
  572. return false;
  573. Quaternion newRotation;
  574. // Do nothing if setting look rotation failed
  575. if (!newRotation.FromLookRotation(lookDir, up))
  576. return false;
  577. SetWorldRotation(newRotation);
  578. return true;
  579. }
  580. void Node::Scale(float scale)
  581. {
  582. Scale(Vector3(scale, scale, scale));
  583. }
  584. void Node::Scale(const Vector3& scale)
  585. {
  586. scale_ *= scale;
  587. MarkDirty();
  588. MarkNetworkUpdate();
  589. }
  590. void Node::SetEnabled(bool enable)
  591. {
  592. SetEnabled(enable, false, true);
  593. }
  594. void Node::SetDeepEnabled(bool enable)
  595. {
  596. SetEnabled(enable, true, false);
  597. }
  598. void Node::ResetDeepEnabled()
  599. {
  600. SetEnabled(enabledPrev_, false, false);
  601. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  602. (*i)->ResetDeepEnabled();
  603. }
  604. void Node::SetEnabledRecursive(bool enable)
  605. {
  606. SetEnabled(enable, true, true);
  607. }
  608. void Node::SetOwner(Connection* owner)
  609. {
  610. impl_->owner_ = owner;
  611. }
  612. void Node::MarkDirty()
  613. {
  614. Node *cur = this;
  615. for (;;)
  616. {
  617. // Precondition:
  618. // a) whenever a node is marked dirty, all its children are marked dirty as well.
  619. // b) whenever a node is cleared from being dirty, all its parents must have been
  620. // cleared as well.
  621. // Therefore if we are recursing here to mark this node dirty, and it already was,
  622. // then all children of this node must also be already dirty, and we don't need to
  623. // reflag them again.
  624. if (cur->dirty_)
  625. return;
  626. cur->dirty_ = true;
  627. // Notify listener components first, then mark child nodes
  628. for (Vector<WeakPtr<Component> >::Iterator i = cur->listeners_.Begin(); i != cur->listeners_.End();)
  629. {
  630. Component *c = *i;
  631. if (c)
  632. {
  633. c->OnMarkedDirty(cur);
  634. ++i;
  635. }
  636. // If listener has expired, erase from list (swap with the last element to avoid O(n^2) behavior)
  637. else
  638. {
  639. *i = cur->listeners_.Back();
  640. cur->listeners_.Pop();
  641. }
  642. }
  643. // Tail call optimization: Don't recurse to mark the first child dirty, but
  644. // instead process it in the context of the current function. If there are more
  645. // than one child, then recurse to the excess children.
  646. Vector<SharedPtr<Node> >::Iterator i = cur->children_.Begin();
  647. if (i != cur->children_.End())
  648. {
  649. Node *next = *i;
  650. for (++i; i != cur->children_.End(); ++i)
  651. (*i)->MarkDirty();
  652. cur = next;
  653. }
  654. else
  655. return;
  656. }
  657. }
  658. Node* Node::CreateChild(const String& name, CreateMode mode, unsigned id, bool temporary)
  659. {
  660. Node* newNode = CreateChild(id, mode, temporary);
  661. newNode->SetName(name);
  662. return newNode;
  663. }
  664. Node* Node::CreateTemporaryChild(const String& name, CreateMode mode, unsigned id)
  665. {
  666. return CreateChild(name, mode, id, true);
  667. }
  668. void Node::AddChild(Node* node, unsigned index)
  669. {
  670. // Check for illegal or redundant parent assignment
  671. if (!node || node == this || node->parent_ == this)
  672. return;
  673. // Check for possible cyclic parent assignment
  674. if (IsChildOf(node))
  675. return;
  676. // Keep a shared ptr to the node while transferring
  677. SharedPtr<Node> nodeShared(node);
  678. Node* oldParent = node->parent_;
  679. if (oldParent)
  680. {
  681. // If old parent is in different scene, perform the full removal
  682. if (oldParent->GetScene() != scene_)
  683. oldParent->RemoveChild(node);
  684. else
  685. {
  686. if (scene_)
  687. {
  688. // Otherwise do not remove from the scene during reparenting, just send the necessary change event
  689. using namespace NodeRemoved;
  690. VariantMap& eventData = GetEventDataMap();
  691. eventData[P_SCENE] = scene_;
  692. eventData[P_PARENT] = oldParent;
  693. eventData[P_NODE] = node;
  694. scene_->SendEvent(E_NODEREMOVED, eventData);
  695. }
  696. oldParent->children_.Remove(nodeShared);
  697. }
  698. }
  699. // Add to the child vector, then add to the scene if not added yet
  700. children_.Insert(index, nodeShared);
  701. if (scene_ && node->GetScene() != scene_)
  702. scene_->NodeAdded(node);
  703. node->parent_ = this;
  704. node->MarkDirty();
  705. node->MarkNetworkUpdate();
  706. // If the child node has components, also mark network update on them to ensure they have a valid NetworkState
  707. for (Vector<SharedPtr<Component> >::Iterator i = node->components_.Begin(); i != node->components_.End(); ++i)
  708. (*i)->MarkNetworkUpdate();
  709. // Send change event
  710. if (scene_)
  711. {
  712. using namespace NodeAdded;
  713. VariantMap& eventData = GetEventDataMap();
  714. eventData[P_SCENE] = scene_;
  715. eventData[P_PARENT] = this;
  716. eventData[P_NODE] = node;
  717. scene_->SendEvent(E_NODEADDED, eventData);
  718. }
  719. }
  720. void Node::RemoveChild(Node* node)
  721. {
  722. if (!node)
  723. return;
  724. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  725. {
  726. if (*i == node)
  727. {
  728. RemoveChild(i);
  729. return;
  730. }
  731. }
  732. }
  733. void Node::RemoveAllChildren()
  734. {
  735. RemoveChildren(true, true, true);
  736. }
  737. void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
  738. {
  739. unsigned numRemoved = 0;
  740. for (unsigned i = children_.Size() - 1; i < children_.Size(); --i)
  741. {
  742. bool remove = false;
  743. Node* childNode = children_[i];
  744. if (recursive)
  745. childNode->RemoveChildren(removeReplicated, removeLocal, true);
  746. if (childNode->IsReplicated() && removeReplicated)
  747. remove = true;
  748. else if (!childNode->IsReplicated() && removeLocal)
  749. remove = true;
  750. if (remove)
  751. {
  752. RemoveChild(children_.Begin() + i);
  753. ++numRemoved;
  754. }
  755. }
  756. // Mark node dirty in all replication states
  757. if (numRemoved)
  758. MarkReplicationDirty();
  759. }
  760. Component* Node::CreateComponent(StringHash type, CreateMode mode, unsigned id)
  761. {
  762. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  763. // as replicated components are synced over
  764. if (mode == REPLICATED && !IsReplicated())
  765. mode = LOCAL;
  766. // Check that creation succeeds and that the object in fact is a component
  767. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  768. if (!newComponent)
  769. {
  770. URHO3D_LOGERROR("Could not create unknown component type " + type.ToString());
  771. return nullptr;
  772. }
  773. AddComponent(newComponent, id, mode);
  774. return newComponent;
  775. }
  776. Component* Node::GetOrCreateComponent(StringHash type, CreateMode mode, unsigned id)
  777. {
  778. Component* oldComponent = GetComponent(type);
  779. if (oldComponent)
  780. return oldComponent;
  781. else
  782. return CreateComponent(type, mode, id);
  783. }
  784. Component* Node::CloneComponent(Component* component, unsigned id)
  785. {
  786. if (!component)
  787. {
  788. URHO3D_LOGERROR("Null source component given for CloneComponent");
  789. return nullptr;
  790. }
  791. return CloneComponent(component, component->IsReplicated() ? REPLICATED : LOCAL, id);
  792. }
  793. Component* Node::CloneComponent(Component* component, CreateMode mode, unsigned id)
  794. {
  795. if (!component)
  796. {
  797. URHO3D_LOGERROR("Null source component given for CloneComponent");
  798. return nullptr;
  799. }
  800. Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0);
  801. if (!cloneComponent)
  802. {
  803. URHO3D_LOGERROR("Could not clone component " + component->GetTypeName());
  804. return nullptr;
  805. }
  806. const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
  807. const Vector<AttributeInfo>* cloneAttributes = cloneComponent->GetAttributes();
  808. if (compAttributes)
  809. {
  810. for (unsigned i = 0; i < compAttributes->Size() && i < cloneAttributes->Size(); ++i)
  811. {
  812. const AttributeInfo& attr = compAttributes->At(i);
  813. const AttributeInfo& cloneAttr = cloneAttributes->At(i);
  814. if (attr.mode_ & AM_FILE)
  815. {
  816. Variant value;
  817. component->OnGetAttribute(attr, value);
  818. // Note: when eg. a ScriptInstance component is cloned, its script object attributes are unique and therefore we
  819. // can not simply refer to the source component's AttributeInfo
  820. cloneComponent->OnSetAttribute(cloneAttr, value);
  821. }
  822. }
  823. cloneComponent->ApplyAttributes();
  824. }
  825. if (scene_)
  826. {
  827. using namespace ComponentCloned;
  828. VariantMap& eventData = GetEventDataMap();
  829. eventData[P_SCENE] = scene_;
  830. eventData[P_COMPONENT] = component;
  831. eventData[P_CLONECOMPONENT] = cloneComponent;
  832. scene_->SendEvent(E_COMPONENTCLONED, eventData);
  833. }
  834. return cloneComponent;
  835. }
  836. void Node::RemoveComponent(Component* component)
  837. {
  838. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  839. {
  840. if (*i == component)
  841. {
  842. RemoveComponent(i);
  843. // Mark node dirty in all replication states
  844. MarkReplicationDirty();
  845. return;
  846. }
  847. }
  848. }
  849. void Node::RemoveComponent(StringHash type)
  850. {
  851. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  852. {
  853. if ((*i)->GetType() == type)
  854. {
  855. RemoveComponent(i);
  856. // Mark node dirty in all replication states
  857. MarkReplicationDirty();
  858. return;
  859. }
  860. }
  861. }
  862. void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
  863. {
  864. unsigned numRemoved = 0;
  865. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  866. {
  867. bool remove = false;
  868. Component* component = components_[i];
  869. if (component->IsReplicated() && removeReplicated)
  870. remove = true;
  871. else if (!component->IsReplicated() && removeLocal)
  872. remove = true;
  873. if (remove)
  874. {
  875. RemoveComponent(components_.Begin() + i);
  876. ++numRemoved;
  877. }
  878. }
  879. // Mark node dirty in all replication states
  880. if (numRemoved)
  881. MarkReplicationDirty();
  882. }
  883. void Node::RemoveComponents(StringHash type)
  884. {
  885. unsigned numRemoved = 0;
  886. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  887. {
  888. if (components_[i]->GetType() == type)
  889. {
  890. RemoveComponent(components_.Begin() + i);
  891. ++numRemoved;
  892. }
  893. }
  894. // Mark node dirty in all replication states
  895. if (numRemoved)
  896. MarkReplicationDirty();
  897. }
  898. void Node::RemoveAllComponents()
  899. {
  900. RemoveComponents(true, true);
  901. }
  902. void Node::ReorderComponent(Component* component, unsigned index)
  903. {
  904. if (!component || component->GetNode() != this)
  905. return;
  906. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  907. {
  908. if (*i == component)
  909. {
  910. // Need shared ptr to insert. Also, prevent destruction when removing first
  911. SharedPtr<Component> componentShared(component);
  912. components_.Erase(i);
  913. components_.Insert(index, componentShared);
  914. return;
  915. }
  916. }
  917. }
  918. Node* Node::Clone(CreateMode mode)
  919. {
  920. // The scene itself can not be cloned
  921. if (this == scene_ || !parent_)
  922. {
  923. URHO3D_LOGERROR("Can not clone node without a parent");
  924. return nullptr;
  925. }
  926. URHO3D_PROFILE(CloneNode);
  927. SceneResolver resolver;
  928. Node* clone = CloneRecursive(parent_, resolver, mode);
  929. resolver.Resolve();
  930. clone->ApplyAttributes();
  931. return clone;
  932. }
  933. void Node::Remove()
  934. {
  935. if (parent_)
  936. parent_->RemoveChild(this);
  937. }
  938. void Node::SetParent(Node* parent)
  939. {
  940. if (parent)
  941. {
  942. Matrix3x4 oldWorldTransform = GetWorldTransform();
  943. parent->AddChild(this);
  944. if (parent != scene_)
  945. {
  946. Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
  947. SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
  948. }
  949. else
  950. {
  951. // The root node is assumed to have identity transform, so can disregard it
  952. SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
  953. }
  954. }
  955. }
  956. void Node::SetVar(StringHash key, const Variant& value)
  957. {
  958. vars_[key] = value;
  959. MarkNetworkUpdate();
  960. }
  961. void Node::AddListener(Component* component)
  962. {
  963. if (!component)
  964. return;
  965. // Check for not adding twice
  966. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  967. {
  968. if (*i == component)
  969. return;
  970. }
  971. listeners_.Push(WeakPtr<Component>(component));
  972. // If the node is currently dirty, notify immediately
  973. if (dirty_)
  974. component->OnMarkedDirty(this);
  975. }
  976. void Node::RemoveListener(Component* component)
  977. {
  978. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  979. {
  980. if (*i == component)
  981. {
  982. listeners_.Erase(i);
  983. return;
  984. }
  985. }
  986. }
  987. Vector3 Node::GetSignedWorldScale() const
  988. {
  989. if (dirty_)
  990. UpdateWorldTransform();
  991. return worldTransform_.SignedScale(worldRotation_.RotationMatrix());
  992. }
  993. Vector3 Node::LocalToWorld(const Vector3& position) const
  994. {
  995. return GetWorldTransform() * position;
  996. }
  997. Vector3 Node::LocalToWorld(const Vector4& vector) const
  998. {
  999. return GetWorldTransform() * vector;
  1000. }
  1001. Vector2 Node::LocalToWorld2D(const Vector2& vector) const
  1002. {
  1003. Vector3 result = LocalToWorld(Vector3(vector));
  1004. return Vector2(result.x_, result.y_);
  1005. }
  1006. Vector3 Node::WorldToLocal(const Vector3& position) const
  1007. {
  1008. return GetWorldTransform().Inverse() * position;
  1009. }
  1010. Vector3 Node::WorldToLocal(const Vector4& vector) const
  1011. {
  1012. return GetWorldTransform().Inverse() * vector;
  1013. }
  1014. Vector2 Node::WorldToLocal2D(const Vector2& vector) const
  1015. {
  1016. Vector3 result = WorldToLocal(Vector3(vector));
  1017. return Vector2(result.x_, result.y_);
  1018. }
  1019. unsigned Node::GetNumChildren(bool recursive) const
  1020. {
  1021. if (!recursive)
  1022. return children_.Size();
  1023. else
  1024. {
  1025. unsigned allChildren = children_.Size();
  1026. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1027. allChildren += (*i)->GetNumChildren(true);
  1028. return allChildren;
  1029. }
  1030. }
  1031. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  1032. {
  1033. dest.Clear();
  1034. if (!recursive)
  1035. {
  1036. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1037. dest.Push(*i);
  1038. }
  1039. else
  1040. GetChildrenRecursive(dest);
  1041. }
  1042. PODVector<Node*> Node::GetChildren(bool recursive) const
  1043. {
  1044. PODVector<Node*> dest;
  1045. GetChildren(dest, recursive);
  1046. return dest;
  1047. }
  1048. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, StringHash type, bool recursive) const
  1049. {
  1050. dest.Clear();
  1051. if (!recursive)
  1052. {
  1053. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1054. {
  1055. if ((*i)->HasComponent(type))
  1056. dest.Push(*i);
  1057. }
  1058. }
  1059. else
  1060. GetChildrenWithComponentRecursive(dest, type);
  1061. }
  1062. PODVector<Node*> Node::GetChildrenWithComponent(StringHash type, bool recursive) const
  1063. {
  1064. PODVector<Node*> dest;
  1065. GetChildrenWithComponent(dest, type, recursive);
  1066. return dest;
  1067. }
  1068. void Node::GetChildrenWithTag(PODVector<Node*>& dest, const String& tag, bool recursive /*= true*/) const
  1069. {
  1070. dest.Clear();
  1071. if (!recursive)
  1072. {
  1073. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1074. {
  1075. if ((*i)->HasTag(tag))
  1076. dest.Push(*i);
  1077. }
  1078. }
  1079. else
  1080. GetChildrenWithTagRecursive(dest, tag);
  1081. }
  1082. PODVector<Node*> Node::GetChildrenWithTag(const String& tag, bool recursive) const
  1083. {
  1084. PODVector<Node*> dest;
  1085. GetChildrenWithTag(dest, tag, recursive);
  1086. return dest;
  1087. }
  1088. Node* Node::GetChild(unsigned index) const
  1089. {
  1090. return index < children_.Size() ? children_[index].Get() : nullptr;
  1091. }
  1092. Node* Node::GetChild(const String& name, bool recursive) const
  1093. {
  1094. return GetChild(StringHash(name), recursive);
  1095. }
  1096. Node* Node::GetChild(const char* name, bool recursive) const
  1097. {
  1098. return GetChild(StringHash(name), recursive);
  1099. }
  1100. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  1101. {
  1102. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1103. {
  1104. if ((*i)->GetNameHash() == nameHash)
  1105. return *i;
  1106. if (recursive)
  1107. {
  1108. Node* node = (*i)->GetChild(nameHash, true);
  1109. if (node)
  1110. return node;
  1111. }
  1112. }
  1113. return nullptr;
  1114. }
  1115. unsigned Node::GetNumNetworkComponents() const
  1116. {
  1117. unsigned num = 0;
  1118. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1119. {
  1120. if ((*i)->IsReplicated())
  1121. ++num;
  1122. }
  1123. return num;
  1124. }
  1125. void Node::GetComponents(PODVector<Component*>& dest, StringHash type, bool recursive) const
  1126. {
  1127. dest.Clear();
  1128. if (!recursive)
  1129. {
  1130. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1131. {
  1132. if ((*i)->GetType() == type)
  1133. dest.Push(*i);
  1134. }
  1135. }
  1136. else
  1137. GetComponentsRecursive(dest, type);
  1138. }
  1139. bool Node::HasComponent(StringHash type) const
  1140. {
  1141. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1142. {
  1143. if ((*i)->GetType() == type)
  1144. return true;
  1145. }
  1146. return false;
  1147. }
  1148. bool Node::IsReplicated() const
  1149. {
  1150. return Scene::IsReplicatedID(id_);
  1151. }
  1152. bool Node::HasTag(const String& tag) const
  1153. {
  1154. return impl_->tags_.Contains(tag);
  1155. }
  1156. bool Node::IsChildOf(Node* node) const
  1157. {
  1158. Node* parent = parent_;
  1159. while (parent)
  1160. {
  1161. if (parent == node)
  1162. return true;
  1163. parent = parent->parent_;
  1164. }
  1165. return false;
  1166. }
  1167. const Variant& Node::GetVar(StringHash key) const
  1168. {
  1169. VariantMap::ConstIterator i = vars_.Find(key);
  1170. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1171. }
  1172. Component* Node::GetComponent(StringHash type, bool recursive) const
  1173. {
  1174. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1175. {
  1176. if ((*i)->GetType() == type)
  1177. return *i;
  1178. }
  1179. if (recursive)
  1180. {
  1181. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1182. {
  1183. Component* component = (*i)->GetComponent(type, true);
  1184. if (component)
  1185. return component;
  1186. }
  1187. }
  1188. return nullptr;
  1189. }
  1190. Component* Node::GetParentComponent(StringHash type, bool fullTraversal) const
  1191. {
  1192. Node* current = GetParent();
  1193. while (current)
  1194. {
  1195. Component* soughtComponent = current->GetComponent(type);
  1196. if (soughtComponent)
  1197. return soughtComponent;
  1198. if (fullTraversal)
  1199. current = current->GetParent();
  1200. else
  1201. break;
  1202. }
  1203. return nullptr;
  1204. }
  1205. void Node::SetID(unsigned id)
  1206. {
  1207. id_ = id;
  1208. }
  1209. void Node::SetScene(Scene* scene)
  1210. {
  1211. scene_ = scene;
  1212. }
  1213. void Node::ResetScene()
  1214. {
  1215. SetID(0);
  1216. SetScene(nullptr);
  1217. SetOwner(nullptr);
  1218. }
  1219. void Node::SetNetPositionAttr(const Vector3& value)
  1220. {
  1221. auto* transform = GetComponent<SmoothedTransform>();
  1222. if (transform)
  1223. transform->SetTargetPosition(value);
  1224. else
  1225. SetPosition(value);
  1226. }
  1227. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  1228. {
  1229. MemoryBuffer buf(value);
  1230. auto* transform = GetComponent<SmoothedTransform>();
  1231. if (transform)
  1232. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  1233. else
  1234. SetRotation(buf.ReadPackedQuaternion());
  1235. }
  1236. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  1237. {
  1238. Scene* scene = GetScene();
  1239. if (!scene)
  1240. return;
  1241. MemoryBuffer buf(value);
  1242. // If nothing in the buffer, parent is the root node
  1243. if (buf.IsEof())
  1244. {
  1245. scene->AddChild(this);
  1246. return;
  1247. }
  1248. unsigned baseNodeID = buf.ReadNetID();
  1249. Node* baseNode = scene->GetNode(baseNodeID);
  1250. if (!baseNode)
  1251. {
  1252. URHO3D_LOGWARNING("Failed to find parent node " + String(baseNodeID));
  1253. return;
  1254. }
  1255. // If buffer contains just an ID, the parent is replicated and we are done
  1256. if (buf.IsEof())
  1257. baseNode->AddChild(this);
  1258. else
  1259. {
  1260. // Else the parent is local and we must find it recursively by name hash
  1261. StringHash nameHash = buf.ReadStringHash();
  1262. Node* parentNode = baseNode->GetChild(nameHash, true);
  1263. if (!parentNode)
  1264. URHO3D_LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  1265. else
  1266. parentNode->AddChild(this);
  1267. }
  1268. }
  1269. const Vector3& Node::GetNetPositionAttr() const
  1270. {
  1271. return position_;
  1272. }
  1273. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  1274. {
  1275. impl_->attrBuffer_.Clear();
  1276. impl_->attrBuffer_.WritePackedQuaternion(rotation_);
  1277. return impl_->attrBuffer_.GetBuffer();
  1278. }
  1279. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  1280. {
  1281. impl_->attrBuffer_.Clear();
  1282. Scene* scene = GetScene();
  1283. if (scene && parent_ && parent_ != scene)
  1284. {
  1285. // If parent is replicated, can write the ID directly
  1286. unsigned parentID = parent_->GetID();
  1287. if (Scene::IsReplicatedID(parentID))
  1288. impl_->attrBuffer_.WriteNetID(parentID);
  1289. else
  1290. {
  1291. // Parent is local: traverse hierarchy to find a non-local base node
  1292. // This iteration always stops due to the scene (root) being non-local
  1293. Node* current = parent_;
  1294. while (!current->IsReplicated())
  1295. current = current->GetParent();
  1296. // Then write the base node ID and the parent's name hash
  1297. impl_->attrBuffer_.WriteNetID(current->GetID());
  1298. impl_->attrBuffer_.WriteStringHash(parent_->GetNameHash());
  1299. }
  1300. }
  1301. return impl_->attrBuffer_.GetBuffer();
  1302. }
  1303. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool loadChildren, bool rewriteIDs, CreateMode mode)
  1304. {
  1305. // Remove all children and components first in case this is not a fresh load
  1306. RemoveAllChildren();
  1307. RemoveAllComponents();
  1308. // ID has been read at the parent level
  1309. if (!Animatable::Load(source))
  1310. return false;
  1311. unsigned numComponents = source.ReadVLE();
  1312. for (unsigned i = 0; i < numComponents; ++i)
  1313. {
  1314. VectorBuffer compBuffer(source, source.ReadVLE());
  1315. StringHash compType = compBuffer.ReadStringHash();
  1316. unsigned compID = compBuffer.ReadUInt();
  1317. Component* newComponent = SafeCreateComponent(String::EMPTY, compType,
  1318. (mode == REPLICATED && Scene::IsReplicatedID(compID)) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1319. if (newComponent)
  1320. {
  1321. resolver.AddComponent(compID, newComponent);
  1322. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  1323. newComponent->Load(compBuffer);
  1324. }
  1325. }
  1326. if (!loadChildren)
  1327. return true;
  1328. unsigned numChildren = source.ReadVLE();
  1329. for (unsigned i = 0; i < numChildren; ++i)
  1330. {
  1331. unsigned nodeID = source.ReadUInt();
  1332. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && Scene::IsReplicatedID(nodeID)) ? REPLICATED :
  1333. LOCAL);
  1334. resolver.AddNode(nodeID, newNode);
  1335. if (!newNode->Load(source, resolver, loadChildren, rewriteIDs, mode))
  1336. return false;
  1337. }
  1338. return true;
  1339. }
  1340. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren, bool rewriteIDs, CreateMode mode)
  1341. {
  1342. // Remove all children and components first in case this is not a fresh load
  1343. RemoveAllChildren();
  1344. RemoveAllComponents();
  1345. if (!Animatable::LoadXML(source))
  1346. return false;
  1347. XMLElement compElem = source.GetChild("component");
  1348. while (compElem)
  1349. {
  1350. String typeName = compElem.GetAttribute("type");
  1351. unsigned compID = compElem.GetUInt("id");
  1352. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1353. (mode == REPLICATED && Scene::IsReplicatedID(compID)) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1354. if (newComponent)
  1355. {
  1356. resolver.AddComponent(compID, newComponent);
  1357. if (!newComponent->LoadXML(compElem))
  1358. return false;
  1359. }
  1360. compElem = compElem.GetNext("component");
  1361. }
  1362. if (!loadChildren)
  1363. return true;
  1364. XMLElement childElem = source.GetChild("node");
  1365. while (childElem)
  1366. {
  1367. unsigned nodeID = childElem.GetUInt("id");
  1368. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && Scene::IsReplicatedID(nodeID)) ? REPLICATED :
  1369. LOCAL);
  1370. resolver.AddNode(nodeID, newNode);
  1371. if (!newNode->LoadXML(childElem, resolver, loadChildren, rewriteIDs, mode))
  1372. return false;
  1373. childElem = childElem.GetNext("node");
  1374. }
  1375. return true;
  1376. }
  1377. bool Node::LoadJSON(const JSONValue& source, SceneResolver& resolver, bool loadChildren, bool rewriteIDs, CreateMode mode)
  1378. {
  1379. // Remove all children and components first in case this is not a fresh load
  1380. RemoveAllChildren();
  1381. RemoveAllComponents();
  1382. if (!Animatable::LoadJSON(source))
  1383. return false;
  1384. const JSONArray& componentsArray = source.Get("components").GetArray();
  1385. for (unsigned i = 0; i < componentsArray.Size(); i++)
  1386. {
  1387. const JSONValue& compVal = componentsArray.At(i);
  1388. String typeName = compVal.Get("type").GetString();
  1389. unsigned compID = compVal.Get("id").GetUInt();
  1390. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1391. (mode == REPLICATED && Scene::IsReplicatedID(compID)) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1392. if (newComponent)
  1393. {
  1394. resolver.AddComponent(compID, newComponent);
  1395. if (!newComponent->LoadJSON(compVal))
  1396. return false;
  1397. }
  1398. }
  1399. if (!loadChildren)
  1400. return true;
  1401. const JSONArray& childrenArray = source.Get("children").GetArray();
  1402. for (unsigned i = 0; i < childrenArray.Size(); i++)
  1403. {
  1404. const JSONValue& childVal = childrenArray.At(i);
  1405. unsigned nodeID = childVal.Get("id").GetUInt();
  1406. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && Scene::IsReplicatedID(nodeID)) ? REPLICATED :
  1407. LOCAL);
  1408. resolver.AddNode(nodeID, newNode);
  1409. if (!newNode->LoadJSON(childVal, resolver, loadChildren, rewriteIDs, mode))
  1410. return false;
  1411. }
  1412. return true;
  1413. }
  1414. void Node::PrepareNetworkUpdate()
  1415. {
  1416. // Update dependency nodes list first
  1417. impl_->dependencyNodes_.Clear();
  1418. // Add the parent node, but if it is local, traverse to the first non-local node
  1419. if (parent_ && parent_ != scene_)
  1420. {
  1421. Node* current = parent_;
  1422. while (!current->IsReplicated())
  1423. current = current->parent_;
  1424. if (current && current != scene_)
  1425. impl_->dependencyNodes_.Push(current);
  1426. }
  1427. // Let the components add their dependencies
  1428. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1429. {
  1430. Component* component = *i;
  1431. if (component->IsReplicated())
  1432. component->GetDependencyNodes(impl_->dependencyNodes_);
  1433. }
  1434. // Then check for node attribute changes
  1435. if (!networkState_)
  1436. AllocateNetworkState();
  1437. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  1438. unsigned numAttributes = attributes->Size();
  1439. // Check for attribute changes
  1440. for (unsigned i = 0; i < numAttributes; ++i)
  1441. {
  1442. const AttributeInfo& attr = attributes->At(i);
  1443. if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
  1444. continue;
  1445. OnGetAttribute(attr, networkState_->currentValues_[i]);
  1446. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  1447. {
  1448. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  1449. // Mark the attribute dirty in all replication states that are tracking this node
  1450. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1451. j != networkState_->replicationStates_.End(); ++j)
  1452. {
  1453. auto* nodeState = static_cast<NodeReplicationState*>(*j);
  1454. nodeState->dirtyAttributes_.Set(i);
  1455. // Add node to the dirty set if not added yet
  1456. if (!nodeState->markedDirty_)
  1457. {
  1458. nodeState->markedDirty_ = true;
  1459. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1460. }
  1461. }
  1462. }
  1463. }
  1464. // Finally check for user var changes
  1465. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  1466. {
  1467. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  1468. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  1469. {
  1470. networkState_->previousVars_[i->first_] = i->second_;
  1471. // Mark the var dirty in all replication states that are tracking this node
  1472. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1473. j != networkState_->replicationStates_.End(); ++j)
  1474. {
  1475. auto* nodeState = static_cast<NodeReplicationState*>(*j);
  1476. nodeState->dirtyVars_.Insert(i->first_);
  1477. if (!nodeState->markedDirty_)
  1478. {
  1479. nodeState->markedDirty_ = true;
  1480. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1481. }
  1482. }
  1483. }
  1484. }
  1485. networkUpdate_ = false;
  1486. }
  1487. void Node::CleanupConnection(Connection* connection)
  1488. {
  1489. if (impl_->owner_ == connection)
  1490. impl_->owner_ = nullptr;
  1491. if (networkState_)
  1492. {
  1493. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  1494. {
  1495. if (networkState_->replicationStates_[i]->connection_ == connection)
  1496. networkState_->replicationStates_.Erase(i);
  1497. }
  1498. }
  1499. }
  1500. void Node::MarkReplicationDirty()
  1501. {
  1502. if (networkState_)
  1503. {
  1504. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1505. j != networkState_->replicationStates_.End(); ++j)
  1506. {
  1507. auto* nodeState = static_cast<NodeReplicationState*>(*j);
  1508. if (!nodeState->markedDirty_)
  1509. {
  1510. nodeState->markedDirty_ = true;
  1511. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1512. }
  1513. }
  1514. }
  1515. }
  1516. Node* Node::CreateChild(unsigned id, CreateMode mode, bool temporary)
  1517. {
  1518. SharedPtr<Node> newNode(new Node(context_));
  1519. newNode->SetTemporary(temporary);
  1520. // If zero ID specified, or the ID is already taken, let the scene assign
  1521. if (scene_)
  1522. {
  1523. if (!id || scene_->GetNode(id))
  1524. id = scene_->GetFreeNodeID(mode);
  1525. newNode->SetID(id);
  1526. }
  1527. else
  1528. newNode->SetID(id);
  1529. AddChild(newNode);
  1530. return newNode;
  1531. }
  1532. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1533. {
  1534. if (!component)
  1535. return;
  1536. components_.Push(SharedPtr<Component>(component));
  1537. if (component->GetNode())
  1538. URHO3D_LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!");
  1539. component->SetNode(this);
  1540. // If zero ID specified, or the ID is already taken, let the scene assign
  1541. if (scene_)
  1542. {
  1543. if (!id || scene_->GetComponent(id))
  1544. id = scene_->GetFreeComponentID(mode);
  1545. component->SetID(id);
  1546. scene_->ComponentAdded(component);
  1547. }
  1548. else
  1549. component->SetID(id);
  1550. component->OnMarkedDirty(this);
  1551. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1552. component->MarkNetworkUpdate();
  1553. MarkNetworkUpdate();
  1554. MarkReplicationDirty();
  1555. // Send change event
  1556. if (scene_)
  1557. {
  1558. using namespace ComponentAdded;
  1559. VariantMap& eventData = GetEventDataMap();
  1560. eventData[P_SCENE] = scene_;
  1561. eventData[P_NODE] = this;
  1562. eventData[P_COMPONENT] = component;
  1563. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1564. }
  1565. }
  1566. unsigned Node::GetNumPersistentChildren() const
  1567. {
  1568. unsigned ret = 0;
  1569. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1570. {
  1571. if (!(*i)->IsTemporary())
  1572. ++ret;
  1573. }
  1574. return ret;
  1575. }
  1576. unsigned Node::GetNumPersistentComponents() const
  1577. {
  1578. unsigned ret = 0;
  1579. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1580. {
  1581. if (!(*i)->IsTemporary())
  1582. ++ret;
  1583. }
  1584. return ret;
  1585. }
  1586. void Node::SetTransformSilent(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  1587. {
  1588. position_ = position;
  1589. rotation_ = rotation;
  1590. scale_ = scale;
  1591. }
  1592. void Node::OnAttributeAnimationAdded()
  1593. {
  1594. if (attributeAnimationInfos_.Size() == 1)
  1595. SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Node, HandleAttributeAnimationUpdate));
  1596. }
  1597. void Node::OnAttributeAnimationRemoved()
  1598. {
  1599. if (attributeAnimationInfos_.Empty())
  1600. UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
  1601. }
  1602. Animatable* Node::FindAttributeAnimationTarget(const String& name, String& outName)
  1603. {
  1604. Vector<String> names = name.Split('/');
  1605. // Only attribute name
  1606. if (names.Size() == 1)
  1607. {
  1608. outName = name;
  1609. return this;
  1610. }
  1611. else
  1612. {
  1613. // Name must in following format: "#0/#1/@component#0/attribute"
  1614. Node* node = this;
  1615. unsigned i = 0;
  1616. for (; i < names.Size() - 1; ++i)
  1617. {
  1618. if (names[i].Front() != '#')
  1619. break;
  1620. String name = names[i].Substring(1, names[i].Length() - 1);
  1621. char s = name.Front();
  1622. if (s >= '0' && s <= '9')
  1623. {
  1624. unsigned index = ToUInt(name);
  1625. node = node->GetChild(index);
  1626. }
  1627. else
  1628. {
  1629. node = node->GetChild(name, true);
  1630. }
  1631. if (!node)
  1632. {
  1633. URHO3D_LOGERROR("Could not find node by name " + name);
  1634. return nullptr;
  1635. }
  1636. }
  1637. if (i == names.Size() - 1)
  1638. {
  1639. outName = names.Back();
  1640. return node;
  1641. }
  1642. if (i != names.Size() - 2 || names[i].Front() != '@')
  1643. {
  1644. URHO3D_LOGERROR("Invalid name " + name);
  1645. return nullptr;
  1646. }
  1647. String componentName = names[i].Substring(1, names[i].Length() - 1);
  1648. Vector<String> componentNames = componentName.Split('#');
  1649. if (componentNames.Size() == 1)
  1650. {
  1651. Component* component = node->GetComponent(StringHash(componentNames.Front()));
  1652. if (!component)
  1653. {
  1654. URHO3D_LOGERROR("Could not find component by name " + name);
  1655. return nullptr;
  1656. }
  1657. outName = names.Back();
  1658. return component;
  1659. }
  1660. else
  1661. {
  1662. unsigned index = ToUInt(componentNames[1]);
  1663. PODVector<Component*> components;
  1664. node->GetComponents(components, StringHash(componentNames.Front()));
  1665. if (index >= components.Size())
  1666. {
  1667. URHO3D_LOGERROR("Could not find component by name " + name);
  1668. return nullptr;
  1669. }
  1670. outName = names.Back();
  1671. return components[index];
  1672. }
  1673. }
  1674. }
  1675. void Node::SetEnabled(bool enable, bool recursive, bool storeSelf)
  1676. {
  1677. // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
  1678. if (GetType() == Scene::GetTypeStatic())
  1679. {
  1680. URHO3D_LOGERROR("Can not change enabled state of the Scene");
  1681. return;
  1682. }
  1683. if (storeSelf)
  1684. enabledPrev_ = enable;
  1685. if (enable != enabled_)
  1686. {
  1687. enabled_ = enable;
  1688. MarkNetworkUpdate();
  1689. // Notify listener components of the state change
  1690. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  1691. {
  1692. if (*i)
  1693. {
  1694. (*i)->OnNodeSetEnabled(this);
  1695. ++i;
  1696. }
  1697. // If listener has expired, erase from list
  1698. else
  1699. i = listeners_.Erase(i);
  1700. }
  1701. // Send change event
  1702. if (scene_)
  1703. {
  1704. using namespace NodeEnabledChanged;
  1705. VariantMap& eventData = GetEventDataMap();
  1706. eventData[P_SCENE] = scene_;
  1707. eventData[P_NODE] = this;
  1708. scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
  1709. }
  1710. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  1711. {
  1712. (*i)->OnSetEnabled();
  1713. // Send change event for the component
  1714. if (scene_)
  1715. {
  1716. using namespace ComponentEnabledChanged;
  1717. VariantMap& eventData = GetEventDataMap();
  1718. eventData[P_SCENE] = scene_;
  1719. eventData[P_NODE] = this;
  1720. eventData[P_COMPONENT] = (*i);
  1721. scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
  1722. }
  1723. }
  1724. }
  1725. if (recursive)
  1726. {
  1727. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1728. (*i)->SetEnabled(enable, recursive, storeSelf);
  1729. }
  1730. }
  1731. Component* Node::SafeCreateComponent(const String& typeName, StringHash type, CreateMode mode, unsigned id)
  1732. {
  1733. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  1734. // as replicated components are synced over
  1735. if (mode == REPLICATED && !IsReplicated())
  1736. mode = LOCAL;
  1737. // First check if factory for type exists
  1738. if (!context_->GetTypeName(type).Empty())
  1739. return CreateComponent(type, mode, id);
  1740. else
  1741. {
  1742. URHO3D_LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder");
  1743. // Else create as UnknownComponent
  1744. SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
  1745. if (typeName.Empty() || typeName.StartsWith("Unknown", false))
  1746. newComponent->SetType(type);
  1747. else
  1748. newComponent->SetTypeName(typeName);
  1749. AddComponent(newComponent, id, mode);
  1750. return newComponent;
  1751. }
  1752. }
  1753. void Node::UpdateWorldTransform() const
  1754. {
  1755. Matrix3x4 transform = GetTransform();
  1756. // Assume the root node (scene) has identity transform
  1757. if (parent_ == scene_ || !parent_)
  1758. {
  1759. worldTransform_ = transform;
  1760. worldRotation_ = rotation_;
  1761. }
  1762. else
  1763. {
  1764. worldTransform_ = parent_->GetWorldTransform() * transform;
  1765. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1766. }
  1767. dirty_ = false;
  1768. }
  1769. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1770. {
  1771. // Keep a shared pointer to the child about to be removed, to make sure the erase from container completes first. Otherwise
  1772. // it would be possible that other child nodes get removed as part of the node's components' cleanup, causing a re-entrant
  1773. // erase and a crash
  1774. SharedPtr<Node> child(*i);
  1775. // Send change event. Do not send when this node is already being destroyed
  1776. if (Refs() > 0 && scene_)
  1777. {
  1778. using namespace NodeRemoved;
  1779. VariantMap& eventData = GetEventDataMap();
  1780. eventData[P_SCENE] = scene_;
  1781. eventData[P_PARENT] = this;
  1782. eventData[P_NODE] = child;
  1783. scene_->SendEvent(E_NODEREMOVED, eventData);
  1784. }
  1785. child->parent_ = nullptr;
  1786. child->MarkDirty();
  1787. child->MarkNetworkUpdate();
  1788. if (scene_)
  1789. scene_->NodeRemoved(child);
  1790. children_.Erase(i);
  1791. }
  1792. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1793. {
  1794. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1795. {
  1796. Node* node = *i;
  1797. dest.Push(node);
  1798. if (!node->children_.Empty())
  1799. node->GetChildrenRecursive(dest);
  1800. }
  1801. }
  1802. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, StringHash type) const
  1803. {
  1804. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1805. {
  1806. Node* node = *i;
  1807. if (node->HasComponent(type))
  1808. dest.Push(node);
  1809. if (!node->children_.Empty())
  1810. node->GetChildrenWithComponentRecursive(dest, type);
  1811. }
  1812. }
  1813. void Node::GetComponentsRecursive(PODVector<Component*>& dest, StringHash type) const
  1814. {
  1815. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1816. {
  1817. if ((*i)->GetType() == type)
  1818. dest.Push(*i);
  1819. }
  1820. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1821. (*i)->GetComponentsRecursive(dest, type);
  1822. }
  1823. void Node::GetChildrenWithTagRecursive(PODVector<Node*>& dest, const String& tag) const
  1824. {
  1825. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1826. {
  1827. Node* node = *i;
  1828. if (node->HasTag(tag))
  1829. dest.Push(node);
  1830. if (!node->children_.Empty())
  1831. node->GetChildrenWithTagRecursive(dest, tag);
  1832. }
  1833. }
  1834. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1835. {
  1836. // Create clone node
  1837. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && IsReplicated()) ? REPLICATED : LOCAL);
  1838. resolver.AddNode(id_, cloneNode);
  1839. // Copy attributes
  1840. const Vector<AttributeInfo>* attributes = GetAttributes();
  1841. for (unsigned j = 0; j < attributes->Size(); ++j)
  1842. {
  1843. const AttributeInfo& attr = attributes->At(j);
  1844. // Do not copy network-only attributes, as they may have unintended side effects
  1845. if (attr.mode_ & AM_FILE)
  1846. {
  1847. Variant value;
  1848. OnGetAttribute(attr, value);
  1849. cloneNode->OnSetAttribute(attr, value);
  1850. }
  1851. }
  1852. // Clone components
  1853. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1854. {
  1855. Component* component = *i;
  1856. if (component->IsTemporary())
  1857. continue;
  1858. Component* cloneComponent = cloneNode->CloneComponent(component,
  1859. (mode == REPLICATED && component->IsReplicated()) ? REPLICATED : LOCAL, 0);
  1860. if (cloneComponent)
  1861. resolver.AddComponent(component->GetID(), cloneComponent);
  1862. }
  1863. // Clone child nodes recursively
  1864. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1865. {
  1866. Node* node = *i;
  1867. if (node->IsTemporary())
  1868. continue;
  1869. node->CloneRecursive(cloneNode, resolver, mode);
  1870. }
  1871. if (scene_)
  1872. {
  1873. using namespace NodeCloned;
  1874. VariantMap& eventData = GetEventDataMap();
  1875. eventData[P_SCENE] = scene_;
  1876. eventData[P_NODE] = this;
  1877. eventData[P_CLONENODE] = cloneNode;
  1878. scene_->SendEvent(E_NODECLONED, eventData);
  1879. }
  1880. return cloneNode;
  1881. }
  1882. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1883. {
  1884. // Send node change event. Do not send when already being destroyed
  1885. if (Refs() > 0 && scene_)
  1886. {
  1887. using namespace ComponentRemoved;
  1888. VariantMap& eventData = GetEventDataMap();
  1889. eventData[P_SCENE] = scene_;
  1890. eventData[P_NODE] = this;
  1891. eventData[P_COMPONENT] = (*i).Get();
  1892. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1893. }
  1894. RemoveListener(*i);
  1895. if (scene_)
  1896. scene_->ComponentRemoved(*i);
  1897. (*i)->SetNode(nullptr);
  1898. components_.Erase(i);
  1899. }
  1900. void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1901. {
  1902. using namespace AttributeAnimationUpdate;
  1903. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1904. }
  1905. }