BsSceneObject.cpp 13 KB

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