Node.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269
  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. // Can remove this check once bone nodes use temporary flag instead and new prefabs no longer use temporary flag.
  188. if (node->HasTag("Atomic_Temporary"))
  189. continue;
  190. XMLElement childElem = dest.CreateChild("node");
  191. if (!node->SaveXML(childElem))
  192. return false;
  193. }
  194. return true;
  195. }
  196. bool Node::SaveJSON(JSONValue& dest) const
  197. {
  198. // Write node ID
  199. dest.Set("id", id_);
  200. // Write attributes
  201. if (!Animatable::SaveJSON(dest))
  202. return false;
  203. // Write components
  204. JSONArray componentsArray;
  205. componentsArray.Reserve(components_.Size());
  206. for (unsigned i = 0; i < components_.Size(); ++i)
  207. {
  208. Component* component = components_[i];
  209. if (component->IsTemporary())
  210. continue;
  211. JSONValue compVal;
  212. if (!component->SaveJSON(compVal))
  213. return false;
  214. componentsArray.Push(compVal);
  215. }
  216. dest.Set("components", componentsArray);
  217. // Write child nodes
  218. JSONArray childrenArray;
  219. childrenArray.Reserve(children_.Size());
  220. for (unsigned i = 0; i < children_.Size(); ++i)
  221. {
  222. Node* node = children_[i];
  223. if (node->IsTemporary())
  224. continue;
  225. JSONValue childVal;
  226. if (!node->SaveJSON(childVal))
  227. return false;
  228. childrenArray.Push(childVal);
  229. }
  230. dest.Set("children", childrenArray);
  231. return true;
  232. }
  233. void Node::ApplyAttributes()
  234. {
  235. for (unsigned i = 0; i < components_.Size(); ++i)
  236. components_[i]->ApplyAttributes();
  237. for (unsigned i = 0; i < children_.Size(); ++i)
  238. children_[i]->ApplyAttributes();
  239. }
  240. void Node::MarkNetworkUpdate()
  241. {
  242. if (!networkUpdate_ && scene_ && id_ < FIRST_LOCAL_ID)
  243. {
  244. scene_->MarkNetworkUpdate(this);
  245. networkUpdate_ = true;
  246. }
  247. }
  248. void Node::AddReplicationState(NodeReplicationState* state)
  249. {
  250. if (!networkState_)
  251. AllocateNetworkState();
  252. networkState_->replicationStates_.Push(state);
  253. }
  254. bool Node::SaveXML(Serializer& dest, const String& indentation) const
  255. {
  256. SharedPtr<XMLFile> xml(new XMLFile(context_));
  257. XMLElement rootElem = xml->CreateRoot("node");
  258. if (!SaveXML(rootElem))
  259. return false;
  260. return xml->Save(dest, indentation);
  261. }
  262. bool Node::SaveJSON(Serializer& dest, const String& indentation) const
  263. {
  264. SharedPtr<JSONFile> json(new JSONFile(context_));
  265. JSONValue& rootElem = json->GetRoot();
  266. if (!SaveJSON(rootElem))
  267. return false;
  268. return json->Save(dest, indentation);
  269. }
  270. void Node::SetName(const String& name)
  271. {
  272. if (name != name_)
  273. {
  274. name_ = name;
  275. nameHash_ = name_;
  276. MarkNetworkUpdate();
  277. // Send change event
  278. if (scene_)
  279. {
  280. using namespace NodeNameChanged;
  281. VariantMap& eventData = GetEventDataMap();
  282. eventData[P_SCENE] = scene_;
  283. eventData[P_NODE] = this;
  284. scene_->SendEvent(E_NODENAMECHANGED, eventData);
  285. }
  286. }
  287. }
  288. void Node::SetTags(const StringVector& tags)
  289. {
  290. RemoveAllTags();
  291. AddTags(tags);
  292. // MarkNetworkUpdate() already called in RemoveAllTags() / AddTags()
  293. }
  294. void Node::AddTag(const String& tag)
  295. {
  296. // Check if tag empty or already added
  297. if (tag.Empty() || HasTag(tag))
  298. return;
  299. // Add tag
  300. tags_.Push(tag);
  301. // Cache
  302. scene_->NodeTagAdded(this, tag);
  303. // Send event
  304. using namespace NodeTagAdded;
  305. VariantMap& eventData = GetEventDataMap();
  306. eventData[P_SCENE] = scene_;
  307. eventData[P_NODE] = this;
  308. eventData[P_TAG] = tag;
  309. scene_->SendEvent(E_NODETAGADDED, eventData);
  310. // Sync
  311. MarkNetworkUpdate();
  312. }
  313. void Node::AddTags(const String& tags, String separator)
  314. {
  315. if (!separator.Length())
  316. return;
  317. StringVector tagVector = tags.Split(separator[0]);
  318. AddTags(tagVector);
  319. }
  320. void Node::AddTags(const StringVector& tags)
  321. {
  322. // This is OK, as MarkNetworkUpdate() early-outs when called multiple times
  323. for (unsigned i = 0; i < tags.Size(); ++i)
  324. AddTag(tags[i]);
  325. }
  326. bool Node::RemoveTag(const String& tag)
  327. {
  328. bool removed = tags_.Remove(tag);
  329. // Nothing to do
  330. if (!removed)
  331. return false;
  332. // Scene cache update
  333. if (scene_)
  334. {
  335. scene_->NodeTagRemoved(this, tag);
  336. // Send event
  337. using namespace NodeTagRemoved;
  338. VariantMap& eventData = GetEventDataMap();
  339. eventData[P_SCENE] = scene_;
  340. eventData[P_NODE] = this;
  341. eventData[P_TAG] = tag;
  342. scene_->SendEvent(E_NODETAGREMOVED, eventData);
  343. }
  344. // Sync
  345. MarkNetworkUpdate();
  346. return true;
  347. }
  348. void Node::RemoveAllTags()
  349. {
  350. // Clear old scene cache
  351. if (scene_)
  352. {
  353. for (unsigned i = 0; i < tags_.Size(); ++i)
  354. {
  355. scene_->NodeTagRemoved(this, tags_[i]);
  356. // Send event
  357. using namespace NodeTagRemoved;
  358. VariantMap& eventData = GetEventDataMap();
  359. eventData[P_SCENE] = scene_;
  360. eventData[P_NODE] = this;
  361. eventData[P_TAG] = tags_[i];
  362. scene_->SendEvent(E_NODETAGREMOVED, eventData);
  363. }
  364. }
  365. tags_.Clear();
  366. // Sync
  367. MarkNetworkUpdate();
  368. }
  369. void Node::SetPosition(const Vector3& position)
  370. {
  371. position_ = position;
  372. MarkDirty();
  373. MarkNetworkUpdate();
  374. }
  375. void Node::SetRotation(const Quaternion& rotation)
  376. {
  377. rotation_ = rotation;
  378. MarkDirty();
  379. MarkNetworkUpdate();
  380. }
  381. void Node::SetDirection(const Vector3& direction)
  382. {
  383. SetRotation(Quaternion(Vector3::FORWARD, direction));
  384. }
  385. void Node::SetScale(float scale)
  386. {
  387. SetScale(Vector3(scale, scale, scale));
  388. }
  389. void Node::SetScale(const Vector3& scale)
  390. {
  391. scale_ = scale;
  392. // Prevent exact zero scale e.g. from momentary edits as this may cause division by zero
  393. // when decomposing the world transform matrix
  394. if (scale_.x_ == 0.0f)
  395. scale_.x_ = M_EPSILON;
  396. if (scale_.y_ == 0.0f)
  397. scale_.y_ = M_EPSILON;
  398. if (scale_.z_ == 0.0f)
  399. scale_.z_ = M_EPSILON;
  400. MarkDirty();
  401. MarkNetworkUpdate();
  402. }
  403. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  404. {
  405. position_ = position;
  406. rotation_ = rotation;
  407. MarkDirty();
  408. MarkNetworkUpdate();
  409. }
  410. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  411. {
  412. SetTransform(position, rotation, Vector3(scale, scale, scale));
  413. }
  414. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  415. {
  416. position_ = position;
  417. rotation_ = rotation;
  418. scale_ = scale;
  419. MarkDirty();
  420. MarkNetworkUpdate();
  421. }
  422. void Node::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. 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)
  651. {
  652. Node* newNode = CreateChild(id, mode);
  653. newNode->SetName(name);
  654. return newNode;
  655. }
  656. void Node::AddChild(Node* node, unsigned index)
  657. {
  658. // Check for illegal or redundant parent assignment
  659. if (!node || node == this || node->parent_ == this)
  660. return;
  661. // Check for possible cyclic parent assignment
  662. Node* parent = parent_;
  663. while (parent)
  664. {
  665. if (parent == node)
  666. return;
  667. parent = parent->parent_;
  668. }
  669. // Keep a shared ptr to the node while transfering
  670. SharedPtr<Node> nodeShared(node);
  671. Node* oldParent = node->parent_;
  672. if (oldParent)
  673. {
  674. // If old parent is in different scene, perform the full removal
  675. if (oldParent->GetScene() != scene_)
  676. oldParent->RemoveChild(node);
  677. else
  678. {
  679. if (scene_)
  680. {
  681. // Otherwise do not remove from the scene during reparenting, just send the necessary change event
  682. using namespace NodeRemoved;
  683. VariantMap& eventData = GetEventDataMap();
  684. eventData[P_SCENE] = scene_;
  685. eventData[P_PARENT] = oldParent;
  686. eventData[P_NODE] = node;
  687. scene_->SendEvent(E_NODEREMOVED, eventData);
  688. }
  689. oldParent->children_.Remove(nodeShared);
  690. }
  691. }
  692. // Add to the child vector, then add to the scene if not added yet
  693. children_.Insert(index, nodeShared);
  694. if (scene_ && node->GetScene() != scene_)
  695. scene_->NodeAdded(node);
  696. node->parent_ = this;
  697. node->MarkDirty();
  698. node->MarkNetworkUpdate();
  699. // If the child node has components, also mark network update on them to ensure they have a valid NetworkState
  700. for (Vector<SharedPtr<Component> >::Iterator i = node->components_.Begin(); i != node->components_.End(); ++i)
  701. (*i)->MarkNetworkUpdate();
  702. // Send change event
  703. if (scene_)
  704. {
  705. using namespace NodeAdded;
  706. VariantMap& eventData = GetEventDataMap();
  707. eventData[P_SCENE] = scene_;
  708. eventData[P_PARENT] = this;
  709. eventData[P_NODE] = node;
  710. scene_->SendEvent(E_NODEADDED, eventData);
  711. }
  712. }
  713. void Node::RemoveChild(Node* node)
  714. {
  715. if (!node)
  716. return;
  717. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  718. {
  719. if (*i == node)
  720. {
  721. RemoveChild(i);
  722. return;
  723. }
  724. }
  725. }
  726. void Node::RemoveAllChildren()
  727. {
  728. RemoveChildren(true, true, true);
  729. }
  730. void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
  731. {
  732. unsigned numRemoved = 0;
  733. for (unsigned i = children_.Size() - 1; i < children_.Size(); --i)
  734. {
  735. bool remove = false;
  736. Node* childNode = children_[i];
  737. if (recursive)
  738. childNode->RemoveChildren(removeReplicated, removeLocal, true);
  739. if (childNode->GetID() < FIRST_LOCAL_ID && removeReplicated)
  740. remove = true;
  741. else if (childNode->GetID() >= FIRST_LOCAL_ID && removeLocal)
  742. remove = true;
  743. if (remove)
  744. {
  745. RemoveChild(children_.Begin() + i);
  746. ++numRemoved;
  747. }
  748. }
  749. // Mark node dirty in all replication states
  750. if (numRemoved)
  751. MarkReplicationDirty();
  752. }
  753. // ATOMIC BEGIN
  754. Component* Node::CreateComponentInternal(StringHash type, CreateMode mode, unsigned id, const XMLElement& source)
  755. {
  756. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  757. // as replicated components are synced over
  758. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  759. mode = LOCAL;
  760. // Check that creation succeeds and that the object in fact is a component
  761. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type, source));
  762. if (!newComponent)
  763. {
  764. ATOMIC_LOGERROR("Could not create unknown component type " + type.ToString());
  765. return 0;
  766. }
  767. AddComponent(newComponent, id, mode);
  768. return newComponent;
  769. }
  770. Component* Node::CreateComponent(StringHash type, CreateMode mode, unsigned id)
  771. {
  772. return CreateComponentInternal(type, mode, id);
  773. }
  774. // ATOMIC END
  775. Component* Node::GetOrCreateComponent(StringHash type, CreateMode mode, unsigned id)
  776. {
  777. Component* oldComponent = GetComponent(type);
  778. if (oldComponent)
  779. return oldComponent;
  780. else
  781. return CreateComponent(type, mode, id);
  782. }
  783. Component* Node::CloneComponent(Component* component, unsigned id)
  784. {
  785. if (!component)
  786. {
  787. ATOMIC_LOGERROR("Null source component given for CloneComponent");
  788. return 0;
  789. }
  790. return CloneComponent(component, component->GetID() < FIRST_LOCAL_ID ? REPLICATED : LOCAL, id);
  791. }
  792. Component* Node::CloneComponent(Component* component, CreateMode mode, unsigned id)
  793. {
  794. if (!component)
  795. {
  796. ATOMIC_LOGERROR("Null source component given for CloneComponent");
  797. return 0;
  798. }
  799. Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0);
  800. if (!cloneComponent)
  801. {
  802. ATOMIC_LOGERROR("Could not clone component " + component->GetTypeName());
  803. return 0;
  804. }
  805. const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
  806. const Vector<AttributeInfo>* cloneAttributes = cloneComponent->GetAttributes();
  807. if (compAttributes)
  808. {
  809. for (unsigned i = 0; i < compAttributes->Size() && i < cloneAttributes->Size(); ++i)
  810. {
  811. const AttributeInfo& attr = compAttributes->At(i);
  812. const AttributeInfo& cloneAttr = cloneAttributes->At(i);
  813. if (attr.mode_ & AM_FILE)
  814. {
  815. Variant value;
  816. component->OnGetAttribute(attr, value);
  817. // Note: when eg. a ScriptInstance component is cloned, its script object attributes are unique and therefore we
  818. // can not simply refer to the source component's AttributeInfo
  819. cloneComponent->OnSetAttribute(cloneAttr, value);
  820. }
  821. }
  822. cloneComponent->ApplyAttributes();
  823. }
  824. {
  825. using namespace ComponentCloned;
  826. VariantMap& eventData = GetEventDataMap();
  827. eventData[P_SCENE] = scene_;
  828. eventData[P_COMPONENT] = component;
  829. eventData[P_CLONECOMPONENT] = cloneComponent;
  830. scene_->SendEvent(E_COMPONENTCLONED, eventData);
  831. }
  832. return cloneComponent;
  833. }
  834. void Node::RemoveComponent(Component* component)
  835. {
  836. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  837. {
  838. if (*i == component)
  839. {
  840. RemoveComponent(i);
  841. // Mark node dirty in all replication states
  842. MarkReplicationDirty();
  843. return;
  844. }
  845. }
  846. }
  847. void Node::RemoveComponent(StringHash type)
  848. {
  849. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  850. {
  851. if ((*i)->GetType() == type)
  852. {
  853. RemoveComponent(i);
  854. // Mark node dirty in all replication states
  855. MarkReplicationDirty();
  856. return;
  857. }
  858. }
  859. }
  860. void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
  861. {
  862. unsigned numRemoved = 0;
  863. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  864. {
  865. bool remove = false;
  866. Component* component = components_[i];
  867. if (component->GetID() < FIRST_LOCAL_ID && removeReplicated)
  868. remove = true;
  869. else if (component->GetID() >= FIRST_LOCAL_ID && removeLocal)
  870. remove = true;
  871. if (remove)
  872. {
  873. RemoveComponent(components_.Begin() + i);
  874. ++numRemoved;
  875. }
  876. }
  877. // Mark node dirty in all replication states
  878. if (numRemoved)
  879. MarkReplicationDirty();
  880. }
  881. void Node::RemoveComponents(StringHash type)
  882. {
  883. unsigned numRemoved = 0;
  884. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  885. {
  886. if (components_[i]->GetType() == type)
  887. {
  888. RemoveComponent(components_.Begin() + i);
  889. ++numRemoved;
  890. }
  891. }
  892. // Mark node dirty in all replication states
  893. if (numRemoved)
  894. MarkReplicationDirty();
  895. }
  896. void Node::RemoveAllComponents()
  897. {
  898. RemoveComponents(true, true);
  899. }
  900. void Node::ReorderComponent(Component* component, unsigned index)
  901. {
  902. if (!component || component->GetNode() != this)
  903. return;
  904. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  905. {
  906. if (*i == component)
  907. {
  908. // Need shared ptr to insert. Also, prevent destruction when removing first
  909. SharedPtr<Component> componentShared(component);
  910. components_.Erase(i);
  911. components_.Insert(index, componentShared);
  912. return;
  913. }
  914. }
  915. }
  916. Node* Node::Clone(CreateMode mode)
  917. {
  918. // The scene itself can not be cloned
  919. if (this == scene_ || !parent_)
  920. {
  921. ATOMIC_LOGERROR("Can not clone node without a parent");
  922. return 0;
  923. }
  924. ATOMIC_PROFILE(CloneNode);
  925. SceneResolver resolver;
  926. Node* clone = CloneRecursive(parent_, resolver, mode);
  927. resolver.Resolve();
  928. clone->ApplyAttributes();
  929. return clone;
  930. }
  931. void Node::Remove()
  932. {
  933. if (parent_)
  934. parent_->RemoveChild(this);
  935. }
  936. void Node::SetParent(Node* parent)
  937. {
  938. if (parent)
  939. {
  940. Matrix3x4 oldWorldTransform = GetWorldTransform();
  941. parent->AddChild(this);
  942. if (parent != scene_)
  943. {
  944. Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
  945. SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
  946. }
  947. else
  948. {
  949. // The root node is assumed to have identity transform, so can disregard it
  950. SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
  951. }
  952. }
  953. }
  954. void Node::SetVar(StringHash key, const Variant& value)
  955. {
  956. vars_[key] = value;
  957. MarkNetworkUpdate();
  958. }
  959. void Node::AddListener(Component* component)
  960. {
  961. if (!component)
  962. return;
  963. // Check for not adding twice
  964. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  965. {
  966. if (*i == component)
  967. return;
  968. }
  969. listeners_.Push(WeakPtr<Component>(component));
  970. // If the node is currently dirty, notify immediately
  971. if (dirty_)
  972. component->OnMarkedDirty(this);
  973. }
  974. void Node::RemoveListener(Component* component)
  975. {
  976. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  977. {
  978. if (*i == component)
  979. {
  980. listeners_.Erase(i);
  981. return;
  982. }
  983. }
  984. }
  985. Vector3 Node::LocalToWorld(const Vector3& position) const
  986. {
  987. return GetWorldTransform() * position;
  988. }
  989. Vector3 Node::LocalToWorld(const Vector4& vector) const
  990. {
  991. return GetWorldTransform() * vector;
  992. }
  993. Vector2 Node::LocalToWorld2D(const Vector2& vector) const
  994. {
  995. Vector3 result = LocalToWorld(Vector3(vector));
  996. return Vector2(result.x_, result.y_);
  997. }
  998. Vector3 Node::WorldToLocal(const Vector3& position) const
  999. {
  1000. return GetWorldTransform().Inverse() * position;
  1001. }
  1002. Vector3 Node::WorldToLocal(const Vector4& vector) const
  1003. {
  1004. return GetWorldTransform().Inverse() * vector;
  1005. }
  1006. Vector2 Node::WorldToLocal2D(const Vector2& vector) const
  1007. {
  1008. Vector3 result = WorldToLocal(Vector3(vector));
  1009. return Vector2(result.x_, result.y_);
  1010. }
  1011. unsigned Node::GetNumChildren(bool recursive) const
  1012. {
  1013. if (!recursive)
  1014. return children_.Size();
  1015. else
  1016. {
  1017. unsigned allChildren = children_.Size();
  1018. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1019. allChildren += (*i)->GetNumChildren(true);
  1020. return allChildren;
  1021. }
  1022. }
  1023. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  1024. {
  1025. dest.Clear();
  1026. if (!recursive)
  1027. {
  1028. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1029. dest.Push(*i);
  1030. }
  1031. else
  1032. GetChildrenRecursive(dest);
  1033. }
  1034. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, StringHash type, bool recursive) 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)->HasComponent(type))
  1042. dest.Push(*i);
  1043. }
  1044. }
  1045. else
  1046. GetChildrenWithComponentRecursive(dest, type);
  1047. }
  1048. void Node::GetChildrenWithTag(PODVector<Node*>& dest, const String& tag, bool recursive /*= true*/) const
  1049. {
  1050. dest.Clear();
  1051. if (!recursive)
  1052. {
  1053. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1054. {
  1055. if ((*i)->HasTag(tag))
  1056. dest.Push(*i);
  1057. }
  1058. }
  1059. else
  1060. GetChildrenWithTagRecursive(dest, tag);
  1061. }
  1062. Node* Node::GetChild(unsigned index) const
  1063. {
  1064. return index < children_.Size() ? children_[index].Get() : 0;
  1065. }
  1066. Node* Node::GetChild(const String& name, bool recursive) const
  1067. {
  1068. return GetChild(StringHash(name), recursive);
  1069. }
  1070. Node* Node::GetChild(const char* name, bool recursive) const
  1071. {
  1072. return GetChild(StringHash(name), recursive);
  1073. }
  1074. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  1075. {
  1076. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1077. {
  1078. if ((*i)->GetNameHash() == nameHash)
  1079. return *i;
  1080. if (recursive)
  1081. {
  1082. Node* node = (*i)->GetChild(nameHash, true);
  1083. if (node)
  1084. return node;
  1085. }
  1086. }
  1087. return 0;
  1088. }
  1089. unsigned Node::GetNumNetworkComponents() const
  1090. {
  1091. unsigned num = 0;
  1092. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1093. {
  1094. if ((*i)->GetID() < FIRST_LOCAL_ID)
  1095. ++num;
  1096. }
  1097. return num;
  1098. }
  1099. void Node::GetComponents(PODVector<Component*>& dest, StringHash type, bool recursive) const
  1100. {
  1101. dest.Clear();
  1102. // ATOMIC BEGIN
  1103. bool all = type == Component::GetTypeStatic();
  1104. if (!recursive)
  1105. {
  1106. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1107. {
  1108. if (all || (*i)->GetType() == type)
  1109. dest.Push(*i);
  1110. }
  1111. }
  1112. else
  1113. GetComponentsRecursive(dest, type);
  1114. // ATOMIC END
  1115. }
  1116. bool Node::HasComponent(StringHash type) const
  1117. {
  1118. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1119. {
  1120. if ((*i)->GetType() == type)
  1121. return true;
  1122. }
  1123. return false;
  1124. }
  1125. bool Node::HasTag(const String& tag) const
  1126. {
  1127. return tags_.Contains(tag);
  1128. }
  1129. const Variant& Node::GetVar(StringHash key) const
  1130. {
  1131. VariantMap::ConstIterator i = vars_.Find(key);
  1132. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1133. }
  1134. Component* Node::GetComponent(StringHash type, bool recursive) const
  1135. {
  1136. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1137. {
  1138. if ((*i)->GetType() == type)
  1139. return *i;
  1140. }
  1141. if (recursive)
  1142. {
  1143. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1144. {
  1145. Component* component = (*i)->GetComponent(type, true);
  1146. if (component)
  1147. return component;
  1148. }
  1149. }
  1150. return 0;
  1151. }
  1152. Component* Node::GetParentComponent(StringHash type, bool fullTraversal) const
  1153. {
  1154. Node* current = GetParent();
  1155. while (current)
  1156. {
  1157. Component* soughtComponent = current->GetComponent(type);
  1158. if (soughtComponent)
  1159. return soughtComponent;
  1160. if (fullTraversal)
  1161. current = current->GetParent();
  1162. else
  1163. break;
  1164. }
  1165. return 0;
  1166. }
  1167. void Node::SetID(unsigned id)
  1168. {
  1169. id_ = id;
  1170. }
  1171. void Node::SetScene(Scene* scene)
  1172. {
  1173. scene_ = scene;
  1174. }
  1175. void Node::ResetScene()
  1176. {
  1177. SetID(0);
  1178. SetScene(0);
  1179. SetOwner(0);
  1180. }
  1181. void Node::SetNetPositionAttr(const Vector3& value)
  1182. {
  1183. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  1184. if (transform)
  1185. transform->SetTargetPosition(value);
  1186. else
  1187. SetPosition(value);
  1188. }
  1189. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  1190. {
  1191. MemoryBuffer buf(value);
  1192. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  1193. if (transform)
  1194. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  1195. else
  1196. SetRotation(buf.ReadPackedQuaternion());
  1197. }
  1198. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  1199. {
  1200. Scene* scene = GetScene();
  1201. if (!scene)
  1202. return;
  1203. MemoryBuffer buf(value);
  1204. // If nothing in the buffer, parent is the root node
  1205. if (buf.IsEof())
  1206. {
  1207. scene->AddChild(this);
  1208. return;
  1209. }
  1210. unsigned baseNodeID = buf.ReadNetID();
  1211. Node* baseNode = scene->GetNode(baseNodeID);
  1212. if (!baseNode)
  1213. {
  1214. ATOMIC_LOGWARNING("Failed to find parent node " + String(baseNodeID));
  1215. return;
  1216. }
  1217. // If buffer contains just an ID, the parent is replicated and we are done
  1218. if (buf.IsEof())
  1219. baseNode->AddChild(this);
  1220. else
  1221. {
  1222. // Else the parent is local and we must find it recursively by name hash
  1223. StringHash nameHash = buf.ReadStringHash();
  1224. Node* parentNode = baseNode->GetChild(nameHash, true);
  1225. if (!parentNode)
  1226. ATOMIC_LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  1227. else
  1228. parentNode->AddChild(this);
  1229. }
  1230. }
  1231. const Vector3& Node::GetNetPositionAttr() const
  1232. {
  1233. return position_;
  1234. }
  1235. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  1236. {
  1237. attrBuffer_.Clear();
  1238. attrBuffer_.WritePackedQuaternion(rotation_);
  1239. return attrBuffer_.GetBuffer();
  1240. }
  1241. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  1242. {
  1243. attrBuffer_.Clear();
  1244. Scene* scene = GetScene();
  1245. if (scene && parent_ && parent_ != scene)
  1246. {
  1247. // If parent is replicated, can write the ID directly
  1248. unsigned parentID = parent_->GetID();
  1249. if (parentID < FIRST_LOCAL_ID)
  1250. attrBuffer_.WriteNetID(parentID);
  1251. else
  1252. {
  1253. // Parent is local: traverse hierarchy to find a non-local base node
  1254. // This iteration always stops due to the scene (root) being non-local
  1255. Node* current = parent_;
  1256. while (current->GetID() >= FIRST_LOCAL_ID)
  1257. current = current->GetParent();
  1258. // Then write the base node ID and the parent's name hash
  1259. attrBuffer_.WriteNetID(current->GetID());
  1260. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  1261. }
  1262. }
  1263. return attrBuffer_.GetBuffer();
  1264. }
  1265. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1266. {
  1267. // Remove all children and components first in case this is not a fresh load
  1268. RemoveAllChildren();
  1269. RemoveAllComponents();
  1270. // ID has been read at the parent level
  1271. if (!Animatable::Load(source))
  1272. return false;
  1273. unsigned numComponents = source.ReadVLE();
  1274. for (unsigned i = 0; i < numComponents; ++i)
  1275. {
  1276. VectorBuffer compBuffer(source, source.ReadVLE());
  1277. StringHash compType = compBuffer.ReadStringHash();
  1278. unsigned compID = compBuffer.ReadUInt();
  1279. Component* newComponent = SafeCreateComponent(String::EMPTY, compType,
  1280. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1281. if (newComponent)
  1282. {
  1283. resolver.AddComponent(compID, newComponent);
  1284. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  1285. newComponent->Load(compBuffer);
  1286. }
  1287. }
  1288. if (!readChildren)
  1289. return true;
  1290. unsigned numChildren = source.ReadVLE();
  1291. for (unsigned i = 0; i < numChildren; ++i)
  1292. {
  1293. unsigned nodeID = source.ReadUInt();
  1294. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1295. LOCAL);
  1296. resolver.AddNode(nodeID, newNode);
  1297. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  1298. return false;
  1299. }
  1300. return true;
  1301. }
  1302. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1303. {
  1304. // Remove all children and components first in case this is not a fresh load
  1305. RemoveAllChildren();
  1306. RemoveAllComponents();
  1307. if (!Animatable::LoadXML(source))
  1308. return false;
  1309. XMLElement compElem = source.GetChild("component");
  1310. while (compElem)
  1311. {
  1312. String typeName = compElem.GetAttribute("type");
  1313. unsigned compID = compElem.GetUInt("id");
  1314. // ATOMIC BEGIN
  1315. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1316. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID, compElem);
  1317. // ATOMIC END
  1318. if (newComponent)
  1319. {
  1320. resolver.AddComponent(compID, newComponent);
  1321. if (!newComponent->LoadXML(compElem))
  1322. return false;
  1323. }
  1324. compElem = compElem.GetNext("component");
  1325. }
  1326. if (!readChildren)
  1327. return true;
  1328. XMLElement childElem = source.GetChild("node");
  1329. while (childElem)
  1330. {
  1331. unsigned nodeID = childElem.GetUInt("id");
  1332. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1333. LOCAL);
  1334. resolver.AddNode(nodeID, newNode);
  1335. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  1336. return false;
  1337. childElem = childElem.GetNext("node");
  1338. }
  1339. return true;
  1340. }
  1341. bool Node::LoadJSON(const JSONValue& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1342. {
  1343. // Remove all children and components first in case this is not a fresh load
  1344. RemoveAllChildren();
  1345. RemoveAllComponents();
  1346. if (!Animatable::LoadJSON(source))
  1347. return false;
  1348. const JSONArray& componentsArray = source.Get("components").GetArray();
  1349. for (unsigned i = 0; i < componentsArray.Size(); i++)
  1350. {
  1351. const JSONValue& compVal = componentsArray.At(i);
  1352. String typeName = compVal.Get("type").GetString();
  1353. unsigned compID = compVal.Get("id").GetUInt();
  1354. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1355. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1356. if (newComponent)
  1357. {
  1358. resolver.AddComponent(compID, newComponent);
  1359. if (!newComponent->LoadJSON(compVal))
  1360. return false;
  1361. }
  1362. }
  1363. if (!readChildren)
  1364. return true;
  1365. const JSONArray& childrenArray = source.Get("children").GetArray();
  1366. for (unsigned i = 0; i < childrenArray.Size(); i++)
  1367. {
  1368. const JSONValue& childVal = childrenArray.At(i);
  1369. unsigned nodeID = childVal.Get("id").GetUInt();
  1370. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1371. LOCAL);
  1372. resolver.AddNode(nodeID, newNode);
  1373. if (!newNode->LoadJSON(childVal, resolver, readChildren, rewriteIDs, mode))
  1374. return false;
  1375. }
  1376. return true;
  1377. }
  1378. void Node::PrepareNetworkUpdate()
  1379. {
  1380. // Update dependency nodes list first
  1381. dependencyNodes_.Clear();
  1382. // Add the parent node, but if it is local, traverse to the first non-local node
  1383. if (parent_ && parent_ != scene_)
  1384. {
  1385. Node* current = parent_;
  1386. while (current->id_ >= FIRST_LOCAL_ID)
  1387. current = current->parent_;
  1388. if (current && current != scene_)
  1389. dependencyNodes_.Push(current);
  1390. }
  1391. // Let the components add their dependencies
  1392. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1393. {
  1394. Component* component = *i;
  1395. if (component->GetID() < FIRST_LOCAL_ID)
  1396. component->GetDependencyNodes(dependencyNodes_);
  1397. }
  1398. // Then check for node attribute changes
  1399. if (!networkState_)
  1400. AllocateNetworkState();
  1401. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  1402. unsigned numAttributes = attributes->Size();
  1403. // Check for attribute changes
  1404. for (unsigned i = 0; i < numAttributes; ++i)
  1405. {
  1406. const AttributeInfo& attr = attributes->At(i);
  1407. if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
  1408. continue;
  1409. OnGetAttribute(attr, networkState_->currentValues_[i]);
  1410. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  1411. {
  1412. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  1413. // Mark the attribute dirty in all replication states that are tracking this node
  1414. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1415. j != networkState_->replicationStates_.End(); ++j)
  1416. {
  1417. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1418. nodeState->dirtyAttributes_.Set(i);
  1419. // Add node to the dirty set if not added yet
  1420. if (!nodeState->markedDirty_)
  1421. {
  1422. nodeState->markedDirty_ = true;
  1423. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1424. }
  1425. }
  1426. }
  1427. }
  1428. // Finally check for user var changes
  1429. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  1430. {
  1431. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  1432. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  1433. {
  1434. networkState_->previousVars_[i->first_] = i->second_;
  1435. // Mark the var dirty in all replication states that are tracking this node
  1436. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1437. j != networkState_->replicationStates_.End(); ++j)
  1438. {
  1439. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1440. nodeState->dirtyVars_.Insert(i->first_);
  1441. if (!nodeState->markedDirty_)
  1442. {
  1443. nodeState->markedDirty_ = true;
  1444. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1445. }
  1446. }
  1447. }
  1448. }
  1449. networkUpdate_ = false;
  1450. }
  1451. void Node::CleanupConnection(Connection* connection)
  1452. {
  1453. if (owner_ == connection)
  1454. owner_ = 0;
  1455. if (networkState_)
  1456. {
  1457. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  1458. {
  1459. if (networkState_->replicationStates_[i]->connection_ == connection)
  1460. networkState_->replicationStates_.Erase(i);
  1461. }
  1462. }
  1463. }
  1464. void Node::MarkReplicationDirty()
  1465. {
  1466. if (networkState_)
  1467. {
  1468. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1469. j != networkState_->replicationStates_.End(); ++j)
  1470. {
  1471. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1472. if (!nodeState->markedDirty_)
  1473. {
  1474. nodeState->markedDirty_ = true;
  1475. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1476. }
  1477. }
  1478. }
  1479. }
  1480. Node* Node::CreateChild(unsigned id, CreateMode mode)
  1481. {
  1482. SharedPtr<Node> newNode(new Node(context_));
  1483. // If zero ID specified, or the ID is already taken, let the scene assign
  1484. if (scene_)
  1485. {
  1486. if (!id || scene_->GetNode(id))
  1487. id = scene_->GetFreeNodeID(mode);
  1488. newNode->SetID(id);
  1489. }
  1490. else
  1491. newNode->SetID(id);
  1492. AddChild(newNode);
  1493. return newNode;
  1494. }
  1495. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1496. {
  1497. if (!component)
  1498. return;
  1499. components_.Push(SharedPtr<Component>(component));
  1500. if (component->GetNode())
  1501. ATOMIC_LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!");
  1502. component->SetNode(this);
  1503. // If zero ID specified, or the ID is already taken, let the scene assign
  1504. if (scene_)
  1505. {
  1506. if (!id || scene_->GetComponent(id))
  1507. id = scene_->GetFreeComponentID(mode);
  1508. component->SetID(id);
  1509. scene_->ComponentAdded(component);
  1510. }
  1511. else
  1512. component->SetID(id);
  1513. component->OnMarkedDirty(this);
  1514. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1515. component->MarkNetworkUpdate();
  1516. MarkNetworkUpdate();
  1517. MarkReplicationDirty();
  1518. // Send change event
  1519. if (scene_)
  1520. {
  1521. using namespace ComponentAdded;
  1522. VariantMap& eventData = GetEventDataMap();
  1523. eventData[P_SCENE] = scene_;
  1524. eventData[P_NODE] = this;
  1525. eventData[P_COMPONENT] = component;
  1526. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1527. }
  1528. }
  1529. unsigned Node::GetNumPersistentChildren() const
  1530. {
  1531. unsigned ret = 0;
  1532. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1533. {
  1534. if (!(*i)->IsTemporary())
  1535. ++ret;
  1536. }
  1537. return ret;
  1538. }
  1539. unsigned Node::GetNumPersistentComponents() const
  1540. {
  1541. unsigned ret = 0;
  1542. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1543. {
  1544. if (!(*i)->IsTemporary())
  1545. ++ret;
  1546. }
  1547. return ret;
  1548. }
  1549. void Node::SetTransformSilent(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  1550. {
  1551. position_ = position;
  1552. rotation_ = rotation;
  1553. scale_ = scale;
  1554. }
  1555. void Node::OnAttributeAnimationAdded()
  1556. {
  1557. if (attributeAnimationInfos_.Size() == 1)
  1558. SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, ATOMIC_HANDLER(Node, HandleAttributeAnimationUpdate));
  1559. }
  1560. void Node::OnAttributeAnimationRemoved()
  1561. {
  1562. if (attributeAnimationInfos_.Empty())
  1563. UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
  1564. }
  1565. Animatable* Node::FindAttributeAnimationTarget(const String& name, String& outName)
  1566. {
  1567. Vector<String> names = name.Split('/');
  1568. // Only attribute name
  1569. if (names.Size() == 1)
  1570. {
  1571. outName = name;
  1572. return this;
  1573. }
  1574. else
  1575. {
  1576. // Name must in following format: "#0/#1/@component#0/attribute"
  1577. Node* node = this;
  1578. unsigned i = 0;
  1579. for (; i < names.Size() - 1; ++i)
  1580. {
  1581. if (names[i].Front() != '#')
  1582. break;
  1583. unsigned index = ToUInt(names[i].Substring(1, names[i].Length() - 1));
  1584. node = node->GetChild(index);
  1585. if (!node)
  1586. {
  1587. ATOMIC_LOGERROR("Could not find node by name " + name);
  1588. return 0;
  1589. }
  1590. }
  1591. if (i == names.Size() - 1)
  1592. {
  1593. outName = names.Back();
  1594. return node;
  1595. }
  1596. if (i != names.Size() - 2 || names[i].Front() != '@')
  1597. {
  1598. ATOMIC_LOGERROR("Invalid name " + name);
  1599. return 0;
  1600. }
  1601. String componentName = names[i].Substring(1, names[i].Length() - 1);
  1602. Vector<String> componentNames = componentName.Split('#');
  1603. if (componentNames.Size() == 1)
  1604. {
  1605. Component* component = node->GetComponent(StringHash(componentNames.Front()));
  1606. if (!component)
  1607. {
  1608. ATOMIC_LOGERROR("Could not find component by name " + name);
  1609. return 0;
  1610. }
  1611. outName = names.Back();
  1612. return component;
  1613. }
  1614. else
  1615. {
  1616. unsigned index = ToUInt(componentNames[1]);
  1617. PODVector<Component*> components;
  1618. node->GetComponents(components, StringHash(componentNames.Front()));
  1619. if (index >= components.Size())
  1620. {
  1621. ATOMIC_LOGERROR("Could not find component by name " + name);
  1622. return 0;
  1623. }
  1624. outName = names.Back();
  1625. return components[index];
  1626. }
  1627. }
  1628. }
  1629. void Node::SetEnabled(bool enable, bool recursive, bool storeSelf)
  1630. {
  1631. // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
  1632. if (GetType() == Scene::GetTypeStatic())
  1633. {
  1634. ATOMIC_LOGERROR("Can not change enabled state of the Scene");
  1635. return;
  1636. }
  1637. if (storeSelf)
  1638. enabledPrev_ = enable;
  1639. if (enable != enabled_)
  1640. {
  1641. enabled_ = enable;
  1642. MarkNetworkUpdate();
  1643. // Notify listener components of the state change
  1644. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  1645. {
  1646. if (*i)
  1647. {
  1648. (*i)->OnNodeSetEnabled(this);
  1649. ++i;
  1650. }
  1651. // If listener has expired, erase from list
  1652. else
  1653. i = listeners_.Erase(i);
  1654. }
  1655. // Send change event
  1656. if (scene_)
  1657. {
  1658. using namespace NodeEnabledChanged;
  1659. VariantMap& eventData = GetEventDataMap();
  1660. eventData[P_SCENE] = scene_;
  1661. eventData[P_NODE] = this;
  1662. scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
  1663. }
  1664. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  1665. {
  1666. (*i)->OnSetEnabled();
  1667. // Send change event for the component
  1668. if (scene_)
  1669. {
  1670. using namespace ComponentEnabledChanged;
  1671. VariantMap& eventData = GetEventDataMap();
  1672. eventData[P_SCENE] = scene_;
  1673. eventData[P_NODE] = this;
  1674. eventData[P_COMPONENT] = (*i);
  1675. scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
  1676. }
  1677. }
  1678. }
  1679. if (recursive)
  1680. {
  1681. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1682. (*i)->SetEnabled(enable, recursive, storeSelf);
  1683. }
  1684. }
  1685. // ATOMIC BEGIN
  1686. Component* Node::SafeCreateComponent(const String& typeName, StringHash type, CreateMode mode, unsigned id, const XMLElement& source)
  1687. {
  1688. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  1689. // as replicated components are synced over
  1690. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  1691. mode = LOCAL;
  1692. // First check if factory for type exists
  1693. if (!context_->GetTypeName(type).Empty())
  1694. return CreateComponentInternal(type, mode, id, source);
  1695. else
  1696. {
  1697. ATOMIC_LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder");
  1698. // Else create as UnknownComponent
  1699. SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
  1700. if (typeName.Empty() || typeName.StartsWith("Unknown", false))
  1701. newComponent->SetType(type);
  1702. else
  1703. newComponent->SetTypeName(typeName);
  1704. AddComponent(newComponent, id, mode);
  1705. return newComponent;
  1706. }
  1707. }
  1708. // ATOMIC END
  1709. void Node::UpdateWorldTransform() const
  1710. {
  1711. Matrix3x4 transform = GetTransform();
  1712. // Assume the root node (scene) has identity transform
  1713. if (parent_ == scene_ || !parent_)
  1714. {
  1715. worldTransform_ = transform;
  1716. worldRotation_ = rotation_;
  1717. }
  1718. else
  1719. {
  1720. worldTransform_ = parent_->GetWorldTransform() * transform;
  1721. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1722. }
  1723. dirty_ = false;
  1724. }
  1725. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1726. {
  1727. // Send change event. Do not send when already being destroyed
  1728. Node* child = *i;
  1729. if (Refs() > 0 && scene_)
  1730. {
  1731. using namespace NodeRemoved;
  1732. VariantMap& eventData = GetEventDataMap();
  1733. eventData[P_SCENE] = scene_;
  1734. eventData[P_PARENT] = this;
  1735. eventData[P_NODE] = child;
  1736. scene_->SendEvent(E_NODEREMOVED, eventData);
  1737. }
  1738. child->parent_ = 0;
  1739. child->MarkDirty();
  1740. child->MarkNetworkUpdate();
  1741. if (scene_)
  1742. scene_->NodeRemoved(child);
  1743. children_.Erase(i);
  1744. }
  1745. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1746. {
  1747. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1748. {
  1749. Node* node = *i;
  1750. dest.Push(node);
  1751. if (!node->children_.Empty())
  1752. node->GetChildrenRecursive(dest);
  1753. }
  1754. }
  1755. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, StringHash type) const
  1756. {
  1757. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1758. {
  1759. Node* node = *i;
  1760. if (node->HasComponent(type))
  1761. dest.Push(node);
  1762. if (!node->children_.Empty())
  1763. node->GetChildrenWithComponentRecursive(dest, type);
  1764. }
  1765. }
  1766. void Node::GetComponentsRecursive(PODVector<Component*>& dest, StringHash type) const
  1767. {
  1768. // ATOMIC BEGIN
  1769. bool all = type == Component::GetTypeStatic();
  1770. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1771. {
  1772. if (all || (*i)->GetType() == type)
  1773. dest.Push(*i);
  1774. }
  1775. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1776. (*i)->GetComponentsRecursive(dest, type);
  1777. // ATOMIC END
  1778. }
  1779. void Node::GetChildrenWithTagRecursive(PODVector<Node*>& dest, const String& tag) const
  1780. {
  1781. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1782. {
  1783. Node* node = *i;
  1784. if (node->HasTag(tag))
  1785. dest.Push(node);
  1786. if (!node->children_.Empty())
  1787. node->GetChildrenWithTagRecursive(dest, tag);
  1788. }
  1789. }
  1790. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1791. {
  1792. // Create clone node
  1793. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1794. resolver.AddNode(id_, cloneNode);
  1795. // Copy attributes
  1796. const Vector<AttributeInfo>* attributes = GetAttributes();
  1797. for (unsigned j = 0; j < attributes->Size(); ++j)
  1798. {
  1799. const AttributeInfo& attr = attributes->At(j);
  1800. // Do not copy network-only attributes, as they may have unintended side effects
  1801. if (attr.mode_ & AM_FILE)
  1802. {
  1803. Variant value;
  1804. OnGetAttribute(attr, value);
  1805. cloneNode->OnSetAttribute(attr, value);
  1806. }
  1807. }
  1808. // Clone components
  1809. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1810. {
  1811. Component* component = *i;
  1812. if (component->IsTemporary())
  1813. continue;
  1814. Component* cloneComponent = cloneNode->CloneComponent(component,
  1815. (mode == REPLICATED && component->GetID() < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, 0);
  1816. if (cloneComponent)
  1817. resolver.AddComponent(component->GetID(), cloneComponent);
  1818. }
  1819. // Clone child nodes recursively
  1820. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1821. {
  1822. Node* node = *i;
  1823. if (node->IsTemporary())
  1824. continue;
  1825. node->CloneRecursive(cloneNode, resolver, mode);
  1826. }
  1827. {
  1828. using namespace NodeCloned;
  1829. VariantMap& eventData = GetEventDataMap();
  1830. eventData[P_SCENE] = scene_;
  1831. eventData[P_NODE] = this;
  1832. eventData[P_CLONENODE] = cloneNode;
  1833. scene_->SendEvent(E_NODECLONED, eventData);
  1834. }
  1835. return cloneNode;
  1836. }
  1837. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1838. {
  1839. // Send node change event. Do not send when already being destroyed
  1840. if (Refs() > 0 && scene_)
  1841. {
  1842. using namespace ComponentRemoved;
  1843. VariantMap& eventData = GetEventDataMap();
  1844. eventData[P_SCENE] = scene_;
  1845. eventData[P_NODE] = this;
  1846. eventData[P_COMPONENT] = (*i).Get();
  1847. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1848. }
  1849. RemoveListener(*i);
  1850. if (scene_)
  1851. scene_->ComponentRemoved(*i);
  1852. (*i)->SetNode(0);
  1853. components_.Erase(i);
  1854. }
  1855. void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1856. {
  1857. using namespace AttributeAnimationUpdate;
  1858. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1859. }
  1860. // ATOMIC BEGIN
  1861. void Node::GetChildrenWithName(PODVector<Node*>& dest, const String& name, bool recursive) const
  1862. {
  1863. GetChildrenWithName(dest, StringHash(name), recursive);
  1864. }
  1865. void Node::GetChildrenWithName(PODVector<Node*>& dest, const char* name, bool recursive) const
  1866. {
  1867. GetChildrenWithName(dest, StringHash(name), recursive);
  1868. }
  1869. void Node::GetChildrenWithName(PODVector<Node*>& dest, StringHash nameHash, bool recursive) const
  1870. {
  1871. dest.Clear();
  1872. if (!recursive)
  1873. {
  1874. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1875. {
  1876. if ((*i)->GetNameHash() == nameHash)
  1877. dest.Push(*i);
  1878. }
  1879. }
  1880. else
  1881. GetChildrenWithNameRecursive(dest, nameHash);
  1882. }
  1883. void Node::GetChildrenWithNameRecursive(PODVector<Node*>& dest, StringHash nameHash) const
  1884. {
  1885. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1886. {
  1887. Node* node = *i;
  1888. if (node->GetNameHash() == nameHash)
  1889. dest.Push(node);
  1890. if (!node->children_.Empty())
  1891. node->GetChildrenWithNameRecursive(dest, nameHash);
  1892. }
  1893. }
  1894. // ATOMIC END
  1895. }