Node.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  1. //
  2. // Copyright (c) 2008-2013 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 "Component.h"
  24. #include "Context.h"
  25. #include "Log.h"
  26. #include "MemoryBuffer.h"
  27. #include "Profiler.h"
  28. #include "ReplicationState.h"
  29. #include "Scene.h"
  30. #include "SceneEvents.h"
  31. #include "SmoothedTransform.h"
  32. #include "XMLFile.h"
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. // Normalize rotation quaternion after this many incremental updates to prevent distortion
  37. static const int NORMALIZE_ROTATION_EVERY = 32;
  38. OBJECTTYPESTATIC(Node);
  39. Node::Node(Context* context) :
  40. Serializable(context),
  41. worldTransform_(Matrix3x4::IDENTITY),
  42. dirty_(false),
  43. networkUpdate_(false),
  44. rotateCount_(0),
  45. parent_(0),
  46. scene_(0),
  47. id_(0),
  48. position_(Vector3::ZERO),
  49. rotation_(Quaternion::IDENTITY),
  50. scale_(Vector3::ONE),
  51. owner_(0)
  52. {
  53. }
  54. Node::~Node()
  55. {
  56. RemoveAllChildren();
  57. RemoveAllComponents();
  58. // Remove from the scene
  59. if (scene_)
  60. scene_->NodeRemoved(this);
  61. }
  62. void Node::RegisterObject(Context* context)
  63. {
  64. context->RegisterFactory<Node>();
  65. /// \todo When position/rotation updates are received from the network, route to SmoothedTransform if exists
  66. REF_ACCESSOR_ATTRIBUTE(Node, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  67. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
  68. REF_ACCESSOR_ATTRIBUTE(Node, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  69. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  70. ATTRIBUTE(Node, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  71. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  72. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  73. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  74. }
  75. void Node::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  76. {
  77. Serializable::OnSetAttribute(attr, src);
  78. MarkNetworkUpdate();
  79. }
  80. bool Node::Load(Deserializer& source)
  81. {
  82. SceneResolver resolver;
  83. // Read own ID. Will not be applied, only stored for resolving possible references
  84. unsigned nodeID = source.ReadInt();
  85. resolver.AddNode(nodeID, this);
  86. // Read attributes, components and child nodes
  87. bool success = Load(source, resolver);
  88. if (success)
  89. {
  90. resolver.Resolve();
  91. ApplyAttributes();
  92. }
  93. return success;
  94. }
  95. bool Node::Save(Serializer& dest)
  96. {
  97. // Write node ID
  98. if (!dest.WriteUInt(id_))
  99. return false;
  100. // Write attributes
  101. if (!Serializable::Save(dest))
  102. return false;
  103. // Write components
  104. dest.WriteVLE(components_.Size());
  105. for (unsigned i = 0; i < components_.Size(); ++i)
  106. {
  107. Component* component = components_[i];
  108. // Create a separate buffer to be able to skip unknown components during deserialization
  109. VectorBuffer compBuffer;
  110. if (!component->Save(compBuffer))
  111. return false;
  112. dest.WriteVLE(compBuffer.GetSize());
  113. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  114. }
  115. // Write child nodes
  116. dest.WriteVLE(children_.Size());
  117. for (unsigned i = 0; i < children_.Size(); ++i)
  118. {
  119. Node* node = children_[i];
  120. if (!node->Save(dest))
  121. return false;
  122. }
  123. return true;
  124. }
  125. bool Node::LoadXML(const XMLElement& source)
  126. {
  127. SceneResolver resolver;
  128. // Read own ID. Will not be applied, only stored for resolving possible references
  129. unsigned nodeID = source.GetInt("id");
  130. resolver.AddNode(nodeID, this);
  131. // Read attributes, components and child nodes
  132. bool success = LoadXML(source, resolver);
  133. if (success)
  134. {
  135. resolver.Resolve();
  136. ApplyAttributes();
  137. }
  138. return success;
  139. }
  140. bool Node::SaveXML(XMLElement& dest)
  141. {
  142. // Write node ID
  143. if (!dest.SetInt("id", id_))
  144. return false;
  145. // Write attributes
  146. if (!Serializable::SaveXML(dest))
  147. return false;
  148. // Write components
  149. for (unsigned i = 0; i < components_.Size(); ++i)
  150. {
  151. Component* component = components_[i];
  152. XMLElement compElem = dest.CreateChild("component");
  153. if (!component->SaveXML(compElem))
  154. return false;
  155. }
  156. // Write child nodes
  157. for (unsigned i = 0; i < children_.Size(); ++i)
  158. {
  159. Node* node = children_[i];
  160. XMLElement childElem = dest.CreateChild("node");
  161. if (!node->SaveXML(childElem))
  162. return false;
  163. }
  164. return true;
  165. }
  166. void Node::ApplyAttributes()
  167. {
  168. for (unsigned i = 0; i < components_.Size(); ++i)
  169. components_[i]->ApplyAttributes();
  170. for (unsigned i = 0; i < children_.Size(); ++i)
  171. children_[i]->ApplyAttributes();
  172. }
  173. void Node::AddReplicationState(NodeReplicationState* state)
  174. {
  175. if (!networkState_)
  176. AllocateNetworkState();
  177. networkState_->replicationStates_.Push(state);
  178. }
  179. bool Node::SaveXML(Serializer& dest)
  180. {
  181. SharedPtr<XMLFile> xml(new XMLFile(context_));
  182. XMLElement rootElem = xml->CreateRoot("node");
  183. if (!SaveXML(rootElem))
  184. return false;
  185. return xml->Save(dest);
  186. }
  187. void Node::SetName(const String& name)
  188. {
  189. name_ = name;
  190. nameHash_ = StringHash(name);
  191. MarkNetworkUpdate();
  192. // Send change event
  193. if (scene_)
  194. {
  195. using namespace NodeNameChanged;
  196. VariantMap eventData;
  197. eventData[P_SCENE] = (void*)scene_;
  198. eventData[P_NODE] = (void*)this;
  199. scene_->SendEvent(E_NODENAMECHANGED, eventData);
  200. }
  201. }
  202. void Node::SetPosition(const Vector3& position)
  203. {
  204. position_ = position;
  205. MarkDirty();
  206. MarkNetworkUpdate();
  207. }
  208. void Node::SetRotation(const Quaternion& rotation)
  209. {
  210. rotation_ = rotation;
  211. rotateCount_ = 0;
  212. MarkDirty();
  213. MarkNetworkUpdate();
  214. }
  215. void Node::SetDirection(const Vector3& direction)
  216. {
  217. SetRotation(Quaternion(Vector3::FORWARD, direction));
  218. }
  219. void Node::SetScale(float scale)
  220. {
  221. SetScale(Vector3(scale, scale, scale));
  222. }
  223. void Node::SetScale(const Vector3& scale)
  224. {
  225. scale_ = scale.Abs();
  226. MarkDirty();
  227. MarkNetworkUpdate();
  228. }
  229. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  230. {
  231. position_ = position;
  232. rotation_ = rotation;
  233. rotateCount_ = 0;
  234. MarkDirty();
  235. MarkNetworkUpdate();
  236. }
  237. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  238. {
  239. SetTransform(position, rotation, Vector3(scale, scale, scale));
  240. }
  241. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  242. {
  243. position_ = position;
  244. rotation_ = rotation;
  245. rotateCount_ = 0;
  246. scale_ = scale;
  247. MarkDirty();
  248. MarkNetworkUpdate();
  249. }
  250. void Node::SetWorldPosition(const Vector3& position)
  251. {
  252. if (!parent_)
  253. SetPosition(position);
  254. else
  255. SetPosition(parent_->GetWorldTransform().Inverse() * position);
  256. }
  257. void Node::SetWorldRotation(const Quaternion& rotation)
  258. {
  259. if (!parent_)
  260. SetRotation(rotation);
  261. else
  262. SetRotation(parent_->GetWorldRotation().Inverse() * rotation);
  263. }
  264. void Node::SetWorldDirection(const Vector3& direction)
  265. {
  266. Vector3 localDirection;
  267. if (!parent_)
  268. localDirection = direction;
  269. else
  270. localDirection = parent_->GetWorldTransform().Inverse() * direction;
  271. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  272. }
  273. void Node::SetWorldScale(float scale)
  274. {
  275. if (!parent_)
  276. SetScale(scale);
  277. else
  278. {
  279. Vector3 parentWorldScale = parent_->GetWorldScale();
  280. SetScale(Vector3(scale / parentWorldScale.x_, scale / parentWorldScale.y_, scale / parentWorldScale.z_));
  281. }
  282. }
  283. void Node::SetWorldScale(const Vector3& scale)
  284. {
  285. if (!parent_)
  286. SetScale(scale);
  287. else
  288. SetScale(scale / parent_->GetWorldScale());
  289. }
  290. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  291. {
  292. SetWorldPosition(position);
  293. SetWorldRotation(rotation);
  294. }
  295. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  296. {
  297. SetWorldPosition(position);
  298. SetWorldRotation(rotation);
  299. SetWorldScale(scale);
  300. }
  301. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  302. {
  303. SetWorldPosition(position);
  304. SetWorldRotation(rotation);
  305. SetWorldScale(scale);
  306. }
  307. void Node::Translate(const Vector3& delta)
  308. {
  309. position_ += delta;
  310. MarkDirty();
  311. MarkNetworkUpdate();
  312. }
  313. void Node::TranslateRelative(const Vector3& delta)
  314. {
  315. position_ += rotation_ * delta;
  316. MarkDirty();
  317. MarkNetworkUpdate();
  318. }
  319. void Node::Rotate(const Quaternion& delta, bool fixedAxis)
  320. {
  321. if (!fixedAxis)
  322. rotation_ = rotation_ * delta;
  323. else
  324. rotation_ = delta * rotation_;
  325. if (++rotateCount_ >= NORMALIZE_ROTATION_EVERY)
  326. {
  327. rotation_.Normalize();
  328. rotateCount_ = 0;
  329. }
  330. MarkDirty();
  331. MarkNetworkUpdate();
  332. }
  333. void Node::Yaw(float angle, bool fixedAxis)
  334. {
  335. Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
  336. }
  337. void Node::Pitch(float angle, bool fixedAxis)
  338. {
  339. Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
  340. }
  341. void Node::Roll(float angle, bool fixedAxis)
  342. {
  343. Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
  344. }
  345. void Node::LookAt(const Vector3& target, const Vector3& upAxis, bool worldSpace)
  346. {
  347. Vector3 targetZ;
  348. if (worldSpace)
  349. targetZ = (target - GetWorldPosition()).Normalized();
  350. else
  351. targetZ = (target - position_).Normalized();
  352. Vector3 targetX = upAxis.CrossProduct(targetZ).Normalized();
  353. Vector3 targetY = targetZ.CrossProduct(targetX).Normalized();
  354. if (!worldSpace || !parent_)
  355. SetRotation(Quaternion(targetX, targetY, targetZ));
  356. else
  357. SetRotation(parent_->GetWorldRotation().Inverse() * Quaternion(targetX, targetY, targetZ));
  358. }
  359. void Node::Scale(float scale)
  360. {
  361. Scale(Vector3(scale, scale, scale));
  362. }
  363. void Node::Scale(const Vector3& scale)
  364. {
  365. scale_ *= scale;
  366. MarkDirty();
  367. MarkNetworkUpdate();
  368. }
  369. void Node::SetOwner(Connection* owner)
  370. {
  371. owner_ = owner;
  372. }
  373. void Node::MarkDirty()
  374. {
  375. if (dirty_)
  376. return;
  377. dirty_ = true;
  378. // Notify listener components first, then mark child nodes
  379. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  380. {
  381. if (*i)
  382. {
  383. (*i)->OnMarkedDirty(this);
  384. ++i;
  385. }
  386. // If listener has expired, erase from list
  387. else
  388. i = listeners_.Erase(i);
  389. }
  390. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  391. (*i)->MarkDirty();
  392. }
  393. Node* Node::CreateChild(const String& name, CreateMode mode)
  394. {
  395. Node* newNode = CreateChild(0, mode);
  396. newNode->SetName(name);
  397. return newNode;
  398. }
  399. void Node::AddChild(Node* node)
  400. {
  401. // Check for illegal or redundant parent assignment
  402. if (!node || node == this || node->parent_ == this)
  403. return;
  404. // Check for possible cyclic parent assignment
  405. Node* parent = parent_;
  406. while (parent)
  407. {
  408. if (parent == node)
  409. return;
  410. parent = parent->parent_;
  411. }
  412. // Add first, then remove from old parent, to ensure the node does not get deleted
  413. children_.Push(SharedPtr<Node>(node));
  414. node->Remove();
  415. // Add to the scene if not added yet
  416. if (scene_ && !node->GetScene())
  417. scene_->NodeAdded(node);
  418. node->parent_ = this;
  419. node->MarkDirty();
  420. node->MarkNetworkUpdate();
  421. // Send change event
  422. if (scene_)
  423. {
  424. using namespace NodeAdded;
  425. VariantMap eventData;
  426. eventData[P_SCENE] = (void*)scene_;
  427. eventData[P_PARENT] = (void*)this;
  428. eventData[P_NODE] = (void*)node;
  429. scene_->SendEvent(E_NODEADDED, eventData);
  430. }
  431. }
  432. void Node::RemoveChild(Node* node)
  433. {
  434. if (!node)
  435. return;
  436. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  437. {
  438. if (*i == node)
  439. {
  440. RemoveChild(i);
  441. return;
  442. }
  443. }
  444. }
  445. void Node::RemoveAllChildren()
  446. {
  447. while (children_.Size())
  448. RemoveChild(--children_.End());
  449. }
  450. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode, unsigned id)
  451. {
  452. // Check that creation succeeds and that the object in fact is a component
  453. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  454. if (!newComponent)
  455. {
  456. LOGERROR("Could not create unknown component type " + type.ToString());
  457. return 0;
  458. }
  459. AddComponent(newComponent, id, mode);
  460. return newComponent;
  461. }
  462. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode)
  463. {
  464. Component* oldComponent = GetComponent(type);
  465. if (oldComponent)
  466. return oldComponent;
  467. else
  468. return CreateComponent(type, mode);
  469. }
  470. void Node::RemoveComponent(Component* component)
  471. {
  472. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  473. {
  474. if (*i == component)
  475. {
  476. RemoveComponent(i);
  477. // Mark node dirty in all replication states
  478. MarkReplicationDirty();
  479. return;
  480. }
  481. }
  482. }
  483. void Node::RemoveComponent(ShortStringHash type)
  484. {
  485. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  486. {
  487. if ((*i)->GetType() == type)
  488. {
  489. RemoveComponent(i);
  490. // Mark node dirty in all replication states
  491. MarkReplicationDirty();
  492. return;
  493. }
  494. }
  495. }
  496. void Node::RemoveAllComponents()
  497. {
  498. if (components_.Empty())
  499. return;
  500. while (components_.Size())
  501. RemoveComponent(--components_.End());
  502. // Mark node dirty in all replication states
  503. MarkReplicationDirty();
  504. }
  505. Node* Node::Clone(CreateMode mode)
  506. {
  507. // The scene itself can not be cloned
  508. if (this == scene_ || !parent_)
  509. {
  510. LOGERROR("Can not clone node without a parent");
  511. return 0;
  512. }
  513. PROFILE(CloneNode);
  514. SceneResolver resolver;
  515. Node* clone = CloneRecursive(parent_, resolver, mode);
  516. resolver.Resolve();
  517. clone->ApplyAttributes();
  518. return clone;
  519. }
  520. void Node::Remove()
  521. {
  522. if (parent_)
  523. parent_->RemoveChild(this);
  524. }
  525. void Node::SetParent(Node* parent)
  526. {
  527. if (parent)
  528. {
  529. Vector3 worldPosition;
  530. Quaternion worldRotation;
  531. Vector3 worldScale;
  532. GetWorldTransform().Decompose(worldPosition, worldRotation, worldScale);
  533. parent->AddChild(this);
  534. SetWorldTransform(worldPosition, worldRotation, worldScale);
  535. }
  536. }
  537. void Node::SetVar(ShortStringHash key, const Variant& value)
  538. {
  539. vars_[key] = value;
  540. MarkNetworkUpdate();
  541. }
  542. void Node::AddListener(Component* component)
  543. {
  544. if (!component)
  545. return;
  546. // Check for not adding twice
  547. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  548. {
  549. if (*i == component)
  550. return;
  551. }
  552. listeners_.Push(WeakPtr<Component>(component));
  553. // If the node is currently dirty, notify immediately
  554. if (dirty_)
  555. component->OnMarkedDirty(this);
  556. }
  557. void Node::RemoveListener(Component* component)
  558. {
  559. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  560. {
  561. if (*i == component)
  562. {
  563. listeners_.Erase(i);
  564. return;
  565. }
  566. }
  567. }
  568. Vector3 Node::LocalToWorld(const Vector3& position) const
  569. {
  570. return GetWorldTransform() * position;
  571. }
  572. Vector3 Node::LocalToWorld(const Vector4& vector) const
  573. {
  574. return GetWorldTransform() * vector;
  575. }
  576. Vector3 Node::WorldToLocal(const Vector3& position) const
  577. {
  578. return GetWorldTransform().Inverse() * position;
  579. }
  580. Vector3 Node::WorldToLocal(const Vector4& vector) const
  581. {
  582. return GetWorldTransform().Inverse() * vector;
  583. }
  584. unsigned Node::GetNumChildren(bool recursive) const
  585. {
  586. if (!recursive)
  587. return children_.Size();
  588. else
  589. {
  590. unsigned allChildren = children_.Size();
  591. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  592. allChildren += (*i)->GetNumChildren(true);
  593. return allChildren;
  594. }
  595. }
  596. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  597. {
  598. dest.Clear();
  599. if (!recursive)
  600. {
  601. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  602. dest.Push(*i);
  603. }
  604. else
  605. GetChildrenRecursive(dest);
  606. }
  607. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  608. {
  609. dest.Clear();
  610. if (!recursive)
  611. {
  612. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  613. {
  614. if ((*i)->HasComponent(type))
  615. dest.Push(*i);
  616. }
  617. }
  618. else
  619. GetChildrenWithComponentRecursive(dest, type);
  620. }
  621. Node* Node::GetChild(unsigned index) const
  622. {
  623. return index < children_.Size() ? children_[index].Get() : 0;
  624. }
  625. Node* Node::GetChild(const String& name, bool recursive) const
  626. {
  627. return GetChild(StringHash(name), recursive);
  628. }
  629. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  630. {
  631. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  632. {
  633. if ((*i)->GetNameHash() == nameHash)
  634. return *i;
  635. if (recursive)
  636. {
  637. Node* node = (*i)->GetChild(nameHash, true);
  638. if (node)
  639. return node;
  640. }
  641. }
  642. return 0;
  643. }
  644. unsigned Node::GetNumNetworkComponents() const
  645. {
  646. unsigned num = 0;
  647. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  648. {
  649. if ((*i)->GetID() < FIRST_LOCAL_ID)
  650. ++num;
  651. }
  652. return num;
  653. }
  654. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type, bool recursive) const
  655. {
  656. dest.Clear();
  657. if (!recursive)
  658. {
  659. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  660. {
  661. if ((*i)->GetType() == type)
  662. dest.Push(*i);
  663. }
  664. }
  665. else
  666. GetComponentsRecursive(dest, type);
  667. }
  668. bool Node::HasComponent(ShortStringHash type) const
  669. {
  670. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  671. {
  672. if ((*i)->GetType() == type)
  673. return true;
  674. }
  675. return false;
  676. }
  677. const Variant& Node::GetVar(ShortStringHash key) const
  678. {
  679. VariantMap::ConstIterator i = vars_.Find(key);
  680. if (i != vars_.End())
  681. return i->second_;
  682. else
  683. return Variant::EMPTY;
  684. }
  685. Component* Node::GetComponent(ShortStringHash type) const
  686. {
  687. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  688. {
  689. if ((*i)->GetType() == type)
  690. return *i;
  691. }
  692. return 0;
  693. }
  694. void Node::SetID(unsigned id)
  695. {
  696. id_ = id;
  697. }
  698. void Node::SetScene(Scene* scene)
  699. {
  700. scene_ = scene;
  701. }
  702. void Node::ResetScene()
  703. {
  704. SetID(0);
  705. SetScene(0);
  706. SetOwner(0);
  707. }
  708. void Node::SetNetPositionAttr(const Vector3& value)
  709. {
  710. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  711. if (transform)
  712. transform->SetTargetPosition(value);
  713. else
  714. SetPosition(value);
  715. }
  716. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  717. {
  718. MemoryBuffer buf(value);
  719. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  720. if (transform)
  721. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  722. else
  723. SetRotation(buf.ReadPackedQuaternion());
  724. }
  725. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  726. {
  727. Scene* scene = GetScene();
  728. if (!scene)
  729. return;
  730. MemoryBuffer buf(value);
  731. // If nothing in the buffer, parent is the root node
  732. if (buf.IsEof())
  733. {
  734. scene->AddChild(this);
  735. return;
  736. }
  737. unsigned baseNodeID = buf.ReadNetID();
  738. Node* baseNode = scene->GetNode(baseNodeID);
  739. if (!baseNode)
  740. {
  741. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  742. return;
  743. }
  744. // If buffer contains just an ID, the parent is replicated and we are done
  745. if (buf.IsEof())
  746. baseNode->AddChild(this);
  747. else
  748. {
  749. // Else the parent is local and we must find it recursively by name hash
  750. StringHash nameHash = buf.ReadStringHash();
  751. Node* parentNode = baseNode->GetChild(nameHash, true);
  752. if (!parentNode)
  753. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  754. else
  755. parentNode->AddChild(this);
  756. }
  757. }
  758. const Vector3& Node::GetNetPositionAttr() const
  759. {
  760. return position_;
  761. }
  762. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  763. {
  764. attrBuffer_.Clear();
  765. attrBuffer_.WritePackedQuaternion(rotation_);
  766. return attrBuffer_.GetBuffer();
  767. }
  768. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  769. {
  770. attrBuffer_.Clear();
  771. Scene* scene = GetScene();
  772. if (scene && parent_ && parent_ != scene)
  773. {
  774. // If parent is replicated, can write the ID directly
  775. unsigned parentID = parent_->GetID();
  776. if (parentID < FIRST_LOCAL_ID)
  777. attrBuffer_.WriteNetID(parentID);
  778. else
  779. {
  780. // Parent is local: traverse hierarchy to find a non-local base node
  781. // This iteration always stops due to the scene (root) being non-local
  782. Node* current = parent_;
  783. while (current->GetID() >= FIRST_LOCAL_ID)
  784. current = current->GetParent();
  785. // Then write the base node ID and the parent's name hash
  786. attrBuffer_.WriteNetID(current->GetID());
  787. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  788. }
  789. }
  790. return attrBuffer_.GetBuffer();
  791. }
  792. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  793. {
  794. // Remove all children and components first in case this is not a fresh load
  795. RemoveAllChildren();
  796. RemoveAllComponents();
  797. // ID has been read at the parent level
  798. if (!Serializable::Load(source))
  799. return false;
  800. unsigned numComponents = source.ReadVLE();
  801. for (unsigned i = 0; i < numComponents; ++i)
  802. {
  803. VectorBuffer compBuffer(source, source.ReadVLE());
  804. ShortStringHash compType = compBuffer.ReadShortStringHash();
  805. unsigned compID = compBuffer.ReadUInt();
  806. Component* newComponent = CreateComponent(compType,
  807. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  808. if (newComponent)
  809. {
  810. resolver.AddComponent(compID, newComponent);
  811. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  812. newComponent->Load(compBuffer);
  813. }
  814. }
  815. if (!readChildren)
  816. return true;
  817. unsigned numChildren = source.ReadVLE();
  818. for (unsigned i = 0; i < numChildren; ++i)
  819. {
  820. unsigned nodeID = source.ReadUInt();
  821. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  822. LOCAL);
  823. resolver.AddNode(nodeID, newNode);
  824. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  825. return false;
  826. }
  827. return true;
  828. }
  829. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  830. {
  831. // Remove all children and components first in case this is not a fresh load
  832. RemoveAllChildren();
  833. RemoveAllComponents();
  834. if (!Serializable::LoadXML(source))
  835. return false;
  836. XMLElement compElem = source.GetChild("component");
  837. while (compElem)
  838. {
  839. String typeName = compElem.GetAttribute("type");
  840. unsigned compID = compElem.GetInt("id");
  841. Component* newComponent = CreateComponent(ShortStringHash(typeName),
  842. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  843. if (newComponent)
  844. {
  845. resolver.AddComponent(compID, newComponent);
  846. if (!newComponent->LoadXML(compElem))
  847. return false;
  848. }
  849. compElem = compElem.GetNext("component");
  850. }
  851. if (!readChildren)
  852. return true;
  853. XMLElement childElem = source.GetChild("node");
  854. while (childElem)
  855. {
  856. unsigned nodeID = childElem.GetInt("id");
  857. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  858. LOCAL);
  859. resolver.AddNode(nodeID, newNode);
  860. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  861. return false;
  862. childElem = childElem.GetNext("node");
  863. }
  864. return true;
  865. }
  866. void Node::PrepareNetworkUpdate()
  867. {
  868. // Update dependency nodes list first
  869. dependencyNodes_.Clear();
  870. // Add the parent node, but if it is local, traverse to the first non-local node
  871. if (parent_ && parent_ != scene_)
  872. {
  873. Node* current = parent_;
  874. while (current->id_ >= FIRST_LOCAL_ID)
  875. current = current->parent_;
  876. if (current && current != scene_)
  877. dependencyNodes_.Push(current);
  878. }
  879. // Let the components add their dependencies
  880. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  881. {
  882. Component* component = *i;
  883. if (component->GetID() < FIRST_LOCAL_ID)
  884. component->GetDependencyNodes(dependencyNodes_);
  885. }
  886. // Then check for node attribute changes
  887. if (!networkState_)
  888. AllocateNetworkState();
  889. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  890. unsigned numAttributes = attributes->Size();
  891. if (networkState_->currentValues_.Size() != numAttributes)
  892. {
  893. networkState_->currentValues_.Resize(numAttributes);
  894. networkState_->previousValues_.Resize(numAttributes);
  895. // Copy the default attribute values to the previous state as a starting point
  896. for (unsigned i = 0; i < numAttributes; ++i)
  897. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  898. }
  899. // Check for attribute changes
  900. for (unsigned i = 0; i < numAttributes; ++i)
  901. {
  902. const AttributeInfo& attr = attributes->At(i);
  903. OnGetAttribute(attr, networkState_->currentValues_[i]);
  904. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  905. {
  906. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  907. // Mark the attribute dirty in all replication states that are tracking this node
  908. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  909. networkState_->replicationStates_.End();
  910. ++j)
  911. {
  912. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  913. nodeState->dirtyAttributes_.Set(i);
  914. // Add node to the dirty set if not added yet
  915. if (!nodeState->markedDirty_)
  916. {
  917. nodeState->markedDirty_ = true;
  918. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  919. }
  920. }
  921. }
  922. }
  923. // Finally check for user var changes
  924. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  925. {
  926. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  927. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  928. {
  929. networkState_->previousVars_[i->first_] = i->second_;
  930. // Mark the var dirty in all replication states that are tracking this node
  931. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  932. networkState_->replicationStates_.End(); ++j)
  933. {
  934. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  935. nodeState->dirtyVars_.Insert(i->first_);
  936. if (!nodeState->markedDirty_)
  937. {
  938. nodeState->markedDirty_ = true;
  939. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  940. }
  941. }
  942. }
  943. }
  944. networkUpdate_ = false;
  945. }
  946. void Node::CleanupConnection(Connection* connection)
  947. {
  948. if (owner_ == connection)
  949. owner_ = 0;
  950. if (networkState_)
  951. {
  952. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  953. {
  954. if (networkState_->replicationStates_[i]->connection_ == connection)
  955. networkState_->replicationStates_.Erase(i);
  956. }
  957. }
  958. }
  959. void Node::MarkNetworkUpdate()
  960. {
  961. if (!networkUpdate_ && scene_ && id_ < FIRST_LOCAL_ID)
  962. {
  963. scene_->MarkNetworkUpdate(this);
  964. networkUpdate_ = true;
  965. }
  966. }
  967. void Node::MarkReplicationDirty()
  968. {
  969. if (networkState_)
  970. {
  971. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  972. networkState_->replicationStates_.End(); ++j)
  973. {
  974. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  975. if (!nodeState->markedDirty_)
  976. {
  977. nodeState->markedDirty_ = true;
  978. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  979. }
  980. }
  981. }
  982. }
  983. Node* Node::CreateChild(unsigned id, CreateMode mode)
  984. {
  985. SharedPtr<Node> newNode(new Node(context_));
  986. // If zero ID specified, or the ID is already taken, let the scene assign
  987. if (scene_)
  988. {
  989. if (!id || scene_->GetNode(id))
  990. id = scene_->GetFreeNodeID(mode);
  991. newNode->SetID(id);
  992. }
  993. else
  994. newNode->SetID(id);
  995. AddChild(newNode);
  996. return newNode;
  997. }
  998. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  999. {
  1000. if (!component)
  1001. return;
  1002. components_.Push(SharedPtr<Component>(component));
  1003. // If zero ID specified, or the ID is already taken, let the scene assign
  1004. if (scene_)
  1005. {
  1006. if (!id || scene_->GetComponent(id))
  1007. id = scene_->GetFreeComponentID(mode);
  1008. component->SetID(id);
  1009. scene_->ComponentAdded(component);
  1010. }
  1011. else
  1012. component->SetID(id);
  1013. component->SetNode(this);
  1014. component->OnMarkedDirty(this);
  1015. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1016. component->MarkNetworkUpdate();
  1017. MarkNetworkUpdate();
  1018. MarkReplicationDirty();
  1019. // Send change event
  1020. if (scene_)
  1021. {
  1022. using namespace ComponentAdded;
  1023. VariantMap eventData;
  1024. eventData[P_SCENE] = (void*)scene_;
  1025. eventData[P_NODE] = (void*)this;
  1026. eventData[P_COMPONENT] = (void*)component;
  1027. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1028. }
  1029. }
  1030. void Node::UpdateWorldTransform() const
  1031. {
  1032. Matrix3x4 transform = GetTransform();
  1033. if (parent_)
  1034. worldTransform_ = parent_->GetWorldTransform() * transform;
  1035. else
  1036. worldTransform_ = transform;
  1037. dirty_ = false;
  1038. }
  1039. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1040. {
  1041. // Send change event. Do not send when already being destroyed
  1042. if (Refs() > 0 && scene_)
  1043. {
  1044. using namespace NodeRemoved;
  1045. VariantMap eventData;
  1046. eventData[P_SCENE] = (void*)scene_;
  1047. eventData[P_PARENT] = (void*)this;
  1048. eventData[P_NODE] = (void*)(*i).Get();
  1049. scene_->SendEvent(E_NODEREMOVED, eventData);
  1050. }
  1051. (*i)->parent_ = 0;
  1052. (*i)->MarkDirty();
  1053. (*i)->MarkNetworkUpdate();
  1054. children_.Erase(i);
  1055. }
  1056. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1057. {
  1058. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1059. {
  1060. Node* node = *i;
  1061. dest.Push(node);
  1062. if (!node->children_.Empty())
  1063. node->GetChildrenRecursive(dest);
  1064. }
  1065. }
  1066. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  1067. {
  1068. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1069. {
  1070. Node* node = *i;
  1071. if (node->HasComponent(type))
  1072. dest.Push(node);
  1073. if (!node->children_.Empty())
  1074. node->GetChildrenWithComponentRecursive(dest, type);
  1075. }
  1076. }
  1077. void Node::GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const
  1078. {
  1079. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1080. {
  1081. if ((*i)->GetType() == type)
  1082. dest.Push(*i);
  1083. }
  1084. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1085. (*i)->GetComponentsRecursive(dest, type);
  1086. }
  1087. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1088. {
  1089. // Create clone node
  1090. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1091. resolver.AddNode(id_, cloneNode);
  1092. // Copy attributes
  1093. unsigned numAttributes = GetNumAttributes();
  1094. for (unsigned j = 0; j < numAttributes; ++j)
  1095. cloneNode->SetAttribute(j, GetAttribute(j));
  1096. // Clone components
  1097. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1098. {
  1099. Component* component = *i;
  1100. Component* cloneComponent = cloneNode->CreateComponent(component->GetType(), (mode == REPLICATED && component->GetID() <
  1101. FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1102. if (!cloneComponent)
  1103. {
  1104. LOGERROR("Could not clone component " + component->GetTypeName());
  1105. continue;
  1106. }
  1107. resolver.AddComponent(component->GetID(), cloneComponent);
  1108. numAttributes = component->GetNumAttributes();
  1109. for (unsigned j = 0; j < numAttributes; ++j)
  1110. cloneComponent->SetAttribute(j, component->GetAttribute(j));
  1111. }
  1112. // Clone child nodes recursively
  1113. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1114. {
  1115. Node* node = *i;
  1116. node->CloneRecursive(cloneNode, resolver, mode);
  1117. }
  1118. return cloneNode;
  1119. }
  1120. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1121. {
  1122. WeakPtr<Component> componentWeak(*i);
  1123. // Send node change event. Do not send when already being destroyed
  1124. if (Refs() > 0 && scene_)
  1125. {
  1126. using namespace ComponentRemoved;
  1127. VariantMap eventData;
  1128. eventData[P_SCENE] = (void*)scene_;
  1129. eventData[P_NODE] = (void*)this;
  1130. eventData[P_COMPONENT] = (void*)(*i).Get();
  1131. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1132. }
  1133. RemoveListener(*i);
  1134. if (scene_)
  1135. scene_->ComponentRemoved(*i);
  1136. components_.Erase(i);
  1137. // If the component is still referenced elsewhere, reset its node pointer now
  1138. if (componentWeak)
  1139. componentWeak->SetNode(0);
  1140. }
  1141. }