Node.cpp 64 KB

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