From 5440734d820606b29a795c46172ade5d7eba8efb Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Mon, 3 Sep 2018 23:34:21 +0100 Subject: Initial commit --- Assets/Cinemachine/Base/Runtime/Behaviours.meta | 9 + .../Behaviours/CinemachineBlendListCamera.cs | 341 +++++++++ .../Behaviours/CinemachineBlendListCamera.cs.meta | 13 + .../Base/Runtime/Behaviours/CinemachineBrain.cs | 831 +++++++++++++++++++++ .../Runtime/Behaviours/CinemachineBrain.cs.meta | 12 + .../Runtime/Behaviours/CinemachineClearShot.cs | 432 +++++++++++ .../Behaviours/CinemachineClearShot.cs.meta | 12 + .../Base/Runtime/Behaviours/CinemachineCollider.cs | 565 ++++++++++++++ .../Runtime/Behaviours/CinemachineCollider.cs.meta | 12 + .../Base/Runtime/Behaviours/CinemachineConfiner.cs | 222 ++++++ .../Runtime/Behaviours/CinemachineConfiner.cs.meta | 12 + .../Runtime/Behaviours/CinemachineDollyCart.cs | 70 ++ .../Behaviours/CinemachineDollyCart.cs.meta | 12 + .../Behaviours/CinemachineExternalCamera.cs | 61 ++ .../Behaviours/CinemachineExternalCamera.cs.meta | 12 + .../Runtime/Behaviours/CinemachineFollowZoom.cs | 91 +++ .../Behaviours/CinemachineFollowZoom.cs.meta | 12 + .../Base/Runtime/Behaviours/CinemachineFreeLook.cs | 673 +++++++++++++++++ .../Runtime/Behaviours/CinemachineFreeLook.cs.meta | 12 + .../Runtime/Behaviours/CinemachineMixingCamera.cs | 262 +++++++ .../Behaviours/CinemachineMixingCamera.cs.meta | 12 + .../Base/Runtime/Behaviours/CinemachinePath.cs | 180 +++++ .../Runtime/Behaviours/CinemachinePath.cs.meta | 12 + .../Base/Runtime/Behaviours/CinemachinePipeline.cs | 12 + .../Runtime/Behaviours/CinemachinePipeline.cs.meta | 12 + .../Runtime/Behaviours/CinemachineSmoothPath.cs | 224 ++++++ .../Behaviours/CinemachineSmoothPath.cs.meta | 12 + .../Base/Runtime/Behaviours/CinemachineSmoother.cs | 103 +++ .../Runtime/Behaviours/CinemachineSmoother.cs.meta | 12 + .../Behaviours/CinemachineStateDrivenCamera.cs | 512 +++++++++++++ .../CinemachineStateDrivenCamera.cs.meta | 12 + .../Runtime/Behaviours/CinemachineTargetGroup.cs | 269 +++++++ .../Behaviours/CinemachineTargetGroup.cs.meta | 12 + .../Runtime/Behaviours/CinemachineVirtualCamera.cs | 464 ++++++++++++ .../Behaviours/CinemachineVirtualCamera.cs.meta | 12 + Assets/Cinemachine/Base/Runtime/Components.meta | 9 + .../CinemachineBasicMultiChannelPerlin.cs | 113 +++ .../CinemachineBasicMultiChannelPerlin.cs.meta | 12 + .../Base/Runtime/Components/CinemachineComposer.cs | 391 ++++++++++ .../Runtime/Components/CinemachineComposer.cs.meta | 12 + .../Components/CinemachineFramingTransposer.cs | 497 ++++++++++++ .../CinemachineFramingTransposer.cs.meta | 12 + .../Runtime/Components/CinemachineGroupComposer.cs | 237 ++++++ .../Components/CinemachineGroupComposer.cs.meta | 12 + .../Components/CinemachineHardLockToTarget.cs | 33 + .../Components/CinemachineHardLockToTarget.cs.meta | 12 + .../Runtime/Components/CinemachineHardLookAt.cs | 42 ++ .../Components/CinemachineHardLookAt.cs.meta | 12 + .../Components/CinemachineOrbitalTransposer.cs | 530 +++++++++++++ .../CinemachineOrbitalTransposer.cs.meta | 12 + .../Base/Runtime/Components/CinemachinePOV.cs | 70 ++ .../Base/Runtime/Components/CinemachinePOV.cs.meta | 12 + .../Components/CinemachineSameAsFollowObject.cs | 33 + .../CinemachineSameAsFollowObject.cs.meta | 12 + .../Runtime/Components/CinemachineTrackedDolly.cs | 312 ++++++++ .../Components/CinemachineTrackedDolly.cs.meta | 12 + .../Runtime/Components/CinemachineTransposer.cs | 310 ++++++++ .../Components/CinemachineTransposer.cs.meta | 12 + Assets/Cinemachine/Base/Runtime/Core.meta | 9 + Assets/Cinemachine/Base/Runtime/Core/AxisState.cs | 200 +++++ .../Base/Runtime/Core/AxisState.cs.meta | 12 + .../Cinemachine/Base/Runtime/Core/CameraState.cs | 352 +++++++++ .../Base/Runtime/Core/CameraState.cs.meta | 12 + .../Base/Runtime/Core/CinemachineBlend.cs | 207 +++++ .../Base/Runtime/Core/CinemachineBlend.cs.meta | 12 + .../Runtime/Core/CinemachineBlenderSettings.cs | 95 +++ .../Core/CinemachineBlenderSettings.cs.meta | 12 + .../Base/Runtime/Core/CinemachineComponentBase.cs | 77 ++ .../Runtime/Core/CinemachineComponentBase.cs.meta | 12 + .../Base/Runtime/Core/CinemachineCore.cs | 429 +++++++++++ .../Base/Runtime/Core/CinemachineCore.cs.meta | 12 + .../Base/Runtime/Core/CinemachineDebugLogger.cs | 47 ++ .../Runtime/Core/CinemachineDebugLogger.cs.meta | 12 + .../Base/Runtime/Core/CinemachineExtension.cs | 89 +++ .../Base/Runtime/Core/CinemachineExtension.cs.meta | 12 + .../Base/Runtime/Core/CinemachinePathBase.cs | 356 +++++++++ .../Base/Runtime/Core/CinemachinePathBase.cs.meta | 12 + .../Runtime/Core/CinemachinePropertyAttribute.cs | 70 ++ .../Core/CinemachinePropertyAttribute.cs.meta | 12 + .../Runtime/Core/CinemachineVirtualCameraBase.cs | 360 +++++++++ .../Core/CinemachineVirtualCameraBase.cs.meta | 12 + .../Base/Runtime/Core/GaussianFilter.cs | 140 ++++ .../Base/Runtime/Core/GaussianFilter.cs.meta | 12 + .../Base/Runtime/Core/ICinemachineCamera.cs | 81 ++ .../Base/Runtime/Core/ICinemachineCamera.cs.meta | 12 + .../Base/Runtime/Core/ICinemachineComponent.cs | 3 + .../Runtime/Core/ICinemachineComponent.cs.meta | 12 + .../Cinemachine/Base/Runtime/Core/LensSettings.cs | 137 ++++ .../Base/Runtime/Core/LensSettings.cs.meta | 12 + .../Cinemachine/Base/Runtime/Core/NoiseSettings.cs | 82 ++ .../Base/Runtime/Core/NoiseSettings.cs.meta | 12 + Assets/Cinemachine/Base/Runtime/Core/Predictor.cs | 141 ++++ .../Base/Runtime/Core/Predictor.cs.meta | 12 + .../Base/Runtime/Core/ReflectionHelpers.cs | 186 +++++ .../Base/Runtime/Core/ReflectionHelpers.cs.meta | 12 + .../Cinemachine/Base/Runtime/Core/SplineHelpers.cs | 137 ++++ .../Base/Runtime/Core/SplineHelpers.cs.meta | 12 + .../Base/Runtime/Core/UnityVectorExtensions.cs | 228 ++++++ .../Runtime/Core/UnityVectorExtensions.cs.meta | 12 + 99 files changed, 11901 insertions(+) create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBlendListCamera.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBlendListCamera.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBrain.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineBrain.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineClearShot.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineClearShot.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineCollider.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineCollider.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineConfiner.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineConfiner.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineDollyCart.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineDollyCart.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineExternalCamera.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineExternalCamera.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFollowZoom.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFollowZoom.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFreeLook.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineFreeLook.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineMixingCamera.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineMixingCamera.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePath.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePath.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePipeline.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachinePipeline.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoothPath.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoothPath.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoother.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineSmoother.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineStateDrivenCamera.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineStateDrivenCamera.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineTargetGroup.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineTargetGroup.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineVirtualCamera.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Behaviours/CinemachineVirtualCamera.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineBasicMultiChannelPerlin.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineBasicMultiChannelPerlin.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineComposer.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineComposer.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineFramingTransposer.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineFramingTransposer.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineGroupComposer.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineGroupComposer.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLockToTarget.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLockToTarget.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLookAt.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLookAt.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineOrbitalTransposer.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineOrbitalTransposer.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachinePOV.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachinePOV.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineSameAsFollowObject.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineSameAsFollowObject.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineTrackedDolly.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineTrackedDolly.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineTransposer.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Components/CinemachineTransposer.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/AxisState.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/AxisState.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CameraState.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CameraState.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineBlend.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineBlend.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineBlenderSettings.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineBlenderSettings.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineComponentBase.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineComponentBase.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineCore.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineCore.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineDebugLogger.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineDebugLogger.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineExtension.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineExtension.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachinePathBase.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachinePathBase.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachinePropertyAttribute.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachinePropertyAttribute.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineVirtualCameraBase.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/CinemachineVirtualCameraBase.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/GaussianFilter.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/GaussianFilter.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/ICinemachineCamera.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/ICinemachineCamera.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/ICinemachineComponent.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/ICinemachineComponent.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/LensSettings.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/LensSettings.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/NoiseSettings.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/NoiseSettings.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/Predictor.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/Predictor.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/ReflectionHelpers.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/ReflectionHelpers.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/SplineHelpers.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/SplineHelpers.cs.meta create mode 100644 Assets/Cinemachine/Base/Runtime/Core/UnityVectorExtensions.cs create mode 100644 Assets/Cinemachine/Base/Runtime/Core/UnityVectorExtensions.cs.meta (limited to 'Assets/Cinemachine/Base/Runtime') diff --git a/Assets/Cinemachine/Base/Runtime/Behaviours.meta b/Assets/Cinemachine/Base/Runtime/Behaviours.meta new file mode 100644 index 0000000..1e83a47 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Behaviours.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: fd10c4a322c950342a9d03a14ae879b7 +folderAsset: yes +timeCreated: 1489096338 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: 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 +{ + /// + /// 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. + /// + [DocumentationSorting(13, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineBlendListCamera")] + public class CinemachineBlendListCamera : CinemachineVirtualCameraBase + { + /// Default object for the camera children to look at (the aim target), if not specified in a child rig. May be empty + [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; + + /// Default object for the camera children wants to move with (the body target), if not specified in a child rig. May be empty + [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; + + /// When enabled, the current camera and blend will be indicated in the game window, for debugging + [Tooltip("When enabled, the current child camera and blend will be indicated in the game window, for debugging")] + public bool m_ShowDebugText = false; + + /// Force all child cameras to be enabled. This is useful if animating them in Timeline, but consumes extra resources. + [Tooltip("Force all child cameras to be enabled. This is useful if animating them in Timeline, but consumes extra resources")] + public bool m_EnableAllChildCameras; + + /// Internal API for the editor. Do not use this field + [SerializeField][HideInInspector][NoSaveDuringPlay] + public CinemachineVirtualCameraBase[] m_ChildCameras = null; + + /// This represents a single entry in the instrunction list of the BlendListCamera. + [Serializable] + public struct Instruction + { + /// The virtual camera to activate when this instruction becomes active + [Tooltip("The virtual camera to activate when this instruction becomes active")] + public CinemachineVirtualCameraBase m_VirtualCamera; + /// How long to wait (in seconds) before activating the next virtual camera in the list (if any) + [Tooltip("How long to wait (in seconds) before activating the next virtual camera in the list (if any)")] + public float m_Hold; + /// How to blend to the next virtual camera in the list (if any) + [CinemachineBlendDefinitionProperty] + [Tooltip("How to blend to the next virtual camera in the list (if any)")] + public CinemachineBlendDefinition m_Blend; + }; + + /// The set of instructions associating virtual cameras with states. + /// The set of instructions for enabling child cameras + [Tooltip("The set of instructions for enabling child cameras.")] + public Instruction[] m_Instructions; + + /// Gets a brief debug description of this virtual camera, for use when displayiong debug info + 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; + } + } + + /// Get the current "best" child virtual camera, that would be chosen + /// if the State Driven Camera were active. + public ICinemachineCamera LiveChild { set; get; } + + /// Return the live child. + public override ICinemachineCamera LiveChildOrSelf { get { return LiveChild; } } + + /// Check whether the vcam a live child of this camera. + /// The Virtual Camera to check + /// True if the vcam is currently actively influencing the state of this vcam + public override bool IsLiveChild(ICinemachineCamera vcam) + { + return vcam == LiveChild + || (mActiveBlend != null && (vcam == mActiveBlend.CamA || vcam == mActiveBlend.CamB)); + } + + /// The State of the current live child + public override CameraState State { get { return m_State; } } + + /// Get the current LookAt target. Returns parent's LookAt if parent + /// is non-null and no specific LookAt defined for this camera + override public Transform LookAt + { + get { return ResolveLookAt(m_LookAt); } + set { m_LookAt = value; } + } + + /// Get the current Follow target. Returns parent's Follow if parent + /// is non-null and no specific Follow defined for this camera + override public Transform Follow + { + get { return ResolveFollow(m_Follow); } + set { m_Follow = value; } + } + + /// Remove a Pipeline stage hook callback. + /// Make sure it is removed from all the children. + /// The delegate to remove. + public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + base.RemovePostPipelineStageHook(d); + UpdateListOfChildren(); + foreach (var vcam in m_ChildCameras) + vcam.RemovePostPipelineStageHook(d); + } + + /// Notification that this virtual camera is going live. + /// The camera being deactivated. May be null. + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than or equal to 0) + 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); + } + + /// 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. + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than or equal to 0) + 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(); + } + + /// Makes sure the internal child cache is up to date + protected override void OnEnable() + { + base.OnEnable(); + InvalidateListOfChildren(); + mActiveBlend = null; + } + + /// Makes sure the internal child cache is up to date + public void OnTransformChildrenChanged() + { + InvalidateListOfChildren(); + } + +#if UNITY_EDITOR + /// Displays the current active camera on the game screen, if requested + 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; + + /// The list of child cameras. These are just the immediate children in the hierarchy. + public CinemachineVirtualCameraBase[] ChildCameras { get { UpdateListOfChildren(); return m_ChildCameras; }} + + /// Is there a blend in progress? + public bool IsBlending { get { return mActiveBlend != null; } } + + /// The time at which the current instruction went live + 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 list = new List(); + CinemachineVirtualCameraBase[] kids = GetComponentsInChildren(true); + foreach (CinemachineVirtualCameraBase k in kids) + if (k.transform.parent == transform) + list.Add(k); + m_ChildCameras = list.ToArray(); + ValidateInstructions(); + } + + /// Internal API for the inspector editor. + /// // 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 +{ + /// + /// 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. + /// + [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 + { + /// + /// When enabled, the current camera and blend will be indicated in the game window, for debugging. + /// + [Tooltip("When enabled, the current camera and blend will be indicated in the game window, for debugging")] + public bool m_ShowDebugText = false; + + /// + /// When enabled, shows the camera's frustum in the scene view. + /// + [Tooltip("When enabled, the camera's frustum will be shown at all times in the scene view")] + public bool m_ShowCameraFrustum = true; + + /// + /// When enabled, the cameras will always respond in real-time to user input and damping, + /// even if the game is running in slow motion + /// + [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; + + /// + /// 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. + /// + [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; + + /// This enum defines the options available for the update method. + [DocumentationSorting(0.1f, DocumentationSortingAttribute.Level.UserRef)] + public enum UpdateMethod + { + /// Virtual cameras are updated in sync with the Physics module, in FixedUpdate + FixedUpdate, + /// Virtual cameras are updated in MonoBehaviour LateUpdate. + LateUpdate, + /// Virtual cameras are updated according to how the target is updated. + SmartUpdate + }; + + /// 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. + [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; + + /// + /// The blend which is used if you don't explicitly define a blend between two Virtual Cameras. + /// + [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); + + /// + /// This is the asset which contains custom settings for specific blends. + /// + [Tooltip("This is the asset that contains custom settings for blends between specific virtual cameras in your scene")] + public CinemachineBlenderSettings m_CustomBlends = null; + + /// + /// Get the Unity Camera that is attached to this GameObject. This is the camera + /// that will be controlled by the brain. + /// + public Camera OutputCamera + { + get + { + if (m_OutputCamera == null) + m_OutputCamera = GetComponent(); + return m_OutputCamera; + } + } + private Camera m_OutputCamera = null; // never use directly - use accessor + + /// Event with a CinemachineBrain parameter + [Serializable] public class BrainEvent : UnityEvent {} + + /// Event with a ICinemachineCamera parameter + [Serializable] public class VcamEvent : UnityEvent {} + + /// This event will fire whenever a virtual camera goes live and there is no blend + [Tooltip("This event will fire whenever a virtual camera goes live and there is no blend")] + public BrainEvent m_CameraCutEvent = new BrainEvent(); + + /// 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 + [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(); + + /// Support for opaque post-processing module + internal Component PostProcessingComponent { get; set; } + + /// + /// 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. + /// + internal static BrainEvent sPostProcessingHandler = new BrainEvent(); + + /// + /// API for the Unity Editor. + /// Show this camera no matter what. This is static, and so affects all Cinemachine brains. + /// + public static ICinemachineCamera SoloCamera { get; set; } + + /// API for the Unity Editor. + /// Color used to indicate that a camera is in Solo mode. + public static Color GetSoloGUIColor() { return Color.Lerp(Color.red, Color.yellow, 0.8f); } + + /// Get the default world up for the virtual cameras. + 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 mOverrideStack = new List(); + 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; + } + + /// + /// 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. + /// + /// 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. + /// The camera to set, corresponding to weight=0 + /// The camera to set, corresponding to weight=1 + /// The blend weight. 0=camA, 1=camB + /// override for deltaTime. Should be Time.FixedDelta for + /// time-based calculations to be included, -1 otherwise + /// The oiverride ID. Don't forget to call ReleaseCameraOverride + /// after all overriding is finished, to free the OverideStack resources. + 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; + } + + /// + /// This API is specifically for Timeline. Do not use it. + /// Release the resources used for a camera override client. + /// See SetCameraOverride. + /// + /// The ID to released. This is the value that + /// was returned by SetCameraOverride + 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(); + } + + /// + /// Is there a blend in progress? + /// + public bool IsBlending { get { return ActiveBlend != null && ActiveBlend.IsValid; } } + + /// + /// Get the current blend in progress. Returns null if none. + /// + public CinemachineBlend ActiveBlend + { + get + { + if (SoloCamera != null) + return null; + OverrideStackFrame ovr = GetActiveOverride(); + return (ovr != null && ovr.blend != null) ? ovr.blend : mActiveBlend; + } + } + + /// + /// True if the ICinemachineCamera the current active camera, + /// or part of a current blend, either directly or indirectly because its parents are live. + /// + /// The camera to test whether it is live + /// True if the camera is live (directly or indirectly) + /// or part of a blend in progress. + 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; + } + + /// + /// Get the current active virtual camera. + /// + public ICinemachineCamera ActiveVirtualCamera + { + get + { + if (SoloCamera != null) + return SoloCamera; + OverrideStackFrame ovr = GetActiveOverride(); + return (ovr != null && ovr.camera != null) + ? ovr.camera : TopCameraFromPriorityQueue(); + } + } + + /// + /// The current state applied to the unity camera (may be the result of a blend) + /// + public CameraState CurrentCameraState { get; private set; } + + /// + /// Get the highest-priority Enabled ICinemachineCamera + /// that is visible to my camera. Culling Mask is used to test visibility. + /// + 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; + } + + /// + /// 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. + /// + 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; + } + + /// + /// Create a blend from one ICinemachineCamera to another, + /// or to/from a point, if we can't do anything else + /// + 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; + } + + /// Apply a cref="CameraState"/> to the game object + 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; + } + } + + /// API for CinemachineCore only: Get the number of subframes to + /// update the virtual cameras. + /// Number of subframes registered by the first brain's FixedUpdate + internal static int GetSubframeCount() { return Math.Max(1, msSubframes); } + } + + /// + /// 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. + /// + 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) {} + } + + /// + /// 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. + /// + 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 +{ + /// + /// 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. + /// + [DocumentationSorting(12, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineClearShot")] + public class CinemachineClearShot : CinemachineVirtualCameraBase + { + /// Default object for the camera children to look at (the aim target), if not specified in a child camera. May be empty. + [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; + + /// Default object for the camera children wants to move with (the body target), if not specified in a child camera. May be empty. + [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; + + /// When enabled, the current camera and blend will be indicated in the game window, for debugging + [Tooltip("When enabled, the current child camera and blend will be indicated in the game window, for debugging")] + [NoSaveDuringPlay] + public bool m_ShowDebugText = false; + + /// Internal API for the editor. Do not use this filed. + [SerializeField, HideInInspector, NoSaveDuringPlay] + public CinemachineVirtualCameraBase[] m_ChildCameras = null; + + /// Wait this many seconds before activating a new child camera + [Tooltip("Wait this many seconds before activating a new child camera")] + public float m_ActivateAfter; + + /// An active camera must be active for at least this many seconds + [Tooltip("An active camera must be active for at least this many seconds")] + public float m_MinDuration; + + /// If checked, camera choice will be randomized if multiple cameras are equally desirable. Otherwise, child list order will be used + [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; + + /// The blend which is used if you don't explicitly define a blend between two Virtual Cameras + [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); + + /// This is the asset which contains custom settings for specific blends + [HideInInspector] + public CinemachineBlenderSettings m_CustomBlends = null; + + /// Gets a brief debug description of this virtual camera, for use when displayiong debug info + 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; + } + } + + /// Get the current "best" child virtual camera, that would be chosen + /// if the ClearShot camera were active. + public ICinemachineCamera LiveChild { set; get; } + + /// The CameraState of the currently live child + public override CameraState State { get { return m_State; } } + + /// Return the live child. + public override ICinemachineCamera LiveChildOrSelf { get { return LiveChild; } } + + /// Check whether the vcam a live child of this camera. + /// The Virtual Camera to check + /// True if the vcam is currently actively influencing the state of this vcam + public override bool IsLiveChild(ICinemachineCamera vcam) + { + return vcam == LiveChild + || (mActiveBlend != null && (vcam == mActiveBlend.CamA || vcam == mActiveBlend.CamB)); + } + + /// Get the current LookAt target. Returns parent's LookAt if parent + /// is non-null and no specific LookAt defined for this camera + override public Transform LookAt + { + get { return ResolveLookAt(m_LookAt); } + set { m_LookAt = value; } + } + + /// Get the current Follow target. Returns parent's Follow if parent + /// is non-null and no specific Follow defined for this camera + override public Transform Follow + { + get { return ResolveFollow(m_Follow); } + set { m_Follow = value; } + } + + /// Remove a Pipeline stage hook callback. + /// Make sure it is removed from all the children. + /// The delegate to remove. + public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + base.RemovePostPipelineStageHook(d); + UpdateListOfChildren(); + foreach (var vcam in m_ChildCameras) + vcam.RemovePostPipelineStageHook(d); + } + + /// 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. + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than 0) + 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(); + } + + /// Makes sure the internal child cache is up to date + protected override void OnEnable() + { + base.OnEnable(); + InvalidateListOfChildren(); + mActiveBlend = null; + } + + /// Makes sure the internal child cache is up to date + public void OnTransformChildrenChanged() + { + InvalidateListOfChildren(); + } + +#if UNITY_EDITOR + /// Displays the current active camera on the game screen, if requested + 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 + /// Is there a blend in progress? + public bool IsBlending { get { return mActiveBlend != null; } } + + CameraState m_State = CameraState.Default; + + /// The list of child cameras. These are just the immediate children in the hierarchy. + 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; + } + + /// If RandomizeChoice is enabled, call this to re-randomize the children next frame. + /// This is useful if you want to freshen up the shot. + public void ResetRandomization() + { + m_RandomizedChilden = null; + mRandomizeNow = true; + } + + void UpdateListOfChildren() + { + if (m_ChildCameras != null) + return; + + List list = new List(); + CinemachineVirtualCameraBase[] kids = GetComponentsInChildren(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 pairs = new List(); + 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); + } + + /// Notification that this virtual camera is going live. + /// This implementation resets the child randomization. + /// The camera being deactivated. May be null. + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than or equal to 0) + 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 +{ + /// + /// 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. + /// + [DocumentationSorting(15, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] + [AddComponentMenu("")] // Hide in menu + [SaveDuringPlay] + public class CinemachineCollider : CinemachineExtension + { + /// The Unity layer mask against which the collider will raycast. + [Header("Obstacle Detection")] + [Tooltip("The Unity layer mask against which the collider will raycast")] + public LayerMask m_CollideAgainst = 1; + + /// Obstacles with this tag will be ignored. It is a good idea to set this field to the target's tag + [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; + + /// Obstacles closer to the target than this will be ignored + [Tooltip("Obstacles closer to the target than this will be ignored")] + public float m_MinimumDistanceFromTarget = 0.1f; + + /// + /// When enabled, will attempt to resolve situations where the line of sight to the + /// target is blocked by an obstacle + /// + [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; + + /// + /// The raycast distance to test for when checking if the line of sight to this camera's target is clear. + /// + [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; + + /// + /// 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. + /// + [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; + + /// The way in which the Collider will attempt to preserve sight of the target. + public enum ResolutionStrategy + { + /// Camera will be pulled forward along its Z axis until it is in front of + /// the nearest obstacle + PullCameraForward, + /// In addition to pulling the camera forward, an effort will be made to + /// return the camera to its original height + PreserveCameraHeight, + /// In addition to pulling the camera forward, an effort will be made to + /// return the camera to its original distance from the target + PreserveCameraDistance + }; + /// The way in which the Collider will attempt to preserve sight of the target. + [Tooltip("The way in which the Collider will attempt to preserve sight of the target.")] + public ResolutionStrategy m_Strategy = ResolutionStrategy.PreserveCameraHeight; + + /// + /// Upper limit on how many obstacle hits to process. Higher numbers may impact performance. + /// In most environments, 4 is enough. + /// + [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; + + /// + /// The gradualness of collision resolution. Higher numbers will move the + /// camera more gradually away from obstructions. + /// + [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; + + /// 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 + [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; + + /// See wheter an object is blocking the camera's view of the target + /// 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 + /// True if something is blocking the view + public bool IsTargetObscured(ICinemachineCamera vcam) + { + return GetExtraState(vcam).targetObscured; + } + + /// See whether the virtual camera has been moved nby the collider + /// 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 + /// True if the virtual camera has been displaced due to collision or + /// target obstruction + public bool CameraWasDisplaced(CinemachineVirtualCameraBase vcam) + { + return GetExtraState(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); + } + + /// Cleanup + 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 debugResolutionPath; + + public void AddPointToDebugPath(Vector3 p) + { +#if UNITY_EDITOR + if (debugResolutionPath == null) + debugResolutionPath = new List(); + debugResolutionPath.Add(p); +#endif + } + }; + + /// Inspector API for debugging collision resolution path + public List> DebugPaths + { + get + { + List> list = new List>(); + List extraStates = GetAllExtraStates(); + foreach (var v in extraStates) + if (v.debugResolutionPath != null) + list.Add(v.debugResolutionPath); + return list; + } + } + + /// Callcack to to the collision resolution and shot evaluation + protected override void PostPipelineStageCallback( + CinemachineVirtualCameraBase vcam, + CinemachineCore.Stage stage, ref CameraState state, float deltaTime) + { + VcamExtraState extra = null; + if (stage == CinemachineCore.Stage.Body) + { + extra = GetExtraState(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(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(); + } + 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 +{ + /// + /// 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. + /// + [DocumentationSorting(22, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] + [AddComponentMenu("")] // Hide in menu + [SaveDuringPlay] + public class CinemachineConfiner : CinemachineExtension + { + /// The confiner can operate using a 2D bounding shape or a 3D bounding volume + public enum Mode + { + Confine2D, + Confine3D + }; + /// The confiner can operate using a 2D bounding shape or a 3D bounding volume + [Tooltip("The confiner can operate using a 2D bounding shape or a 3D bounding volume")] + public Mode m_ConfineMode; + + /// The volume within which the camera is to be contained. + [Tooltip("The volume within which the camera is to be contained")] + public Collider m_BoundingVolume; + + /// The 2D shape within which the camera is to be contained. + [Tooltip("The 2D shape within which the camera is to be contained")] + public Collider2D m_BoundingShape2D; + + /// If camera is orthographic, screen edges will be confined to the volume. + [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; + + /// How gradually to return the camera to the bounding volume if it goes beyond the borders + [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; + + /// See whether the virtual camera has been moved by the confiner + /// 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 + /// True if the virtual camera has been repositioned + public bool CameraWasDisplaced(CinemachineVirtualCameraBase vcam) + { + return GetExtraState(vcam).confinerDisplacement > 0; + } + + private void OnValidate() + { + m_Damping = Mathf.Max(0, m_Damping); + } + + class VcamExtraState + { + public Vector3 m_previousDisplacement; + public float confinerDisplacement; + }; + + /// Check if the bounding volume is defined + public bool IsValid + { + get + { + return ((m_ConfineMode == Mode.Confine3D && m_BoundingVolume != null) + || (m_ConfineMode == Mode.Confine2D && m_BoundingShape2D != null)); + } + } + + /// Callback to to the camera confining + 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(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> m_pathCache; + + /// Call this if the bounding shape's points change at runtime + 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>(); + for (int i = 0; i < poly.pathCount; ++i) + { + Vector2[] path = poly.GetPath(i); + List dst = new List(); + 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>(); + Vector2[] path = new Vector2[poly.pointCount]; + for (int i = 0; i < poly.pathCount; ++i) + { + int numPoints = poly.GetPath(i, path); + List dst = new List(); + 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 +{ + /// + /// 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. + /// + [DocumentationSorting(21f, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] + public class CinemachineDollyCart : MonoBehaviour + { + /// The path to follow + [Tooltip("The path to follow")] + public CinemachinePathBase m_Path; + + /// This enum defines the options available for the update method. + public enum UpdateMethod + { + /// Updated in normal MonoBehaviour Update. + Update, + /// Updated in sync with the Physics module, in FixedUpdate + FixedUpdate + }; + + /// When to move the cart, if Velocity is non-zero + [Tooltip("When to move the cart, if Velocity is non-zero")] + public UpdateMethod m_UpdateMethod = UpdateMethod.Update; + + /// How to interpret the Path Position + [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; + + /// Move the cart with this speed + [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; + + /// The cart's current position on the path, in distance units + [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 +{ + /// + /// 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. + /// + [DocumentationSorting(14, DocumentationSortingAttribute.Level.UserRef)] + [RequireComponent(typeof(Camera)), DisallowMultipleComponent, ExecuteInEditMode] + [AddComponentMenu("Cinemachine/CinemachineExternalCamera")] + public class CinemachineExternalCamera : CinemachineVirtualCameraBase + { + /// The object that the camera is looking at. + [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; + + /// Get the CameraState, as we are able to construct one from the Unity Camera + public override CameraState State { get { return m_State; } } + + /// The object that the camera is looking at + override public Transform LookAt + { + get { return m_LookAt; } + set { m_LookAt = value; } + } + + /// This vcam defines no targets + override public Transform Follow { get; set; } + + /// Construct a CameraState object from the Unity Camera + public override void UpdateCameraState(Vector3 worldUp, float deltaTime) + { + // Get the state from the camera + if (m_Camera == null) + m_Camera = GetComponent(); + + 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 +{ + /// + /// 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. + /// + [DocumentationSorting(16, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] + [AddComponentMenu("")] // Hide in menu + [SaveDuringPlay] + public class CinemachineFollowZoom : CinemachineExtension + { + /// 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. + [Tooltip("The shot width to maintain, in world units, at target distance.")] + public float m_Width = 2f; + + /// 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. + [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; + + /// Will not generate an FOV smaller than this. + [Range(1f, 179f)] + [Tooltip("Lower limit for the FOV that this behaviour will generate.")] + public float m_MinFOV = 3f; + + /// Will not generate an FOV larget than this. + [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; + } + + /// Callback to preform the zoom adjustment + protected override void PostPipelineStageCallback( + CinemachineVirtualCameraBase vcam, + CinemachineCore.Stage stage, ref CameraState state, float deltaTime) + { + VcamExtraState extra = GetExtraState(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 +{ + /// + /// 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. + /// + [DocumentationSorting(11, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineFreeLook")] + public class CinemachineFreeLook : CinemachineVirtualCameraBase + { + /// Object for the camera children to look at (the aim target) + [Tooltip("Object for the camera children to look at (the aim target).")] + [NoSaveDuringPlay] + public Transform m_LookAt = null; + + /// Object for the camera children wants to move with (the body target) + [Tooltip("Object for the camera children wants to move with (the body target).")] + [NoSaveDuringPlay] + public Transform m_Follow = null; + + /// If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used + [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; + + /// 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 + [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; + + /// The Vertical axis. Value is 0..1. Chooses how to blend the child rigs + [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); + + /// The Horizontal axis. Value is 0..359. This is passed on to the rigs' OrbitalTransposer component + [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); + + /// The definition of Forward. Camera will follow behind + [Tooltip("The definition of Forward. Camera will follow behind.")] + public CinemachineOrbitalTransposer.Heading m_Heading + = new CinemachineOrbitalTransposer.Heading( + CinemachineOrbitalTransposer.Heading.HeadingDefinition.TargetForward, 4, 0); + + /// Controls how automatic recentering of the X axis is accomplished + [Tooltip("Controls how automatic recentering of the X axis is accomplished")] + public CinemachineOrbitalTransposer.Recentering m_RecenterToTargetHeading + = new CinemachineOrbitalTransposer.Recentering(false, 1, 2); + + /// The coordinate space to use when interpreting the offset from the target + [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; + + /// + [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; + + /// Defines the height and radius of the Rig orbit + [Serializable] + public struct Orbit + { + /// Height relative to target + public float m_Height; + /// Radius of orbit + public float m_Radius; + /// Constructor with specific values + public Orbit(float h, float r) { m_Height = h; m_Radius = r; } + } + + /// The radius and height of the three orbiting rigs + [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; + + /// Enforce bounds for fields, when changed in inspector. + 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(); + } + + /// Get a child rig + /// Rig index. Can be 0, 1, or 2 + /// The rig, or null if index is bad. + public CinemachineVirtualCamera GetRig(int i) + { + UpdateRigCache(); + return (i < 0 || i > 2) ? null : m_Rigs[i]; + } + + /// Names of the 3 child rigs + public static string[] RigNames { get { return new string[] { "TopRig", "MiddleRig", "BottomRig" }; } } + + bool mIsDestroyed = false; + + /// Updates the child rig cache + protected override void OnEnable() + { + mIsDestroyed = false; + base.OnEnable(); + InvalidateRigCache(); + } + + /// Makes sure that the child rigs get destroyed in an undo-firndly manner. + /// Invalidates the rig cache. + 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(); + } + + /// Invalidates the rig cache + void OnTransformChildrenChanged() + { + InvalidateRigCache(); + } + + void Reset() + { + DestroyRigs(); + } + + /// The cacmera state, which will be a blend of the child rig states + override public CameraState State { get { return m_State; } } + + /// Get the current LookAt target. Returns parent's LookAt if parent + /// is non-null and no specific LookAt defined for this camera + override public Transform LookAt + { + get { return ResolveLookAt(m_LookAt); } + set { m_LookAt = value; } + } + + /// Get the current Follow target. Returns parent's Follow if parent + /// is non-null and no specific Follow defined for this camera + override public Transform Follow + { + get { return ResolveFollow(m_Follow); } + set { m_Follow = value; } + } + + /// Returns the rig with the greatest weight + 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]; + } + } + + /// Check whether the vcam a live child of this camera. + /// Returns true if the child is currently contributing actively to the camera state. + /// The Virtual Camera to check + /// True if the vcam is currently actively influencing the state of this vcam + 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]; + } + + /// Remove a Pipeline stage hook callback. + /// Make sure it is removed from all the children. + /// The delegate to remove. + 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); + } + + /// 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. + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than 0) + 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(); + } + + /// If we are transitioning from another FreeLook, grab the axis values from it. + /// The camera being deactivated. May be null. + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than or equal to 0) + 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; + + /// + /// 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. + /// + public static CreateRigDelegate CreateRigOverride; + + /// + /// 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. + /// + public delegate CinemachineVirtualCamera CreateRigDelegate( + CinemachineFreeLook vcam, string name, CinemachineVirtualCamera copyFrom); + + /// + /// Override component pipeline destruction. + /// This needs to be done by the editor to support Undo. + /// + public static DestroyRigDelegate DestroyRigOverride; + + /// + /// Override component pipeline destruction. + /// This needs to be done by the editor to support Undo. + /// + 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(); + } + 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(); + if (src != null) + ReflectionHelpers.CopyFields(src, newRigs[i]); + else + { + go = newRigs[i].GetComponentOwner().gameObject; + go.AddComponent(); + go.AddComponent(); + } + } + + // Set up the defaults + newRigs[i].InvalidateComponentPipeline(); + CinemachineOrbitalTransposer orbital = newRigs[i].GetCinemachineComponent(); + if (orbital == null) + orbital = newRigs[i].AddCinemachineComponent(); // should not happen + if (src == null) + { + // Only set defaults if not copying + orbital.m_YawDamping = 0; + CinemachineComposer composer = newRigs[i].GetCinemachineComponent(); + 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(); + 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(); + if (mOrbitals[i] == null && forceOrbital) + mOrbitals[i] = vcam.AddCinemachineComponent(); + 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; + } + + /// + /// 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) + /// + /// The t-value for the camera on its spline. Internally clamped to + /// the value [0,1] + /// The local offset (back + up) of the camera WRT its target based on the + /// supplied t-value + 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 +{ + /// + /// 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. + /// + [DocumentationSorting(20, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineMixingCamera")] + public class CinemachineMixingCamera : CinemachineVirtualCameraBase + { + /// 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. + public const int MaxCameras = 8; + + /// Weight of the first tracked camera + [Tooltip("The weight of the first tracked camera")] + public float m_Weight0 = 0.5f; + /// Weight of the second tracked camera + [Tooltip("The weight of the second tracked camera")] + public float m_Weight1 = 0.5f; + /// Weight of the third tracked camera + [Tooltip("The weight of the third tracked camera")] + public float m_Weight2 = 0.5f; + /// Weight of the fourth tracked camera + [Tooltip("The weight of the fourth tracked camera")] + public float m_Weight3 = 0.5f; + /// Weight of the fifth tracked camera + [Tooltip("The weight of the fifth tracked camera")] + public float m_Weight4 = 0.5f; + /// Weight of the sixth tracked camera + [Tooltip("The weight of the sixth tracked camera")] + public float m_Weight5 = 0.5f; + /// Weight of the seventh tracked camera + [Tooltip("The weight of the seventh tracked camera")] + public float m_Weight6 = 0.5f; + /// Weight of the eighth tracked camera + [Tooltip("The weight of the eighth tracked camera")] + public float m_Weight7 = 0.5f; + + /// Get the weight of the child at an index. + /// The child index. Only immediate CinemachineVirtualCameraBase + /// children are counted. + /// The weight of the camera. Valid only if camera is active and enabled. + 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; + } + + /// Set the weight of the child at an index. + /// The child index. Only immediate CinemachineVirtualCameraBase + /// children are counted. + /// The weight to set. Can be any non-negative number. + 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); + } + + /// Get the weight of the child CinemachineVirtualCameraBase. + /// The child camera. + /// The weight of the camera. Valid only if camera is active and enabled. + 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; + } + + /// Set the weight of the child CinemachineVirtualCameraBase. + /// The child camera. + /// The weight to set. Can be any non-negative number. + 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)")); + } + + /// Blended camera state + private CameraState m_State = CameraState.Default; + + /// Get the current "best" child virtual camera, which is nominally + /// the one with the greatest weight. + private ICinemachineCamera LiveChild { set; get; } + + /// The blended CameraState + public override CameraState State { get { return m_State; } } + + /// Not used + override public Transform LookAt { get; set; } + + /// Not used + override public Transform Follow { get; set; } + + /// Return the live child. + public override ICinemachineCamera LiveChildOrSelf { get { return LiveChild; } } + + /// Remove a Pipeline stage hook callback. + /// Make sure it is removed from all the children. + /// The delegate to remove. + public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + base.RemovePostPipelineStageHook(d); + ValidateListOfChildren(); + foreach (var vcam in m_ChildCameras) + vcam.RemovePostPipelineStageHook(d); + } + + /// Makes sure the internal child cache is up to date + protected override void OnEnable() + { + base.OnEnable(); + InvalidateListOfChildren(); + } + + /// Makes sure the internal child cache is up to date + public void OnTransformChildrenChanged() + { + InvalidateListOfChildren(); + } + + /// Makes sure the weights are non-negative + protected override void OnValidate() + { + base.OnValidate(); + for (int i = 0; i < MaxCameras; ++i) + SetWeight(i, Mathf.Max(0, GetWeight(i))); + } + + /// Check whether the vcam a live child of this camera. + /// The Virtual Camera to check + /// True if the vcam is currently actively influencing the state of this vcam + 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 m_indexMap; + + /// 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 + public CinemachineVirtualCameraBase[] ChildCameras + { + get { ValidateListOfChildren(); return m_ChildCameras; } + } + + /// Invalidate the cached list of child cameras. + protected void InvalidateListOfChildren() + { + m_ChildCameras = null; + m_indexMap = null; + LiveChild = null; + } + + /// Rebuild the cached list of child cameras. + protected void ValidateListOfChildren() + { + if (m_ChildCameras != null) + return; + + m_indexMap = new Dictionary(); + List list = new List(); + CinemachineVirtualCameraBase[] kids + = GetComponentsInChildren(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(); + } + + /// 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. + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than 0) + 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 +{ + /// 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. + [DocumentationSorting(18, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("Cinemachine/CinemachinePath")] + [SaveDuringPlay] + public class CinemachinePath : CinemachinePathBase + { + /// A waypoint along the path + [DocumentationSorting(18.2f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] public struct Waypoint + { + /// Position in path-local space + [Tooltip("Position in path-local space")] + public Vector3 position; + + /// 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. + [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; + + /// Defines the roll of the path at this waypoint. + /// The other orientation axes are inferred from the tangent and world up. + [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; + } + + /// If checked, then the path ends are joined to form a continuous loop + [Tooltip("If checked, then the path ends are joined to form a continuous loop.")] + public bool m_Looped; + + /// The waypoints that define the path. + /// They will be interpolated using a bezier curve + [Tooltip("The waypoints that define the path. They will be interpolated using a bezier curve.")] + public Waypoint[] m_Waypoints = new Waypoint[0]; + + /// The minimum value for the path position + public override float MinPos { get { return 0; } } + + /// The maximum value for the path position + public override float MaxPos + { + get + { + int count = m_Waypoints.Length - 1; + if (count < 1) + return 0; + return m_Looped ? count + 1 : count; + } + } + /// True if the path ends are joined to form a continuous loop + public override bool Looped { get { return m_Looped; } } + + /// When calculating the distance cache, sample the path this many + /// times between points + public override int DistanceCacheSampleStepsPerSegment { get { return m_Resolution; } } + + /// Returns normalized position + 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; + } + + /// Get a worldspace position of a point along the path + /// Postion along the path. Need not be normalized. + /// World-space position of the point along at path at pos + 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); + } + + /// Get the tangent of the curve at a point along the path. + /// Postion along the path. Need not be normalized. + /// World-space direction of the path tangent. + /// Length of the vector represents the tangent strength + 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); + } + + /// Get the orientation the curve at a point along the path. + /// Postion along the path. Need not be normalized. + /// World-space orientation of the path, as defined by tangent, up, and roll. + 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 +{ + /// + /// Internal container for CinemachineComponentBase. Does nothing but contain. + /// + [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 +{ + /// 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 + [DocumentationSorting(18.5f, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("Cinemachine/CinemachineSmoothPath")] + [SaveDuringPlay] + public class CinemachineSmoothPath : CinemachinePathBase + { + /// If checked, then the path ends are joined to form a continuous loop + [Tooltip("If checked, then the path ends are joined to form a continuous loop.")] + public bool m_Looped; + + /// A waypoint along the path + [DocumentationSorting(18.7f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] public struct Waypoint + { + /// Position in path-local space + [Tooltip("Position in path-local space")] + public Vector3 position; + + /// Defines the roll of the path at this waypoint. + /// The other orientation axes are inferred from the tangent and world up. + [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; + + /// Representation as Vector4 + 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; + } + } + + /// The waypoints that define the path. + /// They will be interpolated using a bezier curve + [Tooltip("The waypoints that define the path. They will be interpolated using a bezier curve.")] + public Waypoint[] m_Waypoints = new Waypoint[0]; + + /// The minimum value for the path position + public override float MinPos { get { return 0; } } + + /// The maximum value for the path position + public override float MaxPos + { + get + { + int count = m_Waypoints.Length - 1; + if (count < 1) + return 0; + return m_Looped ? count + 1 : count; + } + } + /// True if the path ends are joined to form a continuous loop + public override bool Looped { get { return m_Looped; } } + + /// When calculating the distance cache, sample the path this many + /// times between points + public override int DistanceCacheSampleStepsPerSegment { get { return m_Resolution; } } + + private void OnValidate() { InvalidateDistanceCache(); } + + /// Call this if the path changes in such a way as to affect distances + /// or other cached path elements + 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; + } + } + + /// Returns normalized position + 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; + } + + /// Get a worldspace position of a point along the path + /// Postion along the path. Need not be normalized. + /// World-space position of the point along at path at pos + 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); + } + + /// Get the tangent of the curve at a point along the path. + /// Postion along the path. Need not be normalized. + /// World-space direction of the path tangent. + /// Length of the vector represents the tangent strength + 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); + } + + /// Get the orientation the curve at a point along the path. + /// Postion along the path. Need not be normalized. + /// World-space orientation of the path, as defined by tangent, up, and roll. + 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 +{ + /// + /// 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. + /// + [DocumentationSorting(17, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] + [AddComponentMenu("")] // Hide in menu + [SaveDuringPlay] + public class CinemachineSmoother : CinemachineExtension + { + /// + /// The strength of the smoothing for position. This is applied after the vcam cas calculated its state. + /// + [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; + + /// + /// The strength of the smoothing for the LookAt target. This is applied after the vcam cas calculated its state. + /// + [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; + + /// + /// The strength of the smoothing for rotation. This is applied after the vcam cas calculated its state. + /// + [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(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(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 +{ + /// + /// 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. + /// + [DocumentationSorting(13, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineStateDrivenCamera")] + public class CinemachineStateDrivenCamera : CinemachineVirtualCameraBase + { + /// Default object for the camera children to look at (the aim target), if not specified in a child rig. May be empty + [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; + + /// Default object for the camera children wants to move with (the body target), if not specified in a child rig. May be empty + [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; + + /// The state machine whose state changes will drive this camera's choice of active child + [Space] + [Tooltip("The state machine whose state changes will drive this camera's choice of active child")] + public Animator m_AnimatedTarget; + + /// Which layer in the target FSM to observe + [Tooltip("Which layer in the target state machine to observe")] + public int m_LayerIndex; + + /// When enabled, the current camera and blend will be indicated in the game window, for debugging + [Tooltip("When enabled, the current child camera and blend will be indicated in the game window, for debugging")] + public bool m_ShowDebugText = false; + + /// Force all child cameras to be enabled. This is useful if animating them in Timeline, but consumes extra resources. + [Tooltip("Force all child cameras to be enabled. This is useful if animating them in Timeline, but consumes extra resources")] + public bool m_EnableAllChildCameras; + + /// Internal API for the editor. Do not use this field + [SerializeField][HideInInspector][NoSaveDuringPlay] + public CinemachineVirtualCameraBase[] m_ChildCameras = null; + + /// 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. + [Serializable] + public struct Instruction + { + /// The full hash of the animation state + [Tooltip("The full hash of the animation state")] + public int m_FullHash; + /// The virtual camera to activate whrn the animation state becomes active + [Tooltip("The virtual camera to activate whrn the animation state becomes active")] + public CinemachineVirtualCameraBase m_VirtualCamera; + /// How long to wait (in seconds) before activating the virtual camera. + /// This filters out very short state durations + [Tooltip("How long to wait (in seconds) before activating the virtual camera. This filters out very short state durations")] + public float m_ActivateAfter; + /// The minimum length of time (in seconds) to keep a virtual camera active + [Tooltip("The minimum length of time (in seconds) to keep a virtual camera active")] + public float m_MinDuration; + }; + + /// The set of instructions associating virtual cameras with states. + /// These instructions are used to choose the live child at any given moment + [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; + + /// + /// The blend which is used if you don't explicitly define a blend between two Virtual Camera children. + /// + [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); + + /// + /// This is the asset which contains custom settings for specific child blends. + /// + [Tooltip("This is the asset which contains custom settings for specific child blends")] + public CinemachineBlenderSettings m_CustomBlends = null; + + /// Internal API for the Inspector editor. This implements nested states. + [Serializable] + [DocumentationSorting(13.2f, DocumentationSortingAttribute.Level.Undoc)] + public struct ParentHash + { + /// Internal API for the Inspector editor + public int m_Hash; + /// Internal API for the Inspector editor + public int m_ParentHash; + /// Internal API for the Inspector editor + public ParentHash(int h, int p) { m_Hash = h; m_ParentHash = p; } + } + /// Internal API for the Inspector editor + [HideInInspector][SerializeField] public ParentHash[] m_ParentHash = null; + + /// Gets a brief debug description of this virtual camera, for use when displayiong debug info + 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; + } + } + + /// Get the current "best" child virtual camera, that would be chosen + /// if the State Driven Camera were active. + public ICinemachineCamera LiveChild { set; get; } + + /// Return the live child. + public override ICinemachineCamera LiveChildOrSelf { get { return LiveChild; } } + + /// Check whether the vcam a live child of this camera. + /// The Virtual Camera to check + /// True if the vcam is currently actively influencing the state of this vcam + public override bool IsLiveChild(ICinemachineCamera vcam) + { + return vcam == LiveChild + || (mActiveBlend != null && (vcam == mActiveBlend.CamA || vcam == mActiveBlend.CamB)); + } + + /// The State of the current live child + public override CameraState State { get { return m_State; } } + + /// Get the current LookAt target. Returns parent's LookAt if parent + /// is non-null and no specific LookAt defined for this camera + override public Transform LookAt + { + get { return ResolveLookAt(m_LookAt); } + set { m_LookAt = value; } + } + + /// Get the current Follow target. Returns parent's Follow if parent + /// is non-null and no specific Follow defined for this camera + override public Transform Follow + { + get { return ResolveFollow(m_Follow); } + set { m_Follow = value; } + } + + /// Remove a Pipeline stage hook callback. + /// Make sure it is removed from all the children. + /// The delegate to remove. + public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + base.RemovePostPipelineStageHook(d); + UpdateListOfChildren(); + foreach (var vcam in m_ChildCameras) + vcam.RemovePostPipelineStageHook(d); + } + + /// 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. + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than or equal to 0) + 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(); + } + + /// Makes sure the internal child cache is up to date + protected override void OnEnable() + { + base.OnEnable(); + InvalidateListOfChildren(); + mActiveBlend = null; + } + + /// Makes sure the internal child cache is up to date + public void OnTransformChildrenChanged() + { + InvalidateListOfChildren(); + } + +#if UNITY_EDITOR + /// Displays the current active camera on the game screen, if requested + 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; + + /// The list of child cameras. These are just the immediate children in the hierarchy. + public CinemachineVirtualCameraBase[] ChildCameras { get { UpdateListOfChildren(); return m_ChildCameras; }} + + /// Is there a blend in progress? + public bool IsBlending { get { return mActiveBlend != null; } } + + /// 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 + 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 list = new List(); + CinemachineVirtualCameraBase[] kids = GetComponentsInChildren(true); + foreach (CinemachineVirtualCameraBase k in kids) + if (k.transform.parent == transform) + list.Add(k); + m_ChildCameras = list.ToArray(); + ValidateInstructions(); + } + + private Dictionary mInstructionDictionary; + private Dictionary mStateParentLookup; + /// Internal API for the inspector editor. + public void ValidateInstructions() + { + if (m_Instructions == null) + m_Instructions = new Instruction[0]; + mInstructionDictionary = new Dictionary(); + 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(); + 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 m_clipInfoList = new List(); + 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 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 +{ + /// 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. + /// + [DocumentationSorting(19, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("Cinemachine/CinemachineTargetGroup")] + [SaveDuringPlay] + [ExecuteInEditMode] + public class CinemachineTargetGroup : MonoBehaviour + { + /// Holds the information that represents a member of the group + [DocumentationSorting(19.1f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] public struct Target + { + /// The target objects. This object's position and orientation will contribute to the + /// group's average position and orientation, in accordance with its weight + [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; + /// How much weight to give the target when averaging. Cannot be negative + [Tooltip("How much weight to give the target when averaging. Cannot be negative")] + public float weight; + /// The radius of the target, used for calculating the bounding box. Cannot be negative + [Tooltip("The radius of the target, used for calculating the bounding box. Cannot be negative")] + public float radius; + } + + /// How the group's position is calculated + [DocumentationSorting(19.2f, DocumentationSortingAttribute.Level.UserRef)] + public enum PositionMode + { + ///Group position will be the center of the group's axis-aligned bounding box + GroupCenter, + /// Group position will be the weighted average of the positions of the members + GroupAverage + } + + /// How the group's position is calculated + [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; + + /// How the group's orientation is calculated + [DocumentationSorting(19.3f, DocumentationSortingAttribute.Level.UserRef)] + public enum RotationMode + { + /// Manually set in the group's transform + Manual, + /// Weighted average of the orientation of its members. + GroupAverage + } + + /// How the group's orientation is calculated + [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; + + /// This enum defines the options available for the update method. + public enum UpdateMethod + { + /// Updated in normal MonoBehaviour Update. + Update, + /// Updated in sync with the Physics module, in FixedUpdate + FixedUpdate, + /// Updated in MonoBehaviour LateUpdate. + LateUpdate + }; + + /// When to update the group's transform based on the position of the group members + [Tooltip("When to update the group's transform based on the position of the group members")] + public UpdateMethod m_UpdateMethod = UpdateMethod.LateUpdate; + + /// The target objects, together with their weights and radii, that will + /// contribute to the group's average position, orientation, and size + [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; + + /// The axis-aligned bounding box of the group, computed using the + /// targets positions and radii + 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; + } + } + + /// Return true if there are no members with weight > 0 + 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; + } + } + + /// The axis-aligned bounding box of the group, in a specific reference frame + /// The frame of reference in which to compute the bounding box + /// The axis-aligned bounding box of the group, in the desired frame of reference + 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 +{ + /// + /// 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. + /// + /// + /// + /// + /// + /// + [DocumentationSorting(1, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode, DisallowMultipleComponent] + [AddComponentMenu("Cinemachine/CinemachineVirtualCamera")] + public class CinemachineVirtualCamera : CinemachineVirtualCameraBase + { + /// 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. + [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; + + /// 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. + [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; + + /// Specifies the LensSettings of this Virtual Camera. + /// These settings will be transferred to the Unity camera when the vcam is live. + [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; + + /// 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. + public const string PipelineName = "cm"; + + /// The CameraState object holds all of the information + /// necessary to position the Unity camera. It is the output of this class. + override public CameraState State { get { return m_State; } } + + /// 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. + override public Transform LookAt + { + get { return ResolveLookAt(m_LookAt); } + set { m_LookAt = value; } + } + + /// 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. + override public Transform Follow + { + get { return ResolveFollow(m_Follow); } + set { m_Follow = value; } + } + + /// 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. + 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(); + } + + /// Make sure that the pipeline cache is up-to-date. + 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(); + if (LookAt != null && GetCinemachineComponent(CinemachineCore.Stage.Aim) == null) + AddCinemachineComponent(); + } + } + + /// Calls the DestroyPipelineDelegate for destroying the hidden + /// child object, to support undo. + 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() != null) + child.gameObject.hideFlags + &= ~(HideFlags.HideInHierarchy | HideFlags.HideInInspector); + + base.OnDestroy(); + } + + /// Enforce bounds for fields, when changed in inspector. + protected override void OnValidate() + { + base.OnValidate(); + m_Lens.Validate(); + } + + void OnTransformChildrenChanged() + { + InvalidateComponentPipeline(); + } + + void Reset() + { + DestroyPipeline(); + } + + /// + /// 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. + /// + public static CreatePipelineDelegate CreatePipelineOverride; + + /// + /// 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. + /// + public delegate Transform CreatePipelineDelegate( + CinemachineVirtualCamera vcam, string name, CinemachineComponentBase[] copyFrom); + + /// + /// Override component pipeline destruction. + /// This needs to be done by the editor to support Undo. + /// + public static DestroyPipelineDelegate DestroyPipelineOverride; + + /// + /// Override component pipeline destruction. + /// This needs to be done by the editor to support Undo. + /// + public delegate void DestroyPipelineDelegate(GameObject pipeline); + + /// Destroy any existing pipeline container. + private void DestroyPipeline() + { + List oldPipeline = new List(); + foreach (Transform child in transform) + if (child.GetComponent() != null) + oldPipeline.Add(child); + + foreach (Transform child in oldPipeline) + { + if (DestroyPipelineOverride != null) + DestroyPipelineOverride(child.gameObject); + else + Destroy(child.gameObject); + } + m_ComponentOwner = null; + PreviousStateIsValid = false; + } + + /// Create a default pipeline container. + 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(); + 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; + } + + /// + /// Editor API: Call this when changing the pipeline from the editor. + /// Will force a rebuild of the pipeline cache. + /// + public void InvalidateComponentPipeline() { m_ComponentPipeline = null; } + + /// Get the hidden CinemachinePipeline child object. + public Transform GetComponentOwner() { UpdateComponentPipeline(); return m_ComponentOwner; } + + /// Get the component pipeline owned by the hidden child pipline container. + /// For most purposes, it is preferable to use the GetCinemachineComponent method. + public CinemachineComponentBase[] GetComponentPipeline() { UpdateComponentPipeline(); return m_ComponentPipeline; } + + /// Get the component set for a specific stage. + /// The stage for which we want the component + /// The Cinemachine component for that stage, or null if not defined + 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; + } + + /// Get an existing component of a specific type from the cinemachine pipeline. + public T GetCinemachineComponent() where T : CinemachineComponentBase + { + CinemachineComponentBase[] components = GetComponentPipeline(); + if (components != null) + foreach (var c in components) + if (c is T) + return c as T; + return null; + } + + /// Add a component to the cinemachine pipeline. + public T AddCinemachineComponent() where T : CinemachineComponentBase + { + // Get the existing components + Transform owner = GetComponentOwner(); + CinemachineComponentBase[] components = owner.GetComponents(); + + T component = owner.gameObject.AddComponent(); + 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; + } + + /// Remove a component from the cinemachine pipeline. + public void DestroyCinemachineComponent() where T : CinemachineComponentBase + { + CinemachineComponentBase[] components = GetComponentPipeline(); + if (components != null) + { + foreach (var c in components) + { + if (c is T) + { + c.enabled = false; + DestroyImmediate(c); + InvalidateComponentPipeline(); + } + } + } + } + + /// API for the editor, to make the dragging of position handles behave better. + public bool UserIsDragging { get; set; } + + /// API for the editor, to process a position drag from the user. + 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() : 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 list = new List(); + foreach (Transform child in transform) + { + if (child.GetComponent() != null) + { + m_ComponentOwner = child; + CinemachineComponentBase[] components = child.GetComponents(); + 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: diff --git a/Assets/Cinemachine/Base/Runtime/Components.meta b/Assets/Cinemachine/Base/Runtime/Components.meta new file mode 100644 index 0000000..29e55f1 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 0fafdc3d4f989ff48803e7d870539b41 +folderAsset: yes +timeCreated: 1489096338 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineBasicMultiChannelPerlin.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachineBasicMultiChannelPerlin.cs new file mode 100644 index 0000000..6b43df1 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineBasicMultiChannelPerlin.cs @@ -0,0 +1,113 @@ +using UnityEngine; +using UnityEngine.Serialization; + +namespace Cinemachine +{ + /// + /// As a part of the Cinemachine Pipeline implementing the Noise stage, this + /// component adds Perlin Noise to the Camera state, in the Correction + /// channel of the CameraState. + /// + /// The noise is created by using a predefined noise profile asset. This defines the + /// shape of the noise over time. You can scale this in amplitude or in time, to produce + /// a large family of different noises using the same profile. + /// + /// + [DocumentationSorting(8, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachineBasicMultiChannelPerlin : CinemachineComponentBase + { + /// + /// Serialized property for referencing a NoiseSettings asset + /// + [HideInInspector] + [Tooltip("The asset containing the Noise Profile. Define the frequencies and amplitudes there to make a characteristic noise profile. Make your own or just use one of the many presets.")] + [FormerlySerializedAs("m_Definition")] + public NoiseSettings m_NoiseProfile; + + /// + /// Gain to apply to the amplitudes defined in the settings asset. + /// + [Tooltip("Gain to apply to the amplitudes defined in the NoiseSettings asset. 1 is normal. Setting this to 0 completely mutes the noise.")] + public float m_AmplitudeGain = 1f; + + /// + /// Scale factor to apply to the frequencies defined in the settings asset. + /// + [Tooltip("Scale factor to apply to the frequencies defined in the NoiseSettings asset. 1 is normal. Larger magnitudes will make the noise shake more rapidly.")] + public float m_FrequencyGain = 1f; + + /// True if the component is valid, i.e. it has a noise definition and is enabled. + public override bool IsValid { get { return enabled && m_NoiseProfile != null; } } + + /// Get the Cinemachine Pipeline stage that this component implements. + /// Always returns the Noise stage + public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Noise; } } + + /// Applies noise to the Correction channel of the CameraState if the + /// delta time is greater than 0. Otherwise, does nothing. + /// The current camera state + /// How much to advance the perlin noise generator. + /// Noise is only applied if this value is greater than or equal to 0 + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + if (!IsValid || deltaTime < 0) + return; + + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineBasicMultiChannelPerlin.MutateCameraState"); + if (!mInitialized) + Initialize(); + + mNoiseTime += deltaTime * m_FrequencyGain; + curState.PositionCorrection += curState.CorrectedOrientation * GetCombinedFilterResults( + m_NoiseProfile.PositionNoise, mNoiseTime, mNoiseOffsets) * m_AmplitudeGain; + Quaternion rotNoise = Quaternion.Euler(GetCombinedFilterResults( + m_NoiseProfile.OrientationNoise, mNoiseTime, mNoiseOffsets) * m_AmplitudeGain); + curState.OrientationCorrection = curState.OrientationCorrection * rotNoise; + //UnityEngine.Profiling.Profiler.EndSample(); + } + + private bool mInitialized = false; + private float mNoiseTime = 0; + private Vector3 mNoiseOffsets = Vector3.zero; + + void Initialize() + { + mInitialized = true; + mNoiseTime = 0; + mNoiseOffsets = new Vector3( + UnityEngine.Random.Range(-10000f, 10000f), + UnityEngine.Random.Range(-10000f, 10000f), + UnityEngine.Random.Range(-10000f, 10000f)); + } + + static Vector3 GetCombinedFilterResults( + NoiseSettings.TransformNoiseParams[] noiseParams, float time, Vector3 noiseOffsets) + { + float xPos = 0f; + float yPos = 0f; + float zPos = 0f; + if (noiseParams != null) + { + for (int i = 0; i < noiseParams.Length; ++i) + { + NoiseSettings.TransformNoiseParams param = noiseParams[i]; + Vector3 timeVal = new Vector3(param.X.Frequency, param.Y.Frequency, param.Z.Frequency) * time; + timeVal += noiseOffsets; + + Vector3 noise = new Vector3( + Mathf.PerlinNoise(timeVal.x, 0f) - 0.5f, + Mathf.PerlinNoise(timeVal.y, 0f) - 0.5f, + Mathf.PerlinNoise(timeVal.z, 0f) - 0.5f); + + xPos += noise.x * param.X.Amplitude; + yPos += noise.y * param.Y.Amplitude; + zPos += noise.z * param.Z.Amplitude; + } + } + return new Vector3(xPos, yPos, zPos); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineBasicMultiChannelPerlin.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachineBasicMultiChannelPerlin.cs.meta new file mode 100644 index 0000000..a4e5847 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineBasicMultiChannelPerlin.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 68bb026fafb42b14791938953eaace77 +timeCreated: 1484001117 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineComposer.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachineComposer.cs new file mode 100644 index 0000000..86c091c --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineComposer.cs @@ -0,0 +1,391 @@ +using UnityEngine; +using System; +using Cinemachine.Utility; + +namespace Cinemachine +{ + /// + /// This is a CinemachineComponent in the Aim section of the component pipeline. + /// Its job is to aim the camera at the vcam's LookAt target object, with + /// configurable offsets, damping, and composition rules. + /// + /// The composer does not change the camera's position. It will only pan and tilt the + /// camera where it is, in order to get the desired framing. To move the camera, you have + /// to use the virtual camera's Body section. + /// + [DocumentationSorting(3, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] // for OnGUI + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachineComposer : CinemachineComponentBase + { + /// Used by the Inspector Editor to display on-screen guides. + [NoSaveDuringPlay, HideInInspector] + public Action OnGUICallback = null; + + /// Target offset from the object's center in LOCAL space which + /// the Composer tracks. Use this to fine-tune the tracking target position + /// when the desired area is not in the tracked object's center + [Tooltip("Target offset from the target object's center in target-local space. Use this to fine-tune the tracking target position when the desired area is not the tracked object's center.")] + public Vector3 m_TrackedObjectOffset = Vector3.zero; + + /// This setting will instruct the composer to adjust its target offset based + /// on the motion of the target. The composer will look at a point where it estimates + /// the target will be this many seconds into the future. Note that this setting is sensitive + /// to noisy animation, and can amplify the noise, resulting in undesirable camera jitter. + /// If the camera jitters unacceptably when the target is in motion, turn down this setting, + /// or animate the target more smoothly. + [Tooltip("This setting will instruct the composer to adjust its target offset based on the motion of the target. The composer will look at a point where it estimates the target will be this many seconds into the future. Note that this setting is sensitive to noisy animation, and can amplify the noise, resulting in undesirable camera jitter. If the camera jitters unacceptably when the target is in motion, turn down this setting, or animate the target more smoothly.")] + [Range(0f, 1f)] + public float m_LookaheadTime = 0; + + /// Controls the smoothness of the lookahead algorithm. Larger values smooth out + /// jittery predictions and also increase prediction lag + [Tooltip("Controls the smoothness of the lookahead algorithm. Larger values smooth out jittery predictions and also increase prediction lag")] + [Range(3, 30)] + public float m_LookaheadSmoothing = 10; + + /// How aggressively the camera tries to follow the target in the screen-horizontal direction. + /// Small numbers are more responsive, rapidly orienting the camera to keep the target in + /// the dead zone. Larger numbers give a more heavy slowly responding camera. + /// Using different vertical and horizontal settings can yield a wide range of camera behaviors. + [Space] + [Range(0f, 20)] + [Tooltip("How aggressively the camera tries to follow the target in the screen-horizontal direction. Small numbers are more responsive, rapidly orienting the camera to keep the target in the dead zone. Larger numbers give a more heavy slowly responding camera. Using different vertical and horizontal settings can yield a wide range of camera behaviors.")] + public float m_HorizontalDamping = 0.5f; + + /// How aggressively the camera tries to follow the target in the screen-vertical direction. + /// Small numbers are more responsive, rapidly orienting the camera to keep the target in + /// the dead zone. Larger numbers give a more heavy slowly responding camera. Using different vertical + /// and horizontal settings can yield a wide range of camera behaviors. + [Range(0f, 20)] + [Tooltip("How aggressively the camera tries to follow the target in the screen-vertical direction. Small numbers are more responsive, rapidly orienting the camera to keep the target in the dead zone. Larger numbers give a more heavy slowly responding camera. Using different vertical and horizontal settings can yield a wide range of camera behaviors.")] + public float m_VerticalDamping = 0.5f; + + /// Horizontal screen position for target. The camera will rotate to the position the tracked object here + [Space] + [Range(0f, 1f)] + [Tooltip("Horizontal screen position for target. The camera will rotate to position the tracked object here.")] + public float m_ScreenX = 0.5f; + + /// Vertical screen position for target, The camera will rotate to to position the tracked object here + [Range(0f, 1f)] + [Tooltip("Vertical screen position for target, The camera will rotate to position the tracked object here.")] + public float m_ScreenY = 0.5f; + + /// Camera will not rotate horizontally if the target is within this range of the position + [Range(0f, 1f)] + [Tooltip("Camera will not rotate horizontally if the target is within this range of the position.")] + public float m_DeadZoneWidth = 0.1f; + + /// Camera will not rotate vertically if the target is within this range of the position + [Range(0f, 1f)] + [Tooltip("Camera will not rotate vertically if the target is within this range of the position.")] + public float m_DeadZoneHeight = 0.1f; + + /// When target is within this region, camera will gradually move to re-align + /// towards the desired position, depending onm the damping speed + [Range(0f, 2f)] + [Tooltip("When target is within this region, camera will gradually rotate horizontally to re-align towards the desired position, depending on the damping speed.")] + public float m_SoftZoneWidth = 0.8f; + + /// When target is within this region, camera will gradually move to re-align + /// towards the desired position, depending onm the damping speed + [Range(0f, 2f)] + [Tooltip("When target is within this region, camera will gradually rotate vertically to re-align towards the desired position, depending on the damping speed.")] + public float m_SoftZoneHeight = 0.8f; + + /// A non-zero bias will move the targt position away from the center of the soft zone + [Range(-0.5f, 0.5f)] + [Tooltip("A non-zero bias will move the target position horizontally away from the center of the soft zone.")] + public float m_BiasX = 0f; + + /// A non-zero bias will move the targt position away from the center of the soft zone + [Range(-0.5f, 0.5f)] + [Tooltip("A non-zero bias will move the target position vertically away from the center of the soft zone.")] + public float m_BiasY = 0f; + + /// True if component is enabled and has a LookAt defined + public override bool IsValid { get { return enabled && LookAtTarget != null; } } + + /// Get the Cinemachine Pipeline stage that this component implements. + /// Always returns the Aim stage + public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Aim; } } + + /// Internal API for inspector + public Vector3 TrackedPoint { get; private set; } + + /// Apply the target offsets to the target location. + /// Also set the TrackedPoint property, taking lookahead into account. + /// The unoffset LookAt point + /// The LookAt point with the offset applied + protected virtual Vector3 GetLookAtPointAndSetTrackedPoint(Vector3 lookAt) + { + Vector3 pos = lookAt; + if (LookAtTarget != null) + pos += LookAtTarget.transform.rotation * m_TrackedObjectOffset; + + m_Predictor.Smoothing = m_LookaheadSmoothing; + m_Predictor.AddPosition(pos); + TrackedPoint = (m_LookaheadTime > 0) + ? m_Predictor.PredictPosition(m_LookaheadTime) : pos; + + return pos; + } + +#if UNITY_EDITOR + private void OnGUI() { if (OnGUICallback != null) OnGUICallback(); } +#endif + + /// State information for damping + Vector3 m_CameraPosPrevFrame = Vector3.zero; + Vector3 m_LookAtPrevFrame = Vector3.zero; + Vector2 m_ScreenOffsetPrevFrame = Vector2.zero; + Quaternion m_CameraOrientationPrevFrame = Quaternion.identity; + PositionPredictor m_Predictor = new PositionPredictor(); + + public override void PrePipelineMutateCameraState(ref CameraState curState) + { + if (IsValid && curState.HasLookAt) + curState.ReferenceLookAt = GetLookAtPointAndSetTrackedPoint(curState.ReferenceLookAt); + } + + /// Applies the composer rules and orients the camera accordingly + /// The current camera state + /// Used for calculating damping. If less than + /// zero, then target will snap to the center of the dead zone. + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + // Initialize the state for previous frame if appropriate + if (deltaTime < 0) + m_Predictor.Reset(); + + if (!IsValid || !curState.HasLookAt) + return; + + float targetDistance = (TrackedPoint - curState.CorrectedPosition).magnitude; + if (targetDistance < Epsilon) + { + if (deltaTime >= 0) + curState.RawOrientation = m_CameraOrientationPrevFrame; + return; // navel-gazing, get outa here + } + + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineComposer.MutateCameraState"); + float fov, fovH; + if (curState.Lens.Orthographic) + { + // Calculate effective fov - fake it for ortho based on target distance + fov = Mathf.Rad2Deg * 2 * Mathf.Atan(curState.Lens.OrthographicSize / targetDistance); + fovH = Mathf.Rad2Deg * 2 * Mathf.Atan( + curState.Lens.Aspect * curState.Lens.OrthographicSize / targetDistance); + } + else + { + fov = curState.Lens.FieldOfView; + double radHFOV = 2 * Math.Atan(Math.Tan(fov * Mathf.Deg2Rad / 2) * curState.Lens.Aspect); + fovH = (float)(Mathf.Rad2Deg * radHFOV); + } + + Quaternion rigOrientation = curState.RawOrientation; + Rect softGuideFOV = ScreenToFOV(SoftGuideRect, fov, fovH, curState.Lens.Aspect); + if (deltaTime < 0) + { + // No damping, just snap to central bounds, skipping the soft zone + Rect rect = new Rect(softGuideFOV.center, Vector2.zero); // Force to center + RotateToScreenBounds(ref curState, rect, ref rigOrientation, fov, fovH, -1); + } + else + { + // Start with previous frame's orientation (but with current up) + Vector3 dir = m_LookAtPrevFrame - (m_CameraPosPrevFrame + curState.PositionDampingBypass); + if (dir.AlmostZero()) + rigOrientation = Quaternion.LookRotation( + m_CameraOrientationPrevFrame * Vector3.forward, curState.ReferenceUp); + else + { + rigOrientation = Quaternion.LookRotation(dir, curState.ReferenceUp); + rigOrientation = rigOrientation.ApplyCameraRotation( + -m_ScreenOffsetPrevFrame, curState.ReferenceUp); + } + + // First force the previous rotation into the hard bounds, no damping, + // then Now move it through the soft zone, with damping + Rect hardGuideFOV = ScreenToFOV(HardGuideRect, fov, fovH, curState.Lens.Aspect); + if (!RotateToScreenBounds(ref curState, hardGuideFOV, ref rigOrientation, fov, fovH, -1)) + RotateToScreenBounds(ref curState, softGuideFOV, ref rigOrientation, fov, fovH, deltaTime); + } + m_CameraPosPrevFrame = curState.CorrectedPosition; + m_LookAtPrevFrame = TrackedPoint; + m_CameraOrientationPrevFrame = UnityQuaternionExtensions.Normalized(rigOrientation); + m_ScreenOffsetPrevFrame = m_CameraOrientationPrevFrame.GetCameraRotationToTarget( + m_LookAtPrevFrame - curState.CorrectedPosition, curState.ReferenceUp); + + curState.RawOrientation = m_CameraOrientationPrevFrame; + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// Internal API for the inspector editor + public Rect SoftGuideRect + { + get + { + return new Rect( + m_ScreenX - m_DeadZoneWidth / 2, m_ScreenY - m_DeadZoneHeight / 2, + m_DeadZoneWidth, m_DeadZoneHeight); + } + set + { + m_DeadZoneWidth = Mathf.Clamp01(value.width); + m_DeadZoneHeight = Mathf.Clamp01(value.height); + m_ScreenX = Mathf.Clamp01(value.x + m_DeadZoneWidth / 2); + m_ScreenY = Mathf.Clamp01(value.y + m_DeadZoneHeight / 2); + m_SoftZoneWidth = Mathf.Max(m_SoftZoneWidth, m_DeadZoneWidth); + m_SoftZoneHeight = Mathf.Max(m_SoftZoneHeight, m_DeadZoneHeight); + } + } + + /// Internal API for the inspector editor + public Rect HardGuideRect + { + get + { + Rect r = new Rect( + m_ScreenX - m_SoftZoneWidth / 2, m_ScreenY - m_SoftZoneHeight / 2, + m_SoftZoneWidth, m_SoftZoneHeight); + r.position += new Vector2( + m_BiasX * (m_SoftZoneWidth - m_DeadZoneWidth), + m_BiasY * (m_SoftZoneHeight - m_DeadZoneHeight)); + return r; + } + set + { + m_SoftZoneWidth = Mathf.Clamp(value.width, 0, 2f); + m_SoftZoneHeight = Mathf.Clamp(value.height, 0, 2f); + m_DeadZoneWidth = Mathf.Min(m_DeadZoneWidth, m_SoftZoneWidth); + m_DeadZoneHeight = Mathf.Min(m_DeadZoneHeight, m_SoftZoneHeight); + + Vector2 center = value.center; + Vector2 bias = center - new Vector2(m_ScreenX, m_ScreenY); + float biasWidth = Mathf.Max(0, m_SoftZoneWidth - m_DeadZoneWidth); + float biasHeight = Mathf.Max(0, m_SoftZoneHeight - m_DeadZoneHeight); + m_BiasX = biasWidth < Epsilon ? 0 : Mathf.Clamp(bias.x / biasWidth, -0.5f, 0.5f); + m_BiasY = biasHeight < Epsilon ? 0 : Mathf.Clamp(bias.y / biasHeight, -0.5f, 0.5f); + } + } + + // Convert from screen coords to normalized FOV angular coords + private Rect ScreenToFOV(Rect rScreen, float fov, float fovH, float aspect) + { + Rect r = new Rect(rScreen); + Matrix4x4 persp = Matrix4x4.Perspective(fov, aspect, 0.01f, 10000f).inverse; + + Vector3 p = persp.MultiplyPoint(new Vector3(0, (r.yMin * 2f) - 1f, 0.1f)); p.z = -p.z; + float angle = UnityVectorExtensions.SignedAngle(Vector3.forward, p, Vector3.left); + r.yMin = ((fov / 2) + angle) / fov; + + p = persp.MultiplyPoint(new Vector3(0, (r.yMax * 2f) - 1f, 0.1f)); p.z = -p.z; + angle = UnityVectorExtensions.SignedAngle(Vector3.forward, p, Vector3.left); + r.yMax = ((fov / 2) + angle) / fov; + + p = persp.MultiplyPoint(new Vector3((r.xMin * 2f) - 1f, 0, 0.1f)); p.z = -p.z; + angle = UnityVectorExtensions.SignedAngle(Vector3.forward, p, Vector3.up); + r.xMin = ((fovH / 2) + angle) / fovH; + + p = persp.MultiplyPoint(new Vector3((r.xMax * 2f) - 1f, 0, 0.1f)); p.z = -p.z; + angle = UnityVectorExtensions.SignedAngle(Vector3.forward, p, Vector3.up); + r.xMax = ((fovH / 2) + angle) / fovH; + return r; + } + + /// + /// Adjust the rigOrientation to put the camera within the screen bounds. + /// If deltaTime >= 0 then damping will be applied. + /// Assumes that currentOrientation fwd is such that input rigOrientation's + /// local up is NEVER NEVER NEVER pointing downwards, relative to + /// state.ReferenceUp. If this condition is violated + /// then you will see crazy spinning. That's the symptom. + /// + private bool RotateToScreenBounds( + ref CameraState state, Rect screenRect, + ref Quaternion rigOrientation, float fov, float fovH, float deltaTime) + { + Vector3 targetDir = TrackedPoint - state.CorrectedPosition; + Vector2 rotToRect = rigOrientation.GetCameraRotationToTarget(targetDir, state.ReferenceUp); + + // Bring it to the edge of screenRect, if outside. Leave it alone if inside. + ClampVerticalBounds(ref screenRect, targetDir, state.ReferenceUp, fov); + float min = (screenRect.yMin - 0.5f) * fov; + float max = (screenRect.yMax - 0.5f) * fov; + if (rotToRect.x < min) + rotToRect.x -= min; + else if (rotToRect.x > max) + rotToRect.x -= max; + else + rotToRect.x = 0; + + min = (screenRect.xMin - 0.5f) * fovH; + max = (screenRect.xMax - 0.5f) * fovH; + if (rotToRect.y < min) + rotToRect.y -= min; + else if (rotToRect.y > max) + rotToRect.y -= max; + else + rotToRect.y = 0; + + // Apply damping + if (deltaTime >= 0) + { + rotToRect.x = Damper.Damp(rotToRect.x, m_VerticalDamping, deltaTime); + rotToRect.y = Damper.Damp(rotToRect.y, m_HorizontalDamping, deltaTime); + } + + // Rotate + rigOrientation = rigOrientation.ApplyCameraRotation(rotToRect, state.ReferenceUp); +#if false + // GML this gives false positives when the camera is moving. + // The way to address this would be to grow the hard rect by the amount + // that it would be damped + return Mathf.Abs(rotToRect.x) > Epsilon || Mathf.Abs(rotToRect.y) > Epsilon; +#else + return false; +#endif + } + + /// + /// Prevent upside-down camera situation. This can happen if we have a high + /// camera pitch combined with composer settings that cause the camera to tilt + /// beyond the vertical in order to produce the desired framing. We prevent this by + /// clamping the composer's vertical settings so that this situation can't happen. + /// + private bool ClampVerticalBounds(ref Rect r, Vector3 dir, Vector3 up, float fov) + { + float angle = Vector3.Angle(dir, up); + float halfFov = (fov / 2f) + 1; // give it a little extra to accommodate precision errors + if (angle < halfFov) + { + // looking up + float maxY = 1f - (halfFov - angle) / fov; + if (r.yMax > maxY) + { + r.yMin = Mathf.Min(r.yMin, maxY); + r.yMax = Mathf.Min(r.yMax, maxY); + return true; + } + } + if (angle > (180 - halfFov)) + { + // looking down + float minY = (angle - (180 - halfFov)) / fov; + if (minY > r.yMin) + { + r.yMin = Mathf.Max(r.yMin, minY); + r.yMax = Mathf.Max(r.yMax, minY); + return true; + } + } + return false; + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineComposer.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachineComposer.cs.meta new file mode 100644 index 0000000..fa03c76 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineComposer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f4044717213e31446939f7bd49c896ea +timeCreated: 1488314898 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineFramingTransposer.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachineFramingTransposer.cs new file mode 100644 index 0000000..32ca9b3 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineFramingTransposer.cs @@ -0,0 +1,497 @@ +using System; +using Cinemachine.Utility; +using UnityEngine; +using UnityEngine.Serialization; + +namespace Cinemachine +{ + /// + /// This is a Cinemachine Component in the Body section of the component pipeline. + /// Its job is to position the camera in a fixed screen-space relationship to + /// the vcam's Follow target object, with offsets and damping. + /// + /// The camera will be first moved along the camera Z axis until the Follow target + /// is at the desired distance from the camera's X-Y plane. The camera will then + /// be moved in its XY plane until the Follow target is at the desired point on + /// the camera's screen. + /// + /// The FramingTansposer will only change the camera's position in space. It will not + /// re-orient or otherwise aim the camera. + /// + /// For this component to work properly, the vcam's LookAt target must be null. + /// The Follow target will define what the camera is looking at. + /// + /// If the Follow target is a CinemachineTargetGroup, then additional controls will + /// be available to dynamically adjust the camera’s view in order to frame the entire group. + /// + /// Although this component was designed for orthographic cameras, it works equally + /// well with persective cameras and can be used in 3D environments. + /// + [DocumentationSorting(5.5f, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] // for OnGUI + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachineFramingTransposer : CinemachineComponentBase + { + /// Used by the Inspector Editor to display on-screen guides. + [NoSaveDuringPlay, HideInInspector] + public Action OnGUICallback = null; + + /// This setting will instruct the composer to adjust its target offset based + /// on the motion of the target. The composer will look at a point where it estimates + /// the target will be this many seconds into the future. Note that this setting is sensitive + /// to noisy animation, and can amplify the noise, resulting in undesirable camera jitter. + /// If the camera jitters unacceptably when the target is in motion, turn down this setting, + /// or animate the target more smoothly. + [Tooltip("This setting will instruct the composer to adjust its target offset based on the motion of the target. The composer will look at a point where it estimates the target will be this many seconds into the future. Note that this setting is sensitive to noisy animation, and can amplify the noise, resulting in undesirable camera jitter. If the camera jitters unacceptably when the target is in motion, turn down this setting, or animate the target more smoothly.")] + [Range(0f, 1f)] + public float m_LookaheadTime = 0; + + /// Controls the smoothness of the lookahead algorithm. Larger values smooth out + /// jittery predictions and also increase prediction lag + [Tooltip("Controls the smoothness of the lookahead algorithm. Larger values smooth out jittery predictions and also increase prediction lag")] + [Range(3, 30)] + public float m_LookaheadSmoothing = 10; + + /// How aggressively the camera tries to maintain the offset in the X-axis. + /// Small numbers are more responsive, rapidly translating the camera to keep the target's + /// x-axis offset. Larger numbers give a more heavy slowly responding camera. + /// Using different settings per axis can yield a wide range of camera behaviors + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to maintain the offset in the X-axis. Small numbers are more responsive, rapidly translating the camera to keep the target's x-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] + public float m_XDamping = 1f; + + /// How aggressively the camera tries to maintain the offset in the Y-axis. + /// Small numbers are more responsive, rapidly translating the camera to keep the target's + /// y-axis offset. Larger numbers give a more heavy slowly responding camera. + /// Using different settings per axis can yield a wide range of camera behaviors + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to maintain the offset in the Y-axis. Small numbers are more responsive, rapidly translating the camera to keep the target's y-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] + public float m_YDamping = 1f; + + /// How aggressively the camera tries to maintain the offset in the Z-axis. + /// Small numbers are more responsive, rapidly translating the camera to keep the + /// target's z-axis offset. Larger numbers give a more heavy slowly responding camera. + /// Using different settings per axis can yield a wide range of camera behaviors + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to maintain the offset in the Z-axis. Small numbers are more responsive, rapidly translating the camera to keep the target's z-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] + public float m_ZDamping = 1f; + + /// Horizontal screen position for target. The camera will move to position the tracked object here + [Space] + [Range(0f, 1f)] + [Tooltip("Horizontal screen position for target. The camera will move to position the tracked object here.")] + public float m_ScreenX = 0.5f; + + /// Vertical screen position for target, The camera will move to to position the tracked object here + [Range(0f, 1f)] + [Tooltip("Vertical screen position for target, The camera will move to position the tracked object here.")] + public float m_ScreenY = 0.5f; + + /// The distance along the camera axis that will be maintained from the Follow target + [Tooltip("The distance along the camera axis that will be maintained from the Follow target")] + public float m_CameraDistance = 10f; + + /// Camera will not move horizontally if the target is within this range of the position + [Space] + [Range(0f, 1f)] + [Tooltip("Camera will not move horizontally if the target is within this range of the position.")] + public float m_DeadZoneWidth = 0.1f; + + /// Camera will not move vertically if the target is within this range of the position + [Range(0f, 1f)] + [Tooltip("Camera will not move vertically if the target is within this range of the position.")] + public float m_DeadZoneHeight = 0.1f; + + /// The camera will not move along its z-axis if the Follow target is within this distance of the specified camera distance + [Tooltip("The camera will not move along its z-axis if the Follow target is within this distance of the specified camera distance")] + [FormerlySerializedAs("m_DistanceDeadZoneSize")] + public float m_DeadZoneDepth = 0; + + [Space] + /// If checked, then then soft zone will be unlimited in size + [Tooltip("If checked, then then soft zone will be unlimited in size.")] + public bool m_UnlimitedSoftZone = false; + + /// When target is within this region, camera will gradually move to re-align + /// towards the desired position, depending onm the damping speed + [Range(0f, 2f)] + [Tooltip("When target is within this region, camera will gradually move horizontally to re-align towards the desired position, depending on the damping speed.")] + public float m_SoftZoneWidth = 0.8f; + + /// When target is within this region, camera will gradually move to re-align + /// towards the desired position, depending onm the damping speed + [Range(0f, 2f)] + [Tooltip("When target is within this region, camera will gradually move vertically to re-align towards the desired position, depending on the damping speed.")] + public float m_SoftZoneHeight = 0.8f; + + /// A non-zero bias will move the targt position away from the center of the soft zone + [Range(-0.5f, 0.5f)] + [Tooltip("A non-zero bias will move the target position horizontally away from the center of the soft zone.")] + public float m_BiasX = 0f; + + /// A non-zero bias will move the targt position away from the center of the soft zone + [Range(-0.5f, 0.5f)] + [Tooltip("A non-zero bias will move the target position vertically away from the center of the soft zone.")] + public float m_BiasY = 0f; + + /// What screen dimensions to consider when framing + [DocumentationSorting(4.01f, DocumentationSortingAttribute.Level.UserRef)] + public enum FramingMode + { + /// Consider only the horizontal dimension. Vertical framing is ignored. + Horizontal, + /// Consider only the vertical dimension. Horizontal framing is ignored. + Vertical, + /// The larger of the horizontal and vertical dimensions will dominate, to get the best fit. + HorizontalAndVertical, + /// Don't do any framing adjustment + None + }; + + /// What screen dimensions to consider when framing + [Space] + [Tooltip("What screen dimensions to consider when framing. Can be Horizontal, Vertical, or both")] + [FormerlySerializedAs("m_FramingMode")] + public FramingMode m_GroupFramingMode = FramingMode.HorizontalAndVertical; + + /// How to adjust the camera to get the desired framing + public enum AdjustmentMode + { + /// Do not move the camera, only adjust the FOV. + ZoomOnly, + /// Just move the camera, don't change the FOV. + DollyOnly, + /// Move the camera as much as permitted by the ranges, then + /// adjust the FOV if necessary to make the shot. + DollyThenZoom + }; + + /// How to adjust the camera to get the desired framing + [Tooltip("How to adjust the camera to get the desired framing. You can zoom, dolly in/out, or do both.")] + public AdjustmentMode m_AdjustmentMode = AdjustmentMode.DollyThenZoom; + + /// How much of the screen to fill with the bounding box of the targets. + [Tooltip("The bounding box of the targets should occupy this amount of the screen space. 1 means fill the whole screen. 0.5 means fill half the screen, etc.")] + public float m_GroupFramingSize = 0.8f; + + /// How much closer to the target can the camera go? + [Tooltip("The maximum distance toward the target that this behaviour is allowed to move the camera.")] + public float m_MaxDollyIn = 5000f; + + /// How much farther from the target can the camera go? + [Tooltip("The maximum distance away the target that this behaviour is allowed to move the camera.")] + public float m_MaxDollyOut = 5000f; + + /// Set this to limit how close to the target the camera can get + [Tooltip("Set this to limit how close to the target the camera can get.")] + public float m_MinimumDistance = 1; + + /// Set this to limit how far from the taregt the camera can get + [Tooltip("Set this to limit how far from the target the camera can get.")] + public float m_MaximumDistance = 5000f; + + /// If adjusting FOV, will not set the FOV lower than this + [Range(1, 179)] + [Tooltip("If adjusting FOV, will not set the FOV lower than this.")] + public float m_MinimumFOV = 3; + + /// If adjusting FOV, will not set the FOV higher than this + [Range(1, 179)] + [Tooltip("If adjusting FOV, will not set the FOV higher than this.")] + public float m_MaximumFOV = 60; + + /// If adjusting Orthographic Size, will not set it lower than this + [Tooltip("If adjusting Orthographic Size, will not set it lower than this.")] + public float m_MinimumOrthoSize = 1; + + /// If adjusting Orthographic Size, will not set it higher than this + [Tooltip("If adjusting Orthographic Size, will not set it higher than this.")] + public float m_MaximumOrthoSize = 100; + + /// Internal API for the inspector editor + public Rect SoftGuideRect + { + get + { + return new Rect( + m_ScreenX - m_DeadZoneWidth / 2, m_ScreenY - m_DeadZoneHeight / 2, + m_DeadZoneWidth, m_DeadZoneHeight); + } + set + { + m_DeadZoneWidth = Mathf.Clamp01(value.width); + m_DeadZoneHeight = Mathf.Clamp01(value.height); + m_ScreenX = Mathf.Clamp01(value.x + m_DeadZoneWidth / 2); + m_ScreenY = Mathf.Clamp01(value.y + m_DeadZoneHeight / 2); + m_SoftZoneWidth = Mathf.Max(m_SoftZoneWidth, m_DeadZoneWidth); + m_SoftZoneHeight = Mathf.Max(m_SoftZoneHeight, m_DeadZoneHeight); + } + } + + /// Internal API for the inspector editor + public Rect HardGuideRect + { + get + { + Rect r = new Rect( + m_ScreenX - m_SoftZoneWidth / 2, m_ScreenY - m_SoftZoneHeight / 2, + m_SoftZoneWidth, m_SoftZoneHeight); + r.position += new Vector2( + m_BiasX * (m_SoftZoneWidth - m_DeadZoneWidth), + m_BiasY * (m_SoftZoneHeight - m_DeadZoneHeight)); + return r; + } + set + { + m_SoftZoneWidth = Mathf.Clamp(value.width, 0, 2f); + m_SoftZoneHeight = Mathf.Clamp(value.height, 0, 2f); + m_DeadZoneWidth = Mathf.Min(m_DeadZoneWidth, m_SoftZoneWidth); + m_DeadZoneHeight = Mathf.Min(m_DeadZoneHeight, m_SoftZoneHeight); + + Vector2 center = value.center; + Vector2 bias = center - new Vector2(m_ScreenX, m_ScreenY); + float biasWidth = Mathf.Max(0, m_SoftZoneWidth - m_DeadZoneWidth); + float biasHeight = Mathf.Max(0, m_SoftZoneHeight - m_DeadZoneHeight); + m_BiasX = biasWidth < Epsilon ? 0 : Mathf.Clamp(bias.x / biasWidth, -0.5f, 0.5f); + m_BiasY = biasHeight < Epsilon ? 0 : Mathf.Clamp(bias.y / biasHeight, -0.5f, 0.5f); + } + } + + private void OnValidate() + { + m_CameraDistance = Mathf.Max(m_CameraDistance, kMinimumCameraDistance); + m_DeadZoneDepth = Mathf.Max(m_DeadZoneDepth, 0); + + m_GroupFramingSize = Mathf.Max(Epsilon, m_GroupFramingSize); + m_MaxDollyIn = Mathf.Max(0, m_MaxDollyIn); + m_MaxDollyOut = Mathf.Max(0, m_MaxDollyOut); + m_MinimumDistance = Mathf.Max(0, m_MinimumDistance); + m_MaximumDistance = Mathf.Max(m_MinimumDistance, m_MaximumDistance); + m_MinimumFOV = Mathf.Max(1, m_MinimumFOV); + m_MaximumFOV = Mathf.Clamp(m_MaximumFOV, m_MinimumFOV, 179); + m_MinimumOrthoSize = Mathf.Max(0.01f, m_MinimumOrthoSize); + m_MaximumOrthoSize = Mathf.Max(m_MinimumOrthoSize, m_MaximumOrthoSize); + } + +#if UNITY_EDITOR + private void OnGUI() { if (OnGUICallback != null) OnGUICallback(); } +#endif + + /// True if component is enabled and has a valid Follow target + public override bool IsValid { get { return enabled && FollowTarget != null && LookAtTarget == null; } } + + /// Get the Cinemachine Pipeline stage that this component implements. + /// Always returns the Body stage + public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Body; } } + + const float kMinimumCameraDistance = 0.01f; + + /// State information for damping + Vector3 m_PreviousCameraPosition = Vector3.zero; + PositionPredictor m_Predictor = new PositionPredictor(); + + /// Internal API for inspector + public Vector3 TrackedPoint { get; private set; } + + /// Positions the virtual camera according to the transposer rules. + /// The current camera state + /// Used for damping. If less than 0, no damping is done. + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + if (deltaTime < 0) + { + m_Predictor.Reset(); + m_PreviousCameraPosition = curState.RawPosition + + (curState.RawOrientation * Vector3.back) * m_CameraDistance; + } + if (!IsValid) + return; + + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFramingTransposer.MutateCameraState"); + Vector3 camPosWorld = m_PreviousCameraPosition; + curState.ReferenceLookAt = FollowTarget.position; + m_Predictor.Smoothing = m_LookaheadSmoothing; + m_Predictor.AddPosition(curState.ReferenceLookAt); + TrackedPoint = (m_LookaheadTime > 0) + ? m_Predictor.PredictPosition(m_LookaheadTime) : curState.ReferenceLookAt; + + // Work in camera-local space + Quaternion localToWorld = curState.RawOrientation; + Quaternion worldToLocal = Quaternion.Inverse(localToWorld); + Vector3 cameraPos = worldToLocal * camPosWorld; + Vector3 targetPos = (worldToLocal * TrackedPoint) - cameraPos; + + // Move along camera z + Vector3 cameraOffset = Vector3.zero; + float cameraMin = Mathf.Max(kMinimumCameraDistance, m_CameraDistance - m_DeadZoneDepth/2); + float cameraMax = Mathf.Max(cameraMin, m_CameraDistance + m_DeadZoneDepth/2); + if (targetPos.z < cameraMin) + cameraOffset.z = targetPos.z - cameraMin; + if (targetPos.z > cameraMax) + cameraOffset.z = targetPos.z - cameraMax; + + // Adjust for group framing + CinemachineTargetGroup group = TargetGroup; + if (group != null && m_GroupFramingMode != FramingMode.None) + cameraOffset.z += AdjustCameraDepthAndLensForGroupFraming( + group, targetPos.z - cameraOffset.z, ref curState, deltaTime); + + // Move along the XY plane + targetPos.z -= cameraOffset.z; + float screenSize = curState.Lens.Orthographic + ? curState.Lens.OrthographicSize + : Mathf.Tan(0.5f * curState.Lens.FieldOfView * Mathf.Deg2Rad) * targetPos.z; + Rect softGuideOrtho = ScreenToOrtho(SoftGuideRect, screenSize, curState.Lens.Aspect); + if (deltaTime < 0) + { + // No damping or hard bounds, just snap to central bounds, skipping the soft zone + Rect rect = new Rect(softGuideOrtho.center, Vector2.zero); // Force to center + cameraOffset += OrthoOffsetToScreenBounds(targetPos, rect); + } + else + { + // Move it through the soft zone + cameraOffset += OrthoOffsetToScreenBounds(targetPos, softGuideOrtho); + + // Find where it intersects the hard zone + Vector3 hard = Vector3.zero; + if (!m_UnlimitedSoftZone) + { + Rect hardGuideOrtho = ScreenToOrtho(HardGuideRect, screenSize, curState.Lens.Aspect); + hard = OrthoOffsetToScreenBounds(targetPos, hardGuideOrtho); + float t = Mathf.Max(hard.x / (cameraOffset.x + Epsilon), hard.y / (cameraOffset.y + Epsilon)); + hard = cameraOffset * t; + } + // Apply damping, but only to the portion of the move that's inside the hard zone + cameraOffset = hard + Damper.Damp( + cameraOffset - hard, new Vector3(m_XDamping, m_YDamping, m_ZDamping), deltaTime); + } + curState.RawPosition = m_PreviousCameraPosition = localToWorld * (cameraPos + cameraOffset); + //UnityEngine.Profiling.Profiler.EndSample(); + } + + // Convert from screen coords to normalized orthographic distance coords + private Rect ScreenToOrtho(Rect rScreen, float orthoSize, float aspect) + { + Rect r = new Rect(); + r.yMax = 2 * orthoSize * ((1f-rScreen.yMin) - 0.5f); + r.yMin = 2 * orthoSize * ((1f-rScreen.yMax) - 0.5f); + r.xMin = 2 * orthoSize * aspect * (rScreen.xMin - 0.5f); + r.xMax = 2 * orthoSize * aspect * (rScreen.xMax - 0.5f); + return r; + } + + private Vector3 OrthoOffsetToScreenBounds(Vector3 targetPos2D, Rect screenRect) + { + // Bring it to the edge of screenRect, if outside. Leave it alone if inside. + Vector3 delta = Vector3.zero; + if (targetPos2D.x < screenRect.xMin) + delta.x += targetPos2D.x - screenRect.xMin; + if (targetPos2D.x > screenRect.xMax) + delta.x += targetPos2D.x - screenRect.xMax; + if (targetPos2D.y < screenRect.yMin) + delta.y += targetPos2D.y - screenRect.yMin; + if (targetPos2D.y > screenRect.yMax) + delta.y += targetPos2D.y - screenRect.yMax; + return delta; + } + + float m_prevTargetHeight; // State for frame damping + + /// For editor visulaization of the calculated bounding box of the group + public Bounds m_LastBounds { get; private set; } + + /// For editor visualization of the calculated bounding box of the group + public Matrix4x4 m_lastBoundsMatrix { get; private set; } + + /// Get Follow target as CinemachineTargetGroup, or null if target is not a group + public CinemachineTargetGroup TargetGroup + { + get + { + Transform follow = FollowTarget; + if (follow != null) + return follow.GetComponent(); + return null; + } + } + + float AdjustCameraDepthAndLensForGroupFraming( + CinemachineTargetGroup group, float targetZ, + ref CameraState curState, float deltaTime) + { + float cameraOffset = 0; + + // Get the bounding box from that POV in view space, and find its height + Bounds bounds = group.BoundingBox; + Vector3 fwd = curState.RawOrientation * Vector3.forward; + m_lastBoundsMatrix = Matrix4x4.TRS( + bounds.center - (fwd * bounds.extents.magnitude), + curState.RawOrientation, Vector3.one); + m_LastBounds = group.GetViewSpaceBoundingBox(m_lastBoundsMatrix); + float targetHeight = GetTargetHeight(m_LastBounds); + + // Apply damping + if (deltaTime >= 0) + { + float delta = targetHeight - m_prevTargetHeight; + delta = Damper.Damp(delta, m_ZDamping, deltaTime); + targetHeight = m_prevTargetHeight + delta; + } + m_prevTargetHeight = targetHeight; + + // Move the camera + if (!curState.Lens.Orthographic && m_AdjustmentMode != AdjustmentMode.ZoomOnly) + { + // What distance would be needed to get the target height, at the current FOV + float desiredDistance + = targetHeight / (2f * Mathf.Tan(curState.Lens.FieldOfView * Mathf.Deg2Rad / 2f)); + + // target the near surface of the bounding box + desiredDistance += m_LastBounds.extents.z; + + // Clamp to respect min/max distance settings + desiredDistance = Mathf.Clamp( + desiredDistance, targetZ - m_MaxDollyIn, targetZ + m_MaxDollyOut); + desiredDistance = Mathf.Clamp(desiredDistance, m_MinimumDistance, m_MaximumDistance); + + // Apply + cameraOffset += desiredDistance - targetZ; + } + + // Apply zoom + if (curState.Lens.Orthographic || m_AdjustmentMode != AdjustmentMode.DollyOnly) + { + float nearBoundsDistance = (targetZ + cameraOffset) - m_LastBounds.extents.z; + float currentFOV = 179; + if (nearBoundsDistance > Epsilon) + currentFOV = 2f * Mathf.Atan(targetHeight / (2 * nearBoundsDistance)) * Mathf.Rad2Deg; + + LensSettings lens = curState.Lens; + lens.FieldOfView = Mathf.Clamp(currentFOV, m_MinimumFOV, m_MaximumFOV); + lens.OrthographicSize = Mathf.Clamp(targetHeight / 2, m_MinimumOrthoSize, m_MaximumOrthoSize); + curState.Lens = lens; + } + return -cameraOffset; + } + + float GetTargetHeight(Bounds b) + { + float framingSize = Mathf.Max(Epsilon, m_GroupFramingSize); + switch (m_GroupFramingMode) + { + case FramingMode.Horizontal: + return b.size.x / (framingSize * VcamState.Lens.Aspect); + case FramingMode.Vertical: + return b.size.y / framingSize; + default: + case FramingMode.HorizontalAndVertical: + return Mathf.Max( + b.size.x / (framingSize * VcamState.Lens.Aspect), + b.size.y / framingSize); + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineFramingTransposer.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachineFramingTransposer.cs.meta new file mode 100644 index 0000000..c3713e2 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineFramingTransposer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6ad980451443d70438faac0bc6c235a0 +timeCreated: 1502038595 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineGroupComposer.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachineGroupComposer.cs new file mode 100644 index 0000000..fc59a4a --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineGroupComposer.cs @@ -0,0 +1,237 @@ +using UnityEngine; +using Cinemachine.Utility; + +namespace Cinemachine +{ + /// + /// This is a CinemachineComponent in the Aim section of the component pipeline. + /// Its job is to aim the camera at a target object, with configurable offsets, damping, + /// and composition rules. + /// + /// In addition, if the target is a CinemachineTargetGroup, the behaviour + /// will adjust the FOV and the camera distance to ensure that the entire group of targets + /// is framed properly. + /// + [DocumentationSorting(4, DocumentationSortingAttribute.Level.UserRef)] + [ExecuteInEditMode] // for OnGUI + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachineGroupComposer : CinemachineComposer + { + /// How much of the screen to fill with the bounding box of the targets. + [Space] + [Tooltip("The bounding box of the targets should occupy this amount of the screen space. 1 means fill the whole screen. 0.5 means fill half the screen, etc.")] + public float m_GroupFramingSize = 0.8f; + + /// What screen dimensions to consider when framing + [DocumentationSorting(4.01f, DocumentationSortingAttribute.Level.UserRef)] + public enum FramingMode + { + /// Consider only the horizontal dimension. Vertical framing is ignored. + Horizontal, + /// Consider only the vertical dimension. Horizontal framing is ignored. + Vertical, + /// The larger of the horizontal and vertical dimensions will dominate, to get the best fit. + HorizontalAndVertical + }; + + /// What screen dimensions to consider when framing + [Tooltip("What screen dimensions to consider when framing. Can be Horizontal, Vertical, or both")] + public FramingMode m_FramingMode = FramingMode.HorizontalAndVertical; + + /// How aggressively the camera tries to frame the group. + /// Small numbers are more responsive + [Range(0, 20)] + [Tooltip("How aggressively the camera tries to frame the group. Small numbers are more responsive, rapidly adjusting the camera to keep the group in the frame. Larger numbers give a more heavy slowly responding camera.")] + public float m_FrameDamping = 2f; + + /// How to adjust the camera to get the desired framing + public enum AdjustmentMode + { + /// Do not move the camera, only adjust the FOV. + ZoomOnly, + /// Just move the camera, don't change the FOV. + DollyOnly, + /// Move the camera as much as permitted by the ranges, then + /// adjust the FOV if necessary to make the shot. + DollyThenZoom + }; + + /// How to adjust the camera to get the desired framing + [Tooltip("How to adjust the camera to get the desired framing. You can zoom, dolly in/out, or do both.")] + public AdjustmentMode m_AdjustmentMode = AdjustmentMode.DollyThenZoom; + + /// How much closer to the target can the camera go? + [Tooltip("The maximum distance toward the target that this behaviour is allowed to move the camera.")] + public float m_MaxDollyIn = 5000f; + + /// How much farther from the target can the camera go? + [Tooltip("The maximum distance away the target that this behaviour is allowed to move the camera.")] + public float m_MaxDollyOut = 5000f; + + /// Set this to limit how close to the target the camera can get + [Tooltip("Set this to limit how close to the target the camera can get.")] + public float m_MinimumDistance = 1; + + /// Set this to limit how far from the taregt the camera can get + [Tooltip("Set this to limit how far from the target the camera can get.")] + public float m_MaximumDistance = 5000f; + + /// If adjusting FOV, will not set the FOV lower than this + [Range(1, 179)] + [Tooltip("If adjusting FOV, will not set the FOV lower than this.")] + public float m_MinimumFOV = 3; + + /// If adjusting FOV, will not set the FOV higher than this + [Range(1, 179)] + [Tooltip("If adjusting FOV, will not set the FOV higher than this.")] + public float m_MaximumFOV = 60; + + /// If adjusting Orthographic Size, will not set it lower than this + [Tooltip("If adjusting Orthographic Size, will not set it lower than this.")] + public float m_MinimumOrthoSize = 1; + + /// If adjusting Orthographic Size, will not set it higher than this + [Tooltip("If adjusting Orthographic Size, will not set it higher than this.")] + public float m_MaximumOrthoSize = 100; + + private void OnValidate() + { + m_GroupFramingSize = Mathf.Max(Epsilon, m_GroupFramingSize); + m_MaxDollyIn = Mathf.Max(0, m_MaxDollyIn); + m_MaxDollyOut = Mathf.Max(0, m_MaxDollyOut); + m_MinimumDistance = Mathf.Max(0, m_MinimumDistance); + m_MaximumDistance = Mathf.Max(m_MinimumDistance, m_MaximumDistance); + m_MinimumFOV = Mathf.Max(1, m_MinimumFOV); + m_MaximumFOV = Mathf.Clamp(m_MaximumFOV, m_MinimumFOV, 179); + m_MinimumOrthoSize = Mathf.Max(0.01f, m_MinimumOrthoSize); + m_MaximumOrthoSize = Mathf.Max(m_MinimumOrthoSize, m_MaximumOrthoSize); + } + + /// Get LookAt target as CinemachineTargetGroup, or null if target is not a group + public CinemachineTargetGroup TargetGroup + { + get + { + Transform lookAt = LookAtTarget; + if (lookAt != null) + return lookAt.GetComponent(); + return null; + } + } + + /// Applies the composer rules and orients the camera accordingly + /// The current camera state + /// Used for calculating damping. If less than + /// zero, then target will snap to the center of the dead zone. + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + // Can't do anything without a group to look at + CinemachineTargetGroup group = TargetGroup; + if (group == null) + { + base.MutateCameraState(ref curState, deltaTime); + return; + } + + if (!IsValid || !curState.HasLookAt) + { + m_prevTargetHeight = 0; + return; + } + + curState.ReferenceLookAt = GetLookAtPointAndSetTrackedPoint(group.transform.position); + Vector3 currentOffset = TrackedPoint - curState.RawPosition; + float currentDistance = currentOffset.magnitude; + if (currentDistance < Epsilon) + return; // navel-gazing, get outa here + + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineGroupComposer.MutateCameraState"); + + // Get the camera axis + Vector3 fwd = currentOffset.AlmostZero() ? Vector3.forward : currentOffset.normalized; + + // Get the bounding box from that POV in view space, and find its width + Bounds bounds = group.BoundingBox; + m_lastBoundsMatrix = Matrix4x4.TRS( + bounds.center - (fwd * bounds.extents.magnitude), + Quaternion.LookRotation(fwd, curState.ReferenceUp), Vector3.one); + m_LastBounds = group.GetViewSpaceBoundingBox(m_lastBoundsMatrix); + float targetHeight = GetTargetHeight(m_LastBounds); + Vector3 targetPos = m_lastBoundsMatrix.MultiplyPoint3x4(m_LastBounds.center); + + // Apply damping + if (deltaTime >= 0) + { + float delta = targetHeight - m_prevTargetHeight; + delta = Damper.Damp(delta, m_FrameDamping, deltaTime); + targetHeight = m_prevTargetHeight + delta; + } + m_prevTargetHeight = targetHeight; + + // Move the camera + if (!curState.Lens.Orthographic && m_AdjustmentMode != AdjustmentMode.ZoomOnly) + { + // What distance would be needed to get the target height, at the current FOV + float currentFOV = curState.Lens.FieldOfView; + float targetDistance = targetHeight / (2f * Mathf.Tan(currentFOV * Mathf.Deg2Rad / 2f)); + + // target the near surface of the bounding box + float cameraDistance = targetDistance + m_LastBounds.extents.z; + + // Clamp to respect min/max distance settings + cameraDistance = Mathf.Clamp( + cameraDistance, currentDistance - m_MaxDollyIn, currentDistance + m_MaxDollyOut); + cameraDistance = Mathf.Clamp(cameraDistance, m_MinimumDistance, m_MaximumDistance); + + // Apply + curState.PositionCorrection += targetPos - fwd * cameraDistance - curState.RawPosition; + } + + // Apply zoom + if (curState.Lens.Orthographic || m_AdjustmentMode != AdjustmentMode.DollyOnly) + { + float nearBoundsDistance = (TrackedPoint - curState.CorrectedPosition).magnitude + - m_LastBounds.extents.z; + float currentFOV = 179; + if (nearBoundsDistance > Epsilon) + currentFOV = 2f * Mathf.Atan(targetHeight / (2 * nearBoundsDistance)) * Mathf.Rad2Deg; + + LensSettings lens = curState.Lens; + lens.FieldOfView = Mathf.Clamp(currentFOV, m_MinimumFOV, m_MaximumFOV); + lens.OrthographicSize = Mathf.Clamp(targetHeight / 2, m_MinimumOrthoSize, m_MaximumOrthoSize); + curState.Lens = lens; + } + + // Now compose normally + base.MutateCameraState(ref curState, deltaTime); + //UnityEngine.Profiling.Profiler.EndSample(); + } + + float m_prevTargetHeight; // State for damping + + /// For editor visulaization of the calculated bounding box of the group + public Bounds m_LastBounds { get; private set; } + + /// For editor visualization of the calculated bounding box of the group + public Matrix4x4 m_lastBoundsMatrix { get; private set; } + + float GetTargetHeight(Bounds b) + { + float framingSize = Mathf.Max(Epsilon, m_GroupFramingSize); + switch (m_FramingMode) + { + case FramingMode.Horizontal: + return Mathf.Max(Epsilon, b.size.x )/ (framingSize * VcamState.Lens.Aspect); + case FramingMode.Vertical: + return Mathf.Max(Epsilon, b.size.y) / framingSize; + default: + case FramingMode.HorizontalAndVertical: + return Mathf.Max( + Mathf.Max(Epsilon, b.size.x) / (framingSize * VcamState.Lens.Aspect), + Mathf.Max(Epsilon, b.size.y) / framingSize); + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineGroupComposer.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachineGroupComposer.cs.meta new file mode 100644 index 0000000..e0738cd --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineGroupComposer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0f7633c93f0364a418841eeb8b058634 +timeCreated: 1496696780 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLockToTarget.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLockToTarget.cs new file mode 100644 index 0000000..e53ed32 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLockToTarget.cs @@ -0,0 +1,33 @@ +using UnityEngine; + +namespace Cinemachine +{ + /// + /// This is a CinemachineComponent in the Aim section of the component pipeline. + /// Its job is to place the camera on the Follow Target. + /// + [DocumentationSorting(23, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachineHardLockToTarget : CinemachineComponentBase + { + /// True if component is enabled and has a LookAt defined + public override bool IsValid { get { return enabled && FollowTarget != null; } } + + /// Get the Cinemachine Pipeline stage that this component implements. + /// Always returns the Aim stage + public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Body; } } + + /// Applies the composer rules and orients the camera accordingly + /// The current camera state + /// Used for calculating damping. If less than + /// zero, then target will snap to the center of the dead zone. + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + if (IsValid) + curState.RawPosition = FollowTarget.position; + } + } +} + diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLockToTarget.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLockToTarget.cs.meta new file mode 100644 index 0000000..da28d51 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLockToTarget.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 36d1163fa822e8b418a0a603ec078d5c +timeCreated: 1506531396 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLookAt.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLookAt.cs new file mode 100644 index 0000000..dfb3855 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLookAt.cs @@ -0,0 +1,42 @@ +using UnityEngine; + +namespace Cinemachine +{ + /// + /// This is a CinemachineComponent in the Aim section of the component pipeline. + /// Its job is to aim the camera hard at the LookAt target. + /// + [DocumentationSorting(23, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachineHardLookAt : CinemachineComponentBase + { + /// True if component is enabled and has a LookAt defined + public override bool IsValid { get { return enabled && LookAtTarget != null; } } + + /// Get the Cinemachine Pipeline stage that this component implements. + /// Always returns the Aim stage + public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Aim; } } + + /// Applies the composer rules and orients the camera accordingly + /// The current camera state + /// Used for calculating damping. If less than + /// zero, then target will snap to the center of the dead zone. + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + if (IsValid && curState.HasLookAt) + { + Vector3 dir = (curState.ReferenceLookAt - curState.CorrectedPosition); + if (dir.magnitude > Epsilon) + { + if (Vector3.Cross(dir.normalized, curState.ReferenceUp).magnitude < Epsilon) + curState.RawOrientation = Quaternion.FromToRotation(Vector3.forward, dir); + else + curState.RawOrientation = Quaternion.LookRotation(dir, curState.ReferenceUp); + } + } + } + } +} + diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLookAt.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLookAt.cs.meta new file mode 100644 index 0000000..6330854 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineHardLookAt.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 1e8b78ac948f05a46a6d8339a503172b +timeCreated: 1506531396 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineOrbitalTransposer.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachineOrbitalTransposer.cs new file mode 100644 index 0000000..b0363d4 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineOrbitalTransposer.cs @@ -0,0 +1,530 @@ +using System; +using UnityEngine; +using Cinemachine.Utility; +using UnityEngine.Serialization; + +namespace Cinemachine +{ + /// + /// This is a CinemachineComponent in the the Body section of the component pipeline. + /// Its job is to position the camera in a variable relationship to a the vcam's + /// Follow target object, with offsets and damping. + /// + /// This component is typically used to implement a camera that follows its target. + /// It can accept player input from an input device, which allows the player to + /// dynamically control the relationship between the camera and the target, + /// for example with a joystick. + /// + /// The OrbitalTransposer introduces the concept of __Heading__, which is the direction + /// in which the target is moving, and the OrbitalTransposer will attempt to position + /// the camera in relationship to the heading, which is by default directly behind the target. + /// You can control the default relationship by adjusting the Heading Bias setting. + /// + /// If you attach an input controller to the OrbitalTransposer, then the player can also + /// control the way the camera positions itself in relation to the target heading. This allows + /// the camera to move to any spot on an orbit around the target. + /// + [DocumentationSorting(6, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachineOrbitalTransposer : CinemachineTransposer + { + /// + /// How the "forward" direction is defined. Orbital offset is in relation to the forward + /// direction. + /// + [DocumentationSorting(6.2f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public struct Heading + { + /// + /// Sets the algorithm for determining the target's heading for purposes + /// of re-centering the camera + /// + [DocumentationSorting(6.21f, DocumentationSortingAttribute.Level.UserRef)] + public enum HeadingDefinition + { + /// + /// Target heading calculated from the difference between its position on + /// the last update and current frame. + /// + PositionDelta, + /// + /// Target heading calculated from its Rigidbody's velocity. + /// If no Rigidbody exists, it will fall back + /// to HeadingDerivationMode.PositionDelta + /// + Velocity, + /// + /// Target heading calculated from the Target Transform's euler Y angle + /// + TargetForward, + /// + /// Default heading is a constant world space heading. + /// + WorldForward, + } + /// The method by which the 'default heading' is calculated if + /// recentering to target heading is enabled + [Tooltip("How 'forward' is defined. The camera will be placed by default behind the target. PositionDelta will consider 'forward' to be the direction in which the target is moving.")] + public HeadingDefinition m_HeadingDefinition; + + /// Size of the velocity sampling window for target heading filter. + /// Used only if deriving heading from target's movement + [Range(0, 10)] + [Tooltip("Size of the velocity sampling window for target heading filter. This filters out irregularities in the target's movement. Used only if deriving heading from target's movement (PositionDelta or Velocity)")] + public int m_VelocityFilterStrength; + + /// Additional Y rotation applied to the target heading. + /// When this value is 0, the camera will be placed behind the target + [Range(-180f, 180f)] + [Tooltip("Where the camera is placed when the X-axis value is zero. This is a rotation in degrees around the Y axis. When this value is 0, the camera will be placed behind the target. Nonzero offsets will rotate the zero position around the target.")] + public float m_HeadingBias; + + /// Constructor + public Heading(HeadingDefinition def, int filterStrength, float bias) + { + m_HeadingDefinition = def; + m_VelocityFilterStrength = filterStrength; + m_HeadingBias = bias; + } + }; + + /// The definition of Forward. Camera will follow behind. + [Space] + [Tooltip("The definition of Forward. Camera will follow behind.")] + public Heading m_Heading = new Heading(Heading.HeadingDefinition.TargetForward, 4, 0); + + /// Controls how automatic orbit recentering occurs + [DocumentationSorting(6.5f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public struct Recentering + { + /// If checked, will enable automatic recentering of the + /// camera based on the heading calculation mode. If FALSE, recenting is disabled. + [Tooltip("If checked, will enable automatic recentering of the camera based on the heading definition. If unchecked, recenting is disabled.")] + public bool m_enabled; + + /// If no input has been detected, the camera will wait + /// this long in seconds before moving its heading to the default heading. + [Tooltip("If no input has been detected, the camera will wait this long in seconds before moving its heading to the zero position.")] + public float m_RecenterWaitTime; + + /// Maximum angular speed of recentering. Will accelerate into and decelerate out of this + [Tooltip("Maximum angular speed of recentering. Will accelerate into and decelerate out of this.")] + public float m_RecenteringTime; + + /// Constructor with specific field values + public Recentering(bool enabled, float recenterWaitTime, float recenteringSpeed) + { + m_enabled = enabled; + m_RecenterWaitTime = recenterWaitTime; + m_RecenteringTime = recenteringSpeed; + m_LegacyHeadingDefinition = m_LegacyVelocityFilterStrength = -1; + } + + /// Call this from OnValidate() + public void Validate() + { + m_RecenterWaitTime = Mathf.Max(0, m_RecenterWaitTime); + m_RecenteringTime = Mathf.Max(0, m_RecenteringTime); + } + + // Legacy support + [SerializeField] [HideInInspector] [FormerlySerializedAs("m_HeadingDefinition")] private int m_LegacyHeadingDefinition; + [SerializeField] [HideInInspector] [FormerlySerializedAs("m_VelocityFilterStrength")] private int m_LegacyVelocityFilterStrength; + internal bool LegacyUpgrade(ref Heading.HeadingDefinition heading, ref int velocityFilter) + { + if (m_LegacyHeadingDefinition != -1 && m_LegacyVelocityFilterStrength != -1) + { + heading = (Heading.HeadingDefinition)m_LegacyHeadingDefinition; + velocityFilter = m_LegacyVelocityFilterStrength; + m_LegacyHeadingDefinition = m_LegacyVelocityFilterStrength = -1; + return true; + } + return false; + } + }; + + /// Parameters that control Automating Heading Recentering + [Tooltip("Automatic heading recentering. The settings here defines how the camera will reposition itself in the absence of player input.")] + public Recentering m_RecenterToTargetHeading = new Recentering(true, 1, 2); + + /// Axis representing the current heading. Value is in degrees + /// and represents a rotation about the up vector + [Tooltip("Heading Control. The settings here control the behaviour of the camera in response to the player's input.")] + public AxisState m_XAxis = new AxisState(300f, 2f, 1f, 0f, "Mouse X", true); + + // Legacy support + [SerializeField] [HideInInspector] [FormerlySerializedAs("m_Radius")] private float m_LegacyRadius = float.MaxValue; + [SerializeField] [HideInInspector] [FormerlySerializedAs("m_HeightOffset")] private float m_LegacyHeightOffset = float.MaxValue; + [SerializeField] [HideInInspector] [FormerlySerializedAs("m_HeadingBias")] private float m_LegacyHeadingBias = float.MaxValue; + protected override void OnValidate() + { + // Upgrade after a legacy deserialize + if (m_LegacyRadius != float.MaxValue + && m_LegacyHeightOffset != float.MaxValue + && m_LegacyHeadingBias != float.MaxValue) + { + m_FollowOffset = new Vector3(0, m_LegacyHeightOffset, -m_LegacyRadius); + m_LegacyHeightOffset = m_LegacyRadius = float.MaxValue; + + m_Heading.m_HeadingBias = m_LegacyHeadingBias; + m_XAxis.m_MaxSpeed /= 10; + m_XAxis.m_AccelTime /= 10; + m_XAxis.m_DecelTime /= 10; + m_LegacyHeadingBias = float.MaxValue; + m_RecenterToTargetHeading.LegacyUpgrade( + ref m_Heading.m_HeadingDefinition, ref m_Heading.m_VelocityFilterStrength); + } + m_XAxis.Validate(); + m_RecenterToTargetHeading.Validate(); + + base.OnValidate(); + } + + /// + /// Drive the x-axis setting programmatically. + /// Automatic heading updating will be disabled. + /// + [HideInInspector, NoSaveDuringPlay] + public bool m_HeadingIsSlave = false; + + /// + /// Delegate that allows the the m_XAxis object to be replaced with another one. + /// + internal delegate float UpdateHeadingDelegate( + CinemachineOrbitalTransposer orbital, float deltaTime, Vector3 up); + + /// + /// Delegate that allows the the XAxis object to be replaced with another one. + /// To use it, just call orbital.UpdateHeading() with a reference to a + /// private AxisState object, and that AxisState object will be updated and + /// used to calculate the heading. + /// + internal UpdateHeadingDelegate HeadingUpdater + = (CinemachineOrbitalTransposer orbital, float deltaTime, Vector3 up) + => { return orbital.UpdateHeading(deltaTime, up, ref orbital.m_XAxis); }; + + /// + /// Update the X axis and calculate the heading. This can be called by a delegate + /// with a custom axis. + /// Used for damping. If less than 0, no damping is done. + /// World Up, set by the CinemachineBrain + /// + /// Axis value + /// + public float UpdateHeading(float deltaTime, Vector3 up, ref AxisState axis) + { + // Only read joystick when game is playing + if (deltaTime >= 0 || CinemachineCore.Instance.IsLive(VirtualCamera)) + { + bool xAxisInput = false; + xAxisInput |= axis.Update(deltaTime); + if (xAxisInput) + { + mLastHeadingAxisInputTime = Time.time; + mHeadingRecenteringVelocity = 0; + } + } + float targetHeading = GetTargetHeading(axis.Value, GetReferenceOrientation(up), deltaTime); + if (deltaTime < 0) + { + mHeadingRecenteringVelocity = 0; + if (m_RecenterToTargetHeading.m_enabled) + axis.Value = targetHeading; + } + else + { + // Recentering + if (m_BindingMode != BindingMode.SimpleFollowWithWorldUp + && m_RecenterToTargetHeading.m_enabled + && (Time.time > (mLastHeadingAxisInputTime + m_RecenterToTargetHeading.m_RecenterWaitTime))) + { + // Scale value determined heuristically, to account for accel/decel + float recenterTime = m_RecenterToTargetHeading.m_RecenteringTime / 3f; + if (recenterTime <= deltaTime) + axis.Value = targetHeading; + else + { + float headingError = Mathf.DeltaAngle(axis.Value, targetHeading); + float absHeadingError = Mathf.Abs(headingError); + if (absHeadingError < UnityVectorExtensions.Epsilon) + { + axis.Value = targetHeading; + mHeadingRecenteringVelocity = 0; + } + else + { + float scale = deltaTime / recenterTime; + float desiredVelocity = Mathf.Sign(headingError) + * Mathf.Min(absHeadingError, absHeadingError * scale); + // Accelerate to the desired velocity + float accel = desiredVelocity - mHeadingRecenteringVelocity; + if ((desiredVelocity < 0 && accel < 0) || (desiredVelocity > 0 && accel > 0)) + desiredVelocity = mHeadingRecenteringVelocity + desiredVelocity * scale; + axis.Value += desiredVelocity; + mHeadingRecenteringVelocity = desiredVelocity; + } + } + } + } + float finalHeading = axis.Value; + if (m_BindingMode == BindingMode.SimpleFollowWithWorldUp) + axis.Value = 0; + return finalHeading; + } + + private void OnEnable() + { + m_XAxis.SetThresholds(0f, 360f, true); + PreviousTarget = null; + mLastTargetPosition = Vector3.zero; + } + + private float mLastHeadingAxisInputTime = 0f; + private float mHeadingRecenteringVelocity = 0f; + private Vector3 mLastTargetPosition = Vector3.zero; + private HeadingTracker mHeadingTracker; + private Rigidbody mTargetRigidBody = null; + private Transform PreviousTarget { get; set; } + private Quaternion mHeadingPrevFrame = Quaternion.identity; + private Vector3 mOffsetPrevFrame = Vector3.zero; + + /// Positions the virtual camera according to the transposer rules. + /// The current camera state + /// Used for damping. If less than 0, no damping is done. + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineOrbitalTransposer.MutateCameraState"); + InitPrevFrameStateInfo(ref curState, deltaTime); + + // Update the heading + if (FollowTarget != PreviousTarget) + { + PreviousTarget = FollowTarget; + mTargetRigidBody = (PreviousTarget == null) ? null : PreviousTarget.GetComponent(); + mLastTargetPosition = (PreviousTarget == null) ? Vector3.zero : PreviousTarget.position; + mHeadingTracker = null; + } + float heading = HeadingUpdater(this, deltaTime, curState.ReferenceUp); + + if (IsValid) + { + mLastTargetPosition = FollowTarget.position; + + // Calculate the heading + if (m_BindingMode != BindingMode.SimpleFollowWithWorldUp) + heading += m_Heading.m_HeadingBias; + Quaternion headingRot = Quaternion.AngleAxis(heading, curState.ReferenceUp); + + // Track the target, with damping + Vector3 offset = EffectiveOffset; + Vector3 pos; + Quaternion orient; + TrackTarget(deltaTime, curState.ReferenceUp, headingRot * offset, out pos, out orient); + + // Place the camera + curState.ReferenceUp = orient * Vector3.up; + if (deltaTime >= 0) + { + Vector3 bypass = (headingRot * offset) - mHeadingPrevFrame * mOffsetPrevFrame; + bypass = orient * bypass; + curState.PositionDampingBypass = bypass; + } + orient = orient * headingRot; + curState.RawPosition = pos + orient * offset; + + mHeadingPrevFrame = (m_BindingMode == BindingMode.SimpleFollowWithWorldUp) ? Quaternion.identity : headingRot; + mOffsetPrevFrame = offset; + } + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// API for the editor, to process a position drag from the user. + /// This implementation adds the delta to the follow offset, after zeroing out local x. + /// The amount dragged this frame + public override void OnPositionDragged(Vector3 delta) + { + Quaternion targetOrientation = GetReferenceOrientation(VcamState.ReferenceUp); + Vector3 localOffset = Quaternion.Inverse(targetOrientation) * delta; + localOffset.x = 0; + m_FollowOffset += localOffset; + m_FollowOffset = EffectiveOffset; + } + + static string GetFullName(GameObject current) + { + if (current == null) + return ""; + if (current.transform.parent == null) + return "/" + current.name; + return GetFullName(current.transform.parent.gameObject) + "/" + current.name; + } + + // Make sure this is calld only once per frame + private float GetTargetHeading( + float currentHeading, Quaternion targetOrientation, float deltaTime) + { + if (m_BindingMode == BindingMode.SimpleFollowWithWorldUp) + return 0; + if (FollowTarget == null) + return currentHeading; + + if (m_Heading.m_HeadingDefinition == Heading.HeadingDefinition.Velocity + && mTargetRigidBody == null) + { + Debug.Log(string.Format( + "Attempted to use HeadingDerivationMode.Velocity to calculate heading for {0}. No RigidBody was present on '{1}'. Defaulting to position delta", + GetFullName(VirtualCamera.VirtualCameraGameObject), FollowTarget)); + m_Heading.m_HeadingDefinition = Heading.HeadingDefinition.PositionDelta; + } + + Vector3 velocity = Vector3.zero; + switch (m_Heading.m_HeadingDefinition) + { + case Heading.HeadingDefinition.PositionDelta: + velocity = FollowTarget.position - mLastTargetPosition; + break; + case Heading.HeadingDefinition.Velocity: + velocity = mTargetRigidBody.velocity; + break; + case Heading.HeadingDefinition.TargetForward: + velocity = FollowTarget.forward; + break; + default: + case Heading.HeadingDefinition.WorldForward: + return 0; + } + + // Process the velocity and derive the heading from it. + int filterSize = m_Heading.m_VelocityFilterStrength * 5; + if (mHeadingTracker == null || mHeadingTracker.FilterSize != filterSize) + mHeadingTracker = new HeadingTracker(filterSize); + mHeadingTracker.DecayHistory(); + Vector3 up = targetOrientation * Vector3.up; + velocity = velocity.ProjectOntoPlane(up); + if (!velocity.AlmostZero()) + mHeadingTracker.Add(velocity); + + velocity = mHeadingTracker.GetReliableHeading(); + if (!velocity.AlmostZero()) + return UnityVectorExtensions.SignedAngle(targetOrientation * Vector3.forward, velocity, up); + + // If no reliable heading, then stay where we are. + return currentHeading; + } + + class HeadingTracker + { + struct Item + { + public Vector3 velocity; + public float weight; + public float time; + }; + Item[] mHistory; + int mTop; + int mBottom; + int mCount; + + Vector3 mHeadingSum; + float mWeightSum = 0; + float mWeightTime = 0; + + Vector3 mLastGoodHeading = Vector3.zero; + + public HeadingTracker(int filterSize) + { + mHistory = new Item[filterSize]; + float historyHalfLife = filterSize / 5f; // somewhat arbitrarily + mDecayExponent = -Mathf.Log(2f) / historyHalfLife; + ClearHistory(); + } + + public int FilterSize { get { return mHistory.Length; } } + + void ClearHistory() + { + mTop = mBottom = mCount = 0; + mWeightSum = 0; + mHeadingSum = Vector3.zero; + } + + static float mDecayExponent; + static float Decay(float time) { return Mathf.Exp(time * mDecayExponent); } + + public void Add(Vector3 velocity) + { + if (FilterSize == 0) + { + mLastGoodHeading = velocity; + return; + } + float weight = velocity.magnitude; + if (weight > UnityVectorExtensions.Epsilon) + { + Item item = new Item(); + item.velocity = velocity; + item.weight = weight; + item.time = Time.time; + if (mCount == FilterSize) + PopBottom(); + ++mCount; + mHistory[mTop] = item; + if (++mTop == FilterSize) + mTop = 0; + + mWeightSum *= Decay(item.time - mWeightTime); + mWeightTime = item.time; + mWeightSum += weight; + mHeadingSum += item.velocity; + } + } + + void PopBottom() + { + if (mCount > 0) + { + float time = Time.time; + Item item = mHistory[mBottom]; + if (++mBottom == FilterSize) + mBottom = 0; + --mCount; + + float decay = Decay(time - item.time); + mWeightSum -= item.weight * decay; + mHeadingSum -= item.velocity * decay; + if (mWeightSum <= UnityVectorExtensions.Epsilon || mCount == 0) + ClearHistory(); + } + } + + public void DecayHistory() + { + float time = Time.time; + float decay = Decay(time - mWeightTime); + mWeightSum *= decay; + mWeightTime = time; + if (mWeightSum < UnityVectorExtensions.Epsilon) + ClearHistory(); + else + mHeadingSum = mHeadingSum * decay; + } + + public Vector3 GetReliableHeading() + { + // Update Last Good Heading + if (mWeightSum > UnityVectorExtensions.Epsilon + && (mCount == mHistory.Length || mLastGoodHeading.AlmostZero())) + { + Vector3 h = mHeadingSum / mWeightSum; + if (!h.AlmostZero()) + mLastGoodHeading = h.normalized; + } + return mLastGoodHeading; + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineOrbitalTransposer.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachineOrbitalTransposer.cs.meta new file mode 100644 index 0000000..69fc527 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineOrbitalTransposer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9384ab8608cdc3d479fe89cd51eed48f +timeCreated: 1485281954 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachinePOV.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachinePOV.cs new file mode 100644 index 0000000..ebd357d --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachinePOV.cs @@ -0,0 +1,70 @@ +using UnityEngine; + +namespace Cinemachine +{ + /// + /// This is a CinemachineComponent in the Aim section of the component pipeline. + /// Its job is to aim the camera in response to the user's mouse or joystick input. + /// + /// The composer does not change the camera's position. It will only pan and tilt the + /// camera where it is, in order to get the desired framing. To move the camera, you have + /// to use the virtual camera's Body section. + /// + [DocumentationSorting(23, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachinePOV : CinemachineComponentBase + { + /// The Vertical axis. Value is -90..90. Controls the vertical orientation + [Tooltip("The Vertical axis. Value is -90..90. Controls the vertical orientation")] + public AxisState m_VerticalAxis = new AxisState(300f, 0.1f, 0.1f, 0f, "Mouse Y", true); + + /// The Horizontal axis. Value is -180..180. Controls the horizontal orientation + [Tooltip("The Horizontal axis. Value is -180..180. Controls the horizontal orientation")] + public AxisState m_HorizontalAxis = new AxisState(300f, 0.1f, 0.1f, 0f, "Mouse X", false); + + /// True if component is enabled and has a LookAt defined + public override bool IsValid { get { return enabled; } } + + /// Get the Cinemachine Pipeline stage that this component implements. + /// Always returns the Aim stage + public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Aim; } } + + private void OnValidate() + { + m_HorizontalAxis.Validate(); + m_VerticalAxis.Validate(); + } + + private void OnEnable() + { + m_HorizontalAxis.SetThresholds(-180f, 180f, true); + m_VerticalAxis.SetThresholds(-90, 90, false); + } + + /// Applies the axis values and orients the camera accordingly + /// The current camera state + /// Used for calculating damping. Not used. + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + if (!IsValid) + return; + + //UnityEngine.Profiling.Profiler.BeginSample("CinemachinePOV.MutateCameraState"); + + // Only read joystick when game is playing + if (deltaTime >= 0 || CinemachineCore.Instance.IsLive(VirtualCamera)) + { + m_HorizontalAxis.Update(deltaTime); + m_VerticalAxis.Update(deltaTime); + } + Quaternion rot = Quaternion.Euler(m_VerticalAxis.Value, m_HorizontalAxis.Value, 0); + rot = rot * Quaternion.FromToRotation(Vector3.up, curState.ReferenceUp); + curState.OrientationCorrection = curState.OrientationCorrection * rot; + + //UnityEngine.Profiling.Profiler.EndSample(); + } + } +} + diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachinePOV.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachinePOV.cs.meta new file mode 100644 index 0000000..e673e0e --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachinePOV.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3c9beda531928fc40968802117a5d256 +timeCreated: 1504204894 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineSameAsFollowObject.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachineSameAsFollowObject.cs new file mode 100644 index 0000000..9d1e410 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineSameAsFollowObject.cs @@ -0,0 +1,33 @@ +using UnityEngine; + +namespace Cinemachine +{ + /// + /// This is a CinemachineComponent in the Aim section of the component pipeline. + /// Its job is to aim the camera hard at the LookAt target. + /// + [DocumentationSorting(27, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachineSameAsFollowObject : CinemachineComponentBase + { + /// True if component is enabled and has a Follow target defined + public override bool IsValid { get { return enabled && FollowTarget != null; } } + + /// Get the Cinemachine Pipeline stage that this component implements. + /// Always returns the Aim stage + public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Aim; } } + + /// Applies the composer rules and orients the camera accordingly + /// The current camera state + /// Used for calculating damping. If less than + /// zero, then target will snap to the center of the dead zone. + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + if (IsValid) + curState.RawOrientation = FollowTarget.transform.rotation; + } + } +} + diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineSameAsFollowObject.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachineSameAsFollowObject.cs.meta new file mode 100644 index 0000000..2309dcd --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineSameAsFollowObject.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a4c41ac9245b87c4192012080077d830 +timeCreated: 1511551300 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineTrackedDolly.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachineTrackedDolly.cs new file mode 100644 index 0000000..3ce9b14 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineTrackedDolly.cs @@ -0,0 +1,312 @@ +using UnityEngine; +using System; +using Cinemachine.Utility; +using UnityEngine.Serialization; + +namespace Cinemachine +{ + /// + /// A Cinemachine Virtual Camera Body component that constrains camera motion + /// to a CinemachinePath. The camera can move along the path. + /// + /// This behaviour can operate in two modes: manual positioning, and Auto-Dolly positioning. + /// In Manual mode, the camera's position is specified by animating the Path Position field. + /// In Auto-Dolly mode, the Path Position field is animated automatically every frame by finding + /// the position on the path that's closest to the virtual camera's Follow target. + /// + [DocumentationSorting(7, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachineTrackedDolly : CinemachineComponentBase + { + /// The path to which the camera will be constrained. This must be non-null. + [Tooltip("The path to which the camera will be constrained. This must be non-null.")] + public CinemachinePathBase m_Path; + + /// The position along the path at which the camera will be placed. + /// This can be animated directly, or set automatically by the Auto-Dolly feature + /// to get as close as possible to the Follow target. + [Tooltip("The position along the path at which the camera will be placed. This can be animated directly, or set automatically by the Auto-Dolly feature to get as close as possible to the Follow target. The value is interpreted according to the Position Units setting.")] + public float m_PathPosition; + + /// How to interpret the Path Position + [Tooltip("How to interpret 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.PathUnits; + + /// Where to put the camera realtive to the path postion. X is perpendicular to the path, Y is up, and Z is parallel to the path. + [Tooltip("Where to put the camera relative to the path position. X is perpendicular to the path, Y is up, and Z is parallel to the path. This allows the camera to be offset from the path itself (as if on a tripod, for example).")] + public Vector3 m_PathOffset = Vector3.zero; + + /// How aggressively the camera tries to maintain the offset perpendicular to the path. + /// Small numbers are more responsive, rapidly translating the camera to keep the target's + /// x-axis offset. Larger numbers give a more heavy slowly responding camera. + /// Using different settings per axis can yield a wide range of camera behaviors + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to maintain its position in a direction perpendicular to the path. Small numbers are more responsive, rapidly translating the camera to keep the target's x-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] + public float m_XDamping = 0f; + + /// How aggressively the camera tries to maintain the offset in the path-local up direction. + /// Small numbers are more responsive, rapidly translating the camera to keep the target's + /// y-axis offset. Larger numbers give a more heavy slowly responding camera. + /// Using different settings per axis can yield a wide range of camera behaviors + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to maintain its position in the path-local up direction. Small numbers are more responsive, rapidly translating the camera to keep the target's y-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] + public float m_YDamping = 0f; + + /// How aggressively the camera tries to maintain the offset parallel to the path. + /// Small numbers are more responsive, rapidly translating the camera to keep the + /// target's z-axis offset. Larger numbers give a more heavy slowly responding camera. + /// Using different settings per axis can yield a wide range of camera behaviors + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to maintain its position in a direction parallel to the path. Small numbers are more responsive, rapidly translating the camera to keep the target's z-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] + public float m_ZDamping = 1f; + + /// Different ways to set the camera's up vector + [DocumentationSorting(7.1f, DocumentationSortingAttribute.Level.UserRef)] + public enum CameraUpMode + { + /// Leave the camera's up vector alone. It will be set according to the Brain's WorldUp. + Default, + /// Take the up vector from the path's up vector at the current point + Path, + /// Take the up vector from the path's up vector at the current point, but with the roll zeroed out + PathNoRoll, + /// Take the up vector from the Follow target's up vector + FollowTarget, + /// Take the up vector from the Follow target's up vector, but with the roll zeroed out + FollowTargetNoRoll, + }; + + /// How to set the virtual camera's Up vector. This will affect the screen composition. + [Tooltip("How to set the virtual camera's Up vector. This will affect the screen composition, because the camera Aim behaviours will always try to respect the Up direction.")] + public CameraUpMode m_CameraUp = CameraUpMode.Default; + + /// "How aggressively the camera tries to track the target rotation's X angle. + /// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera. + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to track the target rotation's X angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")] + public float m_PitchDamping = 0; + + /// How aggressively the camera tries to track the target rotation's Y angle. + /// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera. + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to track the target rotation's Y angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")] + public float m_YawDamping = 0; + + /// How aggressively the camera tries to track the target rotation's Z angle. + /// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera. + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to track the target rotation's Z angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")] + public float m_RollDamping = 0f; + + /// Controls how automatic dollying occurs + [DocumentationSorting(7.2f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public struct AutoDolly + { + /// If checked, will enable automatic dolly, which chooses a path position + /// that is as close as possible to the Follow target. + [Tooltip("If checked, will enable automatic dolly, which chooses a path position that is as close as possible to the Follow target. Note: this can have significant performance impact")] + public bool m_Enabled; + + /// Offset, in current position units, from the closest point on the path to the follow target. + [Tooltip("Offset, in current position units, from the closest point on the path to the follow target")] + public float m_PositionOffset; + + /// Search up to how many waypoints on either side of the current position. Use 0 for Entire path + [Tooltip("Search up to how many waypoints on either side of the current position. Use 0 for Entire path.")] + public int m_SearchRadius; + + /// We search between waypoints by dividing the segment into this many straight pieces. + /// The higher the number, the more accurate the result, but performance is + /// proportionally slower for higher numbers + [FormerlySerializedAs("m_StepsPerSegment")] + [Tooltip("We search between waypoints by dividing the segment into this many straight pieces. The higher the number, the more accurate the result, but performance is proportionally slower for higher numbers")] + public int m_SearchResolution; + + /// Constructor with specific field values + public AutoDolly(bool enabled, float positionOffset, int searchRadius, int stepsPerSegment) + { + m_Enabled = enabled; + m_PositionOffset = positionOffset; + m_SearchRadius = searchRadius; + m_SearchResolution = stepsPerSegment; + } + }; + + /// Controls how automatic dollying occurs + [Tooltip("Controls how automatic dollying occurs. A Follow target is necessary to use this feature.")] + public AutoDolly m_AutoDolly = new AutoDolly(false, 0, 2, 5); + + /// True if component is enabled and has a path + public override bool IsValid { get { return enabled && m_Path != null; } } + + /// Get the Cinemachine Pipeline stage that this component implements. + /// Always returns the Body stage + public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Body; } } + + /// Positions the virtual camera according to the transposer rules. + /// The current camera state + /// Used for damping. If less that 0, no damping is done. + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + // Init previous frame state info + if (deltaTime < 0) + { + m_PreviousPathPosition = m_PathPosition; + m_PreviousCameraPosition = curState.RawPosition; + } + + if (!IsValid) + return; + + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineTrackedDolly.MutateCameraState"); + // Get the new ideal path base position + if (m_AutoDolly.m_Enabled && FollowTarget != null) + { + float prevPos = m_PreviousPathPosition; + if (m_PositionUnits == CinemachinePathBase.PositionUnits.Distance) + prevPos = m_Path.GetPathPositionFromDistance(prevPos); + // This works in path units + m_PathPosition = m_Path.FindClosestPoint( + FollowTarget.transform.position, + Mathf.FloorToInt(prevPos), + (deltaTime < 0 || m_AutoDolly.m_SearchRadius <= 0) + ? -1 : m_AutoDolly.m_SearchRadius, + m_AutoDolly.m_SearchResolution); + if (m_PositionUnits == CinemachinePathBase.PositionUnits.Distance) + m_PathPosition = m_Path.GetPathDistanceFromPosition(m_PathPosition); + + // Apply the path position offset + m_PathPosition += m_AutoDolly.m_PositionOffset; + } + float newPathPosition = m_PathPosition; + + if (deltaTime >= 0) + { + // Normalize previous position to find the shortest path + float maxUnit = m_Path.MaxUnit(m_PositionUnits); + if (maxUnit > 0) + { + float prev = m_Path.NormalizeUnit(m_PreviousPathPosition, m_PositionUnits); + float next = m_Path.NormalizeUnit(newPathPosition, m_PositionUnits); + if (m_Path.Looped && Mathf.Abs(next - prev) > maxUnit / 2) + { + if (next > prev) + prev += maxUnit; + else + prev -= maxUnit; + } + m_PreviousPathPosition = prev; + newPathPosition = next; + } + + // Apply damping along the path direction + float offset = m_PreviousPathPosition - newPathPosition; + offset = Damper.Damp(offset, m_ZDamping, deltaTime); + newPathPosition = m_PreviousPathPosition - offset; + } + m_PreviousPathPosition = newPathPosition; + Quaternion newPathOrientation = m_Path.EvaluateOrientationAtUnit(newPathPosition, m_PositionUnits); + + // Apply the offset to get the new camera position + Vector3 newCameraPos = m_Path.EvaluatePositionAtUnit(newPathPosition, m_PositionUnits); + Vector3 offsetX = newPathOrientation * Vector3.right; + Vector3 offsetY = newPathOrientation * Vector3.up; + Vector3 offsetZ = newPathOrientation * Vector3.forward; + newCameraPos += m_PathOffset.x * offsetX; + newCameraPos += m_PathOffset.y * offsetY; + newCameraPos += m_PathOffset.z * offsetZ; + + // Apply damping to the remaining directions + if (deltaTime >= 0) + { + Vector3 currentCameraPos = m_PreviousCameraPosition; + Vector3 delta = (currentCameraPos - newCameraPos); + Vector3 delta1 = Vector3.Dot(delta, offsetY) * offsetY; + Vector3 delta0 = delta - delta1; + delta0 = Damper.Damp(delta0, m_XDamping, deltaTime); + delta1 = Damper.Damp(delta1, m_YDamping, deltaTime); + newCameraPos = currentCameraPos - (delta0 + delta1); + } + curState.RawPosition = m_PreviousCameraPosition = newCameraPos; + + // Set the orientation and up + Quaternion newOrientation + = GetTargetOrientationAtPathPoint(newPathOrientation, curState.ReferenceUp); + if (deltaTime < 0) + m_PreviousOrientation = newOrientation; + else + { + if (deltaTime >= 0) + { + Vector3 relative = (Quaternion.Inverse(m_PreviousOrientation) + * newOrientation).eulerAngles; + for (int i = 0; i < 3; ++i) + if (relative[i] > 180) + relative[i] -= 360; + relative = Damper.Damp(relative, AngularDamping, deltaTime); + newOrientation = m_PreviousOrientation * Quaternion.Euler(relative); + } + m_PreviousOrientation = newOrientation; + } + + curState.RawOrientation = newOrientation; + curState.ReferenceUp = curState.RawOrientation * Vector3.up; + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// API for the editor, to process a position drag from the user. + /// This implementation adds the delta to the follow offset. + /// The amount dragged this frame + public override void OnPositionDragged(Vector3 delta) + { + Quaternion targetOrientation = m_Path.EvaluateOrientationAtUnit(m_PathPosition, m_PositionUnits); + Vector3 localOffset = Quaternion.Inverse(targetOrientation) * delta; + m_PathOffset += localOffset; + } + + private Quaternion GetTargetOrientationAtPathPoint(Quaternion pathOrientation, Vector3 up) + { + switch (m_CameraUp) + { + default: + case CameraUpMode.Default: break; + case CameraUpMode.Path: return pathOrientation; + case CameraUpMode.PathNoRoll: + return Quaternion.LookRotation(pathOrientation * Vector3.forward, up); + case CameraUpMode.FollowTarget: + if (FollowTarget != null) + return FollowTarget.rotation; + break; + case CameraUpMode.FollowTargetNoRoll: + if (FollowTarget != null) + return Quaternion.LookRotation(FollowTarget.rotation * Vector3.forward, up); + break; + } + return Quaternion.LookRotation(transform.rotation * Vector3.forward, up); + } + + private Vector3 AngularDamping + { + get + { + switch (m_CameraUp) + { + case CameraUpMode.PathNoRoll: + case CameraUpMode.FollowTargetNoRoll: + return new Vector3(m_PitchDamping, m_YawDamping, 0); + case CameraUpMode.Default: + return Vector3.zero; + default: + return new Vector3(m_PitchDamping, m_YawDamping, m_RollDamping); + } + } + } + + private float m_PreviousPathPosition = 0; + Quaternion m_PreviousOrientation = Quaternion.identity; + private Vector3 m_PreviousCameraPosition = Vector3.zero; + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineTrackedDolly.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachineTrackedDolly.cs.meta new file mode 100644 index 0000000..da09029 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineTrackedDolly.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 418e42c7d0405cc48a7b83f63ea53bb3 +timeCreated: 1493213884 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineTransposer.cs b/Assets/Cinemachine/Base/Runtime/Components/CinemachineTransposer.cs new file mode 100644 index 0000000..9537d58 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineTransposer.cs @@ -0,0 +1,310 @@ +using Cinemachine.Utility; +using UnityEngine; + +namespace Cinemachine +{ + /// + /// This is a CinemachineComponent in the Body section of the component pipeline. + /// Its job is to position the camera in a fixed relationship to the vcam's Follow + /// target object, with offsets and damping. + /// + /// The Tansposer will only change the camera's position in space. It will not + /// re-orient or otherwise aim the camera. To to that, you need to instruct + /// the vcam in the Aim section of its pipeline. + /// + [DocumentationSorting(5, DocumentationSortingAttribute.Level.UserRef)] + [AddComponentMenu("")] // Don't display in add component menu + [RequireComponent(typeof(CinemachinePipeline))] + [SaveDuringPlay] + public class CinemachineTransposer : CinemachineComponentBase + { + /// + /// The coordinate space to use when interpreting the offset from the target + /// + [DocumentationSorting(5.01f, DocumentationSortingAttribute.Level.UserRef)] + public enum BindingMode + { + /// + /// Camera will be bound to the Follow target using a frame of reference consisting + /// of the target's local frame at the moment when the virtual camera was enabled, + /// or when the target was assigned. + /// + LockToTargetOnAssign = 0, + /// + /// Camera will be bound to the Follow target using a frame of reference consisting + /// of the target's local frame, with the tilt and roll zeroed out. + /// + LockToTargetWithWorldUp = 1, + /// + /// Camera will be bound to the Follow target using a frame of reference consisting + /// of the target's local frame, with the roll zeroed out. + /// + LockToTargetNoRoll = 2, + /// + /// Camera will be bound to the Follow target using the target's local frame. + /// + LockToTarget = 3, + /// Camera will be bound to the Follow target using a world space offset. + WorldSpace = 4, + /// Offsets will be calculated relative to the target, using Camera-local axes + SimpleFollowWithWorldUp = 5 + } + /// The coordinate space to use when interpreting the offset from the target + [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 BindingMode m_BindingMode = BindingMode.LockToTargetWithWorldUp; + + /// The distance which the transposer will attempt to maintain from the transposer subject + [Tooltip("The distance vector that the transposer will attempt to maintain from the Follow target")] + public Vector3 m_FollowOffset = Vector3.back * 10f; + + /// How aggressively the camera tries to maintain the offset in the X-axis. + /// Small numbers are more responsive, rapidly translating the camera to keep the target's + /// x-axis offset. Larger numbers give a more heavy slowly responding camera. + /// Using different settings per axis can yield a wide range of camera behaviors + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to maintain the offset in the X-axis. Small numbers are more responsive, rapidly translating the camera to keep the target's x-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] + public float m_XDamping = 1f; + + /// How aggressively the camera tries to maintain the offset in the Y-axis. + /// Small numbers are more responsive, rapidly translating the camera to keep the target's + /// y-axis offset. Larger numbers give a more heavy slowly responding camera. + /// Using different settings per axis can yield a wide range of camera behaviors + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to maintain the offset in the Y-axis. Small numbers are more responsive, rapidly translating the camera to keep the target's y-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] + public float m_YDamping = 1f; + + /// How aggressively the camera tries to maintain the offset in the Z-axis. + /// Small numbers are more responsive, rapidly translating the camera to keep the + /// target's z-axis offset. Larger numbers give a more heavy slowly responding camera. + /// Using different settings per axis can yield a wide range of camera behaviors + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to maintain the offset in the Z-axis. Small numbers are more responsive, rapidly translating the camera to keep the target's z-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] + public float m_ZDamping = 1f; + + /// How aggressively the camera tries to track the target rotation's X angle. + /// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera. + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to track the target rotation's X angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")] + public float m_PitchDamping = 0; + + /// How aggressively the camera tries to track the target rotation's Y angle. + /// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera. + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to track the target rotation's Y angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")] + public float m_YawDamping = 0; + + /// How aggressively the camera tries to track the target rotation's Z angle. + /// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera. + [Range(0f, 20f)] + [Tooltip("How aggressively the camera tries to track the target rotation's Z angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")] + public float m_RollDamping = 0f; + + protected virtual void OnValidate() + { + m_FollowOffset = EffectiveOffset; + } + + /// Get the target offset, with sanitization + protected Vector3 EffectiveOffset + { + get + { + Vector3 offset = m_FollowOffset; + if (m_BindingMode == BindingMode.SimpleFollowWithWorldUp) + { + offset.x = 0; + offset.z = -Mathf.Abs(offset.z); + } + return offset; + } + } + + /// True if component is enabled and has a valid Follow target + public override bool IsValid { get { return enabled && FollowTarget != null; } } + + /// Get the Cinemachine Pipeline stage that this component implements. + /// Always returns the Body stage + public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Body; } } + + /// Positions the virtual camera according to the transposer rules. + /// The current camera state + /// Used for damping. If less than 0, no damping is done. + public override void MutateCameraState(ref CameraState curState, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineTransposer.MutateCameraState"); + InitPrevFrameStateInfo(ref curState, deltaTime); + if (IsValid) + { + Vector3 pos; + Quaternion orient; + Vector3 offset = EffectiveOffset; + TrackTarget(deltaTime, curState.ReferenceUp, offset, out pos, out orient); + curState.RawPosition = pos + orient * offset; + curState.ReferenceUp = orient * Vector3.up; + } + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// API for the editor, to process a position drag from the user. + /// This implementation adds the delta to the follow offset. + /// The amount dragged this frame + public override void OnPositionDragged(Vector3 delta) + { + Quaternion targetOrientation = GetReferenceOrientation(VcamState.ReferenceUp); + Vector3 localOffset = Quaternion.Inverse(targetOrientation) * delta; + m_FollowOffset += localOffset; + m_FollowOffset = EffectiveOffset; + } + + /// Initializes the state for previous frame if appropriate. + protected void InitPrevFrameStateInfo( + ref CameraState curState, float deltaTime) + { + if (m_previousTarget != FollowTarget || deltaTime < 0) + { + m_previousTarget = FollowTarget; + m_targetOrientationOnAssign + = (m_previousTarget == null) ? Quaternion.identity : FollowTarget.rotation; + } + if (deltaTime < 0) + { + m_PreviousTargetPosition = curState.RawPosition; + m_PreviousReferenceOrientation = GetReferenceOrientation(curState.ReferenceUp); + } + } + + /// Positions the virtual camera according to the transposer rules. + /// Used for damping. If less than 0, no damping is done. + /// Current camera up + /// Where we want to put the camera relative to the follow target + /// Resulting camera position + /// Damped target orientation + protected void TrackTarget( + float deltaTime, Vector3 up, Vector3 desiredCameraOffset, + out Vector3 outTargetPosition, out Quaternion outTargetOrient) + { + Quaternion targetOrientation = GetReferenceOrientation(up); + Quaternion dampedOrientation = targetOrientation; + if (deltaTime >= 0) + { + Vector3 relative = (Quaternion.Inverse(m_PreviousReferenceOrientation) + * targetOrientation).eulerAngles; + for (int i = 0; i < 3; ++i) + if (relative[i] > 180) + relative[i] -= 360; + relative = Damper.Damp(relative, AngularDamping, deltaTime); + dampedOrientation = m_PreviousReferenceOrientation * Quaternion.Euler(relative); + } + m_PreviousReferenceOrientation = dampedOrientation; + + Vector3 targetPosition = FollowTarget.position; + Vector3 currentPosition = m_PreviousTargetPosition; + Vector3 worldOffset = targetPosition - currentPosition; + + // Adjust for damping, which is done in camera-offset-local coords + if (deltaTime >= 0) + { + Quaternion dampingSpace; + if (desiredCameraOffset.AlmostZero()) + dampingSpace = VcamState.RawOrientation; + else + dampingSpace = Quaternion.LookRotation(dampedOrientation * desiredCameraOffset.normalized, up); + Vector3 localOffset = Quaternion.Inverse(dampingSpace) * worldOffset; + localOffset = Damper.Damp(localOffset, Damping, deltaTime); + worldOffset = dampingSpace * localOffset; + } + outTargetPosition = m_PreviousTargetPosition = currentPosition + worldOffset; + outTargetOrient = dampedOrientation; + } + + /// + /// Damping speeds for each of the 3 axes of the offset from target + /// + protected Vector3 Damping + { + get + { + switch (m_BindingMode) + { + case BindingMode.SimpleFollowWithWorldUp: + return new Vector3(0, m_YDamping, m_ZDamping); + default: + return new Vector3(m_XDamping, m_YDamping, m_ZDamping); + } + } + } + + /// + /// Damping speeds for each of the 3 axes of the target's rotation + /// + protected Vector3 AngularDamping + { + get + { + switch (m_BindingMode) + { + case BindingMode.LockToTargetNoRoll: + return new Vector3(m_PitchDamping, m_YawDamping, 0); + case BindingMode.LockToTargetWithWorldUp: + return new Vector3(0, m_YawDamping, 0); + case BindingMode.LockToTargetOnAssign: + case BindingMode.WorldSpace: + case BindingMode.SimpleFollowWithWorldUp: + return Vector3.zero; + default: + return new Vector3(m_PitchDamping, m_YawDamping, m_RollDamping); + } + } + } + + /// Internal API for the Inspector Editor, so it can draw a marker at the target + public Vector3 GeTargetCameraPosition(Vector3 worldUp) + { + if (!IsValid) + return Vector3.zero; + return FollowTarget.position + GetReferenceOrientation(worldUp) * EffectiveOffset; + } + + /// State information for damping + Vector3 m_PreviousTargetPosition = Vector3.zero; + Quaternion m_PreviousReferenceOrientation = Quaternion.identity; + Quaternion m_targetOrientationOnAssign = Quaternion.identity; + Transform m_previousTarget = null; + + /// Internal API for the Inspector Editor, so it can draw a marker at the target + public Quaternion GetReferenceOrientation(Vector3 worldUp) + { + if (FollowTarget != null) + { + Quaternion targetOrientation = FollowTarget.rotation; + switch (m_BindingMode) + { + case BindingMode.LockToTargetOnAssign: + return m_targetOrientationOnAssign; + case BindingMode.LockToTargetWithWorldUp: + return Uppify(targetOrientation, worldUp); + case BindingMode.LockToTargetNoRoll: + return Quaternion.LookRotation(targetOrientation * Vector3.forward, worldUp); + case BindingMode.LockToTarget: + return targetOrientation; + case BindingMode.SimpleFollowWithWorldUp: + { + Vector3 dir = FollowTarget.position - VcamState.RawPosition; + if (dir.AlmostZero()) + break; + return Uppify(Quaternion.LookRotation(dir, worldUp), worldUp); + } + default: + break; + } + } + return Quaternion.identity; + } + + static Quaternion Uppify(Quaternion q, Vector3 up) + { + Quaternion r = Quaternion.FromToRotation(q * Vector3.up, up); + return r * q; + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Components/CinemachineTransposer.cs.meta b/Assets/Cinemachine/Base/Runtime/Components/CinemachineTransposer.cs.meta new file mode 100644 index 0000000..e2e0701 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Components/CinemachineTransposer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fa7155796051b734daa718462081dc5f +timeCreated: 1484001119 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core.meta b/Assets/Cinemachine/Base/Runtime/Core.meta new file mode 100644 index 0000000..c34b8d1 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 3d53800f587b60a4191877d7713cd17c +folderAsset: yes +timeCreated: 1489096338 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/AxisState.cs b/Assets/Cinemachine/Base/Runtime/Core/AxisState.cs new file mode 100644 index 0000000..bad769f --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/AxisState.cs @@ -0,0 +1,200 @@ +using UnityEngine; +using System; +using Cinemachine.Utility; +using UnityEngine.Serialization; + +namespace Cinemachine +{ + /// + /// Axis state for defining to react to player input. + /// The settings here control the responsiveness of the axis to player input. + /// + [DocumentationSorting(6.4f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public struct AxisState + { + /// The current value of the axis + [NoSaveDuringPlay] + [Tooltip("The current value of the axis.")] + public float Value; + + /// How fast the axis value can travel. Increasing this number + /// makes the behaviour more responsive to joystick input + [Tooltip("The maximum speed of this axis in units/second")] + public float m_MaxSpeed; + + /// The amount of time in seconds it takes to accelerate to + /// MaxSpeed with the supplied Axis at its maximum value + [Tooltip("The amount of time in seconds it takes to accelerate to MaxSpeed with the supplied Axis at its maximum value")] + public float m_AccelTime; + + /// The amount of time in seconds it takes to decelerate + /// the axis to zero if the supplied axis is in a neutral position + [Tooltip("The amount of time in seconds it takes to decelerate the axis to zero if the supplied axis is in a neutral position")] + public float m_DecelTime; + + /// The name of this axis as specified in Unity Input manager. + /// Setting to an empty string will disable the automatic updating of this axis + [FormerlySerializedAs("m_AxisName")] + [Tooltip("The name of this axis as specified in Unity Input manager. Setting to an empty string will disable the automatic updating of this axis")] + public string m_InputAxisName; + + /// The value of the input axis. A value of 0 means no input + /// You can drive this directly from a + /// custom input system, or you can set the Axis Name and have the value + /// driven by the internal Input Manager + [NoSaveDuringPlay] + [Tooltip("The value of the input axis. A value of 0 means no input. You can drive this directly from a custom input system, or you can set the Axis Name and have the value driven by the internal Input Manager")] + public float m_InputAxisValue; + + /// If checked, then the raw value of the input axis will be inverted + /// before it is used. + [NoSaveDuringPlay] + [Tooltip("If checked, then the raw value of the input axis will be inverted before it is used")] + public bool m_InvertAxis; + + private float mCurrentSpeed; + private float mMinValue; + private float mMaxValue; + private bool mWrapAround; + + /// Constructor with specific values + public AxisState( + float maxSpeed, float accelTime, float decelTime, float val, string name, bool invert) + { + m_MaxSpeed = maxSpeed; + m_AccelTime = accelTime; + m_DecelTime = decelTime; + Value = val; + m_InputAxisName = name; + m_InputAxisValue = 0; + m_InvertAxis = invert; + + mCurrentSpeed = 0f; + mMinValue = 0f; + mMaxValue = 0f; + mWrapAround = false; + } + + /// Call from OnValidate: Make sure the fields are sensible + public void Validate() + { + m_MaxSpeed = Mathf.Max(0, m_MaxSpeed); + m_AccelTime = Mathf.Max(0, m_AccelTime); + m_DecelTime = Mathf.Max(0, m_DecelTime); + } + + /// + /// Sets the constraints by which this axis will operate on + /// + /// The lowest value this axis can achieve + /// The highest value this axis can achieve + /// If true, values commanded greater + /// than mMaxValue or less than mMinValue will wrap around. + /// If false, the value will be clamped within the range. + public void SetThresholds(float minValue, float maxValue, bool wrapAround) + { + mMinValue = minValue; + mMaxValue = maxValue; + mWrapAround = wrapAround; + } + + const float Epsilon = UnityVectorExtensions.Epsilon; + + /// + /// Updates the state of this axis based on the axis defined + /// by AxisState.m_AxisName + /// + /// Delta time in seconds + /// Returns true if this axis' input was non-zero this Update, + /// flase otherwise + public bool Update(float deltaTime) + { + if (!string.IsNullOrEmpty(m_InputAxisName)) + { + try + { + m_InputAxisValue = CinemachineCore.GetInputAxis(m_InputAxisName); + } + catch (ArgumentException e) + { + Debug.LogError(e.ToString()); + } + } + + float input = m_InputAxisValue; + if (m_InvertAxis) + input *= -1f; + + if (m_MaxSpeed > Epsilon) + { + float targetSpeed = input * m_MaxSpeed; + if (Mathf.Abs(targetSpeed) < Epsilon + || (Mathf.Sign(mCurrentSpeed) == Mathf.Sign(targetSpeed) + && Mathf.Abs(targetSpeed) < Mathf.Abs(mCurrentSpeed))) + { + // Need to decelerate + float a = Mathf.Abs(targetSpeed - mCurrentSpeed) / Mathf.Max(Epsilon, m_DecelTime); + float delta = Mathf.Min(a * deltaTime, Mathf.Abs(mCurrentSpeed)); + mCurrentSpeed -= Mathf.Sign(mCurrentSpeed) * delta; + } + else + { + // Accelerate to the target speed + float a = Mathf.Abs(targetSpeed - mCurrentSpeed) / Mathf.Max(Epsilon, m_AccelTime); + mCurrentSpeed += Mathf.Sign(targetSpeed) * a * deltaTime; + if (Mathf.Sign(mCurrentSpeed) == Mathf.Sign(targetSpeed) + && Mathf.Abs(mCurrentSpeed) > Mathf.Abs(targetSpeed)) + { + mCurrentSpeed = targetSpeed; + } + } + } + + // Clamp our max speeds so we don't go crazy + float maxSpeed = GetMaxSpeed(); + mCurrentSpeed = Mathf.Clamp(mCurrentSpeed, -maxSpeed, maxSpeed); + + Value += mCurrentSpeed * deltaTime; + bool isOutOfRange = (Value > mMaxValue) || (Value < mMinValue); + if (isOutOfRange) + { + if (mWrapAround) + { + if (Value > mMaxValue) + Value = mMinValue + (Value - mMaxValue); + else + Value = mMaxValue + (Value - mMinValue); + } + else + { + Value = Mathf.Clamp(Value, mMinValue, mMaxValue); + mCurrentSpeed = 0f; + } + } + return Mathf.Abs(input) > Epsilon; + } + + // MaxSpeed may be limited as we approach the range ends, in order + // to prevent a hard bump + private float GetMaxSpeed() + { + float range = mMaxValue - mMinValue; + if (!mWrapAround && range > 0) + { + float threshold = range / 10f; + if (mCurrentSpeed > 0 && (mMaxValue - Value) < threshold) + { + float t = (mMaxValue - Value) / threshold; + return Mathf.Lerp(0, m_MaxSpeed, t); + } + else if (mCurrentSpeed < 0 && (Value - mMinValue) < threshold) + { + float t = (Value - mMinValue) / threshold; + return Mathf.Lerp(0, m_MaxSpeed, t); + } + } + return m_MaxSpeed; + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/AxisState.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/AxisState.cs.meta new file mode 100644 index 0000000..d86b4b8 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/AxisState.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 557c6f70a7173744abaa3967b6da6f5d +timeCreated: 1504195334 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/CameraState.cs b/Assets/Cinemachine/Base/Runtime/Core/CameraState.cs new file mode 100644 index 0000000..bfd9851 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CameraState.cs @@ -0,0 +1,352 @@ +using UnityEngine; +using Cinemachine.Utility; +using System.Collections.Generic; + +namespace Cinemachine +{ + /// + /// The output of the Cinemachine engine for a specific virtual camera. The information + /// in this struct can be blended, and provides what is needed to calculate an + /// appropriate camera position, orientation, and lens setting. + /// + /// Raw values are what the Cinemachine behaviours generate. The correction channel + /// holds perturbations to the raw values - e.g. noise or smoothing, or obstacle + /// avoidance corrections. Coirrections are not considered when making time-based + /// calculations such as damping. + /// + /// The Final position and orientation is the comination of the raw values and + /// their corrections. + /// + public struct CameraState + { + /// + /// Camera Lens Settings. + /// + public LensSettings Lens { get; set; } + + /// + /// Which way is up. World space unit vector. + /// + public Vector3 ReferenceUp { get; set; } + + /// + /// The world space focus point of the camera. What the camera wants to look at. + /// There is a special constant define to represent "nothing". Be careful to + /// check for that (or check the HasLookAt property). + /// + public Vector3 ReferenceLookAt { get; set; } + + /// + /// Returns true if this state has a valid ReferenceLookAt value. + /// + public bool HasLookAt { get { return ReferenceLookAt == ReferenceLookAt; } } // will be false if NaN + + /// + /// This constant represents "no point in space" or "no direction". + /// + public static Vector3 kNoPoint = new Vector3(float.NaN, float.NaN, float.NaN); + + /// + /// Raw (un-corrected) world space position of this camera + /// + public Vector3 RawPosition { get; set; } + + /// + /// Raw (un-corrected) world space orientation of this camera + /// + public Quaternion RawOrientation { get; set; } + + /// This is a way for the Body component to bypass aim damping, + /// useful for when the body need to rotate its point of view, but does not + /// want interference from the aim damping + internal Vector3 PositionDampingBypass { get; set; } + + /// + /// Subjective estimation of how "good" the shot is. + /// Larger values mean better quality. Default is 1. + /// + public float ShotQuality { get; set; } + + /// + /// Position correction. This will be added to the raw position. + /// This value doesn't get fed back into the system when calculating the next frame. + /// Can be noise, or smoothing, or both, or something else. + /// + public Vector3 PositionCorrection { get; set; } + + /// + /// Orientation correction. This will be added to the raw orientation. + /// This value doesn't get fed back into the system when calculating the next frame. + /// Can be noise, or smoothing, or both, or something else. + /// + public Quaternion OrientationCorrection { get; set; } + + /// + /// Position with correction applied. + /// + public Vector3 CorrectedPosition { get { return RawPosition + PositionCorrection; } } + + /// + /// Orientation with correction applied. + /// + public Quaternion CorrectedOrientation { get { return RawOrientation * OrientationCorrection; } } + + /// + /// Position with correction applied. This is what the final camera gets. + /// + public Vector3 FinalPosition { get { return RawPosition + PositionCorrection; } } + + /// + /// Orientation with correction and dutch applied. This is what the final camera gets. + /// + public Quaternion FinalOrientation + { + get + { + if (Mathf.Abs(Lens.Dutch) > UnityVectorExtensions.Epsilon) + return CorrectedOrientation * Quaternion.AngleAxis(Lens.Dutch, Vector3.forward); + return CorrectedOrientation; + } + } + + /// + /// State with default values + /// + public static CameraState Default + { + get + { + CameraState state = new CameraState(); + state.Lens = LensSettings.Default; + state.ReferenceUp = Vector3.up; + state.ReferenceLookAt = kNoPoint; + state.RawPosition = Vector3.zero; + state.RawOrientation = Quaternion.identity; + state.ShotQuality = 1; + state.PositionCorrection = Vector3.zero; + state.OrientationCorrection = Quaternion.identity; + state.PositionDampingBypass = Vector3.zero; + return state; + } + } + + /// Opaque structure represent extra blendable stuff and its weight. + /// The base system ignores this data - it is intended for extension modules + public struct CustomBlendable + { + /// The custom stuff that the extention module will consider + public Object m_Custom; + /// The weight of the custom stuff. Must be 0...1 + public float m_Weight; + + /// Constructor with specific values + /// The custom stuff that the extention module will consider + /// The weight of the custom stuff. Must be 0...1 + public CustomBlendable(Object custom, float weight) + { m_Custom = custom; m_Weight = weight; } + }; + + // This is to avoid excessive GC allocs + CustomBlendable mCustom0; + CustomBlendable mCustom1; + CustomBlendable mCustom2; + CustomBlendable mCustom3; + List m_CustomOverflow; + + /// The number of custom blendables that will be applied to the camera. + /// The base system manages but otherwise ignores this data - it is intended for + /// extension modules + public int NumCustomBlendables { get; private set; } + + /// Get a custom blendable that will be applied to the camera. + /// The base system manages but otherwise ignores this data - it is intended for + /// extension modules + /// Which one to get. Must be in range [0...NumCustomBlendables) + /// The custom blendable at the specified index. + public CustomBlendable GetCustomBlendable(int index) + { + switch (index) + { + case 0: return mCustom0; + case 1: return mCustom1; + case 2: return mCustom2; + case 3: return mCustom3; + default: + { + index -= 4; + if (m_CustomOverflow != null && index < m_CustomOverflow.Count) + return m_CustomOverflow[index]; + return new CustomBlendable(null, 0); + } + } + } + + int FindCustomBlendable(Object custom) + { + if (mCustom0.m_Custom == custom) + return 0; + if (mCustom1.m_Custom == custom) + return 1; + if (mCustom2.m_Custom == custom) + return 2; + if (mCustom3.m_Custom == custom) + return 3; + if (m_CustomOverflow != null) + { + for (int i = 0; i < m_CustomOverflow.Count; ++i) + if (m_CustomOverflow[i].m_Custom == custom) + return i + 4; + } + return -1; + } + + /// Add a custom blendable to the pot for eventual application to the camera. + /// The base system manages but otherwise ignores this data - it is intended for + /// extension modules + /// The custom blendable to add. If b.m_Custom is the same as an + /// already-added custom blendable, then they will be merged and the weights combined. + public void AddCustomBlendable(CustomBlendable b) + { + // Attempt to merge common blendables to avoid growth + int index = FindCustomBlendable(b.m_Custom); + if (index >= 0) + b.m_Weight += GetCustomBlendable(index).m_Weight; + else + { + index = NumCustomBlendables; + NumCustomBlendables = index + 1; + } + switch (index) + { + case 0: mCustom0 = b; break; + case 1: mCustom1 = b; break; + case 2: mCustom2 = b; break; + case 3: mCustom3 = b; break; + default: + { + if (m_CustomOverflow == null) + m_CustomOverflow = new List(); + m_CustomOverflow.Add(b); + break; + } + } + } + + /// Intelligently blend the contents of two states. + /// The first state, corresponding to t=0 + /// The second state, corresponding to t=1 + /// How much to interpolate. Internally clamped to 0..1 + /// Linearly interpolated CameraState + public static CameraState Lerp(CameraState stateA, CameraState stateB, float t) + { + t = Mathf.Clamp01(t); + float adjustedT = t; + + CameraState state = new CameraState(); + state.Lens = LensSettings.Lerp(stateA.Lens, stateB.Lens, t); + state.ReferenceUp = Vector3.Slerp(stateA.ReferenceUp, stateB.ReferenceUp, t); + state.RawPosition = Vector3.Lerp(stateA.RawPosition, stateB.RawPosition, t); + + state.ShotQuality = Mathf.Lerp(stateA.ShotQuality, stateB.ShotQuality, t); + state.PositionCorrection = Vector3.Lerp( + stateA.PositionCorrection, stateB.PositionCorrection, t); + // GML todo: is this right? Can it introduce a roll? + state.OrientationCorrection = Quaternion.Slerp( + stateA.OrientationCorrection, stateB.OrientationCorrection, t); + + Vector3 dirTarget = Vector3.zero; + if (!stateA.HasLookAt || !stateB.HasLookAt) + state.ReferenceLookAt = kNoPoint; // can't interpolate if undefined + else + { + // Re-interpolate FOV to preserve target composition, if possible + float fovA = stateA.Lens.FieldOfView; + float fovB = stateB.Lens.FieldOfView; + if (!state.Lens.Orthographic && !Mathf.Approximately(fovA, fovB)) + { + LensSettings lens = state.Lens; + lens.FieldOfView = state.InterpolateFOV( + fovA, fovB, + Mathf.Max((stateA.ReferenceLookAt - stateA.CorrectedPosition).magnitude, stateA.Lens.NearClipPlane), + Mathf.Max((stateB.ReferenceLookAt - stateB.CorrectedPosition).magnitude, stateB.Lens.NearClipPlane), t); + state.Lens = lens; + + // Make sure we preserve the screen composition through FOV changes + adjustedT = Mathf.Abs((lens.FieldOfView - fovA) / (fovB - fovA)); + } + + // Linear interpolation of lookAt target point + state.ReferenceLookAt = Vector3.Lerp( + stateA.ReferenceLookAt, stateB.ReferenceLookAt, adjustedT); + + // If orientations are different, use LookAt to blend them + float angle = Quaternion.Angle(stateA.RawOrientation, stateB.RawOrientation); + if (angle > UnityVectorExtensions.Epsilon) + dirTarget = state.ReferenceLookAt - state.CorrectedPosition; + } + + // Clever orientation interpolation + if (dirTarget.AlmostZero()) + { + // Don't know what we're looking at - can only slerp + state.RawOrientation = UnityQuaternionExtensions.SlerpWithReferenceUp( + stateA.RawOrientation, stateB.RawOrientation, t, state.ReferenceUp); + } + else + { + // Rotate while preserving our lookAt target + dirTarget = dirTarget.normalized; + if ((dirTarget - state.ReferenceUp).AlmostZero() + || (dirTarget + state.ReferenceUp).AlmostZero()) + { + // Looking up or down at the pole + state.RawOrientation = UnityQuaternionExtensions.SlerpWithReferenceUp( + stateA.RawOrientation, stateB.RawOrientation, t, state.ReferenceUp); + } + else + { + // Put the target in the center + state.RawOrientation = Quaternion.LookRotation(dirTarget, state.ReferenceUp); + + // Blend the desired offsets from center + Vector2 deltaA = -stateA.RawOrientation.GetCameraRotationToTarget( + stateA.ReferenceLookAt - stateA.CorrectedPosition, stateA.ReferenceUp); + Vector2 deltaB = -stateB.RawOrientation.GetCameraRotationToTarget( + stateB.ReferenceLookAt - stateB.CorrectedPosition, stateB.ReferenceUp); + state.RawOrientation = state.RawOrientation.ApplyCameraRotation( + Vector2.Lerp(deltaA, deltaB, adjustedT), state.ReferenceUp); + } + } + + // Accumulate the custom blendables and apply the weights + for (int i = 0; i < stateA.NumCustomBlendables; ++i) + { + CustomBlendable b = stateA.GetCustomBlendable(i); + b.m_Weight *= (1-t); + if (b.m_Weight > UnityVectorExtensions.Epsilon) + state.AddCustomBlendable(b); + } + for (int i = 0; i < stateB.NumCustomBlendables; ++i) + { + CustomBlendable b = stateB.GetCustomBlendable(i); + b.m_Weight *= t; + if (b.m_Weight > UnityVectorExtensions.Epsilon) + state.AddCustomBlendable(b); + } + return state; + } + + float InterpolateFOV(float fovA, float fovB, float dA, float dB, float t) + { + // We interpolate shot height + float hA = dA * 2f * Mathf.Tan(fovA * Mathf.Deg2Rad / 2f); + float hB = dB * 2f * Mathf.Tan(fovB * Mathf.Deg2Rad / 2f); + float h = Mathf.Lerp(hA, hB, t); + float fov = 179f; + float d = Mathf.Lerp(dA, dB, t); + if (d > UnityVectorExtensions.Epsilon) + fov = 2f * Mathf.Atan(h / (2 * d)) * Mathf.Rad2Deg; + return Mathf.Clamp(fov, Mathf.Min(fovA, fovB), Mathf.Max(fovA, fovB)); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/CameraState.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/CameraState.cs.meta new file mode 100644 index 0000000..b290ca4 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CameraState.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c2a918f460a69394eb9726b31e1d404c +timeCreated: 1488314898 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlend.cs b/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlend.cs new file mode 100644 index 0000000..2e8da48 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlend.cs @@ -0,0 +1,207 @@ +using System; +using UnityEngine; + +namespace Cinemachine +{ + /// + /// Describes a blend between 2 Cinemachine Virtual Cameras, and holds the + /// current state of the blend. + /// + public class CinemachineBlend + { + /// First camera in the blend + public ICinemachineCamera CamA { get; set; } + + /// Second camera in the blend + public ICinemachineCamera CamB { get; set; } + + /// The curve that describes the way the blend transitions over time + /// from the first camera to the second. X-axis is time in seconds over which + /// the blend takes place and Y axis is blend weight (0..1) + public AnimationCurve BlendCurve { get; set; } + + /// The current time relative to the start of the blend + public float TimeInBlend { get; set; } + + /// The current weight of the blend. This is an evaluation of the + /// BlendCurve at the current time relative to the start of the blend. + /// 0 means camA, 1 means camB. + public float BlendWeight + { + get { return BlendCurve != null ? BlendCurve.Evaluate(TimeInBlend) : 0; } + } + + /// Validity test for the blend. True if both cameras are defined. + public bool IsValid + { + get { return (CamA != null || CamB != null); } + } + + /// Duration in seconds of the blend. + /// This is given read from the BlendCurve. + public float Duration { get; set; } + + /// True if the time relative to the start of the blend is greater + /// than or equal to the blend duration + public bool IsComplete { get { return TimeInBlend >= Duration; } } + + /// Text description of the blend, for debugging + public string Description + { + get + { + string fromName = (CamA != null) ? "[" + CamA.Name + "]": "(none)"; + string toName = (CamB != null) ? "[" + CamB.Name + "]" : "(none)"; + int percent = (int)(BlendWeight * 100f); + return string.Format("{0} {1}% from {2}", toName, percent, fromName); + } + } + + /// Does the blend use a specific Cinemachine Virtual Camera? + /// The camera to test + /// True if the camera is involved in the blend + public bool Uses(ICinemachineCamera cam) + { + if (cam == CamA || cam == CamB) + return true; + BlendSourceVirtualCamera b = CamA as BlendSourceVirtualCamera; + if (b != null && b.Blend.Uses(cam)) + return true; + b = CamB as BlendSourceVirtualCamera; + if (b != null && b.Blend.Uses(cam)) + return true; + return false; + } + + /// Construct a blend + /// First camera + /// Second camera + /// Blend curve + /// Current time in blend, relative to the start of the blend + public CinemachineBlend( + ICinemachineCamera a, ICinemachineCamera b, AnimationCurve curve, float duration, float t) + { + if (a == null || b == null) + throw new ArgumentException("Blend cameras cannot be null"); + CamA = a; + CamB = b; + BlendCurve = curve; + TimeInBlend = t; + Duration = duration; + } + + /// Make sure the source cameras get updated. + /// Default world up. Individual vcams may modify this + /// Time increment used for calculating time-based behaviours (e.g. damping) + public void UpdateCameraState(Vector3 worldUp, float deltaTime) + { + // Make sure both cameras have been updated (they are not necessarily + // enabled, and only enabled cameras get updated automatically + // every frame) + CinemachineCore.Instance.UpdateVirtualCamera(CamA, worldUp, deltaTime); + CinemachineCore.Instance.UpdateVirtualCamera(CamB, worldUp, deltaTime); + } + + /// Compute the blended CameraState for the current time in the blend. + public CameraState State { get { return CameraState.Lerp(CamA.State, CamB.State, BlendWeight); } } + } + + /// Definition of a Camera blend. This struct holds the information + /// necessary to generate a suitable AnimationCurve for a Cinemachine Blend. + [Serializable] + [DocumentationSorting(10.2f, DocumentationSortingAttribute.Level.UserRef)] + public struct CinemachineBlendDefinition + { + /// Supported predefined shapes for the blend curve. + [DocumentationSorting(10.21f, DocumentationSortingAttribute.Level.UserRef)] + public enum Style + { + /// Zero-length blend + Cut, + /// S-shaped curve, giving a gentle and smooth transition + EaseInOut, + /// Linear out of the outgoing shot, and easy into the incoming + EaseIn, + /// Easy out of the outgoing shot, and linear into the incoming + EaseOut, + /// Easy out of the outgoing, and hard into the incoming + HardIn, + /// Hard out of the outgoing, and easy into the incoming + HardOut, + /// Linear blend. Mechanical-looking. + Linear + }; + + /// The shape of the blend curve. + [Tooltip("Shape of the blend curve")] + public Style m_Style; + + /// The duration (in seconds) of the blend + [Tooltip("Duration of the blend, in seconds")] + public float m_Time; + + /// Constructor + /// The shape of the blend curve. + /// The duration (in seconds) of the blend + public CinemachineBlendDefinition(Style style, float time) + { + m_Style = style; + m_Time = time; + } + + /// + /// An AnimationCurve specifying the interpolation duration and value + /// for this camera blend. The time of the last key frame is assumed to the be the + /// duration of the blend. Y-axis values must be in range [0,1] (internally clamped + /// within Blender) and time must be in range of [0, +infinity) + /// + public AnimationCurve BlendCurve + { + get + { + float time = Mathf.Max(0, m_Time); + switch (m_Style) + { + default: + case Style.Cut: return new AnimationCurve(); + case Style.EaseInOut: return AnimationCurve.EaseInOut(0f, 0f, time, 1f); + case Style.EaseIn: + { + AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); + Keyframe[] keys = curve.keys; + keys[1].inTangent = 0; + curve.keys = keys; + return curve; + } + case Style.EaseOut: + { + AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); + Keyframe[] keys = curve.keys; + keys[0].outTangent = 0; + curve.keys = keys; + return curve; + } + case Style.HardIn: + { + AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); + Keyframe[] keys = curve.keys; + keys[0].outTangent = 0; + keys[1].inTangent = 1.5708f; // pi/2 = up + curve.keys = keys; + return curve; + } + case Style.HardOut: + { + AnimationCurve curve = AnimationCurve.Linear(0f, 0f, time, 1f); + Keyframe[] keys = curve.keys; + keys[0].outTangent = 1.5708f; // pi/2 = up + keys[1].inTangent = 0; + curve.keys = keys; + return curve; + } + case Style.Linear: return AnimationCurve.Linear(0f, 0f, time, 1f); + } + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlend.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlend.cs.meta new file mode 100644 index 0000000..61bb18d --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlend.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3fed8968b96eb924891cf86f5c51f661 +timeCreated: 1484407000 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlenderSettings.cs b/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlenderSettings.cs new file mode 100644 index 0000000..8abb672 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlenderSettings.cs @@ -0,0 +1,95 @@ +using UnityEngine; +using System; + +namespace Cinemachine +{ + /// + /// Asset that defines the rules for blending between Virtual Cameras. + /// + [DocumentationSorting(10, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public sealed class CinemachineBlenderSettings : ScriptableObject + { + /// + /// Container specifying how two specific Cinemachine Virtual Cameras + /// blend together. + /// + [DocumentationSorting(10.1f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public struct CustomBlend + { + [Tooltip("When blending from this camera")] + public string m_From; + + [Tooltip("When blending to this camera")] + public string m_To; + + [Tooltip("Blend curve definition")] + public CinemachineBlendDefinition m_Blend; + } + /// The array containing explicitly defined blends between two Virtual Cameras + [Tooltip("The array containing explicitly defined blends between two Virtual Cameras")] + public CustomBlend[] m_CustomBlends = null; + + /// Internal API for the inspector editopr: a label to represent any camera + public const string kBlendFromAnyCameraLabel = "**ANY CAMERA**"; + + /// + /// Attempts to find a blend curve which matches the to and from cameras as specified. + /// If no match is found, the function returns either the + /// default blend for this Blender or NULL depending on the state + /// of returnDefaultOnNoMatch. + /// + /// The game object name of the from camera + /// The game object name of the to camera + /// Curve to return if no curve found. Can be NULL. + /// + public AnimationCurve GetBlendCurveForVirtualCameras( + string fromCameraName, string toCameraName, AnimationCurve defaultCurve) + { + AnimationCurve anyToMe = null; + AnimationCurve meToAny = null; + if (m_CustomBlends != null) + { + for (int i = 0; i < m_CustomBlends.Length; ++i) + { + // Attempt to find direct name first + CustomBlend blendParams = m_CustomBlends[i]; + if ((blendParams.m_From == fromCameraName) + && (blendParams.m_To == toCameraName)) + { + return blendParams.m_Blend.BlendCurve; + } + // If we come across default applicable wildcards, remember them + if (blendParams.m_From == kBlendFromAnyCameraLabel) + { + if (!string.IsNullOrEmpty(toCameraName) + && blendParams.m_To == toCameraName) + { + anyToMe = blendParams.m_Blend.BlendCurve; + } + else if (blendParams.m_To == kBlendFromAnyCameraLabel) + defaultCurve = blendParams.m_Blend.BlendCurve; + } + else if (blendParams.m_To == kBlendFromAnyCameraLabel + && !string.IsNullOrEmpty(fromCameraName) + && blendParams.m_From == fromCameraName) + { + meToAny = blendParams.m_Blend.BlendCurve; + } + } + } + + // If nothing is found try to find wild card blends from any + // camera to our new one + if (anyToMe != null) + return anyToMe; + + // Still have nothing? Try from our camera to any camera + if (meToAny != null) + return meToAny; + + return defaultCurve; + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlenderSettings.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlenderSettings.cs.meta new file mode 100644 index 0000000..ed99c07 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineBlenderSettings.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 36baaa8bdcb9d8b49b9199833965d2c3 +timeCreated: 1486497606 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineComponentBase.cs b/Assets/Cinemachine/Base/Runtime/Core/CinemachineComponentBase.cs new file mode 100644 index 0000000..cfcbaf8 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineComponentBase.cs @@ -0,0 +1,77 @@ +using UnityEngine; + +namespace Cinemachine +{ + /// + /// An abstract representation of a mutator acting on a Cinemachine Virtual Camera + /// + [DocumentationSorting(24, DocumentationSortingAttribute.Level.API)] + public abstract class CinemachineComponentBase : MonoBehaviour + { + /// Useful constant for very small floats + protected const float Epsilon = Utility.UnityVectorExtensions.Epsilon; + + /// Get the associated CinemachineVirtualCameraBase + public CinemachineVirtualCameraBase VirtualCamera + { + get + { + if (m_vcamOwner == null) + m_vcamOwner = gameObject.transform.parent.gameObject.GetComponent(); + return m_vcamOwner; + } + } + CinemachineVirtualCameraBase m_vcamOwner; + + /// Returns the owner vcam's Follow target. + public Transform FollowTarget + { + get + { + CinemachineVirtualCameraBase vcam = VirtualCamera; + return vcam == null ? null : vcam.Follow; + } + } + + /// Returns the owner vcam's LookAt target. + public Transform LookAtTarget + { + get + { + CinemachineVirtualCameraBase vcam = VirtualCamera; + return vcam == null ? null : vcam.LookAt; + } + } + + /// Returns the owner vcam's CameraState. + public CameraState VcamState + { + get + { + CinemachineVirtualCameraBase vcam = VirtualCamera; + return vcam == null ? CameraState.Default : vcam.State; + } + } + + /// Returns true if this object is enabled and set up to produce results. + public abstract bool IsValid { get; } + + /// Override this to do such things as offset the RefereceLookAt. + /// Base class implementation does nothing. + /// Input state that must be mutated + public virtual void PrePipelineMutateCameraState(ref CameraState state) {} + + /// What part of the pipeline this fits into + public abstract CinemachineCore.Stage Stage { get; } + + /// Mutates the camera state. This state will later be applied to the camera. + /// Input state that must be mutated + /// Delta time for time-based effects (ignore if less than 0) + public abstract void MutateCameraState(ref CameraState curState, float deltaTime); + + /// API for the editor, to process a position drag from the user. + /// Base class implementation does nothing. + /// The amount dragged this frame + public virtual void OnPositionDragged(Vector3 delta) {} + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineComponentBase.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/CinemachineComponentBase.cs.meta new file mode 100644 index 0000000..fde2723 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineComponentBase.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b2f73bdc979030e419f33c10913639cc +timeCreated: 1510078351 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineCore.cs b/Assets/Cinemachine/Base/Runtime/Core/CinemachineCore.cs new file mode 100644 index 0000000..8bf6877 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineCore.cs @@ -0,0 +1,429 @@ +using UnityEngine; +using System.Collections.Generic; + +namespace Cinemachine +{ + /// A singleton that manages complete lists of CinemachineBrain and, + /// Cinemachine Virtual Cameras, and the priority queue. Provides + /// services to keeping track of whether Cinemachine Virtual Cameras have + /// been updated each frame. + public sealed class CinemachineCore + { + /// Data version string. Used to upgrade from legacy projects + public static readonly int kStreamingVersion = 20170927; + + /// Human-readable Cinemachine Version + public static readonly string kVersionString = "2.1"; + + /// + /// Stages in the Cinemachine Component pipeline, used for + /// UI organization>. This enum defines the pipeline order. + /// + public enum Stage + { + /// Second stage: position the camera in space + Body, + + /// Third stage: orient the camera to point at the target + Aim, + + /// Final stage: apply noise (this is done separately, in the + /// Correction channel of the CameraState) + Noise + }; + + private static CinemachineCore sInstance = null; + + /// Get the singleton instance + public static CinemachineCore Instance + { + get + { + if (sInstance == null) + sInstance = new CinemachineCore(); + return sInstance; + } + } + + /// + /// If true, show hidden Cinemachine objects, to make manual script mapping possible. + /// + public static bool sShowHiddenObjects = false; + + /// Delegate for overriding Unity's default input system. Returns the value + /// of the named axis. + public delegate float AxisInputDelegate(string axisName); + + /// Delegate for overriding Unity's default input system. + /// If you set this, then your delegate will be called instead of + /// System.Input.GetAxis(axisName) whenever in-game user input is needed. + public static AxisInputDelegate GetInputAxis = UnityEngine.Input.GetAxis; + + /// List of all active CinemachineBrains. + private List mActiveBrains = new List(); + + /// Access the array of active CinemachineBrains in the scene + public int BrainCount { get { return mActiveBrains.Count; } } + + /// Access the array of active CinemachineBrains in the scene + /// without gebnerating garbage + /// Index of the brain to access, range 0-BrainCount + /// The brain at the specified index + public CinemachineBrain GetActiveBrain(int index) + { + return mActiveBrains[index]; + } + + /// Called when a CinemachineBrain is enabled. + internal void AddActiveBrain(CinemachineBrain brain) + { + // First remove it, just in case it's being added twice + RemoveActiveBrain(brain); + mActiveBrains.Insert(0, brain); + } + + /// Called when a CinemachineBrain is disabled. + internal void RemoveActiveBrain(CinemachineBrain brain) + { + mActiveBrains.Remove(brain); + } + + /// List of all active ICinemachineCameras. + private List mActiveCameras = new List(); + + /// + /// List of all active Cinemachine Virtual Cameras for all brains. + /// This list is kept sorted by priority. + /// + public int VirtualCameraCount { get { return mActiveCameras.Count; } } + + /// Access the array of active ICinemachineCamera in the scene + /// without gebnerating garbage + /// Index of the camera to access, range 0-VirtualCameraCount + /// The virtual camera at the specified index + public ICinemachineCamera GetVirtualCamera(int index) + { + return mActiveCameras[index]; + } + + /// Called when a Cinemachine Virtual Camera is enabled. + internal void AddActiveCamera(ICinemachineCamera vcam) + { + // Bring it to the top of the list + RemoveActiveCamera(vcam); + + // Keep list sorted by priority + int insertIndex; + for (insertIndex = 0; insertIndex < mActiveCameras.Count; ++insertIndex) + if (vcam.Priority >= mActiveCameras[insertIndex].Priority) + break; + + mActiveCameras.Insert(insertIndex, vcam); + } + + /// Called when a Cinemachine Virtual Camera is disabled. + internal void RemoveActiveCamera(ICinemachineCamera vcam) + { + mActiveCameras.Remove(vcam); + } + + // Registry of all vcams that are parented (i.e. slaves of) to other vcams + private List> mChildCameras = new List>(); + + /// Called when a child vcam is enabled. + internal void AddChildCamera(ICinemachineCamera vcam) + { + RemoveChildCamera(vcam); + + int parentLevel = 0; + for (ICinemachineCamera p = vcam; p != null; p = p.ParentCamera) + ++parentLevel; + while (mChildCameras.Count < parentLevel) + mChildCameras.Add(new List()); + mChildCameras[parentLevel-1].Add(vcam); + } + + /// Called when a child vcam is disabled. + internal void RemoveChildCamera(ICinemachineCamera vcam) + { + for (int i = 0; i < mChildCameras.Count; ++i) + mChildCameras[i].Remove(vcam); + } + + /// Update all the active vcams in the scene, in the correct dependency order. + internal void UpdateAllActiveVirtualCameras(Vector3 worldUp, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineCore.UpdateAllActiveVirtualCameras"); + int numCameras; + + // Update the leaf-most cameras first + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineCore.UpdateAllActiveVirtualCameras.leaf-most"); + for (int i = mChildCameras.Count-1; i >= 0; --i) + { + numCameras = mChildCameras[i].Count; + for (int j = 0; j < numCameras; ++j) + UpdateVirtualCamera(mChildCameras[i][j], worldUp, deltaTime); + } + //UnityEngine.Profiling.Profiler.EndSample(); + + // Then all the top-level cameras + numCameras = VirtualCameraCount; + for (int i = 0; i < numCameras; ++i) + UpdateVirtualCamera(GetVirtualCamera(i), worldUp, deltaTime); + //UnityEngine.Profiling.Profiler.EndSample(); + } + + /// + /// Update a single Cinemachine Virtual Camera if and only if it + /// hasn't already been updated this frame. Always update vcams via this method. + /// Calling this more than once per frame for the same camera will have no effect. + /// + internal bool UpdateVirtualCamera(ICinemachineCamera vcam, Vector3 worldUp, float deltaTime) + { + //UnityEngine.Profiling.Profiler.BeginSample("CinemachineCore.UpdateVirtualCamera"); + int now = Time.frameCount; + UpdateFilter filter = CurrentUpdateFilter; + bool isSmartUpdate = filter != UpdateFilter.ForcedFixed + && filter != UpdateFilter.ForcedLate; + bool isSmartLateUpdate = filter == UpdateFilter.Late; + if (!isSmartUpdate) + { + if (filter == UpdateFilter.ForcedFixed) + filter = UpdateFilter.Fixed; + if (filter == UpdateFilter.ForcedLate) + filter = UpdateFilter.Late; + } + + if (mUpdateStatus == null) + mUpdateStatus = new Dictionary(); + if (vcam.VirtualCameraGameObject == null) + { + if (mUpdateStatus.ContainsKey(vcam)) + mUpdateStatus.Remove(vcam); + //UnityEngine.Profiling.Profiler.EndSample(); + return false; // camera was deleted + } + UpdateStatus status; + if (!mUpdateStatus.TryGetValue(vcam, out status)) + { + status = new UpdateStatus(now); + mUpdateStatus.Add(vcam, status); + } + + int subframes = isSmartLateUpdate ? 1 : CinemachineBrain.GetSubframeCount(); + if (status.lastUpdateFrame != now) + status.lastUpdateSubframe = 0; + + // If we're in smart update mode and the target moved, then we must examine + // how the target has been moving recently in order to figure out whether to + // update now + bool updateNow = !isSmartUpdate; + if (isSmartUpdate) + { + Matrix4x4 targetPos; + if (!GetTargetPosition(vcam, out targetPos)) + updateNow = isSmartLateUpdate; // no target + else + updateNow = status.ChoosePreferredUpdate(now, targetPos, filter) + == filter; + } + + if (updateNow) + { + status.preferredUpdate = filter; + while (status.lastUpdateSubframe < subframes) + { +//Debug.Log(vcam.Name + ": frame " + Time.frameCount + "." + status.lastUpdateSubframe + ", " + CurrentUpdateFilter + ", deltaTime = " + deltaTime); + vcam.UpdateCameraState(worldUp, deltaTime); + ++status.lastUpdateSubframe; + } + status.lastUpdateFrame = now; + } + + mUpdateStatus[vcam] = status; + //UnityEngine.Profiling.Profiler.EndSample(); + return true; + } + + struct UpdateStatus + { + const int kWindowSize = 30; + + public int lastUpdateFrame; + public int lastUpdateSubframe; + + public int windowStart; + public int numWindowLateUpdateMoves; + public int numWindowFixedUpdateMoves; + public int numWindows; + public UpdateFilter preferredUpdate; + + public Matrix4x4 targetPos; + + public UpdateStatus(int currentFrame) + { + lastUpdateFrame = -1; + lastUpdateSubframe = 0; + windowStart = currentFrame; + numWindowLateUpdateMoves = 0; + numWindowFixedUpdateMoves = 0; + numWindows = 0; + preferredUpdate = UpdateFilter.Late; + targetPos = Matrix4x4.zero; + } + + // Important: updateFilter may ONLY be Late or Fixed + public UpdateFilter ChoosePreferredUpdate( + int currentFrame, Matrix4x4 pos, UpdateFilter updateFilter) + { + if (targetPos != pos) + { + if (updateFilter == UpdateFilter.Late) + ++numWindowLateUpdateMoves; + else if (lastUpdateSubframe == 0) + ++numWindowFixedUpdateMoves; + targetPos = pos; + } + //Debug.Log("Fixed=" + numWindowFixedUpdateMoves + ", Late=" + numWindowLateUpdateMoves); + UpdateFilter choice = preferredUpdate; + bool inconsistent = numWindowLateUpdateMoves > 0 && numWindowFixedUpdateMoves > 0; + if (inconsistent || numWindowLateUpdateMoves >= numWindowFixedUpdateMoves) + choice = UpdateFilter.Late; + else + choice = UpdateFilter.Fixed; + if (numWindows == 0) + preferredUpdate = choice; + + if (windowStart + kWindowSize <= currentFrame) + { + preferredUpdate = choice; + ++numWindows; + windowStart = currentFrame; + numWindowLateUpdateMoves = numWindowFixedUpdateMoves = 0; + } + return preferredUpdate; + } + } + Dictionary mUpdateStatus; + + /// Internal use only + public enum UpdateFilter { Fixed, ForcedFixed, Late, ForcedLate }; + internal UpdateFilter CurrentUpdateFilter { get; set; } + private static bool GetTargetPosition(ICinemachineCamera vcam, out Matrix4x4 targetPos) + { + ICinemachineCamera vcamTarget = vcam.LiveChildOrSelf; + if (vcamTarget == null || vcamTarget.VirtualCameraGameObject == null) + { + targetPos = Matrix4x4.identity; + return false; + } + targetPos = vcamTarget.VirtualCameraGameObject.transform.localToWorldMatrix; + if (vcamTarget.LookAt != null) + { + targetPos = vcamTarget.LookAt.localToWorldMatrix; + return true; + } + if (vcamTarget.Follow != null) + { + targetPos = vcamTarget.Follow.localToWorldMatrix; + return true; + } + // If no target, use the vcam itself + targetPos = vcam.VirtualCameraGameObject.transform.localToWorldMatrix; + return true; + } + + /// Internal use only + public UpdateFilter GetVcamUpdateStatus(ICinemachineCamera vcam) + { + UpdateStatus status; + if (mUpdateStatus == null || !mUpdateStatus.TryGetValue(vcam, out status)) + return UpdateFilter.Late; + return status.preferredUpdate; + } + + /// + /// Is this virtual camera currently actively controlling any Camera? + /// + public bool IsLive(ICinemachineCamera vcam) + { + if (vcam != null) + { + for (int i = 0; i < BrainCount; ++i) + { + CinemachineBrain b = GetActiveBrain(i); + if (b != null && b.IsLive(vcam)) + return true; + } + } + return false; + } + + /// + /// Signal that the virtual has been activated. + /// If the camera is live, then all CinemachineBrains that are showing it will + /// send an activation event. + /// + public void GenerateCameraActivationEvent(ICinemachineCamera vcam) + { + if (vcam != null) + { + for (int i = 0; i < BrainCount; ++i) + { + CinemachineBrain b = GetActiveBrain(i); + if (b != null && b.IsLive(vcam)) + b.m_CameraActivatedEvent.Invoke(vcam); + } + } + } + + /// + /// Signal that the virtual camera's content is discontinuous WRT the previous frame. + /// If the camera is live, then all CinemachineBrains that are showing it will send a cut event. + /// + public void GenerateCameraCutEvent(ICinemachineCamera vcam) + { + if (vcam != null) + { + for (int i = 0; i < BrainCount; ++i) + { + CinemachineBrain b = GetActiveBrain(i); + if (b != null && b.IsLive(vcam)) + b.m_CameraCutEvent.Invoke(b); + } + } + } + + /// + /// Try to find a CinemachineBrain to associate with a + /// Cinemachine Virtual Camera. The first CinemachineBrain + /// in which this Cinemachine Virtual Camera is live will be used. + /// If none, then the first active CinemachineBrain will be used. + /// Brains with OutputCamera == null will not be returned. + /// Final result may be null. + /// + /// Virtual camera whose potential brain we need. + /// First CinemachineBrain found that might be + /// appropriate for this vcam, or null + public CinemachineBrain FindPotentialTargetBrain(ICinemachineCamera vcam) + { + int numBrains = BrainCount; + if (vcam != null && numBrains > 1) + { + for (int i = 0; i < numBrains; ++i) + { + CinemachineBrain b = GetActiveBrain(i); + if (b != null && b.OutputCamera != null && b.IsLive(vcam)) + return b; + } + } + for (int i = 0; i < numBrains; ++i) + { + CinemachineBrain b = GetActiveBrain(i); + if (b != null && b.OutputCamera != null) + return b; + } + return null; + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineCore.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/CinemachineCore.cs.meta new file mode 100644 index 0000000..8c8c945 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineCore.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c7d73314dfe49f8458398c6dc8edcda8 +timeCreated: 1484001119 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineDebugLogger.cs b/Assets/Cinemachine/Base/Runtime/Core/CinemachineDebugLogger.cs new file mode 100644 index 0000000..77c4912 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineDebugLogger.cs @@ -0,0 +1,47 @@ +using UnityEngine; +using System.Collections.Generic; + +namespace Cinemachine.Utility +{ + /// Manages onscreen positions for Cinemachine debugging output + public class CinemachineGameWindowDebug + { + static HashSet mClients; + + /// Release a screen rectangle previously obtained through GetScreenPos() + /// The client caller. Used as a handle. + public static void ReleaseScreenPos(Object client) + { + if (mClients != null && mClients.Contains(client)) + mClients.Remove(client); + } + + /// Reserve an on-screen rectangle for debugging output. + /// The client caller. This is used as a handle. + /// Sample text, for determining rectangle size + /// What style will be used to draw, used here for + /// determining rect size + /// An area on the game screen large enough to print the text + /// in the style indicated + public static Rect GetScreenPos(Object client, string text, GUIStyle style) + { + if (mClients == null) + mClients = new HashSet(); + if (!mClients.Contains(client)) + mClients.Add(client); + + Vector2 pos = new Vector2(0, 0); + Vector2 size = style.CalcSize(new GUIContent(text)); + if (mClients != null) + { + foreach (var c in mClients) + { + if (c == client) + break; + pos.y += size.y; + } + } + return new Rect(pos, size); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineDebugLogger.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/CinemachineDebugLogger.cs.meta new file mode 100644 index 0000000..25ba399 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineDebugLogger.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 10e6f8c815d3c4d45b1d98b951d53912 +timeCreated: 1481654954 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineExtension.cs b/Assets/Cinemachine/Base/Runtime/Core/CinemachineExtension.cs new file mode 100644 index 0000000..a993882 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineExtension.cs @@ -0,0 +1,89 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Cinemachine +{ + /// + /// Base class for a Cinemachine Virtual Camera extension module. + /// Hooks into the Cinemachine Pipeline. + /// + [DocumentationSorting(23, DocumentationSortingAttribute.Level.API)] + public abstract class CinemachineExtension : MonoBehaviour + { + /// Useful constant for very small floats + protected const float Epsilon = Utility.UnityVectorExtensions.Epsilon; + + /// Get the associated CinemachineVirtualCameraBase + public CinemachineVirtualCameraBase VirtualCamera + { + get + { + if (m_vcamOwner == null) + m_vcamOwner = GetComponent(); + return m_vcamOwner; + } + } + CinemachineVirtualCameraBase m_vcamOwner; + + /// Connect to virtual camera pipeline. + /// Override implementations must call this base implementation + protected virtual void Awake() + { + ConnectToVcam(); + } + + /// Disconnect from virtual camera pipeline. + /// Override implementations must call this base implementation + protected virtual void OnDestroy() + { + if (VirtualCamera != null) + VirtualCamera.RemovePostPipelineStageHook(PostPipelineStageCallback); + } + + void ConnectToVcam() + { + if (VirtualCamera == null) + Debug.LogError("CinemachineExtension requires a Cinemachine Virtual Camera component"); + else + VirtualCamera.AddPostPipelineStageHook(PostPipelineStageCallback); + mExtraState = null; + } + + /// + /// This callback will be called after the virtual camera has implemented + /// each stage in the pipeline. This method may modify the referenced state. + /// If deltaTime less than 0, reset all state info and perform no damping. + /// + protected abstract void PostPipelineStageCallback( + CinemachineVirtualCameraBase vcam, + CinemachineCore.Stage stage, ref CameraState state, float deltaTime); + + /// Because extensions can be placed on manager cams and will in that + /// case be called for all the vcam children, vcam-specific state information + /// should be stored here. Just define a class to hold your state info + /// and use it exclusively when calling this. + protected T GetExtraState(ICinemachineCamera vcam) where T : class, new() + { + if (mExtraState == null) + mExtraState = new Dictionary(); + System.Object extra = null; + if (!mExtraState.TryGetValue(vcam, out extra)) + extra = mExtraState[vcam] = new T(); + return extra as T; + } + + /// Ineffeicient method to get all extra state infor for all vcams. + /// Intended for Editor use only, not runtime! + /// + protected List GetAllExtraStates() where T : class, new() + { + var list = new List(); + if (mExtraState != null) + foreach (var v in mExtraState) + list.Add(v.Value as T); + return list; + } + + private Dictionary mExtraState; + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineExtension.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/CinemachineExtension.cs.meta new file mode 100644 index 0000000..afa0ba2 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineExtension.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4fa53a91a43ae1a4bbf6b29961b45c38 +timeCreated: 1504804419 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachinePathBase.cs b/Assets/Cinemachine/Base/Runtime/Core/CinemachinePathBase.cs new file mode 100644 index 0000000..6254b25 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachinePathBase.cs @@ -0,0 +1,356 @@ +using UnityEngine; +using Cinemachine.Utility; +using System; + +namespace Cinemachine +{ + /// Abstract base class for a world-space path, + /// suitable for a camera dolly track. + public abstract class CinemachinePathBase : MonoBehaviour + { + /// Path samples per waypoint + [Tooltip("Path samples per waypoint. This is used for calculating path distances.")] + [Range(1, 100)] + public int m_Resolution = 20; + + /// This class holds the settings that control how the path + /// will appear in the editor scene view. The path is not visible in the game view + [DocumentationSorting(18.1f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] public class Appearance + { + [Tooltip("The color of the path itself when it is active in the editor")] + public Color pathColor = Color.green; + [Tooltip("The color of the path itself when it is inactive in the editor")] + public Color inactivePathColor = Color.gray; + [Tooltip("The width of the railroad-tracks that are drawn to represent the path")] + [Range(0f, 10f)] + public float width = 0.2f; + } + /// The settings that control how the path + /// will appear in the editor scene view. + [Tooltip("The settings that control how the path will appear in the editor scene view.")] + public Appearance m_Appearance = new Appearance(); + + /// The minimum value for the path position + public abstract float MinPos { get; } + + /// The maximum value for the path position + public abstract float MaxPos { get; } + + /// True if the path ends are joined to form a continuous loop + public abstract bool Looped { get; } + + /// Get a normalized path position, taking spins into account if looped + /// Position along the path + /// Normalized position, between MinPos and MaxPos + public virtual float NormalizePos(float pos) + { + if (MaxPos == 0) + return 0; + if (Looped) + { + pos = pos % MaxPos; + if (pos < 0) + pos += MaxPos; + return pos; + } + return Mathf.Clamp(pos, 0, MaxPos); + } + + /// Get a worldspace position of a point along the path + /// Postion along the path. Need not be normalized. + /// World-space position of the point along at path at pos + public abstract Vector3 EvaluatePosition(float pos); + + /// Get the tangent of the curve at a point along the path. + /// Postion along the path. Need not be normalized. + /// World-space direction of the path tangent. + /// Length of the vector represents the tangent strength + public abstract Vector3 EvaluateTangent(float pos); + + /// Get the orientation the curve at a point along the path. + /// Postion along the path. Need not be normalized. + /// World-space orientation of the path + public abstract Quaternion EvaluateOrientation(float pos); + + /// Find the closest point on the path to a given worldspace target point. + /// Performance could be improved by checking the bounding polygon of each segment, + /// and only entering the best segment(s) + /// Worldspace target that we want to approach + /// In what segment of the path to start the search. + /// A Segment is a section of path between 2 waypoints. + /// How many segments on either side of the startSegment + /// to search. -1 means no limit, i.e. search the entire path + /// We search a segment by dividing it into this many + /// straight pieces. The higher the number, the more accurate the result, but performance + /// is proportionally slower for higher numbers + /// The position along the path that is closest to the target point. + /// The value is in Path Units, not Distance units. + public virtual float FindClosestPoint( + Vector3 p, int startSegment, int searchRadius, int stepsPerSegment) + { + float start = MinPos; + float end = MaxPos; + if (searchRadius >= 0) + { + int r = Mathf.FloorToInt(Mathf.Min(searchRadius, (end - start) / 2f)); + start = startSegment - r; + end = startSegment + r + 1; + if (!Looped) + { + start = Mathf.Max(start, MinPos); + end = Mathf.Max(end, MaxPos); + } + } + stepsPerSegment = Mathf.RoundToInt(Mathf.Clamp(stepsPerSegment, 1f, 100f)); + float stepSize = 1f / stepsPerSegment; + float bestPos = startSegment; + float bestDistance = float.MaxValue; + int iterations = (stepsPerSegment == 1) ? 1 : 3; + for (int i = 0; i < iterations; ++i) + { + Vector3 v0 = EvaluatePosition(start); + for (float f = start + stepSize; f <= end; f += stepSize) + { + Vector3 v = EvaluatePosition(f); + float t = p.ClosestPointOnSegment(v0, v); + float d = Vector3.SqrMagnitude(p - Vector3.Lerp(v0, v, t)); + if (d < bestDistance) + { + bestDistance = d; + bestPos = f - (1 - t) * stepSize; + } + v0 = v; + } + start = bestPos - stepSize; + end = bestPos + stepSize; + stepSize /= stepsPerSegment; + } + return bestPos; + } + + /// How to interpret the Path Position + public enum PositionUnits + { + /// Use PathPosition units, where 0 is first waypoint, 1 is second waypoint, etc + PathUnits, + /// Use Distance Along Path. Path will be sampled according to its Resolution + /// setting, and a distance lookup table will be cached internally + Distance + } + + /// Get the minimum value, for the given unity type + /// The uniot type + /// The minimum allowable value for this path + public float MinUnit(PositionUnits units) + { + return units == PositionUnits.Distance ? 0 : MinPos; + } + + /// Get the maximum value, for the given unity type + /// The uniot type + /// The maximum allowable value for this path + public float MaxUnit(PositionUnits units) + { + return units == PositionUnits.Distance ? PathLength : MaxPos; + } + + /// Normalize the unit, so that it lies between MinUmit and MaxUnit + /// The value to be normalized + /// The unit type + /// The normalized value of pos, between MinUnit and MaxUnit + public virtual float NormalizeUnit(float pos, PositionUnits units) + { + if (units == PositionUnits.Distance) + return NormalizePathDistance(pos); + return NormalizePos(pos); + } + + /// Get a worldspace position of a point along the path + /// Postion along the path. Need not be normalized. + /// The unit to use when interpreting the value of pos. + /// World-space position of the point along at path at pos + public Vector3 EvaluatePositionAtUnit(float pos, PositionUnits units) + { + if (units == PositionUnits.Distance) + pos = GetPathPositionFromDistance(pos); + return EvaluatePosition(pos); + } + + /// Get the tangent of the curve at a point along the path. + /// Postion along the path. Need not be normalized. + /// The unit to use when interpreting the value of pos. + /// World-space direction of the path tangent. + /// Length of the vector represents the tangent strength + public Vector3 EvaluateTangentAtUnit(float pos, PositionUnits units) + { + if (units == PositionUnits.Distance) + pos = GetPathPositionFromDistance(pos); + return EvaluateTangent(pos); + } + + /// Get the orientation the curve at a point along the path. + /// Postion along the path. Need not be normalized. + /// The unit to use when interpreting the value of pos. + /// World-space orientation of the path + public Quaternion EvaluateOrientationAtUnit(float pos, PositionUnits units) + { + if (units == PositionUnits.Distance) + pos = GetPathPositionFromDistance(pos); + return EvaluateOrientation(pos); + } + + /// When calculating the distance cache, sample the path this many + /// times between points + public abstract int DistanceCacheSampleStepsPerSegment { get; } + + /// Call this if the path changes in such a way as to affect distances + /// or other cached path elements + public virtual void InvalidateDistanceCache() + { + m_DistanceToPos = null; + m_PosToDistance = null; + m_CachedSampleSteps = 0; + m_PathLength = 0; + } + + /// See whether the distance cache is valid. If it's not valid, + /// then any call to GetPathLength() or GetPathPositionFromDistance() will + /// trigger a potentially costly regeneration of the path distance cache + /// The number of steps to take between path points + /// Whether the cache is valid for this sampling rate + public bool DistanceCacheIsValid() + { + return (MaxPos == MinPos) + || (m_DistanceToPos != null && m_PosToDistance != null + && m_CachedSampleSteps == DistanceCacheSampleStepsPerSegment + && m_CachedSampleSteps > 0); + } + + /// Get the length of the path in distance units. + /// If the distance cache is not valid, then calling this will + /// trigger a potentially costly regeneration of the path distance cache + /// The length of the path in distance units, when sampled at this rate + public float PathLength + { + get + { + if (DistanceCacheSampleStepsPerSegment < 1) + return 0; + if (!DistanceCacheIsValid()) + ResamplePath(DistanceCacheSampleStepsPerSegment); + return m_PathLength; + } + } + + /// Normalize a distance along the path based on the path length. + /// If the distance cache is not valid, then calling this will + /// trigger a potentially costly regeneration of the path distance cache + /// The distance to normalize + /// The normalized distance, ranging from 0 to path length + public float NormalizePathDistance(float distance) + { + float length = PathLength; + if (length < Vector3.kEpsilon) + return 0; + if (Looped) + { + distance = distance % length; + if (distance < 0) + distance += length; + } + return Mathf.Clamp(distance, 0, length); + } + + /// Get the path position (in path units) corresponding to this distance along the path. + /// If the distance cache is not valid, then calling this will + /// trigger a potentially costly regeneration of the path distance cache + /// The length of the path in distance units, when sampled at this rate + public float GetPathPositionFromDistance(float distance) + { + if (DistanceCacheSampleStepsPerSegment < 1 || PathLength < UnityVectorExtensions.Epsilon) + return MinPos; + distance = NormalizePathDistance(distance); + float d = distance / m_cachedDistanceStepSize; + int i = Mathf.FloorToInt(d); + if (i >= m_DistanceToPos.Length-1) + return MaxPos; + float t = d - (float)i; + return MinPos + Mathf.Lerp(m_DistanceToPos[i], m_DistanceToPos[i+1], t); + } + + /// Get the path position (in path units) corresponding to this distance along the path. + /// If the distance cache is not valid, then calling this will + /// trigger a potentially costly regeneration of the path distance cache + /// The length of the path in distance units, when sampled at this rate + public float GetPathDistanceFromPosition(float pos) + { + if (DistanceCacheSampleStepsPerSegment < 1 || PathLength < UnityVectorExtensions.Epsilon) + return 0; + pos = NormalizePos(pos); + float d = pos / m_cachedPosStepSize; + int i = Mathf.FloorToInt(d); + if (i >= m_PosToDistance.Length-1) + return m_PathLength; + float t = d - (float)i; + return Mathf.Lerp(m_PosToDistance[i], m_PosToDistance[i+1], t); + } + + private float[] m_DistanceToPos; + private float[] m_PosToDistance; + private int m_CachedSampleSteps; + private float m_PathLength; + private float m_cachedPosStepSize; + private float m_cachedDistanceStepSize; + + private void ResamplePath(int stepsPerSegment) + { + InvalidateDistanceCache(); + + float minPos = MinPos; + float maxPos = MaxPos; + float stepSize = 1f / Mathf.Max(1, stepsPerSegment); + + // Sample the positions + int numKeys = Mathf.RoundToInt((maxPos - minPos) / stepSize) + 1; + m_PosToDistance = new float[numKeys]; + m_CachedSampleSteps = stepsPerSegment; + m_cachedPosStepSize = stepSize; + + Vector3 p0 = EvaluatePosition(0); + m_PosToDistance[0] = 0; + float pos = minPos; + for (int i = 1; i < numKeys; ++i) + { + pos += stepSize; + Vector3 p = EvaluatePosition(pos); + float d = Vector3.Distance(p0, p); + m_PathLength += d; + p0 = p; + m_PosToDistance[i] = m_PathLength; + } + + // Resample the distances + m_DistanceToPos = new float[numKeys]; + m_DistanceToPos[0] = 0; + if (numKeys > 1) + { + stepSize = m_PathLength / (numKeys - 1); + m_cachedDistanceStepSize = stepSize; + float distance = 0; + int posIndex = 1; + for (int i = 1; i < numKeys; ++i) + { + distance += stepSize; + float d = m_PosToDistance[posIndex]; + while (d < distance && posIndex < numKeys-1) + d = m_PosToDistance[++posIndex]; + float d0 = m_PosToDistance[posIndex-1]; + float delta = d - d0; + float t = (distance - d0) / delta; + m_DistanceToPos[i] = m_cachedPosStepSize * (t + posIndex - 1); + } + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachinePathBase.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/CinemachinePathBase.cs.meta new file mode 100644 index 0000000..518e34c --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachinePathBase.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a73149a4b6c41d741bc5e4e3b7711c0d +timeCreated: 1494359378 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachinePropertyAttribute.cs b/Assets/Cinemachine/Base/Runtime/Core/CinemachinePropertyAttribute.cs new file mode 100644 index 0000000..3d64092 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachinePropertyAttribute.cs @@ -0,0 +1,70 @@ +using UnityEngine; + +namespace Cinemachine +{ + /// + /// Property applied to LensSettings. Used for custom drawing in the inspector. + /// + public sealed class LensSettingsPropertyAttribute : PropertyAttribute + { + } + + /// + /// Property applied to CinemachineBlendDefinition. Used for custom drawing in the inspector. + /// + public sealed class CinemachineBlendDefinitionPropertyAttribute : PropertyAttribute + { + } + + /// + /// Invoke play-mode-save for a class. This class's fields will be scanned + /// upon exiting play mode, and its property values will be applied to the scene object. + /// This is a stopgap measure that will become obsolete once Unity implements + /// play-mode-save in a more general way. + /// + public sealed class SaveDuringPlayAttribute : System.Attribute + { + } + + /// + /// Suppresses play-mode-save for a field. Use it if the calsee has [SaveDuringPlay] + /// attribute but there are fields in the class that shouldn't be saved. + /// + public sealed class NoSaveDuringPlayAttribute : PropertyAttribute + { + } + + /// Property field is a Tag. + public sealed class TagFieldAttribute : PropertyAttribute + { + } + + /// + /// Atrtribute to control the automatic generation of documentation. + /// + [DocumentationSorting(0f, DocumentationSortingAttribute.Level.Undoc)] + public sealed class DocumentationSortingAttribute : System.Attribute + { + /// Refinement level of the documentation + public enum Level + { + /// Type is excluded from documentation + Undoc, + /// Type is documented in the API reference + API, + /// Type is documented in the highly-refined User Manual + UserRef + }; + /// Where this type appears in the manual. Smaller number sort earlier. + public float SortOrder { get; private set; } + /// Refinement level of the documentation. The more refined, the more is excluded. + public Level Category { get; private set; } + + /// Contructor with specific values + public DocumentationSortingAttribute(float sortOrder, Level category) + { + SortOrder = sortOrder; + Category = category; + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachinePropertyAttribute.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/CinemachinePropertyAttribute.cs.meta new file mode 100644 index 0000000..81dd691 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachinePropertyAttribute.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2c760cb7073c57e44959f36cbed8ed39 +timeCreated: 1486510400 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineVirtualCameraBase.cs b/Assets/Cinemachine/Base/Runtime/Core/CinemachineVirtualCameraBase.cs new file mode 100644 index 0000000..5057343 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineVirtualCameraBase.cs @@ -0,0 +1,360 @@ +using System; +using UnityEngine; + +namespace Cinemachine +{ + /// + /// Base class for a Monobehaviour that represents a Virtual Camera within the Unity scene. + /// + /// This is intended to be attached to an empty Transform GameObject. + /// Inherited classes can be either standalone virtual cameras such + /// as CinemachineVirtualCamera, or meta-cameras such as + /// CinemachineClearShot or CinemachineFreeLook. + /// + /// A CinemachineVirtualCameraBase exposes a Priority property. When the behaviour is + /// enabled in the game, the Virtual Camera is automatically placed in a queue + /// maintained by the static CinemachineCore singleton. + /// The queue is sorted by priority. When a Unity camera is equipped with a + /// CinemachineBrain behaviour, the brain will choose the camera + /// at the head of the queue. If you have multiple Unity cameras with CinemachineBrain + /// behaviours (say in a split-screen context), then you can filter the queue by + /// setting the culling flags on the virtual cameras. The culling mask of the + /// Unity Camera will then act as a filter for the brain. Apart from this, + /// there is nothing that prevents a virtual camera from controlling multiple + /// Unity cameras simultaneously. + /// + [SaveDuringPlay] + public abstract class CinemachineVirtualCameraBase : MonoBehaviour, ICinemachineCamera + { + /// This is deprecated. It is here to support the soon-to-be-removed + /// Cinemachine Debugger in the Editor. + [HideInInspector, NoSaveDuringPlay] + public Action CinemachineGUIDebuggerCallback = null; + + /// Inspector control - Use for hiding sections of the Inspector UI. + [HideInInspector, SerializeField, NoSaveDuringPlay] + public string[] m_ExcludedPropertiesInInspector = new string[] { "m_Script" }; + + /// Inspector control - Use for enabling sections of the Inspector UI. + [HideInInspector, SerializeField, NoSaveDuringPlay] + public CinemachineCore.Stage[] m_LockStageInInspector; + + /// Version that was last streamed, for upgrading legacy + public int ValidatingStreamVersion + { + get { return m_OnValidateCalled ? m_ValidatingStreamVersion : CinemachineCore.kStreamingVersion; } + private set { m_ValidatingStreamVersion = value; } + } + private int m_ValidatingStreamVersion = 0; + private bool m_OnValidateCalled = false; + + [HideInInspector, SerializeField, NoSaveDuringPlay] + private int m_StreamingVersion; + + /// The priority will determine which camera becomes active based on the + /// state of other cameras and this camera. Higher numbers have greater priority. + /// + [NoSaveDuringPlay] + [Tooltip("The priority will determine which camera becomes active based on the state of other cameras and this camera. Higher numbers have greater priority.")] + public int m_Priority = 10; + + /// + /// A delegate to hook into the state calculation pipeline. + /// This will be called after each pipeline stage, to allow others to hook into the pipeline. + /// See CinemachineCore.Stage. + /// + /// The delegate to call. + public virtual void AddPostPipelineStageHook(OnPostPipelineStageDelegate d) + { + OnPostPipelineStage -= d; + OnPostPipelineStage += d; + } + + /// Remove a Pipeline stage hook callback. + /// The delegate to remove. + public virtual void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + OnPostPipelineStage -= d; + } + + /// + /// A delegate to hook into the state calculation pipeline. + /// This will be called after each pipeline stage, to allow other + /// services to hook into the pipeline. + /// See CinemachineCore.Stage. + /// + /// Parameters: + /// + /// * CinemachineVirtualCameraBase vcam: the virtual camera being updated + /// * CinemachineCore.Stage stage: what stage in the pipeline has just been updated + /// * ref CameraState newState: the current state of the vcam + /// * float deltaTime: the frame timestep. Less than 0 means "don't consider the previous frame" + /// + public delegate void OnPostPipelineStageDelegate( + CinemachineVirtualCameraBase vcam, CinemachineCore.Stage stage, + ref CameraState newState, float deltaTime); + + /// + /// A delegate to hook into the state calculation pipeline. + /// Implementaion must be sure to call this after each pipeline stage, to allow + /// other services to hook into the pipeline. + /// See CinemachineCore.Stage. + /// + protected OnPostPipelineStageDelegate OnPostPipelineStage; + + /// + /// Invokes the PostPipelineStageDelegate for this camera, and up the hierarchy for all + /// parent cameras (if any). + /// + protected void InvokePostPipelineStageCallback( + CinemachineVirtualCameraBase vcam, CinemachineCore.Stage stage, + ref CameraState newState, float deltaTime) + { + if (OnPostPipelineStage != null) + OnPostPipelineStage(vcam, stage, ref newState, deltaTime); + CinemachineVirtualCameraBase parent = ParentCamera as CinemachineVirtualCameraBase; + if (parent != null) + parent.InvokePostPipelineStageCallback(vcam, stage, ref newState, deltaTime); + } + + /// Get the name of the Virtual Camera. Base implementation + /// returns the owner GameObject's name. + public string Name { get { return name; } } + + /// Gets a brief debug description of this virtual camera, for use when displayiong debug info + public virtual string Description { get { return ""; }} + + /// Get the Priority of the virtual camera. This determines its placement + /// in the CinemachineCore's queue of eligible shots. + public int Priority { get { return m_Priority; } set { m_Priority = value; } } + + /// The GameObject owner of the Virtual Camera behaviour. + public GameObject VirtualCameraGameObject + { + get + { + if (this == null) + return null; // object deleted + return gameObject; + } + } + + /// The CameraState object holds all of the information + /// necessary to position the Unity camera. It is the output of this class. + public abstract CameraState State { get; } + + /// Just returns self. + public virtual ICinemachineCamera LiveChildOrSelf { get { return this; } } + + /// Support for meta-virtual-cameras. This is the situation where a + /// virtual camera is in fact the public face of a private army of virtual cameras, which + /// it manages on its own. This method gets the VirtualCamera owner, if any. + /// Private armies are implemented as Transform children of the parent vcam. + public ICinemachineCamera ParentCamera + { + get + { + if (!mSlaveStatusUpdated || !Application.isPlaying) + UpdateSlaveStatus(); + return m_parentVcam; + } + } + + /// Check whether the vcam a live child of this camera. + /// This base class implementation always returns false. + /// The Virtual Camera to check + /// True if the vcam is currently actively influencing the state of this vcam + public virtual bool IsLiveChild(ICinemachineCamera vcam) { return false; } + + /// Get the LookAt target for the Aim component in the CinemachinePipeline. + public abstract Transform LookAt { get; set; } + + /// Get the Follow target for the Body component in the CinemachinePipeline. + public abstract Transform Follow { get; set; } + + /// Set this to force the next update to ignore deltaTime and reset itself + public bool PreviousStateIsValid + { + get + { + if (LookAt != m_previousLookAtTarget) + { + m_previousLookAtTarget = LookAt; + m_previousStateIsValid = false; + } + if (Follow != m_previousFollowTarget) + { + m_previousFollowTarget = Follow; + m_previousStateIsValid = false; + } + return m_previousStateIsValid; + } + set + { + m_previousStateIsValid = value; + } + } + private bool m_previousStateIsValid; + private Transform m_previousLookAtTarget; + private Transform m_previousFollowTarget; + + + /// Called by CinemachineCore at designated update time + /// so the vcam can position itself and track its targets. + /// Do not call this method. Let the framework do it at the appropriate time + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than 0) + public abstract void UpdateCameraState(Vector3 worldUp, float deltaTime); + + /// Notification that this virtual camera is going live. + /// Base class implementationmust be called by any overridden method. + /// The camera being deactivated. May be null. + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than or equal to 0) + public virtual void OnTransitionFromCamera( + ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime) + { + if (!gameObject.activeInHierarchy) + PreviousStateIsValid = false; + } + + /// Base class implementation does nothing. + protected virtual void Start() + { + } + + /// Base class implementation removes the virtual camera from the priority queue. + protected virtual void OnDestroy() + { + CinemachineCore.Instance.RemoveActiveCamera(this); + } + + /// Enforce bounds for fields, when changed in inspector. + /// Call base class implementation at the beginning of overridden method. + /// After base method is called, ValidatingStreamVersion will be valid. + protected virtual void OnValidate() + { + m_OnValidateCalled = true; + ValidatingStreamVersion = m_StreamingVersion; + m_StreamingVersion = CinemachineCore.kStreamingVersion; + } + + /// Base class implementation adds the virtual camera from the priority queue. + protected virtual void OnEnable() + { + // Sanity check - if another vcam component is enabled, shut down + var vcamComponents = GetComponents(); + for (int i = 0; i < vcamComponents.Length; ++i) + { + if (vcamComponents[i].enabled && vcamComponents[i] != this) + { + Debug.LogError(Name + + " has multiple CinemachineVirtualCameraBase-derived components. Disabling " + + GetType().Name + "."); + enabled = false; + } + } + UpdateSlaveStatus(); + UpdateVcamPoolStatus(); // Add to queue + PreviousStateIsValid = false; + } + + /// Base class implementation makes sure the priority queue remains up-to-date. + protected virtual void OnDisable() + { + UpdateVcamPoolStatus(); // Remove from queue + } + + /// Base class implementation makes sure the priority queue remains up-to-date. + protected virtual void Update() + { + if (m_Priority != m_QueuePriority) + UpdateVcamPoolStatus(); + } + + /// Base class implementation makes sure the priority queue remains up-to-date. + protected virtual void OnTransformParentChanged() + { + UpdateSlaveStatus(); + UpdateVcamPoolStatus(); + } + +#if UNITY_EDITOR + /// Support for the deprecated CinemachineDebugger. + protected virtual void OnGUI() + { + if (CinemachineGUIDebuggerCallback != null) + CinemachineGUIDebuggerCallback(); + } +#endif + private bool mSlaveStatusUpdated = false; + private CinemachineVirtualCameraBase m_parentVcam = null; + + private void UpdateSlaveStatus() + { + mSlaveStatusUpdated = true; + m_parentVcam = null; + Transform p = transform.parent; + if (p != null) + m_parentVcam = p.GetComponent(); + } + + /// Returns this vcam's LookAt target, or if that is null, will retrun + /// the parent vcam's LookAt target. + /// This vcam's LookAt value. + /// The same value, or the parent's if null and a parent exists. + protected Transform ResolveLookAt(Transform localLookAt) + { + Transform lookAt = localLookAt; + if (lookAt == null && ParentCamera != null) + lookAt = ParentCamera.LookAt; // Parent provides default + return lookAt; + } + + /// Returns this vcam's Follow target, or if that is null, will retrun + /// the parent vcam's Follow target. + /// This vcam's Follow value. + /// The same value, or the parent's if null and a parent exists. + protected Transform ResolveFollow(Transform localFollow) + { + Transform follow = localFollow; + if (follow == null && ParentCamera != null) + follow = ParentCamera.Follow; // Parent provides default + return follow; + } + + private int m_QueuePriority = int.MaxValue; + private void UpdateVcamPoolStatus() + { + m_QueuePriority = int.MaxValue; + CinemachineCore.Instance.RemoveActiveCamera(this); + CinemachineCore.Instance.RemoveChildCamera(this); + if (m_parentVcam == null) + { + if (isActiveAndEnabled) + { + CinemachineCore.Instance.AddActiveCamera(this); + m_QueuePriority = m_Priority; + } + } + else + { + if (isActiveAndEnabled) + CinemachineCore.Instance.AddChildCamera(this); + } + } + + /// When multiple virtual cameras have the highest priority, there is + /// sometimes the need to push one to the top, making it the current Live camera if + /// it shares the highest priority in the queue with its peers. + /// + /// This happens automatically when a + /// new vcam is enabled: the most recent one goes to the top of the priority subqueue. + /// Use this method to push a vcam to the top of its priority peers. + /// If it and its peers share the highest priority, then this vcam will become Live. + public void MoveToTopOfPrioritySubqueue() + { + UpdateVcamPoolStatus(); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/CinemachineVirtualCameraBase.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/CinemachineVirtualCameraBase.cs.meta new file mode 100644 index 0000000..16f6df8 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/CinemachineVirtualCameraBase.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 15ebf04de67923d41a36c21e1fc63718 +timeCreated: 1488314898 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/GaussianFilter.cs b/Assets/Cinemachine/Base/Runtime/Core/GaussianFilter.cs new file mode 100644 index 0000000..8a1e5f7 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/GaussianFilter.cs @@ -0,0 +1,140 @@ +using System; +using UnityEngine; + +namespace Cinemachine.Utility +{ + internal abstract class GaussianWindow1d + { + protected T[] mData; + protected float[] mKernel; + protected float mKernelSum; + protected int mCurrentPos; + + public float Sigma { get; private set; } // Filter strength: bigger numbers are stronger. 0.5 is minimal. + public int KernelSize { get { return mKernel.Length; } } + + void GenerateKernel(float sigma, int maxKernelRadius) + { + // Weight is close to 0 at a distance of sigma*3, so let's just cut it off a little early + int kernelRadius = Math.Min(maxKernelRadius, Mathf.FloorToInt(Mathf.Abs(sigma) * 2.5f)); + mKernel = new float[2 * kernelRadius + 1]; + mKernelSum = 0; + if (kernelRadius == 0) + mKernelSum = mKernel[0] = 1; + else for (int i = -kernelRadius; i <= kernelRadius; ++i) + { + mKernel[i + kernelRadius] + = (float)(Math.Exp(-(i * i) / (2 * sigma * sigma)) / Math.Sqrt(2.0 * Math.PI * sigma)); + mKernelSum += mKernel[i + kernelRadius]; + } + Sigma = sigma; + } + + protected abstract T Compute(int windowPos); + + public GaussianWindow1d(float sigma, int maxKernelRadius = 10) + { + GenerateKernel(sigma, maxKernelRadius); + mCurrentPos = 0; + } + + public void Reset() { mData = null; } + + public bool IsEmpty() { return mData == null; } + + public void AddValue(T v) + { + if (mData == null) + { + mData = new T[KernelSize]; + for (int i = 0; i < KernelSize; ++i) + mData[i] = v; + mCurrentPos = Mathf.Min(1, KernelSize-1); + } + mData[mCurrentPos] = v; + if (++mCurrentPos == KernelSize) + mCurrentPos = 0; + } + + public T Filter(T v) + { + if (KernelSize < 3) + return v; + AddValue(v); + return Value(); + } + + /// Returned value will be kernelRadius old + public T Value() { return Compute(mCurrentPos); } + } + + internal class GaussianWindow1D_Vector3 : GaussianWindow1d + { + public GaussianWindow1D_Vector3(float sigma, int maxKernelRadius = 10) + : base(sigma, maxKernelRadius) {} + + protected override Vector3 Compute(int windowPos) + { + Vector3 sum = Vector3.zero; + for (int i = 0; i < KernelSize; ++i) + { + sum += mData[windowPos] * mKernel[i]; + if (++windowPos == KernelSize) + windowPos = 0; + } + return sum / mKernelSum; + } + } + + internal class GaussianWindow1D_Quaternion : GaussianWindow1d + { + public GaussianWindow1D_Quaternion(float sigma, int maxKernelRadius = 10) + : base(sigma, maxKernelRadius) {} + protected override Quaternion Compute(int windowPos) + { + Quaternion sum = new Quaternion(0, 0, 0, 0); + Quaternion q = mData[mCurrentPos]; + Quaternion qInverse = Quaternion.Inverse(q); + for (int i = 0; i < KernelSize; ++i) + { + // Make sure the quaternion is in the same hemisphere, or averaging won't work + float scale = mKernel[i]; + Quaternion q2 = qInverse * mData[windowPos]; + if (Quaternion.Dot(Quaternion.identity, q2) < 0) + scale = -scale; + sum.x += q2.x * scale; + sum.y += q2.y * scale; + sum.z += q2.z * scale; + sum.w += q2.w * scale; + + if (++windowPos == KernelSize) + windowPos = 0; + } + return q * sum; + } + } + + internal class GaussianWindow1D_CameraRotation : GaussianWindow1d + { + public GaussianWindow1D_CameraRotation(float sigma, int maxKernelRadius = 10) + : base(sigma, maxKernelRadius) {} + + protected override Vector2 Compute(int windowPos) + { + Vector2 sum = Vector2.zero; + Vector2 v = mData[mCurrentPos]; + for (int i = 0; i < KernelSize; ++i) + { + Vector2 v2 = mData[windowPos] - v; + if (v2.y > 180f) + v2.y -= 360f; + if (v2.y < -180f) + v2.y += 360f; + sum += v2 * mKernel[i]; + if (++windowPos == KernelSize) + windowPos = 0; + } + return v + (sum / mKernelSum); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/GaussianFilter.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/GaussianFilter.cs.meta new file mode 100644 index 0000000..cd35138 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/GaussianFilter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 68839a4bf8790cd449d4043f5efb5aec +timeCreated: 1490719908 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/ICinemachineCamera.cs b/Assets/Cinemachine/Base/Runtime/Core/ICinemachineCamera.cs new file mode 100644 index 0000000..82e7af5 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/ICinemachineCamera.cs @@ -0,0 +1,81 @@ +using UnityEngine; + +namespace Cinemachine +{ + /// + /// An abstract representation of a virtual camera which lives within the Unity scene + /// + public interface ICinemachineCamera + { + /// + /// Gets the name of this virtual camera. For use when deciding how to blend + /// to or from this camera + /// + string Name { get; } + + /// + /// Gets a brief debug description of this virtual camera, for use when displayiong debug info + /// + string Description { get; } + + /// + /// Gets the priority of this ICinemachineCamera. The virtual camera + /// will be inserted into the global priority stack based on this value. + /// + int Priority { get; set; } + + /// + /// The thing the camera wants to look at (aim). May be null. + /// + Transform LookAt { get; set; } + + /// + /// The thing the camera wants to follow (moving camera). May be null. + /// + Transform Follow { get; set; } + + /// + /// Camera state at the current time. + /// + CameraState State { get; } + + /// + /// Gets the virtual camera game attached to this class. + /// + GameObject VirtualCameraGameObject { get; } + + /// For cameras that implement child cameras, return the live child, + /// otherwise, just returns self. + ICinemachineCamera LiveChildOrSelf { get; } + + /// + /// For cameras that implement child cameras, returns the parent vcam, otherwise null. + /// + ICinemachineCamera ParentCamera { get; } + + /// Check whether the vcam is a live child of this camera. + /// The Virtual Camera to check + /// True if the vcam is currently actively influencing the state of this vcam + bool IsLiveChild(ICinemachineCamera vcam); + + /// + /// Updates this Cinemachine Camera. For an active camera this should be + /// called once and only once each frame. To guarantee this, you should never + /// call this method directly. Always use + /// CinemachineCore.UpdateVirtualCamera(ICinemachineCamera, float), which + /// has protection against multiple calls per frame. + /// + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than 0) + void UpdateCameraState(Vector3 worldUp, float deltaTime); + + /// + /// Notification that a new camera is being activated. This is sent to the + /// currently active camera. Both may be active simultaneously for a while, if blending. + /// + /// The camera being deactivated. May be null. + /// Default world Up, set by the CinemachineBrain + /// Delta time for time-based effects (ignore if less than 0) + void OnTransitionFromCamera(ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime); + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/ICinemachineCamera.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/ICinemachineCamera.cs.meta new file mode 100644 index 0000000..4296ec0 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/ICinemachineCamera.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2643ac9881a89594a80c242b565b34ec +timeCreated: 1484407000 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/ICinemachineComponent.cs b/Assets/Cinemachine/Base/Runtime/Core/ICinemachineComponent.cs new file mode 100644 index 0000000..d9249fd --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/ICinemachineComponent.cs @@ -0,0 +1,3 @@ +// This file is intentionally blank. +// If you were implementing ICinemachineComponent interface, please refactor to +// inherit from CinemachineComponentBase instead. diff --git a/Assets/Cinemachine/Base/Runtime/Core/ICinemachineComponent.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/ICinemachineComponent.cs.meta new file mode 100644 index 0000000..1e2bd3c --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/ICinemachineComponent.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9a53087ba28aaf145a184ea363108831 +timeCreated: 1510078351 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/LensSettings.cs b/Assets/Cinemachine/Base/Runtime/Core/LensSettings.cs new file mode 100644 index 0000000..c0686a6 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/LensSettings.cs @@ -0,0 +1,137 @@ +using UnityEngine; +using System; + +namespace Cinemachine +{ + /// + /// Describes the FOV and clip planes for a camera. This generally mirrors the Unity Camera's + /// lens settings, and will be used to drive the Unity camera when the vcam is active. + /// + [Serializable] + [DocumentationSorting(2, DocumentationSortingAttribute.Level.UserRef)] + public struct LensSettings + { + /// Default Lens Settings + public static LensSettings Default = new LensSettings(40f, 10, 0.1f, 5000f, 0, false, 1); + + /// + /// This is the camera view in vertical degrees. For cinematic people, a 50mm lens + /// on a super-35mm sensor would equal a 19.6 degree FOV + /// + [Range(1f, 179f)] + [Tooltip("This is the camera view in vertical degrees. For cinematic people, a 50mm lens on a super-35mm sensor would equal a 19.6 degree FOV")] + public float FieldOfView; + + /// + /// When using an orthographic camera, this defines the height, in world + /// co-ordinates, of the camera view. + /// + [Tooltip("When using an orthographic camera, this defines the half-height, in world coordinates, of the camera view.")] + public float OrthographicSize; + + /// + /// The near clip plane for this LensSettings + /// + [Tooltip("This defines the near region in the renderable range of the camera frustum. Raising this value will stop the game from drawing things near the camera, which can sometimes come in handy. Larger values will also increase your shadow resolution.")] + public float NearClipPlane; + + /// + /// The far clip plane for this LensSettings + /// + [Tooltip("This defines the far region of the renderable range of the camera frustum. Typically you want to set this value as low as possible without cutting off desired distant objects")] + public float FarClipPlane; + + /// + /// The dutch (tilt) to be applied to the camera. In degrees + /// + [Range(-180f, 180f)] + [Tooltip("Camera Z roll, or tilt, in degrees.")] + public float Dutch; + + /// + /// This is set every frame by the virtual camera, based on the value found in the + /// currently associated Unity camera + /// + internal bool Orthographic { get; set; } + + /// + /// This is set every frame by the virtual camera, based on the value + /// found in the currently associated Unity camera + /// + internal float Aspect { get; set; } + + /// + /// Creates a new LensSettings, copying the values from the + /// supplied Camera + /// + /// The Camera from which the FoV, near + /// and far clip planes will be copied. + public static LensSettings FromCamera(Camera fromCamera) + { + LensSettings lens = Default; + if (fromCamera != null) + { + lens.FieldOfView = fromCamera.fieldOfView; + lens.OrthographicSize = fromCamera.orthographicSize; + lens.NearClipPlane = fromCamera.nearClipPlane; + lens.FarClipPlane = fromCamera.farClipPlane; + lens.Orthographic = fromCamera.orthographic; + lens.Aspect = fromCamera.aspect; + } + return lens; + } + + /// + /// Explicit constructor for this LensSettings + /// + /// The Vertical field of view + /// If orthographic, this is the half-height of the screen + /// The near clip plane + /// The far clip plane + /// Camera roll, in degrees. This is applied at the end + /// Whether the lens is orthographic + /// The aspect ratio of the lens Width/height + /// after shot composition. + public LensSettings( + float fov, float orthographicSize, + float nearClip, float farClip, float dutch, + bool ortho, float aspect) : this() + { + FieldOfView = fov; + OrthographicSize = orthographicSize; + NearClipPlane = nearClip; + FarClipPlane = farClip; + Dutch = dutch; + Orthographic = ortho; + Aspect = aspect; + } + + /// + /// Linearly blends the fields of two LensSettings and returns the result + /// + /// The LensSettings to blend from + /// The LensSettings to blend to + /// The interpolation value. Internally clamped to the range [0,1] + /// Interpolated settings + public static LensSettings Lerp(LensSettings lensA, LensSettings lensB, float t) + { + t = Mathf.Clamp01(t); + LensSettings blendedLens = new LensSettings(); + blendedLens.FarClipPlane = Mathf.Lerp(lensA.FarClipPlane, lensB.FarClipPlane, t); + blendedLens.NearClipPlane = Mathf.Lerp(lensA.NearClipPlane, lensB.NearClipPlane, t); + blendedLens.FieldOfView = Mathf.Lerp(lensA.FieldOfView, lensB.FieldOfView, t); + blendedLens.OrthographicSize = Mathf.Lerp(lensA.OrthographicSize, lensB.OrthographicSize, t); + blendedLens.Dutch = Mathf.Lerp(lensA.Dutch, lensB.Dutch, t); + blendedLens.Aspect = Mathf.Lerp(lensA.Aspect, lensB.Aspect, t); + blendedLens.Orthographic = lensA.Orthographic && lensB.Orthographic; + return blendedLens; + } + + /// Make sure lens settings are sane. Call this from OnValidate(). + public void Validate() + { + NearClipPlane = Mathf.Max(NearClipPlane, 0.01f); + FarClipPlane = Mathf.Max(FarClipPlane, NearClipPlane + 0.01f); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/LensSettings.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/LensSettings.cs.meta new file mode 100644 index 0000000..747d7be --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/LensSettings.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5778d22ca832d9f47b5e73a8c5fe78a2 +timeCreated: 1481654955 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/NoiseSettings.cs b/Assets/Cinemachine/Base/Runtime/Core/NoiseSettings.cs new file mode 100644 index 0000000..424d809 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/NoiseSettings.cs @@ -0,0 +1,82 @@ +using UnityEngine; +using System; + +namespace Cinemachine +{ + /// + /// This is an asset that defines a noise profile. A noise profile is the + /// shape of the noise as a function of time. You can build arbitrarily complex shapes by + /// combining different base perlin noise frequencies at different amplitudes. + /// + /// The frequencies and amplitudes should be chosen with care, to ensure an interesting + /// noise quality that is not obviously repetitive. + /// + /// As a mathematical side-note, any arbitrary periodic curve can be broken down into a + /// series of fixed-amplitude sine-waves added together. This is called fourier decomposition, + /// and is the basis of much signal processing. It doesn't really have much to do with this + /// asset, but it's super interesting! + /// + [DocumentationSorting(9, DocumentationSortingAttribute.Level.UserRef)] + public sealed class NoiseSettings : ScriptableObject + { + /// + /// Describes the behaviour for a channel of noise + /// + [DocumentationSorting(9.1f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public struct NoiseParams + { + /// The amplitude of the noise for this channel. Larger numbers vibrate higher + [Tooltip("The amplitude of the noise for this channel. Larger numbers vibrate higher.")] + public float Amplitude; + /// The frequency of noise for this channel. Higher magnitudes vibrate faster + [Tooltip("The frequency of noise for this channel. Higher magnitudes vibrate faster.")] + public float Frequency; + } + + /// + /// Contains the behaviour of noise for the noise module for all 3 cardinal axes of the camera + /// + [DocumentationSorting(9.2f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public struct TransformNoiseParams + { + /// Noise definition for X-axis + [Tooltip("Noise definition for X-axis")] + public NoiseParams X; + /// Noise definition for Y-axis + [Tooltip("Noise definition for Y-axis")] + public NoiseParams Y; + /// Noise definition for Z-axis + [Tooltip("Noise definition for Z-axis")] + public NoiseParams Z; + } + + [SerializeField] + [Tooltip("These are the noise channels for the virtual camera's position. Convincing noise setups typically mix low, medium and high frequencies together, so start with a size of 3")] + private TransformNoiseParams[] m_Position = new TransformNoiseParams[0]; + + /// + /// Gets the array of positional noise channels for this NoiseSettings + /// + public TransformNoiseParams[] PositionNoise { get { return m_Position; } } + + [SerializeField] + [Tooltip("These are the noise channels for the virtual camera's orientation. Convincing noise setups typically mix low, medium and high frequencies together, so start with a size of 3")] + private TransformNoiseParams[] m_Orientation = new TransformNoiseParams[0]; + + /// + /// Gets the array of orientation noise channels for this NoiseSettings + /// + public TransformNoiseParams[] OrientationNoise { get { return m_Orientation; } } + + /// Clones the contents of the other asset into this one + public void CopyFrom(NoiseSettings other) + { + m_Position = new TransformNoiseParams[other.m_Position.Length]; + other.m_Position.CopyTo(m_Position, 0); + m_Orientation = new TransformNoiseParams[other.m_Orientation.Length]; + other.m_Orientation.CopyTo(m_Orientation, 0); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/NoiseSettings.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/NoiseSettings.cs.meta new file mode 100644 index 0000000..70afde9 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/NoiseSettings.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b7f59e54f2bfd184b9dd451a678d089b +timeCreated: 1481654957 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/Predictor.cs b/Assets/Cinemachine/Base/Runtime/Core/Predictor.cs new file mode 100644 index 0000000..8b5c898 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/Predictor.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Cinemachine.Utility +{ + internal class PositionPredictor + { + Vector3 m_Position; + + const float kSmoothingDefault = 10; + float mSmoothing = kSmoothingDefault; + public float Smoothing + { + get { return mSmoothing; } + set + { + if (value != mSmoothing) + { + mSmoothing = value; + int maxRadius = Mathf.Max(10, Mathf.FloorToInt(value * 1.5f)); + m_Velocity = new GaussianWindow1D_Vector3(mSmoothing, maxRadius); + m_Accel = new GaussianWindow1D_Vector3(mSmoothing, maxRadius); + } + } + } + + GaussianWindow1D_Vector3 m_Velocity = new GaussianWindow1D_Vector3(kSmoothingDefault); + GaussianWindow1D_Vector3 m_Accel = new GaussianWindow1D_Vector3(kSmoothingDefault); + + public bool IsEmpty { get { return m_Velocity.IsEmpty(); } } + + public void Reset() + { + m_Velocity.Reset(); + m_Accel.Reset(); + } + + public void AddPosition(Vector3 pos) + { + if (IsEmpty) + m_Velocity.AddValue(Vector3.zero); + else + { + Vector3 vel = m_Velocity.Value(); + Vector3 vel2 = (pos - m_Position) / Time.deltaTime; + m_Velocity.AddValue(vel2); + m_Accel.AddValue(vel2 - vel); + } + m_Position = pos; + } + + public Vector3 PredictPosition(float lookaheadTime) + { + int numSteps = Mathf.Min(Mathf.RoundToInt(lookaheadTime / Time.deltaTime), 6); + float dt = lookaheadTime / numSteps; + Vector3 pos = m_Position; + Vector3 vel = m_Velocity.IsEmpty() ? Vector3.zero : m_Velocity.Value(); + Vector3 accel = m_Accel.IsEmpty() ? Vector3.zero : m_Accel.Value(); + for (int i = 0; i < numSteps; ++i) + { + pos += vel * dt; + Vector3 vel2 = vel + (accel * dt); + accel = Quaternion.FromToRotation(vel, vel2) * accel; + vel = vel2; + } + return pos; + } + } + + /// Utility to perform realistic damping of float or Vector3 values. + /// The algorithm is based on exponentially decaying the delta until only + /// a negligible amount remains. + public static class Damper + { + const float Epsilon = UnityVectorExtensions.Epsilon; + + // Get the decay constant that would leave a given residual after a given time + static float DecayConstant(float time, float residual) + { + return Mathf.Log(1f / residual) / time; + } + + // Exponential decay: decay a given quantity opver a period of time + static float Decay(float initial, float decayConstant, float deltaTime) + { + return initial / Mathf.Exp(decayConstant * deltaTime); + } + + /// Standard residual + public const float kNegligibleResidual = 0.01f; + + /// Get a damped version of a quantity. This is the portion of the + /// quantity that will take effect over the given time. + /// The amount that will be damped + /// The rate of damping. This is the time it would + /// take to reduce the original amount to a negligible percentage + /// The time over which to damp + /// The damped amount. This will be the original amount scaled by + /// a value between 0 and 1. + public static float Damp(float initial, float dampTime, float deltaTime) + { + if (dampTime < Epsilon || Mathf.Abs(initial) < Epsilon) + return initial; + if (deltaTime < Epsilon) + return 0; + return initial - Decay( + initial, DecayConstant(dampTime, kNegligibleResidual), deltaTime); + } + + /// Get a damped version of a quantity. This is the portion of the + /// quantity that will take effect over the given time. + /// The amount that will be damped + /// The rate of damping. This is the time it would + /// take to reduce the original amount to a negligible percentage + /// The time over which to damp + /// The damped amount. This will be the original amount scaled by + /// a value between 0 and 1. + public static Vector3 Damp(Vector3 initial, Vector3 dampTime, float deltaTime) + { + for (int i = 0; i < 3; ++i) + initial[i] = Damp(initial[i], dampTime[i], deltaTime); + return initial; + } + + /// Get a damped version of a quantity. This is the portion of the + /// quantity that will take effect over the given time. + /// The amount that will be damped + /// The rate of damping. This is the time it would + /// take to reduce the original amount to a negligible percentage + /// The time over which to damp + /// The damped amount. This will be the original amount scaled by + /// a value between 0 and 1. + public static Vector3 Damp(Vector3 initial, float dampTime, float deltaTime) + { + for (int i = 0; i < 3; ++i) + initial[i] = Damp(initial[i], dampTime, deltaTime); + return initial; + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/Predictor.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/Predictor.cs.meta new file mode 100644 index 0000000..ddbc47d --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/Predictor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6cef82e891a45884fb2b70604b0f8c29 +timeCreated: 1505225008 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/ReflectionHelpers.cs b/Assets/Cinemachine/Base/Runtime/Core/ReflectionHelpers.cs new file mode 100644 index 0000000..ca7a3e0 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/ReflectionHelpers.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text; + +namespace Cinemachine.Utility +{ + /// An ad-hoc collection of helpers for reflection, used by Cinemachine + /// or its editor tools in various places + [DocumentationSorting(0, DocumentationSortingAttribute.Level.Undoc)] + public static class ReflectionHelpers + { + /// Copy the fields from one object to another + /// The source object to copy from + /// The destination object to copy to + /// The mask to filter the attributes. + /// Only those fields that get caught in the filter will be copied + public static void CopyFields( + Object src, Object dst, + BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) + { + if (src != null && dst != null) + { + Type type = src.GetType(); + FieldInfo[] fields = type.GetFields(bindingAttr); + for (int i = 0; i < fields.Length; ++i) + if (!fields[i].IsStatic) + fields[i].SetValue(dst, fields[i].GetValue(src)); + } + } + +#if UNITY_EDITOR + /// Search the assembly for all types that match a predicate + /// The assembly to search + /// The type to look for + /// A list of types found in the assembly that inherit from the predicate + public static IEnumerable GetTypesInAssembly( + Assembly assembly, Predicate predicate) + { + if (assembly == null) + return null; + + Type[] types = new Type[0]; + try + { + types = assembly.GetTypes(); + } + catch (Exception) + { + // Can't load the types in this assembly + } + types = (from t in types + where t != null && predicate(t) + select t).ToArray(); + return types; + } + + /// Get a type from a name + /// The name of the type to search for + /// The type matching the name, or null if not found + public static Type GetTypeInAllLoadedAssemblies(string typeName) + { + foreach (Type type in GetTypesInAllLoadedAssemblies(t => t.Name == typeName)) + return type; + return null; + } + + /// Search all assemblies for all types that match a predicate + /// The type to look for + /// A list of types found in the assembly that inherit from the predicate + public static IEnumerable GetTypesInAllLoadedAssemblies(Predicate predicate) + { + Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); + List foundTypes = new List(100); + foreach (Assembly assembly in assemblies) + { + foreach (Type foundType in GetTypesInAssembly(assembly, predicate)) + foundTypes.Add(foundType); + } + return foundTypes; + } + + /// call GetTypesInAssembly() for all assemblies that match a predicate + /// Which assemblies to search + /// What type to look for + public static IEnumerable GetTypesInLoadedAssemblies( + Predicate assemblyPredicate, Predicate predicate) + { + Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); + assemblies = assemblies.Where((Assembly assembly) + => { return assemblyPredicate(assembly); }).OrderBy((Assembly ass) + => { return ass.FullName; }).ToArray(); + + List foundTypes = new List(100); + foreach (Assembly assembly in assemblies) + { + foreach (Type foundType in GetTypesInAssembly(assembly, predicate)) + foundTypes.Add(foundType); + } + + return foundTypes; + } + + public static bool TypeIsDefined(string fullname) + { + return (from assembly in AppDomain.CurrentDomain.GetAssemblies() + from type in assembly.GetTypes() + where type.FullName == fullname + select type).Count() > 0; + } +#endif + + /// Cheater extension to access internal field of an object + /// The type of the field + /// The object to access + /// The string name of the field to access + /// The value of the field in the objects + public static T AccessInternalField(this Type type, object obj, string memberName) + { + if (string.IsNullOrEmpty(memberName) || (type == null)) + return default(T); + + BindingFlags bindingFlags = BindingFlags.NonPublic; + if (obj != null) + bindingFlags |= BindingFlags.Instance; + else + bindingFlags |= BindingFlags.Static; + + FieldInfo field = type.GetField(memberName, bindingFlags); + if ((field != null) && (field.FieldType == typeof(T))) + return (T)field.GetValue(obj); + else + return default(T); + } + + /// Get the object owner of a field. This method processes + /// the '.' separator to get from the object that owns the compound field + /// to the object that owns the leaf field + /// The name of the field, which may contain '.' separators + /// the owner of the compound field + public static object GetParentObject(string path, object obj) + { + var fields = path.Split('.'); + if (fields.Length == 1) + return obj; + + var info = obj.GetType().GetField( + fields[0], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + obj = info.GetValue(obj); + + return GetParentObject(string.Join(".", fields, 1, fields.Length - 1), obj); + } + + /// Returns a string path from an expression - mostly used to retrieve serialized properties + /// without hardcoding the field path. Safer, and allows for proper refactoring. + public static string GetFieldPath(Expression> expr) + { + MemberExpression me; + switch (expr.Body.NodeType) + { + case ExpressionType.MemberAccess: + me = expr.Body as MemberExpression; + break; + default: + throw new InvalidOperationException(); + } + + var members = new List(); + while (me != null) + { + members.Add(me.Member.Name); + me = me.Expression as MemberExpression; + } + + var sb = new StringBuilder(); + for (int i = members.Count - 1; i >= 0; i--) + { + sb.Append(members[i]); + if (i > 0) sb.Append('.'); + } + return sb.ToString(); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/ReflectionHelpers.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/ReflectionHelpers.cs.meta new file mode 100644 index 0000000..7cb3794 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/ReflectionHelpers.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8986fa27e90db314d8a3359520e7fd1a +timeCreated: 1487370732 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/SplineHelpers.cs b/Assets/Cinemachine/Base/Runtime/Core/SplineHelpers.cs new file mode 100644 index 0000000..8a7d29e --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/SplineHelpers.cs @@ -0,0 +1,137 @@ +using UnityEngine; + +namespace Cinemachine.Utility +{ + internal static class SplineHelpers + { + public static Vector3 Bezier3( + float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) + { + t = Mathf.Clamp01(t); + float d = 1f - t; + return d * d * d * p0 + 3f * d * d * t * p1 + + 3f * d * t * t * p2 + t * t * t * p3; + } + + public static Vector3 BezierTangent3( + float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) + { + t = Mathf.Clamp01(t); + return (-3f * p0 + 9f * p1 - 9f * p2 + 3f * p3) * t * t + + (6f * p0 - 12f * p1 + 6f * p2) * t + - 3f * p0 + 3f * p1; + } + + public static float Bezier1(float t, float p0, float p1, float p2, float p3) + { + t = Mathf.Clamp01(t); + float d = 1f - t; + return d * d * d * p0 + 3f * d * d * t * p1 + + 3f * d * t * t * p2 + t * t * t * p3; + } + + public static float BezierTangent1( + float t, float p0, float p1, float p2, float p3) + { + t = Mathf.Clamp01(t); + return (-3f * p0 + 9f * p1 - 9f * p2 + 3f * p3) * t * t + + (6f * p0 - 12f * p1 + 6f * p2) * t + - 3f * p0 + 3f * p1; + } + + public static void ComputeSmoothControlPoints( + ref Vector4[] knot, ref Vector4[] ctrl1, ref Vector4[] ctrl2) + { + int numPoints = knot.Length; + if (numPoints <= 2) + { + if (numPoints == 2) + { + ctrl1[0] = Vector4.Lerp(knot[0], knot[1], 0.33333f); + ctrl2[0] = Vector4.Lerp(knot[0], knot[1], 0.66666f); + } + else if (numPoints == 1) + ctrl1[0] = ctrl2[0] = knot[0]; + return; + } + + var a = new float[numPoints]; + var b = new float[numPoints]; + var c = new float[numPoints]; + var r = new float[numPoints]; + for (int axis = 0; axis < 4; ++axis) + { + int n = numPoints - 1; + + // Linear into the first segment + a[0] = 0; + b[0] = 2; + c[0] = 1; + r[0] = knot[0][axis] + 2 * knot[1][axis]; + + // Internal segments + for (int i = 1; i < n - 1; ++i) + { + a[i] = 1; + b[i] = 4; + c[i] = 1; + r[i] = 4 * knot[i][axis] + 2 * knot[i+1][axis]; + } + + // Linear out of the last segment + a[n - 1] = 2; + b[n - 1] = 7; + c[n - 1] = 0; + r[n - 1] = 8 * knot[n - 1][axis] + knot[n][axis]; + + // Solve with Thomas algorithm + for (int i = 1; i < n; ++i) + { + float m = a[i] / b[i-1]; + b[i] = b[i] - m * c[i-1]; + r[i] = r[i] - m * r[i-1]; + } + + // Compute ctrl1 + ctrl1[n-1][axis] = r[n-1] / b[n-1]; + for (int i = n - 2; i >= 0; --i) + ctrl1[i][axis] = (r[i] - c[i] * ctrl1[i + 1][axis]) / b[i]; + + // Compute ctrl2 from ctrl1 + for (int i = 0; i < n; i++) + ctrl2[i][axis] = 2 * knot[i + 1][axis] - ctrl1[i + 1][axis]; + ctrl2[n - 1][axis] = 0.5f * (knot[n][axis] + ctrl1[n - 1][axis]); + } + } + + public static void ComputeSmoothControlPointsLooped( + ref Vector4[] knot, ref Vector4[] ctrl1, ref Vector4[] ctrl2) + { + int numPoints = knot.Length; + if (numPoints < 2) + { + if (numPoints == 1) + ctrl1[0] = ctrl2[0] = knot[0]; + return; + } + + int margin = Mathf.Min(4, numPoints-1); + Vector4[] knotLooped = new Vector4[numPoints + 2 * margin]; + Vector4[] ctrl1Looped = new Vector4[numPoints + 2 * margin]; + Vector4[] ctrl2Looped = new Vector4[numPoints + 2 * margin]; + for (int i = 0; i < margin; ++i) + { + knotLooped[i] = knot[numPoints-(margin-i)]; + knotLooped[numPoints+margin+i] = knot[i]; + } + for (int i = 0; i < numPoints; ++i) + knotLooped[i + margin] = knot[i]; + ComputeSmoothControlPoints(ref knotLooped, ref ctrl1Looped, ref ctrl2Looped); + for (int i = 0; i < numPoints; ++i) + { + ctrl1[i] = ctrl1Looped[i + margin]; + ctrl2[i] = ctrl2Looped[i + margin]; + } + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/SplineHelpers.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/SplineHelpers.cs.meta new file mode 100644 index 0000000..59e559f --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/SplineHelpers.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fca2bf25139920d4f9bf86711457992e +timeCreated: 1505844077 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cinemachine/Base/Runtime/Core/UnityVectorExtensions.cs b/Assets/Cinemachine/Base/Runtime/Core/UnityVectorExtensions.cs new file mode 100644 index 0000000..4767832 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/UnityVectorExtensions.cs @@ -0,0 +1,228 @@ +using UnityEngine; + +namespace Cinemachine.Utility +{ + /// Extensions to the Vector3 class, used by Cinemachine + public static class UnityVectorExtensions + { + /// A useful Epsilon + public const float Epsilon = 0.0001f; + + /// + /// Get the closest point on a line segment. + /// + /// A point in space + /// Start of line segment + /// End of line segment + /// The interpolation parameter representing the point on the segment, with 0==s0, and 1==s1 + public static float ClosestPointOnSegment(this Vector3 p, Vector3 s0, Vector3 s1) + { + Vector3 s = s1 - s0; + float len2 = Vector3.SqrMagnitude(s); + if (len2 < Epsilon) + return 0; // degenrate segment + return Mathf.Clamp01(Vector3.Dot(p - s0, s) / len2); + } + + /// + /// Get the closest point on a line segment. + /// + /// A point in space + /// Start of line segment + /// End of line segment + /// The interpolation parameter representing the point on the segment, with 0==s0, and 1==s1 + public static float ClosestPointOnSegment(this Vector2 p, Vector2 s0, Vector2 s1) + { + Vector2 s = s1 - s0; + float len2 = Vector2.SqrMagnitude(s); + if (len2 < Epsilon) + return 0; // degenrate segment + return Mathf.Clamp01(Vector2.Dot(p - s0, s) / len2); + } + + /// + /// Returns a non-normalized projection of the supplied vector onto a plane + /// as described by its normal + /// + /// + /// The normal that defines the plane. Cannot be zero-length. + /// The component of the vector that lies in the plane + public static Vector3 ProjectOntoPlane(this Vector3 vector, Vector3 planeNormal) + { + return (vector - Vector3.Dot(vector, planeNormal) * planeNormal); + } + + /// Is the vector within Epsilon of zero length? + /// + /// True if the square magnitude of the vector is within Epsilon of zero + public static bool AlmostZero(this Vector3 v) + { + return v.sqrMagnitude < (Epsilon * Epsilon); + } + + /// Get a signed angle between two vectors + /// Start direction + /// End direction + /// This is needed in order to determine the sign. + /// For example, if from an to lie on the XZ plane, then this would be the + /// Y unit vector, or indeed any vector which, when dotted with Y unit vector, + /// would give a positive result. + /// The signed angle between the vectors + public static float SignedAngle(Vector3 from, Vector3 to, Vector3 refNormal) + { + from.Normalize(); + to.Normalize(); + float dot = Vector3.Dot(Vector3.Cross(from, to), refNormal); + if (Mathf.Abs(dot) < -Epsilon) + return Vector3.Dot(from, to) < 0 ? 180 : 0; + float angle = Vector3.Angle(from, to); + if (dot < 0) + return -angle; + return angle; + } + + /// This is a slerp that mimics a camera operator's movement in that + /// it chooses a path that avoids the lower hemisphere, as defined by + /// the up param + /// First direction + /// Second direction + /// Interpolation amoun t + /// Defines the up direction + public static Vector3 SlerpWithReferenceUp( + Vector3 vA, Vector3 vB, float t, Vector3 up) + { + float dA = vA.magnitude; + float dB = vB.magnitude; + if (dA < Epsilon || dB < Epsilon) + return Vector3.Lerp(vA, vB, t); + + Vector3 dirA = vA / dA; + Vector3 dirB = vB / dB; + Quaternion qA = Quaternion.LookRotation(dirA, up); + Quaternion qB = Quaternion.LookRotation(dirB, up); + Quaternion q = UnityQuaternionExtensions.SlerpWithReferenceUp(qA, qB, t, up); + Vector3 dir = q * Vector3.forward; + return dir * Mathf.Lerp(dA, dB, t); + } + } + + /// Extentions to the Quaternion class, usen in various places by Cinemachine + public static class UnityQuaternionExtensions + { + /// This is a slerp that mimics a camera operator's movement in that + /// it chooses a path that avoids the lower hemisphere, as defined by + /// the up param + /// First direction + /// Second direction + /// Interpolation amoun t + /// Defines the up direction + public static Quaternion SlerpWithReferenceUp( + Quaternion qA, Quaternion qB, float t, Vector3 up) + { + Vector3 dirA = (qA * Vector3.forward).ProjectOntoPlane(up); + Vector3 dirB = (qB * Vector3.forward).ProjectOntoPlane(up); + if (dirA.AlmostZero() || dirB.AlmostZero()) + return Quaternion.Slerp(qA, qB, t); + + // Work on the plane, in eulers + Quaternion qBase = Quaternion.LookRotation(dirA, up); + Quaternion qA1 = Quaternion.Inverse(qBase) * qA; + Quaternion qB1 = Quaternion.Inverse(qBase) * qB; + Vector3 eA = qA1.eulerAngles; + Vector3 eB = qB1.eulerAngles; + return qBase * Quaternion.Euler( + Mathf.LerpAngle(eA.x, eB.x, t), + Mathf.LerpAngle(eA.y, eB.y, t), + Mathf.LerpAngle(eA.z, eB.z, t)); + } + + /// Normalize a quaternion + /// + /// The normalized quaternion. Unit length is 1. + public static Quaternion Normalized(this Quaternion q) + { + Vector4 v = new Vector4(q.x, q.y, q.z, q.w).normalized; + return new Quaternion(v.x, v.y, v.z, v.w); + } + + /// + /// Get the rotations, first about world up, then about (travelling) local right, + /// necessary to align the quaternion's forward with the target direction. + /// This represents the tripod head movement needed to look at the target. + /// This formulation makes it easy to interpolate without introducing spurious roll. + /// + /// + /// The worldspace target direction in which we want to look + /// Which way is up + /// Vector2.y is rotation about worldUp, and Vector2.x is second rotation, + /// about local right. + public static Vector2 GetCameraRotationToTarget( + this Quaternion orient, Vector3 lookAtDir, Vector3 worldUp) + { + if (lookAtDir.AlmostZero()) + return Vector2.zero; // degenerate + + // Work in local space + Quaternion toLocal = Quaternion.Inverse(orient); + Vector3 up = toLocal * worldUp; + lookAtDir = toLocal * lookAtDir; + + // Align yaw based on world up + float angleH = 0; + { + Vector3 targetDirH = lookAtDir.ProjectOntoPlane(up); + if (!targetDirH.AlmostZero()) + { + Vector3 currentDirH = Vector3.forward.ProjectOntoPlane(up); + if (currentDirH.AlmostZero()) + { + // We're looking at the north or south pole + if (Vector3.Dot(currentDirH, up) > 0) + currentDirH = Vector3.down.ProjectOntoPlane(up); + else + currentDirH = Vector3.up.ProjectOntoPlane(up); + } + angleH = UnityVectorExtensions.SignedAngle(currentDirH, targetDirH, up); + } + } + Quaternion q = Quaternion.AngleAxis(angleH, up); + + // Get local vertical angle + float angleV = UnityVectorExtensions.SignedAngle( + q * Vector3.forward, lookAtDir, q * Vector3.right); + + return new Vector2(angleV, angleH); + } + + /// + /// Apply rotations, first about world up, then about (travelling) local right. + /// rot.y is rotation about worldUp, and rot.x is second rotation, about local right. + /// + /// + /// Vector2.y is rotation about worldUp, and Vector2.x is second rotation, + /// about local right. + /// Which way is up + public static Quaternion ApplyCameraRotation( + this Quaternion orient, Vector2 rot, Vector3 worldUp) + { + Quaternion q = Quaternion.AngleAxis(rot.x, Vector3.right); + return (Quaternion.AngleAxis(rot.y, worldUp) * orient) * q; + } + } + + /// Ad-hoc xxtentions to the Rect structure, used by Cinemachine + public static class UnityRectExtensions + { + /// Inflate a rect + /// + /// x and y are added/subtracted fto/from the edges of + /// the rect, inflating it in all directions + /// The inflated rect + public static Rect Inflated(this Rect r, Vector2 delta) + { + return new Rect( + r.xMin - delta.x, r.yMin - delta.y, + r.width + delta.x * 2, r.height + delta.y * 2); + } + } +} diff --git a/Assets/Cinemachine/Base/Runtime/Core/UnityVectorExtensions.cs.meta b/Assets/Cinemachine/Base/Runtime/Core/UnityVectorExtensions.cs.meta new file mode 100644 index 0000000..3c665f6 --- /dev/null +++ b/Assets/Cinemachine/Base/Runtime/Core/UnityVectorExtensions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6a0472cd31396f741969b8c1af8dd5a0 +timeCreated: 1481654955 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: -- cgit v1.2.1