summaryrefslogtreecommitdiff
path: root/VRCSDK3Worlds/Assets/VRWorldToolkit/Scripts/Editor/MassTextureImporter.cs
blob: 32c233ab4ddb9bdf5061138e38a62b357ec71b8e (plain)
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
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using VRWorldToolkit.DataStructures;

namespace VRWorldToolkit
{
    public class TextureDetails
    {
        private int? uncrunchedCount;
        private int? normalMaps;
        private int? cubemaps;
        private long? storageSize;

        private readonly Dictionary<Texture, TextureImporter> textureList = new Dictionary<Texture, TextureImporter>();

        public void AddTexture(TextureImporter textureImporter, Texture texture)
        {
            if (!textureList.ContainsKey(texture) && textureImporter != null)
            {
                textureList.Add(texture, textureImporter);
            }
        }

        public int TextureCount => textureList.Count;

        public int UncrunchedCount
        {
            get
            {
                if (uncrunchedCount is null)
                {
                    uncrunchedCount = textureList.Count(x => !x.Value.crunchedCompression);
                }

                return (int) uncrunchedCount;
            }
        }

        public int NormalMaps
        {
            get
            {
                if (normalMaps is null)
                {
                    normalMaps = textureList.Count(x => x.Value.textureType == TextureImporterType.NormalMap);
                }

                return (int) normalMaps;
            }
        }

        public int Cubemaps
        {
            get
            {
                if (cubemaps is null)
                {
                    cubemaps = textureList.Count(x => x.Value.textureShape == TextureImporterShape.TextureCube);
                }

                return (int) cubemaps;
            }
        }

        public long StorageSize
        {
            get
            {
                if (storageSize is null)
                {
                    storageSize = textureList.Sum(x => EditorTextureUtil.GetStorageMemorySize(x.Key));
                }

                return (long) storageSize;
            }
        }

        public IEnumerable<TextureImporter> GetImporters
        {
            get { return textureList.Select(x => x.Value).ToArray(); }
        }

        public void ResetStats()
        {
            uncrunchedCount = null;
            storageSize = null;
        }
    }

    public class ImporterSettingsManager
    {
        // Mip Maps
        public bool DontChangeMipMaps { get; private set; }
        public bool StreamingMipMap { get; private set; } = true;
        public bool GenerateMipMaps { get; private set; } = true;
        public bool DontChangeAniso { get; private set; } = true;
        public int AnisoLevel { get; private set; } = 1;
        public OverrideWhenSize OverrideAnisoWhen { get; private set; }

        // Max Texture Size
        public int MaxTextureSize { get; private set; } = 2048;
        public OverrideWhenSize OverrideMaxTextureSizeWhen { get; private set; } = OverrideWhenSize.BiggerThan;

        // Crunch compression
        public bool CrunchCompression { get; private set; } = true;
        public int CompressionQuality { get; private set; } = 80;
        public DontOverrideWhen DontOverrideCrunchWhen { get; private set; } = DontOverrideWhen.AlreadyEnabled;
        public OverrideWhenSize OverrideCrunchCompressionSizeWhen { get; private set; } = OverrideWhenSize.BiggerThan;

        // Ignores
        public bool IgnoreCubemaps { get; private set; } = true;
        public OverrideWhenSize OverrideCubemapSettingsWhen { get; private set; } = OverrideWhenSize.SmallerThan;
        public int CubemapSize { get; private set; } = 512;
        public bool IgnoreNormalMaps { get; private set; } = true;

        private readonly string[] maxTextureNames = {"32", "64", "128", "256", "512", "1024", "2048", "4096", "8192"};
        private readonly int[] maxTextureSizes = {32, 64, 128, 256, 512, 1024, 2048, 4096, 8192};

        public enum OverrideWhenSize
        {
            Always,
            SmallerThan,
            BiggerThan
        }

        public enum DontOverrideWhen
        {
            Never,
            AlreadyDisabled,
            AlreadyEnabled
        }

