Ingen beskrivning
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ControlPlayableAsset.cs 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine.Playables;
  5. namespace UnityEngine.Timeline
  6. {
  7. /// <summary>
  8. /// Playable Asset that generates playables for controlling time-related elements on a GameObject.
  9. /// </summary>
  10. [Serializable]
  11. [NotKeyable]
  12. public class ControlPlayableAsset : PlayableAsset, IPropertyPreview, ITimelineClipAsset
  13. {
  14. const int k_MaxRandInt = 10000;
  15. static readonly List<PlayableDirector> k_EmptyDirectorsList = new List<PlayableDirector>(0);
  16. static readonly List<ParticleSystem> k_EmptyParticlesList = new List<ParticleSystem>(0);
  17. static readonly HashSet<ParticleSystem> s_SubEmitterCollector = new HashSet<ParticleSystem>();
  18. /// <summary>
  19. /// GameObject in the scene to control, or the parent of the instantiated prefab.
  20. /// </summary>
  21. [SerializeField] public ExposedReference<GameObject> sourceGameObject;
  22. /// <summary>
  23. /// Prefab object that will be instantiated.
  24. /// </summary>
  25. [SerializeField] public GameObject prefabGameObject;
  26. /// <summary>
  27. /// Indicates whether Particle Systems will be controlled.
  28. /// </summary>
  29. [SerializeField] public bool updateParticle = true;
  30. /// <summary>
  31. /// Random seed to supply particle systems that are set to use autoRandomSeed
  32. /// </summary>
  33. /// <remarks>
  34. /// This is used to maintain determinism when playing back in timeline. Sub emitters will be assigned incrementing random seeds to maintain determinism and distinction.
  35. /// </remarks>
  36. [SerializeField] public uint particleRandomSeed;
  37. /// <summary>
  38. /// Indicates whether playableDirectors are controlled.
  39. /// </summary>
  40. [SerializeField] public bool updateDirector = true;
  41. /// <summary>
  42. /// Indicates whether Monobehaviours implementing ITimeControl will be controlled.
  43. /// </summary>
  44. [SerializeField] public bool updateITimeControl = true;
  45. /// <summary>
  46. /// Indicates whether to search the entire hierarchy for controllable components.
  47. /// </summary>
  48. [SerializeField] public bool searchHierarchy;
  49. /// <summary>
  50. /// Indicate whether GameObject activation is controlled
  51. /// </summary>
  52. [SerializeField] public bool active = true;
  53. /// <summary>
  54. /// Indicates the active state of the GameObject when Timeline is stopped.
  55. /// </summary>
  56. [SerializeField]
  57. public ActivationControlPlayable.PostPlaybackState postPlayback = ActivationControlPlayable.PostPlaybackState.Revert;
  58. /// <summary>
  59. /// Which action to apply to the <see cref="PlayableDirector"/> at the end of the control clip. <seealso cref="DirectorControlPlayable.PauseAction"/>
  60. /// </summary>
  61. [SerializeField]
  62. public DirectorControlPlayable.PauseAction directorOnClipEnd;
  63. PlayableAsset m_ControlDirectorAsset;
  64. double m_Duration = PlayableBinding.DefaultDuration;
  65. bool m_SupportLoop;
  66. private static HashSet<PlayableDirector> s_ProcessedDirectors = new HashSet<PlayableDirector>();
  67. private static HashSet<GameObject> s_CreatedPrefabs = new HashSet<GameObject>();
  68. // does the last instance created control directors and/or particles
  69. internal bool controllingDirectors { get; private set; }
  70. internal bool controllingParticles { get; private set; }
  71. /// <summary>
  72. /// This function is called when the object is loaded.
  73. /// </summary>
  74. public void OnEnable()
  75. {
  76. // can't be set in a constructor
  77. if (particleRandomSeed == 0)
  78. particleRandomSeed = (uint)Random.Range(1, k_MaxRandInt);
  79. }
  80. /// <summary>
  81. /// Returns the duration in seconds needed to play the underlying director or particle system exactly once.
  82. /// </summary>
  83. public override double duration { get { return m_Duration; } }
  84. /// <summary>
  85. /// Returns the capabilities of TimelineClips that contain a ControlPlayableAsset
  86. /// </summary>
  87. public ClipCaps clipCaps
  88. {
  89. get { return ClipCaps.ClipIn | ClipCaps.SpeedMultiplier | (m_SupportLoop ? ClipCaps.Looping : ClipCaps.None); }
  90. }
  91. /// <summary>
  92. /// Creates the root of a Playable subgraph to control the contents of the game object.
  93. /// </summary>
  94. /// <param name="graph">PlayableGraph that will own the playable</param>
  95. /// <param name="go">The GameObject that triggered the graph build</param>
  96. /// <returns>The root playable of the subgraph</returns>
  97. public override Playable CreatePlayable(PlayableGraph graph, GameObject go)
  98. {
  99. // case 989856
  100. if (prefabGameObject != null)
  101. {
  102. if (s_CreatedPrefabs.Contains(prefabGameObject))
  103. {
  104. Debug.LogWarningFormat("Control Track Clip ({0}) is causing a prefab to instantiate itself recursively. Aborting further instances.", name);
  105. return Playable.Create(graph);
  106. }
  107. s_CreatedPrefabs.Add(prefabGameObject);
  108. }
  109. Playable root = Playable.Null;
  110. var playables = new List<Playable>();
  111. GameObject sourceObject = sourceGameObject.Resolve(graph.GetResolver());
  112. if (prefabGameObject != null)
  113. {
  114. Transform parenTransform = sourceObject != null ? sourceObject.transform : null;
  115. var controlPlayable = PrefabControlPlayable.Create(graph, prefabGameObject, parenTransform);
  116. sourceObject = controlPlayable.GetBehaviour().prefabInstance;
  117. playables.Add(controlPlayable);
  118. }
  119. m_Duration = PlayableBinding.DefaultDuration;
  120. m_SupportLoop = false;
  121. controllingParticles = false;
  122. controllingDirectors = false;
  123. if (sourceObject != null)
  124. {
  125. var directors = updateDirector ? GetComponent<PlayableDirector>(sourceObject) : k_EmptyDirectorsList;
  126. var particleSystems = updateParticle ? GetControllableParticleSystems(sourceObject) : k_EmptyParticlesList;
  127. // update the duration and loop values (used for UI purposes) here
  128. // so they are tied to the latest gameObject bound
  129. UpdateDurationAndLoopFlag(directors, particleSystems);
  130. var director = go.GetComponent<PlayableDirector>();
  131. if (director != null)
  132. m_ControlDirectorAsset = director.playableAsset;
  133. if (go == sourceObject && prefabGameObject == null)
  134. {
  135. Debug.LogWarningFormat("Control Playable ({0}) is referencing the same PlayableDirector component than the one in which it is playing.", name);
  136. active = false;
  137. if (!searchHierarchy)
  138. updateDirector = false;
  139. }
  140. if (active)
  141. CreateActivationPlayable(sourceObject, graph, playables);
  142. if (updateDirector)
  143. SearchHierarchyAndConnectDirector(directors, graph, playables, prefabGameObject != null);
  144. if (updateParticle)
  145. SearchHierarchyAndConnectParticleSystem(particleSystems, graph, playables);
  146. if (updateITimeControl)
  147. SearchHierarchyAndConnectControlableScripts(GetControlableScripts(sourceObject), graph, playables);
  148. // Connect Playables to Generic to Mixer
  149. root = ConnectPlayablesToMixer(graph, playables);
  150. }
  151. if (prefabGameObject != null)
  152. s_CreatedPrefabs.Remove(prefabGameObject);
  153. if (!root.IsValid())
  154. root = Playable.Create(graph);
  155. return root;
  156. }
  157. static Playable ConnectPlayablesToMixer(PlayableGraph graph, List<Playable> playables)
  158. {
  159. var mixer = Playable.Create(graph, playables.Count);
  160. for (int i = 0; i != playables.Count; ++i)
  161. {
  162. ConnectMixerAndPlayable(graph, mixer, playables[i], i);
  163. }
  164. mixer.SetPropagateSetTime(true);
  165. return mixer;
  166. }
  167. void CreateActivationPlayable(GameObject root, PlayableGraph graph,
  168. List<Playable> outplayables)
  169. {
  170. var activation = ActivationControlPlayable.Create(graph, root, postPlayback);
  171. if (activation.IsValid())
  172. outplayables.Add(activation);
  173. }
  174. void SearchHierarchyAndConnectParticleSystem(IEnumerable<ParticleSystem> particleSystems, PlayableGraph graph,
  175. List<Playable> outplayables)
  176. {
  177. foreach (var particleSystem in particleSystems)
  178. {
  179. if (particleSystem != null)
  180. {
  181. controllingParticles = true;
  182. outplayables.Add(ParticleControlPlayable.Create(graph, particleSystem, particleRandomSeed));
  183. }
  184. }
  185. }
  186. void SearchHierarchyAndConnectDirector(IEnumerable<PlayableDirector> directors, PlayableGraph graph,
  187. List<Playable> outplayables, bool disableSelfReferences)
  188. {
  189. foreach (var director in directors)
  190. {
  191. if (director != null)
  192. {
  193. if (director.playableAsset != m_ControlDirectorAsset)
  194. {
  195. ScriptPlayable<DirectorControlPlayable> directorControlPlayable = DirectorControlPlayable.Create(graph, director);
  196. directorControlPlayable.GetBehaviour().pauseAction = directorOnClipEnd;
  197. outplayables.Add(directorControlPlayable);
  198. controllingDirectors = true;
  199. }
  200. // if this self references, disable the director.
  201. else if (disableSelfReferences)
  202. {
  203. director.enabled = false;
  204. }
  205. }
  206. }
  207. }
  208. static void SearchHierarchyAndConnectControlableScripts(IEnumerable<MonoBehaviour> controlableScripts, PlayableGraph graph, List<Playable> outplayables)
  209. {
  210. foreach (var script in controlableScripts)
  211. {
  212. outplayables.Add(TimeControlPlayable.Create(graph, (ITimeControl)script));
  213. }
  214. }
  215. static void ConnectMixerAndPlayable(PlayableGraph graph, Playable mixer, Playable playable,
  216. int portIndex)
  217. {
  218. graph.Connect(playable, 0, mixer, portIndex);
  219. mixer.SetInputWeight(playable, 1.0f);
  220. }
  221. internal IList<T> GetComponent<T>(GameObject gameObject)
  222. {
  223. var components = new List<T>();
  224. if (gameObject != null)
  225. {
  226. if (searchHierarchy)
  227. {
  228. gameObject.GetComponentsInChildren<T>(true, components);
  229. }
  230. else
  231. {
  232. gameObject.GetComponents<T>(components);
  233. }
  234. }
  235. return components;
  236. }
  237. internal static IEnumerable<MonoBehaviour> GetControlableScripts(GameObject root)
  238. {
  239. if (root == null)
  240. yield break;
  241. foreach (var script in root.GetComponentsInChildren<MonoBehaviour>())
  242. {
  243. if (script is ITimeControl)
  244. yield return script;
  245. }
  246. }
  247. internal void UpdateDurationAndLoopFlag(IList<PlayableDirector> directors, IList<ParticleSystem> particleSystems)
  248. {
  249. if (directors.Count == 0 && particleSystems.Count == 0)
  250. return;
  251. const double invalidDuration = double.NegativeInfinity;
  252. var maxDuration = invalidDuration;
  253. var supportsLoop = false;
  254. foreach (var director in directors)
  255. {
  256. if (director.playableAsset != null)
  257. {
  258. var assetDuration = director.playableAsset.duration;
  259. if (director.playableAsset is TimelineAsset && assetDuration > 0.0)
  260. // Timeline assets report being one tick shorter than they actually are, unless they are empty
  261. assetDuration = (double)((DiscreteTime)assetDuration).OneTickAfter();
  262. maxDuration = Math.Max(maxDuration, assetDuration);
  263. supportsLoop = supportsLoop || director.extrapolationMode == DirectorWrapMode.Loop;
  264. }
  265. }
  266. foreach (var particleSystem in particleSystems)
  267. {
  268. maxDuration = Math.Max(maxDuration, particleSystem.main.duration);
  269. supportsLoop = supportsLoop || particleSystem.main.loop;
  270. }
  271. m_Duration = double.IsNegativeInfinity(maxDuration) ? PlayableBinding.DefaultDuration : maxDuration;
  272. m_SupportLoop = supportsLoop;
  273. }
  274. IList<ParticleSystem> GetControllableParticleSystems(GameObject go)
  275. {
  276. var roots = new List<ParticleSystem>();
  277. // searchHierarchy will look for particle systems on child objects.
  278. // once a particle system is found, all child particle systems are controlled with playables
  279. // unless they are subemitters
  280. if (searchHierarchy || go.GetComponent<ParticleSystem>() != null)
  281. {
  282. GetControllableParticleSystems(go.transform, roots, s_SubEmitterCollector);
  283. s_SubEmitterCollector.Clear();
  284. }
  285. return roots;
  286. }
  287. static void GetControllableParticleSystems(Transform t, ICollection<ParticleSystem> roots, HashSet<ParticleSystem> subEmitters)
  288. {
  289. var ps = t.GetComponent<ParticleSystem>();
  290. if (ps != null)
  291. {
  292. if (!subEmitters.Contains(ps))
  293. {
  294. roots.Add(ps);
  295. CacheSubEmitters(ps, subEmitters);
  296. }
  297. }
  298. for (int i = 0; i < t.childCount; ++i)
  299. {
  300. GetControllableParticleSystems(t.GetChild(i), roots, subEmitters);
  301. }
  302. }
  303. static void CacheSubEmitters(ParticleSystem ps, HashSet<ParticleSystem> subEmitters)
  304. {
  305. if (ps == null)
  306. return;
  307. for (int i = 0; i < ps.subEmitters.subEmittersCount; i++)
  308. {
  309. subEmitters.Add(ps.subEmitters.GetSubEmitterSystem(i));
  310. // don't call this recursively. subEmitters are only simulated one level deep.
  311. }
  312. }
  313. /// <inheritdoc/>
  314. public void GatherProperties(PlayableDirector director, IPropertyCollector driver)
  315. {
  316. // This method is no longer called by Control Tracks.
  317. if (director == null)
  318. return;
  319. // prevent infinite recursion
  320. if (s_ProcessedDirectors.Contains(director))
  321. return;
  322. s_ProcessedDirectors.Add(director);
  323. var gameObject = sourceGameObject.Resolve(director);
  324. if (gameObject != null)
  325. {
  326. if (updateParticle)// case 1076850 -- drive all emitters, not just roots.
  327. PreviewParticles(driver, gameObject.GetComponentsInChildren<ParticleSystem>(true));
  328. if (active)
  329. PreviewActivation(driver, new[] { gameObject });
  330. if (updateITimeControl)
  331. PreviewTimeControl(driver, director, GetControlableScripts(gameObject));
  332. if (updateDirector)
  333. PreviewDirectors(driver, GetComponent<PlayableDirector>(gameObject));
  334. }
  335. s_ProcessedDirectors.Remove(director);
  336. }
  337. internal static void PreviewParticles(IPropertyCollector driver, IEnumerable<ParticleSystem> particles)
  338. {
  339. foreach (var ps in particles)
  340. {
  341. driver.AddFromName<ParticleSystem>(ps.gameObject, "randomSeed");
  342. driver.AddFromName<ParticleSystem>(ps.gameObject, "autoRandomSeed");
  343. }
  344. }
  345. internal static void PreviewActivation(IPropertyCollector driver, IEnumerable<GameObject> objects)
  346. {
  347. foreach (var gameObject in objects)
  348. driver.AddFromName(gameObject, "m_IsActive");
  349. }
  350. internal static void PreviewTimeControl(IPropertyCollector driver, PlayableDirector director, IEnumerable<MonoBehaviour> scripts)
  351. {
  352. foreach (var script in scripts)
  353. {
  354. var propertyPreview = script as IPropertyPreview;
  355. if (propertyPreview != null)
  356. propertyPreview.GatherProperties(director, driver);
  357. else
  358. driver.AddFromComponent(script.gameObject, script);
  359. }
  360. }
  361. internal static void PreviewDirectors(IPropertyCollector driver, IEnumerable<PlayableDirector> directors)
  362. {
  363. foreach (var childDirector in directors)
  364. {
  365. if (childDirector == null)
  366. continue;
  367. var timeline = childDirector.playableAsset as TimelineAsset;
  368. if (timeline == null)
  369. continue;
  370. timeline.GatherProperties(childDirector, driver);
  371. }
  372. }
  373. }
  374. }