You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

384 lines
13 KiB

  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. #if UNITY_EDITOR
  5. using UnityEditor;
  6. #endif
  7. namespace UnityStandardAssets.Utility
  8. {
  9. public class WaypointCircuit : MonoBehaviour
  10. {
  11. public WaypointList waypointList = new WaypointList();
  12. [SerializeField] private bool smoothRoute = true;
  13. private int numPoints;
  14. private Vector3[] points;
  15. private float[] distances;
  16. public float editorVisualisationSubsteps = 100;
  17. public float Length { get; private set; }
  18. public Transform[] Waypoints
  19. {
  20. get { return waypointList.items; }
  21. }
  22. //this being here will save GC allocs
  23. private int p0n;
  24. private int p1n;
  25. private int p2n;
  26. private int p3n;
  27. private float i;
  28. private Vector3 P0;
  29. private Vector3 P1;
  30. private Vector3 P2;
  31. private Vector3 P3;
  32. // Use this for initialization
  33. private void Awake()
  34. {
  35. if (Waypoints.Length > 1)
  36. {
  37. CachePositionsAndDistances();
  38. }
  39. numPoints = Waypoints.Length;
  40. }
  41. public RoutePoint GetRoutePoint(float dist)
  42. {
  43. // position and direction
  44. Vector3 p1 = GetRoutePosition(dist);
  45. Vector3 p2 = GetRoutePosition(dist + 0.1f);
  46. Vector3 delta = p2 - p1;
  47. return new RoutePoint(p1, delta.normalized);
  48. }
  49. public Vector3 GetRoutePosition(float dist)
  50. {
  51. int point = 0;
  52. if (Length == 0)
  53. {
  54. Length = distances[distances.Length - 1];
  55. }
  56. dist = Mathf.Repeat(dist, Length);
  57. while (distances[point] < dist)
  58. {
  59. ++point;
  60. }
  61. // get nearest two points, ensuring points wrap-around start & end of circuit
  62. p1n = ((point - 1) + numPoints)%numPoints;
  63. p2n = point;
  64. // found point numbers, now find interpolation value between the two middle points
  65. i = Mathf.InverseLerp(distances[p1n], distances[p2n], dist);
  66. if (smoothRoute)
  67. {
  68. // smooth catmull-rom calculation between the two relevant points
  69. // get indices for the surrounding 2 points, because
  70. // four points are required by the catmull-rom function
  71. p0n = ((point - 2) + numPoints)%numPoints;
  72. p3n = (point + 1)%numPoints;
  73. // 2nd point may have been the 'last' point - a dupe of the first,
  74. // (to give a value of max track distance instead of zero)
  75. // but now it must be wrapped back to zero if that was the case.
  76. p2n = p2n%numPoints;
  77. P0 = points[p0n];
  78. P1 = points[p1n];
  79. P2 = points[p2n];
  80. P3 = points[p3n];
  81. return CatmullRom(P0, P1, P2, P3, i);
  82. }
  83. else
  84. {
  85. // simple linear lerp between the two points:
  86. p1n = ((point - 1) + numPoints)%numPoints;
  87. p2n = point;
  88. return Vector3.Lerp(points[p1n], points[p2n], i);
  89. }
  90. }
  91. private Vector3 CatmullRom(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float i)
  92. {
  93. // comments are no use here... it's the catmull-rom equation.
  94. // Un-magic this, lord vector!
  95. return 0.5f*
  96. ((2*p1) + (-p0 + p2)*i + (2*p0 - 5*p1 + 4*p2 - p3)*i*i +
  97. (-p0 + 3*p1 - 3*p2 + p3)*i*i*i);
  98. }
  99. private void CachePositionsAndDistances()
  100. {
  101. // transfer the position of each point and distances between points to arrays for
  102. // speed of lookup at runtime
  103. points = new Vector3[Waypoints.Length + 1];
  104. distances = new float[Waypoints.Length + 1];
  105. float accumulateDistance = 0;
  106. for (int i = 0; i < points.Length; ++i)
  107. {
  108. var t1 = Waypoints[(i)%Waypoints.Length];
  109. var t2 = Waypoints[(i + 1)%Waypoints.Length];
  110. if (t1 != null && t2 != null)
  111. {
  112. Vector3 p1 = t1.position;
  113. Vector3 p2 = t2.position;
  114. points[i] = Waypoints[i%Waypoints.Length].position;
  115. distances[i] = accumulateDistance;
  116. accumulateDistance += (p1 - p2).magnitude;
  117. }
  118. }
  119. }
  120. private void OnDrawGizmos()
  121. {
  122. DrawGizmos(false);
  123. }
  124. private void OnDrawGizmosSelected()
  125. {
  126. DrawGizmos(true);
  127. }
  128. private void DrawGizmos(bool selected)
  129. {
  130. waypointList.circuit = this;
  131. if (Waypoints.Length > 1)
  132. {
  133. numPoints = Waypoints.Length;
  134. CachePositionsAndDistances();
  135. Length = distances[distances.Length - 1];
  136. Gizmos.color = selected ? Color.yellow : new Color(1, 1, 0, 0.5f);
  137. Vector3 prev = Waypoints[0].position;
  138. if (smoothRoute)
  139. {
  140. for (float dist = 0; dist < Length; dist += Length/editorVisualisationSubsteps)
  141. {
  142. Vector3 next = GetRoutePosition(dist + 1);
  143. Gizmos.DrawLine(prev, next);
  144. prev = next;
  145. }
  146. Gizmos.DrawLine(prev, Waypoints[0].position);
  147. }
  148. else
  149. {
  150. for (int n = 0; n < Waypoints.Length; ++n)
  151. {
  152. Vector3 next = Waypoints[(n + 1)%Waypoints.Length].position;
  153. Gizmos.DrawLine(prev, next);
  154. prev = next;
  155. }
  156. }
  157. }
  158. }
  159. [Serializable]
  160. public class WaypointList
  161. {
  162. public WaypointCircuit circuit;
  163. public Transform[] items = new Transform[0];
  164. }
  165. public struct RoutePoint
  166. {
  167. public Vector3 position;
  168. public Vector3 direction;
  169. public RoutePoint(Vector3 position, Vector3 direction)
  170. {
  171. this.position = position;
  172. this.direction = direction;
  173. }
  174. }
  175. }
  176. }
  177. namespace UnityStandardAssets.Utility.Inspector
  178. {
  179. #if UNITY_EDITOR
  180. [CustomPropertyDrawer(typeof (WaypointCircuit.WaypointList))]
  181. public class WaypointListDrawer : PropertyDrawer
  182. {
  183. private float lineHeight = 18;
  184. private float spacing = 4;
  185. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  186. {
  187. EditorGUI.BeginProperty(position, label, property);
  188. float x = position.x;
  189. float y = position.y;
  190. float inspectorWidth = position.width;
  191. // Draw label
  192. // Don't make child fields be indented
  193. var indent = EditorGUI.indentLevel;
  194. EditorGUI.indentLevel = 0;
  195. var items = property.FindPropertyRelative("items");
  196. var titles = new string[] {"Transform", "", "", ""};
  197. var props = new string[] {"transform", "^", "v", "-"};
  198. var widths = new float[] {.7f, .1f, .1f, .1f};
  199. float lineHeight = 18;
  200. bool changedLength = false;
  201. if (items.arraySize > 0)
  202. {
  203. for (int i = -1; i < items.arraySize; ++i)
  204. {
  205. var item = items.GetArrayElementAtIndex(i);
  206. float rowX = x;
  207. for (int n = 0; n < props.Length; ++n)
  208. {
  209. float w = widths[n]*inspectorWidth;
  210. // Calculate rects
  211. Rect rect = new Rect(rowX, y, w, lineHeight);
  212. rowX += w;
  213. if (i == -1)
  214. {
  215. EditorGUI.LabelField(rect, titles[n]);
  216. }
  217. else
  218. {
  219. if (n == 0)
  220. {
  221. EditorGUI.ObjectField(rect, item.objectReferenceValue, typeof (Transform), true);
  222. }
  223. else
  224. {
  225. if (GUI.Button(rect, props[n]))
  226. {
  227. switch (props[n])
  228. {
  229. case "-":
  230. items.DeleteArrayElementAtIndex(i);
  231. items.DeleteArrayElementAtIndex(i);
  232. changedLength = true;
  233. break;
  234. case "v":
  235. if (i > 0)
  236. {
  237. items.MoveArrayElement(i, i + 1);
  238. }
  239. break;
  240. case "^":
  241. if (i < items.arraySize - 1)
  242. {
  243. items.MoveArrayElement(i, i - 1);
  244. }
  245. break;
  246. }
  247. }
  248. }
  249. }
  250. }
  251. y += lineHeight + spacing;
  252. if (changedLength)
  253. {
  254. break;
  255. }
  256. }
  257. }
  258. else
  259. {
  260. // add button
  261. var addButtonRect = new Rect((x + position.width) - widths[widths.Length - 1]*inspectorWidth, y,
  262. widths[widths.Length - 1]*inspectorWidth, lineHeight);
  263. if (GUI.Button(addButtonRect, "+"))
  264. {
  265. items.InsertArrayElementAtIndex(items.arraySize);
  266. }
  267. y += lineHeight + spacing;
  268. }
  269. // add all button
  270. var addAllButtonRect = new Rect(x, y, inspectorWidth, lineHeight);
  271. if (GUI.Button(addAllButtonRect, "Assign using all child objects"))
  272. {
  273. var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit;
  274. var children = new Transform[circuit.transform.childCount];
  275. int n = 0;
  276. foreach (Transform child in circuit.transform)
  277. {
  278. children[n++] = child;
  279. }
  280. Array.Sort(children, new TransformNameComparer());
  281. circuit.waypointList.items = new Transform[children.Length];
  282. for (n = 0; n < children.Length; ++n)
  283. {
  284. circuit.waypointList.items[n] = children[n];
  285. }
  286. }
  287. y += lineHeight + spacing;
  288. // rename all button
  289. var renameButtonRect = new Rect(x, y, inspectorWidth, lineHeight);
  290. if (GUI.Button(renameButtonRect, "Auto Rename numerically from this order"))
  291. {
  292. var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit;
  293. int n = 0;
  294. foreach (Transform child in circuit.waypointList.items)
  295. {
  296. child.name = "Waypoint " + (n++).ToString("000");
  297. }
  298. }
  299. y += lineHeight + spacing;
  300. // Set indent back to what it was
  301. EditorGUI.indentLevel = indent;
  302. EditorGUI.EndProperty();
  303. }
  304. public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
  305. {
  306. SerializedProperty items = property.FindPropertyRelative("items");
  307. float lineAndSpace = lineHeight + spacing;
  308. return 40 + (items.arraySize*lineAndSpace) + lineAndSpace;
  309. }
  310. // comparer for check distances in ray cast hits
  311. public class TransformNameComparer : IComparer
  312. {
  313. public int Compare(object x, object y)
  314. {
  315. return ((Transform) x).name.CompareTo(((Transform) y).name);
  316. }
  317. }
  318. }
  319. #endif
  320. }