/
SpineEditorUtilities.cs
1999 lines (1693 loc) · 76 KB
/
SpineEditorUtilities.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
* 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.
*****************************************************************************/
#pragma warning disable 0219
// Original contribution by: Mitch Thompson
#define SPINE_SKELETONMECANIM
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection;
using Spine;
namespace Spine.Unity.Editor {
using EventType = UnityEngine.EventType;
// Analysis disable once ConvertToStaticType
[InitializeOnLoad]
public class SpineEditorUtilities : AssetPostprocessor {
public static class Icons {
public static Texture2D skeleton;
public static Texture2D nullBone;
public static Texture2D bone;
public static Texture2D poseBones;
public static Texture2D boneNib;
public static Texture2D slot;
public static Texture2D slotRoot;
public static Texture2D skinPlaceholder;
public static Texture2D image;
public static Texture2D genericAttachment;
public static Texture2D boundingBox;
public static Texture2D point;
public static Texture2D mesh;
public static Texture2D weights;
public static Texture2D path;
public static Texture2D clipping;
public static Texture2D skin;
public static Texture2D skinsRoot;
public static Texture2D animation;
public static Texture2D animationRoot;
public static Texture2D spine;
public static Texture2D userEvent;
public static Texture2D constraintNib;
public static Texture2D constraintRoot;
public static Texture2D constraintTransform;
public static Texture2D constraintPath;
public static Texture2D constraintIK;
public static Texture2D warning;
public static Texture2D skeletonUtility;
public static Texture2D hingeChain;
public static Texture2D subMeshRenderer;
public static Texture2D skeletonDataAssetIcon;
public static Texture2D info;
public static Texture2D unity;
// public static Texture2D controllerIcon;
static Texture2D LoadIcon (string filename) {
return (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/" + filename);
}
public static void Initialize () {
skeleton = LoadIcon("icon-skeleton.png");
nullBone = LoadIcon("icon-null.png");
bone = LoadIcon("icon-bone.png");
poseBones = LoadIcon("icon-poseBones.png");
boneNib = LoadIcon("icon-boneNib.png");
slot = LoadIcon("icon-slot.png");
slotRoot = LoadIcon("icon-slotRoot.png");
skinPlaceholder = LoadIcon("icon-skinPlaceholder.png");
genericAttachment = LoadIcon("icon-attachment.png");
image = LoadIcon("icon-image.png");
boundingBox = LoadIcon("icon-boundingBox.png");
point = LoadIcon("icon-point.png");
mesh = LoadIcon("icon-mesh.png");
weights = LoadIcon("icon-weights.png");
path = LoadIcon("icon-path.png");
clipping = LoadIcon("icon-clipping.png");
skin = LoadIcon("icon-skin.png");
skinsRoot = LoadIcon("icon-skinsRoot.png");
animation = LoadIcon("icon-animation.png");
animationRoot = LoadIcon("icon-animationRoot.png");
spine = LoadIcon("icon-spine.png");
userEvent = LoadIcon("icon-event.png");
constraintNib = LoadIcon("icon-constraintNib.png");
constraintRoot = LoadIcon("icon-constraints.png");
constraintTransform = LoadIcon("icon-constraintTransform.png");
constraintPath = LoadIcon("icon-constraintPath.png");
constraintIK = LoadIcon("icon-constraintIK.png");
warning = LoadIcon("icon-warning.png");
skeletonUtility = LoadIcon("icon-skeletonUtility.png");
hingeChain = LoadIcon("icon-hingeChain.png");
subMeshRenderer = LoadIcon("icon-subMeshRenderer.png");
skeletonDataAssetIcon = LoadIcon("SkeletonDataAsset Icon.png");
info = EditorGUIUtility.FindTexture("console.infoicon.sml");
unity = EditorGUIUtility.FindTexture("SceneAsset Icon");
// controllerIcon = EditorGUIUtility.FindTexture("AnimatorController Icon");
}
public static Texture2D GetAttachmentIcon (Attachment attachment) {
// Analysis disable once CanBeReplacedWithTryCastAndCheckForNull
if (attachment is RegionAttachment)
return Icons.image;
else if (attachment is MeshAttachment)
return ((MeshAttachment)attachment).IsWeighted() ? Icons.weights : Icons.mesh;
else if (attachment is BoundingBoxAttachment)
return Icons.boundingBox;
else if (attachment is PointAttachment)
return Icons.point;
else if (attachment is PathAttachment)
return Icons.path;
else if (attachment is ClippingAttachment)
return Icons.clipping;
else
return Icons.warning;
}
}
public static string editorPath = "";
public static string editorGUIPath = "";
public static bool initialized;
// Preferences entry point
[PreferenceItem("Spine")]
static void PreferencesGUI () {
Preferences.HandlePreferencesGUI();
}
// Auto-import entry point
static void OnPostprocessAllAssets (string[] imported, string[] deleted, string[] moved, string[] movedFromAssetPaths) {
if (imported.Length == 0)
return;
AssetUtility.HandleOnPostprocessAllAssets(imported);
}
#region Initialization
static SpineEditorUtilities () {
Initialize();
}
static void Initialize () {
Preferences.Load();
DirectoryInfo rootDir = new DirectoryInfo(Application.dataPath);
FileInfo[] files = rootDir.GetFiles("SpineEditorUtilities.cs", SearchOption.AllDirectories);
editorPath = Path.GetDirectoryName(files[0].FullName.Replace("\\", "/").Replace(Application.dataPath, "Assets"));
editorGUIPath = editorPath + "/GUI";
Icons.Initialize();
// Drag and Drop
SceneView.onSceneGUIDelegate -= DragAndDropInstantiation.SceneViewDragAndDrop;
SceneView.onSceneGUIDelegate += DragAndDropInstantiation.SceneViewDragAndDrop;
EditorApplication.hierarchyWindowItemOnGUI -= HierarchyHandler.HandleDragAndDrop;
EditorApplication.hierarchyWindowItemOnGUI += HierarchyHandler.HandleDragAndDrop;
// Hierarchy Icons
#if UNITY_2017_2_OR_NEWER
EditorApplication.playModeStateChanged -= HierarchyHandler.IconsOnPlaymodeStateChanged;
EditorApplication.playModeStateChanged += HierarchyHandler.IconsOnPlaymodeStateChanged;
HierarchyHandler.IconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode);
#else
EditorApplication.playmodeStateChanged -= HierarchyHandler.IconsOnPlaymodeStateChanged;
EditorApplication.playmodeStateChanged += HierarchyHandler.IconsOnPlaymodeStateChanged;
HierarchyHandler.IconsOnPlaymodeStateChanged();
#endif
initialized = true;
}
public static void ConfirmInitialization () {
if (!initialized || Icons.skeleton == null)
Initialize();
}
#endregion
public static class Preferences {
#if SPINE_TK2D
const float DEFAULT_DEFAULT_SCALE = 1f;
#else
const float DEFAULT_DEFAULT_SCALE = 0.01f;
#endif
const string DEFAULT_SCALE_KEY = "SPINE_DEFAULT_SCALE";
public static float defaultScale = DEFAULT_DEFAULT_SCALE;
const float DEFAULT_DEFAULT_MIX = 0.2f;
const string DEFAULT_MIX_KEY = "SPINE_DEFAULT_MIX";
public static float defaultMix = DEFAULT_DEFAULT_MIX;
const string DEFAULT_DEFAULT_SHADER = "Spine/Skeleton";
const string DEFAULT_SHADER_KEY = "SPINE_DEFAULT_SHADER";
public static string defaultShader = DEFAULT_DEFAULT_SHADER;
const float DEFAULT_DEFAULT_ZSPACING = 0f;
const string DEFAULT_ZSPACING_KEY = "SPINE_DEFAULT_ZSPACING";
public static float defaultZSpacing = DEFAULT_DEFAULT_ZSPACING;
const bool DEFAULT_SHOW_HIERARCHY_ICONS = true;
const string SHOW_HIERARCHY_ICONS_KEY = "SPINE_SHOW_HIERARCHY_ICONS";
public static bool showHierarchyIcons = DEFAULT_SHOW_HIERARCHY_ICONS;
const bool DEFAULT_SET_TEXTUREIMPORTER_SETTINGS = true;
const string SET_TEXTUREIMPORTER_SETTINGS_KEY = "SPINE_SET_TEXTUREIMPORTER_SETTINGS";
public static bool setTextureImporterSettings = DEFAULT_SET_TEXTUREIMPORTER_SETTINGS;
internal const float DEFAULT_MIPMAPBIAS = -0.5f;
public const float DEFAULT_SCENE_ICONS_SCALE = 1f;
public const string SCENE_ICONS_SCALE_KEY = "SPINE_SCENE_ICONS_SCALE";
static bool preferencesLoaded = false;
public static void Load () {
defaultMix = EditorPrefs.GetFloat(DEFAULT_MIX_KEY, DEFAULT_DEFAULT_MIX);
defaultScale = EditorPrefs.GetFloat(DEFAULT_SCALE_KEY, DEFAULT_DEFAULT_SCALE);
defaultZSpacing = EditorPrefs.GetFloat(DEFAULT_ZSPACING_KEY, DEFAULT_DEFAULT_ZSPACING);
defaultShader = EditorPrefs.GetString(DEFAULT_SHADER_KEY, DEFAULT_DEFAULT_SHADER);
showHierarchyIcons = EditorPrefs.GetBool(SHOW_HIERARCHY_ICONS_KEY, DEFAULT_SHOW_HIERARCHY_ICONS);
setTextureImporterSettings = EditorPrefs.GetBool(SET_TEXTUREIMPORTER_SETTINGS_KEY, DEFAULT_SET_TEXTUREIMPORTER_SETTINGS);
SpineHandles.handleScale = EditorPrefs.GetFloat(SCENE_ICONS_SCALE_KEY, DEFAULT_SCENE_ICONS_SCALE);
preferencesLoaded = true;
}
public static void HandlePreferencesGUI () {
if (!preferencesLoaded)
Load();
EditorGUI.BeginChangeCheck();
showHierarchyIcons = EditorGUILayout.Toggle(new GUIContent("Show Hierarchy Icons", "Show relevant icons on GameObjects with Spine Components on them. Disable this if you have large, complex scenes."), showHierarchyIcons);
if (EditorGUI.EndChangeCheck()) {
EditorPrefs.SetBool(SHOW_HIERARCHY_ICONS_KEY, showHierarchyIcons);
#if UNITY_2017_2_OR_NEWER
HierarchyHandler.IconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode);
#else
HierarchyHandler.IconsOnPlaymodeStateChanged();
#endif
}
EditorGUILayout.Separator();
EditorGUILayout.LabelField("Auto-Import Settings", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
defaultMix = EditorGUILayout.FloatField("Default Mix", defaultMix);
if (EditorGUI.EndChangeCheck())
EditorPrefs.SetFloat(DEFAULT_MIX_KEY, defaultMix);
EditorGUI.BeginChangeCheck();
defaultScale = EditorGUILayout.FloatField("Default SkeletonData Scale", defaultScale);
if (EditorGUI.EndChangeCheck())
EditorPrefs.SetFloat(DEFAULT_SCALE_KEY, defaultScale);
EditorGUI.BeginChangeCheck();
var shader = (EditorGUILayout.ObjectField("Default Shader", Shader.Find(defaultShader), typeof(Shader), false) as Shader);
defaultShader = shader != null ? shader.name : DEFAULT_DEFAULT_SHADER;
if (EditorGUI.EndChangeCheck())
EditorPrefs.SetString(DEFAULT_SHADER_KEY, defaultShader);
EditorGUI.BeginChangeCheck();
setTextureImporterSettings = EditorGUILayout.Toggle(new GUIContent("Apply Atlas Texture Settings", "Apply the recommended settings for Texture Importers."), showHierarchyIcons);
if (EditorGUI.EndChangeCheck()) {
EditorPrefs.SetBool(SET_TEXTUREIMPORTER_SETTINGS_KEY, showHierarchyIcons);
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Editor Instantiation", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
defaultZSpacing = EditorGUILayout.Slider("Default Slot Z-Spacing", defaultZSpacing, -0.1f, 0f);
if (EditorGUI.EndChangeCheck())
EditorPrefs.SetFloat(DEFAULT_ZSPACING_KEY, defaultZSpacing);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Handles and Gizmos", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
SpineHandles.handleScale = EditorGUILayout.Slider("Editor Bone Scale", SpineHandles.handleScale, 0.01f, 2f);
SpineHandles.handleScale = Mathf.Max(0.01f, SpineHandles.handleScale);
if (EditorGUI.EndChangeCheck()) {
EditorPrefs.SetFloat(SCENE_ICONS_SCALE_KEY, SpineHandles.handleScale);
SceneView.RepaintAll();
}
GUILayout.Space(20);
EditorGUILayout.LabelField("3rd Party Settings", EditorStyles.boldLabel);
using (new GUILayout.HorizontalScope()) {
EditorGUILayout.PrefixLabel("Define TK2D");
if (GUILayout.Button("Enable", GUILayout.Width(64)))
SpineTK2DEditorUtility.EnableTK2D();
if (GUILayout.Button("Disable", GUILayout.Width(64)))
SpineTK2DEditorUtility.DisableTK2D();
}
}
}
public static class AssetUtility {
public const string SkeletonDataSuffix = "_SkeletonData";
public const string AtlasSuffix = "_Atlas";
static readonly int[][] compatibleBinaryVersions = { new[] { 3, 7, 0 } };
static readonly int[][] compatibleJsonVersions = { new[] { 3, 7, 0 }, new[] { 3, 6, 0 }, new[] { 3, 5, 0 } };
//static bool isFixVersionRequired = false;
/// HACK: This list keeps the asset reference temporarily during importing.
///
/// In cases of very large projects/sufficient RAM pressure, when AssetDatabase.SaveAssets is called,
/// Unity can mistakenly unload assets whose references are only on the stack.
/// This leads to MissingReferenceException and other errors.
public static readonly List<ScriptableObject> protectFromStackGarbageCollection = new List<ScriptableObject>();
public static HashSet<string> assetsImportedInWrongState = new HashSet<string>();
public static void HandleOnPostprocessAllAssets (string[] imported) {
// In case user used "Assets -> Reimport All", during the import process,
// asset database is not initialized until some point. During that period,
// all attempts to load any assets using API (i.e. AssetDatabase.LoadAssetAtPath)
// will return null, and as result, assets won't be loaded even if they actually exists,
// which may lead to numerous importing errors.
// This situation also happens if Library folder is deleted from the project, which is a pretty
// common case, since when using version control systems, the Library folder must be excluded.
//
// So to avoid this, in case asset database is not available, we delay loading the assets
// until next time.
//
// Unity *always* reimports some internal assets after the process is done, so this method
// is always called once again in a state when asset database is available.
//
// Checking whether AssetDatabase is initialized is done by attempting to load
// a known "marker" asset that should always be available. Failing to load this asset
// means that AssetDatabase is not initialized.
AssetUtility.assetsImportedInWrongState.UnionWith(imported);
if (AssetDatabaseAvailabilityDetector.IsAssetDatabaseAvailable()) {
string[] combinedAssets = AssetUtility.assetsImportedInWrongState.ToArray();
AssetUtility.assetsImportedInWrongState.Clear();
AssetUtility.ImportSpineContent(combinedAssets);
}
}
#region Match SkeletonData with Atlases
static readonly AttachmentType[] AtlasTypes = { AttachmentType.Region, AttachmentType.Linkedmesh, AttachmentType.Mesh };
public static List<string> GetRequiredAtlasRegions (string skeletonDataPath) {
List<string> requiredPaths = new List<string>();
if (skeletonDataPath.Contains(".skel")) {
AddRequiredAtlasRegionsFromBinary(skeletonDataPath, requiredPaths);
return requiredPaths;
}
TextAsset spineJson = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonDataPath, typeof(TextAsset));
StringReader reader = new StringReader(spineJson.text);
var root = Json.Deserialize(reader) as Dictionary<string, object>;
if (!root.ContainsKey("skins"))
return requiredPaths;
foreach (var skin in (Dictionary<string, object>)root["skins"]) {
foreach (var slot in (Dictionary<string, object>)skin.Value) {
foreach (var attachment in ((Dictionary<string, object>)slot.Value)) {
var data = ((Dictionary<string, object>)attachment.Value);
// Ignore non-atlas-requiring types.
if (data.ContainsKey("type")) {
AttachmentType attachmentType;
string typeString = (string)data["type"];
try {
attachmentType = (AttachmentType)System.Enum.Parse(typeof(AttachmentType), typeString, true);
} catch (System.ArgumentException e) {
// For more info, visit: http://esotericsoftware.com/forum/Spine-editor-and-runtime-version-management-6534
Debug.LogWarning(string.Format("Unidentified Attachment type: \"{0}\". Skeleton may have been exported from an incompatible Spine version.", typeString));
throw e;
}
if (!AtlasTypes.Contains(attachmentType))
continue;
}
if (data.ContainsKey("path"))
requiredPaths.Add((string)data["path"]);
else if (data.ContainsKey("name"))
requiredPaths.Add((string)data["name"]);
//else
// requiredPaths.Add(attachment.Key);
}
}
}
return requiredPaths;
}
internal static void AddRequiredAtlasRegionsFromBinary (string skeletonDataPath, List<string> requiredPaths) {
SkeletonBinary binary = new SkeletonBinary(new AtlasRequirementLoader(requiredPaths));
TextAsset data = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonDataPath, typeof(TextAsset));
MemoryStream input = new MemoryStream(data.bytes);
binary.ReadSkeletonData(input);
binary = null;
}
internal static AtlasAssetBase GetMatchingAtlas (List<string> requiredPaths, List<AtlasAssetBase> atlasAssets) {
AtlasAssetBase atlasAssetMatch = null;
foreach (AtlasAssetBase a in atlasAssets) {
Atlas atlas = a.GetAtlas();
bool failed = false;
foreach (string regionPath in requiredPaths) {
if (atlas.FindRegion(regionPath) == null) {
failed = true;
break;
}
}
if (!failed) {
atlasAssetMatch = a;
break;
}
}
return atlasAssetMatch;
}
public class AtlasRequirementLoader : AttachmentLoader {
List<string> requirementList;
public AtlasRequirementLoader (List<string> requirementList) {
this.requirementList = requirementList;
}
public RegionAttachment NewRegionAttachment (Skin skin, string name, string path) {
requirementList.Add(path);
return new RegionAttachment(name);
}
public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) {
requirementList.Add(path);
return new MeshAttachment(name);
}
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);
}
}
#endregion
public static void ImportSpineContent (string[] imported, bool reimport = false) {
var atlasPaths = new List<string>();
var imagePaths = new List<string>();
var skeletonPaths = new List<string>();
foreach (string str in imported) {
string extension = Path.GetExtension(str).ToLower();
switch (extension) {
case ".txt":
if (str.EndsWith(".atlas.txt", System.StringComparison.Ordinal))
atlasPaths.Add(str);
break;
case ".png":
case ".jpg":
imagePaths.Add(str);
break;
case ".json":
var jsonAsset = (TextAsset)AssetDatabase.LoadAssetAtPath(str, typeof(TextAsset));
if (jsonAsset != null && IsSpineData(jsonAsset))
skeletonPaths.Add(str);
break;
case ".bytes":
if (str.ToLower().EndsWith(".skel.bytes", System.StringComparison.Ordinal)) {
if (IsSpineData((TextAsset)AssetDatabase.LoadAssetAtPath(str, typeof(TextAsset))))
skeletonPaths.Add(str);
}
break;
}
}
// Import atlases first.
var atlases = new List<AtlasAssetBase>();
foreach (string ap in atlasPaths) {
TextAsset atlasText = (TextAsset)AssetDatabase.LoadAssetAtPath(ap, typeof(TextAsset));
AtlasAssetBase atlas = IngestSpineAtlas(atlasText);
atlases.Add(atlas);
}
// Import skeletons and match them with atlases.
bool abortSkeletonImport = false;
foreach (string skeletonPath in skeletonPaths) {
if (!reimport && CheckForValidSkeletonData(skeletonPath)) {
ReloadSkeletonData(skeletonPath);
continue;
}
string dir = Path.GetDirectoryName(skeletonPath);
#if SPINE_TK2D
IngestSpineProject(AssetDatabase.LoadAssetAtPath(sp, typeof(TextAsset)) as TextAsset, null);
#else
var localAtlases = FindAtlasesAtPath(dir);
var requiredPaths = GetRequiredAtlasRegions(skeletonPath);
var atlasMatch = GetMatchingAtlas(requiredPaths, localAtlases);
if (atlasMatch != null || requiredPaths.Count == 0) {
IngestSpineProject(AssetDatabase.LoadAssetAtPath(skeletonPath, typeof(TextAsset)) as TextAsset, atlasMatch);
} else {
SkeletonImportDialog(skeletonPath, localAtlases, requiredPaths, ref abortSkeletonImport);
}
if (abortSkeletonImport)
break;
#endif
}
// Any post processing of images
}
static void ReloadSkeletonData (string skeletonJSONPath) {
string dir = Path.GetDirectoryName(skeletonJSONPath);
TextAsset textAsset = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonJSONPath, typeof(TextAsset));
DirectoryInfo dirInfo = new DirectoryInfo(dir);
FileInfo[] files = dirInfo.GetFiles("*.asset");
foreach (var f in files) {
string localPath = dir + "/" + f.Name;
var obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object));
var skeletonDataAsset = obj as SkeletonDataAsset;
if (skeletonDataAsset != null) {
if (skeletonDataAsset.skeletonJSON == textAsset) {
if (Selection.activeObject == skeletonDataAsset)
Selection.activeObject = null;
Debug.LogFormat("Changes to '{0}' detected. Clearing SkeletonDataAsset: {1}", skeletonJSONPath, localPath);
skeletonDataAsset.Clear();
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(skeletonDataAsset));
string lastHash = EditorPrefs.GetString(guid + "_hash");
// For some weird reason sometimes Unity loses the internal Object pointer,
// and as a result, all comparisons with null returns true.
// But the C# wrapper is still alive, so we can "restore" the object
// by reloading it from its Instance ID.
AtlasAssetBase[] skeletonDataAtlasAssets = skeletonDataAsset.atlasAssets;
if (skeletonDataAtlasAssets != null) {
for (int i = 0; i < skeletonDataAtlasAssets.Length; i++) {
if (!ReferenceEquals(null, skeletonDataAtlasAssets[i]) &&
skeletonDataAtlasAssets[i].Equals(null) &&
skeletonDataAtlasAssets[i].GetInstanceID() != 0
) {
skeletonDataAtlasAssets[i] = EditorUtility.InstanceIDToObject(skeletonDataAtlasAssets[i].GetInstanceID()) as AtlasAssetBase;
}
}
}
SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(true);
string currentHash = skeletonData != null ? skeletonData.Hash : null;
#if SPINE_SKELETONMECANIM
if (currentHash == null || lastHash != currentHash)
SkeletonBaker.UpdateMecanimClips(skeletonDataAsset);
#endif
// if (currentHash == null || lastHash != currentHash)
// Do any upkeep on synchronized assets
if (currentHash != null)
EditorPrefs.SetString(guid + "_hash", currentHash);
}
}
}
}
#region Import Atlases
static List<AtlasAssetBase> FindAtlasesAtPath (string path) {
List<AtlasAssetBase> arr = new List<AtlasAssetBase>();
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] assetInfoArr = dir.GetFiles("*.asset");
int subLen = Application.dataPath.Length - 6;
foreach (var f in assetInfoArr) {
string assetRelativePath = f.FullName.Substring(subLen, f.FullName.Length - subLen).Replace("\\", "/");
Object obj = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(AtlasAssetBase));
if (obj != null)
arr.Add(obj as AtlasAssetBase);
}
return arr;
}
static AtlasAssetBase IngestSpineAtlas (TextAsset atlasText) {
if (atlasText == null) {
Debug.LogWarning("Atlas source cannot be null!");
return null;
}
string primaryName = Path.GetFileNameWithoutExtension(atlasText.name).Replace(".atlas", "");
string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(atlasText));
string atlasPath = assetPath + "/" + primaryName + AtlasSuffix + ".asset";
SpineAtlasAsset atlasAsset = (SpineAtlasAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(SpineAtlasAsset));
List<Material> vestigialMaterials = new List<Material>();
if (atlasAsset == null)
atlasAsset = SpineAtlasAsset.CreateInstance<SpineAtlasAsset>();
else {
foreach (Material m in atlasAsset.materials)
vestigialMaterials.Add(m);
}
protectFromStackGarbageCollection.Add(atlasAsset);
atlasAsset.atlasFile = atlasText;
//strip CR
string atlasStr = atlasText.text;
atlasStr = atlasStr.Replace("\r", "");
string[] atlasLines = atlasStr.Split('\n');
List<string> pageFiles = new List<string>();
for (int i = 0; i < atlasLines.Length - 1; i++) {
if (atlasLines[i].Trim().Length == 0)
pageFiles.Add(atlasLines[i + 1].Trim());
}
var populatingMaterials = new List<Material>(pageFiles.Count);//atlasAsset.materials = new Material[pageFiles.Count];
for (int i = 0; i < pageFiles.Count; i++) {
string texturePath = assetPath + "/" + pageFiles[i];
Texture2D texture = (Texture2D)AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D));
if (SpineEditorUtilities.Preferences.setTextureImporterSettings) {
TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath);
if (texImporter == null) {
Debug.LogWarning(string.Format("{0} ::: Texture asset \"{1}\" not found. Skipping. Please check your atlas file for renamed files.", atlasAsset.name, texturePath));
continue;
}
texImporter.textureCompression = TextureImporterCompression.Uncompressed;
texImporter.alphaSource = TextureImporterAlphaSource.FromInput;
texImporter.mipmapEnabled = false;
texImporter.alphaIsTransparency = false; // Prevent the texture importer from applying bleed to the transparent parts for PMA.
texImporter.spriteImportMode = SpriteImportMode.None;
texImporter.maxTextureSize = 2048;
EditorUtility.SetDirty(texImporter);
AssetDatabase.ImportAsset(texturePath);
AssetDatabase.SaveAssets();
}
string pageName = Path.GetFileNameWithoutExtension(pageFiles[i]);
//because this looks silly
if (pageName == primaryName && pageFiles.Count == 1)
pageName = "Material";
string materialPath = assetPath + "/" + primaryName + "_" + pageName + ".mat";
Material mat = (Material)AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material));
if (mat == null) {
mat = new Material(Shader.Find(SpineEditorUtilities.Preferences.defaultShader));
AssetDatabase.CreateAsset(mat, materialPath);
} else {
vestigialMaterials.Remove(mat);
}
mat.mainTexture = texture;
EditorUtility.SetDirty(mat);
AssetDatabase.SaveAssets();
populatingMaterials.Add(mat); //atlasAsset.materials[i] = mat;
}
atlasAsset.materials = populatingMaterials.ToArray();
for (int i = 0; i < vestigialMaterials.Count; i++)
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(vestigialMaterials[i]));
if (AssetDatabase.GetAssetPath(atlasAsset) == "")
AssetDatabase.CreateAsset(atlasAsset, atlasPath);
else
atlasAsset.Clear();
EditorUtility.SetDirty(atlasAsset);
AssetDatabase.SaveAssets();
if (pageFiles.Count != atlasAsset.materials.Length)
Debug.LogWarning(string.Format("{0} :: Not all atlas pages were imported. If you rename your image files, please make sure you also edit the filenames specified in the atlas file.", atlasAsset.name));
else
Debug.Log(string.Format("{0} :: Imported with {1} material", atlasAsset.name, atlasAsset.materials.Length));
// Iterate regions and bake marked.
Atlas atlas = atlasAsset.GetAtlas();
FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic);
List<AtlasRegion> regions = (List<AtlasRegion>)field.GetValue(atlas);
string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset);
string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath);
string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name);
bool hasBakedRegions = false;
for (int i = 0; i < regions.Count; i++) {
AtlasRegion region = regions[i];
string bakedPrefabPath = Path.Combine(bakedDirPath, SpineEditorUtilities.AssetUtility.GetPathSafeName(region.name) + ".prefab").Replace("\\", "/");
GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject));
if (prefab != null) {
SkeletonBaker.BakeRegion(atlasAsset, region, false);
hasBakedRegions = true;
}
}
if (hasBakedRegions) {
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
protectFromStackGarbageCollection.Remove(atlasAsset);
return (AtlasAssetBase)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAssetBase));
}
#endregion
#region Import SkeletonData (json or binary)
internal static SkeletonDataAsset IngestSpineProject (TextAsset spineJson, params AtlasAssetBase[] atlasAssets) {
string primaryName = Path.GetFileNameWithoutExtension(spineJson.name);
string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(spineJson));
string filePath = assetPath + "/" + primaryName + SkeletonDataSuffix + ".asset";
#if SPINE_TK2D
if (spineJson != null) {
SkeletonDataAsset skeletonDataAsset = (SkeletonDataAsset)AssetDatabase.LoadAssetAtPath(filePath, typeof(SkeletonDataAsset));
if (skeletonDataAsset == null) {
skeletonDataAsset = SkeletonDataAsset.CreateInstance<SkeletonDataAsset>();
skeletonDataAsset.skeletonJSON = spineJson;
skeletonDataAsset.fromAnimation = new string[0];
skeletonDataAsset.toAnimation = new string[0];
skeletonDataAsset.duration = new float[0];
skeletonDataAsset.defaultMix = defaultMix;
skeletonDataAsset.scale = defaultScale;
AssetDatabase.CreateAsset(skeletonDataAsset, filePath);
AssetDatabase.SaveAssets();
} else {
skeletonDataAsset.Clear();
skeletonDataAsset.GetSkeletonData(true);
}
return skeletonDataAsset;
} else {
EditorUtility.DisplayDialog("Error!", "Tried to ingest null Spine data.", "OK");
return null;
}
#else
if (spineJson != null && atlasAssets != null) {
SkeletonDataAsset skeletonDataAsset = (SkeletonDataAsset)AssetDatabase.LoadAssetAtPath(filePath, typeof(SkeletonDataAsset));
if (skeletonDataAsset == null) {
skeletonDataAsset = ScriptableObject.CreateInstance<SkeletonDataAsset>();
{
skeletonDataAsset.atlasAssets = atlasAssets;
skeletonDataAsset.skeletonJSON = spineJson;
skeletonDataAsset.defaultMix = SpineEditorUtilities.Preferences.defaultMix;
skeletonDataAsset.scale = SpineEditorUtilities.Preferences.defaultScale;
}
AssetDatabase.CreateAsset(skeletonDataAsset, filePath);
AssetDatabase.SaveAssets();
} else {
skeletonDataAsset.atlasAssets = atlasAssets;
skeletonDataAsset.Clear();
skeletonDataAsset.GetSkeletonData(true);
}
return skeletonDataAsset;
} else {
EditorUtility.DisplayDialog("Error!", "Must specify both Spine JSON and AtlasAsset array", "OK");
return null;
}
#endif
}
#endregion
#region Spine Skeleton Data File Validation
public static bool CheckForValidSkeletonData (string skeletonJSONPath) {
string dir = Path.GetDirectoryName(skeletonJSONPath);
TextAsset textAsset = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonJSONPath, typeof(TextAsset));
DirectoryInfo dirInfo = new DirectoryInfo(dir);
FileInfo[] files = dirInfo.GetFiles("*.asset");
foreach (var path in files) {
string localPath = dir + "/" + path.Name;
var obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object));
var skeletonDataAsset = obj as SkeletonDataAsset;
if (skeletonDataAsset != null && skeletonDataAsset.skeletonJSON == textAsset)
return true;
}
return false;
}
public static bool IsSpineData (TextAsset asset) {
if (asset == null)
return false;
bool isSpineData = false;
string rawVersion = null;
int[][] compatibleVersions;
if (asset.name.Contains(".skel")) {
try {
rawVersion = SkeletonBinary.GetVersionString(new MemoryStream(asset.bytes));
isSpineData = !(string.IsNullOrEmpty(rawVersion));
compatibleVersions = compatibleBinaryVersions;
} catch (System.Exception e) {
Debug.LogErrorFormat("Failed to read '{0}'. It is likely not a binary Spine SkeletonData file.\n{1}", asset.name, e);
return false;
}
} else {
object obj = Json.Deserialize(new StringReader(asset.text));
if (obj == null) {
Debug.LogErrorFormat("'{0}' is not valid JSON.", asset.name);
return false;
}
var root = obj as Dictionary<string, object>;
if (root == null) {
Debug.LogError("Parser returned an incorrect type.");
return false;
}
isSpineData = root.ContainsKey("skeleton");
if (isSpineData) {
var skeletonInfo = (Dictionary<string, object>)root["skeleton"];
object jv;
skeletonInfo.TryGetValue("spine", out jv);
rawVersion = jv as string;
}
compatibleVersions = compatibleJsonVersions;
}
// Version warning
if (isSpineData) {
string primaryRuntimeVersionDebugString = compatibleVersions[0][0] + "." + compatibleVersions[0][1];
if (string.IsNullOrEmpty(rawVersion)) {
Debug.LogWarningFormat("Skeleton '{0}' has no version information. It may be incompatible with your runtime version: spine-unity v{1}", asset.name, primaryRuntimeVersionDebugString);
} else {
string[] versionSplit = rawVersion.Split('.');
bool match = false;
foreach (var version in compatibleVersions) {
bool primaryMatch = version[0] == int.Parse(versionSplit[0]);
bool secondaryMatch = version[1] == int.Parse(versionSplit[1]);
// if (isFixVersionRequired) secondaryMatch &= version[2] <= int.Parse(jsonVersionSplit[2]);
if (primaryMatch && secondaryMatch) {
match = true;
break;
}
}
if (!match)
Debug.LogWarningFormat("Skeleton '{0}' (exported with Spine {1}) may be incompatible with your runtime version: spine-unity v{2}", asset.name, rawVersion, primaryRuntimeVersionDebugString);
}
}
return isSpineData;
}
#endregion
#region Dialogs
public static void SkeletonImportDialog (string skeletonPath, List<AtlasAssetBase> localAtlases, List<string> requiredPaths, ref bool abortSkeletonImport) {
bool resolved = false;
while (!resolved) {
string filename = Path.GetFileNameWithoutExtension(skeletonPath);
int result = EditorUtility.DisplayDialogComplex(
string.Format("AtlasAsset for \"{0}\"", filename),
string.Format("Could not automatically set the AtlasAsset for \"{0}\".\n\n (You may resolve this manually later.)", filename),
"Resolve atlases...", "Import without atlases", "Stop importing"
);
switch (result) {
case -1:
//Debug.Log("Select Atlas");
AtlasAssetBase selectedAtlas = BrowseAtlasDialog(Path.GetDirectoryName(skeletonPath));
if (selectedAtlas != null) {
localAtlases.Clear();
localAtlases.Add(selectedAtlas);
var atlasMatch = AssetUtility.GetMatchingAtlas(requiredPaths, localAtlases);
if (atlasMatch != null) {
resolved = true;
AssetUtility.IngestSpineProject(AssetDatabase.LoadAssetAtPath(skeletonPath, typeof(TextAsset)) as TextAsset, atlasMatch);
}
}
break;
case 0: // Resolve AtlasAssets...
var atlasList = MultiAtlasDialog(requiredPaths, Path.GetDirectoryName(skeletonPath), Path.GetFileNameWithoutExtension(skeletonPath));
if (atlasList != null)
AssetUtility.IngestSpineProject(AssetDatabase.LoadAssetAtPath(skeletonPath, typeof(TextAsset)) as TextAsset, atlasList.ToArray());
resolved = true;
break;
case 1: // Import without atlas
Debug.LogWarning("Imported with missing atlases. Skeleton will not render: " + Path.GetFileName(skeletonPath));
AssetUtility.IngestSpineProject(AssetDatabase.LoadAssetAtPath(skeletonPath, typeof(TextAsset)) as TextAsset, new AtlasAssetBase[] { });
resolved = true;
break;
case 2: // Stop importing all
abortSkeletonImport = true;
resolved = true;
break;
}
}
}
public static List<AtlasAssetBase> MultiAtlasDialog (List<string> requiredPaths, string initialDirectory, string filename = "") {
List<AtlasAssetBase> atlasAssets = new List<AtlasAssetBase>();
bool resolved = false;
string lastAtlasPath = initialDirectory;
while (!resolved) {
// Build dialog box message.
var missingRegions = new List<string>(requiredPaths);
var dialogText = new StringBuilder();
{
dialogText.AppendLine(string.Format("SkeletonDataAsset for \"{0}\"", filename));
dialogText.AppendLine("has missing regions.");
dialogText.AppendLine();
dialogText.AppendLine("Current Atlases:");
if (atlasAssets.Count == 0)
dialogText.AppendLine("\t--none--");
for (int i = 0; i < atlasAssets.Count; i++)
dialogText.AppendLine("\t" + atlasAssets[i].name);
dialogText.AppendLine();
dialogText.AppendLine("Missing Regions:");
foreach (var atlasAsset in atlasAssets) {
var atlas = atlasAsset.GetAtlas();
for (int i = 0; i < missingRegions.Count; i++) {
if (atlas.FindRegion(missingRegions[i]) != null) {
missingRegions.RemoveAt(i);
i--;
}
}
}
int n = missingRegions.Count;
if (n == 0)
break;
const int MaxListLength = 15;