Node.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. //
  2. // Copyright (c) 2008-2014 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. #pragma once
  23. #include "Matrix3x4.h"
  24. #include "Serializable.h"
  25. #include "VectorBuffer.h"
  26. namespace Urho3D
  27. {
  28. class Component;
  29. class Connection;
  30. class Scene;
  31. class SceneResolver;
  32. struct NodeReplicationState;
  33. /// Component and child node creation mode for networking.
  34. enum CreateMode
  35. {
  36. REPLICATED = 0,
  37. LOCAL = 1
  38. };
  39. /// %Scene node that may contain components and child nodes.
  40. class URHO3D_API Node : public Serializable
  41. {
  42. OBJECT(Node);
  43. BASEOBJECT(Node);
  44. friend class Connection;
  45. public:
  46. /// Construct.
  47. Node(Context* context);
  48. /// Destruct. Any child nodes are detached.
  49. virtual ~Node();
  50. /// Register object factory.
  51. static void RegisterObject(Context* context);
  52. /// Handle attribute write access.
  53. virtual void OnSetAttribute(const AttributeInfo& attr, const Variant& src);
  54. /// Load from binary data. Return true if successful.
  55. virtual bool Load(Deserializer& source, bool setInstanceDefault = false);
  56. /// Load from XML data. Return true if successful.
  57. virtual bool LoadXML(const XMLElement& source, bool setInstanceDefault = false);
  58. /// Save as binary data. Return true if successful.
  59. virtual bool Save(Serializer& dest) const;
  60. /// Save as XML data. Return true if successful.
  61. virtual bool SaveXML(XMLElement& dest) const;
  62. /// Apply attribute changes that can not be applied immediately recursively to child nodes and components.
  63. virtual void ApplyAttributes();
  64. /// Return whether should save default-valued attributes into XML. Always save node transforms for readability, even if identity.
  65. virtual bool SaveDefaultAttributes() const { return true; }
  66. /// Add a replication state that is tracking this node.
  67. virtual void AddReplicationState(NodeReplicationState* state);
  68. /// Save to an XML file. Return true if successful.
  69. bool SaveXML(Serializer& dest) const;
  70. /// Set name of the scene node. Names are not required to be unique.
  71. void SetName(const String& name);
  72. /// Set position in parent space. If the scene node is on the root level (is child of the scene itself), this is same as world space.
  73. void SetPosition(const Vector3& position);
  74. /// Set rotation in parent space.
  75. void SetRotation(const Quaternion& rotation);
  76. /// Set forward direction in parent space. Positive Z axis equals identity rotation.
  77. void SetDirection(const Vector3& direction);
  78. /// Set uniform scale in parent space.
  79. void SetScale(float scale);
  80. /// Set scale in parent space.
  81. void SetScale(const Vector3& scale);
  82. /// Set both position and rotation in parent space as an atomic operation. This is faster than setting position and rotation separately.
  83. void SetTransform(const Vector3& position, const Quaternion& rotation);
  84. /// Set both position, rotation and uniform scale in parent space as an atomic operation.
  85. void SetTransform(const Vector3& position, const Quaternion& rotation, float scale);
  86. /// Set both position, rotation and scale in parent space as an atomic operation.
  87. void SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  88. /// Set position in world space.
  89. void SetWorldPosition(const Vector3& position);
  90. /// Set rotation in world space.
  91. void SetWorldRotation(const Quaternion& rotation);
  92. /// Set forward direction in world space.
  93. void SetWorldDirection(const Vector3& direction);
  94. /// Set uniform scale in world space.
  95. void SetWorldScale(float scale);
  96. /// Set scale in world space.
  97. void SetWorldScale(const Vector3& scale);
  98. /// Set both position and rotation in world space as an atomic operation.
  99. void SetWorldTransform(const Vector3& position, const Quaternion& rotation);
  100. /// Set both position, rotation and uniform scale in world space as an atomic operation.
  101. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale);
  102. /// Set both position, rotation and scale in world space as an atomic opration.
  103. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  104. /// Move the scene node in parent space, which is the same as world space if the scene node is on the root level.
  105. void Translate(const Vector3& delta);
  106. /// Move the scene node in parent space relative to its current rotation.
  107. void TranslateRelative(const Vector3& delta);
  108. /// Rotate the scene node in parent space either relative to its current rotation axes, or a fixed axis.
  109. void Rotate(const Quaternion& delta, bool fixedAxis = false);
  110. /// Rotate around the X axis.
  111. void Pitch(float angle, bool fixedAxis = false);
  112. /// Rotate around the Y axis.
  113. void Yaw(float angle, bool fixedAxis = false);
  114. /// Rotate around the Z axis.
  115. void Roll(float angle, bool fixedAxis = false);
  116. /// Look at a target world position. Return true if successful, or false if resulted in an illegal rotation, in which case the current rotation remains.
  117. bool LookAt(const Vector3& target, const Vector3& up = Vector3::UP);
  118. /// Modify scale in parent space uniformly.
  119. void Scale(float scale);
  120. /// Modify scale in parent space.
  121. void Scale(const Vector3& scale);
  122. /// Set enabled/disabled state without recursion. Components in a disabled node become effectively disabled regardless of their own enable/disable state.
  123. void SetEnabled(bool enable);
  124. /// Set enabled/disabled state with optional recursion.
  125. void SetEnabled(bool enable, bool recursive);
  126. /// Set owner connection for networking.
  127. void SetOwner(Connection* owner);
  128. /// Mark node and child nodes to need world transform recalculation. Notify listener components.
  129. void MarkDirty();
  130. /// Create a child scene node (with specified ID if provided).
  131. Node* CreateChild(const String& name = String::EMPTY, CreateMode mode = REPLICATED, unsigned id = 0);
  132. /// Add a child scene node at a specific index. If index is not explicitly specified or is greater than current children size, append the new child at the end.
  133. void AddChild(Node* node, unsigned index = M_MAX_UNSIGNED);
  134. /// Remove a child scene node.
  135. void RemoveChild(Node* node);
  136. /// Remove all child scene nodes.
  137. void RemoveAllChildren();
  138. /// Remove child scene nodes that match criteria.
  139. void RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive);
  140. /// Create a component to this node (with specified ID if provided).
  141. Component* CreateComponent(ShortStringHash type, CreateMode mode = REPLICATED, unsigned id = 0);
  142. /// Create a component to this node if it does not exist already.
  143. Component* GetOrCreateComponent(ShortStringHash type, CreateMode mode = REPLICATED, unsigned id = 0);
  144. /// Remove a component from this node.
  145. void RemoveComponent(Component* component);
  146. /// Remove the first component of specific type from this node.
  147. void RemoveComponent(ShortStringHash type);
  148. /// Remove all components from this node.
  149. void RemoveAllComponents();
  150. /// Remove components that match criteria.
  151. void RemoveComponents(bool removeReplicated, bool removeLocal);
  152. /// Clone scene node, components and child nodes. Return the clone.
  153. Node* Clone(CreateMode mode = REPLICATED);
  154. /// Remove from the parent node. If no other shared pointer references exist, causes immediate deletion.
  155. void Remove();
  156. /// Set parent scene node. Retains the world transform.
  157. void SetParent(Node* parent);
  158. /// Set a user variable.
  159. void SetVar(ShortStringHash key, const Variant& value);
  160. /// Add listener component that is notified of node being dirtied. Can either be in the same node or another.
  161. void AddListener(Component* component);
  162. /// Remove listener component.
  163. void RemoveListener(Component* component);
  164. /// Template version of creating a component.
  165. template <class T> T* CreateComponent(CreateMode mode = REPLICATED, unsigned id = 0);
  166. /// Template version of getting or creating a component.
  167. template <class T> T* GetOrCreateComponent(CreateMode mode = REPLICATED, unsigned id = 0);
  168. /// Template version of removing a component.
  169. template <class T> void RemoveComponent();
  170. /// Return ID.
  171. unsigned GetID() const { return id_; }
  172. /// Return name.
  173. const String& GetName() const { return name_; }
  174. /// Return name hash.
  175. StringHash GetNameHash() const { return nameHash_; }
  176. /// Return parent scene node.
  177. Node* GetParent() const { return parent_; }
  178. /// Return scene.
  179. Scene* GetScene() const { return scene_; }
  180. /// Return whether is enabled. Disables nodes effectively disable all their components.
  181. bool IsEnabled() const { return enabled_; }
  182. /// Return owner connection in networking.
  183. Connection* GetOwner() const { return owner_; }
  184. /// Return position in parent space.
  185. const Vector3& GetPosition() const { return position_; }
  186. /// Return rotation in parent space.
  187. const Quaternion& GetRotation() const { return rotation_; }
  188. /// Return forward direction in parent space. Positive Z axis equals identity rotation.
  189. Vector3 GetDirection() const { return rotation_ * Vector3::FORWARD; }
  190. /// Return up direction in parent space. Positive Y axis equals identity rotation.
  191. Vector3 GetUp() const { return rotation_ * Vector3::UP; }
  192. /// Return right direction in parent space. Positive X axis equals identity rotation.
  193. Vector3 GetRight() const { return rotation_ * Vector3::RIGHT; }
  194. /// Return scale in parent space.
  195. const Vector3& GetScale() const { return scale_; }
  196. /// Return parent space transform matrix.
  197. Matrix3x4 GetTransform() const { return Matrix3x4(position_, rotation_, scale_); }
  198. /// Return position in world space.
  199. Vector3 GetWorldPosition() const
  200. {
  201. if (dirty_)
  202. UpdateWorldTransform();
  203. return worldTransform_.Translation();
  204. }
  205. /// Return rotation in world space.
  206. Quaternion GetWorldRotation() const
  207. {
  208. if (dirty_)
  209. UpdateWorldTransform();
  210. return worldRotation_;
  211. }
  212. /// Return direction in world space.
  213. Vector3 GetWorldDirection() const
  214. {
  215. if (dirty_)
  216. UpdateWorldTransform();
  217. return worldRotation_ * Vector3::FORWARD;
  218. }
  219. /// Return node's up vector in world space.
  220. Vector3 GetWorldUp() const
  221. {
  222. if (dirty_)
  223. UpdateWorldTransform();
  224. return worldRotation_ * Vector3::UP;
  225. }
  226. /// Return node's right vector in world space.
  227. Vector3 GetWorldRight() const
  228. {
  229. if (dirty_)
  230. UpdateWorldTransform();
  231. return worldRotation_ * Vector3::RIGHT;
  232. }
  233. /// Return scale in world space.
  234. Vector3 GetWorldScale() const
  235. {
  236. if (dirty_)
  237. UpdateWorldTransform();
  238. return worldTransform_.Scale();
  239. }
  240. /// Return world space transform matrix.
  241. const Matrix3x4& GetWorldTransform() const
  242. {
  243. if (dirty_)
  244. UpdateWorldTransform();
  245. return worldTransform_;
  246. }
  247. /// Convert a local space position to world space.
  248. Vector3 LocalToWorld(const Vector3& position) const;
  249. /// Convert a local space position or rotation to world space.
  250. Vector3 LocalToWorld(const Vector4& vector) const;
  251. /// Convert a world space position to local space.
  252. Vector3 WorldToLocal(const Vector3& position) const;
  253. /// Convert a world space position or rotation to local space.
  254. Vector3 WorldToLocal(const Vector4& vector) const;
  255. /// Return whether transform has changed and world transform needs recalculation.
  256. bool IsDirty() const { return dirty_; }
  257. /// Return number of child scene nodes.
  258. unsigned GetNumChildren(bool recursive = false) const;
  259. /// Return immediate child scene nodes.
  260. const Vector<SharedPtr<Node> >& GetChildren() const { return children_; }
  261. /// Return child scene nodes, optionally recursive.
  262. void GetChildren(PODVector<Node*>& dest, bool recursive = false) const;
  263. /// Return child scene nodes with a specific component.
  264. void GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive = false) const;
  265. /// Return child scene node by index.
  266. Node* GetChild(unsigned index) const;
  267. /// Return child scene node by name.
  268. Node* GetChild(const String& name, bool recursive = false) const;
  269. /// Return child scene node by name.
  270. Node* GetChild(const char* name, bool recursive = false) const;
  271. /// Return child scene node by name hash.
  272. Node* GetChild(StringHash nameHash, bool recursive = false) const;
  273. /// Return number of components.
  274. unsigned GetNumComponents() const { return components_.Size(); }
  275. /// Return number of non-local components.
  276. unsigned GetNumNetworkComponents() const;
  277. /// Return all components.
  278. const Vector<SharedPtr<Component> >& GetComponents() const { return components_; }
  279. /// Return all components of type. Optionally recursive.
  280. void GetComponents(PODVector<Component*>& dest, ShortStringHash type, bool recursive = false) const;
  281. /// Return component by type. If there are several, returns the first.
  282. Component* GetComponent(ShortStringHash type) const;
  283. /// Return whether has a specific component.
  284. bool HasComponent(ShortStringHash type) const;
  285. /// Return listener components.
  286. const Vector<WeakPtr<Component> > GetListeners() const { return listeners_; }
  287. /// Return a user variable.
  288. const Variant& GetVar(ShortStringHash key) const;
  289. /// Return all user variables.
  290. const VariantMap& GetVars() const { return vars_; }
  291. /// Return first component derived from class.
  292. template <class T> T* GetDerivedComponent() const;
  293. /// Return components derived from class.
  294. template <class T> void GetDerivedComponents(PODVector<T*>& dest) const;
  295. /// Template version of returning child nodes with a specific component.
  296. template <class T> void GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive = false) const;
  297. /// Template version of returning a component by type.
  298. template <class T> T* GetComponent() const;
  299. /// Template version of returning all components of type.
  300. template <class T> void GetComponents(PODVector<T*>& dest, bool recursive = false) const;
  301. /// Template version of checking whether has a specific component.
  302. template <class T> bool HasComponent() const;
  303. /// Set ID. Called by Scene.
  304. void SetID(unsigned id);
  305. /// Set scene. Called by Scene.
  306. void SetScene(Scene* scene);
  307. /// Reset scene. Called by Scene.
  308. void ResetScene();
  309. /// Set network position attribute.
  310. void SetNetPositionAttr(const Vector3& value);
  311. /// Set network rotation attribute.
  312. void SetNetRotationAttr(const PODVector<unsigned char>& value);
  313. /// Set network parent attribute.
  314. void SetNetParentAttr(const PODVector<unsigned char>& value);
  315. /// Return network position attribute.
  316. const Vector3& GetNetPositionAttr() const;
  317. /// Return network rotation attribute.
  318. const PODVector<unsigned char>& GetNetRotationAttr() const;
  319. /// Return network parent attribute.
  320. const PODVector<unsigned char>& GetNetParentAttr() const;
  321. /// Load components and optionally load child nodes.
  322. bool Load(Deserializer& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  323. /// Load components from XML data and optionally load child nodes.
  324. bool LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  325. /// Return the depended on nodes to order network updates.
  326. const PODVector<Node*>& GetDependencyNodes() const { return dependencyNodes_; }
  327. /// Prepare network update by comparing attributes and marking replication states dirty as necessary.
  328. void PrepareNetworkUpdate();
  329. /// Clean up all references to a network connection that is about to be removed.
  330. void CleanupConnection(Connection* connection);
  331. /// Mark for attribute check on the next network update.
  332. void MarkNetworkUpdate();
  333. /// Mark node dirty in scene replication states.
  334. void MarkReplicationDirty();
  335. /// Create a child node with specific ID.
  336. Node* CreateChild(unsigned id, CreateMode mode);
  337. /// Add a pre-created component.
  338. void AddComponent(Component* component, unsigned id, CreateMode mode);
  339. /// Calculate number of non-temporary child nodes.
  340. unsigned GetNumPersistentChildren() const;
  341. /// Calculate number of non-temporary components.
  342. unsigned GetNumPersistentComponents() const;
  343. protected:
  344. /// User variables.
  345. VariantMap vars_;
  346. private:
  347. /// Create component, allowing UnknownComponent if actual type is not supported. Leave typeName empty if not known.
  348. Component* SafeCreateComponent(const String& typeName, ShortStringHash type, CreateMode mode, unsigned id);
  349. /// Recalculate the world transform.
  350. void UpdateWorldTransform() const;
  351. /// Remove child node by iterator.
  352. void RemoveChild(Vector<SharedPtr<Node> >::Iterator i);
  353. /// Return child nodes recursively.
  354. void GetChildrenRecursive(PODVector<Node*>& dest) const;
  355. /// Return child nodes with a specific component recursively.
  356. void GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const;
  357. /// Return specific components recursively.
  358. void GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const;
  359. /// Clone node recursively.
  360. Node* CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode);
  361. /// Remove a component from this node with the specified iterator.
  362. void RemoveComponent(Vector<SharedPtr<Component> >::Iterator i);
  363. /// World-space transform matrix.
  364. mutable Matrix3x4 worldTransform_;
  365. /// World transform needs update flag.
  366. mutable bool dirty_;
  367. /// Network update queued flag.
  368. bool networkUpdate_;
  369. /// Enabled flag.
  370. bool enabled_;
  371. /// Parent scene node.
  372. Node* parent_;
  373. /// Scene (root node.)
  374. Scene* scene_;
  375. /// Unique ID within the scene.
  376. unsigned id_;
  377. /// Position.
  378. Vector3 position_;
  379. /// Rotation.
  380. Quaternion rotation_;
  381. /// Scale.
  382. Vector3 scale_;
  383. /// World-space rotation.
  384. mutable Quaternion worldRotation_;
  385. /// Components.
  386. Vector<SharedPtr<Component> > components_;
  387. /// Child scene nodes.
  388. Vector<SharedPtr<Node> > children_;
  389. /// Node listeners.
  390. Vector<WeakPtr<Component> > listeners_;
  391. /// Nodes this node depends on for network updates.
  392. PODVector<Node*> dependencyNodes_;
  393. /// Network owner connection.
  394. Connection* owner_;
  395. /// Name.
  396. String name_;
  397. /// Name hash.
  398. StringHash nameHash_;
  399. /// Attribute buffer for network updates.
  400. mutable VectorBuffer attrBuffer_;
  401. };
  402. template <class T> T* Node::CreateComponent(CreateMode mode, unsigned id) { return static_cast<T*>(CreateComponent(T::GetTypeStatic(), mode, id)); }
  403. template <class T> T* Node::GetOrCreateComponent(CreateMode mode, unsigned id) { return static_cast<T*>(GetOrCreateComponent(T::GetTypeStatic(), mode, id)); }
  404. template <class T> void Node::RemoveComponent() { RemoveComponent(T::GetTypeStatic()); }
  405. template <class T> void Node::GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive) const { GetChildrenWithComponent(dest, T::GetTypeStatic(), recursive); }
  406. template <class T> T* Node::GetComponent() const { return static_cast<T*>(GetComponent(T::GetTypeStatic())); }
  407. template <class T> void Node::GetComponents(PODVector<T*>& dest, bool recursive) const { GetComponents(reinterpret_cast<PODVector<Component*>&>(dest), T::GetTypeStatic(), recursive); }
  408. template <class T> bool Node::HasComponent() const { return HasComponent(T::GetTypeStatic()); }
  409. template <class T> T* Node::GetDerivedComponent() const
  410. {
  411. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  412. {
  413. T* component = dynamic_cast<T*>(i->Get());
  414. if (component)
  415. return component;
  416. }
  417. return 0;
  418. }
  419. template <class T> void Node::GetDerivedComponents(PODVector<T*>& dest) const
  420. {
  421. dest.Clear();
  422. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  423. {
  424. T* component = dynamic_cast<T*>(i->Get());
  425. if (component)
  426. dest.Push(component);
  427. }
  428. }
  429. }