        public void DrawSettings()
        {
            GUILayout.Label("Mip Maps", Styles.BoldWrap);
            DontChangeMipMaps = EditorGUILayout.Toggle("Don't Change", DontChangeMipMaps);
            using (new EditorGUI.DisabledScope(DontChangeMipMaps))
            {
                StreamingMipMap = EditorGUILayout.Toggle("Streaming Mip Maps", StreamingMipMap);
                GenerateMipMaps = EditorGUILayout.Toggle("Generate Mip Maps", GenerateMipMaps);
            }

            GUILayout.Label("Aniso Level", Styles.BoldWrap);
            DontChangeAniso = EditorGUILayout.Toggle("Don't Change", DontChangeAniso);
            using (new EditorGUI.DisabledScope(DontChangeAniso))
            {
                AnisoLevel = EditorGUILayout.IntSlider("Aniso Level", AnisoLevel, 0, 16);
                using (new EditorGUI.IndentLevelScope())
                {
                    OverrideAnisoWhen = (OverrideWhenSize) EditorGUILayout.EnumPopup("Override When", OverrideAnisoWhen);
                }
            }

            GUILayout.Label("Size", Styles.BoldWrap);
            MaxTextureSize = EditorGUILayout.IntPopup("Max Size", MaxTextureSize, maxTextureNames, maxTextureSizes);
            using (new EditorGUI.IndentLevelScope())
            {
                OverrideMaxTextureSizeWhen = (OverrideWhenSize) EditorGUILayout.EnumPopup("Override When", OverrideMaxTextureSizeWhen);
            }

            GUILayout.Label("Crunch Compression", Styles.BoldWrap);
            CrunchCompression = EditorGUILayout.Toggle("Use Crunch Compression", CrunchCompression);
            using (new EditorGUI.DisabledScope(!CrunchCompression))
            {
                CompressionQuality = EditorGUILayout.IntSlider(CompressionQuality, 1, 100);
                using (new EditorGUI.IndentLevelScope())
                {
                    OverrideCrunchCompressionSizeWhen = (OverrideWhenSize) EditorGUILayout.EnumPopup("Override When", OverrideCrunchCompressionSizeWhen);
                }
            }

            using (new EditorGUI.IndentLevelScope())
            {
                DontOverrideCrunchWhen = (DontOverrideWhen) EditorGUILayout.EnumPopup("Don't Override When", DontOverrideCrunchWhen);
            }

            GUILayout.Label("Ignore", Styles.BoldWrap);
            IgnoreCubemaps = EditorGUILayout.Toggle("Cubemaps", IgnoreCubemaps);
            using (new EditorGUI.IndentLevelScope())
            {
                using (new EditorGUI.DisabledScope(!IgnoreCubemaps))
                {
                    OverrideCubemapSettingsWhen = (OverrideWhenSize) EditorGUILayout.EnumPopup("Ignore When", OverrideCubemapSettingsWhen);
                    using (new EditorGUI.DisabledScope(OverrideCubemapSettingsWhen == OverrideWhenSize.Always))
                    {
                        CubemapSize = EditorGUILayout.IntPopup("Ignore Size", CubemapSize, maxTextureNames, maxTextureSizes);
                    }
                }
            }

            IgnoreNormalMaps = EditorGUILayout.Toggle("Normal maps", IgnoreNormalMaps);
        }

