Node.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #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.
  117. void LookAt(const Vector3& target, const Vector3& upAxis = 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.
  133. void AddChild(Node* node);
  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 scale in parent space.
  191. const Vector3& GetScale() const { return scale_; }
  192. /// Return parent space transform matrix.
  193. Matrix3x4 GetTransform() const { return Matrix3x4(position_, rotation_, scale_); }
  194. /// Return position in world space.
  195. Vector3 GetWorldPosition() const
  196. {
  197. if (dirty_)
  198. UpdateWorldTransform();
  199. return worldTransform_.Translation();
  200. }
  201. /// Return rotation in world space.
  202. Quaternion GetWorldRotation() const
  203. {
  204. if (dirty_)
  205. UpdateWorldTransform();
  206. return worldRotation_;
  207. }
  208. /// Return direction in world space.
  209. Vector3 GetWorldDirection() const
  210. {
  211. if (dirty_)
  212. UpdateWorldTransform();
  213. return worldRotation_ * Vector3::FORWARD;
  214. }
  215. /// Return scale in world space.
  216. Vector3 GetWorldScale() const
  217. {
  218. if (dirty_)
  219. UpdateWorldTransform();
  220. return worldTransform_.Scale();
  221. }
  222. /// Return world space transform matrix.
  223. const Matrix3x4& GetWorldTransform() const
  224. {
  225. if (dirty_)
  226. UpdateWorldTransform();
  227. return worldTransform_;
  228. }
  229. /// Convert a local space position to world space.
  230. Vector3 LocalToWorld(const Vector3& position) const;
  231. /// Convert a local space position or rotation to world space.
  232. Vector3 LocalToWorld(const Vector4& vector) const;
  233. /// Convert a world space position to local space.
  234. Vector3 WorldToLocal(const Vector3& position) const;
  235. /// Convert a world space position or rotation to local space.
  236. Vector3 WorldToLocal(const Vector4& vector) const;
  237. /// Return whether transform has changed and world transform needs recalculation.
  238. bool IsDirty() const { return dirty_; }
  239. /// Return number of child scene nodes.
  240. unsigned GetNumChildren(bool recursive = false) const;
  241. /// Return immediate child scene nodes.
  242. const Vector<SharedPtr<Node> >& GetChildren() const { return children_; }
  243. /// Return child scene nodes, optionally recursive.
  244. void GetChildren(PODVector<Node*>& dest, bool recursive = false) const;
  245. /// Return child scene nodes with a specific component.
  246. void GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive = false) const;
  247. /// Return child scene node by index.
  248. Node* GetChild(unsigned index) const;
  249. /// Return child scene node by name.
  250. Node* GetChild(const String& name, bool recursive = false) const;
  251. /// Return child scene node by name.
  252. Node* GetChild(const char* name, bool recursive = false) const;
  253. /// Return child scene node by name hash.
  254. Node* GetChild(StringHash nameHash, bool recursive = false) const;
  255. /// Return number of components.
  256. unsigned GetNumComponents() const { return components_.Size(); }
  257. /// Return number of non-local components.
  258. unsigned GetNumNetworkComponents() const;
  259. /// Return all components.
  260. const Vector<SharedPtr<Component> >& GetComponents() const { return components_; }
  261. /// Return all components of type. Optionally recursive.
  262. void GetComponents(PODVector<Component*>& dest, ShortStringHash type, bool recursive = false) const;
  263. /// Return component by type. If there are several, returns the first.
  264. Component* GetComponent(ShortStringHash type) const;
  265. /// Return whether has a specific component.
  266. bool HasComponent(ShortStringHash type) const;
  267. /// Return listener components.
  268. const Vector<WeakPtr<Component> > GetListeners() const { return listeners_; }
  269. /// Return a user variable.
  270. const Variant& GetVar(ShortStringHash key) const;
  271. /// Return all user variables.
  272. const VariantMap& GetVars() const { return vars_; }
  273. /// Return first component derived from class.
  274. template <class T> T* GetDerivedComponent() const;
  275. /// Return components derived from class.
  276. template <class T> void GetDerivedComponents(PODVector<T*>& dest) const;
  277. /// Template version of returning child nodes with a specific component.
  278. template <class T> void GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive = false) const;
  279. /// Template version of returning a component by type.
  280. template <class T> T* GetComponent() const;
  281. /// Template version of returning all components of type.
  282. template <class T> void GetComponents(PODVector<T*>& dest, bool recursive = false) const;
  283. /// Template version of checking whether has a specific component.
  284. template <class T> bool HasComponent() const;
  285. /// Set ID. Called by Scene.
  286. void SetID(unsigned id);
  287. /// Set scene. Called by Scene.
  288. void SetScene(Scene* scene);
  289. /// Reset scene. Called by Scene.
  290. void ResetScene();
  291. /// Set network position attribute.
  292. void SetNetPositionAttr(const Vector3& value);
  293. /// Set network rotation attribute.
  294. void SetNetRotationAttr(const PODVector<unsigned char>& value);
  295. /// Set network parent attribute.
  296. void SetNetParentAttr(const PODVector<unsigned char>& value);
  297. /// Return network position attribute.
  298. const Vector3& GetNetPositionAttr() const;
  299. /// Return network rotation attribute.
  300. const PODVector<unsigned char>& GetNetRotationAttr() const;
  301. /// Return network parent attribute.
  302. const PODVector<unsigned char>& GetNetParentAttr() const;
  303. /// Load components and optionally load child nodes.
  304. bool Load(Deserializer& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  305. /// Load components from XML data and optionally load child nodes.
  306. bool LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  307. /// Return the depended on nodes to order network updates.
  308. const PODVector<Node*>& GetDependencyNodes() const { return dependencyNodes_; }
  309. /// Prepare network update by comparing attributes and marking replication states dirty as necessary.
  310. void PrepareNetworkUpdate();
  311. /// Clean up all references to a network connection that is about to be removed.
  312. void CleanupConnection(Connection* connection);
  313. /// Mark for attribute check on the next network update.
  314. void MarkNetworkUpdate();
  315. /// Mark node dirty in scene replication states.
  316. void MarkReplicationDirty();
  317. /// Create a child node with specific ID.
  318. Node* CreateChild(unsigned id, CreateMode mode);
  319. /// Add a pre-created component.
  320. void AddComponent(Component* component, unsigned id, CreateMode mode);
  321. /// Calculate number of non-temporary child nodes.
  322. unsigned GetNumPersistentChildren() const;
  323. /// Calculate number of non-temporary components.
  324. unsigned GetNumPersistentComponents() const;
  325. protected:
  326. /// User variables.
  327. VariantMap vars_;
  328. private:
  329. /// Recalculate the world transform.
  330. void UpdateWorldTransform() const;
  331. /// Remove child node by iterator.
  332. void RemoveChild(Vector<SharedPtr<Node> >::Iterator i);
  333. /// Return child nodes recursively.
  334. void GetChildrenRecursive(PODVector<Node*>& dest) const;
  335. /// Return child nodes with a specific component recursively.
  336. void GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const;
  337. /// Return specific components recursively.
  338. void GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const;
  339. /// Clone node recursively.
  340. Node* CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode);
  341. /// Remove a component from this node with the specified iterator.
  342. void RemoveComponent(Vector<SharedPtr<Component> >::Iterator i);
  343. /// World-space transform matrix.
  344. mutable Matrix3x4 worldTransform_;
  345. /// World transform needs update flag.
  346. mutable bool dirty_;
  347. /// Network update queued flag.
  348. bool networkUpdate_;
  349. /// Enabled flag.
  350. bool enabled_;
  351. /// Parent scene node.
  352. Node* parent_;
  353. /// Scene (root node.)
  354. Scene* scene_;
  355. /// Unique ID within the scene.
  356. unsigned id_;
  357. /// Position.
  358. Vector3 position_;
  359. /// Rotation.
  360. Quaternion rotation_;
  361. /// Scale.
  362. Vector3 scale_;
  363. /// World-space rotation.
  364. mutable Quaternion worldRotation_;
  365. /// Components.
  366. Vector<SharedPtr<Component> > components_;
  367. /// Child scene nodes.
  368. Vector<SharedPtr<Node> > children_;
  369. /// Node listeners.
  370. Vector<WeakPtr<Component> > listeners_;
  371. /// Nodes this node depends on for network updates.
  372. PODVector<Node*> dependencyNodes_;
  373. /// Network owner connection.
  374. Connection* owner_;
  375. /// Name.
  376. String name_;
  377. /// Name hash.
  378. StringHash nameHash_;
  379. /// Attribute buffer for network updates.
  380. mutable VectorBuffer attrBuffer_;
  381. };
  382. template <class T> T* Node::CreateComponent(CreateMode mode, unsigned id) { return static_cast<T*>(CreateComponent(T::GetTypeStatic(), mode, id)); }
  383. template <class T> T* Node::GetOrCreateComponent(CreateMode mode, unsigned id) { return static_cast<T*>(GetOrCreateComponent(T::GetTypeStatic(), mode, id)); }
  384. template <class T> void Node::RemoveComponent() { RemoveComponent(T::GetTypeStatic()); }
  385. template <class T> void Node::GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive) const { GetChildrenWithComponent(dest, T::GetTypeStatic(), recursive); }
  386. template <class T> T* Node::GetComponent() const { return static_cast<T*>(GetComponent(T::GetTypeStatic())); }
  387. template <class T> void Node::GetComponents(PODVector<T*>& dest, bool recursive) const { GetComponents(reinterpret_cast<PODVector<Component*>&>(dest), T::GetTypeStatic(), recursive); }
  388. template <class T> bool Node::HasComponent() const { return HasComponent(T::GetTypeStatic()); }
  389. template <class T> T* Node::GetDerivedComponent() const
  390. {
  391. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  392. {
  393. T* component = dynamic_cast<T*>(i->Get());
  394. if (component)
  395. return component;
  396. }
  397. return 0;
  398. }
  399. template <class T> void Node::GetDerivedComponents(PODVector<T*>& dest) const
  400. {
  401. dest.Clear();
  402. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  403. {
  404. T* component = dynamic_cast<T*>(i->Get());
  405. if (component)
  406. dest.Push(component);
  407. }
  408. }
  409. }