TimelineHelpers.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Reflection;
  6. using UnityEditor.MemoryProfiler;
  7. using UnityEditor.SceneManagement;
  8. using UnityEngine;
  9. using UnityEngine.Playables;
  10. using UnityEngine.Timeline;
  11. using Component = UnityEngine.Component;
  12. using Object = UnityEngine.Object;
  13. namespace UnityEditor.Timeline
  14. {
  15. static class TimelineHelpers
  16. {
  17. static List<Type> s_SubClassesOfTrackDrawer;
  18. // check whether the exposed reference is explicitly named
  19. static bool IsExposedReferenceExplicitlyNamed(string name)
  20. {
  21. if (string.IsNullOrEmpty(name))
  22. return false;
  23. GUID guid;
  24. return !GUID.TryParse(name, out guid);
  25. }
  26. static string GenerateExposedReferenceName()
  27. {
  28. return UnityEditor.GUID.Generate().ToString();
  29. }
  30. public static void CloneExposedReferences(ScriptableObject clone, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable)
  31. {
  32. var cloneObject = new SerializedObject(clone);
  33. SerializedProperty prop = cloneObject.GetIterator();
  34. while (prop.Next(true))
  35. {
  36. if (prop.propertyType == SerializedPropertyType.ExposedReference)
  37. {
  38. var exposedNameProp = prop.FindPropertyRelative("exposedName");
  39. var sourceKey = exposedNameProp.stringValue;
  40. var destKey = sourceKey;
  41. if (!IsExposedReferenceExplicitlyNamed(sourceKey))
  42. destKey = GenerateExposedReferenceName();
  43. exposedNameProp.stringValue = destKey;
  44. var requiresCopy = sourceTable != destTable || sourceKey != destKey;
  45. if (requiresCopy && sourceTable != null && destTable != null)
  46. {
  47. var valid = false;
  48. var target = sourceTable.GetReferenceValue(sourceKey, out valid);
  49. if (valid && target != null)
  50. {
  51. var existing = destTable.GetReferenceValue(destKey, out valid);
  52. if (!valid || existing != target)
  53. {
  54. var destTableObj = destTable as UnityEngine.Object;
  55. if (destTableObj != null)
  56. TimelineUndo.PushUndo(destTableObj, "Create Clip");
  57. destTable.SetReferenceValue(destKey, target);
  58. }
  59. }
  60. }
  61. }
  62. }
  63. cloneObject.ApplyModifiedPropertiesWithoutUndo();
  64. }
  65. public static ScriptableObject CloneReferencedPlayableAsset(ScriptableObject original, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, Object newOwner)
  66. {
  67. var clone = Object.Instantiate(original);
  68. SaveCloneToAsset(clone, newOwner);
  69. if (clone == null || (clone as IPlayableAsset) == null)
  70. {
  71. throw new InvalidCastException("could not cast instantiated object into IPlayableAsset");
  72. }
  73. CloneExposedReferences(clone, sourceTable, destTable);
  74. TimelineUndo.RegisterCreatedObjectUndo(clone, "Create clip");
  75. return clone;
  76. }
  77. static void SaveCloneToAsset(Object clone, Object newOwner)
  78. {
  79. if (newOwner == null)
  80. return;
  81. var containerPath = AssetDatabase.GetAssetPath(newOwner);
  82. var containerAsset = AssetDatabase.LoadAssetAtPath<Object>(containerPath);
  83. if (containerAsset != null)
  84. {
  85. TimelineCreateUtilities.SaveAssetIntoObject(clone, containerAsset);
  86. EditorUtility.SetDirty(containerAsset);
  87. }
  88. }
  89. static AnimationClip CloneAnimationClip(AnimationClip clip, Object owner)
  90. {
  91. if (clip == null)
  92. return null;
  93. var newClip = Object.Instantiate(clip);
  94. newClip.name = AnimationTrackRecorder.GetUniqueRecordedClipName(owner, clip.name);
  95. SaveAnimClipIntoObject(newClip, owner);
  96. TimelineUndo.RegisterCreatedObjectUndo(newClip, "Create clip");
  97. return newClip;
  98. }
  99. public static TimelineClip Clone(TimelineClip clip, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, double time, PlayableAsset newOwner = null)
  100. {
  101. if (newOwner == null)
  102. newOwner = clip.parentTrack;
  103. TimelineClip newClip = DuplicateClip(clip, sourceTable, destTable, newOwner);
  104. newClip.start = time;
  105. var track = newClip.parentTrack;
  106. track.SortClips();
  107. return newClip;
  108. }
  109. // Creates a complete clone of a track and returns it.
  110. // Does not parent, or add the track to the sequence
  111. public static TrackAsset Clone(PlayableAsset parent, TrackAsset trackAsset, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, PlayableAsset assetOwner = null)
  112. {
  113. if (trackAsset == null)
  114. return null;
  115. var timelineAsset = trackAsset.timelineAsset;
  116. if (timelineAsset == null)
  117. return null;
  118. if (assetOwner == null)
  119. assetOwner = parent;
  120. // create a duplicate, then clear the clips and subtracks
  121. var newTrack = Object.Instantiate(trackAsset);
  122. newTrack.name = trackAsset.name;
  123. newTrack.ClearClipsInternal();
  124. newTrack.parent = parent;
  125. newTrack.ClearSubTracksInternal();
  126. if (trackAsset.hasCurves)
  127. newTrack.curves = CloneAnimationClip(trackAsset.curves, assetOwner);
  128. var animTrack = trackAsset as AnimationTrack;
  129. if (animTrack != null && animTrack.infiniteClip != null)
  130. ((AnimationTrack)newTrack).infiniteClip = CloneAnimationClip(animTrack.infiniteClip, assetOwner);
  131. foreach (var clip in trackAsset.clips)
  132. {
  133. var newClip = DuplicateClip(clip, sourceTable, destTable, assetOwner);
  134. newClip.parentTrack = newTrack;
  135. }
  136. newTrack.ClearMarkers();
  137. foreach (var e in trackAsset.GetMarkersRaw())
  138. {
  139. var newMarker = Object.Instantiate(e);
  140. newTrack.AddMarker(newMarker);
  141. SaveCloneToAsset(newMarker, assetOwner);
  142. if (newMarker is IMarker)
  143. {
  144. (newMarker as IMarker).Initialize(newTrack);
  145. }
  146. }
  147. newTrack.SetCollapsed(trackAsset.GetCollapsed());
  148. // calling code is responsible for adding to asset, adding to sequence, and parenting,
  149. // and duplicating subtracks
  150. return newTrack;
  151. }
  152. public static IEnumerable<ITimelineItem> DuplicateItemsUsingCurrentEditMode(IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, ItemsPerTrack items, TrackAsset targetParent, double candidateTime, string undoOperation)
  153. {
  154. if (targetParent != null)
  155. {
  156. var aTrack = targetParent as AnimationTrack;
  157. if (aTrack != null)
  158. aTrack.ConvertToClipMode();
  159. var duplicatedItems = DuplicateItems(items, targetParent, sourceTable, destTable, undoOperation);
  160. FinalizeInsertItemsUsingCurrentEditMode(new[] {duplicatedItems}, candidateTime);
  161. return duplicatedItems.items;
  162. }
  163. return Enumerable.Empty<ITimelineItem>();
  164. }
  165. public static IEnumerable<ITimelineItem> DuplicateItemsUsingCurrentEditMode(IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, IEnumerable<ItemsPerTrack> items, double candidateTime, string undoOperation)
  166. {
  167. var duplicatedItemsGroups = new List<ItemsPerTrack>();
  168. foreach (var i in items)
  169. duplicatedItemsGroups.Add(DuplicateItems(i, i.targetTrack, sourceTable, destTable, undoOperation));
  170. FinalizeInsertItemsUsingCurrentEditMode(duplicatedItemsGroups, candidateTime);
  171. return duplicatedItemsGroups.SelectMany(i => i.items);
  172. }
  173. internal static ItemsPerTrack DuplicateItems(ItemsPerTrack items, TrackAsset target, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, string undoOperation)
  174. {
  175. var duplicatedItems = new List<ITimelineItem>();
  176. var clips = items.clips.ToList();
  177. if (clips.Any())
  178. {
  179. TimelineUndo.PushUndo(target, undoOperation);
  180. duplicatedItems.AddRange(DuplicateClips(clips, sourceTable, destTable, target).ToItems());
  181. TimelineUndo.PushUndo(target, undoOperation); // second undo causes reference fixups on redo (case 1063868)
  182. }
  183. var markers = items.markers.ToList();
  184. if (markers.Any())
  185. {
  186. duplicatedItems.AddRange(MarkerModifier.CloneMarkersToParent(markers, target).ToItems());
  187. }
  188. return new ItemsPerTrack(target, duplicatedItems.ToArray());
  189. }
  190. static void FinalizeInsertItemsUsingCurrentEditMode(IList<ItemsPerTrack> itemsGroups, double candidateTime)
  191. {
  192. EditMode.FinalizeInsertItemsAtTime(itemsGroups, candidateTime);
  193. SelectionManager.Clear();
  194. foreach (var itemsGroup in itemsGroups)
  195. {
  196. var track = itemsGroup.targetTrack;
  197. var items = itemsGroup.items;
  198. EditModeUtils.SetParentTrack(items, track);
  199. track.SortClips();
  200. TrackExtensions.ComputeBlendsFromOverlaps(track.clips);
  201. track.CalculateExtrapolationTimes();
  202. foreach (var item in items)
  203. if (item.gui != null) item.gui.Select();
  204. }
  205. var allItems = itemsGroups.SelectMany(x => x.items).ToList();
  206. foreach (var item in allItems)
  207. {
  208. SelectionManager.Add(item);
  209. }
  210. FrameItems(allItems);
  211. }
  212. internal static TimelineClip Clone(TimelineClip clip, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, PlayableAsset newOwner)
  213. {
  214. var editorClip = EditorClipFactory.GetEditorClip(clip);
  215. // Workaround for Clips not being unity object, assign it to a editor clip wrapper, clone it, and pull the clip back out
  216. var newClip = Object.Instantiate(editorClip).clip;
  217. // perform fix ups for what Instantiate cannot properly detect
  218. SelectionManager.Remove(newClip);
  219. newClip.parentTrack = null;
  220. newClip.curves = null; // instantiate might copy the reference, we need to clear it
  221. // curves are explicitly owned by the clip
  222. if (clip.curves != null)
  223. {
  224. newClip.CreateCurves(AnimationTrackRecorder.GetUniqueRecordedClipName(newOwner, clip.curves.name));
  225. EditorUtility.CopySerialized(clip.curves, newClip.curves);
  226. TimelineCreateUtilities.SaveAssetIntoObject(newClip.curves, newOwner);
  227. }
  228. ScriptableObject playableAsset = newClip.asset as ScriptableObject;
  229. if (playableAsset != null && newClip.asset is IPlayableAsset)
  230. {
  231. var clone = CloneReferencedPlayableAsset(playableAsset, sourceTable, destTable, newOwner);
  232. newClip.asset = clone;
  233. // special case to make the name match the recordable clips, but only if they match on the original clip
  234. var originalRecordedAsset = clip.asset as AnimationPlayableAsset;
  235. if (clip.recordable && originalRecordedAsset != null && originalRecordedAsset.clip != null)
  236. {
  237. AnimationPlayableAsset clonedAnimationAsset = clone as AnimationPlayableAsset;
  238. if (clonedAnimationAsset != null && clonedAnimationAsset.clip != null)
  239. {
  240. clonedAnimationAsset.clip = CloneAnimationClip(originalRecordedAsset.clip, newOwner);
  241. if (clip.displayName == originalRecordedAsset.clip.name && newClip.recordable)
  242. {
  243. clonedAnimationAsset.name = clonedAnimationAsset.clip.name;
  244. newClip.displayName = clonedAnimationAsset.name;
  245. }
  246. }
  247. }
  248. }
  249. return newClip;
  250. }
  251. static TimelineClip[] DuplicateClips(IEnumerable<TimelineClip> clips, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, PlayableAsset newOwner)
  252. {
  253. var newClips = new TimelineClip[clips.Count()];
  254. int i = 0;
  255. foreach (var clip in clips)
  256. {
  257. var newParent = newOwner == null ? clip.parentTrack : newOwner;
  258. var newClip = DuplicateClip(clip, sourceTable, destTable, newParent);
  259. newClip.parentTrack = null;
  260. newClips[i++] = newClip;
  261. }
  262. return newClips;
  263. }
  264. static TimelineClip DuplicateClip(TimelineClip clip, IExposedPropertyTable sourceTable, IExposedPropertyTable destTable, PlayableAsset newOwner)
  265. {
  266. var newClip = Clone(clip, sourceTable, destTable, newOwner);
  267. var track = clip.parentTrack;
  268. if (track != null)
  269. {
  270. newClip.parentTrack = track;
  271. track.AddClip(newClip);
  272. }
  273. var editor = CustomTimelineEditorCache.GetClipEditor(clip);
  274. try
  275. {
  276. editor.OnCreate(newClip, track, clip);
  277. }
  278. catch (Exception e)
  279. {
  280. Debug.LogException(e);
  281. }
  282. return newClip;
  283. }
  284. // Given a track type, return all the playable asset types that should be
  285. // visible to the user via menus
  286. // Given a track type, return all the playable asset types
  287. public static Type GetCustomDrawer(Type trackType)
  288. {
  289. if (s_SubClassesOfTrackDrawer == null)
  290. {
  291. s_SubClassesOfTrackDrawer = TypeCache.GetTypesDerivedFrom<TrackDrawer>().ToList();
  292. }
  293. foreach (var drawer in s_SubClassesOfTrackDrawer)
  294. {
  295. var attr = Attribute.GetCustomAttribute(drawer, typeof(CustomTrackDrawerAttribute), false) as CustomTrackDrawerAttribute;
  296. if (attr != null && attr.assetType.IsAssignableFrom(trackType))
  297. return drawer;
  298. }
  299. return typeof(TrackDrawer);
  300. }
  301. public static bool HaveSameContainerAsset(Object assetA, Object assetB)
  302. {
  303. if (assetA == null || assetB == null)
  304. return false;
  305. if ((assetA.hideFlags & HideFlags.DontSave) != 0 && (assetB.hideFlags & HideFlags.DontSave) != 0)
  306. return true;
  307. return AssetDatabase.GetAssetPath(assetA) == AssetDatabase.GetAssetPath(assetB);
  308. }
  309. public static void SaveAnimClipIntoObject(AnimationClip clip, Object asset)
  310. {
  311. if (asset != null)
  312. {
  313. clip.hideFlags = asset.hideFlags & ~HideFlags.HideInHierarchy; // show animation clips, even if the parent track isn't
  314. if ((clip.hideFlags & HideFlags.DontSave) == 0)
  315. {
  316. AssetDatabase.AddObjectToAsset(clip, asset);
  317. }
  318. }
  319. }
  320. // Make sure a gameobject has all the required component for the given TrackAsset
  321. public static Component AddRequiredComponent(GameObject go, TrackAsset asset)
  322. {
  323. if (go == null || asset == null)
  324. return null;
  325. var bindings = asset.outputs;
  326. if (!bindings.Any())
  327. return null;
  328. var binding = bindings.First();
  329. if (binding.outputTargetType == null || !typeof(Component).IsAssignableFrom(binding.outputTargetType))
  330. return null;
  331. var component = go.GetComponent(binding.outputTargetType);
  332. if (component == null)
  333. {
  334. component = Undo.AddComponent(go, binding.outputTargetType);
  335. }
  336. return component;
  337. }
  338. public static string GetTrackCategoryName(System.Type trackType)
  339. {
  340. if (trackType == null)
  341. return string.Empty;
  342. string s = GetItemCategoryName(trackType);
  343. if (!String.IsNullOrEmpty(s))
  344. return s;
  345. // if as display name with a path is specified use that
  346. var attr = Attribute.GetCustomAttribute(trackType, typeof(DisplayNameAttribute)) as DisplayNameAttribute;
  347. if (attr != null && attr.DisplayName.Contains('/'))
  348. return string.Empty;
  349. if (trackType.Namespace == null || trackType.Namespace.Contains("UnityEngine"))
  350. return string.Empty;
  351. return trackType.Namespace + "/";
  352. }
  353. public static string GetItemCategoryName(System.Type itemType)
  354. {
  355. if (itemType == null)
  356. return string.Empty;
  357. var attribute = itemType.GetCustomAttribute(typeof(MenuCategoryAttribute)) as MenuCategoryAttribute;
  358. if (attribute != null)
  359. {
  360. var s = attribute.category;
  361. if (!s.EndsWith("/"))
  362. s += "/";
  363. return s;
  364. }
  365. return string.Empty;
  366. }
  367. public static string GetTrackMenuName(System.Type trackType)
  368. {
  369. return TypeUtility.GetDisplayName(trackType);
  370. }
  371. // retrieve the duration of a single loop, taking into account speed
  372. public static double GetLoopDuration(TimelineClip clip)
  373. {
  374. double length = clip.clipAssetDuration;
  375. if (double.IsNegativeInfinity(length) || double.IsNaN(length))
  376. return TimelineClip.kMinDuration;
  377. if (length == double.MaxValue || double.IsInfinity(length))
  378. {
  379. return double.MaxValue;
  380. }
  381. return Math.Max(TimelineClip.kMinDuration, length / clip.timeScale);
  382. }
  383. public static double GetClipAssetEndTime(TimelineClip clip)
  384. {
  385. var d = GetLoopDuration(clip);
  386. if (d < double.MaxValue)
  387. d = clip.FromLocalTimeUnbound(d);
  388. return d;
  389. }
  390. // Checks if the underlying asset duration is usable. This means the clip
  391. // can loop or hold
  392. public static bool HasUsableAssetDuration(TimelineClip clip)
  393. {
  394. double length = clip.clipAssetDuration;
  395. return (length < TimelineClip.kMaxTimeValue) && !double.IsInfinity(length) && !double.IsNaN(length);
  396. }
  397. // Retrieves the starting point of each loop of a clip, relative to the start of the clip
  398. // Note that if clip-in is bigger than the loopDuration, negative times will be added
  399. public static double[] GetLoopTimes(TimelineClip clip)
  400. {
  401. if (!HasUsableAssetDuration(clip))
  402. return new[] {-clip.clipIn / clip.timeScale};
  403. var times = new List<double>();
  404. double loopDuration = GetLoopDuration(clip);
  405. if (loopDuration <= TimeUtility.kTimeEpsilon)
  406. return new double[] {};
  407. double start = -clip.clipIn / clip.timeScale;
  408. double end = start + loopDuration;
  409. times.Add(start);
  410. while (end < clip.duration - WindowState.kTimeEpsilon)
  411. {
  412. times.Add(end);
  413. end += loopDuration;
  414. }
  415. return times.ToArray();
  416. }
  417. public static double GetCandidateTime(Vector2? mousePosition, params TrackAsset[] trackAssets)
  418. {
  419. // Right-Click
  420. if (mousePosition != null)
  421. {
  422. return TimeReferenceUtility.GetSnappedTimeAtMousePosition(mousePosition.Value);
  423. }
  424. // Playhead
  425. if (TimelineEditor.inspectedDirector != null)
  426. {
  427. return TimeReferenceUtility.SnapToFrameIfRequired(TimelineEditor.inspectedSequenceTime);
  428. }
  429. // Specific tracks end
  430. if (trackAssets != null && trackAssets.Any())
  431. {
  432. var items = trackAssets.SelectMany(t => t.GetItems()).ToList();
  433. return items.Any() ? items.Max(i => i.end) : 0;
  434. }
  435. // Timeline tracks end
  436. if (TimelineEditor.inspectedAsset != null)
  437. return TimelineEditor.inspectedAsset.flattenedTracks.Any() ? TimelineEditor.inspectedAsset.flattenedTracks.Max(t => t.end) : 0;
  438. return 0.0;
  439. }
  440. public static TimelineClip CreateClipOnTrack(Object asset, TrackAsset parentTrack, WindowState state)
  441. {
  442. return CreateClipOnTrack(asset, parentTrack, GetCandidateTime(null, parentTrack), state);
  443. }
  444. public static TimelineClip CreateClipOnTrack(Object asset, TrackAsset parentTrack, double candidateTime)
  445. {
  446. WindowState state = null;
  447. if (TimelineWindow.instance != null)
  448. state = TimelineWindow.instance.state;
  449. return CreateClipOnTrack(asset, parentTrack, candidateTime, state);
  450. }
  451. public static TimelineClip CreateClipOnTrack(Type playableAssetType, TrackAsset parentTrack, WindowState state)
  452. {
  453. return CreateClipOnTrack(playableAssetType, null, parentTrack, GetCandidateTime(null, parentTrack), state);
  454. }
  455. public static TimelineClip CreateClipOnTrack(Type playableAssetType, TrackAsset parentTrack, double candidateTime)
  456. {
  457. return CreateClipOnTrack(playableAssetType, null, parentTrack, candidateTime);
  458. }
  459. public static TimelineClip CreateClipOnTrack(Object asset, TrackAsset parentTrack, double candidateTime, WindowState state)
  460. {
  461. if (parentTrack == null)
  462. return null;
  463. // pick the first clip type available, unless there is one that matches the asset
  464. var clipType = TypeUtility.GetPlayableAssetsHandledByTrack(parentTrack.GetType()).FirstOrDefault();
  465. if (asset != null)
  466. clipType = TypeUtility.GetAssetTypesForObject(parentTrack.GetType(), asset).FirstOrDefault();
  467. if (clipType == null)
  468. return null;
  469. return CreateClipOnTrack(clipType, asset, parentTrack, candidateTime, state);
  470. }
  471. public static TimelineClip CreateClipOnTrack(Type playableAssetType, Object assignableObject, TrackAsset parentTrack, double candidateTime)
  472. {
  473. WindowState state = null;
  474. if (TimelineWindow.instance != null)
  475. state = TimelineWindow.instance.state;
  476. return CreateClipOnTrack(playableAssetType, assignableObject, parentTrack, candidateTime, state);
  477. }
  478. public static TimelineClip CreateClipOnTrack(Type playableAssetType, Object assignableObject, TrackAsset parentTrack, double candidateTime, WindowState state)
  479. {
  480. if (parentTrack == null)
  481. return null;
  482. bool revertClipMode = false;
  483. // Ideally this is done automatically by the animation track,
  484. // but it's editor only because it does animation clip manipulation
  485. var animTrack = parentTrack as AnimationTrack;
  486. if (animTrack != null && animTrack.CanConvertToClipMode())
  487. {
  488. animTrack.ConvertToClipMode();
  489. revertClipMode = true;
  490. }
  491. TimelineClip newClip = null;
  492. if (TypeUtility.IsConcretePlayableAsset(playableAssetType))
  493. {
  494. try
  495. {
  496. newClip = parentTrack.CreateClipOfType(playableAssetType);
  497. }
  498. catch (InvalidOperationException) {} // expected on a mismatch
  499. }
  500. if (newClip == null)
  501. {
  502. if (revertClipMode)
  503. animTrack.ConvertFromClipMode(animTrack.timelineAsset);
  504. Debug.LogWarningFormat("Cannot create a clip of type {0} on a track of type {1}", playableAssetType.Name, parentTrack.GetType().Name);
  505. return null;
  506. }
  507. AddClipOnTrack(newClip, parentTrack, candidateTime, assignableObject, state);
  508. return newClip;
  509. }
  510. /// <summary>
  511. /// Create a clip on track from an existing PlayableAsset
  512. /// </summary>
  513. public static TimelineClip CreateClipOnTrackFromPlayableAsset(IPlayableAsset asset, TrackAsset parentTrack, double candidateTime)
  514. {
  515. if (parentTrack == null || asset == null || !TypeUtility.IsConcretePlayableAsset(asset.GetType()))
  516. return null;
  517. TimelineClip newClip = null;
  518. try
  519. {
  520. newClip = parentTrack.CreateClipFromPlayableAsset(asset);
  521. }
  522. catch
  523. {
  524. return null;
  525. }
  526. WindowState state = null;
  527. if (TimelineWindow.instance != null)
  528. state = TimelineWindow.instance.state;
  529. AddClipOnTrack(newClip, parentTrack, candidateTime, null, state);
  530. return newClip;
  531. }
  532. public static void CreateClipsFromObjects(Type assetType, TrackAsset targetTrack, double candidateTime, IEnumerable<Object> objects)
  533. {
  534. foreach (var obj in objects)
  535. {
  536. if (ObjectReferenceField.FindObjectReferences(assetType).Any(f => f.IsAssignable(obj)))
  537. {
  538. var clip = CreateClipOnTrack(assetType, obj, targetTrack, candidateTime);
  539. candidateTime += clip.duration;
  540. }
  541. }
  542. }
  543. public static void CreateMarkersFromObjects(Type assetType, TrackAsset targetTrack, double candidateTime, IEnumerable<Object> objects)
  544. {
  545. var mList = new List<ITimelineItem>();
  546. foreach (var obj in objects)
  547. {
  548. if (ObjectReferenceField.FindObjectReferences(assetType).Any(f => f.IsAssignable(obj)))
  549. {
  550. var marker = CreateMarkerOnTrack(assetType, obj, targetTrack, candidateTime);
  551. mList.Add(marker.ToItem());
  552. }
  553. }
  554. var state = TimelineWindow.instance.state;
  555. for (var i = 1; i < mList.Count; ++i)
  556. {
  557. var delta = ItemsUtils.TimeGapBetweenItems(mList[i - 1], mList[i]);
  558. mList[i].start += delta;
  559. }
  560. FinalizeInsertItemsUsingCurrentEditMode(new[] {new ItemsPerTrack(targetTrack, mList)}, candidateTime);
  561. state.Refresh();
  562. }
  563. public static IMarker CreateMarkerOnTrack(Type markerType, Object assignableObject, TrackAsset parentTrack, double candidateTime)
  564. {
  565. WindowState state = null;
  566. if (TimelineWindow.instance != null)
  567. state = TimelineWindow.instance.state;
  568. var newMarker = parentTrack.CreateMarker(markerType, candidateTime); //Throws if marker is not an object
  569. var obj = newMarker as ScriptableObject;
  570. if (obj != null)
  571. obj.name = TypeUtility.GetDisplayName(markerType);
  572. if (assignableObject != null)
  573. {
  574. var director = state != null ? state.editSequence.director : null;
  575. foreach (var field in ObjectReferenceField.FindObjectReferences(markerType))
  576. {
  577. if (field.IsAssignable(assignableObject))
  578. {
  579. field.Assign(newMarker as ScriptableObject, assignableObject, director);
  580. break;
  581. }
  582. }
  583. }
  584. try
  585. {
  586. CustomTimelineEditorCache.GetMarkerEditor(newMarker).OnCreate(newMarker, null);
  587. }
  588. catch (Exception e)
  589. {
  590. Debug.LogException(e);
  591. }
  592. return newMarker;
  593. }
  594. public static void CreateClipsFromTypes(IEnumerable<Type> assetTypes, TrackAsset targetTrack, double candidateTime)
  595. {
  596. foreach (var assetType in assetTypes)
  597. {
  598. var clip = CreateClipOnTrack(assetType, targetTrack, candidateTime);
  599. candidateTime += clip.duration;
  600. }
  601. }
  602. public static void FrameItems(IEnumerable<ITimelineItem> items)
  603. {
  604. if (items == null || !items.Any())
  605. return;
  606. // if this is called before a repaint, the timeArea can be null
  607. if (TimelineEditor.window.timeArea == null)
  608. return;
  609. var start = (float)items.Min(x => x.start);
  610. var end = (float)items.Max(x => x.end);
  611. var timeRange = TimelineEditor.visibleTimeRange;
  612. // nothing to do
  613. if (timeRange.x <= start && timeRange.y >= end)
  614. return;
  615. timeRange.x = Mathf.Max(0, timeRange.x);
  616. timeRange.y = Mathf.Max(0, timeRange.y);
  617. var ds = start - timeRange.x;
  618. var de = end - timeRange.y;
  619. var padding = TimeReferenceUtility.PixelToTime(15) - TimeReferenceUtility.PixelToTime(0);
  620. var d = Math.Abs(ds) < Math.Abs(de) ? ds - padding : de + padding;
  621. TimelineEditor.visibleTimeRange = new Vector2(timeRange.x + d, timeRange.y + d);
  622. }
  623. public static void Frame(WindowState state, double start, double end)
  624. {
  625. var timeRange = state.timeAreaShownRange;
  626. // nothing to do
  627. if (timeRange.x <= start && timeRange.y >= end)
  628. return;
  629. var ds = (float)start - timeRange.x;
  630. var de = (float)end - timeRange.y;
  631. var padding = state.PixelDeltaToDeltaTime(15);
  632. var d = Math.Abs(ds) < Math.Abs(de) ? ds - padding : de + padding;
  633. state.SetTimeAreaShownRange(timeRange.x + d, timeRange.y + d);
  634. }
  635. public static void RangeSelect<T>(IList<T> totalCollection, IList<T> currentSelection, T clickedItem, Action<T> selector, Action<T> remover) where T : class
  636. {
  637. var firstSelect = currentSelection.FirstOrDefault();
  638. if (firstSelect == null)
  639. {
  640. selector(clickedItem);
  641. return;
  642. }
  643. var idxFirstSelect = totalCollection.IndexOf(firstSelect);
  644. var idxLastSelect = totalCollection.IndexOf(currentSelection.Last());
  645. var idxClicked = totalCollection.IndexOf(clickedItem);
  646. //case 927807: selection is invalid
  647. if (idxFirstSelect < 0)
  648. {
  649. SelectionManager.Clear();
  650. selector(clickedItem);
  651. return;
  652. }
  653. // Expand the selection between the first selected clip and clicked clip (insertion order is important)
  654. if (idxFirstSelect < idxClicked)
  655. for (var i = idxFirstSelect; i <= idxClicked; ++i)
  656. selector(totalCollection[i]);
  657. else
  658. for (var i = idxFirstSelect; i >= idxClicked; --i)
  659. selector(totalCollection[i]);
  660. // If clicked inside the selected range, shrink the selection between the the click and last selected clip
  661. if (Math.Min(idxFirstSelect, idxLastSelect) < idxClicked && idxClicked < Math.Max(idxFirstSelect, idxLastSelect))
  662. for (var i = Math.Min(idxLastSelect, idxClicked); i <= Math.Max(idxLastSelect, idxClicked); ++i)
  663. remover(totalCollection[i]);
  664. // Ensure clicked clip is selected
  665. selector(clickedItem);
  666. }
  667. public static void Bind(TrackAsset track, Object obj, PlayableDirector director)
  668. {
  669. if (director != null && track != null)
  670. {
  671. var bindType = TypeUtility.GetTrackBindingAttribute(track.GetType());
  672. if (bindType == null || bindType.type == null)
  673. return;
  674. if (obj == null || bindType.type.IsInstanceOfType(obj))
  675. {
  676. TimelineUndo.PushUndo(director, "Bind Track");
  677. director.SetGenericBinding(track, obj);
  678. }
  679. else if (obj is GameObject && typeof(Component).IsAssignableFrom(bindType.type))
  680. {
  681. var component = (obj as GameObject).GetComponent(bindType.type);
  682. if (component == null)
  683. component = Undo.AddComponent(obj as GameObject, bindType.type);
  684. TimelineUndo.PushUndo(director, "Bind Track");
  685. director.SetGenericBinding(track, component);
  686. }
  687. }
  688. }
  689. /// <summary>
  690. /// Shared code for adding a clip to a track
  691. /// </summary>
  692. static void AddClipOnTrack(TimelineClip newClip, TrackAsset parentTrack, double candidateTime, Object assignableObject, WindowState state)
  693. {
  694. var playableAsset = newClip.asset as IPlayableAsset;
  695. newClip.parentTrack = null;
  696. newClip.timeScale = 1.0;
  697. newClip.mixInCurve = AnimationCurve.EaseInOut(0, 0, 1, 1);
  698. newClip.mixOutCurve = AnimationCurve.EaseInOut(0, 1, 1, 0);
  699. var playableDirector = state != null ? state.editSequence.director : null;
  700. if (assignableObject != null)
  701. {
  702. foreach (var field in ObjectReferenceField.FindObjectReferences(playableAsset.GetType()))
  703. {
  704. if (field.IsAssignable(assignableObject))
  705. {
  706. newClip.displayName = assignableObject.name;
  707. field.Assign(newClip.asset as PlayableAsset, assignableObject, playableDirector);
  708. break;
  709. }
  710. }
  711. }
  712. // get the clip editor
  713. try
  714. {
  715. CustomTimelineEditorCache.GetClipEditor(newClip).OnCreate(newClip, parentTrack, null);
  716. }
  717. catch (Exception e)
  718. {
  719. Debug.LogException(e);
  720. }
  721. // reset the duration as the newly assigned values may have changed the default
  722. if (playableAsset != null)
  723. {
  724. var candidateDuration = playableAsset.duration;
  725. if (!double.IsInfinity(candidateDuration) && candidateDuration > 0)
  726. newClip.duration = Math.Min(Math.Max(candidateDuration, TimelineClip.kMinDuration), TimelineClip.kMaxTimeValue);
  727. }
  728. var newClipsByTracks = new[] { new ItemsPerTrack(parentTrack, new[] {newClip.ToItem()}) };
  729. FinalizeInsertItemsUsingCurrentEditMode(newClipsByTracks, candidateTime);
  730. if (state != null)
  731. state.Refresh();
  732. }
  733. public static TrackAsset CreateTrack(TimelineAsset asset, Type type, TrackAsset parent = null, string name = null)
  734. {
  735. if (asset == null)
  736. return null;
  737. var track = asset.CreateTrack(type, parent, name);
  738. if (track != null)
  739. {
  740. if (parent != null)
  741. parent.SetCollapsed(false);
  742. var editor = CustomTimelineEditorCache.GetTrackEditor(track);
  743. try
  744. {
  745. editor.OnCreate(track, null);
  746. }
  747. catch (Exception e)
  748. {
  749. Debug.LogException(e);
  750. }
  751. TimelineEditor.Refresh(RefreshReason.ContentsAddedOrRemoved);
  752. }
  753. return track;
  754. }
  755. public static TrackAsset CreateTrack(Type type, TrackAsset parent = null, string name = null)
  756. {
  757. return CreateTrack(TimelineEditor.inspectedAsset, type, parent, name);
  758. }
  759. public static T CreateTrack<T>(TimelineAsset asset, TrackAsset parent = null, string name = null) where T : TrackAsset
  760. {
  761. return (T)CreateTrack(asset, typeof(T), parent, name);
  762. }
  763. public static T CreateTrack<T>(TrackAsset parent = null, string name = null) where T : TrackAsset
  764. {
  765. return (T)CreateTrack(TimelineEditor.inspectedAsset, typeof(T), parent, name);
  766. }
  767. }
  768. }