No Description
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.

Solver2D.cs 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.Scripting.APIUpdating;
  4. using UnityEngine.Serialization;
  5. namespace UnityEngine.U2D.IK
  6. {
  7. /// <summary>
  8. /// Abstract class for implementing a 2D IK Solver.
  9. /// </summary>
  10. [MovedFrom("UnityEngine.Experimental.U2D.IK")]
  11. public abstract class Solver2D : MonoBehaviour
  12. {
  13. [SerializeField]
  14. bool m_ConstrainRotation = true;
  15. [FormerlySerializedAs("m_RestoreDefaultPose")]
  16. [SerializeField]
  17. bool m_SolveFromDefaultPose = true;
  18. [SerializeField]
  19. [Range(0f, 1f)]
  20. float m_Weight = 1f;
  21. Plane m_Plane;
  22. List<Vector3> m_TargetPositions = new List<Vector3>();
  23. /// <summary>
  24. /// Used to evaluate if Solver2D needs to be updated.
  25. /// </summary>
  26. float m_LastFinalWeight;
  27. /// <summary>
  28. /// Returns the number of IKChain2D in the solver.
  29. /// </summary>
  30. public int chainCount => GetChainCount();
  31. /// <summary>
  32. /// Get Set for rotation constrain property.
  33. /// </summary>
  34. public bool constrainRotation
  35. {
  36. get => m_ConstrainRotation;
  37. set => m_ConstrainRotation = value;
  38. }
  39. /// <summary>
  40. /// Get Set for restoring default pose.
  41. /// </summary>
  42. public bool solveFromDefaultPose
  43. {
  44. get => m_SolveFromDefaultPose;
  45. set => m_SolveFromDefaultPose = value;
  46. }
  47. /// <summary>
  48. /// Returns true if the Solver2D is in a valid state.
  49. /// </summary>
  50. public bool isValid => Validate();
  51. /// <summary>
  52. /// Returns true if all chains in the Solver has a target.
  53. /// </summary>
  54. public bool allChainsHaveTargets => HasTargets();
  55. /// <summary>
  56. /// Get and Set Solver weights.
  57. /// </summary>
  58. public float weight
  59. {
  60. get => m_Weight;
  61. set => m_Weight = Mathf.Clamp01(value);
  62. }
  63. /// <summary>
  64. /// Validate and initialize the Solver.
  65. /// </summary>
  66. protected virtual void OnValidate()
  67. {
  68. m_Weight = Mathf.Clamp01(m_Weight);
  69. if (!isValid)
  70. Initialize();
  71. }
  72. bool Validate()
  73. {
  74. for (var i = 0; i < GetChainCount(); ++i)
  75. {
  76. var chain = GetChain(i);
  77. if (!chain.isValid)
  78. return false;
  79. }
  80. return DoValidate();
  81. }
  82. bool HasTargets()
  83. {
  84. for (var i = 0; i < GetChainCount(); ++i)
  85. {
  86. var chain = GetChain(i);
  87. if (chain.target == null)
  88. return false;
  89. }
  90. return true;
  91. }
  92. /// <summary>
  93. /// Initializes the solver.
  94. /// </summary>
  95. public void Initialize()
  96. {
  97. DoInitialize();
  98. for (var i = 0; i < GetChainCount(); ++i)
  99. {
  100. var chain = GetChain(i);
  101. chain.Initialize();
  102. }
  103. }
  104. void Prepare()
  105. {
  106. var rootTransform = GetPlaneRootTransform();
  107. if (rootTransform != null)
  108. {
  109. m_Plane.normal = rootTransform.forward;
  110. m_Plane.distance = -Vector3.Dot(m_Plane.normal, rootTransform.position);
  111. }
  112. for (var i = 0; i < GetChainCount(); ++i)
  113. {
  114. var chain = GetChain(i);
  115. var constrainTargetRotation = constrainRotation && chain.target != null;
  116. if (m_SolveFromDefaultPose)
  117. chain.RestoreDefaultPose(constrainTargetRotation);
  118. }
  119. DoPrepare();
  120. }
  121. void PrepareEffectorPositions()
  122. {
  123. m_TargetPositions.Clear();
  124. for (var i = 0; i < GetChainCount(); ++i)
  125. {
  126. var chain = GetChain(i);
  127. if (chain.target)
  128. m_TargetPositions.Add(chain.target.position);
  129. }
  130. }
  131. /// <summary>
  132. /// Perform Solver IK update.
  133. /// </summary>
  134. /// <param name="globalWeight">Weight for position solving.</param>
  135. public void UpdateIK(float globalWeight)
  136. {
  137. if (allChainsHaveTargets)
  138. {
  139. PrepareEffectorPositions();
  140. UpdateIK(m_TargetPositions, globalWeight);
  141. }
  142. }
  143. /// <summary>
  144. /// Perform Solver IK update.
  145. /// </summary>
  146. /// <param name="positions">Positions of chain.</param>
  147. /// <param name="globalWeight">Weight for position solving.</param>
  148. public void UpdateIK(List<Vector3> positions, float globalWeight)
  149. {
  150. if (positions.Count != chainCount)
  151. return;
  152. var finalWeight = globalWeight * weight;
  153. var weightValueChanged = Math.Abs(finalWeight - m_LastFinalWeight) > 0.0001f;
  154. m_LastFinalWeight = finalWeight;
  155. if (finalWeight == 0f && !weightValueChanged)
  156. return;
  157. if (!isValid)
  158. return;
  159. Prepare();
  160. if (finalWeight < 1f)
  161. StoreLocalRotations();
  162. DoUpdateIK(positions);
  163. if (constrainRotation)
  164. {
  165. for (var i = 0; i < GetChainCount(); ++i)
  166. {
  167. var chain = GetChain(i);
  168. if (chain.target)
  169. chain.effector.rotation = chain.target.rotation;
  170. }
  171. }
  172. if (finalWeight < 1f)
  173. BlendFkToIk(finalWeight);
  174. }
  175. void StoreLocalRotations()
  176. {
  177. for (var i = 0; i < GetChainCount(); ++i)
  178. {
  179. var chain = GetChain(i);
  180. chain.StoreLocalRotations();
  181. }
  182. }
  183. void BlendFkToIk(float finalWeight)
  184. {
  185. for (var i = 0; i < GetChainCount(); ++i)
  186. {
  187. var chain = GetChain(i);
  188. var constrainTargetRotation = constrainRotation && chain.target != null;
  189. chain.BlendFkToIk(finalWeight, constrainTargetRotation);
  190. }
  191. }
  192. /// <summary>
  193. /// Override to return the IKChain2D at the given index.
  194. /// </summary>
  195. /// <param name="index">Index for IKChain2D.</param>
  196. /// <returns></returns>
  197. public abstract IKChain2D GetChain(int index);
  198. /// <summary>
  199. /// Override to return the number of chains in the Solver
  200. /// </summary>
  201. /// <returns>Integer represents IKChain2D count.</returns>
  202. protected abstract int GetChainCount();
  203. /// <summary>
  204. /// Override to perform Solver IK update
  205. /// </summary>
  206. /// <param name="effectorPositions">Position of the effectors.</param>
  207. protected abstract void DoUpdateIK(List<Vector3> effectorPositions);
  208. /// <summary>
  209. /// Override to perform custom validation.
  210. /// </summary>
  211. /// <returns>Returns true if the Solver is in a valid state. False otherwise.</returns>
  212. protected virtual bool DoValidate() => true;
  213. /// <summary>
  214. /// Override to perform initialize the solver
  215. /// </summary>
  216. protected virtual void DoInitialize() { }
  217. /// <summary>
  218. /// Override to prepare the solver for update
  219. /// </summary>
  220. protected virtual void DoPrepare() { }
  221. /// <summary>
  222. /// Override to return the root Unity Transform of the Solver. The default implementation returns the root
  223. /// transform of the first chain.
  224. /// </summary>
  225. /// <returns>Unity Transform that represents the root.</returns>
  226. protected virtual Transform GetPlaneRootTransform()
  227. {
  228. return chainCount > 0 ? GetChain(0).rootTransform : null;
  229. }
  230. /// <summary>
  231. /// Convert a world position coordinate to the solver's plane space
  232. /// </summary>
  233. /// <param name="worldPosition">Vector3 representing world position</param>
  234. /// <returns>Converted position in solver's plane</returns>
  235. protected Vector3 GetPointOnSolverPlane(Vector3 worldPosition)
  236. {
  237. return GetPlaneRootTransform().InverseTransformPoint(m_Plane.ClosestPointOnPlane(worldPosition));
  238. }
  239. /// <summary>
  240. /// Convert a position from solver's plane to world coordinate
  241. /// </summary>
  242. /// <param name="planePoint">Vector3 representing a position in the Solver's plane.</param>
  243. /// <returns>Converted position to world coordinate.</returns>
  244. protected Vector3 GetWorldPositionFromSolverPlanePoint(Vector2 planePoint)
  245. {
  246. return GetPlaneRootTransform().TransformPoint(planePoint);
  247. }
  248. }
  249. }