CubicBezierCurve.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Events;
  6. namespace SplineMesh {
  7. /// <summary>
  8. /// Mathematical object for cubic Bézier curve definition.
  9. /// It is made of two spline nodes which hold the four needed control points : two positions and two directions
  10. /// It provides methods to get positions and tangent along the curve, specifying a distance or a ratio, plus the curve length.
  11. ///
  12. /// Note that a time of 0.5 and half the total distance won't necessarily define the same curve point as the curve curvature is not linear.
  13. /// </summary>
  14. [Serializable]
  15. public class CubicBezierCurve {
  16. private const int STEP_COUNT = 30;
  17. private const float T_STEP = 1.0f / STEP_COUNT;
  18. private readonly List<CurveSample> samples = new List<CurveSample>(STEP_COUNT);
  19. public SplineNode n1, n2;
  20. /// <summary>
  21. /// Length of the curve in world unit.
  22. /// </summary>
  23. public float Length { get; private set; }
  24. /// <summary>
  25. /// This event is raised when of of the control points has moved.
  26. /// </summary>
  27. public UnityEvent Changed = new UnityEvent();
  28. /// <summary>
  29. /// Build a new cubic Bézier curve between two given spline node.
  30. /// </summary>
  31. /// <param name="n1"></param>
  32. /// <param name="n2"></param>
  33. public CubicBezierCurve(SplineNode n1, SplineNode n2) {
  34. this.n1 = n1;
  35. this.n2 = n2;
  36. n1.Changed += ComputeSamples;
  37. n2.Changed += ComputeSamples;
  38. ComputeSamples(null, null);
  39. }
  40. /// <summary>
  41. /// Change the start node of the curve.
  42. /// </summary>
  43. /// <param name="n1"></param>
  44. public void ConnectStart(SplineNode n1) {
  45. this.n1.Changed -= ComputeSamples;
  46. this.n1 = n1;
  47. n1.Changed += ComputeSamples;
  48. ComputeSamples(null, null);
  49. }
  50. /// <summary>
  51. /// Change the end node of the curve.
  52. /// </summary>
  53. /// <param name="n2"></param>
  54. public void ConnectEnd(SplineNode n2) {
  55. this.n2.Changed -= ComputeSamples;
  56. this.n2 = n2;
  57. n2.Changed += ComputeSamples;
  58. ComputeSamples(null, null);
  59. }
  60. /// <summary>
  61. /// Convinent method to get the third control point of the curve, as the direction of the end spline node indicates the starting tangent of the next curve.
  62. /// </summary>
  63. /// <returns></returns>
  64. public Vector3 GetInverseDirection() {
  65. return (2 * n2.Position) - n2.Direction;
  66. }
  67. /// <summary>
  68. /// Returns point on curve at given time. Time must be between 0 and 1.
  69. /// </summary>
  70. /// <param name="t"></param>
  71. /// <returns></returns>
  72. private Vector3 GetLocation(float t) {
  73. float omt = 1f - t;
  74. float omt2 = omt * omt;
  75. float t2 = t * t;
  76. return
  77. n1.Position * (omt2 * omt) +
  78. n1.Direction * (3f * omt2 * t) +
  79. GetInverseDirection() * (3f * omt * t2) +
  80. n2.Position * (t2 * t);
  81. }
  82. /// <summary>
  83. /// Returns tangent of curve at given time. Time must be between 0 and 1.
  84. /// </summary>
  85. /// <param name="t"></param>
  86. /// <returns></returns>
  87. private Vector3 GetTangent(float t) {
  88. float omt = 1f - t;
  89. float omt2 = omt * omt;
  90. float t2 = t * t;
  91. Vector3 tangent =
  92. n1.Position * (-omt2) +
  93. n1.Direction * (3 * omt2 - 2 * omt) +
  94. GetInverseDirection() * (-3 * t2 + 2 * t) +
  95. n2.Position * (t2);
  96. return tangent.normalized;
  97. }
  98. private Vector3 GetUp(float t) {
  99. return Vector3.Lerp(n1.Up, n2.Up, t);
  100. }
  101. private Vector2 GetScale(float t) {
  102. return Vector2.Lerp(n1.Scale, n2.Scale, t);
  103. }
  104. private float GetRoll(float t) {
  105. return Mathf.Lerp(n1.Roll, n2.Roll, t);
  106. }
  107. private void ComputeSamples(object sender, EventArgs e) {
  108. samples.Clear();
  109. Length = 0;
  110. Vector3 previousPosition = GetLocation(0);
  111. for (float t = 0; t < 1; t += T_STEP) {
  112. Vector3 position = GetLocation(t);
  113. Length += Vector3.Distance(previousPosition, position);
  114. previousPosition = position;
  115. samples.Add(CreateSample(Length, t));
  116. }
  117. Length += Vector3.Distance(previousPosition, GetLocation(1));
  118. samples.Add(CreateSample(Length, 1));
  119. if (Changed != null) Changed.Invoke();
  120. }
  121. private CurveSample CreateSample(float distance, float time) {
  122. return new CurveSample(
  123. GetLocation(time),
  124. GetTangent(time),
  125. GetUp(time),
  126. GetScale(time),
  127. GetRoll(time),
  128. distance,
  129. time,
  130. this);
  131. }
  132. /// <summary>
  133. /// Returns an interpolated sample of the curve, containing all curve data at this time.
  134. /// </summary>
  135. /// <param name="time"></param>
  136. /// <returns></returns>
  137. public CurveSample GetSample(float time) {
  138. AssertTimeInBounds(time);
  139. CurveSample previous = samples[0];
  140. CurveSample next = default(CurveSample);
  141. bool found = false;
  142. foreach (CurveSample cp in samples) {
  143. if (cp.timeInCurve >= time) {
  144. next = cp;
  145. found = true;
  146. break;
  147. }
  148. previous = cp;
  149. }
  150. if (!found) throw new Exception("Can't find curve samples.");
  151. float t = next == previous ? 0 : (time - previous.timeInCurve) / (next.timeInCurve - previous.timeInCurve);
  152. return CurveSample.Lerp(previous, next, t);
  153. }
  154. /// <summary>
  155. /// Returns an interpolated sample of the curve, containing all curve data at this distance.
  156. /// </summary>
  157. /// <param name="d"></param>
  158. /// <returns></returns>
  159. public CurveSample GetSampleAtDistance(float d) {
  160. if (d < 0 || d > Length)
  161. throw new ArgumentException("Distance must be positive and less than curve length. Length = " + Length + ", given distance was " + d);
  162. CurveSample previous = samples[0];
  163. CurveSample next = default(CurveSample);
  164. bool found = false;
  165. foreach (CurveSample cp in samples) {
  166. if (cp.distanceInCurve >= d) {
  167. next = cp;
  168. found = true;
  169. break;
  170. }
  171. previous = cp;
  172. }
  173. if (!found) throw new Exception("Can't find curve samples.");
  174. float t = next == previous ? 0 : (d - previous.distanceInCurve) / (next.distanceInCurve - previous.distanceInCurve);
  175. return CurveSample.Lerp(previous, next, t);
  176. }
  177. private static void AssertTimeInBounds(float time) {
  178. if (time < 0 || time > 1) throw new ArgumentException("Time must be between 0 and 1 (was " + time + ").");
  179. }
  180. public CurveSample GetProjectionSample(Vector3 pointToProject) {
  181. float minSqrDistance = float.PositiveInfinity;
  182. int closestIndex = -1;
  183. int i = 0;
  184. foreach (var sample in samples) {
  185. float sqrDistance = (sample.location - pointToProject).sqrMagnitude;
  186. if (sqrDistance < minSqrDistance) {
  187. minSqrDistance = sqrDistance;
  188. closestIndex = i;
  189. }
  190. i++;
  191. }
  192. CurveSample previous, next;
  193. if(closestIndex == 0) {
  194. previous = samples[closestIndex];
  195. next = samples[closestIndex + 1];
  196. } else if(closestIndex == samples.Count - 1) {
  197. previous = samples[closestIndex - 1];
  198. next = samples[closestIndex];
  199. } else {
  200. var toPreviousSample = (pointToProject - samples[closestIndex - 1].location).sqrMagnitude;
  201. var toNextSample = (pointToProject - samples[closestIndex + 1].location).sqrMagnitude;
  202. if (toPreviousSample < toNextSample) {
  203. previous = samples[closestIndex - 1];
  204. next = samples[closestIndex];
  205. } else {
  206. previous = samples[closestIndex];
  207. next = samples[closestIndex + 1];
  208. }
  209. }
  210. var onCurve = Vector3.Project(pointToProject - previous.location, next.location - previous.location) + previous.location;
  211. var rate = (onCurve - previous.location).sqrMagnitude / (next.location - previous.location).sqrMagnitude;
  212. rate = Mathf.Clamp(rate, 0, 1);
  213. var result = CurveSample.Lerp(previous, next, rate);
  214. return result;
  215. }
  216. }
  217. }