Node.cpp 64 KB

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