BsAnimationManager.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsAnimationManager.h"
  4. #include "BsAnimation.h"
  5. #include "BsAnimationClip.h"
  6. #include "BsTaskScheduler.h"
  7. #include "BsTime.h"
  8. #include "BsCoreSceneManager.h"
  9. namespace BansheeEngine
  10. {
  11. AnimationManager::AnimationManager()
  12. : mNextId(1), mUpdateRate(1.0f / 60.0f), mAnimationTime(0.0f), mLastAnimationUpdateTime(0.0f)
  13. , mNextAnimationUpdateTime(0.0f), mPaused(false), mWorkerRunning(false), mPoseReadBufferIdx(0)
  14. , mPoseWriteBufferIdx(0), mDataReadyCount(0)
  15. {
  16. mAnimationWorker = Task::create("Animation", std::bind(&AnimationManager::evaluateAnimation, this));
  17. }
  18. void AnimationManager::setPaused(bool paused)
  19. {
  20. mPaused = paused;
  21. }
  22. void AnimationManager::setUpdateRate(UINT32 fps)
  23. {
  24. if (fps == 0)
  25. fps = 1;
  26. mUpdateRate = 1.0f / fps;
  27. }
  28. void AnimationManager::preUpdate()
  29. {
  30. if (mPaused || !mWorkerRunning)
  31. return;
  32. mAnimationWorker->wait();
  33. // Make sure we don't load obsolete skeletal pose and other evaluation ouputs written by the animation thread
  34. std::atomic_thread_fence(std::memory_order_acquire);
  35. // Trigger events
  36. for (auto& anim : mAnimations)
  37. {
  38. anim.second->updateFromProxy();
  39. anim.second->triggerEvents(mAnimationTime, gTime().getFrameDelta());
  40. }
  41. mWorkerRunning = false;
  42. }
  43. void AnimationManager::postUpdate(const Vector<ConvexVolume>& cullFrustums)
  44. {
  45. if (mPaused)
  46. return;
  47. mAnimationTime += gTime().getFrameDelta();
  48. if (mAnimationTime < mNextAnimationUpdateTime)
  49. return;
  50. mNextAnimationUpdateTime = Math::floor(mAnimationTime / mUpdateRate) * mUpdateRate + mUpdateRate;
  51. float timeDelta = mAnimationTime - mLastAnimationUpdateTime;
  52. mLastAnimationUpdateTime = mAnimationTime;
  53. // Update poses in the currently active buffer. Multi-buffering allows the core thread to safely read the
  54. // poses without worrying about them being overwritten by another call to postUpdate, as long as the simulation
  55. // thread doesn't go more than (CoreThread::NUM_SYNC_BUFFERS - 1) frames ahead.
  56. mProxies.clear();
  57. for (auto& anim : mAnimations)
  58. {
  59. anim.second->updateAnimProxy(timeDelta);
  60. mProxies.push_back(anim.second->mAnimProxy);
  61. }
  62. mCullFrustums = cullFrustums;
  63. // Make sure thread finishes writing all changes to the anim proxies as they will be read by the animation thread
  64. std::atomic_thread_fence(std::memory_order_release);
  65. // Note: Animation thread will trigger about the same time as the core thread. The core thread will need to wait
  66. // until animation thread finishes, which might end up blocking it (and losing the multi-threading performance).
  67. // Consider delaying displayed animation for a single frame or pre-calculating animations (by advancing time the
  68. // previous frame) for non-dirty animations.
  69. TaskScheduler::instance().addTask(mAnimationWorker);
  70. mWorkerRunning = true;
  71. }
  72. void AnimationManager::evaluateAnimation()
  73. {
  74. // Make sure we don't load obsolete anim proxy data written by the simulation thread
  75. std::atomic_thread_fence(std::memory_order_acquire);
  76. // No need for locking, as we are sure that only postUpdate() writes to the proxy buffer, and increments the write
  77. // buffer index. And it's called sequentially ensuring previous call to evaluate finishes.
  78. UINT32 totalNumBones = 0;
  79. for (auto& anim : mProxies)
  80. {
  81. if (anim->skeleton != nullptr)
  82. totalNumBones += anim->skeleton->getNumBones();
  83. }
  84. RendererAnimationData& renderData = mAnimData[mPoseWriteBufferIdx];
  85. mPoseWriteBufferIdx = (mPoseWriteBufferIdx + 1) % CoreThread::NUM_SYNC_BUFFERS;
  86. renderData.poseInfos.clear();
  87. renderData.transforms.resize(totalNumBones);
  88. UINT32 curBoneIdx = 0;
  89. for(auto& anim : mProxies)
  90. {
  91. if(anim->mCullEnabled)
  92. {
  93. bool isVisible = false;
  94. for(auto& frustum : mCullFrustums)
  95. {
  96. if(frustum.intersects(anim->mBounds))
  97. {
  98. isVisible = true;
  99. break;
  100. }
  101. }
  102. if (!isVisible)
  103. continue;
  104. }
  105. if (anim->skeleton != nullptr)
  106. {
  107. UINT32 numBones = anim->skeleton->getNumBones();
  108. RendererAnimationData::PoseInfo info;
  109. info.animId = anim->id;
  110. info.startIdx = curBoneIdx;
  111. info.numBones = numBones;
  112. Matrix4* boneDst = renderData.transforms.data() + curBoneIdx;
  113. // Copy transforms from mapped scene objects
  114. UINT32 boneTfrmIdx = 0;
  115. for(UINT32 i = 0; i < anim->numSceneObjects; i++)
  116. {
  117. const AnimatedSceneObjectInfo& soInfo = anim->sceneObjectInfos[i];
  118. if (soInfo.boneIdx == -1)
  119. continue;
  120. boneDst[soInfo.boneIdx] = anim->sceneObjectTransforms[boneTfrmIdx];
  121. boneTfrmIdx++;
  122. }
  123. // Animate bones
  124. anim->skeleton->getPose(boneDst, anim->skeletonPose, anim->skeletonMask, anim->layers, anim->numLayers);
  125. renderData.poseInfos[anim->id] = info;
  126. curBoneIdx += numBones;
  127. }
  128. // Reset mapped SO transform
  129. for (UINT32 i = 0; i < anim->sceneObjectPose.numBones; i++)
  130. {
  131. anim->sceneObjectPose.positions[i] = Vector3::ZERO;
  132. anim->sceneObjectPose.rotations[i] = Quaternion::IDENTITY;
  133. anim->sceneObjectPose.scales[i] = Vector3::ONE;
  134. }
  135. // Update mapped scene objects
  136. for(UINT32 i = 0; i < anim->numSceneObjects; i++)
  137. {
  138. const AnimatedSceneObjectInfo& soInfo = anim->sceneObjectInfos[i];
  139. // We already evaluated bones
  140. if (soInfo.boneIdx != -1)
  141. continue;
  142. const AnimationState& state = anim->layers[soInfo.layerIdx].states[soInfo.stateIdx];
  143. if (state.disabled)
  144. continue;
  145. {
  146. UINT32 curveIdx = soInfo.curveIndices.position;
  147. if (curveIdx != (UINT32)-1)
  148. {
  149. const TAnimationCurve<Vector3>& curve = state.curves->position[curveIdx].curve;
  150. anim->sceneObjectPose.positions[curveIdx] = curve.evaluate(state.time, state.positionCaches[curveIdx], state.loop);
  151. }
  152. }
  153. {
  154. UINT32 curveIdx = soInfo.curveIndices.rotation;
  155. if (curveIdx != (UINT32)-1)
  156. {
  157. const TAnimationCurve<Quaternion>& curve = state.curves->rotation[curveIdx].curve;
  158. anim->sceneObjectPose.rotations[curveIdx] = curve.evaluate(state.time, state.rotationCaches[curveIdx], state.loop);
  159. anim->sceneObjectPose.rotations[curveIdx].normalize();
  160. }
  161. }
  162. {
  163. UINT32 curveIdx = soInfo.curveIndices.scale;
  164. if (curveIdx != (UINT32)-1)
  165. {
  166. const TAnimationCurve<Vector3>& curve = state.curves->scale[curveIdx].curve;
  167. anim->sceneObjectPose.scales[curveIdx] = curve.evaluate(state.time, state.scaleCaches[curveIdx], state.loop);
  168. }
  169. }
  170. }
  171. // Note: No blending for generic animations, just use first animation
  172. if (anim->numLayers > 0 && anim->layers[0].numStates > 0)
  173. {
  174. const AnimationState& state = anim->layers[0].states[0];
  175. if (state.disabled)
  176. continue;
  177. {
  178. UINT32 numCurves = (UINT32)state.curves->generic.size();
  179. for (UINT32 i = 0; i < numCurves; i++)
  180. {
  181. const TAnimationCurve<float>& curve = state.curves->generic[i].curve;
  182. anim->genericCurveOutputs[i] = curve.evaluate(state.time, state.genericCaches[i], state.loop);
  183. }
  184. }
  185. }
  186. }
  187. mDataReadyCount.fetch_add(1, std::memory_order_relaxed);
  188. // Make sure the thread finishes writing skeletal pose and other evaluation outputs as they will be read by sim and
  189. // core threads
  190. std::atomic_thread_fence(std::memory_order_release);
  191. }
  192. const RendererAnimationData& AnimationManager::getRendererData()
  193. {
  194. mAnimationWorker->wait();
  195. // Make sure we don't load obsolete skeletal pose and other evaluation ouputs written by the animation thread
  196. std::atomic_thread_fence(std::memory_order_acquire);
  197. INT32 dataReadyCount = mDataReadyCount.load(std::memory_order_relaxed);
  198. assert(dataReadyCount <= CoreThread::NUM_SYNC_BUFFERS);
  199. if (dataReadyCount <= 0)
  200. {
  201. static RendererAnimationData dummy;
  202. return dummy;
  203. }
  204. const RendererAnimationData& output = mAnimData[mPoseReadBufferIdx];
  205. mPoseReadBufferIdx = (mPoseReadBufferIdx + 1) % CoreThread::NUM_SYNC_BUFFERS;
  206. mDataReadyCount.fetch_add(-1, std::memory_order_relaxed);
  207. return output;
  208. }
  209. UINT64 AnimationManager::registerAnimation(Animation* anim)
  210. {
  211. mAnimations[mNextId] = anim;
  212. return mNextId++;
  213. }
  214. void AnimationManager::unregisterAnimation(UINT64 animId)
  215. {
  216. mAnimations.erase(animId);
  217. }
  218. AnimationManager& gAnimation()
  219. {
  220. return AnimationManager::instance();
  221. }
  222. }