BsSceneObject.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. #pragma once
  2. #include "BsCorePrerequisites.h"
  3. #include "BsMatrix4.h"
  4. #include "BsVector3.h"
  5. #include "BsQuaternion.h"
  6. #include "BsRTTIType.h"
  7. #include "BsCoreSceneManager.h"
  8. #include "BsGameObjectManager.h"
  9. #include "BsGameObject.h"
  10. #include "BsComponent.h"
  11. namespace BansheeEngine
  12. {
  13. /**
  14. * @brief Possible modifiers that can be applied to a SceneObject
  15. */
  16. enum SceneObjectFlags
  17. {
  18. SOF_DontInstantiate = 0x01, /**< Object wont be in the main scene and its components won't receive updates. */
  19. SOF_DontSave = 0x02 /**< Object will be skipped when saving the scene hierarchy or a prefab. */
  20. };
  21. /**
  22. * @brief SceneObject represents an object in the scene graph. It has a world position,
  23. * place in the hierarchy and optionally a number of attached components.
  24. */
  25. class BS_CORE_EXPORT SceneObject : public GameObject
  26. {
  27. /**
  28. * @brief Flags that signify which part of the SceneObject needs updating.
  29. */
  30. enum DirtyFlags
  31. {
  32. LocalTfrmDirty = 0x01,
  33. WorldTfrmDirty = 0x02
  34. };
  35. friend class CoreSceneManager;
  36. friend class Prefab;
  37. friend class PrefabDiff;
  38. public:
  39. ~SceneObject();
  40. /**
  41. * @brief Creates a new SceneObject with the specified name. Object will be placed in the top
  42. * of the scene hierarchy.
  43. */
  44. static HSceneObject create(const String& name, UINT32 flags = 0);
  45. /**
  46. * @brief Destroys this object and any of its held components.
  47. *
  48. * @param [in] immediate If true, the object will be deallocated and become unusable
  49. * right away. Otherwise the deallocation will be delayed to the end of
  50. * frame (preferred method).
  51. */
  52. void destroy(bool immediate = false);
  53. /**
  54. * @copydoc GameObject::_setInstanceData
  55. */
  56. void _setInstanceData(GameObjectInstanceDataPtr& other);
  57. /**
  58. * @brief Returns a handle to this object.
  59. */
  60. HSceneObject getHandle() const { return mThisHandle; }
  61. /**
  62. * @brief Returns the prefab this object is linked to, if any.
  63. *
  64. * @note Requires a search of all parents potentially.
  65. */
  66. HPrefab getPrefabLink() const;
  67. private:
  68. SceneObject(const String& name, UINT32 flags);
  69. /**
  70. * @brief Creates a new SceneObject instance, registers it with the game object manager,
  71. * creates and returns a handle to the new object.
  72. *
  73. * @note When creating objects with DontInstantiate flag it is the callers responsibility
  74. * to manually destroy the object, otherwise it will leak.
  75. */
  76. static HSceneObject createInternal(const String& name, UINT32 flags = 0);
  77. /**
  78. * @brief Destroys this object and any of its held components.
  79. *
  80. * @param [in] immediate If true, the object will be deallocated and become unusable
  81. * right away. Otherwise the deallocation will be delayed to the end of
  82. * frame (preferred method).
  83. *
  84. * @note Unlike "destroy", does not remove the object from its parent.
  85. */
  86. void destroyInternal(bool immediate = false);
  87. /**
  88. * @brief Recursively enables the provided set of flags on
  89. * this object and all children.
  90. */
  91. void setFlags(UINT32 flags);
  92. /**
  93. * @brief Recursively disables the provided set of flags on
  94. * this object and all children.
  95. */
  96. void unsetFlags(UINT32 flags);
  97. /**
  98. * @brief Checks is the scene object instantiated and visible in the scene.
  99. */
  100. bool isInstantiated() const { return (mFlags & SOF_DontInstantiate) == 0; }
  101. /**
  102. * @brief Register the scene object with the scene and activate all of its components.
  103. */
  104. void instantiate();
  105. private:
  106. HSceneObject mThisHandle;
  107. HPrefab mPrefabLink;
  108. UINT32 mFlags;
  109. /************************************************************************/
  110. /* Transform */
  111. /************************************************************************/
  112. public:
  113. /**
  114. * @brief Sets the local position of the object.
  115. */
  116. void setPosition(const Vector3& position);
  117. /**
  118. * @brief Gets the local position of the object.
  119. */
  120. const Vector3& getPosition() const { return mPosition; }
  121. /**
  122. * @brief Sets the world position of the object.
  123. */
  124. void setWorldPosition(const Vector3& position);
  125. /**
  126. * @brief Gets the world position of the object.
  127. *
  128. * @note Performance warning: This might involve updating the transforms if the transform is dirty.
  129. */
  130. const Vector3& getWorldPosition() const;
  131. /**
  132. * @brief Sets the local rotation of the object.
  133. */
  134. void setRotation(const Quaternion& rotation);
  135. /**
  136. * @brief Gets the local rotation of the object.
  137. */
  138. const Quaternion& getRotation() const { return mRotation; }
  139. /**
  140. * @brief Sets the world rotation of the object.
  141. */
  142. void setWorldRotation(const Quaternion& rotation);
  143. /**
  144. * @brief Gets world rotation of the object.
  145. *
  146. * @note Performance warning: This might involve updating the transforms if the transform is dirty.
  147. */
  148. const Quaternion& getWorldRotation() const;
  149. /**
  150. * @brief Sets the local scale of the object.
  151. */
  152. void setScale(const Vector3& scale);
  153. /**
  154. * @brief Gets the local scale of the object.
  155. */
  156. const Vector3& getScale() const { return mScale; }
  157. /**
  158. * @brief Sets the world scale of the object.
  159. *
  160. * @note This will not work properly if this object or any of its parents
  161. * have non-affine transform matrices.
  162. */
  163. void setWorldScale(const Vector3& scale);
  164. /**
  165. * @brief Gets world scale of the object.
  166. *
  167. * @note Performance warning: This might involve updating the transforms if the transform is dirty.
  168. */
  169. const Vector3& getWorldScale() const;
  170. /**
  171. * @brief Orients the object so it is looking at the provided "location" (local space)
  172. * where "up" is used for determining the location of the objects Y axis.
  173. *
  174. */
  175. void lookAt(const Vector3& location, const Vector3& up = Vector3::UNIT_Y);
  176. /**
  177. * @brief Gets the objects world transform matrix.
  178. *
  179. * @note Performance warning: This might involve updating the transforms if the transform is dirty.
  180. */
  181. const Matrix4& getWorldTfrm() const;
  182. /**
  183. * @brief Gets the objects local transform matrix.
  184. */
  185. const Matrix4& getLocalTfrm() const;
  186. /**
  187. * @brief Moves the object's position by the vector offset provided along world axes.
  188. */
  189. void move(const Vector3& vec);
  190. /**
  191. * @brief Moves the object's position by the vector offset provided along it's own axes (relative to orientation).
  192. */
  193. void moveRelative(const Vector3& vec);
  194. /**
  195. * @brief Gets the Z (forward) axis of the object, in world space.
  196. *
  197. * @return Forward axis of the object.
  198. */
  199. Vector3 getForward() const { return getWorldRotation().rotate(-Vector3::UNIT_Z); }
  200. /**
  201. * @brief Gets the Y (up) axis of the object, in world space.
  202. *
  203. * @return Up axis of the object.
  204. */
  205. Vector3 getUp() const { return getWorldRotation().rotate(Vector3::UNIT_Y); }
  206. /**
  207. * @brief Gets the X (right) axis of the object, in world space.
  208. *
  209. * @return Right axis of the object.
  210. */
  211. Vector3 getRight() const { return getWorldRotation().rotate(Vector3::UNIT_X); }
  212. /**
  213. * @brief Rotates the game object so it's forward axis faces the provided
  214. * direction.
  215. *
  216. * @note Local forward axis is considered to be negative Z.
  217. *
  218. * @param forwardDir The forward direction to face, in world space.
  219. */
  220. void setForward(const Vector3& forwardDir);
  221. /**
  222. * @brief Rotate the object around an arbitrary axis.
  223. */
  224. void rotate(const Vector3& axis, const Radian& angle);
  225. /**
  226. * @brief Rotate the object around an arbitrary axis using a Quaternion.
  227. */
  228. void rotate(const Quaternion& q);
  229. /**
  230. * @brief Rotates around local Z axis.
  231. *
  232. * @param angle Angle to rotate by.
  233. */
  234. void roll(const Radian& angle);
  235. /**
  236. * @brief Rotates around Y axis.
  237. *
  238. * @param angle Angle to rotate by.
  239. */
  240. void yaw(const Radian& angle);
  241. /**
  242. * @brief Rotates around X axis
  243. *
  244. * @param angle Angle to rotate by.
  245. */
  246. void pitch(const Radian& angle);
  247. /**
  248. * @brief Forces any dirty transform matrices on this object to be updated.
  249. *
  250. * @note Normally this is done internally when retrieving a transform, but sometimes
  251. * it is useful to update transforms manually.
  252. */
  253. void updateTransformsIfDirty();
  254. /**
  255. * @brief Returns a hash value that changes whenever a scene objects
  256. * transform gets updated. It allows you to detect changes with
  257. * the local or world transforms without directly comparing their
  258. * values with some older state.
  259. */
  260. UINT32 getTransformHash() const { return mDirtyHash; }
  261. private:
  262. Vector3 mPosition;
  263. Quaternion mRotation;
  264. Vector3 mScale;
  265. mutable Vector3 mWorldPosition;
  266. mutable Quaternion mWorldRotation;
  267. mutable Vector3 mWorldScale;
  268. mutable Matrix4 mCachedLocalTfrm;
  269. mutable Matrix4 mCachedWorldTfrm;
  270. mutable UINT32 mDirtyFlags;
  271. mutable UINT32 mDirtyHash;
  272. /**
  273. * @brief Marks the transform as dirty so that we know to update
  274. * it when the transform is requested.
  275. */
  276. void markTfrmDirty() const;
  277. /**
  278. * @brief Updates the local transform. Normally just reconstructs the
  279. * transform matrix from the position/rotation/scale.
  280. */
  281. void updateLocalTfrm() const;
  282. /**
  283. * @brief Updates the world transform. Reconstructs the local transform
  284. * matrix and multiplies it with any parent transforms.
  285. *
  286. * @note If parent transforms are dirty they will be updated.
  287. */
  288. void updateWorldTfrm() const;
  289. /**
  290. * @brief Checks if cached local transform needs updating.
  291. */
  292. bool isCachedLocalTfrmUpToDate() const { return (mDirtyFlags & DirtyFlags::LocalTfrmDirty) == 0; }
  293. /**
  294. * @brief Checks if cached world transform needs updating.
  295. */
  296. bool isCachedWorldTfrmUpToDate() const { return (mDirtyFlags & DirtyFlags::WorldTfrmDirty) == 0; }
  297. /************************************************************************/
  298. /* Hierarchy */
  299. /************************************************************************/
  300. public:
  301. /**
  302. * @brief Changes the parent of this object. Also removes the object from the current parent,
  303. * and assigns it to the new parent.
  304. *
  305. * @param [in] parent New parent.
  306. */
  307. void setParent(const HSceneObject& parent);
  308. /**
  309. * @brief Gets the parent of this object.
  310. *
  311. * @return Parent object, or nullptr if this SceneObject is at root level.
  312. */
  313. HSceneObject getParent() const { return mParent; }
  314. /**
  315. * @brief Gets a child of this item.
  316. *
  317. * @param idx The zero based index of the child.
  318. *
  319. * @return SceneObject of the child.
  320. */
  321. HSceneObject getChild(UINT32 idx) const;
  322. /**
  323. * @brief Find the index of the specified child. Don't persist this value as
  324. * it may change whenever you add/remove children.
  325. *
  326. * @param child The child to look for.
  327. *
  328. * @return The zero-based index of the found child, or -1 if no match was found.
  329. */
  330. int indexOfChild(const HSceneObject& child) const;
  331. /**
  332. * @brief Gets the number of all child GameObjects.
  333. */
  334. UINT32 getNumChildren() const { return (UINT32)mChildren.size(); }
  335. /**
  336. * @brief Enables or disables this object. Disabled objects also implicitly disable
  337. * all their child objects. No components on the disabled object are updated.
  338. */
  339. void setActive(bool active);
  340. /**
  341. * @brief Returns whether or not an object is active.
  342. *
  343. * @param self If true, the method will only check if this particular object was activated
  344. * or deactivated directly via setActive. If false we we also check if any of
  345. * the objects parents are inactive.
  346. */
  347. bool getActive(bool self = false);
  348. /**
  349. * @brief Makes a deep copy of this object.
  350. */
  351. HSceneObject clone();
  352. private:
  353. HSceneObject mParent;
  354. Vector<HSceneObject> mChildren;
  355. bool mActiveSelf;
  356. bool mActiveHierarchy;
  357. /**
  358. * @brief Adds a child to the child array. This method doesn't check for null or duplicate values.
  359. *
  360. * @param [in] object New child.
  361. */
  362. void addChild(const HSceneObject& object);
  363. /**
  364. * @brief Removes the child from the object.
  365. *
  366. * @param [in] object Child to remove.
  367. *
  368. * @throws INTERNAL_ERROR If the provided child isn't a child of the current object.
  369. */
  370. void removeChild(const HSceneObject& object);
  371. /**
  372. * @brief Changes the object active in hierarchy state.
  373. */
  374. void setActiveHierarchy(bool active);
  375. /************************************************************************/
  376. /* Component */
  377. /************************************************************************/
  378. public:
  379. /**
  380. * @brief Constructs a new component of the specified type and adds it to
  381. * the internal component list.
  382. */
  383. template<class T, class... Args>
  384. GameObjectHandle<T> addComponent(Args &&... args)
  385. {
  386. static_assert((std::is_base_of<BansheeEngine::Component, T>::value),
  387. "Specified type is not a valid Component.");
  388. std::shared_ptr<T> gameObject(new (bs_alloc<T, PoolAlloc>()) T(mThisHandle,
  389. std::forward<Args>(args)...),
  390. &bs_delete<PoolAlloc, T>, StdAlloc<T, PoolAlloc>());
  391. GameObjectHandle<T> newComponent =
  392. GameObjectHandle<T>(GameObjectManager::instance().registerObject(gameObject));
  393. mComponents.push_back(newComponent);
  394. if (isInstantiated())
  395. newComponent->onInitialized();
  396. return newComponent;
  397. }
  398. /**
  399. * @brief Searches for a component with the specific type and returns the first one
  400. * it finds.
  401. *
  402. * @note Don't call this too often as it is relatively slow. It is more efficient
  403. * to call it once and store the result for further use.
  404. *
  405. * @tparam typename T Type of the component.
  406. *
  407. * @return Component if found, nullptr otherwise.
  408. */
  409. template <typename T>
  410. GameObjectHandle<T> getComponent()
  411. {
  412. static_assert((std::is_base_of<BansheeEngine::Component, T>::value),
  413. "Specified type is not a valid Component.");
  414. return static_object_cast<T>(getComponent(T::getRTTIStatic()->getRTTIId()));
  415. }
  416. /**
  417. * @brief Checks if the current object contains the specified component
  418. *
  419. * @note Don't call this too often as it is relatively slow.
  420. *
  421. * @tparam typename T Type of the component.
  422. *
  423. * @return True if component exists on the object.
  424. */
  425. template <typename T>
  426. bool hasComponent()
  427. {
  428. static_assert((std::is_base_of<BansheeEngine::Component, T>::value),
  429. "Specified type is not a valid Component.");
  430. for (auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  431. {
  432. if ((*iter)->getRTTI()->getRTTIId() == T::getRTTIStatic()->getRTTIId())
  433. return true;
  434. }
  435. return false;
  436. }
  437. /**
  438. * @brief Searches for a component with the specified type id and returns the first one it
  439. * finds.
  440. *
  441. * @note Don't call this too often as it is relatively slow. It is more efficient to
  442. * call it once and store the result for further use.
  443. *
  444. * @param typeId Identifier for the type.
  445. *
  446. * @return Component if found, nullptr otherwise.
  447. */
  448. HComponent getComponent(UINT32 typeId) const;
  449. /**
  450. * @brief Removes the component from this object, and deallocates it.
  451. *
  452. * @param [in] component The component to destroy.
  453. * @param [in] immediate If true, the component will be deallocated and become unusable
  454. * right away. Otherwise the deallocation will be delayed to the end of
  455. * frame (preferred method).
  456. */
  457. void destroyComponent(const HComponent& component, bool immediate = false);
  458. /**
  459. * @brief Removes the component from this object, and deallocates it.
  460. *
  461. * @param [in] component The component to destroy.
  462. * @param [in] immediate If true, the component will be deallocated and become unusable
  463. * right away. Otherwise the deallocation will be delayed to the end of
  464. * frame (preferred method).
  465. */
  466. void destroyComponent(Component* component, bool immediate = false);
  467. /**
  468. * @brief Returns all components on this object.
  469. */
  470. const Vector<HComponent>& getComponents() const { return mComponents; }
  471. private:
  472. /**
  473. * @brief Creates an empty component with the default constructor.
  474. */
  475. template <typename T>
  476. static std::shared_ptr<T> createEmptyComponent()
  477. {
  478. static_assert((std::is_base_of<BansheeEngine::Component, T>::value), "Specified type is not a valid Component.");
  479. std::shared_ptr<T> gameObject(new (bs_alloc<T, PoolAlloc>()) T(), &bs_delete<PoolAlloc, T>, StdAlloc<T, PoolAlloc>());
  480. GameObjectHandle<T>(GameObjectManager::instance().registerObject(gameObject));
  481. return gameObject;
  482. }
  483. /**
  484. * @brief Adds the component to the internal component array.
  485. */
  486. void addComponentInternal(const std::shared_ptr<Component> component);
  487. Vector<HComponent> mComponents;
  488. /************************************************************************/
  489. /* RTTI */
  490. /************************************************************************/
  491. public:
  492. friend class GameObjectRTTI;
  493. friend class SceneObjectRTTI;
  494. static RTTITypeBase* getRTTIStatic();
  495. virtual RTTITypeBase* getRTTI() const;
  496. };
  497. }