TimelineHelpers.cs 36 KB

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