BsSceneObject.cpp 15 KB

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