From f4d12bae6e6f67c0c6223111912b3a76bab025de Mon Sep 17 00:00:00 2001 From: John Date: Sun, 4 Mar 2018 14:00:13 +0800 Subject: [PATCH 01/12] [unity] Handle editor adding the same InstanceID to the Dictionaires more than once. --- .../Editor/SpineEditorUtilities.cs | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs b/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs index e6b0f0605..309cfeb25 100644 --- a/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs +++ b/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs @@ -155,16 +155,17 @@ namespace Spine.Unity.Editor { public static string editorGUIPath = ""; public static bool initialized; - /// This list keeps the asset reference temporarily during importing. + /// HACK: This list keeps the asset reference temporarily during importing. /// /// In cases of very large projects/sufficient RAM pressure, when AssetDatabase.SaveAssets is called, /// Unity can mistakenly unload assets whose references are only on the stack. /// This leads to MissingReferenceException and other errors. static readonly List protectFromStackGarbageCollection = new List(); - static HashSet assetsImportedInWrongState; - static Dictionary skeletonRendererTable; - static Dictionary skeletonUtilityBoneTable; - static Dictionary boundingBoxFollowerTable; + static HashSet assetsImportedInWrongState = new HashSet(); + + static Dictionary skeletonRendererTable = new Dictionary(); + static Dictionary skeletonUtilityBoneTable = new Dictionary(); + static Dictionary boundingBoxFollowerTable = new Dictionary(); #if SPINE_TK2D const float DEFAULT_DEFAULT_SCALE = 1f; @@ -220,11 +221,6 @@ namespace Spine.Unity.Editor { Icons.Initialize(); - assetsImportedInWrongState = new HashSet(); - skeletonRendererTable = new Dictionary(); - skeletonUtilityBoneTable = new Dictionary(); - boundingBoxFollowerTable = new Dictionary(); - // Drag and Drop SceneView.onSceneGUIDelegate -= SceneViewDragAndDrop; SceneView.onSceneGUIDelegate += SceneViewDragAndDrop; @@ -535,15 +531,15 @@ namespace Spine.Unity.Editor { SkeletonRenderer[] arr = Object.FindObjectsOfType(); foreach (SkeletonRenderer r in arr) - skeletonRendererTable.Add(r.gameObject.GetInstanceID(), r.gameObject); + skeletonRendererTable[r.gameObject.GetInstanceID()] = r.gameObject; SkeletonUtilityBone[] boneArr = Object.FindObjectsOfType(); foreach (SkeletonUtilityBone b in boneArr) - skeletonUtilityBoneTable.Add(b.gameObject.GetInstanceID(), b); + skeletonUtilityBoneTable[b.gameObject.GetInstanceID()] = b; BoundingBoxFollower[] bbfArr = Object.FindObjectsOfType(); foreach (BoundingBoxFollower bbf in bbfArr) - boundingBoxFollowerTable.Add(bbf.gameObject.GetInstanceID(), bbf); + boundingBoxFollowerTable[bbf.gameObject.GetInstanceID()] = bbf; } static void HierarchyIconsOnGUI (int instanceId, Rect selectionRect) { From 83d0e6b9beecbaa089e7cb1dcd59fbc48ceb6800 Mon Sep 17 00:00:00 2001 From: John Date: Wed, 7 Mar 2018 01:50:20 +0800 Subject: [PATCH 02/12] [unity] Handle arrays in FindBaseOrSiblingProperty --- .../Editor/SpineInspectorUtility.cs | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/spine-unity/Assets/spine-unity/Editor/SpineInspectorUtility.cs b/spine-unity/Assets/spine-unity/Editor/SpineInspectorUtility.cs index d6b46271e..9a88727ed 100644 --- a/spine-unity/Assets/spine-unity/Editor/SpineInspectorUtility.cs +++ b/spine-unity/Assets/spine-unity/Editor/SpineInspectorUtility.cs @@ -86,13 +86,34 @@ namespace Spine.Unity.Editor { #region SerializedProperty Helpers public static SerializedProperty FindBaseOrSiblingProperty (this SerializedProperty property, string propertyName) { if (string.IsNullOrEmpty(propertyName)) return null; + SerializedProperty relativeProperty = property.serializedObject.FindProperty(propertyName); // baseProperty - if (relativeProperty == null) { // If no baseProperty, find sibling property. - int nameLength = property.name.Length; + + // If base property is not found, look for the sibling property. + if (relativeProperty == null) { string propertyPath = property.propertyPath; - propertyPath = propertyPath.Remove(propertyPath.Length - nameLength, nameLength) + propertyName; + int localPathLength = 0; + + if (property.isArray) { + const int internalArrayPathLength = 14; // int arrayPathLength = ".Array.data[x]".Length; + int propertyPathLength = propertyPath.Length; + int n = propertyPathLength - internalArrayPathLength; + // Find the dot before the array property name and + // store the total length from the name of the array until the end of the propertyPath. + for (int i = internalArrayPathLength + 1; i < n; i++) { + if (propertyPath[propertyPathLength - i] == '.') { + localPathLength = i - 1; + break; + } + } + } else { + localPathLength = property.name.Length; + } + + propertyPath = propertyPath.Remove(propertyPath.Length - localPathLength, localPathLength) + propertyName; relativeProperty = property.serializedObject.FindProperty(propertyPath); } + return relativeProperty; } #endregion From cb29ca9ae4e0b004e184bc262753643fba31d6a6 Mon Sep 17 00:00:00 2001 From: pharan Date: Thu, 8 Mar 2018 21:59:47 +0800 Subject: [PATCH 03/12] [unity] Move Components into their own folder. --- .../{ => Components}/BoneFollower.cs | 368 +++++----- .../{ => Components}/BoneFollower.cs.meta | 0 .../{ => Components}/PointFollower.cs | 0 .../{ => Components}/PointFollower.cs.meta | 0 .../{ => Components}/SkeletonAnimation.cs | 420 +++++------ .../SkeletonAnimation.cs.meta | 0 .../{ => Components}/SkeletonAnimator.cs | 0 .../{ => Components}/SkeletonAnimator.cs.meta | 0 .../{ => Components}/SkeletonRenderer.cs | 652 +++++++++--------- .../{ => Components}/SkeletonRenderer.cs.meta | 0 10 files changed, 720 insertions(+), 720 deletions(-) rename spine-unity/Assets/spine-unity/{ => Components}/BoneFollower.cs (97%) rename spine-unity/Assets/spine-unity/{ => Components}/BoneFollower.cs.meta (100%) rename spine-unity/Assets/spine-unity/{ => Components}/PointFollower.cs (100%) rename spine-unity/Assets/spine-unity/{ => Components}/PointFollower.cs.meta (100%) rename spine-unity/Assets/spine-unity/{ => Components}/SkeletonAnimation.cs (97%) rename spine-unity/Assets/spine-unity/{ => Components}/SkeletonAnimation.cs.meta (100%) rename spine-unity/Assets/spine-unity/{ => Components}/SkeletonAnimator.cs (100%) rename spine-unity/Assets/spine-unity/{ => Components}/SkeletonAnimator.cs.meta (100%) rename spine-unity/Assets/spine-unity/{ => Components}/SkeletonRenderer.cs (97%) rename spine-unity/Assets/spine-unity/{ => Components}/SkeletonRenderer.cs.meta (100%) diff --git a/spine-unity/Assets/spine-unity/BoneFollower.cs b/spine-unity/Assets/spine-unity/Components/BoneFollower.cs similarity index 97% rename from spine-unity/Assets/spine-unity/BoneFollower.cs rename to spine-unity/Assets/spine-unity/Components/BoneFollower.cs index 49ff44b27..6ce6f147c 100644 --- a/spine-unity/Assets/spine-unity/BoneFollower.cs +++ b/spine-unity/Assets/spine-unity/Components/BoneFollower.cs @@ -1,184 +1,184 @@ -/****************************************************************************** - * Spine Runtimes Software License v2.5 - * - * Copyright (c) 2013-2016, Esoteric Software - * All rights reserved. - * - * You are granted a perpetual, non-exclusive, non-sublicensable, and - * non-transferable license to use, install, execute, and perform the Spine - * Runtimes software and derivative works solely for personal or internal - * use. Without the written permission of Esoteric Software (see Section 2 of - * the Spine Software License Agreement), you may not (a) modify, translate, - * adapt, or develop new applications using the Spine Runtimes or otherwise - * create derivative works or improvements of the Spine Runtimes or (b) remove, - * delete, alter, or obscure any trademarks or any copyright, trademark, patent, - * or other intellectual property or proprietary rights notices on or in the - * Software, including any copy thereof. Redistributions in binary or source - * form must include this license and terms. - * - * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF - * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - *****************************************************************************/ - -using System; -using UnityEngine; - -namespace Spine.Unity { - /// Sets a GameObject's transform to match a bone on a Spine skeleton. - [ExecuteInEditMode] - [AddComponentMenu("Spine/BoneFollower")] - public class BoneFollower : MonoBehaviour { - - #region Inspector - public SkeletonRenderer skeletonRenderer; - public SkeletonRenderer SkeletonRenderer { - get { return skeletonRenderer; } - set { - skeletonRenderer = value; - Initialize(); - } - } - - /// If a bone isn't set in code, boneName is used to find the bone at the beginning. For runtime switching by name, use SetBoneByName. You can also set the BoneFollower.bone field directly. - [SpineBone(dataField: "skeletonRenderer")] - [SerializeField] public string boneName; - - public bool followZPosition = true; - public bool followBoneRotation = true; - - [Tooltip("Follows the skeleton's flip state by controlling this Transform's local scale.")] - public bool followSkeletonFlip = true; - - [Tooltip("Follows the target bone's local scale. BoneFollower cannot inherit world/skewed scale because of UnityEngine.Transform property limitations.")] - public bool followLocalScale = false; - - [UnityEngine.Serialization.FormerlySerializedAs("resetOnAwake")] - public bool initializeOnAwake = true; - #endregion - - [NonSerialized] public bool valid; - /// - /// The bone. - /// - [NonSerialized] public Bone bone; - Transform skeletonTransform; - bool skeletonTransformIsParent; - - /// - /// Sets the target bone by its bone name. Returns false if no bone was found. To set the bone by reference, use BoneFollower.bone directly. - public bool SetBone (string name) { - bone = skeletonRenderer.skeleton.FindBone(name); - if (bone == null) { - Debug.LogError("Bone not found: " + name, this); - return false; - } - boneName = name; - return true; - } - - public void Awake () { - if (initializeOnAwake) Initialize(); - } - - public void HandleRebuildRenderer (SkeletonRenderer skeletonRenderer) { - Initialize(); - } - - public void Initialize () { - bone = null; - valid = skeletonRenderer != null && skeletonRenderer.valid; - if (!valid) return; - - skeletonTransform = skeletonRenderer.transform; - skeletonRenderer.OnRebuild -= HandleRebuildRenderer; - skeletonRenderer.OnRebuild += HandleRebuildRenderer; - skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); - - if (!string.IsNullOrEmpty(boneName)) - bone = skeletonRenderer.skeleton.FindBone(boneName); - - #if UNITY_EDITOR - if (Application.isEditor) - LateUpdate(); - #endif - } - - void OnDestroy () { - if (skeletonRenderer != null) - skeletonRenderer.OnRebuild -= HandleRebuildRenderer; - } - - public void LateUpdate () { - if (!valid) { - Initialize(); - return; - } - - #if UNITY_EDITOR - if (!Application.isPlaying) - skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); - #endif - - if (bone == null) { - if (string.IsNullOrEmpty(boneName)) return; - bone = skeletonRenderer.skeleton.FindBone(boneName); - if (!SetBone(boneName)) return; - } - - Transform thisTransform = this.transform; - if (skeletonTransformIsParent) { - // Recommended setup: Use local transform properties if Spine GameObject is the immediate parent - thisTransform.localPosition = new Vector3(bone.worldX, bone.worldY, followZPosition ? 0f : thisTransform.localPosition.z); - if (followBoneRotation) { - float halfRotation = Mathf.Atan2(bone.c, bone.a) * 0.5f; - if (followLocalScale && bone.scaleX < 0) // Negate rotation from negative scaleX. Don't use negative determinant. local scaleY doesn't factor into used rotation. - halfRotation += Mathf.PI * 0.5f; - - var q = default(Quaternion); - q.z = Mathf.Sin(halfRotation); - q.w = Mathf.Cos(halfRotation); - thisTransform.localRotation = q; - } - } else { - // For special cases: Use transform world properties if transform relationship is complicated - Vector3 targetWorldPosition = skeletonTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY, 0f)); - if (!followZPosition) targetWorldPosition.z = thisTransform.position.z; - - float boneWorldRotation = bone.WorldRotationX; - - Transform transformParent = thisTransform.parent; - if (transformParent != null) { - Matrix4x4 m = transformParent.localToWorldMatrix; - if (m.m00 * m.m11 - m.m01 * m.m10 < 0) // Determinant2D is negative - boneWorldRotation = -boneWorldRotation; - } - - if (followBoneRotation) { - Vector3 worldRotation = skeletonTransform.rotation.eulerAngles; - if (followLocalScale && bone.scaleX < 0) boneWorldRotation += 180f; - #if UNITY_5_6_OR_NEWER - thisTransform.SetPositionAndRotation(targetWorldPosition, Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + boneWorldRotation)); - #else - thisTransform.position = targetWorldPosition; - thisTransform.rotation = Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + bone.WorldRotationX); - #endif - } else { - thisTransform.position = targetWorldPosition; - } - } - - Vector3 localScale = followLocalScale ? new Vector3(bone.scaleX, bone.scaleY, 1f) : new Vector3(1f, 1f, 1f); - if (followSkeletonFlip) localScale.y *= bone.skeleton.flipX ^ bone.skeleton.flipY ? -1f : 1f; - thisTransform.localScale = localScale; - } - } - -} +/****************************************************************************** + * Spine Runtimes Software License v2.5 + * + * Copyright (c) 2013-2016, Esoteric Software + * All rights reserved. + * + * You are granted a perpetual, non-exclusive, non-sublicensable, and + * non-transferable license to use, install, execute, and perform the Spine + * Runtimes software and derivative works solely for personal or internal + * use. Without the written permission of Esoteric Software (see Section 2 of + * the Spine Software License Agreement), you may not (a) modify, translate, + * adapt, or develop new applications using the Spine Runtimes or otherwise + * create derivative works or improvements of the Spine Runtimes or (b) remove, + * delete, alter, or obscure any trademarks or any copyright, trademark, patent, + * or other intellectual property or proprietary rights notices on or in the + * Software, including any copy thereof. Redistributions in binary or source + * form must include this license and terms. + * + * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF + * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER + * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using UnityEngine; + +namespace Spine.Unity { + /// Sets a GameObject's transform to match a bone on a Spine skeleton. + [ExecuteInEditMode] + [AddComponentMenu("Spine/BoneFollower")] + public class BoneFollower : MonoBehaviour { + + #region Inspector + public SkeletonRenderer skeletonRenderer; + public SkeletonRenderer SkeletonRenderer { + get { return skeletonRenderer; } + set { + skeletonRenderer = value; + Initialize(); + } + } + + /// If a bone isn't set in code, boneName is used to find the bone at the beginning. For runtime switching by name, use SetBoneByName. You can also set the BoneFollower.bone field directly. + [SpineBone(dataField: "skeletonRenderer")] + [SerializeField] public string boneName; + + public bool followZPosition = true; + public bool followBoneRotation = true; + + [Tooltip("Follows the skeleton's flip state by controlling this Transform's local scale.")] + public bool followSkeletonFlip = true; + + [Tooltip("Follows the target bone's local scale. BoneFollower cannot inherit world/skewed scale because of UnityEngine.Transform property limitations.")] + public bool followLocalScale = false; + + [UnityEngine.Serialization.FormerlySerializedAs("resetOnAwake")] + public bool initializeOnAwake = true; + #endregion + + [NonSerialized] public bool valid; + /// + /// The bone. + /// + [NonSerialized] public Bone bone; + Transform skeletonTransform; + bool skeletonTransformIsParent; + + /// + /// Sets the target bone by its bone name. Returns false if no bone was found. To set the bone by reference, use BoneFollower.bone directly. + public bool SetBone (string name) { + bone = skeletonRenderer.skeleton.FindBone(name); + if (bone == null) { + Debug.LogError("Bone not found: " + name, this); + return false; + } + boneName = name; + return true; + } + + public void Awake () { + if (initializeOnAwake) Initialize(); + } + + public void HandleRebuildRenderer (SkeletonRenderer skeletonRenderer) { + Initialize(); + } + + public void Initialize () { + bone = null; + valid = skeletonRenderer != null && skeletonRenderer.valid; + if (!valid) return; + + skeletonTransform = skeletonRenderer.transform; + skeletonRenderer.OnRebuild -= HandleRebuildRenderer; + skeletonRenderer.OnRebuild += HandleRebuildRenderer; + skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); + + if (!string.IsNullOrEmpty(boneName)) + bone = skeletonRenderer.skeleton.FindBone(boneName); + + #if UNITY_EDITOR + if (Application.isEditor) + LateUpdate(); + #endif + } + + void OnDestroy () { + if (skeletonRenderer != null) + skeletonRenderer.OnRebuild -= HandleRebuildRenderer; + } + + public void LateUpdate () { + if (!valid) { + Initialize(); + return; + } + + #if UNITY_EDITOR + if (!Application.isPlaying) + skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); + #endif + + if (bone == null) { + if (string.IsNullOrEmpty(boneName)) return; + bone = skeletonRenderer.skeleton.FindBone(boneName); + if (!SetBone(boneName)) return; + } + + Transform thisTransform = this.transform; + if (skeletonTransformIsParent) { + // Recommended setup: Use local transform properties if Spine GameObject is the immediate parent + thisTransform.localPosition = new Vector3(bone.worldX, bone.worldY, followZPosition ? 0f : thisTransform.localPosition.z); + if (followBoneRotation) { + float halfRotation = Mathf.Atan2(bone.c, bone.a) * 0.5f; + if (followLocalScale && bone.scaleX < 0) // Negate rotation from negative scaleX. Don't use negative determinant. local scaleY doesn't factor into used rotation. + halfRotation += Mathf.PI * 0.5f; + + var q = default(Quaternion); + q.z = Mathf.Sin(halfRotation); + q.w = Mathf.Cos(halfRotation); + thisTransform.localRotation = q; + } + } else { + // For special cases: Use transform world properties if transform relationship is complicated + Vector3 targetWorldPosition = skeletonTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY, 0f)); + if (!followZPosition) targetWorldPosition.z = thisTransform.position.z; + + float boneWorldRotation = bone.WorldRotationX; + + Transform transformParent = thisTransform.parent; + if (transformParent != null) { + Matrix4x4 m = transformParent.localToWorldMatrix; + if (m.m00 * m.m11 - m.m01 * m.m10 < 0) // Determinant2D is negative + boneWorldRotation = -boneWorldRotation; + } + + if (followBoneRotation) { + Vector3 worldRotation = skeletonTransform.rotation.eulerAngles; + if (followLocalScale && bone.scaleX < 0) boneWorldRotation += 180f; + #if UNITY_5_6_OR_NEWER + thisTransform.SetPositionAndRotation(targetWorldPosition, Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + boneWorldRotation)); + #else + thisTransform.position = targetWorldPosition; + thisTransform.rotation = Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + bone.WorldRotationX); + #endif + } else { + thisTransform.position = targetWorldPosition; + } + } + + Vector3 localScale = followLocalScale ? new Vector3(bone.scaleX, bone.scaleY, 1f) : new Vector3(1f, 1f, 1f); + if (followSkeletonFlip) localScale.y *= bone.skeleton.flipX ^ bone.skeleton.flipY ? -1f : 1f; + thisTransform.localScale = localScale; + } + } + +} diff --git a/spine-unity/Assets/spine-unity/BoneFollower.cs.meta b/spine-unity/Assets/spine-unity/Components/BoneFollower.cs.meta similarity index 100% rename from spine-unity/Assets/spine-unity/BoneFollower.cs.meta rename to spine-unity/Assets/spine-unity/Components/BoneFollower.cs.meta diff --git a/spine-unity/Assets/spine-unity/PointFollower.cs b/spine-unity/Assets/spine-unity/Components/PointFollower.cs similarity index 100% rename from spine-unity/Assets/spine-unity/PointFollower.cs rename to spine-unity/Assets/spine-unity/Components/PointFollower.cs diff --git a/spine-unity/Assets/spine-unity/PointFollower.cs.meta b/spine-unity/Assets/spine-unity/Components/PointFollower.cs.meta similarity index 100% rename from spine-unity/Assets/spine-unity/PointFollower.cs.meta rename to spine-unity/Assets/spine-unity/Components/PointFollower.cs.meta diff --git a/spine-unity/Assets/spine-unity/SkeletonAnimation.cs b/spine-unity/Assets/spine-unity/Components/SkeletonAnimation.cs similarity index 97% rename from spine-unity/Assets/spine-unity/SkeletonAnimation.cs rename to spine-unity/Assets/spine-unity/Components/SkeletonAnimation.cs index 7014eb727..218bd3516 100644 --- a/spine-unity/Assets/spine-unity/SkeletonAnimation.cs +++ b/spine-unity/Assets/spine-unity/Components/SkeletonAnimation.cs @@ -1,210 +1,210 @@ -/****************************************************************************** - * Spine Runtimes Software License v2.5 - * - * Copyright (c) 2013-2016, Esoteric Software - * All rights reserved. - * - * You are granted a perpetual, non-exclusive, non-sublicensable, and - * non-transferable license to use, install, execute, and perform the Spine - * Runtimes software and derivative works solely for personal or internal - * use. Without the written permission of Esoteric Software (see Section 2 of - * the Spine Software License Agreement), you may not (a) modify, translate, - * adapt, or develop new applications using the Spine Runtimes or otherwise - * create derivative works or improvements of the Spine Runtimes or (b) remove, - * delete, alter, or obscure any trademarks or any copyright, trademark, patent, - * or other intellectual property or proprietary rights notices on or in the - * Software, including any copy thereof. Redistributions in binary or source - * form must include this license and terms. - * - * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF - * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - *****************************************************************************/ - -using UnityEngine; - -namespace Spine.Unity { - - [ExecuteInEditMode] - [AddComponentMenu("Spine/SkeletonAnimation")] - [HelpURL("http://esotericsoftware.com/spine-unity-documentation#Controlling-Animation")] - public class SkeletonAnimation : SkeletonRenderer, ISkeletonAnimation, IAnimationStateComponent { - - #region IAnimationStateComponent - /// - /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it. - /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start - public Spine.AnimationState state; - /// - /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it. - /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start - public Spine.AnimationState AnimationState { get { return this.state; } } - #endregion - - #region Bone Callbacks ISkeletonAnimation - protected event UpdateBonesDelegate _UpdateLocal; - protected event UpdateBonesDelegate _UpdateWorld; - protected event UpdateBonesDelegate _UpdateComplete; - - /// - /// Occurs after the animations are applied and before world space values are resolved. - /// Use this callback when you want to set bone local values. - /// - public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } } - - /// - /// Occurs after the Skeleton's bone world space values are resolved (including all constraints). - /// Using this callback will cause the world space values to be solved an extra time. - /// Use this callback if want to use bone world space values, and also set bone local values. - public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } } - - /// - /// Occurs after the Skeleton's bone world space values are resolved (including all constraints). - /// Use this callback if you want to use bone world space values, but don't intend to modify bone local values. - /// This callback can also be used when setting world position and the bone matrix. - public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } } - #endregion - - #region Serialized state and Beginner API - [SerializeField] - [SpineAnimation] - private string _animationName; - - /// - /// Setting this property sets the animation of the skeleton. If invalid, it will store the animation name for the next time the skeleton is properly initialized. - /// Getting this property gets the name of the currently playing animation. If invalid, it will return the last stored animation name set through this property. - public string AnimationName { - get { - if (!valid) { - return _animationName; - } else { - TrackEntry entry = state.GetCurrent(0); - return entry == null ? null : entry.Animation.Name; - } - } - set { - if (_animationName == value) - return; - _animationName = value; - - if (string.IsNullOrEmpty(value)) { - state.ClearTrack(0); - } else { - TrySetAnimation(value, loop); - } - } - } - - TrackEntry TrySetAnimation (string animationName, bool animationLoop) { - var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(animationName); - if (animationObject != null) - return state.SetAnimation(0, animationObject, animationLoop); - - return null; - } - - /// Whether or not should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected. - public bool loop; - - /// - /// The rate at which animations progress over time. 1 means 100%. 0.5 means 50%. - /// AnimationState and TrackEntry also have their own timeScale. These are combined multiplicatively. - public float timeScale = 1; - #endregion - - #region Runtime Instantiation - /// Adds and prepares a SkeletonAnimation component to a GameObject at runtime. - /// The newly instantiated SkeletonAnimation - public static SkeletonAnimation AddToGameObject (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) { - return SkeletonRenderer.AddSpineComponent(gameObject, skeletonDataAsset); - } - - /// Instantiates a new UnityEngine.GameObject and adds a prepared SkeletonAnimation component to it. - /// The newly instantiated SkeletonAnimation component. - public static SkeletonAnimation NewSkeletonAnimationGameObject (SkeletonDataAsset skeletonDataAsset) { - return SkeletonRenderer.NewSpineGameObject(skeletonDataAsset); - } - #endregion - - /// - /// Clears the previously generated mesh, resets the skeleton's pose, and clears all previously active animations. - public override void ClearState () { - base.ClearState(); - if (state != null) state.ClearTracks(); - } - - /// - /// Initialize this component. Attempts to load the SkeletonData and creates the internal Spine objects and buffers. - /// If set to true, force overwrite an already initialized object. - public override void Initialize (bool overwrite) { - if (valid && !overwrite) - return; - - base.Initialize(overwrite); - - if (!valid) - return; - - state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData()); - - #if UNITY_EDITOR - if (!string.IsNullOrEmpty(_animationName)) { - if (Application.isPlaying) { - TrackEntry startingTrack = TrySetAnimation(_animationName, loop); - if (startingTrack != null) - Update(0); - } else { - // Assume SkeletonAnimation is valid for skeletonData and skeleton. Checked above. - var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(_animationName); - if (animationObject != null) - animationObject.PoseSkeleton(skeleton, 0f); - } - } - #else - if (!string.IsNullOrEmpty(_animationName)) { - TrackEntry startingTrack = TrySetAnimation(_animationName, loop); - if (startingTrack != null) - Update(0); - } - #endif - } - - void Update () { - Update(Time.deltaTime); - } - - /// Progresses the AnimationState according to the given deltaTime, and applies it to the Skeleton. Use Time.deltaTime to update manually. Use deltaTime 0 to update without progressing the time. - public void Update (float deltaTime) { - if (!valid) - return; - - deltaTime *= timeScale; - skeleton.Update(deltaTime); - state.Update(deltaTime); - state.Apply(skeleton); - - if (_UpdateLocal != null) - _UpdateLocal(this); - - skeleton.UpdateWorldTransform(); - - if (_UpdateWorld != null) { - _UpdateWorld(this); - skeleton.UpdateWorldTransform(); - } - - if (_UpdateComplete != null) { - _UpdateComplete(this); - } - } - - } - -} +/****************************************************************************** + * Spine Runtimes Software License v2.5 + * + * Copyright (c) 2013-2016, Esoteric Software + * All rights reserved. + * + * You are granted a perpetual, non-exclusive, non-sublicensable, and + * non-transferable license to use, install, execute, and perform the Spine + * Runtimes software and derivative works solely for personal or internal + * use. Without the written permission of Esoteric Software (see Section 2 of + * the Spine Software License Agreement), you may not (a) modify, translate, + * adapt, or develop new applications using the Spine Runtimes or otherwise + * create derivative works or improvements of the Spine Runtimes or (b) remove, + * delete, alter, or obscure any trademarks or any copyright, trademark, patent, + * or other intellectual property or proprietary rights notices on or in the + * Software, including any copy thereof. Redistributions in binary or source + * form must include this license and terms. + * + * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF + * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER + * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; + +namespace Spine.Unity { + + [ExecuteInEditMode] + [AddComponentMenu("Spine/SkeletonAnimation")] + [HelpURL("http://esotericsoftware.com/spine-unity-documentation#Controlling-Animation")] + public class SkeletonAnimation : SkeletonRenderer, ISkeletonAnimation, IAnimationStateComponent { + + #region IAnimationStateComponent + /// + /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it. + /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start + public Spine.AnimationState state; + /// + /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it. + /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start + public Spine.AnimationState AnimationState { get { return this.state; } } + #endregion + + #region Bone Callbacks ISkeletonAnimation + protected event UpdateBonesDelegate _UpdateLocal; + protected event UpdateBonesDelegate _UpdateWorld; + protected event UpdateBonesDelegate _UpdateComplete; + + /// + /// Occurs after the animations are applied and before world space values are resolved. + /// Use this callback when you want to set bone local values. + /// + public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } } + + /// + /// Occurs after the Skeleton's bone world space values are resolved (including all constraints). + /// Using this callback will cause the world space values to be solved an extra time. + /// Use this callback if want to use bone world space values, and also set bone local values. + public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } } + + /// + /// Occurs after the Skeleton's bone world space values are resolved (including all constraints). + /// Use this callback if you want to use bone world space values, but don't intend to modify bone local values. + /// This callback can also be used when setting world position and the bone matrix. + public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } } + #endregion + + #region Serialized state and Beginner API + [SerializeField] + [SpineAnimation] + private string _animationName; + + /// + /// Setting this property sets the animation of the skeleton. If invalid, it will store the animation name for the next time the skeleton is properly initialized. + /// Getting this property gets the name of the currently playing animation. If invalid, it will return the last stored animation name set through this property. + public string AnimationName { + get { + if (!valid) { + return _animationName; + } else { + TrackEntry entry = state.GetCurrent(0); + return entry == null ? null : entry.Animation.Name; + } + } + set { + if (_animationName == value) + return; + _animationName = value; + + if (string.IsNullOrEmpty(value)) { + state.ClearTrack(0); + } else { + TrySetAnimation(value, loop); + } + } + } + + TrackEntry TrySetAnimation (string animationName, bool animationLoop) { + var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(animationName); + if (animationObject != null) + return state.SetAnimation(0, animationObject, animationLoop); + + return null; + } + + /// Whether or not should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected. + public bool loop; + + /// + /// The rate at which animations progress over time. 1 means 100%. 0.5 means 50%. + /// AnimationState and TrackEntry also have their own timeScale. These are combined multiplicatively. + public float timeScale = 1; + #endregion + + #region Runtime Instantiation + /// Adds and prepares a SkeletonAnimation component to a GameObject at runtime. + /// The newly instantiated SkeletonAnimation + public static SkeletonAnimation AddToGameObject (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) { + return SkeletonRenderer.AddSpineComponent(gameObject, skeletonDataAsset); + } + + /// Instantiates a new UnityEngine.GameObject and adds a prepared SkeletonAnimation component to it. + /// The newly instantiated SkeletonAnimation component. + public static SkeletonAnimation NewSkeletonAnimationGameObject (SkeletonDataAsset skeletonDataAsset) { + return SkeletonRenderer.NewSpineGameObject(skeletonDataAsset); + } + #endregion + + /// + /// Clears the previously generated mesh, resets the skeleton's pose, and clears all previously active animations. + public override void ClearState () { + base.ClearState(); + if (state != null) state.ClearTracks(); + } + + /// + /// Initialize this component. Attempts to load the SkeletonData and creates the internal Spine objects and buffers. + /// If set to true, force overwrite an already initialized object. + public override void Initialize (bool overwrite) { + if (valid && !overwrite) + return; + + base.Initialize(overwrite); + + if (!valid) + return; + + state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData()); + + #if UNITY_EDITOR + if (!string.IsNullOrEmpty(_animationName)) { + if (Application.isPlaying) { + TrackEntry startingTrack = TrySetAnimation(_animationName, loop); + if (startingTrack != null) + Update(0); + } else { + // Assume SkeletonAnimation is valid for skeletonData and skeleton. Checked above. + var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(_animationName); + if (animationObject != null) + animationObject.PoseSkeleton(skeleton, 0f); + } + } + #else + if (!string.IsNullOrEmpty(_animationName)) { + TrackEntry startingTrack = TrySetAnimation(_animationName, loop); + if (startingTrack != null) + Update(0); + } + #endif + } + + void Update () { + Update(Time.deltaTime); + } + + /// Progresses the AnimationState according to the given deltaTime, and applies it to the Skeleton. Use Time.deltaTime to update manually. Use deltaTime 0 to update without progressing the time. + public void Update (float deltaTime) { + if (!valid) + return; + + deltaTime *= timeScale; + skeleton.Update(deltaTime); + state.Update(deltaTime); + state.Apply(skeleton); + + if (_UpdateLocal != null) + _UpdateLocal(this); + + skeleton.UpdateWorldTransform(); + + if (_UpdateWorld != null) { + _UpdateWorld(this); + skeleton.UpdateWorldTransform(); + } + + if (_UpdateComplete != null) { + _UpdateComplete(this); + } + } + + } + +} diff --git a/spine-unity/Assets/spine-unity/SkeletonAnimation.cs.meta b/spine-unity/Assets/spine-unity/Components/SkeletonAnimation.cs.meta similarity index 100% rename from spine-unity/Assets/spine-unity/SkeletonAnimation.cs.meta rename to spine-unity/Assets/spine-unity/Components/SkeletonAnimation.cs.meta diff --git a/spine-unity/Assets/spine-unity/SkeletonAnimator.cs b/spine-unity/Assets/spine-unity/Components/SkeletonAnimator.cs similarity index 100% rename from spine-unity/Assets/spine-unity/SkeletonAnimator.cs rename to spine-unity/Assets/spine-unity/Components/SkeletonAnimator.cs diff --git a/spine-unity/Assets/spine-unity/SkeletonAnimator.cs.meta b/spine-unity/Assets/spine-unity/Components/SkeletonAnimator.cs.meta similarity index 100% rename from spine-unity/Assets/spine-unity/SkeletonAnimator.cs.meta rename to spine-unity/Assets/spine-unity/Components/SkeletonAnimator.cs.meta diff --git a/spine-unity/Assets/spine-unity/SkeletonRenderer.cs b/spine-unity/Assets/spine-unity/Components/SkeletonRenderer.cs similarity index 97% rename from spine-unity/Assets/spine-unity/SkeletonRenderer.cs rename to spine-unity/Assets/spine-unity/Components/SkeletonRenderer.cs index 17d851384..fbce68644 100644 --- a/spine-unity/Assets/spine-unity/SkeletonRenderer.cs +++ b/spine-unity/Assets/spine-unity/Components/SkeletonRenderer.cs @@ -1,326 +1,326 @@ -/****************************************************************************** - * Spine Runtimes Software License v2.5 - * - * Copyright (c) 2013-2016, Esoteric Software - * All rights reserved. - * - * You are granted a perpetual, non-exclusive, non-sublicensable, and - * non-transferable license to use, install, execute, and perform the Spine - * Runtimes software and derivative works solely for personal or internal - * use. Without the written permission of Esoteric Software (see Section 2 of - * the Spine Software License Agreement), you may not (a) modify, translate, - * adapt, or develop new applications using the Spine Runtimes or otherwise - * create derivative works or improvements of the Spine Runtimes or (b) remove, - * delete, alter, or obscure any trademarks or any copyright, trademark, patent, - * or other intellectual property or proprietary rights notices on or in the - * Software, including any copy thereof. Redistributions in binary or source - * form must include this license and terms. - * - * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF - * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - *****************************************************************************/ - -#define SPINE_OPTIONAL_RENDEROVERRIDE -#define SPINE_OPTIONAL_MATERIALOVERRIDE - -using System.Collections.Generic; -using UnityEngine; - -namespace Spine.Unity { - /// Renders a skeleton. - [ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer)), DisallowMultipleComponent] - [HelpURL("http://esotericsoftware.com/spine-unity-documentation#Rendering")] - public class SkeletonRenderer : MonoBehaviour, ISkeletonComponent, IHasSkeletonDataAsset { - - public delegate void SkeletonRendererDelegate (SkeletonRenderer skeletonRenderer); - public event SkeletonRendererDelegate OnRebuild; - - /// Occurs after the vertex data is populated every frame, before the vertices are pushed into the mesh. - public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices; - - public SkeletonDataAsset skeletonDataAsset; - public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } // ISkeletonComponent - public string initialSkinName; - public bool initialFlipX, initialFlipY; - - #region Advanced - // Submesh Separation - [UnityEngine.Serialization.FormerlySerializedAs("submeshSeparators")] [SpineSlot] public string[] separatorSlotNames = new string[0]; - [System.NonSerialized] public readonly List separatorSlots = new List(); - - [Range(-0.1f, 0f)] public float zSpacing; - //public bool renderMeshes = true; - public bool useClipping = true; - public bool immutableTriangles = false; - public bool pmaVertexColors = true; - /// Clears the state when this component or its GameObject is disabled. This prevents previous state from being retained when it is enabled again. When pooling your skeleton, setting this to true can be helpful. - public bool clearStateOnDisable = false; - public bool tintBlack = false; - public bool singleSubmesh = false; - - [UnityEngine.Serialization.FormerlySerializedAs("calculateNormals")] - public bool addNormals = false; - public bool calculateTangents = false; - - public bool logErrors = false; - - #if SPINE_OPTIONAL_RENDEROVERRIDE - public bool disableRenderingOnOverride = true; - public delegate void InstructionDelegate (SkeletonRendererInstruction instruction); - event InstructionDelegate generateMeshOverride; - public event InstructionDelegate GenerateMeshOverride { - add { - generateMeshOverride += value; - if (disableRenderingOnOverride && generateMeshOverride != null) { - Initialize(false); - meshRenderer.enabled = false; - } - } - remove { - generateMeshOverride -= value; - if (disableRenderingOnOverride && generateMeshOverride == null) { - Initialize(false); - meshRenderer.enabled = true; - } - } - } - #endif - - #if SPINE_OPTIONAL_MATERIALOVERRIDE - [System.NonSerialized] readonly Dictionary customMaterialOverride = new Dictionary(); - public Dictionary CustomMaterialOverride { get { return customMaterialOverride; } } - #endif - - // Custom Slot Material - [System.NonSerialized] readonly Dictionary customSlotMaterials = new Dictionary(); - public Dictionary CustomSlotMaterials { get { return customSlotMaterials; } } - #endregion - - MeshRenderer meshRenderer; - MeshFilter meshFilter; - - [System.NonSerialized] public bool valid; - [System.NonSerialized] public Skeleton skeleton; - public Skeleton Skeleton { - get { - Initialize(false); - return skeleton; - } - } - - [System.NonSerialized] readonly SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction(); - readonly MeshGenerator meshGenerator = new MeshGenerator(); - [System.NonSerialized] readonly MeshRendererBuffers rendererBuffers = new MeshRendererBuffers(); - - #region Runtime Instantiation - public static T NewSpineGameObject (SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer { - return SkeletonRenderer.AddSpineComponent(new GameObject("New Spine GameObject"), skeletonDataAsset); - } - - /// Add and prepare a Spine component that derives from SkeletonRenderer to a GameObject at runtime. - /// T should be SkeletonRenderer or any of its derived classes. - public static T AddSpineComponent (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer { - var c = gameObject.AddComponent(); - if (skeletonDataAsset != null) { - c.skeletonDataAsset = skeletonDataAsset; - c.Initialize(false); - } - return c; - } - - /// Applies MeshGenerator settings to the SkeletonRenderer and its internal MeshGenerator. - public void SetMeshSettings (MeshGenerator.Settings settings) { - this.calculateTangents = settings.calculateTangents; - this.immutableTriangles = settings.immutableTriangles; - this.pmaVertexColors = settings.pmaVertexColors; - this.tintBlack = settings.tintBlack; - this.useClipping = settings.useClipping; - this.zSpacing = settings.zSpacing; - - this.meshGenerator.settings = settings; - } - #endregion - - public virtual void Awake () { - Initialize(false); - } - - void OnDisable () { - if (clearStateOnDisable && valid) - ClearState(); - } - - void OnDestroy () { - rendererBuffers.Dispose(); - valid = false; - } - - /// - /// Clears the previously generated mesh and resets the skeleton's pose. - public virtual void ClearState () { - meshFilter.sharedMesh = null; - currentInstructions.Clear(); - if (skeleton != null) skeleton.SetToSetupPose(); - } - - /// - /// Initialize this component. Attempts to load the SkeletonData and creates the internal Skeleton object and buffers. - /// If set to true, it will overwrite internal objects if they were already generated. Otherwise, the initialized component will ignore subsequent calls to initialize. - public virtual void Initialize (bool overwrite) { - if (valid && !overwrite) - return; - - // Clear - { - if (meshFilter != null) - meshFilter.sharedMesh = null; - - meshRenderer = GetComponent(); - if (meshRenderer != null) meshRenderer.sharedMaterial = null; - - currentInstructions.Clear(); - rendererBuffers.Clear(); - meshGenerator.Begin(); - skeleton = null; - valid = false; - } - - if (!skeletonDataAsset) { - if (logErrors) Debug.LogError("Missing SkeletonData asset.", this); - return; - } - - SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false); - if (skeletonData == null) return; - valid = true; - - meshFilter = GetComponent(); - meshRenderer = GetComponent(); - rendererBuffers.Initialize(); - - skeleton = new Skeleton(skeletonData) { - flipX = initialFlipX, - flipY = initialFlipY - }; - - if (!string.IsNullOrEmpty(initialSkinName) && !string.Equals(initialSkinName, "default", System.StringComparison.Ordinal)) - skeleton.SetSkin(initialSkinName); - - separatorSlots.Clear(); - for (int i = 0; i < separatorSlotNames.Length; i++) - separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i])); - - LateUpdate(); // Generate mesh for the first frame it exists. - - if (OnRebuild != null) - OnRebuild(this); - } - - /// - /// Generates a new UnityEngine.Mesh from the internal Skeleton. - public virtual void LateUpdate () { - if (!valid) return; - - #if SPINE_OPTIONAL_RENDEROVERRIDE - bool doMeshOverride = generateMeshOverride != null; - if ((!meshRenderer.enabled) && !doMeshOverride) return; - #else - const bool doMeshOverride = false; - if (!meshRenderer.enabled) return; - #endif - var currentInstructions = this.currentInstructions; - var workingSubmeshInstructions = currentInstructions.submeshInstructions; - var currentSmartMesh = rendererBuffers.GetNextMesh(); // Double-buffer for performance. - - bool updateTriangles; - - if (this.singleSubmesh) { - // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. ============================================= - MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, skeletonDataAsset.atlasAssets[0].materials[0]); - - // STEP 1.9. Post-process workingInstructions. ================================================================================== - #if SPINE_OPTIONAL_MATERIALOVERRIDE - if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated - MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride); - #endif - - // STEP 2. Update vertex buffer based on verts from the attachments. =========================================================== - meshGenerator.settings = new MeshGenerator.Settings { - pmaVertexColors = this.pmaVertexColors, - zSpacing = this.zSpacing, - useClipping = this.useClipping, - tintBlack = this.tintBlack, - calculateTangents = this.calculateTangents, - addNormals = this.addNormals - }; - meshGenerator.Begin(); - updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed); - if (currentInstructions.hasActiveClipping) { - meshGenerator.AddSubmesh(workingSubmeshInstructions.Items[0], updateTriangles); - } else { - meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); - } - - } else { - // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. ============================================= - MeshGenerator.GenerateSkeletonRendererInstruction(currentInstructions, skeleton, customSlotMaterials, separatorSlots, doMeshOverride, this.immutableTriangles); - - // STEP 1.9. Post-process workingInstructions. ================================================================================== - #if SPINE_OPTIONAL_MATERIALOVERRIDE - if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated - MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride); - #endif - - #if SPINE_OPTIONAL_RENDEROVERRIDE - if (doMeshOverride) { - this.generateMeshOverride(currentInstructions); - if (disableRenderingOnOverride) return; - } - #endif - - updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed); - - // STEP 2. Update vertex buffer based on verts from the attachments. =========================================================== - meshGenerator.settings = new MeshGenerator.Settings { - pmaVertexColors = this.pmaVertexColors, - zSpacing = this.zSpacing, - useClipping = this.useClipping, - tintBlack = this.tintBlack, - calculateTangents = this.calculateTangents, - addNormals = this.addNormals - }; - meshGenerator.Begin(); - if (currentInstructions.hasActiveClipping) - meshGenerator.BuildMesh(currentInstructions, updateTriangles); - else - meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); - } - - if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers); - - // STEP 3. Move the mesh data into a UnityEngine.Mesh =========================================================================== - var currentMesh = currentSmartMesh.mesh; - meshGenerator.FillVertexData(currentMesh); - rendererBuffers.UpdateSharedMaterials(workingSubmeshInstructions); - if (updateTriangles) { // Check if the triangles should also be updated. - meshGenerator.FillTriangles(currentMesh); - meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray(); - } else if (rendererBuffers.MaterialsChangedInLastUpdate()) { - meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray(); - } - - - // STEP 4. The UnityEngine.Mesh is ready. Set it as the MeshFilter's mesh. Store the instructions used for that mesh. =========== - meshFilter.sharedMesh = currentMesh; - currentSmartMesh.instructionUsed.Set(currentInstructions); - } - } -} +/****************************************************************************** + * Spine Runtimes Software License v2.5 + * + * Copyright (c) 2013-2016, Esoteric Software + * All rights reserved. + * + * You are granted a perpetual, non-exclusive, non-sublicensable, and + * non-transferable license to use, install, execute, and perform the Spine + * Runtimes software and derivative works solely for personal or internal + * use. Without the written permission of Esoteric Software (see Section 2 of + * the Spine Software License Agreement), you may not (a) modify, translate, + * adapt, or develop new applications using the Spine Runtimes or otherwise + * create derivative works or improvements of the Spine Runtimes or (b) remove, + * delete, alter, or obscure any trademarks or any copyright, trademark, patent, + * or other intellectual property or proprietary rights notices on or in the + * Software, including any copy thereof. Redistributions in binary or source + * form must include this license and terms. + * + * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF + * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER + * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#define SPINE_OPTIONAL_RENDEROVERRIDE +#define SPINE_OPTIONAL_MATERIALOVERRIDE + +using System.Collections.Generic; +using UnityEngine; + +namespace Spine.Unity { + /// Renders a skeleton. + [ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer)), DisallowMultipleComponent] + [HelpURL("http://esotericsoftware.com/spine-unity-documentation#Rendering")] + public class SkeletonRenderer : MonoBehaviour, ISkeletonComponent, IHasSkeletonDataAsset { + + public delegate void SkeletonRendererDelegate (SkeletonRenderer skeletonRenderer); + public event SkeletonRendererDelegate OnRebuild; + + /// Occurs after the vertex data is populated every frame, before the vertices are pushed into the mesh. + public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices; + + public SkeletonDataAsset skeletonDataAsset; + public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } // ISkeletonComponent + public string initialSkinName; + public bool initialFlipX, initialFlipY; + + #region Advanced + // Submesh Separation + [UnityEngine.Serialization.FormerlySerializedAs("submeshSeparators")] [SpineSlot] public string[] separatorSlotNames = new string[0]; + [System.NonSerialized] public readonly List separatorSlots = new List(); + + [Range(-0.1f, 0f)] public float zSpacing; + //public bool renderMeshes = true; + public bool useClipping = true; + public bool immutableTriangles = false; + public bool pmaVertexColors = true; + /// Clears the state when this component or its GameObject is disabled. This prevents previous state from being retained when it is enabled again. When pooling your skeleton, setting this to true can be helpful. + public bool clearStateOnDisable = false; + public bool tintBlack = false; + public bool singleSubmesh = false; + + [UnityEngine.Serialization.FormerlySerializedAs("calculateNormals")] + public bool addNormals = false; + public bool calculateTangents = false; + + public bool logErrors = false; + + #if SPINE_OPTIONAL_RENDEROVERRIDE + public bool disableRenderingOnOverride = true; + public delegate void InstructionDelegate (SkeletonRendererInstruction instruction); + event InstructionDelegate generateMeshOverride; + public event InstructionDelegate GenerateMeshOverride { + add { + generateMeshOverride += value; + if (disableRenderingOnOverride && generateMeshOverride != null) { + Initialize(false); + meshRenderer.enabled = false; + } + } + remove { + generateMeshOverride -= value; + if (disableRenderingOnOverride && generateMeshOverride == null) { + Initialize(false); + meshRenderer.enabled = true; + } + } + } + #endif + + #if SPINE_OPTIONAL_MATERIALOVERRIDE + [System.NonSerialized] readonly Dictionary customMaterialOverride = new Dictionary(); + public Dictionary CustomMaterialOverride { get { return customMaterialOverride; } } + #endif + + // Custom Slot Material + [System.NonSerialized] readonly Dictionary customSlotMaterials = new Dictionary(); + public Dictionary CustomSlotMaterials { get { return customSlotMaterials; } } + #endregion + + MeshRenderer meshRenderer; + MeshFilter meshFilter; + + [System.NonSerialized] public bool valid; + [System.NonSerialized] public Skeleton skeleton; + public Skeleton Skeleton { + get { + Initialize(false); + return skeleton; + } + } + + [System.NonSerialized] readonly SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction(); + readonly MeshGenerator meshGenerator = new MeshGenerator(); + [System.NonSerialized] readonly MeshRendererBuffers rendererBuffers = new MeshRendererBuffers(); + + #region Runtime Instantiation + public static T NewSpineGameObject (SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer { + return SkeletonRenderer.AddSpineComponent(new GameObject("New Spine GameObject"), skeletonDataAsset); + } + + /// Add and prepare a Spine component that derives from SkeletonRenderer to a GameObject at runtime. + /// T should be SkeletonRenderer or any of its derived classes. + public static T AddSpineComponent (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer { + var c = gameObject.AddComponent(); + if (skeletonDataAsset != null) { + c.skeletonDataAsset = skeletonDataAsset; + c.Initialize(false); + } + return c; + } + + /// Applies MeshGenerator settings to the SkeletonRenderer and its internal MeshGenerator. + public void SetMeshSettings (MeshGenerator.Settings settings) { + this.calculateTangents = settings.calculateTangents; + this.immutableTriangles = settings.immutableTriangles; + this.pmaVertexColors = settings.pmaVertexColors; + this.tintBlack = settings.tintBlack; + this.useClipping = settings.useClipping; + this.zSpacing = settings.zSpacing; + + this.meshGenerator.settings = settings; + } + #endregion + + public virtual void Awake () { + Initialize(false); + } + + void OnDisable () { + if (clearStateOnDisable && valid) + ClearState(); + } + + void OnDestroy () { + rendererBuffers.Dispose(); + valid = false; + } + + /// + /// Clears the previously generated mesh and resets the skeleton's pose. + public virtual void ClearState () { + meshFilter.sharedMesh = null; + currentInstructions.Clear(); + if (skeleton != null) skeleton.SetToSetupPose(); + } + + /// + /// Initialize this component. Attempts to load the SkeletonData and creates the internal Skeleton object and buffers. + /// If set to true, it will overwrite internal objects if they were already generated. Otherwise, the initialized component will ignore subsequent calls to initialize. + public virtual void Initialize (bool overwrite) { + if (valid && !overwrite) + return; + + // Clear + { + if (meshFilter != null) + meshFilter.sharedMesh = null; + + meshRenderer = GetComponent(); + if (meshRenderer != null) meshRenderer.sharedMaterial = null; + + currentInstructions.Clear(); + rendererBuffers.Clear(); + meshGenerator.Begin(); + skeleton = null; + valid = false; + } + + if (!skeletonDataAsset) { + if (logErrors) Debug.LogError("Missing SkeletonData asset.", this); + return; + } + + SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false); + if (skeletonData == null) return; + valid = true; + + meshFilter = GetComponent(); + meshRenderer = GetComponent(); + rendererBuffers.Initialize(); + + skeleton = new Skeleton(skeletonData) { + flipX = initialFlipX, + flipY = initialFlipY + }; + + if (!string.IsNullOrEmpty(initialSkinName) && !string.Equals(initialSkinName, "default", System.StringComparison.Ordinal)) + skeleton.SetSkin(initialSkinName); + + separatorSlots.Clear(); + for (int i = 0; i < separatorSlotNames.Length; i++) + separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i])); + + LateUpdate(); // Generate mesh for the first frame it exists. + + if (OnRebuild != null) + OnRebuild(this); + } + + /// + /// Generates a new UnityEngine.Mesh from the internal Skeleton. + public virtual void LateUpdate () { + if (!valid) return; + + #if SPINE_OPTIONAL_RENDEROVERRIDE + bool doMeshOverride = generateMeshOverride != null; + if ((!meshRenderer.enabled) && !doMeshOverride) return; + #else + const bool doMeshOverride = false; + if (!meshRenderer.enabled) return; + #endif + var currentInstructions = this.currentInstructions; + var workingSubmeshInstructions = currentInstructions.submeshInstructions; + var currentSmartMesh = rendererBuffers.GetNextMesh(); // Double-buffer for performance. + + bool updateTriangles; + + if (this.singleSubmesh) { + // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. ============================================= + MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, skeletonDataAsset.atlasAssets[0].materials[0]); + + // STEP 1.9. Post-process workingInstructions. ================================================================================== + #if SPINE_OPTIONAL_MATERIALOVERRIDE + if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated + MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride); + #endif + + // STEP 2. Update vertex buffer based on verts from the attachments. =========================================================== + meshGenerator.settings = new MeshGenerator.Settings { + pmaVertexColors = this.pmaVertexColors, + zSpacing = this.zSpacing, + useClipping = this.useClipping, + tintBlack = this.tintBlack, + calculateTangents = this.calculateTangents, + addNormals = this.addNormals + }; + meshGenerator.Begin(); + updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed); + if (currentInstructions.hasActiveClipping) { + meshGenerator.AddSubmesh(workingSubmeshInstructions.Items[0], updateTriangles); + } else { + meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); + } + + } else { + // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. ============================================= + MeshGenerator.GenerateSkeletonRendererInstruction(currentInstructions, skeleton, customSlotMaterials, separatorSlots, doMeshOverride, this.immutableTriangles); + + // STEP 1.9. Post-process workingInstructions. ================================================================================== + #if SPINE_OPTIONAL_MATERIALOVERRIDE + if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated + MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride); + #endif + + #if SPINE_OPTIONAL_RENDEROVERRIDE + if (doMeshOverride) { + this.generateMeshOverride(currentInstructions); + if (disableRenderingOnOverride) return; + } + #endif + + updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed); + + // STEP 2. Update vertex buffer based on verts from the attachments. =========================================================== + meshGenerator.settings = new MeshGenerator.Settings { + pmaVertexColors = this.pmaVertexColors, + zSpacing = this.zSpacing, + useClipping = this.useClipping, + tintBlack = this.tintBlack, + calculateTangents = this.calculateTangents, + addNormals = this.addNormals + }; + meshGenerator.Begin(); + if (currentInstructions.hasActiveClipping) + meshGenerator.BuildMesh(currentInstructions, updateTriangles); + else + meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); + } + + if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers); + + // STEP 3. Move the mesh data into a UnityEngine.Mesh =========================================================================== + var currentMesh = currentSmartMesh.mesh; + meshGenerator.FillVertexData(currentMesh); + rendererBuffers.UpdateSharedMaterials(workingSubmeshInstructions); + if (updateTriangles) { // Check if the triangles should also be updated. + meshGenerator.FillTriangles(currentMesh); + meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray(); + } else if (rendererBuffers.MaterialsChangedInLastUpdate()) { + meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray(); + } + + + // STEP 4. The UnityEngine.Mesh is ready. Set it as the MeshFilter's mesh. Store the instructions used for that mesh. =========== + meshFilter.sharedMesh = currentMesh; + currentSmartMesh.instructionUsed.Set(currentInstructions); + } + } +} diff --git a/spine-unity/Assets/spine-unity/SkeletonRenderer.cs.meta b/spine-unity/Assets/spine-unity/Components/SkeletonRenderer.cs.meta similarity index 100% rename from spine-unity/Assets/spine-unity/SkeletonRenderer.cs.meta rename to spine-unity/Assets/spine-unity/Components/SkeletonRenderer.cs.meta From aaeee6de135e82b3f98610a061fb26245bae7303 Mon Sep 17 00:00:00 2001 From: pharan Date: Thu, 8 Mar 2018 22:00:19 +0800 Subject: [PATCH 04/12] [unity] Move Components into their own folder. --- spine-unity/Assets/spine-unity/Components.meta | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 spine-unity/Assets/spine-unity/Components.meta diff --git a/spine-unity/Assets/spine-unity/Components.meta b/spine-unity/Assets/spine-unity/Components.meta new file mode 100644 index 000000000..c8b46595a --- /dev/null +++ b/spine-unity/Assets/spine-unity/Components.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 954179821df28404683b8289f05d0c6f +folderAsset: yes +timeCreated: 1518344191 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: From a8921ac7e3f2ab3c2ea01ffeb8dc7b9bbc3f504c Mon Sep 17 00:00:00 2001 From: pharan Date: Thu, 8 Mar 2018 22:02:15 +0800 Subject: [PATCH 05/12] [unity] Some SpineEditorUtilities cleanup. --- .../Editor/SpineEditorUtilities.cs | 254 +++++++++--------- 1 file changed, 128 insertions(+), 126 deletions(-) diff --git a/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs b/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs index 309cfeb25..61be6c602 100644 --- a/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs +++ b/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs @@ -163,9 +163,7 @@ namespace Spine.Unity.Editor { static readonly List protectFromStackGarbageCollection = new List(); static HashSet assetsImportedInWrongState = new HashSet(); - static Dictionary skeletonRendererTable = new Dictionary(); - static Dictionary skeletonUtilityBoneTable = new Dictionary(); - static Dictionary boundingBoxFollowerTable = new Dictionary(); + #if SPINE_TK2D const float DEFAULT_DEFAULT_SCALE = 1f; @@ -224,21 +222,20 @@ namespace Spine.Unity.Editor { // Drag and Drop SceneView.onSceneGUIDelegate -= SceneViewDragAndDrop; SceneView.onSceneGUIDelegate += SceneViewDragAndDrop; - EditorApplication.hierarchyWindowItemOnGUI -= HierarchyDragAndDrop; - EditorApplication.hierarchyWindowItemOnGUI += HierarchyDragAndDrop; + EditorApplication.hierarchyWindowItemOnGUI -= SpineEditorHierarchyHandler.HierarchyDragAndDrop; + EditorApplication.hierarchyWindowItemOnGUI += SpineEditorHierarchyHandler.HierarchyDragAndDrop; // Hierarchy Icons #if UNITY_2017_2_OR_NEWER - EditorApplication.playModeStateChanged -= HierarchyIconsOnPlaymodeStateChanged; - EditorApplication.playModeStateChanged += HierarchyIconsOnPlaymodeStateChanged; - HierarchyIconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); + EditorApplication.playModeStateChanged -= SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged; + EditorApplication.playModeStateChanged += SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged; + SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); #else - EditorApplication.playmodeStateChanged -= HierarchyIconsOnPlaymodeStateChanged; - EditorApplication.playmodeStateChanged += HierarchyIconsOnPlaymodeStateChanged; - HierarchyIconsOnPlaymodeStateChanged(); + EditorApplication.playmodeStateChanged -= SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged; + EditorApplication.playmodeStateChanged += SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged; + SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged(); #endif - initialized = true; } @@ -261,9 +258,9 @@ namespace Spine.Unity.Editor { if (EditorGUI.EndChangeCheck()) { EditorPrefs.SetBool(SHOW_HIERARCHY_ICONS_KEY, showHierarchyIcons); #if UNITY_2017_2_OR_NEWER - HierarchyIconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); + SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); #else - HierarchyIconsOnPlaymodeStateChanged(); + SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged(); #endif } @@ -319,10 +316,9 @@ namespace Spine.Unity.Editor { #endregion #region Drag and Drop Instantiation - public delegate Component InstantiateDelegate (SkeletonDataAsset skeletonDataAsset); - struct SpawnMenuData { + public struct SpawnMenuData { public Vector3 spawnPoint; public SkeletonDataAsset skeletonDataAsset; public InstantiateDelegate instantiateDelegate; @@ -335,7 +331,7 @@ namespace Spine.Unity.Editor { public bool isUI; } - public static readonly List additionalSpawnTypes = new List(); + internal static readonly List additionalSpawnTypes = new List(); static void SceneViewDragAndDrop (SceneView sceneview) { var current = UnityEngine.Event.current; @@ -374,45 +370,6 @@ namespace Spine.Unity.Editor { } } - static void HierarchyDragAndDrop (int instanceId, Rect selectionRect) { - // HACK: Uses EditorApplication.hierarchyWindowItemOnGUI. - // Only works when there is at least one item in the scene. - var current = UnityEngine.Event.current; - var eventType = current.type; - bool isDraggingEvent = eventType == EventType.DragUpdated; - bool isDropEvent = eventType == EventType.DragPerform; - if (isDraggingEvent || isDropEvent) { - var mouseOverWindow = EditorWindow.mouseOverWindow; - if (mouseOverWindow != null) { - - // One, existing, valid SkeletonDataAsset - var references = DragAndDrop.objectReferences; - if (references.Length == 1) { - var skeletonDataAsset = references[0] as SkeletonDataAsset; - if (skeletonDataAsset != null && skeletonDataAsset.GetSkeletonData(true) != null) { - - // Allow drag-and-dropping anywhere in the Hierarchy Window. - // HACK: string-compare because we can't get its type via reflection. - const string HierarchyWindow = "UnityEditor.SceneHierarchyWindow"; - if (HierarchyWindow.Equals(mouseOverWindow.GetType().ToString(), System.StringComparison.Ordinal)) { - if (isDraggingEvent) { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - current.Use(); - } else if (isDropEvent) { - ShowInstantiateContextMenu(skeletonDataAsset, Vector3.zero); - DragAndDrop.AcceptDrag(); - current.Use(); - return; - } - } - - } - } - } - } - - } - public static void ShowInstantiateContextMenu (SkeletonDataAsset skeletonDataAsset, Vector3 spawnPoint) { var menu = new GenericMenu(); @@ -450,8 +407,8 @@ namespace Spine.Unity.Editor { menu.ShowAsContext(); } - public static void HandleSkeletonComponentDrop (object menuData) { - var data = (SpawnMenuData)menuData; + public static void HandleSkeletonComponentDrop (object spawnMenuData) { + var data = (SpawnMenuData)spawnMenuData; if (data.skeletonDataAsset.GetSkeletonData(true) == null) { EditorUtility.DisplayDialog("Invalid SkeletonDataAsset", "Unable to create Spine GameObject.\n\nPlease check your SkeletonDataAsset.", "Ok"); @@ -460,16 +417,15 @@ namespace Spine.Unity.Editor { bool isUI = data.isUI; - GameObject newGameObject = null; Component newSkeletonComponent = data.instantiateDelegate.Invoke(data.skeletonDataAsset); - newGameObject = newSkeletonComponent.gameObject; - var transform = newGameObject.transform; + GameObject newGameObject = newSkeletonComponent.gameObject; + Transform newTransform = newGameObject.transform; var activeGameObject = Selection.activeGameObject; if (isUI && activeGameObject != null) - transform.SetParent(activeGameObject.transform, false); + newTransform.SetParent(activeGameObject.transform, false); - newGameObject.transform.position = isUI ? data.spawnPoint : RoundVector(data.spawnPoint, 2); + newTransform.position = isUI ? data.spawnPoint : RoundVector(data.spawnPoint, 2); if (isUI && (activeGameObject == null || activeGameObject.GetComponent() == null)) Debug.Log("Created a UI Skeleton GameObject not under a RectTransform. It may not be visible until you parent it to a canvas."); @@ -505,72 +461,117 @@ namespace Spine.Unity.Editor { #endregion #region Hierarchy - #if UNITY_2017_2_OR_NEWER - static void HierarchyIconsOnPlaymodeStateChanged (PlayModeStateChange stateChange) { - #else - static void HierarchyIconsOnPlaymodeStateChanged () { - #endif - skeletonRendererTable.Clear(); - skeletonUtilityBoneTable.Clear(); - boundingBoxFollowerTable.Clear(); + static class SpineEditorHierarchyHandler { + static Dictionary skeletonRendererTable = new Dictionary(); + static Dictionary skeletonUtilityBoneTable = new Dictionary(); + static Dictionary boundingBoxFollowerTable = new Dictionary(); - EditorApplication.hierarchyWindowChanged -= HierarchyIconsOnChanged; - EditorApplication.hierarchyWindowItemOnGUI -= HierarchyIconsOnGUI; + #if UNITY_2017_2_OR_NEWER + internal static void HierarchyIconsOnPlaymodeStateChanged (PlayModeStateChange stateChange) { + #else + internal static void HierarchyIconsOnPlaymodeStateChanged () { + #endif + skeletonRendererTable.Clear(); + skeletonUtilityBoneTable.Clear(); + boundingBoxFollowerTable.Clear(); - if (!Application.isPlaying && showHierarchyIcons) { - EditorApplication.hierarchyWindowChanged += HierarchyIconsOnChanged; - EditorApplication.hierarchyWindowItemOnGUI += HierarchyIconsOnGUI; - HierarchyIconsOnChanged(); + EditorApplication.hierarchyWindowChanged -= HierarchyIconsOnChanged; + EditorApplication.hierarchyWindowItemOnGUI -= HierarchyIconsOnGUI; + + if (!Application.isPlaying && showHierarchyIcons) { + EditorApplication.hierarchyWindowChanged += HierarchyIconsOnChanged; + EditorApplication.hierarchyWindowItemOnGUI += HierarchyIconsOnGUI; + HierarchyIconsOnChanged(); + } } - } - static void HierarchyIconsOnChanged () { - skeletonRendererTable.Clear(); - skeletonUtilityBoneTable.Clear(); - boundingBoxFollowerTable.Clear(); + internal static void HierarchyIconsOnChanged () { + skeletonRendererTable.Clear(); + skeletonUtilityBoneTable.Clear(); + boundingBoxFollowerTable.Clear(); - SkeletonRenderer[] arr = Object.FindObjectsOfType(); - foreach (SkeletonRenderer r in arr) - skeletonRendererTable[r.gameObject.GetInstanceID()] = r.gameObject; + SkeletonRenderer[] arr = Object.FindObjectsOfType(); + foreach (SkeletonRenderer r in arr) + skeletonRendererTable[r.gameObject.GetInstanceID()] = r.gameObject; - SkeletonUtilityBone[] boneArr = Object.FindObjectsOfType(); - foreach (SkeletonUtilityBone b in boneArr) - skeletonUtilityBoneTable[b.gameObject.GetInstanceID()] = b; + SkeletonUtilityBone[] boneArr = Object.FindObjectsOfType(); + foreach (SkeletonUtilityBone b in boneArr) + skeletonUtilityBoneTable[b.gameObject.GetInstanceID()] = b; - BoundingBoxFollower[] bbfArr = Object.FindObjectsOfType(); - foreach (BoundingBoxFollower bbf in bbfArr) - boundingBoxFollowerTable[bbf.gameObject.GetInstanceID()] = bbf; - } + BoundingBoxFollower[] bbfArr = Object.FindObjectsOfType(); + foreach (BoundingBoxFollower bbf in bbfArr) + boundingBoxFollowerTable[bbf.gameObject.GetInstanceID()] = bbf; + } - static void HierarchyIconsOnGUI (int instanceId, Rect selectionRect) { - Rect r = new Rect(selectionRect); - if (skeletonRendererTable.ContainsKey(instanceId)) { - r.x = r.width - 15; - r.width = 15; - GUI.Label(r, Icons.spine); - } else if (skeletonUtilityBoneTable.ContainsKey(instanceId)) { - r.x -= 26; - if (skeletonUtilityBoneTable[instanceId] != null) { - if (skeletonUtilityBoneTable[instanceId].transform.childCount == 0) - r.x += 13; - r.y += 2; - r.width = 13; - r.height = 13; - if (skeletonUtilityBoneTable[instanceId].mode == SkeletonUtilityBone.Mode.Follow) - GUI.DrawTexture(r, Icons.bone); - else - GUI.DrawTexture(r, Icons.poseBones); + internal static void HierarchyIconsOnGUI (int instanceId, Rect selectionRect) { + Rect r = new Rect(selectionRect); + if (skeletonRendererTable.ContainsKey(instanceId)) { + r.x = r.width - 15; + r.width = 15; + GUI.Label(r, Icons.spine); + } else if (skeletonUtilityBoneTable.ContainsKey(instanceId)) { + r.x -= 26; + if (skeletonUtilityBoneTable[instanceId] != null) { + if (skeletonUtilityBoneTable[instanceId].transform.childCount == 0) + r.x += 13; + r.y += 2; + r.width = 13; + r.height = 13; + if (skeletonUtilityBoneTable[instanceId].mode == SkeletonUtilityBone.Mode.Follow) + GUI.DrawTexture(r, Icons.bone); + else + GUI.DrawTexture(r, Icons.poseBones); + } + } else if (boundingBoxFollowerTable.ContainsKey(instanceId)) { + r.x -= 26; + if (boundingBoxFollowerTable[instanceId] != null) { + if (boundingBoxFollowerTable[instanceId].transform.childCount == 0) + r.x += 13; + r.y += 2; + r.width = 13; + r.height = 13; + GUI.DrawTexture(r, Icons.boundingBox); + } } - } else if (boundingBoxFollowerTable.ContainsKey(instanceId)) { - r.x -= 26; - if (boundingBoxFollowerTable[instanceId] != null) { - if (boundingBoxFollowerTable[instanceId].transform.childCount == 0) - r.x += 13; - r.y += 2; - r.width = 13; - r.height = 13; - GUI.DrawTexture(r, Icons.boundingBox); + } + + internal static void HierarchyDragAndDrop (int instanceId, Rect selectionRect) { + // HACK: Uses EditorApplication.hierarchyWindowItemOnGUI. + // Only works when there is at least one item in the scene. + var current = UnityEngine.Event.current; + var eventType = current.type; + bool isDraggingEvent = eventType == EventType.DragUpdated; + bool isDropEvent = eventType == EventType.DragPerform; + if (isDraggingEvent || isDropEvent) { + var mouseOverWindow = EditorWindow.mouseOverWindow; + if (mouseOverWindow != null) { + + // One, existing, valid SkeletonDataAsset + var references = DragAndDrop.objectReferences; + if (references.Length == 1) { + var skeletonDataAsset = references[0] as SkeletonDataAsset; + if (skeletonDataAsset != null && skeletonDataAsset.GetSkeletonData(true) != null) { + + // Allow drag-and-dropping anywhere in the Hierarchy Window. + // HACK: string-compare because we can't get its type via reflection. + const string HierarchyWindow = "UnityEditor.SceneHierarchyWindow"; + if (HierarchyWindow.Equals(mouseOverWindow.GetType().ToString(), System.StringComparison.Ordinal)) { + if (isDraggingEvent) { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + current.Use(); + } else if (isDropEvent) { + ShowInstantiateContextMenu(skeletonDataAsset, Vector3.zero); + DragAndDrop.AcceptDrag(); + current.Use(); + return; + } + } + + } + } + } } + } } #endregion @@ -665,7 +666,7 @@ namespace Spine.Unity.Editor { bool resolved = false; while (!resolved) { - var filename = Path.GetFileNameWithoutExtension(sp); + string filename = Path.GetFileNameWithoutExtension(sp); int result = EditorUtility.DisplayDialogComplex( string.Format("AtlasAsset for \"{0}\"", filename), string.Format("Could not automatically set the AtlasAsset for \"{0}\". You may set it manually.", filename), @@ -1653,11 +1654,12 @@ namespace Spine.Unity.Editor { public static GUIStyle BoneNameStyle { get { if (_boneNameStyle == null) { - _boneNameStyle = new GUIStyle(EditorStyles.whiteMiniLabel); - _boneNameStyle.alignment = TextAnchor.MiddleCenter; - _boneNameStyle.stretchWidth = true; - _boneNameStyle.padding = new RectOffset(0, 0, 0, 0); - _boneNameStyle.contentOffset = new Vector2(-5f, 0f); + _boneNameStyle = new GUIStyle(EditorStyles.whiteMiniLabel) { + alignment = TextAnchor.MiddleCenter, + stretchWidth = true, + padding = new RectOffset(0, 0, 0, 0), + contentOffset = new Vector2(-5f, 0f) + }; } return _boneNameStyle; } @@ -1979,7 +1981,7 @@ namespace Spine.Unity.Editor { } static void DrawArrowhead (Matrix4x4 m) { - var s = SpineHandles.handleScale; + float s = SpineHandles.handleScale; m.m00 *= s; m.m01 *= s; m.m02 *= s; From d3bce39d656b0ca7bd9bdd6ba0f3c24e01087863 Mon Sep 17 00:00:00 2001 From: pharan Date: Thu, 8 Mar 2018 22:28:42 +0800 Subject: [PATCH 06/12] [unity] Updated compatibility just for json. --- .../spine-unity/Editor/SpineEditorUtilities.cs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs b/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs index 61be6c602..e38546d0c 100644 --- a/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs +++ b/spine-unity/Assets/spine-unity/Editor/SpineEditorUtilities.cs @@ -1240,7 +1240,8 @@ namespace Spine.Unity.Editor { #endregion #region Checking Methods - static int[][] compatibleVersions = { new[] {3, 6, 0}, new[] {3, 5, 0} }; + static int[][] compatibleBinaryVersions = { new[] {3, 6, 0}, new[] {3, 5, 0} }; + static int[][] compatibleJsonVersions = { new[] { 3, 6, 0 }, new[] { 3, 7, 0 }, new[] { 3, 5, 0 } }; //static bool isFixVersionRequired = false; static bool CheckForValidSkeletonData (string skeletonJSONPath) { @@ -1266,17 +1267,18 @@ namespace Spine.Unity.Editor { bool isSpineData = false; string rawVersion = null; + int[][] compatibleVersions; if (asset.name.Contains(".skel")) { try { rawVersion = SkeletonBinary.GetVersionString(new MemoryStream(asset.bytes)); - //Debug.Log(rawVersion); isSpineData = !(string.IsNullOrEmpty(rawVersion)); + compatibleVersions = compatibleBinaryVersions; } catch (System.Exception e) { Debug.LogErrorFormat("Failed to read '{0}'. It is likely not a binary Spine SkeletonData file.\n{1}", asset.name, e); return false; } } else { - var obj = Json.Deserialize(new StringReader(asset.text)); + object obj = Json.Deserialize(new StringReader(asset.text)); if (obj == null) { Debug.LogErrorFormat("'{0}' is not valid JSON.", asset.name); return false; @@ -1295,14 +1297,16 @@ namespace Spine.Unity.Editor { skeletonInfo.TryGetValue("spine", out jv); rawVersion = jv as string; } + + compatibleVersions = compatibleJsonVersions; } // Version warning if (isSpineData) { - string runtimeVersionDebugString = compatibleVersions[0][0] + "." + compatibleVersions[0][1]; + string primaryRuntimeVersionDebugString = compatibleVersions[0][0] + "." + compatibleVersions[0][1]; if (string.IsNullOrEmpty(rawVersion)) { - Debug.LogWarningFormat("Skeleton '{0}' has no version information. It may be incompatible with your runtime version: spine-unity v{1}", asset.name, runtimeVersionDebugString); + Debug.LogWarningFormat("Skeleton '{0}' has no version information. It may be incompatible with your runtime version: spine-unity v{1}", asset.name, primaryRuntimeVersionDebugString); } else { string[] versionSplit = rawVersion.Split('.'); bool match = false; @@ -1319,7 +1323,7 @@ namespace Spine.Unity.Editor { } if (!match) - Debug.LogWarningFormat("Skeleton '{0}' (exported with Spine {1}) may be incompatible with your runtime version: spine-unity v{2}", asset.name, rawVersion, runtimeVersionDebugString); + Debug.LogWarningFormat("Skeleton '{0}' (exported with Spine {1}) may be incompatible with your runtime version: spine-unity v{2}", asset.name, rawVersion, primaryRuntimeVersionDebugString); } } From 9958bf48e89832fac3961fe73b7fb08620a07b78 Mon Sep 17 00:00:00 2001 From: pharan Date: Thu, 8 Mar 2018 22:35:00 +0800 Subject: [PATCH 07/12] [unity] Allow skeleton data to load without atlases. --- .../Asset Types/RegionlessAttachmentLoader.cs | 84 +++++++++++++++++++ .../RegionlessAttachmentLoader.cs.meta | 12 +++ .../Asset Types/SkeletonDataAsset.cs | 2 +- .../Editor/SkeletonDataAssetInspector.cs | 58 ++++++++----- 4 files changed, 132 insertions(+), 24 deletions(-) create mode 100644 spine-unity/Assets/spine-unity/Asset Types/RegionlessAttachmentLoader.cs create mode 100644 spine-unity/Assets/spine-unity/Asset Types/RegionlessAttachmentLoader.cs.meta diff --git a/spine-unity/Assets/spine-unity/Asset Types/RegionlessAttachmentLoader.cs b/spine-unity/Assets/spine-unity/Asset Types/RegionlessAttachmentLoader.cs new file mode 100644 index 000000000..cbfd25c12 --- /dev/null +++ b/spine-unity/Assets/spine-unity/Asset Types/RegionlessAttachmentLoader.cs @@ -0,0 +1,84 @@ +/****************************************************************************** + * Spine Runtimes Software License v2.5 + * + * Copyright (c) 2013-2016, Esoteric Software + * All rights reserved. + * + * You are granted a perpetual, non-exclusive, non-sublicensable, and + * non-transferable license to use, install, execute, and perform the Spine + * Runtimes software and derivative works solely for personal or internal + * use. Without the written permission of Esoteric Software (see Section 2 of + * the Spine Software License Agreement), you may not (a) modify, translate, + * adapt, or develop new applications using the Spine Runtimes or otherwise + * create derivative works or improvements of the Spine Runtimes or (b) remove, + * delete, alter, or obscure any trademarks or any copyright, trademark, patent, + * or other intellectual property or proprietary rights notices on or in the + * Software, including any copy thereof. Redistributions in binary or source + * form must include this license and terms. + * + * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF + * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER + * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using UnityEngine; + +namespace Spine.Unity { + + public class RegionlessAttachmentLoader : AttachmentLoader { + + static AtlasRegion emptyRegion; + static AtlasRegion EmptyRegion { + get { + if (emptyRegion == null) { + emptyRegion = new AtlasRegion { + name = "Empty AtlasRegion", + page = new AtlasPage { + name = "Empty AtlasPage", + rendererObject = new Material(Shader.Find("Spine/Special/HiddenPass")) { name = "NoRender Material" } + } + }; + } + return emptyRegion; + } + } + + public RegionAttachment NewRegionAttachment (Skin skin, string name, string path) { + RegionAttachment attachment = new RegionAttachment(name) { + RendererObject = EmptyRegion + }; + return attachment; + } + + public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) { + MeshAttachment attachment = new MeshAttachment(name) { + RendererObject = EmptyRegion + }; + return attachment; + } + + public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name) { + return new BoundingBoxAttachment(name); + } + + public PathAttachment NewPathAttachment (Skin skin, string name) { + return new PathAttachment(name); + } + + public PointAttachment NewPointAttachment (Skin skin, string name) { + return new PointAttachment(name); + } + + public ClippingAttachment NewClippingAttachment (Skin skin, string name) { + return new ClippingAttachment(name); + } + } +} diff --git a/spine-unity/Assets/spine-unity/Asset Types/RegionlessAttachmentLoader.cs.meta b/spine-unity/Assets/spine-unity/Asset Types/RegionlessAttachmentLoader.cs.meta new file mode 100644 index 000000000..5d7a368b9 --- /dev/null +++ b/spine-unity/Assets/spine-unity/Asset Types/RegionlessAttachmentLoader.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 15f0f78b87720c047a320c5e0e3f91b7 +timeCreated: 1520505662 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/spine-unity/Assets/spine-unity/Asset Types/SkeletonDataAsset.cs b/spine-unity/Assets/spine-unity/Asset Types/SkeletonDataAsset.cs index f1846e0c8..66b0cd97c 100644 --- a/spine-unity/Assets/spine-unity/Asset Types/SkeletonDataAsset.cs +++ b/spine-unity/Assets/spine-unity/Asset Types/SkeletonDataAsset.cs @@ -126,7 +126,7 @@ namespace Spine.Unity { Atlas[] atlasArray = this.GetAtlasArray(); #if !SPINE_TK2D - attachmentLoader = new AtlasAttachmentLoader(atlasArray); + attachmentLoader = (atlasArray.Length == 0) ? (AttachmentLoader)new RegionlessAttachmentLoader() : (AttachmentLoader)new AtlasAttachmentLoader(atlasArray); skeletonDataScale = scale; #else if (spriteCollection != null) { diff --git a/spine-unity/Assets/spine-unity/Editor/SkeletonDataAssetInspector.cs b/spine-unity/Assets/spine-unity/Editor/SkeletonDataAssetInspector.cs index 0ae00c3ce..750f56855 100644 --- a/spine-unity/Assets/spine-unity/Editor/SkeletonDataAssetInspector.cs +++ b/spine-unity/Assets/spine-unity/Editor/SkeletonDataAssetInspector.cs @@ -274,6 +274,9 @@ namespace Spine.Unity.Editor { EditorGUILayout.LabelField("spine-tk2d", EditorStyles.boldLabel); EditorGUILayout.PropertyField(spriteCollection, true); #endif + + if (atlasAssets.arraySize == 0) + EditorGUILayout.HelpBox("AtlasAssets array is empty. Skeleton's attachments will load without being mapped to images.", MessageType.Info); } void HandleAtlasAssetsNulls () { @@ -485,7 +488,7 @@ namespace Spine.Unity.Editor { } void DrawWarningList () { - foreach (var line in warnings) + foreach (string line in warnings) EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(line, Icons.warning)); } @@ -525,25 +528,30 @@ namespace Spine.Unity.Editor { if (detectedNullAtlasEntry) { warnings.Add("AtlasAsset elements should not be null."); } else { - var missingPaths = SpineEditorUtilities.GetRequiredAtlasRegions(AssetDatabase.GetAssetPath(skeletonJSON.objectReferenceValue)); + List missingPaths = null; + if (atlasAssets.arraySize > 0) { + missingPaths = SpineEditorUtilities.GetRequiredAtlasRegions(AssetDatabase.GetAssetPath(skeletonJSON.objectReferenceValue)); - foreach (var atlas in atlasList) { - for (int i = 0; i < missingPaths.Count; i++) { - if (atlas.FindRegion(missingPaths[i]) != null) { - missingPaths.RemoveAt(i); - i--; + foreach (var atlas in atlasList) { + for (int i = 0; i < missingPaths.Count; i++) { + if (atlas.FindRegion(missingPaths[i]) != null) { + missingPaths.RemoveAt(i); + i--; + } } } + + #if SPINE_TK2D + if (missingPaths.Count > 0) + warnings.Add("Missing regions. SkeletonDataAsset requires tk2DSpriteCollectionData or Spine AtlasAssets."); + #endif } - #if SPINE_TK2D - if (missingPaths.Count > 0) - warnings.Add("Missing regions. SkeletonDataAsset requires tk2DSpriteCollectionData or Spine AtlasAssets."); - #endif - - foreach (var str in missingPaths) - warnings.Add("Missing Region: '" + str + "'"); - + if (missingPaths != null) { + foreach (string str in missingPaths) + warnings.Add("Missing Region: '" + str + "'"); + } + } } @@ -629,7 +637,10 @@ namespace Spine.Unity.Editor { PreviewRenderUtility previewRenderUtility; Camera PreviewUtilityCamera { get { - if (previewRenderUtility == null) return null; + if (previewRenderUtility == null) { + + return null; + } #if UNITY_2017_1_OR_NEWER return previewRenderUtility.camera; @@ -770,7 +781,7 @@ namespace Spine.Unity.Editor { skeleton.SetToSetupPose(); animationState.SetAnimation(0, targetAnimation, loop); } else { - var sameAnimation = (currentTrack.Animation == targetAnimation); + bool sameAnimation = (currentTrack.Animation == targetAnimation); if (sameAnimation) { currentTrack.TimeScale = (currentTrack.TimeScale == 0) ? 1f : 0f; // pause/play } else { @@ -974,18 +985,19 @@ namespace Spine.Unity.Editor { for (int i = 0; i < currentAnimationEvents.Count; i++) { float fr = currentAnimationEventTimes[i]; - var evRect = new Rect(barRect); - evRect.x = Mathf.Clamp(((fr / t.Animation.Duration) * width) - (Icons.userEvent.width / 2), barRect.x, float.MaxValue); - evRect.width = Icons.userEvent.width; - evRect.height = Icons.userEvent.height; - evRect.y += Icons.userEvent.height; + var evRect = new Rect(barRect) { + x = Mathf.Clamp(((fr / t.Animation.Duration) * width) - (Icons.userEvent.width / 2), barRect.x, float.MaxValue), + y = barRect.y + Icons.userEvent.height, + width = Icons.userEvent.width, + height = Icons.userEvent.height + }; GUI.DrawTexture(evRect, Icons.userEvent); Event ev = Event.current; if (ev.type == EventType.Repaint) { if (evRect.Contains(ev.mousePosition)) { - Rect tooltipRect = new Rect(evRect); GUIStyle tooltipStyle = EditorStyles.helpBox; + Rect tooltipRect = new Rect(evRect); tooltipRect.width = tooltipStyle.CalcSize(new GUIContent(currentAnimationEvents[i].Data.Name)).x; tooltipRect.y -= 4; tooltipRect.x += 4; From 0f5172a89d96f439ba5f47ba105604873522dd76 Mon Sep 17 00:00:00 2001 From: pharan Date: Thu, 8 Mar 2018 22:36:42 +0800 Subject: [PATCH 08/12] [unity] Hint at code with fixed eye normal. --- spine-unity/Assets/spine-unity/Shaders/Spine-SkeletonLit.shader | 1 + 1 file changed, 1 insertion(+) diff --git a/spine-unity/Assets/spine-unity/Shaders/Spine-SkeletonLit.shader b/spine-unity/Assets/spine-unity/Shaders/Spine-SkeletonLit.shader index 1917340ee..8b193c295 100644 --- a/spine-unity/Assets/spine-unity/Shaders/Spine-SkeletonLit.shader +++ b/spine-unity/Assets/spine-unity/Shaders/Spine-SkeletonLit.shader @@ -113,6 +113,7 @@ Shader "Spine/Skeleton Lit" { float3 eyePos = UnityObjectToViewPos(float4(v.pos, 1)).xyz; //mul(UNITY_MATRIX_MV, float4(v.pos,1)).xyz; half3 fixedNormal = half3(0,0,-1); half3 eyeNormal = normalize(mul((float3x3)UNITY_MATRIX_IT_MV, fixedNormal)); + //half3 eyeNormal = half3(0,0,1); half3 viewDir = 0.0; // Lights From 0b019536904b5f73bb7c8029786c3ff49b755040 Mon Sep 17 00:00:00 2001 From: pharan Date: Thu, 8 Mar 2018 22:38:28 +0800 Subject: [PATCH 09/12] [csharp] Some cleanup. --- spine-csharp/src/Animation.cs | 16 +-- spine-csharp/src/SkeletonJson.cs | 179 +++++++++++++++---------------- spine-csharp/src/Skin.cs | 2 +- 3 files changed, 99 insertions(+), 98 deletions(-) diff --git a/spine-csharp/src/Animation.cs b/spine-csharp/src/Animation.cs index 7bd5e0c5a..57fa1fe4a 100644 --- a/spine-csharp/src/Animation.cs +++ b/spine-csharp/src/Animation.cs @@ -154,7 +154,7 @@ namespace Spine { protected const float LINEAR = 0, STEPPED = 1, BEZIER = 2; protected const int BEZIER_SIZE = 10 * 2 - 1; - private float[] curves; // type, x, y, ... + internal float[] curves; // type, x, y, ... public int FrameCount { get { return curves.Length / BEZIER_SIZE + 1; } } public CurveTimeline (int frameCount) { @@ -607,17 +607,19 @@ namespace Spine { protected const int PREV_R2 = -3, PREV_G2 = -2, PREV_B2 = -1; protected const int R = 1, G = 2, B = 3, A = 4, R2 = 5, G2 = 6, B2 = 7; - internal float[] frames; // time, r, g, b, a, r2, g2, b2, ... - public float[] Frames { get { return frames; } } - internal int slotIndex; + internal float[] frames; // time, r, g, b, a, r2, g2, b2, ... + public int SlotIndex { get { return slotIndex; } set { - if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + if (value < 0) + throw new ArgumentOutOfRangeException("index must be >= 0."); slotIndex = value; } } + + public float[] Frames { get { return frames; } } override public int PropertyId { get { return ((int)TimelineType.TwoColor << 24) + slotIndex; } @@ -745,11 +747,11 @@ namespace Spine { public class AttachmentTimeline : Timeline { internal int slotIndex; internal float[] frames; - private String[] attachmentNames; + internal string[] attachmentNames; public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } } public float[] Frames { get { return frames; } set { frames = value; } } // time, ... - public String[] AttachmentNames { get { return attachmentNames; } set { attachmentNames = value; } } + public string[] AttachmentNames { get { return attachmentNames; } set { attachmentNames = value; } } public int FrameCount { get { return frames.Length; } } public int PropertyId { diff --git a/spine-csharp/src/SkeletonJson.cs b/spine-csharp/src/SkeletonJson.cs index 848adb4a5..924e3036d 100644 --- a/spine-csharp/src/SkeletonJson.cs +++ b/spine-csharp/src/SkeletonJson.cs @@ -69,11 +69,11 @@ namespace Spine { } } - public SkeletonData ReadSkeletonData (String path) { + public SkeletonData ReadSkeletonData (string path) { return this.ReadFile(path).Result; } #else - public SkeletonData ReadSkeletonData (String path) { + public SkeletonData ReadSkeletonData (string path) { #if WINDOWS_PHONE using (var reader = new StreamReader(Microsoft.Xna.Framework.TitleContainer.OpenStream(path))) { #else @@ -89,17 +89,17 @@ namespace Spine { public SkeletonData ReadSkeletonData (TextReader reader) { if (reader == null) throw new ArgumentNullException("reader", "reader cannot be null."); - var scale = this.Scale; + float scale = this.Scale; var skeletonData = new SkeletonData(); - var root = Json.Deserialize(reader) as Dictionary; + var root = Json.Deserialize(reader) as Dictionary; if (root == null) throw new Exception("Invalid JSON."); // Skeleton. if (root.ContainsKey("skeleton")) { - var skeletonMap = (Dictionary)root["skeleton"]; - skeletonData.hash = (String)skeletonMap["hash"]; - skeletonData.version = (String)skeletonMap["spine"]; + var skeletonMap = (Dictionary)root["skeleton"]; + skeletonData.hash = (string)skeletonMap["hash"]; + skeletonData.version = (string)skeletonMap["spine"]; skeletonData.width = GetFloat(skeletonMap, "width", 0); skeletonData.height = GetFloat(skeletonMap, "height", 0); skeletonData.fps = GetFloat(skeletonMap, "fps", 0); @@ -107,14 +107,14 @@ namespace Spine { } // Bones. - foreach (Dictionary boneMap in (List)root["bones"]) { + foreach (Dictionary boneMap in (List)root["bones"]) { BoneData parent = null; if (boneMap.ContainsKey("parent")) { - parent = skeletonData.FindBone((String)boneMap["parent"]); + parent = skeletonData.FindBone((string)boneMap["parent"]); if (parent == null) throw new Exception("Parent bone not found: " + boneMap["parent"]); } - var data = new BoneData(skeletonData.Bones.Count, (String)boneMap["name"], parent); + var data = new BoneData(skeletonData.Bones.Count, (string)boneMap["name"], parent); data.length = GetFloat(boneMap, "length", 0) * scale; data.x = GetFloat(boneMap, "x", 0) * scale; data.y = GetFloat(boneMap, "y", 0) * scale; @@ -132,15 +132,15 @@ namespace Spine { // Slots. if (root.ContainsKey("slots")) { - foreach (Dictionary slotMap in (List)root["slots"]) { - var slotName = (String)slotMap["name"]; - var boneName = (String)slotMap["bone"]; + foreach (Dictionary slotMap in (List)root["slots"]) { + var slotName = (string)slotMap["name"]; + var boneName = (string)slotMap["bone"]; BoneData boneData = skeletonData.FindBone(boneName); if (boneData == null) throw new Exception("Slot bone not found: " + boneName); var data = new SlotData(skeletonData.Slots.Count, slotName, boneData); if (slotMap.ContainsKey("color")) { - var color = (String)slotMap["color"]; + string color = (string)slotMap["color"]; data.r = ToColor(color, 0); data.g = ToColor(color, 1); data.b = ToColor(color, 2); @@ -148,7 +148,7 @@ namespace Spine { } if (slotMap.ContainsKey("dark")) { - var color2 = (String)slotMap["dark"]; + var color2 = (string)slotMap["dark"]; data.r2 = ToColor(color2, 0, 6); // expectedLength = 6. ie. "RRGGBB" data.g2 = ToColor(color2, 1, 6); data.b2 = ToColor(color2, 2, 6); @@ -157,7 +157,7 @@ namespace Spine { data.attachmentName = GetString(slotMap, "attachment", null); if (slotMap.ContainsKey("blend")) - data.blendMode = (BlendMode)Enum.Parse(typeof(BlendMode), (String)slotMap["blend"], true); + data.blendMode = (BlendMode)Enum.Parse(typeof(BlendMode), (string)slotMap["blend"], true); else data.blendMode = BlendMode.Normal; skeletonData.slots.Add(data); @@ -166,17 +166,17 @@ namespace Spine { // IK constraints. if (root.ContainsKey("ik")) { - foreach (Dictionary constraintMap in (List)root["ik"]) { - IkConstraintData data = new IkConstraintData((String)constraintMap["name"]); + foreach (Dictionary constraintMap in (List)root["ik"]) { + IkConstraintData data = new IkConstraintData((string)constraintMap["name"]); data.order = GetInt(constraintMap, "order", 0); - foreach (String boneName in (List)constraintMap["bones"]) { + foreach (string boneName in (List)constraintMap["bones"]) { BoneData bone = skeletonData.FindBone(boneName); if (bone == null) throw new Exception("IK constraint bone not found: " + boneName); data.bones.Add(bone); } - - String targetName = (String)constraintMap["target"]; + + string targetName = (string)constraintMap["target"]; data.target = skeletonData.FindBone(targetName); if (data.target == null) throw new Exception("Target bone not found: " + targetName); @@ -189,17 +189,17 @@ namespace Spine { // Transform constraints. if (root.ContainsKey("transform")) { - foreach (Dictionary constraintMap in (List)root["transform"]) { - TransformConstraintData data = new TransformConstraintData((String)constraintMap["name"]); + foreach (Dictionary constraintMap in (List)root["transform"]) { + TransformConstraintData data = new TransformConstraintData((string)constraintMap["name"]); data.order = GetInt(constraintMap, "order", 0); - foreach (String boneName in (List)constraintMap["bones"]) { + foreach (string boneName in (List)constraintMap["bones"]) { BoneData bone = skeletonData.FindBone(boneName); if (bone == null) throw new Exception("Transform constraint bone not found: " + boneName); data.bones.Add(bone); } - String targetName = (String)constraintMap["target"]; + string targetName = (string)constraintMap["target"]; data.target = skeletonData.FindBone(targetName); if (data.target == null) throw new Exception("Target bone not found: " + targetName); @@ -224,17 +224,17 @@ namespace Spine { // Path constraints. if(root.ContainsKey("path")) { - foreach (Dictionary constraintMap in (List)root["path"]) { - PathConstraintData data = new PathConstraintData((String)constraintMap["name"]); + foreach (Dictionary constraintMap in (List)root["path"]) { + PathConstraintData data = new PathConstraintData((string)constraintMap["name"]); data.order = GetInt(constraintMap, "order", 0); - foreach (String boneName in (List)constraintMap["bones"]) { + foreach (string boneName in (List)constraintMap["bones"]) { BoneData bone = skeletonData.FindBone(boneName); if (bone == null) throw new Exception("Path bone not found: " + boneName); data.bones.Add(bone); } - String targetName = (String)constraintMap["target"]; + string targetName = (string)constraintMap["target"]; data.target = skeletonData.FindSlot(targetName); if (data.target == null) throw new Exception("Target slot not found: " + targetName); @@ -255,13 +255,13 @@ namespace Spine { // Skins. if (root.ContainsKey("skins")) { - foreach (KeyValuePair skinMap in (Dictionary)root["skins"]) { + foreach (KeyValuePair skinMap in (Dictionary)root["skins"]) { var skin = new Skin(skinMap.Key); - foreach (KeyValuePair slotEntry in (Dictionary)skinMap.Value) { + foreach (KeyValuePair slotEntry in (Dictionary)skinMap.Value) { int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key); - foreach (KeyValuePair entry in ((Dictionary)slotEntry.Value)) { + foreach (KeyValuePair entry in ((Dictionary)slotEntry.Value)) { try { - Attachment attachment = ReadAttachment((Dictionary)entry.Value, skin, slotIndex, entry.Key, skeletonData); + Attachment attachment = ReadAttachment((Dictionary)entry.Value, skin, slotIndex, entry.Key, skeletonData); if (attachment != null) skin.AddAttachment(slotIndex, entry.Key, attachment); } catch (Exception e) { throw new Exception("Error reading attachment: " + entry.Key + ", skin: " + skin, e); @@ -287,8 +287,8 @@ namespace Spine { // Events. if (root.ContainsKey("events")) { - foreach (KeyValuePair entry in (Dictionary)root["events"]) { - var entryMap = (Dictionary)entry.Value; + foreach (KeyValuePair entry in (Dictionary)root["events"]) { + var entryMap = (Dictionary)entry.Value; var data = new EventData(entry.Key); data.Int = GetInt(entryMap, "int", 0); data.Float = GetFloat(entryMap, "float", 0); @@ -299,9 +299,9 @@ namespace Spine { // Animations. if (root.ContainsKey("animations")) { - foreach (KeyValuePair entry in (Dictionary)root["animations"]) { + foreach (KeyValuePair entry in (Dictionary)root["animations"]) { try { - ReadAnimation((Dictionary)entry.Value, entry.Key, skeletonData); + ReadAnimation((Dictionary)entry.Value, entry.Key, skeletonData); } catch (Exception e) { throw new Exception("Error reading animation: " + entry.Key, e); } @@ -317,8 +317,8 @@ namespace Spine { return skeletonData; } - private Attachment ReadAttachment (Dictionary map, Skin skin, int slotIndex, String name, SkeletonData skeletonData) { - var scale = this.Scale; + private Attachment ReadAttachment (Dictionary map, Skin skin, int slotIndex, string name, SkeletonData skeletonData) { + float scale = this.Scale; name = GetString(map, "name", name); var typeName = GetString(map, "type", "region"); @@ -327,7 +327,7 @@ namespace Spine { if (typeName == "weightedlinkedmesh") typeName = "linkedmesh"; var type = (AttachmentType)Enum.Parse(typeof(AttachmentType), typeName, true); - String path = GetString(map, "path", name); + string path = GetString(map, "path", name); switch (type) { case AttachmentType.Region: @@ -341,10 +341,9 @@ namespace Spine { region.rotation = GetFloat(map, "rotation", 0); region.width = GetFloat(map, "width", 32) * scale; region.height = GetFloat(map, "height", 32) * scale; - region.UpdateOffset(); if (map.ContainsKey("color")) { - var color = (String)map["color"]; + var color = (string)map["color"]; region.r = ToColor(color, 0); region.g = ToColor(color, 1); region.b = ToColor(color, 2); @@ -365,7 +364,7 @@ namespace Spine { mesh.Path = path; if (map.ContainsKey("color")) { - var color = (String)map["color"]; + var color = (string)map["color"]; mesh.r = ToColor(color, 0); mesh.g = ToColor(color, 1); mesh.b = ToColor(color, 2); @@ -375,7 +374,7 @@ namespace Spine { mesh.Width = GetFloat(map, "width", 0) * scale; mesh.Height = GetFloat(map, "height", 0) * scale; - String parent = GetString(map, "parent", null); + string parent = GetString(map, "parent", null); if (parent != null) { mesh.InheritDeform = GetBoolean(map, "deform", true); linkedMeshes.Add(new LinkedMesh(mesh, GetString(map, "skin", null), slotIndex, parent)); @@ -437,7 +436,7 @@ namespace Spine { return null; } - private void ReadVertices (Dictionary map, VertexAttachment attachment, int verticesLength) { + private void ReadVertices (Dictionary map, VertexAttachment attachment, int verticesLength) { attachment.WorldVerticesLength = verticesLength; float[] vertices = GetFloatArray(map, "vertices", 1); float scale = Scale; @@ -466,28 +465,28 @@ namespace Spine { attachment.vertices = weights.ToArray(); } - private void ReadAnimation (Dictionary map, String name, SkeletonData skeletonData) { + private void ReadAnimation (Dictionary map, string name, SkeletonData skeletonData) { var scale = this.Scale; var timelines = new ExposedList(); float duration = 0; // Slot timelines. if (map.ContainsKey("slots")) { - foreach (KeyValuePair entry in (Dictionary)map["slots"]) { - String slotName = entry.Key; + foreach (KeyValuePair entry in (Dictionary)map["slots"]) { + string slotName = entry.Key; int slotIndex = skeletonData.FindSlotIndex(slotName); - var timelineMap = (Dictionary)entry.Value; - foreach (KeyValuePair timelineEntry in timelineMap) { + var timelineMap = (Dictionary)entry.Value; + foreach (KeyValuePair timelineEntry in timelineMap) { var values = (List)timelineEntry.Value; - var timelineName = (String)timelineEntry.Key; + var timelineName = (string)timelineEntry.Key; if (timelineName == "attachment") { var timeline = new AttachmentTimeline(values.Count); timeline.slotIndex = slotIndex; int frameIndex = 0; - foreach (Dictionary valueMap in values) { + foreach (Dictionary valueMap in values) { float time = (float)valueMap["time"]; - timeline.SetFrame(frameIndex++, time, (String)valueMap["name"]); + timeline.SetFrame(frameIndex++, time, (string)valueMap["name"]); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]); @@ -532,20 +531,20 @@ namespace Spine { // Bone timelines. if (map.ContainsKey("bones")) { - foreach (KeyValuePair entry in (Dictionary)map["bones"]) { - String boneName = entry.Key; + foreach (KeyValuePair entry in (Dictionary)map["bones"]) { + string boneName = entry.Key; int boneIndex = skeletonData.FindBoneIndex(boneName); if (boneIndex == -1) throw new Exception("Bone not found: " + boneName); - var timelineMap = (Dictionary)entry.Value; - foreach (KeyValuePair timelineEntry in timelineMap) { + var timelineMap = (Dictionary)entry.Value; + foreach (KeyValuePair timelineEntry in timelineMap) { var values = (List)timelineEntry.Value; - var timelineName = (String)timelineEntry.Key; + var timelineName = (string)timelineEntry.Key; if (timelineName == "rotate") { var timeline = new RotateTimeline(values.Count); timeline.boneIndex = boneIndex; int frameIndex = 0; - foreach (Dictionary valueMap in values) { + foreach (Dictionary valueMap in values) { timeline.SetFrame(frameIndex, (float)valueMap["time"], (float)valueMap["angle"]); ReadCurve(valueMap, timeline, frameIndex); frameIndex++; @@ -567,7 +566,7 @@ namespace Spine { timeline.boneIndex = boneIndex; int frameIndex = 0; - foreach (Dictionary valueMap in values) { + foreach (Dictionary valueMap in values) { float time = (float)valueMap["time"]; float x = GetFloat(valueMap, "x", 0); float y = GetFloat(valueMap, "y", 0); @@ -586,13 +585,13 @@ namespace Spine { // IK constraint timelines. if (map.ContainsKey("ik")) { - foreach (KeyValuePair constraintMap in (Dictionary)map["ik"]) { + foreach (KeyValuePair constraintMap in (Dictionary)map["ik"]) { IkConstraintData constraint = skeletonData.FindIkConstraint(constraintMap.Key); var values = (List)constraintMap.Value; var timeline = new IkConstraintTimeline(values.Count); timeline.ikConstraintIndex = skeletonData.ikConstraints.IndexOf(constraint); int frameIndex = 0; - foreach (Dictionary valueMap in values) { + foreach (Dictionary valueMap in values) { float time = (float)valueMap["time"]; float mix = GetFloat(valueMap, "mix", 1); bool bendPositive = GetBoolean(valueMap, "bendPositive", true); @@ -607,13 +606,13 @@ namespace Spine { // Transform constraint timelines. if (map.ContainsKey("transform")) { - foreach (KeyValuePair constraintMap in (Dictionary)map["transform"]) { + foreach (KeyValuePair constraintMap in (Dictionary)map["transform"]) { TransformConstraintData constraint = skeletonData.FindTransformConstraint(constraintMap.Key); var values = (List)constraintMap.Value; var timeline = new TransformConstraintTimeline(values.Count); timeline.transformConstraintIndex = skeletonData.transformConstraints.IndexOf(constraint); int frameIndex = 0; - foreach (Dictionary valueMap in values) { + foreach (Dictionary valueMap in values) { float time = (float)valueMap["time"]; float rotateMix = GetFloat(valueMap, "rotateMix", 1); float translateMix = GetFloat(valueMap, "translateMix", 1); @@ -630,14 +629,14 @@ namespace Spine { // Path constraint timelines. if (map.ContainsKey("paths")) { - foreach (KeyValuePair constraintMap in (Dictionary)map["paths"]) { + foreach (KeyValuePair constraintMap in (Dictionary)map["paths"]) { int index = skeletonData.FindPathConstraintIndex(constraintMap.Key); if (index == -1) throw new Exception("Path constraint not found: " + constraintMap.Key); PathConstraintData data = skeletonData.pathConstraints.Items[index]; - var timelineMap = (Dictionary)constraintMap.Value; - foreach (KeyValuePair timelineEntry in timelineMap) { + var timelineMap = (Dictionary)constraintMap.Value; + foreach (KeyValuePair timelineEntry in timelineMap) { var values = (List)timelineEntry.Value; - var timelineName = (String)timelineEntry.Key; + var timelineName = (string)timelineEntry.Key; if (timelineName == "position" || timelineName == "spacing") { PathConstraintPositionTimeline timeline; float timelineScale = 1; @@ -651,7 +650,7 @@ namespace Spine { } timeline.pathConstraintIndex = index; int frameIndex = 0; - foreach (Dictionary valueMap in values) { + foreach (Dictionary valueMap in values) { timeline.SetFrame(frameIndex, (float)valueMap["time"], GetFloat(valueMap, timelineName, 0) * timelineScale); ReadCurve(valueMap, timeline, frameIndex); frameIndex++; @@ -663,7 +662,7 @@ namespace Spine { PathConstraintMixTimeline timeline = new PathConstraintMixTimeline(values.Count); timeline.pathConstraintIndex = index; int frameIndex = 0; - foreach (Dictionary valueMap in values) { + foreach (Dictionary valueMap in values) { timeline.SetFrame(frameIndex, (float)valueMap["time"], GetFloat(valueMap, "rotateMix", 1), GetFloat(valueMap, "translateMix", 1)); ReadCurve(valueMap, timeline, frameIndex); frameIndex++; @@ -677,12 +676,12 @@ namespace Spine { // Deform timelines. if (map.ContainsKey("deform")) { - foreach (KeyValuePair deformMap in (Dictionary)map["deform"]) { + foreach (KeyValuePair deformMap in (Dictionary)map["deform"]) { Skin skin = skeletonData.FindSkin(deformMap.Key); - foreach (KeyValuePair slotMap in (Dictionary)deformMap.Value) { + foreach (KeyValuePair slotMap in (Dictionary)deformMap.Value) { int slotIndex = skeletonData.FindSlotIndex(slotMap.Key); if (slotIndex == -1) throw new Exception("Slot not found: " + slotMap.Key); - foreach (KeyValuePair timelineMap in (Dictionary)slotMap.Value) { + foreach (KeyValuePair timelineMap in (Dictionary)slotMap.Value) { var values = (List)timelineMap.Value; VertexAttachment attachment = (VertexAttachment)skin.GetAttachment(slotIndex, timelineMap.Key); if (attachment == null) throw new Exception("Deform attachment not found: " + timelineMap.Key); @@ -695,7 +694,7 @@ namespace Spine { timeline.attachment = attachment; int frameIndex = 0; - foreach (Dictionary valueMap in values) { + foreach (Dictionary valueMap in values) { float[] deform; if (!valueMap.ContainsKey("vertices")) { deform = weighted ? new float[deformLength] : vertices; @@ -732,7 +731,7 @@ namespace Spine { var timeline = new DrawOrderTimeline(values.Count); int slotCount = skeletonData.slots.Count; int frameIndex = 0; - foreach (Dictionary drawOrderMap in values) { + foreach (Dictionary drawOrderMap in values) { int[] drawOrder = null; if (drawOrderMap.ContainsKey("offsets")) { drawOrder = new int[slotCount]; @@ -741,8 +740,8 @@ namespace Spine { var offsets = (List)drawOrderMap["offsets"]; int[] unchanged = new int[slotCount - offsets.Count]; int originalIndex = 0, unchangedIndex = 0; - foreach (Dictionary offsetMap in offsets) { - int slotIndex = skeletonData.FindSlotIndex((String)offsetMap["slot"]); + foreach (Dictionary offsetMap in offsets) { + int slotIndex = skeletonData.FindSlotIndex((string)offsetMap["slot"]); if (slotIndex == -1) throw new Exception("Slot not found: " + offsetMap["slot"]); // Collect unchanged items. while (originalIndex != slotIndex) @@ -769,8 +768,8 @@ namespace Spine { var eventsMap = (List)map["events"]; var timeline = new EventTimeline(eventsMap.Count); int frameIndex = 0; - foreach (Dictionary eventMap in eventsMap) { - EventData eventData = skeletonData.FindEvent((String)eventMap["name"]); + foreach (Dictionary eventMap in eventsMap) { + EventData eventData = skeletonData.FindEvent((string)eventMap["name"]); if (eventData == null) throw new Exception("Event not found: " + eventMap["name"]); var e = new Event((float)eventMap["time"], eventData); e.Int = GetInt(eventMap, "int", eventData.Int); @@ -786,7 +785,7 @@ namespace Spine { skeletonData.animations.Add(new Animation(name, timelines, duration)); } - static void ReadCurve (Dictionary valueMap, CurveTimeline timeline, int frameIndex) { + static void ReadCurve (Dictionary valueMap, CurveTimeline timeline, int frameIndex) { if (!valueMap.ContainsKey("curve")) return; Object curveObject = valueMap["curve"]; @@ -800,11 +799,11 @@ namespace Spine { } internal class LinkedMesh { - internal String parent, skin; + internal string parent, skin; internal int slotIndex; internal MeshAttachment mesh; - public LinkedMesh (MeshAttachment mesh, String skin, int slotIndex, String parent) { + public LinkedMesh (MeshAttachment mesh, string skin, int slotIndex, string parent) { this.mesh = mesh; this.skin = skin; this.slotIndex = slotIndex; @@ -812,7 +811,7 @@ namespace Spine { } } - static float[] GetFloatArray(Dictionary map, String name, float scale) { + static float[] GetFloatArray(Dictionary map, string name, float scale) { var list = (List)map[name]; var values = new float[list.Count]; if (scale == 1) { @@ -825,7 +824,7 @@ namespace Spine { return values; } - static int[] GetIntArray(Dictionary map, String name) { + static int[] GetIntArray(Dictionary map, string name) { var list = (List)map[name]; var values = new int[list.Count]; for (int i = 0, n = list.Count; i < n; i++) @@ -833,31 +832,31 @@ namespace Spine { return values; } - static float GetFloat(Dictionary map, String name, float defaultValue) { + static float GetFloat(Dictionary map, string name, float defaultValue) { if (!map.ContainsKey(name)) return defaultValue; return (float)map[name]; } - static int GetInt(Dictionary map, String name, int defaultValue) { + static int GetInt(Dictionary map, string name, int defaultValue) { if (!map.ContainsKey(name)) return defaultValue; return (int)(float)map[name]; } - static bool GetBoolean(Dictionary map, String name, bool defaultValue) { + static bool GetBoolean(Dictionary map, string name, bool defaultValue) { if (!map.ContainsKey(name)) return defaultValue; return (bool)map[name]; } - static String GetString(Dictionary map, String name, String defaultValue) { + static string GetString(Dictionary map, string name, string defaultValue) { if (!map.ContainsKey(name)) return defaultValue; - return (String)map[name]; + return (string)map[name]; } - static float ToColor(String hexString, int colorIndex, int expectedLength = 8) { + static float ToColor(string hexString, int colorIndex, int expectedLength = 8) { if (hexString.Length != expectedLength) throw new ArgumentException("Color hexidecimal length must be " + expectedLength + ", recieved: " + hexString, "hexString"); return Convert.ToInt32(hexString.Substring(colorIndex * 2, 2), 16) / (float)255; diff --git a/spine-csharp/src/Skin.cs b/spine-csharp/src/Skin.cs index 4ac70c80f..4bb94d998 100644 --- a/spine-csharp/src/Skin.cs +++ b/spine-csharp/src/Skin.cs @@ -114,7 +114,7 @@ namespace Spine { internal static readonly AttachmentKeyTupleComparer Instance = new AttachmentKeyTupleComparer(); bool IEqualityComparer.Equals (AttachmentKeyTuple o1, AttachmentKeyTuple o2) { - return o1.slotIndex == o2.slotIndex && o1.nameHashCode == o2.nameHashCode && o1.name == o2.name; + return o1.slotIndex == o2.slotIndex && o1.nameHashCode == o2.nameHashCode && string.Equals(o1.name, o2.name, StringComparison.Ordinal); } int IEqualityComparer.GetHashCode (AttachmentKeyTuple o) { From 2345764fbf56559352b54d34b70c417104e4bc35 Mon Sep 17 00:00:00 2001 From: pharan Date: Thu, 8 Mar 2018 22:40:00 +0800 Subject: [PATCH 10/12] [csharp] Port RegionAttachment.java checking for compatible region values. --- .../src/Attachments/RegionAttachment.cs | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/spine-csharp/src/Attachments/RegionAttachment.cs b/spine-csharp/src/Attachments/RegionAttachment.cs index cb477d901..248fe0157 100644 --- a/spine-csharp/src/Attachments/RegionAttachment.cs +++ b/spine-csharp/src/Attachments/RegionAttachment.cs @@ -79,14 +79,22 @@ namespace Spine { public void UpdateOffset () { float width = this.width; float height = this.height; + float localX2 = width * 0.5f; + float localY2 = height * 0.5f; + float localX = -localX2; + float localY = -localY2; + if (regionOriginalWidth != 0) { // if (region != null) + localX += regionOffsetX / regionOriginalWidth * width; + localY += regionOffsetY / regionOriginalHeight * height; + localX2 -= (regionOriginalWidth - regionOffsetX - regionWidth) / regionOriginalWidth * width; + localY2 -= (regionOriginalHeight - regionOffsetY - regionHeight) / regionOriginalHeight * height; + } float scaleX = this.scaleX; float scaleY = this.scaleY; - float regionScaleX = width / regionOriginalWidth * scaleX; - float regionScaleY = height / regionOriginalHeight * scaleY; - float localX = -width / 2 * scaleX + regionOffsetX * regionScaleX; - float localY = -height / 2 * scaleY + regionOffsetY * regionScaleY; - float localX2 = localX + regionWidth * regionScaleX; - float localY2 = localY + regionHeight * regionScaleY; + localX *= scaleX; + localY *= scaleY; + localX2 *= scaleX; + localY2 *= scaleY; float rotation = this.rotation; float cos = MathUtils.CosDeg(rotation); float sin = MathUtils.SinDeg(rotation); From 578b9e3660db67e6c71519bca6f9f5a95fcd5cd7 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 13 Mar 2018 00:09:54 +0800 Subject: [PATCH 11/12] [unity] Handle Unity2017.3 patch Color32 attrib. --- spine-unity/Assets/spine-unity/Mesh Generation/SpineMesh.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spine-unity/Assets/spine-unity/Mesh Generation/SpineMesh.cs b/spine-unity/Assets/spine-unity/Mesh Generation/SpineMesh.cs index 40be3a896..c4b3793c8 100644 --- a/spine-unity/Assets/spine-unity/Mesh Generation/SpineMesh.cs +++ b/spine-unity/Assets/spine-unity/Mesh Generation/SpineMesh.cs @@ -467,7 +467,7 @@ namespace Spine.Unity { var skeleton = instruction.skeleton; var drawOrderItems = skeleton.drawOrder.Items; - Color32 color = default(Color32); + Color32 color = new Color32(); //Color32 color = default(Color32); float skeletonA = skeleton.a * 255, skeletonR = skeleton.r, skeletonG = skeleton.g, skeletonB = skeleton.b; Vector2 meshBoundsMin = this.meshBoundsMin, meshBoundsMax = this.meshBoundsMax; @@ -677,7 +677,7 @@ namespace Spine.Unity { } // Populate Verts - Color32 color = default(Color32); + Color32 color = new Color32(); //Color32 color = default(Color32); int vertexIndex = 0; var tempVerts = this.tempVerts; From 9e3c31839d4770d36ab5f0c94203ca3d666e3772 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 13 Mar 2018 00:37:39 +0800 Subject: [PATCH 12/12] [unity] Revert ctor use to default(T). --- spine-unity/Assets/spine-unity/Mesh Generation/SpineMesh.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spine-unity/Assets/spine-unity/Mesh Generation/SpineMesh.cs b/spine-unity/Assets/spine-unity/Mesh Generation/SpineMesh.cs index c4b3793c8..40be3a896 100644 --- a/spine-unity/Assets/spine-unity/Mesh Generation/SpineMesh.cs +++ b/spine-unity/Assets/spine-unity/Mesh Generation/SpineMesh.cs @@ -467,7 +467,7 @@ namespace Spine.Unity { var skeleton = instruction.skeleton; var drawOrderItems = skeleton.drawOrder.Items; - Color32 color = new Color32(); //Color32 color = default(Color32); + Color32 color = default(Color32); float skeletonA = skeleton.a * 255, skeletonR = skeleton.r, skeletonG = skeleton.g, skeletonB = skeleton.b; Vector2 meshBoundsMin = this.meshBoundsMin, meshBoundsMax = this.meshBoundsMax; @@ -677,7 +677,7 @@ namespace Spine.Unity { } // Populate Verts - Color32 color = new Color32(); //Color32 color = default(Color32); + Color32 color = default(Color32); int vertexIndex = 0; var tempVerts = this.tempVerts;