BsSceneObject.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. #include "BsSceneObject.h"
  2. #include "BsComponent.h"
  3. #include "BsCoreSceneManager.h"
  4. #include "BsException.h"
  5. #include "BsDebug.h"
  6. #include "BsSceneObjectRTTI.h"
  7. #include "BsMemorySerializer.h"
  8. #include "BsGameObjectManager.h"
  9. namespace BansheeEngine
  10. {
  11. SceneObject::SceneObject(const String& name)
  12. :GameObject(), mPosition(Vector3::ZERO), mRotation(Quaternion::IDENTITY), mScale(Vector3::ONE),
  13. mWorldPosition(Vector3::ZERO), mWorldRotation(Quaternion::IDENTITY), mWorldScale(Vector3::ONE),
  14. mCachedLocalTfrm(Matrix4::IDENTITY), mDirtyFlags(0xFFFFFFFF), mCachedWorldTfrm(Matrix4::IDENTITY),
  15. mActiveSelf(true), mActiveHierarchy(true), mDirtyHash(0)
  16. {
  17. setName(name);
  18. }
  19. SceneObject::~SceneObject()
  20. {
  21. if(!mThisHandle.isDestroyed())
  22. {
  23. LOGWRN("Object is being deleted without being destroyed first?");
  24. destroyInternal(true);
  25. }
  26. }
  27. HSceneObject SceneObject::create(const String& name)
  28. {
  29. HSceneObject newObject = createInternal(name);
  30. gCoreSceneManager().registerNewSO(newObject);
  31. return newObject;
  32. }
  33. HSceneObject SceneObject::createInternal(const String& name)
  34. {
  35. std::shared_ptr<SceneObject> sceneObjectPtr = std::shared_ptr<SceneObject>(new (bs_alloc<SceneObject, PoolAlloc>()) SceneObject(name),
  36. &bs_delete<PoolAlloc, SceneObject>, StdAlloc<SceneObject, PoolAlloc>());
  37. HSceneObject sceneObject = GameObjectManager::instance().registerObject(sceneObjectPtr);
  38. sceneObject->mThisHandle = sceneObject;
  39. return sceneObject;
  40. }
  41. void SceneObject::destroy(bool immediate)
  42. {
  43. // Parent is our owner, so when his reference to us is removed, delete might be called.
  44. // So make sure this is the last thing we do.
  45. if(mParent != nullptr)
  46. {
  47. if(!mParent.isDestroyed())
  48. mParent->removeChild(mThisHandle);
  49. }
  50. destroyInternal(immediate);
  51. }
  52. void SceneObject::destroyInternal(bool immediate)
  53. {
  54. for(auto iter = mChildren.begin(); iter != mChildren.end(); ++iter)
  55. (*iter)->destroyInternal(immediate);
  56. mChildren.clear();
  57. for(auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  58. {
  59. (*iter)->onDestroyed();
  60. if (immediate)
  61. {
  62. GameObjectManager::instance().unregisterObject(*iter);
  63. (*iter).destroy();
  64. }
  65. else
  66. GameObjectManager::instance().queueForDestroy(*iter);
  67. }
  68. mComponents.clear();
  69. if (immediate)
  70. {
  71. GameObjectManager::instance().unregisterObject(mThisHandle);
  72. mThisHandle.destroy();
  73. }
  74. else
  75. GameObjectManager::instance().queueForDestroy(mThisHandle);
  76. }
  77. void SceneObject::_setInstanceData(GameObjectInstanceDataPtr& other)
  78. {
  79. GameObject::_setInstanceData(other);
  80. // Instance data changed, so make sure to refresh the handles to reflect that
  81. mThisHandle._setHandleData(mThisHandle.getInternalPtr());
  82. }
  83. /************************************************************************/
  84. /* Transform */
  85. /************************************************************************/
  86. void SceneObject::setPosition(const Vector3& position)
  87. {
  88. mPosition = position;
  89. markTfrmDirty();
  90. }
  91. void SceneObject::setRotation(const Quaternion& rotation)
  92. {
  93. mRotation = rotation;
  94. markTfrmDirty();
  95. }
  96. void SceneObject::setScale(const Vector3& scale)
  97. {
  98. mScale = scale;
  99. markTfrmDirty();
  100. }
  101. void SceneObject::setWorldPosition(const Vector3& position)
  102. {
  103. if (mParent != nullptr)
  104. {
  105. Vector3 invScale = mParent->getWorldScale();
  106. if (invScale.x != 0) invScale.x = 1.0f / invScale.x;
  107. if (invScale.y != 0) invScale.y = 1.0f / invScale.y;
  108. if (invScale.z != 0) invScale.z = 1.0f / invScale.z;
  109. Quaternion invRotation = mParent->getWorldRotation().inverse();
  110. mPosition = invRotation.rotate(position - mParent->getWorldPosition()) * invScale;
  111. }
  112. else
  113. mPosition = position;
  114. markTfrmDirty();
  115. }
  116. void SceneObject::setWorldRotation(const Quaternion& rotation)
  117. {
  118. if (mParent != nullptr)
  119. {
  120. Quaternion invRotation = mParent->getWorldRotation().inverse();
  121. mRotation = invRotation * rotation;
  122. }
  123. else
  124. mRotation = rotation;
  125. markTfrmDirty();
  126. }
  127. const Vector3& SceneObject::getWorldPosition() const
  128. {
  129. if (!isCachedWorldTfrmUpToDate())
  130. updateWorldTfrm();
  131. return mWorldPosition;
  132. }
  133. const Quaternion& SceneObject::getWorldRotation() const
  134. {
  135. if (!isCachedWorldTfrmUpToDate())
  136. updateWorldTfrm();
  137. return mWorldRotation;
  138. }
  139. const Vector3& SceneObject::getWorldScale() const
  140. {
  141. if (!isCachedWorldTfrmUpToDate())
  142. updateWorldTfrm();
  143. return mWorldScale;
  144. }
  145. void SceneObject::lookAt(const Vector3& location, const Vector3& up)
  146. {
  147. Vector3 forward = location - mPosition;
  148. forward.normalize();
  149. setForward(forward);
  150. Quaternion upRot = Quaternion::getRotationFromTo(getUp(), up);
  151. setRotation(getRotation() * upRot);
  152. }
  153. const Matrix4& SceneObject::getWorldTfrm() const
  154. {
  155. if (!isCachedWorldTfrmUpToDate())
  156. updateWorldTfrm();
  157. return mCachedWorldTfrm;
  158. }
  159. const Matrix4& SceneObject::getLocalTfrm() const
  160. {
  161. if (!isCachedLocalTfrmUpToDate())
  162. updateLocalTfrm();
  163. return mCachedLocalTfrm;
  164. }
  165. void SceneObject::move(const Vector3& vec)
  166. {
  167. setPosition(mPosition + vec);
  168. }
  169. void SceneObject::moveRelative(const Vector3& vec)
  170. {
  171. // Transform the axes of the relative vector by camera's local axes
  172. Vector3 trans = mRotation.rotate(vec);
  173. setPosition(mPosition + trans);
  174. }
  175. void SceneObject::rotate(const Vector3& axis, const Radian& angle)
  176. {
  177. Quaternion q;
  178. q.fromAxisAngle(axis, angle);
  179. rotate(q);
  180. }
  181. void SceneObject::rotate(const Quaternion& q)
  182. {
  183. // Note the order of the mult, i.e. q comes after
  184. // Normalize the quat to avoid cumulative problems with precision
  185. Quaternion qnorm = q;
  186. qnorm.normalize();
  187. setRotation(qnorm * mRotation);
  188. }
  189. void SceneObject::roll(const Radian& angle)
  190. {
  191. // Rotate around local Z axis
  192. Vector3 zAxis = mRotation.rotate(Vector3::UNIT_Z);
  193. rotate(zAxis, angle);
  194. }
  195. void SceneObject::yaw(const Radian& angle)
  196. {
  197. Vector3 yAxis = mRotation.rotate(Vector3::UNIT_Y);
  198. rotate(yAxis, angle);
  199. }
  200. void SceneObject::pitch(const Radian& angle)
  201. {
  202. // Rotate around local X axis
  203. Vector3 xAxis = mRotation.rotate(Vector3::UNIT_X);
  204. rotate(xAxis, angle);
  205. }
  206. void SceneObject::setForward(const Vector3& forwardDir)
  207. {
  208. if (forwardDir == Vector3::ZERO)
  209. return;
  210. Vector3 nrmForwardDir = Vector3::normalize(forwardDir);
  211. Vector3 currentForwardDir = getForward();
  212. const Quaternion& currentRotation = getWorldRotation();
  213. Quaternion targetRotation;
  214. if ((nrmForwardDir+currentForwardDir).squaredLength() < 0.00005f)
  215. {
  216. // Oops, a 180 degree turn (infinite possible rotation axes)
  217. // Default to yaw i.e. use current UP
  218. targetRotation = Quaternion(-currentRotation.y, -currentRotation.z, currentRotation.w, currentRotation.x);
  219. }
  220. else
  221. {
  222. // Derive shortest arc to new direction
  223. Quaternion rotQuat = Quaternion::getRotationFromTo(currentForwardDir, nrmForwardDir);
  224. targetRotation = rotQuat * currentRotation;
  225. }
  226. setRotation(targetRotation);
  227. }
  228. void SceneObject::updateTransformsIfDirty()
  229. {
  230. if (!isCachedLocalTfrmUpToDate())
  231. updateLocalTfrm();
  232. if (!isCachedWorldTfrmUpToDate())
  233. updateWorldTfrm();
  234. }
  235. void SceneObject::markTfrmDirty() const
  236. {
  237. mDirtyFlags |= DirtyFlags::LocalTfrmDirty | DirtyFlags::WorldTfrmDirty;
  238. mDirtyHash++;
  239. for(auto iter = mChildren.begin(); iter != mChildren.end(); ++iter)
  240. {
  241. (*iter)->markTfrmDirty();
  242. }
  243. }
  244. void SceneObject::updateWorldTfrm() const
  245. {
  246. if(mParent != nullptr)
  247. {
  248. mCachedWorldTfrm = getLocalTfrm() * mParent->getWorldTfrm();
  249. // Update orientation
  250. const Quaternion& parentOrientation = mParent->getWorldRotation();
  251. mWorldRotation = parentOrientation * mRotation;
  252. // Update scale
  253. const Vector3& parentScale = mParent->getWorldScale();
  254. // Scale own position by parent scale, just combine
  255. // as equivalent axes, no shearing
  256. mWorldScale = parentScale * mScale;
  257. // Change position vector based on parent's orientation & scale
  258. mWorldPosition = parentOrientation.rotate(parentScale * mPosition);
  259. // Add altered position vector to parents
  260. mWorldPosition += mParent->getWorldPosition();
  261. }
  262. else
  263. {
  264. mCachedWorldTfrm = getLocalTfrm();
  265. mWorldRotation = mRotation;
  266. mWorldPosition = mPosition;
  267. mWorldScale = mScale;
  268. }
  269. mDirtyFlags &= ~DirtyFlags::WorldTfrmDirty;
  270. }
  271. void SceneObject::updateLocalTfrm() const
  272. {
  273. mCachedLocalTfrm.setTRS(mPosition, mRotation, mScale);
  274. mDirtyFlags &= ~DirtyFlags::LocalTfrmDirty;
  275. }
  276. /************************************************************************/
  277. /* Hierarchy */
  278. /************************************************************************/
  279. void SceneObject::setParent(const HSceneObject& parent)
  280. {
  281. if(parent.isDestroyed())
  282. {
  283. BS_EXCEPT(InternalErrorException,
  284. "Trying to assign a SceneObject parent that is destroyed.");
  285. }
  286. if(mParent == nullptr || mParent != parent)
  287. {
  288. if(mParent != nullptr)
  289. mParent->removeChild(mThisHandle);
  290. if(parent != nullptr)
  291. parent->addChild(mThisHandle);
  292. mParent = parent;
  293. markTfrmDirty();
  294. }
  295. }
  296. HSceneObject SceneObject::getChild(UINT32 idx) const
  297. {
  298. if(idx < 0 || idx >= mChildren.size())
  299. {
  300. BS_EXCEPT(InternalErrorException, "Child index out of range.");
  301. }
  302. return mChildren[idx];
  303. }
  304. int SceneObject::indexOfChild(const HSceneObject& child) const
  305. {
  306. for(int i = 0; i < (int)mChildren.size(); i++)
  307. {
  308. if(mChildren[i] == child)
  309. return i;
  310. }
  311. return -1;
  312. }
  313. void SceneObject::addChild(const HSceneObject& object)
  314. {
  315. mChildren.push_back(object);
  316. }
  317. void SceneObject::removeChild(const HSceneObject& object)
  318. {
  319. auto result = find(mChildren.begin(), mChildren.end(), object);
  320. if(result != mChildren.end())
  321. mChildren.erase(result);
  322. else
  323. {
  324. BS_EXCEPT(InternalErrorException,
  325. "Trying to remove a child but it's not a child of the transform.");
  326. }
  327. }
  328. void SceneObject::setActive(bool active)
  329. {
  330. mActiveSelf = active;
  331. setActiveHierarchy(active);
  332. }
  333. void SceneObject::setActiveHierarchy(bool active)
  334. {
  335. mActiveHierarchy = active && mActiveSelf;
  336. for (auto child : mChildren)
  337. {
  338. child->setActiveHierarchy(mActiveHierarchy);
  339. }
  340. }
  341. bool SceneObject::getActive(bool self)
  342. {
  343. if (self)
  344. return mActiveSelf;
  345. else
  346. return mActiveHierarchy;
  347. }
  348. HSceneObject SceneObject::clone()
  349. {
  350. UINT32 bufferSize = 0;
  351. MemorySerializer serializer;
  352. UINT8* buffer = serializer.encode(this, bufferSize, &bs_alloc);
  353. GameObjectManager::instance().setDeserializationMode(GODM_UseNewIds | GODM_RestoreExternal);
  354. std::shared_ptr<SceneObject> cloneObj = std::static_pointer_cast<SceneObject>(serializer.decode(buffer, bufferSize));
  355. bs_free(buffer);
  356. return cloneObj->mThisHandle;
  357. }
  358. HComponent SceneObject::getComponent(UINT32 typeId) const
  359. {
  360. for(auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  361. {
  362. if((*iter)->getRTTI()->getRTTIId() == typeId)
  363. return *iter;
  364. }
  365. return HComponent();
  366. }
  367. void SceneObject::destroyComponent(const HComponent& component, bool immediate)
  368. {
  369. if(component == nullptr)
  370. {
  371. LOGDBG("Trying to remove a null component");
  372. return;
  373. }
  374. auto iter = std::find(mComponents.begin(), mComponents.end(), component);
  375. if(iter != mComponents.end())
  376. {
  377. (*iter)->onDestroyed();
  378. mComponents.erase(iter);
  379. if (immediate)
  380. {
  381. GameObjectManager::instance().unregisterObject(component);
  382. (*iter).destroy();
  383. }
  384. else
  385. {
  386. GameObjectManager::instance().queueForDestroy(component);
  387. }
  388. }
  389. else
  390. LOGDBG("Trying to remove a component that doesn't exist on this SceneObject.");
  391. }
  392. void SceneObject::destroyComponent(Component* component, bool immediate)
  393. {
  394. auto iterFind = std::find_if(mComponents.begin(), mComponents.end(),
  395. [component](const HComponent& x)
  396. {
  397. if(x.isDestroyed())
  398. return false;
  399. return x._getHandleData()->mPtr->object.get() == component; }
  400. );
  401. if(iterFind != mComponents.end())
  402. {
  403. destroyComponent(*iterFind, immediate);
  404. }
  405. }
  406. void SceneObject::addComponentInternal(const std::shared_ptr<Component> component)
  407. {
  408. GameObjectHandle<Component> newComponent = GameObjectHandle<Component>(component);
  409. newComponent->mParent = mThisHandle;
  410. mComponents.push_back(newComponent);
  411. }
  412. RTTITypeBase* SceneObject::getRTTIStatic()
  413. {
  414. return SceneObjectRTTI::instance();
  415. }
  416. RTTITypeBase* SceneObject::getRTTI() const
  417. {
  418. return SceneObject::getRTTIStatic();
  419. }
  420. }