Açıklama Yok
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

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