TrackExtensions.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.Timeline;
  6. using UnityEngine.Playables;
  7. namespace UnityEditor.Timeline
  8. {
  9. // Editor-only extension methods on track assets
  10. static class TrackExtensions
  11. {
  12. public static readonly double kMinOverlapTime = TimeUtility.kTimeEpsilon * 1000;
  13. public static AnimationClip GetOrCreateClip(this AnimationTrack track)
  14. {
  15. if (track.infiniteClip == null && !track.inClipMode)
  16. track.CreateInfiniteClip(AnimationTrackRecorder.GetUniqueRecordedClipName(track, AnimationTrackRecorder.kRecordClipDefaultName));
  17. return track.infiniteClip;
  18. }
  19. public static TimelineClip CreateClip(this TrackAsset track, double time)
  20. {
  21. var attr = track.GetType().GetCustomAttributes(typeof(TrackClipTypeAttribute), true);
  22. if (attr.Length == 0)
  23. return null;
  24. if (TimelineWindow.instance.state == null)
  25. return null;
  26. if (attr.Length == 1)
  27. {
  28. var clipClass = (TrackClipTypeAttribute)attr[0];
  29. var clip = TimelineHelpers.CreateClipOnTrack(clipClass.inspectedType, track, TimelineWindow.instance.state);
  30. clip.start = time;
  31. return clip;
  32. }
  33. return null;
  34. }
  35. static bool Overlaps(TimelineClip blendOut, TimelineClip blendIn)
  36. {
  37. if (blendIn == blendOut)
  38. return false;
  39. if (Math.Abs(blendIn.start - blendOut.start) < TimeUtility.kTimeEpsilon)
  40. {
  41. return blendIn.duration >= blendOut.duration;
  42. }
  43. return blendIn.start >= blendOut.start && blendIn.start < blendOut.end;
  44. }
  45. public static void ComputeBlendsFromOverlaps(this TrackAsset asset)
  46. {
  47. ComputeBlendsFromOverlaps(asset.clips);
  48. }
  49. internal static void ComputeBlendsFromOverlaps(TimelineClip[] clips)
  50. {
  51. foreach (var clip in clips)
  52. {
  53. clip.blendInDuration = -1;
  54. clip.blendOutDuration = -1;
  55. }
  56. foreach (var clip in clips)
  57. {
  58. var blendIn = clip;
  59. var blendOut = clips
  60. .Where(c => Overlaps(c, blendIn))
  61. .OrderBy(c => c.start)
  62. .FirstOrDefault();
  63. if (blendOut != null)
  64. {
  65. UpdateClipIntersection(blendOut, blendIn);
  66. }
  67. }
  68. }
  69. internal static void UpdateClipIntersection(TimelineClip blendOutClip, TimelineClip blendInClip)
  70. {
  71. if (!blendOutClip.SupportsBlending() || !blendInClip.SupportsBlending())
  72. return;
  73. if (blendInClip.end < blendOutClip.end)
  74. return;
  75. double duration = Math.Max(0, blendOutClip.start + blendOutClip.duration - blendInClip.start);
  76. duration = duration <= kMinOverlapTime ? 0 : duration;
  77. blendOutClip.blendOutDuration = duration;
  78. blendInClip.blendInDuration = duration;
  79. var blendInMode = blendInClip.blendInCurveMode;
  80. var blendOutMode = blendOutClip.blendOutCurveMode;
  81. if (blendInMode == TimelineClip.BlendCurveMode.Manual && blendOutMode == TimelineClip.BlendCurveMode.Auto)
  82. {
  83. blendOutClip.mixOutCurve = CurveEditUtility.CreateMatchingCurve(blendInClip.mixInCurve);
  84. }
  85. else if (blendInMode == TimelineClip.BlendCurveMode.Auto && blendOutMode == TimelineClip.BlendCurveMode.Manual)
  86. {
  87. blendInClip.mixInCurve = CurveEditUtility.CreateMatchingCurve(blendOutClip.mixOutCurve);
  88. }
  89. else if (blendInMode == TimelineClip.BlendCurveMode.Auto && blendOutMode == TimelineClip.BlendCurveMode.Auto)
  90. {
  91. blendInClip.mixInCurve = null; // resets to default curves
  92. blendOutClip.mixOutCurve = null;
  93. }
  94. }
  95. internal static void RecursiveSubtrackClone(TrackAsset source, TrackAsset duplicate, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, PlayableAsset assetOwner)
  96. {
  97. var subtracks = source.GetChildTracks();
  98. foreach (var sub in subtracks)
  99. {
  100. var newSub = TimelineHelpers.Clone(duplicate, sub, sourceTable, destTable, assetOwner);
  101. duplicate.AddChild(newSub);
  102. RecursiveSubtrackClone(sub, newSub, sourceTable, destTable, assetOwner);
  103. // Call the custom editor on Create
  104. var customEditor = CustomTimelineEditorCache.GetTrackEditor(newSub);
  105. try
  106. {
  107. customEditor.OnCreate(newSub, sub);
  108. }
  109. catch (Exception e)
  110. {
  111. Debug.LogException(e);
  112. }
  113. // registration has to happen AFTER recursion
  114. TimelineCreateUtilities.SaveAssetIntoObject(newSub, assetOwner);
  115. TimelineUndo.RegisterCreatedObjectUndo(newSub, "Duplicate");
  116. }
  117. }
  118. internal static TrackAsset Duplicate(this TrackAsset track, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable,
  119. TimelineAsset destinationTimeline = null)
  120. {
  121. if (track == null)
  122. return null;
  123. // if the destination is us, clear to avoid bad parenting (case 919421)
  124. if (destinationTimeline == track.timelineAsset)
  125. destinationTimeline = null;
  126. var timelineParent = track.parent as TimelineAsset;
  127. var trackParent = track.parent as TrackAsset;
  128. if (timelineParent == null && trackParent == null)
  129. {
  130. Debug.LogWarning("Cannot duplicate track because it is not parented to known type");
  131. return null;
  132. }
  133. // Determine who the final parent is. If we are pasting into another track, it's always the timeline.
  134. // Otherwise it's the original parent
  135. PlayableAsset finalParent = destinationTimeline != null ? destinationTimeline : track.parent;
  136. // grab the list of tracks to generate a name from (923360) to get the list of names
  137. // no need to do this part recursively
  138. var finalTrackParent = finalParent as TrackAsset;
  139. var finalTimelineAsset = finalParent as TimelineAsset;
  140. var otherTracks = (finalTimelineAsset != null) ? finalTimelineAsset.trackObjects : finalTrackParent.subTracksObjects;
  141. // Important to create the new objects before pushing the original undo, or redo breaks the
  142. // sequence
  143. var newTrack = TimelineHelpers.Clone(finalParent, track, sourceTable, destTable, finalParent);
  144. newTrack.name = TimelineCreateUtilities.GenerateUniqueActorName(otherTracks, newTrack.name);
  145. RecursiveSubtrackClone(track, newTrack, sourceTable, destTable, finalParent);
  146. TimelineCreateUtilities.SaveAssetIntoObject(newTrack, finalParent);
  147. TimelineUndo.RegisterCreatedObjectUndo(newTrack, "Duplicate");
  148. TimelineUndo.PushUndo(finalParent, "Duplicate");
  149. if (destinationTimeline != null) // other timeline
  150. destinationTimeline.AddTrackInternal(newTrack);
  151. else if (timelineParent != null) // this timeline, no parent
  152. ReparentTracks(new List<TrackAsset> { newTrack }, timelineParent, timelineParent.GetRootTracks().Last(), false);
  153. else // this timeline, with parent
  154. trackParent.AddChild(newTrack);
  155. // Call the custom editor. this check prevents the call when copying to the clipboard
  156. if (destinationTimeline == null || destinationTimeline == TimelineEditor.inspectedAsset)
  157. {
  158. var customEditor = CustomTimelineEditorCache.GetTrackEditor(newTrack);
  159. try
  160. {
  161. customEditor.OnCreate(newTrack, track);
  162. }
  163. catch (Exception e)
  164. {
  165. Debug.LogException(e);
  166. }
  167. }
  168. return newTrack;
  169. }
  170. // Reparents a list of tracks to a new parent
  171. // the new parent cannot be null (has to be track asset or sequence)
  172. // the insertAfter can be null (will not reorder)
  173. internal static bool ReparentTracks(List<TrackAsset> tracksToMove, PlayableAsset targetParent,
  174. TrackAsset insertMarker = null, bool insertBefore = false)
  175. {
  176. var targetParentTrack = targetParent as TrackAsset;
  177. var targetSequenceTrack = targetParent as TimelineAsset;
  178. if (tracksToMove == null || tracksToMove.Count == 0 || (targetParentTrack == null && targetSequenceTrack == null))
  179. return false;
  180. // invalid parent type on a track
  181. if (targetParentTrack != null && tracksToMove.Any(x => !TimelineCreateUtilities.ValidateParentTrack(targetParentTrack, x.GetType())))
  182. return false;
  183. // no valid tracks means this is simply a rearrangement
  184. var validTracks = tracksToMove.Where(x => x.parent != targetParent).ToList();
  185. if (insertMarker == null && !validTracks.Any())
  186. return false;
  187. var parents = validTracks.Select(x => x.parent).Where(x => x != null).Distinct().ToList();
  188. // push the current state of the tracks that will change
  189. foreach (var p in parents)
  190. {
  191. TimelineUndo.PushUndo(p, "Reparent");
  192. }
  193. foreach (var t in validTracks)
  194. {
  195. TimelineUndo.PushUndo(t, "Reparent");
  196. }
  197. TimelineUndo.PushUndo(targetParent, "Reparent");
  198. // need to reparent tracks first, before moving them.
  199. foreach (var t in validTracks)
  200. {
  201. if (t.parent != targetParent)
  202. {
  203. TrackAsset toMoveParent = t.parent as TrackAsset;
  204. TimelineAsset toMoveTimeline = t.parent as TimelineAsset;
  205. if (toMoveTimeline != null)
  206. {
  207. toMoveTimeline.RemoveTrack(t);
  208. }
  209. else if (toMoveParent != null)
  210. {
  211. toMoveParent.RemoveSubTrack(t);
  212. }
  213. if (targetParentTrack != null)
  214. {
  215. targetParentTrack.AddChild(t);
  216. targetParentTrack.SetCollapsed(false);
  217. }
  218. else
  219. {
  220. targetSequenceTrack.AddTrackInternal(t);
  221. }
  222. }
  223. }
  224. if (insertMarker != null)
  225. {
  226. // re-ordering track. This is using internal APIs, so invalidation of the tracks must be done manually to avoid
  227. // cache mismatches
  228. var children = targetParentTrack != null ? targetParentTrack.subTracksObjects : targetSequenceTrack.trackObjects;
  229. TimelineUtility.ReorderTracks(children, tracksToMove, insertMarker, insertBefore);
  230. if (targetParentTrack != null)
  231. targetParentTrack.Invalidate();
  232. if (insertMarker.timelineAsset != null)
  233. insertMarker.timelineAsset.Invalidate();
  234. }
  235. return true;
  236. }
  237. internal static IEnumerable<TrackAsset> FilterTracks(IEnumerable<TrackAsset> tracks)
  238. {
  239. var nTracks = tracks.Count();
  240. // Duplicate is recursive. If should not have parent and child in the list
  241. var hash = new HashSet<TrackAsset>(tracks);
  242. var take = new Dictionary<TrackAsset, bool>(nTracks);
  243. foreach (var track in tracks)
  244. {
  245. var parent = track.parent as TrackAsset;
  246. var foundParent = false;
  247. // go up the hierarchy
  248. while (parent != null && !foundParent)
  249. {
  250. if (hash.Contains(parent))
  251. {
  252. foundParent = true;
  253. }
  254. parent = parent.parent as TrackAsset;
  255. }
  256. take[track] = !foundParent;
  257. }
  258. foreach (var track in tracks)
  259. {
  260. if (take[track])
  261. yield return track;
  262. }
  263. }
  264. internal static bool IsVisibleRecursive(this TrackAsset track)
  265. {
  266. var t = track;
  267. while ((t = t.parent as TrackAsset) != null)
  268. {
  269. if (t.GetCollapsed())
  270. return false;
  271. }
  272. return true;
  273. }
  274. internal static bool GetCollapsed(this TrackAsset track)
  275. {
  276. return TimelineWindowViewPrefs.IsTrackCollapsed(track);
  277. }
  278. internal static void SetCollapsed(this TrackAsset track, bool collapsed)
  279. {
  280. TimelineWindowViewPrefs.SetTrackCollapsed(track, collapsed);
  281. }
  282. internal static bool GetShowMarkers(this TrackAsset track)
  283. {
  284. return TimelineWindowViewPrefs.IsShowMarkers(track);
  285. }
  286. internal static void SetShowMarkers(this TrackAsset track, bool collapsed)
  287. {
  288. TimelineWindowViewPrefs.SetTrackShowMarkers(track, collapsed);
  289. }
  290. internal static bool GetShowInlineCurves(this TrackAsset track)
  291. {
  292. return TimelineWindowViewPrefs.GetShowInlineCurves(track);
  293. }
  294. internal static void SetShowInlineCurves(this TrackAsset track, bool inlineOn)
  295. {
  296. TimelineWindowViewPrefs.SetShowInlineCurves(track, inlineOn);
  297. }
  298. internal static bool ShouldShowInfiniteClipEditor(this TrackAsset track)
  299. {
  300. var animationTrack = track as AnimationTrack;
  301. if (animationTrack != null)
  302. return animationTrack.ShouldShowInfiniteClipEditor();
  303. return track.HasAnyAnimatableParameters();
  304. }
  305. internal static bool ShouldShowInfiniteClipEditor(this AnimationTrack track)
  306. {
  307. return track != null && !track.inClipMode && track.infiniteClip != null;
  308. }
  309. // Special method to remove a track that is in a broken state. i.e. the script won't load
  310. internal static bool RemoveBrokenTrack(PlayableAsset parent, ScriptableObject track)
  311. {
  312. var parentTrack = parent as TrackAsset;
  313. var parentTimeline = parent as TimelineAsset;
  314. if (parentTrack == null && parentTimeline == null)
  315. throw new ArgumentException("parent is not a valid parent type", "parent");
  316. // this object must be a Unity null, but not actually null;
  317. object trackAsObject = track;
  318. if (trackAsObject == null || track != null) // yes, this is correct
  319. throw new ArgumentException("track is not in a broken state");
  320. // this belongs to a parent track
  321. if (parentTrack != null)
  322. {
  323. int index = parentTrack.subTracksObjects.FindIndex(t => t.GetInstanceID() == track.GetInstanceID());
  324. if (index >= 0)
  325. {
  326. TimelineUndo.PushUndo(parentTrack, "Remove Track");
  327. parentTrack.subTracksObjects.RemoveAt(index);
  328. parentTrack.Invalidate();
  329. Undo.DestroyObjectImmediate(track);
  330. return true;
  331. }
  332. }
  333. else if (parentTimeline != null)
  334. {
  335. int index = parentTimeline.trackObjects.FindIndex(t => t.GetInstanceID() == track.GetInstanceID());
  336. if (index >= 0)
  337. {
  338. TimelineUndo.PushUndo(parentTimeline, "Remove Track");
  339. parentTimeline.trackObjects.RemoveAt(index);
  340. parentTimeline.Invalidate();
  341. Undo.DestroyObjectImmediate(track);
  342. return true;
  343. }
  344. }
  345. return false;
  346. }
  347. // Find the gap at the given time
  348. // return true if there is a gap, false if there is an intersection
  349. // endGap will be Infinity if the gap has no end
  350. internal static bool GetGapAtTime(this TrackAsset track, double time, out double startGap, out double endGap)
  351. {
  352. startGap = 0;
  353. endGap = Double.PositiveInfinity;
  354. if (track == null || !track.GetClips().Any())
  355. {
  356. return false;
  357. }
  358. track.SortClips();
  359. var sortedByStartTime = track.clips;
  360. for (int i = 0; i < sortedByStartTime.Length; i++)
  361. {
  362. var clip = sortedByStartTime[i];
  363. // intersection
  364. if (time >= clip.start && time <= clip.end)
  365. {
  366. endGap = time;
  367. startGap = time;
  368. return false;
  369. }
  370. if (clip.end < time)
  371. {
  372. startGap = clip.end;
  373. }
  374. if (clip.start > time)
  375. {
  376. endGap = clip.start;
  377. break;
  378. }
  379. }
  380. if (endGap - startGap < TimelineClip.kMinDuration)
  381. {
  382. startGap = time;
  383. endGap = time;
  384. return false;
  385. }
  386. return true;
  387. }
  388. public static bool IsCompatibleWithClip(this TrackAsset track, TimelineClip clip)
  389. {
  390. if (track == null || clip == null || clip.asset == null)
  391. return false;
  392. return TypeUtility.GetPlayableAssetsHandledByTrack(track.GetType()).Contains(clip.asset.GetType());
  393. }
  394. // Get a flattened list of all child tracks
  395. public static void GetFlattenedChildTracks(this TrackAsset asset, List<TrackAsset> list)
  396. {
  397. if (asset == null || list == null)
  398. return;
  399. foreach (var track in asset.GetChildTracks())
  400. {
  401. list.Add(track);
  402. GetFlattenedChildTracks(track, list);
  403. }
  404. }
  405. public static IEnumerable<TrackAsset> GetFlattenedChildTracks(this TrackAsset asset)
  406. {
  407. if (asset == null || !asset.GetChildTracks().Any())
  408. return Enumerable.Empty<TrackAsset>();
  409. var flattenedChildTracks = new List<TrackAsset>();
  410. GetFlattenedChildTracks(asset, flattenedChildTracks);
  411. return flattenedChildTracks;
  412. }
  413. }
  414. }