BsSceneObject.cpp 18 KB

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