Без опису
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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