Node.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 Node : public Serializable
  41. {
  42. OBJECT(Node);
  43. friend class Connection;
  44. public:
  45. /// Construct.
  46. Node(Context* context);
  47. /// Destruct. Any child nodes are detached.
  48. virtual ~Node();
  49. /// Register object factory.
  50. static void RegisterObject(Context* context);
  51. /// Handle attribute write access.
  52. virtual void OnSetAttribute(const AttributeInfo& attr, const Variant& src);
  53. /// Load from binary data. Return true if successful.
  54. virtual bool Load(Deserializer& source);
  55. /// Load from XML data. Return true if successful.
  56. virtual bool LoadXML(const XMLElement& source);
  57. /// Save as binary data. Return true if successful.
  58. virtual bool Save(Serializer& dest);
  59. /// Save as XML data. Return true if successful.
  60. virtual bool SaveXML(XMLElement& dest);
  61. /// Apply attribute changes that can not be applied immediately recursively to child nodes and components.
  62. virtual void ApplyAttributes();
  63. /// Add a replication state that is tracking this node.
  64. virtual void AddReplicationState(NodeReplicationState* state);
  65. /// Save to an XML file. Return true if successful.
  66. bool SaveXML(Serializer& dest);
  67. /// Set name.
  68. void SetName(const String& name);
  69. /// Set position relative to parent node.
  70. void SetPosition(const Vector3& position);
  71. /// Set rotation relative to parent node.
  72. void SetRotation(const Quaternion& rotation);
  73. /// Set direction relative to parent node. Positive Z equals identity.
  74. void SetDirection(const Vector3& direction);
  75. /// Set uniform scale relative to parent node.
  76. void SetScale(float scale);
  77. /// Set scale relative to parent node.
  78. void SetScale(const Vector3& scale);
  79. /// Set transform relative to parent node.
  80. void SetTransform(const Vector3& position, const Quaternion& rotation);
  81. /// Set transform relative to parent node.
  82. void SetTransform(const Vector3& position, const Quaternion& rotation, float scale);
  83. /// Set transform relative to parent node.
  84. void SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  85. /// Set position relative to world space.
  86. void SetWorldPosition(const Vector3& position);
  87. /// Set rotation relative to world space.
  88. void SetWorldRotation(const Quaternion& rotation);
  89. /// Set direction relative to world space.
  90. void SetWorldDirection(const Vector3& direction);
  91. /// Set uniform scale relative to world space.
  92. void SetWorldScale(float scale);
  93. /// Set scale relative to world space.
  94. void SetWorldScale(const Vector3& scale);
  95. /// Set transform relative to world space.
  96. void SetWorldTransform(const Vector3& position, const Quaternion& rotation);
  97. /// Set transform relative to world space.
  98. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale);
  99. /// Set transform relative to world space.
  100. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  101. /// Move the scene node.
  102. void Translate(const Vector3& delta);
  103. /// Move the scene node relative to its rotation.
  104. void TranslateRelative(const Vector3& delta);
  105. /// Rotate the scene node.
  106. void Rotate(const Quaternion& delta, bool fixedAxis = false);
  107. /// Rotate around the X axis.
  108. void Pitch(float angle, bool fixedAxis = false);
  109. /// Rotate around the Y axis.
  110. void Yaw(float angle, bool fixedAxis = false);
  111. /// Rotate around the Z axis.
  112. void Roll(float angle, bool fixedAxis = false);
  113. /// Look at a target position.
  114. void LookAt(const Vector3& target, const Vector3& upAxis = Vector3::UP, bool worldSpace = false);
  115. /// Modify scale uniformly.
  116. void Scale(float scale);
  117. /// Modify scale.
  118. void Scale(const Vector3& scale);
  119. /// Set owner connection for networking.
  120. void SetOwner(Connection* owner);
  121. /// Mark node and child nodes to need world transform recalculation. Notify listener components.
  122. void MarkDirty();
  123. /// Create a child scene node.
  124. Node* CreateChild(const String& name = String::EMPTY, CreateMode mode = REPLICATED);
  125. /// Add a child scene node.
  126. void AddChild(Node* node);
  127. /// Remove a child scene node.
  128. void RemoveChild(Node* node);
  129. /// Remove all child scene nodes.
  130. void RemoveAllChildren();
  131. /// Create a component to this node (with specified ID if provided).
  132. Component* CreateComponent(ShortStringHash type, CreateMode mode = REPLICATED, unsigned id = 0);
  133. /// Create a component to this node if it does not exist already.
  134. Component* GetOrCreateComponent(ShortStringHash type, CreateMode mode = REPLICATED);
  135. /// Remove a component from this node.
  136. void RemoveComponent(Component* component);
  137. /// Remove the first component of specific type from this node.
  138. void RemoveComponent(ShortStringHash type);
  139. /// Remove all components from this node.
  140. void RemoveAllComponents();
  141. /// Clone scene node, components and child nodes. Return the clone.
  142. Node* Clone(CreateMode mode = REPLICATED);
  143. /// Remove from the parent node. If no other shared pointer references exist, causes immediate deletion.
  144. void Remove();
  145. /// Set parent scene node. Retains the world transform.
  146. void SetParent(Node* parent);
  147. /// Set a user variable.
  148. void SetVar(ShortStringHash key, const Variant& value);
  149. /// Add listener component that is notified of node being dirtied. Can either be in the same node or another.
  150. void AddListener(Component* component);
  151. /// Remove listener component.
  152. void RemoveListener(Component* component);
  153. /// Template version of creating a component.
  154. template <class T> T* CreateComponent(CreateMode mode = REPLICATED);
  155. /// Template version of getting or creating a component.
  156. template <class T> T* GetOrCreateComponent(CreateMode mode = REPLICATED);
  157. /// Return ID.
  158. unsigned GetID() const { return id_; }
  159. /// Return name.
  160. const String& GetName() const { return name_; }
  161. /// Return name hash.
  162. StringHash GetNameHash() const { return nameHash_; }
  163. /// Return parent scene node.
  164. Node* GetParent() const { return parent_; }
  165. /// Return scene.
  166. Scene* GetScene() const { return scene_; }
  167. /// Return owner connection in networking.
  168. Connection* GetOwner() const { return owner_; }
  169. /// Return position relative to parent node.
  170. const Vector3& GetPosition() const { return position_; }
  171. /// Return rotation relative to parent node.
  172. const Quaternion& GetRotation() const { return rotation_; }
  173. /// Return direction relative to parent node. Identity rotation equals positive Z.
  174. Vector3 GetDirection() const { return rotation_ * Vector3::FORWARD; }
  175. /// Return scale relative to parent node.
  176. const Vector3& GetScale() const { return scale_; }
  177. /// Return transform matrix relative to parent node.
  178. Matrix3x4 GetTransform() const { return Matrix3x4(position_, rotation_, scale_); }
  179. /// Return position in world space.
  180. Vector3 GetWorldPosition() const
  181. {
  182. return GetWorldTransform().Translation();
  183. }
  184. /// Return rotation in world space.
  185. Quaternion GetWorldRotation() const
  186. {
  187. return GetWorldTransform().Rotation();
  188. }
  189. /// Return direction in world space.
  190. Vector3 GetWorldDirection() const
  191. {
  192. return GetWorldTransform().RotationMatrix() * Vector3::FORWARD;
  193. }
  194. /// Return scale in world space.
  195. Vector3 GetWorldScale() const
  196. {
  197. return GetWorldTransform().Scale();
  198. }
  199. /// Return transform matrix in world space.
  200. const Matrix3x4& GetWorldTransform() const
  201. {
  202. if (dirty_)
  203. UpdateWorldTransform();
  204. return worldTransform_;
  205. }
  206. /// Convert a local space position to world space.
  207. Vector3 LocalToWorld(const Vector3& position) const;
  208. /// Convert a local space position or rotation to world space.
  209. Vector3 LocalToWorld(const Vector4& vector) const;
  210. /// Convert a world space position to local space.
  211. Vector3 WorldToLocal(const Vector3& position) const;
  212. /// Convert a world space position or rotation to local space.
  213. Vector3 WorldToLocal(const Vector4& vector) const;
  214. /// Return whether transform has changed and world transform needs recalculation.
  215. bool IsDirty() const { return dirty_; }
  216. /// Return number of child scene nodes.
  217. unsigned GetNumChildren(bool recursive = false) const;
  218. /// Return immediate child scene nodes.
  219. const Vector<SharedPtr<Node> >& GetChildren() const { return children_; }
  220. /// Return child scene nodes, optionally recursive.
  221. void GetChildren(PODVector<Node*>& dest, bool recursive = false) const;
  222. /// Return child scene nodes with a specific component.
  223. void GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive = false) const;
  224. /// Return child scene node by index.
  225. Node* GetChild(unsigned index) const;
  226. /// Return child scene node by name.
  227. Node* GetChild(const String& name, bool recursive = false) const;
  228. /// Return child scene node by name hash.
  229. Node* GetChild(StringHash nameHash, bool recursive = false) const;
  230. /// Return number of components.
  231. unsigned GetNumComponents() const { return components_.Size(); }
  232. /// Return number of non-local components.
  233. unsigned GetNumNetworkComponents() const;
  234. /// Return all components.
  235. const Vector<SharedPtr<Component> >& GetComponents() const { return components_; }
  236. /// Return all components of type.
  237. void GetComponents(PODVector<Component*>& dest, ShortStringHash type) const;
  238. /// Return component by type. If there are several, returns the first.
  239. Component* GetComponent(ShortStringHash type) const;
  240. /// Return whether has a specific component.
  241. bool HasComponent(ShortStringHash type) const;
  242. /// Return listener components.
  243. const Vector<WeakPtr<Component> > GetListeners() const { return listeners_; }
  244. /// Return a user variable.
  245. const Variant& GetVar(ShortStringHash key) const;
  246. /// Return all user variables.
  247. const VariantMap& GetVars() const { return vars_; }
  248. /// Return first component derived from class.
  249. template <class T> T* GetDerivedComponent() const;
  250. /// Return components derived from class.
  251. template <class T> void GetDerivedComponents(PODVector<T*>& dest) const;
  252. /// Template version of returning child nodes with a specific component.
  253. template <class T> void GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive = false) const;
  254. /// Template version of returning a component by type.
  255. template <class T> T* GetComponent() const;
  256. /// Template version of returning all components of type.
  257. template <class T> void GetComponents(PODVector<T*>& dest) const;
  258. /// Template version of checking whether has a specific component.
  259. template <class T> bool HasComponent() const;
  260. /// Set ID. Called by Scene.
  261. void SetID(unsigned id);
  262. /// Set scene. Called by Scene.
  263. void SetScene(Scene* scene);
  264. /// Reset scene. Called by Scene.
  265. void ResetScene();
  266. /// Set network position attribute.
  267. void SetNetPositionAttr(const Vector3& value);
  268. /// Set network rotation attribute.
  269. void SetNetRotationAttr(const PODVector<unsigned char>& value);
  270. /// Set network parent attribute.
  271. void SetNetParentAttr(const PODVector<unsigned char>& value);
  272. /// Return network position attribute.
  273. const Vector3& GetNetPositionAttr() const;
  274. /// Return network rotation attribute.
  275. const PODVector<unsigned char>& GetNetRotationAttr() const;
  276. /// Return network parent attribute.
  277. const PODVector<unsigned char>& GetNetParentAttr() const;
  278. /// Load components and optionally load child nodes.
  279. bool Load(Deserializer& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  280. /// Load components from XML data and optionally load child nodes.
  281. bool LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  282. /// Return the depended on nodes to order network updates.
  283. const PODVector<Node*>& GetDependencyNodes() const { return dependencyNodes_; }
  284. /// Prepare network update by comparing attributes and marking replication states dirty as necessary.
  285. void PrepareNetworkUpdate();
  286. /// Clean up all references to a network connection that is about to be removed.
  287. void CleanupConnection(Connection* connection);
  288. /// Mark for attribute check on the next network update.
  289. void MarkNetworkUpdate();
  290. /// Mark node dirty in scene replication states.
  291. void MarkReplicationDirty();
  292. /// Create a child node with specific ID.
  293. Node* CreateChild(unsigned id, CreateMode mode);
  294. /// Add a pre-created component.
  295. void AddComponent(Component* component, unsigned id, CreateMode mode);
  296. protected:
  297. /// User variables.
  298. VariantMap vars_;
  299. private:
  300. /// Recalculate the world transform.
  301. void UpdateWorldTransform() const;
  302. /// Remove child node by iterator.
  303. void RemoveChild(Vector<SharedPtr<Node> >::Iterator i);
  304. /// Return child nodes recursively.
  305. void GetChildrenRecursive(PODVector<Node*>& dest) const;
  306. /// Return child nodes with a specific component recursively.
  307. void GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const;
  308. /// Clone node recursively.
  309. Node* CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode);
  310. /// Remove a component from this node with the specified iterator.
  311. void RemoveComponent(Vector<SharedPtr<Component> >::Iterator i);
  312. /// World-space transform matrix.
  313. mutable Matrix3x4 worldTransform_;
  314. /// World transform needs update flag.
  315. mutable bool dirty_;
  316. /// Network update queued flag.
  317. bool networkUpdate_;
  318. /// Consecutive rotation count for rotation renormalization.
  319. unsigned short rotateCount_;
  320. /// Parent scene node.
  321. Node* parent_;
  322. /// Scene (root node.)
  323. Scene* scene_;
  324. /// Unique ID within the scene.
  325. unsigned id_;
  326. /// Position.
  327. Vector3 position_;
  328. /// Rotation.
  329. Quaternion rotation_;
  330. /// Scale.
  331. Vector3 scale_;
  332. /// Components.
  333. Vector<SharedPtr<Component> > components_;
  334. /// Child scene nodes.
  335. Vector<SharedPtr<Node> > children_;
  336. /// Node listeners.
  337. Vector<WeakPtr<Component> > listeners_;
  338. /// Nodes this node depends on for network updates.
  339. PODVector<Node*> dependencyNodes_;
  340. /// Network owner connection.
  341. Connection* owner_;
  342. /// Name.
  343. String name_;
  344. /// Name hash.
  345. StringHash nameHash_;
  346. /// Attribute buffer for network updates.
  347. mutable VectorBuffer attrBuffer_;
  348. };
  349. template <class T> T* Node::CreateComponent(CreateMode mode) { return static_cast<T*>(CreateComponent(T::GetTypeStatic(), mode)); }
  350. template <class T> T* Node::GetOrCreateComponent(CreateMode mode) { return static_cast<T*>(GetOrCreateComponent(T::GetTypeStatic(), mode)); }
  351. template <class T> void Node::GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive) const { GetChildrenWithComponent(dest, T::GetTypeStatic(), recursive); }
  352. template <class T> T* Node::GetComponent() const { return static_cast<T*>(GetComponent(T::GetTypeStatic())); }
  353. template <class T> void Node::GetComponents(PODVector<T*>& dest) const { GetComponents(reinterpret_cast<PODVector<Component*>&>(dest), T::GetTypeStatic()); }
  354. template <class T> bool Node::HasComponent() const { return HasComponent(T::GetTypeStatic()); }
  355. template <class T> T* Node::GetDerivedComponent() const
  356. {
  357. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  358. {
  359. T* component = dynamic_cast<T*>(i->Get());
  360. if (component)
  361. return component;
  362. }
  363. return 0;
  364. }
  365. template <class T> void Node::GetDerivedComponents(PODVector<T*>& dest) const
  366. {
  367. dest.Clear();
  368. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  369. {
  370. T* component = dynamic_cast<T*>(i->Get());
  371. if (component)
  372. dest.Push(component);
  373. }
  374. }
  375. }