유니티 스프라이트 아틀라스를 PNG파일 (스프라이트시트)로 생성할수는 없을까? 1탄

Unity3D 2020. 5. 29. 12:58
반응형

유니티 스프라이트 아틀라스를 PNG파일 (스프라이트시트)로 생성할수는 없을까? 에서 시작된 R&D 내용임.

유니티에서 개별 텍스쳐를 아틀라스로 생성후 이미지파일(png) 즉 스프라이트 시트로 생성할수 있었다.

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.U2D;
using System;
using System.Reflection;
using System.IO;
 
public class Test : Editor
{
 
    [MenuItem("Tools/Export atlases as PNG")]
    static void ExportAtlases()
    {
        string exportPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Atlases";
        foreach (UnityEngine.Object obj in Selection.objects)
        {
            SpriteAtlas atlas = (SpriteAtlas)obj;
            if (atlas == nullcontinue;
            Debug.Log("Exporting selected atlas: " + atlas);
 
            // use reflection to run this internal editor method
            // UnityEditor.U2D.SpriteAtlasExtensions.GetPreviewTextures
            // internal static extern Texture2D[] GetPreviewTextures(this SpriteAtlas spriteAtlas);
            Type type = typeof(UnityEditor.U2D.SpriteAtlasExtensions);
            MethodInfo methodInfo = type.GetMethod("GetPreviewTextures", BindingFlags.Static 
                | BindingFlags.NonPublic);
 
            if (methodInfo == null)
            {
                Debug.LogWarning("Failed to get UnityEditor.U2D.SpriteAtlasExtensions");
                return;
            }
            Texture2D[] textures = (Texture2D[])methodInfo.Invoke(nullnew object[] { atlas });
            if (textures == null)
            {
                Debug.LogWarning("Failed to get texture results");
                continue;
            }
 
            Debug.LogFormat("----> {0}", textures.Length);
            
            foreach (Texture2D texture in textures)
            {
                Debug.LogFormat("=> {0}", texture.name);
                // these textures in memory are not saveable so copy them to a RenderTexture first
                Texture2D textureCopy = DuplicateTexture(texture);
                //if (!Directory.Exists(exportPath)) Directory.CreateDirectory(exportPath);
                //string filename = exportPath + "/" + texture.name + ".png";
                //FileStream fs = new FileStream(filename, FileMode.Create);
                //BinaryWriter bw = new BinaryWriter(fs);
                //bw.Write(textureCopy.EncodeToPNG());
                //bw.Close();
                //fs.Close();
                //Debug.Log("Saved texture to " + filename);
            }
        }
    }
 
    private static Texture2D DuplicateTexture(Texture2D source)
    {
        RenderTexture renderTex = RenderTexture.GetTemporary(
            source.width,
            source.height,
            0,
            RenderTextureFormat.Default,
            RenderTextureReadWrite.Linear);
 
        Graphics.Blit(source, renderTex);
        RenderTexture previous = RenderTexture.active;
        RenderTexture.active = renderTex;
        Texture2D readableText = new Texture2D(source.width, source.height);
 
        Debug.LogFormat("--> {0}, {1}", renderTex.width, renderTex.height);
 
        readableText.ReadPixels(new Rect(00, renderTex.width, renderTex.height), 00);
        readableText.Apply();
        RenderTexture.active = previous;
        RenderTexture.ReleaseTemporary(renderTex);
        return readableText;
    }
}
 
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
//using DotEditor.Core.Util;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;
using SystemObject = System.Object;
 
namespace DotEditor.Core.UI.Atlas
{
    public static class SpriteAtlasExporter
    {
        public static string[] Export(SpriteAtlas atlas, string dirPath)
        {
            string platformName = "Standalone";
            if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android)
            {
                platformName = "Android";
            }
            else if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS)
            {
                platformName = "iPhone";
            }
 
            TextureImporterPlatformSettings tips = atlas.GetPlatformSettings(platformName);
            TextureImporterPlatformSettings cachedTips = new TextureImporterPlatformSettings();
            tips.CopyTo(cachedTips);
 
            tips.overridden = true;
            tips.format = TextureImporterFormat.RGBA32;
            atlas.SetPlatformSettings(tips);
 
            List<string> texturePathList = new List<string>();
 
            SpriteAtlasUtility.PackAtlases(new SpriteAtlas[] { atlas }, EditorUserBuildSettings.activeBuildTarget);
            MethodInfo getPreviewTextureMI = typeof(SpriteAtlasExtensions).GetMethod("GetPreviewTextures", BindingFlags.Static | BindingFlags.NonPublic);
 
            Debug.LogFormat("spriteCount: {0}", atlas.spriteCount); //spriteCount: 53
 
            var sysObj = new SystemObject[] { atlas };
            foreach (var obj in sysObj) {
                Debug.Log(obj); //TestAtlas (UnityEngine.SpriteAtlas)
            }
            var arrSprites = new Sprite[atlas.spriteCount];
            atlas.GetSprites(arrSprites);
 
            int idx = 0;
            foreach (var sp in arrSprites) {
                Debug.LogFormat("{0}, {1}", idx++, sp.texture.name);
            }
            Texture2D[] atlasTextures = 
                (Texture2D[])getPreviewTextureMI.Invoke(nullnew SystemObject[] { atlas });
 
            Debug.LogFormat("atlasTextures: {0}", atlasTextures);
 
            if (atlasTextures != null && atlasTextures.Length > 0)
            {
                for (int i = 0; i < atlasTextures.Length; i++)
                {
                    Texture2D packTexture = atlasTextures[i];
                    byte[] rawBytes = packTexture.GetRawTextureData();
 
                    Texture2D nTexture = new Texture2D(packTexture.width, packTexture.height, packTexture.format, falsefalse);
                    nTexture.LoadRawTextureData(rawBytes);
                    nTexture.Apply();
                    string textPath = string.Format("{0}/{1}_{2}.png", dirPath, atlas.name, i);
                    File.WriteAllBytes(textPath, nTexture.EncodeToPNG());
 
                    texturePathList.Add(textPath);
                }
            }
 
            atlas.SetPlatformSettings(cachedTips);
 
            return texturePathList.ToArray();
        }
 
 
        [MenuItem("Game/UI/Atlas/SpriteAtlas Exporter")]
        private static void ExportAltas()
        {
            List<SpriteAtlas> atlasList = new List<SpriteAtlas>();
            if (Selection.objects != null && Selection.objects.Length > 0)
            {
                foreach (var obj in Selection.objects)
                {
                    if (obj.GetType() == typeof(SpriteAtlas))
                    {
                        atlasList.Add(obj as SpriteAtlas);
                    }
                }
            }
 
            if (atlasList.Count == 0)
            {
                EditorUtility.DisplayDialog("Tips""Please Selected SpriteAtlas""OK");
                return;
            }
 
            string dirPath = EditorUtility.OpenFolderPanel("Save Dir""D:/""");
            if (string.IsNullOrEmpty(dirPath))
            {
                EditorUtility.DisplayDialog("Tips""Please Selected a folder""OK");
                return;
            }
 
            foreach (var atlas in atlasList)
            {
                Export(atlas, dirPath);
            }
 
            //ExplorerUtil.OpenExplorerFolder(dirPath);
            //itemPath = itemPath.Replace(@"/", @"\");   // explorer doesn't like front slashes
            Debug.LogFormat("dirPath: {0}", dirPath);
            //System.Diagnostics.Process.Start(dirPath);
        }
    }
}
cs

 

