Aucune description
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

TimelineHelpers.cs 35KB

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