TimelineAsset.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.Playables;
  4. namespace UnityEngine.Timeline
  5. {
  6. /// <summary>
  7. /// A PlayableAsset that represents a timeline.
  8. /// </summary>
  9. [ExcludeFromPreset]
  10. [Serializable]
  11. public partial class TimelineAsset : PlayableAsset, ISerializationCallbackReceiver, ITimelineClipAsset, IPropertyPreview
  12. {
  13. /// <summary>
  14. /// How the duration of the timeline is determined.
  15. /// </summary>
  16. public enum DurationMode
  17. {
  18. /// <summary>
  19. /// The duration of the timeline is determined based on the clips present.
  20. /// </summary>
  21. BasedOnClips,
  22. /// <summary>
  23. /// The duration of the timeline is a fixed length.
  24. /// </summary>
  25. FixedLength
  26. }
  27. /// <summary>
  28. /// Properties of the timeline that are used by the editor
  29. /// </summary>
  30. [Serializable]
  31. public class EditorSettings
  32. {
  33. internal static readonly float kMinFps = (float)TimeUtility.kFrameRateEpsilon;
  34. internal static readonly float kMaxFps = 1000.0f;
  35. internal static readonly float kDefaultFps = 60.0f;
  36. [HideInInspector, SerializeField] float m_Framerate = kDefaultFps;
  37. /// <summary>
  38. /// The frames per second used for snapping and time ruler display
  39. /// </summary>
  40. public float fps
  41. {
  42. get
  43. {
  44. return m_Framerate;
  45. }
  46. set
  47. {
  48. m_Framerate = GetValidFramerate(value);
  49. }
  50. }
  51. }
  52. [HideInInspector, SerializeField] List<ScriptableObject> m_Tracks;
  53. [HideInInspector, SerializeField] double m_FixedDuration; // only applied if duration mode is Fixed
  54. [HideInInspector, NonSerialized] TrackAsset[] m_CacheOutputTracks;
  55. [HideInInspector, NonSerialized] List<TrackAsset> m_CacheRootTracks;
  56. [HideInInspector, NonSerialized] List<TrackAsset> m_CacheFlattenedTracks;
  57. [HideInInspector, SerializeField] EditorSettings m_EditorSettings = new EditorSettings();
  58. [SerializeField] DurationMode m_DurationMode;
  59. [HideInInspector, SerializeField] MarkerTrack m_MarkerTrack;
  60. /// <summary>
  61. /// Settings used by timeline for editing purposes
  62. /// </summary>
  63. public EditorSettings editorSettings
  64. {
  65. get { return m_EditorSettings; }
  66. }
  67. /// <summary>
  68. /// The length, in seconds, of the timeline
  69. /// </summary>
  70. public override double duration
  71. {
  72. get
  73. {
  74. // @todo cache this value when rebuilt
  75. if (m_DurationMode == DurationMode.BasedOnClips)
  76. return CalculateDuration();
  77. return m_FixedDuration;
  78. }
  79. }
  80. /// <summary>
  81. /// The length of the timeline when durationMode is set to fixed length.
  82. /// </summary>
  83. public double fixedDuration
  84. {
  85. get
  86. {
  87. DiscreteTime discreteDuration = (DiscreteTime)m_FixedDuration;
  88. if (discreteDuration <= 0)
  89. return 0.0;
  90. //avoid having no clip evaluated at the end by removing a tick from the total duration
  91. return (double)discreteDuration.OneTickBefore();
  92. }
  93. set { m_FixedDuration = Math.Max(0.0, value); }
  94. }
  95. /// <summary>
  96. /// The mode used to determine the duration of the Timeline
  97. /// </summary>
  98. public DurationMode durationMode
  99. {
  100. get { return m_DurationMode; }
  101. set { m_DurationMode = value; }
  102. }
  103. /// <summary>
  104. /// A description of the PlayableOutputs that will be created by the timeline when instantiated.
  105. /// </summary>
  106. /// <remarks>
  107. /// Each track will create an PlayableOutput
  108. /// </remarks>
  109. public override IEnumerable<PlayableBinding> outputs
  110. {
  111. get
  112. {
  113. foreach (var outputTracks in GetOutputTracks())
  114. foreach (var output in outputTracks.outputs)
  115. yield return output;
  116. }
  117. }
  118. public ClipCaps clipCaps
  119. {
  120. get
  121. {
  122. var caps = ClipCaps.All;
  123. foreach (var track in GetRootTracks())
  124. {
  125. foreach (var clip in track.clips)
  126. caps &= clip.clipCaps;
  127. }
  128. return caps;
  129. }
  130. }
  131. /// <summary>
  132. /// Returns the the number of output tracks in the Timeline.
  133. /// </summary>
  134. /// <remarks>
  135. /// An output track is a track the generates a PlayableOutput. In general, an output track is any track that is not a GroupTrack, a subtrack, or override track.
  136. /// </remarks>
  137. public int outputTrackCount
  138. {
  139. get
  140. {
  141. UpdateOutputTrackCache(); // updates the cache if necessary
  142. return m_CacheOutputTracks.Length;
  143. }
  144. }
  145. /// <summary>
  146. /// Returns the number of tracks at the root level of the timeline.
  147. /// </summary>
  148. /// <remarks>
  149. /// A root track refers to all tracks that occur at the root of the timeline. These are the outmost level GroupTracks, and output tracks that do not belong to any group
  150. /// </remarks>
  151. public int rootTrackCount
  152. {
  153. get
  154. {
  155. UpdateRootTrackCache();
  156. return m_CacheRootTracks.Count;
  157. }
  158. }
  159. void OnValidate()
  160. {
  161. editorSettings.fps = GetValidFramerate(editorSettings.fps);
  162. }
  163. static float GetValidFramerate(float framerate)
  164. {
  165. return Mathf.Clamp(framerate, EditorSettings.kMinFps, EditorSettings.kMaxFps);
  166. }
  167. /// <summary>
  168. /// Retrieves at root track at the specified index.
  169. /// </summary>
  170. /// <param name="index">Index of the root track to get. Must be between 0 and rootTrackCount</param>
  171. /// <remarks>
  172. /// A root track refers to all tracks that occur at the root of the timeline. These are the outmost level GroupTracks, and output tracks that do not belong to any group.
  173. /// </remarks>
  174. public TrackAsset GetRootTrack(int index)
  175. {
  176. UpdateRootTrackCache();
  177. return m_CacheRootTracks[index];
  178. }
  179. /// <summary>
  180. /// Get an enumerable list of all root tracks.
  181. /// </summary>
  182. /// <returns>An IEnumerable of all root tracks.</returns>
  183. /// <remarks>A root track refers to all tracks that occur at the root of the timeline. These are the outmost level GroupTracks, and output tracks that do not belong to any group.</remarks>
  184. public IEnumerable<TrackAsset> GetRootTracks()
  185. {
  186. UpdateRootTrackCache();
  187. return m_CacheRootTracks;
  188. }
  189. /// <summary>
  190. /// Retrives the output track from the given index.
  191. /// </summary>
  192. /// <param name="index">Index of the output track to retrieve. Must be between 0 and outputTrackCount</param>
  193. /// <returns>The output track from the given index</returns>
  194. public TrackAsset GetOutputTrack(int index)
  195. {
  196. UpdateOutputTrackCache();
  197. return m_CacheOutputTracks[index];
  198. }
  199. /// <summary>
  200. /// Gets a list of all output tracks in the Timeline.
  201. /// </summary>
  202. /// <returns>An IEnumerable of all output tracks</returns>
  203. /// <remarks>
  204. /// An output track is a track the generates a PlayableOutput. In general, an output track is any track that is not a GroupTrack or subtrack.
  205. /// </remarks>
  206. public IEnumerable<TrackAsset> GetOutputTracks()
  207. {
  208. UpdateOutputTrackCache();
  209. return m_CacheOutputTracks;
  210. }
  211. void UpdateRootTrackCache()
  212. {
  213. if (m_CacheRootTracks == null)
  214. {
  215. if (m_Tracks == null)
  216. m_CacheRootTracks = new List<TrackAsset>();
  217. else
  218. {
  219. m_CacheRootTracks = new List<TrackAsset>(m_Tracks.Count);
  220. if (markerTrack != null)
  221. {
  222. m_CacheRootTracks.Add(markerTrack);
  223. }
  224. foreach (var t in m_Tracks)
  225. {
  226. var trackAsset = t as TrackAsset;
  227. if (trackAsset != null)
  228. m_CacheRootTracks.Add(trackAsset);
  229. }
  230. }
  231. }
  232. }
  233. void UpdateOutputTrackCache()
  234. {
  235. if (m_CacheOutputTracks == null)
  236. {
  237. var outputTracks = new List<TrackAsset>();
  238. foreach (var flattenedTrack in flattenedTracks)
  239. {
  240. if (flattenedTrack != null && flattenedTrack.GetType() != typeof(GroupTrack) && !flattenedTrack.isSubTrack)
  241. outputTracks.Add(flattenedTrack);
  242. }
  243. m_CacheOutputTracks = outputTracks.ToArray();
  244. }
  245. }
  246. internal IEnumerable<TrackAsset> flattenedTracks
  247. {
  248. get
  249. {
  250. if (m_CacheFlattenedTracks == null)
  251. {
  252. m_CacheFlattenedTracks = new List<TrackAsset>(m_Tracks.Count * 2);
  253. UpdateRootTrackCache();
  254. m_CacheFlattenedTracks.AddRange(m_CacheRootTracks);
  255. for (int i = 0; i < m_CacheRootTracks.Count; i++)
  256. {
  257. AddSubTracksRecursive(m_CacheRootTracks[i], ref m_CacheFlattenedTracks);
  258. }
  259. }
  260. return m_CacheFlattenedTracks;
  261. }
  262. }
  263. /// <summary>
  264. /// Gets the marker track for this TimelineAsset.
  265. /// </summary>
  266. /// <returns>Returns the marker track.</returns>
  267. /// <remarks>
  268. /// Use <see cref="TrackAsset.GetMarkers"/> to get a list of the markers on the returned track.
  269. /// </remarks>
  270. public MarkerTrack markerTrack
  271. {
  272. get { return m_MarkerTrack; }
  273. }
  274. // access to the track list as scriptable object
  275. internal List<ScriptableObject> trackObjects
  276. {
  277. get { return m_Tracks; }
  278. }
  279. internal void AddTrackInternal(TrackAsset track)
  280. {
  281. m_Tracks.Add(track);
  282. track.parent = this;
  283. Invalidate();
  284. }
  285. internal void RemoveTrack(TrackAsset track)
  286. {
  287. m_Tracks.Remove(track);
  288. Invalidate();
  289. var parentTrack = track.parent as TrackAsset;
  290. if (parentTrack != null)
  291. {
  292. parentTrack.RemoveSubTrack(track);
  293. }
  294. }
  295. /// <summary>
  296. /// Creates an instance of the timeline
  297. /// </summary>
  298. /// <param name="graph">PlayableGraph that will own the playable</param>
  299. /// <param name="go">The gameobject that triggered the graph build</param>
  300. /// <returns>The Root Playable of the Timeline</returns>
  301. public override Playable CreatePlayable(PlayableGraph graph, GameObject go)
  302. {
  303. bool autoRebalanceTree = false;
  304. #if UNITY_EDITOR
  305. autoRebalanceTree = true;
  306. #endif
  307. // only create outputs if we are not nested
  308. bool createOutputs = graph.GetPlayableCount() == 0;
  309. var timeline = TimelinePlayable.Create(graph, GetOutputTracks(), go, autoRebalanceTree, createOutputs);
  310. timeline.SetPropagateSetTime(true);
  311. return timeline.IsValid() ? timeline : Playable.Null;
  312. }
  313. void ISerializationCallbackReceiver.OnBeforeSerialize()
  314. {
  315. m_Version = k_LatestVersion;
  316. }
  317. // resets cache on an Undo
  318. void ISerializationCallbackReceiver.OnAfterDeserialize()
  319. {
  320. Invalidate(); // resets cache on an Undo
  321. if (m_Version < k_LatestVersion)
  322. {
  323. UpgradeToLatestVersion();
  324. }
  325. }
  326. void __internalAwake()
  327. {
  328. if (m_Tracks == null)
  329. m_Tracks = new List<ScriptableObject>();
  330. // validate the array. DON'T remove Unity null objects, just actual null objects
  331. for (int i = m_Tracks.Count - 1; i >= 0; i--)
  332. {
  333. TrackAsset asset = m_Tracks[i] as TrackAsset;
  334. if (asset != null)
  335. asset.parent = this;
  336. #if UNITY_EDITOR
  337. object o = m_Tracks[i];
  338. if (o == null)
  339. {
  340. Debug.LogWarning("Empty track found while loading timeline. It will be removed.");
  341. m_Tracks.RemoveAt(i);
  342. }
  343. #endif
  344. }
  345. }
  346. /// <summary>
  347. /// Called by the Timeline Editor to gather properties requiring preview.
  348. /// </summary>
  349. /// <param name="director">The PlayableDirector invoking the preview</param>
  350. /// <param name="driver">PropertyCollector used to gather previewable properties</param>
  351. public void GatherProperties(PlayableDirector director, IPropertyCollector driver)
  352. {
  353. var outputTracks = GetOutputTracks();
  354. foreach (var track in outputTracks)
  355. {
  356. track.GatherProperties(director, driver);
  357. }
  358. }
  359. /// <summary>
  360. /// Creates a marker track for the TimelineAsset.
  361. /// </summary>
  362. /// In the editor, the marker track appears under the Timeline ruler.
  363. /// <remarks>
  364. /// This track is always bound to the GameObject that contains the PlayableDirector component for the current timeline.
  365. /// The marker track is created the first time this method is called. If the marker track is already created, this method does nothing.
  366. /// </remarks>
  367. public void CreateMarkerTrack()
  368. {
  369. if (m_MarkerTrack == null)
  370. {
  371. m_MarkerTrack = CreateInstance<MarkerTrack>();
  372. TimelineCreateUtilities.SaveAssetIntoObject(m_MarkerTrack, this);
  373. m_MarkerTrack.parent = this;
  374. m_MarkerTrack.name = "Markers"; // This name will show up in the bindings list if it contains signals
  375. Invalidate();
  376. }
  377. }
  378. // Invalidates the asset, call this if changing the asset data
  379. internal void Invalidate()
  380. {
  381. m_CacheRootTracks = null;
  382. m_CacheOutputTracks = null;
  383. m_CacheFlattenedTracks = null;
  384. }
  385. double CalculateDuration()
  386. {
  387. var discreteDuration = new DiscreteTime(0);
  388. foreach (var track in flattenedTracks)
  389. {
  390. if (track.muted)
  391. continue;
  392. discreteDuration = DiscreteTime.Max(discreteDuration, (DiscreteTime)track.end);
  393. }
  394. if (discreteDuration <= 0)
  395. return 0.0;
  396. //avoid having no clip evaluated at the end by removing a tick from the total duration
  397. return (double)discreteDuration.OneTickBefore();
  398. }
  399. static void AddSubTracksRecursive(TrackAsset track, ref List<TrackAsset> allTracks)
  400. {
  401. if (track == null)
  402. return;
  403. allTracks.AddRange(track.GetChildTracks());
  404. foreach (TrackAsset subTrack in track.GetChildTracks())
  405. {
  406. AddSubTracksRecursive(subTrack, ref allTracks);
  407. }
  408. }
  409. }
  410. }