BsSceneObject.cpp 17 KB

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