BsSceneObject.cpp 18 KB

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