BsSceneObject.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. namespace BansheeEngine
  10. {
  11. SceneObject::SceneObject(const String& name)
  12. :GameObject(), mPosition(Vector3::ZERO), mRotation(Quaternion::IDENTITY), mScale(Vector3::ONE),
  13. mWorldPosition(Vector3::ZERO), mWorldRotation(Quaternion::IDENTITY), mWorldScale(Vector3::ONE),
  14. mCachedLocalTfrm(Matrix4::IDENTITY), mDirtyFlags(0xFFFFFFFF), mCachedWorldTfrm(Matrix4::IDENTITY),
  15. mIsCoreDirtyFlags(0xFFFFFFFF), mActiveSelf(true), mActiveHierarchy(true), mDirtyHash(0)
  16. {
  17. setName(name);
  18. }
  19. SceneObject::~SceneObject()
  20. {
  21. if(!mThisHandle.isDestroyed())
  22. {
  23. LOGWRN("Object is being deleted without being destroyed first?");
  24. destroyInternal();
  25. }
  26. }
  27. HSceneObject SceneObject::create(const String& name)
  28. {
  29. HSceneObject newObject = createInternal(name);
  30. gCoreSceneManager().registerNewSO(newObject);
  31. return newObject;
  32. }
  33. HSceneObject SceneObject::createInternal(const String& name)
  34. {
  35. std::shared_ptr<SceneObject> sceneObjectPtr = std::shared_ptr<SceneObject>(new (bs_alloc<SceneObject, PoolAlloc>()) SceneObject(name),
  36. &bs_delete<PoolAlloc, SceneObject>, StdAlloc<SceneObject, PoolAlloc>());
  37. HSceneObject sceneObject = GameObjectManager::instance().registerObject(sceneObjectPtr);
  38. sceneObject->mThisHandle = sceneObject;
  39. return sceneObject;
  40. }
  41. void SceneObject::destroy()
  42. {
  43. // Parent is our owner, so when his reference to us is removed, delete might be called.
  44. // So make sure this is the last thing we do.
  45. if(mParent != nullptr)
  46. {
  47. if(!mParent.isDestroyed())
  48. mParent->removeChild(mThisHandle);
  49. }
  50. destroyInternal();
  51. }
  52. void SceneObject::destroyInternal()
  53. {
  54. for(auto iter = mChildren.begin(); iter != mChildren.end(); ++iter)
  55. (*iter)->destroyInternal();
  56. mChildren.clear();
  57. for(auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  58. {
  59. gCoreSceneManager().notifyComponentRemoved((*iter));
  60. GameObjectManager::instance().unregisterObject(*iter);
  61. (*iter).destroy();
  62. }
  63. mComponents.clear();
  64. GameObjectManager::instance().unregisterObject(mThisHandle);
  65. mThisHandle.destroy();
  66. }
  67. void SceneObject::_setInstanceData(GameObjectInstanceDataPtr& other)
  68. {
  69. GameObject::_setInstanceData(other);
  70. // Instance data changed, so make sure to refresh the handles to reflect that
  71. mThisHandle._setHandleData(mThisHandle.getInternalPtr());
  72. }
  73. /************************************************************************/
  74. /* Transform */
  75. /************************************************************************/
  76. void SceneObject::setPosition(const Vector3& position)
  77. {
  78. mPosition = position;
  79. markTfrmDirty();
  80. }
  81. void SceneObject::setRotation(const Quaternion& rotation)
  82. {
  83. mRotation = rotation;
  84. markTfrmDirty();
  85. }
  86. void SceneObject::setScale(const Vector3& scale)
  87. {
  88. mScale = scale;
  89. markTfrmDirty();
  90. }
  91. void SceneObject::setWorldPosition(const Vector3& position)
  92. {
  93. if (mParent != nullptr)
  94. {
  95. Vector3 invScale = mParent->getWorldScale();
  96. if (invScale.x != 0) invScale.x = 1.0f / invScale.x;
  97. if (invScale.y != 0) invScale.y = 1.0f / invScale.y;
  98. if (invScale.z != 0) invScale.z = 1.0f / invScale.z;
  99. Quaternion invRotation = mParent->getWorldRotation().inverse();
  100. mPosition = invRotation.rotate(position - mParent->getWorldPosition()) * invScale;
  101. }
  102. else
  103. mPosition = position;
  104. markTfrmDirty();
  105. }
  106. void SceneObject::setWorldRotation(const Quaternion& rotation)
  107. {
  108. if (mParent != nullptr)
  109. {
  110. Quaternion invRotation = mParent->getWorldRotation().inverse();
  111. mRotation = invRotation * rotation;
  112. }
  113. else
  114. mRotation = rotation;
  115. markTfrmDirty();
  116. }
  117. const Vector3& SceneObject::getWorldPosition() const
  118. {
  119. if (!isCachedWorldTfrmUpToDate())
  120. updateWorldTfrm();
  121. return mWorldPosition;
  122. }
  123. const Quaternion& SceneObject::getWorldRotation() const
  124. {
  125. if (!isCachedWorldTfrmUpToDate())
  126. updateWorldTfrm();
  127. return mWorldRotation;
  128. }
  129. const Vector3& SceneObject::getWorldScale() const
  130. {
  131. if (!isCachedWorldTfrmUpToDate())
  132. updateWorldTfrm();
  133. return mWorldScale;
  134. }
  135. void SceneObject::lookAt(const Vector3& location, const Vector3& up)
  136. {
  137. Vector3 forward = location - mPosition;
  138. forward.normalize();
  139. setForward(forward);
  140. Quaternion upRot = Quaternion::getRotationFromTo(getUp(), up);
  141. setRotation(getRotation() * upRot);
  142. }
  143. const Matrix4& SceneObject::getWorldTfrm() const
  144. {
  145. if (!isCachedWorldTfrmUpToDate())
  146. updateWorldTfrm();
  147. return mCachedWorldTfrm;
  148. }
  149. const Matrix4& SceneObject::getLocalTfrm() const
  150. {
  151. if (!isCachedLocalTfrmUpToDate())
  152. updateLocalTfrm();
  153. return mCachedLocalTfrm;
  154. }
  155. void SceneObject::move(const Vector3& vec)
  156. {
  157. setPosition(mPosition + vec);
  158. }
  159. void SceneObject::moveRelative(const Vector3& vec)
  160. {
  161. // Transform the axes of the relative vector by camera's local axes
  162. Vector3 trans = mRotation.rotate(vec);
  163. setPosition(mPosition + trans);
  164. }
  165. void SceneObject::rotate(const Vector3& axis, const Radian& angle)
  166. {
  167. Quaternion q;
  168. q.fromAxisAngle(axis, angle);
  169. rotate(q);
  170. }
  171. void SceneObject::rotate(const Quaternion& q)
  172. {
  173. // Note the order of the mult, i.e. q comes after
  174. // Normalize the quat to avoid cumulative problems with precision
  175. Quaternion qnorm = q;
  176. qnorm.normalize();
  177. setRotation(qnorm * mRotation);
  178. }
  179. void SceneObject::roll(const Radian& angle)
  180. {
  181. // Rotate around local Z axis
  182. Vector3 zAxis = mRotation.rotate(Vector3::UNIT_Z);
  183. rotate(zAxis, angle);
  184. }
  185. void SceneObject::yaw(const Radian& angle)
  186. {
  187. Vector3 yAxis = mRotation.rotate(Vector3::UNIT_Y);
  188. rotate(yAxis, angle);
  189. }
  190. void SceneObject::pitch(const Radian& angle)
  191. {
  192. // Rotate around local X axis
  193. Vector3 xAxis = mRotation.rotate(Vector3::UNIT_X);
  194. rotate(xAxis, angle);
  195. }
  196. void SceneObject::setForward(const Vector3& forwardDir)
  197. {
  198. if (forwardDir == Vector3::ZERO)
  199. return;
  200. Vector3 nrmForwardDir = Vector3::normalize(forwardDir);
  201. Vector3 currentForwardDir = getForward();
  202. const Quaternion& currentRotation = getWorldRotation();
  203. Quaternion targetRotation;
  204. if ((nrmForwardDir+currentForwardDir).squaredLength() < 0.00005f)
  205. {
  206. // Oops, a 180 degree turn (infinite possible rotation axes)
  207. // Default to yaw i.e. use current UP
  208. targetRotation = Quaternion(-currentRotation.y, -currentRotation.z, currentRotation.w, currentRotation.x);
  209. }
  210. else
  211. {
  212. // Derive shortest arc to new direction
  213. Quaternion rotQuat = Quaternion::getRotationFromTo(currentForwardDir, nrmForwardDir);
  214. targetRotation = rotQuat * currentRotation;
  215. }
  216. setRotation(targetRotation);
  217. }
  218. void SceneObject::updateTransformsIfDirty()
  219. {
  220. if (!isCachedLocalTfrmUpToDate())
  221. updateLocalTfrm();
  222. if (!isCachedWorldTfrmUpToDate())
  223. updateWorldTfrm();
  224. }
  225. void SceneObject::markTfrmDirty() const
  226. {
  227. mDirtyFlags |= DirtyFlags::LocalTfrmDirty | DirtyFlags::WorldTfrmDirty;
  228. mIsCoreDirtyFlags = 0xFFFFFFFF;
  229. mDirtyHash++;
  230. for(auto iter = mChildren.begin(); iter != mChildren.end(); ++iter)
  231. {
  232. (*iter)->markTfrmDirty();
  233. }
  234. }
  235. void SceneObject::updateWorldTfrm() const
  236. {
  237. if(mParent != nullptr)
  238. {
  239. mCachedWorldTfrm = getLocalTfrm() * mParent->getWorldTfrm();
  240. // Update orientation
  241. const Quaternion& parentOrientation = mParent->getWorldRotation();
  242. mWorldRotation = parentOrientation * mRotation;
  243. // Update scale
  244. const Vector3& parentScale = mParent->getWorldScale();
  245. // Scale own position by parent scale, just combine
  246. // as equivalent axes, no shearing
  247. mWorldScale = parentScale * mScale;
  248. // Change position vector based on parent's orientation & scale
  249. mWorldPosition = parentOrientation.rotate(parentScale * mPosition);
  250. // Add altered position vector to parents
  251. mWorldPosition += mParent->getWorldPosition();
  252. }
  253. else
  254. {
  255. mCachedWorldTfrm = getLocalTfrm();
  256. mWorldRotation = mRotation;
  257. mWorldPosition = mPosition;
  258. mWorldScale = mScale;
  259. }
  260. mDirtyFlags &= ~DirtyFlags::WorldTfrmDirty;
  261. }
  262. void SceneObject::updateLocalTfrm() const
  263. {
  264. mCachedLocalTfrm.setTRS(mPosition, mRotation, mScale);
  265. mDirtyFlags &= ~DirtyFlags::LocalTfrmDirty;
  266. }
  267. /************************************************************************/
  268. /* Hierarchy */
  269. /************************************************************************/
  270. void SceneObject::setParent(const HSceneObject& parent)
  271. {
  272. if(parent.isDestroyed())
  273. {
  274. BS_EXCEPT(InternalErrorException,
  275. "Trying to assign a SceneObject parent that is destroyed.");
  276. }
  277. if(mParent == nullptr || mParent != parent)
  278. {
  279. if(mParent != nullptr)
  280. mParent->removeChild(mThisHandle);
  281. if(parent != nullptr)
  282. parent->addChild(mThisHandle);
  283. mParent = parent;
  284. markTfrmDirty();
  285. }
  286. }
  287. HSceneObject SceneObject::getChild(UINT32 idx) const
  288. {
  289. if(idx < 0 || idx >= mChildren.size())
  290. {
  291. BS_EXCEPT(InternalErrorException, "Child index out of range.");
  292. }
  293. return mChildren[idx];
  294. }
  295. int SceneObject::indexOfChild(const HSceneObject& child) const
  296. {
  297. for(int i = 0; i < (int)mChildren.size(); i++)
  298. {
  299. if(mChildren[i] == child)
  300. return i;
  301. }
  302. return -1;
  303. }
  304. void SceneObject::addChild(const HSceneObject& object)
  305. {
  306. mChildren.push_back(object);
  307. }
  308. void SceneObject::removeChild(const HSceneObject& object)
  309. {
  310. auto result = find(mChildren.begin(), mChildren.end(), object);
  311. if(result != mChildren.end())
  312. mChildren.erase(result);
  313. else
  314. {
  315. BS_EXCEPT(InternalErrorException,
  316. "Trying to remove a child but it's not a child of the transform.");
  317. }
  318. }
  319. void SceneObject::setActive(bool active)
  320. {
  321. mActiveSelf = active;
  322. setActiveHierarchy(active);
  323. }
  324. void SceneObject::setActiveHierarchy(bool active)
  325. {
  326. mActiveHierarchy = active && mActiveSelf;
  327. for (auto child : mChildren)
  328. {
  329. child->setActiveHierarchy(mActiveHierarchy);
  330. }
  331. mIsCoreDirtyFlags = 0xFFFFFFFF;
  332. }
  333. bool SceneObject::getActive(bool self)
  334. {
  335. if (self)
  336. return mActiveSelf;
  337. else
  338. return mActiveHierarchy;
  339. }
  340. HSceneObject SceneObject::clone()
  341. {
  342. UINT32 bufferSize = 0;
  343. MemorySerializer serializer;
  344. UINT8* buffer = serializer.encode(this, bufferSize, &bs_alloc);
  345. GameObjectManager::instance().setDeserializationMode(GODM_UseNewIds | GODM_RestoreExternal);
  346. std::shared_ptr<SceneObject> cloneObj = std::static_pointer_cast<SceneObject>(serializer.decode(buffer, bufferSize));
  347. bs_free(buffer);
  348. return cloneObj->mThisHandle;
  349. }
  350. HComponent SceneObject::getComponent(UINT32 typeId) const
  351. {
  352. for(auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  353. {
  354. if((*iter)->getRTTI()->getRTTIId() == typeId)
  355. return *iter;
  356. }
  357. return HComponent();
  358. }
  359. void SceneObject::destroyComponent(const HComponent& component)
  360. {
  361. if(component == nullptr)
  362. {
  363. LOGDBG("Trying to remove a null component");
  364. return;
  365. }
  366. auto iter = std::find(mComponents.begin(), mComponents.end(), component);
  367. if(iter != mComponents.end())
  368. {
  369. gCoreSceneManager().notifyComponentRemoved((*iter));
  370. GameObjectManager::instance().unregisterObject(component);
  371. (*iter)->onDestroyed();
  372. (*iter).destroy();
  373. mComponents.erase(iter);
  374. }
  375. else
  376. LOGDBG("Trying to remove a component that doesn't exist on this SceneObject.");
  377. }
  378. void SceneObject::destroyComponent(Component* component)
  379. {
  380. auto iterFind = std::find_if(mComponents.begin(), mComponents.end(),
  381. [component](const HComponent& x)
  382. {
  383. if(x.isDestroyed())
  384. return false;
  385. return x._getHandleData()->mPtr->object.get() == component; }
  386. );
  387. if(iterFind != mComponents.end())
  388. {
  389. destroyComponent(*iterFind);
  390. }
  391. }
  392. void SceneObject::addComponentInternal(const std::shared_ptr<Component> component)
  393. {
  394. GameObjectHandle<Component> newComponent = GameObjectHandle<Component>(component);
  395. newComponent->mParent = mThisHandle;
  396. mComponents.push_back(newComponent);
  397. gCoreSceneManager().notifyComponentAdded(newComponent);
  398. }
  399. RTTITypeBase* SceneObject::getRTTIStatic()
  400. {
  401. return SceneObjectRTTI::instance();
  402. }
  403. RTTITypeBase* SceneObject::getRTTI() const
  404. {
  405. return SceneObject::getRTTIStatic();
  406. }
  407. }