Node.cpp 63 KB

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