This commit is contained in:
Nim XD
2024-08-27 21:01:33 +05:30
parent 99eaf514fd
commit 121a1b7c73
31803 changed files with 623461 additions and 623399 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,108 +1,108 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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>
/// <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) {
var atlasRegion = premultiplyAlpha ? sprite.ToAtlasRegionPMAClone(sourceMaterial) : 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) {
var regionAttachment = o as RegionAttachment;
if (regionAttachment != null)
scale = regionAttachment.Width / regionAttachment.RegionOriginalWidth;
}
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) {
var regionAttachment = o as RegionAttachment;
if (regionAttachment != null) {
RegionAttachment newAttachment = (RegionAttachment)regionAttachment.Copy();
newAttachment.SetRegion(atlasRegion, false);
if (!useOriginalRegionSize) {
newAttachment.Width = atlasRegion.width * scale;
newAttachment.Height = atlasRegion.height * scale;
}
newAttachment.UpdateOffset();
return newAttachment;
} else {
var meshAttachment = o as MeshAttachment;
if (meshAttachment != null) {
MeshAttachment newAttachment = cloneMeshAsLinked ? meshAttachment.NewLinkedMesh() : (MeshAttachment)meshAttachment.Copy();
newAttachment.SetRegion(atlasRegion);
return newAttachment;
}
}
return o.Copy();
}
#endregion
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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>
/// <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) {
var atlasRegion = premultiplyAlpha ? sprite.ToAtlasRegionPMAClone(sourceMaterial) : 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) {
var regionAttachment = o as RegionAttachment;
if (regionAttachment != null)
scale = regionAttachment.Width / regionAttachment.RegionOriginalWidth;
}
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) {
var regionAttachment = o as RegionAttachment;
if (regionAttachment != null) {
RegionAttachment newAttachment = (RegionAttachment)regionAttachment.Copy();
newAttachment.SetRegion(atlasRegion, false);
if (!useOriginalRegionSize) {
newAttachment.Width = atlasRegion.width * scale;
newAttachment.Height = atlasRegion.height * scale;
}
newAttachment.UpdateOffset();
return newAttachment;
} else {
var meshAttachment = o as MeshAttachment;
if (meshAttachment != null) {
MeshAttachment newAttachment = cloneMeshAsLinked ? meshAttachment.NewLinkedMesh() : (MeshAttachment)meshAttachment.Copy();
newAttachment.SetRegion(atlasRegion);
return newAttachment;
}
}
return o.Copy();
}
#endregion
}
}

View File

