CinemachineImpulseManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. using System;
  2. using System.Collections.Generic;
  3. using Cinemachine.Utility;
  4. using UnityEngine;
  5. namespace Cinemachine
  6. {
  7. /// <summary>
  8. /// Property applied to CinemachineImpulseManager.EnvelopeDefinition.
  9. /// Used for custom drawing in the inspector. This attribute is obsolete and not used.
  10. /// </summary>
  11. public sealed class CinemachineImpulseEnvelopePropertyAttribute : PropertyAttribute {}
  12. /// <summary>
  13. /// Property applied to CinemachineImpulseManager Channels.
  14. /// Used for custom drawing in the inspector.
  15. /// </summary>
  16. public sealed class CinemachineImpulseChannelPropertyAttribute : PropertyAttribute {}
  17. /// <summary>
  18. /// This is a singleton object that manages all Impulse Events generated by the Cinemachine
  19. /// Impulse module. This singleton owns and manages all ImpulseEvent objectss.
  20. /// </summary>
  21. [DocumentationSorting(DocumentationSortingAttribute.Level.API)]
  22. public class CinemachineImpulseManager
  23. {
  24. private CinemachineImpulseManager() {}
  25. private static CinemachineImpulseManager sInstance = null;
  26. /// <summary>Get the singleton instance</summary>
  27. public static CinemachineImpulseManager Instance
  28. {
  29. get
  30. {
  31. if (sInstance == null)
  32. sInstance = new CinemachineImpulseManager();
  33. return sInstance;
  34. }
  35. }
  36. [RuntimeInitializeOnLoadMethod]
  37. static void InitializeModule()
  38. {
  39. if (sInstance != null)
  40. sInstance.Clear();
  41. }
  42. const float Epsilon = UnityVectorExtensions.Epsilon;
  43. /// <summary>This defines the time-envelope of the signal.
  44. /// Thie raw signal will be scaled to fit inside the envelope.</summary>
  45. [Serializable]
  46. public struct EnvelopeDefinition
  47. {
  48. /// <summary>Normalized curve defining the shape of the start of the envelope.</summary>
  49. [Tooltip("Normalized curve defining the shape of the start of the envelope. If blank a default curve will be used")]
  50. public AnimationCurve m_AttackShape;
  51. /// <summary>Normalized curve defining the shape of the end of the envelope.</summary>
  52. [Tooltip("Normalized curve defining the shape of the end of the envelope. If blank a default curve will be used")]
  53. public AnimationCurve m_DecayShape;
  54. /// <summary>Duration in seconds of the attack. Attack curve will be scaled to fit. Must be >= 0</summary>
  55. [Tooltip("Duration in seconds of the attack. Attack curve will be scaled to fit. Must be >= 0.")]
  56. public float m_AttackTime; // Must be >= 0
  57. /// <summary>Duration in seconds of the central fully-scaled part of the envelope. Must be >= 0.</summary>
  58. [Tooltip("Duration in seconds of the central fully-scaled part of the envelope. Must be >= 0.")]
  59. public float m_SustainTime; // Must be >= 0
  60. /// <summary>Duration in seconds of the decay. Decay curve will be scaled to fit. Must be >= 0.</summary>
  61. [Tooltip("Duration in seconds of the decay. Decay curve will be scaled to fit. Must be >= 0.")]
  62. public float m_DecayTime; // Must be >= 0
  63. /// <summary>If checked, signal amplitude scaling will also be applied to the time envelope of the signal. Bigger signals will last longer</summary>
  64. [Tooltip("If checked, signal amplitude scaling will also be applied to the time envelope of the signal. Stronger signals will last longer.")]
  65. public bool m_ScaleWithImpact;
  66. /// <summary>If true, then duration is infinite.</summary>
  67. [Tooltip("If true, then duration is infinite.")]
  68. public bool m_HoldForever;
  69. /// <summary>Get an envelope with default values.</summary>
  70. /// <returns>An event with default values</returns>
  71. public static EnvelopeDefinition Default()
  72. {
  73. return new EnvelopeDefinition { m_DecayTime = 0.7f, m_SustainTime = 0.2f, m_ScaleWithImpact = true };
  74. }
  75. /// <summary>Duration of the envelope, in seconds. If negative, then duration is infinite.</summary>
  76. public float Duration
  77. {
  78. get
  79. {
  80. if (m_HoldForever)
  81. return -1;
  82. return m_AttackTime + m_SustainTime + m_DecayTime;
  83. }
  84. }
  85. /// <summary>
  86. /// Get the value of the tenvelope at a given time relative to the envelope start.
  87. /// </summary>
  88. /// <param name="offset">Time in seconds from the envelope start</param>
  89. /// <returns>Envelope amplitude. This will range from 0...1</returns>
  90. public float GetValueAt(float offset)
  91. {
  92. if (offset >= 0)
  93. {
  94. if (offset < m_AttackTime && m_AttackTime > Epsilon)
  95. {
  96. if (m_AttackShape == null || m_AttackShape.length < 2)
  97. return Damper.Damp(1, m_AttackTime, offset);
  98. return m_AttackShape.Evaluate(offset / m_AttackTime);
  99. }
  100. offset -= m_AttackTime;
  101. if (m_HoldForever || offset < m_SustainTime)
  102. return 1;
  103. offset -= m_SustainTime;
  104. if (offset < m_DecayTime && m_DecayTime > Epsilon)
  105. {
  106. if (m_DecayShape == null || m_DecayShape.length < 2)
  107. return 1 - Damper.Damp(1, m_DecayTime, offset);
  108. return m_DecayShape.Evaluate(offset / m_DecayTime);
  109. }
  110. }
  111. return 0;
  112. }
  113. /// <summary>
  114. /// Change the envelope so that it stops at a specific offset from its start time.
  115. /// Use this to extend or cut short an existing envelope, while respecting the
  116. /// attack and decay as much as possible.
  117. /// </summary>
  118. /// <param name="offset">When to stop the envelope</param>
  119. /// <param name="forceNoDecay">If true, enevlope will not decay, but cut off instantly</param>
  120. public void ChangeStopTime(float offset, bool forceNoDecay)
  121. {
  122. if (offset < 0)
  123. offset = 0;
  124. if (offset < m_AttackTime)
  125. m_AttackTime = 0; // How to prevent pop? GML
  126. m_SustainTime = offset - m_AttackTime;
  127. if (forceNoDecay)
  128. m_DecayTime = 0;
  129. }
  130. /// <summary>
  131. /// Set the envelop times to 0 and the shapes to default.
  132. /// </summary>
  133. public void Clear()
  134. {
  135. m_AttackShape = m_DecayShape = null;
  136. m_AttackTime = m_SustainTime = m_DecayTime = 0;
  137. }
  138. /// <summary>
  139. /// Call from OnValidate to ensure that envelope values are sane
  140. /// </summary>
  141. public void Validate()
  142. {
  143. m_AttackTime = Mathf.Max(0, m_AttackTime);
  144. m_DecayTime = Mathf.Max(0, m_DecayTime);
  145. m_SustainTime = Mathf.Max(0, m_SustainTime);
  146. }
  147. }
  148. internal static float EvaluateDissipationScale(float spread, float normalizedDistance)
  149. {
  150. const float kMin = -0.8f;
  151. const float kMax = 0.8f;
  152. var b = kMin + (kMax - kMin) * (1f - spread);
  153. b = (1f - b) * 0.5f;
  154. var t = Mathf.Clamp01(normalizedDistance) / ((((1f/Mathf.Clamp01(b)) - 2f) * (1f - normalizedDistance)) + 1f);
  155. return 1 - SplineHelpers.Bezier1(t, 0, 0, 1, 1);
  156. }
  157. /// <summary>Describes an event that generates an impulse signal on one or more channels.
  158. /// The event has a location in space, a start time, a duration, and a signal. The signal
  159. /// will dissipate as the distance from the event location increases.</summary>
  160. public class ImpulseEvent
  161. {
  162. /// <summary>Start time of the event.</summary>
  163. public float m_StartTime;
  164. /// <summary>Time-envelope of the signal.</summary>
  165. public EnvelopeDefinition m_Envelope;
  166. /// <summary>Raw signal source. The ouput of this will be scaled to fit in the envelope.</summary>
  167. public ISignalSource6D m_SignalSource;
  168. /// <summary>Worldspace origin of the signal.</summary>
  169. public Vector3 m_Position;
  170. /// <summary>Radius around the signal origin that has full signal value. Distance dissipation begins after this distance.</summary>
  171. public float m_Radius;
  172. /// <summary>How the signal behaves as the listener moves away from the origin.</summary>
  173. public enum DirectionMode
  174. {
  175. /// <summary>Signal direction remains constant everywhere.</summary>
  176. Fixed,
  177. /// <summary>Signal is rotated in the direction of the source.</summary>
  178. RotateTowardSource
  179. }
  180. /// <summary>How the signal direction behaves as the listener moves away from the source.</summary>
  181. public DirectionMode m_DirectionMode = DirectionMode.Fixed;
  182. /// <summary>Channels on which this event will broadcast its signal.</summary>
  183. public int m_Channel;
  184. /// <summary>How the signal dissipates with distance.</summary>
  185. public enum DissipationMode
  186. {
  187. /// <summary>Simple linear interpolation to zero over the dissipation distance.</summary>
  188. LinearDecay,
  189. /// <summary>Ease-in-ease-out dissipation over the dissipation distance.</summary>
  190. SoftDecay,
  191. /// <summary>Half-life decay, hard out from full and ease into 0 over the dissipation distance.</summary>
  192. ExponentialDecay
  193. }
  194. /// <summary>How the signal dissipates with distance.</summary>
  195. public DissipationMode m_DissipationMode;
  196. /// <summary>Distance over which the dissipation occurs. Must be >= 0.</summary>
  197. public float m_DissipationDistance;
  198. /// <summary>
  199. /// How the effect fades with distance. 0 = no dissipation, 1 = rapid dissipation, -1 = off (legacy mode)
  200. /// </summary>
  201. public float m_CustomDissipation;
  202. /// <summary>
  203. /// The speed (m/s) at which the impulse propagates through space. High speeds
  204. /// allow listeners to react instantaneously, while slower speeds allow listeres in the
  205. /// scene to react as if to a wave spreading from the source.
  206. /// </summary>
  207. public float m_PropagationSpeed;
  208. /// <summary>Returns true if the event is no longer generating a signal because its time has expired</summary>
  209. public bool Expired
  210. {
  211. get
  212. {
  213. var d = m_Envelope.Duration;
  214. var maxDistance = m_Radius + m_DissipationDistance;
  215. float time = Instance.CurrentTime - maxDistance / Mathf.Max(1, m_PropagationSpeed);
  216. return d > 0 && m_StartTime + d <= time;
  217. }
  218. }
  219. /// <summary>Cancel the event at the supplied time</summary>
  220. /// <param name="time">The time at which to cancel the event</param>
  221. /// <param name="forceNoDecay">If true, event will be cut immediately at the time,
  222. /// otherwise its envelope's decay curve will begin at the cancel time</param>
  223. public void Cancel(float time, bool forceNoDecay)
  224. {
  225. m_Envelope.m_HoldForever = false;
  226. m_Envelope.ChangeStopTime(time - m_StartTime, forceNoDecay);
  227. }
  228. /// <summary>Calculate the the decay applicable at a given distance from the impact point</summary>
  229. /// <param name="distance">The distance over which to perform the decay</param>
  230. /// <returns>Scale factor 0...1</returns>
  231. public float DistanceDecay(float distance)
  232. {
  233. float radius = Mathf.Max(m_Radius, 0);
  234. if (distance < radius)
  235. return 1;
  236. distance -= radius;
  237. if (distance >= m_DissipationDistance)
  238. return 0;
  239. if (m_CustomDissipation >= 0)
  240. return EvaluateDissipationScale(m_CustomDissipation, distance / m_DissipationDistance);
  241. switch (m_DissipationMode)
  242. {
  243. default:
  244. case DissipationMode.LinearDecay:
  245. return Mathf.Lerp(1, 0, distance / m_DissipationDistance);
  246. case DissipationMode.SoftDecay:
  247. return 0.5f * (1 + Mathf.Cos(Mathf.PI * (distance / m_DissipationDistance)));
  248. case DissipationMode.ExponentialDecay:
  249. return 1 - Damper.Damp(1, m_DissipationDistance, distance);
  250. }
  251. }
  252. /// <summary>Get the signal that a listener at a given position would perceive</summary>
  253. /// <param name="listenerPosition">The listener's position in world space</param>
  254. /// <param name="use2D">True if distance calculation should ignore Z</param>
  255. /// <param name="pos">The position impulse signal</param>
  256. /// <param name="rot">The rotation impulse signal</param>
  257. /// <returns>true if non-trivial signal is returned</returns>
  258. public bool GetDecayedSignal(
  259. Vector3 listenerPosition, bool use2D, out Vector3 pos, out Quaternion rot)
  260. {
  261. if (m_SignalSource != null)
  262. {
  263. float distance = use2D ? Vector2.Distance(listenerPosition, m_Position)
  264. : Vector3.Distance(listenerPosition, m_Position);
  265. float time = Instance.CurrentTime - m_StartTime
  266. - distance / Mathf.Max(1, m_PropagationSpeed);
  267. float scale = m_Envelope.GetValueAt(time) * DistanceDecay(distance);
  268. if (scale != 0)
  269. {
  270. m_SignalSource.GetSignal(time, out pos, out rot);
  271. pos *= scale;
  272. rot = Quaternion.SlerpUnclamped(Quaternion.identity, rot, scale);
  273. if (m_DirectionMode == DirectionMode.RotateTowardSource && distance > Epsilon)
  274. {
  275. Quaternion q = Quaternion.FromToRotation(Vector3.up, listenerPosition - m_Position);
  276. if (m_Radius > Epsilon)
  277. {
  278. float t = Mathf.Clamp01(distance / m_Radius);
  279. q = Quaternion.Slerp(
  280. q, Quaternion.identity, Mathf.Cos(Mathf.PI * t / 2));
  281. }
  282. pos = q * pos;
  283. }
  284. return true;
  285. }
  286. }
  287. pos = Vector3.zero;
  288. rot = Quaternion.identity;
  289. return false;
  290. }
  291. /// <summary>Reset the event to a default state</summary>
  292. public void Clear()
  293. {
  294. m_Envelope.Clear();
  295. m_StartTime = 0;
  296. m_SignalSource = null;
  297. m_Position = Vector3.zero;
  298. m_Channel = 0;
  299. m_Radius = 0;
  300. m_DissipationDistance = 100;
  301. m_DissipationMode = DissipationMode.ExponentialDecay;
  302. m_CustomDissipation = -1;
  303. }
  304. /// <summary>Don't create them yourself. Use CinemachineImpulseManager.NewImpulseEvent().</summary>
  305. internal ImpulseEvent() {}
  306. }
  307. List<ImpulseEvent> m_ExpiredEvents;
  308. List<ImpulseEvent> m_ActiveEvents;
  309. /// <summary>Get the signal perceived by a listener at a geven location</summary>
  310. /// <param name="listenerLocation">Where the listener is, in world coords</param>
  311. /// <param name="distance2D">True if distance calculation should ignore Z</param>
  312. /// <param name="channelMask">Only Impulse signals on channels in this mask will be considered</param>
  313. /// <param name="pos">The combined position impulse signal resulting from all signals active on the specified channels</param>
  314. /// <param name="rot">The combined rotation impulse signal resulting from all signals active on the specified channels</param>
  315. /// <returns>true if non-trivial signal is returned</returns>
  316. public bool GetImpulseAt(
  317. Vector3 listenerLocation, bool distance2D, int channelMask,
  318. out Vector3 pos, out Quaternion rot)
  319. {
  320. bool nontrivialResult = false;
  321. pos = Vector3.zero;
  322. rot = Quaternion.identity;
  323. if (m_ActiveEvents != null)
  324. {
  325. for (int i = m_ActiveEvents.Count - 1; i >= 0; --i)
  326. {
  327. ImpulseEvent e = m_ActiveEvents[i];
  328. // Prune invalid or expired events
  329. if (e == null || e.Expired)
  330. {
  331. m_ActiveEvents.RemoveAt(i);
  332. if (e != null)
  333. {
  334. // Recycle it
  335. if (m_ExpiredEvents == null)
  336. m_ExpiredEvents = new List<ImpulseEvent>();
  337. e.Clear();
  338. m_ExpiredEvents.Add(e);
  339. }
  340. }
  341. else if ((e.m_Channel & channelMask) != 0)
  342. {
  343. Vector3 pos0 = Vector3.zero;
  344. Quaternion rot0 = Quaternion.identity;
  345. if (e.GetDecayedSignal(listenerLocation, distance2D, out pos0, out rot0))
  346. {
  347. nontrivialResult = true;
  348. pos += pos0;
  349. rot *= rot0;
  350. }
  351. }
  352. }
  353. }
  354. return nontrivialResult;
  355. }
  356. /// <summary>Set this to ignore time scaling so impulses can progress while the game is paused</summary>
  357. public bool IgnoreTimeScale;
  358. /// <summary>
  359. /// This is the Impulse system's current time.
  360. /// Takes into accoount whether impulse is ignoring time scale.
  361. /// </summary>
  362. public float CurrentTime => IgnoreTimeScale ? Time.realtimeSinceStartup : CinemachineCore.CurrentTime;
  363. /// <summary>Get a new ImpulseEvent</summary>
  364. /// <returns>A newly-created impulse event. May be recycled from expired events</returns>
  365. public ImpulseEvent NewImpulseEvent()
  366. {
  367. ImpulseEvent e;
  368. if (m_ExpiredEvents == null || m_ExpiredEvents.Count == 0)
  369. return new ImpulseEvent() { m_CustomDissipation = -1 };
  370. e = m_ExpiredEvents[m_ExpiredEvents.Count-1];
  371. m_ExpiredEvents.RemoveAt(m_ExpiredEvents.Count-1);
  372. return e;
  373. }
  374. /// <summary>Activate an impulse event, so that it may begin broadcasting its signal</summary>
  375. /// Events will be automatically removed after they expire.
  376. /// You can tweak the ImpulseEvent fields dynamically if you keep a pointer to it.
  377. /// <param name="e">The event to add to the current active events</param>
  378. public void AddImpulseEvent(ImpulseEvent e)
  379. {
  380. if (m_ActiveEvents == null)
  381. m_ActiveEvents = new List<ImpulseEvent>();
  382. if (e != null)
  383. {
  384. e.m_StartTime = CurrentTime;
  385. m_ActiveEvents.Add(e);
  386. }
  387. }
  388. /// <summary>Immediately terminate all active impulse signals</summary>
  389. public void Clear()
  390. {
  391. if (m_ActiveEvents != null)
  392. {
  393. for (int i = 0; i < m_ActiveEvents.Count; ++i)
  394. m_ActiveEvents[i].Clear();
  395. m_ActiveEvents.Clear();
  396. }
  397. }
  398. }
  399. }