BsSceneObject.cpp 12 KB

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