TrackExtensions.cs 19 KB

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