아틀라스를 이미지로 생성가능 

 

 

 

 

하지만 생성된 스프라이트시트의 타입을 멀티로 변경하게 되면 아래와 같이 하나의 덩어리로 잘리지 않았다.

 

왜 그런것일까?

https://www.codeandweb.com/blog/2015/09/21/optimizing-unity-sprite-meshes

 

Optimizing sprite meshes for Unity

Optimize Unity sprite meshes to increase your game's performance

www.codeandweb.com

TexturePacker에서 SpriteSheet로 내보내기 했을때 함께 생성되는 .tpsheet파일을 읽어 

유니티 TexturePacker 플러그인 (TexturePackerImporter.dll)이 처리해주고 자동으로 tpsheet의 정보를  가지고 영역을 잘라내주고 있는것이였음 

 

 

 

1. 스프라이트시트 생성시 모든 요소들의 정보를 기록 ( 위치와 가로세로 등)

2. 스프라이트시트 + 시트정보 import 

3. 시트정보를 기반으로 스프라이트시트(Texture)를 Sprite/Multiple로 변경 (이때 각영역잘라냄)

어떻게 잘라내고 있는것일까...?

 

 

 

 

 

시트정보

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Decompiled with JetBrains decompiler
// Type: TPImporter.SheetInfo
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
 
using UnityEditor;
 
namespace TPImporter
{
  public class SheetInfo
  {
    public SpriteMetaData[] metadata = (SpriteMetaData[]) null;
    public int width = -1;
    public int height = -1;
    public bool pivotPointsEnabled = true;
    public bool bordersEnabled = false;
    public bool polygonsEnabled = false;
    public bool alphaIsTransparency = true;
    public string sheetHash;
  }
}
 
cs

 

 

 

 

 

 

https://www.jetbrains.com/decompiler/download/download-thanks.html?platform=windowsWeb

 

Thank you for downloading dotPeek!

Free .NET decompiler and assembly browser

www.jetbrains.com

 

 

궁금해서 dll파일을 열어 보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Decompiled with JetBrains decompiler
// Type: TPImporter.Dbg
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
 
using UnityEngine;
 
namespace TPImporter
{
  public class Dbg
  {
    public static bool enabled = false;
 
    public static void Log(string msg)
    {
      if (!Dbg.enabled)
        return;
      Debug.Log((object) ("TPImporter: " + msg));
    }
  }
}
 
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Decompiled with JetBrains decompiler
// Type: TPImporter.InvalidVertexException
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
 
using System;
 
namespace TPImporter
{
  public class InvalidVertexException : Exception
  {
  }
}
 
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Decompiled with JetBrains decompiler
// Type: TPImporter.LoaderResult
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
 
namespace TPImporter
{
  public enum LoaderResult
  {
    Loaded,
    NoChanges,
    Error,
  }
}
 
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
// Decompiled with JetBrains decompiler
// Type: TPImporter.MenuItems
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
 
using UnityEditor;
 
namespace TPImporter
{
  public class MenuItems
  {
    [MenuItem("Assets/TexturePacker/Reload sprite sheets")]
    private static void ReloadSpriteSheets()
    {
      foreach (string allDataFile in SettingsDatabase.getInstance().allDataFiles())
      {
        TexturePackerImporter.spriteSheets.sheetInfoForDataFile(allDataFile).sheetHash = "";
        AssetDatabase.ImportAsset(allDataFile, (ImportAssetOptions) 1);
      }
    }
  }
}
 
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
// Decompiled with JetBrains decompiler
// Type: TPImporter.MetaDataUpdate
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
 
using UnityEditor;
using UnityEngine;
 
namespace TPImporter
{
  public class MetaDataUpdate
  {
    public static bool areEqual(SpriteMetaData[] meta1, SpriteMetaData[] meta2)
    {
      bool flag = meta1.Length == meta2.Length;
      for (int index = 0; flag && index < meta1.Length; ++index)
        flag = flag && (string) meta1[index].name == (string) meta2[index].name && Rect.op_Equality((Rect) meta1[index].rect, (Rect) meta2[index].rect) && Vector4.op_Equality((Vector4) meta1[index].border, (Vector4) meta2[index].border) && Vector2.op_Equality((Vector2) meta1[index].pivot, (Vector2) meta2[index].pivot) && meta1[index].alignment == meta2[index].alignment;
      return flag;
    }
 
