Node.cpp 63 KB

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