Няма описание
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. [TimelineHelpURL(typeof(TimelineAsset))]
  12. public partial class TimelineAsset : PlayableAsset, ISerializationCallbackReceiver, ITimelineClipAsset, IPropertyPreview
  13. {
  14. /// <summary>
  15. /// How the duration of the timeline is determined.
  16. /// </summary>
  17. public enum DurationMode
  18. {
  19. /// <summary>
  20. /// The duration of the timeline is determined based on the clips present.
  21. /// </summary>
  22. BasedOnClips,
  23. /// <summary>
  24. /// The duration of the timeline is a fixed length.
  25. /// </summary>
  26. FixedLength
  27. }
  28. /// <summary>
  29. /// Properties of the timeline that are used by the editor
  30. /// </summary>
  31. [Serializable]
  32. public class EditorSettings
  33. {
  34. internal static readonly double kMinFrameRate = TimeUtility.kFrameRateEpsilon;
  35. internal static readonly double kMaxFrameRate = 1000.0;
  36. internal static readonly double kDefaultFrameRate = 60.0;
  37. [HideInInspector, SerializeField, FrameRateField] double m_Framerate = kDefaultFrameRate;
  38. [HideInInspector, SerializeField] bool m_ScenePreview = true;
  39. /// <summary>
  40. /// The frames per second used for snapping and time ruler display
  41. /// </summary>
  42. [Obsolete("EditorSettings.fps has been deprecated. Use editorSettings.frameRate instead.", false)]
  43. public float fps
  44. {
  45. get
  46. {
  47. return (float)m_Framerate;
  48. }
  49. set
  50. {
  51. m_Framerate = Mathf.Clamp(value, (float)kMinFrameRate, (float)kMaxFrameRate);
  52. }
  53. }
  54. /// <summary>
  55. /// The frames per second used for framelocked preview, frame snapping and time ruler display,
  56. /// </summary>
  57. /// <remarks>
  58. /// If frameRate is set to a non-standard custom frame rate, Timeline playback
  59. /// may give incorrect results when playbackLockedToFrame is true.
  60. /// </remarks>
  61. /// <seealso cref="UnityEngine.Timeline.TimelineAsset"/>
  62. public double frameRate
  63. {
  64. get { return m_Framerate; }
  65. set { m_Framerate = GetValidFrameRate(value); }
  66. }
  67. /// <summary>
  68. /// Sets the EditorSetting frameRate to one of the provided standard frame rates.
  69. /// </summary>
  70. /// <param name="enumValue"> StandardFrameRates value, used to set the current EditorSettings frameRate value.</param>
  71. /// <remarks>
  72. /// When specifying drop frame values, it is recommended to select one of the provided standard frame rates.
  73. /// Specifying a non-standard custom frame rate may give incorrect results when playbackLockedToFrame
  74. /// is enabled during Timeline playback.
  75. /// </remarks>
  76. /// <exception cref="ArgumentException">Thrown when the enumValue is not a valid member of StandardFrameRates.</exception>
  77. /// <seealso cref="UnityEngine.Timeline.TimelineAsset"/>
  78. public void SetStandardFrameRate(StandardFrameRates enumValue)
  79. {
  80. FrameRate rate = TimeUtility.ToFrameRate(enumValue);
  81. if (rate.IsValid())
  82. throw new ArgumentException(String.Format("StandardFrameRates {0}, is not defined",
  83. enumValue.ToString()));
  84. m_Framerate = rate.rate;
  85. }
  86. /// <summary>
  87. /// Set to false to ignore scene preview when this timeline is played by the Timeline window.
  88. /// </summary>
  89. /// <remarks>
  90. /// When set to false, this setting will
  91. /// - Disable scene preview when this timeline is played by the Timeline window.
  92. /// - Disable recording for all recordable tracks.
  93. /// - Disable play range in the Timeline window.
  94. /// - `Stop()` is not called on the `PlayableDirector` when switching between different `TimelineAsset`s in the TimelineWindow.
  95. ///
  96. /// `scenePreview` will only be applied if the asset is the master timeline.
  97. /// </remarks>
  98. /// <seealso cref="UnityEngine.Timeline.TimelineAsset"/>
  99. public bool scenePreview
  100. {
  101. get => m_ScenePreview;
  102. set => m_ScenePreview = value;
  103. }
  104. }
  105. [HideInInspector, SerializeField] List<ScriptableObject> m_Tracks;
  106. [HideInInspector, SerializeField] double m_FixedDuration; // only applied if duration mode is Fixed
  107. [HideInInspector, NonSerialized] TrackAsset[] m_CacheOutputTracks;
  108. [HideInInspector, NonSerialized] List<TrackAsset> m_CacheRootTracks;
  109. [HideInInspector, NonSerialized] TrackAsset[] m_CacheFlattenedTracks;
  110. [HideInInspector, SerializeField] EditorSettings m_EditorSettings = new EditorSettings();
  111. [SerializeField] DurationMode m_DurationMode;
  112. [HideInInspector, SerializeField] MarkerTrack m_MarkerTrack;
  113. /// <summary>
  114. /// Settings used by timeline for editing purposes
  115. /// </summary>
  116. public EditorSettings editorSettings
  117. {
  118. get { return m_EditorSettings; }
  119. }
  120. /// <summary>
  121. /// The length, in seconds, of the timeline
  122. /// </summary>
  123. public override double duration
  124. {
  125. get
  126. {
  127. // @todo cache this value when rebuilt
  128. if (m_DurationMode == DurationMode.BasedOnClips)
  129. {
  130. //avoid having no clip evaluated at the end by removing a tick from the total duration
  131. var discreteDuration = CalculateItemsDuration();
  132. if (discreteDuration <= 0)
  133. return 0.0;
  134. return (double)discreteDuration.OneTickBefore();
  135. }
  136. return m_FixedDuration;
  137. }
  138. }
  139. /// <summary>
  140. /// The length of the timeline when durationMode is set to fixed length.
  141. /// </summary>
  142. public double fixedDuration
  143. {
  144. get
  145. {
  146. DiscreteTime discreteDuration = (DiscreteTime)m_FixedDuration;
  147. if (discreteDuration <= 0)
  148. return 0.0;
  149. //avoid having no clip evaluated at the end by removing a tick from the total duration
  150. return (double)discreteDuration.OneTickBefore();
  151. }
  152. set { m_FixedDuration = Math.Max(0.0, value); }
  153. }
  154. /// <summary>
  155. /// The mode used to determine the duration of the Timeline
  156. /// </summary>
  157. public DurationMode durationMode
  158. {
  159. get { return m_DurationMode; }
  160. set { m_DurationMode = value; }
  161. }
  162. /// <summary>
  163. /// A description of the PlayableOutputs that will be created by the timeline when instantiated.
  164. /// </summary>
  165. /// <remarks>
  166. /// Each track will create an PlayableOutput
  167. /// </remarks>
  168. public override IEnumerable<PlayableBinding> outputs
  169. {
  170. get
  171. {
  172. foreach (var outputTracks in GetOutputTracks())
  173. foreach (var output in outputTracks.outputs)
  174. yield return output;
  175. }
  176. }
  177. /// <summary>
  178. /// The capabilities supported by all clips in the timeline.
  179. /// </summary>
  180. public ClipCaps clipCaps
  181. {
  182. get
  183. {
  184. var caps = ClipCaps.All;
  185. foreach (var track in GetRootTracks())
  186. {
  187. foreach (var clip in track.clips)
  188. caps &= clip.clipCaps;
  189. }
  190. return caps;
  191. }
  192. }
  193. /// <summary>
  194. /// Returns the the number of output tracks in the Timeline.
  195. /// </summary>
  196. /// <remarks>
  197. /// 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.
  198. /// </remarks>
  199. public int outputTrackCount
  200. {
  201. get
  202. {
  203. UpdateOutputTrackCache(); // updates the cache if necessary
  204. return m_CacheOutputTracks.Length;
  205. }
  206. }
  207. /// <summary>
  208. /// Returns the number of tracks at the root level of the timeline.
  209. /// </summary>
  210. /// <remarks>
  211. /// 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
  212. /// </remarks>
  213. public int rootTrackCount
  214. {
  215. get
  216. {
  217. UpdateRootTrackCache();
  218. return m_CacheRootTracks.Count;
  219. }
  220. }
  221. void OnValidate()
  222. {
  223. editorSettings.frameRate = GetValidFrameRate(editorSettings.frameRate);
  224. }
  225. /// <summary>
  226. /// Retrieves at root track at the specified index.
  227. /// </summary>
  228. /// <param name="index">Index of the root track to get. Must be between 0 and rootTrackCount</param>
  229. /// <remarks>
  230. /// 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.
  231. /// </remarks>
  232. /// <returns>Root track at the specified index.</returns>
  233. public TrackAsset GetRootTrack(int index)
  234. {
  235. UpdateRootTrackCache();
  236. return m_CacheRootTracks[index];
  237. }
  238. /// <summary>
  239. /// Get an enumerable list of all root tracks.
  240. /// </summary>
  241. /// <returns>An IEnumerable of all root tracks.</returns>
  242. /// <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>
  243. public IEnumerable<TrackAsset> GetRootTracks()
  244. {
  245. UpdateRootTrackCache();
  246. return m_CacheRootTracks;
  247. }
  248. /// <summary>
  249. /// Retrives the output track from the given index.
  250. /// </summary>
  251. /// <param name="index">Index of the output track to retrieve. Must be between 0 and outputTrackCount</param>
  252. /// <returns>The output track from the given index</returns>
  253. public TrackAsset GetOutputTrack(int index)
  254. {
  255. UpdateOutputTrackCache();
  256. return m_CacheOutputTracks[index];
  257. }
  258. /// <summary>
  259. /// Gets a list of all output tracks in the Timeline.
  260. /// </summary>
  261. /// <returns>An IEnumerable of all output tracks</returns>
  262. /// <remarks>
  263. /// 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.
  264. /// </remarks>
  265. public IEnumerable<TrackAsset> GetOutputTracks()
  266. {
  267. UpdateOutputTrackCache();
  268. return m_CacheOutputTracks;
  269. }
  270. static double GetValidFrameRate(double frameRate)
  271. {
  272. return Math.Min(Math.Max(frameRate, EditorSettings.kMinFrameRate), EditorSettings.kMaxFrameRate);
  273. }
  274. void UpdateRootTrackCache()
  275. {
  276. if (m_CacheRootTracks == null)
  277. {
  278. if (m_Tracks == null)
  279. m_CacheRootTracks = new List<TrackAsset>();
  280. else
  281. {
  282. m_CacheRootTracks = new List<TrackAsset>(m_Tracks.Count);
  283. if (markerTrack != null)
  284. {
  285. m_CacheRootTracks.Add(markerTrack);
  286. }
  287. foreach (var t in m_Tracks)
  288. {
  289. var trackAsset = t as TrackAsset;
  290. if (trackAsset != null)
  291. m_CacheRootTracks.Add(trackAsset);
  292. }
  293. }
  294. }
  295. }
  296. void UpdateOutputTrackCache()
  297. {
  298. if (m_CacheOutputTracks == null)
  299. {
  300. var outputTracks = new List<TrackAsset>();
  301. foreach (var flattenedTrack in flattenedTracks)
  302. {
  303. if (flattenedTrack != null && flattenedTrack.GetType() != typeof(GroupTrack) && !flattenedTrack.isSubTrack)
  304. outputTracks.Add(flattenedTrack);
  305. }
  306. m_CacheOutputTracks = outputTracks.ToArray();
  307. }
  308. }
  309. internal TrackAsset[] flattenedTracks
  310. {
  311. get
  312. {
  313. if (m_CacheFlattenedTracks == null)
  314. {
  315. var list = new List<TrackAsset>(m_Tracks.Count * 2);
  316. UpdateRootTrackCache();
  317. list.AddRange(m_CacheRootTracks);
  318. for (int i = 0; i < m_CacheRootTracks.Count; i++)
  319. {
  320. AddSubTracksRecursive(m_CacheRootTracks[i], ref list);
  321. }
  322. m_CacheFlattenedTracks = list.ToArray();
  323. }
  324. return m_CacheFlattenedTracks;
  325. }
  326. }
  327. /// <summary>
  328. /// Gets the marker track for this TimelineAsset.
  329. /// </summary>
  330. /// <returns>Returns the marker track.</returns>
  331. /// <remarks>
  332. /// Use <see cref="TrackAsset.GetMarkers"/> to get a list of the markers on the returned track.
  333. /// </remarks>
  334. public MarkerTrack markerTrack
  335. {
  336. get { return m_MarkerTrack; }
  337. }
  338. // access to the track list as scriptable object
  339. internal List<ScriptableObject> trackObjects
  340. {
  341. get { return m_Tracks; }
  342. }
  343. internal void AddTrackInternal(TrackAsset track)
  344. {
  345. m_Tracks.Add(track);
  346. track.parent = this;
  347. Invalidate();
  348. }
  349. internal void RemoveTrack(TrackAsset track)
  350. {
  351. m_Tracks.Remove(track);
  352. Invalidate();
  353. var parentTrack = track.parent as TrackAsset;
  354. if (parentTrack != null)
  355. {
  356. parentTrack.RemoveSubTrack(track);
  357. }
  358. }
  359. /// <summary>
  360. /// Creates an instance of the timeline
  361. /// </summary>
  362. /// <param name="graph">PlayableGraph that will own the playable</param>
  363. /// <param name="go">The gameobject that triggered the graph build</param>
  364. /// <returns>The Root Playable of the Timeline</returns>
  365. public override Playable CreatePlayable(PlayableGraph graph, GameObject go)
  366. {
  367. bool autoRebalanceTree = false;
  368. #if UNITY_EDITOR
  369. autoRebalanceTree = true;
  370. #endif
  371. // only create outputs if we are not nested
  372. bool createOutputs = graph.GetPlayableCount() == 0;
  373. var timeline = TimelinePlayable.Create(graph, GetOutputTracks(), go, autoRebalanceTree, createOutputs);
  374. timeline.SetDuration(this.duration);
  375. timeline.SetPropagateSetTime(true);
  376. return timeline.IsValid() ? timeline : Playable.Null;
  377. }
  378. /// <summary>
  379. /// Called before Unity serializes this object.
  380. /// </summary>
  381. void ISerializationCallbackReceiver.OnBeforeSerialize()
  382. {
  383. m_Version = k_LatestVersion;
  384. }
  385. /// <summary>
  386. /// Called after Unity deserializes this object.
  387. /// </summary>
  388. void ISerializationCallbackReceiver.OnAfterDeserialize()
  389. {
  390. // resets cache on an Undo
  391. Invalidate(); // resets cache on an Undo
  392. if (m_Version < k_LatestVersion)
  393. {
  394. UpgradeToLatestVersion();
  395. }
  396. }
  397. #if UNITY_EDITOR
  398. internal event Action AssetModifiedOnDisk;
  399. #endif
  400. void __internalAwake()
  401. {
  402. if (m_Tracks == null)
  403. m_Tracks = new List<ScriptableObject>();
  404. #if UNITY_EDITOR
  405. // case 1280331 -- embedding the timeline asset inside a prefab will create a temporary non-persistent version of an asset
  406. // setting the track parents to this will change persistent tracks
  407. if (!UnityEditor.EditorUtility.IsPersistent(this))
  408. return;
  409. #endif
  410. // validate the array. DON'T remove Unity null objects, just actual null objects
  411. for (int i = m_Tracks.Count - 1; i >= 0; i--)
  412. {
  413. TrackAsset asset = m_Tracks[i] as TrackAsset;
  414. if (asset != null)
  415. asset.parent = this;
  416. #if UNITY_EDITOR
  417. object o = m_Tracks[i];
  418. if (o == null)
  419. {
  420. Debug.LogWarning("Empty track found while loading timeline. It will be removed.");
  421. m_Tracks.RemoveAt(i);
  422. }
  423. #endif
  424. }
  425. #if UNITY_EDITOR
  426. AssetModifiedOnDisk?.Invoke();
  427. #endif
  428. }
  429. /// <summary>
  430. /// Called by the Timeline Editor to gather properties requiring preview.
  431. /// </summary>
  432. /// <param name="director">The PlayableDirector invoking the preview</param>
  433. /// <param name="driver">PropertyCollector used to gather previewable properties</param>
  434. public void GatherProperties(PlayableDirector director, IPropertyCollector driver)
  435. {
  436. var outputTracks = GetOutputTracks();
  437. foreach (var track in outputTracks)
  438. {
  439. if (!track.mutedInHierarchy)
  440. track.GatherProperties(director, driver);
  441. }
  442. }
  443. /// <summary>
  444. /// Creates a marker track for the TimelineAsset.
  445. /// </summary>
  446. /// In the editor, the marker track appears under the Timeline ruler.
  447. /// <remarks>
  448. /// This track is always bound to the GameObject that contains the PlayableDirector component for the current timeline.
  449. /// The marker track is created the first time this method is called. If the marker track is already created, this method does nothing.
  450. /// </remarks>
  451. public void CreateMarkerTrack()
  452. {
  453. if (m_MarkerTrack == null)
  454. {
  455. m_MarkerTrack = CreateInstance<MarkerTrack>();
  456. TimelineCreateUtilities.SaveAssetIntoObject(m_MarkerTrack, this);
  457. m_MarkerTrack.parent = this;
  458. m_MarkerTrack.name = "Markers"; // This name will show up in the bindings list if it contains signals
  459. Invalidate();
  460. }
  461. }
  462. internal void RemoveMarkerTrack()
  463. {
  464. if (m_MarkerTrack != null)
  465. {
  466. MarkerTrack markerTrack = m_MarkerTrack;
  467. m_MarkerTrack = null;
  468. TimelineCreateUtilities.RemoveAssetFromObject(markerTrack, this);
  469. Invalidate();
  470. }
  471. }
  472. // Invalidates the asset, call this if changing the asset data
  473. internal void Invalidate()
  474. {
  475. m_CacheRootTracks = null;
  476. m_CacheOutputTracks = null;
  477. m_CacheFlattenedTracks = null;
  478. }
  479. internal void UpdateFixedDurationWithItemsDuration()
  480. {
  481. m_FixedDuration = (double)CalculateItemsDuration();
  482. }
  483. DiscreteTime CalculateItemsDuration()
  484. {
  485. var discreteDuration = new DiscreteTime(0);
  486. foreach (var track in flattenedTracks)
  487. {
  488. if (track.muted)
  489. continue;
  490. discreteDuration = DiscreteTime.Max(discreteDuration, (DiscreteTime)track.end);
  491. }
  492. if (discreteDuration <= 0)
  493. return new DiscreteTime(0);
  494. return discreteDuration;
  495. }
  496. static void AddSubTracksRecursive(TrackAsset track, ref List<TrackAsset> allTracks)
  497. {
  498. if (track == null)
  499. return;
  500. allTracks.AddRange(track.GetChildTracks());
  501. foreach (TrackAsset subTrack in track.GetChildTracks())
  502. {
  503. AddSubTracksRecursive(subTrack, ref allTracks);
  504. }
  505. }
  506. }
  507. }