暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TimelinePlayable.cs 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Animations;
  5. using UnityEngine.Audio;
  6. using UnityEngine.Playables;
  7. namespace UnityEngine.Timeline
  8. {
  9. // Generic evaluation callback called after all the clips have been processed
  10. internal interface ITimelineEvaluateCallback
  11. {
  12. void Evaluate();
  13. }
  14. #if UNITY_EDITOR
  15. /// <summary>
  16. /// This Rebalancer class ensures that the interval tree structures stays balance regardless of whether the intervals inside change.
  17. /// </summary>
  18. class IntervalTreeRebalancer
  19. {
  20. private IntervalTree<RuntimeElement> m_Tree;
  21. public IntervalTreeRebalancer(IntervalTree<RuntimeElement> tree)
  22. {
  23. m_Tree = tree;
  24. }
  25. public bool Rebalance()
  26. {
  27. m_Tree.UpdateIntervals();
  28. return m_Tree.dirty;
  29. }
  30. }
  31. #endif
  32. // The TimelinePlayable Playable
  33. // This is the actual runtime playable that gets evaluated as part of a playable graph.
  34. // It "compiles" a list of tracks into an IntervalTree of Runtime clips.
  35. // At each frame, it advances time, then fetches the "intersection: of various time interval
  36. // using the interval tree.
  37. // Finally, on each intersecting clip, it will calculate each clips' local time, as well as
  38. // blend weight and set them accordingly
  39. /// <summary>
  40. /// The root Playable generated by timeline.
  41. /// </summary>
  42. public class TimelinePlayable : PlayableBehaviour
  43. {
  44. private IntervalTree<RuntimeElement> m_IntervalTree = new IntervalTree<RuntimeElement>();
  45. private List<RuntimeElement> m_ActiveClips = new List<RuntimeElement>();
  46. private List<RuntimeElement> m_CurrentListOfActiveClips;
  47. private int m_ActiveBit = 0;
  48. private List<ITimelineEvaluateCallback> m_EvaluateCallbacks = new List<ITimelineEvaluateCallback>();
  49. private Dictionary<TrackAsset, Playable> m_PlayableCache = new Dictionary<TrackAsset, Playable>();
  50. internal static bool muteAudioScrubbing = true;
  51. #if UNITY_EDITOR
  52. private IntervalTreeRebalancer m_Rebalancer;
  53. internal static event Action<Playable> playableLooped;
  54. #endif
  55. /// <summary>
  56. /// Creates an instance of a Timeline
  57. /// </summary>
  58. /// <param name="graph">The playable graph to inject the timeline.</param>
  59. /// <param name="tracks">The list of tracks to compile</param>
  60. /// <param name="go">The GameObject that initiated the compilation</param>
  61. /// <param name="autoRebalance">In the editor, whether the graph should account for the possibility of changing clip times</param>
  62. /// <param name="createOutputs">Whether to create PlayableOutputs in the graph</param>
  63. /// <returns>A subgraph with the playable containing a TimelinePlayable behaviour as the root</returns>
  64. public static ScriptPlayable<TimelinePlayable> Create(PlayableGraph graph, IEnumerable<TrackAsset> tracks, GameObject go, bool autoRebalance, bool createOutputs)
  65. {
  66. if (tracks == null)
  67. throw new ArgumentNullException("Tracks list is null", "tracks");
  68. if (go == null)
  69. throw new ArgumentNullException("GameObject parameter is null", "go");
  70. var playable = ScriptPlayable<TimelinePlayable>.Create(graph);
  71. playable.SetTraversalMode(PlayableTraversalMode.Passthrough);
  72. var sequence = playable.GetBehaviour();
  73. sequence.Compile(graph, playable, tracks, go, autoRebalance, createOutputs);
  74. return playable;
  75. }
  76. /// <summary>
  77. /// Compiles the subgraph of this timeline
  78. /// </summary>
  79. /// <param name="graph">The playable graph to inject the timeline.</param>
  80. /// <param name="timelinePlayable"></param>
  81. /// <param name="tracks">The list of tracks to compile</param>
  82. /// <param name="go">The GameObject that initiated the compilation</param>
  83. /// <param name="autoRebalance">In the editor, whether the graph should account for the possibility of changing clip times</param>
  84. /// <param name="createOutputs">Whether to create PlayableOutputs in the graph</param>
  85. public void Compile(PlayableGraph graph, Playable timelinePlayable, IEnumerable<TrackAsset> tracks, GameObject go, bool autoRebalance, bool createOutputs)
  86. {
  87. if (tracks == null)
  88. throw new ArgumentNullException("Tracks list is null", "tracks");
  89. if (go == null)
  90. throw new ArgumentNullException("GameObject parameter is null", "go");
  91. var outputTrackList = new List<TrackAsset>(tracks);
  92. var maximumNumberOfIntersections = outputTrackList.Count * 2 + outputTrackList.Count; // worse case: 2 overlapping clips per track + each track
  93. m_CurrentListOfActiveClips = new List<RuntimeElement>(maximumNumberOfIntersections);
  94. m_ActiveClips = new List<RuntimeElement>(maximumNumberOfIntersections);
  95. m_EvaluateCallbacks.Clear();
  96. m_PlayableCache.Clear();
  97. CompileTrackList(graph, timelinePlayable, outputTrackList, go, createOutputs);
  98. #if UNITY_EDITOR
  99. if (autoRebalance)
  100. {
  101. m_Rebalancer = new IntervalTreeRebalancer(m_IntervalTree);
  102. }
  103. #endif
  104. }
  105. private void CompileTrackList(PlayableGraph graph, Playable timelinePlayable, IEnumerable<TrackAsset> tracks, GameObject go, bool createOutputs)
  106. {
  107. foreach (var track in tracks)
  108. {
  109. if (!track.IsCompilable())
  110. continue;
  111. if (!m_PlayableCache.ContainsKey(track))
  112. {
  113. track.SortClips();
  114. CreateTrackPlayable(graph, timelinePlayable, track, go, createOutputs);
  115. }
  116. }
  117. }
  118. void CreateTrackOutput(PlayableGraph graph, TrackAsset track, GameObject go, Playable playable, int port)
  119. {
  120. if (track.isSubTrack)
  121. return;
  122. var bindings = track.outputs;
  123. foreach (var binding in bindings)
  124. {
  125. var playableOutput = binding.CreateOutput(graph);
  126. playableOutput.SetReferenceObject(binding.sourceObject);
  127. playableOutput.SetSourcePlayable(playable, port);
  128. playableOutput.SetWeight(1.0f);
  129. // only apply this on our animation track
  130. if (track as AnimationTrack != null)
  131. {
  132. EvaluateWeightsForAnimationPlayableOutput(track, (AnimationPlayableOutput)playableOutput);
  133. #if UNITY_EDITOR
  134. if (!Application.isPlaying)
  135. EvaluateAnimationPreviewUpdateCallback(track, (AnimationPlayableOutput)playableOutput);
  136. #endif
  137. }
  138. if (playableOutput.IsPlayableOutputOfType<AudioPlayableOutput>())
  139. ((AudioPlayableOutput)playableOutput).SetEvaluateOnSeek(!muteAudioScrubbing);
  140. // If the track is the timeline marker track, assume binding is the PlayableDirector
  141. if (track.timelineAsset.markerTrack == track)
  142. {
  143. var director = go.GetComponent<PlayableDirector>();
  144. playableOutput.SetUserData(director);
  145. foreach (var c in go.GetComponents<INotificationReceiver>())
  146. {
  147. playableOutput.AddNotificationReceiver(c);
  148. }
  149. }
  150. }
  151. }
  152. void EvaluateWeightsForAnimationPlayableOutput(TrackAsset track, AnimationPlayableOutput animOutput)
  153. {
  154. m_EvaluateCallbacks.Add(new AnimationOutputWeightProcessor(animOutput));
  155. }
  156. void EvaluateAnimationPreviewUpdateCallback(TrackAsset track, AnimationPlayableOutput animOutput)
  157. {
  158. m_EvaluateCallbacks.Add(new AnimationPreviewUpdateCallback(animOutput));
  159. }
  160. Playable CreateTrackPlayable(PlayableGraph graph, Playable timelinePlayable, TrackAsset track, GameObject go, bool createOutputs)
  161. {
  162. if (!track.IsCompilable()) // where parents are not compilable (group tracks)
  163. return timelinePlayable;
  164. Playable playable;
  165. if (m_PlayableCache.TryGetValue(track, out playable))
  166. return playable;
  167. if (track.name == "root")
  168. return timelinePlayable;
  169. TrackAsset parentActor = track.parent as TrackAsset;
  170. var parentPlayable = parentActor != null ? CreateTrackPlayable(graph, timelinePlayable, parentActor, go, createOutputs) : timelinePlayable;
  171. var actorPlayable = track.CreatePlayableGraph(graph, go, m_IntervalTree, timelinePlayable);
  172. bool connected = false;
  173. if (!actorPlayable.IsValid())
  174. {
  175. // if a track says it's compilable, but returns Playable.Null, that can screw up the whole graph.
  176. throw new InvalidOperationException(track.name + "(" + track.GetType() + ") did not produce a valid playable.");
  177. }
  178. // Special case for animation tracks
  179. if (parentPlayable.IsValid() && actorPlayable.IsValid())
  180. {
  181. int port = parentPlayable.GetInputCount();
  182. parentPlayable.SetInputCount(port + 1);
  183. connected = graph.Connect(actorPlayable, 0, parentPlayable, port);
  184. parentPlayable.SetInputWeight(port, 1.0f);
  185. }
  186. if (createOutputs && connected)
  187. {
  188. CreateTrackOutput(graph, track, go, parentPlayable, parentPlayable.GetInputCount() - 1);
  189. }
  190. CacheTrack(track, actorPlayable, connected ? (parentPlayable.GetInputCount() - 1) : -1, parentPlayable);
  191. return actorPlayable;
  192. }
  193. /// <summary>
  194. /// Overridden to handle synchronizing time on the timeline instance.
  195. /// </summary>
  196. /// <param name="playable">The Playable that owns the current PlayableBehaviour.</param>
  197. /// <param name="info">A FrameData structure that contains information about the current frame context.</param>
  198. public override void PrepareFrame(Playable playable, FrameData info)
  199. {
  200. #if UNITY_EDITOR
  201. if (m_Rebalancer != null)
  202. m_Rebalancer.Rebalance();
  203. // avoids loop creating a time offset during framelocked playback
  204. // if the timeline duration does not fall on a frame boundary.
  205. if (playableLooped != null && info.timeLooped)
  206. playableLooped.Invoke(playable);
  207. #endif
  208. // force seek if we are being evaluated
  209. // or if our time has jumped. This is used to
  210. // resynchronize
  211. Evaluate(playable, info);
  212. }
  213. private void Evaluate(Playable playable, FrameData frameData)
  214. {
  215. if (m_IntervalTree == null)
  216. return;
  217. double localTime = playable.GetTime();
  218. m_ActiveBit = m_ActiveBit == 0 ? 1 : 0;
  219. m_CurrentListOfActiveClips.Clear();
  220. m_IntervalTree.IntersectsWith(DiscreteTime.GetNearestTick(localTime), m_CurrentListOfActiveClips);
  221. foreach (var c in m_CurrentListOfActiveClips)
  222. {
  223. c.intervalBit = m_ActiveBit;
  224. }
  225. // all previously active clips having a different intervalBit flag are not
  226. // in the current intersection, therefore are considered becoming disabled at this frame
  227. var timelineEnd = (double)new DiscreteTime(playable.GetDuration());
  228. foreach (var c in m_ActiveClips)
  229. {
  230. if (c.intervalBit != m_ActiveBit)
  231. c.DisableAt(localTime, timelineEnd, frameData);
  232. }
  233. m_ActiveClips.Clear();
  234. // case 998642 - don't use m_ActiveClips.AddRange, as in 4.6 .Net scripting it causes GC allocs
  235. for (var a = 0; a < m_CurrentListOfActiveClips.Count; a++)
  236. {
  237. m_CurrentListOfActiveClips[a].EvaluateAt(localTime, frameData);
  238. m_ActiveClips.Add(m_CurrentListOfActiveClips[a]);
  239. }
  240. int count = m_EvaluateCallbacks.Count;
  241. for (int i = 0; i < count; i++)
  242. {
  243. m_EvaluateCallbacks[i].Evaluate();
  244. }
  245. }
  246. private void CacheTrack(TrackAsset track, Playable playable, int port, Playable parent)
  247. {
  248. m_PlayableCache[track] = playable;
  249. }
  250. //necessary to build on AOT platforms
  251. static void ForAOTCompilationOnly()
  252. {
  253. new List<IntervalTree<RuntimeElement>.Entry>();
  254. }
  255. }
  256. }