SkeletonUtility.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. #if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
  30. #define NEW_PREFAB_SYSTEM
  31. #endif
  32. using UnityEngine;
  33. using System.Collections.Generic;
  34. namespace Spine.Unity {
  35. #if NEW_PREFAB_SYSTEM
  36. [ExecuteAlways]
  37. #else
  38. [ExecuteInEditMode]
  39. #endif
  40. [RequireComponent(typeof(ISkeletonAnimation))]
  41. [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonUtility")]
  42. public sealed class SkeletonUtility : MonoBehaviour {
  43. #region BoundingBoxAttachment
  44. public static PolygonCollider2D AddBoundingBoxGameObject (Skeleton skeleton, string skinName, string slotName, string attachmentName, Transform parent, bool isTrigger = true) {
  45. Skin skin = string.IsNullOrEmpty(skinName) ? skeleton.data.defaultSkin : skeleton.data.FindSkin(skinName);
  46. if (skin == null) {
  47. Debug.LogError("Skin " + skinName + " not found!");
  48. return null;
  49. }
  50. var attachment = skin.GetAttachment(skeleton.FindSlotIndex(slotName), attachmentName);
  51. if (attachment == null) {
  52. Debug.LogFormat("Attachment in slot '{0}' named '{1}' not found in skin '{2}'.", slotName, attachmentName, skin.name);
  53. return null;
  54. }
  55. var box = attachment as BoundingBoxAttachment;
  56. if (box != null) {
  57. var slot = skeleton.FindSlot(slotName);
  58. return AddBoundingBoxGameObject(box.Name, box, slot, parent, isTrigger);
  59. } else {
  60. Debug.LogFormat("Attachment '{0}' was not a Bounding Box.", attachmentName);
  61. return null;
  62. }
  63. }
  64. public static PolygonCollider2D AddBoundingBoxGameObject (string name, BoundingBoxAttachment box, Slot slot, Transform parent, bool isTrigger = true) {
  65. var go = new GameObject("[BoundingBox]" + (string.IsNullOrEmpty(name) ? box.Name : name));
  66. #if UNITY_EDITOR
  67. if (!Application.isPlaying)
  68. UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Spawn BoundingBox");
  69. # endif
  70. var got = go.transform;
  71. got.parent = parent;
  72. got.localPosition = Vector3.zero;
  73. got.localRotation = Quaternion.identity;
  74. got.localScale = Vector3.one;
  75. return AddBoundingBoxAsComponent(box, slot, go, isTrigger);
  76. }
  77. public static PolygonCollider2D AddBoundingBoxAsComponent (BoundingBoxAttachment box, Slot slot, GameObject gameObject, bool isTrigger = true) {
  78. if (box == null) return null;
  79. var collider = gameObject.AddComponent<PolygonCollider2D>();
  80. collider.isTrigger = isTrigger;
  81. SetColliderPointsLocal(collider, slot, box);
  82. return collider;
  83. }
  84. public static void SetColliderPointsLocal (PolygonCollider2D collider, Slot slot, BoundingBoxAttachment box, float scale = 1.0f) {
  85. if (box == null) return;
  86. if (box.IsWeighted()) Debug.LogWarning("UnityEngine.PolygonCollider2D does not support weighted or animated points. Collider points will not be animated and may have incorrect orientation. If you want to use it as a collider, please remove weights and animations from the bounding box in Spine editor.");
  87. var verts = box.GetLocalVertices(slot, null);
  88. if (scale != 1.0f) {
  89. for (int i = 0, n = verts.Length; i < n; ++i)
  90. verts[i] *= scale;
  91. }
  92. collider.SetPath(0, verts);
  93. }
  94. public static Bounds GetBoundingBoxBounds (BoundingBoxAttachment boundingBox, float depth = 0) {
  95. float[] floats = boundingBox.Vertices;
  96. int floatCount = floats.Length;
  97. Bounds bounds = new Bounds();
  98. bounds.center = new Vector3(floats[0], floats[1], 0);
  99. for (int i = 2; i < floatCount; i += 2)
  100. bounds.Encapsulate(new Vector3(floats[i], floats[i + 1], 0));
  101. Vector3 size = bounds.size;
  102. size.z = depth;
  103. bounds.size = size;
  104. return bounds;
  105. }
  106. public static Rigidbody2D AddBoneRigidbody2D (GameObject gameObject, bool isKinematic = true, float gravityScale = 0f) {
  107. var rb = gameObject.GetComponent<Rigidbody2D>();
  108. if (rb == null) {
  109. rb = gameObject.AddComponent<Rigidbody2D>();
  110. rb.isKinematic = isKinematic;
  111. rb.gravityScale = gravityScale;
  112. }
  113. return rb;
  114. }
  115. #endregion
  116. public delegate void SkeletonUtilityDelegate ();
  117. public event SkeletonUtilityDelegate OnReset;
  118. public Transform boneRoot;
  119. /// <summary>
  120. /// If true, <see cref="Skeleton.ScaleX"/> and <see cref="Skeleton.ScaleY"/> are followed
  121. /// by 180 degree rotation. If false, negative Transform scale is used.
  122. /// Note that using negative scale is consistent with previous behaviour (hence the default),
  123. /// however causes serious problems with rigidbodies and physics. Therefore, it is recommended to
  124. /// enable this parameter where possible. When creating hinge chains for a chain of skeleton bones
  125. /// via <see cref="SkeletonUtilityBone"/>, it is mandatory to have <c>flipBy180DegreeRotation</c> enabled.
  126. /// </summary>
  127. public bool flipBy180DegreeRotation = false;
  128. void Update () {
  129. var skeleton = skeletonComponent.Skeleton;
  130. if (skeleton != null && boneRoot != null) {
  131. if (flipBy180DegreeRotation) {
  132. boneRoot.localScale = new Vector3(Mathf.Abs(skeleton.ScaleX), Mathf.Abs(skeleton.ScaleY), 1f);
  133. boneRoot.eulerAngles = new Vector3(skeleton.ScaleY > 0 ? 0 : 180,
  134. skeleton.ScaleX > 0 ? 0 : 180,
  135. 0);
  136. }
  137. else {
  138. boneRoot.localScale = new Vector3(skeleton.ScaleX, skeleton.ScaleY, 1f);
  139. }
  140. }
  141. if (canvas != null) {
  142. positionScale = canvas.referencePixelsPerUnit;
  143. }
  144. }
  145. [HideInInspector] public SkeletonRenderer skeletonRenderer;
  146. [HideInInspector] public SkeletonGraphic skeletonGraphic;
  147. private Canvas canvas;
  148. [System.NonSerialized] public ISkeletonAnimation skeletonAnimation;
  149. private ISkeletonComponent skeletonComponent;
  150. [System.NonSerialized] public List<SkeletonUtilityBone> boneComponents = new List<SkeletonUtilityBone>();
  151. [System.NonSerialized] public List<SkeletonUtilityConstraint> constraintComponents = new List<SkeletonUtilityConstraint>();
  152. public ISkeletonComponent SkeletonComponent {
  153. get {
  154. if (skeletonComponent == null) {
  155. skeletonComponent = skeletonRenderer != null ? skeletonRenderer.GetComponent<ISkeletonComponent>() :
  156. skeletonGraphic != null ? skeletonGraphic.GetComponent<ISkeletonComponent>() :
  157. GetComponent<ISkeletonComponent>();
  158. }
  159. return skeletonComponent;
  160. }
  161. }
  162. public Skeleton Skeleton {
  163. get {
  164. if (SkeletonComponent == null)
  165. return null;
  166. return skeletonComponent.Skeleton;
  167. }
  168. }
  169. public bool IsValid {
  170. get {
  171. return (skeletonRenderer != null && skeletonRenderer.valid) ||
  172. (skeletonGraphic != null && skeletonGraphic.IsValid);
  173. }
  174. }
  175. public float PositionScale { get { return positionScale; } }
  176. float positionScale = 1.0f;
  177. bool hasOverrideBones;
  178. bool hasConstraints;
  179. bool needToReprocessBones;
  180. public void ResubscribeEvents () {
  181. OnDisable();
  182. OnEnable();
  183. }
  184. void OnEnable () {
  185. if (skeletonRenderer == null) {
  186. skeletonRenderer = GetComponent<SkeletonRenderer>();
  187. }
  188. if (skeletonGraphic == null) {
  189. skeletonGraphic = GetComponent<SkeletonGraphic>();
  190. }
  191. if (skeletonAnimation == null) {
  192. skeletonAnimation = skeletonRenderer != null ? skeletonRenderer.GetComponent<ISkeletonAnimation>() :
  193. skeletonGraphic != null ? skeletonGraphic.GetComponent<ISkeletonAnimation>() :
  194. GetComponent<ISkeletonAnimation>();
  195. }
  196. if (skeletonComponent == null) {
  197. skeletonComponent = skeletonRenderer != null ? skeletonRenderer.GetComponent<ISkeletonComponent>() :
  198. skeletonGraphic != null ? skeletonGraphic.GetComponent<ISkeletonComponent>() :
  199. GetComponent<ISkeletonComponent>();
  200. }
  201. if (skeletonRenderer != null) {
  202. skeletonRenderer.OnRebuild -= HandleRendererReset;
  203. skeletonRenderer.OnRebuild += HandleRendererReset;
  204. }
  205. else if (skeletonGraphic != null) {
  206. skeletonGraphic.OnRebuild -= HandleRendererReset;
  207. skeletonGraphic.OnRebuild += HandleRendererReset;
  208. canvas = skeletonGraphic.canvas;
  209. if (canvas == null)
  210. canvas = skeletonGraphic.GetComponentInParent<Canvas>();
  211. if (canvas == null)
  212. positionScale = 100.0f;
  213. }
  214. if (skeletonAnimation != null) {
  215. skeletonAnimation.UpdateLocal -= UpdateLocal;
  216. skeletonAnimation.UpdateLocal += UpdateLocal;
  217. }
  218. CollectBones();
  219. }
  220. void Start () {
  221. //recollect because order of operations failure when switching between game mode and edit mode...
  222. CollectBones();
  223. }
  224. void OnDisable () {
  225. if (skeletonRenderer != null)
  226. skeletonRenderer.OnRebuild -= HandleRendererReset;
  227. if (skeletonGraphic != null)
  228. skeletonGraphic.OnRebuild -= HandleRendererReset;
  229. if (skeletonAnimation != null) {
  230. skeletonAnimation.UpdateLocal -= UpdateLocal;
  231. skeletonAnimation.UpdateWorld -= UpdateWorld;
  232. skeletonAnimation.UpdateComplete -= UpdateComplete;
  233. }
  234. }
  235. void HandleRendererReset (SkeletonRenderer r) {
  236. if (OnReset != null) OnReset();
  237. CollectBones();
  238. }
  239. void HandleRendererReset (SkeletonGraphic g) {
  240. if (OnReset != null) OnReset();
  241. CollectBones();
  242. }
  243. public void RegisterBone (SkeletonUtilityBone bone) {
  244. if (boneComponents.Contains(bone)) {
  245. return;
  246. } else {
  247. boneComponents.Add(bone);
  248. needToReprocessBones = true;
  249. }
  250. }
  251. public void UnregisterBone (SkeletonUtilityBone bone) {
  252. boneComponents.Remove(bone);
  253. }
  254. public void RegisterConstraint (SkeletonUtilityConstraint constraint) {
  255. if (constraintComponents.Contains(constraint))
  256. return;
  257. else {
  258. constraintComponents.Add(constraint);
  259. needToReprocessBones = true;
  260. }
  261. }
  262. public void UnregisterConstraint (SkeletonUtilityConstraint constraint) {
  263. constraintComponents.Remove(constraint);
  264. }
  265. public void CollectBones () {
  266. var skeleton = skeletonComponent.Skeleton;
  267. if (skeleton == null) return;
  268. if (boneRoot != null) {
  269. var constraintTargets = new List<System.Object>();
  270. var ikConstraints = skeleton.IkConstraints;
  271. for (int i = 0, n = ikConstraints.Count; i < n; i++)
  272. constraintTargets.Add(ikConstraints.Items[i].target);
  273. var transformConstraints = skeleton.TransformConstraints;
  274. for (int i = 0, n = transformConstraints.Count; i < n; i++)
  275. constraintTargets.Add(transformConstraints.Items[i].target);
  276. var boneComponents = this.boneComponents;
  277. for (int i = 0, n = boneComponents.Count; i < n; i++) {
  278. var b = boneComponents[i];
  279. if (b.bone == null) {
  280. b.DoUpdate(SkeletonUtilityBone.UpdatePhase.Local);
  281. if (b.bone == null) continue;
  282. }
  283. hasOverrideBones |= (b.mode == SkeletonUtilityBone.Mode.Override);
  284. hasConstraints |= constraintTargets.Contains(b.bone);
  285. }
  286. hasConstraints |= constraintComponents.Count > 0;
  287. if (skeletonAnimation != null) {
  288. skeletonAnimation.UpdateWorld -= UpdateWorld;
  289. skeletonAnimation.UpdateComplete -= UpdateComplete;
  290. if (hasOverrideBones || hasConstraints)
  291. skeletonAnimation.UpdateWorld += UpdateWorld;
  292. if (hasConstraints)
  293. skeletonAnimation.UpdateComplete += UpdateComplete;
  294. }
  295. needToReprocessBones = false;
  296. } else {
  297. boneComponents.Clear();
  298. constraintComponents.Clear();
  299. }
  300. }
  301. void UpdateLocal (ISkeletonAnimation anim) {
  302. if (needToReprocessBones)
  303. CollectBones();
  304. var boneComponents = this.boneComponents;
  305. if (boneComponents == null) return;
  306. for (int i = 0, n = boneComponents.Count; i < n; i++)
  307. boneComponents[i].transformLerpComplete = false;
  308. UpdateAllBones(SkeletonUtilityBone.UpdatePhase.Local);
  309. }
  310. void UpdateWorld (ISkeletonAnimation anim) {
  311. UpdateAllBones(SkeletonUtilityBone.UpdatePhase.World);
  312. for (int i = 0, n = constraintComponents.Count; i < n; i++)
  313. constraintComponents[i].DoUpdate();
  314. }
  315. void UpdateComplete (ISkeletonAnimation anim) {
  316. UpdateAllBones(SkeletonUtilityBone.UpdatePhase.Complete);
  317. }
  318. void UpdateAllBones (SkeletonUtilityBone.UpdatePhase phase) {
  319. if (boneRoot == null)
  320. CollectBones();
  321. var boneComponents = this.boneComponents;
  322. if (boneComponents == null) return;
  323. for (int i = 0, n = boneComponents.Count; i < n; i++)
  324. boneComponents[i].DoUpdate(phase);
  325. }
  326. public Transform GetBoneRoot () {
  327. if (boneRoot != null)
  328. return boneRoot;
  329. var boneRootObject = new GameObject("SkeletonUtility-SkeletonRoot");
  330. #if UNITY_EDITOR
  331. if (!Application.isPlaying)
  332. UnityEditor.Undo.RegisterCreatedObjectUndo(boneRootObject, "Spawn Bone");
  333. #endif
  334. if (skeletonGraphic != null)
  335. boneRootObject.AddComponent<RectTransform>();
  336. boneRoot = boneRootObject.transform;
  337. boneRoot.SetParent(transform);
  338. boneRoot.localPosition = Vector3.zero;
  339. boneRoot.localRotation = Quaternion.identity;
  340. boneRoot.localScale = Vector3.one;
  341. return boneRoot;
  342. }
  343. public GameObject SpawnRoot (SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
  344. GetBoneRoot();
  345. Skeleton skeleton = this.skeletonComponent.Skeleton;
  346. GameObject go = SpawnBone(skeleton.RootBone, boneRoot, mode, pos, rot, sca);
  347. CollectBones();
  348. return go;
  349. }
  350. public GameObject SpawnHierarchy (SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
  351. GetBoneRoot();
  352. Skeleton skeleton = this.skeletonComponent.Skeleton;
  353. GameObject go = SpawnBoneRecursively(skeleton.RootBone, boneRoot, mode, pos, rot, sca);
  354. CollectBones();
  355. return go;
  356. }
  357. public GameObject SpawnBoneRecursively (Bone bone, Transform parent, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
  358. GameObject go = SpawnBone(bone, parent, mode, pos, rot, sca);
  359. ExposedList<Bone> childrenBones = bone.Children;
  360. for (int i = 0, n = childrenBones.Count; i < n; i++) {
  361. Bone child = childrenBones.Items[i];
  362. SpawnBoneRecursively(child, go.transform, mode, pos, rot, sca);
  363. }
  364. return go;
  365. }
  366. public GameObject SpawnBone (Bone bone, Transform parent, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) {
  367. GameObject go = new GameObject(bone.Data.Name);
  368. #if UNITY_EDITOR
  369. if (!Application.isPlaying)
  370. UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Spawn Bone");
  371. #endif
  372. if (skeletonGraphic != null)
  373. go.AddComponent<RectTransform>();
  374. var goTransform = go.transform;
  375. goTransform.SetParent(parent);
  376. SkeletonUtilityBone b = go.AddComponent<SkeletonUtilityBone>();
  377. b.hierarchy = this;
  378. b.position = pos;
  379. b.rotation = rot;
  380. b.scale = sca;
  381. b.mode = mode;
  382. b.zPosition = true;
  383. b.Reset();
  384. b.bone = bone;
  385. b.boneName = bone.Data.Name;
  386. b.valid = true;
  387. if (mode == SkeletonUtilityBone.Mode.Override) {
  388. if (rot) goTransform.localRotation = Quaternion.Euler(0, 0, b.bone.AppliedRotation);
  389. if (pos) goTransform.localPosition = new Vector3(b.bone.X * positionScale, b.bone.Y * positionScale, 0);
  390. goTransform.localScale = new Vector3(b.bone.scaleX, b.bone.scaleY, 0);
  391. }
  392. return go;
  393. }
  394. }
  395. }