BsAnimation.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsCorePrerequisites.h"
  5. #include "BsCoreObject.h"
  6. #include "BsIResourceListener.h"
  7. #include "BsFlags.h"
  8. #include "BsSkeleton.h"
  9. #include "BsSkeletonMask.h"
  10. #include "BsVector2.h"
  11. #include "BsAABox.h"
  12. namespace BansheeEngine
  13. {
  14. /** @addtogroup Animation-Internal
  15. * @{
  16. */
  17. /** Determines how an animation clip behaves when it reaches the end. */
  18. enum class AnimWrapMode
  19. {
  20. Loop, /**< Loop around to the beginning/end when the last/first frame is reached. */
  21. Clamp /**< Clamp to end/beginning, keeping the last/first frame active. */
  22. };
  23. /** Flags that determine which portion of Animation was changed and needs to be updated. */
  24. enum class AnimDirtyStateFlag
  25. {
  26. Clean = 0,
  27. Value = 1 << 0,
  28. Layout = 1 << 1,
  29. Skeleton = 1 << 2,
  30. Culling = 1 << 3
  31. };
  32. typedef Flags<AnimDirtyStateFlag> AnimDirtyState;
  33. BS_FLAGS_OPERATORS(AnimDirtyStateFlag)
  34. /** Contains information about a currently playing animation clip. */
  35. struct AnimationClipState
  36. {
  37. AnimationClipState() { }
  38. /** Layer the clip is playing on. Multiple clips can be played simulatenously on different layers. */
  39. UINT32 layer = 0;
  40. float time = 0.0f; /**< Current time the animation is playing from. */
  41. float speed = 1.0f; /**< Speed at which the animation is playing. */
  42. float weight = 1.0f; /**< Determines how much of an influence does the clip have on the final pose. */
  43. /** Determines what happens to other animation clips when a new clip starts playing. */
  44. AnimWrapMode wrapMode = AnimWrapMode::Loop;
  45. /**
  46. * Determines should the time be advanced automatically. Certain type of animation clips don't involve playback
  47. * (e.g. for blending where animation weight controls the animation).
  48. */
  49. bool stopped = false;
  50. };
  51. /** Type of playback for animation clips. */
  52. enum class AnimPlaybackType
  53. {
  54. /** Play back the animation normally by advancing time. */
  55. Normal,
  56. /** Sample only a single frame from the animation. */
  57. Sampled,
  58. /** Do not play the animation. */
  59. None
  60. };
  61. /** Internal information about a single playing animation clip within Animation. */
  62. struct AnimationClipInfo
  63. {
  64. AnimationClipInfo();
  65. AnimationClipInfo(const HAnimationClip& clip);
  66. HAnimationClip clip;
  67. AnimationClipState state;
  68. AnimPlaybackType playbackType;
  69. float fadeDirection;
  70. float fadeTime;
  71. float fadeLength;
  72. /**
  73. * Version of the animation curves used by the AnimationProxy. Used to detecting the internal animation curves
  74. * changed.
  75. */
  76. UINT64 curveVersion;
  77. UINT32 layerIdx; /**< Layer index this clip belongs to in AnimationProxy structure. */
  78. UINT32 stateIdx; /**< State index this clip belongs to in AnimationProxy structure. */
  79. };
  80. /** Represents an animation clip used in 1D blending. Each clip has a position on the number line. */
  81. struct BS_CORE_EXPORT BlendClipInfo
  82. {
  83. BlendClipInfo() { }
  84. HAnimationClip clip;
  85. float position = 0.0f;
  86. };
  87. /** Defines a 1D blend where multiple animation clips are blended between each other using linear interpolation. */
  88. struct BS_CORE_EXPORT Blend1DInfo
  89. {
  90. Blend1DInfo(UINT32 numClips);
  91. ~Blend1DInfo();
  92. UINT32 numClips;
  93. BlendClipInfo* clips;
  94. };
  95. /** Defines a 2D blend where two animation clips are blended between each other using bilinear interpolation. */
  96. struct Blend2DInfo
  97. {
  98. HAnimationClip topLeftClip;
  99. HAnimationClip topRightClip;
  100. HAnimationClip botLeftClip;
  101. HAnimationClip botRightClip;
  102. };
  103. /** Contains a mapping between a scene object and an animation curve it is animated with. */
  104. struct AnimatedSceneObject
  105. {
  106. HSceneObject so;
  107. String curveName;
  108. };
  109. /** Contains information about a scene object that is animated by a specific animation curve. */
  110. struct AnimatedSceneObjectInfo
  111. {
  112. UINT64 id; /**< Instance ID of the scene object. */
  113. INT32 boneIdx; /**< Bone from which to access the transform. If -1 then no bone mapping is present. */
  114. INT32 layerIdx; /**< If no bone mapping, layer on which the animation containing the referenced curve is in. */
  115. INT32 stateIdx; /**< If no bone mapping, animation state containing the referenced curve. */
  116. AnimationCurveMapping curveIndices; /**< Indices of the curves used for the transform. */
  117. UINT32 hash; /**< Hash value of the scene object's transform. */
  118. };
  119. /** Represents a copy of the Animation data for use specifically on the animation thread. */
  120. struct AnimationProxy
  121. {
  122. AnimationProxy(UINT64 id);
  123. AnimationProxy(const AnimationProxy&) = delete;
  124. ~AnimationProxy();
  125. AnimationProxy& operator=(const AnimationProxy&) = delete;
  126. /**
  127. * Rebuilds the internal proxy data according to the newly assigned skeleton and clips. This should be called
  128. * whenever the animation skeleton changes.
  129. *
  130. * @param[in] skeleton New skeleton to assign to the proxy.
  131. * @param[in] mask Mask that filters which skeleton bones are enabled or disabled.
  132. * @param[in, out] clipInfos Potentially new clip infos that will be used for rebuilding the proxy. Once the
  133. * method completes clip info layout and state indices will be populated for
  134. * further use in the update*() methods.
  135. * @param[in] sceneObjects A list of scene objects that are influenced by specific animation curves.
  136. *
  137. * @note Should be called from the sim thread when the caller is sure the animation thread is not using it.
  138. */
  139. void rebuild(const SPtr<Skeleton>& skeleton, const SkeletonMask& mask, Vector<AnimationClipInfo>& clipInfos,
  140. const Vector<AnimatedSceneObject>& sceneObjects);
  141. /**
  142. * Rebuilds the internal proxy data according to the newly clips. This should be called whenever clips are added
  143. * or removed, or clip layout indices change.
  144. *
  145. * @param[in, out] clipInfos New clip infos that will be used for rebuilding the proxy. Once the method
  146. * completes clip info layout and state indices will be populated for further use
  147. * in the update*() methods.
  148. * @param[in] sceneObjects A list of scene objects that are influenced by specific animation curves.
  149. *
  150. * @note Should be called from the sim thread when the caller is sure the animation thread is not using it.
  151. */
  152. void rebuild(Vector<AnimationClipInfo>& clipInfos, const Vector<AnimatedSceneObject>& sceneObjects);
  153. /**
  154. * Updates the proxy data with new information about the clips. Caller must guarantee that clip layout didn't
  155. * change since the last call to rebuild().
  156. *
  157. * @note Should be called from the sim thread when the caller is sure the animation thread is not using it.
  158. */
  159. void updateValues(const Vector<AnimationClipInfo>& clipInfos);
  160. /**
  161. * Updates the proxy data with new scene object transforms. Caller must guarantee that clip layout didn't
  162. * change since the last call to rebuild().
  163. *
  164. * @note Should be called from the sim thread when the caller is sure the animation thread is not using it.
  165. */
  166. void updateTransforms(const Vector<AnimatedSceneObject>& sceneObjects);
  167. /**
  168. * Updates the proxy data with new clip times. Caller must guarantee that clip layout didn't change since the last
  169. * call to rebuild().
  170. *
  171. * @note Should be called from the sim thread when the caller is sure the animation thread is not using it.
  172. */
  173. void updateTime(const Vector<AnimationClipInfo>& clipInfos);
  174. /** Destroys all dynamically allocated objects. */
  175. void clear();
  176. UINT64 id;
  177. AnimationStateLayer* layers;
  178. UINT32 numLayers;
  179. SPtr<Skeleton> skeleton;
  180. SkeletonMask skeletonMask;
  181. UINT32 numSceneObjects;
  182. AnimatedSceneObjectInfo* sceneObjectInfos;
  183. Matrix4* sceneObjectTransforms;
  184. // Culling
  185. AABox mBounds;
  186. bool mCullEnabled;
  187. // Evaluation results
  188. LocalSkeletonPose skeletonPose;
  189. LocalSkeletonPose sceneObjectPose;
  190. UINT32 numGenericCurves;
  191. float* genericCurveOutputs;
  192. };
  193. /**
  194. * Handles animation playback. Takes one or multiple animation clips as input and evaluates them every animation update
  195. * tick depending on set properties. The evaluated data is used by the core thread for skeletal animation, by the sim
  196. * thread for updating attached scene objects and bones (if skeleton is attached), or the data is made available for
  197. * manual queries in the case of generic animation.
  198. */
  199. class BS_CORE_EXPORT Animation : public CoreObject, public IResourceListener
  200. {
  201. public:
  202. ~Animation();
  203. /**
  204. * Changes the skeleton which will the translation/rotation/scale animation values manipulate. If no skeleton is set
  205. * the animation will only evaluate the generic curves, and the root translation/rotation/scale curves.
  206. */
  207. void setSkeleton(const SPtr<Skeleton>& skeleton);
  208. /**
  209. * Sets a mask that allows certain bones from the skeleton to be disabled. Caller must ensure that the mask matches
  210. * the skeleton assigned to the animation.
  211. */
  212. void setMask(const SkeletonMask& mask);
  213. /**
  214. * Changes the wrap mode for all active animations. Wrap mode determines what happens when animation reaches the
  215. * first or last frame.
  216. *
  217. * @see AnimWrapMode
  218. */
  219. void setWrapMode(AnimWrapMode wrapMode);
  220. /** Changes the speed for all animations. The default value is 1.0f. Use negative values to play-back in reverse. */
  221. void setSpeed(float speed);
  222. /** Sets bounds that will be used for animation culling, if enabled. Bounds must be in world space. */
  223. void setBounds(const AABox& bounds);
  224. /**
  225. * When enabled, animation that is not in a view of any camera will not be evaluated. View determination is done by
  226. * checking the bounds provided in setBounds().
  227. */
  228. void setCulling(bool cull);
  229. /**
  230. * Plays the specified animation clip.
  231. *
  232. * @param[in] clip Clip to play.
  233. */
  234. void play(const HAnimationClip& clip);
  235. /**
  236. * Plays the specified animation clip on top of the animation currently playing in the main layer. Multiple
  237. * such clips can be playing at once, as long as you ensure each is given its own layer. Each animation can
  238. * also have a weight that determines how much it influences the main animation.
  239. *
  240. * @param[in] clip Clip to additively blend. Must contain additive animation curves.
  241. * @param[in] weight Determines how much of an effect will the blended animation have on the final output.
  242. * In range [0, 1].
  243. * @param[in] fadeLength Applies the blend over a specified time period, increasing the weight as the time
  244. * passes. Set to zero to blend immediately. In seconds.
  245. * @param[in] layer Layer to play the clip in. Multiple additive clips can be playing at once in separate
  246. * layers and each layer has its own weight.
  247. */
  248. void blendAdditive(const HAnimationClip& clip, float weight, float fadeLength = 0.0f, UINT32 layer = 0);
  249. /**
  250. * Blend multiple animation clips between each other using linear interpolation. Unlike normal animations these
  251. * animations are not advanced with the progress of time, and is instead expected the user manually changes the
  252. * @p t parameter.
  253. *
  254. * @param[in] info Information about the clips to blend. Clip positions must be sorted from lowest to highest.
  255. * @param[in] t Parameter that controls the blending. Range depends on the positions of the provided
  256. * animation clips.
  257. */
  258. void blend1D(const Blend1DInfo& info, float t);
  259. /**
  260. * Blend four animation clips between each other using bilinear interpolation. Unlike normal animations these
  261. * animations are not advanced with the progress of time, and is instead expected the user manually changes the
  262. * @p t parameter.
  263. *
  264. * @param[in] info Information about the clips to blend.
  265. * @param[in] t Parameter that controls the blending, in range [(0, 0), (1, 1)]. t = (0, 0) means top left
  266. * animation has full influence, t = (0, 1) means top right animation has full influence,
  267. * t = (1, 0) means bottom left animation has full influence, t = (1, 1) means bottom right
  268. * animation has full influence.
  269. */
  270. void blend2D(const Blend2DInfo& info, const Vector2& t);
  271. /**
  272. * Fades the specified animation clip in, while fading other playing animation out, over the specified time
  273. * period.
  274. *
  275. * @param[in] clip Clip to fade in.
  276. * @param[in] fadeLength Determines the time period over which the fade occurs. In seconds.
  277. */
  278. void crossFade(const HAnimationClip& clip, float fadeLength);
  279. /**
  280. * Samples an animation clip at the specified time, displaying only that particular frame without further playback.
  281. *
  282. * @param[in] clip Animation clip to sample.
  283. * @param[in] time Time to sample the clip at.
  284. */
  285. void sample(const HAnimationClip& clip, float time);
  286. /**
  287. * Stops playing all animations on the provided layer. Specify -1 to stop animation on the main layer
  288. * (non-additive animations).
  289. */
  290. void stop(UINT32 layer);
  291. /** Stops playing all animations. */
  292. void stopAll();
  293. /** Checks if any animation clips are currently playing. */
  294. bool isPlaying() const;
  295. /** Returns the total number of animation clips influencing this animation. */
  296. UINT32 getNumClips() const;
  297. /**
  298. * Returns one of the animation clips influencing this animation.
  299. *
  300. * @param[in] idx Sequential index of the animation clip to retrieve. In range [0, getNumClips()].
  301. * @return Animation clip at the specified index, or null if the index is out of range.
  302. */
  303. HAnimationClip getClip(UINT32 idx) const;
  304. /**
  305. * Retrieves detailed information about a currently playing animation clip.
  306. *
  307. * @param[in] clip Clip to retrieve the information for.
  308. * @param[out] state Animation clip state containing the requested information. Only valid if the method returns
  309. * true.
  310. * @return True if the state was found (animation clip is playing), false otherwise.
  311. */
  312. bool getState(const HAnimationClip& clip, AnimationClipState& state);
  313. /**
  314. * Changes the state of a playing animation clip. If animation clip is not currently playing the state change is
  315. * ignored.
  316. *
  317. * @param[in] clip Clip to change the state for.
  318. * @param[in] state New state of the animation (e.g. changing the time for seeking).
  319. */
  320. void setState(const HAnimationClip& clip, AnimationClipState state);
  321. /**
  322. * Ensures that any position/rotation/scale animation of a specific animation curve is transfered to the
  323. * the provided scene object. Also allow the opposite operation which can allow scene object transform changes
  324. * to manipulate object bones.
  325. *
  326. * @param[in] curve Name of the curve (bone) to connect the scene object with. Use empty string to map to the
  327. * root bone, regardless of the bone name.
  328. * @param[in] so Scene object to influence by the curve modifications, and vice versa.
  329. */
  330. void mapCurveToSceneObject(const String& curve, const HSceneObject& so);
  331. /** Removes the curve <-> scene object mapping that was set via mapCurveToSceneObject(). */
  332. void unmapSceneObject(const HSceneObject& so);
  333. /**
  334. * Retrieves an evaluated value for a generic curve with the specified index.
  335. *
  336. * @param[in] curveIdx The curve index referencing a set of curves from the first playing animation clip.
  337. * Generic curves from all other clips are ignored.
  338. * @param[out] value Value of the generic curve. Only valid if the method return true.
  339. * @return True if the value was retrieved successfully. The method might fail if animation update
  340. * didn't yet have a chance to execute and values are not yet available, or if the
  341. * animation clip changed since the last frame (the last problem can be avoided by ensuring
  342. * to read the curve values before changing the clip).
  343. */
  344. bool getGenericCurveValue(UINT32 curveIdx, float& value);
  345. /** Creates a new empty Animation object. */
  346. static SPtr<Animation> create();
  347. /** Triggered whenever an animation event is reached. */
  348. Event<void(const HAnimationClip&, const String&)> onEventTriggered;
  349. /** @name Internal
  350. * @{
  351. */
  352. /** Returns the unique ID for this animation object. */
  353. UINT64 _getId() const { return mId; }
  354. /** @} */
  355. private:
  356. friend class AnimationManager;
  357. Animation();
  358. /**
  359. * Triggers any events between the last frame and current one.
  360. *
  361. * @param[in] lastFrameTime Time of the last frame.
  362. * @param[in] delta Difference between the last and this frame.
  363. */
  364. void triggerEvents(float lastFrameTime, float delta);
  365. /**
  366. * Updates the animation proxy object based on the currently set skeleton, playing clips and dirty flags.
  367. *
  368. * @param[in] timeDelta Seconds passed since the last call to this method.
  369. */
  370. void updateAnimProxy(float timeDelta);
  371. /**
  372. * Applies any outputs stored in the animation proxy (as written by the animation thread), and uses them to update
  373. * the animation state on the simulation thread. Caller must ensure that the animation thread has finished
  374. * with the animation proxy.
  375. */
  376. void updateFromProxy();
  377. /**
  378. * Registers a new animation in the specified layer, or returns an existing animation clip info if the animation is
  379. * already registered. If @p stopExisting is true any existing animations in the layer will be stopped. Layout
  380. * will be marked as dirty if any changes were made.
  381. */
  382. AnimationClipInfo* addClip(const HAnimationClip& clip, UINT32 layer, bool stopExisting = true);
  383. /** @copydoc IResourceListener::getListenerResources */
  384. void getListenerResources(Vector<HResource>& resources) override;
  385. /** @copydoc IResourceListener::notifyResourceLoaded */
  386. void notifyResourceLoaded(const HResource& resource) override;
  387. /** @copydoc IResourceListener::notifyResourceChanged */
  388. void notifyResourceChanged(const HResource& resource) override;
  389. UINT64 mId;
  390. AnimWrapMode mDefaultWrapMode;
  391. float mDefaultSpeed;
  392. AABox mBounds;
  393. bool mCull;
  394. AnimDirtyState mDirty;
  395. SPtr<Skeleton> mSkeleton;
  396. SkeletonMask mSkeletonMask;
  397. Vector<AnimationClipInfo> mClipInfos;
  398. UnorderedMap<UINT64, AnimatedSceneObject> mSceneObjects;
  399. Vector<float> mGenericCurveOutputs;
  400. bool mGenericCurveValuesValid;
  401. // Animation thread only
  402. SPtr<AnimationProxy> mAnimProxy;
  403. };
  404. /** @} */
  405. }