@@ -1,189 +1,189 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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 SetRegion
/// <summary>
/// Tries to set the region (image) of a renderable attachment. If the attachment is not renderable, nothing is applied.</summary>
public static void SetRegion (this Attachment attachment, AtlasRegion region, bool updateOffset = true) {
var regionAttachment = attachment as RegionAttachment;
if (regionAttachment != null)
regionAttachment.SetRegion(region, updateOffset);
var meshAttachment = attachment as MeshAttachment;
if (meshAttachment != null)
meshAttachment.SetRegion(region, updateOffset);
}
/// <summary>Sets the region (image) of a RegionAttachment</summary>
public static void SetRegion (this RegionAttachment attachment, AtlasRegion region, bool updateOffset = true) {
if (region == null) throw new System.ArgumentNullException("region");
// (AtlasAttachmentLoader.cs)
attachment.RendererObject = region;
attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.degrees);
attachment.RegionOffsetX = region.offsetX;
attachment.RegionOffsetY = region.offsetY;
attachment.RegionWidth = region.width;
attachment.RegionHeight = region.height;
attachment.RegionOriginalWidth = region.originalWidth;
attachment.RegionOriginalHeight = region.originalHeight;
if (updateOffset) attachment.UpdateOffset();
}
/// <summary>Sets the region (image) of a MeshAttachment</summary>
public static void SetRegion (this MeshAttachment attachment, AtlasRegion region, bool updateUVs = true) {
if (region == null) throw new System.ArgumentNullException("region");
// (AtlasAttachmentLoader.cs)
attachment.RendererObject = region;
attachment.RegionU = region.u;
attachment.RegionV = region.v;
attachment.RegionU2 = region.u2;
attachment.RegionV2 = region.v2;
attachment.RegionDegrees = region.degrees;
attachment.RegionOffsetX = region.offsetX;
attachment.RegionOffsetY = region.offsetY;
attachment.RegionWidth = region.width;
attachment.RegionHeight = region.height;
attachment.RegionOriginalWidth = region.originalWidth;
attachment.RegionOriginalHeight = region.originalHeight;
if (updateUVs) attachment.UpdateUVs();
}
#endregion
#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");
var region = sprite.ToAtlasRegion(page);
var 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");
var region = sprite.ToAtlasRegionPMAClone(shader, textureFormat, mipmaps, materialPropertySource);
var 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)
var attachment = new RegionAttachment(attachmentName);
attachment.RendererObject = region;
attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.degrees);
attachment.RegionOffsetX = region.offsetX;
attachment.RegionOffsetY = region.offsetY;
attachment.RegionWidth = region.width;
attachment.RegionHeight = region.height;
attachment.RegionOriginalWidth = region.originalWidth;
attachment.RegionOriginalHeight = region.originalHeight;
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.
attachment.Width = attachment.RegionOriginalWidth * scale;
attachment.Height = attachment.RegionOriginalHeight * scale;
attachment.SetColor(Color.white);
attachment.UpdateOffset();
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
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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 SetRegion
/// <summary>
/// Tries to set the region (image) of a renderable attachment. If the attachment is not renderable, nothing is applied.</summary>
public static void SetRegion (this Attachment attachment, AtlasRegion region, bool updateOffset = true) {
var regionAttachment = attachment as RegionAttachment;
if (regionAttachment != null)
regionAttachment.SetRegion(region, updateOffset);
var meshAttachment = attachment as MeshAttachment;
if (meshAttachment != null)
meshAttachment.SetRegion(region, updateOffset);
}
/// <summary>Sets the region (image) of a RegionAttachment</summary>
public static void SetRegion (this RegionAttachment attachment, AtlasRegion region, bool updateOffset = true) {
if (region == null) throw new System.ArgumentNullException("region");
// (AtlasAttachmentLoader.cs)
attachment.RendererObject = region;
attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.degrees);
attachment.RegionOffsetX = region.offsetX;
attachment.RegionOffsetY = region.offsetY;
attachment.RegionWidth = region.width;
attachment.RegionHeight = region.height;
attachment.RegionOriginalWidth = region.originalWidth;
attachment.RegionOriginalHeight = region.originalHeight;
if (updateOffset) attachment.UpdateOffset();
}
/// <summary>Sets the region (image) of a MeshAttachment</summary>
public static void SetRegion (this MeshAttachment attachment, AtlasRegion region, bool updateUVs = true) {
if (region == null) throw new System.ArgumentNullException("region");
// (AtlasAttachmentLoader.cs)
attachment.RendererObject = region;
attachment.RegionU = region.u;
attachment.RegionV = region.v;
attachment.RegionU2 = region.u2;
attachment.RegionV2 = region.v2;
attachment.RegionDegrees = region.degrees;
attachment.RegionOffsetX = region.offsetX;
attachment.RegionOffsetY = region.offsetY;
attachment.RegionWidth = region.width;
attachment.RegionHeight = region.height;
attachment.RegionOriginalWidth = region.originalWidth;
attachment.RegionOriginalHeight = region.originalHeight;
if (updateUVs) attachment.UpdateUVs();
}
#endregion
#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");
var region = sprite.ToAtlasRegion(page);
var 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");
var region = sprite.ToAtlasRegionPMAClone(shader, textureFormat, mipmaps, materialPropertySource);
var 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)
var attachment = new RegionAttachment(attachmentName);
attachment.RendererObject = region;
attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.degrees);
attachment.RegionOffsetX = region.offsetX;
attachment.RegionOffsetY = region.offsetY;
attachment.RegionWidth = region.width;
attachment.RegionHeight = region.height;
attachment.RegionOriginalWidth = region.originalWidth;
attachment.RegionOriginalHeight = region.originalHeight;
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.
attachment.Width = attachment.RegionOriginalWidth * scale;
attachment.Height = attachment.RegionOriginalHeight * scale;
attachment.SetColor(Color.white);
attachment.UpdateOffset();
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
}
}

View File

