CinemachineBlendListCamera.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. using Cinemachine.Utility;
  2. using System;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. namespace Cinemachine
  6. {
  7. /// <summary>
  8. /// This is a virtual camera "manager" that owns and manages a collection
  9. /// of child Virtual Cameras. When the camera goes live, these child vcams
  10. /// are enabled, one after another, holding each camera for a designated time.
  11. /// Blends between cameras are specified.
  12. /// The last camera is held indefinitely.
  13. /// </summary>
  14. [DocumentationSorting(DocumentationSortingAttribute.Level.UserRef)]
  15. [DisallowMultipleComponent]
  16. #if UNITY_2018_3_OR_NEWER
  17. [ExecuteAlways]
  18. #else
  19. [ExecuteInEditMode]
  20. #endif
  21. [ExcludeFromPreset]
  22. [AddComponentMenu("Cinemachine/CinemachineBlendListCamera")]
  23. [HelpURL(Documentation.BaseURL + "manual/CinemachineBlendListCamera.html")]
  24. public class CinemachineBlendListCamera : CinemachineVirtualCameraBase
  25. {
  26. /// <summary>Default object for the camera children to look at (the aim target),
  27. /// if not specified in a child rig. May be empty</summary>
  28. [Tooltip("Default object for the camera children to look at (the aim target), if not "
  29. + "specified in a child camera. May be empty if all of the children define targets of their own.")]
  30. [NoSaveDuringPlay]
  31. [VcamTargetProperty]
  32. public Transform m_LookAt;
  33. /// <summary>Default object for the camera children wants to move with (the body target),
  34. /// if not specified in a child rig. May be empty</summary>
  35. [Tooltip("Default object for the camera children wants to move with (the body target), "
  36. + "if not specified in a child camera. May be empty if all of the children define targets of their own.")]
  37. [NoSaveDuringPlay]
  38. [VcamTargetProperty]
  39. public Transform m_Follow;
  40. /// <summary>When enabled, the current camera and blend will be indicated in the game window, for debugging</summary>
  41. [Tooltip("When enabled, the current child camera and blend will be indicated in the game window, for debugging")]
  42. public bool m_ShowDebugText;
  43. /// <summary>When enabled, the child vcams will cycle indefinitely instead of just stopping at the last one</summary>
  44. [Tooltip("When enabled, the child vcams will cycle indefinitely instead of just stopping at the last one")]
  45. public bool m_Loop;
  46. /// <summary>Internal API for the editor. Do not use this field</summary>
  47. [SerializeField][HideInInspector][NoSaveDuringPlay]
  48. internal CinemachineVirtualCameraBase[] m_ChildCameras;
  49. /// <summary>This represents a single entry in the instrunction list of the BlendListCamera.</summary>
  50. [Serializable]
  51. public struct Instruction
  52. {
  53. /// <summary>The virtual camera to activate when this instruction becomes active</summary>
  54. [Tooltip("The virtual camera to activate when this instruction becomes active")]
  55. public CinemachineVirtualCameraBase m_VirtualCamera;
  56. /// <summary>How long to wait (in seconds) before activating the next virtual camera in the list (if any)</summary>
  57. [Tooltip("How long to wait (in seconds) before activating the next virtual camera in the list (if any)")]
  58. public float m_Hold;
  59. /// <summary>How to blend to the next virtual camera in the list (if any)</summary>
  60. [CinemachineBlendDefinitionProperty]
  61. [Tooltip("How to blend to the next virtual camera in the list (if any)")]
  62. public CinemachineBlendDefinition m_Blend;
  63. };
  64. /// <summary>The set of instructions associating virtual cameras with states.
  65. /// The set of instructions for enabling child cameras</summary>
  66. [Tooltip("The set of instructions for enabling child cameras.")]
  67. public Instruction[] m_Instructions;
  68. /// <summary>Gets a brief debug description of this virtual camera, for use when displayiong debug info</summary>
  69. public override string Description
  70. {
  71. get
  72. {
  73. // Show the active camera and blend
  74. if (mActiveBlend != null)
  75. return mActiveBlend.Description;
  76. ICinemachineCamera vcam = LiveChild;
  77. if (vcam == null)
  78. return "(none)";
  79. var sb = CinemachineDebug.SBFromPool();
  80. sb.Append("["); sb.Append(vcam.Name); sb.Append("]");
  81. string text = sb.ToString();
  82. CinemachineDebug.ReturnToPool(sb);
  83. return text;
  84. }
  85. }
  86. void Reset()
  87. {
  88. m_LookAt = null;
  89. m_Follow = null;
  90. m_ShowDebugText = false;
  91. m_Loop = false;
  92. m_Instructions = null;
  93. m_ChildCameras = null;
  94. }
  95. /// <summary>Get the current "best" child virtual camera, that would be chosen
  96. /// if the State Driven Camera were active.</summary>
  97. public ICinemachineCamera LiveChild { set; get; }
  98. /// <summary>Check whether the vcam a live child of this camera.</summary>
  99. /// <param name="vcam">The Virtual Camera to check</param>
  100. /// <param name="dominantChildOnly">If truw, will only return true if this vcam is the dominat live child</param>
  101. /// <returns>True if the vcam is currently actively influencing the state of this vcam</returns>
  102. public override bool IsLiveChild(ICinemachineCamera vcam, bool dominantChildOnly = false)
  103. {
  104. return vcam == LiveChild || (mActiveBlend != null && mActiveBlend.Uses(vcam));
  105. }
  106. /// <summary>The State of the current live child</summary>
  107. public override CameraState State { get { return m_State; } }
  108. /// <summary>Get the current LookAt target. Returns parent's LookAt if parent
  109. /// is non-null and no specific LookAt defined for this camera</summary>
  110. override public Transform LookAt
  111. {
  112. get { return ResolveLookAt(m_LookAt); }
  113. set { m_LookAt = value; }
  114. }
  115. /// <summary>Get the current Follow target. Returns parent's Follow if parent
  116. /// is non-null and no specific Follow defined for this camera</summary>
  117. override public Transform Follow
  118. {
  119. get { return ResolveFollow(m_Follow); }
  120. set { m_Follow = value; }
  121. }
  122. /// <summary>This is called to notify the vcam that a target got warped,
  123. /// so that the vcam can update its internal state to make the camera
  124. /// also warp seamlessy.</summary>
  125. /// <param name="target">The object that was warped</param>
  126. /// <param name="positionDelta">The amount the target's position changed</param>
  127. public override void OnTargetObjectWarped(Transform target, Vector3 positionDelta)
  128. {
  129. UpdateListOfChildren();
  130. foreach (var vcam in m_ChildCameras)
  131. vcam.OnTargetObjectWarped(target, positionDelta);
  132. base.OnTargetObjectWarped(target, positionDelta);
  133. }
  134. /// <summary>
  135. /// Force the virtual camera to assume a given position and orientation
  136. /// </summary>
  137. /// <param name="pos">Worldspace pposition to take</param>
  138. /// <param name="rot">Worldspace orientation to take</param>
  139. public override void ForceCameraPosition(Vector3 pos, Quaternion rot)
  140. {
  141. UpdateListOfChildren();
  142. foreach (var vcam in m_ChildCameras)
  143. vcam.ForceCameraPosition(pos, rot);
  144. base.ForceCameraPosition(pos, rot);
  145. }
  146. /// <summary>Notification that this virtual camera is going live.</summary>
  147. /// <param name="fromCam">The camera being deactivated. May be null.</param>
  148. /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param>
  149. /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param>
  150. public override void OnTransitionFromCamera(
  151. ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime)
  152. {
  153. base.OnTransitionFromCamera(fromCam, worldUp, deltaTime);
  154. InvokeOnTransitionInExtensions(fromCam, worldUp, deltaTime);
  155. mActivationTime = CinemachineCore.CurrentTime;
  156. mCurrentInstruction = 0;
  157. LiveChild = null;
  158. mActiveBlend = null;
  159. TransitioningFrom = fromCam;
  160. InternalUpdateCameraState(worldUp, deltaTime);
  161. }
  162. ICinemachineCamera TransitioningFrom { get; set; }
  163. /// <summary>Called by CinemachineCore at designated update time
  164. /// so the vcam can position itself and track its targets. This implementation
  165. /// updates all the children, chooses the best one, and implements any required blending.</summary>
  166. /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param>
  167. /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param>
  168. public override void InternalUpdateCameraState(Vector3 worldUp, float deltaTime)
  169. {
  170. if (!PreviousStateIsValid)
  171. {
  172. mCurrentInstruction = -1;
  173. mActiveBlend = null;
  174. }
  175. UpdateListOfChildren();
  176. AdvanceCurrentInstruction(deltaTime);
  177. CinemachineVirtualCameraBase best = null;
  178. if (mCurrentInstruction >= 0 && mCurrentInstruction < m_Instructions.Length)
  179. best = m_Instructions[mCurrentInstruction].m_VirtualCamera;
  180. if (best != null)
  181. {
  182. if (!best.gameObject.activeInHierarchy)
  183. {
  184. best.gameObject.SetActive(true);
  185. best.UpdateCameraState(worldUp, deltaTime);
  186. }
  187. ICinemachineCamera previousCam = LiveChild;
  188. LiveChild = best;
  189. // Are we transitioning cameras?
  190. if (previousCam != LiveChild && LiveChild != null)
  191. {
  192. // Notify incoming camera of transition
  193. LiveChild.OnTransitionFromCamera(previousCam, worldUp, deltaTime);
  194. // Generate Camera Activation event in the brain if live
  195. CinemachineCore.Instance.GenerateCameraActivationEvent(LiveChild, previousCam);
  196. if (previousCam != null)
  197. {
  198. // Create a blend (will be null if a cut)
  199. mActiveBlend = CreateBlend(
  200. previousCam, LiveChild,
  201. m_Instructions[mCurrentInstruction].m_Blend,
  202. mActiveBlend);
  203. // If cutting, generate a camera cut event if live
  204. if (mActiveBlend == null || !mActiveBlend.Uses(previousCam))
  205. CinemachineCore.Instance.GenerateCameraCutEvent(LiveChild);
  206. }
  207. }
  208. }
  209. // Advance the current blend (if any)
  210. if (mActiveBlend != null)
  211. {
  212. mActiveBlend.TimeInBlend += (deltaTime >= 0) ? deltaTime : mActiveBlend.Duration;
  213. if (mActiveBlend.IsComplete)
  214. mActiveBlend = null;
  215. }
  216. if (mActiveBlend != null)
  217. {
  218. mActiveBlend.UpdateCameraState(worldUp, deltaTime);
  219. m_State = mActiveBlend.State;
  220. }
  221. else if (LiveChild != null)
  222. {
  223. if (TransitioningFrom != null)
  224. LiveChild.OnTransitionFromCamera(TransitioningFrom, worldUp, deltaTime);
  225. m_State = LiveChild.State;
  226. }
  227. TransitioningFrom = null;
  228. InvokePostPipelineStageCallback(
  229. this, CinemachineCore.Stage.Finalize, ref m_State, deltaTime);
  230. PreviousStateIsValid = true;
  231. }
  232. /// <summary>Makes sure the internal child cache is up to date</summary>
  233. protected override void OnEnable()
  234. {
  235. base.OnEnable();
  236. InvalidateListOfChildren();
  237. LiveChild = null;
  238. mActiveBlend = null;
  239. CinemachineDebug.OnGUIHandlers -= OnGuiHandler;
  240. CinemachineDebug.OnGUIHandlers += OnGuiHandler;
  241. }
  242. /// <summary>
  243. /// Uninstall the GUI handler
  244. /// </summary>
  245. protected override void OnDisable()
  246. {
  247. base.OnDisable();
  248. CinemachineDebug.OnGUIHandlers -= OnGuiHandler;
  249. }
  250. /// <summary>Makes sure the internal child cache is up to date</summary>
  251. void OnTransformChildrenChanged()
  252. {
  253. InvalidateListOfChildren();
  254. }
  255. /// Will only be called if Unity Editor - never in build
  256. private void OnGuiHandler()
  257. {
  258. if (!m_ShowDebugText)
  259. CinemachineDebug.ReleaseScreenPos(this);
  260. else
  261. {
  262. var sb = CinemachineDebug.SBFromPool();
  263. sb.Append(Name); sb.Append(": "); sb.Append(Description);
  264. string text = sb.ToString();
  265. Rect r = CinemachineDebug.GetScreenPos(this, text, GUI.skin.box);
  266. GUI.Label(r, text, GUI.skin.box);
  267. CinemachineDebug.ReturnToPool(sb);
  268. }
  269. }
  270. CameraState m_State = CameraState.Default;
  271. /// <summary>The list of child cameras. These are just the immediate children in the hierarchy.</summary>
  272. public CinemachineVirtualCameraBase[] ChildCameras { get { UpdateListOfChildren(); return m_ChildCameras; }}
  273. /// <summary>Is there a blend in progress?</summary>
  274. public bool IsBlending { get { return mActiveBlend != null; } }
  275. /// <summary>The time at which the current instruction went live</summary>
  276. float mActivationTime = -1;
  277. int mCurrentInstruction = 0;
  278. private CinemachineBlend mActiveBlend = null;
  279. void InvalidateListOfChildren() { m_ChildCameras = null; LiveChild = null; }
  280. void UpdateListOfChildren()
  281. {
  282. if (m_ChildCameras != null)
  283. return;
  284. List<CinemachineVirtualCameraBase> list = new List<CinemachineVirtualCameraBase>();
  285. CinemachineVirtualCameraBase[] kids = GetComponentsInChildren<CinemachineVirtualCameraBase>(true);
  286. foreach (CinemachineVirtualCameraBase k in kids)
  287. if (k.transform.parent == transform)
  288. list.Add(k);
  289. m_ChildCameras = list.ToArray();
  290. ValidateInstructions();
  291. }
  292. /// <summary>Internal API for the inspector editor.</summary>
  293. /// // GML todo: make this private, part of UpdateListOfChildren()
  294. internal void ValidateInstructions()
  295. {
  296. if (m_Instructions == null)
  297. m_Instructions = new Instruction[0];
  298. for (int i = 0; i < m_Instructions.Length; ++i)
  299. {
  300. if (m_Instructions[i].m_VirtualCamera != null
  301. && m_Instructions[i].m_VirtualCamera.transform.parent != transform)
  302. {
  303. m_Instructions[i].m_VirtualCamera = null;
  304. }
  305. }
  306. mActiveBlend = null;
  307. }
  308. private void AdvanceCurrentInstruction(float deltaTime)
  309. {
  310. if (m_ChildCameras == null || m_ChildCameras.Length == 0
  311. || mActivationTime < 0 || m_Instructions.Length == 0)
  312. {
  313. mActivationTime = -1;
  314. mCurrentInstruction = -1;
  315. mActiveBlend = null;
  316. return;
  317. }
  318. float now = CinemachineCore.CurrentTime;
  319. if (mCurrentInstruction < 0 || deltaTime < 0)
  320. {
  321. mActivationTime = now;
  322. mCurrentInstruction = 0;
  323. }
  324. if (mCurrentInstruction > m_Instructions.Length - 1)
  325. {
  326. mActivationTime = now;
  327. mCurrentInstruction = m_Instructions.Length - 1;
  328. }
  329. var holdTime = m_Instructions[mCurrentInstruction].m_Hold
  330. + m_Instructions[mCurrentInstruction].m_Blend.BlendTime;
  331. var minHold = mCurrentInstruction < m_Instructions.Length - 1 || m_Loop
  332. ? 0 : float.MaxValue;
  333. if (now - mActivationTime > Mathf.Max(minHold, holdTime))
  334. {
  335. mActivationTime = now;
  336. ++mCurrentInstruction;
  337. if (m_Loop && mCurrentInstruction == m_Instructions.Length)
  338. mCurrentInstruction = 0;
  339. }
  340. }
  341. }
  342. }