Node.cpp 60 KB

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