@@ -1,42 +1,42 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2022, 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
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2022, 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

View File

@@ -1,337 +1,337 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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 'SkeletonGraphicDefault' material and change settings at the duplicate to not affect all instances.";
public static bool IsMaterialSetupProblematic (SkeletonRenderer renderer, ref string errorMessage) {
var materials = renderer.GetComponent<Renderer>().sharedMaterials;
bool isProblematic = false;
foreach (var 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) {
var material = skeletonGraphic.material;
bool isProblematic = false;
if (material) {
isProblematic |= IsMaterialSetupProblematic(material, ref errorMessage);
var 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;
}
}
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
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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 'SkeletonGraphicDefault' material and change settings at the duplicate to not affect all instances.";
public static bool IsMaterialSetupProblematic (SkeletonRenderer renderer, ref string errorMessage) {
var materials = renderer.GetComponent<Renderer>().sharedMaterials;
bool isProblematic = false;
foreach (var 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) {
var material = skeletonGraphic.material;
bool isProblematic = false;
if (material) {
isProblematic |= IsMaterialSetupProblematic(material, ref errorMessage);
var 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;
}
}
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

View File

@@ -1,42 +1,42 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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
}
}

View File

@@ -1,461 +1,461 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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) {
var 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) {
var 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 {
var 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;
var renderableAttachment = a as IHasRendererObject;
if (renderableAttachment != null)
rendererObject = renderableAttachment.RendererObject;
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) {
var localVerts = va.Vertices;
for (int i = 0; i < bufferTargetSize; i++) {
int j = i * 2;
buffer[i] = new Vector2(localVerts[j], localVerts[j + 1]);
}
} else {
var 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");
var 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) {
var 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
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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) {
var 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) {
var 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 {
var 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;
var renderableAttachment = a as IHasRendererObject;
if (renderableAttachment != null)
rendererObject = renderableAttachment.RendererObject;
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) {
var localVerts = va.Vertices;
for (int i = 0; i < bufferTargetSize; i++) {
int j = i * 2;
buffer[i] = new Vector2(localVerts[j], localVerts[j + 1]);
}
} else {
var 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");
var 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) {
var 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
}
}

View File

@@ -1,105 +1,105 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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 given, 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 {
var bonesItems = skeletonData.Bones.Items;
BoneData boneDataX = bonesItems[xTimeline.BoneIndex];
BoneData boneDataY = bonesItems[yTimeline.BoneIndex];
return new Vector2(boneDataX.X + x, boneDataY.Y + y);
}
}
/// <summary>Gets the translate timeline 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 TranslateTimeline is not found.</summary>
public static TranslateTimeline FindTranslateTimelineForBone (this Animation a, int boneIndex) {
foreach (var timeline in a.Timelines) {
if (timeline.GetType().IsSubclassOf(typeof(TranslateTimeline)))
continue;
var 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 (var timeline in a.Timelines) {
T translateTimeline = timeline as T;
if (translateTimeline != null && translateTimeline.BoneIndex == boneIndex)
return translateTimeline;
}
return null;
}
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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 given, 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 {
var bonesItems = skeletonData.Bones.Items;
BoneData boneDataX = bonesItems[xTimeline.BoneIndex];
BoneData boneDataY = bonesItems[yTimeline.BoneIndex];
return new Vector2(boneDataX.X + x, boneDataY.Y + y);
}
}
/// <summary>Gets the translate timeline 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 TranslateTimeline is not found.</summary>
public static TranslateTimeline FindTranslateTimelineForBone (this Animation a, int boneIndex) {
foreach (var timeline in a.Timelines) {
if (timeline.GetType().IsSubclassOf(typeof(TranslateTimeline)))
continue;
var 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 (var timeline in a.Timelines) {
T translateTimeline = timeline as T;
if (translateTimeline != null && translateTimeline.BoneIndex == boneIndex)
return translateTimeline;
}
return null;
}
}
}

View File

@@ -1,106 +1,106 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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;
}
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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;
}
}
}

View File

@@ -1,61 +1,61 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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
}
}

View File

@@ -1,58 +1,58 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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
}
}

View File

@@ -1,159 +1,159 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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
}
}

View File

@@ -1,85 +1,85 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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
}
}
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, 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
}
}