BsSceneObject.cpp 16 KB

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