    public static void copyOldAttributes(
      SpriteMetaData[] oldMeta,
      SpriteMetaData[] newMeta,
      bool copyPivotPoints,
      bool copyBorders)
    {
      for (int index = 0; index < newMeta.Length; ++index)
      {
        foreach (SpriteMetaData spriteMetaData in oldMeta)
        {
          if ((string) spriteMetaData.name == (string) newMeta[index].name)
          {
            if (copyPivotPoints)
            {
              newMeta[index].pivot = spriteMetaData.pivot;
              newMeta[index].alignment = spriteMetaData.alignment;
            }
            if (copyBorders)
            {
              newMeta[index].border = spriteMetaData.border;
              break;
            }
            break;
          }
        }
      }
    }
  }
}
 
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
// Decompiled with JetBrains decompiler
// Type: TPImporter.SettingsDatabase
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace TPImporter
{
  [InitializeOnLoad]
  public class SettingsDatabase : ScriptableObject
  {
    private static SettingsDatabase instance = (SettingsDatabase) null;
    private int version;
    private bool importPivots;
    private List<string> tpsheetFileNames;
    private List<string> textureFileNames;
    private List<string> normalmapFileNames;
    private const int DATABASE_VERSION = 2;
    private const string PIVOTPOINT_KEY = "TPImporter.ImportPivotPoints";
    private const string IMPORTER_DLL = "TexturePackerImporter.dll";
    private const string DATABASE_FILE = "SettingsTexturePackerImporter.txt";
    private const string ASSET_FILE = "SettingsTexturePackerImporter.asset";
    private const string DEFAULT_PATH = "/codeandweb.com/Editor";
    private const string EXAMPLE_SHEET = "/codeandweb.com/Example/SpriteSheet/sprites.tpsheet";
    private static string databaseFilePath;
    private static string assetFilePath;
    static SettingsDatabase()
    {
      Dbg.Log("Adding delayed call");
      // ISSUE: variable of the null type
      __Null delayCall = EditorApplication.delayCall;
      // ISSUE: reference to a compiler-generated field
      if (SettingsDatabase.\u003C\u003Ef__mg\u0024cache0 == null)
      {
        // ISSUE: reference to a compiler-generated field
        // ISSUE: method pointer
        SettingsDatabase.\u003C\u003Ef__mg\u0024cache0 = new EditorApplication.CallbackFunction((objectnull, __methodptr(InitDatabase));
      }
      // ISSUE: reference to a compiler-generated field
      EditorApplication.CallbackFunction fMgCache0 = SettingsDatabase.\u003C\u003Ef__mg\u0024cache0;
      EditorApplication.delayCall = (__Null) Delegate.Combine((Delegate) delayCall, (Delegate) fMgCache0);
    }
    public SettingsDatabase()
    {
      base.\u002Ector();
    }
    private static void InitDatabase()
    {
      Dbg.Log("Initializing...");
      SettingsDatabase instance = SettingsDatabase.getInstance();
      Dbg.Log("TexturePacker Importer initialized");
      if (!File.Exists(SettingsDatabase.fixPath(Application.get_dataPath() + "/codeandweb.com/Example/SpriteSheet/sprites.tpsheet")) || instance.containsDataFile(SettingsDatabase.fixPath("Assets/codeandweb.com/Example/SpriteSheet/sprites.tpsheet")))
        return;
      Dbg.Log("Initializing example sheet");
      AssetDatabase.ImportAsset(SettingsDatabase.fixPath("Assets/codeandweb.com/Example/SpriteSheet/sprites.tpsheet"), (ImportAssetOptions) 1);
    }
    public void Awake()
    {
      Dbg.Log("Awake " + (object) ((Object) this).GetInstanceID());
    }
    public void OnDestroy()
    {
      Dbg.Log("OnDestroy " + (object) ((Object) this).GetInstanceID());
      if (Object.op_Equality((Object) this, (Object) SettingsDatabase.instance))
      {
        this.saveDatabase();
        SettingsDatabase.instance = (SettingsDatabase) null;
        Dbg.Log("settings database destroyed");
      }
      else
        Dbg.Log("destructor of partially initialized database object called; ignoring");
    }
    public void OnDisable()
    {
      Dbg.Log("OnDisable " + (object) ((Object) this).GetInstanceID());
    }
    public void OnEnable()
    {
      Dbg.Log("OnEnable " + (object) ((Object) this).GetInstanceID());
    }
    public void addSheet(string dataFile, string textureFile, string normalmapFile)
    {
      this.removeSheet(dataFile, false);
      Dbg.Log("add sheet");
      this.tpsheetFileNames.Add(dataFile);
      this.textureFileNames.Add(textureFile);
      this.normalmapFileNames.Add(normalmapFile);
      this.saveDatabase();
    }
    public void removeSheet(string dataFile, bool save = true)
    {
      int index = this.tpsheetFileNames.IndexOf(dataFile);
      if (index < 0)
        return;
      this.tpsheetFileNames.RemoveAt(index);
      this.textureFileNames.RemoveAt(index);
      this.normalmapFileNames.RemoveAt(index);
      if (!save)
        return;
      Dbg.Log("remove sheet");
      this.saveDatabase();
    }
    public bool containsDataFile(string dataFile)
    {
      return this.tpsheetFileNames.IndexOf(dataFile) >= 0;
    }
    public string spriteFileForNormalsFile(string normalsFile)
    {
      int index = this.normalmapFileNames.IndexOf(normalsFile);
      return index >= 0 ? this.textureFileNames[index] : (stringnull;
    }
    public string spriteFileForDataFile(string dataFile)
    {
      int index = this.tpsheetFileNames.IndexOf(dataFile);
      return index >= 0 ? this.textureFileNames[index] : (stringnull;
    }
    public string normalsFileForDataFile(string dataFile)
    {
      int index = this.tpsheetFileNames.IndexOf(dataFile);
      return index >= 0 ? this.normalmapFileNames[index] : (stringnull;
    }
    public string dataFileForSpriteFile(string spriteFile)
    {
      int index = this.textureFileNames.IndexOf(spriteFile);
      return index >= 0 ? this.tpsheetFileNames[index] : (stringnull;
    }
    public bool isSpriteSheet(string textureFile)
    {
      return this.textureFileNames.Contains(textureFile);
    }
    public bool isNormalmapSheet(string textureFile)
    {
      return this.normalmapFileNames.Contains(textureFile);
    }
    public List<string> allDataFiles()
    {
      return new List<string>((IEnumerable<string>this.tpsheetFileNames);
    }
    public bool importPivotPoints()
    {
      return this.importPivots;
    }
    private static string fixPath(string path)
    {
      return path.Replace("\\""/").Replace("//""/");
    }
    private static void updateFileLocations()
    {
      Dbg.Log("updateFileLocations()");
      string dataPath = Application.get_dataPath();
      string str1 = dataPath + "/codeandweb.com/Editor";
      if (!File.Exists(str1 + "/TexturePackerImporter.dll"))
      {
        string[] files = Directory.GetFiles(dataPath, "TexturePackerImporter.dll", SearchOption.AllDirectories);
        if (files.Length > 0)
          str1 = files[0].Remove(files[0].Length - "TexturePackerImporter.dll".Length);
        else
          Dbg.Log("TexturePackerImporter.dll not found in " + dataPath);
      }
      string str2 = "Assets/" + str1.Remove(0, dataPath.Length);
      SettingsDatabase.databaseFilePath = SettingsDatabase.fixPath(str1 + "/SettingsTexturePackerImporter.txt");
      SettingsDatabase.assetFilePath = SettingsDatabase.fixPath(str2 + "/SettingsTexturePackerImporter.asset");
      Dbg.Log("database location: " + SettingsDatabase.databaseFilePath + "\nasset location: " + SettingsDatabase.assetFilePath);
    }
    public static SettingsDatabase getInstance()
    {
      Dbg.Log("getInstance()");
      if (Object.op_Equality((Object) SettingsDatabase.instance, (Object) null))
      {
        SettingsDatabase.updateFileLocations();
        SettingsDatabase.instance = (SettingsDatabase) ScriptableObject.CreateInstance<SettingsDatabase>();
        SettingsDatabase.instance.loadDatabase();
      }
      Dbg.Log("instance id: " + (object) ((Object) SettingsDatabase.instance).GetInstanceID() + ", " + (object) SettingsDatabase.instance.tpsheetFileNames.Count + " sheets");
      return SettingsDatabase.instance;
    }
    private static List<string> readStringList(StreamReader file)
    {
      List<string> stringList = new List<string>();
      while (file.Peek() == 45)
      {
        string str = file.ReadLine().Remove(01).Trim();
        stringList.Add(str);
      }
      return stringList;
    }
    private void loadDatabase()
    {
      Dbg.Log("Loading database, instance id: " + (object) ((Object) this).GetInstanceID());
      if (SettingsDatabase.databaseFilePath == null)
      {
        Dbg.Log("databaseFilePath is null");
      }
      else
      {
        try
        {
          StreamReader file = new StreamReader(SettingsDatabase.databaseFilePath);
          this.importPivots = EditorPrefs.GetBool("TPImporter.ImportPivotPoints"true);
          string str1;
          while ((str1 = file.ReadLine()) != null)
          {
            string[] strArray = str1.Split(':');
            string str2 = strArray[0].Trim();
            string s = strArray[1].Trim();
            if (str2 == "version")
              this.version = int.Parse(s);
            else if (str2 == "importPivots")
              this.importPivots = int.Parse(s) != 0;
            else if (str2 == "tpsheetFileNames")
              this.tpsheetFileNames = SettingsDatabase.readStringList(file);
            else if (str2 == "textureFileNames")
              this.textureFileNames = SettingsDatabase.readStringList(file);
            else if (str2 == "normalmapFileNames")
              this.normalmapFileNames = SettingsDatabase.readStringList(file);
            else if (str2 == "enableDebugOutput")
              Dbg.enabled = int.Parse(s) != 0;
          }
          file.Close();
        }
        catch (IOException ex)
        {
          Dbg.Log("exception catched");
        }
        Dbg.Log("Loaded database " + SettingsDatabase.databaseFilePath + " (" + (objectthis.tpsheetFileNames.Count + " sheets)");
      }
    }
    private static void swap<T>(List<T> list, int index1, int index2)
    {
      T obj = list[index1];
      list[index1] = list[index2];
      list[index2] = obj;
    }
    private void sortLists()
    {
      for (int index1 = 0; index1 < this.tpsheetFileNames.Count; ++index1)
      {
        for (int index2 = index1 + 1; index2 < this.tpsheetFileNames.Count; ++index2)
        {
          if (string.Compare(this.tpsheetFileNames[index1], this.tpsheetFileNames[index2], true> 0)
          {
            SettingsDatabase.swap<string>(this.tpsheetFileNames, index1, index2);
            SettingsDatabase.swap<string>(this.textureFileNames, index1, index2);
            SettingsDatabase.swap<string>(this.normalmapFileNames, index1, index2);
          }
        }
      }
    }
    private static void writeStringList(StreamWriter file, List<string> list)
    {
      foreach (string str in list)
        file.WriteLine("- " + str);
    }
    private void saveDatabase()
    {
      Dbg.Log("Saving database, instance id: " + (object) ((Object) this).GetInstanceID());
      if (!File.Exists(SettingsDatabase.databaseFilePath))
        SettingsDatabase.updateFileLocations();
      if (SettingsDatabase.databaseFilePath == null)
      {
        Dbg.Log("databaseFilePath is null");
      }
      else
      {
        Dbg.Log("Saving database " + SettingsDatabase.databaseFilePath + " (" + (objectthis.tpsheetFileNames.Count + " sheets)");
        StreamWriter file = new StreamWriter(SettingsDatabase.databaseFilePath);
        this.sortLists();
        file.WriteLine(string.Format("version: {0}", (objectthis.version));
        file.WriteLine(string.Format("importPivots: {0}", (object) (!this.importPivots ? 0 : 1)));
        file.WriteLine("tpsheetFileNames:");
        SettingsDatabase.writeStringList(file, this.tpsheetFileNames);
        file.WriteLine("textureFileNames:");
        SettingsDatabase.writeStringList(file, this.textureFileNames);
        file.WriteLine("normalmapFileNames:");
        SettingsDatabase.writeStringList(file, this.normalmapFileNames);
        file.WriteLine(string.Format("enableDebugOutput: {0}", (object) (!Dbg.enabled ? 0 : 1)));
        file.Close();
      }
    }
  }
}
 
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
// Decompiled with JetBrains decompiler
// Type: TPImporter.SpriteGeometry
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
 
using System;
using System.Globalization;
using UnityEngine;
 
namespace TPImporter
{
  public class SpriteGeometry
  {
    private Vector2[] vertices;
    private ushort[] triangles;
 
    public int parse(string[] values, int idx)
    {
      if (idx >= values.Length)
        return idx;
      int length = int.Parse(values[idx++]);
      if (2 * length + idx > values.Length)
      {
        Debug.LogError((object) ("vertex values missing: " + (object) length + (object) values.Length));
        return -1;
      }
      this.vertices = new Vector2[length];
      for (int index = 0; index < length; ++index)
        ((Vector2) ref this.vertices[index]).Set(float.Parse(values[idx++], (IFormatProvider) CultureInfo.InvariantCulture), float.Parse(values[idx++], (IFormatProvider) CultureInfo.InvariantCulture));
      int num = int.Parse(values[idx++]);
      if (3 * num + idx > values.Length)
      {
        Debug.LogError((object) ("triangle values missing: " + (object) num + (object) values.Length));
        return -1;
      }
      this.triangles = new ushort[3 * num];
      for (int index = 0; index < 3 * num; ++index)
        this.triangles[index] = ushort.Parse(values[idx++]);
      return idx;
    }
 
    public void setQuad(int w, int h)
    {
      this.vertices = new Vector2[4];
      this.triangles = new ushort[6]
      {
        (ushort0,
        (ushort2,
        (ushort1,
        (ushort1,
        (ushort2,
        (ushort3
      };
      ((Vector2) ref this.vertices[0]).Set(0.0f, 0.0f);
      ((Vector2) ref this.vertices[1]).Set((float) w, 0.0f);
      ((Vector2) ref this.vertices[2]).Set(0.0f, (float) h);
      ((Vector2) ref this.vertices[3]).Set((float) w, (float) h);
    }
 
    public void ensureVerticesFitInFrame(Vector2[] vertices, float frameWidth, float frameHeight)
    {
      for (int index = 0; index < vertices.Length; ++index)
      {
        if (vertices[index].x > (double) frameWidth || vertices[index].y > (double) frameHeight)
          throw new InvalidVertexException();
      }
    }
 
    public void assignToSprite(Sprite sprite, float scaleFactor)
    {
      Vector2[] vector2Array = this.vertices;
      if ((double) scaleFactor != 1.0)
      {
        vector2Array = new Vector2[this.vertices.Length];
        for (int index = 0; index < this.vertices.Length; ++index)
          ((Vector2) ref vector2Array[index]).Set(scaleFactor * (floatthis.vertices[index].x, scaleFactor * (floatthis.vertices[index].y);
      }
      Vector2[] vertices = vector2Array;
      Rect rect1 = sprite.get_rect();
      double width = (double) ((Rect) ref rect1).get_width();
      Rect rect2 = sprite.get_rect();
      double height = (double) ((Rect) ref rect2).get_height();
      this.ensureVerticesFitInFrame(vertices, (float) width, (float) height);
      sprite.OverrideGeometry(vector2Array, this.triangles);
    }
  }
}
 
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
// Decompiled with JetBrains decompiler
// Type: TPImporter.SpriteGeometryHash
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
 
using System.Collections.Generic;
using UnityEngine;
 
namespace TPImporter
{
  public class SpriteGeometryHash
  {
    private Dictionary<string, SpriteGeometry> geometries = new Dictionary<string, SpriteGeometry>();
 
    public void addGeometry(string texturePath, string spriteName, SpriteGeometry geometry)
    {
      this.geometries[texturePath + "/" + spriteName] = geometry;
    }
 
    public void assignGeometryToSprite(string texturePath, Sprite sprite, float scaleFactor)
    {
      if (!this.geometries.ContainsKey(texturePath + "/" + ((Object) sprite).get_name()))
        return;
      this.geometries[texturePath + "/" + ((Object) sprite).get_name()].assignToSprite(sprite, scaleFactor);
    }
  }
}
 
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
// Decompiled with JetBrains decompiler
// Type: TPImporter.SpritesheetCollection
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
 
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;
 
namespace TPImporter
{
  public class SpritesheetCollection
  {
    private Dictionary<string, SheetInfo> spriteSheetData = new Dictionary<string, SheetInfo>();
    private SpriteGeometryHash spriteGeometries = new SpriteGeometryHash();
    private const int SUPPORTED_TPSHEET_VERSION = 40300;
 
    private string getAssetDependencyHash(string assetFile)
    {
      try
      {
        object[] parameters = new object[1]
        {
          (object) assetFile
        };
        MethodInfo method = typeof (AssetDatabase).GetMethod("GetAssetDependencyHash", BindingFlags.Static | BindingFlags.Public, (Binder) nullnew Type[1]
        {
          typeof (string)
        }, (ParameterModifier[]) null);
        if (method != null)
          return ((Hash128) method.Invoke((objectnull, parameters)).ToString();
        Dbg.Log("AssetDatabase.GetAssetDependencyHash() not defined, disabling optimized loader");
        return (stringnull;
      }
      catch (Exception ex)
      {
        Dbg.Log("Invoking AssetDatabase.GetAssetDependencyHash() failed, disabling optimized loader");
        return (stringnull;
      }
    }
 
    public LoaderResult loadSheetData(string dataFile)
    {
      if (this.spriteSheetData.ContainsKey(dataFile) && SettingsDatabase.getInstance().containsDataFile(dataFile))
      {
        string assetDependencyHash = this.getAssetDependencyHash(dataFile);
        if (assetDependencyHash != null)
        {
          if (assetDependencyHash == this.spriteSheetData[dataFile].sheetHash)
          {
            Dbg.Log("Checked " + dataFile + ", no changes found");
            return LoaderResult.NoChanges;
          }
          Dbg.Log("Data file changed, old hash: " + this.spriteSheetData[dataFile].sheetHash + ", new hash: " + assetDependencyHash);
        }
      }
      if (this.spriteSheetData.ContainsKey(dataFile))
        this.spriteSheetData.Remove(dataFile);
      string[] strArray1 = File.ReadAllLines(dataFile);
      int num1 = 30302;
      string str1 = (stringnull;
      string normalmapFile = (stringnull;
      SheetInfo sheetInfo = new SheetInfo();
      foreach (string str2 in strArray1)
      {
        if (str2.StartsWith(":format="))
          num1 = int.Parse(str2.Remove(08));
        if (str2.StartsWith(":normalmap="))
          normalmapFile = str2.Remove(011);
        if (str2.StartsWith(":texture="))
          str1 = str2.Remove(09);
        if (str2.StartsWith(":size="))
        {
          string[] strArray2 = str2.Remove(06).Split('x');
          sheetInfo.width = int.Parse(strArray2[0]);
          sheetInfo.height = int.Parse(strArray2[1]);
        }
        if (str2.StartsWith(":pivotpoints="))
        {
          string str3 = str2.Remove(013).ToLower().Trim();
          sheetInfo.pivotPointsEnabled = str3 == "enabled";
        }
        if (str2.StartsWith(":borders="))
        {
          string str3 = str2.Remove(09).ToLower().Trim();
          sheetInfo.bordersEnabled = str3 == "enabled";
        }
        if (str2.StartsWith("# Sprite sheet: "))
        {
          string str3 = str2.Remove(016);
          str1 = str3.Remove(str3.LastIndexOf("("- 1);
        }
        if (str2.StartsWith(":alphahandling=KeepTransparentPixels"|| str2.StartsWith(":alphahandling=PremultiplyAlpha"))
          sheetInfo.alphaIsTransparency = false;
      }
      bool flag1 = strArray1[0].StartsWith("{\"frames\": {");
      bool flag2 = strArray1[0].StartsWith("{");
      if (flag1)
      {
        EditorUtility.DisplayDialog("Incompatible data format""The data file '" + dataFile + "' contains an invalid format!\n\nPlease select 'Unity - Texture2D sprite sheet' as data format in your TexturePacker project!""Ok");
        return LoaderResult.Error;
      }
      if (num1 > 40300 || flag2)
      {
        EditorUtility.DisplayDialog("Please update TexturePacker Importer""Your TexturePacker Importer is too old to import '" + dataFile + "', please load a new version from the asset store!\n\nEnsure that you have selected 'Unity - Texture2D sprite sheet' as data format in your TexturePacker project!""Ok");
        return LoaderResult.Error;
      }
      string str4 = SpritesheetCollection.fixPath(Path.GetDirectoryName(dataFile) + "/" + str1);
      if (normalmapFile != null)
        normalmapFile = SpritesheetCollection.fixPath(Path.GetDirectoryName(dataFile) + "/" + normalmapFile);
      SettingsDatabase.getInstance().addSheet(dataFile, str4, normalmapFile);
      Dictionary<string, SpriteMetaData> dictionary = new Dictionary<string, SpriteMetaData>();
      foreach (string str2 in strArray1)
      {
        if (!string.IsNullOrEmpty(str2) && !str2.StartsWith("#"&& !str2.StartsWith(":"))
        {
          string[] values = str2.Split(';');
          int num2 = 0;
          if (values.Length < 7)
          {
            EditorUtility.DisplayDialog("File format error""Failed to import '" + dataFile + "'""Ok");
            return LoaderResult.Error;
          }
          SpriteMetaData smd = (SpriteMetaData) null;
          ref SpriteMetaData local = ref smd;
          string[] strArray2 = values;
          int index1 = num2;
          int num3 = index1 + 1;
          string str3 = this.unescapeName(strArray2[index1]);
          local.name = (__Null) str3;
          if (dictionary.ContainsKey((string) smd.name))
          {
            EditorUtility.DisplayDialog("Sprite sheet import failed""Name conflict: Sprite sheet '" + Path.GetFileNameWithoutExtension(dataFile) + "' contains multiple sprites with name '" + (string) smd.name + "'""Abort");
            return LoaderResult.Error;
          }
          string[] strArray3 = values;
          int index2 = num3;
          int num4 = index2 + 1;
          float num5 = float.Parse(strArray3[index2], (IFormatProvider) CultureInfo.InvariantCulture);
          string[] strArray4 = values;
          int index3 = num4;
          int num6 = index3 + 1;
          float num7 = float.Parse(strArray4[index3], (IFormatProvider) CultureInfo.InvariantCulture);
          string[] strArray5 = values;
          int index4 = num6;
          int num8 = index4 + 1;
          float num9 = float.Parse(strArray5[index4], (IFormatProvider) CultureInfo.InvariantCulture);
          string[] strArray6 = values;
          int index5 = num8;
          int num10 = index5 + 1;
          float num11 = float.Parse(strArray6[index5], (IFormatProvider) CultureInfo.InvariantCulture);
          smd.rect = (__Null) new Rect(num5, num7, num9, num11);
          string[] strArray7 = values;
          int index6 = num10;
          int num12 = index6 + 1;
          string x = strArray7[index6];
          string[] strArray8 = values;
          int index7 = num12;
          int idx = index7 + 1;
          string y = strArray8[index7];
          sheetInfo.pivotPointsEnabled = sheetInfo.pivotPointsEnabled && this.parsePivotPoint(x, y, ref smd);
          if (num1 >= 40300)
          {
            string[] strArray9 = values;
            int index8 = idx;
            int num13 = index8 + 1;
            float num14 = float.Parse(strArray9[index8], (IFormatProvider) CultureInfo.InvariantCulture);
            string[] strArray10 = values;
            int index9 = num13;
            int num15 = index9 + 1;
            float num16 = float.Parse(strArray10[index9], (IFormatProvider) CultureInfo.InvariantCulture);
            string[] strArray11 = values;
            int index10 = num15;
            int num17 = index10 + 1;
            float num18 = float.Parse(strArray11[index10], (IFormatProvider) CultureInfo.InvariantCulture);
            string[] strArray12 = values;
            int index11 = num17;
            idx = index11 + 1;
            float num19 = float.Parse(strArray12[index11], (IFormatProvider) CultureInfo.InvariantCulture);
            smd.border = (__Null) new Vector4(num14, num19, num16, num18);
          }
          dictionary.Add((string) smd.name, smd);
          if (Application.get_unityVersion()[0== '4')
          {
            if (idx < values.Length)
            {
              EditorUtility.DisplayDialog("Sprite sheet import failed.""Import of polygon sprites requires Unity 5!""Abort");
              return LoaderResult.Error;
            }
          }
          else
          {
            SpriteGeometry geometry = new SpriteGeometry();
            if (idx < values.Length)
            {
              if (geometry.parse(values, idx) < 0)
              {
                Debug.LogError((object) ("format error in file " + dataFile));
                return LoaderResult.Error;
              }
              sheetInfo.polygonsEnabled = true;
            }
            else
              geometry.setQuad((int) num9, (int) num11);
            this.spriteGeometries.addGeometry(str4, (string) smd.name, geometry);
          }
        }
      }
      sheetInfo.metadata = new SpriteMetaData[dictionary.Count];
      dictionary.Values.CopyTo(sheetInfo.metadata, 0);
      if (!sheetInfo.pivotPointsEnabled)
      {
        Dbg.Log("Pivot points disabled in .tpsheet, using 'center'");
        for (int index = 0; index < sheetInfo.metadata.Length; ++index)
        {
          sheetInfo.metadata[index].pivot = (__Null) new Vector2(0.5f, 0.5f);
          sheetInfo.metadata[index].alignment = (__Null) 0;
        }
      }
      sheetInfo.sheetHash = this.getAssetDependencyHash(dataFile);
      this.spriteSheetData[dataFile] = sheetInfo;
      Dbg.Log("Successfully loaded tpsheet file containing " + (object) sheetInfo.metadata.Length + " sprite definitions");
      return LoaderResult.Loaded;
    }
 
    private static string fixPath(string path)
    {
      return path?.Replace("\\""/").Replace("//""/");
    }
 
    private bool parsePivotPoint(string x, string y, ref SpriteMetaData smd)
    {
      float num1;
      float num2;
      try
      {
        num1 = float.Parse(x, (IFormatProvider) CultureInfo.InvariantCulture);
        num2 = float.Parse(y, (IFormatProvider) CultureInfo.InvariantCulture);
      }
      catch
      {
        return false;
      }
      smd.pivot = (__Null) new Vector2(num1, num2);
      smd.alignment = (double) num1 != 0.0 || (double) num2 != 0.0 ? ((double) num1 != 0.5 || (double) num2 != 0.0 ? ((double) num1 != 1.0 || (double) num2 != 0.0 ? ((double) num1 != 0.0 || (double) num2 != 0.5 ? ((double) num1 != 0.5 || (double) num2 != 0.5 ? ((double) num1 != 1.0 || (double) num2 != 0.5 ? ((double) num1 != 0.0 || (double) num2 != 1.0 ? ((double) num1 != 0.5 || (double) num2 != 1.0 ? ((double) num1 != 1.0 || (double) num2 != 1.0 ? (__Null) 9 : (__Null) 3) : (__Null) 2) : (__Null) 1) : (__Null) 5) : (__Null) 0) : (__Null) 4) : (__Null) 8) : (__Null) 7) : (__Null) 6;
      return true;
    }
 
    public void unloadSheetData(string dataFile)
    {
      this.spriteSheetData.Remove(dataFile);
      SettingsDatabase.getInstance().removeSheet(dataFile, true);
    }
 
    private string unescapeName(string name)
    {
      return name.Replace("%23""#").Replace("%3A"":").Replace("%3B"";").Replace("%25""%").Replace("/""-");
    }
 
    public SheetInfo sheetInfoForSpriteFile(string textureFile)
    {
      string dataFile = SettingsDatabase.getInstance().dataFileForSpriteFile(textureFile);
      return dataFile == null ? (SheetInfo) null : this.sheetInfoForDataFile(dataFile);
    }
 
    public SheetInfo sheetInfoForDataFile(string dataFile)
    {
      if (!this.spriteSheetData.ContainsKey(dataFile))
      {
        int num = (intthis.loadSheetData(dataFile);
      }
      return this.spriteSheetData.ContainsKey(dataFile) ? this.spriteSheetData[dataFile] : (SheetInfo) null;
    }
 
    public void assignGeometries(string texturePath, Sprite[] sprites)
    {
      SheetInfo sheetInfo = this.sheetInfoForSpriteFile(texturePath);
      if (sheetInfo == null || !sheetInfo.polygonsEnabled)
        return;
      float scaleFactor = 1f;
      if (sheetInfo.width > 0 && sprites.Length > 0)
      {
        scaleFactor = Math.Min((float) ((Texture) sprites[0].get_texture()).get_width() / (float) sheetInfo.width, (float) ((Texture) sprites[0].get_texture()).get_height() / (float) sheetInfo.height);
        Dbg.Log("Texture scale factor: " + (object) scaleFactor);
      }
      Dbg.Log("Updating geometry of " + (object) sprites.Length + " sprites ");
      try
      {
        foreach (Sprite sprite in sprites)
          this.spriteGeometries.assignGeometryToSprite(texturePath, sprite, scaleFactor);
      }
      catch (InvalidVertexException ex)
      {
        Dbg.Log("Sprite geometry doesn't match sprite frame (texture meta data might be outdated, geometries will be updated later)");
      }
    }
  }
}
 
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
// Decompiled with JetBrains decompiler
// Type: TPImporter.TexturePackerImporter
// Assembly: TPImporter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E2878734-D547-40E0-937A-625B29249F16
// Assembly location: D:\workspace\unity\CookieRun\Assets\codeandweb.com\Editor\TexturePackerImporter.dll
 
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;
 
namespace TPImporter
{
  public class TexturePackerImporter : AssetPostprocessor
  {
    public static SpritesheetCollection spriteSheets = new SpritesheetCollection();
    private static bool createMaterials = false;
    private static bool runningInDelayedCall = false;
 
    public TexturePackerImporter()
    {
      base.\u002Ector();
    }
 
    private static void OnPostprocessAllAssets(
      string[] importedAssets,
      string[] deletedAssets,
      string[] movedAssets,
      string[] movedFromAssetPaths)
    {
      List<string> stringList1 = new List<string>((IEnumerable<string>) deletedAssets);
      stringList1.AddRange((IEnumerable<string>) movedFromAssetPaths);
      foreach (string str in stringList1)
      {
        if (Path.GetExtension(str).Equals(".tpsheet"))
        {
          Dbg.Log("OnPostprocessAllAssets: removing sprite sheet data " + str);
          TexturePackerImporter.spriteSheets.unloadSheetData(str);
        }
      }
      List<string> stringList2 = new List<string>((IEnumerable<string>) importedAssets);
      stringList2.AddRange((IEnumerable<string>) movedAssets);
      foreach (string str1 in stringList2)
      {
        if (Path.GetExtension(str1).Equals(".tpsheet"))
        {
          Dbg.Log("OnPostprocessAllAssets: " + (!SettingsDatabase.getInstance().containsDataFile(str1) ? "adding " : "updating "+ " sprite sheet data " + str1);
          if (TexturePackerImporter.spriteSheets.loadSheetData(str1) == LoaderResult.Loaded)
          {
            SettingsDatabase instance = SettingsDatabase.getInstance();
            AssetDatabase.ImportAsset(instance.spriteFileForDataFile(str1), (ImportAssetOptions) 1);
            string str2 = instance.normalsFileForDataFile(str1);
            if (str2 != null)
              AssetDatabase.ImportAsset(str2, (ImportAssetOptions) 1);
          }
        }
      }
      if (!TexturePackerImporter.createMaterials)
        return;
      // ISSUE: variable of the null type
      __Null delayCall = EditorApplication.delayCall;
      // ISSUE: reference to a compiler-generated field
      if (TexturePackerImporter.\u003C\u003Ef__mg\u0024cache0 == null)
      {
        // ISSUE: reference to a compiler-generated field
        // ISSUE: method pointer
        TexturePackerImporter.\u003C\u003Ef__mg\u0024cache0 = new EditorApplication.CallbackFunction((objectnull, __methodptr(createAllMaterials));
      }
      // ISSUE: reference to a compiler-generated field
      EditorApplication.CallbackFunction fMgCache0 = TexturePackerImporter.\u003C\u003Ef__mg\u0024cache0;
      EditorApplication.delayCall = (__Null) Delegate.Combine((Delegate) delayCall, (Delegate) fMgCache0);
    }
 
    private static void GetOrigImageSize(
      Texture2D texture,
      TextureImporter importer,
      out int width,
      out int height)
    {
      try
      {
        object[] parameters = new object[2]
        {
          (object0,
          (object0
        };
        MethodInfo method = typeof (TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.Instance | BindingFlags.NonPublic, (Binder) nullnew Type[2]
        {
          typeof (int).MakeByRefType(),
          typeof (int).MakeByRefType()
        }, (ParameterModifier[]) null);
        if ((object) method is null)
          throw new Exception("Method GetWidthAndHeight(int,int) not found");
        method.Invoke((object) importer, parameters);
        width = (int) parameters[0];
        height = (int) parameters[1];
      }
      catch (Exception ex)
      {
        Debug.LogError((object) ("Invoking TextureImporter.GetWidthAndHeight() failed: " + ex.ToString()));
        width = ((Texture) texture).get_width();
        height = ((Texture) texture).get_height();
      }
    }
 
    private void OnPreprocessTexture()
    {
      TextureImporter assetImporter = this.get_assetImporter() as TextureImporter;
      SettingsDatabase instance = SettingsDatabase.getInstance();
      if (instance.isSpriteSheet(this.get_assetPath()))
      {
        assetImporter.set_textureType((TextureImporterType) 8);
      }
      else
      {
        if (!instance.isNormalmapSheet(this.get_assetPath()))
          return;
        assetImporter.set_textureType((TextureImporterType) 1);
      }
    }
 
    public void OnPostprocessTexture(Texture2D texture)
    {
      TextureImporter assetImporter = this.get_assetImporter() as TextureImporter;
      int width;
      int height;
      TexturePackerImporter.GetOrigImageSize(texture, assetImporter, out width, out height);
      Dbg.Log("OnPostprocessTexture(" + this.get_assetPath() + "), " + (object) ((Texture) texture).get_width() + "x" + (object) ((Texture) texture).get_height() + ", orig:" + (object) width + "x" + (object) height);
      SettingsDatabase instance = SettingsDatabase.getInstance();
      if (!instance.isSpriteSheet(this.get_assetPath()))
      {
        string str1 = Path.ChangeExtension(this.get_assetPath(), ".tpsheet");
        if (File.Exists(str1))
        {
          Dbg.Log("No tpsheet loaded for " + this.get_assetPath() + ", loading fallback: " + str1);
          if (TexturePackerImporter.spriteSheets.loadSheetData(str1) == LoaderResult.Error)
          {
            Dbg.Log("Failed to load sprite sheet data " + str1);
          }
          else
          {
            string str2 = instance.normalsFileForDataFile(str1);
            if (str2 != null)
              AssetDatabase.ImportAsset(str2, (ImportAssetOptions) 1);
          }
        }
      }
      if (instance.isSpriteSheet(this.get_assetPath()))
      {
        SheetInfo sheetInfo = TexturePackerImporter.spriteSheets.sheetInfoForSpriteFile(this.get_assetPath());
        if (sheetInfo.width > 0 && sheetInfo.height > 0 && (sheetInfo.width != width || sheetInfo.height != height))
          Dbg.Log("Inconsistent sheet size in png/tpsheet");
        else if (assetImporter.get_textureType() != 8)
        {
          Dbg.Log("Sprite has type " + (object) assetImporter.get_textureType() + ", re-importing it as 'Sprite'");
          assetImporter.set_textureType((TextureImporterType) 8);
          ((AssetImporter) assetImporter).SaveAndReimport();
        }
        else
        {
          assetImporter.set_alphaIsTransparency(sheetInfo.alphaIsTransparency);
          TexturePackerImporter.setSpriteMeshType(assetImporter, !sheetInfo.polygonsEnabled ? (SpriteMeshType) 0 : (SpriteMeshType) 1);
          TexturePackerImporter.updateSpriteMetaData(assetImporter, sheetInfo, texture);
        }
      }
      else if (instance.isNormalmapSheet(this.get_assetPath()))
      {
        assetImporter.set_textureType((TextureImporterType) 1);
        TexturePackerImporter.createMaterials = true;
      }
      else
        Dbg.Log("No tpsheet file loaded for " + this.get_assetPath() + ", skipping");
    }
 
    public void OnPostprocessSprites(Texture2D texture, Sprite[] sprites)
    {
      TexturePackerImporter.spriteSheets.assignGeometries(this.get_assetPath(), sprites);
    }
 
    private static void setSpriteMeshType(TextureImporter importer, SpriteMeshType type)
    {
      TextureImporterSettings importerSettings = new TextureImporterSettings();
      importer.ReadTextureSettings(importerSettings);
      importerSettings.set_spriteMeshType(type);
      importer.SetTextureSettings(importerSettings);
    }
 
    private static void updateSpriteMetaData(
      TextureImporter importer,
      SheetInfo sheetInfo,
      Texture2D texture)
    {
      Dbg.Log("PNG has type " + (object) importer.get_textureType());
      if (importer.get_spriteImportMode() != 2)
      {
        Dbg.Log("changing sprite import mode to Multiple");
        importer.set_spriteImportMode((SpriteImportMode) 2);
        ((AssetImporter) importer).SaveAndReimport();
      }
      SpriteMetaData[] metadata = sheetInfo.metadata;
      bool copyPivotPoints = !sheetInfo.pivotPointsEnabled || !SettingsDatabase.getInstance().importPivotPoints();
      bool copyBorders = !sheetInfo.bordersEnabled;
      MetaDataUpdate.copyOldAttributes(importer.get_spritesheet(), metadata, copyPivotPoints, copyBorders);
      if (!MetaDataUpdate.areEqual(importer.get_spritesheet(), metadata))
      {
        Dbg.Log("Set new meta data with " + (object) metadata.Length + " sprites on " + ((AssetImporter) importer).get_assetPath());
        importer.set_spritesheet(metadata);
        EditorUtility.SetDirty((Object) importer);
        EditorUtility.SetDirty((Object) texture);
        AssetDatabase.WriteImportSettingsIfDirty(((AssetImporter) importer).get_assetPath());
        if (TexturePackerImporter.runningInDelayedCall)
          return;
        // ISSUE: variable of the null type
        __Null delayCall = EditorApplication.delayCall;
        // ISSUE: reference to a compiler-generated field
        if (TexturePackerImporter.\u003C\u003Ef__am\u0024cache0 == null)
        {
          // ISSUE: reference to a compiler-generated field
          // ISSUE: method pointer
          TexturePackerImporter.\u003C\u003Ef__am\u0024cache0 = new EditorApplication.CallbackFunction((objectnull, __methodptr(\u003CupdateSpriteMetaData\u003Em__0));
        }
        // ISSUE: reference to a compiler-generated field
        EditorApplication.CallbackFunction fAmCache0 = TexturePackerImporter.\u003C\u003Ef__am\u0024cache0;
        EditorApplication.delayCall = (__Null) Delegate.Combine((Delegate) delayCall, (Delegate) fAmCache0);
      }
      else
        Dbg.Log("Meta data hasn't changed");
    }
 
    private static void createAllMaterials()
    {
      Dbg.Log("Creating material files");
      SettingsDatabase instance = SettingsDatabase.getInstance();
      foreach (string allDataFile in instance.allDataFiles())
        TexturePackerImporter.createMaterialForNormalmap(instance.normalsFileForDataFile(allDataFile), instance.spriteFileForDataFile(allDataFile));
      TexturePackerImporter.createMaterials = false;
    }
 
    private static void createMaterialForNormalmap(string normalSheet, string spriteSheet)
    {
      string path = Path.ChangeExtension(spriteSheet, ".mat");
      if (File.Exists(path))
        return;
      Texture2D texture2D1 = AssetDatabase.LoadAssetAtPath(spriteSheet, typeof (Texture2D)) as Texture2D;
      Texture2D texture2D2 = AssetDatabase.LoadAssetAtPath(normalSheet, typeof (Texture2D)) as Texture2D;
      if (Object.op_Equality((Object) texture2D1, (Object) null|| Object.op_Equality((Object) texture2D2, (Object) null))
      {
        Dbg.Log("Create material: sheet or normals not yet available");
      }
      else
      {
        bool flag = true;
        Shader shader = Shader.Find("Standard");
        if (Object.op_Equality((Object) shader, (Object) null))
        {
          shader = Shader.Find("Transparent/Bumped Diffuse");
          flag = false;
        }
        Material material = new Material(shader);
        material.SetTexture("_MainTex", (Texture) texture2D1);
        material.SetTexture("_BumpMap", (Texture) texture2D2);
        if (flag)
        {
          material.SetFloat("_Mode", 2f);
          material.SetInt("_SrcBlend"5);
          material.SetInt("_DstBlend"10);
          material.SetInt("_ZWrite"0);
          material.DisableKeyword("_ALPHATEST_ON");
          material.EnableKeyword("_ALPHABLEND_ON");
          material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
          material.set_renderQueue(3000);
        }
        Dbg.Log("Create material file " + path);
        AssetDatabase.CreateAsset((Object) material, path);
        EditorUtility.SetDirty((Object) material);
      }
    }
  }
}
 
cs
반응형

'Unity3D' 카테고리의 다른 글

AssetBundle 만들기 (Unity Pro, iPhone Advanced Only)  (0) 2020.08.06
XR is currently not supported when using the Vulkan Graphics API.  (0) 2020.06.02
중력가속도 점프 Jump  (0) 2020.05.27
fire auth 주의사항  (0) 2020.02.20
keystore sha1  (0) 2020.02.20
: