/// <summary> /// Sets the asset texture format. /// </summary> /// <returns><c>true</c>, if set format was set, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> /// <param name="format">Format.</param> public static bool AssetSetFormat(string path, TextureImporterFormat format) { if (string.IsNullOrEmpty(path)) { return(false); } TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; if (ti == null) { return(false); } TextureImporterSettings settings = new TextureImporterSettings(); TextureImporterPlatformSettings platformSetting = new TextureImporterPlatformSettings(); ti.ReadTextureSettings(settings); platformSetting.format = format; ti.SetTextureSettings(settings); SPTools.DoAssetReimport(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); return(true); }
/// <summary> /// Sets the asset Read/Write enabled state. /// </summary> /// <returns><c>true</c>, if set read write enabled was asseted, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> /// <param name="enabled">If set to <c>true</c> enabled.</param> /// <param name="force">If set to <c>true</c> force.</param> public static bool AssetSetReadWriteEnabled(string path, bool enabled, bool force) { if (string.IsNullOrEmpty(path)) { return(false); } TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; if (ti == null) { return(false); } TextureImporterSettings settings = new TextureImporterSettings(); ti.ReadTextureSettings(settings); if (force || settings.readable != enabled) { settings.readable = enabled; ti.SetTextureSettings(settings); SPTools.DoAssetReimport(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); } return(true); }
public static void CreateInstance() { string assetPath = GetSavePath(); if (string.IsNullOrEmpty(assetPath)) { return; } // Create the sprite packer instance SPInstance asset = ScriptableObject.CreateInstance("SPInstance") as SPInstance; AssetDatabase.CreateAsset(asset, AssetDatabase.GenerateUniqueAssetPath(assetPath)); AssetDatabase.Refresh(); // Save the instance id in the editor prefs EditorPrefs.SetInt(SPTools.Settings_SavedInstanceIDKey, asset.GetInstanceID()); // Repaint the SPDropWindow EditorWindow.GetWindow(typeof(SPDropWindow)).Repaint(); // Get a name for the texture string texturePath = assetPath.Replace(".asset", ".png"); // Create blank texture if (SPTools.CreateBlankTexture(texturePath, true)) { // Set the texture reff in the sprite packer instance asset.texture = AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D)) as Texture2D; } // Focus on the new sprite packer EditorUtility.FocusProjectWindow(); Selection.activeObject = asset; }
/// <summary> /// Sets the asset texture format. /// </summary> /// <returns><c>true</c>, if set format was set, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> /// <param name="format">Format.</param> public static bool AssetSetFormat(string path, TextureImporterFormat format) { if (string.IsNullOrEmpty(path)) { return(false); } TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; if (ti == null) { return(false); } TextureImporterPlatformSettings tips = ti.GetDefaultPlatformTextureSettings(); tips.format = format; tips.overridden = true; ti.SetPlatformTextureSettings(tips); SPTools.DoAssetReimport(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); return(true); }
/// <summary> /// Sets the asset texture format. /// </summary> /// <returns><c>true</c>, if set format was set, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> /// <param name="format">Format.</param> public static bool AssetSetFormat(string path, TextureImporterFormat format) { if (string.IsNullOrEmpty(path)) { return(false); } TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; if (ti == null) { return(false); } #if UNITY_5_5_OR_NEWER TextureImporterPlatformSettings platformSettings = ti.GetDefaultPlatformTextureSettings(); platformSettings.format = format; ti.SetPlatformTextureSettings(platformSettings); #else TextureImporterSettings settings = new TextureImporterSettings(); ti.ReadTextureSettings(settings); settings.textureFormat = format; ti.SetTextureSettings(settings); #endif SPTools.DoAssetReimport(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); return(true); }
/// <summary> /// Filters the resources for atlas import. /// </summary> /// <returns>The resources for atlas import.</returns> /// <param name="resources">Resources.</param> public static Object[] FilterResourcesForAtlasImport(Object[] resources) { List <Object> tempList = new List <Object>(); foreach (Object resource in resources) { string resourcePath = SPTools.GetAssetPath(resource); // Check if this is a main asset and queue all it's sub assets if (SPTools.IsMainAsset(resource) && SPTools.HasSubAssets(resource)) { Object[] subAssets = SPTools.FilterResourcesForAtlasImport(SPTools.GetSubAssets(resource)); foreach (Object a in subAssets) { tempList.Add(a); } } else if (resource is Texture2D || resource is Sprite) { tempList.Add(resource); } else if (SPTools.IsDirectory(resourcePath)) { Object[] subAssets = SPTools.FilterResourcesForAtlasImport(SPTools.GetDirectoryAssets(resourcePath)); foreach (Object a in subAssets) { tempList.Add(a); } } } return(tempList.ToArray()); }
/// <summary> /// Sets the asset texture format. /// </summary> /// <returns><c>true</c>, if set format was set, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> /// <param name="format">Format.</param> public static bool AssetSetFormat(string path, TextureImporterFormat format, Texture2D texture) { if (string.IsNullOrEmpty(path)) { return(false); } TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; if (ti == null) { return(false); } TextureImporterSettings settings = new TextureImporterSettings(); ti.ReadTextureSettings(settings); int size = Mathf.Max(texture.height, texture.width); SetPlatformTextureSettings("Standalone", size, ti, format); SetPlatformTextureSettings("Android", size, ti, format); SetPlatformTextureSettings("iPhone", size, ti, format); SPTools.DoAssetReimport(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); return(true); }
/// <summary> /// Replaces all the references in all scenes. /// </summary> /// <param name="spriteInfoList">Sprite info list.</param> /// <param name="spriteRenderersOnly">If set to <c>true</c> sprite renderers only.</param> /// <param name="skipCurrent">If set to <c>true</c> skip current scene.</param> /// <returns>The replaced references count.</returns> public static int ReplaceReferencesInAllScenes(List <SPSpriteInfo> spriteInfoList, SPReferenceReplacerWindow.ReplaceMode replaceMode, bool spriteRenderersOnly, bool skipCurrent) { int count = 0; bool replaceAtlas = (replaceMode == SPReferenceReplacerWindow.ReplaceMode.AtlasWithSource); // Grab the current scene name //string startingScene = EditorApplication.currentScene; Scene scene = EditorSceneManager.GetActiveScene(); string startingScene = scene.ToString(); // Get all scene names string[] sceneNames = SPTools.GetAllScenesNames(); if (sceneNames.Length == 0) { return(count); } foreach (string sceneName in sceneNames) { // Check if we should skip the scene if (skipCurrent && sceneName.Equals(startingScene)) { continue; } // Try opening the scene //if (EditorApplication.OpenScene(sceneName)) Scene _scene = EditorSceneManager.OpenScene(sceneName); if (EditorSceneManager.SetActiveScene(_scene)) { Component[] comps = Object.FindObjectsOfType <Component>(); foreach (SPSpriteInfo spriteInfo in spriteInfoList) { if (spriteInfo.source == null || !(spriteInfo.source is Sprite) || spriteInfo.targetSprite == null) { continue; } count += SPTools.ReplaceReferences(comps, (replaceAtlas ? spriteInfo.targetSprite : (spriteInfo.source as Sprite)), (replaceAtlas ? (spriteInfo.source as Sprite) : spriteInfo.targetSprite), spriteRenderersOnly); } //EditorApplication.SaveScene(); Scene __scene = EditorSceneManager.GetActiveScene(); EditorSceneManager.SaveScene(__scene); } } // Load back the original scene //EditorApplication.OpenScene(sceneName) EditorSceneManager.OpenScene(startingScene); // Return the replaced references count return(count); }
/// <summary> /// Creates a blank atlas texture. /// </summary> /// <returns><c>true</c>, if blank texture was created, <c>false</c> otherwise.</returns> /// <param name="path">Asset Path.</param> /// <param name="alphaTransparency">If set to <c>true</c> alpha transparency.</param> public static bool CreateBlankTexture(string path, bool alphaTransparency) { if (string.IsNullOrEmpty(path)) { return(false); } // Prepare blank texture Texture2D texture = new Texture2D(1, 1, TextureFormat.ARGB32, false); // Create the texture asset AssetDatabase.CreateAsset(texture, AssetDatabase.GenerateUniqueAssetPath(path)); // Clear the read-only flag in texture file attributes if (!SPTools.RemoveReadOnlyFlag(path)) { return(false); } // Write the texture data byte[] bytes = texture.EncodeToPNG(); System.IO.File.WriteAllBytes(path, bytes); bytes = null; // Get the asset texture importer TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter; if (textureImporter == null) { return(false); } TextureImporterSettings settings = new TextureImporterSettings(); TextureImporterPlatformSettings platformSetting = new TextureImporterPlatformSettings(); textureImporter.ReadTextureSettings(settings); settings.spriteMode = 2; settings.readable = false; textureImporter.maxTextureSize = 4096; settings.wrapMode = TextureWrapMode.Clamp; settings.npotScale = TextureImporterNPOTScale.ToNearest; platformSetting.format = TextureImporterFormat.ARGB32; settings.filterMode = FilterMode.Point; settings.aniso = 4; settings.alphaIsTransparency = alphaTransparency; textureImporter.SetTextureSettings(settings); textureImporter.textureType = TextureImporterType.Sprite; AssetDatabase.SaveAssets(); SPTools.DoAssetReimport(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); return(true); }
protected void OnEnable() { this.m_SPInstance = this.target as SPInstance; this.m_AtlasBuilder = new SPAtlasBuilder(this.m_SPInstance); SPTools.PrepareDefaultEditorPrefs(); this.boxStyle = new GUIStyle(EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).box); this.paddingStyle = new GUIStyle(); this.paddingStyle.padding = new RectOffset(3, 3, 3, 3); }
private void DropAreaGUI() { Event evt = Event.current; Rect drop_area = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true)); this.boxStyle.alignment = TextAnchor.MiddleCenter; GUI.color = SPInstanceEditor.green; GUI.Box(drop_area, "Add Sprite (Drop Here)", this.boxStyle); GUI.color = Color.white; switch (evt.type) { case EventType.DragUpdated: case EventType.DragPerform: { if (!drop_area.Contains(evt.mousePosition)) { return; } DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (evt.type == EventType.DragPerform) { DragAndDrop.AcceptDrag(); Object[] filtered = SPTools.FilterResourcesForAtlasImport(DragAndDrop.objectReferences); // Disallow miltiple sprites of the same source, if set so if (!SPTools.GetEditorPrefBool(SPTools.Settings_AllowMuliSpritesOneSource)) { // Additional filtering specific to the instance for (int i = 0; i < filtered.Length; i++) { if (this.m_SPInstance.sprites.Find(s => s.source == filtered[i]) != null) { Debug.LogWarning("A sprite with source \"" + SimpleSpritePackerEditor.SPTools.GetAssetPath(filtered[i]) + "\" already exists in the atlas, consider changing the Sprite Packer settings to allow multiple sprites from the same source."); System.Array.Clear(filtered, i, 1); } } } // Types are handled internally this.m_SPInstance.QueueAction_AddSprites(filtered); } break; } } }
/// <summary> /// Corrects the textures format. /// </summary> /// <param name="spriteInfoList">Sprite info list.</param> protected void CorrectTexturesFormat(List <SPSpriteInfo> spriteInfoList) { if (spriteInfoList == null || spriteInfoList.Count == 0) { return; } foreach (SPSpriteInfo spriteInfo in spriteInfoList) { Texture2D texture = null; // No source but present target sprite if (spriteInfo.source == null && spriteInfo.targetSprite != null) { texture = spriteInfo.targetSprite.texture; } // Texture source else if (spriteInfo.source is Texture2D) { texture = (spriteInfo.source as Texture2D); } // Sprite source else if (spriteInfo.source is Sprite) { texture = (spriteInfo.source as Sprite).texture; } if (texture != null) { // Make sure it's the correct format if (texture.format != TextureFormat.ARGB32 && texture.format != TextureFormat.RGBA32 && texture.format != TextureFormat.BGRA32 && texture.format != TextureFormat.RGB24 && texture.format != TextureFormat.Alpha8 && texture.format != TextureFormat.DXT1 && texture.format != TextureFormat.DXT5) { // Get the texture asset path string assetPath = SPTools.GetAssetPath(texture); // Set new texture format if (!SPTools.AssetSetFormat(assetPath, TextureImporterFormat.ARGB32)) { Debug.LogWarning("Sprite Packer failed to set texture format ARGB32 on asset: " + assetPath); } } } } }
/// <summary> /// Replaces all the references in the project (does not work with internal properties). /// </summary> /// <param name="spriteInfoList">Sprite info list.</param> /// <param name="spriteRenderersOnly">If set to <c>true</c> sprite renderers only.</param> /// <returns>The replaced references count.</returns> public static int ReplaceReferencesInProject(List <SPSpriteInfo> spriteInfoList, bool spriteRenderersOnly) { Component[] comps = SPTools.GetProjectPrefabComponents(); int count = 0; foreach (SPSpriteInfo spriteInfo in spriteInfoList) { if (spriteInfo.source != null && spriteInfo.source is Sprite && spriteInfo.targetSprite != null) { count += SPTools.ReplaceReferences(comps, (spriteInfo.source as Sprite), spriteInfo.targetSprite, spriteRenderersOnly); } } return(count); }
/// <summary> /// Replaces all the references in the scene (does not work with internal properties). /// </summary> /// <param name="spriteInfoList">Sprite info list.</param> /// <param name="spriteRenderersOnly">If set to <c>true</c> sprite renderers only.</param> /// <returns>The replaced references count.</returns> public static int ReplaceReferencesInScene(List <SPSpriteInfo> spriteInfoList, bool spriteRenderersOnly) { Component[] comps = Resources.FindObjectsOfTypeAll <Component>(); int count = 0; foreach (SPSpriteInfo spriteInfo in spriteInfoList) { if (spriteInfo.source != null && spriteInfo.source is Sprite && spriteInfo.targetSprite != null) { count += SPTools.ReplaceReferences(comps, (spriteInfo.source as Sprite), spriteInfo.targetSprite, spriteRenderersOnly); } } return(count); }
/// <summary> /// Loads a sprite from a texture. /// </summary> /// <returns>The sprite.</returns> /// <param name="mainTexture">Main texture.</param> /// <param name="name">Name.</param> public static Sprite LoadSprite(Texture2D mainTexture, string name) { string texturePath = SPTools.GetAssetPath(mainTexture); Object[] atlasAssets = AssetDatabase.LoadAllAssetsAtPath(texturePath); foreach (Object asset in atlasAssets) { if (AssetDatabase.IsSubAsset(asset) && asset.name == name) { return(asset as Sprite); } } return(null); }
/// <summary> /// Replaces all the references in all scenes. /// </summary> /// <param name="spriteInfoList">Sprite info list.</param> /// <param name="spriteRenderersOnly">If set to <c>true</c> sprite renderers only.</param> /// <param name="skipCurrent">If set to <c>true</c> skip current scene.</param> /// <returns>The replaced references count.</returns> public static int ReplaceReferencesInAllScenes(List <SPSpriteInfo> spriteInfoList, bool spriteRenderersOnly, bool skipCurrent) { int count = 0; // Grab the current scene name string startingScene = EditorSceneManager.GetActiveScene().name; // Get all scene names string[] sceneNames = SPTools.GetAllScenesNames(); if (sceneNames.Length == 0) { return(count); } foreach (string sceneName in sceneNames) { // Check if we should skip the scene if (skipCurrent && sceneName.Equals(startingScene)) { continue; } // Try opening the scene Scene scene = EditorSceneManager.OpenScene(sceneName, OpenSceneMode.Single); if (scene.IsValid()) { Component[] comps = Object.FindObjectsOfType <Component>(); foreach (SPSpriteInfo spriteInfo in spriteInfoList) { if (spriteInfo.source != null && spriteInfo.source is Sprite && spriteInfo.targetSprite != null) { count += SPTools.ReplaceReferences(comps, (spriteInfo.source as Sprite), spriteInfo.targetSprite, spriteRenderersOnly); } } EditorSceneManager.SaveOpenScenes(); } } // Load back the original scene EditorSceneManager.OpenScene(startingScene, OpenSceneMode.Single); // Return the replaced references count return(count); }
/// <summary> /// Sets the assets read write enabled. /// </summary> /// <returns><c>true</c>, if assets read write enabled was set, <c>false</c> otherwise.</returns> /// <param name="assetPaths">Asset paths.</param> /// <param name="enabled">If set to <c>true</c> enabled.</param> protected bool SetAssetsReadWriteEnabled(string[] assetPaths, bool enabled) { bool success = true; // Make the assets readable foreach (string assetPath in assetPaths) { // Make the texture readable if (!SPTools.AssetSetReadWriteEnabled(assetPath, enabled, false)) { Debug.LogWarning("Sprite Packer failed to set Read/Write state (" + enabled.ToString() + ") on asset: " + assetPath); success = false; } } // Return the result return(success); }
/// <summary> /// Replaces all the references in the project (does not work with internal properties). /// </summary> /// <param name="spriteInfoList">Sprite info list.</param> /// <param name="spriteRenderersOnly">If set to <c>true</c> sprite renderers only.</param> /// <returns>The replaced references count.</returns> public static int ReplaceReferencesInProject(List <SPSpriteInfo> spriteInfoList, SPReferenceReplacerWindow.ReplaceMode replaceMode, bool spriteRenderersOnly) { Component[] comps = SPTools.GetProjectPrefabComponents(); bool replaceAtlas = (replaceMode == SPReferenceReplacerWindow.ReplaceMode.AtlasWithSource); int count = 0; foreach (SPSpriteInfo spriteInfo in spriteInfoList) { if (spriteInfo.source == null || !(spriteInfo.source is Sprite) || spriteInfo.targetSprite == null) { continue; } count += SPTools.ReplaceReferences(comps, (replaceAtlas ? spriteInfo.targetSprite : (spriteInfo.source as Sprite)), (replaceAtlas ? (spriteInfo.source as Sprite) : spriteInfo.targetSprite), spriteRenderersOnly); } return(count); }
/// <summary> /// Imports a texture as asset. /// </summary> /// <returns><c>true</c>, if texture was imported, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> /// <param name="texture">Texture.</param> public static bool ImportTexture(string path, Texture2D texture) { if (string.IsNullOrEmpty(path)) { return(false); } // Clear the read-only flag in texture file attributes if (!SPTools.RemoveReadOnlyFlag(path)) { return(false); } byte[] bytes = texture.EncodeToPNG(); System.IO.File.WriteAllBytes(path, bytes); bytes = null; AssetDatabase.SaveAssets(); SPTools.DoAssetReimport(path, ImportAssetOptions.ForceSynchronousImport); return(true); }
/// <summary> /// Collects the source textures asset paths. /// </summary> /// <returns>The source texture asset paths.</returns> /// <param name="spriteInfoList">Sprite info list.</param> protected string[] CollectSourceTextureAssetPaths(List <SPSpriteInfo> spriteInfoList) { List <string> texturePaths = new List <string>(); // Add the textures from the sprite info list into our textures list foreach (SPSpriteInfo spriteInfo in spriteInfoList) { string path = string.Empty; // No source but present target sprite if (spriteInfo.source == null && spriteInfo.targetSprite != null) { path = SPTools.GetAssetPath(spriteInfo.targetSprite.texture); } // Texture source else if (spriteInfo.source is Texture2D) { path = SPTools.GetAssetPath(spriteInfo.source as Texture2D); } // Sprite source else if (spriteInfo.source is Sprite) { path = SPTools.GetAssetPath((spriteInfo.source as Sprite).texture); } if (!string.IsNullOrEmpty(path)) { if (!texturePaths.Contains(path)) { texturePaths.Add(path); } } } return(texturePaths.ToArray()); }
/// <summary> /// Creates a blank atlas texture. /// </summary> /// <returns><c>true</c>, if blank texture was created, <c>false</c> otherwise.</returns> /// <param name="path">Asset Path.</param> /// <param name="alphaTransparency">If set to <c>true</c> alpha transparency.</param> public static bool CreateBlankTexture(string path, bool alphaTransparency) { if (string.IsNullOrEmpty(path)) { return(false); } // Prepare blank texture Texture2D texture = new Texture2D(1, 1, TextureFormat.ARGB32, false); // Create the texture asset byte[] bytes = texture.EncodeToPNG(); FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); BinaryWriter writer = new BinaryWriter(stream); for (int i = 0; i < bytes.Length; i++) { writer.Write(bytes[i]); } writer.Close(); stream.Close(); // Clear the read-only flag in texture file attributes if (!SPTools.RemoveReadOnlyFlag(path)) { return(false); } // Import the texture asset SPTools.DoAssetReimport(path, ImportAssetOptions.ForceUpdate); // Get the asset texture importer TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter; if (textureImporter == null) { return(false); } TextureImporterSettings settings = new TextureImporterSettings(); textureImporter.ReadTextureSettings(settings); //TextureImporterPlatformSettings settings.spriteMode = 2; settings.readable = false; //settings.maxTextureSize = 4096; settings.wrapMode = TextureWrapMode.Clamp; settings.npotScale = TextureImporterNPOTScale.ToNearest; //settings.textureFormat = TextureImporterFormat.ARGB32; settings.filterMode = FilterMode.Trilinear; settings.aniso = 4; settings.alphaIsTransparency = alphaTransparency; textureImporter.SetTextureSettings(settings); textureImporter.textureType = TextureImporterType.Sprite; TextureImporterPlatformSettings tips = new TextureImporterPlatformSettings(); tips.maxTextureSize = 4096; tips.format = TextureImporterFormat.Automatic; tips.textureCompression = TextureImporterCompression.Uncompressed; tips.overridden = true; textureImporter.SetPlatformTextureSettings(tips); AssetDatabase.SaveAssets(); SPTools.DoAssetReimport(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); return(true); }
protected void OnGUI() { EditorGUIUtility.labelWidth = 100f; GUILayout.BeginVertical(); GUILayout.Space((float)SPReferenceReplacerWindow.padding.top); GUILayout.BeginHorizontal(); GUILayout.Space((float)SPReferenceReplacerWindow.padding.left); GUILayout.BeginVertical(); GUI.changed = false; this.m_Instance = EditorGUILayout.ObjectField("Sprite Packer", this.m_Instance, typeof(SPInstance), false) as SPInstance; if (GUI.changed) { // Save the instance id EditorPrefs.SetInt(SPTools.Settings_SavedInstanceIDKey, (this.m_Instance == null) ? 0 : this.m_Instance.GetInstanceID()); } GUILayout.Space(6f); GUILayout.BeginVertical(GUI.skin.box); GUILayout.Space(6f); GUILayout.BeginHorizontal(); GUILayout.Space(6f); EditorGUILayout.LabelField("Replace mode", GUILayout.Width(130f)); this.m_ReplaceMode = (ReplaceMode)EditorGUILayout.EnumPopup(this.m_ReplaceMode); GUILayout.Space(6f); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Space(6f); EditorGUI.BeginChangeCheck(); EditorGUILayout.LabelField("Replace references in", GUILayout.Width(130f)); this.m_TargetMode = (TargetMode)EditorGUILayout.EnumPopup(this.m_TargetMode); if (EditorGUI.EndChangeCheck()) { EditorPrefs.SetInt(SPReferenceReplacerWindow.PrefsKey_TargetMode, (int)this.m_TargetMode); } GUILayout.Space(6f); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Space(6f); GUI.changed = false; bool spriteRenderersOnly = GUILayout.Toggle(EditorPrefs.GetBool(SPReferenceReplacerWindow.PrefsKey_SpriteRenderersOnly), " Replace references in Sprite Renderers only ?"); if (GUI.changed) { EditorPrefs.SetBool(SPReferenceReplacerWindow.PrefsKey_SpriteRenderersOnly, spriteRenderersOnly); } GUILayout.Space(6f); GUILayout.EndHorizontal(); GUILayout.Space(6f); GUILayout.EndVertical(); GUILayout.Space(6f); if (this.m_Instance == null) { EditorGUILayout.HelpBox("Please set the sprite packer instance reference in order to use this feature.", MessageType.Info); } else { if (GUILayout.Button("Replace")) { int replacedCount = 0; switch (this.m_TargetMode) { case TargetMode.CurrentScene: { replacedCount += SPTools.ReplaceReferencesInScene(this.m_Instance.copyOfSprites, this.m_ReplaceMode, spriteRenderersOnly); break; } case TargetMode.ProjectOnly: { replacedCount += SPTools.ReplaceReferencesInProject(this.m_Instance.copyOfSprites, this.m_ReplaceMode, spriteRenderersOnly); break; } case TargetMode.CurrentSceneAndProject: { replacedCount += SPTools.ReplaceReferencesInProject(this.m_Instance.copyOfSprites, this.m_ReplaceMode, spriteRenderersOnly); replacedCount += SPTools.ReplaceReferencesInScene(this.m_Instance.copyOfSprites, this.m_ReplaceMode, spriteRenderersOnly); break; } case TargetMode.AllScenes: { replacedCount += SPTools.ReplaceReferencesInAllScenes(this.m_Instance.copyOfSprites, this.m_ReplaceMode, spriteRenderersOnly, false); break; } case TargetMode.AllScenesAndProject: { replacedCount += SPTools.ReplaceReferencesInProject(this.m_Instance.copyOfSprites, this.m_ReplaceMode, spriteRenderersOnly); replacedCount += SPTools.ReplaceReferencesInScene(this.m_Instance.copyOfSprites, this.m_ReplaceMode, spriteRenderersOnly); EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene()); replacedCount += SPTools.ReplaceReferencesInAllScenes(this.m_Instance.copyOfSprites, this.m_ReplaceMode, spriteRenderersOnly, true); break; } } EditorUtility.DisplayDialog("Reference Replacer", "Replaced references count: " + replacedCount.ToString(), "Okay"); } } GUILayout.EndVertical(); GUILayout.Space((float)SPReferenceReplacerWindow.padding.right); GUILayout.EndHorizontal(); GUILayout.Space((float)SPReferenceReplacerWindow.padding.bottom); GUILayout.EndVertical(); }
/// <summary> /// Imports and configures atlas texture. /// </summary> /// <returns><c>true</c>, if import and configure atlas texture was successful, <c>false</c> otherwise.</returns> /// <param name="targetTexture">Target texture.</param> /// <param name="sourceTexture">Source texture.</param> /// <param name="uvs">Uvs.</param> /// <param name="names">Names.</param> /// <param name="defaultPivot">Default pivot.</param> /// <param name="defaultCustomPivot">Default custom pivot.</param> public static bool ImportAndConfigureAtlasTexture(Texture2D targetTexture, Texture2D sourceTexture, Rect[] uvs, SPSpriteImportData[] spritesImportData) { // Get the asset path string assetPath = SPTools.GetAssetPath(targetTexture); if (string.IsNullOrEmpty(assetPath)) { Debug.LogError("Sprite Packer failed to Import and Configure the atlas texture, reason: Could not resolve asset path."); return(false); } // Clear the read-only flag in texture file attributes if (!SPTools.RemoveReadOnlyFlag(assetPath)) { Debug.LogError("Sprite Packer failed to Import and Configure the atlas texture, reason: Could not remove the readonly flag from the asset."); return(false); } // Write the source texture data to the asset byte[] bytes = sourceTexture.EncodeToPNG(); System.IO.File.WriteAllBytes(assetPath, bytes); bytes = null; // Get the asset texture importer TextureImporter texImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (texImporter == null) { Debug.LogError("Sprite Packer failed to Import and Configure the atlas texture, reason: Could not get the texture importer for the asset."); return(false); } // Get the asset texture importer settings TextureImporterSettings texImporterSettings = new TextureImporterSettings(); // Apply sprite type texImporter.textureType = TextureImporterType.Sprite; texImporter.spriteImportMode = SpriteImportMode.Multiple; // Configure the spritesheet meta data SpriteMetaData[] spritesheetMeta = new SpriteMetaData[uvs.Length]; for (int i = 0; i < uvs.Length; i++) { if (SPTools.HasSpritesheetMeta(texImporter.spritesheet, spritesImportData[i].name)) { SpriteMetaData currentMeta = SPTools.GetSpritesheetMeta(texImporter.spritesheet, spritesImportData[i].name); Rect currentRect = uvs[i]; currentRect.x *= sourceTexture.width; currentRect.width *= sourceTexture.width; currentRect.y *= sourceTexture.height; currentRect.height *= sourceTexture.height; currentMeta.rect = currentRect; spritesheetMeta[i] = currentMeta; } else { SpriteMetaData currentMeta = new SpriteMetaData(); Rect currentRect = uvs[i]; currentRect.x *= sourceTexture.width; currentRect.width *= sourceTexture.width; currentRect.y *= sourceTexture.height; currentRect.height *= sourceTexture.height; currentMeta.rect = currentRect; currentMeta.name = spritesImportData[i].name; currentMeta.alignment = (int)spritesImportData[i].alignment; currentMeta.pivot = spritesImportData[i].pivot; currentMeta.border = spritesImportData[i].border; spritesheetMeta[i] = currentMeta; } } texImporter.spritesheet = spritesheetMeta; // Read the texture importer settings texImporter.ReadTextureSettings(texImporterSettings); // Disable Read/Write texImporterSettings.readable = false; // Re-set the texture importer settings texImporter.SetTextureSettings(texImporterSettings); // Save and Reimport the asset AssetDatabase.SaveAssets(); SPTools.DoAssetReimport(assetPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); // Return success return(true); }
/// <summary> /// Sets the texture asset Read/Write enabled state. /// </summary> /// <returns><c>true</c>, if set read write enabled was textured, <c>false</c> otherwise.</returns> /// <param name="texture">Texture.</param> /// <param name="enabled">If set to <c>true</c> enabled.</param> /// <param name="force">If set to <c>true</c> force.</param> public static bool TextureSetReadWriteEnabled(Texture2D texture, bool enabled, bool force) { return(SPTools.AssetSetReadWriteEnabled(SPTools.GetAssetPath(texture), enabled, force)); }
protected void OnGUI() { EditorGUIUtility.labelWidth = 100f; GUILayout.BeginVertical(); GUILayout.Space(8f); GUI.changed = false; this.m_Instance = EditorGUILayout.ObjectField("Sprite Packer", this.m_Instance, typeof(SPInstance), false) as SPInstance; if (GUI.changed) { // Save the instance id EditorPrefs.SetInt(SPTools.Settings_SavedInstanceIDKey, (this.m_Instance == null) ? 0 : this.m_Instance.GetInstanceID()); } GUILayout.Space(4f); if (this.m_Instance == null) { EditorGUILayout.HelpBox("Please set the sprite packer instance reference in order to use this feature.", MessageType.Info); } else { Event evt = Event.current; Rect drop_area = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); GUIStyle boxStyle = new GUIStyle(GUI.skin.box); boxStyle.alignment = TextAnchor.MiddleCenter; GUI.color = SPDropWindow.green; GUI.Box(drop_area, "Add Sprite (Drop Here)", boxStyle); GUI.color = Color.white; switch (evt.type) { case EventType.DragUpdated: case EventType.DragPerform: { if (!drop_area.Contains(evt.mousePosition)) { return; } DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (evt.type == EventType.DragPerform) { DragAndDrop.AcceptDrag(); Object[] filtered = SPTools.FilterResourcesForAtlasImport(DragAndDrop.objectReferences); // Additional filtering specific to the instance for (int i = 0; i < filtered.Length; i++) { if (this.m_Instance.sprites.Find(s => s.name == filtered[i].name) != null) { Debug.LogWarning("A sprite with source \"" + SimpleSpritePackerEditor.SPTools.GetAssetPath(filtered[i]) + "\" already exists in the atlas, consider changing the Sprite Packer settings to allow multiple sprites from the same source."); System.Array.Clear(filtered, i, 1); } } // Types are handled internally this.m_Instance.QueueAction_AddSprites(filtered); Selection.activeObject = this.m_Instance; //EditorPrefs.SetBool(SPTools.Settings_ShowSpritesKeys, false); } break; } } } GUILayout.EndVertical(); }
/// <summary> /// Rebuilds the atlas texture. /// </summary> public void RebuildAtlas() { if (this.m_Instance == null) { Debug.LogError( "SPAtlasBuilder failed to rebuild the atlas, reason: Sprite Packer Instance reference is null."); return; } if (this.m_Instance.texture == null) { Debug.LogWarning( "Sprite Packer failed to rebuild the atlas, please make sure the atlas texture reference is set."); return; } // Make the atlas texture readable if (SPTools.TextureSetReadWriteEnabled(this.m_Instance.texture, true, false)) { // Get a list with the current sprites and applied actions List <SPSpriteInfo> spriteInfoList = this.m_Instance.GetSpriteListWithAppliedActions(); // Get the source textures asset paths string[] sourceTexturePaths = this.CollectSourceTextureAssetPaths(spriteInfoList); // Make the source textures readable if (!this.SetAssetsReadWriteEnabled(sourceTexturePaths, true)) { Debug.LogError( "Sprite Packer failed to make one or more of the source texture readable, please do it manually."); return; } // Make sure all the textures have the correct texture format this.CorrectTexturesFormat(spriteInfoList); // If we are using max rects packing, sort the sprite info list by size if (this.m_Instance.packingMethod == SPInstance.PackingMethod.MaxRects) { spriteInfoList.Sort(CompareBySize); } // Temporary textures array Texture2D[] textures = new Texture2D[spriteInfoList.Count]; // Create an array to contain the sprite import data SPSpriteImportData[] spritesImportData = new SPSpriteImportData[spriteInfoList.Count]; // Populate the textures and names arrays int ia = 0; foreach (SPSpriteInfo si in spriteInfoList) { // Temporary texture Texture2D texture = null; // Prepare the sprite import data SPSpriteImportData importData = new SPSpriteImportData(); // Prepare the sprite name importData.name = "Sprite_" + ia.ToString(); if (si.targetSprite != null) { importData.name = si.targetSprite.name; } else if (si.source != null && (si.source is Texture2D || si.source is Sprite)) { if (si.source is Texture2D) { importData.name = (si.source as Texture2D).name; } else { importData.name = (si.source as Sprite).name; } } // Prepare texture // In case the source texture is missing, rebuild from the already existing sprite if (si.source == null && si.targetSprite != null) { // Copy the sprite into the temporary texture texture = new Texture2D((int)si.targetSprite.rect.width, (int)si.targetSprite.rect.height, TextureFormat.ARGB32, false); Color[] pixels = si.targetSprite.texture.GetPixels((int)si.targetSprite.rect.x, (int)si.targetSprite.rect.y, (int)si.targetSprite.rect.width, (int)si.targetSprite.rect.height); texture.SetPixels(pixels); texture.Apply(); } // Handle texture source else if (si.source is Texture2D) { // Get as texture Texture2D sourceTex = si.source as Texture2D; // Check if we have as source texture if (sourceTex != null) { // Copy the source texture into the temp one texture = new Texture2D(sourceTex.width, sourceTex.height, TextureFormat.ARGB32, false); Color[] pixels = sourceTex.GetPixels(0, 0, sourceTex.width, sourceTex.height); texture.SetPixels(pixels); texture.Apply(); // Transfer the sprite data importData.border = Vector4.zero; importData.alignment = this.m_Instance.defaultPivot; importData.pivot = this.m_Instance.defaultCustomPivot; } } // Handle sprite source else if (si.source is Sprite) { // Get as sprite Sprite sourceSprite = si.source as Sprite; // Make sure we have the sprite if (sourceSprite != null) { // Copy the sprite into the temporary texture texture = new Texture2D((int)sourceSprite.rect.width, (int)sourceSprite.rect.height, TextureFormat.ARGB32, false); Color[] pixels = sourceSprite.texture.GetPixels((int)sourceSprite.rect.x, (int)sourceSprite.rect.y, (int)sourceSprite.rect.width, (int)sourceSprite.rect.height); texture.SetPixels(pixels); texture.Apply(); // Transfer the sprite data importData.border = sourceSprite.border; importData.alignment = SpriteAlignment.Custom; importData.pivot = new Vector2( (0f - sourceSprite.bounds.center.x / sourceSprite.bounds.extents.x / 2 + 0.5f), (0f - sourceSprite.bounds.center.y / sourceSprite.bounds.extents.y / 2 + 0.5f)); } } // Save the new texture into our array textures[ia] = (texture != null) ? texture : new Texture2D(1, 1); // Set the sprite import data spritesImportData[ia] = importData; // Increase the indexer ia++; } // Make the source textures assets non readable if (SPTools.GetEditorPrefBool(SPTools.Settings_DisableReadWriteEnabled)) { this.SetAssetsReadWriteEnabled(sourceTexturePaths, false); } // Clear the source textures asset paths System.Array.Clear(sourceTexturePaths, 0, sourceTexturePaths.Length); // Create a temporary texture for the packing Texture2D tempTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false); // UV coords array Rect[] uvs; // Pack the textures into the temporary if (this.m_Instance.packingMethod == SPInstance.PackingMethod.Unity) { uvs = tempTexture.PackTextures(textures, this.m_Instance.padding, this.m_Instance.maxSize); } else { uvs = UITexturePacker.PackTextures(tempTexture, textures, this.m_Instance.padding, this.m_Instance.maxSize); // Check if packing failed if (uvs == null) { Debug.LogError( "Sprite Packer texture packing failed, the textures might be exceeding the specified maximum size."); return; } } // Import and Configure the texture atlas (also disables Read/Write) SPTools.ImportAndConfigureAtlasTexture(this.m_Instance.texture, tempTexture, uvs, spritesImportData); // Clear the current sprite info list this.m_Instance.ClearSprites(); // Clear the actions list this.m_Instance.ClearActions(); // Destroy the textures from the temporary textures array for (int ib = 0; ib < textures.Length; ib++) { UnityEngine.Object.DestroyImmediate(textures[ib]); } // Destroy the temporary texture UnityEngine.Object.DestroyImmediate(tempTexture); // Convert the temporary sprite info into array SPSpriteInfo[] spriteInfoArray = spriteInfoList.ToArray(); // Clear the temporary sprite info list spriteInfoList.Clear(); // Apply the new sprite reff to the sprite info and add the sprite info to the sprites list for (int i = 0; i < spriteInfoArray.Length; i++) { SPSpriteInfo info = spriteInfoArray[i]; if (info.targetSprite == null) { info.targetSprite = SPTools.LoadSprite(this.m_Instance.texture, spritesImportData[i].name); } // Add to the instance sprite info list this.m_Instance.AddSprite(info); } // Clear the sprites import data array System.Array.Clear(spritesImportData, 0, spritesImportData.Length); // Set dirty EditorUtility.SetDirty(this.m_Instance); } else { Debug.LogError("Sprite Packer failed to make the atlas texture readable, please do it manually."); } }