AnimationTrack.cs 36 KB

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