BsSceneObject.cpp 17 KB

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