Node.cpp 37 KB

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