BsAnimationManager.cpp 7.9 KB

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