diff options
| author | Tom Harley | 2018-09-03 23:34:21 +0100 |
|---|---|---|
| committer | Tom Harley | 2018-09-03 23:36:01 +0100 |
| commit | 5440734d820606b29a795c46172ade5d7eba8efb (patch) | |
| tree | 85867f40afb02cfa2a5028b515ed0a195866b7e9 /Assets/Cinemachine/Base/Runtime/Behaviours | |
| download | powerless-5440734d820606b29a795c46172ade5d7eba8efb.tar.gz powerless-5440734d820606b29a795c46172ade5d7eba8efb.zip | |
Initial commit
Diffstat (limited to 'Assets/Cinemachine/Base/Runtime/Behaviours')
34 files changed, 5517 insertions, 0 deletions
diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBlendListCamera.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBlendListCamera.cs new file mode 100644 index 0000000..b380bfa --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBlendListCamera.cs @@ -0,0 +1,341 @@ +using Cinemachine.Utility; +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Cinemachine +{ + /// <summary> + /// This is a virtual camera "manager" that owns and manages a collection + /// of child Virtual Cameras. When the camera goes live, these child vcams + /// are enabled, one after another, holding each camera for a designated time. + /// Blends between cameras are specified. + /// The last camera is held indefinitely. + /// </summary> + [DocumentationSorting(13, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineBlendListCamera")] + public class CinemachineBlendListCamera : CinemachineVirtualCameraBase + { + /// <summary>Default object for the camera children to look at (the aim target), if not specified in a child rig. May be empty</summary> + [Tooltip("Default object for the camera children to look at (the aim target), if not specified in a child camera. May be empty if all of the children define targets of their own.")] + [NoSaveDuringPlay] + public Transform m_LookAt = null; + + /// <summary>Default object for the camera children wants to move with (the body target), if not specified in a child rig. May be empty</summary> + [Tooltip("Default object for the camera children wants to move with (the body target), if not specified in a child camera. May be empty if all of the children define targets of their own.")] + [NoSaveDuringPlay] + public Transform m_Follow = null; + + /// <summary>When enabled, the current camera and blend will be indicated in the game window, for debugging</summary> + [Tooltip("When enabled, the current child camera and blend will be indicated in the game window, for debugging")] + public bool m_ShowDebugText = false; + + /// <summary>Force all child cameras to be enabled. This is useful if animating them in Timeline, but consumes extra resources.</summary> + [Tooltip("Force all child cameras to be enabled. This is useful if animating them in Timeline, but consumes extra resources")] + public bool m_EnableAllChildCameras; + + /// <summary>Internal API for the editor. Do not use this field</summary> + [SerializeField][HideInInspector][NoSaveDuringPlay] + public CinemachineVirtualCameraBase[] m_ChildCameras = null; + + /// <summary>This represents a single entry in the instrunction list of the BlendListCamera.</summary> + [Serializable] + public struct Instruction + { + /// <summary>The virtual camera to activate when this instruction becomes active</summary> + [Tooltip("The virtual camera to activate when this instruction becomes active")] + public CinemachineVirtualCameraBase m_VirtualCamera; + /// <summary>How long to wait (in seconds) before activating the next virtual camera in the list (if any)</summary> + [Tooltip("How long to wait (in seconds) before activating the next virtual camera in the list (if any)")] + public float m_Hold; + /// <summary>How to blend to the next virtual camera in the list (if any)</summary> + [CinemachineBlendDefinitionProperty] + [Tooltip("How to blend to the next virtual camera in the list (if any)")] + public CinemachineBlendDefinition m_Blend; + }; + + /// <summary>The set of instructions associating virtual cameras with states. + /// The set of instructions for enabling child cameras</summary> + [Tooltip("The set of instructions for enabling child cameras.")] + public Instruction[] m_Instructions; + + /// <summary>Gets a brief debug description of this virtual camera, for use when displayiong debug info</summary> + public override string Description + { + get + { + // Show the active camera and blend + ICinemachineCamera vcam = LiveChild; + if (mActiveBlend == null) + return (vcam != null) ? "[" + vcam.Name + "]": "(none)"; + return mActiveBlend.Description; + } + } + + /// <summary>Get the current "best" child virtual camera, that would be chosen + /// if the State Driven Camera were active.</summary> + public ICinemachineCamera LiveChild { set; get; } + + /// <summary>Return the live child.</summary> + public override ICinemachineCamera LiveChildOrSelf { get { return LiveChild; } } + + /// <summary>Check whether the vcam a live child of this camera.</summary> + /// <param name="vcam">The Virtual Camera to check</param> + /// <returns>True if the vcam is currently actively influencing the state of this vcam</returns> + public override bool IsLiveChild(ICinemachineCamera vcam) + { + return vcam == LiveChild + || (mActiveBlend != null && (vcam == mActiveBlend.CamA || vcam == mActiveBlend.CamB)); + } + + /// <summary>The State of the current live child</summary> + public override CameraState State { get { return m_State; } } + + /// <summary>Get the current LookAt target. Returns parent's LookAt if parent + /// is non-null and no specific LookAt defined for this camera</summary> + override public Transform LookAt + { + get { return ResolveLookAt(m_LookAt); } + set { m_LookAt = value; } + } + + /// <summary>Get the current Follow target. Returns parent's Follow if parent + /// is non-null and no specific Follow defined for this camera</summary> + override public Transform Follow + { + get { return ResolveFollow(m_Follow); } + set { m_Follow = value; } + } + + /// <summary>Remove a Pipeline stage hook callback. + /// Make sure it is removed from all the children.</summary> + /// <param name="d">The delegate to remove.</param> + public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + base.RemovePostPipelineStageHook(d); + UpdateListOfChildren(); + foreach (var vcam in m_ChildCameras) + vcam.RemovePostPipelineStageHook(d); + } + + /// <summary>Notification that this virtual camera is going live. + /// <param name="fromCam">The camera being deactivated. May be null.</param> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param> + public override void OnTransitionFromCamera( + ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime) + { + base.OnTransitionFromCamera(fromCam, worldUp, deltaTime); + mActivationTime = Time.time; + mCurrentInstruction = -1; + LiveChild = null; + mActiveBlend = null; + UpdateCameraState(worldUp, deltaTime); + } + + /// <summary>Called by CinemachineCore at designated update time + /// so the vcam can position itself and track its targets. This implementation + /// updates all the children, chooses the best one, and implements any required blending.</summary> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param> + public override void UpdateCameraState(Vector3 worldUp, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineBlendListCamera.UpdateCameraState"); + if (!PreviousStateIsValid) + deltaTime = -1; + + UpdateListOfChildren(); + + AdvanceCurrentInstruction(); + CinemachineVirtualCameraBase best = null; + if (mCurrentInstruction >= 0 && mCurrentInstruction < m_Instructions.Length) + best = m_Instructions[mCurrentInstruction].m_VirtualCamera; + + if (m_ChildCameras != null) + { + for (int i = 0; i < m_ChildCameras.Length; ++i) + { + CinemachineVirtualCameraBase vcam = m_ChildCameras[i]; + if (vcam != null) + { + bool enableChild = m_EnableAllChildCameras || vcam == best; + if (enableChild != vcam.VirtualCameraGameObject.activeInHierarchy) + { + vcam.gameObject.SetActive(enableChild); + if (enableChild) + CinemachineCore.Instance.UpdateVirtualCamera(vcam, worldUp, deltaTime); + } + } + } + } + + if (best != null) + { + ICinemachineCamera previousCam = LiveChild; + LiveChild = best; + + // Are we transitioning cameras? + if (previousCam != null && LiveChild != null && previousCam != LiveChild && mCurrentInstruction > 0) + { + // Create a blend (will be null if a cut) + mActiveBlend = CreateBlend( + previousCam, LiveChild, + m_Instructions[mCurrentInstruction].m_Blend.BlendCurve, + m_Instructions[mCurrentInstruction].m_Blend.m_Time, mActiveBlend, deltaTime); + + // Notify incoming camera of transition + LiveChild.OnTransitionFromCamera(previousCam, worldUp, deltaTime); + + // Generate Camera Activation event if live + CinemachineCore.Instance.GenerateCameraActivationEvent(LiveChild); + + // If cutting, generate a camera cut event if live + if (mActiveBlend == null) + CinemachineCore.Instance.GenerateCameraCutEvent(LiveChild); + } + } + + // Advance the current blend (if any) + if (mActiveBlend != null) + { + mActiveBlend.TimeInBlend += (deltaTime >= 0) ? deltaTime : mActiveBlend.Duration; + if (mActiveBlend.IsComplete) + mActiveBlend = null; + } + + if (mActiveBlend != null) + { + mActiveBlend.UpdateCameraState(worldUp, deltaTime); + m_State = mActiveBlend.State; + } + else if (LiveChild != null) + m_State = LiveChild.State; + + PreviousStateIsValid = true; + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// <summary>Makes sure the internal child cache is up to date</summary> + protected override void OnEnable() + { + base.OnEnable(); + InvalidateListOfChildren(); + mActiveBlend = null; + } + + /// <summary>Makes sure the internal child cache is up to date</summary> + public void OnTransformChildrenChanged() + { + InvalidateListOfChildren(); + } + +#if UNITY_EDITOR + /// <summary>Displays the current active camera on the game screen, if requested</summary> + protected override void OnGUI() + { + base.OnGUI(); + if (!m_ShowDebugText) + CinemachineGameWindowDebug.ReleaseScreenPos(this); + else + { + string text = Name + ": " + Description; + Rect r = CinemachineGameWindowDebug.GetScreenPos(this, text, GUI.skin.box); + GUI.Label(r, text, GUI.skin.box); + } + } +#endif + CameraState m_State = CameraState.Default; + + /// <summary>The list of child cameras. These are just the immediate children in the hierarchy.</summary> + public CinemachineVirtualCameraBase[] ChildCameras { get { UpdateListOfChildren(); return m_ChildCameras; }} + + /// <summary>Is there a blend in progress?</summary> + public bool IsBlending { get { return mActiveBlend != null; } } + + /// <summary>The time at which the current instruction went live</summary> + float mActivationTime = -1; + int mCurrentInstruction = 0; + private CinemachineBlend mActiveBlend = null; + + void InvalidateListOfChildren() { m_ChildCameras = null; LiveChild = null; } + + void UpdateListOfChildren() + { + if (m_ChildCameras != null) + return; + List<CinemachineVirtualCameraBase> list = new List<CinemachineVirtualCameraBase>(); + CinemachineVirtualCameraBase[] kids = GetComponentsInChildren<CinemachineVirtualCameraBase>(true); + foreach (CinemachineVirtualCameraBase k in kids) + if (k.transform.parent == transform) + list.Add(k); + m_ChildCameras = list.ToArray(); + ValidateInstructions(); + } + + /// <summary>Internal API for the inspector editor.</summary> + /// // GML todo: make this private, part of UpdateListOfChildren() + public void ValidateInstructions() + { + if (m_Instructions == null) + m_Instructions = new Instruction[0]; + for (int i = 0; i < m_Instructions.Length; ++i) + { + if (m_Instructions[i].m_VirtualCamera != null + && m_Instructions[i].m_VirtualCamera.transform.parent != transform) + { + m_Instructions[i].m_VirtualCamera = null; + } + } + mActiveBlend = null; + } + + private void AdvanceCurrentInstruction() + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineBlendListCamera.AdvanceCurrentInstruction"); + if (m_ChildCameras == null || m_ChildCameras.Length == 0 + || mActivationTime < 0 || m_Instructions.Length == 0) + { + mActivationTime = -1; + mCurrentInstruction = -1; + mActiveBlend = null; + } + else if (mCurrentInstruction >= m_Instructions.Length - 1) + { + mCurrentInstruction = m_Instructions.Length - 1; + } + else + { + float now = Time.time; + if (mCurrentInstruction < 0) + { + mActivationTime = now; + mCurrentInstruction = 0; + } + else if (now - mActivationTime > Mathf.Max(0, m_Instructions[mCurrentInstruction].m_Hold)) + { + mActivationTime = now; + ++mCurrentInstruction; + } + } + //UnityEngine.Profiling.Profiler.EndSample(); + } + + private CinemachineBlend CreateBlend( + ICinemachineCamera camA, ICinemachineCamera camB, + AnimationCurve blendCurve, float duration, + CinemachineBlend activeBlend, float deltaTime) + { + if (blendCurve == null || duration <= 0 || (camA == null && camB == null)) + return null; + + if (camA == null || activeBlend != null) + { + // Blend from the current camera position + CameraState state = (activeBlend != null) ? activeBlend.State : State; + camA = new StaticPointVirtualCamera(state, (activeBlend != null) ? "Mid-blend" : "(none)"); + } + return new CinemachineBlend(camA, camB, blendCurve,duration, 0); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBlendListCamera.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBlendListCamera.cs.meta new file mode 100644 index 0000000..6f0c492 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBlendListCamera.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: 53258ad9ad6e71e48bb8643c9522112e +timeCreated: 1509546373 +licenseType: Store +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBrain.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBrain.cs new file mode 100644 index 0000000..cb88160 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBrain.cs @@ -0,0 +1,831 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using Cinemachine.Utility; +using UnityEngine.Events; +using System.Collections; + +namespace Cinemachine +{ + /// <summary> + /// CinemachineBrain is the link between the Unity Camera and the Cinemachine Virtual + /// Cameras in the scene. It monitors the priority stack to choose the current + /// Virtual Camera, and blend with another if necessary. Finally and most importantly, + /// it applies the Virtual Camera state to the attached Unity Camera. + /// + /// The CinemachineBrain is also the place where rules for blending between virtual cameras + /// are defined. Camera blending is an interpolation over time of one virtual camera + /// position and state to another. If you think of virtual cameras as cameramen, then + /// blending is a little like one cameraman smoothly passing the camera to another cameraman. + /// You can specify the time over which to blend, as well as the blend curve shape. + /// Note that a camera cut is just a zero-time blend. + /// </summary> + [DocumentationSorting(0, DocumentationSortingAttribute.Level.UserRef)] +// [RequireComponent(typeof(Camera))] // strange but true: we can live without it + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineBrain")] + [SaveDuringPlay] + public class CinemachineBrain : MonoBehaviour + { + /// <summary> + /// When enabled, the current camera and blend will be indicated in the game window, for debugging. + /// </summary> + [Tooltip("When enabled, the current camera and blend will be indicated in the game window, for debugging")] + public bool m_ShowDebugText = false; + + /// <summary> + /// When enabled, shows the camera's frustum in the scene view. + /// </summary> + [Tooltip("When enabled, the camera's frustum will be shown at all times in the scene view")] + public bool m_ShowCameraFrustum = true; + + /// <summary> + /// When enabled, the cameras will always respond in real-time to user input and damping, + /// even if the game is running in slow motion + /// </summary> + [Tooltip("When enabled, the cameras will always respond in real-time to user input and damping, even if the game is running in slow motion")] + public bool m_IgnoreTimeScale = false; + + /// <summary> + /// If set, this object's Y axis will define the worldspace Up vector for all the + /// virtual cameras. This is useful in top-down game environments. If not set, Up is worldspace Y. + /// </summary> + [Tooltip("If set, this object's Y axis will define the worldspace Up vector for all the virtual cameras. This is useful for instance in top-down game environments. If not set, Up is worldspace Y. Setting this appropriately is important, because Virtual Cameras don't like looking straight up or straight down.")] + public Transform m_WorldUpOverride; + + /// <summary>This enum defines the options available for the update method.</summary> + [DocumentationSorting(0.1f, DocumentationSortingAttribute.Level.UserRef)] + public enum UpdateMethod + { + /// <summary>Virtual cameras are updated in sync with the Physics module, in FixedUpdate</summary> + FixedUpdate, + /// <summary>Virtual cameras are updated in MonoBehaviour LateUpdate.</summary> + LateUpdate, + /// <summary>Virtual cameras are updated according to how the target is updated.</summary> + SmartUpdate + }; + + /// <summary>Depending on how the target objects are animated, adjust the update method to + /// minimize the potential jitter. Use FixedUpdate if all your targets are animated with for RigidBody animation. + /// SmartUpdate will choose the best method for each virtual camera, depending + /// on how the target is animated.</summary> + [Tooltip("Use FixedUpdate if all your targets are animated during FixedUpdate (e.g. RigidBodies), LateUpdate if all your targets are animated during the normal Update loop, and SmartUpdate if you want Cinemachine to do the appropriate thing on a per-target basis. SmartUpdate is the recommended setting")] + public UpdateMethod m_UpdateMethod = UpdateMethod.SmartUpdate; + + /// <summary> + /// The blend which is used if you don't explicitly define a blend between two Virtual Cameras. + /// </summary> + [CinemachineBlendDefinitionProperty] + [Tooltip("The blend that is used in cases where you haven't explicitly defined a blend between two Virtual Cameras")] + public CinemachineBlendDefinition m_DefaultBlend + = new CinemachineBlendDefinition(CinemachineBlendDefinition.Style.EaseInOut, 2f); + + /// <summary> + /// This is the asset which contains custom settings for specific blends. + /// </summary> + [Tooltip("This is the asset that contains custom settings for blends between specific virtual cameras in your scene")] + public CinemachineBlenderSettings m_CustomBlends = null; + + /// <summary> + /// Get the Unity Camera that is attached to this GameObject. This is the camera + /// that will be controlled by the brain. + /// </summary> + public Camera OutputCamera + { + get + { + if (m_OutputCamera == null) + m_OutputCamera = GetComponent<Camera>(); + return m_OutputCamera; + } + } + private Camera m_OutputCamera = null; // never use directly - use accessor + + /// <summary>Event with a CinemachineBrain parameter</summary> + [Serializable] public class BrainEvent : UnityEvent<CinemachineBrain> {} + + /// <summary>Event with a ICinemachineCamera parameter</summary> + [Serializable] public class VcamEvent : UnityEvent<ICinemachineCamera> {} + + /// <summary>This event will fire whenever a virtual camera goes live and there is no blend</summary> + [Tooltip("This event will fire whenever a virtual camera goes live and there is no blend")] + public BrainEvent m_CameraCutEvent = new BrainEvent(); + + /// <summary>This event will fire whenever a virtual camera goes live. If a blend is involved, + /// then the event will fire on the first frame of the blend</summary> + [Tooltip("This event will fire whenever a virtual camera goes live. If a blend is involved, then the event will fire on the first frame of the blend.")] + public VcamEvent m_CameraActivatedEvent = new VcamEvent(); + + /// <summary>Support for opaque post-processing module</summary> + internal Component PostProcessingComponent { get; set; } + + /// <summary> + /// Because the PostProcessing package is not guaranteed to be present, + /// we must handle PostFX in this opaque way. This delegate will be called + /// every frame (during LateUpdate) after the camera has been positioned. + /// The intention is that the callback will make the right calls to the PostProcessing module. + /// Cinemachine provides the CinemachinePostFX behaviour that makes use of this delegate. + /// </summary> + internal static BrainEvent sPostProcessingHandler = new BrainEvent(); + + /// <summary> + /// API for the Unity Editor. + /// Show this camera no matter what. This is static, and so affects all Cinemachine brains. + /// </summary> + public static ICinemachineCamera SoloCamera { get; set; } + + /// <summary>API for the Unity Editor.</summary> + /// <returns>Color used to indicate that a camera is in Solo mode.</returns> + public static Color GetSoloGUIColor() { return Color.Lerp(Color.red, Color.yellow, 0.8f); } + + /// <summary>Get the default world up for the virtual cameras.</summary> + public Vector3 DefaultWorldUp + { get { return (m_WorldUpOverride != null) ? m_WorldUpOverride.transform.up : Vector3.up; } } + + private ICinemachineCamera mActiveCameraPreviousFrame; + private ICinemachineCamera mOutgoingCameraPreviousFrame; + private CinemachineBlend mActiveBlend = null; + private bool mPreviousFrameWasOverride = false; + + private class OverrideStackFrame + { + public int id; + public ICinemachineCamera camera; + public CinemachineBlend blend; + public float deltaTime; + public float timeOfOverride; + public bool Active { get { return camera != null; } } + public bool Expired + { + get + { + return !Application.isPlaying + && Time.realtimeSinceStartup - timeOfOverride > Time.maximumDeltaTime; + } + } + } + private List<OverrideStackFrame> mOverrideStack = new List<OverrideStackFrame>(); + private int mNextOverrideId = 1; + + /// Get the override if it's present, else insert it + private OverrideStackFrame GetOverrideFrame(int id) + { + int count = mOverrideStack.Count; + for (int i = 0; i < count; ++i) + if (mOverrideStack[i].id == id) + return mOverrideStack[i]; + OverrideStackFrame ovr = new OverrideStackFrame(); + ovr.id = id; + mOverrideStack.Insert(0, ovr); + return ovr; + } + + /// Get the next active blend on the stack. Used when an override blends in from nothing. + private OverrideStackFrame mOverrideBlendFromNothing = new OverrideStackFrame(); + private OverrideStackFrame GetNextActiveFrame(int overrideId) + { + bool pastMine = false; + int count = mOverrideStack.Count; + for (int i = 0; i < count; ++i) + { + if (mOverrideStack[i].id == overrideId) + pastMine = true; + else if (mOverrideStack[i].Active && pastMine) + return mOverrideStack[i]; + } + // Create a frame representing the non-override state (gameplay) + mOverrideBlendFromNothing.camera = TopCameraFromPriorityQueue(); + mOverrideBlendFromNothing.blend = mActiveBlend; + return mOverrideBlendFromNothing; + } + + /// Get the first override that has a camera + private OverrideStackFrame GetActiveOverride() + { + int count = mOverrideStack.Count; + for (int i = 0; i < count; ++i) + if (mOverrideStack[i].Active) + return mOverrideStack[i]; + return null; + } + + /// <summary> + /// This API is specifically for Timeline. Do not use it. + /// Override the current camera and current blend. This setting will trump + /// any in-game logic that sets virtual camera priorities and Enabled states. + /// This is the main API for the timeline. + /// </summary> + /// <param name="overrideId">Id to represent a specific client. An internal + /// stack is maintained, with the most recent non-empty override taking precenence. + /// This id must be > 0. If you pass -1, a new id will be created, and returned. + /// Use that id for subsequent calls. Don't forget to + /// call ReleaseCameraOverride after all overriding is finished, to + /// free the OverideStack resources.</param> + /// <param name="camA"> The camera to set, corresponding to weight=0</param> + /// <param name="camB"> The camera to set, corresponding to weight=1</param> + /// <param name="weightB">The blend weight. 0=camA, 1=camB</param> + /// <param name="deltaTime">override for deltaTime. Should be Time.FixedDelta for + /// time-based calculations to be included, -1 otherwise</param> + /// <returns>The oiverride ID. Don't forget to call ReleaseCameraOverride + /// after all overriding is finished, to free the OverideStack resources.</returns> + internal int SetCameraOverride( + int overrideId, + ICinemachineCamera camA, ICinemachineCamera camB, + float weightB, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineBrain.SetCameraOverride"); + if (overrideId < 0) + overrideId = mNextOverrideId++; + + OverrideStackFrame ovr = GetOverrideFrame(overrideId); + ovr.camera = null; + ovr.deltaTime = deltaTime; + ovr.timeOfOverride = Time.realtimeSinceStartup; + if (camA != null || camB != null) + { + if (weightB <= Utility.UnityVectorExtensions.Epsilon) + { + ovr.blend = null; + if (camA != null) + ovr.camera = camA; // no blend + } + else if (weightB >= (1f - Utility.UnityVectorExtensions.Epsilon)) + { + ovr.blend = null; + if (camB != null) + ovr.camera = camB; // no blend + } + else + { + // We have a blend. If one of the supplied cameras is null, + // we use the current active virtual camera (blending in/out of game logic), + // If we do have a null camera, make sure it's the 'from' camera. + // Timeline does not distinguish between from and to cams, but we do. + if (camB == null) + { + // Swap them + ICinemachineCamera c = camB; + camB = camA; + camA = c; + weightB = 1f - weightB; + } + + // Are we blending with something in progress? + if (camA == null) + { + OverrideStackFrame frame = GetNextActiveFrame(overrideId); + if (frame.blend != null) + camA = new BlendSourceVirtualCamera(frame.blend, deltaTime); + else + camA = frame.camera != null ? frame.camera : camB; + } + + // Create the override blend + if (ovr.blend == null) + ovr.blend = new CinemachineBlend( + camA, camB, AnimationCurve.Linear(0, 0, 1, 1), 1, weightB); + ovr.blend.CamA = camA; + ovr.blend.CamB = camB; + ovr.blend.TimeInBlend = weightB; + ovr.camera = camB; + } + } + //UnityEngine.Profiling.Profiler.EndSample(); + return overrideId; + } + + /// <summary> + /// This API is specifically for Timeline. Do not use it. + /// Release the resources used for a camera override client. + /// See SetCameraOverride. + /// </summary> + /// <param name="overrideId">The ID to released. This is the value that + /// was returned by SetCameraOverride</param> + internal void ReleaseCameraOverride(int overrideId) + { + int count = mOverrideStack.Count; + for (int i = 0; i < count; ++i) + { + if (mOverrideStack[i].id == overrideId) + { + mOverrideStack.RemoveAt(i); + return; + } + } + } + + private void OnEnable() + { + mActiveBlend = null; + mActiveCameraPreviousFrame = null; + mOutgoingCameraPreviousFrame = null; + mPreviousFrameWasOverride = false; + CinemachineCore.Instance.AddActiveBrain(this); + } + + private void OnDisable() + { + CinemachineCore.Instance.RemoveActiveBrain(this); + mActiveBlend = null; + mActiveCameraPreviousFrame = null; + mOutgoingCameraPreviousFrame = null; + mPreviousFrameWasOverride = false; + mOverrideStack.Clear(); + } + + private void Start() + { + UpdateVirtualCameras(CinemachineCore.UpdateFilter.Late, -1f); + + // We check in after the physics system has had a chance to move things + StartCoroutine(AfterPhysics()); + } + +#if UNITY_EDITOR + private void OnGUI() + { + if (!m_ShowDebugText) + CinemachineGameWindowDebug.ReleaseScreenPos(this); + else + { + // Show the active camera and blend + Color color = GUI.color; + ICinemachineCamera vcam = ActiveVirtualCamera; + string text = "CM " + gameObject.name + ": "; + if (SoloCamera != null) + { + text += "SOLO "; + GUI.color = GetSoloGUIColor(); + } + if (ActiveBlend == null) + text += (vcam != null ? "[" + vcam.Name + "]" : "(none)"); + else + text += ActiveBlend.Description; + Rect r = CinemachineGameWindowDebug.GetScreenPos(this, text, GUI.skin.box); + GUI.Label(r, text, GUI.skin.box); + GUI.color = color; + } + } +#endif + + WaitForFixedUpdate mWaitForFixedUpdate = new WaitForFixedUpdate(); + private IEnumerator AfterPhysics() + { + while (true) + { + yield return mWaitForFixedUpdate; + if (m_UpdateMethod == UpdateMethod.SmartUpdate) + { + AddSubframe(); // FixedUpdate can be called multiple times per frame + UpdateVirtualCameras(CinemachineCore.UpdateFilter.Fixed, GetEffectiveDeltaTime(true)); + } + else + { + if (m_UpdateMethod == UpdateMethod.LateUpdate) + msSubframes = 1; + else + { + AddSubframe(); // FixedUpdate can be called multiple times per frame + UpdateVirtualCameras(CinemachineCore.UpdateFilter.ForcedFixed, GetEffectiveDeltaTime(true)); + } + } + } + } + + private void LateUpdate() + { + float deltaTime = GetEffectiveDeltaTime(false); + if (m_UpdateMethod == UpdateMethod.SmartUpdate) + UpdateVirtualCameras(CinemachineCore.UpdateFilter.Late, deltaTime); + else if (m_UpdateMethod == UpdateMethod.LateUpdate) + UpdateVirtualCameras(CinemachineCore.UpdateFilter.ForcedLate, deltaTime); + + // Choose the active vcam and apply it to the Unity camera + ProcessActiveCamera(GetEffectiveDeltaTime(false)); + } + +#if UNITY_EDITOR + /// This is only needed in editor mode to force timeline to call OnGUI while + /// timeline is up and the game is not running, in order to allow dragging + /// the composer guide in the game view. + private void OnPreCull() + { + if (!Application.isPlaying) + { + // Note: this call will cause any screen canvas attached to the camera + // to be painted one frame out of sync. It will only happen in the editor when not playing. + float deltaTime = GetEffectiveDeltaTime(false); + msSubframes = 1; + UpdateVirtualCameras(CinemachineCore.UpdateFilter.Late, deltaTime); + ProcessActiveCamera(GetEffectiveDeltaTime(false)); + } + } + +#endif + private float GetEffectiveDeltaTime(bool fixedDelta) + { + if (SoloCamera != null) + return Time.unscaledDeltaTime; + OverrideStackFrame activeOverride = GetActiveOverride(); + if (activeOverride != null) + return activeOverride.Expired ? -1 : activeOverride.deltaTime; + if (!Application.isPlaying) + return -1; + if (m_IgnoreTimeScale) + return fixedDelta ? Time.fixedDeltaTime : Time.unscaledDeltaTime; + return fixedDelta ? Time.fixedDeltaTime * Time.timeScale : Time.deltaTime; + } + + private void UpdateVirtualCameras(CinemachineCore.UpdateFilter updateFilter, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineBrain.UpdateVirtualCameras"); + CinemachineCore.Instance.CurrentUpdateFilter = updateFilter; + + // We always update all active virtual cameras + CinemachineCore.Instance.UpdateAllActiveVirtualCameras(DefaultWorldUp, deltaTime); + + // Make sure that the current live cameras get updated this frame. + // Only cameras that are enabled get automatically updated. + ICinemachineCamera vcam = ActiveVirtualCamera; + if (vcam != null) + CinemachineCore.Instance.UpdateVirtualCamera(vcam, DefaultWorldUp, deltaTime); + CinemachineBlend activeBlend = ActiveBlend; + if (activeBlend != null) + activeBlend.UpdateCameraState(DefaultWorldUp, deltaTime); + + // Restore the filter for general use + CinemachineCore.Instance.CurrentUpdateFilter = CinemachineCore.UpdateFilter.Late; + //UnityEngine.Profiling.Profiler.EndSample(); + } + + private void ProcessActiveCamera(float deltaTime) + { + // This condition should never occur, but let's be defensive + if (!isActiveAndEnabled) + { + mActiveCameraPreviousFrame = null; + mOutgoingCameraPreviousFrame = null; + mPreviousFrameWasOverride = false; + return; + } + + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineBrain.ProcessActiveCamera"); + + OverrideStackFrame activeOverride = GetActiveOverride(); + ICinemachineCamera activeCamera = ActiveVirtualCamera; + if (activeCamera == null) + mOutgoingCameraPreviousFrame = null; + else + { + // If there is an override, we kill the in-game blend + if (activeOverride != null) + mActiveBlend = null; + CinemachineBlend activeBlend = ActiveBlend; + + // Check for unexpected deletion of the cached mActiveCameraPreviousFrame + if (mActiveCameraPreviousFrame != null && mActiveCameraPreviousFrame.VirtualCameraGameObject == null) + mActiveCameraPreviousFrame = null; + + // Are we transitioning cameras? + if (mActiveCameraPreviousFrame != activeCamera) + { + // Do we need to create a game-play blend? + if (mActiveCameraPreviousFrame != null + && !mPreviousFrameWasOverride + && activeOverride == null + && deltaTime >= 0) + { + // Create a blend (will be null if a cut) + float duration = 0; + AnimationCurve curve = LookupBlendCurve( + mActiveCameraPreviousFrame, activeCamera, out duration); + activeBlend = CreateBlend( + mActiveCameraPreviousFrame, activeCamera, + curve, duration, mActiveBlend); + } + // Need this check because Timeline override sometimes inverts outgoing and incoming + if (activeCamera != mOutgoingCameraPreviousFrame) + { + // Notify incoming camera of transition + activeCamera.OnTransitionFromCamera(mActiveCameraPreviousFrame, DefaultWorldUp, deltaTime); + + // If the incoming camera is disabled, then we must assume + // that it has not been updated properly + if (!activeCamera.VirtualCameraGameObject.activeInHierarchy + && (activeBlend == null || !activeBlend.Uses(activeCamera))) + { + activeCamera.UpdateCameraState(DefaultWorldUp, -1); + } + if (m_CameraActivatedEvent != null) + m_CameraActivatedEvent.Invoke(activeCamera); + } + // If we're cutting without a blend, or no active cameras + // were active last frame, send an event + if (activeBlend == null + || (activeBlend.CamA != mActiveCameraPreviousFrame + && activeBlend.CamB != mActiveCameraPreviousFrame + && activeBlend.CamA != mOutgoingCameraPreviousFrame + && activeBlend.CamB != mOutgoingCameraPreviousFrame)) + { + if (m_CameraCutEvent != null) + m_CameraCutEvent.Invoke(this); + } + } + + // Advance the current blend (if any) + if (activeBlend != null) + { + if (activeOverride == null) + activeBlend.TimeInBlend += (deltaTime >= 0) + ? deltaTime : activeBlend.Duration; + if (activeBlend.IsComplete) + activeBlend = null; + } + if (activeOverride == null) + mActiveBlend = activeBlend; + + // Apply the result to the Unity camera + CameraState state = activeCamera.State; + if (activeBlend != null) + state = activeBlend.State; + PushStateToUnityCamera(state, activeCamera); + + mOutgoingCameraPreviousFrame = null; + if (activeBlend != null) + mOutgoingCameraPreviousFrame = activeBlend.CamB; + } + + mActiveCameraPreviousFrame = activeCamera; + mPreviousFrameWasOverride = activeOverride != null; + + if (mPreviousFrameWasOverride) + { + // Hack: Because we don't know whether blending in or out... grrr... + if (activeOverride.blend != null) + { + if (activeOverride.blend.BlendWeight < 0.5f) + { + mActiveCameraPreviousFrame = activeOverride.blend.CamA; + mOutgoingCameraPreviousFrame = activeOverride.blend.CamB; + } + else + { + mActiveCameraPreviousFrame = activeOverride.blend.CamB; + mOutgoingCameraPreviousFrame = activeOverride.blend.CamA; + } + } + } + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// <summary> + /// Is there a blend in progress? + /// </summary> + public bool IsBlending { get { return ActiveBlend != null && ActiveBlend.IsValid; } } + + /// <summary> + /// Get the current blend in progress. Returns null if none. + /// </summary> + public CinemachineBlend ActiveBlend + { + get + { + if (SoloCamera != null) + return null; + OverrideStackFrame ovr = GetActiveOverride(); + return (ovr != null && ovr.blend != null) ? ovr.blend : mActiveBlend; + } + } + + /// <summary> + /// True if the ICinemachineCamera the current active camera, + /// or part of a current blend, either directly or indirectly because its parents are live. + /// </summary> + /// <param name="vcam">The camera to test whether it is live</param> + /// <returns>True if the camera is live (directly or indirectly) + /// or part of a blend in progress.</returns> + public bool IsLive(ICinemachineCamera vcam) + { + if (IsLiveItself(vcam)) + return true; + + ICinemachineCamera parent = vcam.ParentCamera; + while (parent != null && parent.IsLiveChild(vcam)) + { + if (IsLiveItself(parent)) + return true; + vcam = parent; + parent = vcam.ParentCamera; + } + return false; + } + + // True if this vcam (not considering parents) actually live. + private bool IsLiveItself(ICinemachineCamera vcam) + { + if (mActiveCameraPreviousFrame == vcam) + return true; + if (ActiveVirtualCamera == vcam) + return true; + if (IsBlending && ActiveBlend.Uses(vcam)) + return true; + return false; + } + + /// <summary> + /// Get the current active virtual camera. + /// </summary> + public ICinemachineCamera ActiveVirtualCamera + { + get + { + if (SoloCamera != null) + return SoloCamera; + OverrideStackFrame ovr = GetActiveOverride(); + return (ovr != null && ovr.camera != null) + ? ovr.camera : TopCameraFromPriorityQueue(); + } + } + + /// <summary> + /// The current state applied to the unity camera (may be the result of a blend) + /// </summary> + public CameraState CurrentCameraState { get; private set; } + + /// <summary> + /// Get the highest-priority Enabled ICinemachineCamera + /// that is visible to my camera. Culling Mask is used to test visibility. + /// </summary> + private ICinemachineCamera TopCameraFromPriorityQueue() + { + Camera outputCamera = OutputCamera; + int mask = outputCamera == null ? ~0 : outputCamera.cullingMask; + int numCameras = CinemachineCore.Instance.VirtualCameraCount; + for (int i = 0; i < numCameras; ++i) + { + ICinemachineCamera cam = CinemachineCore.Instance.GetVirtualCamera(i); + GameObject go = cam != null ? cam.VirtualCameraGameObject : null; + if (go != null && (mask & (1 << go.layer)) != 0) + return cam; + } + return null; + } + + /// <summary> + /// Create a blend curve for blending from one ICinemachineCamera to another. + /// If there is a specific blend defined for these cameras it will be used, otherwise + /// a default blend will be created, which could be a cut. + /// </summary> + private AnimationCurve LookupBlendCurve( + ICinemachineCamera fromKey, ICinemachineCamera toKey, out float duration) + { + // Get the blend curve that's most appropriate for these cameras + AnimationCurve blendCurve = m_DefaultBlend.BlendCurve; + if (m_CustomBlends != null) + { + string fromCameraName = (fromKey != null) ? fromKey.Name : string.Empty; + string toCameraName = (toKey != null) ? toKey.Name : string.Empty; + blendCurve = m_CustomBlends.GetBlendCurveForVirtualCameras( + fromCameraName, toCameraName, blendCurve); + } + var keys = blendCurve.keys; + duration = (keys == null || keys.Length == 0) ? 0 : keys[keys.Length-1].time; + return blendCurve; + } + + /// <summary> + /// Create a blend from one ICinemachineCamera to another, + /// or to/from a point, if we can't do anything else + /// </summary> + private CinemachineBlend CreateBlend( + ICinemachineCamera camA, ICinemachineCamera camB, + AnimationCurve blendCurve, float duration, + CinemachineBlend activeBlend) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineTrackedDolly.MutateCameraState"); + if (blendCurve == null || duration <= 0 || (camA == null && camB == null)) + { + //UnityEngine.Profiling.Profiler.EndSample(); + return null; + } + if (camA == null || activeBlend != null) + { + // Blend from the current camera position + CameraState state = CameraState.Default; + if (activeBlend != null) + state = activeBlend.State; + else + { + state.RawPosition = transform.position; + state.RawOrientation = transform.rotation; + state.Lens = LensSettings.FromCamera(OutputCamera); + } + camA = new StaticPointVirtualCamera(state, activeBlend == null ? "(none)" : "Mid-blend"); + } + CinemachineBlend blend = new CinemachineBlend(camA, camB, blendCurve, duration, 0); + //UnityEngine.Profiling.Profiler.EndSample(); + return blend; + } + + /// <summary> Apply a cref="CameraState"/> to the game object</summary> + private void PushStateToUnityCamera(CameraState state, ICinemachineCamera vcam) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineBrain.PushStateToUnityCamera"); + CurrentCameraState = state; + transform.position = state.FinalPosition; + transform.rotation = state.FinalOrientation; + Camera cam = OutputCamera; + if (cam != null) + { + cam.fieldOfView = state.Lens.FieldOfView; + cam.orthographicSize = state.Lens.OrthographicSize; + cam.nearClipPlane = state.Lens.NearClipPlane; + cam.farClipPlane = state.Lens.FarClipPlane; + } + if (sPostProcessingHandler != null) + sPostProcessingHandler.Invoke(this); + //UnityEngine.Profiling.Profiler.EndSample(); + } + + static int msCurrentFrame; + static int msFirstBrainObjectId; + static int msSubframes; + void AddSubframe() + { + int now = Time.frameCount; + if (now == msCurrentFrame) + { + if (msFirstBrainObjectId == GetInstanceID()) + ++msSubframes; + } + else + { + msCurrentFrame = now; + msFirstBrainObjectId = GetInstanceID(); + msSubframes = 1; + } + } + + /// <summary>API for CinemachineCore only: Get the number of subframes to + /// update the virtual cameras.</summary> + /// <returns>Number of subframes registered by the first brain's FixedUpdate</returns> + internal static int GetSubframeCount() { return Math.Max(1, msSubframes); } + } + + /// <summary> + /// Point source for blending. It's not really a virtual camera, but takes + /// a CameraState and exposes it as a virtual camera for the purposes of blending. + /// </summary> + internal class StaticPointVirtualCamera : ICinemachineCamera + { + public StaticPointVirtualCamera(CameraState state, string name) { State = state; Name = name; } + public void SetState(CameraState state) { State = state; } + + public string Name { get; private set; } + public string Description { get { return ""; }} + public int Priority { get; set; } + public Transform LookAt { get; set; } + public Transform Follow { get; set; } + public CameraState State { get; private set; } + public GameObject VirtualCameraGameObject { get { return null; } } + public ICinemachineCamera LiveChildOrSelf { get { return this; } } + public ICinemachineCamera ParentCamera { get { return null; } } + public bool IsLiveChild(ICinemachineCamera vcam) { return false; } + public void UpdateCameraState(Vector3 worldUp, float deltaTime) {} + public void OnTransitionFromCamera(ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime) {} + } + + /// <summary> + /// Blend result source for blending. This exposes a CinemachineBlend object + /// as an ersatz virtual camera for the purposes of blending. This achieves the purpose + /// of blending the result oif a blend. + /// </summary> + internal class BlendSourceVirtualCamera : ICinemachineCamera + { + public BlendSourceVirtualCamera(CinemachineBlend blend, float deltaTime) + { + Blend = blend; + UpdateCameraState(blend.CamA.State.ReferenceUp, deltaTime); + } + + public CinemachineBlend Blend { get; private set; } + + public string Name { get { return "Blend"; }} + public string Description { get { return Blend.Description; }} + public int Priority { get; set; } + public Transform LookAt { get; set; } + public Transform Follow { get; set; } + public CameraState State { get; private set; } + public GameObject VirtualCameraGameObject { get { return null; } } + public ICinemachineCamera LiveChildOrSelf { get { return Blend.CamB; } } + public ICinemachineCamera ParentCamera { get { return null; } } + public bool IsLiveChild(ICinemachineCamera vcam) { return vcam == Blend.CamA || vcam == Blend.CamB; } + public CameraState CalculateNewState(float deltaTime) { return State; } + public void UpdateCameraState(Vector3 worldUp, float deltaTime) + { + Blend.UpdateCameraState(worldUp, deltaTime); + State = Blend.State; + } + public void OnTransitionFromCamera(ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime) {} + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBrain.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBrain.cs.meta new file mode 100644 index 0000000..df91cff --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBrain.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 72ece51f2901e7445ab60da3685d6b5f +timeCreated: 1493069520 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 100 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineClearShot.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineClearShot.cs new file mode 100644 index 0000000..814f616 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineClearShot.cs @@ -0,0 +1,432 @@ +using System.Collections.Generic; +using UnityEngine; +using Cinemachine.Utility; + +namespace Cinemachine +{ + /// <summary> + /// Cinemachine ClearShot is a "manager camera" that owns and manages a set of + /// Virtual Camera gameObject children. When Live, the ClearShot will check the + /// children, and choose the one with the best quality shot and make it Live. + /// + /// This can be a very powerful tool. If the child cameras have CinemachineCollider + /// extensions, they will analyze the scene for target obstructions, optimal target + /// distance, and other items, and report their assessment of shot quality back to + /// the ClearShot parent, who will then choose the best one. You can use this to set + /// up complex multi-camera coverage of a scene, and be assured that a clear shot of + /// the target will always be available. + /// + /// If multiple child cameras have the same shot quality, the one with the highest + /// priority will be chosen. + /// + /// You can also define custom blends between the ClearShot children. + /// </summary> + [DocumentationSorting(12, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineClearShot")] + public class CinemachineClearShot : CinemachineVirtualCameraBase + { + /// <summary>Default object for the camera children to look at (the aim target), if not specified in a child camera. May be empty.</summary> + [Tooltip("Default object for the camera children to look at (the aim target), if not specified in a child camera. May be empty if all children specify targets of their own.")] + [NoSaveDuringPlay] + public Transform m_LookAt = null; + + /// <summary>Default object for the camera children wants to move with (the body target), if not specified in a child camera. May be empty.</summary> + [Tooltip("Default object for the camera children wants to move with (the body target), if not specified in a child camera. May be empty if all children specify targets of their own.")] + [NoSaveDuringPlay] + public Transform m_Follow = null; + + /// <summary>When enabled, the current camera and blend will be indicated in the game window, for debugging</summary> + [Tooltip("When enabled, the current child camera and blend will be indicated in the game window, for debugging")] + [NoSaveDuringPlay] + public bool m_ShowDebugText = false; + + /// <summary>Internal API for the editor. Do not use this filed.</summary> + [SerializeField, HideInInspector, NoSaveDuringPlay] + public CinemachineVirtualCameraBase[] m_ChildCameras = null; + + /// <summary>Wait this many seconds before activating a new child camera</summary> + [Tooltip("Wait this many seconds before activating a new child camera")] + public float m_ActivateAfter; + + /// <summary>An active camera must be active for at least this many seconds</summary> + [Tooltip("An active camera must be active for at least this many seconds")] + public float m_MinDuration; + + /// <summary>If checked, camera choice will be randomized if multiple cameras are equally desirable. Otherwise, child list order will be used</summary> + [Tooltip("If checked, camera choice will be randomized if multiple cameras are equally desirable. Otherwise, child list order and child camera priority will be used.")] + public bool m_RandomizeChoice = false; + + /// <summary>The blend which is used if you don't explicitly define a blend between two Virtual Cameras</summary> + [CinemachineBlendDefinitionProperty] + [Tooltip("The blend which is used if you don't explicitly define a blend between two Virtual Cameras")] + public CinemachineBlendDefinition m_DefaultBlend + = new CinemachineBlendDefinition(CinemachineBlendDefinition.Style.Cut, 0); + + /// <summary>This is the asset which contains custom settings for specific blends</summary> + [HideInInspector] + public CinemachineBlenderSettings m_CustomBlends = null; + + /// <summary>Gets a brief debug description of this virtual camera, for use when displayiong debug info</summary> + public override string Description + { + get + { + // Show the active camera and blend + ICinemachineCamera vcam = LiveChild; + if (mActiveBlend == null) + return (vcam != null) ? "[" + vcam.Name + "]" : "(none)"; + return mActiveBlend.Description; + } + } + + /// <summary>Get the current "best" child virtual camera, that would be chosen + /// if the ClearShot camera were active.</summary> + public ICinemachineCamera LiveChild { set; get; } + + /// <summary>The CameraState of the currently live child</summary> + public override CameraState State { get { return m_State; } } + + /// <summary>Return the live child.</summary> + public override ICinemachineCamera LiveChildOrSelf { get { return LiveChild; } } + + /// <summary>Check whether the vcam a live child of this camera.</summary> + /// <param name="vcam">The Virtual Camera to check</param> + /// <returns>True if the vcam is currently actively influencing the state of this vcam</returns> + public override bool IsLiveChild(ICinemachineCamera vcam) + { + return vcam == LiveChild + || (mActiveBlend != null && (vcam == mActiveBlend.CamA || vcam == mActiveBlend.CamB)); + } + + /// <summary>Get the current LookAt target. Returns parent's LookAt if parent + /// is non-null and no specific LookAt defined for this camera</summary> + override public Transform LookAt + { + get { return ResolveLookAt(m_LookAt); } + set { m_LookAt = value; } + } + + /// <summary>Get the current Follow target. Returns parent's Follow if parent + /// is non-null and no specific Follow defined for this camera</summary> + override public Transform Follow + { + get { return ResolveFollow(m_Follow); } + set { m_Follow = value; } + } + + /// <summary>Remove a Pipeline stage hook callback. + /// Make sure it is removed from all the children.</summary> + /// <param name="d">The delegate to remove.</param> + public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + base.RemovePostPipelineStageHook(d); + UpdateListOfChildren(); + foreach (var vcam in m_ChildCameras) + vcam.RemovePostPipelineStageHook(d); + } + + /// <summary>Called by CinemachineCore at designated update time + /// so the vcam can position itself and track its targets. This implementation + /// updates all the children, chooses the best one, and implements any required blending.</summary> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than 0)</param> + public override void UpdateCameraState(Vector3 worldUp, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineClearShot.UpdateCameraState"); + if (!PreviousStateIsValid) + deltaTime = -1; + + // Choose the best camera + UpdateListOfChildren(); + ICinemachineCamera previousCam = LiveChild; + LiveChild = ChooseCurrentCamera(worldUp, deltaTime); + + // Are we transitioning cameras? + if (previousCam != null && LiveChild != null && previousCam != LiveChild) + { + // Create a blend (will be null if a cut) + float duration = 0; + AnimationCurve curve = LookupBlendCurve(previousCam, LiveChild, out duration); + mActiveBlend = CreateBlend( + previousCam, LiveChild, + curve, duration, mActiveBlend, deltaTime); + + // Notify incoming camera of transition + LiveChild.OnTransitionFromCamera(previousCam, worldUp, deltaTime); + + // Generate Camera Activation event if live + CinemachineCore.Instance.GenerateCameraActivationEvent(LiveChild); + + // If cutting, generate a camera cut event if live + if (mActiveBlend == null) + CinemachineCore.Instance.GenerateCameraCutEvent(LiveChild); + } + + // Advance the current blend (if any) + if (mActiveBlend != null) + { + mActiveBlend.TimeInBlend += (deltaTime >= 0) + ? deltaTime : mActiveBlend.Duration; + if (mActiveBlend.IsComplete) + mActiveBlend = null; + } + + if (mActiveBlend != null) + { + mActiveBlend.UpdateCameraState(worldUp, deltaTime); + m_State = mActiveBlend.State; + } + else if (LiveChild != null) + m_State = LiveChild.State; + + PreviousStateIsValid = true; + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// <summary>Makes sure the internal child cache is up to date</summary> + protected override void OnEnable() + { + base.OnEnable(); + InvalidateListOfChildren(); + mActiveBlend = null; + } + + /// <summary>Makes sure the internal child cache is up to date</summary> + public void OnTransformChildrenChanged() + { + InvalidateListOfChildren(); + } + +#if UNITY_EDITOR + /// <summary>Displays the current active camera on the game screen, if requested</summary> + protected override void OnGUI() + { + base.OnGUI(); + if (!m_ShowDebugText) + CinemachineGameWindowDebug.ReleaseScreenPos(this); + else + { + string text = Name + ": " + Description; + Rect r = CinemachineGameWindowDebug.GetScreenPos(this, text, GUI.skin.box); + GUI.Label(r, text, GUI.skin.box); + } + } +#endif + /// <summary>Is there a blend in progress?</summary> + public bool IsBlending { get { return mActiveBlend != null; } } + + CameraState m_State = CameraState.Default; + + /// <summary>The list of child cameras. These are just the immediate children in the hierarchy.</summary> + public CinemachineVirtualCameraBase[] ChildCameras + { + get { UpdateListOfChildren(); return m_ChildCameras; } + } + + float mActivationTime = 0; + float mPendingActivationTime = 0; + ICinemachineCamera mPendingCamera; + private CinemachineBlend mActiveBlend = null; + + void InvalidateListOfChildren() + { + m_ChildCameras = null; + m_RandomizedChilden = null; + LiveChild = null; + } + + /// <summary>If RandomizeChoice is enabled, call this to re-randomize the children next frame. + /// This is useful if you want to freshen up the shot.</summary> + public void ResetRandomization() + { + m_RandomizedChilden = null; + mRandomizeNow = true; + } + + void UpdateListOfChildren() + { + if (m_ChildCameras != null) + return; + + List<CinemachineVirtualCameraBase> list = new List<CinemachineVirtualCameraBase>(); + CinemachineVirtualCameraBase[] kids = GetComponentsInChildren<CinemachineVirtualCameraBase>(true); + foreach (CinemachineVirtualCameraBase k in kids) + if (k.transform.parent == transform) + list.Add(k); + m_ChildCameras = list.ToArray(); + + // Zap the cached current instructions + mActivationTime = mPendingActivationTime = 0; + mPendingCamera = null; + LiveChild = null; + mActiveBlend = null; + } + + private bool mRandomizeNow = false; + private CinemachineVirtualCameraBase[] m_RandomizedChilden = null; + + private ICinemachineCamera ChooseCurrentCamera(Vector3 worldUp, float deltaTime) + { + if (m_ChildCameras == null || m_ChildCameras.Length == 0) + { + mActivationTime = 0; + return null; + } + + CinemachineVirtualCameraBase[] childCameras = m_ChildCameras; + if (!m_RandomizeChoice) + m_RandomizedChilden = null; + else if (m_ChildCameras.Length > 1) + { + if (m_RandomizedChilden == null) + m_RandomizedChilden = Randomize(m_ChildCameras); + childCameras = m_RandomizedChilden; + } + + if (LiveChild != null && !LiveChild.VirtualCameraGameObject.activeSelf) + LiveChild = null; + ICinemachineCamera best = LiveChild; + for (int i = 0; i < childCameras.Length; ++i) + { + CinemachineVirtualCameraBase vcam = childCameras[i]; + if (vcam != null && vcam.VirtualCameraGameObject.activeInHierarchy) + { + // Choose the first in the list that is better than the current + if (best == null + || vcam.State.ShotQuality > best.State.ShotQuality + || (vcam.State.ShotQuality == best.State.ShotQuality && vcam.Priority > best.Priority) + || (m_RandomizeChoice && mRandomizeNow && (ICinemachineCamera)vcam != LiveChild + && vcam.State.ShotQuality == best.State.ShotQuality + && vcam.Priority == best.Priority)) + { + best = vcam; + } + } + } + mRandomizeNow = false; + + float now = Time.time; + if (mActivationTime != 0) + { + // Is it active now? + if (LiveChild == best) + { + // Yes, cancel any pending + mPendingActivationTime = 0; + mPendingCamera = null; + return best; + } + + // Is it pending? + if (deltaTime >= 0) + { + if (mPendingActivationTime != 0 && mPendingCamera == best) + { + // Has it been pending long enough, and are we allowed to switch away + // from the active action? + if ((now - mPendingActivationTime) > m_ActivateAfter + && (now - mActivationTime) > m_MinDuration) + { + // Yes, activate it now + m_RandomizedChilden = null; // reshuffle the children + mActivationTime = now; + mPendingActivationTime = 0; + mPendingCamera = null; + return best; + } + return LiveChild; + } + } + } + // Neither active nor pending. + mPendingActivationTime = 0; // cancel the pending, if any + mPendingCamera = null; + + // Can we activate it now? + if (deltaTime >= 0 && mActivationTime > 0) + { + if (m_ActivateAfter > 0 + || (now - mActivationTime) < m_MinDuration) + { + // Too early - make it pending + mPendingCamera = best; + mPendingActivationTime = now; + return LiveChild; + } + } + // Activate now + m_RandomizedChilden = null; // reshuffle the children + mActivationTime = now; + return best; + } + + struct Pair { public int a; public float b; } + CinemachineVirtualCameraBase[] Randomize(CinemachineVirtualCameraBase[] src) + { + List<Pair> pairs = new List<Pair>(); + for (int i = 0; i < src.Length; ++i) + { + Pair p = new Pair(); p.a = i; p.b = Random.Range(0, 1000f); + pairs.Add(p); + } + pairs.Sort((p1, p2) => (int)p1.b - (int)p2.b); + CinemachineVirtualCameraBase[] dst = new CinemachineVirtualCameraBase[src.Length]; + Pair[] result = pairs.ToArray(); + for (int i = 0; i < src.Length; ++i) + dst[i] = src[result[i].a]; + return dst; + } + + private AnimationCurve LookupBlendCurve( + ICinemachineCamera fromKey, ICinemachineCamera toKey, out float duration) + { + // Get the blend curve that's most appropriate for these cameras + AnimationCurve blendCurve = m_DefaultBlend.BlendCurve; + if (m_CustomBlends != null) + { + string fromCameraName = (fromKey != null) ? fromKey.Name : string.Empty; + string toCameraName = (toKey != null) ? toKey.Name : string.Empty; + blendCurve = m_CustomBlends.GetBlendCurveForVirtualCameras( + fromCameraName, toCameraName, blendCurve); + } + var keys = blendCurve.keys; + duration = (keys == null || keys.Length == 0) ? 0 : keys[keys.Length-1].time; + return blendCurve; + } + + private CinemachineBlend CreateBlend( + ICinemachineCamera camA, ICinemachineCamera camB, + AnimationCurve blendCurve, float duration, + CinemachineBlend activeBlend, float deltaTime) + { + if (blendCurve == null || duration <= 0 || (camA == null && camB == null)) + return null; + + if (camA == null || activeBlend != null) + { + // Blend from the current camera position + CameraState state = (activeBlend != null) ? activeBlend.State : State; + camA = new StaticPointVirtualCamera(state, (activeBlend != null) ? "Mid-blend" : "(none)"); + } + return new CinemachineBlend(camA, camB, blendCurve, duration, 0); + } + + /// <summary>Notification that this virtual camera is going live. + /// This implementation resets the child randomization.</summary> + /// <param name="fromCam">The camera being deactivated. May be null.</param> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param> + public override void OnTransitionFromCamera( + ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime) + { + base.OnTransitionFromCamera(fromCam, worldUp, deltaTime); + if (m_RandomizeChoice && mActiveBlend == null) + { + m_RandomizedChilden = null; + LiveChild = null; + UpdateCameraState(worldUp, deltaTime); + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineClearShot.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineClearShot.cs.meta new file mode 100644 index 0000000..9c3cd3a --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineClearShot.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d62f748f5292bb343be9e6b0c84416d9 +timeCreated: 1489088130 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineCollider.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineCollider.cs new file mode 100644 index 0000000..99e6739 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineCollider.cs @@ -0,0 +1,565 @@ +using UnityEngine; +using System.Collections.Generic; +using Cinemachine.Utility; +using UnityEngine.Serialization; +using System; + +namespace Cinemachine +{ + /// <summary> + /// An add-on module for Cinemachine Virtual Camera that post-processes + /// the final position of the virtual camera. Based on the supplied settings, + /// the Collider will attempt to preserve the line of sight + /// with the LookAt target of the virtual camera by moving + /// away from objects that will obstruct the view. + /// + /// Additionally, the Collider can be used to assess the shot quality and + /// report this as a field in the camera State. + /// </summary> + [DocumentationSorting(15, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] + [AddComponentMenu("")] // Hide in menu + [SaveDuringPlay] + public class CinemachineCollider : CinemachineExtension + { + /// <summary>The Unity layer mask against which the collider will raycast.</summary> + [Header("Obstacle Detection")] + [Tooltip("The Unity layer mask against which the collider will raycast")] + public LayerMask m_CollideAgainst = 1; + + /// <summary>Obstacles with this tag will be ignored. It is a good idea to set this field to the target's tag</summary> + [TagField] + [Tooltip("Obstacles with this tag will be ignored. It is a good idea to set this field to the target's tag")] + public string m_IgnoreTag = string.Empty; + + /// <summary>Obstacles closer to the target than this will be ignored</summary> + [Tooltip("Obstacles closer to the target than this will be ignored")] + public float m_MinimumDistanceFromTarget = 0.1f; + + /// <summary> + /// When enabled, will attempt to resolve situations where the line of sight to the + /// target is blocked by an obstacle + /// </summary> + [Space] + [Tooltip("When enabled, will attempt to resolve situations where the line of sight to the target is blocked by an obstacle")] + [FormerlySerializedAs("m_PreserveLineOfSight")] + public bool m_AvoidObstacles = true; + + /// <summary> + /// The raycast distance to test for when checking if the line of sight to this camera's target is clear. + /// </summary> + [Tooltip("The maximum raycast distance when checking if the line of sight to this camera's target is clear. If the setting is 0 or less, the current actual distance to target will be used.")] + [FormerlySerializedAs("m_LineOfSightFeelerDistance")] + public float m_DistanceLimit = 0f; + + /// <summary> + /// Camera will try to maintain this distance from any obstacle. + /// Increase this value if you are seeing inside obstacles due to a large + /// FOV on the camera. + /// </summary> + [Tooltip("Camera will try to maintain this distance from any obstacle. Try to keep this value small. Increase it if you are seeing inside obstacles due to a large FOV on the camera.")] + public float m_CameraRadius = 0.1f; + + /// <summary>The way in which the Collider will attempt to preserve sight of the target.</summary> + public enum ResolutionStrategy + { + /// <summary>Camera will be pulled forward along its Z axis until it is in front of + /// the nearest obstacle</summary> + PullCameraForward, + /// <summary>In addition to pulling the camera forward, an effort will be made to + /// return the camera to its original height</summary> + PreserveCameraHeight, + /// <summary>In addition to pulling the camera forward, an effort will be made to + /// return the camera to its original distance from the target</summary> + PreserveCameraDistance + }; + /// <summary>The way in which the Collider will attempt to preserve sight of the target.</summary> + [Tooltip("The way in which the Collider will attempt to preserve sight of the target.")] + public ResolutionStrategy m_Strategy = ResolutionStrategy.PreserveCameraHeight; + + /// <summary> + /// Upper limit on how many obstacle hits to process. Higher numbers may impact performance. + /// In most environments, 4 is enough. + /// </summary> + [Range(1, 10)] + [Tooltip("Upper limit on how many obstacle hits to process. Higher numbers may impact performance. In most environments, 4 is enough.")] + public int m_MaximumEffort = 4; + + /// <summary> + /// The gradualness of collision resolution. Higher numbers will move the + /// camera more gradually away from obstructions. + /// </summary> + [Range(0, 10)] + [Tooltip("The gradualness of collision resolution. Higher numbers will move the camera more gradually away from obstructions.")] + [FormerlySerializedAs("m_Smoothing")] + public float m_Damping = 0; + + /// <summary>If greater than zero, a higher score will be given to shots when the target is closer to + /// this distance. Set this to zero to disable this feature</summary> + [Header("Shot Evaluation")] + [Tooltip("If greater than zero, a higher score will be given to shots when the target is closer to this distance. Set this to zero to disable this feature.")] + public float m_OptimalTargetDistance = 0; + + /// <summary>See wheter an object is blocking the camera's view of the target</summary> + /// <param name="vcam">The virtual camera in question. This might be different from the + /// virtual camera that owns the collider, in the event that the camera has children</param> + /// <returns>True if something is blocking the view</returns> + public bool IsTargetObscured(ICinemachineCamera vcam) + { + return GetExtraState<VcamExtraState>(vcam).targetObscured; + } + + /// <summary>See whether the virtual camera has been moved nby the collider</summary> + /// <param name="vcam">The virtual camera in question. This might be different from the + /// virtual camera that owns the collider, in the event that the camera has children</param> + /// <returns>True if the virtual camera has been displaced due to collision or + /// target obstruction</returns> + public bool CameraWasDisplaced(CinemachineVirtualCameraBase vcam) + { + return GetExtraState<VcamExtraState>(vcam).colliderDisplacement > 0; + } + + private void OnValidate() + { + m_DistanceLimit = Mathf.Max(0, m_DistanceLimit); + m_CameraRadius = Mathf.Max(0, m_CameraRadius); + m_MinimumDistanceFromTarget = Mathf.Max(0.01f, m_MinimumDistanceFromTarget); + m_OptimalTargetDistance = Mathf.Max(0, m_OptimalTargetDistance); + } + + /// <summary>Cleanup</summary> + protected override void OnDestroy() + { + base.OnDestroy(); + CleanupCameraCollider(); + } + + /// This must be small but greater than 0 - reduces false results due to precision + const float PrecisionSlush = 0.001f; + + // Per-vcam extra state info + class VcamExtraState + { + public Vector3 m_previousDisplacement; + public float colliderDisplacement; + public bool targetObscured; + public List<Vector3> debugResolutionPath; + + public void AddPointToDebugPath(Vector3 p) + { +#if UNITY_EDITOR + if (debugResolutionPath == null) + debugResolutionPath = new List<Vector3>(); + debugResolutionPath.Add(p); +#endif + } + }; + + /// <summary>Inspector API for debugging collision resolution path</summary> + public List<List<Vector3>> DebugPaths + { + get + { + List<List<Vector3>> list = new List<List<Vector3>>(); + List<VcamExtraState> extraStates = GetAllExtraStates<VcamExtraState>(); + foreach (var v in extraStates) + if (v.debugResolutionPath != null) + list.Add(v.debugResolutionPath); + return list; + } + } + + /// <summary>Callcack to to the collision resolution and shot evaluation</summary> + protected override void PostPipelineStageCallback( + CinemachineVirtualCameraBase vcam, + CinemachineCore.Stage stage, ref CameraState state, float deltaTime) + { + VcamExtraState extra = null; + if (stage == CinemachineCore.Stage.Body) + { + extra = GetExtraState<VcamExtraState>(vcam); + extra.targetObscured = false; + extra.colliderDisplacement = 0; + extra.debugResolutionPath = null; + } + + // Move the body before the Aim is calculated + if (stage == CinemachineCore.Stage.Body) + { + if (m_AvoidObstacles) + { + Vector3 displacement = PreserveLignOfSight(ref state, ref extra); + if (m_Damping > 0 && deltaTime >= 0) + { + Vector3 delta = displacement - extra.m_previousDisplacement; + delta = Damper.Damp(delta, m_Damping, deltaTime); + displacement = extra.m_previousDisplacement + delta; + } + extra.m_previousDisplacement = displacement; + state.PositionCorrection += displacement; + extra.colliderDisplacement += displacement.magnitude; + } + } + // Rate the shot after the aim was set + if (stage == CinemachineCore.Stage.Aim) + { + extra = GetExtraState<VcamExtraState>(vcam); + extra.targetObscured = CheckForTargetObstructions(state); + + // GML these values are an initial arbitrary attempt at rating quality + if (extra.targetObscured) + state.ShotQuality *= 0.2f; + if (extra.colliderDisplacement > 0) + state.ShotQuality *= 0.8f; + + float nearnessBoost = 0; + const float kMaxNearBoost = 0.2f; + if (m_OptimalTargetDistance > 0 && state.HasLookAt) + { + float distance = Vector3.Magnitude(state.ReferenceLookAt - state.FinalPosition); + if (distance <= m_OptimalTargetDistance) + { + float threshold = m_OptimalTargetDistance / 2; + if (distance >= threshold) + nearnessBoost = kMaxNearBoost * (distance - threshold) + / (m_OptimalTargetDistance - threshold); + } + else + { + distance -= m_OptimalTargetDistance; + float threshold = m_OptimalTargetDistance * 3; + if (distance < threshold) + nearnessBoost = kMaxNearBoost * (1f - (distance / threshold)); + } + state.ShotQuality *= (1f + nearnessBoost); + } + } + } + + private Vector3 PreserveLignOfSight(ref CameraState state, ref VcamExtraState extra) + { + Vector3 displacement = Vector3.zero; + if (state.HasLookAt) + { + Vector3 cameraPos = state.CorrectedPosition; + Vector3 lookAtPos = state.ReferenceLookAt; + Vector3 pos = cameraPos; + Vector3 dir = pos - lookAtPos; + float targetDistance = dir.magnitude; + float minDistanceFromTarget = Mathf.Max(m_MinimumDistanceFromTarget, Epsilon); + if (targetDistance > minDistanceFromTarget) + { + dir.Normalize(); + float rayLength = targetDistance - minDistanceFromTarget; + if (m_DistanceLimit > Epsilon) + rayLength = Mathf.Min(m_DistanceLimit, rayLength); + + // Make a ray that looks towards the camera, to get the most distant obstruction + Ray ray = new Ray(pos - rayLength * dir, dir); + rayLength += PrecisionSlush; + if (rayLength > Epsilon) + { + RaycastHit hitInfo; + if (RaycastIgnoreTag(ray, out hitInfo, rayLength)) + { + // Pull camera forward in front of obstacle + float adjustment = Mathf.Max(0, hitInfo.distance - PrecisionSlush); + pos = ray.GetPoint(adjustment); + extra.AddPointToDebugPath(pos); + if (m_Strategy != ResolutionStrategy.PullCameraForward) + { + pos = PushCameraBack( + pos, dir, hitInfo, lookAtPos, + new Plane(state.ReferenceUp, cameraPos), + targetDistance, m_MaximumEffort, ref extra); + } + } + } + } + if (m_CameraRadius > Epsilon) + pos += RespectCameraRadius(pos, state.ReferenceLookAt); + else if (mCameraColliderGameObject != null) + CleanupCameraCollider(); + displacement = pos - cameraPos; + } + return displacement; + } + + private bool RaycastIgnoreTag(Ray ray, out RaycastHit hitInfo, float rayLength) + { + while (Physics.Raycast( + ray, out hitInfo, rayLength, m_CollideAgainst.value, + QueryTriggerInteraction.Ignore)) + { + if (m_IgnoreTag.Length == 0 || !hitInfo.collider.CompareTag(m_IgnoreTag)) + return true; + + // Pull ray origin forward in front of tagged obstacle + Ray inverseRay = new Ray(ray.GetPoint(rayLength), -ray.direction); + if (!hitInfo.collider.Raycast(inverseRay, out hitInfo, rayLength)) + break; // should never happen! + rayLength = hitInfo.distance - PrecisionSlush; + if (rayLength < Epsilon) + break; + ray.origin = inverseRay.GetPoint(rayLength); + } + return false; + } + + private Vector3 PushCameraBack( + Vector3 currentPos, Vector3 pushDir, RaycastHit obstacle, + Vector3 lookAtPos, Plane startPlane, float targetDistance, int iterations, + ref VcamExtraState extra) + { + // Take a step along the wall. + Vector3 pos = currentPos; + Vector3 dir = Vector3.zero; + if (!GetWalkingDirection(pos, pushDir, obstacle, ref dir)) + return pos; + + Ray ray = new Ray(pos, dir); + float distance = GetPushBackDistance(ray, startPlane, targetDistance, lookAtPos); + if (distance <= Epsilon) + return pos; + + // Check only as far as the obstacle bounds + float clampedDistance = ClampRayToBounds(ray, distance, obstacle.collider.bounds); + distance = Mathf.Min(distance, clampedDistance + PrecisionSlush); + + RaycastHit hitInfo; + if (RaycastIgnoreTag(ray, out hitInfo, distance)) + { + // We hit something. Stop there and take a step along that wall. + float adjustment = hitInfo.distance - PrecisionSlush; + pos = ray.GetPoint(adjustment); + extra.AddPointToDebugPath(pos); + if (iterations > 1) + pos = PushCameraBack( + pos, dir, hitInfo, + lookAtPos, startPlane, + targetDistance, iterations-1, ref extra); + + return pos; + } + + // Didn't hit anything. Can we push back all the way now? + pos = ray.GetPoint(distance); + + // First check if we can still see the target. If not, abort + dir = pos - lookAtPos; + float d = dir.magnitude; + RaycastHit hitInfo2; + if (d < Epsilon || RaycastIgnoreTag(new Ray(lookAtPos, dir), out hitInfo2, d - PrecisionSlush)) + return currentPos; + + // All clear + ray = new Ray(pos, dir); + extra.AddPointToDebugPath(pos); + distance = GetPushBackDistance(ray, startPlane, targetDistance, lookAtPos); + if (distance > Epsilon) + { + if (!RaycastIgnoreTag(ray, out hitInfo, distance)) + { + pos = ray.GetPoint(distance); // no obstacles - all good + extra.AddPointToDebugPath(pos); + } + else + { + // We hit something. Stop there and maybe take a step along that wall + float adjustment = hitInfo.distance - PrecisionSlush; + pos = ray.GetPoint(adjustment); + extra.AddPointToDebugPath(pos); + if (iterations > 1) + pos = PushCameraBack( + pos, dir, hitInfo, lookAtPos, startPlane, + targetDistance, iterations-1, ref extra); + } + } + return pos; + } + + private RaycastHit[] m_CornerBuffer = new RaycastHit[4]; + private bool GetWalkingDirection( + Vector3 pos, Vector3 pushDir, RaycastHit obstacle, ref Vector3 outDir) + { + Vector3 normal2 = obstacle.normal; + + // Check for nearby obstacles. Are we in a corner? + float nearbyDistance = PrecisionSlush * 5; + int numFound = Physics.SphereCastNonAlloc( + pos, nearbyDistance, pushDir.normalized, m_CornerBuffer, 0, + m_CollideAgainst.value, QueryTriggerInteraction.Ignore); + if (numFound > 1) + { + // Calculate the second normal + for (int i = 0; i < numFound; ++i) + { + if (m_IgnoreTag.Length > 0 && m_CornerBuffer[i].collider.CompareTag(m_IgnoreTag)) + continue; + Type type = m_CornerBuffer[i].collider.GetType(); + if (type == typeof(BoxCollider) + || type == typeof(SphereCollider) + || type == typeof(CapsuleCollider)) + { + Vector3 p = m_CornerBuffer[i].collider.ClosestPoint(pos); + Vector3 d = p - pos; + if (d.magnitude > Vector3.kEpsilon) + { + if (m_CornerBuffer[i].collider.Raycast( + new Ray(pos, d), out m_CornerBuffer[i], nearbyDistance)) + { + if (!(m_CornerBuffer[i].normal - obstacle.normal).AlmostZero()) + normal2 = m_CornerBuffer[i].normal; + break; + } + } + } + } + } + + // Walk along the wall. If we're in a corner, walk their intersecting line + Vector3 dir = Vector3.Cross(obstacle.normal, normal2); + if (dir.AlmostZero()) + dir = Vector3.ProjectOnPlane(pushDir, obstacle.normal); + else + { + float dot = Vector3.Dot(dir, pushDir); + if (Mathf.Abs(dot) < Epsilon) + return false; + if (dot < 0) + dir = -dir; + } + if (dir.AlmostZero()) + return false; + + outDir = dir.normalized; + return true; + } + + const float AngleThreshold = 0.1f; + float GetPushBackDistance(Ray ray, Plane startPlane, float targetDistance, Vector3 lookAtPos) + { + float maxDistance = targetDistance - (ray.origin - lookAtPos).magnitude; + if (maxDistance < Epsilon) + return 0; + if (m_Strategy == ResolutionStrategy.PreserveCameraDistance) + return maxDistance; + + float distance; + if (!startPlane.Raycast(ray, out distance)) + distance = 0; + distance = Mathf.Min(maxDistance, distance); + if (distance < Epsilon) + return 0; + + // If we are close to parallel to the plane, we have to take special action + float angle = Mathf.Abs(Vector3.Angle(startPlane.normal, ray.direction) - 90); + if (angle < AngleThreshold) + distance = Mathf.Lerp(0, distance, angle / AngleThreshold); + return distance; + } + + float ClampRayToBounds(Ray ray, float distance, Bounds bounds) + { + float d; + if (Vector3.Dot(ray.direction, Vector3.up) > 0) + { + if (new Plane(Vector3.down, bounds.max).Raycast(ray, out d) && d > Epsilon) + distance = Mathf.Min(distance, d); + } + else if (Vector3.Dot(ray.direction, Vector3.down) > 0) + { + if (new Plane(Vector3.up, bounds.min).Raycast(ray, out d) && d > Epsilon) + distance = Mathf.Min(distance, d); + } + + if (Vector3.Dot(ray.direction, Vector3.right) > 0) + { + if (new Plane(Vector3.left, bounds.max).Raycast(ray, out d) && d > Epsilon) + distance = Mathf.Min(distance, d); + } + else if (Vector3.Dot(ray.direction, Vector3.left) > 0) + { + if (new Plane(Vector3.right, bounds.min).Raycast(ray, out d) && d > Epsilon) + distance = Mathf.Min(distance, d); + } + + if (Vector3.Dot(ray.direction, Vector3.forward) > 0) + { + if (new Plane(Vector3.back, bounds.max).Raycast(ray, out d) && d > Epsilon) + distance = Mathf.Min(distance, d); + } + else if (Vector3.Dot(ray.direction, Vector3.back) > 0) + { + if (new Plane(Vector3.forward, bounds.min).Raycast(ray, out d) && d > Epsilon) + distance = Mathf.Min(distance, d); + } + return distance; + } + + private Collider[] mColliderBuffer = new Collider[5]; + private SphereCollider mCameraCollider; + private GameObject mCameraColliderGameObject; + private Vector3 RespectCameraRadius(Vector3 cameraPos, Vector3 lookAtPos) + { + Vector3 result = Vector3.zero; + int numObstacles = Physics.OverlapSphereNonAlloc( + cameraPos, m_CameraRadius, mColliderBuffer, + m_CollideAgainst, QueryTriggerInteraction.Ignore); + if (numObstacles > 0) + { + if (mCameraColliderGameObject == null) + { + mCameraColliderGameObject = new GameObject("Cinemachine Collider Collider"); + mCameraColliderGameObject.hideFlags = HideFlags.HideAndDontSave; + mCameraColliderGameObject.transform.position = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); + mCameraColliderGameObject.SetActive(true); + mCameraCollider = mCameraColliderGameObject.AddComponent<SphereCollider>(); + } + mCameraCollider.radius = m_CameraRadius; + for (int i = 0; i < numObstacles; ++i) + { + Collider c = mColliderBuffer[i]; + if (m_IgnoreTag.Length > 0 && c.CompareTag(m_IgnoreTag)) + continue; + Vector3 dir; + float distance; + if (Physics.ComputePenetration( + mCameraCollider, cameraPos, Quaternion.identity, + c, c.transform.position, c.transform.rotation, + out dir, out distance)) + { + result += dir * distance; // naive, but maybe enough + } + } + } + return result; + } + + private void CleanupCameraCollider() + { + if (mCameraColliderGameObject != null) + DestroyImmediate(mCameraColliderGameObject); + mCameraColliderGameObject = null; + mCameraCollider = null; + } + + private bool CheckForTargetObstructions(CameraState state) + { + if (state.HasLookAt) + { + Vector3 lookAtPos = state.ReferenceLookAt; + Vector3 pos = state.CorrectedPosition; + Vector3 dir = lookAtPos - pos; + float distance = dir.magnitude; + if (distance < Mathf.Max(m_MinimumDistanceFromTarget, Epsilon)) + return true; + Ray ray = new Ray(pos, dir.normalized); + RaycastHit hitInfo; + if (RaycastIgnoreTag(ray, out hitInfo, distance - m_MinimumDistanceFromTarget)) + return true; + } + return false; + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineCollider.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineCollider.cs.meta new file mode 100644 index 0000000..64be66f --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineCollider.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e501d18bb52cf8c40b1853ca4904654f +timeCreated: 1491854845 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineConfiner.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineConfiner.cs new file mode 100644 index 0000000..f4ff41b --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineConfiner.cs @@ -0,0 +1,222 @@ +using UnityEngine; +using System.Collections.Generic; +using Cinemachine.Utility; +using System; + +namespace Cinemachine +{ + /// <summary> + /// An add-on module for Cinemachine Virtual Camera that post-processes + /// the final position of the virtual camera. It will confine the virtual + /// camera's position to the volume specified in the Bounding Volume field. + /// </summary> + [DocumentationSorting(22, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] + [AddComponentMenu("")] // Hide in menu + [SaveDuringPlay] + public class CinemachineConfiner : CinemachineExtension + { + /// <summary>The confiner can operate using a 2D bounding shape or a 3D bounding volume</summary> + public enum Mode + { + Confine2D, + Confine3D + }; + /// <summary>The confiner can operate using a 2D bounding shape or a 3D bounding volume</summary> + [Tooltip("The confiner can operate using a 2D bounding shape or a 3D bounding volume")] + public Mode m_ConfineMode; + + /// <summary>The volume within which the camera is to be contained.</summary> + [Tooltip("The volume within which the camera is to be contained")] + public Collider m_BoundingVolume; + + /// <summary>The 2D shape within which the camera is to be contained.</summary> + [Tooltip("The 2D shape within which the camera is to be contained")] + public Collider2D m_BoundingShape2D; + + /// <summary>If camera is orthographic, screen edges will be confined to the volume.</summary> + [Tooltip("If camera is orthographic, screen edges will be confined to the volume. If not checked, then only the camera center will be confined")] + public bool m_ConfineScreenEdges = true; + + /// <summary>How gradually to return the camera to the bounding volume if it goes beyond the borders</summary> + [Tooltip("How gradually to return the camera to the bounding volume if it goes beyond the borders. Higher numbers are more gradual.")] + [Range(0, 10)] + public float m_Damping = 0; + + /// <summary>See whether the virtual camera has been moved by the confiner</summary> + /// <param name="vcam">The virtual camera in question. This might be different from the + /// virtual camera that owns the confiner, in the event that the camera has children</param> + /// <returns>True if the virtual camera has been repositioned</returns> + public bool CameraWasDisplaced(CinemachineVirtualCameraBase vcam) + { + return GetExtraState<VcamExtraState>(vcam).confinerDisplacement > 0; + } + + private void OnValidate() + { + m_Damping = Mathf.Max(0, m_Damping); + } + + class VcamExtraState + { + public Vector3 m_previousDisplacement; + public float confinerDisplacement; + }; + + /// <summary>Check if the bounding volume is defined</summary> + public bool IsValid + { + get + { + return ((m_ConfineMode == Mode.Confine3D && m_BoundingVolume != null) + || (m_ConfineMode == Mode.Confine2D && m_BoundingShape2D != null)); + } + } + + /// <summary>Callback to to the camera confining</summary> + protected override void PostPipelineStageCallback( + CinemachineVirtualCameraBase vcam, + CinemachineCore.Stage stage, ref CameraState state, float deltaTime) + { + if (IsValid) + { + // Move the body before the Aim is calculated + if (stage == CinemachineCore.Stage.Body) + { + Vector3 displacement; + if (m_ConfineScreenEdges && state.Lens.Orthographic) + displacement = ConfineScreenEdges(vcam, ref state); + else + displacement = ConfinePoint(state.CorrectedPosition); + + VcamExtraState extra = GetExtraState<VcamExtraState>(vcam); + if (m_Damping > 0 && deltaTime >= 0) + { + Vector3 delta = displacement - extra.m_previousDisplacement; + delta = Damper.Damp(delta, m_Damping, deltaTime); + displacement = extra.m_previousDisplacement + delta; + } + extra.m_previousDisplacement = displacement; + state.PositionCorrection += displacement; + extra.confinerDisplacement = displacement.magnitude; + } + } + } + + private List<List<Vector2>> m_pathCache; + + /// <summary>Call this if the bounding shape's points change at runtime</summary> + public void InvalidatePathCache() { m_pathCache = null; } + + bool ValidatePathCache() + { + Type colliderType = m_BoundingShape2D == null ? null: m_BoundingShape2D.GetType(); + if (colliderType == typeof(PolygonCollider2D)) + { + PolygonCollider2D poly = m_BoundingShape2D as PolygonCollider2D; + if (m_pathCache == null || m_pathCache.Count != poly.pathCount) + { + m_pathCache = new List<List<Vector2>>(); + for (int i = 0; i < poly.pathCount; ++i) + { + Vector2[] path = poly.GetPath(i); + List<Vector2> dst = new List<Vector2>(); + for (int j = 0; j < path.Length; ++j) + dst.Add(path[j]); + m_pathCache.Add(dst); + } + } + return true; + } + else if (colliderType == typeof(CompositeCollider2D)) + { + CompositeCollider2D poly = m_BoundingShape2D as CompositeCollider2D; + if (m_pathCache == null || m_pathCache.Count != poly.pathCount) + { + m_pathCache = new List<List<Vector2>>(); + Vector2[] path = new Vector2[poly.pointCount]; + for (int i = 0; i < poly.pathCount; ++i) + { + int numPoints = poly.GetPath(i, path); + List<Vector2> dst = new List<Vector2>(); + for (int j = 0; j < numPoints; ++j) + dst.Add(path[j]); + m_pathCache.Add(dst); + } + } + return true; + } + InvalidatePathCache(); + return false; + } + + private Vector3 ConfinePoint(Vector3 camPos) + { + // 3D version + if (m_ConfineMode == Mode.Confine3D) + return m_BoundingVolume.ClosestPoint(camPos) - camPos; + + // 2D version + if (m_BoundingShape2D.OverlapPoint(camPos)) + return Vector3.zero; + + // Find the nearest point on the shape's boundary + if (!ValidatePathCache()) + return Vector3.zero; + + Vector2 p = camPos; + Vector2 closest = p; + float bestDistance = float.MaxValue; + for (int i = 0; i < m_pathCache.Count; ++i) + { + int numPoints = m_pathCache[i].Count; + if (numPoints > 0) + { + Vector2 v0 = m_BoundingShape2D.transform.TransformPoint(m_pathCache[i][numPoints-1]); + for (int j = 0; j < numPoints; ++j) + { + Vector2 v = m_BoundingShape2D.transform.TransformPoint(m_pathCache[i][j]); + Vector2 c = Vector2.Lerp(v0, v, p.ClosestPointOnSegment(v0, v)); + float d = Vector2.SqrMagnitude(p - c); + if (d < bestDistance) + { + bestDistance = d; + closest = c; + } + v0 = v; + } + } + } + return closest - p; + } + + // Camera must be orthographic + private Vector3 ConfineScreenEdges(CinemachineVirtualCameraBase vcam, ref CameraState state) + { + Quaternion rot = Quaternion.Inverse(state.CorrectedOrientation); + float dy = state.Lens.OrthographicSize; + float dx = dy * state.Lens.Aspect; + Vector3 vx = (rot * Vector3.right) * dx; + Vector3 vy = (rot * Vector3.up) * dy; + + Vector3 displacement = Vector3.zero; + Vector3 camPos = state.CorrectedPosition; + const int kMaxIter = 12; + for (int i = 0; i < kMaxIter; ++i) + { + Vector3 d = ConfinePoint((camPos - vy) - vx); + if (d.AlmostZero()) + d = ConfinePoint((camPos - vy) + vx); + if (d.AlmostZero()) + d = ConfinePoint((camPos + vy) - vx); + if (d.AlmostZero()) + d = ConfinePoint((camPos + vy) + vx); + if (d.AlmostZero()) + break; + displacement += d; + camPos += d; + } + return displacement; + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineConfiner.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineConfiner.cs.meta new file mode 100644 index 0000000..00eb9ad --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineConfiner.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a2fba25a5cd15594e8f050a11e386c80 +timeCreated: 1503419997 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineDollyCart.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineDollyCart.cs new file mode 100644 index 0000000..42e97cf --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineDollyCart.cs @@ -0,0 +1,70 @@ +using UnityEngine; +using UnityEngine.Serialization; + +namespace Cinemachine +{ + /// <summary> + /// This is a very simple behaviour that constrains its transform to a CinemachinePath. + /// It can be used to animate any objects along a path, or as a Follow target for + /// Cinemachine Virtual Cameras. + /// </summary> + [DocumentationSorting(21f, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] + public class CinemachineDollyCart : MonoBehaviour + { + /// <summary>The path to follow</summary> + [Tooltip("The path to follow")] + public CinemachinePathBase m_Path; + + /// <summary>This enum defines the options available for the update method.</summary> + public enum UpdateMethod + { + /// <summary>Updated in normal MonoBehaviour Update.</summary> + Update, + /// <summary>Updated in sync with the Physics module, in FixedUpdate</summary> + FixedUpdate + }; + + /// <summary>When to move the cart, if Velocity is non-zero</summary> + [Tooltip("When to move the cart, if Velocity is non-zero")] + public UpdateMethod m_UpdateMethod = UpdateMethod.Update; + + /// <summary>How to interpret the Path Position</summary> + [Tooltip("How to interpret the Path Position. If set to Path Units, values are as follows: 0 represents the first waypoint on the path, 1 is the second, and so on. Values in-between are points on the path in between the waypoints. If set to Distance, then Path Position represents distance along the path.")] + public CinemachinePathBase.PositionUnits m_PositionUnits = CinemachinePathBase.PositionUnits.Distance; + + /// <summary>Move the cart with this speed</summary> + [Tooltip("Move the cart with this speed along the path. The value is interpreted according to the Position Units setting.")] + [FormerlySerializedAs("m_Velocity")] + public float m_Speed; + + /// <summary>The cart's current position on the path, in distance units</summary> + [Tooltip("The position along the path at which the cart will be placed. This can be animated directly or, if the velocity is non-zero, will be updated automatically. The value is interpreted according to the Position Units setting.")] + [FormerlySerializedAs("m_CurrentDistance")] + public float m_Position; + + void FixedUpdate() + { + if (m_UpdateMethod == UpdateMethod.FixedUpdate) + SetCartPosition(m_Position += m_Speed * Time.deltaTime); + } + + void Update() + { + if (!Application.isPlaying) + SetCartPosition(m_Position); + else if (m_UpdateMethod == UpdateMethod.Update) + SetCartPosition(m_Position += m_Speed * Time.deltaTime); + } + + void SetCartPosition(float distanceAlongPath) + { + if (m_Path != null) + { + m_Position = m_Path.NormalizeUnit(distanceAlongPath, m_PositionUnits); + transform.position = m_Path.EvaluatePositionAtUnit(m_Position, m_PositionUnits); + transform.rotation = m_Path.EvaluateOrientationAtUnit(m_Position, m_PositionUnits); + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineDollyCart.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineDollyCart.cs.meta new file mode 100644 index 0000000..a0a0e0a --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineDollyCart.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 99a9c787e5d1bbf48a389834c4a9641c +timeCreated: 1502981597 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineExternalCamera.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineExternalCamera.cs new file mode 100644 index 0000000..9417b59 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineExternalCamera.cs @@ -0,0 +1,61 @@ +using Cinemachine.Utility; +using UnityEngine; + +namespace Cinemachine +{ + /// <summary> + /// This component will expose a non-cinemachine camera to the cinemachine system, + /// allowing it to participate in blends. + /// Just add it as a component alongside an existing Unity Camera component. + /// </summary> + [DocumentationSorting(14, DocumentationSortingAttribute.Level.UserRef)] + [RequireComponent(typeof(Camera)), DisallowMultipleComponent, ExecuteInEditMode] + [AddComponentMenu("Cinemachine/CinemachineExternalCamera")] + public class CinemachineExternalCamera : CinemachineVirtualCameraBase + { + /// <summary>The object that the camera is looking at.</summary> + [Tooltip("The object that the camera is looking at. Setting this will improve the quality of the blends to and from this camera")] + [NoSaveDuringPlay] + public Transform m_LookAt = null; + + private Camera m_Camera; + private CameraState m_State = CameraState.Default; + + /// <summary>Get the CameraState, as we are able to construct one from the Unity Camera</summary> + public override CameraState State { get { return m_State; } } + + /// <summary>The object that the camera is looking at</summary> + override public Transform LookAt + { + get { return m_LookAt; } + set { m_LookAt = value; } + } + + /// <summary>This vcam defines no targets</summary> + override public Transform Follow { get; set; } + + /// <summary>Construct a CameraState object from the Unity Camera</summary> + public override void UpdateCameraState(Vector3 worldUp, float deltaTime) + { + // Get the state from the camera + if (m_Camera == null) + m_Camera = GetComponent<Camera>(); + + m_State = CameraState.Default; + m_State.RawPosition = transform.position; + m_State.RawOrientation = transform.rotation; + m_State.ReferenceUp = m_State.RawOrientation * Vector3.up; + if (m_Camera != null) + m_State.Lens = LensSettings.FromCamera(m_Camera); + + if (m_LookAt != null) + { + m_State.ReferenceLookAt = m_LookAt.transform.position; + Vector3 dir = m_State.ReferenceLookAt - State.RawPosition; + if (!dir.AlmostZero()) + m_State.ReferenceLookAt = m_State.RawPosition + Vector3.Project( + dir, State.RawOrientation * Vector3.forward); + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineExternalCamera.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineExternalCamera.cs.meta new file mode 100644 index 0000000..c1e2d83 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineExternalCamera.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 57744762d9079934292f57896d8193e0 +timeCreated: 1489441713 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFollowZoom.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFollowZoom.cs new file mode 100644 index 0000000..cf14dc6 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFollowZoom.cs @@ -0,0 +1,91 @@ +using UnityEngine; +using Cinemachine.Utility; + +namespace Cinemachine +{ + /// <summary> + /// An add-on module for Cinemachine Virtual Camera that adjusts + /// the FOV of the lens to keep the target object at a constant size on the screen, + /// regardless of camera and target position. + /// </summary> + [DocumentationSorting(16, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] + [AddComponentMenu("")] // Hide in menu + [SaveDuringPlay] + public class CinemachineFollowZoom : CinemachineExtension + { + /// <summary>The shot width to maintain, in world units, at target distance. + /// FOV will be adusted as far as possible to maintain this width at the + /// target distance from the camera.</summary> + [Tooltip("The shot width to maintain, in world units, at target distance.")] + public float m_Width = 2f; + + /// <summary>Increase this value to soften the aggressiveness of the follow-zoom. + /// Small numbers are more responsive, larger numbers give a more heavy slowly responding camera. </summary> + [Range(0f, 20f)] + [Tooltip("Increase this value to soften the aggressiveness of the follow-zoom. Small numbers are more responsive, larger numbers give a more heavy slowly responding camera.")] + public float m_Damping = 1f; + + /// <summary>Will not generate an FOV smaller than this.</summary> + [Range(1f, 179f)] + [Tooltip("Lower limit for the FOV that this behaviour will generate.")] + public float m_MinFOV = 3f; + + /// <summary>Will not generate an FOV larget than this.</summary> + [Range(1f, 179f)] + [Tooltip("Upper limit for the FOV that this behaviour will generate.")] + public float m_MaxFOV = 60f; + + private void OnValidate() + { + m_Width = Mathf.Max(0, m_Width); + m_MaxFOV = Mathf.Clamp(m_MaxFOV, 1, 179); + m_MinFOV = Mathf.Clamp(m_MinFOV, 1, m_MaxFOV); + } + + class VcamExtraState + { + public float m_previousFrameZoom = 0; + } + + /// <summary>Callback to preform the zoom adjustment</summary> + protected override void PostPipelineStageCallback( + CinemachineVirtualCameraBase vcam, + CinemachineCore.Stage stage, ref CameraState state, float deltaTime) + { + VcamExtraState extra = GetExtraState<VcamExtraState>(vcam); + if (!enabled || deltaTime < 0) + extra.m_previousFrameZoom = state.Lens.FieldOfView; + + // Set the zoom after the body has been positioned, but before the aim, + // so that composer can compose using the updated fov. + if (stage == CinemachineCore.Stage.Body) + { + // Try to reproduce the target width + float targetWidth = Mathf.Max(m_Width, 0); + float fov = 179f; + float d = Vector3.Distance(state.CorrectedPosition, state.ReferenceLookAt); + if (d > UnityVectorExtensions.Epsilon) + { + // Clamp targetWidth to FOV min/max + float minW = d * 2f * Mathf.Tan(m_MinFOV * Mathf.Deg2Rad / 2f); + float maxW = d * 2f * Mathf.Tan(m_MaxFOV * Mathf.Deg2Rad / 2f); + targetWidth = Mathf.Clamp(targetWidth, minW, maxW); + + // Apply damping + if (deltaTime >= 0 && m_Damping > 0) + { + float currentWidth = d * 2f * Mathf.Tan(extra.m_previousFrameZoom * Mathf.Deg2Rad / 2f); + float delta = targetWidth - currentWidth; + delta = Damper.Damp(delta, m_Damping, deltaTime); + targetWidth = currentWidth + delta; + } + fov = 2f * Mathf.Atan(targetWidth / (2 * d)) * Mathf.Rad2Deg; + } + LensSettings lens = state.Lens; + lens.FieldOfView = extra.m_previousFrameZoom = Mathf.Clamp(fov, m_MinFOV, m_MaxFOV); + state.Lens = lens; + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFollowZoom.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFollowZoom.cs.meta new file mode 100644 index 0000000..386862d --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFollowZoom.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4700f9f03ad19f94baf0367cb7a9c988 +timeCreated: 1491854845 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFreeLook.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFreeLook.cs new file mode 100644 index 0000000..69d8f56 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFreeLook.cs @@ -0,0 +1,673 @@ +using UnityEngine; +using Cinemachine.Utility; +using UnityEngine.Serialization; +using System; + +namespace Cinemachine +{ + /// <summary> + /// A Cinemachine Camera geared towards a 3rd person camera experience. + /// The camera orbits around its subject with three separate camera rigs defining + /// rings around the target. Each rig has its own radius, height offset, composer, + /// and lens settings. + /// Depending on the camera's position along the spline connecting these three rigs, + /// these settings are interpolated to give the final camera position and state. + /// </summary> + [DocumentationSorting(11, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineFreeLook")] + public class CinemachineFreeLook : CinemachineVirtualCameraBase + { + /// <summary>Object for the camera children to look at (the aim target)</summary> + [Tooltip("Object for the camera children to look at (the aim target).")] + [NoSaveDuringPlay] + public Transform m_LookAt = null; + + /// <summary>Object for the camera children wants to move with (the body target)</summary> + [Tooltip("Object for the camera children wants to move with (the body target).")] + [NoSaveDuringPlay] + public Transform m_Follow = null; + + /// <summary>If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used</summary> + [Tooltip("If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used")] + [FormerlySerializedAs("m_UseCommonLensSetting")] + public bool m_CommonLens = true; + + /// <summary>Specifies the lens properties of this Virtual Camera. + /// This generally mirrors the Unity Camera's lens settings, and will be used to drive + /// the Unity camera when the vcam is active</summary> + [FormerlySerializedAs("m_LensAttributes")] + [Tooltip("Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active")] + [LensSettingsProperty] + public LensSettings m_Lens = LensSettings.Default; + + /// <summary>The Vertical axis. Value is 0..1. Chooses how to blend the child rigs</summary> + [Header("Axis Control")] + [Tooltip("The Vertical axis. Value is 0..1. Chooses how to blend the child rigs")] + public AxisState m_YAxis = new AxisState(2f, 0.2f, 0.1f, 0.5f, "Mouse Y", false); + + /// <summary>The Horizontal axis. Value is 0..359. This is passed on to the rigs' OrbitalTransposer component</summary> + [Tooltip("The Horizontal axis. Value is 0..359. This is passed on to the rigs' OrbitalTransposer component")] + public AxisState m_XAxis = new AxisState(300f, 0.1f, 0.1f, 0f, "Mouse X", true); + + /// <summary>The definition of Forward. Camera will follow behind</summary> + [Tooltip("The definition of Forward. Camera will follow behind.")] + public CinemachineOrbitalTransposer.Heading m_Heading + = new CinemachineOrbitalTransposer.Heading( + CinemachineOrbitalTransposer.Heading.HeadingDefinition.TargetForward, 4, 0); + + /// <summary>Controls how automatic recentering of the X axis is accomplished</summary> + [Tooltip("Controls how automatic recentering of the X axis is accomplished")] + public CinemachineOrbitalTransposer.Recentering m_RecenterToTargetHeading + = new CinemachineOrbitalTransposer.Recentering(false, 1, 2); + + /// <summary>The coordinate space to use when interpreting the offset from the target</summary> + [Header("Orbits")] + [Tooltip("The coordinate space to use when interpreting the offset from the target. This is also used to set the camera's Up vector, which will be maintained when aiming the camera.")] + public CinemachineOrbitalTransposer.BindingMode m_BindingMode + = CinemachineOrbitalTransposer.BindingMode.SimpleFollowWithWorldUp; + + /// <summary></summary> + [Tooltip("Controls how taut is the line that connects the rigs' orbits, which determines final placement on the Y axis")] + [Range(0f, 1f)] + [FormerlySerializedAs("m_SplineTension")] + public float m_SplineCurvature = 0.2f; + + /// <summary>Defines the height and radius of the Rig orbit</summary> + [Serializable] + public struct Orbit + { + /// <summary>Height relative to target</summary> + public float m_Height; + /// <summary>Radius of orbit</summary> + public float m_Radius; + /// <summary>Constructor with specific values</summary> + public Orbit(float h, float r) { m_Height = h; m_Radius = r; } + } + + /// <summary>The radius and height of the three orbiting rigs</summary> + [Tooltip("The radius and height of the three orbiting rigs.")] + public Orbit[] m_Orbits = new Orbit[3] + { + // These are the default orbits + new Orbit(4.5f, 1.75f), + new Orbit(2.5f, 3f), + new Orbit(0.4f, 1.3f) + }; + + // Legacy support + [SerializeField] [HideInInspector] [FormerlySerializedAs("m_HeadingBias")] + private float m_LegacyHeadingBias = float.MaxValue; + bool mUseLegacyRigDefinitions = false; + + /// <summary>Enforce bounds for fields, when changed in inspector.</summary> + protected override void OnValidate() + { + base.OnValidate(); + + // Upgrade after a legacy deserialize + if (m_LegacyHeadingBias != float.MaxValue) + { + m_Heading.m_HeadingBias = m_LegacyHeadingBias; + m_LegacyHeadingBias = float.MaxValue; + m_RecenterToTargetHeading.LegacyUpgrade( + ref m_Heading.m_HeadingDefinition, ref m_Heading.m_VelocityFilterStrength); + mUseLegacyRigDefinitions = true; + } + m_YAxis.Validate(); + m_XAxis.Validate(); + m_RecenterToTargetHeading.Validate(); + m_Lens.Validate(); + + InvalidateRigCache(); + } + + /// <summary>Get a child rig</summary> + /// <param name="i">Rig index. Can be 0, 1, or 2</param> + /// <returns>The rig, or null if index is bad.</returns> + public CinemachineVirtualCamera GetRig(int i) + { + UpdateRigCache(); + return (i < 0 || i > 2) ? null : m_Rigs[i]; + } + + /// <summary>Names of the 3 child rigs</summary> + public static string[] RigNames { get { return new string[] { "TopRig", "MiddleRig", "BottomRig" }; } } + + bool mIsDestroyed = false; + + /// <summary>Updates the child rig cache</summary> + protected override void OnEnable() + { + mIsDestroyed = false; + base.OnEnable(); + InvalidateRigCache(); + } + + /// <summary>Makes sure that the child rigs get destroyed in an undo-firndly manner. + /// Invalidates the rig cache.</summary> + protected override void OnDestroy() + { + // Make the rigs visible instead of destroying - this is to keep Undo happy + if (m_Rigs != null) + foreach (var rig in m_Rigs) + if (rig != null && rig.gameObject != null) + rig.gameObject.hideFlags + &= ~(HideFlags.HideInHierarchy | HideFlags.HideInInspector); + + mIsDestroyed = true; + base.OnDestroy(); + } + + /// <summary>Invalidates the rig cache</summary> + void OnTransformChildrenChanged() + { + InvalidateRigCache(); + } + + void Reset() + { + DestroyRigs(); + } + + /// <summary>The cacmera state, which will be a blend of the child rig states</summary> + override public CameraState State { get { return m_State; } } + + /// <summary>Get the current LookAt target. Returns parent's LookAt if parent + /// is non-null and no specific LookAt defined for this camera</summary> + override public Transform LookAt + { + get { return ResolveLookAt(m_LookAt); } + set { m_LookAt = value; } + } + + /// <summary>Get the current Follow target. Returns parent's Follow if parent + /// is non-null and no specific Follow defined for this camera</summary> + override public Transform Follow + { + get { return ResolveFollow(m_Follow); } + set { m_Follow = value; } + } + + /// <summary>Returns the rig with the greatest weight</summary> + public override ICinemachineCamera LiveChildOrSelf + { + get + { + // Do not update the rig cache here or there will be infinite loop at creation time + if (m_Rigs == null || m_Rigs.Length != 3) + return this; + if (m_YAxis.Value < 0.33f) + return m_Rigs[2]; + if (m_YAxis.Value > 0.66f) + return m_Rigs[0]; + return m_Rigs[1]; + } + } + + /// <summary>Check whether the vcam a live child of this camera. + /// Returns true if the child is currently contributing actively to the camera state.</summary> + /// <param name="vcam">The Virtual Camera to check</param> + /// <returns>True if the vcam is currently actively influencing the state of this vcam</returns> + public override bool IsLiveChild(ICinemachineCamera vcam) + { + // Do not update the rig cache here or there will be infinite loop at creation time + if (m_Rigs == null || m_Rigs.Length != 3) + return false; + + if (m_YAxis.Value < 0.33f) + return vcam == (ICinemachineCamera)m_Rigs[2]; + if (m_YAxis.Value > 0.66f) + return vcam == (ICinemachineCamera)m_Rigs[0]; + return vcam == (ICinemachineCamera)m_Rigs[1]; + } + + /// <summary>Remove a Pipeline stage hook callback. + /// Make sure it is removed from all the children.</summary> + /// <param name="d">The delegate to remove.</param> + public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + base.RemovePostPipelineStageHook(d); + UpdateRigCache(); + if (m_Rigs != null) + foreach (var vcam in m_Rigs) + if (vcam != null) + vcam.RemovePostPipelineStageHook(d); + } + + /// <summary>Called by CinemachineCore at designated update time + /// so the vcam can position itself and track its targets. All 3 child rigs are updated, + /// and a blend calculated, depending on the value of the Y axis.</summary> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than 0)</param> + override public void UpdateCameraState(Vector3 worldUp, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.UpdateCameraState"); + if (!PreviousStateIsValid) + deltaTime = -1; + + UpdateRigCache(); + + // Reset the base camera state, in case the game object got moved in the editor + if (deltaTime < 0) + m_State = PullStateFromVirtualCamera(worldUp); // Not in gameplay + + // Update the current state by invoking the component pipeline + m_State = CalculateNewState(worldUp, deltaTime); + + // Push the raw position back to the game object's transform, so it + // moves along with the camera. Leave the orientation alone, because it + // screws up camera dragging when there is a LookAt behaviour. + if (Follow != null) + { + Vector3 delta = State.RawPosition - transform.position; + transform.position = State.RawPosition; + m_Rigs[0].transform.position -= delta; + m_Rigs[1].transform.position -= delta; + m_Rigs[2].transform.position -= delta; + } + + PreviousStateIsValid = true; + + // Set up for next frame + bool activeCam = (deltaTime >= 0) || CinemachineCore.Instance.IsLive(this); + if (activeCam) + m_YAxis.Update(deltaTime); + + PushSettingsToRigs(); + + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// <summary>If we are transitioning from another FreeLook, grab the axis values from it.</summary> + /// <param name="fromCam">The camera being deactivated. May be null.</param> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param> + public override void OnTransitionFromCamera( + ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime) + { + base.OnTransitionFromCamera(fromCam, worldUp, deltaTime); + if ((fromCam != null) && (fromCam is CinemachineFreeLook)) + { + CinemachineFreeLook freeLookFrom = fromCam as CinemachineFreeLook; + if (freeLookFrom.Follow == Follow) + { + m_XAxis.Value = freeLookFrom.m_XAxis.Value; + m_YAxis.Value = freeLookFrom.m_YAxis.Value; + UpdateCameraState(worldUp, deltaTime); + } + } + } + + CameraState m_State = CameraState.Default; // Current state this frame + + /// Serialized in order to support copy/paste + [SerializeField][HideInInspector][NoSaveDuringPlay] private CinemachineVirtualCamera[] m_Rigs + = new CinemachineVirtualCamera[3]; + + void InvalidateRigCache() { mOrbitals = null; } + CinemachineOrbitalTransposer[] mOrbitals = null; + CinemachineBlend mBlendA; + CinemachineBlend mBlendB; + + /// <summary> + /// Override component pipeline creation. + /// This needs to be done by the editor to support Undo. + /// The override must do exactly the same thing as the CreatePipeline method in this class. + /// </summary> + public static CreateRigDelegate CreateRigOverride; + + /// <summary> + /// Override component pipeline creation. + /// This needs to be done by the editor to support Undo. + /// The override must do exactly the same thing as the CreatePipeline method in this class. + /// </summary> + public delegate CinemachineVirtualCamera CreateRigDelegate( + CinemachineFreeLook vcam, string name, CinemachineVirtualCamera copyFrom); + + /// <summary> + /// Override component pipeline destruction. + /// This needs to be done by the editor to support Undo. + /// </summary> + public static DestroyRigDelegate DestroyRigOverride; + + /// <summary> + /// Override component pipeline destruction. + /// This needs to be done by the editor to support Undo. + /// </summary> + public delegate void DestroyRigDelegate(GameObject rig); + + private void DestroyRigs() + { + CinemachineVirtualCamera[] oldRigs = new CinemachineVirtualCamera[RigNames.Length]; + for (int i = 0; i < RigNames.Length; ++i) + { + foreach (Transform child in transform) + if (child.gameObject.name == RigNames[i]) + oldRigs[i] = child.GetComponent<CinemachineVirtualCamera>(); + } + for (int i = 0; i < oldRigs.Length; ++i) + { + if (oldRigs[i] != null) + { + if (DestroyRigOverride != null) + DestroyRigOverride(oldRigs[i].gameObject); + else + Destroy(oldRigs[i].gameObject); + } + } + m_Rigs = null; + mOrbitals = null; + } + + private CinemachineVirtualCamera[] CreateRigs(CinemachineVirtualCamera[] copyFrom) + { + // Invalidate the cache + mOrbitals = null; + float[] softCenterDefaultsV = new float[] { 0.5f, 0.55f, 0.6f }; + CinemachineVirtualCamera[] newRigs = new CinemachineVirtualCamera[3]; + for (int i = 0; i < RigNames.Length; ++i) + { + CinemachineVirtualCamera src = null; + if (copyFrom != null && copyFrom.Length > i) + src = copyFrom[i]; + + if (CreateRigOverride != null) + newRigs[i] = CreateRigOverride(this, RigNames[i], src); + else + { + // Create a new rig with default components + GameObject go = new GameObject(RigNames[i]); + go.transform.parent = transform; + newRigs[i] = go.AddComponent<CinemachineVirtualCamera>(); + if (src != null) + ReflectionHelpers.CopyFields(src, newRigs[i]); + else + { + go = newRigs[i].GetComponentOwner().gameObject; + go.AddComponent<CinemachineOrbitalTransposer>(); + go.AddComponent<CinemachineComposer>(); + } + } + + // Set up the defaults + newRigs[i].InvalidateComponentPipeline(); + CinemachineOrbitalTransposer orbital = newRigs[i].GetCinemachineComponent<CinemachineOrbitalTransposer>(); + if (orbital == null) + orbital = newRigs[i].AddCinemachineComponent<CinemachineOrbitalTransposer>(); // should not happen + if (src == null) + { + // Only set defaults if not copying + orbital.m_YawDamping = 0; + CinemachineComposer composer = newRigs[i].GetCinemachineComponent<CinemachineComposer>(); + if (composer != null) + { + composer.m_HorizontalDamping = composer.m_VerticalDamping = 0; + composer.m_ScreenX = 0.5f; + composer.m_ScreenY = softCenterDefaultsV[i]; + composer.m_DeadZoneWidth = composer.m_DeadZoneHeight = 0.1f; + composer.m_SoftZoneWidth = composer.m_SoftZoneHeight = 0.8f; + composer.m_BiasX = composer.m_BiasY = 0; + } + } + } + return newRigs; + } + + private void UpdateRigCache() + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.UpdateRigCache"); + if (mIsDestroyed) + { + //UnityEngine.Profiling.Profiler.EndSample(); + return; + } + + // Special condition: Did we just get copy/pasted? + if (m_Rigs != null && m_Rigs.Length == 3 && m_Rigs[0] != null && m_Rigs[0].transform.parent != transform) + { + DestroyRigs(); + m_Rigs = CreateRigs(m_Rigs); + } + + // Early out if we're up to date + if (mOrbitals != null && mOrbitals.Length == 3) + { + //UnityEngine.Profiling.Profiler.EndSample(); + return; + } + + // Locate existing rigs, and recreate them if any are missing + if (LocateExistingRigs(RigNames, false) != 3) + { + DestroyRigs(); + m_Rigs = CreateRigs(null); + LocateExistingRigs(RigNames, true); + } + + foreach (var rig in m_Rigs) + { + // Configure the UI + rig.m_ExcludedPropertiesInInspector = m_CommonLens + ? new string[] { "m_Script", "Header", "Extensions", "m_Priority", "m_Follow", "m_Lens" } + : new string[] { "m_Script", "Header", "Extensions", "m_Priority", "m_Follow" }; + rig.m_LockStageInInspector = new CinemachineCore.Stage[] { CinemachineCore.Stage.Body }; + } + + // Create the blend objects + mBlendA = new CinemachineBlend(m_Rigs[1], m_Rigs[0], AnimationCurve.Linear(0, 0, 1, 1), 1, 0); + mBlendB = new CinemachineBlend(m_Rigs[2], m_Rigs[1], AnimationCurve.Linear(0, 0, 1, 1), 1, 0); + + // Horizontal rotation clamped to [0,360] (with wraparound) + m_XAxis.SetThresholds(0f, 360f, true); + + // Vertical rotation cleamped to [0,1] as it is a t-value for the + // catmull-rom spline going through the 3 points on the rig + m_YAxis.SetThresholds(0f, 1f, false); + //UnityEngine.Profiling.Profiler.EndSample(); + } + + private int LocateExistingRigs(string[] rigNames, bool forceOrbital) + { + mOrbitals = new CinemachineOrbitalTransposer[rigNames.Length]; + m_Rigs = new CinemachineVirtualCamera[rigNames.Length]; + int rigsFound = 0; + foreach (Transform child in transform) + { + CinemachineVirtualCamera vcam = child.GetComponent<CinemachineVirtualCamera>(); + if (vcam != null) + { + GameObject go = child.gameObject; + for (int i = 0; i < rigNames.Length; ++i) + { + if (mOrbitals[i] == null && go.name == rigNames[i]) + { + // Must have an orbital transposer or it's no good + mOrbitals[i] = vcam.GetCinemachineComponent<CinemachineOrbitalTransposer>(); + if (mOrbitals[i] == null && forceOrbital) + mOrbitals[i] = vcam.AddCinemachineComponent<CinemachineOrbitalTransposer>(); + if (mOrbitals[i] != null) + { + mOrbitals[i].m_HeadingIsSlave = true; + if (i == 0) + mOrbitals[i].HeadingUpdater + = (CinemachineOrbitalTransposer orbital, float deltaTime, Vector3 up) + => { return orbital.UpdateHeading(deltaTime, up, ref m_XAxis); }; + m_Rigs[i] = vcam; + ++rigsFound; + } + } + } + } + } + return rigsFound; + } + + void PushSettingsToRigs() + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs"); + UpdateRigCache(); + for (int i = 0; i < m_Rigs.Length; ++i) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs.m_Rigs[i] == null"); + if (m_Rigs[i] == null) + { + //UnityEngine.Profiling.Profiler.EndSample(); + continue; + } + //UnityEngine.Profiling.Profiler.EndSample(); + + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs.m_CommonLens"); + if (m_CommonLens) + m_Rigs[i].m_Lens = m_Lens; + //UnityEngine.Profiling.Profiler.EndSample(); + + // If we just deserialized from a legacy version, + // pull the orbits and targets from the rigs + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs.mUseLegacyRigDefinitions"); + if (mUseLegacyRigDefinitions) + { + mUseLegacyRigDefinitions = false; + m_Orbits[i].m_Height = mOrbitals[i].m_FollowOffset.y; + m_Orbits[i].m_Radius = -mOrbitals[i].m_FollowOffset.z; + if (m_Rigs[i].Follow != null) + Follow = m_Rigs[i].Follow; + } + m_Rigs[i].Follow = null; + //UnityEngine.Profiling.Profiler.EndSample(); + + // Hide the rigs from prying eyes + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs.Hide the rigs"); + if (CinemachineCore.sShowHiddenObjects) + m_Rigs[i].gameObject.hideFlags + &= ~(HideFlags.HideInHierarchy | HideFlags.HideInInspector); + else + m_Rigs[i].gameObject.hideFlags + |= (HideFlags.HideInHierarchy | HideFlags.HideInInspector); + //UnityEngine.Profiling.Profiler.EndSample(); + + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs.Push"); + mOrbitals[i].m_FollowOffset = GetLocalPositionForCameraFromInput(m_YAxis.Value); + mOrbitals[i].m_BindingMode = m_BindingMode; + mOrbitals[i].m_Heading = m_Heading; + mOrbitals[i].m_XAxis = m_XAxis; + mOrbitals[i].m_RecenterToTargetHeading = m_RecenterToTargetHeading; + if (i > 0) + mOrbitals[i].m_RecenterToTargetHeading.m_enabled = false; + + // Hack to get SimpleFollow with heterogeneous dampings to work + if (m_BindingMode == CinemachineTransposer.BindingMode.SimpleFollowWithWorldUp) + m_Rigs[i].SetStateRawPosition(State.RawPosition); + + //UnityEngine.Profiling.Profiler.EndSample(); + } + //UnityEngine.Profiling.Profiler.EndSample(); + } + + private CameraState CalculateNewState(Vector3 worldUp, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.CalculateNewState"); + CameraState state = PullStateFromVirtualCamera(worldUp); + + // Blend from the appropriate rigs + float t = m_YAxis.Value; + if (t > 0.5f) + { + if (mBlendA != null) + { + mBlendA.TimeInBlend = (t - 0.5f) * 2f; + mBlendA.UpdateCameraState(worldUp, deltaTime); + state = mBlendA.State; + } + } + else + { + if (mBlendB != null) + { + mBlendB.TimeInBlend = t * 2f; + mBlendB.UpdateCameraState(worldUp, deltaTime); + state = mBlendB.State; + } + } + //UnityEngine.Profiling.Profiler.EndSample(); + return state; + } + + private CameraState PullStateFromVirtualCamera(Vector3 worldUp) + { + CameraState state = CameraState.Default; + state.RawPosition = transform.position; + state.RawOrientation = transform.rotation; + state.ReferenceUp = worldUp; + + CinemachineBrain brain = CinemachineCore.Instance.FindPotentialTargetBrain(this); + m_Lens.Aspect = brain != null ? brain.OutputCamera.aspect : 1; + m_Lens.Orthographic = brain != null ? brain.OutputCamera.orthographic : false; + state.Lens = m_Lens; + + return state; + } + + /// <summary> + /// Returns the local position of the camera along the spline used to connect the + /// three camera rigs. Does not take into account the current heading of the + /// camera (or its target) + /// </summary> + /// <param name="t">The t-value for the camera on its spline. Internally clamped to + /// the value [0,1]</param> + /// <returns>The local offset (back + up) of the camera WRT its target based on the + /// supplied t-value</returns> + public Vector3 GetLocalPositionForCameraFromInput(float t) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.GetLocalPositionForCameraFromInput"); + if (mOrbitals == null) + { + //UnityEngine.Profiling.Profiler.EndSample(); + return Vector3.zero; + } + UpdateCachedSpline(); + int n = 1; + if (t > 0.5f) + { + t -= 0.5f; + n = 2; + } + //UnityEngine.Profiling.Profiler.EndSample(); + return SplineHelpers.Bezier3( + t * 2f, m_CachedKnots[n], m_CachedCtrl1[n], m_CachedCtrl2[n], m_CachedKnots[n+1]); + } + + Orbit[] m_CachedOrbits; + float m_CachedTension; + Vector4[] m_CachedKnots; + Vector4[] m_CachedCtrl1; + Vector4[] m_CachedCtrl2; + void UpdateCachedSpline() + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.UpdateCachedSpline"); + bool cacheIsValid = (m_CachedOrbits != null && m_CachedTension == m_SplineCurvature); + for (int i = 0; i < 3 && cacheIsValid; ++i) + cacheIsValid = (m_CachedOrbits[i].m_Height == m_Orbits[i].m_Height + && m_CachedOrbits[i].m_Radius == m_Orbits[i].m_Radius); + if (!cacheIsValid) + { + float t = m_SplineCurvature; + m_CachedKnots = new Vector4[5]; + m_CachedCtrl1 = new Vector4[5]; + m_CachedCtrl2 = new Vector4[5]; + m_CachedKnots[1] = new Vector4(0, m_Orbits[2].m_Height, -m_Orbits[2].m_Radius, 0); + m_CachedKnots[2] = new Vector4(0, m_Orbits[1].m_Height, -m_Orbits[1].m_Radius, 0); + m_CachedKnots[3] = new Vector4(0, m_Orbits[0].m_Height, -m_Orbits[0].m_Radius, 0); + m_CachedKnots[0] = Vector4.Lerp(m_CachedKnots[1], Vector4.zero, t); + m_CachedKnots[4] = Vector4.Lerp(m_CachedKnots[3], Vector4.zero, t); + SplineHelpers.ComputeSmoothControlPoints( + ref m_CachedKnots, ref m_CachedCtrl1, ref m_CachedCtrl2); + m_CachedOrbits = new Orbit[3]; + for (int i = 0; i < 3; ++i) + m_CachedOrbits[i] = m_Orbits[i]; + m_CachedTension = m_SplineCurvature; + } + //UnityEngine.Profiling.Profiler.EndSample(); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFreeLook.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFreeLook.cs.meta new file mode 100644 index 0000000..21a70d9 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFreeLook.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 319d2fe34a804e245819465c9505ea59 +timeCreated: 1496775487 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineMixingCamera.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineMixingCamera.cs new file mode 100644 index 0000000..57d3ccb --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineMixingCamera.cs @@ -0,0 +1,262 @@ +using UnityEngine; +using Cinemachine.Utility; +using System.Collections.Generic; + +namespace Cinemachine +{ + /// <summary> + /// CinemachineMixingCamera is a "manager camera" that takes on the state of + /// the weighted average of the states of its child virtual cameras. + /// + /// A fixed number of slots are made available for cameras, rather than a dynamic array. + /// We do it this way in order to support weight animation from the Timeline. + /// Timeline cannot animate array elements. + /// </summary> + [DocumentationSorting(20, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineMixingCamera")] + public class CinemachineMixingCamera : CinemachineVirtualCameraBase + { + /// <summary>The maximum number of tracked cameras. If you want to add + /// more cameras, do it here in the source code, and be sure to add the + /// extra member variables and to make the appropriate changes in + /// GetWeight() and SetWeight(). + /// The inspector will figure itself out based on this value.</summary> + public const int MaxCameras = 8; + + /// <summary>Weight of the first tracked camera</summary> + [Tooltip("The weight of the first tracked camera")] + public float m_Weight0 = 0.5f; + /// <summary>Weight of the second tracked camera</summary> + [Tooltip("The weight of the second tracked camera")] + public float m_Weight1 = 0.5f; + /// <summary>Weight of the third tracked camera</summary> + [Tooltip("The weight of the third tracked camera")] + public float m_Weight2 = 0.5f; + /// <summary>Weight of the fourth tracked camera</summary> + [Tooltip("The weight of the fourth tracked camera")] + public float m_Weight3 = 0.5f; + /// <summary>Weight of the fifth tracked camera</summary> + [Tooltip("The weight of the fifth tracked camera")] + public float m_Weight4 = 0.5f; + /// <summary>Weight of the sixth tracked camera</summary> + [Tooltip("The weight of the sixth tracked camera")] + public float m_Weight5 = 0.5f; + /// <summary>Weight of the seventh tracked camera</summary> + [Tooltip("The weight of the seventh tracked camera")] + public float m_Weight6 = 0.5f; + /// <summary>Weight of the eighth tracked camera</summary> + [Tooltip("The weight of the eighth tracked camera")] + public float m_Weight7 = 0.5f; + + /// <summary>Get the weight of the child at an index.</summary> + /// <param name="index">The child index. Only immediate CinemachineVirtualCameraBase + /// children are counted.</param> + /// <returns>The weight of the camera. Valid only if camera is active and enabled.</returns> + public float GetWeight(int index) + { + switch (index) + { + case 0: return m_Weight0; + case 1: return m_Weight1; + case 2: return m_Weight2; + case 3: return m_Weight3; + case 4: return m_Weight4; + case 5: return m_Weight5; + case 6: return m_Weight6; + case 7: return m_Weight7; + } + Debug.LogError("CinemachineMixingCamera: Invalid index: " + index); + return 0; + } + + /// <summary>Set the weight of the child at an index.</summary> + /// <param name="index">The child index. Only immediate CinemachineVirtualCameraBase + /// children are counted.</param> + /// <param name="w">The weight to set. Can be any non-negative number.</param> + public void SetWeight(int index, float w) + { + switch (index) + { + case 0: m_Weight0 = w; return; + case 1: m_Weight1 = w; return; + case 2: m_Weight2 = w; return; + case 3: m_Weight3 = w; return; + case 4: m_Weight4 = w; return; + case 5: m_Weight5 = w; return; + case 6: m_Weight6 = w; return; + case 7: m_Weight7 = w; return; + } + Debug.LogError("CinemachineMixingCamera: Invalid index: " + index); + } + + /// <summary>Get the weight of the child CinemachineVirtualCameraBase.</summary> + /// <param name="vcam">The child camera.</param> + /// <returns>The weight of the camera. Valid only if camera is active and enabled.</returns> + public float GetWeight(CinemachineVirtualCameraBase vcam) + { + int index; + if (m_indexMap.TryGetValue(vcam, out index)) + return GetWeight(index); + Debug.LogError("CinemachineMixingCamera: Invalid child: " + + ((vcam != null) ? vcam.Name : "(null)")); + return 0; + } + + /// <summary>Set the weight of the child CinemachineVirtualCameraBase.</summary> + /// <param name="vcam">The child camera.</param> + /// <param name="w">The weight to set. Can be any non-negative number.</param> + public void SetWeight(CinemachineVirtualCameraBase vcam, float w) + { + int index; + if (m_indexMap.TryGetValue(vcam, out index)) + SetWeight(index, w); + else + Debug.LogError("CinemachineMixingCamera: Invalid child: " + + ((vcam != null) ? vcam.Name : "(null)")); + } + + /// <summary>Blended camera state</summary> + private CameraState m_State = CameraState.Default; + + /// <summary>Get the current "best" child virtual camera, which is nominally + /// the one with the greatest weight.</summary> + private ICinemachineCamera LiveChild { set; get; } + + /// <summary>The blended CameraState</summary> + public override CameraState State { get { return m_State; } } + + /// <summary>Not used</summary> + override public Transform LookAt { get; set; } + + /// <summary>Not used</summary> + override public Transform Follow { get; set; } + + /// <summary>Return the live child.</summary> + public override ICinemachineCamera LiveChildOrSelf { get { return LiveChild; } } + + /// <summary>Remove a Pipeline stage hook callback. + /// Make sure it is removed from all the children.</summary> + /// <param name="d">The delegate to remove.</param> + public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + base.RemovePostPipelineStageHook(d); + ValidateListOfChildren(); + foreach (var vcam in m_ChildCameras) + vcam.RemovePostPipelineStageHook(d); + } + + /// <summary>Makes sure the internal child cache is up to date</summary> + protected override void OnEnable() + { + base.OnEnable(); + InvalidateListOfChildren(); + } + + /// <summary>Makes sure the internal child cache is up to date</summary> + public void OnTransformChildrenChanged() + { + InvalidateListOfChildren(); + } + + /// <summary>Makes sure the weights are non-negative</summary> + protected override void OnValidate() + { + base.OnValidate(); + for (int i = 0; i < MaxCameras; ++i) + SetWeight(i, Mathf.Max(0, GetWeight(i))); + } + + /// <summary>Check whether the vcam a live child of this camera.</summary> + /// <param name="vcam">The Virtual Camera to check</param> + /// <returns>True if the vcam is currently actively influencing the state of this vcam</returns> + public override bool IsLiveChild(ICinemachineCamera vcam) + { + CinemachineVirtualCameraBase[] children = ChildCameras; + for (int i = 0; i < MaxCameras && i < children.Length; ++i) + if ((ICinemachineCamera)children[i] == vcam) + return GetWeight(i) > UnityVectorExtensions.Epsilon && children[i].isActiveAndEnabled; + return false; + } + + private CinemachineVirtualCameraBase[] m_ChildCameras; + private Dictionary<CinemachineVirtualCameraBase, int> m_indexMap; + + /// <summary>Get the cached list of child cameras. + /// These are just the immediate children in the hierarchy. + /// Note: only the first entries of this list participate in the + /// final blend, up to MaxCameras</summary> + public CinemachineVirtualCameraBase[] ChildCameras + { + get { ValidateListOfChildren(); return m_ChildCameras; } + } + + /// <summary>Invalidate the cached list of child cameras.</summary> + protected void InvalidateListOfChildren() + { + m_ChildCameras = null; + m_indexMap = null; + LiveChild = null; + } + + /// <summary>Rebuild the cached list of child cameras.</summary> + protected void ValidateListOfChildren() + { + if (m_ChildCameras != null) + return; + + m_indexMap = new Dictionary<CinemachineVirtualCameraBase, int>(); + List<CinemachineVirtualCameraBase> list = new List<CinemachineVirtualCameraBase>(); + CinemachineVirtualCameraBase[] kids + = GetComponentsInChildren<CinemachineVirtualCameraBase>(true); + foreach (CinemachineVirtualCameraBase k in kids) + { + if (k.transform.parent == transform) + { + int index = list.Count; + list.Add(k); + if (index < MaxCameras) + m_indexMap.Add(k, index); + } + } + m_ChildCameras = list.ToArray(); + } + + /// <summary>Called by CinemachineCore at designated update time + /// so the vcam can position itself and track its targets. This implementation + /// computes and caches the weighted blend of the tracked cameras.</summary> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than 0)</param> + public override void UpdateCameraState(Vector3 worldUp, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineMixingCamera.UpdateCameraState"); + CinemachineVirtualCameraBase[] children = ChildCameras; + LiveChild = null; + float highestWeight = 0; + float totalWeight = 0; + for (int i = 0; i < MaxCameras && i < children.Length; ++i) + { + CinemachineVirtualCameraBase vcam = children[i]; + if (vcam.isActiveAndEnabled) + { + float weight = Mathf.Max(0, GetWeight(i)); + if (weight > UnityVectorExtensions.Epsilon) + { + totalWeight += weight; + if (totalWeight == weight) + m_State = vcam.State; + else + m_State = CameraState.Lerp(m_State, vcam.State, weight / totalWeight); + + if (weight > highestWeight) + { + highestWeight = weight; + LiveChild = vcam; + } + } + } + } + //UnityEngine.Profiling.Profiler.EndSample(); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineMixingCamera.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineMixingCamera.cs.meta new file mode 100644 index 0000000..d4856d5 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineMixingCamera.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6c26251a3e1f5ac41afa5ffb404c5f71 +timeCreated: 1502201564 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePath.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePath.cs new file mode 100644 index 0000000..b050d2f --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePath.cs @@ -0,0 +1,180 @@ +using UnityEngine; +using System; +using Cinemachine.Utility; + +namespace Cinemachine +{ + /// <summary>Defines a world-space path, consisting of an array of waypoints, + /// each of which has position, tangent, and roll settings. Bezier interpolation + /// is performed between the waypoints, to get a smooth and continuous path.</summary> + [DocumentationSorting(18, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("Cinemachine/CinemachinePath")] + [SaveDuringPlay] + public class CinemachinePath : CinemachinePathBase + { + /// <summary>A waypoint along the path</summary> + [DocumentationSorting(18.2f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] public struct Waypoint + { + /// <summary>Position in path-local space</summary> + [Tooltip("Position in path-local space")] + public Vector3 position; + + /// <summary>Offset from the position, which defines the tangent of the curve at the waypoint. + /// The length of the tangent encodes the strength of the bezier handle. + /// The same handle is used symmetrically on both sides of the waypoint, to ensure smoothness.</summary> + [Tooltip("Offset from the position, which defines the tangent of the curve at the waypoint. The length of the tangent encodes the strength of the bezier handle. The same handle is used symmetrically on both sides of the waypoint, to ensure smoothness.")] + public Vector3 tangent; + + /// <summary>Defines the roll of the path at this waypoint. + /// The other orientation axes are inferred from the tangent and world up.</summary> + [Tooltip("Defines the roll of the path at this waypoint. The other orientation axes are inferred from the tangent and world up.")] + public float roll; + } + + /// <summary>If checked, then the path ends are joined to form a continuous loop</summary> + [Tooltip("If checked, then the path ends are joined to form a continuous loop.")] + public bool m_Looped; + + /// <summary>The waypoints that define the path. + /// They will be interpolated using a bezier curve</summary> + [Tooltip("The waypoints that define the path. They will be interpolated using a bezier curve.")] + public Waypoint[] m_Waypoints = new Waypoint[0]; + + /// <summary>The minimum value for the path position</summary> + public override float MinPos { get { return 0; } } + + /// <summary>The maximum value for the path position</summary> + public override float MaxPos + { + get + { + int count = m_Waypoints.Length - 1; + if (count < 1) + return 0; + return m_Looped ? count + 1 : count; + } + } + /// <summary>True if the path ends are joined to form a continuous loop</summary> + public override bool Looped { get { return m_Looped; } } + + /// <summary>When calculating the distance cache, sample the path this many + /// times between points</summary> + public override int DistanceCacheSampleStepsPerSegment { get { return m_Resolution; } } + + /// <summary>Returns normalized position</summary> + float GetBoundingIndices(float pos, out int indexA, out int indexB) + { + pos = NormalizePos(pos); + int rounded = Mathf.RoundToInt(pos); + if (Mathf.Abs(pos - rounded) < UnityVectorExtensions.Epsilon) + indexA = indexB = (rounded == m_Waypoints.Length) ? 0 : rounded; + else + { + indexA = Mathf.FloorToInt(pos); + if (indexA >= m_Waypoints.Length) + { + pos -= MaxPos; + indexA = 0; + } + indexB = Mathf.CeilToInt(pos); + if (indexB >= m_Waypoints.Length) + indexB = 0; + } + return pos; + } + + /// <summary>Get a worldspace position of a point along the path</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <returns>World-space position of the point along at path at pos</returns> + public override Vector3 EvaluatePosition(float pos) + { + Vector3 result = new Vector3(); + if (m_Waypoints.Length == 0) + result = transform.position; + else + { + int indexA, indexB; + pos = GetBoundingIndices(pos, out indexA, out indexB); + if (indexA == indexB) + result = m_Waypoints[indexA].position; + else + { + // interpolate + Waypoint wpA = m_Waypoints[indexA]; + Waypoint wpB = m_Waypoints[indexB]; + result = SplineHelpers.Bezier3(pos - indexA, + m_Waypoints[indexA].position, wpA.position + wpA.tangent, + wpB.position - wpB.tangent, wpB.position); + } + } + return transform.TransformPoint(result); + } + + /// <summary>Get the tangent of the curve at a point along the path.</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <returns>World-space direction of the path tangent. + /// Length of the vector represents the tangent strength</returns> + public override Vector3 EvaluateTangent(float pos) + { + Vector3 result = new Vector3(); + if (m_Waypoints.Length == 0) + result = transform.rotation * Vector3.forward; + else + { + int indexA, indexB; + pos = GetBoundingIndices(pos, out indexA, out indexB); + if (indexA == indexB) + result = m_Waypoints[indexA].tangent; + else + { + Waypoint wpA = m_Waypoints[indexA]; + Waypoint wpB = m_Waypoints[indexB]; + result = SplineHelpers.BezierTangent3(pos - indexA, + m_Waypoints[indexA].position, wpA.position + wpA.tangent, + wpB.position - wpB.tangent, wpB.position); + } + } + return transform.TransformDirection(result); + } + + /// <summary>Get the orientation the curve at a point along the path.</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <returns>World-space orientation of the path, as defined by tangent, up, and roll.</returns> + public override Quaternion EvaluateOrientation(float pos) + { + Quaternion result = transform.rotation; + if (m_Waypoints.Length > 0) + { + float roll = 0; + int indexA, indexB; + pos = GetBoundingIndices(pos, out indexA, out indexB); + if (indexA == indexB) + roll = m_Waypoints[indexA].roll; + else + { + float rollA = m_Waypoints[indexA].roll; + float rollB = m_Waypoints[indexB].roll; + if (indexB == 0) + { + // Special handling at the wraparound - cancel the spins + rollA = rollA % 360; + rollB = rollB % 360; + } + roll = Mathf.Lerp(rollA, rollB, pos - indexA); + } + + Vector3 fwd = EvaluateTangent(pos); + if (!fwd.AlmostZero()) + { + Vector3 up = transform.rotation * Vector3.up; + Quaternion q = Quaternion.LookRotation(fwd, up); + result = q * Quaternion.AngleAxis(roll, Vector3.forward); + } + } + return result; + } + + private void OnValidate() { InvalidateDistanceCache(); } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePath.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePath.cs.meta new file mode 100644 index 0000000..0021d0c --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePath.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2d37e5385efd7064cb1d54c94960acae +timeCreated: 1496785107 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePipeline.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePipeline.cs new file mode 100644 index 0000000..5474e7c --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePipeline.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +namespace Cinemachine +{ + /// <summary> + /// Internal container for CinemachineComponentBase. Does nothing but contain. + /// </summary> + [AddComponentMenu("")] // Don't display in add component menu + public sealed class CinemachinePipeline : MonoBehaviour + { + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePipeline.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePipeline.cs.meta new file mode 100644 index 0000000..0f151c5 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePipeline.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ac0b09e7857660247b1477e93731de29 +timeCreated: 1489088253 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoothPath.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoothPath.cs new file mode 100644 index 0000000..5eef99e --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoothPath.cs @@ -0,0 +1,224 @@ +using UnityEngine; +using System; +using Cinemachine.Utility; + +namespace Cinemachine +{ + /// <summary>Defines a world-space path, consisting of an array of waypoints, + /// each of which has position and roll settings. Bezier interpolation + /// is performed between the waypoints, to get a smooth and continuous path. + /// The path will pass through all waypoints, and (unlike CinemachinePath) first + /// and second order continuity is guaranteed</summary> + [DocumentationSorting(18.5f, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("Cinemachine/CinemachineSmoothPath")] + [SaveDuringPlay] + public class CinemachineSmoothPath : CinemachinePathBase + { + /// <summary>If checked, then the path ends are joined to form a continuous loop</summary> + [Tooltip("If checked, then the path ends are joined to form a continuous loop.")] + public bool m_Looped; + + /// <summary>A waypoint along the path</summary> + [DocumentationSorting(18.7f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] public struct Waypoint + { + /// <summary>Position in path-local space</summary> + [Tooltip("Position in path-local space")] + public Vector3 position; + + /// <summary>Defines the roll of the path at this waypoint. + /// The other orientation axes are inferred from the tangent and world up.</summary> + [Tooltip("Defines the roll of the path at this waypoint. The other orientation axes are inferred from the tangent and world up.")] + public float roll; + + /// <summary>Representation as Vector4</summary> + internal Vector4 AsVector4 + { + get { return new Vector4(position.x, position.y, position.z, roll); } + } + + internal static Waypoint FromVector4(Vector4 v) + { + Waypoint wp = new Waypoint(); + wp.position = new Vector3(v[0], v[1], v[2]); + wp.roll = v[3]; + return wp; + } + } + + /// <summary>The waypoints that define the path. + /// They will be interpolated using a bezier curve</summary> + [Tooltip("The waypoints that define the path. They will be interpolated using a bezier curve.")] + public Waypoint[] m_Waypoints = new Waypoint[0]; + + /// <summary>The minimum value for the path position</summary> + public override float MinPos { get { return 0; } } + + /// <summary>The maximum value for the path position</summary> + public override float MaxPos + { + get + { + int count = m_Waypoints.Length - 1; + if (count < 1) + return 0; + return m_Looped ? count + 1 : count; + } + } + /// <summary>True if the path ends are joined to form a continuous loop</summary> + public override bool Looped { get { return m_Looped; } } + + /// <summary>When calculating the distance cache, sample the path this many + /// times between points</summary> + public override int DistanceCacheSampleStepsPerSegment { get { return m_Resolution; } } + + private void OnValidate() { InvalidateDistanceCache(); } + + /// <summary>Call this if the path changes in such a way as to affect distances + /// or other cached path elements</summary> + public override void InvalidateDistanceCache() + { + base.InvalidateDistanceCache(); + m_ControlPoints1 = null; + m_ControlPoints2 = null; + } + + Waypoint[] m_ControlPoints1; + Waypoint[] m_ControlPoints2; + bool m_IsLoopedCache; + + void UpdateControlPoints() + { + int numPoints = (m_Waypoints == null) ? 0 : m_Waypoints.Length; + if (numPoints > 1 + && (Looped != m_IsLoopedCache + || m_ControlPoints1 == null || m_ControlPoints1.Length != numPoints + || m_ControlPoints2 == null || m_ControlPoints2.Length != numPoints)) + { + Vector4[] p1 = new Vector4[numPoints]; + Vector4[] p2 = new Vector4[numPoints]; + Vector4[] K = new Vector4[numPoints]; + for (int i = 0; i < numPoints; ++i) + K[i] = m_Waypoints[i].AsVector4; + if (Looped) + SplineHelpers.ComputeSmoothControlPointsLooped(ref K, ref p1, ref p2); + else + SplineHelpers.ComputeSmoothControlPoints(ref K, ref p1, ref p2); + + m_ControlPoints1 = new Waypoint[numPoints]; + m_ControlPoints2 = new Waypoint[numPoints]; + for (int i = 0; i < numPoints; ++i) + { + m_ControlPoints1[i] = Waypoint.FromVector4(p1[i]); + m_ControlPoints2[i] = Waypoint.FromVector4(p2[i]); + } + m_IsLoopedCache = Looped; + } + } + + /// <summary>Returns normalized position</summary> + float GetBoundingIndices(float pos, out int indexA, out int indexB) + { + pos = NormalizePos(pos); + int numWaypoints = m_Waypoints.Length; + if (numWaypoints < 2) + indexA = indexB = 0; + else + { + indexA = Mathf.FloorToInt(pos); + if (indexA >= numWaypoints) + { + // Only true if looped + pos -= MaxPos; + indexA = 0; + } + indexB = indexA + 1; + if (indexB == numWaypoints) + { + if (Looped) + indexB = 0; + else + { + --indexB; + --indexA; + } + } + } + return pos; + } + + /// <summary>Get a worldspace position of a point along the path</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <returns>World-space position of the point along at path at pos</returns> + public override Vector3 EvaluatePosition(float pos) + { + Vector3 result = Vector3.zero; + if (m_Waypoints.Length > 0) + { + UpdateControlPoints(); + int indexA, indexB; + pos = GetBoundingIndices(pos, out indexA, out indexB); + if (indexA == indexB) + result = m_Waypoints[indexA].position; + else + result = SplineHelpers.Bezier3(pos - indexA, + m_Waypoints[indexA].position, m_ControlPoints1[indexA].position, + m_ControlPoints2[indexA].position, m_Waypoints[indexB].position); + } + return transform.TransformPoint(result); + } + + /// <summary>Get the tangent of the curve at a point along the path.</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <returns>World-space direction of the path tangent. + /// Length of the vector represents the tangent strength</returns> + public override Vector3 EvaluateTangent(float pos) + { + Vector3 result = transform.rotation * Vector3.forward; + if (m_Waypoints.Length > 1) + { + UpdateControlPoints(); + int indexA, indexB; + pos = GetBoundingIndices(pos, out indexA, out indexB); + if (!Looped && indexA == m_Waypoints.Length - 1) + --indexA; + result = SplineHelpers.BezierTangent3(pos - indexA, + m_Waypoints[indexA].position, m_ControlPoints1[indexA].position, + m_ControlPoints2[indexA].position, m_Waypoints[indexB].position); + } + return transform.TransformDirection(result); + } + + /// <summary>Get the orientation the curve at a point along the path.</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <returns>World-space orientation of the path, as defined by tangent, up, and roll.</returns> + public override Quaternion EvaluateOrientation(float pos) + { + Quaternion result = transform.rotation; + if (m_Waypoints.Length > 0) + { + float roll = 0; + int indexA, indexB; + pos = GetBoundingIndices(pos, out indexA, out indexB); + if (indexA == indexB) + roll = m_Waypoints[indexA].roll; + else + { + UpdateControlPoints(); + roll = SplineHelpers.Bezier1(pos - indexA, + m_Waypoints[indexA].roll, m_ControlPoints1[indexA].roll, + m_ControlPoints2[indexA].roll, m_Waypoints[indexB].roll); + } + + Vector3 fwd = EvaluateTangent(pos); + if (!fwd.AlmostZero()) + { + Vector3 up = transform.rotation * Vector3.up; + Quaternion q = Quaternion.LookRotation(fwd, up); + result = q * Quaternion.AngleAxis(roll, Vector3.forward); + } + } + return result; + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoothPath.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoothPath.cs.meta new file mode 100644 index 0000000..4dd2554 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoothPath.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a200b19ca1a9685429ed7e043c28e904 +timeCreated: 1505831686 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoother.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoother.cs new file mode 100644 index 0000000..f0b5290 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoother.cs @@ -0,0 +1,103 @@ +#if false // GML We disable smoother because people are too tempted to use it. It won't give good results. +using UnityEngine; +using Cinemachine.Utility; + +namespace Cinemachine +{ + /// <summary> + /// An add-on module for Cinemachine Virtual Camera which post-processes + /// the final position and orientation of the virtual camera, as a kind of low-pass filter. + /// </summary> + [DocumentationSorting(17, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] + [AddComponentMenu("")] // Hide in menu + [SaveDuringPlay] + public class CinemachineSmoother : CinemachineExtension + { + /// <summary> + /// The strength of the smoothing for position. This is applied after the vcam cas calculated its state. + /// </summary> + [Range(0f, 10f)] + [Tooltip("The strength of the smoothing for position. Higher numbers smooth more but reduce performance and introduce lag.")] + public float m_PositionSmoothing = 1; + + /// <summary> + /// The strength of the smoothing for the LookAt target. This is applied after the vcam cas calculated its state. + /// </summary> + [Range(0f, 10f)] + [Tooltip("The strength of the smoothing for the LookAt target. Higher numbers smooth more but reduce performance and introduce lag.")] + public float m_LookAtSmoothing = 1; + + /// <summary> + /// The strength of the smoothing for rotation. This is applied after the vcam cas calculated its state. + /// </summary> + [Range(0f, 10f)] + [Tooltip("The strength of the smoothing for rotation. Higher numbers smooth more but reduce performance and introduce lag.")] + public float m_RotationSmoothing = 1; + + protected override void PostPipelineStageCallback( + CinemachineVirtualCameraBase vcam, + CinemachineCore.Stage stage, ref CameraState state, float deltaTime) + { + if (stage == CinemachineCore.Stage.Body) + { + VcamExtraState extra = GetExtraState<VcamExtraState>(vcam); + if (m_PositionSmoothing > 0) + { + if (deltaTime < 0) + extra.mSmoothingFilter = null; // reset the filter + state.PositionCorrection + += ApplySmoothing(vcam, state.CorrectedPosition, extra) - state.CorrectedPosition; + } + if (m_LookAtSmoothing > 0 && state.HasLookAt) + { + if (deltaTime < 0) + extra.mSmoothingFilterLookAt = null; // reset the filter + state.ReferenceLookAt = ApplySmoothingLookAt(vcam, state.ReferenceLookAt, extra); + } + } + if (stage == CinemachineCore.Stage.Aim) + { + if (m_RotationSmoothing > 0) + { + VcamExtraState extra = GetExtraState<VcamExtraState>(vcam); + if (deltaTime < 0) + extra.mSmoothingFilterRotation = null; // reset the filter + Quaternion q = Quaternion.Inverse(state.CorrectedOrientation) + * ApplySmoothing(vcam, state.CorrectedOrientation, state.ReferenceUp, extra); + state.OrientationCorrection = state.OrientationCorrection * q; + } + } + } + + class VcamExtraState + { + public GaussianWindow1D_Vector3 mSmoothingFilter; + public GaussianWindow1D_Vector3 mSmoothingFilterLookAt; + public GaussianWindow1D_CameraRotation mSmoothingFilterRotation; + }; + + private Vector3 ApplySmoothing(CinemachineVirtualCameraBase vcam, Vector3 pos, VcamExtraState extra) + { + if (extra.mSmoothingFilter == null || extra.mSmoothingFilter.Sigma != m_PositionSmoothing) + extra.mSmoothingFilter = new GaussianWindow1D_Vector3(m_PositionSmoothing); + return extra.mSmoothingFilter.Filter(pos); + } + + private Vector3 ApplySmoothingLookAt(CinemachineVirtualCameraBase vcam, Vector3 pos, VcamExtraState extra) + { + if (extra.mSmoothingFilterLookAt == null || extra.mSmoothingFilterLookAt.Sigma != m_LookAtSmoothing) + extra.mSmoothingFilterLookAt = new GaussianWindow1D_Vector3(m_LookAtSmoothing); + return extra.mSmoothingFilterLookAt.Filter(pos); + } + + private Quaternion ApplySmoothing(CinemachineVirtualCameraBase vcam, Quaternion rot, Vector3 up, VcamExtraState extra) + { + if (extra.mSmoothingFilterRotation == null || extra.mSmoothingFilterRotation.Sigma != m_RotationSmoothing) + extra.mSmoothingFilterRotation = new GaussianWindow1D_CameraRotation(m_RotationSmoothing); + Vector3 camRot = Quaternion.identity.GetCameraRotationToTarget(rot * Vector3.forward, up); + return Quaternion.identity.ApplyCameraRotation(extra.mSmoothingFilterRotation.Filter(camRot), up); + } + } +} +#endif diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoother.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoother.cs.meta new file mode 100644 index 0000000..1b213cb --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoother.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f497b01325ac7a041bd6e365a9ea0e93 +timeCreated: 1490724540 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineStateDrivenCamera.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineStateDrivenCamera.cs new file mode 100644 index 0000000..50d3d34 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineStateDrivenCamera.cs @@ -0,0 +1,512 @@ +using Cinemachine.Utility; +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Cinemachine +{ + /// <summary> + /// This is a virtual camera "manager" that owns and manages a collection + /// of child Virtual Cameras. These child vcams are mapped to individual states in + /// an animation state machine, allowing you to associate specific vcams to specific + /// animation states. When that state is active in the state machine, then the + /// associated camera will be activated. + /// + /// You can define custom blends and transitions between child cameras. + /// + /// In order to use this behaviour, you must have an animated target (i.e. an object + /// animated with a state machine) to drive the behaviour. + /// </summary> + [DocumentationSorting(13, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineStateDrivenCamera")] + public class CinemachineStateDrivenCamera : CinemachineVirtualCameraBase + { + /// <summary>Default object for the camera children to look at (the aim target), if not specified in a child rig. May be empty</summary> + [Tooltip("Default object for the camera children to look at (the aim target), if not specified in a child camera. May be empty if all of the children define targets of their own.")] + [NoSaveDuringPlay] + public Transform m_LookAt = null; + + /// <summary>Default object for the camera children wants to move with (the body target), if not specified in a child rig. May be empty</summary> + [Tooltip("Default object for the camera children wants to move with (the body target), if not specified in a child camera. May be empty if all of the children define targets of their own.")] + [NoSaveDuringPlay] + public Transform m_Follow = null; + + /// <summary>The state machine whose state changes will drive this camera's choice of active child</summary> + [Space] + [Tooltip("The state machine whose state changes will drive this camera's choice of active child")] + public Animator m_AnimatedTarget; + + /// <summary>Which layer in the target FSM to observe</summary> + [Tooltip("Which layer in the target state machine to observe")] + public int m_LayerIndex; + + /// <summary>When enabled, the current camera and blend will be indicated in the game window, for debugging</summary> + [Tooltip("When enabled, the current child camera and blend will be indicated in the game window, for debugging")] + public bool m_ShowDebugText = false; + + /// <summary>Force all child cameras to be enabled. This is useful if animating them in Timeline, but consumes extra resources.</summary> + [Tooltip("Force all child cameras to be enabled. This is useful if animating them in Timeline, but consumes extra resources")] + public bool m_EnableAllChildCameras; + + /// <summary>Internal API for the editor. Do not use this field</summary> + [SerializeField][HideInInspector][NoSaveDuringPlay] + public CinemachineVirtualCameraBase[] m_ChildCameras = null; + + /// <summary>This represents a single instrunction to the StateDrivenCamera. It associates + /// an state from the state machine with a child Virtual Camera, and also holds + /// activation tuning parameters.</summary> + [Serializable] + public struct Instruction + { + /// <summary>The full hash of the animation state</summary> + [Tooltip("The full hash of the animation state")] + public int m_FullHash; + /// <summary>The virtual camera to activate whrn the animation state becomes active</summary> + [Tooltip("The virtual camera to activate whrn the animation state becomes active")] + public CinemachineVirtualCameraBase m_VirtualCamera; + /// <summary>How long to wait (in seconds) before activating the virtual camera. + /// This filters out very short state durations</summary> + [Tooltip("How long to wait (in seconds) before activating the virtual camera. This filters out very short state durations")] + public float m_ActivateAfter; + /// <summary>The minimum length of time (in seconds) to keep a virtual camera active</summary> + [Tooltip("The minimum length of time (in seconds) to keep a virtual camera active")] + public float m_MinDuration; + }; + + /// <summary>The set of instructions associating virtual cameras with states. + /// These instructions are used to choose the live child at any given moment</summary> + [Tooltip("The set of instructions associating virtual cameras with states. These instructions are used to choose the live child at any given moment")] + public Instruction[] m_Instructions; + + /// <summary> + /// The blend which is used if you don't explicitly define a blend between two Virtual Camera children. + /// </summary> + [CinemachineBlendDefinitionProperty] + [Tooltip("The blend which is used if you don't explicitly define a blend between two Virtual Camera children")] + public CinemachineBlendDefinition m_DefaultBlend + = new CinemachineBlendDefinition(CinemachineBlendDefinition.Style.EaseInOut, 0.5f); + + /// <summary> + /// This is the asset which contains custom settings for specific child blends. + /// </summary> + [Tooltip("This is the asset which contains custom settings for specific child blends")] + public CinemachineBlenderSettings m_CustomBlends = null; + + /// <summary>Internal API for the Inspector editor. This implements nested states.</summary> + [Serializable] + [DocumentationSorting(13.2f, DocumentationSortingAttribute.Level.Undoc)] + public struct ParentHash + { + /// <summary>Internal API for the Inspector editor</summary> + public int m_Hash; + /// <summary>Internal API for the Inspector editor</summary> + public int m_ParentHash; + /// <summary>Internal API for the Inspector editor</summary> + public ParentHash(int h, int p) { m_Hash = h; m_ParentHash = p; } + } + /// <summary>Internal API for the Inspector editor</summary> + [HideInInspector][SerializeField] public ParentHash[] m_ParentHash = null; + + /// <summary>Gets a brief debug description of this virtual camera, for use when displayiong debug info</summary> + public override string Description + { + get + { + // Show the active camera and blend + ICinemachineCamera vcam = LiveChild; + if (mActiveBlend == null) + return (vcam != null) ? "[" + vcam.Name + "]" : "(none)"; + return mActiveBlend.Description; + } + } + + /// <summary>Get the current "best" child virtual camera, that would be chosen + /// if the State Driven Camera were active.</summary> + public ICinemachineCamera LiveChild { set; get; } + + /// <summary>Return the live child.</summary> + public override ICinemachineCamera LiveChildOrSelf { get { return LiveChild; } } + + /// <summary>Check whether the vcam a live child of this camera.</summary> + /// <param name="vcam">The Virtual Camera to check</param> + /// <returns>True if the vcam is currently actively influencing the state of this vcam</returns> + public override bool IsLiveChild(ICinemachineCamera vcam) + { + return vcam == LiveChild + || (mActiveBlend != null && (vcam == mActiveBlend.CamA || vcam == mActiveBlend.CamB)); + } + + /// <summary>The State of the current live child</summary> + public override CameraState State { get { return m_State; } } + + /// <summary>Get the current LookAt target. Returns parent's LookAt if parent + /// is non-null and no specific LookAt defined for this camera</summary> + override public Transform LookAt + { + get { return ResolveLookAt(m_LookAt); } + set { m_LookAt = value; } + } + + /// <summary>Get the current Follow target. Returns parent's Follow if parent + /// is non-null and no specific Follow defined for this camera</summary> + override public Transform Follow + { + get { return ResolveFollow(m_Follow); } + set { m_Follow = value; } + } + + /// <summary>Remove a Pipeline stage hook callback. + /// Make sure it is removed from all the children.</summary> + /// <param name="d">The delegate to remove.</param> + public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + base.RemovePostPipelineStageHook(d); + UpdateListOfChildren(); + foreach (var vcam in m_ChildCameras) + vcam.RemovePostPipelineStageHook(d); + } + + /// <summary>Called by CinemachineCore at designated update time + /// so the vcam can position itself and track its targets. This implementation + /// updates all the children, chooses the best one, and implements any required blending.</summary> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param> + public override void UpdateCameraState(Vector3 worldUp, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineStateDrivenCamera.UpdateCameraState"); + if (!PreviousStateIsValid) + deltaTime = -1; + + UpdateListOfChildren(); + CinemachineVirtualCameraBase best = ChooseCurrentCamera(deltaTime); + if (m_ChildCameras != null) + { + for (int i = 0; i < m_ChildCameras.Length; ++i) + { + CinemachineVirtualCameraBase vcam = m_ChildCameras[i]; + if (vcam != null) + { + bool enableChild = m_EnableAllChildCameras || vcam == best; + if (enableChild != vcam.VirtualCameraGameObject.activeInHierarchy) + { + vcam.gameObject.SetActive(enableChild); + if (enableChild) + CinemachineCore.Instance.UpdateVirtualCamera(vcam, worldUp, deltaTime); + } + } + } + } + + ICinemachineCamera previousCam = LiveChild; + LiveChild = best; + + // Are we transitioning cameras? + if (previousCam != null && LiveChild != null && previousCam != LiveChild) + { + // Create a blend (will be null if a cut) + float duration = 0; + AnimationCurve curve = LookupBlendCurve(previousCam, LiveChild, out duration); + mActiveBlend = CreateBlend( + previousCam, LiveChild, + curve, duration, mActiveBlend, deltaTime); + + // Notify incoming camera of transition + LiveChild.OnTransitionFromCamera(previousCam, worldUp, deltaTime); + + // Generate Camera Activation event if live + CinemachineCore.Instance.GenerateCameraActivationEvent(LiveChild); + + // If cutting, generate a camera cut event if live + if (mActiveBlend == null) + CinemachineCore.Instance.GenerateCameraCutEvent(LiveChild); + } + + // Advance the current blend (if any) + if (mActiveBlend != null) + { + mActiveBlend.TimeInBlend += (deltaTime >= 0) + ? deltaTime : mActiveBlend.Duration; + if (mActiveBlend.IsComplete) + mActiveBlend = null; + } + + if (mActiveBlend != null) + { + mActiveBlend.UpdateCameraState(worldUp, deltaTime); + m_State = mActiveBlend.State; + } + else if (LiveChild != null) + m_State = LiveChild.State; + + PreviousStateIsValid = true; + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// <summary>Makes sure the internal child cache is up to date</summary> + protected override void OnEnable() + { + base.OnEnable(); + InvalidateListOfChildren(); + mActiveBlend = null; + } + + /// <summary>Makes sure the internal child cache is up to date</summary> + public void OnTransformChildrenChanged() + { + InvalidateListOfChildren(); + } + +#if UNITY_EDITOR + /// <summary>Displays the current active camera on the game screen, if requested</summary> + protected override void OnGUI() + { + base.OnGUI(); + if (!m_ShowDebugText) + CinemachineGameWindowDebug.ReleaseScreenPos(this); + else + { + string text = Name + ": " + Description; + Rect r = CinemachineGameWindowDebug.GetScreenPos(this, text, GUI.skin.box); + GUI.Label(r, text, GUI.skin.box); + } + } +#endif + CameraState m_State = CameraState.Default; + + /// <summary>The list of child cameras. These are just the immediate children in the hierarchy.</summary> + public CinemachineVirtualCameraBase[] ChildCameras { get { UpdateListOfChildren(); return m_ChildCameras; }} + + /// <summary>Is there a blend in progress?</summary> + public bool IsBlending { get { return mActiveBlend != null; } } + + /// <summary>API for the inspector editor. Animation module does not have hashes + /// for state parents, so we have to invent them in order to implement nested state + /// handling</summary> + public static string CreateFakeHashName(int parentHash, string stateName) + { return parentHash.ToString() + "_" + stateName; } + + float mActivationTime = 0; + Instruction mActiveInstruction; + float mPendingActivationTime = 0; + Instruction mPendingInstruction; + private CinemachineBlend mActiveBlend = null; + + void InvalidateListOfChildren() { m_ChildCameras = null; LiveChild = null; } + + void UpdateListOfChildren() + { + if (m_ChildCameras != null && mInstructionDictionary != null && mStateParentLookup != null) + return; + List<CinemachineVirtualCameraBase> list = new List<CinemachineVirtualCameraBase>(); + CinemachineVirtualCameraBase[] kids = GetComponentsInChildren<CinemachineVirtualCameraBase>(true); + foreach (CinemachineVirtualCameraBase k in kids) + if (k.transform.parent == transform) + list.Add(k); + m_ChildCameras = list.ToArray(); + ValidateInstructions(); + } + + private Dictionary<int, int> mInstructionDictionary; + private Dictionary<int, int> mStateParentLookup; + /// <summary>Internal API for the inspector editor.</summary> + public void ValidateInstructions() + { + if (m_Instructions == null) + m_Instructions = new Instruction[0]; + mInstructionDictionary = new Dictionary<int, int>(); + for (int i = 0; i < m_Instructions.Length; ++i) + { + if (m_Instructions[i].m_VirtualCamera != null + && m_Instructions[i].m_VirtualCamera.transform.parent != transform) + { + m_Instructions[i].m_VirtualCamera = null; + } + mInstructionDictionary[m_Instructions[i].m_FullHash] = i; + } + + // Create the parent lookup + mStateParentLookup = new Dictionary<int, int>(); + if (m_ParentHash != null) + foreach (var i in m_ParentHash) + mStateParentLookup[i.m_Hash] = i.m_ParentHash; + + // Zap the cached current instructions + mActivationTime = mPendingActivationTime = 0; + mActiveBlend = null; + } + + List<AnimatorClipInfo> m_clipInfoList = new List<AnimatorClipInfo>(); + private CinemachineVirtualCameraBase ChooseCurrentCamera(float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineStateDrivenCamera.ChooseCurrentCamera"); + if (m_ChildCameras == null || m_ChildCameras.Length == 0) + { + mActivationTime = 0; + //UnityEngine.Profiling.Profiler.EndSample(); + return null; + } + CinemachineVirtualCameraBase defaultCam = m_ChildCameras[0]; + if (m_AnimatedTarget == null || !m_AnimatedTarget.gameObject.activeSelf + || m_AnimatedTarget.runtimeAnimatorController == null + || m_LayerIndex < 0 || m_LayerIndex >= m_AnimatedTarget.layerCount) + { + mActivationTime = 0; + //UnityEngine.Profiling.Profiler.EndSample(); + return defaultCam; + } + + // Get the current state + int hash; + if (m_AnimatedTarget.IsInTransition(m_LayerIndex)) + { + // Force "current" state to be the state we're transitionaing to + AnimatorStateInfo info = m_AnimatedTarget.GetNextAnimatorStateInfo(m_LayerIndex); + hash = info.fullPathHash; + if (m_AnimatedTarget.GetNextAnimatorClipInfoCount(m_LayerIndex) > 1) + { + m_AnimatedTarget.GetNextAnimatorClipInfo(m_LayerIndex, m_clipInfoList); + hash = GetClipHash(info.fullPathHash, m_clipInfoList); + } + } + else + { + AnimatorStateInfo info = m_AnimatedTarget.GetCurrentAnimatorStateInfo(m_LayerIndex); + hash = info.fullPathHash; + if (m_AnimatedTarget.GetCurrentAnimatorClipInfoCount(m_LayerIndex) > 1) + { + m_AnimatedTarget.GetCurrentAnimatorClipInfo(m_LayerIndex, m_clipInfoList); + hash = GetClipHash(info.fullPathHash, m_clipInfoList); + } + } + + // If we don't have an instruction for this state, find a suitable default + while (hash != 0 && !mInstructionDictionary.ContainsKey(hash)) + hash = mStateParentLookup.ContainsKey(hash) ? mStateParentLookup[hash] : 0; + + float now = Time.time; + if (mActivationTime != 0) + { + // Is it active now? + if (mActiveInstruction.m_FullHash == hash) + { + // Yes, cancel any pending + mPendingActivationTime = 0; + //UnityEngine.Profiling.Profiler.EndSample(); + return mActiveInstruction.m_VirtualCamera; + } + + // Is it pending? + if (deltaTime >= 0) + { + if (mPendingActivationTime != 0 && mPendingInstruction.m_FullHash == hash) + { + // Has it been pending long enough, and are we allowed to switch away + // from the active action? + if ((now - mPendingActivationTime) > mPendingInstruction.m_ActivateAfter + && ((now - mActivationTime) > mActiveInstruction.m_MinDuration + || mPendingInstruction.m_VirtualCamera.Priority + > mActiveInstruction.m_VirtualCamera.Priority)) + { + // Yes, activate it now + mActiveInstruction = mPendingInstruction; + mActivationTime = now; + mPendingActivationTime = 0; + } + //UnityEngine.Profiling.Profiler.EndSample(); + return mActiveInstruction.m_VirtualCamera; + } + } + } + // Neither active nor pending. + mPendingActivationTime = 0; // cancel the pending, if any + + if (!mInstructionDictionary.ContainsKey(hash)) + { + // No defaults set, we just ignore this state + if (mActivationTime != 0) + return mActiveInstruction.m_VirtualCamera; + //UnityEngine.Profiling.Profiler.EndSample(); + return defaultCam; + } + + // Can we activate it now? + Instruction newInstr = m_Instructions[mInstructionDictionary[hash]]; + if (newInstr.m_VirtualCamera == null) + newInstr.m_VirtualCamera = defaultCam; + if (deltaTime >= 0 && mActivationTime > 0) + { + if (newInstr.m_ActivateAfter > 0 + || ((now - mActivationTime) < mActiveInstruction.m_MinDuration + && newInstr.m_VirtualCamera.Priority + <= mActiveInstruction.m_VirtualCamera.Priority)) + { + // Too early - make it pending + mPendingInstruction = newInstr; + mPendingActivationTime = now; + if (mActivationTime != 0) + return mActiveInstruction.m_VirtualCamera; + //UnityEngine.Profiling.Profiler.EndSample(); + return defaultCam; + } + } + // Activate now + mActiveInstruction = newInstr; + mActivationTime = now; + //UnityEngine.Profiling.Profiler.EndSample(); + return mActiveInstruction.m_VirtualCamera; + } + + int GetClipHash(int hash, List<AnimatorClipInfo> clips) + { + // Is there an animation clip substate? + if (clips.Count > 1) + { + // Find the strongest-weighted one + int bestClip = -1; + for (int i = 0; i < clips.Count; ++i) + if (bestClip < 0 || clips[i].weight > clips[bestClip].weight) + bestClip = i; + + // Use its hash + if (bestClip >= 0 && clips[bestClip].weight > 0) + hash = Animator.StringToHash(CreateFakeHashName(hash, clips[bestClip].clip.name)); + } + return hash; + } + + private AnimationCurve LookupBlendCurve( + ICinemachineCamera fromKey, ICinemachineCamera toKey, out float duration) + { + // Get the blend curve that's most appropriate for these cameras + AnimationCurve blendCurve = m_DefaultBlend.BlendCurve; + if (m_CustomBlends != null) + { + string fromCameraName = (fromKey != null) ? fromKey.Name : string.Empty; + string toCameraName = (toKey != null) ? toKey.Name : string.Empty; + blendCurve = m_CustomBlends.GetBlendCurveForVirtualCameras( + fromCameraName, toCameraName, blendCurve); + } + var keys = blendCurve.keys; + duration = (keys == null || keys.Length == 0) ? 0 : keys[keys.Length-1].time; + return blendCurve; + } + + private CinemachineBlend CreateBlend( + ICinemachineCamera camA, ICinemachineCamera camB, + AnimationCurve blendCurve, float duration, + CinemachineBlend activeBlend, float deltaTime) + { + if (blendCurve == null || duration <= 0 || (camA == null && camB == null)) + return null; + + if (camA == null || activeBlend != null) + { + // Blend from the current camera position + CameraState state = (activeBlend != null) ? activeBlend.State : State; + camA = new StaticPointVirtualCamera(state, (activeBlend != null) ? "Mid-blend" : "(none)"); + } + return new CinemachineBlend(camA, camB, blendCurve,duration, 0); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineStateDrivenCamera.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineStateDrivenCamera.cs.meta new file mode 100644 index 0000000..d4e4029 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineStateDrivenCamera.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 325a6a3050a061e4b8aa51386c30e8e1 +timeCreated: 1489088095 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineTargetGroup.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineTargetGroup.cs new file mode 100644 index 0000000..b26065a --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineTargetGroup.cs @@ -0,0 +1,269 @@ +using UnityEngine; +using System; +using Cinemachine.Utility; + +namespace Cinemachine +{ + /// <summary>Defines a group of target objects, each with a radius and a weight. + /// The weight is used when calculating the average position of the target group. + /// Higher-weighted members of the group will count more. + /// The bounding box is calculated by taking the member positions, weight, + /// and radii into account. + /// </summary> + [DocumentationSorting(19, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("Cinemachine/CinemachineTargetGroup")] + [SaveDuringPlay] + [ExecuteInEditMode] + public class CinemachineTargetGroup : MonoBehaviour + { + /// <summary>Holds the information that represents a member of the group</summary> + [DocumentationSorting(19.1f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] public struct Target + { + /// <summary>The target objects. This object's position and orientation will contribute to the + /// group's average position and orientation, in accordance with its weight</summary> + [Tooltip("The target objects. This object's position and orientation will contribute to the group's average position and orientation, in accordance with its weight")] + public Transform target; + /// <summary>How much weight to give the target when averaging. Cannot be negative</summary> + [Tooltip("How much weight to give the target when averaging. Cannot be negative")] + public float weight; + /// <summary>The radius of the target, used for calculating the bounding box. Cannot be negative</summary> + [Tooltip("The radius of the target, used for calculating the bounding box. Cannot be negative")] + public float radius; + } + + /// <summary>How the group's position is calculated</summary> + [DocumentationSorting(19.2f, DocumentationSortingAttribute.Level.UserRef)] + public enum PositionMode + { + ///<summary>Group position will be the center of the group's axis-aligned bounding box</summary> + GroupCenter, + /// <summary>Group position will be the weighted average of the positions of the members</summary> + GroupAverage + } + + /// <summary>How the group's position is calculated</summary> + [Tooltip("How the group's position is calculated. Select GroupCenter for the center of the bounding box, and GroupAverage for a weighted average of the positions of the members.")] + public PositionMode m_PositionMode = PositionMode.GroupCenter; + + /// <summary>How the group's orientation is calculated</summary> + [DocumentationSorting(19.3f, DocumentationSortingAttribute.Level.UserRef)] + public enum RotationMode + { + /// <summary>Manually set in the group's transform</summary> + Manual, + /// <summary>Weighted average of the orientation of its members.</summary> + GroupAverage + } + + /// <summary>How the group's orientation is calculated</summary> + [Tooltip("How the group's rotation is calculated. Select Manual to use the value in the group's transform, and GroupAverage for a weighted average of the orientations of the members.")] + public RotationMode m_RotationMode = RotationMode.Manual; + + /// <summary>This enum defines the options available for the update method.</summary> + public enum UpdateMethod + { + /// <summary>Updated in normal MonoBehaviour Update.</summary> + Update, + /// <summary>Updated in sync with the Physics module, in FixedUpdate</summary> + FixedUpdate, + /// <summary>Updated in MonoBehaviour LateUpdate.</summary> + LateUpdate + }; + + /// <summary>When to update the group's transform based on the position of the group members</summary> + [Tooltip("When to update the group's transform based on the position of the group members")] + public UpdateMethod m_UpdateMethod = UpdateMethod.LateUpdate; + + /// <summary>The target objects, together with their weights and radii, that will + /// contribute to the group's average position, orientation, and size</summary> + [NoSaveDuringPlay] + [Tooltip("The target objects, together with their weights and radii, that will contribute to the group's average position, orientation, and size.")] + public Target[] m_Targets = new Target[0]; + + /// Cache of the last valid radius + private float m_lastRadius = 0; + + /// <summary>The axis-aligned bounding box of the group, computed using the + /// targets positions and radii</summary> + public Bounds BoundingBox + { + get + { + float averageWeight; + Vector3 center = CalculateAveragePosition(out averageWeight); + bool gotOne = false; + Bounds b = new Bounds(center, new Vector3(m_lastRadius*2, m_lastRadius*2, m_lastRadius*2)); + if (averageWeight > UnityVectorExtensions.Epsilon) + { + for (int i = 0; i < m_Targets.Length; ++i) + { + if (m_Targets[i].target != null) + { + float w = m_Targets[i].weight; + if (w < averageWeight - UnityVectorExtensions.Epsilon) + w = w / averageWeight; + else + w = 1; + float d = m_Targets[i].radius * 2 * w; + Vector3 p = Vector3.Lerp(center, m_Targets[i].target.position, w); + Bounds b2 = new Bounds(p, new Vector3(d, d, d)); + if (!gotOne) + b = b2; + else + b.Encapsulate(b2); + gotOne = true; + } + } + } + Vector3 r = b.extents; + m_lastRadius = Mathf.Max(r.x, Mathf.Max(r.y, r.z)); + return b; + } + } + + /// <summary>Return true if there are no members with weight > 0</summary> + public bool IsEmpty + { + get + { + for (int i = 0; i < m_Targets.Length; ++i) + if (m_Targets[i].target != null && m_Targets[i].weight > UnityVectorExtensions.Epsilon) + return false; + return true; + } + } + + /// <summary>The axis-aligned bounding box of the group, in a specific reference frame</summary> + /// <param name="mView">The frame of reference in which to compute the bounding box</param> + /// <returns>The axis-aligned bounding box of the group, in the desired frame of reference</returns> + public Bounds GetViewSpaceBoundingBox(Matrix4x4 mView) + { + Matrix4x4 inverseView = mView.inverse; + float averageWeight; + Vector3 center = inverseView.MultiplyPoint3x4(CalculateAveragePosition(out averageWeight)); + bool gotOne = false; + Bounds b = new Bounds(center, new Vector3(m_lastRadius*2, m_lastRadius*2, m_lastRadius*2)); + if (averageWeight > UnityVectorExtensions.Epsilon) + { + for (int i = 0; i < m_Targets.Length; ++i) + { + if (m_Targets[i].target != null) + { + float w = m_Targets[i].weight; + if (w < averageWeight - UnityVectorExtensions.Epsilon) + w = w / averageWeight; + else + w = 1; + float d = m_Targets[i].radius * 2; + Vector4 p = inverseView.MultiplyPoint3x4(m_Targets[i].target.position); + p = Vector3.Lerp(center, p, w); + Bounds b2 = new Bounds(p, new Vector3(d, d, d)); + if (!gotOne) + b = b2; + else + b.Encapsulate(b2); + gotOne = true; + } + } + } + Vector3 r = b.extents; + m_lastRadius = Mathf.Max(r.x, Mathf.Max(r.y, r.z)); + return b; + } + + Vector3 CalculateAveragePosition(out float averageWeight) + { + Vector3 pos = Vector3.zero; + float weight = 0; + int numTargets = 0; + for (int i = 0; i < m_Targets.Length; ++i) + { + if (m_Targets[i].target != null && m_Targets[i].weight > UnityVectorExtensions.Epsilon) + { + ++numTargets; + weight += m_Targets[i].weight; + pos += m_Targets[i].target.position * m_Targets[i].weight; + } + } + if (weight > UnityVectorExtensions.Epsilon) + pos /= weight; + if (numTargets == 0) + { + averageWeight = 0; + return transform.position; + } + averageWeight = weight / numTargets; + return pos; + } + + Quaternion CalculateAverageOrientation() + { + Quaternion r = Quaternion.identity; + for (int i = 0; i < m_Targets.Length; ++i) + { + if (m_Targets[i].target != null) + { + float w = m_Targets[i].weight; + Quaternion q = m_Targets[i].target.rotation; + // This is probably bogus + r = new Quaternion(r.x + q.x * w, r.y + q.y * w, r.z + q.z * w, r.w + q.w * w); + } + } + return r.Normalized(); + } + + private void OnValidate() + { + for (int i = 0; i < m_Targets.Length; ++i) + { + if (m_Targets[i].weight < 0) + m_Targets[i].weight = 0; + if (m_Targets[i].radius < 0) + m_Targets[i].radius = 0; + } + } + + void FixedUpdate() + { + if (m_UpdateMethod == UpdateMethod.FixedUpdate) + UpdateTransform(); + } + + void Update() + { + if (!Application.isPlaying || m_UpdateMethod == UpdateMethod.Update) + UpdateTransform(); + } + + void LateUpdate() + { + if (m_UpdateMethod == UpdateMethod.LateUpdate) + UpdateTransform(); + } + + void UpdateTransform() + { + if (IsEmpty) + return; + switch (m_PositionMode) + { + case PositionMode.GroupCenter: + transform.position = BoundingBox.center; + break; + case PositionMode.GroupAverage: + float averageWeight; + transform.position = CalculateAveragePosition(out averageWeight); + break; + } + switch (m_RotationMode) + { + case RotationMode.Manual: + break; + case RotationMode.GroupAverage: + transform.rotation = CalculateAverageOrientation(); + break; + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineTargetGroup.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineTargetGroup.cs.meta new file mode 100644 index 0000000..db252ef --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineTargetGroup.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e5eb80d8e62d9d145bb50fb783c0f731 +timeCreated: 1496785096 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineVirtualCamera.cs b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineVirtualCamera.cs new file mode 100644 index 0000000..5d5fe64 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineVirtualCamera.cs @@ -0,0 +1,464 @@ +using Cinemachine.Utility; +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Serialization; + +namespace Cinemachine +{ + /// <summary> + /// This behaviour is intended to be attached to an empty Transform GameObject, + /// and it represents a Virtual Camera within the Unity scene. + /// + /// The Virtual Camera will animate its Transform according to the rules contained + /// in its CinemachineComponent pipeline (Aim, Body, and Noise). When the virtual + /// camera is Live, the Unity camera will assume the position and orientation + /// of the virtual camera. + /// + /// A virtual camera is not a camera. Instead, it can be thought of as a camera controller, + /// not unlike a cameraman. It can drive the Unity Camera and control its position, + /// orientation, lens settings, and PostProcessing effects. Each Virtual Camera owns + /// its own Cinemachine Component Pipeline, through which you provide the instructions + /// for dynamically tracking specific game objects. + /// + /// A virtual camera is very lightweight, and does no rendering of its own. It merely + /// tracks interesting GameObjects, and positions itself accordingly. A typical game + /// can have dozens of virtual cameras, each set up to follow a particular character + /// or capture a particular event. + /// + /// A Virtual Camera can be in any of three states: + /// + /// * **Live**: The virtual camera is actively controlling the Unity Camera. The + /// virtual camera is tracking its targets and being updated every frame. + /// * **Standby**: The virtual camera is tracking its targets and being updated + /// every frame, but no Unity Camera is actively being controlled by it. This is + /// the state of a virtual camera that is enabled in the scene but perhaps at a + /// lower priority than the Live virtual camera. + /// * **Disabled**: The virtual camera is present but disabled in the scene. It is + /// not actively tracking its targets and so consumes no processing power. However, + /// the virtual camera can be made live from the Timeline. + /// + /// The Unity Camera can be driven by any virtual camera in the scene. The game + /// logic can choose the virtual camera to make live by manipulating the virtual + /// cameras' enabled flags and their priorities, based on game logic. + /// + /// In order to be driven by a virtual camera, the Unity Camera must have a CinemachineBrain + /// behaviour, which will select the most eligible virtual camera based on its priority + /// or on other criteria, and will manage blending. + /// </summary> + /// <seealso cref="CinemachineVirtualCameraBase"/> + /// <seealso cref="LensSettings"/> + /// <seealso cref="CinemachineComposer"/> + /// <seealso cref="CinemachineTransposer"/> + /// <seealso cref="CinemachineBasicMultiChannelPerlin"/> + [DocumentationSorting(1, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineVirtualCamera")] + public class CinemachineVirtualCamera : CinemachineVirtualCameraBase + { + /// <summary>The object that the camera wants to look at (the Aim target). + /// The Aim component of the CinemachineComponent pipeline + /// will refer to this target and orient the vcam in accordance with rules and + /// settings that are provided to it. + /// If this is null, then the vcam's Transform orientation will be used.</summary> + [Tooltip("The object that the camera wants to look at (the Aim target). If this is null, then the vcam's Transform orientation will define the camera's orientation.")] + [NoSaveDuringPlay] + public Transform m_LookAt = null; + + /// <summary>The object that the camera wants to move with (the Body target). + /// The Body component of the CinemachineComponent pipeline + /// will refer to this target and position the vcam in accordance with rules and + /// settings that are provided to it. + /// If this is null, then the vcam's Transform position will be used.</summary> + [Tooltip("The object that the camera wants to move with (the Body target). If this is null, then the vcam's Transform position will define the camera's position.")] + [NoSaveDuringPlay] + public Transform m_Follow = null; + + /// <summary>Specifies the LensSettings of this Virtual Camera. + /// These settings will be transferred to the Unity camera when the vcam is live.</summary> + [FormerlySerializedAs("m_LensAttributes")] + [Tooltip("Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active.")] + [LensSettingsProperty] + public LensSettings m_Lens = LensSettings.Default; + + /// <summary>This is the name of the hidden GameObject that will be created as a child object + /// of the virtual camera. This hidden game object acts as a container for the polymorphic + /// CinemachineComponent pipeline. The Inspector UI for the Virtual Camera + /// provides access to this pipleline, as do the CinemachineComponent-family of + /// public methods in this class. + /// The lifecycle of the pipeline GameObject is managed automatically.</summary> + public const string PipelineName = "cm"; + + /// <summary>The CameraState object holds all of the information + /// necessary to position the Unity camera. It is the output of this class.</summary> + override public CameraState State { get { return m_State; } } + + /// <summary>Get the LookAt target for the Aim component in the CinemachinePipeline. + /// If this vcam is a part of a meta-camera collection, then the owner's target + /// will be used if the local target is null.</summary> + override public Transform LookAt + { + get { return ResolveLookAt(m_LookAt); } + set { m_LookAt = value; } + } + + /// <summary>Get the Follow target for the Body component in the CinemachinePipeline. + /// If this vcam is a part of a meta-camera collection, then the owner's target + /// will be used if the local target is null.</summary> + override public Transform Follow + { + get { return ResolveFollow(m_Follow); } + set { m_Follow = value; } + } + + /// <summary>Called by CinemachineCore at LateUpdate time + /// so the vcam can position itself and track its targets. This class will + /// invoke its pipeline and generate a CameraState for this frame.</summary> + override public void UpdateCameraState(Vector3 worldUp, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineVirtualCamera.UpdateCameraState"); + if (!PreviousStateIsValid) + deltaTime = -1; + + // Reset the base camera state, in case the game object got moved in the editor + if (deltaTime < 0) + m_State = PullStateFromVirtualCamera(worldUp); // not in gameplay + + // Update the state by invoking the component pipeline + m_State = CalculateNewState(worldUp, deltaTime); + + // Push the raw position back to the game object's transform, so it + // moves along with the camera. + if (!UserIsDragging) + { + if (Follow != null) + transform.position = State.RawPosition; + if (LookAt != null) + transform.rotation = State.RawOrientation; + } + PreviousStateIsValid = true; + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// <summary>Make sure that the pipeline cache is up-to-date.</summary> + override protected void OnEnable() + { + base.OnEnable(); + InvalidateComponentPipeline(); + + // Can't add components during OnValidate + if (ValidatingStreamVersion < 20170927) + { + if (Follow != null && GetCinemachineComponent(CinemachineCore.Stage.Body) == null) + AddCinemachineComponent<CinemachineHardLockToTarget>(); + if (LookAt != null && GetCinemachineComponent(CinemachineCore.Stage.Aim) == null) + AddCinemachineComponent<CinemachineHardLookAt>(); + } + } + + /// <summary>Calls the DestroyPipelineDelegate for destroying the hidden + /// child object, to support undo.</summary> + protected override void OnDestroy() + { + // Make the pipeline visible instead of destroying - this is to keep Undo happy + foreach (Transform child in transform) + if (child.GetComponent<CinemachinePipeline>() != null) + child.gameObject.hideFlags + &= ~(HideFlags.HideInHierarchy | HideFlags.HideInInspector); + + base.OnDestroy(); + } + + /// <summary>Enforce bounds for fields, when changed in inspector.</summary> + protected override void OnValidate() + { + base.OnValidate(); + m_Lens.Validate(); + } + + void OnTransformChildrenChanged() + { + InvalidateComponentPipeline(); + } + + void Reset() + { + DestroyPipeline(); + } + + /// <summary> + /// Override component pipeline creation. + /// This needs to be done by the editor to support Undo. + /// The override must do exactly the same thing as the CreatePipeline method in this class. + /// </summary> + public static CreatePipelineDelegate CreatePipelineOverride; + + /// <summary> + /// Override component pipeline creation. + /// This needs to be done by the editor to support Undo. + /// The override must do exactly the same thing as the CreatePipeline method in + /// the CinemachineVirtualCamera class. + /// </summary> + public delegate Transform CreatePipelineDelegate( + CinemachineVirtualCamera vcam, string name, CinemachineComponentBase[] copyFrom); + + /// <summary> + /// Override component pipeline destruction. + /// This needs to be done by the editor to support Undo. + /// </summary> + public static DestroyPipelineDelegate DestroyPipelineOverride; + + /// <summary> + /// Override component pipeline destruction. + /// This needs to be done by the editor to support Undo. + /// </summary> + public delegate void DestroyPipelineDelegate(GameObject pipeline); + + /// <summary>Destroy any existing pipeline container.</summary> + private void DestroyPipeline() + { + List<Transform> oldPipeline = new List<Transform>(); + foreach (Transform child in transform) + if (child.GetComponent<CinemachinePipeline>() != null) + oldPipeline.Add(child); + + foreach (Transform child in oldPipeline) + { + if (DestroyPipelineOverride != null) + DestroyPipelineOverride(child.gameObject); + else + Destroy(child.gameObject); + } + m_ComponentOwner = null; + PreviousStateIsValid = false; + } + + /// <summary>Create a default pipeline container.</summary> + private Transform CreatePipeline(CinemachineVirtualCamera copyFrom) + { + CinemachineComponentBase[] components = null; + if (copyFrom != null) + { + copyFrom.InvalidateComponentPipeline(); // make sure it's up to date + components = copyFrom.GetComponentPipeline(); + } + + Transform newPipeline = null; + if (CreatePipelineOverride != null) + newPipeline = CreatePipelineOverride(this, PipelineName, components); + else + { + GameObject go = new GameObject(PipelineName); + go.transform.parent = transform; + go.AddComponent<CinemachinePipeline>(); + newPipeline = go.transform; + + // If copying, transfer the components + if (components != null) + foreach (Component c in components) + ReflectionHelpers.CopyFields(c, go.AddComponent(c.GetType())); + } + PreviousStateIsValid = false; + return newPipeline; + } + + /// <summary> + /// Editor API: Call this when changing the pipeline from the editor. + /// Will force a rebuild of the pipeline cache. + /// </summary> + public void InvalidateComponentPipeline() { m_ComponentPipeline = null; } + + /// <summary>Get the hidden CinemachinePipeline child object.</summary> + public Transform GetComponentOwner() { UpdateComponentPipeline(); return m_ComponentOwner; } + + /// <summary>Get the component pipeline owned by the hidden child pipline container. + /// For most purposes, it is preferable to use the GetCinemachineComponent method.</summary> + public CinemachineComponentBase[] GetComponentPipeline() { UpdateComponentPipeline(); return m_ComponentPipeline; } + + /// <summary>Get the component set for a specific stage.</summary> + /// <param name="stage">The stage for which we want the component</param> + /// <returns>The Cinemachine component for that stage, or null if not defined</returns> + public CinemachineComponentBase GetCinemachineComponent(CinemachineCore.Stage stage) + { + CinemachineComponentBase[] components = GetComponentPipeline(); + if (components != null) + foreach (var c in components) + if (c.Stage == stage) + return c; + return null; + } + + /// <summary>Get an existing component of a specific type from the cinemachine pipeline.</summary> + public T GetCinemachineComponent<T>() where T : CinemachineComponentBase + { + CinemachineComponentBase[] components = GetComponentPipeline(); + if (components != null) + foreach (var c in components) + if (c is T) + return c as T; + return null; + } + + /// <summary>Add a component to the cinemachine pipeline.</summary> + public T AddCinemachineComponent<T>() where T : CinemachineComponentBase + { + // Get the existing components + Transform owner = GetComponentOwner(); + CinemachineComponentBase[] components = owner.GetComponents<CinemachineComponentBase>(); + + T component = owner.gameObject.AddComponent<T>(); + if (component != null && components != null) + { + // Remove the existing components at that stage + CinemachineCore.Stage stage = component.Stage; + for (int i = components.Length - 1; i >= 0; --i) + { + if (components[i].Stage == stage) + { + components[i].enabled = false; + DestroyImmediate(components[i]); + } + } + } + InvalidateComponentPipeline(); + return component; + } + + /// <summary>Remove a component from the cinemachine pipeline.</summary> + public void DestroyCinemachineComponent<T>() where T : CinemachineComponentBase + { + CinemachineComponentBase[] components = GetComponentPipeline(); + if (components != null) + { + foreach (var c in components) + { + if (c is T) + { + c.enabled = false; + DestroyImmediate(c); + InvalidateComponentPipeline(); + } + } + } + } + + /// <summary>API for the editor, to make the dragging of position handles behave better.</summary> + public bool UserIsDragging { get; set; } + + /// <summary>API for the editor, to process a position drag from the user.</summary> + public void OnPositionDragged(Vector3 delta) + { + CinemachineComponentBase[] components = GetComponentPipeline(); + if (components != null) + for (int i = 0; i < components.Length; ++i) + components[i].OnPositionDragged(delta); + } + + CameraState m_State = CameraState.Default; // Current state this frame + + CinemachineComponentBase[] m_ComponentPipeline = null; + [SerializeField][HideInInspector] private Transform m_ComponentOwner = null; // serialized to handle copy/paste + void UpdateComponentPipeline() + { + // Did we just get copy/pasted? + if (m_ComponentOwner != null && m_ComponentOwner.parent != transform) + { + CinemachineVirtualCamera copyFrom = (m_ComponentOwner.parent != null) + ? m_ComponentOwner.parent.gameObject.GetComponent<CinemachineVirtualCamera>() : null; + DestroyPipeline(); + m_ComponentOwner = CreatePipeline(copyFrom); + } + + // Early out if we're up-to-date + if (m_ComponentOwner != null && m_ComponentPipeline != null) + return; + + m_ComponentOwner = null; + List<CinemachineComponentBase> list = new List<CinemachineComponentBase>(); + foreach (Transform child in transform) + { + if (child.GetComponent<CinemachinePipeline>() != null) + { + m_ComponentOwner = child; + CinemachineComponentBase[] components = child.GetComponents<CinemachineComponentBase>(); + foreach (CinemachineComponentBase c in components) + list.Add(c); + } + } + + // Make sure we have a pipeline owner + if (m_ComponentOwner == null) + m_ComponentOwner = CreatePipeline(null); + + // Make sure the pipeline stays hidden, even through prefab + if (CinemachineCore.sShowHiddenObjects) + m_ComponentOwner.gameObject.hideFlags + &= ~(HideFlags.HideInHierarchy | HideFlags.HideInInspector); + else + m_ComponentOwner.gameObject.hideFlags + |= (HideFlags.HideInHierarchy | HideFlags.HideInInspector); + + // Sort the pipeline + list.Sort((c1, c2) => (int)c1.Stage - (int)c2.Stage); + m_ComponentPipeline = list.ToArray(); + } + + private CameraState CalculateNewState(Vector3 worldUp, float deltaTime) + { + // Initialize the camera state, in case the game object got moved in the editor + CameraState state = PullStateFromVirtualCamera(worldUp); + + if (LookAt != null) + state.ReferenceLookAt = LookAt.position; + + // Update the state by invoking the component pipeline + CinemachineCore.Stage curStage = CinemachineCore.Stage.Body; + UpdateComponentPipeline(); // avoid GetComponentPipeline() here because of GC + if (m_ComponentPipeline != null) + { + for (int i = 0; i < m_ComponentPipeline.Length; ++i) + m_ComponentPipeline[i].PrePipelineMutateCameraState(ref state); + + for (int i = 0; i < m_ComponentPipeline.Length; ++i) + { + curStage = AdvancePipelineStage( + ref state, deltaTime, curStage, (int)m_ComponentPipeline[i].Stage); + m_ComponentPipeline[i].MutateCameraState(ref state, deltaTime); + } + } + int numStages = 3; //Enum.GetValues(typeof(CinemachineCore.Stage)).Length; + AdvancePipelineStage(ref state, deltaTime, curStage, numStages); + return state; + } + + private CinemachineCore.Stage AdvancePipelineStage( + ref CameraState state, float deltaTime, + CinemachineCore.Stage curStage, int maxStage) + { + while ((int)curStage < maxStage) + { + InvokePostPipelineStageCallback(this, curStage, ref state, deltaTime); + ++curStage; + } + return curStage; + } + + private CameraState PullStateFromVirtualCamera(Vector3 worldUp) + { + CameraState state = CameraState.Default; + state.RawPosition = transform.position; + state.RawOrientation = transform.rotation; + state.ReferenceUp = worldUp; + + CinemachineBrain brain = CinemachineCore.Instance.FindPotentialTargetBrain(this); + m_Lens.Aspect = brain != null ? brain.OutputCamera.aspect : 1; + m_Lens.Orthographic = brain != null ? brain.OutputCamera.orthographic : false; + state.Lens = m_Lens; + + return state; + } + + // This is a hack for FreeLook rigs - to be removed + internal void SetStateRawPosition(Vector3 pos) { m_State.RawPosition = pos; } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineVirtualCamera.cs.meta b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineVirtualCamera.cs.meta new file mode 100644 index 0000000..de82b62 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineVirtualCamera.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 45e653bab7fb20e499bda25e1b646fea +timeCreated: 1496775476 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 5f2a108eb023faf43a809979fd3d38f2, type: 3} + userData: + assetBundleName: + assetBundleVariant: |