        public void ProcessTextures(TextureDetails details)
        {
            try
            {
                AssetDatabase.StartAssetEditing();

                var importers = details.GetImporters;
                var count = details.TextureCount;
                var current = 1;
                foreach (var importer in importers)
                {
                    EditorUtility.DisplayProgressBar("Applying New Settings", importer.assetPath, (float) current / count);

                    if (IgnoreNormalMaps && importer.textureType == TextureImporterType.NormalMap)
                        continue;

                    if (IgnoreCubemaps && importer.textureShape == TextureImporterShape.TextureCube)
                    {
                        var oldMaxTextureSize = importer.maxTextureSize;
                        var newMaxTextureSize = MaxTextureSize;

                        switch (OverrideCubemapSettingsWhen)
                        {
                            case OverrideWhenSize.SmallerThan:
                                if (oldMaxTextureSize > newMaxTextureSize) continue;
                                break;
                            case OverrideWhenSize.BiggerThan:
                                if (oldMaxTextureSize < newMaxTextureSize) continue;
                                break;
                        }
                    }

                    if (!DontChangeMipMaps)
                    {
                        importer.mipmapEnabled = GenerateMipMaps;
                        importer.streamingMipmaps = StreamingMipMap;
                    }

                    if (!DontChangeAniso)
                    {
                        var oldAnisoLevel = importer.anisoLevel;
                        var newAnisoLevel = AnisoLevel;

                        switch (OverrideAnisoWhen)
                        {
                            case OverrideWhenSize.Always:
                                importer.anisoLevel = AnisoLevel;
                                break;
                            case OverrideWhenSize.SmallerThan:
                                if (oldAnisoLevel < newAnisoLevel)
                                {
                                    importer.anisoLevel = newAnisoLevel;
                                }

                                break;
                            case OverrideWhenSize.BiggerThan:
                                if (oldAnisoLevel > newAnisoLevel)
                                {
                                    importer.maxTextureSize = newAnisoLevel;
                                }

                                break;
                        }
                    }

                    var skipCrunchCompression = false;

                    if (DontOverrideCrunchWhen != DontOverrideWhen.Never)
                    {
                        switch (DontOverrideCrunchWhen)
                        {
                            case DontOverrideWhen.AlreadyDisabled:
                                if (!importer.crunchedCompression) skipCrunchCompression = true;
                                break;
                            case DontOverrideWhen.AlreadyEnabled:
                                if (importer.crunchedCompression) skipCrunchCompression = true;
                                break;
                        }
                    }

                    if (!skipCrunchCompression)
                    {
                        var oldMaxTextureSize = importer.maxTextureSize;
                        var newMaxTextureSize = MaxTextureSize;
                        importer.crunchedCompression = CrunchCompression;

                        if (importer.crunchedCompression)
                        {
                            switch (OverrideMaxTextureSizeWhen)
                            {
                                case OverrideWhenSize.Always:
                                    importer.maxTextureSize = newMaxTextureSize;
                                    break;
                                case OverrideWhenSize.SmallerThan:
                                    if (oldMaxTextureSize < newMaxTextureSize)
                                    {
                                        importer.maxTextureSize = newMaxTextureSize;
                                    }

                                    break;
                                case OverrideWhenSize.BiggerThan:
                                    if (oldMaxTextureSize > newMaxTextureSize)
                                    {
                                        importer.maxTextureSize = newMaxTextureSize;
                                    }

                                    break;
                            }
                        }
                    }

                    importer.SaveAndReimport();
                    current++;
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                details.ResetStats();
                AssetDatabase.StopAssetEditing();
            }
        }
    }

    public class MassTextureImporter : EditorWindow
    {
        [MenuItem("VRWorld Toolkit/Quick Functions/Mass Texture Importer", false, 4)]
        public static void ShowWindow()
        {
            var window = GetWindow(typeof(MassTextureImporter));
            window.titleContent = new GUIContent("Mass Texture Importer");
            window.minSize = new Vector2(400, 530);
            window.Show();
        }

        private TextureDetails details = new TextureDetails();

        private Vector2 scrollPos;

        private ImporterSettingsManager importerSettingsManager = new ImporterSettingsManager();

