Node.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  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::SetID(unsigned id)
  720. {
  721. id_ = id;
  722. }
  723. void Node::SetScene(Scene* scene)
  724. {
  725. scene_ = scene;
  726. }
  727. void Node::SetNetPositionAttr(const Vector3& value)
  728. {
  729. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  730. if (transform)
  731. transform->SetTargetPosition(value);
  732. else
  733. SetPosition(value);
  734. }
  735. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  736. {
  737. MemoryBuffer buf(value);
  738. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  739. if (transform)
  740. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  741. else
  742. SetRotation(buf.ReadPackedQuaternion());
  743. }
  744. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  745. {
  746. Scene* scene = GetScene();
  747. if (!scene)
  748. return;
  749. MemoryBuffer buf(value);
  750. // If nothing in the buffer, parent is the root node
  751. if (buf.IsEof())
  752. {
  753. scene->AddChild(this);
  754. return;
  755. }
  756. unsigned baseNodeID = buf.ReadNetID();
  757. Node* baseNode = scene->GetNode(baseNodeID);
  758. if (!baseNode)
  759. {
  760. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  761. return;
  762. }
  763. // If buffer contains just an ID, the parent is replicated and we are done
  764. if (buf.IsEof())
  765. baseNode->AddChild(this);
  766. else
  767. {
  768. // Else the parent is local and we must find it recursively by name hash
  769. StringHash nameHash = buf.ReadStringHash();
  770. Node* parentNode = baseNode->GetChild(nameHash, true);
  771. if (!parentNode)
  772. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  773. else
  774. parentNode->AddChild(this);
  775. }
  776. }
  777. const Vector3& Node::GetNetPositionAttr() const
  778. {
  779. return position_;
  780. }
  781. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  782. {
  783. attrBuffer_.Clear();
  784. attrBuffer_.WritePackedQuaternion(rotation_);
  785. return attrBuffer_.GetBuffer();
  786. }
  787. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  788. {
  789. attrBuffer_.Clear();
  790. Scene* scene = GetScene();
  791. if (scene && parent_ && parent_ != scene)
  792. {
  793. // If parent is replicated, can write the ID directly
  794. unsigned parentID = parent_->GetID();
  795. if (parentID < FIRST_LOCAL_ID)
  796. attrBuffer_.WriteNetID(parentID);
  797. else
  798. {
  799. // Parent is local: traverse hierarchy to find a non-local base node
  800. // This iteration always stops due to the scene (root) being non-local
  801. Node* current = parent_;
  802. while (current->GetID() >= FIRST_LOCAL_ID)
  803. current = current->GetParent();
  804. // Then write the base node ID and the parent's name hash
  805. attrBuffer_.WriteVLE(current->GetID());
  806. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  807. }
  808. }
  809. return attrBuffer_.GetBuffer();
  810. }
  811. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  812. {
  813. // Remove all children and components first in case this is not a fresh load
  814. RemoveAllChildren();
  815. RemoveAllComponents();
  816. // ID has been read at the parent level
  817. if (!Serializable::Load(source))
  818. return false;
  819. unsigned numComponents = source.ReadVLE();
  820. for (unsigned i = 0; i < numComponents; ++i)
  821. {
  822. VectorBuffer compBuffer(source, source.ReadVLE());
  823. ShortStringHash compType = compBuffer.ReadShortStringHash();
  824. unsigned compID = compBuffer.ReadUInt();
  825. Component* newComponent = CreateComponent(compType, rewriteIDs ? 0 : compID, (mode == REPLICATED &&
  826. compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  827. if (newComponent)
  828. {
  829. resolver.AddComponent(compID, newComponent);
  830. if (!newComponent->Load(compBuffer))
  831. return false;
  832. }
  833. }
  834. if (!readChildren)
  835. return true;
  836. unsigned numChildren = source.ReadVLE();
  837. for (unsigned i = 0; i < numChildren; ++i)
  838. {
  839. unsigned nodeID = source.ReadUInt();
  840. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  841. LOCAL);
  842. resolver.AddNode(nodeID, newNode);
  843. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  844. return false;
  845. }
  846. return true;
  847. }
  848. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  849. {
  850. // Remove all children and components first in case this is not a fresh load
  851. RemoveAllChildren();
  852. RemoveAllComponents();
  853. if (!Serializable::LoadXML(source))
  854. return false;
  855. XMLElement compElem = source.GetChild("component");
  856. while (compElem)
  857. {
  858. String typeName = compElem.GetAttribute("type");
  859. unsigned compID = compElem.GetInt("id");
  860. Component* newComponent = CreateComponent(ShortStringHash(typeName), rewriteIDs ? 0 : compID, (mode == REPLICATED &&
  861. compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  862. if (newComponent)
  863. {
  864. resolver.AddComponent(compID, newComponent);
  865. if (!newComponent->LoadXML(compElem))
  866. return false;
  867. }
  868. compElem = compElem.GetNext("component");
  869. }
  870. if (!readChildren)
  871. return true;
  872. XMLElement childElem = source.GetChild("node");
  873. while (childElem)
  874. {
  875. unsigned nodeID = childElem.GetInt("id");
  876. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  877. LOCAL);
  878. resolver.AddNode(nodeID, newNode);
  879. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  880. return false;
  881. childElem = childElem.GetNext("node");
  882. }
  883. return true;
  884. }
  885. void Node::PrepareNetworkUpdate()
  886. {
  887. // Update dependency nodes list first
  888. dependencyNodes_.Clear();
  889. // Add the parent node, but if it is local, traverse to the first non-local node
  890. if (parent_ && parent_ != scene_)
  891. {
  892. Node* current = parent_;
  893. while (current->id_ >= FIRST_LOCAL_ID)
  894. current = current->parent_;
  895. if (current && current != scene_)
  896. dependencyNodes_.Push(current);
  897. }
  898. // Let the components add their dependencies
  899. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  900. {
  901. Component* component = *i;
  902. if (component->GetID() < FIRST_LOCAL_ID)
  903. component->GetDependencyNodes(dependencyNodes_);
  904. }
  905. // Then check for node attribute changes
  906. if (!networkState_)
  907. AllocateNetworkState();
  908. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  909. unsigned numAttributes = attributes->Size();
  910. if (networkState_->currentValues_.Size() != numAttributes)
  911. {
  912. networkState_->currentValues_.Resize(numAttributes);
  913. networkState_->previousValues_.Resize(numAttributes);
  914. // Copy the default attribute values to the previous state as a starting point
  915. for (unsigned i = 0; i < numAttributes; ++i)
  916. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  917. }
  918. // Check for attribute changes
  919. for (unsigned i = 0; i < numAttributes; ++i)
  920. {
  921. const AttributeInfo& attr = attributes->At(i);
  922. OnGetAttribute(attr, networkState_->currentValues_[i]);
  923. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  924. {
  925. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  926. // Mark the attribute dirty in all replication states that are tracking this node
  927. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  928. networkState_->replicationStates_.End();
  929. ++j)
  930. {
  931. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  932. nodeState->dirtyAttributes_.Set(i);
  933. // Add node to the dirty set if not added yet
  934. if (!nodeState->markedDirty_)
  935. {
  936. nodeState->markedDirty_ = true;
  937. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  938. }
  939. }
  940. }
  941. }
  942. // Finally check for user var changes
  943. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  944. {
  945. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  946. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  947. {
  948. networkState_->previousVars_[i->first_] = i->second_;
  949. // Mark the var dirty in all replication states that are tracking this node
  950. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  951. networkState_->replicationStates_.End(); ++j)
  952. {
  953. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  954. nodeState->dirtyVars_.Insert(i->first_);
  955. if (!nodeState->markedDirty_)
  956. {
  957. nodeState->markedDirty_ = true;
  958. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  959. }
  960. }
  961. }
  962. }
  963. networkUpdate_ = false;
  964. }
  965. void Node::CleanupConnection(Connection* connection)
  966. {
  967. if (owner_ == connection)
  968. owner_ = 0;
  969. if (networkState_)
  970. {
  971. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  972. {
  973. if (networkState_->replicationStates_[i]->connection_ == connection)
  974. networkState_->replicationStates_.Erase(i);
  975. }
  976. }
  977. }
  978. void Node::MarkNetworkUpdate()
  979. {
  980. if (id_ < FIRST_LOCAL_ID && !networkUpdate_ && scene_)
  981. {
  982. scene_->MarkNetworkUpdate(this);
  983. networkUpdate_ = true;
  984. }
  985. }
  986. void Node::MarkReplicationDirty()
  987. {
  988. if (networkState_)
  989. {
  990. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  991. networkState_->replicationStates_.End(); ++j)
  992. {
  993. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  994. if (!nodeState->markedDirty_)
  995. {
  996. nodeState->markedDirty_ = true;
  997. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  998. }
  999. }
  1000. }
  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. AddComponent(newComponent, id, mode);
  1012. return newComponent;
  1013. }
  1014. Node* Node::CreateChild(unsigned id, CreateMode mode)
  1015. {
  1016. SharedPtr<Node> newNode(new Node(context_));
  1017. // If zero ID specified, or the ID is already taken, let the scene assign
  1018. if (scene_)
  1019. {
  1020. if (!id || scene_->GetNode(id))
  1021. id = scene_->GetFreeNodeID(mode);
  1022. newNode->SetID(id);
  1023. }
  1024. else
  1025. newNode->SetID(id);
  1026. AddChild(newNode);
  1027. return newNode;
  1028. }
  1029. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1030. {
  1031. if (!component)
  1032. return;
  1033. components_.Push(SharedPtr<Component>(component));
  1034. // If zero ID specified, or the ID is already taken, let the scene assign
  1035. if (scene_)
  1036. {
  1037. if (!id || scene_->GetComponent(id))
  1038. id = scene_->GetFreeComponentID(mode);
  1039. component->SetID(id);
  1040. scene_->ComponentAdded(component);
  1041. }
  1042. else
  1043. component->SetID(id);
  1044. component->SetNode(this);
  1045. component->OnMarkedDirty(this);
  1046. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1047. component->MarkNetworkUpdate();
  1048. MarkNetworkUpdate();
  1049. MarkReplicationDirty();
  1050. }
  1051. void Node::UpdateWorldTransform() const
  1052. {
  1053. if (parent_)
  1054. {
  1055. if (parent_->dirty_)
  1056. parent_->UpdateWorldTransform();
  1057. worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
  1058. }
  1059. else
  1060. worldTransform_ = Matrix3x4(position_, rotation_, scale_);
  1061. dirty_ = false;
  1062. }
  1063. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1064. {
  1065. (*i)->parent_ = 0;
  1066. (*i)->MarkDirty();
  1067. (*i)->MarkNetworkUpdate();
  1068. children_.Erase(i);
  1069. }
  1070. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1071. {
  1072. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1073. {
  1074. Node* node = *i;
  1075. dest.Push(node);
  1076. if (!node->children_.Empty())
  1077. node->GetChildrenRecursive(dest);
  1078. }
  1079. }
  1080. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  1081. {
  1082. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1083. {
  1084. Node* node = *i;
  1085. if (node->HasComponent(type))
  1086. dest.Push(node);
  1087. if (!node->children_.Empty())
  1088. node->GetChildrenRecursive(dest);
  1089. }
  1090. }
  1091. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1092. {
  1093. // Create clone node
  1094. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1095. resolver.AddNode(id_, cloneNode);
  1096. // Copy attributes
  1097. unsigned numAttributes = GetNumAttributes();
  1098. for (unsigned j = 0; j < numAttributes; ++j)
  1099. cloneNode->SetAttribute(j, GetAttribute(j));
  1100. // Clone components
  1101. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1102. {
  1103. Component* component = *i;
  1104. Component* cloneComponent = cloneNode->CreateComponent(component->GetType(), (mode == REPLICATED && component->GetID() <
  1105. FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1106. if (!cloneComponent)
  1107. {
  1108. LOGERROR("Could not clone component " + component->GetTypeName());
  1109. continue;
  1110. }
  1111. resolver.AddComponent(component->GetID(), cloneComponent);
  1112. numAttributes = component->GetNumAttributes();
  1113. for (unsigned j = 0; j < numAttributes; ++j)
  1114. cloneComponent->SetAttribute(j, component->GetAttribute(j));
  1115. }
  1116. // Clone child nodes recursively
  1117. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1118. {
  1119. Node* node = *i;
  1120. node->CloneRecursive(cloneNode, resolver, mode);
  1121. }
  1122. return cloneNode;
  1123. }