BsSceneObject.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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. #include "BsPrefab.h"
  10. #include "BsPrefabUtility.h"
  11. #include "BsPrefabDiff.h"
  12. #include "BsMatrix3.h"
  13. namespace BansheeEngine
  14. {
  15. SceneObject::SceneObject(const String& name, UINT32 flags)
  16. :GameObject(), mPosition(Vector3::ZERO), mRotation(Quaternion::IDENTITY), mScale(Vector3::ONE),
  17. mWorldPosition(Vector3::ZERO), mWorldRotation(Quaternion::IDENTITY), mWorldScale(Vector3::ONE),
  18. mCachedLocalTfrm(Matrix4::IDENTITY), mDirtyFlags(0xFFFFFFFF), mCachedWorldTfrm(Matrix4::IDENTITY),
  19. mActiveSelf(true), mActiveHierarchy(true), mDirtyHash(0), mFlags(flags), mPrefabHash(0)
  20. {
  21. setName(name);
  22. }
  23. SceneObject::~SceneObject()
  24. {
  25. if(!mThisHandle.isDestroyed())
  26. {
  27. LOGWRN("Object is being deleted without being destroyed first?");
  28. destroyInternal(mThisHandle, true);
  29. }
  30. }
  31. HSceneObject SceneObject::create(const String& name, UINT32 flags)
  32. {
  33. HSceneObject newObject = createInternal(name, flags);
  34. if (newObject->isInstantiated())
  35. gCoreSceneManager().registerNewSO(newObject);
  36. return newObject;
  37. }
  38. HSceneObject SceneObject::createInternal(const String& name, UINT32 flags)
  39. {
  40. std::shared_ptr<SceneObject> sceneObjectPtr = std::shared_ptr<SceneObject>(new (bs_alloc<SceneObject>()) SceneObject(name, flags),
  41. &bs_delete<SceneObject>, StdAlloc<SceneObject>());
  42. HSceneObject sceneObject = GameObjectManager::instance().registerObject(sceneObjectPtr);
  43. sceneObject->mThisHandle = sceneObject;
  44. return sceneObject;
  45. }
  46. void SceneObject::destroy(bool immediate)
  47. {
  48. // Parent is our owner, so when his reference to us is removed, delete might be called.
  49. // So make sure this is the last thing we do.
  50. if(mParent != nullptr)
  51. {
  52. if(!mParent.isDestroyed())
  53. mParent->removeChild(mThisHandle);
  54. mParent = nullptr;
  55. }
  56. destroyInternal(mThisHandle, immediate);
  57. }
  58. void SceneObject::destroyInternal(GameObjectHandleBase& handle, bool immediate)
  59. {
  60. if (immediate)
  61. {
  62. for (auto iter = mChildren.begin(); iter != mChildren.end(); ++iter)
  63. (*iter)->destroyInternal(*iter, true);
  64. mChildren.clear();
  65. for (auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  66. {
  67. HComponent component = *iter;
  68. component->_setIsDestroyed();
  69. if (isInstantiated())
  70. {
  71. if (getActive())
  72. component->onDisabled();
  73. component->onDestroyed();
  74. }
  75. component->destroyInternal(*iter, true);
  76. }
  77. mComponents.clear();
  78. GameObjectManager::instance().unregisterObject(handle);
  79. handle.destroy();
  80. }
  81. else
  82. GameObjectManager::instance().queueForDestroy(handle);
  83. }
  84. void SceneObject::_setInstanceData(GameObjectInstanceDataPtr& other)
  85. {
  86. GameObject::_setInstanceData(other);
  87. // Instance data changed, so make sure to refresh the handles to reflect that
  88. mThisHandle._setHandleData(mThisHandle.getInternalPtr());
  89. }
  90. String SceneObject::getPrefabLink() const
  91. {
  92. const SceneObject* curObj = this;
  93. while (curObj == nullptr)
  94. {
  95. if (!curObj->mPrefabLinkUUID.empty())
  96. return curObj->mPrefabLinkUUID;
  97. if (curObj->mParent != nullptr)
  98. curObj = curObj->mParent.get();
  99. else
  100. curObj = nullptr;
  101. }
  102. return "";
  103. }
  104. void SceneObject::breakPrefabLink()
  105. {
  106. SceneObject* curObj = this;
  107. while (curObj == nullptr)
  108. {
  109. if (!curObj->mPrefabLinkUUID.empty())
  110. {
  111. curObj->mPrefabLinkUUID = "";
  112. curObj->mPrefabDiff = nullptr;
  113. PrefabUtility::clearPrefabIds(curObj->getHandle());
  114. return;
  115. }
  116. if (curObj->mParent != nullptr)
  117. curObj = curObj->mParent.get();
  118. else
  119. curObj = nullptr;
  120. }
  121. }
  122. bool SceneObject::hasFlag(UINT32 flag) const
  123. {
  124. return (mFlags & flag) != 0;
  125. }
  126. void SceneObject::setFlags(UINT32 flags)
  127. {
  128. mFlags |= flags;
  129. for (auto& child : mChildren)
  130. child->setFlags(flags);
  131. }
  132. void SceneObject::unsetFlags(UINT32 flags)
  133. {
  134. mFlags &= ~flags;
  135. for (auto& child : mChildren)
  136. child->unsetFlags(flags);
  137. }
  138. void SceneObject::instantiate()
  139. {
  140. mFlags &= ~SOF_DontInstantiate;
  141. std::function<void(SceneObject*)> instantiateRecursive = [&](SceneObject* obj)
  142. {
  143. if (obj->mParent == nullptr)
  144. gCoreSceneManager().registerNewSO(obj->mThisHandle);
  145. for (auto& component : obj->mComponents)
  146. component->instantiate();
  147. for (auto& child : obj->mChildren)
  148. instantiateRecursive(child.get());
  149. };
  150. std::function<void(SceneObject*)> triggerEventsRecursive = [&](SceneObject* obj)
  151. {
  152. for (auto& component : obj->mComponents)
  153. {
  154. component->onInitialized();
  155. if (obj->getActive())
  156. component->onEnabled();
  157. }
  158. for (auto& child : obj->mChildren)
  159. triggerEventsRecursive(child.get());
  160. };
  161. instantiateRecursive(this);
  162. triggerEventsRecursive(this);
  163. }
  164. /************************************************************************/
  165. /* Transform */
  166. /************************************************************************/
  167. void SceneObject::setPosition(const Vector3& position)
  168. {
  169. mPosition = position;
  170. markTfrmDirty();
  171. }
  172. void SceneObject::setRotation(const Quaternion& rotation)
  173. {
  174. mRotation = rotation;
  175. markTfrmDirty();
  176. }
  177. void SceneObject::setScale(const Vector3& scale)
  178. {
  179. mScale = scale;
  180. markTfrmDirty();
  181. }
  182. void SceneObject::setWorldPosition(const Vector3& position)
  183. {
  184. if (mParent != nullptr)
  185. {
  186. Vector3 invScale = mParent->getWorldScale();
  187. if (invScale.x != 0) invScale.x = 1.0f / invScale.x;
  188. if (invScale.y != 0) invScale.y = 1.0f / invScale.y;
  189. if (invScale.z != 0) invScale.z = 1.0f / invScale.z;
  190. Quaternion invRotation = mParent->getWorldRotation().inverse();
  191. mPosition = invRotation.rotate(position - mParent->getWorldPosition()) * invScale;
  192. }
  193. else
  194. mPosition = position;
  195. markTfrmDirty();
  196. }
  197. void SceneObject::setWorldRotation(const Quaternion& rotation)
  198. {
  199. if (mParent != nullptr)
  200. {
  201. Quaternion invRotation = mParent->getWorldRotation().inverse();
  202. mRotation = invRotation * rotation;
  203. }
  204. else
  205. mRotation = rotation;
  206. markTfrmDirty();
  207. }
  208. void SceneObject::setWorldScale(const Vector3& scale)
  209. {
  210. if (mParent != nullptr)
  211. {
  212. Matrix3 rotScale;
  213. mParent->getWorldTfrm().extract3x3Matrix(rotScale);
  214. rotScale.inverse();
  215. Matrix3 scaleMat = Matrix3(Quaternion::IDENTITY, scale);
  216. scaleMat = rotScale * scaleMat;
  217. Quaternion rotation;
  218. Vector3 localScale;
  219. scaleMat.decomposition(rotation, localScale);
  220. mScale = localScale;
  221. }
  222. else
  223. mScale = scale;
  224. markTfrmDirty();
  225. }
  226. const Vector3& SceneObject::getWorldPosition() const
  227. {
  228. if (!isCachedWorldTfrmUpToDate())
  229. updateWorldTfrm();
  230. return mWorldPosition;
  231. }
  232. const Quaternion& SceneObject::getWorldRotation() const
  233. {
  234. if (!isCachedWorldTfrmUpToDate())
  235. updateWorldTfrm();
  236. return mWorldRotation;
  237. }
  238. const Vector3& SceneObject::getWorldScale() const
  239. {
  240. if (!isCachedWorldTfrmUpToDate())
  241. updateWorldTfrm();
  242. return mWorldScale;
  243. }
  244. void SceneObject::lookAt(const Vector3& location, const Vector3& up)
  245. {
  246. Vector3 forward = location - mPosition;
  247. forward.normalize();
  248. setForward(forward);
  249. Quaternion upRot = Quaternion::getRotationFromTo(getUp(), up);
  250. setRotation(getRotation() * upRot);
  251. }
  252. const Matrix4& SceneObject::getWorldTfrm() const
  253. {
  254. if (!isCachedWorldTfrmUpToDate())
  255. updateWorldTfrm();
  256. return mCachedWorldTfrm;
  257. }
  258. const Matrix4& SceneObject::getLocalTfrm() const
  259. {
  260. if (!isCachedLocalTfrmUpToDate())
  261. updateLocalTfrm();
  262. return mCachedLocalTfrm;
  263. }
  264. void SceneObject::move(const Vector3& vec)
  265. {
  266. setPosition(mPosition + vec);
  267. }
  268. void SceneObject::moveRelative(const Vector3& vec)
  269. {
  270. // Transform the axes of the relative vector by camera's local axes
  271. Vector3 trans = mRotation.rotate(vec);
  272. setPosition(mPosition + trans);
  273. }
  274. void SceneObject::rotate(const Vector3& axis, const Radian& angle)
  275. {
  276. Quaternion q;
  277. q.fromAxisAngle(axis, angle);
  278. rotate(q);
  279. }
  280. void SceneObject::rotate(const Quaternion& q)
  281. {
  282. // Note the order of the mult, i.e. q comes after
  283. // Normalize the quat to avoid cumulative problems with precision
  284. Quaternion qnorm = q;
  285. qnorm.normalize();
  286. setRotation(qnorm * mRotation);
  287. }
  288. void SceneObject::roll(const Radian& angle)
  289. {
  290. // Rotate around local Z axis
  291. Vector3 zAxis = mRotation.rotate(Vector3::UNIT_Z);
  292. rotate(zAxis, angle);
  293. }
  294. void SceneObject::yaw(const Radian& angle)
  295. {
  296. Vector3 yAxis = mRotation.rotate(Vector3::UNIT_Y);
  297. rotate(yAxis, angle);
  298. }
  299. void SceneObject::pitch(const Radian& angle)
  300. {
  301. // Rotate around local X axis
  302. Vector3 xAxis = mRotation.rotate(Vector3::UNIT_X);
  303. rotate(xAxis, angle);
  304. }
  305. void SceneObject::setForward(const Vector3& forwardDir)
  306. {
  307. if (forwardDir == Vector3::ZERO)
  308. return;
  309. Vector3 nrmForwardDir = Vector3::normalize(forwardDir);
  310. Vector3 currentForwardDir = getForward();
  311. const Quaternion& currentRotation = getWorldRotation();
  312. Quaternion targetRotation;
  313. if ((nrmForwardDir+currentForwardDir).squaredLength() < 0.00005f)
  314. {
  315. // Oops, a 180 degree turn (infinite possible rotation axes)
  316. // Default to yaw i.e. use current UP
  317. targetRotation = Quaternion(-currentRotation.y, -currentRotation.z, currentRotation.w, currentRotation.x);
  318. }
  319. else
  320. {
  321. // Derive shortest arc to new direction
  322. Quaternion rotQuat = Quaternion::getRotationFromTo(currentForwardDir, nrmForwardDir);
  323. targetRotation = rotQuat * currentRotation;
  324. }
  325. setRotation(targetRotation);
  326. }
  327. void SceneObject::updateTransformsIfDirty()
  328. {
  329. if (!isCachedLocalTfrmUpToDate())
  330. updateLocalTfrm();
  331. if (!isCachedWorldTfrmUpToDate())
  332. updateWorldTfrm();
  333. }
  334. void SceneObject::markTfrmDirty() const
  335. {
  336. mDirtyFlags |= DirtyFlags::LocalTfrmDirty | DirtyFlags::WorldTfrmDirty;
  337. mDirtyHash++;
  338. for(auto iter = mChildren.begin(); iter != mChildren.end(); ++iter)
  339. {
  340. (*iter)->markTfrmDirty();
  341. }
  342. }
  343. void SceneObject::updateWorldTfrm() const
  344. {
  345. if(mParent != nullptr)
  346. {
  347. mCachedWorldTfrm = getLocalTfrm() * mParent->getWorldTfrm();
  348. // Update orientation
  349. const Quaternion& parentOrientation = mParent->getWorldRotation();
  350. mWorldRotation = parentOrientation * mRotation;
  351. // Update scale
  352. const Vector3& parentScale = mParent->getWorldScale();
  353. // Scale own position by parent scale, just combine
  354. // as equivalent axes, no shearing
  355. mWorldScale = parentScale * mScale;
  356. // Change position vector based on parent's orientation & scale
  357. mWorldPosition = parentOrientation.rotate(parentScale * mPosition);
  358. // Add altered position vector to parents
  359. mWorldPosition += mParent->getWorldPosition();
  360. }
  361. else
  362. {
  363. mCachedWorldTfrm = getLocalTfrm();
  364. mWorldRotation = mRotation;
  365. mWorldPosition = mPosition;
  366. mWorldScale = mScale;
  367. }
  368. mDirtyFlags &= ~DirtyFlags::WorldTfrmDirty;
  369. }
  370. void SceneObject::updateLocalTfrm() const
  371. {
  372. mCachedLocalTfrm.setTRS(mPosition, mRotation, mScale);
  373. mDirtyFlags &= ~DirtyFlags::LocalTfrmDirty;
  374. }
  375. /************************************************************************/
  376. /* Hierarchy */
  377. /************************************************************************/
  378. void SceneObject::setParent(const HSceneObject& parent)
  379. {
  380. if (parent.isDestroyed() || mThisHandle == parent)
  381. return;
  382. if(mParent == nullptr || mParent != parent)
  383. {
  384. // Make sure the object keeps its world coordinates
  385. Vector3 worldPos = getWorldPosition();
  386. Quaternion worldRot = getWorldRotation();
  387. Vector3 worldScale = getWorldScale();
  388. #if BS_EDITOR_BUILD
  389. String originalPrefab = getPrefabLink();
  390. #endif
  391. if(mParent != nullptr)
  392. mParent->removeChild(mThisHandle);
  393. if(parent != nullptr)
  394. parent->addChild(mThisHandle);
  395. mParent = parent;
  396. #if BS_EDITOR_BUILD
  397. String newPrefab = getPrefabLink();
  398. if (originalPrefab != newPrefab)
  399. PrefabUtility::clearPrefabIds(mThisHandle, false);
  400. #endif
  401. setWorldPosition(worldPos);
  402. setWorldRotation(worldRot);
  403. setWorldScale(worldScale);
  404. markTfrmDirty();
  405. }
  406. }
  407. HSceneObject SceneObject::getChild(UINT32 idx) const
  408. {
  409. if(idx < 0 || idx >= mChildren.size())
  410. {
  411. BS_EXCEPT(InternalErrorException, "Child index out of range.");
  412. }
  413. return mChildren[idx];
  414. }
  415. int SceneObject::indexOfChild(const HSceneObject& child) const
  416. {
  417. for(int i = 0; i < (int)mChildren.size(); i++)
  418. {
  419. if(mChildren[i] == child)
  420. return i;
  421. }
  422. return -1;
  423. }
  424. void SceneObject::addChild(const HSceneObject& object)
  425. {
  426. mChildren.push_back(object);
  427. object->setFlags(mFlags);
  428. }
  429. void SceneObject::removeChild(const HSceneObject& object)
  430. {
  431. auto result = find(mChildren.begin(), mChildren.end(), object);
  432. if(result != mChildren.end())
  433. mChildren.erase(result);
  434. else
  435. {
  436. BS_EXCEPT(InternalErrorException,
  437. "Trying to remove a child but it's not a child of the transform.");
  438. }
  439. }
  440. void SceneObject::setActive(bool active)
  441. {
  442. mActiveSelf = active;
  443. setActiveHierarchy(active);
  444. }
  445. void SceneObject::setActiveHierarchy(bool active)
  446. {
  447. bool activeHierarchy = active && mActiveSelf;
  448. if (mActiveHierarchy != activeHierarchy)
  449. {
  450. mActiveHierarchy = activeHierarchy;
  451. if (activeHierarchy)
  452. {
  453. for (auto& component : mComponents)
  454. component->onEnabled();
  455. }
  456. else
  457. {
  458. for (auto& component : mComponents)
  459. component->onDisabled();
  460. }
  461. }
  462. for (auto child : mChildren)
  463. {
  464. child->setActiveHierarchy(mActiveHierarchy);
  465. }
  466. }
  467. bool SceneObject::getActive(bool self)
  468. {
  469. if (self)
  470. return mActiveSelf;
  471. else
  472. return mActiveHierarchy;
  473. }
  474. HSceneObject SceneObject::clone()
  475. {
  476. UINT32 bufferSize = 0;
  477. MemorySerializer serializer;
  478. UINT8* buffer = serializer.encode(this, bufferSize, &bs_alloc);
  479. GameObjectManager::instance().setDeserializationMode(GODM_UseNewIds | GODM_RestoreExternal);
  480. std::shared_ptr<SceneObject> cloneObj = std::static_pointer_cast<SceneObject>(serializer.decode(buffer, bufferSize));
  481. bs_free(buffer);
  482. return cloneObj->mThisHandle;
  483. }
  484. HComponent SceneObject::getComponent(UINT32 typeId) const
  485. {
  486. for(auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  487. {
  488. if((*iter)->getRTTI()->getRTTIId() == typeId)
  489. return *iter;
  490. }
  491. return HComponent();
  492. }
  493. void SceneObject::destroyComponent(const HComponent component, bool immediate)
  494. {
  495. if(component == nullptr)
  496. {
  497. LOGDBG("Trying to remove a null component");
  498. return;
  499. }
  500. auto iter = std::find(mComponents.begin(), mComponents.end(), component);
  501. if(iter != mComponents.end())
  502. {
  503. (*iter)->_setIsDestroyed();
  504. if (isInstantiated())
  505. {
  506. if (getActive())
  507. component->onDisabled();
  508. (*iter)->onDestroyed();
  509. }
  510. (*iter)->destroyInternal(*iter, immediate);
  511. mComponents.erase(iter);
  512. }
  513. else
  514. LOGDBG("Trying to remove a component that doesn't exist on this SceneObject.");
  515. }
  516. void SceneObject::destroyComponent(Component* component, bool immediate)
  517. {
  518. auto iterFind = std::find_if(mComponents.begin(), mComponents.end(),
  519. [component](const HComponent& x)
  520. {
  521. if(x.isDestroyed())
  522. return false;
  523. return x._getHandleData()->mPtr->object.get() == component; }
  524. );
  525. if(iterFind != mComponents.end())
  526. {
  527. destroyComponent(*iterFind, immediate);
  528. }
  529. }
  530. void SceneObject::addComponentInternal(const std::shared_ptr<Component> component)
  531. {
  532. GameObjectHandle<Component> newComponent = GameObjectHandle<Component>(component);
  533. newComponent->mParent = mThisHandle;
  534. mComponents.push_back(newComponent);
  535. }
  536. RTTITypeBase* SceneObject::getRTTIStatic()
  537. {
  538. return SceneObjectRTTI::instance();
  539. }
  540. RTTITypeBase* SceneObject::getRTTI() const
  541. {
  542. return SceneObject::getRTTIStatic();
  543. }
  544. }