Merge branch '3.6' into 3.7-beta

This commit is contained in:
badlogic 2018-03-14 10:24:44 +01:00
commit 4c104ef885
22 changed files with 1140 additions and 990 deletions

View File

@ -174,7 +174,7 @@ namespace Spine {
protected const float LINEAR = 0, STEPPED = 1, BEZIER = 2; protected const float LINEAR = 0, STEPPED = 1, BEZIER = 2;
protected const int BEZIER_SIZE = 10 * 2 - 1; protected const int BEZIER_SIZE = 10 * 2 - 1;
private float[] curves; // type, x, y, ... internal float[] curves; // type, x, y, ...
public int FrameCount { get { return curves.Length / BEZIER_SIZE + 1; } } public int FrameCount { get { return curves.Length / BEZIER_SIZE + 1; } }
public CurveTimeline (int frameCount) { public CurveTimeline (int frameCount) {
@ -689,17 +689,19 @@ namespace Spine {
protected const int PREV_R2 = -3, PREV_G2 = -2, PREV_B2 = -1; protected const int PREV_R2 = -3, PREV_G2 = -2, PREV_B2 = -1;
protected const int R = 1, G = 2, B = 3, A = 4, R2 = 5, G2 = 6, B2 = 7; protected const int R = 1, G = 2, B = 3, A = 4, R2 = 5, G2 = 6, B2 = 7;
internal float[] frames; // time, r, g, b, a, r2, g2, b2, ...
public float[] Frames { get { return frames; } }
internal int slotIndex; internal int slotIndex;
internal float[] frames; // time, r, g, b, a, r2, g2, b2, ...
public int SlotIndex { public int SlotIndex {
get { return slotIndex; } get { return slotIndex; }
set { set {
if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); if (value < 0)
throw new ArgumentOutOfRangeException("index must be >= 0.");
slotIndex = value; slotIndex = value;
} }
} }
public float[] Frames { get { return frames; } }
override public int PropertyId { override public int PropertyId {
get { return ((int)TimelineType.TwoColor << 24) + slotIndex; } get { return ((int)TimelineType.TwoColor << 24) + slotIndex; }
@ -827,11 +829,11 @@ namespace Spine {
public class AttachmentTimeline : Timeline { public class AttachmentTimeline : Timeline {
internal int slotIndex; internal int slotIndex;
internal float[] frames; internal float[] frames;
private String[] attachmentNames; internal string[] attachmentNames;
public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } } public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, ... public float[] Frames { get { return frames; } set { frames = value; } } // time, ...
public String[] AttachmentNames { get { return attachmentNames; } set { attachmentNames = value; } } public string[] AttachmentNames { get { return attachmentNames; } set { attachmentNames = value; } }
public int FrameCount { get { return frames.Length; } } public int FrameCount { get { return frames.Length; } }
public int PropertyId { public int PropertyId {

View File

@ -79,14 +79,22 @@ namespace Spine {
public void UpdateOffset () { public void UpdateOffset () {
float width = this.width; float width = this.width;
float height = this.height; float height = this.height;
float localX2 = width * 0.5f;
float localY2 = height * 0.5f;
float localX = -localX2;
float localY = -localY2;
if (regionOriginalWidth != 0) { // if (region != null)
localX += regionOffsetX / regionOriginalWidth * width;
localY += regionOffsetY / regionOriginalHeight * height;
localX2 -= (regionOriginalWidth - regionOffsetX - regionWidth) / regionOriginalWidth * width;
localY2 -= (regionOriginalHeight - regionOffsetY - regionHeight) / regionOriginalHeight * height;
}
float scaleX = this.scaleX; float scaleX = this.scaleX;
float scaleY = this.scaleY; float scaleY = this.scaleY;
float regionScaleX = width / regionOriginalWidth * scaleX; localX *= scaleX;
float regionScaleY = height / regionOriginalHeight * scaleY; localY *= scaleY;
float localX = -width / 2 * scaleX + regionOffsetX * regionScaleX; localX2 *= scaleX;
float localY = -height / 2 * scaleY + regionOffsetY * regionScaleY; localY2 *= scaleY;
float localX2 = localX + regionWidth * regionScaleX;
float localY2 = localY + regionHeight * regionScaleY;
float rotation = this.rotation; float rotation = this.rotation;
float cos = MathUtils.CosDeg(rotation); float cos = MathUtils.CosDeg(rotation);
float sin = MathUtils.SinDeg(rotation); float sin = MathUtils.SinDeg(rotation);

View File

@ -69,11 +69,11 @@ namespace Spine {
} }
} }
public SkeletonData ReadSkeletonData (String path) { public SkeletonData ReadSkeletonData (string path) {
return this.ReadFile(path).Result; return this.ReadFile(path).Result;
} }
#else #else
public SkeletonData ReadSkeletonData (String path) { public SkeletonData ReadSkeletonData (string path) {
#if WINDOWS_PHONE #if WINDOWS_PHONE
using (var reader = new StreamReader(Microsoft.Xna.Framework.TitleContainer.OpenStream(path))) { using (var reader = new StreamReader(Microsoft.Xna.Framework.TitleContainer.OpenStream(path))) {
#else #else
@ -89,17 +89,17 @@ namespace Spine {
public SkeletonData ReadSkeletonData (TextReader reader) { public SkeletonData ReadSkeletonData (TextReader reader) {
if (reader == null) throw new ArgumentNullException("reader", "reader cannot be null."); if (reader == null) throw new ArgumentNullException("reader", "reader cannot be null.");
var scale = this.Scale; float scale = this.Scale;
var skeletonData = new SkeletonData(); var skeletonData = new SkeletonData();
var root = Json.Deserialize(reader) as Dictionary<String, Object>; var root = Json.Deserialize(reader) as Dictionary<string, Object>;
if (root == null) throw new Exception("Invalid JSON."); if (root == null) throw new Exception("Invalid JSON.");
// Skeleton. // Skeleton.
if (root.ContainsKey("skeleton")) { if (root.ContainsKey("skeleton")) {
var skeletonMap = (Dictionary<String, Object>)root["skeleton"]; var skeletonMap = (Dictionary<string, Object>)root["skeleton"];
skeletonData.hash = (String)skeletonMap["hash"]; skeletonData.hash = (string)skeletonMap["hash"];
skeletonData.version = (String)skeletonMap["spine"]; skeletonData.version = (string)skeletonMap["spine"];
skeletonData.width = GetFloat(skeletonMap, "width", 0); skeletonData.width = GetFloat(skeletonMap, "width", 0);
skeletonData.height = GetFloat(skeletonMap, "height", 0); skeletonData.height = GetFloat(skeletonMap, "height", 0);
skeletonData.fps = GetFloat(skeletonMap, "fps", 0); skeletonData.fps = GetFloat(skeletonMap, "fps", 0);
@ -108,14 +108,14 @@ namespace Spine {
} }
// Bones. // Bones.
foreach (Dictionary<String, Object> boneMap in (List<Object>)root["bones"]) { foreach (Dictionary<string, Object> boneMap in (List<Object>)root["bones"]) {
BoneData parent = null; BoneData parent = null;
if (boneMap.ContainsKey("parent")) { if (boneMap.ContainsKey("parent")) {
parent = skeletonData.FindBone((String)boneMap["parent"]); parent = skeletonData.FindBone((string)boneMap["parent"]);
if (parent == null) if (parent == null)
throw new Exception("Parent bone not found: " + boneMap["parent"]); throw new Exception("Parent bone not found: " + boneMap["parent"]);
} }
var data = new BoneData(skeletonData.Bones.Count, (String)boneMap["name"], parent); var data = new BoneData(skeletonData.Bones.Count, (string)boneMap["name"], parent);
data.length = GetFloat(boneMap, "length", 0) * scale; data.length = GetFloat(boneMap, "length", 0) * scale;
data.x = GetFloat(boneMap, "x", 0) * scale; data.x = GetFloat(boneMap, "x", 0) * scale;
data.y = GetFloat(boneMap, "y", 0) * scale; data.y = GetFloat(boneMap, "y", 0) * scale;
@ -133,15 +133,15 @@ namespace Spine {
// Slots. // Slots.
if (root.ContainsKey("slots")) { if (root.ContainsKey("slots")) {
foreach (Dictionary<String, Object> slotMap in (List<Object>)root["slots"]) { foreach (Dictionary<string, Object> slotMap in (List<Object>)root["slots"]) {
var slotName = (String)slotMap["name"]; var slotName = (string)slotMap["name"];
var boneName = (String)slotMap["bone"]; var boneName = (string)slotMap["bone"];
BoneData boneData = skeletonData.FindBone(boneName); BoneData boneData = skeletonData.FindBone(boneName);
if (boneData == null) throw new Exception("Slot bone not found: " + boneName); if (boneData == null) throw new Exception("Slot bone not found: " + boneName);
var data = new SlotData(skeletonData.Slots.Count, slotName, boneData); var data = new SlotData(skeletonData.Slots.Count, slotName, boneData);
if (slotMap.ContainsKey("color")) { if (slotMap.ContainsKey("color")) {
var color = (String)slotMap["color"]; string color = (string)slotMap["color"];
data.r = ToColor(color, 0); data.r = ToColor(color, 0);
data.g = ToColor(color, 1); data.g = ToColor(color, 1);
data.b = ToColor(color, 2); data.b = ToColor(color, 2);
@ -149,7 +149,7 @@ namespace Spine {
} }
if (slotMap.ContainsKey("dark")) { if (slotMap.ContainsKey("dark")) {
var color2 = (String)slotMap["dark"]; var color2 = (string)slotMap["dark"];
data.r2 = ToColor(color2, 0, 6); // expectedLength = 6. ie. "RRGGBB" data.r2 = ToColor(color2, 0, 6); // expectedLength = 6. ie. "RRGGBB"
data.g2 = ToColor(color2, 1, 6); data.g2 = ToColor(color2, 1, 6);
data.b2 = ToColor(color2, 2, 6); data.b2 = ToColor(color2, 2, 6);
@ -158,7 +158,7 @@ namespace Spine {
data.attachmentName = GetString(slotMap, "attachment", null); data.attachmentName = GetString(slotMap, "attachment", null);
if (slotMap.ContainsKey("blend")) if (slotMap.ContainsKey("blend"))
data.blendMode = (BlendMode)Enum.Parse(typeof(BlendMode), (String)slotMap["blend"], true); data.blendMode = (BlendMode)Enum.Parse(typeof(BlendMode), (string)slotMap["blend"], true);
else else
data.blendMode = BlendMode.Normal; data.blendMode = BlendMode.Normal;
skeletonData.slots.Add(data); skeletonData.slots.Add(data);
@ -167,17 +167,17 @@ namespace Spine {
// IK constraints. // IK constraints.
if (root.ContainsKey("ik")) { if (root.ContainsKey("ik")) {
foreach (Dictionary<String, Object> constraintMap in (List<Object>)root["ik"]) { foreach (Dictionary<string, Object> constraintMap in (List<Object>)root["ik"]) {
IkConstraintData data = new IkConstraintData((String)constraintMap["name"]); IkConstraintData data = new IkConstraintData((string)constraintMap["name"]);
data.order = GetInt(constraintMap, "order", 0); data.order = GetInt(constraintMap, "order", 0);
foreach (String boneName in (List<Object>)constraintMap["bones"]) { foreach (string boneName in (List<Object>)constraintMap["bones"]) {
BoneData bone = skeletonData.FindBone(boneName); BoneData bone = skeletonData.FindBone(boneName);
if (bone == null) throw new Exception("IK constraint bone not found: " + boneName); if (bone == null) throw new Exception("IK constraint bone not found: " + boneName);
data.bones.Add(bone); data.bones.Add(bone);
} }
String targetName = (String)constraintMap["target"]; string targetName = (string)constraintMap["target"];
data.target = skeletonData.FindBone(targetName); data.target = skeletonData.FindBone(targetName);
if (data.target == null) throw new Exception("Target bone not found: " + targetName); if (data.target == null) throw new Exception("Target bone not found: " + targetName);
@ -190,17 +190,17 @@ namespace Spine {
// Transform constraints. // Transform constraints.
if (root.ContainsKey("transform")) { if (root.ContainsKey("transform")) {
foreach (Dictionary<String, Object> constraintMap in (List<Object>)root["transform"]) { foreach (Dictionary<string, Object> constraintMap in (List<Object>)root["transform"]) {
TransformConstraintData data = new TransformConstraintData((String)constraintMap["name"]); TransformConstraintData data = new TransformConstraintData((string)constraintMap["name"]);
data.order = GetInt(constraintMap, "order", 0); data.order = GetInt(constraintMap, "order", 0);
foreach (String boneName in (List<Object>)constraintMap["bones"]) { foreach (string boneName in (List<Object>)constraintMap["bones"]) {
BoneData bone = skeletonData.FindBone(boneName); BoneData bone = skeletonData.FindBone(boneName);
if (bone == null) throw new Exception("Transform constraint bone not found: " + boneName); if (bone == null) throw new Exception("Transform constraint bone not found: " + boneName);
data.bones.Add(bone); data.bones.Add(bone);
} }
String targetName = (String)constraintMap["target"]; string targetName = (string)constraintMap["target"];
data.target = skeletonData.FindBone(targetName); data.target = skeletonData.FindBone(targetName);
if (data.target == null) throw new Exception("Target bone not found: " + targetName); if (data.target == null) throw new Exception("Target bone not found: " + targetName);
@ -225,17 +225,17 @@ namespace Spine {
// Path constraints. // Path constraints.
if(root.ContainsKey("path")) { if(root.ContainsKey("path")) {
foreach (Dictionary<String, Object> constraintMap in (List<Object>)root["path"]) { foreach (Dictionary<string, Object> constraintMap in (List<Object>)root["path"]) {
PathConstraintData data = new PathConstraintData((String)constraintMap["name"]); PathConstraintData data = new PathConstraintData((string)constraintMap["name"]);
data.order = GetInt(constraintMap, "order", 0); data.order = GetInt(constraintMap, "order", 0);
foreach (String boneName in (List<Object>)constraintMap["bones"]) { foreach (string boneName in (List<Object>)constraintMap["bones"]) {
BoneData bone = skeletonData.FindBone(boneName); BoneData bone = skeletonData.FindBone(boneName);
if (bone == null) throw new Exception("Path bone not found: " + boneName); if (bone == null) throw new Exception("Path bone not found: " + boneName);
data.bones.Add(bone); data.bones.Add(bone);
} }
String targetName = (String)constraintMap["target"]; string targetName = (string)constraintMap["target"];
data.target = skeletonData.FindSlot(targetName); data.target = skeletonData.FindSlot(targetName);
if (data.target == null) throw new Exception("Target slot not found: " + targetName); if (data.target == null) throw new Exception("Target slot not found: " + targetName);
@ -256,13 +256,13 @@ namespace Spine {
// Skins. // Skins.
if (root.ContainsKey("skins")) { if (root.ContainsKey("skins")) {
foreach (KeyValuePair<String, Object> skinMap in (Dictionary<String, Object>)root["skins"]) { foreach (KeyValuePair<string, Object> skinMap in (Dictionary<string, Object>)root["skins"]) {
var skin = new Skin(skinMap.Key); var skin = new Skin(skinMap.Key);
foreach (KeyValuePair<String, Object> slotEntry in (Dictionary<String, Object>)skinMap.Value) { foreach (KeyValuePair<string, Object> slotEntry in (Dictionary<string, Object>)skinMap.Value) {
int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key); int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key);
foreach (KeyValuePair<String, Object> entry in ((Dictionary<String, Object>)slotEntry.Value)) { foreach (KeyValuePair<string, Object> entry in ((Dictionary<string, Object>)slotEntry.Value)) {
try { try {
Attachment attachment = ReadAttachment((Dictionary<String, Object>)entry.Value, skin, slotIndex, entry.Key, skeletonData); Attachment attachment = ReadAttachment((Dictionary<string, Object>)entry.Value, skin, slotIndex, entry.Key, skeletonData);
if (attachment != null) skin.AddAttachment(slotIndex, entry.Key, attachment); if (attachment != null) skin.AddAttachment(slotIndex, entry.Key, attachment);
} catch (Exception e) { } catch (Exception e) {
throw new Exception("Error reading attachment: " + entry.Key + ", skin: " + skin, e); throw new Exception("Error reading attachment: " + entry.Key + ", skin: " + skin, e);
@ -288,8 +288,8 @@ namespace Spine {
// Events. // Events.
if (root.ContainsKey("events")) { if (root.ContainsKey("events")) {
foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["events"]) { foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)root["events"]) {
var entryMap = (Dictionary<String, Object>)entry.Value; var entryMap = (Dictionary<string, Object>)entry.Value;
var data = new EventData(entry.Key); var data = new EventData(entry.Key);
data.Int = GetInt(entryMap, "int", 0); data.Int = GetInt(entryMap, "int", 0);
data.Float = GetFloat(entryMap, "float", 0); data.Float = GetFloat(entryMap, "float", 0);
@ -301,9 +301,9 @@ namespace Spine {
// Animations. // Animations.
if (root.ContainsKey("animations")) { if (root.ContainsKey("animations")) {
foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["animations"]) { foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)root["animations"]) {
try { try {
ReadAnimation((Dictionary<String, Object>)entry.Value, entry.Key, skeletonData); ReadAnimation((Dictionary<string, Object>)entry.Value, entry.Key, skeletonData);
} catch (Exception e) { } catch (Exception e) {
throw new Exception("Error reading animation: " + entry.Key, e); throw new Exception("Error reading animation: " + entry.Key, e);
} }
@ -319,8 +319,8 @@ namespace Spine {
return skeletonData; return skeletonData;
} }
private Attachment ReadAttachment (Dictionary<String, Object> map, Skin skin, int slotIndex, String name, SkeletonData skeletonData) { private Attachment ReadAttachment (Dictionary<string, Object> map, Skin skin, int slotIndex, string name, SkeletonData skeletonData) {
var scale = this.Scale; float scale = this.Scale;
name = GetString(map, "name", name); name = GetString(map, "name", name);
var typeName = GetString(map, "type", "region"); var typeName = GetString(map, "type", "region");
@ -329,7 +329,7 @@ namespace Spine {
if (typeName == "weightedlinkedmesh") typeName = "linkedmesh"; if (typeName == "weightedlinkedmesh") typeName = "linkedmesh";
var type = (AttachmentType)Enum.Parse(typeof(AttachmentType), typeName, true); var type = (AttachmentType)Enum.Parse(typeof(AttachmentType), typeName, true);
String path = GetString(map, "path", name); string path = GetString(map, "path", name);
switch (type) { switch (type) {
case AttachmentType.Region: case AttachmentType.Region:
@ -343,10 +343,9 @@ namespace Spine {
region.rotation = GetFloat(map, "rotation", 0); region.rotation = GetFloat(map, "rotation", 0);
region.width = GetFloat(map, "width", 32) * scale; region.width = GetFloat(map, "width", 32) * scale;
region.height = GetFloat(map, "height", 32) * scale; region.height = GetFloat(map, "height", 32) * scale;
region.UpdateOffset();
if (map.ContainsKey("color")) { if (map.ContainsKey("color")) {
var color = (String)map["color"]; var color = (string)map["color"];
region.r = ToColor(color, 0); region.r = ToColor(color, 0);
region.g = ToColor(color, 1); region.g = ToColor(color, 1);
region.b = ToColor(color, 2); region.b = ToColor(color, 2);
@ -367,7 +366,7 @@ namespace Spine {
mesh.Path = path; mesh.Path = path;
if (map.ContainsKey("color")) { if (map.ContainsKey("color")) {
var color = (String)map["color"]; var color = (string)map["color"];
mesh.r = ToColor(color, 0); mesh.r = ToColor(color, 0);
mesh.g = ToColor(color, 1); mesh.g = ToColor(color, 1);
mesh.b = ToColor(color, 2); mesh.b = ToColor(color, 2);
@ -377,7 +376,7 @@ namespace Spine {
mesh.Width = GetFloat(map, "width", 0) * scale; mesh.Width = GetFloat(map, "width", 0) * scale;
mesh.Height = GetFloat(map, "height", 0) * scale; mesh.Height = GetFloat(map, "height", 0) * scale;
String parent = GetString(map, "parent", null); string parent = GetString(map, "parent", null);
if (parent != null) { if (parent != null) {
mesh.InheritDeform = GetBoolean(map, "deform", true); mesh.InheritDeform = GetBoolean(map, "deform", true);
linkedMeshes.Add(new LinkedMesh(mesh, GetString(map, "skin", null), slotIndex, parent)); linkedMeshes.Add(new LinkedMesh(mesh, GetString(map, "skin", null), slotIndex, parent));
@ -439,7 +438,7 @@ namespace Spine {
return null; return null;
} }
private void ReadVertices (Dictionary<String, Object> map, VertexAttachment attachment, int verticesLength) { private void ReadVertices (Dictionary<string, Object> map, VertexAttachment attachment, int verticesLength) {
attachment.WorldVerticesLength = verticesLength; attachment.WorldVerticesLength = verticesLength;
float[] vertices = GetFloatArray(map, "vertices", 1); float[] vertices = GetFloatArray(map, "vertices", 1);
float scale = Scale; float scale = Scale;
@ -468,28 +467,28 @@ namespace Spine {
attachment.vertices = weights.ToArray(); attachment.vertices = weights.ToArray();
} }
private void ReadAnimation (Dictionary<String, Object> map, String name, SkeletonData skeletonData) { private void ReadAnimation (Dictionary<string, Object> map, string name, SkeletonData skeletonData) {
var scale = this.Scale; var scale = this.Scale;
var timelines = new ExposedList<Timeline>(); var timelines = new ExposedList<Timeline>();
float duration = 0; float duration = 0;
// Slot timelines. // Slot timelines.
if (map.ContainsKey("slots")) { if (map.ContainsKey("slots")) {
foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)map["slots"]) { foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)map["slots"]) {
String slotName = entry.Key; string slotName = entry.Key;
int slotIndex = skeletonData.FindSlotIndex(slotName); int slotIndex = skeletonData.FindSlotIndex(slotName);
var timelineMap = (Dictionary<String, Object>)entry.Value; var timelineMap = (Dictionary<string, Object>)entry.Value;
foreach (KeyValuePair<String, Object> timelineEntry in timelineMap) { foreach (KeyValuePair<string, Object> timelineEntry in timelineMap) {
var values = (List<Object>)timelineEntry.Value; var values = (List<Object>)timelineEntry.Value;
var timelineName = (String)timelineEntry.Key; var timelineName = (string)timelineEntry.Key;
if (timelineName == "attachment") { if (timelineName == "attachment") {
var timeline = new AttachmentTimeline(values.Count); var timeline = new AttachmentTimeline(values.Count);
timeline.slotIndex = slotIndex; timeline.slotIndex = slotIndex;
int frameIndex = 0; int frameIndex = 0;
foreach (Dictionary<String, Object> valueMap in values) { foreach (Dictionary<string, Object> valueMap in values) {
float time = (float)valueMap["time"]; float time = (float)valueMap["time"];
timeline.SetFrame(frameIndex++, time, (String)valueMap["name"]); timeline.SetFrame(frameIndex++, time, (string)valueMap["name"]);
} }
timelines.Add(timeline); timelines.Add(timeline);
duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]); duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]);
@ -534,20 +533,20 @@ namespace Spine {
// Bone timelines. // Bone timelines.
if (map.ContainsKey("bones")) { if (map.ContainsKey("bones")) {
foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)map["bones"]) { foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)map["bones"]) {
String boneName = entry.Key; string boneName = entry.Key;
int boneIndex = skeletonData.FindBoneIndex(boneName); int boneIndex = skeletonData.FindBoneIndex(boneName);
if (boneIndex == -1) throw new Exception("Bone not found: " + boneName); if (boneIndex == -1) throw new Exception("Bone not found: " + boneName);
var timelineMap = (Dictionary<String, Object>)entry.Value; var timelineMap = (Dictionary<string, Object>)entry.Value;
foreach (KeyValuePair<String, Object> timelineEntry in timelineMap) { foreach (KeyValuePair<string, Object> timelineEntry in timelineMap) {
var values = (List<Object>)timelineEntry.Value; var values = (List<Object>)timelineEntry.Value;
var timelineName = (String)timelineEntry.Key; var timelineName = (string)timelineEntry.Key;
if (timelineName == "rotate") { if (timelineName == "rotate") {
var timeline = new RotateTimeline(values.Count); var timeline = new RotateTimeline(values.Count);
timeline.boneIndex = boneIndex; timeline.boneIndex = boneIndex;
int frameIndex = 0; int frameIndex = 0;
foreach (Dictionary<String, Object> valueMap in values) { foreach (Dictionary<string, Object> valueMap in values) {
timeline.SetFrame(frameIndex, (float)valueMap["time"], (float)valueMap["angle"]); timeline.SetFrame(frameIndex, (float)valueMap["time"], (float)valueMap["angle"]);
ReadCurve(valueMap, timeline, frameIndex); ReadCurve(valueMap, timeline, frameIndex);
frameIndex++; frameIndex++;
@ -569,7 +568,7 @@ namespace Spine {
timeline.boneIndex = boneIndex; timeline.boneIndex = boneIndex;
int frameIndex = 0; int frameIndex = 0;
foreach (Dictionary<String, Object> valueMap in values) { foreach (Dictionary<string, Object> valueMap in values) {
float time = (float)valueMap["time"]; float time = (float)valueMap["time"];
float x = GetFloat(valueMap, "x", 0); float x = GetFloat(valueMap, "x", 0);
float y = GetFloat(valueMap, "y", 0); float y = GetFloat(valueMap, "y", 0);
@ -588,13 +587,13 @@ namespace Spine {
// IK constraint timelines. // IK constraint timelines.
if (map.ContainsKey("ik")) { if (map.ContainsKey("ik")) {
foreach (KeyValuePair<String, Object> constraintMap in (Dictionary<String, Object>)map["ik"]) { foreach (KeyValuePair<string, Object> constraintMap in (Dictionary<string, Object>)map["ik"]) {
IkConstraintData constraint = skeletonData.FindIkConstraint(constraintMap.Key); IkConstraintData constraint = skeletonData.FindIkConstraint(constraintMap.Key);
var values = (List<Object>)constraintMap.Value; var values = (List<Object>)constraintMap.Value;
var timeline = new IkConstraintTimeline(values.Count); var timeline = new IkConstraintTimeline(values.Count);
timeline.ikConstraintIndex = skeletonData.ikConstraints.IndexOf(constraint); timeline.ikConstraintIndex = skeletonData.ikConstraints.IndexOf(constraint);
int frameIndex = 0; int frameIndex = 0;
foreach (Dictionary<String, Object> valueMap in values) { foreach (Dictionary<string, Object> valueMap in values) {
float time = (float)valueMap["time"]; float time = (float)valueMap["time"];
float mix = GetFloat(valueMap, "mix", 1); float mix = GetFloat(valueMap, "mix", 1);
bool bendPositive = GetBoolean(valueMap, "bendPositive", true); bool bendPositive = GetBoolean(valueMap, "bendPositive", true);
@ -609,13 +608,13 @@ namespace Spine {
// Transform constraint timelines. // Transform constraint timelines.
if (map.ContainsKey("transform")) { if (map.ContainsKey("transform")) {
foreach (KeyValuePair<String, Object> constraintMap in (Dictionary<String, Object>)map["transform"]) { foreach (KeyValuePair<string, Object> constraintMap in (Dictionary<string, Object>)map["transform"]) {
TransformConstraintData constraint = skeletonData.FindTransformConstraint(constraintMap.Key); TransformConstraintData constraint = skeletonData.FindTransformConstraint(constraintMap.Key);
var values = (List<Object>)constraintMap.Value; var values = (List<Object>)constraintMap.Value;
var timeline = new TransformConstraintTimeline(values.Count); var timeline = new TransformConstraintTimeline(values.Count);
timeline.transformConstraintIndex = skeletonData.transformConstraints.IndexOf(constraint); timeline.transformConstraintIndex = skeletonData.transformConstraints.IndexOf(constraint);
int frameIndex = 0; int frameIndex = 0;
foreach (Dictionary<String, Object> valueMap in values) { foreach (Dictionary<string, Object> valueMap in values) {
float time = (float)valueMap["time"]; float time = (float)valueMap["time"];
float rotateMix = GetFloat(valueMap, "rotateMix", 1); float rotateMix = GetFloat(valueMap, "rotateMix", 1);
float translateMix = GetFloat(valueMap, "translateMix", 1); float translateMix = GetFloat(valueMap, "translateMix", 1);
@ -632,14 +631,14 @@ namespace Spine {
// Path constraint timelines. // Path constraint timelines.
if (map.ContainsKey("paths")) { if (map.ContainsKey("paths")) {
foreach (KeyValuePair<String, Object> constraintMap in (Dictionary<String, Object>)map["paths"]) { foreach (KeyValuePair<string, Object> constraintMap in (Dictionary<string, Object>)map["paths"]) {
int index = skeletonData.FindPathConstraintIndex(constraintMap.Key); int index = skeletonData.FindPathConstraintIndex(constraintMap.Key);
if (index == -1) throw new Exception("Path constraint not found: " + constraintMap.Key); if (index == -1) throw new Exception("Path constraint not found: " + constraintMap.Key);
PathConstraintData data = skeletonData.pathConstraints.Items[index]; PathConstraintData data = skeletonData.pathConstraints.Items[index];
var timelineMap = (Dictionary<String, Object>)constraintMap.Value; var timelineMap = (Dictionary<string, Object>)constraintMap.Value;
foreach (KeyValuePair<String, Object> timelineEntry in timelineMap) { foreach (KeyValuePair<string, Object> timelineEntry in timelineMap) {
var values = (List<Object>)timelineEntry.Value; var values = (List<Object>)timelineEntry.Value;
var timelineName = (String)timelineEntry.Key; var timelineName = (string)timelineEntry.Key;
if (timelineName == "position" || timelineName == "spacing") { if (timelineName == "position" || timelineName == "spacing") {
PathConstraintPositionTimeline timeline; PathConstraintPositionTimeline timeline;
float timelineScale = 1; float timelineScale = 1;
@ -653,7 +652,7 @@ namespace Spine {
} }
timeline.pathConstraintIndex = index; timeline.pathConstraintIndex = index;
int frameIndex = 0; int frameIndex = 0;
foreach (Dictionary<String, Object> valueMap in values) { foreach (Dictionary<string, Object> valueMap in values) {
timeline.SetFrame(frameIndex, (float)valueMap["time"], GetFloat(valueMap, timelineName, 0) * timelineScale); timeline.SetFrame(frameIndex, (float)valueMap["time"], GetFloat(valueMap, timelineName, 0) * timelineScale);
ReadCurve(valueMap, timeline, frameIndex); ReadCurve(valueMap, timeline, frameIndex);
frameIndex++; frameIndex++;
@ -665,7 +664,7 @@ namespace Spine {
PathConstraintMixTimeline timeline = new PathConstraintMixTimeline(values.Count); PathConstraintMixTimeline timeline = new PathConstraintMixTimeline(values.Count);
timeline.pathConstraintIndex = index; timeline.pathConstraintIndex = index;
int frameIndex = 0; int frameIndex = 0;
foreach (Dictionary<String, Object> valueMap in values) { foreach (Dictionary<string, Object> valueMap in values) {
timeline.SetFrame(frameIndex, (float)valueMap["time"], GetFloat(valueMap, "rotateMix", 1), GetFloat(valueMap, "translateMix", 1)); timeline.SetFrame(frameIndex, (float)valueMap["time"], GetFloat(valueMap, "rotateMix", 1), GetFloat(valueMap, "translateMix", 1));
ReadCurve(valueMap, timeline, frameIndex); ReadCurve(valueMap, timeline, frameIndex);
frameIndex++; frameIndex++;
@ -679,12 +678,12 @@ namespace Spine {
// Deform timelines. // Deform timelines.
if (map.ContainsKey("deform")) { if (map.ContainsKey("deform")) {
foreach (KeyValuePair<String, Object> deformMap in (Dictionary<String, Object>)map["deform"]) { foreach (KeyValuePair<string, Object> deformMap in (Dictionary<string, Object>)map["deform"]) {
Skin skin = skeletonData.FindSkin(deformMap.Key); Skin skin = skeletonData.FindSkin(deformMap.Key);
foreach (KeyValuePair<String, Object> slotMap in (Dictionary<String, Object>)deformMap.Value) { foreach (KeyValuePair<string, Object> slotMap in (Dictionary<string, Object>)deformMap.Value) {
int slotIndex = skeletonData.FindSlotIndex(slotMap.Key); int slotIndex = skeletonData.FindSlotIndex(slotMap.Key);
if (slotIndex == -1) throw new Exception("Slot not found: " + slotMap.Key); if (slotIndex == -1) throw new Exception("Slot not found: " + slotMap.Key);
foreach (KeyValuePair<String, Object> timelineMap in (Dictionary<String, Object>)slotMap.Value) { foreach (KeyValuePair<string, Object> timelineMap in (Dictionary<string, Object>)slotMap.Value) {
var values = (List<Object>)timelineMap.Value; var values = (List<Object>)timelineMap.Value;
VertexAttachment attachment = (VertexAttachment)skin.GetAttachment(slotIndex, timelineMap.Key); VertexAttachment attachment = (VertexAttachment)skin.GetAttachment(slotIndex, timelineMap.Key);
if (attachment == null) throw new Exception("Deform attachment not found: " + timelineMap.Key); if (attachment == null) throw new Exception("Deform attachment not found: " + timelineMap.Key);
@ -697,7 +696,7 @@ namespace Spine {
timeline.attachment = attachment; timeline.attachment = attachment;
int frameIndex = 0; int frameIndex = 0;
foreach (Dictionary<String, Object> valueMap in values) { foreach (Dictionary<string, Object> valueMap in values) {
float[] deform; float[] deform;
if (!valueMap.ContainsKey("vertices")) { if (!valueMap.ContainsKey("vertices")) {
deform = weighted ? new float[deformLength] : vertices; deform = weighted ? new float[deformLength] : vertices;
@ -734,7 +733,7 @@ namespace Spine {
var timeline = new DrawOrderTimeline(values.Count); var timeline = new DrawOrderTimeline(values.Count);
int slotCount = skeletonData.slots.Count; int slotCount = skeletonData.slots.Count;
int frameIndex = 0; int frameIndex = 0;
foreach (Dictionary<String, Object> drawOrderMap in values) { foreach (Dictionary<string, Object> drawOrderMap in values) {
int[] drawOrder = null; int[] drawOrder = null;
if (drawOrderMap.ContainsKey("offsets")) { if (drawOrderMap.ContainsKey("offsets")) {
drawOrder = new int[slotCount]; drawOrder = new int[slotCount];
@ -743,8 +742,8 @@ namespace Spine {
var offsets = (List<Object>)drawOrderMap["offsets"]; var offsets = (List<Object>)drawOrderMap["offsets"];
int[] unchanged = new int[slotCount - offsets.Count]; int[] unchanged = new int[slotCount - offsets.Count];
int originalIndex = 0, unchangedIndex = 0; int originalIndex = 0, unchangedIndex = 0;
foreach (Dictionary<String, Object> offsetMap in offsets) { foreach (Dictionary<string, Object> offsetMap in offsets) {
int slotIndex = skeletonData.FindSlotIndex((String)offsetMap["slot"]); int slotIndex = skeletonData.FindSlotIndex((string)offsetMap["slot"]);
if (slotIndex == -1) throw new Exception("Slot not found: " + offsetMap["slot"]); if (slotIndex == -1) throw new Exception("Slot not found: " + offsetMap["slot"]);
// Collect unchanged items. // Collect unchanged items.
while (originalIndex != slotIndex) while (originalIndex != slotIndex)
@ -771,8 +770,8 @@ namespace Spine {
var eventsMap = (List<Object>)map["events"]; var eventsMap = (List<Object>)map["events"];
var timeline = new EventTimeline(eventsMap.Count); var timeline = new EventTimeline(eventsMap.Count);
int frameIndex = 0; int frameIndex = 0;
foreach (Dictionary<String, Object> eventMap in eventsMap) { foreach (Dictionary<string, Object> eventMap in eventsMap) {
EventData eventData = skeletonData.FindEvent((String)eventMap["name"]); EventData eventData = skeletonData.FindEvent((string)eventMap["name"]);
if (eventData == null) throw new Exception("Event not found: " + eventMap["name"]); if (eventData == null) throw new Exception("Event not found: " + eventMap["name"]);
var e = new Event((float)eventMap["time"], eventData); var e = new Event((float)eventMap["time"], eventData);
e.Int = GetInt(eventMap, "int", eventData.Int); e.Int = GetInt(eventMap, "int", eventData.Int);
@ -788,7 +787,7 @@ namespace Spine {
skeletonData.animations.Add(new Animation(name, timelines, duration)); skeletonData.animations.Add(new Animation(name, timelines, duration));
} }
static void ReadCurve (Dictionary<String, Object> valueMap, CurveTimeline timeline, int frameIndex) { static void ReadCurve (Dictionary<string, Object> valueMap, CurveTimeline timeline, int frameIndex) {
if (!valueMap.ContainsKey("curve")) if (!valueMap.ContainsKey("curve"))
return; return;
Object curveObject = valueMap["curve"]; Object curveObject = valueMap["curve"];
@ -802,11 +801,11 @@ namespace Spine {
} }
internal class LinkedMesh { internal class LinkedMesh {
internal String parent, skin; internal string parent, skin;
internal int slotIndex; internal int slotIndex;
internal MeshAttachment mesh; internal MeshAttachment mesh;
public LinkedMesh (MeshAttachment mesh, String skin, int slotIndex, String parent) { public LinkedMesh (MeshAttachment mesh, string skin, int slotIndex, string parent) {
this.mesh = mesh; this.mesh = mesh;
this.skin = skin; this.skin = skin;
this.slotIndex = slotIndex; this.slotIndex = slotIndex;
@ -814,7 +813,7 @@ namespace Spine {
} }
} }
static float[] GetFloatArray(Dictionary<String, Object> map, String name, float scale) { static float[] GetFloatArray(Dictionary<string, Object> map, string name, float scale) {
var list = (List<Object>)map[name]; var list = (List<Object>)map[name];
var values = new float[list.Count]; var values = new float[list.Count];
if (scale == 1) { if (scale == 1) {
@ -827,7 +826,7 @@ namespace Spine {
return values; return values;
} }
static int[] GetIntArray(Dictionary<String, Object> map, String name) { static int[] GetIntArray(Dictionary<string, Object> map, string name) {
var list = (List<Object>)map[name]; var list = (List<Object>)map[name];
var values = new int[list.Count]; var values = new int[list.Count];
for (int i = 0, n = list.Count; i < n; i++) for (int i = 0, n = list.Count; i < n; i++)
@ -835,31 +834,31 @@ namespace Spine {
return values; return values;
} }
static float GetFloat(Dictionary<String, Object> map, String name, float defaultValue) { static float GetFloat(Dictionary<string, Object> map, string name, float defaultValue) {
if (!map.ContainsKey(name)) if (!map.ContainsKey(name))
return defaultValue; return defaultValue;
return (float)map[name]; return (float)map[name];
} }
static int GetInt(Dictionary<String, Object> map, String name, int defaultValue) { static int GetInt(Dictionary<string, Object> map, string name, int defaultValue) {
if (!map.ContainsKey(name)) if (!map.ContainsKey(name))
return defaultValue; return defaultValue;
return (int)(float)map[name]; return (int)(float)map[name];
} }
static bool GetBoolean(Dictionary<String, Object> map, String name, bool defaultValue) { static bool GetBoolean(Dictionary<string, Object> map, string name, bool defaultValue) {
if (!map.ContainsKey(name)) if (!map.ContainsKey(name))
return defaultValue; return defaultValue;
return (bool)map[name]; return (bool)map[name];
} }
static String GetString(Dictionary<String, Object> map, String name, String defaultValue) { static string GetString(Dictionary<string, Object> map, string name, string defaultValue) {
if (!map.ContainsKey(name)) if (!map.ContainsKey(name))
return defaultValue; return defaultValue;
return (String)map[name]; return (string)map[name];
} }
static float ToColor(String hexString, int colorIndex, int expectedLength = 8) { static float ToColor(string hexString, int colorIndex, int expectedLength = 8) {
if (hexString.Length != expectedLength) if (hexString.Length != expectedLength)
throw new ArgumentException("Color hexidecimal length must be " + expectedLength + ", recieved: " + hexString, "hexString"); throw new ArgumentException("Color hexidecimal length must be " + expectedLength + ", recieved: " + hexString, "hexString");
return Convert.ToInt32(hexString.Substring(colorIndex * 2, 2), 16) / (float)255; return Convert.ToInt32(hexString.Substring(colorIndex * 2, 2), 16) / (float)255;

View File

@ -114,7 +114,7 @@ namespace Spine {
internal static readonly AttachmentKeyTupleComparer Instance = new AttachmentKeyTupleComparer(); internal static readonly AttachmentKeyTupleComparer Instance = new AttachmentKeyTupleComparer();
bool IEqualityComparer<AttachmentKeyTuple>.Equals (AttachmentKeyTuple o1, AttachmentKeyTuple o2) { bool IEqualityComparer<AttachmentKeyTuple>.Equals (AttachmentKeyTuple o1, AttachmentKeyTuple o2) {
return o1.slotIndex == o2.slotIndex && o1.nameHashCode == o2.nameHashCode && o1.name == o2.name; return o1.slotIndex == o2.slotIndex && o1.nameHashCode == o2.nameHashCode && string.Equals(o1.name, o2.name, StringComparison.Ordinal);
} }
int IEqualityComparer<AttachmentKeyTuple>.GetHashCode (AttachmentKeyTuple o) { int IEqualityComparer<AttachmentKeyTuple>.GetHashCode (AttachmentKeyTuple o) {

View File

@ -0,0 +1,84 @@
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using UnityEngine;
namespace Spine.Unity {
public class RegionlessAttachmentLoader : AttachmentLoader {
static AtlasRegion emptyRegion;
static AtlasRegion EmptyRegion {
get {
if (emptyRegion == null) {
emptyRegion = new AtlasRegion {
name = "Empty AtlasRegion",
page = new AtlasPage {
name = "Empty AtlasPage",
rendererObject = new Material(Shader.Find("Spine/Special/HiddenPass")) { name = "NoRender Material" }
}
};
}
return emptyRegion;
}
}
public RegionAttachment NewRegionAttachment (Skin skin, string name, string path) {
RegionAttachment attachment = new RegionAttachment(name) {
RendererObject = EmptyRegion
};
return attachment;
}
public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) {
MeshAttachment attachment = new MeshAttachment(name) {
RendererObject = EmptyRegion
};
return attachment;
}
public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name) {
return new BoundingBoxAttachment(name);
}
public PathAttachment NewPathAttachment (Skin skin, string name) {
return new PathAttachment(name);
}
public PointAttachment NewPointAttachment (Skin skin, string name) {
return new PointAttachment(name);
}
public ClippingAttachment NewClippingAttachment (Skin skin, string name) {
return new ClippingAttachment(name);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 15f0f78b87720c047a320c5e0e3f91b7
timeCreated: 1520505662
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -126,7 +126,7 @@ namespace Spine.Unity {
Atlas[] atlasArray = this.GetAtlasArray(); Atlas[] atlasArray = this.GetAtlasArray();
#if !SPINE_TK2D #if !SPINE_TK2D
attachmentLoader = new AtlasAttachmentLoader(atlasArray); attachmentLoader = (atlasArray.Length == 0) ? (AttachmentLoader)new RegionlessAttachmentLoader() : (AttachmentLoader)new AtlasAttachmentLoader(atlasArray);
skeletonDataScale = scale; skeletonDataScale = scale;
#else #else
if (spriteCollection != null) { if (spriteCollection != null) {

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 954179821df28404683b8289f05d0c6f
folderAsset: yes
timeCreated: 1518344191
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,184 +1,184 @@
/****************************************************************************** /******************************************************************************
* Spine Runtimes Software License v2.5 * Spine Runtimes Software License v2.5
* *
* Copyright (c) 2013-2016, Esoteric Software * Copyright (c) 2013-2016, Esoteric Software
* All rights reserved. * All rights reserved.
* *
* You are granted a perpetual, non-exclusive, non-sublicensable, and * You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine * non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal * Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of * use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate, * the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise * adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove, * create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent, * delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the * or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source * Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms. * form must include this license and terms.
* *
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. * POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/ *****************************************************************************/
using System; using System;
using UnityEngine; using UnityEngine;
namespace Spine.Unity { namespace Spine.Unity {
/// <summary>Sets a GameObject's transform to match a bone on a Spine skeleton.</summary> /// <summary>Sets a GameObject's transform to match a bone on a Spine skeleton.</summary>
[ExecuteInEditMode] [ExecuteInEditMode]
[AddComponentMenu("Spine/BoneFollower")] [AddComponentMenu("Spine/BoneFollower")]
public class BoneFollower : MonoBehaviour { public class BoneFollower : MonoBehaviour {
#region Inspector #region Inspector
public SkeletonRenderer skeletonRenderer; public SkeletonRenderer skeletonRenderer;
public SkeletonRenderer SkeletonRenderer { public SkeletonRenderer SkeletonRenderer {
get { return skeletonRenderer; } get { return skeletonRenderer; }
set { set {
skeletonRenderer = value; skeletonRenderer = value;
Initialize(); Initialize();
} }
} }
/// <summary>If a bone isn't set in code, boneName is used to find the bone at the beginning. For runtime switching by name, use SetBoneByName. You can also set the BoneFollower.bone field directly.</summary> /// <summary>If a bone isn't set in code, boneName is used to find the bone at the beginning. For runtime switching by name, use SetBoneByName. You can also set the BoneFollower.bone field directly.</summary>
[SpineBone(dataField: "skeletonRenderer")] [SpineBone(dataField: "skeletonRenderer")]
[SerializeField] public string boneName; [SerializeField] public string boneName;
public bool followZPosition = true; public bool followZPosition = true;
public bool followBoneRotation = true; public bool followBoneRotation = true;
[Tooltip("Follows the skeleton's flip state by controlling this Transform's local scale.")] [Tooltip("Follows the skeleton's flip state by controlling this Transform's local scale.")]
public bool followSkeletonFlip = true; public bool followSkeletonFlip = true;
[Tooltip("Follows the target bone's local scale. BoneFollower cannot inherit world/skewed scale because of UnityEngine.Transform property limitations.")] [Tooltip("Follows the target bone's local scale. BoneFollower cannot inherit world/skewed scale because of UnityEngine.Transform property limitations.")]
public bool followLocalScale = false; public bool followLocalScale = false;
[UnityEngine.Serialization.FormerlySerializedAs("resetOnAwake")] [UnityEngine.Serialization.FormerlySerializedAs("resetOnAwake")]
public bool initializeOnAwake = true; public bool initializeOnAwake = true;
#endregion #endregion
[NonSerialized] public bool valid; [NonSerialized] public bool valid;
/// <summary> /// <summary>
/// The bone. /// The bone.
/// </summary> /// </summary>
[NonSerialized] public Bone bone; [NonSerialized] public Bone bone;
Transform skeletonTransform; Transform skeletonTransform;
bool skeletonTransformIsParent; bool skeletonTransformIsParent;
/// <summary> /// <summary>
/// Sets the target bone by its bone name. Returns false if no bone was found. To set the bone by reference, use BoneFollower.bone directly.</summary> /// Sets the target bone by its bone name. Returns false if no bone was found. To set the bone by reference, use BoneFollower.bone directly.</summary>
public bool SetBone (string name) { public bool SetBone (string name) {
bone = skeletonRenderer.skeleton.FindBone(name); bone = skeletonRenderer.skeleton.FindBone(name);
if (bone == null) { if (bone == null) {
Debug.LogError("Bone not found: " + name, this); Debug.LogError("Bone not found: " + name, this);
return false; return false;
} }
boneName = name; boneName = name;
return true; return true;
} }
public void Awake () { public void Awake () {
if (initializeOnAwake) Initialize(); if (initializeOnAwake) Initialize();
} }
public void HandleRebuildRenderer (SkeletonRenderer skeletonRenderer) { public void HandleRebuildRenderer (SkeletonRenderer skeletonRenderer) {
Initialize(); Initialize();
} }
public void Initialize () { public void Initialize () {
bone = null; bone = null;
valid = skeletonRenderer != null && skeletonRenderer.valid; valid = skeletonRenderer != null && skeletonRenderer.valid;
if (!valid) return; if (!valid) return;
skeletonTransform = skeletonRenderer.transform; skeletonTransform = skeletonRenderer.transform;
skeletonRenderer.OnRebuild -= HandleRebuildRenderer; skeletonRenderer.OnRebuild -= HandleRebuildRenderer;
skeletonRenderer.OnRebuild += HandleRebuildRenderer; skeletonRenderer.OnRebuild += HandleRebuildRenderer;
skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent);
if (!string.IsNullOrEmpty(boneName)) if (!string.IsNullOrEmpty(boneName))
bone = skeletonRenderer.skeleton.FindBone(boneName); bone = skeletonRenderer.skeleton.FindBone(boneName);
#if UNITY_EDITOR #if UNITY_EDITOR
if (Application.isEditor) if (Application.isEditor)
LateUpdate(); LateUpdate();
#endif #endif
} }
void OnDestroy () { void OnDestroy () {
if (skeletonRenderer != null) if (skeletonRenderer != null)
skeletonRenderer.OnRebuild -= HandleRebuildRenderer; skeletonRenderer.OnRebuild -= HandleRebuildRenderer;
} }
public void LateUpdate () { public void LateUpdate () {
if (!valid) { if (!valid) {
Initialize(); Initialize();
return; return;
} }
#if UNITY_EDITOR #if UNITY_EDITOR
if (!Application.isPlaying) if (!Application.isPlaying)
skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent);
#endif #endif
if (bone == null) { if (bone == null) {
if (string.IsNullOrEmpty(boneName)) return; if (string.IsNullOrEmpty(boneName)) return;
bone = skeletonRenderer.skeleton.FindBone(boneName); bone = skeletonRenderer.skeleton.FindBone(boneName);
if (!SetBone(boneName)) return; if (!SetBone(boneName)) return;
} }
Transform thisTransform = this.transform; Transform thisTransform = this.transform;
if (skeletonTransformIsParent) { if (skeletonTransformIsParent) {
// Recommended setup: Use local transform properties if Spine GameObject is the immediate parent // Recommended setup: Use local transform properties if Spine GameObject is the immediate parent
thisTransform.localPosition = new Vector3(bone.worldX, bone.worldY, followZPosition ? 0f : thisTransform.localPosition.z); thisTransform.localPosition = new Vector3(bone.worldX, bone.worldY, followZPosition ? 0f : thisTransform.localPosition.z);
if (followBoneRotation) { if (followBoneRotation) {
float halfRotation = Mathf.Atan2(bone.c, bone.a) * 0.5f; float halfRotation = Mathf.Atan2(bone.c, bone.a) * 0.5f;
if (followLocalScale && bone.scaleX < 0) // Negate rotation from negative scaleX. Don't use negative determinant. local scaleY doesn't factor into used rotation. if (followLocalScale && bone.scaleX < 0) // Negate rotation from negative scaleX. Don't use negative determinant. local scaleY doesn't factor into used rotation.
halfRotation += Mathf.PI * 0.5f; halfRotation += Mathf.PI * 0.5f;
var q = default(Quaternion); var q = default(Quaternion);
q.z = Mathf.Sin(halfRotation); q.z = Mathf.Sin(halfRotation);
q.w = Mathf.Cos(halfRotation); q.w = Mathf.Cos(halfRotation);
thisTransform.localRotation = q; thisTransform.localRotation = q;
} }
} else { } else {
// For special cases: Use transform world properties if transform relationship is complicated // For special cases: Use transform world properties if transform relationship is complicated
Vector3 targetWorldPosition = skeletonTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY, 0f)); Vector3 targetWorldPosition = skeletonTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY, 0f));
if (!followZPosition) targetWorldPosition.z = thisTransform.position.z; if (!followZPosition) targetWorldPosition.z = thisTransform.position.z;
float boneWorldRotation = bone.WorldRotationX; float boneWorldRotation = bone.WorldRotationX;
Transform transformParent = thisTransform.parent; Transform transformParent = thisTransform.parent;
if (transformParent != null) { if (transformParent != null) {
Matrix4x4 m = transformParent.localToWorldMatrix; Matrix4x4 m = transformParent.localToWorldMatrix;
if (m.m00 * m.m11 - m.m01 * m.m10 < 0) // Determinant2D is negative if (m.m00 * m.m11 - m.m01 * m.m10 < 0) // Determinant2D is negative
boneWorldRotation = -boneWorldRotation; boneWorldRotation = -boneWorldRotation;
} }
if (followBoneRotation) { if (followBoneRotation) {
Vector3 worldRotation = skeletonTransform.rotation.eulerAngles; Vector3 worldRotation = skeletonTransform.rotation.eulerAngles;
if (followLocalScale && bone.scaleX < 0) boneWorldRotation += 180f; if (followLocalScale && bone.scaleX < 0) boneWorldRotation += 180f;
#if UNITY_5_6_OR_NEWER #if UNITY_5_6_OR_NEWER
thisTransform.SetPositionAndRotation(targetWorldPosition, Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + boneWorldRotation)); thisTransform.SetPositionAndRotation(targetWorldPosition, Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + boneWorldRotation));
#else #else
thisTransform.position = targetWorldPosition; thisTransform.position = targetWorldPosition;
thisTransform.rotation = Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + bone.WorldRotationX); thisTransform.rotation = Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + bone.WorldRotationX);
#endif #endif
} else { } else {
thisTransform.position = targetWorldPosition; thisTransform.position = targetWorldPosition;
} }
} }
Vector3 localScale = followLocalScale ? new Vector3(bone.scaleX, bone.scaleY, 1f) : new Vector3(1f, 1f, 1f); Vector3 localScale = followLocalScale ? new Vector3(bone.scaleX, bone.scaleY, 1f) : new Vector3(1f, 1f, 1f);
if (followSkeletonFlip) localScale.y *= bone.skeleton.flipX ^ bone.skeleton.flipY ? -1f : 1f; if (followSkeletonFlip) localScale.y *= bone.skeleton.flipX ^ bone.skeleton.flipY ? -1f : 1f;
thisTransform.localScale = localScale; thisTransform.localScale = localScale;
} }
} }
} }

View File

@ -1,210 +1,210 @@
/****************************************************************************** /******************************************************************************
* Spine Runtimes Software License v2.5 * Spine Runtimes Software License v2.5
* *
* Copyright (c) 2013-2016, Esoteric Software * Copyright (c) 2013-2016, Esoteric Software
* All rights reserved. * All rights reserved.
* *
* You are granted a perpetual, non-exclusive, non-sublicensable, and * You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine * non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal * Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of * use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate, * the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise * adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove, * create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent, * delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the * or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source * Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms. * form must include this license and terms.
* *
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. * POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/ *****************************************************************************/
using UnityEngine; using UnityEngine;
namespace Spine.Unity { namespace Spine.Unity {
[ExecuteInEditMode] [ExecuteInEditMode]
[AddComponentMenu("Spine/SkeletonAnimation")] [AddComponentMenu("Spine/SkeletonAnimation")]
[HelpURL("http://esotericsoftware.com/spine-unity-documentation#Controlling-Animation")] [HelpURL("http://esotericsoftware.com/spine-unity-documentation#Controlling-Animation")]
public class SkeletonAnimation : SkeletonRenderer, ISkeletonAnimation, IAnimationStateComponent { public class SkeletonAnimation : SkeletonRenderer, ISkeletonAnimation, IAnimationStateComponent {
#region IAnimationStateComponent #region IAnimationStateComponent
/// <summary> /// <summary>
/// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it. /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it.
/// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary> /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary>
public Spine.AnimationState state; public Spine.AnimationState state;
/// <summary> /// <summary>
/// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it. /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it.
/// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary> /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary>
public Spine.AnimationState AnimationState { get { return this.state; } } public Spine.AnimationState AnimationState { get { return this.state; } }
#endregion #endregion
#region Bone Callbacks ISkeletonAnimation #region Bone Callbacks ISkeletonAnimation
protected event UpdateBonesDelegate _UpdateLocal; protected event UpdateBonesDelegate _UpdateLocal;
protected event UpdateBonesDelegate _UpdateWorld; protected event UpdateBonesDelegate _UpdateWorld;
protected event UpdateBonesDelegate _UpdateComplete; protected event UpdateBonesDelegate _UpdateComplete;
/// <summary> /// <summary>
/// Occurs after the animations are applied and before world space values are resolved. /// Occurs after the animations are applied and before world space values are resolved.
/// Use this callback when you want to set bone local values. /// Use this callback when you want to set bone local values.
/// </summary> /// </summary>
public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } } public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } }
/// <summary> /// <summary>
/// Occurs after the Skeleton's bone world space values are resolved (including all constraints). /// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
/// Using this callback will cause the world space values to be solved an extra time. /// Using this callback will cause the world space values to be solved an extra time.
/// Use this callback if want to use bone world space values, and also set bone local values.</summary> /// Use this callback if want to use bone world space values, and also set bone local values.</summary>
public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } } public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } }
/// <summary> /// <summary>
/// Occurs after the Skeleton's bone world space values are resolved (including all constraints). /// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
/// Use this callback if you want to use bone world space values, but don't intend to modify bone local values. /// Use this callback if you want to use bone world space values, but don't intend to modify bone local values.
/// This callback can also be used when setting world position and the bone matrix.</summary> /// This callback can also be used when setting world position and the bone matrix.</summary>
public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } } public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } }
#endregion #endregion
#region Serialized state and Beginner API #region Serialized state and Beginner API
[SerializeField] [SerializeField]
[SpineAnimation] [SpineAnimation]
private string _animationName; private string _animationName;
/// <summary> /// <summary>
/// Setting this property sets the animation of the skeleton. If invalid, it will store the animation name for the next time the skeleton is properly initialized. /// Setting this property sets the animation of the skeleton. If invalid, it will store the animation name for the next time the skeleton is properly initialized.
/// Getting this property gets the name of the currently playing animation. If invalid, it will return the last stored animation name set through this property.</summary> /// Getting this property gets the name of the currently playing animation. If invalid, it will return the last stored animation name set through this property.</summary>
public string AnimationName { public string AnimationName {
get { get {
if (!valid) { if (!valid) {
return _animationName; return _animationName;
} else { } else {
TrackEntry entry = state.GetCurrent(0); TrackEntry entry = state.GetCurrent(0);
return entry == null ? null : entry.Animation.Name; return entry == null ? null : entry.Animation.Name;
} }
} }
set { set {
if (_animationName == value) if (_animationName == value)
return; return;
_animationName = value; _animationName = value;
if (string.IsNullOrEmpty(value)) { if (string.IsNullOrEmpty(value)) {
state.ClearTrack(0); state.ClearTrack(0);
} else { } else {
TrySetAnimation(value, loop); TrySetAnimation(value, loop);
} }
} }
} }
TrackEntry TrySetAnimation (string animationName, bool animationLoop) { TrackEntry TrySetAnimation (string animationName, bool animationLoop) {
var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(animationName); var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(animationName);
if (animationObject != null) if (animationObject != null)
return state.SetAnimation(0, animationObject, animationLoop); return state.SetAnimation(0, animationObject, animationLoop);
return null; return null;
} }
/// <summary>Whether or not <see cref="AnimationName"/> should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected.</summary> /// <summary>Whether or not <see cref="AnimationName"/> should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected.</summary>
public bool loop; public bool loop;
/// <summary> /// <summary>
/// The rate at which animations progress over time. 1 means 100%. 0.5 means 50%.</summary> /// The rate at which animations progress over time. 1 means 100%. 0.5 means 50%.</summary>
/// <remarks>AnimationState and TrackEntry also have their own timeScale. These are combined multiplicatively.</remarks> /// <remarks>AnimationState and TrackEntry also have their own timeScale. These are combined multiplicatively.</remarks>
public float timeScale = 1; public float timeScale = 1;
#endregion #endregion
#region Runtime Instantiation #region Runtime Instantiation
/// <summary>Adds and prepares a SkeletonAnimation component to a GameObject at runtime.</summary> /// <summary>Adds and prepares a SkeletonAnimation component to a GameObject at runtime.</summary>
/// <returns>The newly instantiated SkeletonAnimation</returns> /// <returns>The newly instantiated SkeletonAnimation</returns>
public static SkeletonAnimation AddToGameObject (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) { public static SkeletonAnimation AddToGameObject (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) {
return SkeletonRenderer.AddSpineComponent<SkeletonAnimation>(gameObject, skeletonDataAsset); return SkeletonRenderer.AddSpineComponent<SkeletonAnimation>(gameObject, skeletonDataAsset);
} }
/// <summary>Instantiates a new UnityEngine.GameObject and adds a prepared SkeletonAnimation component to it.</summary> /// <summary>Instantiates a new UnityEngine.GameObject and adds a prepared SkeletonAnimation component to it.</summary>
/// <returns>The newly instantiated SkeletonAnimation component.</returns> /// <returns>The newly instantiated SkeletonAnimation component.</returns>
public static SkeletonAnimation NewSkeletonAnimationGameObject (SkeletonDataAsset skeletonDataAsset) { public static SkeletonAnimation NewSkeletonAnimationGameObject (SkeletonDataAsset skeletonDataAsset) {
return SkeletonRenderer.NewSpineGameObject<SkeletonAnimation>(skeletonDataAsset); return SkeletonRenderer.NewSpineGameObject<SkeletonAnimation>(skeletonDataAsset);
} }
#endregion #endregion
/// <summary> /// <summary>
/// Clears the previously generated mesh, resets the skeleton's pose, and clears all previously active animations.</summary> /// Clears the previously generated mesh, resets the skeleton's pose, and clears all previously active animations.</summary>
public override void ClearState () { public override void ClearState () {
base.ClearState(); base.ClearState();
if (state != null) state.ClearTracks(); if (state != null) state.ClearTracks();
} }
/// <summary> /// <summary>
/// Initialize this component. Attempts to load the SkeletonData and creates the internal Spine objects and buffers.</summary> /// Initialize this component. Attempts to load the SkeletonData and creates the internal Spine objects and buffers.</summary>
/// <param name="overwrite">If set to <c>true</c>, force overwrite an already initialized object.</param> /// <param name="overwrite">If set to <c>true</c>, force overwrite an already initialized object.</param>
public override void Initialize (bool overwrite) { public override void Initialize (bool overwrite) {
if (valid && !overwrite) if (valid && !overwrite)
return; return;
base.Initialize(overwrite); base.Initialize(overwrite);
if (!valid) if (!valid)
return; return;
state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData()); state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData());
#if UNITY_EDITOR #if UNITY_EDITOR
if (!string.IsNullOrEmpty(_animationName)) { if (!string.IsNullOrEmpty(_animationName)) {
if (Application.isPlaying) { if (Application.isPlaying) {
TrackEntry startingTrack = TrySetAnimation(_animationName, loop); TrackEntry startingTrack = TrySetAnimation(_animationName, loop);
if (startingTrack != null) if (startingTrack != null)
Update(0); Update(0);
} else { } else {
// Assume SkeletonAnimation is valid for skeletonData and skeleton. Checked above. // Assume SkeletonAnimation is valid for skeletonData and skeleton. Checked above.
var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(_animationName); var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(_animationName);
if (animationObject != null) if (animationObject != null)
animationObject.PoseSkeleton(skeleton, 0f); animationObject.PoseSkeleton(skeleton, 0f);
} }
} }
#else #else
if (!string.IsNullOrEmpty(_animationName)) { if (!string.IsNullOrEmpty(_animationName)) {
TrackEntry startingTrack = TrySetAnimation(_animationName, loop); TrackEntry startingTrack = TrySetAnimation(_animationName, loop);
if (startingTrack != null) if (startingTrack != null)
Update(0); Update(0);
} }
#endif #endif
} }
void Update () { void Update () {
Update(Time.deltaTime); Update(Time.deltaTime);
} }
/// <summary>Progresses the AnimationState according to the given deltaTime, and applies it to the Skeleton. Use Time.deltaTime to update manually. Use deltaTime 0 to update without progressing the time.</summary> /// <summary>Progresses the AnimationState according to the given deltaTime, and applies it to the Skeleton. Use Time.deltaTime to update manually. Use deltaTime 0 to update without progressing the time.</summary>
public void Update (float deltaTime) { public void Update (float deltaTime) {
if (!valid) if (!valid)
return; return;
deltaTime *= timeScale; deltaTime *= timeScale;
skeleton.Update(deltaTime); skeleton.Update(deltaTime);
state.Update(deltaTime); state.Update(deltaTime);
state.Apply(skeleton); state.Apply(skeleton);
if (_UpdateLocal != null) if (_UpdateLocal != null)
_UpdateLocal(this); _UpdateLocal(this);
skeleton.UpdateWorldTransform(); skeleton.UpdateWorldTransform();
if (_UpdateWorld != null) { if (_UpdateWorld != null) {
_UpdateWorld(this); _UpdateWorld(this);
skeleton.UpdateWorldTransform(); skeleton.UpdateWorldTransform();
} }
if (_UpdateComplete != null) { if (_UpdateComplete != null) {
_UpdateComplete(this); _UpdateComplete(this);
} }
} }
} }
} }

View File

@ -1,326 +1,326 @@
/****************************************************************************** /******************************************************************************
* Spine Runtimes Software License v2.5 * Spine Runtimes Software License v2.5
* *
* Copyright (c) 2013-2016, Esoteric Software * Copyright (c) 2013-2016, Esoteric Software
* All rights reserved. * All rights reserved.
* *
* You are granted a perpetual, non-exclusive, non-sublicensable, and * You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine * non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal * Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of * use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate, * the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise * adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove, * create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent, * delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the * or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source * Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms. * form must include this license and terms.
* *
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. * POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/ *****************************************************************************/
#define SPINE_OPTIONAL_RENDEROVERRIDE #define SPINE_OPTIONAL_RENDEROVERRIDE
#define SPINE_OPTIONAL_MATERIALOVERRIDE #define SPINE_OPTIONAL_MATERIALOVERRIDE
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
namespace Spine.Unity { namespace Spine.Unity {
/// <summary>Renders a skeleton.</summary> /// <summary>Renders a skeleton.</summary>
[ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer)), DisallowMultipleComponent] [ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer)), DisallowMultipleComponent]
[HelpURL("http://esotericsoftware.com/spine-unity-documentation#Rendering")] [HelpURL("http://esotericsoftware.com/spine-unity-documentation#Rendering")]
public class SkeletonRenderer : MonoBehaviour, ISkeletonComponent, IHasSkeletonDataAsset { public class SkeletonRenderer : MonoBehaviour, ISkeletonComponent, IHasSkeletonDataAsset {
public delegate void SkeletonRendererDelegate (SkeletonRenderer skeletonRenderer); public delegate void SkeletonRendererDelegate (SkeletonRenderer skeletonRenderer);
public event SkeletonRendererDelegate OnRebuild; public event SkeletonRendererDelegate OnRebuild;
/// <summary> Occurs after the vertex data is populated every frame, before the vertices are pushed into the mesh.</summary> /// <summary> Occurs after the vertex data is populated every frame, before the vertices are pushed into the mesh.</summary>
public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices; public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices;
public SkeletonDataAsset skeletonDataAsset; public SkeletonDataAsset skeletonDataAsset;
public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } // ISkeletonComponent public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } // ISkeletonComponent
public string initialSkinName; public string initialSkinName;
public bool initialFlipX, initialFlipY; public bool initialFlipX, initialFlipY;
#region Advanced #region Advanced
// Submesh Separation // Submesh Separation
[UnityEngine.Serialization.FormerlySerializedAs("submeshSeparators")] [SpineSlot] public string[] separatorSlotNames = new string[0]; [UnityEngine.Serialization.FormerlySerializedAs("submeshSeparators")] [SpineSlot] public string[] separatorSlotNames = new string[0];
[System.NonSerialized] public readonly List<Slot> separatorSlots = new List<Slot>(); [System.NonSerialized] public readonly List<Slot> separatorSlots = new List<Slot>();
[Range(-0.1f, 0f)] public float zSpacing; [Range(-0.1f, 0f)] public float zSpacing;
//public bool renderMeshes = true; //public bool renderMeshes = true;
public bool useClipping = true; public bool useClipping = true;
public bool immutableTriangles = false; public bool immutableTriangles = false;
public bool pmaVertexColors = true; public bool pmaVertexColors = true;
/// <summary>Clears the state when this component or its GameObject is disabled. This prevents previous state from being retained when it is enabled again. When pooling your skeleton, setting this to true can be helpful.</summary> /// <summary>Clears the state when this component or its GameObject is disabled. This prevents previous state from being retained when it is enabled again. When pooling your skeleton, setting this to true can be helpful.</summary>
public bool clearStateOnDisable = false; public bool clearStateOnDisable = false;
public bool tintBlack = false; public bool tintBlack = false;
public bool singleSubmesh = false; public bool singleSubmesh = false;
[UnityEngine.Serialization.FormerlySerializedAs("calculateNormals")] [UnityEngine.Serialization.FormerlySerializedAs("calculateNormals")]
public bool addNormals = false; public bool addNormals = false;
public bool calculateTangents = false; public bool calculateTangents = false;
public bool logErrors = false; public bool logErrors = false;
#if SPINE_OPTIONAL_RENDEROVERRIDE #if SPINE_OPTIONAL_RENDEROVERRIDE
public bool disableRenderingOnOverride = true; public bool disableRenderingOnOverride = true;
public delegate void InstructionDelegate (SkeletonRendererInstruction instruction); public delegate void InstructionDelegate (SkeletonRendererInstruction instruction);
event InstructionDelegate generateMeshOverride; event InstructionDelegate generateMeshOverride;
public event InstructionDelegate GenerateMeshOverride { public event InstructionDelegate GenerateMeshOverride {
add { add {
generateMeshOverride += value; generateMeshOverride += value;
if (disableRenderingOnOverride && generateMeshOverride != null) { if (disableRenderingOnOverride && generateMeshOverride != null) {
Initialize(false); Initialize(false);
meshRenderer.enabled = false; meshRenderer.enabled = false;
} }
} }
remove { remove {
generateMeshOverride -= value; generateMeshOverride -= value;
if (disableRenderingOnOverride && generateMeshOverride == null) { if (disableRenderingOnOverride && generateMeshOverride == null) {
Initialize(false); Initialize(false);
meshRenderer.enabled = true; meshRenderer.enabled = true;
} }
} }
} }
#endif #endif
#if SPINE_OPTIONAL_MATERIALOVERRIDE #if SPINE_OPTIONAL_MATERIALOVERRIDE
[System.NonSerialized] readonly Dictionary<Material, Material> customMaterialOverride = new Dictionary<Material, Material>(); [System.NonSerialized] readonly Dictionary<Material, Material> customMaterialOverride = new Dictionary<Material, Material>();
public Dictionary<Material, Material> CustomMaterialOverride { get { return customMaterialOverride; } } public Dictionary<Material, Material> CustomMaterialOverride { get { return customMaterialOverride; } }
#endif #endif
// Custom Slot Material // Custom Slot Material
[System.NonSerialized] readonly Dictionary<Slot, Material> customSlotMaterials = new Dictionary<Slot, Material>(); [System.NonSerialized] readonly Dictionary<Slot, Material> customSlotMaterials = new Dictionary<Slot, Material>();
public Dictionary<Slot, Material> CustomSlotMaterials { get { return customSlotMaterials; } } public Dictionary<Slot, Material> CustomSlotMaterials { get { return customSlotMaterials; } }
#endregion #endregion
MeshRenderer meshRenderer; MeshRenderer meshRenderer;
MeshFilter meshFilter; MeshFilter meshFilter;
[System.NonSerialized] public bool valid; [System.NonSerialized] public bool valid;
[System.NonSerialized] public Skeleton skeleton; [System.NonSerialized] public Skeleton skeleton;
public Skeleton Skeleton { public Skeleton Skeleton {
get { get {
Initialize(false); Initialize(false);
return skeleton; return skeleton;
} }
} }
[System.NonSerialized] readonly SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction(); [System.NonSerialized] readonly SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction();
readonly MeshGenerator meshGenerator = new MeshGenerator(); readonly MeshGenerator meshGenerator = new MeshGenerator();
[System.NonSerialized] readonly MeshRendererBuffers rendererBuffers = new MeshRendererBuffers(); [System.NonSerialized] readonly MeshRendererBuffers rendererBuffers = new MeshRendererBuffers();
#region Runtime Instantiation #region Runtime Instantiation
public static T NewSpineGameObject<T> (SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer { public static T NewSpineGameObject<T> (SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer {
return SkeletonRenderer.AddSpineComponent<T>(new GameObject("New Spine GameObject"), skeletonDataAsset); return SkeletonRenderer.AddSpineComponent<T>(new GameObject("New Spine GameObject"), skeletonDataAsset);
} }
/// <summary>Add and prepare a Spine component that derives from SkeletonRenderer to a GameObject at runtime.</summary> /// <summary>Add and prepare a Spine component that derives from SkeletonRenderer to a GameObject at runtime.</summary>
/// <typeparam name="T">T should be SkeletonRenderer or any of its derived classes.</typeparam> /// <typeparam name="T">T should be SkeletonRenderer or any of its derived classes.</typeparam>
public static T AddSpineComponent<T> (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer { public static T AddSpineComponent<T> (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer {
var c = gameObject.AddComponent<T>(); var c = gameObject.AddComponent<T>();
if (skeletonDataAsset != null) { if (skeletonDataAsset != null) {
c.skeletonDataAsset = skeletonDataAsset; c.skeletonDataAsset = skeletonDataAsset;
c.Initialize(false); c.Initialize(false);
} }
return c; return c;
} }
/// <summary>Applies MeshGenerator settings to the SkeletonRenderer and its internal MeshGenerator.</summary> /// <summary>Applies MeshGenerator settings to the SkeletonRenderer and its internal MeshGenerator.</summary>
public void SetMeshSettings (MeshGenerator.Settings settings) { public void SetMeshSettings (MeshGenerator.Settings settings) {
this.calculateTangents = settings.calculateTangents; this.calculateTangents = settings.calculateTangents;
this.immutableTriangles = settings.immutableTriangles; this.immutableTriangles = settings.immutableTriangles;
this.pmaVertexColors = settings.pmaVertexColors; this.pmaVertexColors = settings.pmaVertexColors;
this.tintBlack = settings.tintBlack; this.tintBlack = settings.tintBlack;
this.useClipping = settings.useClipping; this.useClipping = settings.useClipping;
this.zSpacing = settings.zSpacing; this.zSpacing = settings.zSpacing;
this.meshGenerator.settings = settings; this.meshGenerator.settings = settings;
} }
#endregion #endregion
public virtual void Awake () { public virtual void Awake () {
Initialize(false); Initialize(false);
} }
void OnDisable () { void OnDisable () {
if (clearStateOnDisable && valid) if (clearStateOnDisable && valid)
ClearState(); ClearState();
} }
void OnDestroy () { void OnDestroy () {
rendererBuffers.Dispose(); rendererBuffers.Dispose();
valid = false; valid = false;
} }
/// <summary> /// <summary>
/// Clears the previously generated mesh and resets the skeleton's pose.</summary> /// Clears the previously generated mesh and resets the skeleton's pose.</summary>
public virtual void ClearState () { public virtual void ClearState () {
meshFilter.sharedMesh = null; meshFilter.sharedMesh = null;
currentInstructions.Clear(); currentInstructions.Clear();
if (skeleton != null) skeleton.SetToSetupPose(); if (skeleton != null) skeleton.SetToSetupPose();
} }
/// <summary> /// <summary>
/// Initialize this component. Attempts to load the SkeletonData and creates the internal Skeleton object and buffers.</summary> /// Initialize this component. Attempts to load the SkeletonData and creates the internal Skeleton object and buffers.</summary>
/// <param name="overwrite">If set to <c>true</c>, it will overwrite internal objects if they were already generated. Otherwise, the initialized component will ignore subsequent calls to initialize.</param> /// <param name="overwrite">If set to <c>true</c>, it will overwrite internal objects if they were already generated. Otherwise, the initialized component will ignore subsequent calls to initialize.</param>
public virtual void Initialize (bool overwrite) { public virtual void Initialize (bool overwrite) {
if (valid && !overwrite) if (valid && !overwrite)
return; return;
// Clear // Clear
{ {
if (meshFilter != null) if (meshFilter != null)
meshFilter.sharedMesh = null; meshFilter.sharedMesh = null;
meshRenderer = GetComponent<MeshRenderer>(); meshRenderer = GetComponent<MeshRenderer>();
if (meshRenderer != null) meshRenderer.sharedMaterial = null; if (meshRenderer != null) meshRenderer.sharedMaterial = null;
currentInstructions.Clear(); currentInstructions.Clear();
rendererBuffers.Clear(); rendererBuffers.Clear();
meshGenerator.Begin(); meshGenerator.Begin();
skeleton = null; skeleton = null;
valid = false; valid = false;
} }
if (!skeletonDataAsset) { if (!skeletonDataAsset) {
if (logErrors) Debug.LogError("Missing SkeletonData asset.", this); if (logErrors) Debug.LogError("Missing SkeletonData asset.", this);
return; return;
} }
SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false); SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false);
if (skeletonData == null) return; if (skeletonData == null) return;
valid = true; valid = true;
meshFilter = GetComponent<MeshFilter>(); meshFilter = GetComponent<MeshFilter>();
meshRenderer = GetComponent<MeshRenderer>(); meshRenderer = GetComponent<MeshRenderer>();
rendererBuffers.Initialize(); rendererBuffers.Initialize();
skeleton = new Skeleton(skeletonData) { skeleton = new Skeleton(skeletonData) {
flipX = initialFlipX, flipX = initialFlipX,
flipY = initialFlipY flipY = initialFlipY
}; };
if (!string.IsNullOrEmpty(initialSkinName) && !string.Equals(initialSkinName, "default", System.StringComparison.Ordinal)) if (!string.IsNullOrEmpty(initialSkinName) && !string.Equals(initialSkinName, "default", System.StringComparison.Ordinal))
skeleton.SetSkin(initialSkinName); skeleton.SetSkin(initialSkinName);
separatorSlots.Clear(); separatorSlots.Clear();
for (int i = 0; i < separatorSlotNames.Length; i++) for (int i = 0; i < separatorSlotNames.Length; i++)
separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i])); separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i]));
LateUpdate(); // Generate mesh for the first frame it exists. LateUpdate(); // Generate mesh for the first frame it exists.
if (OnRebuild != null) if (OnRebuild != null)
OnRebuild(this); OnRebuild(this);
} }
/// <summary> /// <summary>
/// Generates a new UnityEngine.Mesh from the internal Skeleton.</summary> /// Generates a new UnityEngine.Mesh from the internal Skeleton.</summary>
public virtual void LateUpdate () { public virtual void LateUpdate () {
if (!valid) return; if (!valid) return;
#if SPINE_OPTIONAL_RENDEROVERRIDE #if SPINE_OPTIONAL_RENDEROVERRIDE
bool doMeshOverride = generateMeshOverride != null; bool doMeshOverride = generateMeshOverride != null;
if ((!meshRenderer.enabled) && !doMeshOverride) return; if ((!meshRenderer.enabled) && !doMeshOverride) return;
#else #else
const bool doMeshOverride = false; const bool doMeshOverride = false;
if (!meshRenderer.enabled) return; if (!meshRenderer.enabled) return;
#endif #endif
var currentInstructions = this.currentInstructions; var currentInstructions = this.currentInstructions;
var workingSubmeshInstructions = currentInstructions.submeshInstructions; var workingSubmeshInstructions = currentInstructions.submeshInstructions;
var currentSmartMesh = rendererBuffers.GetNextMesh(); // Double-buffer for performance. var currentSmartMesh = rendererBuffers.GetNextMesh(); // Double-buffer for performance.
bool updateTriangles; bool updateTriangles;
if (this.singleSubmesh) { if (this.singleSubmesh) {
// STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. ============================================= // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. =============================================
MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, skeletonDataAsset.atlasAssets[0].materials[0]); MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, skeletonDataAsset.atlasAssets[0].materials[0]);
// STEP 1.9. Post-process workingInstructions. ================================================================================== // STEP 1.9. Post-process workingInstructions. ==================================================================================
#if SPINE_OPTIONAL_MATERIALOVERRIDE #if SPINE_OPTIONAL_MATERIALOVERRIDE
if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated
MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride); MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride);
#endif #endif
// STEP 2. Update vertex buffer based on verts from the attachments. =========================================================== // STEP 2. Update vertex buffer based on verts from the attachments. ===========================================================
meshGenerator.settings = new MeshGenerator.Settings { meshGenerator.settings = new MeshGenerator.Settings {
pmaVertexColors = this.pmaVertexColors, pmaVertexColors = this.pmaVertexColors,
zSpacing = this.zSpacing, zSpacing = this.zSpacing,
useClipping = this.useClipping, useClipping = this.useClipping,
tintBlack = this.tintBlack, tintBlack = this.tintBlack,
calculateTangents = this.calculateTangents, calculateTangents = this.calculateTangents,
addNormals = this.addNormals addNormals = this.addNormals
}; };
meshGenerator.Begin(); meshGenerator.Begin();
updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed); updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed);
if (currentInstructions.hasActiveClipping) { if (currentInstructions.hasActiveClipping) {
meshGenerator.AddSubmesh(workingSubmeshInstructions.Items[0], updateTriangles); meshGenerator.AddSubmesh(workingSubmeshInstructions.Items[0], updateTriangles);
} else { } else {
meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles);
} }
} else { } else {
// STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. ============================================= // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. =============================================
MeshGenerator.GenerateSkeletonRendererInstruction(currentInstructions, skeleton, customSlotMaterials, separatorSlots, doMeshOverride, this.immutableTriangles); MeshGenerator.GenerateSkeletonRendererInstruction(currentInstructions, skeleton, customSlotMaterials, separatorSlots, doMeshOverride, this.immutableTriangles);
// STEP 1.9. Post-process workingInstructions. ================================================================================== // STEP 1.9. Post-process workingInstructions. ==================================================================================
#if SPINE_OPTIONAL_MATERIALOVERRIDE #if SPINE_OPTIONAL_MATERIALOVERRIDE
if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated
MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride); MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride);
#endif #endif
#if SPINE_OPTIONAL_RENDEROVERRIDE #if SPINE_OPTIONAL_RENDEROVERRIDE
if (doMeshOverride) { if (doMeshOverride) {
this.generateMeshOverride(currentInstructions); this.generateMeshOverride(currentInstructions);
if (disableRenderingOnOverride) return; if (disableRenderingOnOverride) return;
} }
#endif #endif
updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed); updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed);
// STEP 2. Update vertex buffer based on verts from the attachments. =========================================================== // STEP 2. Update vertex buffer based on verts from the attachments. ===========================================================
meshGenerator.settings = new MeshGenerator.Settings { meshGenerator.settings = new MeshGenerator.Settings {
pmaVertexColors = this.pmaVertexColors, pmaVertexColors = this.pmaVertexColors,
zSpacing = this.zSpacing, zSpacing = this.zSpacing,
useClipping = this.useClipping, useClipping = this.useClipping,
tintBlack = this.tintBlack, tintBlack = this.tintBlack,
calculateTangents = this.calculateTangents, calculateTangents = this.calculateTangents,
addNormals = this.addNormals addNormals = this.addNormals
}; };
meshGenerator.Begin(); meshGenerator.Begin();
if (currentInstructions.hasActiveClipping) if (currentInstructions.hasActiveClipping)
meshGenerator.BuildMesh(currentInstructions, updateTriangles); meshGenerator.BuildMesh(currentInstructions, updateTriangles);
else else
meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles);
} }
if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers); if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers);
// STEP 3. Move the mesh data into a UnityEngine.Mesh =========================================================================== // STEP 3. Move the mesh data into a UnityEngine.Mesh ===========================================================================
var currentMesh = currentSmartMesh.mesh; var currentMesh = currentSmartMesh.mesh;
meshGenerator.FillVertexData(currentMesh); meshGenerator.FillVertexData(currentMesh);
rendererBuffers.UpdateSharedMaterials(workingSubmeshInstructions); rendererBuffers.UpdateSharedMaterials(workingSubmeshInstructions);
if (updateTriangles) { // Check if the triangles should also be updated. if (updateTriangles) { // Check if the triangles should also be updated.
meshGenerator.FillTriangles(currentMesh); meshGenerator.FillTriangles(currentMesh);
meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray(); meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray();
} else if (rendererBuffers.MaterialsChangedInLastUpdate()) { } else if (rendererBuffers.MaterialsChangedInLastUpdate()) {
meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray(); meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray();
} }
// STEP 4. The UnityEngine.Mesh is ready. Set it as the MeshFilter's mesh. Store the instructions used for that mesh. =========== // STEP 4. The UnityEngine.Mesh is ready. Set it as the MeshFilter's mesh. Store the instructions used for that mesh. ===========
meshFilter.sharedMesh = currentMesh; meshFilter.sharedMesh = currentMesh;
currentSmartMesh.instructionUsed.Set(currentInstructions); currentSmartMesh.instructionUsed.Set(currentInstructions);
} }
} }
} }

View File

@ -274,6 +274,9 @@ namespace Spine.Unity.Editor {
EditorGUILayout.LabelField("spine-tk2d", EditorStyles.boldLabel); EditorGUILayout.LabelField("spine-tk2d", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(spriteCollection, true); EditorGUILayout.PropertyField(spriteCollection, true);
#endif #endif
if (atlasAssets.arraySize == 0)
EditorGUILayout.HelpBox("AtlasAssets array is empty. Skeleton's attachments will load without being mapped to images.", MessageType.Info);
} }
void HandleAtlasAssetsNulls () { void HandleAtlasAssetsNulls () {
@ -485,7 +488,7 @@ namespace Spine.Unity.Editor {
} }
void DrawWarningList () { void DrawWarningList () {
foreach (var line in warnings) foreach (string line in warnings)
EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(line, Icons.warning)); EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(line, Icons.warning));
} }
@ -525,25 +528,30 @@ namespace Spine.Unity.Editor {
if (detectedNullAtlasEntry) { if (detectedNullAtlasEntry) {
warnings.Add("AtlasAsset elements should not be null."); warnings.Add("AtlasAsset elements should not be null.");
} else { } else {
var missingPaths = SpineEditorUtilities.GetRequiredAtlasRegions(AssetDatabase.GetAssetPath(skeletonJSON.objectReferenceValue)); List<string> missingPaths = null;
if (atlasAssets.arraySize > 0) {
missingPaths = SpineEditorUtilities.GetRequiredAtlasRegions(AssetDatabase.GetAssetPath(skeletonJSON.objectReferenceValue));
foreach (var atlas in atlasList) { foreach (var atlas in atlasList) {
for (int i = 0; i < missingPaths.Count; i++) { for (int i = 0; i < missingPaths.Count; i++) {
if (atlas.FindRegion(missingPaths[i]) != null) { if (atlas.FindRegion(missingPaths[i]) != null) {
missingPaths.RemoveAt(i); missingPaths.RemoveAt(i);
i--; i--;
}
} }
} }
#if SPINE_TK2D
if (missingPaths.Count > 0)
warnings.Add("Missing regions. SkeletonDataAsset requires tk2DSpriteCollectionData or Spine AtlasAssets.");
#endif
} }
#if SPINE_TK2D if (missingPaths != null) {
if (missingPaths.Count > 0) foreach (string str in missingPaths)
warnings.Add("Missing regions. SkeletonDataAsset requires tk2DSpriteCollectionData or Spine AtlasAssets."); warnings.Add("Missing Region: '" + str + "'");
#endif }
foreach (var str in missingPaths)
warnings.Add("Missing Region: '" + str + "'");
} }
} }
@ -629,7 +637,10 @@ namespace Spine.Unity.Editor {
PreviewRenderUtility previewRenderUtility; PreviewRenderUtility previewRenderUtility;
Camera PreviewUtilityCamera { Camera PreviewUtilityCamera {
get { get {
if (previewRenderUtility == null) return null; if (previewRenderUtility == null) {
return null;
}
#if UNITY_2017_1_OR_NEWER #if UNITY_2017_1_OR_NEWER
return previewRenderUtility.camera; return previewRenderUtility.camera;
@ -770,7 +781,7 @@ namespace Spine.Unity.Editor {
skeleton.SetToSetupPose(); skeleton.SetToSetupPose();
animationState.SetAnimation(0, targetAnimation, loop); animationState.SetAnimation(0, targetAnimation, loop);
} else { } else {
var sameAnimation = (currentTrack.Animation == targetAnimation); bool sameAnimation = (currentTrack.Animation == targetAnimation);
if (sameAnimation) { if (sameAnimation) {
currentTrack.TimeScale = (currentTrack.TimeScale == 0) ? 1f : 0f; // pause/play currentTrack.TimeScale = (currentTrack.TimeScale == 0) ? 1f : 0f; // pause/play
} else { } else {
@ -974,18 +985,19 @@ namespace Spine.Unity.Editor {
for (int i = 0; i < currentAnimationEvents.Count; i++) { for (int i = 0; i < currentAnimationEvents.Count; i++) {
float fr = currentAnimationEventTimes[i]; float fr = currentAnimationEventTimes[i];
var evRect = new Rect(barRect); var evRect = new Rect(barRect) {
evRect.x = Mathf.Clamp(((fr / t.Animation.Duration) * width) - (Icons.userEvent.width / 2), barRect.x, float.MaxValue); x = Mathf.Clamp(((fr / t.Animation.Duration) * width) - (Icons.userEvent.width / 2), barRect.x, float.MaxValue),
evRect.width = Icons.userEvent.width; y = barRect.y + Icons.userEvent.height,
evRect.height = Icons.userEvent.height; width = Icons.userEvent.width,
evRect.y += Icons.userEvent.height; height = Icons.userEvent.height
};
GUI.DrawTexture(evRect, Icons.userEvent); GUI.DrawTexture(evRect, Icons.userEvent);
Event ev = Event.current; Event ev = Event.current;
if (ev.type == EventType.Repaint) { if (ev.type == EventType.Repaint) {
if (evRect.Contains(ev.mousePosition)) { if (evRect.Contains(ev.mousePosition)) {
Rect tooltipRect = new Rect(evRect);
GUIStyle tooltipStyle = EditorStyles.helpBox; GUIStyle tooltipStyle = EditorStyles.helpBox;
Rect tooltipRect = new Rect(evRect);
tooltipRect.width = tooltipStyle.CalcSize(new GUIContent(currentAnimationEvents[i].Data.Name)).x; tooltipRect.width = tooltipStyle.CalcSize(new GUIContent(currentAnimationEvents[i].Data.Name)).x;
tooltipRect.y -= 4; tooltipRect.y -= 4;
tooltipRect.x += 4; tooltipRect.x += 4;

View File

@ -155,16 +155,15 @@ namespace Spine.Unity.Editor {
public static string editorGUIPath = ""; public static string editorGUIPath = "";
public static bool initialized; public static bool initialized;
/// This list keeps the asset reference temporarily during importing. /// HACK: This list keeps the asset reference temporarily during importing.
/// ///
/// In cases of very large projects/sufficient RAM pressure, when AssetDatabase.SaveAssets is called, /// In cases of very large projects/sufficient RAM pressure, when AssetDatabase.SaveAssets is called,
/// Unity can mistakenly unload assets whose references are only on the stack. /// Unity can mistakenly unload assets whose references are only on the stack.
/// This leads to MissingReferenceException and other errors. /// This leads to MissingReferenceException and other errors.
static readonly List<ScriptableObject> protectFromStackGarbageCollection = new List<ScriptableObject>(); static readonly List<ScriptableObject> protectFromStackGarbageCollection = new List<ScriptableObject>();
static HashSet<string> assetsImportedInWrongState; static HashSet<string> assetsImportedInWrongState = new HashSet<string>();
static Dictionary<int, GameObject> skeletonRendererTable;
static Dictionary<int, SkeletonUtilityBone> skeletonUtilityBoneTable;
static Dictionary<int, BoundingBoxFollower> boundingBoxFollowerTable;
#if SPINE_TK2D #if SPINE_TK2D
const float DEFAULT_DEFAULT_SCALE = 1f; const float DEFAULT_DEFAULT_SCALE = 1f;
@ -220,29 +219,23 @@ namespace Spine.Unity.Editor {
Icons.Initialize(); Icons.Initialize();
assetsImportedInWrongState = new HashSet<string>();
skeletonRendererTable = new Dictionary<int, GameObject>();
skeletonUtilityBoneTable = new Dictionary<int, SkeletonUtilityBone>();
boundingBoxFollowerTable = new Dictionary<int, BoundingBoxFollower>();
// Drag and Drop // Drag and Drop
SceneView.onSceneGUIDelegate -= SceneViewDragAndDrop; SceneView.onSceneGUIDelegate -= SceneViewDragAndDrop;
SceneView.onSceneGUIDelegate += SceneViewDragAndDrop; SceneView.onSceneGUIDelegate += SceneViewDragAndDrop;
EditorApplication.hierarchyWindowItemOnGUI -= HierarchyDragAndDrop; EditorApplication.hierarchyWindowItemOnGUI -= SpineEditorHierarchyHandler.HierarchyDragAndDrop;
EditorApplication.hierarchyWindowItemOnGUI += HierarchyDragAndDrop; EditorApplication.hierarchyWindowItemOnGUI += SpineEditorHierarchyHandler.HierarchyDragAndDrop;
// Hierarchy Icons // Hierarchy Icons
#if UNITY_2017_2_OR_NEWER #if UNITY_2017_2_OR_NEWER
EditorApplication.playModeStateChanged -= HierarchyIconsOnPlaymodeStateChanged; EditorApplication.playModeStateChanged -= SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged;
EditorApplication.playModeStateChanged += HierarchyIconsOnPlaymodeStateChanged; EditorApplication.playModeStateChanged += SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged;
HierarchyIconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode);
#else #else
EditorApplication.playmodeStateChanged -= HierarchyIconsOnPlaymodeStateChanged; EditorApplication.playmodeStateChanged -= SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged;
EditorApplication.playmodeStateChanged += HierarchyIconsOnPlaymodeStateChanged; EditorApplication.playmodeStateChanged += SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged;
HierarchyIconsOnPlaymodeStateChanged(); SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged();
#endif #endif
initialized = true; initialized = true;
} }
@ -265,9 +258,9 @@ namespace Spine.Unity.Editor {
if (EditorGUI.EndChangeCheck()) { if (EditorGUI.EndChangeCheck()) {
EditorPrefs.SetBool(SHOW_HIERARCHY_ICONS_KEY, showHierarchyIcons); EditorPrefs.SetBool(SHOW_HIERARCHY_ICONS_KEY, showHierarchyIcons);
#if UNITY_2017_2_OR_NEWER #if UNITY_2017_2_OR_NEWER
HierarchyIconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode);
#else #else
HierarchyIconsOnPlaymodeStateChanged(); SpineEditorHierarchyHandler.HierarchyIconsOnPlaymodeStateChanged();
#endif #endif
} }
@ -323,10 +316,9 @@ namespace Spine.Unity.Editor {
#endregion #endregion
#region Drag and Drop Instantiation #region Drag and Drop Instantiation
public delegate Component InstantiateDelegate (SkeletonDataAsset skeletonDataAsset); public delegate Component InstantiateDelegate (SkeletonDataAsset skeletonDataAsset);
struct SpawnMenuData { public struct SpawnMenuData {
public Vector3 spawnPoint; public Vector3 spawnPoint;
public SkeletonDataAsset skeletonDataAsset; public SkeletonDataAsset skeletonDataAsset;
public InstantiateDelegate instantiateDelegate; public InstantiateDelegate instantiateDelegate;
@ -339,7 +331,7 @@ namespace Spine.Unity.Editor {
public bool isUI; public bool isUI;
} }
public static readonly List<SkeletonComponentSpawnType> additionalSpawnTypes = new List<SkeletonComponentSpawnType>(); internal static readonly List<SkeletonComponentSpawnType> additionalSpawnTypes = new List<SkeletonComponentSpawnType>();
static void SceneViewDragAndDrop (SceneView sceneview) { static void SceneViewDragAndDrop (SceneView sceneview) {
var current = UnityEngine.Event.current; var current = UnityEngine.Event.current;
@ -378,45 +370,6 @@ namespace Spine.Unity.Editor {
} }
} }
static void HierarchyDragAndDrop (int instanceId, Rect selectionRect) {
// HACK: Uses EditorApplication.hierarchyWindowItemOnGUI.
// Only works when there is at least one item in the scene.
var current = UnityEngine.Event.current;
var eventType = current.type;
bool isDraggingEvent = eventType == EventType.DragUpdated;
bool isDropEvent = eventType == EventType.DragPerform;
if (isDraggingEvent || isDropEvent) {
var mouseOverWindow = EditorWindow.mouseOverWindow;
if (mouseOverWindow != null) {
// One, existing, valid SkeletonDataAsset
var references = DragAndDrop.objectReferences;
if (references.Length == 1) {
var skeletonDataAsset = references[0] as SkeletonDataAsset;
if (skeletonDataAsset != null && skeletonDataAsset.GetSkeletonData(true) != null) {
// Allow drag-and-dropping anywhere in the Hierarchy Window.
// HACK: string-compare because we can't get its type via reflection.
const string HierarchyWindow = "UnityEditor.SceneHierarchyWindow";
if (HierarchyWindow.Equals(mouseOverWindow.GetType().ToString(), System.StringComparison.Ordinal)) {
if (isDraggingEvent) {
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
current.Use();
} else if (isDropEvent) {
ShowInstantiateContextMenu(skeletonDataAsset, Vector3.zero);
DragAndDrop.AcceptDrag();
current.Use();
return;
}
}
}
}
}
}
}
public static void ShowInstantiateContextMenu (SkeletonDataAsset skeletonDataAsset, Vector3 spawnPoint) { public static void ShowInstantiateContextMenu (SkeletonDataAsset skeletonDataAsset, Vector3 spawnPoint) {
var menu = new GenericMenu(); var menu = new GenericMenu();
@ -454,8 +407,8 @@ namespace Spine.Unity.Editor {
menu.ShowAsContext(); menu.ShowAsContext();
} }
public static void HandleSkeletonComponentDrop (object menuData) { public static void HandleSkeletonComponentDrop (object spawnMenuData) {
var data = (SpawnMenuData)menuData; var data = (SpawnMenuData)spawnMenuData;
if (data.skeletonDataAsset.GetSkeletonData(true) == null) { if (data.skeletonDataAsset.GetSkeletonData(true) == null) {
EditorUtility.DisplayDialog("Invalid SkeletonDataAsset", "Unable to create Spine GameObject.\n\nPlease check your SkeletonDataAsset.", "Ok"); EditorUtility.DisplayDialog("Invalid SkeletonDataAsset", "Unable to create Spine GameObject.\n\nPlease check your SkeletonDataAsset.", "Ok");
@ -464,16 +417,15 @@ namespace Spine.Unity.Editor {
bool isUI = data.isUI; bool isUI = data.isUI;
GameObject newGameObject = null;
Component newSkeletonComponent = data.instantiateDelegate.Invoke(data.skeletonDataAsset); Component newSkeletonComponent = data.instantiateDelegate.Invoke(data.skeletonDataAsset);
newGameObject = newSkeletonComponent.gameObject; GameObject newGameObject = newSkeletonComponent.gameObject;
var transform = newGameObject.transform; Transform newTransform = newGameObject.transform;
var activeGameObject = Selection.activeGameObject; var activeGameObject = Selection.activeGameObject;
if (isUI && activeGameObject != null) if (isUI && activeGameObject != null)
transform.SetParent(activeGameObject.transform, false); newTransform.SetParent(activeGameObject.transform, false);
newGameObject.transform.position = isUI ? data.spawnPoint : RoundVector(data.spawnPoint, 2); newTransform.position = isUI ? data.spawnPoint : RoundVector(data.spawnPoint, 2);
if (isUI && (activeGameObject == null || activeGameObject.GetComponent<RectTransform>() == null)) if (isUI && (activeGameObject == null || activeGameObject.GetComponent<RectTransform>() == null))
Debug.Log("Created a UI Skeleton GameObject not under a RectTransform. It may not be visible until you parent it to a canvas."); Debug.Log("Created a UI Skeleton GameObject not under a RectTransform. It may not be visible until you parent it to a canvas.");
@ -509,72 +461,117 @@ namespace Spine.Unity.Editor {
#endregion #endregion
#region Hierarchy #region Hierarchy
#if UNITY_2017_2_OR_NEWER static class SpineEditorHierarchyHandler {
static void HierarchyIconsOnPlaymodeStateChanged (PlayModeStateChange stateChange) { static Dictionary<int, GameObject> skeletonRendererTable = new Dictionary<int, GameObject>();
#else static Dictionary<int, SkeletonUtilityBone> skeletonUtilityBoneTable = new Dictionary<int, SkeletonUtilityBone>();
static void HierarchyIconsOnPlaymodeStateChanged () { static Dictionary<int, BoundingBoxFollower> boundingBoxFollowerTable = new Dictionary<int, BoundingBoxFollower>();
#endif
skeletonRendererTable.Clear();
skeletonUtilityBoneTable.Clear();
boundingBoxFollowerTable.Clear();
EditorApplication.hierarchyWindowChanged -= HierarchyIconsOnChanged; #if UNITY_2017_2_OR_NEWER
EditorApplication.hierarchyWindowItemOnGUI -= HierarchyIconsOnGUI; internal static void HierarchyIconsOnPlaymodeStateChanged (PlayModeStateChange stateChange) {
#else
internal static void HierarchyIconsOnPlaymodeStateChanged () {
#endif
skeletonRendererTable.Clear();
skeletonUtilityBoneTable.Clear();
boundingBoxFollowerTable.Clear();
if (!Application.isPlaying && showHierarchyIcons) { EditorApplication.hierarchyWindowChanged -= HierarchyIconsOnChanged;
EditorApplication.hierarchyWindowChanged += HierarchyIconsOnChanged; EditorApplication.hierarchyWindowItemOnGUI -= HierarchyIconsOnGUI;
EditorApplication.hierarchyWindowItemOnGUI += HierarchyIconsOnGUI;
HierarchyIconsOnChanged(); if (!Application.isPlaying && showHierarchyIcons) {
EditorApplication.hierarchyWindowChanged += HierarchyIconsOnChanged;
EditorApplication.hierarchyWindowItemOnGUI += HierarchyIconsOnGUI;
HierarchyIconsOnChanged();
}
} }
}
static void HierarchyIconsOnChanged () { internal static void HierarchyIconsOnChanged () {
skeletonRendererTable.Clear(); skeletonRendererTable.Clear();
skeletonUtilityBoneTable.Clear(); skeletonUtilityBoneTable.Clear();
boundingBoxFollowerTable.Clear(); boundingBoxFollowerTable.Clear();
SkeletonRenderer[] arr = Object.FindObjectsOfType<SkeletonRenderer>(); SkeletonRenderer[] arr = Object.FindObjectsOfType<SkeletonRenderer>();
foreach (SkeletonRenderer r in arr) foreach (SkeletonRenderer r in arr)
skeletonRendererTable.Add(r.gameObject.GetInstanceID(), r.gameObject); skeletonRendererTable[r.gameObject.GetInstanceID()] = r.gameObject;
SkeletonUtilityBone[] boneArr = Object.FindObjectsOfType<SkeletonUtilityBone>(); SkeletonUtilityBone[] boneArr = Object.FindObjectsOfType<SkeletonUtilityBone>();
foreach (SkeletonUtilityBone b in boneArr) foreach (SkeletonUtilityBone b in boneArr)
skeletonUtilityBoneTable.Add(b.gameObject.GetInstanceID(), b); skeletonUtilityBoneTable[b.gameObject.GetInstanceID()] = b;
BoundingBoxFollower[] bbfArr = Object.FindObjectsOfType<BoundingBoxFollower>(); BoundingBoxFollower[] bbfArr = Object.FindObjectsOfType<BoundingBoxFollower>();
foreach (BoundingBoxFollower bbf in bbfArr) foreach (BoundingBoxFollower bbf in bbfArr)
boundingBoxFollowerTable.Add(bbf.gameObject.GetInstanceID(), bbf); boundingBoxFollowerTable[bbf.gameObject.GetInstanceID()] = bbf;
} }
static void HierarchyIconsOnGUI (int instanceId, Rect selectionRect) { internal static void HierarchyIconsOnGUI (int instanceId, Rect selectionRect) {
Rect r = new Rect(selectionRect); Rect r = new Rect(selectionRect);
if (skeletonRendererTable.ContainsKey(instanceId)) { if (skeletonRendererTable.ContainsKey(instanceId)) {
r.x = r.width - 15; r.x = r.width - 15;
r.width = 15; r.width = 15;
GUI.Label(r, Icons.spine); GUI.Label(r, Icons.spine);
} else if (skeletonUtilityBoneTable.ContainsKey(instanceId)) { } else if (skeletonUtilityBoneTable.ContainsKey(instanceId)) {
r.x -= 26; r.x -= 26;
if (skeletonUtilityBoneTable[instanceId] != null) { if (skeletonUtilityBoneTable[instanceId] != null) {
if (skeletonUtilityBoneTable[instanceId].transform.childCount == 0) if (skeletonUtilityBoneTable[instanceId].transform.childCount == 0)
r.x += 13; r.x += 13;
r.y += 2; r.y += 2;
r.width = 13; r.width = 13;
r.height = 13; r.height = 13;
if (skeletonUtilityBoneTable[instanceId].mode == SkeletonUtilityBone.Mode.Follow) if (skeletonUtilityBoneTable[instanceId].mode == SkeletonUtilityBone.Mode.Follow)
GUI.DrawTexture(r, Icons.bone); GUI.DrawTexture(r, Icons.bone);
else else
GUI.DrawTexture(r, Icons.poseBones); GUI.DrawTexture(r, Icons.poseBones);
}
} else if (boundingBoxFollowerTable.ContainsKey(instanceId)) {
r.x -= 26;
if (boundingBoxFollowerTable[instanceId] != null) {
if (boundingBoxFollowerTable[instanceId].transform.childCount == 0)
r.x += 13;
r.y += 2;
r.width = 13;
r.height = 13;
GUI.DrawTexture(r, Icons.boundingBox);
}
} }
} else if (boundingBoxFollowerTable.ContainsKey(instanceId)) { }
r.x -= 26;
if (boundingBoxFollowerTable[instanceId] != null) { internal static void HierarchyDragAndDrop (int instanceId, Rect selectionRect) {
if (boundingBoxFollowerTable[instanceId].transform.childCount == 0) // HACK: Uses EditorApplication.hierarchyWindowItemOnGUI.
r.x += 13; // Only works when there is at least one item in the scene.
r.y += 2; var current = UnityEngine.Event.current;
r.width = 13; var eventType = current.type;
r.height = 13; bool isDraggingEvent = eventType == EventType.DragUpdated;
GUI.DrawTexture(r, Icons.boundingBox); bool isDropEvent = eventType == EventType.DragPerform;
if (isDraggingEvent || isDropEvent) {
var mouseOverWindow = EditorWindow.mouseOverWindow;
if (mouseOverWindow != null) {
// One, existing, valid SkeletonDataAsset
var references = DragAndDrop.objectReferences;
if (references.Length == 1) {
var skeletonDataAsset = references[0] as SkeletonDataAsset;
if (skeletonDataAsset != null && skeletonDataAsset.GetSkeletonData(true) != null) {
// Allow drag-and-dropping anywhere in the Hierarchy Window.
// HACK: string-compare because we can't get its type via reflection.
const string HierarchyWindow = "UnityEditor.SceneHierarchyWindow";
if (HierarchyWindow.Equals(mouseOverWindow.GetType().ToString(), System.StringComparison.Ordinal)) {
if (isDraggingEvent) {
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
current.Use();
} else if (isDropEvent) {
ShowInstantiateContextMenu(skeletonDataAsset, Vector3.zero);
DragAndDrop.AcceptDrag();
current.Use();
return;
}
}
}
}
}
} }
} }
} }
#endregion #endregion
@ -669,7 +666,7 @@ namespace Spine.Unity.Editor {
bool resolved = false; bool resolved = false;
while (!resolved) { while (!resolved) {
var filename = Path.GetFileNameWithoutExtension(sp); string filename = Path.GetFileNameWithoutExtension(sp);
int result = EditorUtility.DisplayDialogComplex( int result = EditorUtility.DisplayDialogComplex(
string.Format("AtlasAsset for \"{0}\"", filename), string.Format("AtlasAsset for \"{0}\"", filename),
string.Format("Could not automatically set the AtlasAsset for \"{0}\". You may set it manually.", filename), string.Format("Could not automatically set the AtlasAsset for \"{0}\". You may set it manually.", filename),
@ -1243,7 +1240,8 @@ namespace Spine.Unity.Editor {
#endregion #endregion
#region Checking Methods #region Checking Methods
static int[][] compatibleVersions = { new[] {3, 6, 0}, new[] {3, 5, 0} }; static int[][] compatibleBinaryVersions = { new[] {3, 6, 0}, new[] {3, 5, 0} };
static int[][] compatibleJsonVersions = { new[] { 3, 6, 0 }, new[] { 3, 7, 0 }, new[] { 3, 5, 0 } };
//static bool isFixVersionRequired = false; //static bool isFixVersionRequired = false;
static bool CheckForValidSkeletonData (string skeletonJSONPath) { static bool CheckForValidSkeletonData (string skeletonJSONPath) {
@ -1269,17 +1267,18 @@ namespace Spine.Unity.Editor {
bool isSpineData = false; bool isSpineData = false;
string rawVersion = null; string rawVersion = null;
int[][] compatibleVersions;
if (asset.name.Contains(".skel")) { if (asset.name.Contains(".skel")) {
try { try {
rawVersion = SkeletonBinary.GetVersionString(new MemoryStream(asset.bytes)); rawVersion = SkeletonBinary.GetVersionString(new MemoryStream(asset.bytes));
//Debug.Log(rawVersion);
isSpineData = !(string.IsNullOrEmpty(rawVersion)); isSpineData = !(string.IsNullOrEmpty(rawVersion));
compatibleVersions = compatibleBinaryVersions;
} catch (System.Exception e) { } catch (System.Exception e) {
Debug.LogErrorFormat("Failed to read '{0}'. It is likely not a binary Spine SkeletonData file.\n{1}", asset.name, e); Debug.LogErrorFormat("Failed to read '{0}'. It is likely not a binary Spine SkeletonData file.\n{1}", asset.name, e);
return false; return false;
} }
} else { } else {
var obj = Json.Deserialize(new StringReader(asset.text)); object obj = Json.Deserialize(new StringReader(asset.text));
if (obj == null) { if (obj == null) {
Debug.LogErrorFormat("'{0}' is not valid JSON.", asset.name); Debug.LogErrorFormat("'{0}' is not valid JSON.", asset.name);
return false; return false;
@ -1298,14 +1297,16 @@ namespace Spine.Unity.Editor {
skeletonInfo.TryGetValue("spine", out jv); skeletonInfo.TryGetValue("spine", out jv);
rawVersion = jv as string; rawVersion = jv as string;
} }
compatibleVersions = compatibleJsonVersions;
} }
// Version warning // Version warning
if (isSpineData) { if (isSpineData) {
string runtimeVersionDebugString = compatibleVersions[0][0] + "." + compatibleVersions[0][1]; string primaryRuntimeVersionDebugString = compatibleVersions[0][0] + "." + compatibleVersions[0][1];
if (string.IsNullOrEmpty(rawVersion)) { if (string.IsNullOrEmpty(rawVersion)) {
Debug.LogWarningFormat("Skeleton '{0}' has no version information. It may be incompatible with your runtime version: spine-unity v{1}", asset.name, runtimeVersionDebugString); Debug.LogWarningFormat("Skeleton '{0}' has no version information. It may be incompatible with your runtime version: spine-unity v{1}", asset.name, primaryRuntimeVersionDebugString);
} else { } else {
string[] versionSplit = rawVersion.Split('.'); string[] versionSplit = rawVersion.Split('.');
bool match = false; bool match = false;
@ -1322,7 +1323,7 @@ namespace Spine.Unity.Editor {
} }
if (!match) if (!match)
Debug.LogWarningFormat("Skeleton '{0}' (exported with Spine {1}) may be incompatible with your runtime version: spine-unity v{2}", asset.name, rawVersion, runtimeVersionDebugString); Debug.LogWarningFormat("Skeleton '{0}' (exported with Spine {1}) may be incompatible with your runtime version: spine-unity v{2}", asset.name, rawVersion, primaryRuntimeVersionDebugString);
} }
} }
@ -1657,11 +1658,12 @@ namespace Spine.Unity.Editor {
public static GUIStyle BoneNameStyle { public static GUIStyle BoneNameStyle {
get { get {
if (_boneNameStyle == null) { if (_boneNameStyle == null) {
_boneNameStyle = new GUIStyle(EditorStyles.whiteMiniLabel); _boneNameStyle = new GUIStyle(EditorStyles.whiteMiniLabel) {
_boneNameStyle.alignment = TextAnchor.MiddleCenter; alignment = TextAnchor.MiddleCenter,
_boneNameStyle.stretchWidth = true; stretchWidth = true,
_boneNameStyle.padding = new RectOffset(0, 0, 0, 0); padding = new RectOffset(0, 0, 0, 0),
_boneNameStyle.contentOffset = new Vector2(-5f, 0f); contentOffset = new Vector2(-5f, 0f)
};
} }
return _boneNameStyle; return _boneNameStyle;
} }
@ -1983,7 +1985,7 @@ namespace Spine.Unity.Editor {
} }
static void DrawArrowhead (Matrix4x4 m) { static void DrawArrowhead (Matrix4x4 m) {
var s = SpineHandles.handleScale; float s = SpineHandles.handleScale;
m.m00 *= s; m.m00 *= s;
m.m01 *= s; m.m01 *= s;
m.m02 *= s; m.m02 *= s;

View File

@ -86,13 +86,34 @@ namespace Spine.Unity.Editor {
#region SerializedProperty Helpers #region SerializedProperty Helpers
public static SerializedProperty FindBaseOrSiblingProperty (this SerializedProperty property, string propertyName) { public static SerializedProperty FindBaseOrSiblingProperty (this SerializedProperty property, string propertyName) {
if (string.IsNullOrEmpty(propertyName)) return null; if (string.IsNullOrEmpty(propertyName)) return null;
SerializedProperty relativeProperty = property.serializedObject.FindProperty(propertyName); // baseProperty SerializedProperty relativeProperty = property.serializedObject.FindProperty(propertyName); // baseProperty
if (relativeProperty == null) { // If no baseProperty, find sibling property.
int nameLength = property.name.Length; // If base property is not found, look for the sibling property.
if (relativeProperty == null) {
string propertyPath = property.propertyPath; string propertyPath = property.propertyPath;
propertyPath = propertyPath.Remove(propertyPath.Length - nameLength, nameLength) + propertyName; int localPathLength = 0;
if (property.isArray) {
const int internalArrayPathLength = 14; // int arrayPathLength = ".Array.data[x]".Length;
int propertyPathLength = propertyPath.Length;
int n = propertyPathLength - internalArrayPathLength;
// Find the dot before the array property name and
// store the total length from the name of the array until the end of the propertyPath.
for (int i = internalArrayPathLength + 1; i < n; i++) {
if (propertyPath[propertyPathLength - i] == '.') {
localPathLength = i - 1;
break;
}
}
} else {
localPathLength = property.name.Length;
}
propertyPath = propertyPath.Remove(propertyPath.Length - localPathLength, localPathLength) + propertyName;
relativeProperty = property.serializedObject.FindProperty(propertyPath); relativeProperty = property.serializedObject.FindProperty(propertyPath);
} }
return relativeProperty; return relativeProperty;
} }
#endregion #endregion

View File

@ -113,6 +113,7 @@ Shader "Spine/Skeleton Lit" {
float3 eyePos = UnityObjectToViewPos(float4(v.pos, 1)).xyz; //mul(UNITY_MATRIX_MV, float4(v.pos,1)).xyz; float3 eyePos = UnityObjectToViewPos(float4(v.pos, 1)).xyz; //mul(UNITY_MATRIX_MV, float4(v.pos,1)).xyz;
half3 fixedNormal = half3(0,0,-1); half3 fixedNormal = half3(0,0,-1);
half3 eyeNormal = normalize(mul((float3x3)UNITY_MATRIX_IT_MV, fixedNormal)); half3 eyeNormal = normalize(mul((float3x3)UNITY_MATRIX_IT_MV, fixedNormal));
//half3 eyeNormal = half3(0,0,1);
half3 viewDir = 0.0; half3 viewDir = 0.0;
// Lights // Lights