IkConstraint.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software
  13. * or otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. using System;
  30. namespace Spine {
  31. /// <summary>
  32. /// <para>
  33. /// Stores the current pose for an IK constraint. An IK constraint adjusts the rotation of 1 or 2 constrained bones so the tip of
  34. /// the last bone is as close to the target bone as possible.</para>
  35. /// <para>
  36. /// See <a href="http://esotericsoftware.com/spine-ik-constraints">IK constraints</a> in the Spine User Guide.</para>
  37. /// </summary>
  38. public class IkConstraint : IUpdatable {
  39. internal IkConstraintData data;
  40. internal ExposedList<Bone> bones = new ExposedList<Bone>();
  41. internal Bone target;
  42. internal int bendDirection;
  43. internal bool compress, stretch;
  44. internal float mix = 1, softness;
  45. internal bool active;
  46. public IkConstraint (IkConstraintData data, Skeleton skeleton) {
  47. if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
  48. if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
  49. this.data = data;
  50. mix = data.mix;
  51. softness = data.softness;
  52. bendDirection = data.bendDirection;
  53. compress = data.compress;
  54. stretch = data.stretch;
  55. bones = new ExposedList<Bone>(data.bones.Count);
  56. foreach (BoneData boneData in data.bones)
  57. bones.Add(skeleton.FindBone(boneData.name));
  58. target = skeleton.FindBone(data.target.name);
  59. }
  60. /// <summary>Copy constructor.</summary>
  61. public IkConstraint (IkConstraint constraint, Skeleton skeleton) {
  62. if (constraint == null) throw new ArgumentNullException("constraint cannot be null.");
  63. if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null.");
  64. data = constraint.data;
  65. bones = new ExposedList<Bone>(constraint.Bones.Count);
  66. foreach (Bone bone in constraint.Bones)
  67. bones.Add(skeleton.Bones.Items[bone.data.index]);
  68. target = skeleton.Bones.Items[constraint.target.data.index];
  69. mix = constraint.mix;
  70. softness = constraint.softness;
  71. bendDirection = constraint.bendDirection;
  72. compress = constraint.compress;
  73. stretch = constraint.stretch;
  74. }
  75. public void Update () {
  76. if (mix == 0) return;
  77. Bone target = this.target;
  78. var bones = this.bones.Items;
  79. switch (this.bones.Count) {
  80. case 1:
  81. Apply(bones[0], target.worldX, target.worldY, compress, stretch, data.uniform, mix);
  82. break;
  83. case 2:
  84. Apply(bones[0], bones[1], target.worldX, target.worldY, bendDirection, stretch, data.uniform, softness, mix);
  85. break;
  86. }
  87. }
  88. /// <summary>The bones that will be modified by this IK constraint.</summary>
  89. public ExposedList<Bone> Bones {
  90. get { return bones; }
  91. }
  92. /// <summary>The bone that is the IK target.</summary>
  93. public Bone Target {
  94. get { return target; }
  95. set { target = value; }
  96. }
  97. /// <summary>A percentage (0-1) that controls the mix between the constrained and unconstrained rotation.
  98. /// <para>
  99. /// For two bone IK: if the parent bone has local nonuniform scale, the child bone's local Y translation is set to 0.
  100. /// </para></summary>
  101. public float Mix {
  102. get { return mix; }
  103. set { mix = value; }
  104. }
  105. /// <summary>For two bone IK, the target bone's distance from the maximum reach of the bones where rotation begins to slow. The bones
  106. /// will not straighten completely until the target is this far out of range.</summary>
  107. public float Softness {
  108. get { return softness; }
  109. set { softness = value; }
  110. }
  111. /// <summary>For two bone IK, controls the bend direction of the IK bones, either 1 or -1.</summary>
  112. public int BendDirection {
  113. get { return bendDirection; }
  114. set { bendDirection = value; }
  115. }
  116. /// <summary>For one bone IK, when true and the target is too close, the bone is scaled to reach it.</summary>
  117. public bool Compress {
  118. get { return compress; }
  119. set { compress = value; }
  120. }
  121. /// <summary>When true and the target is out of range, the parent bone is scaled to reach it.
  122. /// <para>
  123. /// For two bone IK: 1) the child bone's local Y translation is set to 0,
  124. /// 2) stretch is not applied if <see cref="Softness"/> is > 0,
  125. /// and 3) if the parent bone has local nonuniform scale, stretch is not applied.
  126. /// </para></summary>
  127. public bool Stretch {
  128. get { return stretch; }
  129. set { stretch = value; }
  130. }
  131. public bool Active {
  132. get { return active; }
  133. }
  134. /// <summary>The IK constraint's setup pose data.</summary>
  135. public IkConstraintData Data {
  136. get { return data; }
  137. }
  138. override public string ToString () {
  139. return data.name;
  140. }
  141. /// <summary>Applies 1 bone IK. The target is specified in the world coordinate system.</summary>
  142. static public void Apply (Bone bone, float targetX, float targetY, bool compress, bool stretch, bool uniform,
  143. float alpha) {
  144. if (bone == null) throw new ArgumentNullException("bone", "bone cannot be null.");
  145. Bone p = bone.parent;
  146. float pa = p.a, pb = p.b, pc = p.c, pd = p.d;
  147. float rotationIK = -bone.ashearX - bone.arotation;
  148. float tx = 0, ty = 0;
  149. switch (bone.data.transformMode) {
  150. case TransformMode.OnlyTranslation:
  151. tx = targetX - bone.worldX;
  152. ty = targetY - bone.worldY;
  153. break;
  154. case TransformMode.NoRotationOrReflection: {
  155. float s = Math.Abs(pa * pd - pb * pc) / (pa * pa + pc * pc);
  156. float sa = pa / bone.skeleton.ScaleX;
  157. float sc = pc / bone.skeleton.ScaleY;
  158. pb = -sc * s * bone.skeleton.ScaleX;
  159. pd = sa * s * bone.skeleton.ScaleY;
  160. rotationIK += (float)Math.Atan2(sc, sa) * MathUtils.RadDeg;
  161. goto default; // Fall through.
  162. }
  163. default: {
  164. float x = targetX - p.worldX, y = targetY - p.worldY;
  165. float d = pa * pd - pb * pc;
  166. tx = (x * pd - y * pb) / d - bone.ax;
  167. ty = (y * pa - x * pc) / d - bone.ay;
  168. break;
  169. }
  170. }
  171. rotationIK += (float)Math.Atan2(ty, tx) * MathUtils.RadDeg;
  172. if (bone.ascaleX < 0) rotationIK += 180;
  173. if (rotationIK > 180)
  174. rotationIK -= 360;
  175. else if (rotationIK < -180) //
  176. rotationIK += 360;
  177. float sx = bone.ascaleX, sy = bone.ascaleY;
  178. if (compress || stretch) {
  179. switch (bone.data.transformMode) {
  180. case TransformMode.NoScale:
  181. case TransformMode.NoScaleOrReflection:
  182. tx = targetX - bone.worldX;
  183. ty = targetY - bone.worldY;
  184. break;
  185. }
  186. float b = bone.data.length * sx, dd = (float)Math.Sqrt(tx * tx + ty * ty);
  187. if ((compress && dd < b) || (stretch && dd > b) && b > 0.0001f) {
  188. float s = (dd / b - 1) * alpha + 1;
  189. sx *= s;
  190. if (uniform) sy *= s;
  191. }
  192. }
  193. bone.UpdateWorldTransform(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, sx, sy, bone.ashearX, bone.ashearY);
  194. }
  195. /// <summary>Applies 2 bone IK. The target is specified in the world coordinate system.</summary>
  196. /// <param name="child">A direct descendant of the parent bone.</param>
  197. static public void Apply (Bone parent, Bone child, float targetX, float targetY, int bendDir, bool stretch, bool uniform,
  198. float softness, float alpha) {
  199. if (parent == null) throw new ArgumentNullException("parent", "parent cannot be null.");
  200. if (child == null) throw new ArgumentNullException("child", "child cannot be null.");
  201. float px = parent.ax, py = parent.ay, psx = parent.ascaleX, psy = parent.ascaleY, sx = psx, sy = psy, csx = child.ascaleX;
  202. int os1, os2, s2;
  203. if (psx < 0) {
  204. psx = -psx;
  205. os1 = 180;
  206. s2 = -1;
  207. } else {
  208. os1 = 0;
  209. s2 = 1;
  210. }
  211. if (psy < 0) {
  212. psy = -psy;
  213. s2 = -s2;
  214. }
  215. if (csx < 0) {
  216. csx = -csx;
  217. os2 = 180;
  218. } else
  219. os2 = 0;
  220. float cx = child.ax, cy, cwx, cwy, a = parent.a, b = parent.b, c = parent.c, d = parent.d;
  221. bool u = Math.Abs(psx - psy) <= 0.0001f;
  222. if (!u || stretch) {
  223. cy = 0;
  224. cwx = a * cx + parent.worldX;
  225. cwy = c * cx + parent.worldY;
  226. } else {
  227. cy = child.ay;
  228. cwx = a * cx + b * cy + parent.worldX;
  229. cwy = c * cx + d * cy + parent.worldY;
  230. }
  231. Bone pp = parent.parent;
  232. a = pp.a;
  233. b = pp.b;
  234. c = pp.c;
  235. d = pp.d;
  236. float id = 1 / (a * d - b * c), x = cwx - pp.worldX, y = cwy - pp.worldY;
  237. float dx = (x * d - y * b) * id - px, dy = (y * a - x * c) * id - py;
  238. float l1 = (float)Math.Sqrt(dx * dx + dy * dy), l2 = child.data.length * csx, a1, a2;
  239. if (l1 < 0.0001f) {
  240. Apply(parent, targetX, targetY, false, stretch, false, alpha);
  241. child.UpdateWorldTransform(cx, cy, 0, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY);
  242. return;
  243. }
  244. x = targetX - pp.worldX;
  245. y = targetY - pp.worldY;
  246. float tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py;
  247. float dd = tx * tx + ty * ty;
  248. if (softness != 0) {
  249. softness *= psx * (csx + 1) * 0.5f;
  250. float td = (float)Math.Sqrt(dd), sd = td - l1 - l2 * psx + softness;
  251. if (sd > 0) {
  252. float p = Math.Min(1, sd / (softness * 2)) - 1;
  253. p = (sd - softness * (1 - p * p)) / td;
  254. tx -= p * tx;
  255. ty -= p * ty;
  256. dd = tx * tx + ty * ty;
  257. }
  258. }
  259. if (u) {
  260. l2 *= psx;
  261. float cos = (dd - l1 * l1 - l2 * l2) / (2 * l1 * l2);
  262. if (cos < -1) {
  263. cos = -1;
  264. a2 = MathUtils.PI * bendDir;
  265. } else if (cos > 1) {
  266. cos = 1;
  267. a2 = 0;
  268. if (stretch) {
  269. a = ((float)Math.Sqrt(dd) / (l1 + l2) - 1) * alpha + 1;
  270. sx *= a;
  271. if (uniform) sy *= a;
  272. }
  273. } else
  274. a2 = (float)Math.Acos(cos) * bendDir;
  275. a = l1 + l2 * cos;
  276. b = l2 * (float)Math.Sin(a2);
  277. a1 = (float)Math.Atan2(ty * a - tx * b, tx * a + ty * b);
  278. } else {
  279. a = psx * l2;
  280. b = psy * l2;
  281. float aa = a * a, bb = b * b, ta = (float)Math.Atan2(ty, tx);
  282. c = bb * l1 * l1 + aa * dd - aa * bb;
  283. float c1 = -2 * bb * l1, c2 = bb - aa;
  284. d = c1 * c1 - 4 * c2 * c;
  285. if (d >= 0) {
  286. float q = (float)Math.Sqrt(d);
  287. if (c1 < 0) q = -q;
  288. q = -(c1 + q) * 0.5f;
  289. float r0 = q / c2, r1 = c / q;
  290. float r = Math.Abs(r0) < Math.Abs(r1) ? r0 : r1;
  291. if (r * r <= dd) {
  292. y = (float)Math.Sqrt(dd - r * r) * bendDir;
  293. a1 = ta - (float)Math.Atan2(y, r);
  294. a2 = (float)Math.Atan2(y / psy, (r - l1) / psx);
  295. goto break_outer; // break outer;
  296. }
  297. }
  298. float minAngle = MathUtils.PI, minX = l1 - a, minDist = minX * minX, minY = 0;
  299. float maxAngle = 0, maxX = l1 + a, maxDist = maxX * maxX, maxY = 0;
  300. c = -a * l1 / (aa - bb);
  301. if (c >= -1 && c <= 1) {
  302. c = (float)Math.Acos(c);
  303. x = a * (float)Math.Cos(c) + l1;
  304. y = b * (float)Math.Sin(c);
  305. d = x * x + y * y;
  306. if (d < minDist) {
  307. minAngle = c;
  308. minDist = d;
  309. minX = x;
  310. minY = y;
  311. }
  312. if (d > maxDist) {
  313. maxAngle = c;
  314. maxDist = d;
  315. maxX = x;
  316. maxY = y;
  317. }
  318. }
  319. if (dd <= (minDist + maxDist) * 0.5f) {
  320. a1 = ta - (float)Math.Atan2(minY * bendDir, minX);
  321. a2 = minAngle * bendDir;
  322. } else {
  323. a1 = ta - (float)Math.Atan2(maxY * bendDir, maxX);
  324. a2 = maxAngle * bendDir;
  325. }
  326. }
  327. break_outer:
  328. float os = (float)Math.Atan2(cy, cx) * s2;
  329. float rotation = parent.arotation;
  330. a1 = (a1 - os) * MathUtils.RadDeg + os1 - rotation;
  331. if (a1 > 180)
  332. a1 -= 360;
  333. else if (a1 < -180)
  334. a1 += 360;
  335. parent.UpdateWorldTransform(px, py, rotation + a1 * alpha, sx, sy, 0, 0);
  336. rotation = child.arotation;
  337. a2 = ((a2 + os) * MathUtils.RadDeg - child.ashearX) * s2 + os2 - rotation;
  338. if (a2 > 180)
  339. a2 -= 360;
  340. else if (a2 < -180)
  341. a2 += 360;
  342. child.UpdateWorldTransform(cx, cy, rotation + a2 * alpha, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY);
  343. }
  344. }
  345. }