AnimationTrack.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.Animations;
  4. using UnityEngine.Experimental.Animations;
  5. using UnityEngine.Playables;
  6. using UnityEngine.Serialization;
  7. #if UNITY_EDITOR
  8. using UnityEditor;
  9. #endif
  10. namespace UnityEngine.Timeline
  11. {
  12. /// <summary>
  13. /// Flags specifying which offset fields to match
  14. /// </summary>
  15. [Flags]
  16. public enum MatchTargetFields
  17. {
  18. /// <summary>
  19. /// Translation X value
  20. /// </summary>
  21. PositionX = 1 << 0,
  22. /// <summary>
  23. /// Translation Y value
  24. /// </summary>
  25. PositionY = 1 << 1,
  26. /// <summary>
  27. /// Translation Z value
  28. /// </summary>
  29. PositionZ = 1 << 2,
  30. /// <summary>
  31. /// Rotation Euler Angle X value
  32. /// </summary>
  33. RotationX = 1 << 3,
  34. /// <summary>
  35. /// Rotation Euler Angle Y value
  36. /// </summary>
  37. RotationY = 1 << 4,
  38. /// <summary>
  39. /// Rotation Euler Angle Z value
  40. /// </summary>
  41. RotationZ = 1 << 5
  42. }
  43. /// <summary>
  44. /// Describes what is used to set the starting position and orientation of each Animation Track.
  45. /// </summary>
  46. /// <remarks>
  47. /// By default, each Animation Track uses ApplyTransformOffsets to start from a set position and orientation.
  48. /// To offset each Animation Track based on the current position and orientation in the scene, use ApplySceneOffsets.
  49. /// </remarks>
  50. public enum TrackOffset
  51. {
  52. /// <summary>
  53. /// Use this setting to offset each Animation Track based on a set position and orientation.
  54. /// </summary>
  55. ApplyTransformOffsets,
  56. /// <summary>
  57. /// Use this setting to offset each Animation Track based on the current position and orientation in the scene.
  58. /// </summary>
  59. ApplySceneOffsets,
  60. /// <summary>
  61. /// Use this setting to offset root transforms based on the state of the animator.
  62. /// </summary>
  63. /// <remarks>
  64. /// Only use this setting to support legacy Animation Tracks. This mode may be deprecated in a future release.
  65. ///
  66. /// In Auto mode, when the animator bound to the animation track contains an AnimatorController, it offsets all animations similar to ApplySceneOffsets.
  67. /// If no controller is assigned, then all offsets are set to start from a fixed position and orientation, similar to ApplyTransformOffsets.
  68. /// In Auto mode, in most cases, root transforms are not affected by local scale or Animator.humanScale, unless the animator has an AnimatorController and Animator.applyRootMotion is set to true.
  69. /// </remarks>
  70. Auto
  71. }
  72. // offset mode
  73. enum AppliedOffsetMode
  74. {
  75. NoRootTransform,
  76. TransformOffset,
  77. SceneOffset,
  78. TransformOffsetLegacy,
  79. SceneOffsetLegacy,
  80. SceneOffsetEditor, // scene offset mode in editor
  81. SceneOffsetLegacyEditor,
  82. }
  83. // separate from the enum to hide them from UI elements
  84. static class MatchTargetFieldConstants
  85. {
  86. public static MatchTargetFields All = MatchTargetFields.PositionX | MatchTargetFields.PositionY |
  87. MatchTargetFields.PositionZ | MatchTargetFields.RotationX |
  88. MatchTargetFields.RotationY | MatchTargetFields.RotationZ;
  89. public static MatchTargetFields None = 0;
  90. public static MatchTargetFields Position = MatchTargetFields.PositionX | MatchTargetFields.PositionY |
  91. MatchTargetFields.PositionZ;
  92. public static MatchTargetFields Rotation = MatchTargetFields.RotationX | MatchTargetFields.RotationY |
  93. MatchTargetFields.RotationZ;
  94. public static bool HasAny(this MatchTargetFields me, MatchTargetFields fields)
  95. {
  96. return (me & fields) != None;
  97. }
  98. public static MatchTargetFields Toggle(this MatchTargetFields me, MatchTargetFields flag)
  99. {
  100. return me ^ flag;
  101. }
  102. }
  103. /// <summary>
  104. /// A Timeline track used for playing back animations on an Animator.
  105. /// </summary>
  106. [Serializable]
  107. [TrackClipType(typeof(AnimationPlayableAsset), false)]
  108. [TrackBindingType(typeof(Animator))]
  109. public partial class AnimationTrack : TrackAsset, ILayerable
  110. {
  111. const string k_DefaultInfiniteClipName = "Recorded";
  112. const string k_DefaultRecordableClipName = "Recorded";
  113. [SerializeField, FormerlySerializedAs("m_OpenClipPreExtrapolation")]
  114. TimelineClip.ClipExtrapolation m_InfiniteClipPreExtrapolation = TimelineClip.ClipExtrapolation.None;
  115. [SerializeField, FormerlySerializedAs("m_OpenClipPostExtrapolation")]
  116. TimelineClip.ClipExtrapolation m_InfiniteClipPostExtrapolation = TimelineClip.ClipExtrapolation.None;
  117. [SerializeField, FormerlySerializedAs("m_OpenClipOffsetPosition")]
  118. Vector3 m_InfiniteClipOffsetPosition = Vector3.zero;
  119. [SerializeField, FormerlySerializedAs("m_OpenClipOffsetEulerAngles")]
  120. Vector3 m_InfiniteClipOffsetEulerAngles = Vector3.zero;
  121. [SerializeField, FormerlySerializedAs("m_OpenClipTimeOffset")]
  122. double m_InfiniteClipTimeOffset;
  123. [SerializeField, FormerlySerializedAs("m_OpenClipRemoveOffset")]
  124. bool m_InfiniteClipRemoveOffset; // cached value for remove offset
  125. [SerializeField]
  126. bool m_InfiniteClipApplyFootIK = true;
  127. [SerializeField, HideInInspector]
  128. AnimationPlayableAsset.LoopMode mInfiniteClipLoop = AnimationPlayableAsset.LoopMode.UseSourceAsset;
  129. [SerializeField]
  130. MatchTargetFields m_MatchTargetFields = MatchTargetFieldConstants.All;
  131. [SerializeField]
  132. Vector3 m_Position = Vector3.zero;
  133. [SerializeField]
  134. Vector3 m_EulerAngles = Vector3.zero;
  135. [SerializeField] AvatarMask m_AvatarMask;
  136. [SerializeField] bool m_ApplyAvatarMask = true;
  137. [SerializeField] TrackOffset m_TrackOffset = TrackOffset.ApplyTransformOffsets;
  138. [SerializeField, HideInInspector] AnimationClip m_InfiniteClip;
  139. #if UNITY_EDITOR
  140. private AnimationClip m_DefaultPoseClip;
  141. private AnimationClip m_CachedPropertiesClip;
  142. AnimationOffsetPlayable m_ClipOffset;
  143. private Vector3 m_SceneOffsetPosition = Vector3.zero;
  144. private Vector3 m_SceneOffsetRotation = Vector3.zero;
  145. private bool m_HasPreviewComponents = false;
  146. #endif
  147. /// <summary>
  148. /// The translation offset of the entire track.
  149. /// </summary>
  150. public Vector3 position
  151. {
  152. get { return m_Position; }
  153. set { m_Position = value; }
  154. }
  155. /// <summary>
  156. /// The rotation offset of the entire track, expressed as a quaternion.
  157. /// </summary>
  158. public Quaternion rotation
  159. {
  160. get { return Quaternion.Euler(m_EulerAngles); }
  161. set { m_EulerAngles = value.eulerAngles; }
  162. }
  163. /// <summary>
  164. /// The euler angle representation of the rotation offset of the entire track.
  165. /// </summary>
  166. public Vector3 eulerAngles
  167. {
  168. get { return m_EulerAngles; }
  169. set { m_EulerAngles = value; }
  170. }
  171. /// <summary>
  172. /// Specifies whether to apply track offsets to all clips on the track.
  173. /// </summary>
  174. /// <remarks>
  175. /// This can be used to offset all clips on a track, in addition to the clips individual offsets.
  176. /// </remarks>
  177. [Obsolete("applyOffset is deprecated. Use trackOffset instead", true)]
  178. public bool applyOffsets
  179. {
  180. get { return false; }
  181. set {}
  182. }
  183. /// <summary>
  184. /// Specifies what is used to set the starting position and orientation of an Animation Track.
  185. /// </summary>
  186. /// <remarks>
  187. /// Track Offset is only applied when the Animation Track contains animation that modifies the root Transform.
  188. /// </remarks>
  189. public TrackOffset trackOffset
  190. {
  191. get { return m_TrackOffset; }
  192. set { m_TrackOffset = value; }
  193. }
  194. /// <summary>
  195. /// Specifies which fields to match when aligning offsets of clips.
  196. /// </summary>
  197. public MatchTargetFields matchTargetFields
  198. {
  199. get { return m_MatchTargetFields; }
  200. set { m_MatchTargetFields = value & MatchTargetFieldConstants.All; }
  201. }
  202. /// <summary>
  203. /// An AnimationClip storing the data for an infinite track.
  204. /// </summary>
  205. /// <remarks>
  206. /// The value of this property is null when the AnimationTrack is in Clip Mode.
  207. /// </remarks>
  208. public AnimationClip infiniteClip
  209. {
  210. get { return m_InfiniteClip; }
  211. internal set { m_InfiniteClip = value; }
  212. }
  213. // saved value for converting to/from infinite mode
  214. internal bool infiniteClipRemoveOffset
  215. {
  216. get { return m_InfiniteClipRemoveOffset; }
  217. set { m_InfiniteClipRemoveOffset = value; }
  218. }
  219. /// <summary>
  220. /// Specifies the AvatarMask to be applied to all clips on the track.
  221. /// </summary>
  222. /// <remarks>
  223. /// Applying an AvatarMask to an animation track will allow discarding portions of the animation being applied on the track.
  224. /// </remarks>
  225. public AvatarMask avatarMask
  226. {
  227. get { return m_AvatarMask; }
  228. set { m_AvatarMask = value; }
  229. }
  230. /// <summary>
  231. /// Specifies whether to apply the AvatarMask to the track.
  232. /// </summary>
  233. public bool applyAvatarMask
  234. {
  235. get { return m_ApplyAvatarMask; }
  236. set { m_ApplyAvatarMask = value; }
  237. }
  238. // is this track compilable
  239. internal override bool CanCompileClips()
  240. {
  241. return !muted && (m_Clips.Count > 0 || (m_InfiniteClip != null && !m_InfiniteClip.empty));
  242. }
  243. /// <inheritdoc/>
  244. public override IEnumerable<PlayableBinding> outputs
  245. {
  246. get { yield return AnimationPlayableBinding.Create(name, this); }
  247. }
  248. /// <summary>
  249. /// Specifies whether the Animation Track has clips, or is in infinite mode.
  250. /// </summary>
  251. public bool inClipMode
  252. {
  253. get { return clips != null && clips.Length != 0; }
  254. }
  255. /// <summary>
  256. /// The translation offset of a track in infinite mode.
  257. /// </summary>
  258. public Vector3 infiniteClipOffsetPosition
  259. {
  260. get { return m_InfiniteClipOffsetPosition; }
  261. set { m_InfiniteClipOffsetPosition = value; }
  262. }
  263. /// <summary>
  264. /// The rotation offset of a track in infinite mode.
  265. /// </summary>
  266. public Quaternion infiniteClipOffsetRotation
  267. {
  268. get { return Quaternion.Euler(m_InfiniteClipOffsetEulerAngles); }
  269. set { m_InfiniteClipOffsetEulerAngles = value.eulerAngles; }
  270. }
  271. /// <summary>
  272. /// The euler angle representation of the rotation offset of the track when in infinite mode.
  273. /// </summary>
  274. public Vector3 infiniteClipOffsetEulerAngles
  275. {
  276. get { return m_InfiniteClipOffsetEulerAngles; }
  277. set { m_InfiniteClipOffsetEulerAngles = value; }
  278. }
  279. internal bool infiniteClipApplyFootIK
  280. {
  281. get { return m_InfiniteClipApplyFootIK; }
  282. set { m_InfiniteClipApplyFootIK = value; }
  283. }
  284. internal double infiniteClipTimeOffset
  285. {
  286. get { return m_InfiniteClipTimeOffset; }
  287. set { m_InfiniteClipTimeOffset = value; }
  288. }
  289. /// <summary>
  290. /// The saved state of pre-extrapolation for clips converted to infinite mode.
  291. /// </summary>
  292. public TimelineClip.ClipExtrapolation infiniteClipPreExtrapolation
  293. {
  294. get { return m_InfiniteClipPreExtrapolation; }
  295. set { m_InfiniteClipPreExtrapolation = value; }
  296. }
  297. /// <summary>
  298. /// The saved state of post-extrapolation for clips when converted to infinite mode.
  299. /// </summary>
  300. public TimelineClip.ClipExtrapolation infiniteClipPostExtrapolation
  301. {
  302. get { return m_InfiniteClipPostExtrapolation; }
  303. set { m_InfiniteClipPostExtrapolation = value; }
  304. }
  305. /// <summary>
  306. /// The saved state of animation clip loop state when converted to infinite mode
  307. /// </summary>
  308. internal AnimationPlayableAsset.LoopMode infiniteClipLoop
  309. {
  310. get { return mInfiniteClipLoop; }
  311. set { mInfiniteClipLoop = value; }
  312. }
  313. [ContextMenu("Reset Offsets")]
  314. void ResetOffsets()
  315. {
  316. m_Position = Vector3.zero;
  317. m_EulerAngles = Vector3.zero;
  318. UpdateClipOffsets();
  319. }
  320. /// <summary>
  321. /// Creates a TimelineClip on this track that uses an AnimationClip.
  322. /// </summary>
  323. /// <param name="clip">Source animation clip of the resulting TimelineClip.</param>
  324. /// <returns>A new TimelineClip which has an AnimationPlayableAsset asset attached.</returns>
  325. public TimelineClip CreateClip(AnimationClip clip)
  326. {
  327. if (clip == null)
  328. return null;
  329. var newClip = CreateClip<AnimationPlayableAsset>();
  330. AssignAnimationClip(newClip, clip);
  331. return newClip;
  332. }
  333. /// <summary>
  334. /// Creates an AnimationClip that stores the data for an infinite track.
  335. /// </summary>
  336. /// <remarks>
  337. /// If an infiniteClip already exists, this method produces no result, even if you provide a different value
  338. /// for infiniteClipName.
  339. /// </remarks>
  340. /// <remarks>
  341. /// This method can't create an infinite clip for an AnimationTrack that contains one or more Timeline clips.
  342. /// Use AnimationTrack.inClipMode to determine whether it is possible to create an infinite clip on an AnimationTrack.
  343. /// </remarks>
  344. /// <remarks>
  345. /// When used from the editor, this method attempts to save the created infinite clip to the TimelineAsset.
  346. /// The TimelineAsset must already exist in the AssetDatabase to save the infinite clip. If the TimelineAsset
  347. /// does not exist, the infinite clip is still created but it is not saved.
  348. /// </remarks>
  349. /// <param name="infiniteClipName">
  350. /// The name of the AnimationClip to create.
  351. /// This method does not ensure unique names. If you want a unique clip name, you must provide one.
  352. /// See ObjectNames.GetUniqueName for information on a method that creates unique names.
  353. /// </param>
  354. public void CreateInfiniteClip(string infiniteClipName)
  355. {
  356. if (inClipMode)
  357. {
  358. Debug.LogWarning("CreateInfiniteClip cannot create an infinite clip for an AnimationTrack that contains one or more Timeline Clips.");
  359. return;
  360. }
  361. if (m_InfiniteClip != null)
  362. return;
  363. m_InfiniteClip = TimelineCreateUtilities.CreateAnimationClipForTrack(string.IsNullOrEmpty(infiniteClipName) ? k_DefaultInfiniteClipName : infiniteClipName, this, false);
  364. }
  365. /// <summary>
  366. /// Creates a TimelineClip, AnimationPlayableAsset and an AnimationClip. Use this clip to record in a timeline.
  367. /// </summary>
  368. /// <remarks>
  369. /// When used from the editor, this method attempts to save the created recordable clip to the TimelineAsset.
  370. /// The TimelineAsset must already exist in the AssetDatabase to save the recordable clip. If the TimelineAsset
  371. /// does not exist, the recordable clip is still created but it is not saved.
  372. /// </remarks>
  373. /// <param name="animClipName">
  374. /// The name of the AnimationClip to create.
  375. /// This method does not ensure unique names. If you want a unique clip name, you must provide one.
  376. /// See ObjectNames.GetUniqueName for information on a method that creates unique names.
  377. /// </param>
  378. /// <returns>
  379. /// Returns a new TimelineClip with an AnimationPlayableAsset asset attached.
  380. /// </returns>
  381. public TimelineClip CreateRecordableClip(string animClipName)
  382. {
  383. var clip = TimelineCreateUtilities.CreateAnimationClipForTrack(string.IsNullOrEmpty(animClipName) ? k_DefaultRecordableClipName : animClipName, this, false);
  384. var timelineClip = CreateClip(clip);
  385. timelineClip.displayName = animClipName;
  386. timelineClip.recordable = true;
  387. timelineClip.start = 0;
  388. timelineClip.duration = 1;
  389. var apa = timelineClip.asset as AnimationPlayableAsset;
  390. if (apa != null)
  391. apa.removeStartOffset = false;
  392. return timelineClip;
  393. }
  394. #if UNITY_EDITOR
  395. internal Vector3 sceneOffsetPosition
  396. {
  397. get { return m_SceneOffsetPosition; }
  398. set { m_SceneOffsetPosition = value; }
  399. }
  400. internal Vector3 sceneOffsetRotation
  401. {
  402. get { return m_SceneOffsetRotation; }
  403. set { m_SceneOffsetRotation = value; }
  404. }
  405. internal bool hasPreviewComponents
  406. {
  407. get
  408. {
  409. if (m_HasPreviewComponents)
  410. return true;
  411. var parentTrack = parent as AnimationTrack;
  412. if (parentTrack != null)
  413. {
  414. return parentTrack.hasPreviewComponents;
  415. }
  416. return false;
  417. }
  418. }
  419. #endif
  420. /// <summary>
  421. /// Used to initialize default values on a newly created clip
  422. /// </summary>
  423. /// <param name="clip">The clip added to the track</param>
  424. protected override void OnCreateClip(TimelineClip clip)
  425. {
  426. var extrapolation = TimelineClip.ClipExtrapolation.None;
  427. if (!isSubTrack)
  428. extrapolation = TimelineClip.ClipExtrapolation.Hold;
  429. clip.preExtrapolationMode = extrapolation;
  430. clip.postExtrapolationMode = extrapolation;
  431. }
  432. protected internal override int CalculateItemsHash()
  433. {
  434. return GetAnimationClipHash(m_InfiniteClip).CombineHash(base.CalculateItemsHash());
  435. }
  436. internal void UpdateClipOffsets()
  437. {
  438. #if UNITY_EDITOR
  439. if (m_ClipOffset.IsValid())
  440. {
  441. m_ClipOffset.SetPosition(position);
  442. m_ClipOffset.SetRotation(rotation);
  443. }
  444. #endif
  445. }
  446. Playable CompileTrackPlayable(PlayableGraph graph, TrackAsset track, GameObject go, IntervalTree<RuntimeElement> tree, AppliedOffsetMode mode)
  447. {
  448. var mixer = AnimationMixerPlayable.Create(graph, track.clips.Length);
  449. for (int i = 0; i < track.clips.Length; i++)
  450. {
  451. var c = track.clips[i];
  452. var asset = c.asset as PlayableAsset;
  453. if (asset == null)
  454. continue;
  455. var animationAsset = asset as AnimationPlayableAsset;
  456. if (animationAsset != null)
  457. animationAsset.appliedOffsetMode = mode;
  458. var source = asset.CreatePlayable(graph, go);
  459. if (source.IsValid())
  460. {
  461. var clip = new RuntimeClip(c, source, mixer);
  462. tree.Add(clip);
  463. graph.Connect(source, 0, mixer, i);
  464. mixer.SetInputWeight(i, 0.0f);
  465. }
  466. }
  467. return ApplyTrackOffset(graph, mixer, go, mode);
  468. }
  469. Playable ILayerable.CreateLayerMixer(PlayableGraph graph, GameObject go, int inputCount)
  470. {
  471. return Playable.Null;
  472. }
  473. internal override Playable OnCreateClipPlayableGraph(PlayableGraph graph, GameObject go, IntervalTree<RuntimeElement> tree)
  474. {
  475. if (isSubTrack)
  476. throw new InvalidOperationException("Nested animation tracks should never be asked to create a graph directly");
  477. List<AnimationTrack> flattenTracks = new List<AnimationTrack>();
  478. if (CanCompileClips())
  479. flattenTracks.Add(this);
  480. bool animatesRootTransform = AnimatesRootTransform();
  481. foreach (var subTrack in GetChildTracks())
  482. {
  483. var child = subTrack as AnimationTrack;
  484. if (child != null && child.CanCompileClips())
  485. {
  486. animatesRootTransform |= child.AnimatesRootTransform();
  487. flattenTracks.Add(child);
  488. }
  489. }
  490. // figure out which mode to apply
  491. AppliedOffsetMode mode = GetOffsetMode(go, animatesRootTransform);
  492. var layerMixer = CreateGroupMixer(graph, go, flattenTracks.Count);
  493. for (int c = 0; c < flattenTracks.Count; c++)
  494. {
  495. var compiledTrackPlayable = flattenTracks[c].inClipMode ?
  496. CompileTrackPlayable(graph, flattenTracks[c], go, tree, mode) :
  497. flattenTracks[c].CreateInfiniteTrackPlayable(graph, go, tree, mode);
  498. graph.Connect(compiledTrackPlayable, 0, layerMixer, c);
  499. layerMixer.SetInputWeight(c, flattenTracks[c].inClipMode ? 0 : 1);
  500. if (flattenTracks[c].applyAvatarMask && flattenTracks[c].avatarMask != null)
  501. {
  502. layerMixer.SetLayerMaskFromAvatarMask((uint)c, flattenTracks[c].avatarMask);
  503. }
  504. }
  505. bool requiresMotionXPlayable = RequiresMotionXPlayable(mode, go);
  506. Playable mixer = layerMixer;
  507. mixer = CreateDefaultBlend(graph, go, mixer, requiresMotionXPlayable);
  508. // motionX playable not required in scene offset mode, or root transform mode
  509. if (requiresMotionXPlayable)
  510. {
  511. // If we are animating a root transform, add the motionX to delta playable as the root node
  512. var motionXToDelta = AnimationMotionXToDeltaPlayable.Create(graph);
  513. graph.Connect(mixer, 0, motionXToDelta, 0);
  514. motionXToDelta.SetInputWeight(0, 1.0f);
  515. motionXToDelta.SetAbsoluteMotion(UsesAbsoluteMotion(mode));
  516. mixer = (Playable)motionXToDelta;
  517. }
  518. #if UNITY_EDITOR
  519. if (!Application.isPlaying)
  520. {
  521. var animator = GetBinding(go != null ? go.GetComponent<PlayableDirector>() : null);
  522. if (animator != null)
  523. {
  524. GameObject targetGO = animator.gameObject;
  525. IAnimationWindowPreview[] previewComponents = targetGO.GetComponents<IAnimationWindowPreview>();
  526. m_HasPreviewComponents = previewComponents.Length > 0;
  527. if (m_HasPreviewComponents)
  528. {
  529. foreach (var component in previewComponents)
  530. {
  531. mixer = component.BuildPreviewGraph(graph, mixer);
  532. }
  533. }
  534. }
  535. }
  536. #endif
  537. return mixer;
  538. }
  539. // Creates a layer mixer containing default blends
  540. // the base layer is a default clip of all driven properties
  541. // the next layer is optionally the desired default pose (in the case of humanoid, the tpose
  542. private Playable CreateDefaultBlend(PlayableGraph graph, GameObject go, Playable mixer, bool requireOffset)
  543. {
  544. #if UNITY_EDITOR
  545. if (Application.isPlaying)
  546. return mixer;
  547. var animator = GetBinding(go != null ? go.GetComponent<PlayableDirector>() : null);
  548. int inputs = 1 + ((m_CachedPropertiesClip != null) ? 1 : 0) + ((m_DefaultPoseClip != null) ? 1 : 0);
  549. if (inputs == 1)
  550. return mixer;
  551. var defaultPoseMixer = AnimationLayerMixerPlayable.Create(graph, inputs);
  552. int mixerInput = 0;
  553. if (m_CachedPropertiesClip)
  554. {
  555. var defaults = (Playable)AnimationClipPlayable.Create(graph, m_CachedPropertiesClip);
  556. if (requireOffset)
  557. defaults = AttachOffsetPlayable(graph, defaults, m_SceneOffsetPosition, Quaternion.Euler(m_SceneOffsetRotation));
  558. graph.Connect(defaults, 0, defaultPoseMixer, mixerInput);
  559. defaultPoseMixer.SetInputWeight(mixerInput, 1.0f);
  560. mixerInput++;
  561. }
  562. if (m_DefaultPoseClip)
  563. {
  564. var blendDefault = (Playable)AnimationClipPlayable.Create(graph, m_DefaultPoseClip);
  565. if (requireOffset)
  566. blendDefault = AttachOffsetPlayable(graph, blendDefault, m_SceneOffsetPosition, Quaternion.Euler(m_SceneOffsetRotation));
  567. graph.Connect(blendDefault, 0, defaultPoseMixer, mixerInput);
  568. defaultPoseMixer.SetInputWeight(mixerInput, 1.0f);
  569. mixerInput++;
  570. }
  571. graph.Connect(mixer, 0, defaultPoseMixer, mixerInput);
  572. defaultPoseMixer.SetInputWeight(mixerInput, 1.0f);
  573. return defaultPoseMixer;
  574. #else
  575. return mixer;
  576. #endif
  577. }
  578. private Playable AttachOffsetPlayable(PlayableGraph graph, Playable playable, Vector3 pos, Quaternion rot)
  579. {
  580. var offsetPlayable = AnimationOffsetPlayable.Create(graph, pos, rot, 1);
  581. offsetPlayable.SetInputWeight(0, 1.0f);
  582. graph.Connect(playable, 0, offsetPlayable, 0);
  583. return offsetPlayable;
  584. }
  585. #if UNITY_EDITOR
  586. private static string k_DefaultHumanoidClipPath = "Packages/com.unity.timeline/Editor/StyleSheets/res/HumanoidDefault.anim";
  587. private static AnimationClip s_DefaultHumanoidClip = null;
  588. AnimationClip GetDefaultHumanoidClip()
  589. {
  590. if (s_DefaultHumanoidClip == null)
  591. {
  592. s_DefaultHumanoidClip = EditorGUIUtility.LoadRequired(k_DefaultHumanoidClipPath) as AnimationClip;
  593. if (s_DefaultHumanoidClip == null)
  594. Debug.LogError("Could not load default humanoid animation clip for Timeline");
  595. }
  596. return s_DefaultHumanoidClip;
  597. }
  598. #endif
  599. bool RequiresMotionXPlayable(AppliedOffsetMode mode, GameObject gameObject)
  600. {
  601. if (mode == AppliedOffsetMode.NoRootTransform)
  602. return false;
  603. if (mode == AppliedOffsetMode.SceneOffsetLegacy)
  604. {
  605. var animator = GetBinding(gameObject != null ? gameObject.GetComponent<PlayableDirector>() : null);
  606. return animator != null && animator.hasRootMotion;
  607. }
  608. return true;
  609. }
  610. static bool UsesAbsoluteMotion(AppliedOffsetMode mode)
  611. {
  612. #if UNITY_EDITOR
  613. // in editor, previewing is always done in absolute motion
  614. if (!Application.isPlaying)
  615. return true;
  616. #endif
  617. return mode != AppliedOffsetMode.SceneOffset &&
  618. mode != AppliedOffsetMode.SceneOffsetLegacy;
  619. }
  620. bool HasController(GameObject gameObject)
  621. {
  622. var animator = GetBinding(gameObject != null ? gameObject.GetComponent<PlayableDirector>() : null);
  623. return animator != null && animator.runtimeAnimatorController != null;
  624. }
  625. internal Animator GetBinding(PlayableDirector director)
  626. {
  627. if (director == null)
  628. return null;
  629. UnityEngine.Object key = this;
  630. if (isSubTrack)
  631. key = parent;
  632. UnityEngine.Object binding = null;
  633. if (director != null)
  634. binding = director.GetGenericBinding(key);
  635. Animator animator = null;
  636. if (binding != null) // the binding can be an animator or game object
  637. {
  638. animator = binding as Animator;
  639. var gameObject = binding as GameObject;
  640. if (animator == null && gameObject != null)
  641. animator = gameObject.GetComponent<Animator>();
  642. }
  643. return animator;
  644. }
  645. static AnimationLayerMixerPlayable CreateGroupMixer(PlayableGraph graph, GameObject go, int inputCount)
  646. {
  647. return AnimationLayerMixerPlayable.Create(graph, inputCount);
  648. }
  649. Playable CreateInfiniteTrackPlayable(PlayableGraph graph, GameObject go, IntervalTree<RuntimeElement> tree, AppliedOffsetMode mode)
  650. {
  651. if (m_InfiniteClip == null)
  652. return Playable.Null;
  653. var mixer = AnimationMixerPlayable.Create(graph, 1);
  654. // In infinite mode, we always force the loop mode of the clip off because the clip keys are offset in infinite mode
  655. // which causes loop to behave different.
  656. // The inline curve editor never shows loops in infinite mode.
  657. var playable = AnimationPlayableAsset.CreatePlayable(graph, m_InfiniteClip, m_InfiniteClipOffsetPosition, m_InfiniteClipOffsetEulerAngles, false, mode, infiniteClipApplyFootIK, AnimationPlayableAsset.LoopMode.Off);
  658. if (playable.IsValid())
  659. {
  660. tree.Add(new InfiniteRuntimeClip(playable));
  661. graph.Connect(playable, 0, mixer, 0);
  662. mixer.SetInputWeight(0, 1.0f);
  663. }
  664. return ApplyTrackOffset(graph, mixer, go, mode);
  665. }
  666. Playable ApplyTrackOffset(PlayableGraph graph, Playable root, GameObject go, AppliedOffsetMode mode)
  667. {
  668. #if UNITY_EDITOR
  669. m_ClipOffset = AnimationOffsetPlayable.Null;
  670. #endif
  671. // offsets don't apply in scene offset, or if there is no root transform (globally or on this track)
  672. if (mode == AppliedOffsetMode.SceneOffsetLegacy ||
  673. mode == AppliedOffsetMode.SceneOffset ||
  674. mode == AppliedOffsetMode.NoRootTransform ||
  675. !AnimatesRootTransform()
  676. )
  677. return root;
  678. var pos = position;
  679. var rot = rotation;
  680. #if UNITY_EDITOR
  681. // in the editor use the preview position to playback from if available
  682. if (mode == AppliedOffsetMode.SceneOffsetEditor)
  683. {
  684. pos = m_SceneOffsetPosition;
  685. rot = Quaternion.Euler(m_SceneOffsetRotation);
  686. }
  687. #endif
  688. var offsetPlayable = AnimationOffsetPlayable.Create(graph, pos, rot, 1);
  689. #if UNITY_EDITOR
  690. m_ClipOffset = offsetPlayable;
  691. #endif
  692. graph.Connect(root, 0, offsetPlayable, 0);
  693. offsetPlayable.SetInputWeight(0, 1);
  694. return offsetPlayable;
  695. }
  696. // the evaluation time is large so that the properties always get evaluated
  697. internal override void GetEvaluationTime(out double outStart, out double outDuration)
  698. {
  699. if (inClipMode)
  700. {
  701. base.GetEvaluationTime(out outStart, out outDuration);
  702. }
  703. else
  704. {
  705. outStart = 0;
  706. outDuration = TimelineClip.kMaxTimeValue;
  707. }
  708. }
  709. internal override void GetSequenceTime(out double outStart, out double outDuration)
  710. {
  711. if (inClipMode)
  712. {
  713. base.GetSequenceTime(out outStart, out outDuration);
  714. }
  715. else
  716. {
  717. outStart = 0;
  718. outDuration = Math.Max(GetNotificationDuration(), TimeUtility.GetAnimationClipLength(m_InfiniteClip));
  719. }
  720. }
  721. void AssignAnimationClip(TimelineClip clip, AnimationClip animClip)
  722. {
  723. if (clip == null || animClip == null)
  724. return;
  725. if (animClip.legacy)
  726. throw new InvalidOperationException("Legacy Animation Clips are not supported");
  727. AnimationPlayableAsset asset = clip.asset as AnimationPlayableAsset;
  728. if (asset != null)
  729. {
  730. asset.clip = animClip;
  731. asset.name = animClip.name;
  732. var duration = asset.duration;
  733. if (!double.IsInfinity(duration) && duration >= TimelineClip.kMinDuration && duration < TimelineClip.kMaxTimeValue)
  734. clip.duration = duration;
  735. }
  736. clip.displayName = animClip.name;
  737. }
  738. /// <summary>
  739. /// Called by the Timeline Editor to gather properties requiring preview.
  740. /// </summary>
  741. /// <param name="director">The PlayableDirector invoking the preview</param>
  742. /// <param name="driver">PropertyCollector used to gather previewable properties</param>
  743. public override void GatherProperties(PlayableDirector director, IPropertyCollector driver)
  744. {
  745. #if UNITY_EDITOR
  746. m_SceneOffsetPosition = Vector3.zero;
  747. m_SceneOffsetRotation = Vector3.zero;
  748. var animator = GetBinding(director);
  749. if (animator == null)
  750. return;
  751. var animClips = new List<AnimationClip>(this.clips.Length + 2);
  752. GetAnimationClips(animClips);
  753. var hasHumanMotion = animClips.Exists(clip => clip.humanMotion);
  754. m_SceneOffsetPosition = animator.transform.localPosition;
  755. m_SceneOffsetRotation = animator.transform.localEulerAngles;
  756. // Create default pose clip from collected properties
  757. if (hasHumanMotion)
  758. animClips.Add(GetDefaultHumanoidClip());
  759. var bindings = AnimationPreviewUtilities.GetBindings(animator.gameObject, animClips);
  760. m_CachedPropertiesClip = AnimationPreviewUtilities.CreateDefaultClip(animator.gameObject, bindings);
  761. AnimationPreviewUtilities.PreviewFromCurves(animator.gameObject, bindings); // faster to preview from curves then an animation clip
  762. m_DefaultPoseClip = hasHumanMotion ? GetDefaultHumanoidClip() : null;
  763. #endif
  764. }
  765. /// <summary>
  766. /// Gather all the animation clips for this track
  767. /// </summary>
  768. /// <param name="animClips"></param>
  769. private void GetAnimationClips(List<AnimationClip> animClips)
  770. {
  771. foreach (var c in clips)
  772. {
  773. var a = c.asset as AnimationPlayableAsset;
  774. if (a != null && a.clip != null)
  775. animClips.Add(a.clip);
  776. }
  777. if (m_InfiniteClip != null)
  778. animClips.Add(m_InfiniteClip);
  779. foreach (var childTrack in GetChildTracks())
  780. {
  781. var animChildTrack = childTrack as AnimationTrack;
  782. if (animChildTrack != null)
  783. animChildTrack.GetAnimationClips(animClips);
  784. }
  785. }
  786. // calculate which offset mode to apply
  787. AppliedOffsetMode GetOffsetMode(GameObject go, bool animatesRootTransform)
  788. {
  789. if (!animatesRootTransform)
  790. return AppliedOffsetMode.NoRootTransform;
  791. if (m_TrackOffset == TrackOffset.ApplyTransformOffsets)
  792. return AppliedOffsetMode.TransformOffset;
  793. if (m_TrackOffset == TrackOffset.ApplySceneOffsets)
  794. return (Application.isPlaying) ? AppliedOffsetMode.SceneOffset : AppliedOffsetMode.SceneOffsetEditor;
  795. if (HasController(go))
  796. {
  797. if (!Application.isPlaying)
  798. return AppliedOffsetMode.SceneOffsetLegacyEditor;
  799. return AppliedOffsetMode.SceneOffsetLegacy;
  800. }
  801. return AppliedOffsetMode.TransformOffsetLegacy;
  802. }
  803. internal bool AnimatesRootTransform()
  804. {
  805. // infinite mode
  806. if (AnimationPlayableAsset.HasRootTransforms(m_InfiniteClip))
  807. return true;
  808. // clip mode
  809. foreach (var c in GetClips())
  810. {
  811. var apa = c.asset as AnimationPlayableAsset;
  812. if (apa != null && apa.hasRootTransforms)
  813. return true;
  814. }
  815. return false;
  816. }
  817. }
  818. }