diff options
Diffstat (limited to 'Assets/Cinemachine/Base/Runtime/Core')
40 files changed, 3657 insertions, 0 deletions
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 +{ + /// <summary> + /// Axis state for defining to react to player input. + /// The settings here control the responsiveness of the axis to player input. + /// </summary> + [DocumentationSorting(6.4f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public struct AxisState + { + /// <summary>The current value of the axis</summary> + [NoSaveDuringPlay] + [Tooltip("The current value of the axis.")] + public float Value; + + /// <summary>How fast the axis value can travel. Increasing this number + /// makes the behaviour more responsive to joystick input</summary> + [Tooltip("The maximum speed of this axis in units/second")] + public float m_MaxSpeed; + + /// <summary>The amount of time in seconds it takes to accelerate to + /// MaxSpeed with the supplied Axis at its maximum value</summary> + [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; + + /// <summary>The amount of time in seconds it takes to decelerate + /// the axis to zero if the supplied axis is in a neutral position</summary> + [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; + + /// <summary>The name of this axis as specified in Unity Input manager. + /// Setting to an empty string will disable the automatic updating of this axis</summary> + [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; + + /// <summary>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</summary> + [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; + + /// <summary>If checked, then the raw value of the input axis will be inverted + /// before it is used.</summary> + [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; + + /// <summary>Constructor with specific values</summary> + 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; + } + + /// <summary>Call from OnValidate: Make sure the fields are sensible</summary> + public void Validate() + { + m_MaxSpeed = Mathf.Max(0, m_MaxSpeed); + m_AccelTime = Mathf.Max(0, m_AccelTime); + m_DecelTime = Mathf.Max(0, m_DecelTime); + } + + /// <summary> + /// Sets the constraints by which this axis will operate on + /// </summary> + /// <param name="minValue">The lowest value this axis can achieve</param> + /// <param name="maxValue">The highest value this axis can achieve</param> + /// <param name="wrapAround">If <b>true</b>, values commanded greater + /// than mMaxValue or less than mMinValue will wrap around. + /// If <b>false</b>, the value will be clamped within the range.</param> + public void SetThresholds(float minValue, float maxValue, bool wrapAround) + { + mMinValue = minValue; + mMaxValue = maxValue; + mWrapAround = wrapAround; + } + + const float Epsilon = UnityVectorExtensions.Epsilon; + + /// <summary> + /// Updates the state of this axis based on the axis defined + /// by AxisState.m_AxisName + /// </summary> + /// <param name="deltaTime">Delta time in seconds</param> + /// <returns>Returns <b>true</b> if this axis' input was non-zero this Update, + /// <b>flase</b> otherwise</returns> + 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 +{ + /// <summary> + /// 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. + /// </summary> + public struct CameraState + { + /// <summary> + /// Camera Lens Settings. + /// </summary> + public LensSettings Lens { get; set; } + + /// <summary> + /// Which way is up. World space unit vector. + /// </summary> + public Vector3 ReferenceUp { get; set; } + + /// <summary> + /// 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). + /// </summary> + public Vector3 ReferenceLookAt { get; set; } + + /// <summary> + /// Returns true if this state has a valid ReferenceLookAt value. + /// </summary> + public bool HasLookAt { get { return ReferenceLookAt == ReferenceLookAt; } } // will be false if NaN + + /// <summary> + /// This constant represents "no point in space" or "no direction". + /// </summary> + public static Vector3 kNoPoint = new Vector3(float.NaN, float.NaN, float.NaN); + + /// <summary> + /// Raw (un-corrected) world space position of this camera + /// </summary> + public Vector3 RawPosition { get; set; } + + /// <summary> + /// Raw (un-corrected) world space orientation of this camera + /// </summary> + public Quaternion RawOrientation { get; set; } + + /// <summary>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</summary> + internal Vector3 PositionDampingBypass { get; set; } + + /// <summary> + /// Subjective estimation of how "good" the shot is. + /// Larger values mean better quality. Default is 1. + /// </summary> + public float ShotQuality { get; set; } + + /// <summary> + /// 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. + /// </summary> + public Vector3 PositionCorrection { get; set; } + + /// <summary> + /// 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. + /// </summary> + public Quaternion OrientationCorrection { get; set; } + + /// <summary> + /// Position with correction applied. + /// </summary> + public Vector3 CorrectedPosition { get { return RawPosition + PositionCorrection; } } + + /// <summary> + /// Orientation with correction applied. + /// </summary> + public Quaternion CorrectedOrientation { get { return RawOrientation * OrientationCorrection; } } + + /// <summary> + /// Position with correction applied. This is what the final camera gets. + /// </summary> + public Vector3 FinalPosition { get { return RawPosition + PositionCorrection; } } + + /// <summary> + /// Orientation with correction and dutch applied. This is what the final camera gets. + /// </summary> + public Quaternion FinalOrientation + { + get + { + if (Mathf.Abs(Lens.Dutch) > UnityVectorExtensions.Epsilon) + return CorrectedOrientation * Quaternion.AngleAxis(Lens.Dutch, Vector3.forward); + return CorrectedOrientation; + } + } + + /// <summary> + /// State with default values + /// </summary> + 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; + } + } + + /// <summary>Opaque structure represent extra blendable stuff and its weight. + /// The base system ignores this data - it is intended for extension modules</summary> + public struct CustomBlendable + { + /// <summary>The custom stuff that the extention module will consider</summary> + public Object m_Custom; + /// <summary>The weight of the custom stuff. Must be 0...1</summary> + public float m_Weight; + + /// <summary>Constructor with specific values</summary> + /// <param name="custom">The custom stuff that the extention module will consider</param> + /// <param name="weight">The weight of the custom stuff. Must be 0...1</param> + 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<CustomBlendable> m_CustomOverflow; + + /// <summary>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</summary> + public int NumCustomBlendables { get; private set; } + + /// <summary>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</summary> + /// <param name="index">Which one to get. Must be in range [0...NumCustomBlendables)</param> + /// <returns>The custom blendable at the specified index.</returns> + 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; + } + + /// <summary>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</summary> + /// <param name="b">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.</param> + 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<CustomBlendable>(); + m_CustomOverflow.Add(b); + break; + } + } + } + + /// <summary>Intelligently blend the contents of two states.</summary> + /// <param name="stateA">The first state, corresponding to t=0</param> + /// <param name="stateB">The second state, corresponding to t=1</param> + /// <param name="t">How much to interpolate. Internally clamped to 0..1</param> + /// <returns>Linearly interpolated CameraState</returns> + 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 +{ + /// <summary> + /// Describes a blend between 2 Cinemachine Virtual Cameras, and holds the + /// current state of the blend. + /// </summary> + public class CinemachineBlend + { + /// <summary>First camera in the blend</summary> + public ICinemachineCamera CamA { get; set; } + + /// <summary>Second camera in the blend</summary> + public ICinemachineCamera CamB { get; set; } + + /// <summary>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)</summary> + public AnimationCurve BlendCurve { get; set; } + + /// <summary>The current time relative to the start of the blend</summary> + public float TimeInBlend { get; set; } + + /// <summary>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.</summary> + public float BlendWeight + { + get { return BlendCurve != null ? BlendCurve.Evaluate(TimeInBlend) : 0; } + } + + /// <summary>Validity test for the blend. True if both cameras are defined.</summary> + public bool IsValid + { + get { return (CamA != null || CamB != null); } + } + + /// <summary>Duration in seconds of the blend. + /// This is given read from the BlendCurve.</summary> + public float Duration { get; set; } + + /// <summary>True if the time relative to the start of the blend is greater + /// than or equal to the blend duration</summary> + public bool IsComplete { get { return TimeInBlend >= Duration; } } + + /// <summary>Text description of the blend, for debugging</summary> + 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); + } + } + + /// <summary>Does the blend use a specific Cinemachine Virtual Camera?</summary> + /// <param name="cam">The camera to test</param> + /// <returns>True if the camera is involved in the blend</returns> + 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; + } + + /// <summary>Construct a blend</summary> + /// <param name="a">First camera</param> + /// <param name="b">Second camera</param> + /// <param name="curve">Blend curve</param> + /// <param name="t">Current time in blend, relative to the start of the blend</param> + 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; + } + + /// <summary>Make sure the source cameras get updated.</summary> + /// <param name="worldUp">Default world up. Individual vcams may modify this</param> + /// <param name="deltaTime">Time increment used for calculating time-based behaviours (e.g. damping)</param> + 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); + } + + /// <summary>Compute the blended CameraState for the current time in the blend.</summary> + public CameraState State { get { return CameraState.Lerp(CamA.State, CamB.State, BlendWeight); } } + } + + /// <summary>Definition of a Camera blend. This struct holds the information + /// necessary to generate a suitable AnimationCurve for a Cinemachine Blend.</summary> + [Serializable] + [DocumentationSorting(10.2f, DocumentationSortingAttribute.Level.UserRef)] + public struct CinemachineBlendDefinition + { + /// <summary>Supported predefined shapes for the blend curve.</summary> + [DocumentationSorting(10.21f, DocumentationSortingAttribute.Level.UserRef)] + public enum Style + { + /// <summary>Zero-length blend</summary> + Cut, + /// <summary>S-shaped curve, giving a gentle and smooth transition</summary> + EaseInOut, + /// <summary>Linear out of the outgoing shot, and easy into the incoming</summary> + EaseIn, + /// <summary>Easy out of the outgoing shot, and linear into the incoming</summary> + EaseOut, + /// <summary>Easy out of the outgoing, and hard into the incoming</summary> + HardIn, + /// <summary>Hard out of the outgoing, and easy into the incoming</summary> + HardOut, + /// <summary>Linear blend. Mechanical-looking.</summary> + Linear + }; + + /// <summary>The shape of the blend curve.</summary> + [Tooltip("Shape of the blend curve")] + public Style m_Style; + + /// <summary>The duration (in seconds) of the blend</summary> + [Tooltip("Duration of the blend, in seconds")] + public float m_Time; + + /// <summary>Constructor</summary> + /// <param name="style">The shape of the blend curve.</param> + /// <param name="time">The duration (in seconds) of the blend</param> + public CinemachineBlendDefinition(Style style, float time) + { + m_Style = style; + m_Time = time; + } + + /// <summary> + /// 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) + /// </summary> + 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 +{ + /// <summary> + /// Asset that defines the rules for blending between Virtual Cameras. + /// </summary> + [DocumentationSorting(10, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public sealed class CinemachineBlenderSettings : ScriptableObject + { + /// <summary> + /// Container specifying how two specific Cinemachine Virtual Cameras + /// blend together. + /// </summary> + [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; + } + /// <summary>The array containing explicitly defined blends between two Virtual Cameras</summary> + [Tooltip("The array containing explicitly defined blends between two Virtual Cameras")] + public CustomBlend[] m_CustomBlends = null; + + /// <summary>Internal API for the inspector editopr: a label to represent any camera</summary> + public const string kBlendFromAnyCameraLabel = "**ANY CAMERA**"; + + /// <summary> + /// 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 <b>returnDefaultOnNoMatch</b>. + /// </summary> + /// <param name="fromCameraName">The game object name of the from camera</param> + /// <param name="toCameraName">The game object name of the to camera</param> + /// <param name="defaultCurve">Curve to return if no curve found. Can be NULL.</param> + /// <returns></returns> + 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 +{ + /// <summary> + /// An abstract representation of a mutator acting on a Cinemachine Virtual Camera + /// </summary> + [DocumentationSorting(24, DocumentationSortingAttribute.Level.API)] + public abstract class CinemachineComponentBase : MonoBehaviour + { + /// <summary>Useful constant for very small floats</summary> + protected const float Epsilon = Utility.UnityVectorExtensions.Epsilon; + + /// <summary>Get the associated CinemachineVirtualCameraBase</summary> + public CinemachineVirtualCameraBase VirtualCamera + { + get + { + if (m_vcamOwner == null) + m_vcamOwner = gameObject.transform.parent.gameObject.GetComponent<CinemachineVirtualCameraBase>(); + return m_vcamOwner; + } + } + CinemachineVirtualCameraBase m_vcamOwner; + + /// <summary>Returns the owner vcam's Follow target.</summary> + public Transform FollowTarget + { + get + { + CinemachineVirtualCameraBase vcam = VirtualCamera; + return vcam == null ? null : vcam.Follow; + } + } + + /// <summary>Returns the owner vcam's LookAt target.</summary> + public Transform LookAtTarget + { + get + { + CinemachineVirtualCameraBase vcam = VirtualCamera; + return vcam == null ? null : vcam.LookAt; + } + } + + /// <summary>Returns the owner vcam's CameraState.</summary> + public CameraState VcamState + { + get + { + CinemachineVirtualCameraBase vcam = VirtualCamera; + return vcam == null ? CameraState.Default : vcam.State; + } + } + + /// <summary>Returns true if this object is enabled and set up to produce results.</summary> + public abstract bool IsValid { get; } + + /// <summary>Override this to do such things as offset the RefereceLookAt. + /// Base class implementation does nothing.</summary> + /// <param name="curState">Input state that must be mutated</param> + public virtual void PrePipelineMutateCameraState(ref CameraState state) {} + + /// <summary>What part of the pipeline this fits into</summary> + public abstract CinemachineCore.Stage Stage { get; } + + /// <summary>Mutates the camera state. This state will later be applied to the camera.</summary> + /// <param name="curState">Input state that must be mutated</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than 0)</param> + public abstract void MutateCameraState(ref CameraState curState, float deltaTime); + + /// <summary>API for the editor, to process a position drag from the user. + /// Base class implementation does nothing.</summary> + /// <param name="delta">The amount dragged this frame</param> + 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 +{ + /// <summary>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.</summary> + public sealed class CinemachineCore + { + /// <summary>Data version string. Used to upgrade from legacy projects</summary> + public static readonly int kStreamingVersion = 20170927; + + /// <summary>Human-readable Cinemachine Version</summary> + public static readonly string kVersionString = "2.1"; + + /// <summary> + /// Stages in the Cinemachine Component pipeline, used for + /// UI organization>. This enum defines the pipeline order. + /// </summary> + public enum Stage + { + /// <summary>Second stage: position the camera in space</summary> + Body, + + /// <summary>Third stage: orient the camera to point at the target</summary> + Aim, + + /// <summary>Final stage: apply noise (this is done separately, in the + /// Correction channel of the CameraState)</summary> + Noise + }; + + private static CinemachineCore sInstance = null; + + /// <summary>Get the singleton instance</summary> + public static CinemachineCore Instance + { + get + { + if (sInstance == null) + sInstance = new CinemachineCore(); + return sInstance; + } + } + + /// <summary> + /// If true, show hidden Cinemachine objects, to make manual script mapping possible. + /// </summary> + public static bool sShowHiddenObjects = false; + + /// <summary>Delegate for overriding Unity's default input system. Returns the value + /// of the named axis.</summary> + public delegate float AxisInputDelegate(string axisName); + + /// <summary>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.</summary> + public static AxisInputDelegate GetInputAxis = UnityEngine.Input.GetAxis; + + /// <summary>List of all active CinemachineBrains.</summary> + private List<CinemachineBrain> mActiveBrains = new List<CinemachineBrain>(); + + /// <summary>Access the array of active CinemachineBrains in the scene</summary> + public int BrainCount { get { return mActiveBrains.Count; } } + + /// <summary>Access the array of active CinemachineBrains in the scene + /// without gebnerating garbage</summary> + /// <param name="index">Index of the brain to access, range 0-BrainCount</param> + /// <returns>The brain at the specified index</returns> + public CinemachineBrain GetActiveBrain(int index) + { + return mActiveBrains[index]; + } + + /// <summary>Called when a CinemachineBrain is enabled.</summary> + internal void AddActiveBrain(CinemachineBrain brain) + { + // First remove it, just in case it's being added twice + RemoveActiveBrain(brain); + mActiveBrains.Insert(0, brain); + } + + /// <summary>Called when a CinemachineBrain is disabled.</summary> + internal void RemoveActiveBrain(CinemachineBrain brain) + { + mActiveBrains.Remove(brain); + } + + /// <summary>List of all active ICinemachineCameras.</summary> + private List<ICinemachineCamera> mActiveCameras = new List<ICinemachineCamera>(); + + /// <summary> + /// List of all active Cinemachine Virtual Cameras for all brains. + /// This list is kept sorted by priority. + /// </summary> + public int VirtualCameraCount { get { return mActiveCameras.Count; } } + + /// <summary>Access the array of active ICinemachineCamera in the scene + /// without gebnerating garbage</summary> + /// <param name="index">Index of the camera to access, range 0-VirtualCameraCount</param> + /// <returns>The virtual camera at the specified index</returns> + public ICinemachineCamera GetVirtualCamera(int index) + { + return mActiveCameras[index]; + } + + /// <summary>Called when a Cinemachine Virtual Camera is enabled.</summary> + 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); + } + + /// <summary>Called when a Cinemachine Virtual Camera is disabled.</summary> + internal void RemoveActiveCamera(ICinemachineCamera vcam) + { + mActiveCameras.Remove(vcam); + } + + // Registry of all vcams that are parented (i.e. slaves of) to other vcams + private List<List<ICinemachineCamera>> mChildCameras = new List<List<ICinemachineCamera>>(); + + /// <summary>Called when a child vcam is enabled.</summary> + 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<ICinemachineCamera>()); + mChildCameras[parentLevel-1].Add(vcam); + } + + /// <summary>Called when a child vcam is disabled.</summary> + internal void RemoveChildCamera(ICinemachineCamera vcam) + { + for (int i = 0; i < mChildCameras.Count; ++i) + mChildCameras[i].Remove(vcam); + } + + /// <summary>Update all the active vcams in the scene, in the correct dependency order.</summary> + 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(); + } + + /// <summary> + /// 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. + /// </summary> + 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<ICinemachineCamera, UpdateStatus>(); + 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<ICinemachineCamera, UpdateStatus> mUpdateStatus; + + /// <summary>Internal use only</summary> + 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; + } + + /// <summary>Internal use only</summary> + public UpdateFilter GetVcamUpdateStatus(ICinemachineCamera vcam) + { + UpdateStatus status; + if (mUpdateStatus == null || !mUpdateStatus.TryGetValue(vcam, out status)) + return UpdateFilter.Late; + return status.preferredUpdate; + } + + /// <summary> + /// Is this virtual camera currently actively controlling any Camera? + /// </summary> + 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; + } + + /// <summary> + /// Signal that the virtual has been activated. + /// If the camera is live, then all CinemachineBrains that are showing it will + /// send an activation event. + /// </summary> + 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); + } + } + } + + /// <summary> + /// 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. + /// </summary> + 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); + } + } + } + + /// <summary> + /// 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. + /// </summary> + /// <param name="vcam">Virtual camera whose potential brain we need.</param> + /// <returns>First CinemachineBrain found that might be + /// appropriate for this vcam, or null</returns> + 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 +{ + /// <summary>Manages onscreen positions for Cinemachine debugging output</summary> + public class CinemachineGameWindowDebug + { + static HashSet<Object> mClients; + + /// <summary>Release a screen rectangle previously obtained through GetScreenPos()</summary> + /// <param name="client">The client caller. Used as a handle.</param> + public static void ReleaseScreenPos(Object client) + { + if (mClients != null && mClients.Contains(client)) + mClients.Remove(client); + } + + /// <summary>Reserve an on-screen rectangle for debugging output.</summary> + /// <param name="client">The client caller. This is used as a handle.</param> + /// <param name="text">Sample text, for determining rectangle size</param> + /// <param name="style">What style will be used to draw, used here for + /// determining rect size</param> + /// <returns>An area on the game screen large enough to print the text + /// in the style indicated</returns> + public static Rect GetScreenPos(Object client, string text, GUIStyle style) + { + if (mClients == null) + mClients = new HashSet<Object>(); + 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 +{ + /// <summary> + /// Base class for a Cinemachine Virtual Camera extension module. + /// Hooks into the Cinemachine Pipeline. + /// </summary> + [DocumentationSorting(23, DocumentationSortingAttribute.Level.API)] + public abstract class CinemachineExtension : MonoBehaviour + { + /// <summary>Useful constant for very small floats</summary> + protected const float Epsilon = Utility.UnityVectorExtensions.Epsilon; + + /// <summary>Get the associated CinemachineVirtualCameraBase</summary> + public CinemachineVirtualCameraBase VirtualCamera + { + get + { + if (m_vcamOwner == null) + m_vcamOwner = GetComponent<CinemachineVirtualCameraBase>(); + return m_vcamOwner; + } + } + CinemachineVirtualCameraBase m_vcamOwner; + + /// <summary>Connect to virtual camera pipeline. + /// Override implementations must call this base implementation</summary> + protected virtual void Awake() + { + ConnectToVcam(); + } + + /// <summary>Disconnect from virtual camera pipeline. + /// Override implementations must call this base implementation</summary> + 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; + } + + /// <summary> + /// 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. + /// </summary> + protected abstract void PostPipelineStageCallback( + CinemachineVirtualCameraBase vcam, + CinemachineCore.Stage stage, ref CameraState state, float deltaTime); + + /// <summary>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.</summary> + protected T GetExtraState<T>(ICinemachineCamera vcam) where T : class, new() + { + if (mExtraState == null) + mExtraState = new Dictionary<ICinemachineCamera, System.Object>(); + System.Object extra = null; + if (!mExtraState.TryGetValue(vcam, out extra)) + extra = mExtraState[vcam] = new T(); + return extra as T; + } + + /// <summary>Ineffeicient method to get all extra state infor for all vcams. + /// Intended for Editor use only, not runtime! + /// </summary> + protected List<T> GetAllExtraStates<T>() where T : class, new() + { + var list = new List<T>(); + if (mExtraState != null) + foreach (var v in mExtraState) + list.Add(v.Value as T); + return list; + } + + private Dictionary<ICinemachineCamera, System.Object> 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 +{ + /// <summary>Abstract base class for a world-space path, + /// suitable for a camera dolly track.</summary> + public abstract class CinemachinePathBase : MonoBehaviour + { + /// <summary>Path samples per waypoint</summary> + [Tooltip("Path samples per waypoint. This is used for calculating path distances.")] + [Range(1, 100)] + public int m_Resolution = 20; + + /// <summary>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</summary> + [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; + } + /// <summary>The settings that control how the path + /// will appear in the editor scene view.</summary> + [Tooltip("The settings that control how the path will appear in the editor scene view.")] + public Appearance m_Appearance = new Appearance(); + + /// <summary>The minimum value for the path position</summary> + public abstract float MinPos { get; } + + /// <summary>The maximum value for the path position</summary> + public abstract float MaxPos { get; } + + /// <summary>True if the path ends are joined to form a continuous loop</summary> + public abstract bool Looped { get; } + + /// <summary>Get a normalized path position, taking spins into account if looped</summary> + /// <param name="pos">Position along the path</param> + /// <returns>Normalized position, between MinPos and MaxPos</returns> + 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); + } + + /// <summary>Get a worldspace position of a point along the path</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <returns>World-space position of the point along at path at pos</returns> + public abstract Vector3 EvaluatePosition(float pos); + + /// <summary>Get the tangent of the curve at a point along the path.</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <returns>World-space direction of the path tangent. + /// Length of the vector represents the tangent strength</returns> + public abstract Vector3 EvaluateTangent(float pos); + + /// <summary>Get the orientation the curve at a point along the path.</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <returns>World-space orientation of the path</returns> + public abstract Quaternion EvaluateOrientation(float pos); + + /// <summary>Find the closest point on the path to a given worldspace target point.</summary> + /// <remarks>Performance could be improved by checking the bounding polygon of each segment, + /// and only entering the best segment(s)</remarks> + /// <param name="p">Worldspace target that we want to approach</param> + /// <param name="startSegment">In what segment of the path to start the search. + /// A Segment is a section of path between 2 waypoints.</param> + /// <param name="searchRadius">How many segments on either side of the startSegment + /// to search. -1 means no limit, i.e. search the entire path</param> + /// <param name="stepsPerSegment">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</param> + /// <returns>The position along the path that is closest to the target point. + /// The value is in Path Units, not Distance units.</returns> + 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; + } + + /// <summary>How to interpret the Path Position</summary> + public enum PositionUnits + { + /// <summary>Use PathPosition units, where 0 is first waypoint, 1 is second waypoint, etc</summary> + PathUnits, + /// <summary>Use Distance Along Path. Path will be sampled according to its Resolution + /// setting, and a distance lookup table will be cached internally</summary> + Distance + } + + /// <summary>Get the minimum value, for the given unity type</summary> + /// <param name="units">The uniot type</param> + /// <returns>The minimum allowable value for this path</returns> + public float MinUnit(PositionUnits units) + { + return units == PositionUnits.Distance ? 0 : MinPos; + } + + /// <summary>Get the maximum value, for the given unity type</summary> + /// <param name="units">The uniot type</param> + /// <returns>The maximum allowable value for this path</returns> + public float MaxUnit(PositionUnits units) + { + return units == PositionUnits.Distance ? PathLength : MaxPos; + } + + /// <summary>Normalize the unit, so that it lies between MinUmit and MaxUnit</summary> + /// <param name="pos">The value to be normalized</param> + /// <param name="units">The unit type</param> + /// <returns>The normalized value of pos, between MinUnit and MaxUnit</returns> + public virtual float NormalizeUnit(float pos, PositionUnits units) + { + if (units == PositionUnits.Distance) + return NormalizePathDistance(pos); + return NormalizePos(pos); + } + + /// <summary>Get a worldspace position of a point along the path</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <param name="units">The unit to use when interpreting the value of pos.</param> + /// <returns>World-space position of the point along at path at pos</returns> + public Vector3 EvaluatePositionAtUnit(float pos, PositionUnits units) + { + if (units == PositionUnits.Distance) + pos = GetPathPositionFromDistance(pos); + return EvaluatePosition(pos); + } + + /// <summary>Get the tangent of the curve at a point along the path.</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <param name="units">The unit to use when interpreting the value of pos.</param> + /// <returns>World-space direction of the path tangent. + /// Length of the vector represents the tangent strength</returns> + public Vector3 EvaluateTangentAtUnit(float pos, PositionUnits units) + { + if (units == PositionUnits.Distance) + pos = GetPathPositionFromDistance(pos); + return EvaluateTangent(pos); + } + + /// <summary>Get the orientation the curve at a point along the path.</summary> + /// <param name="pos">Postion along the path. Need not be normalized.</param> + /// <param name="units">The unit to use when interpreting the value of pos.</param> + /// <returns>World-space orientation of the path</returns> + public Quaternion EvaluateOrientationAtUnit(float pos, PositionUnits units) + { + if (units == PositionUnits.Distance) + pos = GetPathPositionFromDistance(pos); + return EvaluateOrientation(pos); + } + + /// <summary>When calculating the distance cache, sample the path this many + /// times between points</summary> + public abstract int DistanceCacheSampleStepsPerSegment { get; } + + /// <summary>Call this if the path changes in such a way as to affect distances + /// or other cached path elements</summary> + public virtual void InvalidateDistanceCache() + { + m_DistanceToPos = null; + m_PosToDistance = null; + m_CachedSampleSteps = 0; + m_PathLength = 0; + } + + /// <summary>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</summary> + /// <param name="stepsPerSegment">The number of steps to take between path points</param> + /// <returns>Whether the cache is valid for this sampling rate</returns> + public bool DistanceCacheIsValid() + { + return (MaxPos == MinPos) + || (m_DistanceToPos != null && m_PosToDistance != null + && m_CachedSampleSteps == DistanceCacheSampleStepsPerSegment + && m_CachedSampleSteps > 0); + } + + /// <summary>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</summary> + /// <returns>The length of the path in distance units, when sampled at this rate</returns> + public float PathLength + { + get + { + if (DistanceCacheSampleStepsPerSegment < 1) + return 0; + if (!DistanceCacheIsValid()) + ResamplePath(DistanceCacheSampleStepsPerSegment); + return m_PathLength; + } + } + + /// <summary>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</summary> + /// <param name="distance">The distance to normalize</param> + /// <returns>The normalized distance, ranging from 0 to path length</returns> + 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); + } + + /// <summary>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</summary> + /// <returns>The length of the path in distance units, when sampled at this rate</returns> + 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); + } + + /// <summary>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</summary> + /// <returns>The length of the path in distance units, when sampled at this rate</returns> + 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 +{ + /// <summary> + /// Property applied to LensSettings. Used for custom drawing in the inspector. + /// </summary> + public sealed class LensSettingsPropertyAttribute : PropertyAttribute + { + } + + /// <summary> + /// Property applied to CinemachineBlendDefinition. Used for custom drawing in the inspector. + /// </summary> + public sealed class CinemachineBlendDefinitionPropertyAttribute : PropertyAttribute + { + } + + /// <summary> + /// 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. + /// </summary> + public sealed class SaveDuringPlayAttribute : System.Attribute + { + } + + /// <summary> + /// 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. + /// </summary> + public sealed class NoSaveDuringPlayAttribute : PropertyAttribute + { + } + + /// <summary>Property field is a Tag.</summary> + public sealed class TagFieldAttribute : PropertyAttribute + { + } + + /// <summary> + /// Atrtribute to control the automatic generation of documentation. + /// </summary> + [DocumentationSorting(0f, DocumentationSortingAttribute.Level.Undoc)] + public sealed class DocumentationSortingAttribute : System.Attribute + { + /// <summary>Refinement level of the documentation</summary> + public enum Level + { + /// <summary>Type is excluded from documentation</summary> + Undoc, + /// <summary>Type is documented in the API reference</summary> + API, + /// <summary>Type is documented in the highly-refined User Manual</summary> + UserRef + }; + /// <summary>Where this type appears in the manual. Smaller number sort earlier.</summary> + public float SortOrder { get; private set; } + /// <summary>Refinement level of the documentation. The more refined, the more is excluded.</summary> + public Level Category { get; private set; } + + /// <summary>Contructor with specific values</summary> + 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 +{ + /// <summary> + /// 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. + /// </summary> + [SaveDuringPlay] + public abstract class CinemachineVirtualCameraBase : MonoBehaviour, ICinemachineCamera + { + /// <summary>This is deprecated. It is here to support the soon-to-be-removed + /// Cinemachine Debugger in the Editor.</summary> + [HideInInspector, NoSaveDuringPlay] + public Action CinemachineGUIDebuggerCallback = null; + + /// <summary>Inspector control - Use for hiding sections of the Inspector UI.</summary> + [HideInInspector, SerializeField, NoSaveDuringPlay] + public string[] m_ExcludedPropertiesInInspector = new string[] { "m_Script" }; + + /// <summary>Inspector control - Use for enabling sections of the Inspector UI.</summary> + [HideInInspector, SerializeField, NoSaveDuringPlay] + public CinemachineCore.Stage[] m_LockStageInInspector; + + /// <summary>Version that was last streamed, for upgrading legacy</summary> + 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; + + /// <summary>The priority will determine which camera becomes active based on the + /// state of other cameras and this camera. Higher numbers have greater priority. + /// </summary> + [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; + + /// <summary> + /// 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. + /// </summary> + /// <param name="d">The delegate to call.</param> + public virtual void AddPostPipelineStageHook(OnPostPipelineStageDelegate d) + { + OnPostPipelineStage -= d; + OnPostPipelineStage += d; + } + + /// <summary>Remove a Pipeline stage hook callback.</summary> + /// <param name="d">The delegate to remove.</param> + public virtual void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) + { + OnPostPipelineStage -= d; + } + + /// <summary> + /// 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" + /// </summary> + public delegate void OnPostPipelineStageDelegate( + CinemachineVirtualCameraBase vcam, CinemachineCore.Stage stage, + ref CameraState newState, float deltaTime); + + /// <summary> + /// 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. + /// </summary> + protected OnPostPipelineStageDelegate OnPostPipelineStage; + + /// <summary> + /// Invokes the PostPipelineStageDelegate for this camera, and up the hierarchy for all + /// parent cameras (if any). + /// </summary> + 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); + } + + /// <summary>Get the name of the Virtual Camera. Base implementation + /// returns the owner GameObject's name.</summary> + public string Name { get { return name; } } + + /// <summary>Gets a brief debug description of this virtual camera, for use when displayiong debug info</summary> + public virtual string Description { get { return ""; }} + + /// <summary>Get the Priority of the virtual camera. This determines its placement + /// in the CinemachineCore's queue of eligible shots.</summary> + public int Priority { get { return m_Priority; } set { m_Priority = value; } } + + /// <summary>The GameObject owner of the Virtual Camera behaviour.</summary> + public GameObject VirtualCameraGameObject + { + get + { + if (this == null) + return null; // object deleted + return gameObject; + } + } + + /// <summary>The CameraState object holds all of the information + /// necessary to position the Unity camera. It is the output of this class.</summary> + public abstract CameraState State { get; } + + /// <summary>Just returns self.</summary> + public virtual ICinemachineCamera LiveChildOrSelf { get { return this; } } + + /// <summary>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.</summary> + public ICinemachineCamera ParentCamera + { + get + { + if (!mSlaveStatusUpdated || !Application.isPlaying) + UpdateSlaveStatus(); + return m_parentVcam; + } + } + + /// <summary>Check whether the vcam a live child of this camera. + /// This base class implementation always returns false.</summary> + /// <param name="vcam">The Virtual Camera to check</param> + /// <returns>True if the vcam is currently actively influencing the state of this vcam</returns> + public virtual bool IsLiveChild(ICinemachineCamera vcam) { return false; } + + /// <summary>Get the LookAt target for the Aim component in the CinemachinePipeline.</summary> + public abstract Transform LookAt { get; set; } + + /// <summary>Get the Follow target for the Body component in the CinemachinePipeline.</summary> + public abstract Transform Follow { get; set; } + + /// <summary>Set this to force the next update to ignore deltaTime and reset itself</summary> + 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; + + + /// <summary>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</summary> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than 0)</param> + public abstract void UpdateCameraState(Vector3 worldUp, float deltaTime); + + /// <summary>Notification that this virtual camera is going live. + /// Base class implementationmust be called by any overridden method.</summary> + /// <param name="fromCam">The camera being deactivated. May be null.</param> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param> + public virtual void OnTransitionFromCamera( + ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime) + { + if (!gameObject.activeInHierarchy) + PreviousStateIsValid = false; + } + + /// <summary>Base class implementation does nothing.</summary> + protected virtual void Start() + { + } + + /// <summary>Base class implementation removes the virtual camera from the priority queue.</summary> + protected virtual void OnDestroy() + { + CinemachineCore.Instance.RemoveActiveCamera(this); + } + + /// <summary>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.</summary> + protected virtual void OnValidate() + { + m_OnValidateCalled = true; + ValidatingStreamVersion = m_StreamingVersion; + m_StreamingVersion = CinemachineCore.kStreamingVersion; + } + + /// <summary>Base class implementation adds the virtual camera from the priority queue.</summary> + protected virtual void OnEnable() + { + // Sanity check - if another vcam component is enabled, shut down + var vcamComponents = GetComponents<CinemachineVirtualCameraBase>(); + 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; + } + + /// <summary>Base class implementation makes sure the priority queue remains up-to-date.</summary> + protected virtual void OnDisable() + { + UpdateVcamPoolStatus(); // Remove from queue + } + + /// <summary>Base class implementation makes sure the priority queue remains up-to-date.</summary> + protected virtual void Update() + { + if (m_Priority != m_QueuePriority) + UpdateVcamPoolStatus(); + } + + /// <summary>Base class implementation makes sure the priority queue remains up-to-date.</summary> + protected virtual void OnTransformParentChanged() + { + UpdateSlaveStatus(); + UpdateVcamPoolStatus(); + } + +#if UNITY_EDITOR + /// <summary>Support for the deprecated CinemachineDebugger.</summary> + 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<CinemachineVirtualCameraBase>(); + } + + /// <summary>Returns this vcam's LookAt target, or if that is null, will retrun + /// the parent vcam's LookAt target.</summary> + /// <param name="localLookAt">This vcam's LookAt value.</param> + /// <returns>The same value, or the parent's if null and a parent exists.</returns> + protected Transform ResolveLookAt(Transform localLookAt) + { + Transform lookAt = localLookAt; + if (lookAt == null && ParentCamera != null) + lookAt = ParentCamera.LookAt; // Parent provides default + return lookAt; + } + + /// <summary>Returns this vcam's Follow target, or if that is null, will retrun + /// the parent vcam's Follow target.</summary> + /// <param name="localFollow">This vcam's Follow value.</param> + /// <returns>The same value, or the parent's if null and a parent exists.</returns> + 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); + } + } + + /// <summary>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.</summary> + 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<T> + { + 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<Vector3> + { + 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<Quaternion> + { + 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<Vector2> + { + 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 +{ + /// <summary> + /// An abstract representation of a virtual camera which lives within the Unity scene + /// </summary> + public interface ICinemachineCamera + { + /// <summary> + /// Gets the name of this virtual camera. For use when deciding how to blend + /// to or from this camera + /// </summary> + string Name { get; } + + /// <summary> + /// Gets a brief debug description of this virtual camera, for use when displayiong debug info + /// </summary> + string Description { get; } + + /// <summary> + /// Gets the priority of this <c>ICinemachineCamera</c>. The virtual camera + /// will be inserted into the global priority stack based on this value. + /// </summary> + int Priority { get; set; } + + /// <summary> + /// The thing the camera wants to look at (aim). May be null. + /// </summary> + Transform LookAt { get; set; } + + /// <summary> + /// The thing the camera wants to follow (moving camera). May be null. + /// </summary> + Transform Follow { get; set; } + + /// <summary> + /// Camera state at the current time. + /// </summary> + CameraState State { get; } + + /// <summary> + /// Gets the virtual camera game attached to this class. + /// </summary> + GameObject VirtualCameraGameObject { get; } + + /// <summary>For cameras that implement child cameras, return the live child, + /// otherwise, just returns self.</summary> + ICinemachineCamera LiveChildOrSelf { get; } + + /// <summary> + /// For cameras that implement child cameras, returns the parent vcam, otherwise null. + /// </summary> + ICinemachineCamera ParentCamera { get; } + + /// <summary>Check whether the vcam is a live child of this camera.</summary> + /// <param name="vcam">The Virtual Camera to check</param> + /// <returns>True if the vcam is currently actively influencing the state of this vcam</returns> + bool IsLiveChild(ICinemachineCamera vcam); + + /// <summary> + /// 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. + /// </summary> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than 0)</param> + void UpdateCameraState(Vector3 worldUp, float deltaTime); + + /// <summary> + /// 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. + /// </summary> + /// <param name="fromCam">The camera being deactivated. May be null.</param> + /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> + /// <param name="deltaTime">Delta time for time-based effects (ignore if less than 0)</param> + 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 +{ + /// <summary> + /// 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. + /// </summary> + [Serializable] + [DocumentationSorting(2, DocumentationSortingAttribute.Level.UserRef)] + public struct LensSettings + { + /// <summary>Default Lens Settings</summary> + public static LensSettings Default = new LensSettings(40f, 10, 0.1f, 5000f, 0, false, 1); + + /// <summary> + /// 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 + /// </summary> + [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; + + /// <summary> + /// When using an orthographic camera, this defines the height, in world + /// co-ordinates, of the camera view. + /// </summary> + [Tooltip("When using an orthographic camera, this defines the half-height, in world coordinates, of the camera view.")] + public float OrthographicSize; + + /// <summary> + /// The near clip plane for this LensSettings + /// </summary> + [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; + + /// <summary> + /// The far clip plane for this LensSettings + /// </summary> + [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; + + /// <summary> + /// The dutch (tilt) to be applied to the camera. In degrees + /// </summary> + [Range(-180f, 180f)] + [Tooltip("Camera Z roll, or tilt, in degrees.")] + public float Dutch; + + /// <summary> + /// This is set every frame by the virtual camera, based on the value found in the + /// currently associated Unity camera + /// </summary> + internal bool Orthographic { get; set; } + + /// <summary> + /// This is set every frame by the virtual camera, based on the value + /// found in the currently associated Unity camera + /// </summary> + internal float Aspect { get; set; } + + /// <summary> + /// Creates a new LensSettings, copying the values from the + /// supplied Camera + /// </summary> + /// <param name="fromCamera">The Camera from which the FoV, near + /// and far clip planes will be copied.</param> + 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; + } + + /// <summary> + /// Explicit constructor for this LensSettings + /// </summary> + /// <param name="fov">The Vertical field of view</param> + /// <param name="orthographicSize">If orthographic, this is the half-height of the screen</param> + /// <param name="nearClip">The near clip plane</param> + /// <param name="farClip">The far clip plane</param> + /// <param name="dutch">Camera roll, in degrees. This is applied at the end + /// <param name="ortho">Whether the lens is orthographic</param> + /// <param name="aspect">The aspect ratio of the lens Width/height</param> + /// after shot composition.</param> + 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; + } + + /// <summary> + /// Linearly blends the fields of two LensSettings and returns the result + /// </summary> + /// <param name="lensA">The LensSettings to blend from</param> + /// <param name="lensB">The LensSettings to blend to</param> + /// <param name="t">The interpolation value. Internally clamped to the range [0,1]</param> + /// <returns>Interpolated settings</returns> + 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; + } + + /// <summary>Make sure lens settings are sane. Call this from OnValidate().</summary> + 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 +{ + /// <summary> + /// 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! + /// </summary> + [DocumentationSorting(9, DocumentationSortingAttribute.Level.UserRef)] + public sealed class NoiseSettings : ScriptableObject + { + /// <summary> + /// Describes the behaviour for a channel of noise + /// </summary> + [DocumentationSorting(9.1f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public struct NoiseParams + { + /// <summary>The amplitude of the noise for this channel. Larger numbers vibrate higher</summary> + [Tooltip("The amplitude of the noise for this channel. Larger numbers vibrate higher.")] + public float Amplitude; + /// <summary>The frequency of noise for this channel. Higher magnitudes vibrate faster</summary> + [Tooltip("The frequency of noise for this channel. Higher magnitudes vibrate faster.")] + public float Frequency; + } + + /// <summary> + /// Contains the behaviour of noise for the noise module for all 3 cardinal axes of the camera + /// </summary> + [DocumentationSorting(9.2f, DocumentationSortingAttribute.Level.UserRef)] + [Serializable] + public struct TransformNoiseParams + { + /// <summary>Noise definition for X-axis</summary> + [Tooltip("Noise definition for X-axis")] + public NoiseParams X; + /// <summary>Noise definition for Y-axis</summary> + [Tooltip("Noise definition for Y-axis")] + public NoiseParams Y; + /// <summary>Noise definition for Z-axis</summary> + [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]; + + /// <summary> + /// Gets the array of positional noise channels for this <c>NoiseSettings</c> + /// </summary> + 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]; + + /// <summary> + /// Gets the array of orientation noise channels for this <c>NoiseSettings</c> + /// </summary> + public TransformNoiseParams[] OrientationNoise { get { return m_Orientation; } } + + /// <summary>Clones the contents of the other asset into this one</summary> + 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; + } + } + + /// <summary>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.</summary> + 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); + } + + /// <summary>Standard residual</summary> + public const float kNegligibleResidual = 0.01f; + + /// <summary>Get a damped version of a quantity. This is the portion of the + /// quantity that will take effect over the given time.</summary> + /// <param name="initial">The amount that will be damped</param> + /// <param name="dampTime">The rate of damping. This is the time it would + /// take to reduce the original amount to a negligible percentage</param> + /// <param name="deltaTime">The time over which to damp</param> + /// <returns>The damped amount. This will be the original amount scaled by + /// a value between 0 and 1.</returns> + 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); + } + + /// <summary>Get a damped version of a quantity. This is the portion of the + /// quantity that will take effect over the given time.</summary> + /// <param name="initial">The amount that will be damped</param> + /// <param name="dampTime">The rate of damping. This is the time it would + /// take to reduce the original amount to a negligible percentage</param> + /// <param name="deltaTime">The time over which to damp</param> + /// <returns>The damped amount. This will be the original amount scaled by + /// a value between 0 and 1.</returns> + 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; + } + + /// <summary>Get a damped version of a quantity. This is the portion of the + /// quantity that will take effect over the given time.</summary> + /// <param name="initial">The amount that will be damped</param> + /// <param name="dampTime">The rate of damping. This is the time it would + /// take to reduce the original amount to a negligible percentage</param> + /// <param name="deltaTime">The time over which to damp</param> + /// <returns>The damped amount. This will be the original amount scaled by + /// a value between 0 and 1.</returns> + 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 +{ + /// <summary>An ad-hoc collection of helpers for reflection, used by Cinemachine + /// or its editor tools in various places</summary> + [DocumentationSorting(0, DocumentationSortingAttribute.Level.Undoc)] + public static class ReflectionHelpers + { + /// <summary>Copy the fields from one object to another</summary> + /// <param name="src">The source object to copy from</param> + /// <param name="dst">The destination object to copy to</param> + /// <param name="bindingAttr">The mask to filter the attributes. + /// Only those fields that get caught in the filter will be copied</param> + 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 + /// <summary>Search the assembly for all types that match a predicate</summary> + /// <param name="assembly">The assembly to search</param> + /// <param name="predicate">The type to look for</param> + /// <returns>A list of types found in the assembly that inherit from the predicate</returns> + public static IEnumerable<Type> GetTypesInAssembly( + Assembly assembly, Predicate<Type> 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; + } + + /// <summary>Get a type from a name</summary> + /// <param name="typeName">The name of the type to search for</param> + /// <returns>The type matching the name, or null if not found</returns> + public static Type GetTypeInAllLoadedAssemblies(string typeName) + { + foreach (Type type in GetTypesInAllLoadedAssemblies(t => t.Name == typeName)) + return type; + return null; + } + + /// <summary>Search all assemblies for all types that match a predicate</summary> + /// <param name="predicate">The type to look for</param> + /// <returns>A list of types found in the assembly that inherit from the predicate</returns> + public static IEnumerable<Type> GetTypesInAllLoadedAssemblies(Predicate<Type> predicate) + { + Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); + List<Type> foundTypes = new List<Type>(100); + foreach (Assembly assembly in assemblies) + { + foreach (Type foundType in GetTypesInAssembly(assembly, predicate)) + foundTypes.Add(foundType); + } + return foundTypes; + } + + /// <summary>call GetTypesInAssembly() for all assemblies that match a predicate</summary> + /// <param name="assemblyPredicate">Which assemblies to search</param> + /// <param name="predicate">What type to look for</param> + public static IEnumerable<Type> GetTypesInLoadedAssemblies( + Predicate<Assembly> assemblyPredicate, Predicate<Type> predicate) + { + Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); + assemblies = assemblies.Where((Assembly assembly) + => { return assemblyPredicate(assembly); }).OrderBy((Assembly ass) + => { return ass.FullName; }).ToArray(); + + List<Type> foundTypes = new List<Type>(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 + + /// <summary>Cheater extension to access internal field of an object</summary> + /// <param name="type">The type of the field</param> + /// <param name="obj">The object to access</param> + /// <param name="memberName">The string name of the field to access</param> + /// <returns>The value of the field in the objects</returns> + public static T AccessInternalField<T>(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); + } + + /// <summary>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</summary> + /// <param name="path">The name of the field, which may contain '.' separators</param> + /// <param name="obj">the owner of the compound field</param> + 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); + } + + /// <summary>Returns a string path from an expression - mostly used to retrieve serialized properties + /// without hardcoding the field path. Safer, and allows for proper refactoring.</summary> + public static string GetFieldPath<TType, TValue>(Expression<Func<TType, TValue>> expr) + { + MemberExpression me; + switch (expr.Body.NodeType) + { + case ExpressionType.MemberAccess: + me = expr.Body as MemberExpression; + break; + default: + throw new InvalidOperationException(); + } + + var members = new List<string>(); + 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 +{ + /// <summary>Extensions to the Vector3 class, used by Cinemachine</summary> + public static class UnityVectorExtensions + { + /// <summary>A useful Epsilon</summary> + public const float Epsilon = 0.0001f; + + /// <summary> + /// Get the closest point on a line segment. + /// </summary> + /// <param name="p">A point in space</param> + /// <param name="s0">Start of line segment</param> + /// <param name="s1">End of line segment</param> + /// <returns>The interpolation parameter representing the point on the segment, with 0==s0, and 1==s1</returns> + 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); + } + + /// <summary> + /// Get the closest point on a line segment. + /// </summary> + /// <param name="p">A point in space</param> + /// <param name="s0">Start of line segment</param> + /// <param name="s1">End of line segment</param> + /// <returns>The interpolation parameter representing the point on the segment, with 0==s0, and 1==s1</returns> + 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); + } + + /// <summary> + /// Returns a non-normalized projection of the supplied vector onto a plane + /// as described by its normal + /// </summary> + /// <param name="vector"></param> + /// <param name="planeNormal">The normal that defines the plane. Cannot be zero-length.</param> + /// <returns>The component of the vector that lies in the plane</returns> + public static Vector3 ProjectOntoPlane(this Vector3 vector, Vector3 planeNormal) + { + return (vector - Vector3.Dot(vector, planeNormal) * planeNormal); + } + + /// <summary>Is the vector within Epsilon of zero length?</summary> + /// <param name="v"></param> + /// <returns>True if the square magnitude of the vector is within Epsilon of zero</returns> + public static bool AlmostZero(this Vector3 v) + { + return v.sqrMagnitude < (Epsilon * Epsilon); + } + + /// <summary>Get a signed angle between two vectors</summary> + /// <param name="from">Start direction</param> + /// <param name="to">End direction</param> + /// <param name="refNormal">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.</param> + /// <returns>The signed angle between the vectors</returns> + 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; + } + + /// <summary>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</summary> + /// <param name="vA">First direction</param> + /// <param name="vB">Second direction</param> + /// <param name="t">Interpolation amoun t</param> + /// <param name="up">Defines the up direction</param> + 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); + } + } + + /// <summary>Extentions to the Quaternion class, usen in various places by Cinemachine</summary> + public static class UnityQuaternionExtensions + { + /// <summary>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</summary> + /// <param name="qA">First direction</param> + /// <param name="qB">Second direction</param> + /// <param name="t">Interpolation amoun t</param> + /// <param name="up">Defines the up direction</param> + 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)); + } + + /// <summary>Normalize a quaternion</summary> + /// <param name="q"></param> + /// <returns>The normalized quaternion. Unit length is 1.</returns> + 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); + } + + /// <summary> + /// 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. + /// </summary> + /// <param name="orient"></param> + /// <param name="lookAtDir">The worldspace target direction in which we want to look</param> + /// <param name="worldUp">Which way is up</param> + /// <returns>Vector2.y is rotation about worldUp, and Vector2.x is second rotation, + /// about local right.</returns> + 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); + } + + /// <summary> + /// 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. + /// </summary> + /// <param name="orient"></param> + /// <param name="rot">Vector2.y is rotation about worldUp, and Vector2.x is second rotation, + /// about local right.</param> + /// <param name="worldUp">Which way is up</param> + 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; + } + } + + /// <summary>Ad-hoc xxtentions to the Rect structure, used by Cinemachine</summary> + public static class UnityRectExtensions + { + /// <summary>Inflate a rect</summary> + /// <param name="r"></param> + /// <param name="delta">x and y are added/subtracted fto/from the edges of + /// the rect, inflating it in all directions</param> + /// <returns>The inflated rect</returns> + 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: |
