Nenhuma descrição
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

TimelineHelpers.cs 35KB

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