        private void OnGUI()
        {
            GUILayout.Label("Selected Textures", Styles.BoldWrap);
            using (new EditorGUILayout.HorizontalScope(EditorStyles.helpBox))
            {
                using (new EditorGUILayout.VerticalScope())
                {
                    GUILayout.Label("<b>Texture Count:</b> " + details.TextureCount, Styles.LabelRichText);
                    GUILayout.Label("<b>Uncrunched Count:</b> " + details.UncrunchedCount, Styles.LabelRichText);
                    GUILayout.Label("<b>Storage Size:</b> " + EditorUtility.FormatBytes(details.StorageSize), Styles.LabelRichText);
                }

                using (new EditorGUILayout.VerticalScope())
                {
                    GUILayout.Label("<b>Normal Maps:</b> " + details.NormalMaps, Styles.LabelRichText);
                    GUILayout.Label("<b>Cubemaps:</b> " + details.Cubemaps, Styles.LabelRichText);
                }
            }

            importerSettingsManager.DrawSettings();

            GUILayout.Space(5);

            GUILayout.Label("Get textures from:");

            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("Scene", GUILayout.Width(70), GUILayout.Height(20)))
                {
                    details = GetAllTexturesFromScene();
                }

                if (GUILayout.Button("Assets", GUILayout.Width(70), GUILayout.Height(20)))
                {
                    details = GetAllTexturesFromAssets();
                }

                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Revert", GUILayout.Width(70), GUILayout.Height(20)))
                {
                    importerSettingsManager = new ImporterSettingsManager();
                }

                if (GUILayout.Button("Apply", GUILayout.Width(70), GUILayout.Height(20)))
                {
                    if (EditorUtility.DisplayDialog("Process Importers?", $"About to process Texture Import settings on {details.TextureCount} textures, this can take a while depending on the amount and size of them.\n\nDo you want to continue?", "Ok", "Cancel"))
                    {
                        importerSettingsManager.ProcessTextures(details);
                    }
                }
            }
        }

        private static TextureDetails GetAllTexturesFromScene()
        {
            var details = new TextureDetails();
            var checkedMaterials = new List<Material>();

            var allGameObjects = Resources.FindObjectsOfTypeAll(typeof(GameObject));
            var allGameObjectsLength = allGameObjects.Length;
            for (var i = 0; i < allGameObjectsLength; i++)
            {
                var gameObject = allGameObjects[i] as GameObject;

                if (gameObject.hideFlags != HideFlags.None || EditorUtility.IsPersistent(gameObject.transform.root.gameObject)) continue;

                if (EditorUtility.DisplayCancelableProgressBar("Getting All Textures from Scene", gameObject.name, (float) i / allGameObjectsLength))
                {
                    break;
                }

                var renderers = gameObject.GetComponents<Renderer>();
                for (var j = 0; j < renderers.Length; j++)
                {
                    var renderer = renderers[j];
                    for (var k = 0; k < renderer.sharedMaterials.Length; k++)
                    {
                        var material = renderer.sharedMaterials[k];

                        if (material == null || checkedMaterials.Contains(material))
                            continue;

                        checkedMaterials.Add(material);

                        var shader = material.shader;

                        for (var l = 0; l < ShaderUtil.GetPropertyCount(shader); l++)
                        {
                            if (ShaderUtil.GetPropertyType(shader, l) == ShaderUtil.ShaderPropertyType.TexEnv)
                            {
                                var texture = material.GetTexture(ShaderUtil.GetPropertyName(shader, l));

                                var textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter;

                                if (textureImporter != null)
                                {
                                    details.AddTexture(textureImporter, texture);
                                }
                            }
                        }
                    }
                }
            }

            EditorUtility.ClearProgressBar();
            return details;
        }

        private static TextureDetails GetAllTexturesFromAssets()
        {
            var details = new TextureDetails();

            var assetGuidStrings = AssetDatabase.FindAssets("t:texture2D", new[] {"Assets"});

            var assetsLength = assetGuidStrings.Length;
            for (var i = 0; i < assetsLength; i++)
            {
                var path = AssetDatabase.GUIDToAssetPath(assetGuidStrings[i]);

                if (EditorUtility.DisplayCancelableProgressBar("Getting All Textures from Assets", Path.GetFileName(path), (float) i / assetsLength))
                {
                    break;
                }

                var texture = AssetDatabase.LoadAssetAtPath<Texture>(path);
                var textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;

                details.AddTexture(textureImporter, texture);
            }

            EditorUtility.ClearProgressBar();
            return details;
        }
    }
}