备份CatanBuilding瘦身独立工程
This commit is contained in:
@@ -0,0 +1,813 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
#if UNITY_2019_3_OR_NEWER
|
||||
#define CONFIGURABLE_ENTER_PLAY_MODE
|
||||
#endif
|
||||
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
|
||||
namespace Spine.Unity.AttachmentTools {
|
||||
|
||||
public static class AtlasUtilities {
|
||||
internal const TextureFormat SpineTextureFormat = TextureFormat.RGBA32;
|
||||
internal const float DefaultMipmapBias = -0.5f;
|
||||
internal const bool UseMipMaps = false;
|
||||
internal const float DefaultScale = 0.01f;
|
||||
|
||||
const int NonrenderingRegion = -1;
|
||||
|
||||
#if CONFIGURABLE_ENTER_PLAY_MODE
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
||||
static void Init () {
|
||||
// handle disabled domain reload
|
||||
AtlasUtilities.ClearCache();
|
||||
}
|
||||
#endif
|
||||
|
||||
public static AtlasRegion ToAtlasRegion (this Texture2D t, Material materialPropertySource, float scale = DefaultScale) {
|
||||
return t.ToAtlasRegion(materialPropertySource.shader, scale, materialPropertySource);
|
||||
}
|
||||
|
||||
public static AtlasRegion ToAtlasRegion (this Texture2D t, Shader shader, float scale = DefaultScale, Material materialPropertySource = null) {
|
||||
Material material = new Material(shader);
|
||||
if (materialPropertySource != null) {
|
||||
material.CopyPropertiesFromMaterial(materialPropertySource);
|
||||
material.shaderKeywords = materialPropertySource.shaderKeywords;
|
||||
}
|
||||
|
||||
material.mainTexture = t;
|
||||
AtlasPage page = material.ToSpineAtlasPage();
|
||||
|
||||
float width = t.width;
|
||||
float height = t.height;
|
||||
|
||||
AtlasRegion region = new AtlasRegion();
|
||||
region.name = t.name;
|
||||
|
||||
// World space units
|
||||
Vector2 boundsMin = Vector2.zero, boundsMax = new Vector2(width, height) * scale;
|
||||
|
||||
// Texture space/pixel units
|
||||
region.width = (int)width;
|
||||
region.originalWidth = (int)width;
|
||||
region.height = (int)height;
|
||||
region.originalHeight = (int)height;
|
||||
region.offsetX = width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0));
|
||||
region.offsetY = height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0));
|
||||
|
||||
// Use the full area of the texture.
|
||||
region.u = 0;
|
||||
region.v = 1;
|
||||
region.u2 = 1;
|
||||
region.v2 = 0;
|
||||
region.x = 0;
|
||||
region.y = 0;
|
||||
|
||||
region.page = page;
|
||||
|
||||
return region;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
|
||||
public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) {
|
||||
return t.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
|
||||
public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) {
|
||||
Material material = new Material(shader);
|
||||
if (materialPropertySource != null) {
|
||||
material.CopyPropertiesFromMaterial(materialPropertySource);
|
||||
material.shaderKeywords = materialPropertySource.shaderKeywords;
|
||||
}
|
||||
Texture2D newTexture = t.GetClone(textureFormat, mipmaps, applyPMA: true);
|
||||
|
||||
newTexture.name = t.name + "-pma-";
|
||||
material.name = t.name + shader.name;
|
||||
|
||||
material.mainTexture = newTexture;
|
||||
AtlasPage page = material.ToSpineAtlasPage();
|
||||
|
||||
AtlasRegion region = newTexture.ToAtlasRegion(shader);
|
||||
region.page = page;
|
||||
|
||||
return region;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new Spine.AtlasPage from a UnityEngine.Material. If the material has a preassigned texture, the page width and height will be set.</summary>
|
||||
public static AtlasPage ToSpineAtlasPage (this Material m) {
|
||||
AtlasPage newPage = new AtlasPage {
|
||||
rendererObject = m,
|
||||
name = m.name
|
||||
};
|
||||
|
||||
Texture t = m.mainTexture;
|
||||
if (t != null) {
|
||||
newPage.width = t.width;
|
||||
newPage.height = t.height;
|
||||
}
|
||||
|
||||
return newPage;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion from a UnityEngine.Sprite.</summary>
|
||||
public static AtlasRegion ToAtlasRegion (this Sprite s, AtlasPage page) {
|
||||
if (page == null) throw new System.ArgumentNullException("page", "page cannot be null. AtlasPage determines which texture region belongs and how it should be rendered. You can use material.ToSpineAtlasPage() to get a shareable AtlasPage from a Material, or use the sprite.ToAtlasRegion(material) overload.");
|
||||
AtlasRegion region = s.ToAtlasRegion();
|
||||
region.page = page;
|
||||
return region;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion from a UnityEngine.Sprite. This creates a new AtlasPage object for every AtlasRegion you create. You can centralize Material control by creating a shared atlas page using Material.ToSpineAtlasPage and using the sprite.ToAtlasRegion(AtlasPage) overload.</summary>
|
||||
public static AtlasRegion ToAtlasRegion (this Sprite s, Material material) {
|
||||
AtlasRegion region = s.ToAtlasRegion();
|
||||
region.page = material.ToSpineAtlasPage();
|
||||
return region;
|
||||
}
|
||||
|
||||
public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) {
|
||||
return s.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
|
||||
public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) {
|
||||
Material material = new Material(shader);
|
||||
if (materialPropertySource != null) {
|
||||
material.CopyPropertiesFromMaterial(materialPropertySource);
|
||||
material.shaderKeywords = materialPropertySource.shaderKeywords;
|
||||
}
|
||||
|
||||
Texture2D tex = s.ToTexture(textureFormat, mipmaps, applyPMA: true);
|
||||
tex.name = s.name + "-pma-";
|
||||
material.name = tex.name + shader.name;
|
||||
|
||||
material.mainTexture = tex;
|
||||
AtlasPage page = material.ToSpineAtlasPage();
|
||||
|
||||
AtlasRegion region = s.ToAtlasRegion(true);
|
||||
region.page = page;
|
||||
|
||||
return region;
|
||||
}
|
||||
|
||||
internal static AtlasRegion ToAtlasRegion (this Sprite s, bool isolatedTexture = false) {
|
||||
AtlasRegion region = new AtlasRegion();
|
||||
region.name = s.name;
|
||||
region.index = -1;
|
||||
region.degrees = s.packed && s.packingRotation != SpritePackingRotation.None ? 90 : 0;
|
||||
|
||||
// World space units
|
||||
Bounds bounds = s.bounds;
|
||||
Vector2 boundsMin = bounds.min, boundsMax = bounds.max;
|
||||
|
||||
// Texture space/pixel units
|
||||
Rect spineRect = s.textureRect.SpineUnityFlipRect(s.texture.height);
|
||||
Rect originalRect = s.rect;
|
||||
region.width = (int)spineRect.width;
|
||||
region.originalWidth = (int)originalRect.width;
|
||||
region.height = (int)spineRect.height;
|
||||
region.originalHeight = (int)originalRect.height;
|
||||
region.offsetX = s.textureRectOffset.x + spineRect.width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0));
|
||||
region.offsetY = s.textureRectOffset.y + spineRect.height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0));
|
||||
|
||||
if (isolatedTexture) {
|
||||
region.u = 0;
|
||||
region.v = 1;
|
||||
region.u2 = 1;
|
||||
region.v2 = 0;
|
||||
region.x = 0;
|
||||
region.y = 0;
|
||||
} else {
|
||||
Texture2D tex = s.texture;
|
||||
Rect uvRect = TextureRectToUVRect(s.textureRect, tex.width, tex.height);
|
||||
region.u = uvRect.xMin;
|
||||
region.v = uvRect.yMax;
|
||||
region.u2 = uvRect.xMax;
|
||||
region.v2 = uvRect.yMin;
|
||||
region.x = (int)spineRect.x;
|
||||
region.y = (int)spineRect.y;
|
||||
}
|
||||
|
||||
return region;
|
||||
}
|
||||
|
||||
#region Runtime Repacking
|
||||
static readonly Dictionary<AtlasRegion, int> existingRegions = new Dictionary<AtlasRegion, int>();
|
||||
static readonly List<int> regionIndices = new List<int>();
|
||||
static readonly List<AtlasRegion> originalRegions = new List<AtlasRegion>();
|
||||
static readonly List<AtlasRegion> repackedRegions = new List<AtlasRegion>();
|
||||
static List<Texture2D>[] texturesToPackAtParam = new List<Texture2D>[1];
|
||||
static List<Attachment> inoutAttachments = new List<Attachment>();
|
||||
|
||||
/// <summary>
|
||||
/// Fills the outputAttachments list with new attachment objects based on the attachments in sourceAttachments,
|
||||
/// but mapped to a new single texture using the same material.</summary>
|
||||
/// <remarks>Returned <c>Material</c> and <c>Texture</c> behave like <c>new Texture2D()</c>, thus you need to call <c>Destroy()</c>
|
||||
/// to free resources.
|
||||
/// This method caches necessary Texture copies for later re-use, which might steadily increase the texture memory
|
||||
/// footprint when used excessively. Set <paramref name="clearCache"/> to <c>true</c>
|
||||
/// or call <see cref="AtlasUtilities.ClearCache()"/> to clear this texture cache.
|
||||
/// You may want to call <c>Resources.UnloadUnusedAssets()</c> after that.
|
||||
/// </remarks>
|
||||
/// <param name="sourceAttachments">The list of attachments to be repacked.</param>
|
||||
/// <param name = "outputAttachments">The List(Attachment) to populate with the newly created Attachment objects.
|
||||
/// May be equal to <c>sourceAttachments</c> for in-place operation.</param>
|
||||
/// <param name="materialPropertySource">May be null. If no Material property source is provided, a material with
|
||||
/// default parameters using the provided <c>shader</c> will be created.</param>
|
||||
/// <param name="clearCache">When set to <c>true</c>, <see cref="AtlasUtilities.ClearCache()"/> is called after
|
||||
/// repacking to clear the texture cache. See remarks for additional info.</param>
|
||||
/// <param name="additionalTexturePropertyIDsToCopy">Optional additional textures (such as normal maps) to copy while repacking.
|
||||
/// To copy e.g. the main texture and normal maps, pass 'new int[] { Shader.PropertyToID("_BumpMap") }' at this parameter.</param>
|
||||
/// <param name="additionalOutputTextures">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be filled with the resulting repacked texture for every property,
|
||||
/// just as the main repacked texture is assigned to <c>outputTexture</c>.</param>
|
||||
/// <param name="additionalTextureFormats">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be used as <c>TextureFormat</c> at the Texture at the respective property.
|
||||
/// When <c>additionalTextureFormats</c> is <c>null</c> or when its array size is smaller,
|
||||
/// <c>textureFormat</c> is used where there exists no corresponding array item.</param>
|
||||
/// <param name="additionalTextureIsLinear">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be used to determine whether <c>linear</c> or <c>sRGB</c> color space is used at the
|
||||
/// Texture at the respective property. When <c>additionalTextureIsLinear</c> is <c>null</c>, <c>linear</c> color space
|
||||
/// is assumed at every additional Texture element.
|
||||
/// When e.g. packing the main texture and normal maps, pass 'new bool[] { true }' at this parameter, because normal maps use
|
||||
/// linear color space.</param>
|
||||
public static void GetRepackedAttachments (List<Attachment> sourceAttachments, List<Attachment> outputAttachments, Material materialPropertySource,
|
||||
out Material outputMaterial, out Texture2D outputTexture,
|
||||
int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
|
||||
string newAssetName = "Repacked Attachments", bool clearCache = false, bool useOriginalNonrenderables = true,
|
||||
int[] additionalTexturePropertyIDsToCopy = null, Texture2D[] additionalOutputTextures = null,
|
||||
TextureFormat[] additionalTextureFormats = null, bool[] additionalTextureIsLinear = null) {
|
||||
|
||||
Shader shader = materialPropertySource == null ? Shader.Find("Spine/Skeleton") : materialPropertySource.shader;
|
||||
GetRepackedAttachments(sourceAttachments, outputAttachments, shader, out outputMaterial, out outputTexture,
|
||||
maxAtlasSize, padding, textureFormat, mipmaps, newAssetName,
|
||||
materialPropertySource, clearCache, useOriginalNonrenderables,
|
||||
additionalTexturePropertyIDsToCopy, additionalOutputTextures,
|
||||
additionalTextureFormats, additionalTextureIsLinear);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fills the outputAttachments list with new attachment objects based on the attachments in sourceAttachments,
|
||||
/// but mapped to a new single texture using the same material.</summary>
|
||||
/// <remarks>Returned <c>Material</c> and <c>Texture</c> behave like <c>new Texture2D()</c>, thus you need to call <c>Destroy()</c>
|
||||
/// to free resources.</remarks>
|
||||
/// <param name="sourceAttachments">The list of attachments to be repacked.</param>
|
||||
/// <param name = "outputAttachments">The List(Attachment) to populate with the newly created Attachment objects.
|
||||
/// May be equal to <c>sourceAttachments</c> for in-place operation.</param>
|
||||
/// <param name="materialPropertySource">May be null. If no Material property source is provided, a material with
|
||||
/// default parameters using the provided <c>shader</c> will be created.</param>
|
||||
/// <param name="additionalTexturePropertyIDsToCopy">Optional additional textures (such as normal maps) to copy while repacking.
|
||||
/// To copy e.g. the main texture and normal maps, pass 'new int[] { Shader.PropertyToID("_BumpMap") }' at this parameter.</param>
|
||||
/// <param name="additionalOutputTextures">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be filled with the resulting repacked texture for every property,
|
||||
/// just as the main repacked texture is assigned to <c>outputTexture</c>.</param>
|
||||
/// <param name="additionalTextureFormats">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be used as <c>TextureFormat</c> at the Texture at the respective property.
|
||||
/// When <c>additionalTextureFormats</c> is <c>null</c> or when its array size is smaller,
|
||||
/// <c>textureFormat</c> is used where there exists no corresponding array item.</param>
|
||||
/// <param name="additionalTextureIsLinear">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be used to determine whether <c>linear</c> or <c>sRGB</c> color space is used at the
|
||||
/// Texture at the respective property. When <c>additionalTextureIsLinear</c> is <c>null</c>, <c>linear</c> color space
|
||||
/// is assumed at every additional Texture element.
|
||||
/// When e.g. packing the main texture and normal maps, pass 'new bool[] { true }' at this parameter, because normal maps use
|
||||
/// linear color space.</param>
|
||||
public static void GetRepackedAttachments (List<Attachment> sourceAttachments, List<Attachment> outputAttachments, Shader shader,
|
||||
out Material outputMaterial, out Texture2D outputTexture,
|
||||
int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
|
||||
string newAssetName = "Repacked Attachments",
|
||||
Material materialPropertySource = null, bool clearCache = false, bool useOriginalNonrenderables = true,
|
||||
int[] additionalTexturePropertyIDsToCopy = null, Texture2D[] additionalOutputTextures = null,
|
||||
TextureFormat[] additionalTextureFormats = null, bool[] additionalTextureIsLinear = null) {
|
||||
|
||||
if (sourceAttachments == null) throw new System.ArgumentNullException("sourceAttachments");
|
||||
if (outputAttachments == null) throw new System.ArgumentNullException("outputAttachments");
|
||||
outputTexture = null;
|
||||
if (additionalTexturePropertyIDsToCopy != null && additionalTextureIsLinear == null) {
|
||||
additionalTextureIsLinear = new bool[additionalTexturePropertyIDsToCopy.Length];
|
||||
for (int i = 0; i < additionalTextureIsLinear.Length; ++i) {
|
||||
additionalTextureIsLinear[i] = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Use these to detect and use shared regions.
|
||||
existingRegions.Clear();
|
||||
regionIndices.Clear();
|
||||
|
||||
// Collect all textures from original attachments.
|
||||
int numTextureParamsToRepack = 1 + (additionalTexturePropertyIDsToCopy == null ? 0 : additionalTexturePropertyIDsToCopy.Length);
|
||||
additionalOutputTextures = (additionalTexturePropertyIDsToCopy == null ? null : new Texture2D[additionalTexturePropertyIDsToCopy.Length]);
|
||||
if (texturesToPackAtParam.Length < numTextureParamsToRepack)
|
||||
Array.Resize(ref texturesToPackAtParam, numTextureParamsToRepack);
|
||||
for (int i = 0; i < numTextureParamsToRepack; ++i) {
|
||||
if (texturesToPackAtParam[i] != null)
|
||||
texturesToPackAtParam[i].Clear();
|
||||
else
|
||||
texturesToPackAtParam[i] = new List<Texture2D>();
|
||||
}
|
||||
originalRegions.Clear();
|
||||
|
||||
if (!object.ReferenceEquals(sourceAttachments, outputAttachments)) {
|
||||
outputAttachments.Clear();
|
||||
outputAttachments.AddRange(sourceAttachments);
|
||||
}
|
||||
|
||||
int newRegionIndex = 0;
|
||||
for (int attachmentIndex = 0, n = sourceAttachments.Count; attachmentIndex < n; attachmentIndex++) {
|
||||
Attachment originalAttachment = sourceAttachments[attachmentIndex];
|
||||
|
||||
if (originalAttachment is IHasTextureRegion) {
|
||||
MeshAttachment originalMeshAttachment = originalAttachment as MeshAttachment;
|
||||
Attachment newAttachment = (originalMeshAttachment != null) ? originalMeshAttachment.NewLinkedMesh() : originalAttachment.Copy();
|
||||
AtlasRegion region = ((IHasTextureRegion)newAttachment).Region as AtlasRegion;
|
||||
int existingIndex;
|
||||
if (existingRegions.TryGetValue(region, out existingIndex)) {
|
||||
regionIndices.Add(existingIndex);
|
||||
} else {
|
||||
originalRegions.Add(region);
|
||||
for (int i = 0; i < numTextureParamsToRepack; ++i) {
|
||||
Texture2D regionTexture = (i == 0 ?
|
||||
region.ToTexture(textureFormat, mipmaps) :
|
||||
region.ToTexture((additionalTextureFormats != null && i - 1 < additionalTextureFormats.Length) ?
|
||||
additionalTextureFormats[i - 1] : textureFormat,
|
||||
mipmaps, additionalTexturePropertyIDsToCopy[i - 1], additionalTextureIsLinear[i - 1]));
|
||||
texturesToPackAtParam[i].Add(regionTexture);
|
||||
}
|
||||
|
||||
existingRegions.Add(region, newRegionIndex);
|
||||
regionIndices.Add(newRegionIndex);
|
||||
newRegionIndex++;
|
||||
}
|
||||
|
||||
outputAttachments[attachmentIndex] = newAttachment;
|
||||
} else {
|
||||
outputAttachments[attachmentIndex] = useOriginalNonrenderables ? originalAttachment : originalAttachment.Copy();
|
||||
regionIndices.Add(NonrenderingRegion); // Output attachments pairs with regionIndices list 1:1. Pad with a sentinel if the attachment doesn't have a region.
|
||||
}
|
||||
}
|
||||
|
||||
// Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments
|
||||
Material newMaterial = new Material(shader);
|
||||
if (materialPropertySource != null) {
|
||||
newMaterial.CopyPropertiesFromMaterial(materialPropertySource);
|
||||
newMaterial.shaderKeywords = materialPropertySource.shaderKeywords;
|
||||
}
|
||||
newMaterial.name = newAssetName;
|
||||
|
||||
Rect[] rects = null;
|
||||
for (int i = 0; i < numTextureParamsToRepack; ++i) {
|
||||
// Fill a new texture with the collected attachment textures.
|
||||
Texture2D newTexture = new Texture2D(maxAtlasSize, maxAtlasSize,
|
||||
(i > 0 && additionalTextureFormats != null && i - 1 < additionalTextureFormats.Length) ?
|
||||
additionalTextureFormats[i - 1] : textureFormat,
|
||||
mipmaps,
|
||||
(i > 0) ? additionalTextureIsLinear[i - 1] : false);
|
||||
newTexture.mipMapBias = AtlasUtilities.DefaultMipmapBias;
|
||||
|
||||
List<Texture2D> texturesToPack = texturesToPackAtParam[i];
|
||||
if (texturesToPack.Count > 0) {
|
||||
Texture2D sourceTexture = texturesToPack[0];
|
||||
newTexture.CopyTextureAttributesFrom(sourceTexture);
|
||||
}
|
||||
newTexture.name = newAssetName;
|
||||
Rect[] rectsForTexParam = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize);
|
||||
if (i == 0) {
|
||||
rects = rectsForTexParam;
|
||||
newMaterial.mainTexture = newTexture;
|
||||
outputTexture = newTexture;
|
||||
} else {
|
||||
newMaterial.SetTexture(additionalTexturePropertyIDsToCopy[i - 1], newTexture);
|
||||
additionalOutputTextures[i - 1] = newTexture;
|
||||
}
|
||||
}
|
||||
|
||||
AtlasPage page = newMaterial.ToSpineAtlasPage();
|
||||
page.name = newAssetName;
|
||||
|
||||
repackedRegions.Clear();
|
||||
for (int i = 0, n = originalRegions.Count; i < n; i++) {
|
||||
AtlasRegion oldRegion = originalRegions[i];
|
||||
AtlasRegion newRegion = UVRectToAtlasRegion(rects[i], oldRegion, page);
|
||||
repackedRegions.Add(newRegion);
|
||||
}
|
||||
|
||||
// Map the cloned attachments to the repacked atlas.
|
||||
for (int i = 0, n = outputAttachments.Count; i < n; i++) {
|
||||
Attachment attachment = outputAttachments[i];
|
||||
IHasTextureRegion iHasRegion = attachment as IHasTextureRegion;
|
||||
if (iHasRegion != null) {
|
||||
iHasRegion.Region = repackedRegions[regionIndices[i]];
|
||||
iHasRegion.UpdateRegion();
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up.
|
||||
if (clearCache)
|
||||
AtlasUtilities.ClearCache();
|
||||
|
||||
outputMaterial = newMaterial;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas
|
||||
/// comprised of all the regions from the original skin.</summary>
|
||||
/// <remarks>GetRepackedSkin is an expensive operation, preferably call it at level load time.
|
||||
/// No Spine.Atlas object is created so there is no way to find AtlasRegions except through the Attachments using them.
|
||||
/// Returned <c>Material</c> and <c>Texture</c> behave like <c>new Texture2D()</c>, thus you need to call <c>Destroy()</c>
|
||||
/// to free resources.
|
||||
/// This method caches necessary Texture copies for later re-use, which might steadily increase the texture memory
|
||||
/// footprint when used excessively. Set <paramref name="clearCache"/> to <c>true</c>
|
||||
/// or call <see cref="AtlasUtilities.ClearCache()"/> to clear this texture cache.
|
||||
/// You may want to call <c>Resources.UnloadUnusedAssets()</c> after that.
|
||||
/// </remarks>
|
||||
/// <param name="clearCache">When set to <c>true</c>, <see cref="AtlasUtilities.ClearCache()"/> is called after
|
||||
/// repacking to clear the texture cache. See remarks for additional info.</param>
|
||||
/// <param name="additionalTexturePropertyIDsToCopy">Optional additional textures (such as normal maps) to copy while repacking.
|
||||
/// To copy e.g. the main texture and normal maps, pass 'new int[] { Shader.PropertyToID("_BumpMap") }' at this parameter.</param>
|
||||
/// <param name="additionalOutputTextures">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be filled with the resulting repacked texture for every property,
|
||||
/// just as the main repacked texture is assigned to <c>outputTexture</c>.</param>
|
||||
/// <param name="additionalTextureFormats">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be used as <c>TextureFormat</c> at the Texture at the respective property.
|
||||
/// When <c>additionalTextureFormats</c> is <c>null</c> or when its array size is smaller,
|
||||
/// <c>textureFormat</c> is used where there exists no corresponding array item.</param>
|
||||
/// <param name="additionalTextureIsLinear">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
|
||||
/// this array will be used to determine whether <c>linear</c> or <c>sRGB</c> color space is used at the
|
||||
/// Texture at the respective property. When <c>additionalTextureIsLinear</c> is <c>null</c>, <c>linear</c> color space
|
||||
/// is assumed at every additional Texture element.
|
||||
/// When e.g. packing the main texture and normal maps, pass 'new bool[] { true }' at this parameter, because normal maps use
|
||||
/// linear color space.</param>
|
||||
public static Skin GetRepackedSkin (this Skin o, string newName, Material materialPropertySource, out Material outputMaterial, out Texture2D outputTexture,
|
||||
int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
|
||||
bool useOriginalNonrenderables = true, bool clearCache = false,
|
||||
int[] additionalTexturePropertyIDsToCopy = null, Texture2D[] additionalOutputTextures = null,
|
||||
TextureFormat[] additionalTextureFormats = null, bool[] additionalTextureIsLinear = null) {
|
||||
|
||||
return GetRepackedSkin(o, newName, materialPropertySource.shader, out outputMaterial, out outputTexture,
|
||||
maxAtlasSize, padding, textureFormat, mipmaps, materialPropertySource,
|
||||
clearCache, useOriginalNonrenderables, additionalTexturePropertyIDsToCopy, additionalOutputTextures,
|
||||
additionalTextureFormats, additionalTextureIsLinear);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas
|
||||
/// comprised of all the regions from the original skin.</summary>
|
||||
/// See documentation of <see cref="GetRepackedSkin"/> for details.
|
||||
public static Skin GetRepackedSkin (this Skin o, string newName, Shader shader, out Material outputMaterial, out Texture2D outputTexture,
|
||||
int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
|
||||
Material materialPropertySource = null, bool clearCache = false, bool useOriginalNonrenderables = true,
|
||||
int[] additionalTexturePropertyIDsToCopy = null, Texture2D[] additionalOutputTextures = null,
|
||||
TextureFormat[] additionalTextureFormats = null, bool[] additionalTextureIsLinear = null) {
|
||||
|
||||
outputTexture = null;
|
||||
|
||||
if (o == null) throw new System.NullReferenceException("Skin was null");
|
||||
ICollection<Skin.SkinEntry> skinAttachments = o.Attachments;
|
||||
Skin newSkin = new Skin(newName);
|
||||
|
||||
newSkin.Bones.AddRange(o.Bones);
|
||||
newSkin.Constraints.AddRange(o.Constraints);
|
||||
|
||||
inoutAttachments.Clear();
|
||||
foreach (Skin.SkinEntry entry in skinAttachments) {
|
||||
inoutAttachments.Add(entry.Attachment);
|
||||
}
|
||||
GetRepackedAttachments(inoutAttachments, inoutAttachments, materialPropertySource, out outputMaterial, out outputTexture,
|
||||
maxAtlasSize, padding, textureFormat, mipmaps, newName, clearCache, useOriginalNonrenderables,
|
||||
additionalTexturePropertyIDsToCopy, additionalOutputTextures, additionalTextureFormats, additionalTextureIsLinear);
|
||||
int i = 0;
|
||||
foreach (Skin.SkinEntry originalSkinEntry in skinAttachments) {
|
||||
Attachment newAttachment = inoutAttachments[i++];
|
||||
newSkin.SetAttachment(originalSkinEntry.SlotIndex, originalSkinEntry.Name, newAttachment);
|
||||
}
|
||||
return newSkin;
|
||||
}
|
||||
|
||||
public static Sprite ToSprite (this AtlasRegion ar, float pixelsPerUnit = 100) {
|
||||
return Sprite.Create(ar.GetMainTexture(), ar.GetUnityRect(), new Vector2(0.5f, 0.5f), pixelsPerUnit);
|
||||
}
|
||||
|
||||
struct IntAndAtlasRegionKey {
|
||||
int i;
|
||||
AtlasRegion region;
|
||||
|
||||
public IntAndAtlasRegionKey (int i, AtlasRegion region) {
|
||||
this.i = i;
|
||||
this.region = region;
|
||||
}
|
||||
|
||||
public override int GetHashCode () {
|
||||
return i.GetHashCode() * 23 ^ region.GetHashCode();
|
||||
}
|
||||
}
|
||||
static Dictionary<IntAndAtlasRegionKey, Texture2D> CachedRegionTextures = new Dictionary<IntAndAtlasRegionKey, Texture2D>();
|
||||
static List<Texture2D> CachedRegionTexturesList = new List<Texture2D>();
|
||||
|
||||
/// <summary>
|
||||
/// Frees up textures cached by repacking and remapping operations.
|
||||
///
|
||||
/// Calling <see cref="AttachmentCloneExtensions.GetRemappedClone"/> with parameter <c>premultiplyAlpha=true</c>,
|
||||
/// <see cref="GetRepackedAttachments"/> or <see cref="GetRepackedSkin"/> will cache textures for later re-use,
|
||||
/// which might steadily increase the texture memory footprint when used excessively.
|
||||
/// You can clear this Texture cache by calling <see cref="AtlasUtilities.ClearCache()"/>.
|
||||
/// You may also want to call <c>Resources.UnloadUnusedAssets()</c> after that. Be aware that while this cleanup
|
||||
/// frees up memory, it is also a costly operation and will likely cause a spike in the framerate.
|
||||
/// Thus it is recommended to perform costly repacking and cleanup operations after e.g. a character customization
|
||||
/// screen has been exited, and if required additionally after a certain number of <c>GetRemappedClone()</c> calls.
|
||||
/// </summary>
|
||||
public static void ClearCache () {
|
||||
foreach (Texture2D t in CachedRegionTexturesList) {
|
||||
UnityEngine.Object.Destroy(t);
|
||||
}
|
||||
CachedRegionTextures.Clear();
|
||||
CachedRegionTexturesList.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Creates a new Texture2D object based on an AtlasRegion.
|
||||
/// If applyImmediately is true, Texture2D.Apply is called immediately after the Texture2D is filled with data.</summary>
|
||||
public static Texture2D ToTexture (this AtlasRegion ar, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
|
||||
int texturePropertyId = 0, bool linear = false, bool applyPMA = false) {
|
||||
|
||||
Texture2D output;
|
||||
|
||||
IntAndAtlasRegionKey cacheKey = new IntAndAtlasRegionKey(texturePropertyId, ar);
|
||||
CachedRegionTextures.TryGetValue(cacheKey, out output);
|
||||
if (output == null) {
|
||||
Texture2D sourceTexture = texturePropertyId == 0 ? ar.GetMainTexture() : ar.GetTexture(texturePropertyId);
|
||||
Rect r = ar.GetUnityRect();
|
||||
int width = (int)r.width;
|
||||
int height = (int)r.height;
|
||||
output = new Texture2D(width, height, textureFormat, mipmaps, linear) { name = ar.name };
|
||||
output.CopyTextureAttributesFrom(sourceTexture);
|
||||
if (applyPMA)
|
||||
AtlasUtilities.CopyTextureApplyPMA(sourceTexture, r, output);
|
||||
else
|
||||
AtlasUtilities.CopyTexture(sourceTexture, r, output);
|
||||
CachedRegionTextures.Add(cacheKey, output);
|
||||
CachedRegionTexturesList.Add(output);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
static Texture2D ToTexture (this Sprite s, TextureFormat textureFormat = SpineTextureFormat,
|
||||
bool mipmaps = UseMipMaps, bool linear = false, bool applyPMA = false) {
|
||||
|
||||
Texture2D spriteTexture = s.texture;
|
||||
Rect r;
|
||||
if (!s.packed || s.packingMode == SpritePackingMode.Rectangle) {
|
||||
r = s.textureRect;
|
||||
} else {
|
||||
r = new Rect();
|
||||
r.xMin = Math.Min(s.uv[0].x, s.uv[1].x) * spriteTexture.width;
|
||||
r.xMax = Math.Max(s.uv[0].x, s.uv[1].x) * spriteTexture.width;
|
||||
r.yMin = Math.Min(s.uv[0].y, s.uv[2].y) * spriteTexture.height;
|
||||
r.yMax = Math.Max(s.uv[0].y, s.uv[2].y) * spriteTexture.height;
|
||||
#if UNITY_EDITOR
|
||||
if (s.uv.Length > 4) {
|
||||
Debug.LogError("When using a tightly packed SpriteAtlas with Spine, you may only access Sprites that are packed as 'FullRect' from it! " +
|
||||
"You can either disable 'Tight Packing' at the whole SpriteAtlas, or change the single Sprite's TextureImporter Setting 'MeshType' to 'Full Rect'." +
|
||||
"Sprite Asset: " + s.name, s);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
Texture2D newTexture = new Texture2D((int)r.width, (int)r.height, textureFormat, mipmaps, linear);
|
||||
newTexture.CopyTextureAttributesFrom(spriteTexture);
|
||||
if (applyPMA)
|
||||
AtlasUtilities.CopyTextureApplyPMA(spriteTexture, r, newTexture);
|
||||
else
|
||||
AtlasUtilities.CopyTexture(spriteTexture, r, newTexture);
|
||||
return newTexture;
|
||||
}
|
||||
|
||||
static Texture2D GetClone (this Texture2D t, TextureFormat textureFormat = SpineTextureFormat,
|
||||
bool mipmaps = UseMipMaps, bool linear = false, bool applyPMA = false) {
|
||||
|
||||
Texture2D newTexture = new Texture2D((int)t.width, (int)t.height, textureFormat, mipmaps, linear);
|
||||
newTexture.CopyTextureAttributesFrom(t);
|
||||
if (applyPMA)
|
||||
AtlasUtilities.CopyTextureApplyPMA(t, new Rect(0, 0, t.width, t.height), newTexture);
|
||||
else
|
||||
AtlasUtilities.CopyTexture(t, new Rect(0, 0, t.width, t.height), newTexture);
|
||||
return newTexture;
|
||||
}
|
||||
|
||||
static void CopyTexture (Texture2D source, Rect sourceRect, Texture2D destination) {
|
||||
if (SystemInfo.copyTextureSupport == UnityEngine.Rendering.CopyTextureSupport.None) {
|
||||
// GetPixels fallback for old devices.
|
||||
Color[] pixelBuffer = source.GetPixels((int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height);
|
||||
destination.SetPixels(pixelBuffer);
|
||||
destination.Apply();
|
||||
} else {
|
||||
Graphics.CopyTexture(source, 0, 0, (int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height, destination, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
static void CopyTextureApplyPMA (Texture2D source, Rect sourceRect, Texture2D destination) {
|
||||
Color[] pixelBuffer = source.GetPixels((int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height);
|
||||
for (int i = 0, n = pixelBuffer.Length; i < n; i++) {
|
||||
Color p = pixelBuffer[i];
|
||||
float a = p.a;
|
||||
p.r = p.r * a;
|
||||
p.g = p.g * a;
|
||||
p.b = p.b * a;
|
||||
pixelBuffer[i] = p;
|
||||
}
|
||||
destination.SetPixels(pixelBuffer);
|
||||
destination.Apply();
|
||||
}
|
||||
|
||||
static bool IsRenderable (Attachment a) {
|
||||
return a is IHasTextureRegion;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a rect with flipped Y so that a Spine atlas rect gets converted to a Unity Sprite rect and vice versa.</summary>
|
||||
static Rect SpineUnityFlipRect (this Rect rect, int textureHeight) {
|
||||
rect.y = textureHeight - rect.y - rect.height;
|
||||
return rect;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up).
|
||||
/// This overload relies on region.page.height being correctly set.</summary>
|
||||
static Rect GetUnityRect (this AtlasRegion region) {
|
||||
return region.GetSpineAtlasRect().SpineUnityFlipRect(region.page.height);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up).</summary>
|
||||
static Rect GetUnityRect (this AtlasRegion region, int textureHeight) {
|
||||
return region.GetSpineAtlasRect().SpineUnityFlipRect(textureHeight);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a Rect of the AtlasRegion according to Spine texture coordinates. (x-right, y-down)</summary>
|
||||
static Rect GetSpineAtlasRect (this AtlasRegion region, bool includeRotate = true) {
|
||||
float width = region.packedWidth;
|
||||
float height = region.packedHeight;
|
||||
if (includeRotate && region.degrees == 270) {
|
||||
width = region.packedHeight;
|
||||
height = region.packedWidth;
|
||||
}
|
||||
return new Rect(region.x, region.y, width, height);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Denormalize a uvRect into a texture-space Rect.</summary>
|
||||
static Rect UVRectToTextureRect (Rect uvRect, int texWidth, int texHeight) {
|
||||
uvRect.x *= texWidth;
|
||||
uvRect.width *= texWidth;
|
||||
uvRect.y *= texHeight;
|
||||
uvRect.height *= texHeight;
|
||||
return uvRect;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalize a texture Rect into UV coordinates.</summary>
|
||||
static Rect TextureRectToUVRect (Rect textureRect, int texWidth, int texHeight) {
|
||||
textureRect.x = Mathf.InverseLerp(0, texWidth, textureRect.x);
|
||||
textureRect.y = Mathf.InverseLerp(0, texHeight, textureRect.y);
|
||||
textureRect.width = Mathf.InverseLerp(0, texWidth, textureRect.width);
|
||||
textureRect.height = Mathf.InverseLerp(0, texHeight, textureRect.height);
|
||||
return textureRect;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new Spine AtlasRegion according to a Unity UV Rect (x-right, y-up, uv-normalized).</summary>
|
||||
static AtlasRegion UVRectToAtlasRegion (Rect uvRect, AtlasRegion referenceRegion, AtlasPage page) {
|
||||
Rect tr = UVRectToTextureRect(uvRect, page.width, page.height);
|
||||
Rect rr = tr.SpineUnityFlipRect(page.height);
|
||||
|
||||
int x = (int)rr.x;
|
||||
int y = (int)rr.y;
|
||||
int w = (int)rr.width;
|
||||
int h = (int)rr.height;
|
||||
|
||||
if (referenceRegion.degrees == 270) {
|
||||
int tempW = w;
|
||||
w = h;
|
||||
h = tempW;
|
||||
}
|
||||
|
||||
// Note: originalW and originalH need to be scaled according to the
|
||||
// repacked width and height, repacking can mess with aspect ratio, etc.
|
||||
int originalW = Mathf.RoundToInt((float)w * ((float)referenceRegion.originalWidth / (float)referenceRegion.width));
|
||||
int originalH = Mathf.RoundToInt((float)h * ((float)referenceRegion.originalHeight / (float)referenceRegion.height));
|
||||
|
||||
int offsetX = Mathf.RoundToInt((float)referenceRegion.offsetX * ((float)w / (float)referenceRegion.width));
|
||||
int offsetY = Mathf.RoundToInt((float)referenceRegion.offsetY * ((float)h / (float)referenceRegion.height));
|
||||
|
||||
float u = uvRect.xMin;
|
||||
float u2 = uvRect.xMax;
|
||||
float v = uvRect.yMax;
|
||||
float v2 = uvRect.yMin;
|
||||
|
||||
if (referenceRegion.degrees == 270) {
|
||||
// at a 270 degree region, u2/v2 deltas and atlas width/height are swapped, and delta-v is negative.
|
||||
float du = uvRect.width; // u2 - u;
|
||||
float dv = uvRect.height; // v - v2;
|
||||
float atlasAspectRatio = (float)page.width / (float)page.height;
|
||||
u2 = u + (dv / atlasAspectRatio);
|
||||
v2 = v - (du * atlasAspectRatio);
|
||||
}
|
||||
|
||||
return new AtlasRegion {
|
||||
page = page,
|
||||
name = referenceRegion.name,
|
||||
|
||||
u = u,
|
||||
u2 = u2,
|
||||
v = v,
|
||||
v2 = v2,
|
||||
|
||||
index = -1,
|
||||
|
||||
width = w,
|
||||
originalWidth = originalW,
|
||||
height = h,
|
||||
originalHeight = originalH,
|
||||
offsetX = offsetX,
|
||||
offsetY = offsetY,
|
||||
x = x,
|
||||
y = y,
|
||||
|
||||
rotate = referenceRegion.rotate,
|
||||
degrees = referenceRegion.degrees
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convenience method for getting the main texture of the material of the page of the region.</summary>
|
||||
static Texture2D GetMainTexture (this AtlasRegion region) {
|
||||
Material material = (region.page.rendererObject as Material);
|
||||
return material.mainTexture as Texture2D;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convenience method for getting any texture of the material of the page of the region by texture property name.</summary>
|
||||
static Texture2D GetTexture (this AtlasRegion region, string texturePropertyName) {
|
||||
Material material = (region.page.rendererObject as Material);
|
||||
return material.GetTexture(texturePropertyName) as Texture2D;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convenience method for getting any texture of the material of the page of the region by texture property id.</summary>
|
||||
static Texture2D GetTexture (this AtlasRegion region, int texturePropertyId) {
|
||||
Material material = (region.page.rendererObject as Material);
|
||||
return material.GetTexture(texturePropertyId) as Texture2D;
|
||||
}
|
||||
|
||||
static void CopyTextureAttributesFrom (this Texture2D destination, Texture2D source) {
|
||||
destination.filterMode = source.filterMode;
|
||||
destination.anisoLevel = source.anisoLevel;
|
||||
#if UNITY_EDITOR
|
||||
destination.alphaIsTransparency = source.alphaIsTransparency;
|
||||
#endif
|
||||
destination.wrapModeU = source.wrapModeU;
|
||||
destination.wrapModeV = source.wrapModeV;
|
||||
destination.wrapModeW = source.wrapModeW;
|
||||
}
|
||||
#endregion
|
||||
|
||||
static float InverseLerp (float a, float b, float value) {
|
||||
return (value - a) / (b - a);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 25ceef568a3dad448bf8a14fcc326964
|
||||
timeCreated: 1563321428
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,118 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity.AttachmentTools {
|
||||
|
||||
public static class AttachmentCloneExtensions {
|
||||
|
||||
#region RemappedClone Convenience Methods
|
||||
/// <summary>
|
||||
/// Gets a clone of the attachment remapped with a sprite image.</summary>
|
||||
/// <returns>The remapped clone.</returns>
|
||||
/// <param name="o">The original attachment.</param>
|
||||
/// <param name="sprite">The sprite whose texture to use.</param>
|
||||
/// <param name="sourceMaterial">The source material used to copy the shader and material properties from.</param>
|
||||
/// <param name="premultiplyAlpha">If <c>true</c>, a premultiply alpha clone of the original texture will be created.
|
||||
/// See remarks below for additional info.</param>
|
||||
/// <param name="cloneMeshAsLinked">If <c>true</c> MeshAttachments will be cloned as linked meshes and will inherit animation from the original attachment.</param>
|
||||
/// <param name="useOriginalRegionSize">If <c>true</c> the size of the original attachment will be followed, instead of using the Sprite size.</param>
|
||||
/// <param name="pivotShiftsMeshUVCoords">If <c>true</c> and the original Attachment is a MeshAttachment, then
|
||||
/// a non-central sprite pivot will shift uv coords in the opposite direction. Vertices will not be offset in
|
||||
/// any case when the original Attachment is a MeshAttachment.</param>
|
||||
/// <param name="useOriginalRegionScale">If <c>true</c> and the original Attachment is a RegionAttachment, then
|
||||
/// the original region's scale value is used instead of the Sprite's pixels per unit property. Since uniform scale is used,
|
||||
/// x scale of the original attachment (width scale) is used, scale in y direction (height scale) is ignored.</param>
|
||||
/// <param name="pmaCloneTextureFormat">If <c>premultiplyAlpha</c> is <c>true></c>, the TextureFormat of the
|
||||
/// newly created PMA attachment Texture.</param>
|
||||
/// <param name="pmaCloneMipmaps">If <c>premultiplyAlpha</c> is <ctrue></c>, whether the newly created
|
||||
/// PMA attachment Texture has mipmaps enabled.</param>
|
||||
/// <remarks>When parameter <c>premultiplyAlpha</c> is set to <c>true</c>, a premultiply alpha clone of the
|
||||
/// original texture will be created. Additionally, this PMA Texture clone is cached for later re-use,
|
||||
/// which might steadily increase the Texture memory footprint when used excessively.
|
||||
/// See <see cref="AtlasUtilities.ClearCache()"/> on how to clear these cached textures.</remarks>
|
||||
public static Attachment GetRemappedClone (this Attachment o, Sprite sprite, Material sourceMaterial,
|
||||
bool premultiplyAlpha = true, bool cloneMeshAsLinked = true, bool useOriginalRegionSize = false,
|
||||
bool pivotShiftsMeshUVCoords = true, bool useOriginalRegionScale = false,
|
||||
TextureFormat pmaCloneTextureFormat = AtlasUtilities.SpineTextureFormat,
|
||||
bool pmaCloneMipmaps = AtlasUtilities.UseMipMaps) {
|
||||
|
||||
AtlasRegion atlasRegion = premultiplyAlpha ?
|
||||
sprite.ToAtlasRegionPMAClone(sourceMaterial, pmaCloneTextureFormat, pmaCloneMipmaps) :
|
||||
sprite.ToAtlasRegion(new Material(sourceMaterial) { mainTexture = sprite.texture });
|
||||
if (!pivotShiftsMeshUVCoords && o is MeshAttachment) {
|
||||
// prevent non-central sprite pivot setting offsetX/Y and shifting uv coords out of mesh bounds
|
||||
atlasRegion.offsetX = 0;
|
||||
atlasRegion.offsetY = 0;
|
||||
}
|
||||
float scale = 1f / sprite.pixelsPerUnit;
|
||||
if (useOriginalRegionScale) {
|
||||
RegionAttachment regionAttachment = o as RegionAttachment;
|
||||
if (regionAttachment != null)
|
||||
scale = regionAttachment.Width / regionAttachment.Region.OriginalWidth;
|
||||
}
|
||||
return o.GetRemappedClone(atlasRegion, cloneMeshAsLinked, useOriginalRegionSize, scale);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a clone of the attachment remapped with an atlasRegion image.</summary>
|
||||
/// <returns>The remapped clone.</returns>
|
||||
/// <param name="o">The original attachment.</param>
|
||||
/// <param name="atlasRegion">Atlas region.</param>
|
||||
/// <param name="cloneMeshAsLinked">If <c>true</c> MeshAttachments will be cloned as linked meshes and will inherit animation from the original attachment.</param>
|
||||
/// <param name="useOriginalRegionSize">If <c>true</c> the size of the original attachment will be followed, instead of using the Sprite size.</param>
|
||||
/// <param name="scale">Unity units per pixel scale used to scale the atlas region size when not using the original region size.</param>
|
||||
public static Attachment GetRemappedClone (this Attachment o, AtlasRegion atlasRegion, bool cloneMeshAsLinked = true, bool useOriginalRegionSize = false, float scale = 0.01f) {
|
||||
RegionAttachment regionAttachment = o as RegionAttachment;
|
||||
if (regionAttachment != null) {
|
||||
RegionAttachment newAttachment = (RegionAttachment)regionAttachment.Copy();
|
||||
newAttachment.Region = atlasRegion;
|
||||
if (!useOriginalRegionSize) {
|
||||
newAttachment.Width = atlasRegion.width * scale;
|
||||
newAttachment.Height = atlasRegion.height * scale;
|
||||
}
|
||||
newAttachment.UpdateRegion();
|
||||
return newAttachment;
|
||||
} else {
|
||||
MeshAttachment meshAttachment = o as MeshAttachment;
|
||||
if (meshAttachment != null) {
|
||||
MeshAttachment newAttachment = cloneMeshAsLinked ? meshAttachment.NewLinkedMesh() : (MeshAttachment)meshAttachment.Copy();
|
||||
newAttachment.Region = atlasRegion;
|
||||
newAttachment.UpdateRegion();
|
||||
return newAttachment;
|
||||
}
|
||||
}
|
||||
return o.Copy();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3431ed563b2c62f4c8c974a99365ba52
|
||||
timeCreated: 1563321428
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,133 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity.AttachmentTools {
|
||||
public static class AttachmentRegionExtensions {
|
||||
#region Runtime RegionAttachments
|
||||
/// <summary>
|
||||
/// Creates a RegionAttachment based on a sprite. This method creates a real, usable AtlasRegion. That AtlasRegion uses a new AtlasPage with the Material provided./// </summary>
|
||||
public static RegionAttachment ToRegionAttachment (this Sprite sprite, Material material, float rotation = 0f) {
|
||||
return sprite.ToRegionAttachment(material.ToSpineAtlasPage(), rotation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a RegionAttachment based on a sprite. This method creates a real, usable AtlasRegion. That AtlasRegion uses the AtlasPage provided./// </summary>
|
||||
public static RegionAttachment ToRegionAttachment (this Sprite sprite, AtlasPage page, float rotation = 0f) {
|
||||
if (sprite == null) throw new System.ArgumentNullException("sprite");
|
||||
if (page == null) throw new System.ArgumentNullException("page");
|
||||
AtlasRegion region = sprite.ToAtlasRegion(page);
|
||||
float unitsPerPixel = 1f / sprite.pixelsPerUnit;
|
||||
return region.ToRegionAttachment(sprite.name, unitsPerPixel, rotation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate texture of the Sprite's texture data.
|
||||
/// Returns a RegionAttachment that uses it. Use this if you plan to use a premultiply alpha shader such as "Spine/Skeleton".</summary>
|
||||
/// <remarks>The duplicate texture is cached for later re-use. See documentation of
|
||||
/// <see cref="AttachmentCloneExtensions.GetRemappedClone"/> for additional details.</remarks>
|
||||
public static RegionAttachment ToRegionAttachmentPMAClone (this Sprite sprite, Shader shader, TextureFormat textureFormat = AtlasUtilities.SpineTextureFormat, bool mipmaps = AtlasUtilities.UseMipMaps, Material materialPropertySource = null, float rotation = 0f) {
|
||||
if (sprite == null) throw new System.ArgumentNullException("sprite");
|
||||
if (shader == null) throw new System.ArgumentNullException("shader");
|
||||
AtlasRegion region = sprite.ToAtlasRegionPMAClone(shader, textureFormat, mipmaps, materialPropertySource);
|
||||
float unitsPerPixel = 1f / sprite.pixelsPerUnit;
|
||||
return region.ToRegionAttachment(sprite.name, unitsPerPixel, rotation);
|
||||
}
|
||||
|
||||
public static RegionAttachment ToRegionAttachmentPMAClone (this Sprite sprite, Material materialPropertySource, TextureFormat textureFormat = AtlasUtilities.SpineTextureFormat, bool mipmaps = AtlasUtilities.UseMipMaps, float rotation = 0f) {
|
||||
return sprite.ToRegionAttachmentPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource, rotation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new RegionAttachment from a given AtlasRegion.</summary>
|
||||
public static RegionAttachment ToRegionAttachment (this AtlasRegion region, string attachmentName, float scale = 0.01f, float rotation = 0f) {
|
||||
if (string.IsNullOrEmpty(attachmentName)) throw new System.ArgumentException("attachmentName can't be null or empty.", "attachmentName");
|
||||
if (region == null) throw new System.ArgumentNullException("region");
|
||||
|
||||
// (AtlasAttachmentLoader.cs)
|
||||
RegionAttachment attachment = new RegionAttachment(attachmentName);
|
||||
|
||||
attachment.Region = region;
|
||||
attachment.Path = region.name;
|
||||
attachment.ScaleX = 1;
|
||||
attachment.ScaleY = 1;
|
||||
attachment.Rotation = rotation;
|
||||
|
||||
attachment.R = 1;
|
||||
attachment.G = 1;
|
||||
attachment.B = 1;
|
||||
attachment.A = 1;
|
||||
|
||||
// pass OriginalWidth and OriginalHeight because UpdateOffset uses it in its calculation.
|
||||
TextureRegion textreRegion = attachment.Region;
|
||||
AtlasRegion atlasRegion = textreRegion as AtlasRegion;
|
||||
float originalWidth = atlasRegion != null ? atlasRegion.originalWidth : textreRegion.width;
|
||||
float originalHeight = atlasRegion != null ? atlasRegion.originalHeight : textreRegion.height;
|
||||
attachment.Width = originalWidth * scale;
|
||||
attachment.Height = originalHeight * scale;
|
||||
|
||||
attachment.SetColor(Color.white);
|
||||
attachment.UpdateRegion();
|
||||
return attachment;
|
||||
}
|
||||
|
||||
/// <summary> Sets the scale. Call regionAttachment.UpdateOffset to apply the change.</summary>
|
||||
public static void SetScale (this RegionAttachment regionAttachment, Vector2 scale) {
|
||||
regionAttachment.ScaleX = scale.x;
|
||||
regionAttachment.ScaleY = scale.y;
|
||||
}
|
||||
|
||||
/// <summary> Sets the scale. Call regionAttachment.UpdateOffset to apply the change.</summary>
|
||||
public static void SetScale (this RegionAttachment regionAttachment, float x, float y) {
|
||||
regionAttachment.ScaleX = x;
|
||||
regionAttachment.ScaleY = y;
|
||||
}
|
||||
|
||||
/// <summary> Sets the position offset. Call regionAttachment.UpdateOffset to apply the change.</summary>
|
||||
public static void SetPositionOffset (this RegionAttachment regionAttachment, Vector2 offset) {
|
||||
regionAttachment.X = offset.x;
|
||||
regionAttachment.Y = offset.y;
|
||||
}
|
||||
|
||||
/// <summary> Sets the position offset. Call regionAttachment.UpdateOffset to apply the change.</summary>
|
||||
public static void SetPositionOffset (this RegionAttachment regionAttachment, float x, float y) {
|
||||
regionAttachment.X = x;
|
||||
regionAttachment.Y = y;
|
||||
}
|
||||
|
||||
/// <summary> Sets the rotation. Call regionAttachment.UpdateOffset to apply the change.</summary>
|
||||
public static void SetRotation (this RegionAttachment regionAttachment, float rotation) {
|
||||
regionAttachment.Rotation = rotation;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7e7eac783deea004e9bc403eca68a7dc
|
||||
timeCreated: 1563321428
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,42 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
#if UNITY_EDITOR
|
||||
|
||||
namespace Spine.Unity {
|
||||
|
||||
public static class BuildUtilities {
|
||||
public static bool IsInSkeletonAssetBuildPreProcessing = false;
|
||||
public static bool IsInSkeletonAssetBuildPostProcessing = false;
|
||||
public static bool IsInSpriteAtlasBuildPreProcessing = false;
|
||||
public static bool IsInSpriteAtlasBuildPostProcessing = false;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a2f1169aaf0063f4da1c2b6033bbc13f
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,355 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>Utility class providing methods to check material settings for incorrect combinations.</summary>
|
||||
public class MaterialChecks {
|
||||
|
||||
static readonly int STRAIGHT_ALPHA_PARAM_ID = Shader.PropertyToID("_StraightAlphaInput");
|
||||
static readonly string ALPHAPREMULTIPLY_ON_KEYWORD = "_ALPHAPREMULTIPLY_ON";
|
||||
static readonly string ALPHAPREMULTIPLY_VERTEX_ONLY_ON_KEYWORD = "_ALPHAPREMULTIPLY_VERTEX_ONLY";
|
||||
static readonly string ALPHABLEND_ON_KEYWORD = "_ALPHABLEND_ON";
|
||||
static readonly string STRAIGHT_ALPHA_KEYWORD = "_STRAIGHT_ALPHA_INPUT";
|
||||
static readonly string[] FIXED_NORMALS_KEYWORDS = {
|
||||
"_FIXED_NORMALS_VIEWSPACE",
|
||||
"_FIXED_NORMALS_VIEWSPACE_BACKFACE",
|
||||
"_FIXED_NORMALS_MODELSPACE",
|
||||
"_FIXED_NORMALS_MODELSPACE_BACKFACE",
|
||||
"_FIXED_NORMALS_WORLDSPACE"
|
||||
};
|
||||
static readonly string NORMALMAP_KEYWORD = "_NORMALMAP";
|
||||
static readonly string CANVAS_GROUP_COMPATIBLE_KEYWORD = "_CANVAS_GROUP_COMPATIBLE";
|
||||
|
||||
public static readonly string kPMANotSupportedLinearMessage =
|
||||
"\nWarning: Premultiply-alpha atlas textures not supported in Linear color space!"
|
||||
+ "You can use a straight alpha texture with 'PMA Vertex Color' by choosing blend mode 'PMA Vertex, Straight Texture'.\n\n"
|
||||
+ "If you have a PMA Texture, please\n"
|
||||
+ "a) re-export atlas as straight alpha texture with 'premultiply alpha' unchecked\n"
|
||||
+ " (if you have already done this, please set the 'Straight Alpha Texture' Material parameter to 'true') or\n"
|
||||
+ "b) switch to Gamma color space via\nProject Settings - Player - Other Settings - Color Space.\n";
|
||||
public static readonly string kZSpacingRequiredMessage =
|
||||
"\nWarning: Z Spacing required on selected shader! Otherwise you will receive incorrect results.\n\nPlease\n"
|
||||
+ "1) make sure at least minimal 'Z Spacing' is set at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' and\n"
|
||||
+ "2) ensure that the skeleton has overlapping parts on different Z depth. You can adjust this in Spine via draw order.\n";
|
||||
public static readonly string kZSpacingRecommendedMessage =
|
||||
"\nWarning: Z Spacing recommended on selected shader configuration!\n\nPlease\n"
|
||||
+ "1) make sure at least minimal 'Z Spacing' is set at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' and\n"
|
||||
+ "2) ensure that the skeleton has overlapping parts on different Z depth. You can adjust this in Spine via draw order.\n";
|
||||
public static readonly string kAddNormalsMessage =
|
||||
"\nWarning: 'Add Normals' required when not using 'Fixed Normals'!\n\nPlease\n"
|
||||
+ "a) enable 'Add Normals' at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' or\n"
|
||||
+ "b) enable 'Fixed Normals' at the Material.\n";
|
||||
public static readonly string kSolveTangentsMessage =
|
||||
"\nWarning: 'Solve Tangents' required when using a Normal Map!\n\nPlease\n"
|
||||
+ "a) enable 'Solve Tangents' at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' or\n"
|
||||
+ "b) clear the 'Normal Map' parameter at the Material.\n";
|
||||
public static readonly string kNoSkeletonGraphicMaterialMessage =
|
||||
"\nWarning: Normal non-UI shaders other than 'Spine/SkeletonGraphic *' are not compatible with 'SkeletonGraphic' components! "
|
||||
+ "This will lead to incorrect rendering on some devices.\n\n"
|
||||
+ "Please change the assigned Material to e.g. 'SkeletonGraphicDefault' or change the used shader to one of the 'Spine/SkeletonGraphic *' shaders.\n\n"
|
||||
+ "Note that 'Spine/SkeletonGraphic *' shall still be used when using URP.\n";
|
||||
public static readonly string kNoSkeletonGraphicTintBlackMaterialMessage =
|
||||
"\nWarning: Only enable 'Canvas Group Tint Black' when using a 'SkeletonGraphic Tint Black' shader!\n"
|
||||
+ "This will lead to incorrect rendering.\n\nPlease\n"
|
||||
+ "a) disable 'Canvas Group Tint Black' under 'Advanced' or\n"
|
||||
+ "b) use a 'SkeletonGraphic Tint Black' Material if you need Tint Black on a CanvasGroup.\n";
|
||||
|
||||
public static readonly string kTintBlackMessage =
|
||||
"\nWarning: 'Advanced - Tint Black' required when using any 'Tint Black' shader!\n\nPlease\n"
|
||||
+ "a) enable 'Tint Black' at the SkeletonRenderer/SkeletonGraphic component under 'Advanced' or\n"
|
||||
+ "b) use a different shader at the Material.\n";
|
||||
public static readonly string kCanvasTintBlackMessage =
|
||||
"\nWarning: Canvas 'Additional Shader Channels' 'uv1' and 'uv2' are required when 'Advanced - Tint Black' is enabled!\n\n"
|
||||
+ "Please enable both 'uv1' and 'uv2' channels at the parent Canvas component parameter 'Additional Shader Channels'.\n";
|
||||
public static readonly string kCanvasGroupCompatibleMessage =
|
||||
"\nWarning: 'Canvas Group Tint Black' is enabled at SkeletonGraphic but not 'CanvasGroup Compatible' at the Material!\n\nPlease\n"
|
||||
+ "a) enable 'CanvasGroup Compatible' at the Material or\n"
|
||||
+ "b) disable 'Canvas Group Tint Black' at the SkeletonGraphic component under 'Advanced'.\n"
|
||||
+ "You may want to duplicate the 'SkeletonGraphicTintBlack' material and change settings at the duplicate to not affect all instances.";
|
||||
public static readonly string kCanvasGroupCompatibleDisabledMessage =
|
||||
"\nWarning: 'CanvasGroup Compatible' is enabled at the Material but 'Canvas Group Tint Black' is disabled at SkeletonGraphic!\n\nPlease\n"
|
||||
+ "a) disable 'CanvasGroup Compatible' at the Material or\n"
|
||||
+ "b) enable 'Canvas Group Tint Black' at the SkeletonGraphic component under 'Advanced'.\n"
|
||||
+ "You may want to duplicate the 'SkeletonGraphicTintBlack' material and change settings at the duplicate to not affect all instances.";
|
||||
public static readonly string kCanvasGroupCompatiblePMAVertexMessage =
|
||||
"\nWarning: 'CanvasGroup Compatible' is enabled at the Material and 'PMA Vertex Colors' is enabled at SkeletonGraphic!\n\nPlease\n"
|
||||
+ "a) disable 'CanvasGroup Compatible' at the Material or\n"
|
||||
+ "b) disable 'PMA Vertex Colors' at the SkeletonGraphic component under 'Advanced'.";
|
||||
|
||||
public static bool IsMaterialSetupProblematic (SkeletonRenderer renderer, ref string errorMessage) {
|
||||
Material[] materials = renderer.GetComponent<Renderer>().sharedMaterials;
|
||||
bool isProblematic = false;
|
||||
foreach (Material material in materials) {
|
||||
if (material == null) continue;
|
||||
isProblematic |= IsMaterialSetupProblematic(material, ref errorMessage);
|
||||
if (renderer.zSpacing == 0) {
|
||||
isProblematic |= IsZSpacingRequired(material, ref errorMessage);
|
||||
}
|
||||
if (renderer.addNormals == false && RequiresMeshNormals(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kAddNormalsMessage;
|
||||
}
|
||||
if (renderer.calculateTangents == false && RequiresTangents(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kSolveTangentsMessage;
|
||||
}
|
||||
if (renderer.tintBlack == false && RequiresTintBlack(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kTintBlackMessage;
|
||||
}
|
||||
}
|
||||
return isProblematic;
|
||||
}
|
||||
|
||||
public static bool IsMaterialSetupProblematic (SkeletonGraphic skeletonGraphic, ref string errorMessage) {
|
||||
Material material = skeletonGraphic.material;
|
||||
bool isProblematic = false;
|
||||
if (material) {
|
||||
isProblematic |= IsMaterialSetupProblematic(material, ref errorMessage);
|
||||
MeshGenerator.Settings settings = skeletonGraphic.MeshGenerator.settings;
|
||||
if (settings.zSpacing == 0) {
|
||||
isProblematic |= IsZSpacingRequired(material, ref errorMessage);
|
||||
}
|
||||
if (IsSpineNonSkeletonGraphicMaterial(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kNoSkeletonGraphicMaterialMessage;
|
||||
}
|
||||
if (settings.tintBlack == false && RequiresTintBlack(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kTintBlackMessage;
|
||||
}
|
||||
if (settings.tintBlack == true && CanvasNotSetupForTintBlack(skeletonGraphic)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kCanvasTintBlackMessage;
|
||||
}
|
||||
if (settings.canvasGroupTintBlack == true && !IsSkeletonGraphicTintBlackMaterial(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kNoSkeletonGraphicTintBlackMaterialMessage;
|
||||
}
|
||||
if (settings.canvasGroupTintBlack == true && !IsCanvasGroupCompatible(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kCanvasGroupCompatibleMessage;
|
||||
}
|
||||
if (settings.tintBlack == true && settings.canvasGroupTintBlack == false
|
||||
&& IsCanvasGroupCompatible(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kCanvasGroupCompatibleDisabledMessage;
|
||||
}
|
||||
if (settings.pmaVertexColors == true && IsCanvasGroupCompatible(material)) {
|
||||
isProblematic = true;
|
||||
errorMessage += kCanvasGroupCompatiblePMAVertexMessage;
|
||||
}
|
||||
}
|
||||
return isProblematic;
|
||||
}
|
||||
|
||||
public static bool IsMaterialSetupProblematic (Material material, ref string errorMessage) {
|
||||
return !IsColorSpaceSupported(material, ref errorMessage);
|
||||
}
|
||||
|
||||
public static bool IsZSpacingRequired (Material material, ref string errorMessage) {
|
||||
bool hasForwardAddPass = material.FindPass("FORWARD_DELTA") >= 0;
|
||||
if (hasForwardAddPass) {
|
||||
errorMessage += kZSpacingRequiredMessage;
|
||||
return true;
|
||||
}
|
||||
bool zWrite = material.HasProperty("_ZWrite") && material.GetFloat("_ZWrite") > 0.0f;
|
||||
if (zWrite) {
|
||||
errorMessage += kZSpacingRecommendedMessage;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool IsColorSpaceSupported (Material material, ref string errorMessage) {
|
||||
if (QualitySettings.activeColorSpace == ColorSpace.Linear) {
|
||||
if (IsPMATextureMaterial(material)) {
|
||||
errorMessage += kPMANotSupportedLinearMessage;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public static bool UsesSpineShader (Material material) {
|
||||
return material.shader.name.Contains("Spine/");
|
||||
}
|
||||
|
||||
public static bool IsTextureSetupProblematic (Material material, ColorSpace colorSpace,
|
||||
bool sRGBTexture, bool mipmapEnabled, bool alphaIsTransparency,
|
||||
string texturePath, string materialPath,
|
||||
ref string errorMessage) {
|
||||
|
||||
if (material == null || !UsesSpineShader(material)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isProblematic = false;
|
||||
if (IsPMATextureMaterial(material)) {
|
||||
// 'sRGBTexture = true' generates incorrectly weighted mipmaps at PMA textures,
|
||||
// causing white borders due to undesired custom weighting.
|
||||
if (sRGBTexture && mipmapEnabled && colorSpace == ColorSpace.Gamma) {
|
||||
errorMessage += string.Format("`{0}` : Problematic Texture Settings found: " +
|
||||
"When enabling `Generate Mip Maps` in Gamma color space, it is recommended " +
|
||||
"to disable `sRGB (Color Texture)` on `Premultiply alpha` textures. Otherwise " +
|
||||
"you will receive white border artifacts on an atlas exported with default " +
|
||||
"`Premultiply alpha` settings.\n" +
|
||||
"(You can disable this warning in `Edit - Preferences - Spine`)\n", texturePath);
|
||||
isProblematic = true;
|
||||
}
|
||||
if (alphaIsTransparency) {
|
||||
string materialName = System.IO.Path.GetFileName(materialPath);
|
||||
errorMessage += string.Format("`{0}` and material `{1}` : Problematic " +
|
||||
"Texture / Material Settings found: It is recommended to disable " +
|
||||
"`Alpha Is Transparency` on `Premultiply alpha` textures.\n" +
|
||||
"Assuming `Premultiply alpha` texture because `Straight Alpha Texture` " +
|
||||
"is disabled at material). " +
|
||||
"(You can disable this warning in `Edit - Preferences - Spine`)\n", texturePath, materialName);
|
||||
isProblematic = true;
|
||||
}
|
||||
} else { // straight alpha texture
|
||||
if (!alphaIsTransparency) {
|
||||
string materialName = System.IO.Path.GetFileName(materialPath);
|
||||
errorMessage += string.Format("`{0}` and material `{1}` : Incorrect" +
|
||||
"Texture / Material Settings found: It is strongly recommended " +
|
||||
"to enable `Alpha Is Transparency` on `Straight alpha` textures.\n" +
|
||||
"Assuming `Straight alpha` texture because `Straight Alpha Texture` " +
|
||||
"is enabled at material). " +
|
||||
"(You can disable this warning in `Edit - Preferences - Spine`)\n", texturePath, materialName);
|
||||
isProblematic = true;
|
||||
}
|
||||
}
|
||||
return isProblematic;
|
||||
}
|
||||
|
||||
public static void EnablePMATextureAtMaterial (Material material, bool enablePMATexture) {
|
||||
if (material.HasProperty(STRAIGHT_ALPHA_PARAM_ID)) {
|
||||
material.SetInt(STRAIGHT_ALPHA_PARAM_ID, enablePMATexture ? 0 : 1);
|
||||
if (enablePMATexture)
|
||||
material.DisableKeyword(STRAIGHT_ALPHA_KEYWORD);
|
||||
else
|
||||
material.EnableKeyword(STRAIGHT_ALPHA_KEYWORD);
|
||||
} else {
|
||||
if (enablePMATexture) {
|
||||
material.DisableKeyword(ALPHAPREMULTIPLY_ON_KEYWORD);
|
||||
material.DisableKeyword(ALPHABLEND_ON_KEYWORD);
|
||||
material.EnableKeyword(ALPHAPREMULTIPLY_VERTEX_ONLY_ON_KEYWORD);
|
||||
} else {
|
||||
material.DisableKeyword(ALPHAPREMULTIPLY_ON_KEYWORD);
|
||||
material.DisableKeyword(ALPHAPREMULTIPLY_VERTEX_ONLY_ON_KEYWORD);
|
||||
material.EnableKeyword(ALPHABLEND_ON_KEYWORD);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsPMATextureMaterial (Material material) {
|
||||
bool usesAlphaPremultiplyKeyword = IsSpriteShader(material);
|
||||
if (usesAlphaPremultiplyKeyword)
|
||||
return material.IsKeywordEnabled(ALPHAPREMULTIPLY_ON_KEYWORD);
|
||||
else
|
||||
return material.HasProperty(STRAIGHT_ALPHA_PARAM_ID) && material.GetInt(STRAIGHT_ALPHA_PARAM_ID) == 0;
|
||||
}
|
||||
|
||||
static bool IsURP3DMaterial (Material material) {
|
||||
return material.shader.name.Contains("Universal Render Pipeline/Spine");
|
||||
}
|
||||
|
||||
static bool IsSpineNonSkeletonGraphicMaterial (Material material) {
|
||||
return material.shader.name.Contains("Spine") && !material.shader.name.Contains("SkeletonGraphic");
|
||||
}
|
||||
|
||||
static bool IsSkeletonGraphicTintBlackMaterial (Material material) {
|
||||
return material.shader.name.Contains("Spine") && material.shader.name.Contains("SkeletonGraphic")
|
||||
&& material.shader.name.Contains("Black");
|
||||
}
|
||||
|
||||
static bool AreShadowsDisabled (Material material) {
|
||||
return material.IsKeywordEnabled("_RECEIVE_SHADOWS_OFF");
|
||||
}
|
||||
|
||||
static bool RequiresMeshNormals (Material material) {
|
||||
bool anyFixedNormalSet = false;
|
||||
foreach (string fixedNormalKeyword in FIXED_NORMALS_KEYWORDS) {
|
||||
if (material.IsKeywordEnabled(fixedNormalKeyword)) {
|
||||
anyFixedNormalSet = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
bool isShaderWithMeshNormals = IsLitSpriteShader(material);
|
||||
return isShaderWithMeshNormals && !anyFixedNormalSet;
|
||||
}
|
||||
|
||||
static bool IsLitSpriteShader (Material material) {
|
||||
string shaderName = material.shader.name;
|
||||
return shaderName.Contains("Spine/Sprite/Pixel Lit") ||
|
||||
shaderName.Contains("Spine/Sprite/Vertex Lit") ||
|
||||
shaderName.Contains("2D/Spine/Sprite") || // covers both URP and LWRP
|
||||
shaderName.Contains("Pipeline/Spine/Sprite"); // covers both URP and LWRP
|
||||
}
|
||||
|
||||
static bool IsSpriteShader (Material material) {
|
||||
if (IsLitSpriteShader(material))
|
||||
return true;
|
||||
string shaderName = material.shader.name;
|
||||
return shaderName.Contains("Spine/Sprite/Unlit");
|
||||
}
|
||||
|
||||
static bool RequiresTintBlack (Material material) {
|
||||
bool isTintBlackShader =
|
||||
material.shader.name.Contains("Spine") &&
|
||||
material.shader.name.Contains("Tint Black");
|
||||
return isTintBlackShader;
|
||||
}
|
||||
|
||||
static bool RequiresTangents (Material material) {
|
||||
return material.IsKeywordEnabled(NORMALMAP_KEYWORD);
|
||||
}
|
||||
static bool IsCanvasGroupCompatible (Material material) {
|
||||
return material.IsKeywordEnabled(CANVAS_GROUP_COMPATIBLE_KEYWORD);
|
||||
}
|
||||
|
||||
static bool CanvasNotSetupForTintBlack (SkeletonGraphic skeletonGraphic) {
|
||||
Canvas canvas = skeletonGraphic.canvas;
|
||||
if (!canvas)
|
||||
return false;
|
||||
var requiredChannels =
|
||||
AdditionalCanvasShaderChannels.TexCoord1 |
|
||||
AdditionalCanvasShaderChannels.TexCoord2;
|
||||
return (canvas.additionalShaderChannels & requiredChannels) != requiredChannels;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // UNITY_EDITOR
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e68fa8db689084946adce454b83e6d4a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,71 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
public static class MathUtilities {
|
||||
public static float InverseLerp (float a, float b, float value) {
|
||||
return (value - a) / (b - a);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the linear interpolation ratio of <c>a</c> to <c>b</c> that <c>value</c> lies on.
|
||||
/// This is the t value that fulfills <c>value = lerp(a, b, t)</c>.
|
||||
/// </summary>
|
||||
public static Vector2 InverseLerp (Vector2 a, Vector2 b, Vector2 value) {
|
||||
return new Vector2(
|
||||
(value.x - a.x) / (b.x - a.x),
|
||||
(value.y - a.y) / (b.y - a.y));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the linear interpolation ratio of <c>a</c> to <c>b</c> that <c>value</c> lies on.
|
||||
/// This is the t value that fulfills <c>value = lerp(a, b, t)</c>.
|
||||
/// </summary>
|
||||
public static Vector3 InverseLerp (Vector3 a, Vector3 b, Vector3 value) {
|
||||
return new Vector3(
|
||||
(value.x - a.x) / (b.x - a.x),
|
||||
(value.y - a.y) / (b.y - a.y),
|
||||
(value.z - a.z) / (b.z - a.z));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the linear interpolation ratio of <c>a</c> to <c>b</c> that <c>value</c> lies on.
|
||||
/// This is the t value that fulfills <c>value = lerp(a, b, t)</c>.
|
||||
/// </summary>
|
||||
public static Vector4 InverseLerp (Vector4 a, Vector4 b, Vector4 value) {
|
||||
return new Vector4(
|
||||
(value.x - a.x) / (b.x - a.x),
|
||||
(value.y - a.y) / (b.y - a.y),
|
||||
(value.z - a.z) / (b.z - a.z),
|
||||
(value.w - a.w) / (b.w - a.w));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ef2b5da9383ed474d895b702a9baf79e
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,42 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
namespace Spine.Unity {
|
||||
|
||||
/// <summary>
|
||||
/// TriState enum which can be used to replace and extend a bool variable by
|
||||
/// a third <c>UseGlobalSettings</c> state. Automatically maps serialized
|
||||
/// bool values to corresponding <c>Disable</c> and <c>Enable</c> states.
|
||||
/// </summary>
|
||||
public enum SettingsTriState {
|
||||
Disable,
|
||||
Enable,
|
||||
UseGlobalSetting
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8f6692d1b45ac11459207a012cafeb03
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,461 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
public static class SkeletonExtensions {
|
||||
|
||||
#region Colors
|
||||
const float ByteToFloat = 1f / 255f;
|
||||
public static Color GetColor (this Skeleton s) { return new Color(s.R, s.G, s.B, s.A); }
|
||||
public static Color GetColor (this RegionAttachment a) { return new Color(a.R, a.G, a.B, a.A); }
|
||||
public static Color GetColor (this MeshAttachment a) { return new Color(a.R, a.G, a.B, a.A); }
|
||||
public static Color GetColor (this Slot s) { return new Color(s.R, s.G, s.B, s.A); }
|
||||
public static Color GetColorTintBlack (this Slot s) { return new Color(s.R2, s.G2, s.B2, 1f); }
|
||||
|
||||
public static void SetColor (this Skeleton skeleton, Color color) {
|
||||
skeleton.A = color.a;
|
||||
skeleton.R = color.r;
|
||||
skeleton.G = color.g;
|
||||
skeleton.B = color.b;
|
||||
}
|
||||
|
||||
public static void SetColor (this Skeleton skeleton, Color32 color) {
|
||||
skeleton.A = color.a * ByteToFloat;
|
||||
skeleton.R = color.r * ByteToFloat;
|
||||
skeleton.G = color.g * ByteToFloat;
|
||||
skeleton.B = color.b * ByteToFloat;
|
||||
}
|
||||
|
||||
public static void SetColor (this Slot slot, Color color) {
|
||||
slot.A = color.a;
|
||||
slot.R = color.r;
|
||||
slot.G = color.g;
|
||||
slot.B = color.b;
|
||||
}
|
||||
|
||||
public static void SetColor (this Slot slot, Color32 color) {
|
||||
slot.A = color.a * ByteToFloat;
|
||||
slot.R = color.r * ByteToFloat;
|
||||
slot.G = color.g * ByteToFloat;
|
||||
slot.B = color.b * ByteToFloat;
|
||||
}
|
||||
|
||||
public static void SetColor (this RegionAttachment attachment, Color color) {
|
||||
attachment.A = color.a;
|
||||
attachment.R = color.r;
|
||||
attachment.G = color.g;
|
||||
attachment.B = color.b;
|
||||
}
|
||||
|
||||
public static void SetColor (this RegionAttachment attachment, Color32 color) {
|
||||
attachment.A = color.a * ByteToFloat;
|
||||
attachment.R = color.r * ByteToFloat;
|
||||
attachment.G = color.g * ByteToFloat;
|
||||
attachment.B = color.b * ByteToFloat;
|
||||
}
|
||||
|
||||
public static void SetColor (this MeshAttachment attachment, Color color) {
|
||||
attachment.A = color.a;
|
||||
attachment.R = color.r;
|
||||
attachment.G = color.g;
|
||||
attachment.B = color.b;
|
||||
}
|
||||
|
||||
public static void SetColor (this MeshAttachment attachment, Color32 color) {
|
||||
attachment.A = color.a * ByteToFloat;
|
||||
attachment.R = color.r * ByteToFloat;
|
||||
attachment.G = color.g * ByteToFloat;
|
||||
attachment.B = color.b * ByteToFloat;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Skeleton
|
||||
/// <summary>Sets the Skeleton's local scale using a UnityEngine.Vector2. If only individual components need to be set, set Skeleton.ScaleX or Skeleton.ScaleY.</summary>
|
||||
public static void SetLocalScale (this Skeleton skeleton, Vector2 scale) {
|
||||
skeleton.ScaleX = scale.x;
|
||||
skeleton.ScaleY = scale.y;
|
||||
}
|
||||
|
||||
/// <summary>Gets the internal bone matrix as a Unity bonespace-to-skeletonspace transformation matrix.</summary>
|
||||
public static Matrix4x4 GetMatrix4x4 (this Bone bone) {
|
||||
return new Matrix4x4 {
|
||||
m00 = bone.A,
|
||||
m01 = bone.B,
|
||||
m03 = bone.WorldX,
|
||||
m10 = bone.C,
|
||||
m11 = bone.D,
|
||||
m13 = bone.WorldY,
|
||||
m33 = 1
|
||||
};
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Bone
|
||||
/// <summary>Sets the bone's (local) X and Y according to a Vector2</summary>
|
||||
public static void SetLocalPosition (this Bone bone, Vector2 position) {
|
||||
bone.X = position.x;
|
||||
bone.Y = position.y;
|
||||
}
|
||||
|
||||
/// <summary>Sets the bone's (local) X and Y according to a Vector3. The z component is ignored.</summary>
|
||||
public static void SetLocalPosition (this Bone bone, Vector3 position) {
|
||||
bone.X = position.x;
|
||||
bone.Y = position.y;
|
||||
}
|
||||
|
||||
/// <summary>Gets the bone's local X and Y as a Vector2.</summary>
|
||||
public static Vector2 GetLocalPosition (this Bone bone) {
|
||||
return new Vector2(bone.X, bone.Y);
|
||||
}
|
||||
|
||||
/// <summary>Gets the position of the bone in Skeleton-space.</summary>
|
||||
public static Vector2 GetSkeletonSpacePosition (this Bone bone) {
|
||||
return new Vector2(bone.WorldX, bone.WorldY);
|
||||
}
|
||||
|
||||
/// <summary>Gets a local offset from the bone and converts it into Skeleton-space.</summary>
|
||||
public static Vector2 GetSkeletonSpacePosition (this Bone bone, Vector2 boneLocal) {
|
||||
Vector2 o;
|
||||
bone.LocalToWorld(boneLocal.x, boneLocal.y, out o.x, out o.y);
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>Gets the bone's Unity World position using its Spine GameObject Transform. UpdateWorldTransform needs to have been called for this to return the correct, updated value.</summary>
|
||||
public static Vector3 GetWorldPosition (this Bone bone, UnityEngine.Transform spineGameObjectTransform) {
|
||||
return spineGameObjectTransform.TransformPoint(new Vector3(bone.WorldX, bone.WorldY));
|
||||
}
|
||||
|
||||
public static Vector3 GetWorldPosition (this Bone bone, UnityEngine.Transform spineGameObjectTransform, float positionScale) {
|
||||
return spineGameObjectTransform.TransformPoint(new Vector3(bone.WorldX * positionScale, bone.WorldY * positionScale));
|
||||
}
|
||||
|
||||
/// <summary>Gets a skeleton space UnityEngine.Quaternion representation of bone.WorldRotationX.</summary>
|
||||
public static Quaternion GetQuaternion (this Bone bone) {
|
||||
float halfRotation = Mathf.Atan2(bone.C, bone.A) * 0.5f;
|
||||
return new Quaternion(0, 0, Mathf.Sin(halfRotation), Mathf.Cos(halfRotation));
|
||||
}
|
||||
|
||||
/// <summary>Gets a bone-local space UnityEngine.Quaternion representation of bone.rotation.</summary>
|
||||
public static Quaternion GetLocalQuaternion (this Bone bone) {
|
||||
float halfRotation = bone.Rotation * Mathf.Deg2Rad * 0.5f;
|
||||
return new Quaternion(0, 0, Mathf.Sin(halfRotation), Mathf.Cos(halfRotation));
|
||||
}
|
||||
|
||||
/// <summary>Returns the Skeleton's local scale as a UnityEngine.Vector2. If only individual components are needed, use Skeleton.ScaleX or Skeleton.ScaleY.</summary>
|
||||
public static Vector2 GetLocalScale (this Skeleton skeleton) {
|
||||
return new Vector2(skeleton.ScaleX, skeleton.ScaleY);
|
||||
}
|
||||
|
||||
/// <summary>Calculates a 2x2 Transformation Matrix that can convert a skeleton-space position to a bone-local position.</summary>
|
||||
public static void GetWorldToLocalMatrix (this Bone bone, out float ia, out float ib, out float ic, out float id) {
|
||||
float a = bone.A, b = bone.B, c = bone.C, d = bone.D;
|
||||
float invDet = 1 / (a * d - b * c);
|
||||
ia = invDet * d;
|
||||
ib = invDet * -b;
|
||||
ic = invDet * -c;
|
||||
id = invDet * a;
|
||||
}
|
||||
|
||||
/// <summary>UnityEngine.Vector2 override of Bone.WorldToLocal. This converts a skeleton-space position into a bone local position.</summary>
|
||||
public static Vector2 WorldToLocal (this Bone bone, Vector2 worldPosition) {
|
||||
Vector2 o;
|
||||
bone.WorldToLocal(worldPosition.x, worldPosition.y, out o.x, out o.y);
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>Sets the skeleton-space position of a bone.</summary>
|
||||
/// <returns>The local position in its parent bone space, or in skeleton space if it is the root bone.</returns>
|
||||
public static Vector2 SetPositionSkeletonSpace (this Bone bone, Vector2 skeletonSpacePosition) {
|
||||
if (bone.Parent == null) { // root bone
|
||||
bone.SetLocalPosition(skeletonSpacePosition);
|
||||
return skeletonSpacePosition;
|
||||
} else {
|
||||
Bone parent = bone.Parent;
|
||||
Vector2 parentLocal = parent.WorldToLocal(skeletonSpacePosition);
|
||||
bone.SetLocalPosition(parentLocal);
|
||||
return parentLocal;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Attachments
|
||||
public static Material GetMaterial (this Attachment a) {
|
||||
object rendererObject = null;
|
||||
IHasTextureRegion renderableAttachment = a as IHasTextureRegion;
|
||||
if (renderableAttachment != null)
|
||||
rendererObject = renderableAttachment.Region;
|
||||
|
||||
if (rendererObject == null)
|
||||
return null;
|
||||
|
||||
#if SPINE_TK2D
|
||||
return (rendererObject.GetType() == typeof(Material)) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject;
|
||||
#else
|
||||
return (Material)((AtlasRegion)rendererObject).page.rendererObject;
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>Fills a Vector2 buffer with local vertices.</summary>
|
||||
/// <param name="va">The VertexAttachment</param>
|
||||
/// <param name="slot">Slot where the attachment belongs.</param>
|
||||
/// <param name="buffer">Correctly-sized buffer. Use attachment's .WorldVerticesLength to get the correct size. If null, a new Vector2[] of the correct size will be allocated.</param>
|
||||
public static Vector2[] GetLocalVertices (this VertexAttachment va, Slot slot, Vector2[] buffer) {
|
||||
int floatsCount = va.WorldVerticesLength;
|
||||
int bufferTargetSize = floatsCount >> 1;
|
||||
buffer = buffer ?? new Vector2[bufferTargetSize];
|
||||
if (buffer.Length < bufferTargetSize) throw new System.ArgumentException(string.Format("Vector2 buffer too small. {0} requires an array of size {1}. Use the attachment's .WorldVerticesLength to get the correct size.", va.Name, floatsCount), "buffer");
|
||||
|
||||
if (va.Bones == null && slot.Deform.Count == 0) {
|
||||
float[] localVerts = va.Vertices;
|
||||
for (int i = 0; i < bufferTargetSize; i++) {
|
||||
int j = i * 2;
|
||||
buffer[i] = new Vector2(localVerts[j], localVerts[j + 1]);
|
||||
}
|
||||
} else {
|
||||
float[] floats = new float[floatsCount];
|
||||
va.ComputeWorldVertices(slot, floats);
|
||||
|
||||
Bone sb = slot.Bone;
|
||||
float ia, ib, ic, id, bwx = sb.WorldX, bwy = sb.WorldY;
|
||||
sb.GetWorldToLocalMatrix(out ia, out ib, out ic, out id);
|
||||
|
||||
for (int i = 0; i < bufferTargetSize; i++) {
|
||||
int j = i * 2;
|
||||
float x = floats[j] - bwx, y = floats[j + 1] - bwy;
|
||||
buffer[i] = new Vector2(x * ia + y * ib, x * ic + y * id);
|
||||
}
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/// <summary>Calculates world vertices and fills a Vector2 buffer.</summary>
|
||||
/// <param name="a">The VertexAttachment</param>
|
||||
/// <param name="slot">Slot where the attachment belongs.</param>
|
||||
/// <param name="buffer">Correctly-sized buffer. Use attachment's .WorldVerticesLength to get the correct size. If null, a new Vector2[] of the correct size will be allocated.</param>
|
||||
public static Vector2[] GetWorldVertices (this VertexAttachment a, Slot slot, Vector2[] buffer) {
|
||||
int worldVertsLength = a.WorldVerticesLength;
|
||||
int bufferTargetSize = worldVertsLength >> 1;
|
||||
buffer = buffer ?? new Vector2[bufferTargetSize];
|
||||
if (buffer.Length < bufferTargetSize) throw new System.ArgumentException(string.Format("Vector2 buffer too small. {0} requires an array of size {1}. Use the attachment's .WorldVerticesLength to get the correct size.", a.Name, worldVertsLength), "buffer");
|
||||
|
||||
float[] floats = new float[worldVertsLength];
|
||||
a.ComputeWorldVertices(slot, floats);
|
||||
|
||||
for (int i = 0, n = worldVertsLength >> 1; i < n; i++) {
|
||||
int j = i * 2;
|
||||
buffer[i] = new Vector2(floats[j], floats[j + 1]);
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/// <summary>Gets the PointAttachment's Unity World position using its Spine GameObject Transform.</summary>
|
||||
public static Vector3 GetWorldPosition (this PointAttachment attachment, Slot slot, Transform spineGameObjectTransform) {
|
||||
Vector3 skeletonSpacePosition;
|
||||
skeletonSpacePosition.z = 0;
|
||||
attachment.ComputeWorldPosition(slot.Bone, out skeletonSpacePosition.x, out skeletonSpacePosition.y);
|
||||
return spineGameObjectTransform.TransformPoint(skeletonSpacePosition);
|
||||
}
|
||||
|
||||
/// <summary>Gets the PointAttachment's Unity World position using its Spine GameObject Transform.</summary>
|
||||
public static Vector3 GetWorldPosition (this PointAttachment attachment, Bone bone, Transform spineGameObjectTransform) {
|
||||
Vector3 skeletonSpacePosition;
|
||||
skeletonSpacePosition.z = 0;
|
||||
attachment.ComputeWorldPosition(bone, out skeletonSpacePosition.x, out skeletonSpacePosition.y);
|
||||
return spineGameObjectTransform.TransformPoint(skeletonSpacePosition);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
namespace Spine {
|
||||
using System;
|
||||
|
||||
public struct BoneMatrix {
|
||||
public float a, b, c, d, x, y;
|
||||
|
||||
/// <summary>Recursively calculates a worldspace bone matrix based on BoneData.</summary>
|
||||
public static BoneMatrix CalculateSetupWorld (BoneData boneData) {
|
||||
if (boneData == null)
|
||||
return default(BoneMatrix);
|
||||
|
||||
// End condition: isRootBone
|
||||
if (boneData.Parent == null)
|
||||
return GetInheritedInternal(boneData, default(BoneMatrix));
|
||||
|
||||
BoneMatrix result = CalculateSetupWorld(boneData.Parent);
|
||||
return GetInheritedInternal(boneData, result);
|
||||
}
|
||||
|
||||
static BoneMatrix GetInheritedInternal (BoneData boneData, BoneMatrix parentMatrix) {
|
||||
BoneData parent = boneData.Parent;
|
||||
if (parent == null) return new BoneMatrix(boneData); // isRootBone
|
||||
|
||||
float pa = parentMatrix.a, pb = parentMatrix.b, pc = parentMatrix.c, pd = parentMatrix.d;
|
||||
BoneMatrix result = default(BoneMatrix);
|
||||
result.x = pa * boneData.X + pb * boneData.Y + parentMatrix.x;
|
||||
result.y = pc * boneData.X + pd * boneData.Y + parentMatrix.y;
|
||||
|
||||
switch (boneData.TransformMode) {
|
||||
case TransformMode.Normal: {
|
||||
float rotationY = boneData.Rotation + 90 + boneData.ShearY;
|
||||
float la = MathUtils.CosDeg(boneData.Rotation + boneData.ShearX) * boneData.ScaleX;
|
||||
float lb = MathUtils.CosDeg(rotationY) * boneData.ScaleY;
|
||||
float lc = MathUtils.SinDeg(boneData.Rotation + boneData.ShearX) * boneData.ScaleX;
|
||||
float ld = MathUtils.SinDeg(rotationY) * boneData.ScaleY;
|
||||
result.a = pa * la + pb * lc;
|
||||
result.b = pa * lb + pb * ld;
|
||||
result.c = pc * la + pd * lc;
|
||||
result.d = pc * lb + pd * ld;
|
||||
break;
|
||||
}
|
||||
case TransformMode.OnlyTranslation: {
|
||||
float rotationY = boneData.Rotation + 90 + boneData.ShearY;
|
||||
result.a = MathUtils.CosDeg(boneData.Rotation + boneData.ShearX) * boneData.ScaleX;
|
||||
result.b = MathUtils.CosDeg(rotationY) * boneData.ScaleY;
|
||||
result.c = MathUtils.SinDeg(boneData.Rotation + boneData.ShearX) * boneData.ScaleX;
|
||||
result.d = MathUtils.SinDeg(rotationY) * boneData.ScaleY;
|
||||
break;
|
||||
}
|
||||
case TransformMode.NoRotationOrReflection: {
|
||||
float s = pa * pa + pc * pc, prx;
|
||||
if (s > 0.0001f) {
|
||||
s = Math.Abs(pa * pd - pb * pc) / s;
|
||||
pb = pc * s;
|
||||
pd = pa * s;
|
||||
prx = MathUtils.Atan2(pc, pa) * MathUtils.RadDeg;
|
||||
} else {
|
||||
pa = 0;
|
||||
pc = 0;
|
||||
prx = 90 - MathUtils.Atan2(pd, pb) * MathUtils.RadDeg;
|
||||
}
|
||||
float rx = boneData.Rotation + boneData.ShearX - prx;
|
||||
float ry = boneData.Rotation + boneData.ShearY - prx + 90;
|
||||
float la = MathUtils.CosDeg(rx) * boneData.ScaleX;
|
||||
float lb = MathUtils.CosDeg(ry) * boneData.ScaleY;
|
||||
float lc = MathUtils.SinDeg(rx) * boneData.ScaleX;
|
||||
float ld = MathUtils.SinDeg(ry) * boneData.ScaleY;
|
||||
result.a = pa * la - pb * lc;
|
||||
result.b = pa * lb - pb * ld;
|
||||
result.c = pc * la + pd * lc;
|
||||
result.d = pc * lb + pd * ld;
|
||||
break;
|
||||
}
|
||||
case TransformMode.NoScale:
|
||||
case TransformMode.NoScaleOrReflection: {
|
||||
float cos = MathUtils.CosDeg(boneData.Rotation), sin = MathUtils.SinDeg(boneData.Rotation);
|
||||
float za = pa * cos + pb * sin;
|
||||
float zc = pc * cos + pd * sin;
|
||||
float s = (float)Math.Sqrt(za * za + zc * zc);
|
||||
if (s > 0.00001f)
|
||||
s = 1 / s;
|
||||
za *= s;
|
||||
zc *= s;
|
||||
s = (float)Math.Sqrt(za * za + zc * zc);
|
||||
float r = MathUtils.PI / 2 + MathUtils.Atan2(zc, za);
|
||||
float zb = MathUtils.Cos(r) * s;
|
||||
float zd = MathUtils.Sin(r) * s;
|
||||
float la = MathUtils.CosDeg(boneData.ShearX) * boneData.ScaleX;
|
||||
float lb = MathUtils.CosDeg(90 + boneData.ShearY) * boneData.ScaleY;
|
||||
float lc = MathUtils.SinDeg(boneData.ShearX) * boneData.ScaleX;
|
||||
float ld = MathUtils.SinDeg(90 + boneData.ShearY) * boneData.ScaleY;
|
||||
if (boneData.TransformMode != TransformMode.NoScaleOrReflection ? pa * pd - pb * pc < 0 : false) {
|
||||
zb = -zb;
|
||||
zd = -zd;
|
||||
}
|
||||
result.a = za * la + zb * lc;
|
||||
result.b = za * lb + zb * ld;
|
||||
result.c = zc * la + zd * lc;
|
||||
result.d = zc * lb + zd * ld;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Constructor for a local bone matrix based on Setup Pose BoneData.</summary>
|
||||
public BoneMatrix (BoneData boneData) {
|
||||
float rotationY = boneData.Rotation + 90 + boneData.ShearY;
|
||||
float rotationX = boneData.Rotation + boneData.ShearX;
|
||||
|
||||
a = MathUtils.CosDeg(rotationX) * boneData.ScaleX;
|
||||
c = MathUtils.SinDeg(rotationX) * boneData.ScaleX;
|
||||
b = MathUtils.CosDeg(rotationY) * boneData.ScaleY;
|
||||
d = MathUtils.SinDeg(rotationY) * boneData.ScaleY;
|
||||
x = boneData.X;
|
||||
y = boneData.Y;
|
||||
}
|
||||
|
||||
/// <summary>Constructor for a local bone matrix based on a bone instance's current pose.</summary>
|
||||
public BoneMatrix (Bone bone) {
|
||||
float rotationY = bone.Rotation + 90 + bone.ShearY;
|
||||
float rotationX = bone.Rotation + bone.ShearX;
|
||||
|
||||
a = MathUtils.CosDeg(rotationX) * bone.ScaleX;
|
||||
c = MathUtils.SinDeg(rotationX) * bone.ScaleX;
|
||||
b = MathUtils.CosDeg(rotationY) * bone.ScaleY;
|
||||
d = MathUtils.SinDeg(rotationY) * bone.ScaleY;
|
||||
x = bone.X;
|
||||
y = bone.Y;
|
||||
}
|
||||
|
||||
public BoneMatrix TransformMatrix (BoneMatrix local) {
|
||||
return new BoneMatrix {
|
||||
a = this.a * local.a + this.b * local.c,
|
||||
b = this.a * local.b + this.b * local.d,
|
||||
c = this.c * local.a + this.d * local.c,
|
||||
d = this.c * local.b + this.d * local.d,
|
||||
x = this.a * local.x + this.b * local.y + this.x,
|
||||
y = this.c * local.x + this.d * local.y + this.y
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public static class SpineSkeletonExtensions {
|
||||
public static bool IsWeighted (this VertexAttachment va) {
|
||||
return va.Bones != null && va.Bones.Length > 0;
|
||||
}
|
||||
|
||||
#region Transform Modes
|
||||
public static bool InheritsRotation (this TransformMode mode) {
|
||||
const int RotationBit = 0;
|
||||
return ((int)mode & (1U << RotationBit)) == 0;
|
||||
}
|
||||
|
||||
public static bool InheritsScale (this TransformMode mode) {
|
||||
const int ScaleBit = 1;
|
||||
return ((int)mode & (1U << ScaleBit)) == 0;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ea85c8f6a91a6ab45881b0dbdaabb7d0
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
@@ -0,0 +1,158 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity.AnimationTools {
|
||||
public static class TimelineExtensions {
|
||||
|
||||
/// <summary>Evaluates the resulting value of a TranslateTimeline at a given time.
|
||||
/// SkeletonData can be accessed from Skeleton.Data or from SkeletonDataAsset.GetSkeletonData.
|
||||
/// If no SkeletonData is provided, values are returned as difference to setup pose
|
||||
/// instead of absolute values.</summary>
|
||||
public static Vector2 Evaluate (this TranslateTimeline timeline, float time, SkeletonData skeletonData = null) {
|
||||
if (time < timeline.Frames[0]) return Vector2.zero;
|
||||
|
||||
float x, y;
|
||||
timeline.GetCurveValue(out x, out y, time);
|
||||
|
||||
if (skeletonData == null) {
|
||||
return new Vector2(x, y);
|
||||
} else {
|
||||
BoneData boneData = skeletonData.Bones.Items[timeline.BoneIndex];
|
||||
return new Vector2(boneData.X + x, boneData.Y + y);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Evaluates the resulting value of a pair of split translate timelines at a given time.
|
||||
/// SkeletonData can be accessed from Skeleton.Data or from SkeletonDataAsset.GetSkeletonData.
|
||||
/// If no SkeletonData is given, values are returned as difference to setup pose
|
||||
/// instead of absolute values.</summary>
|
||||
public static Vector2 Evaluate (TranslateXTimeline xTimeline, TranslateYTimeline yTimeline,
|
||||
float time, SkeletonData skeletonData = null) {
|
||||
|
||||
float x = 0, y = 0;
|
||||
if (xTimeline != null && time > xTimeline.Frames[0]) x = xTimeline.GetCurveValue(time);
|
||||
if (yTimeline != null && time > yTimeline.Frames[0]) y = yTimeline.GetCurveValue(time);
|
||||
|
||||
if (skeletonData == null) {
|
||||
return new Vector2(x, y);
|
||||
} else {
|
||||
BoneData[] bonesItems = skeletonData.Bones.Items;
|
||||
BoneData boneDataX = bonesItems[xTimeline.BoneIndex];
|
||||
BoneData boneDataY = bonesItems[yTimeline.BoneIndex];
|
||||
return new Vector2(boneDataX.X + x, boneDataY.Y + y);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Evaluates the resulting value of a RotateTimeline at a given time.
|
||||
/// SkeletonData can be accessed from Skeleton.Data or from SkeletonDataAsset.GetSkeletonData.
|
||||
/// If no SkeletonData is given, values are returned as difference to setup pose
|
||||
/// instead of absolute values.</summary>
|
||||
public static float Evaluate (this RotateTimeline timeline, float time, SkeletonData skeletonData = null) {
|
||||
if (time < timeline.Frames[0]) return 0f;
|
||||
|
||||
float rotation = timeline.GetCurveValue(time);
|
||||
if (skeletonData == null) {
|
||||
return rotation;
|
||||
} else {
|
||||
BoneData boneData = skeletonData.Bones.Items[timeline.BoneIndex];
|
||||
return (boneData.Rotation + rotation);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Evaluates the resulting X and Y translate mix values of a
|
||||
/// TransformConstraintTimeline at a given time.</summary>
|
||||
public static Vector2 EvaluateTranslateXYMix (this TransformConstraintTimeline timeline, float time) {
|
||||
if (time < timeline.Frames[0]) return Vector2.zero;
|
||||
|
||||
float rotate, mixX, mixY, scaleX, scaleY, shearY;
|
||||
timeline.GetCurveValue(out rotate, out mixX, out mixY, out scaleX, out scaleY, out shearY, time);
|
||||
return new Vector2(mixX, mixY);
|
||||
}
|
||||
|
||||
/// <summary>Evaluates the resulting rotate mix values of a
|
||||
/// TransformConstraintTimeline at a given time.</summary>
|
||||
public static float EvaluateRotateMix (this TransformConstraintTimeline timeline, float time) {
|
||||
if (time < timeline.Frames[0]) return 0;
|
||||
|
||||
float rotate, mixX, mixY, scaleX, scaleY, shearY;
|
||||
timeline.GetCurveValue(out rotate, out mixX, out mixY, out scaleX, out scaleY, out shearY, time);
|
||||
return rotate;
|
||||
}
|
||||
|
||||
/// <summary>Gets the translate timeline for a given boneIndex.
|
||||
/// You can get the boneIndex using SkeletonData.FindBone().Index.
|
||||
/// The root bone is always boneIndex 0.
|
||||
/// This will return null if a TranslateTimeline is not found.</summary>
|
||||
public static TranslateTimeline FindTranslateTimelineForBone (this Animation a, int boneIndex) {
|
||||
foreach (Timeline timeline in a.Timelines) {
|
||||
if (timeline.GetType().IsSubclassOf(typeof(TranslateTimeline)))
|
||||
continue;
|
||||
|
||||
TranslateTimeline translateTimeline = timeline as TranslateTimeline;
|
||||
if (translateTimeline != null && translateTimeline.BoneIndex == boneIndex)
|
||||
return translateTimeline;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Gets the IBoneTimeline timeline of a given type for a given boneIndex.
|
||||
/// You can get the boneIndex using SkeletonData.FindBoneIndex.
|
||||
/// The root bone is always boneIndex 0.
|
||||
/// This will return null if a timeline of the given type is not found.</summary>
|
||||
public static T FindTimelineForBone<T> (this Animation a, int boneIndex) where T : class, IBoneTimeline {
|
||||
foreach (Timeline timeline in a.Timelines) {
|
||||
T translateTimeline = timeline as T;
|
||||
if (translateTimeline != null && translateTimeline.BoneIndex == boneIndex)
|
||||
return translateTimeline;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Gets the transform constraint timeline for a given boneIndex.
|
||||
/// You can get the boneIndex using SkeletonData.FindBone().Index.
|
||||
/// The root bone is always boneIndex 0.
|
||||
/// This will return null if a TranslateTimeline is not found.</summary>
|
||||
public static TransformConstraintTimeline FindTransformConstraintTimeline (this Animation a, int transformConstraintIndex) {
|
||||
foreach (Timeline timeline in a.Timelines) {
|
||||
if (timeline.GetType().IsSubclassOf(typeof(TransformConstraintTimeline)))
|
||||
continue;
|
||||
|
||||
TransformConstraintTimeline transformConstraintTimeline = timeline as TransformConstraintTimeline;
|
||||
if (transformConstraintTimeline != null &&
|
||||
transformConstraintTimeline.TransformConstraintIndex == transformConstraintIndex)
|
||||
return transformConstraintTimeline;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 07807fefbff25484ba41b1d16911fb0e
|
||||
timeCreated: 1591974498
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,9 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 15ac4befbee15d845ac289de3ab6d3d4
|
||||
folderAsset: yes
|
||||
timeCreated: 1455486167
|
||||
licenseType: Free
|
||||
DefaultImporter:
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,106 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>
|
||||
/// Use this as a condition-blocking yield instruction for Unity Coroutines.
|
||||
/// The routine will pause until the AnimationState.TrackEntry fires any of the
|
||||
/// configured events.
|
||||
/// <p/>
|
||||
/// See the <see cref="http://esotericsoftware.com/spine-unity-events">Spine Unity Events documentation page</see>
|
||||
/// and <see cref="http://esotericsoftware.com/spine-api-reference#AnimationStateListener"/>
|
||||
/// for more information on when track events will be triggered.</summary>
|
||||
public class WaitForSpineAnimation : IEnumerator {
|
||||
|
||||
[Flags]
|
||||
public enum AnimationEventTypes {
|
||||
Start = 1,
|
||||
Interrupt = 2,
|
||||
End = 4,
|
||||
Dispose = 8,
|
||||
Complete = 16
|
||||
}
|
||||
|
||||
bool m_WasFired = false;
|
||||
|
||||
public WaitForSpineAnimation (Spine.TrackEntry trackEntry, AnimationEventTypes eventsToWaitFor) {
|
||||
SafeSubscribe(trackEntry, eventsToWaitFor);
|
||||
}
|
||||
|
||||
#region Reuse
|
||||
/// <summary>
|
||||
/// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure.
|
||||
/// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationComplete.</summary>
|
||||
public WaitForSpineAnimation NowWaitFor (Spine.TrackEntry trackEntry, AnimationEventTypes eventsToWaitFor) {
|
||||
SafeSubscribe(trackEntry, eventsToWaitFor);
|
||||
return this;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IEnumerator
|
||||
bool IEnumerator.MoveNext () {
|
||||
if (m_WasFired) {
|
||||
((IEnumerator)this).Reset(); // auto-reset for YieldInstruction reuse
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
void IEnumerator.Reset () { m_WasFired = false; }
|
||||
object IEnumerator.Current { get { return null; } }
|
||||
#endregion
|
||||
|
||||
protected void SafeSubscribe (Spine.TrackEntry trackEntry, AnimationEventTypes eventsToWaitFor) {
|
||||
if (trackEntry == null) {
|
||||
// Break immediately if trackEntry is null.
|
||||
Debug.LogWarning("TrackEntry was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
} else {
|
||||
if ((eventsToWaitFor & AnimationEventTypes.Start) != 0)
|
||||
trackEntry.Start += HandleComplete;
|
||||
if ((eventsToWaitFor & AnimationEventTypes.Interrupt) != 0)
|
||||
trackEntry.Interrupt += HandleComplete;
|
||||
if ((eventsToWaitFor & AnimationEventTypes.End) != 0)
|
||||
trackEntry.End += HandleComplete;
|
||||
if ((eventsToWaitFor & AnimationEventTypes.Dispose) != 0)
|
||||
trackEntry.Dispose += HandleComplete;
|
||||
if ((eventsToWaitFor & AnimationEventTypes.Complete) != 0)
|
||||
trackEntry.Complete += HandleComplete;
|
||||
}
|
||||
}
|
||||
|
||||
void HandleComplete (TrackEntry trackEntry) {
|
||||
m_WasFired = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d9be5adcaf0003849a1d181173c19635
|
||||
timeCreated: 1566289729
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,61 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using Spine;
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>
|
||||
/// Use this as a condition-blocking yield instruction for Unity Coroutines.
|
||||
/// The routine will pause until the AnimationState.TrackEntry fires its Complete event.
|
||||
/// It can be configured to trigger on the End event as well to cover interruption.
|
||||
/// <p/>
|
||||
/// See the <see cref="http://esotericsoftware.com/spine-unity-events">Spine Unity Events documentation page</see>
|
||||
/// and <see cref="http://esotericsoftware.com/spine-api-reference#AnimationStateListener"/>
|
||||
/// for more information on when track events will be triggered.</summary>
|
||||
public class WaitForSpineAnimationComplete : WaitForSpineAnimation, IEnumerator {
|
||||
|
||||
public WaitForSpineAnimationComplete (Spine.TrackEntry trackEntry, bool includeEndEvent = false) :
|
||||
base(trackEntry,
|
||||
includeEndEvent ? (AnimationEventTypes.Complete | AnimationEventTypes.End) : AnimationEventTypes.Complete) {
|
||||
}
|
||||
|
||||
#region Reuse
|
||||
/// <summary>
|
||||
/// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure.
|
||||
/// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationComplete.</summary>
|
||||
public WaitForSpineAnimationComplete NowWaitFor (Spine.TrackEntry trackEntry, bool includeEndEvent = false) {
|
||||
SafeSubscribe(trackEntry,
|
||||
includeEndEvent ? (AnimationEventTypes.Complete | AnimationEventTypes.End) : AnimationEventTypes.Complete);
|
||||
return this;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a807dd9fb79db3545b6c2859a2bbfc0b
|
||||
timeCreated: 1449704018
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,58 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using Spine;
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>
|
||||
/// Use this as a condition-blocking yield instruction for Unity Coroutines.
|
||||
/// The routine will pause until the AnimationState.TrackEntry fires its End event.
|
||||
/// <p/>
|
||||
/// See the <see cref="http://esotericsoftware.com/spine-unity-events">Spine Unity Events documentation page</see>
|
||||
/// and <see cref="http://esotericsoftware.com/spine-api-reference#AnimationStateListener"/>
|
||||
/// for more information on when track events will be triggered.</summary>
|
||||
public class WaitForSpineAnimationEnd : WaitForSpineAnimation, IEnumerator {
|
||||
|
||||
public WaitForSpineAnimationEnd (Spine.TrackEntry trackEntry) :
|
||||
base(trackEntry, AnimationEventTypes.End) {
|
||||
}
|
||||
|
||||
#region Reuse
|
||||
/// <summary>
|
||||
/// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure.
|
||||
/// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationComplete.</summary>
|
||||
public WaitForSpineAnimationEnd NowWaitFor (Spine.TrackEntry trackEntry) {
|
||||
SafeSubscribe(trackEntry, AnimationEventTypes.End);
|
||||
return this;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3c5a5fe930d1ab24da154d76b24c2747
|
||||
timeCreated: 1566288961
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,159 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using Spine;
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>
|
||||
/// Use this as a condition-blocking yield instruction for Unity Coroutines.
|
||||
/// The routine will pause until the AnimationState fires an event matching the given event name or EventData reference.</summary>
|
||||
public class WaitForSpineEvent : IEnumerator {
|
||||
|
||||
Spine.EventData m_TargetEvent;
|
||||
string m_EventName;
|
||||
Spine.AnimationState m_AnimationState;
|
||||
|
||||
bool m_WasFired = false;
|
||||
bool m_unsubscribeAfterFiring = false;
|
||||
|
||||
#region Constructors
|
||||
void Subscribe (Spine.AnimationState state, Spine.EventData eventDataReference, bool unsubscribe) {
|
||||
if (state == null) {
|
||||
Debug.LogWarning("AnimationState argument was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
return;
|
||||
} else if (eventDataReference == null) {
|
||||
Debug.LogWarning("eventDataReference argument was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
return;
|
||||
}
|
||||
|
||||
m_AnimationState = state;
|
||||
m_TargetEvent = eventDataReference;
|
||||
state.Event += HandleAnimationStateEvent;
|
||||
|
||||
m_unsubscribeAfterFiring = unsubscribe;
|
||||
|
||||
}
|
||||
|
||||
void SubscribeByName (Spine.AnimationState state, string eventName, bool unsubscribe) {
|
||||
if (state == null) {
|
||||
Debug.LogWarning("AnimationState argument was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
return;
|
||||
} else if (string.IsNullOrEmpty(eventName)) {
|
||||
Debug.LogWarning("eventName argument was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
return;
|
||||
}
|
||||
|
||||
m_AnimationState = state;
|
||||
m_EventName = eventName;
|
||||
state.Event += HandleAnimationStateEventByName;
|
||||
|
||||
m_unsubscribeAfterFiring = unsubscribe;
|
||||
}
|
||||
|
||||
public WaitForSpineEvent (Spine.AnimationState state, Spine.EventData eventDataReference, bool unsubscribeAfterFiring = true) {
|
||||
Subscribe(state, eventDataReference, unsubscribeAfterFiring);
|
||||
}
|
||||
|
||||
public WaitForSpineEvent (SkeletonAnimation skeletonAnimation, Spine.EventData eventDataReference, bool unsubscribeAfterFiring = true) {
|
||||
// If skeletonAnimation is invalid, its state will be null. Subscribe handles null states just fine.
|
||||
Subscribe(skeletonAnimation.state, eventDataReference, unsubscribeAfterFiring);
|
||||
}
|
||||
|
||||
public WaitForSpineEvent (Spine.AnimationState state, string eventName, bool unsubscribeAfterFiring = true) {
|
||||
SubscribeByName(state, eventName, unsubscribeAfterFiring);
|
||||
}
|
||||
|
||||
public WaitForSpineEvent (SkeletonAnimation skeletonAnimation, string eventName, bool unsubscribeAfterFiring = true) {
|
||||
// If skeletonAnimation is invalid, its state will be null. Subscribe handles null states just fine.
|
||||
SubscribeByName(skeletonAnimation.state, eventName, unsubscribeAfterFiring);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Event Handlers
|
||||
void HandleAnimationStateEventByName (Spine.TrackEntry trackEntry, Spine.Event e) {
|
||||
m_WasFired |= (e.Data.Name == m_EventName); // Check event name string match.
|
||||
if (m_WasFired && m_unsubscribeAfterFiring)
|
||||
m_AnimationState.Event -= HandleAnimationStateEventByName; // Unsubscribe after correct event fires.
|
||||
}
|
||||
|
||||
void HandleAnimationStateEvent (Spine.TrackEntry trackEntry, Spine.Event e) {
|
||||
m_WasFired |= (e.Data == m_TargetEvent); // Check event data reference match.
|
||||
if (m_WasFired && m_unsubscribeAfterFiring)
|
||||
m_AnimationState.Event -= HandleAnimationStateEvent; // Usubscribe after correct event fires.
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Reuse
|
||||
/// <summary>
|
||||
/// By default, WaitForSpineEvent will unsubscribe from the event immediately after it fires a correct matching event.
|
||||
/// If you want to reuse this WaitForSpineEvent instance on the same event, you can set this to false.</summary>
|
||||
public bool WillUnsubscribeAfterFiring { get { return m_unsubscribeAfterFiring; } set { m_unsubscribeAfterFiring = value; } }
|
||||
|
||||
public WaitForSpineEvent NowWaitFor (Spine.AnimationState state, Spine.EventData eventDataReference, bool unsubscribeAfterFiring = true) {
|
||||
((IEnumerator)this).Reset();
|
||||
Clear(state);
|
||||
Subscribe(state, eventDataReference, unsubscribeAfterFiring);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public WaitForSpineEvent NowWaitFor (Spine.AnimationState state, string eventName, bool unsubscribeAfterFiring = true) {
|
||||
((IEnumerator)this).Reset();
|
||||
Clear(state);
|
||||
SubscribeByName(state, eventName, unsubscribeAfterFiring);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
void Clear (Spine.AnimationState state) {
|
||||
state.Event -= HandleAnimationStateEvent;
|
||||
state.Event -= HandleAnimationStateEventByName;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IEnumerator
|
||||
bool IEnumerator.MoveNext () {
|
||||
if (m_WasFired) {
|
||||
((IEnumerator)this).Reset(); // auto-reset for YieldInstruction reuse
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
void IEnumerator.Reset () { m_WasFired = false; }
|
||||
object IEnumerator.Current { get { return null; } }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fc166d883db083e469872998172f2d38
|
||||
timeCreated: 1449701857
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,85 @@
|
||||
/******************************************************************************
|
||||
* Spine Runtimes License Agreement
|
||||
* Last updated July 28, 2023. Replaces all prior versions.
|
||||
*
|
||||
* Copyright (c) 2013-2023, Esoteric Software LLC
|
||||
*
|
||||
* Integration of the Spine Runtimes into software or otherwise creating
|
||||
* derivative works of the Spine Runtimes is permitted under the terms and
|
||||
* conditions of Section 2 of the Spine Editor License Agreement:
|
||||
* http://esotericsoftware.com/spine-editor-license
|
||||
*
|
||||
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
|
||||
* otherwise create derivative works of the Spine Runtimes (collectively,
|
||||
* "Products"), provided that each user of the Products must obtain their own
|
||||
* Spine Editor license and redistribution of the Products in any form must
|
||||
* include this license and copyright notice.
|
||||
*
|
||||
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 LLC 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 THE
|
||||
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*****************************************************************************/
|
||||
|
||||
using Spine;
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Spine.Unity {
|
||||
/// <summary>
|
||||
/// Use this as a condition-blocking yield instruction for Unity Coroutines.
|
||||
/// The routine will pause until the AnimationState.TrackEntry fires its End event.</summary>
|
||||
public class WaitForSpineTrackEntryEnd : IEnumerator {
|
||||
|
||||
bool m_WasFired = false;
|
||||
|
||||
public WaitForSpineTrackEntryEnd (Spine.TrackEntry trackEntry) {
|
||||
SafeSubscribe(trackEntry);
|
||||
}
|
||||
|
||||
void HandleEnd (TrackEntry trackEntry) {
|
||||
m_WasFired = true;
|
||||
}
|
||||
|
||||
void SafeSubscribe (Spine.TrackEntry trackEntry) {
|
||||
if (trackEntry == null) {
|
||||
// Break immediately if trackEntry is null.
|
||||
Debug.LogWarning("TrackEntry was null. Coroutine will continue immediately.");
|
||||
m_WasFired = true;
|
||||
} else {
|
||||
trackEntry.End += HandleEnd;
|
||||
}
|
||||
}
|
||||
|
||||
#region Reuse
|
||||
/// <summary>
|
||||
/// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure.
|
||||
/// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationEnd.</summary>
|
||||
public WaitForSpineTrackEntryEnd NowWaitFor (Spine.TrackEntry trackEntry) {
|
||||
SafeSubscribe(trackEntry);
|
||||
return this;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IEnumerator
|
||||
bool IEnumerator.MoveNext () {
|
||||
if (m_WasFired) {
|
||||
((IEnumerator)this).Reset(); // auto-reset for YieldInstruction reuse
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
void IEnumerator.Reset () { m_WasFired = false; }
|
||||
object IEnumerator.Current { get { return null; } }
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8036c6c2897d2764db92f632d2aef568
|
||||
timeCreated: 1480672707
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Reference in New Issue
Block a user