UITextureAtlas CreateMyAtlas(string AtlasName, Material BaseMat, string[] sPritesNames) { var size = 1024; Texture2D atlasTex = new Texture2D(size, size, TextureFormat.ARGB32, false); Texture2D[] textures = new Texture2D[sPritesNames.Length]; Rect[] rects = new Rect[sPritesNames.Length]; for(int i = 0; i < sPritesNames.Length; i++) { textures[i] = ResourceLoader.loadTexture(0, 0, sPritesNames[i] + ".png"); } rects = atlasTex.PackTextures(textures, 2, size); UITextureAtlas atlas = ScriptableObject.CreateInstance<UITextureAtlas>(); Material material = Material.Instantiate(BaseMat); material.mainTexture = atlasTex; atlas.material = material; atlas.name = AtlasName; for (int i = 0; i < sPritesNames.Length; i++) { var spriteInfo = new UITextureAtlas.SpriteInfo() { name = sPritesNames[i], texture = atlasTex, region = rects[i] }; atlas.AddSprite(spriteInfo); } return atlas; }
public static void makeAtlas(Texture2D[] textures) { if (textures != null && textures.Length > 1) { // Make our atlas gameobject with a blank atlas script on it. GameObject go = new GameObject("TEST_ATLAS"); go.AddComponent<Atlas>(); // The blank texture is replaced with the packed texture. Texture2D tex = new Texture2D(2, 2); // Now pack the textures Rect[] UVs = tex.PackTextures(textures, 2, 4096); // Create out spriteAnimation components onto the atlas with height/width equal to the source. for (int i = 0; i < UVs.Length; i++) { SpriteAnimation anim = go.AddComponent<SpriteAnimation>(); anim.setData(textures[i].name, UVs[i]); } FileStream fs = new FileStream(Application.dataPath + "/Resources/Sprites/Atlas_Sprite.png", FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(tex.EncodeToPNG()); bw.Close(); fs.Close(); //PrefabUtility.CreatePrefab(Application.dataPath + "/Resources/Atlases/" + go.name + ".prefab", go); } else { Debug.LogWarning("Given Textures are null or singular."); } }
public void GeneratePackage() { GameObject pPackage = new GameObject ("obj_" + PackageName); PackageData pData = pPackage.AddComponent<PackageData> (); pData.TextureNames = new string[Textures.Length]; for (int i = 0; i < Textures.Length; i++) { string pTexpath = AssetDatabase.GetAssetPath(Textures[i]); ConfigureForPacker(pTexpath); pData.TextureNames[i] = pTexpath; } //total Texture Texture2D pTex = new Texture2D (1, 1, TextureFormat.ARGB32, false); pData.TextureUVs = pTex.PackTextures (Textures,padding,4096); string pTexAssetPath = AssetDatabase.GenerateUniqueAssetPath("Assets/" + PackageName + ".png"); byte[] bytes = pTex.EncodeToPNG (); System.IO.File.WriteAllBytes (pTexAssetPath,bytes); bytes = null; UnityEngine.Object.DestroyImmediate (pTex); AssetDatabase.ImportAsset (pTexAssetPath); pData.TotalTexture = AssetDatabase.LoadAssetAtPath (pTexAssetPath, typeof(Texture2D)) as Texture2D; ConfigureForPacker (AssetDatabase.GetAssetPath (pData.TotalTexture)); pTexAssetPath = AssetDatabase.GenerateUniqueAssetPath("Assets/data_" + PackageName + ".prefab"); Object prefab = PrefabUtility.CreateEmptyPrefab (pTexAssetPath); PrefabUtility.ReplacePrefab (pPackage, prefab, ReplacePrefabOptions.ConnectToPrefab); AssetDatabase.SaveAssets (); AssetDatabase.Refresh (); DestroyImmediate (pPackage); }
/// <summary> /// Create a UIAtlas on runtime from a list of Texture2Ds /// </summary> public static UIAtlas CreateAtlas(string atlasName, GameObject parent, List<Texture2D> textures, List<string> names) { Logger.Debug(TAG, "Generating UIAtlas: {0}", atlasName); // Pack textures int maxSize = SystemInfo.maxTextureSize; Texture2D atlasTexture = new Texture2D(maxSize, maxSize); Rect[] rects = atlasTexture.PackTextures(textures.ToArray(), 0, maxSize); // Create new empty GameObject with UIAtlas component UIAtlas atlas = NGUITools.AddChild<UIAtlas>(parent); atlas.name = atlasName; // Set material atlas.coordinates = UIAtlas.Coordinates.TexCoords; atlas.spriteMaterial = new Material(Shader.Find("Unlit/Transparent Colored")); atlas.spriteMaterial.mainTexture = atlasTexture; // Add sprites for (int i = 0; i < rects.Length; i++) { UIAtlas.Sprite sprite = new UIAtlas.Sprite(); sprite.inner = rects[i]; sprite.outer = rects[i]; sprite.name = names[i]; atlas.spriteList.Add(sprite); } // Return reference to the UIAtlas script return atlas; }
/// <summary> /// Builds the texture atlas. /// </summary> public static void BuildTextureAtlas() { // Build texture array Texture2D[] atlasTextures = new Texture2D[textures.Count]; foreach (KeyValuePair<int, Texture2D> texture in textures) { atlasTextures[texture.Key] = texture.Value; } // Build atlas Texture2D _textureAtlas = new Texture2D (4096, 4096, TextureFormat.RGBA32, false); Rect[] uvRects = _textureAtlas.PackTextures (atlasTextures, 0); textureAtlas = new Texture2D(_textureAtlas.width, _textureAtlas.height, TextureFormat.RGBA32, false); textureAtlas.SetPixels (0,0,_textureAtlas.width, _textureAtlas.height, _textureAtlas.GetPixels (0,0,_textureAtlas.width, _textureAtlas.height)); // Set texture atlas properties textureAtlas.anisoLevel = 9; textureAtlas.filterMode = FilterMode.Point; textureAtlas.Apply (); // Save uvs textureCoordinates = new Dictionary<int, Vector2[]> (); foreach (KeyValuePair<int, Texture2D> texture in textures) { textureCoordinates.Add (texture.Key,new Vector2[] { new Vector2(uvRects[texture.Key].x, uvRects[texture.Key].y), new Vector2(uvRects[texture.Key].x+uvRects[texture.Key].width, uvRects[texture.Key].y), new Vector2(uvRects[texture.Key].x+uvRects[texture.Key].width, uvRects[texture.Key].y+uvRects[texture.Key].height), new Vector2(uvRects[texture.Key].x, uvRects[texture.Key].y+uvRects[texture.Key].height) }); } }
void OnGUI() { GUILayout.Label("HairyPlotter Atlas Creator", EditorStyles.boldLabel); if (textures == null) textures = new Texture2D[0]; assetName = EditorGUILayout.TextField("Asset Name", assetName); textureSize = EditorGUILayout.IntField("Max Size", textureSize); padding = EditorGUILayout.IntField("Padding", padding); System.Array.Resize(ref textures, EditorGUILayout.IntField("Textures", textures.Length)); for (int i = 0; i < textures.Length; ++i) { textures[i] = (Texture2D)EditorGUILayout.ObjectField(textures[i], typeof(Texture2D), false); } if (assetName != "" && textures.Where(x => x != null).Count() > 0) { if (GUILayout.Button("Create Atlas", EditorStyles.miniButton)) { Texture2D atlas = new Texture2D(textureSize, textureSize, TextureFormat.ARGB32, true); atlas.PackTextures(textures.Where(x => x != null).ToArray(), padding, textureSize); char dirSep = System.IO.Path.DirectorySeparatorChar; string fileName = "Assets" + dirSep + assetName + ".png"; System.IO.File.WriteAllBytes(fileName, atlas.EncodeToPNG()); AssetDatabase.ImportAsset(fileName); } } }
public static UITextureAtlas CreateTextureAtlas(string atlasName, string[] spriteNames, string assemblyPath) { int maxSize = 1024; Texture2D texture2D = new Texture2D(maxSize, maxSize, TextureFormat.ARGB32, false); Texture2D[] textures = new Texture2D[spriteNames.Length]; Rect[] regions = new Rect[spriteNames.Length]; for (int i = 0; i < spriteNames.Length; i++) textures[i] = TextureLoader.LoadTextureFromAssembly(assemblyPath + spriteNames[i] + ".png"); regions = texture2D.PackTextures(textures, 2, maxSize); UITextureAtlas textureAtlas = ScriptableObject.CreateInstance<UITextureAtlas>(); Material material = UnityEngine.Object.Instantiate<Material>(UIView.GetAView().defaultAtlas.material); material.mainTexture = texture2D; textureAtlas.material = material; textureAtlas.name = atlasName; for (int i = 0; i < spriteNames.Length; i++) { UITextureAtlas.SpriteInfo item = new UITextureAtlas.SpriteInfo { name = spriteNames[i], texture = textures[i], region = regions[i], }; textureAtlas.AddSprite(item); } return textureAtlas; }
private void initializeAtlas() { Texture2D[] cubeTextures = new Texture2D[9]; /* cubeTextures[1] = Resources.Load("Textures/hiDefGrass") as Texture2D; cubeTextures[2] = Resources.Load("Textures/sidegrass") as Texture2D; cubeTextures[3] = Resources.Load("Textures/hiDefDirt") as Texture2D; cubeTextures[4] = Resources.Load("Textures/hiDefDirt") as Texture2D; cubeTextures[5] = Resources.Load("Textures/hiDefDirt") as Texture2D; cubeTextures[6] = Resources.Load("Textures/hiDefStone") as Texture2D; cubeTextures[7] = Resources.Load("Textures/hiDefStone") as Texture2D; cubeTextures[8] = Resources.Load("Textures/hiDefStone") as Texture2D; */ cubeTextures[1] = Resources.Load("Textures/dokuGrass") as Texture2D; cubeTextures[2] = Resources.Load("Textures/dokuGrassSide") as Texture2D; cubeTextures[3] = Resources.Load("Textures/dokuDirt") as Texture2D; cubeTextures[4] = Resources.Load("Textures/dokuDirt") as Texture2D; cubeTextures[5] = Resources.Load("Textures/dokuDirt") as Texture2D; cubeTextures[6] = Resources.Load("Textures/dokuStone") as Texture2D; cubeTextures[7] = Resources.Load("Textures/dokuStone") as Texture2D; cubeTextures[8] = Resources.Load("Textures/dokuStone") as Texture2D; textureAtlas = new Texture2D(4096, 4096); atlasUVs = textureAtlas.PackTextures(cubeTextures, 0); textureAtlas.Apply(); }
public TextureIndex() { List<Texture2D> atlasTextures = new List<Texture2D>(); // Load all files in Textures folder atlasTextures.AddRange(Resources.LoadAll<Texture2D>(Config.Directories.TextureFolder)); //Load and generate all the connected textures List<Texture2D> connectedTextures = new List<Texture2D>(); connectedTextures.AddRange(Resources.LoadAll<Texture2D>(Config.Directories.ConnectedTextureFolder)); if (connectedTextures.Count!=0) atlasTextures.AddRange(ConnectedTextures.GenerateConnectedTextures(connectedTextures)); // Create new atlas atlas = new Texture2D(8192, 8192); atlas.filterMode = FilterMode.Point; // Generate atlas Rect[] rects = atlas.PackTextures(atlasTextures.ToArray(), 0, 8192, false); // Add each atlas entry into texture dictionary for (int i = 0; i < atlasTextures.Count; i++) { if (!atlasTextures[i]) continue; string[] fileName = atlasTextures[i].name.ToString().Split('-'); Rect texture = rects[i]; string textureName = fileName[0]; int connectedTextureType = -1; //Get the properties associated with this texture for (int n = 1; n < fileName.Length; n++) { switch (fileName[n][0]) { case 'c': int.TryParse(fileName[n].Substring(1), out connectedTextureType); break; default: break; } } //Create a texture collection with this name if it doesn't exist already TextureCollection collection; if (!textures.TryGetValue(textureName, out collection)) { collection = new TextureCollection(textureName); textures.Add(textureName, collection); } collection.AddTexture(texture, connectedTextureType); } }
private static void CreateSpriteSheetAtlasSliced() { List<Texture2D> textures = new List<Texture2D> (); Object[] selectedObjects = Selection.objects; foreach (Object obj in selectedObjects) { if(obj is Texture2D){ TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(obj)); if (importer != null) { importer.textureType= TextureImporterType.Advanced; importer.npotScale= TextureImporterNPOTScale.None; importer.mipmapEnabled=false; importer.isReadable=true; AssetDatabase.ImportAsset (AssetDatabase.GetAssetPath(obj)); AssetDatabase.Refresh(); } textures.Add(obj as Texture2D); } } textures.Sort ((x, y) => string.Compare(x.name, y.name)); string path=AssetDatabase.GetAssetPath(textures[0]); path=path.Remove(path.LastIndexOf('/')); Texture2D atlas = new Texture2D(4096, 4096, TextureFormat.ARGB32, false); Color[] colors=new Color[4096*4096]; for(int i=0; i< colors.Length;i++){ colors[i]=Color.clear; } atlas.SetPixels(colors); atlas.Apply(); Rect[] rects=atlas.PackTextures(textures.ToArray(), 0,false); byte[] bytes = atlas.EncodeToPNG(); System.IO.File.WriteAllBytes(path+ "/spritesheet.png", bytes); AssetDatabase.Refresh(); TextureImporter tempImporter = (TextureImporter)AssetImporter.GetAtPath(path+"/spritesheet.png"); if (tempImporter != null) { tempImporter.textureType = TextureImporterType.Sprite; tempImporter.spriteImportMode=SpriteImportMode.Multiple; tempImporter.maxTextureSize=4096; int count=textures.Count; SpriteMetaData[] meta= new SpriteMetaData[count]; for(int i=0; i< count;i++){ meta[i].name=i.ToString(); meta[i].alignment = (int)SpriteAlignment.Center; meta[i].pivot=Vector2.zero; meta[i].rect = rects[i]; } tempImporter.spritesheet=meta; AssetDatabase.ImportAsset (path+"/spritesheet.png"); AssetDatabase.Refresh(); } }
static public int PackTextures(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if (argc == 3) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Texture2D[] a1; checkArray(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); var ret = self.PackTextures(a1, a2); pushValue(l, true); pushValue(l, ret); return(2); } else if (argc == 4) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Texture2D[] a1; checkArray(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); var ret = self.PackTextures(a1, a2, a3); pushValue(l, true); pushValue(l, ret); return(2); } else if (argc == 5) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Texture2D[] a1; checkArray(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); System.Boolean a4; checkType(l, 5, out a4); var ret = self.PackTextures(a1, a2, a3, a4); pushValue(l, true); pushValue(l, ret); return(2); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); return(2); } catch (Exception e) { return(error(l, e)); } }
/// <summary> /// Creates a single texture atlas from the provided source textures. /// </summary> /// <param name="textures">Textures to combine into one</param> /// <param name="textureSize">Size of the texture atlas to create</param> /// <param name="rectAreas">Rect locations of each texture</param> /// <returns>The created atlased texture</returns> /// <example> /// This will atlas the two textures, TextureA and TextureB, into one efficient texture map. /// <code> /// using System; /// using UnityEngine; /// using CivGrid; /// /// class TextureTest : MonoBehaviour /// { /// Texture2D[] texturesToCombine; /// public Texture2D texture1; /// public Texture2D texture2; /// /// Texture2D atlasedTexture; /// Rect[] rectLocations; /// /// void Start() /// { /// texturesToCombine = new Texture2D[2]; /// texturesToCombine[0] = texture1; /// texturesToCombine[1] = texture2; /// /// atlasedTexture = TexturePacker.AtlasTextures(texturesToCombine, 2048, out rectLocations); /// } /// } /// </code> /// </example> public static Texture2D AtlasTextures(Texture2D[] textures, int textureSize, out Rect[] rectAreas) { //creates return texture atlas Texture2D packedTexture = new Texture2D(textureSize, textureSize); //packs all source textures into one rectAreas = packedTexture.PackTextures(textures, 0, textureSize); packedTexture.Apply(); //returns texture atlas return packedTexture; }
void Awake() { Material newMaterial = new Material(Shader.Find("Sprites/ClipArea")); Texture2D[] textures = new Texture2D[textNames.Length]; int width = 0; int height = 0; float deep = 0.01f; for(int i = 0; i < textNames.Length; ++i) { textures[i] = Resources.Load<Texture2D>(textNames[i]); width += textures[i].width; height += textures[i].height; } packedTexture = new Texture2D(1024,1024); Rect[] uvs = packedTexture.PackTextures(textures,0,1024); for(int i = 0; i < uvs.Length; ++i) { GameObject gameObject = new GameObject(); gameObject.name = "item_" + i; gameObject.transform.position = new Vector3(-300 + 150 * i ,0); Mesh mesh = CreateMesh(45, 45); MeshRenderer renderer = gameObject.AddComponent<MeshRenderer>(); MeshFilter meshFilter = gameObject.AddComponent<MeshFilter>(); mesh.uv = RectToUV(uvs[i]); meshFilter.mesh = mesh; newMaterial.mainTexture = packedTexture; renderer.material = newMaterial; } //renderer.material = newMaterial; /* packedTexture = new Texture2D(1024,1024); Rect[] uvs = packedTexture.PackTextures(textures,0,1024); newMaterial.mainTexture = packedTexture; Vector2[] uva,uvb; for (int j=0;j < filters.Length;j++) { filters[j].gameObject.renderer.material=newMaterial; uva = (Vector2[])(((MeshFilter)filters[j]).mesh.uv); uvb = new Vector2[uva.Length]; for (int k=0;k < uva.Length;k++){ uvb[k]=new Vector2((uva[k].x*uvs[j].width)+uvs[j].x, (uva[k].y*uvs[j].height)+uvs[j].y); } ((MeshFilter)filters[j]).mesh.uv=uvb; } */ // Test(); }
static void BuildAtlas( Texture2D[] textures ) { Debug.Log( textures.Length ); Texture2D output = new Texture2D( 1024, 1024 ); output.PackTextures( textures, 0, 1024 ); using ( var fs = new FileStream( "Assets/texMap.png", FileMode.Create ) ) { byte[] pngBytes = output.EncodeToPNG(); fs.Write( pngBytes, 0, pngBytes.Length ); fs.Close(); } }
static public int PackTextures(IntPtr l) { try{ if (matchType(l, 2, typeof(UnityEngine.Texture2D[]), typeof(int), typeof(int), typeof(bool))) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Texture2D[] a1; checkType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); System.Boolean a4; checkType(l, 5, out a4); UnityEngine.Rect[] ret = self.PackTextures(a1, a2, a3, a4); pushValue(l, ret); return(1); } else if (matchType(l, 2, typeof(UnityEngine.Texture2D[]), typeof(int), typeof(int))) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Texture2D[] a1; checkType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); UnityEngine.Rect[] ret = self.PackTextures(a1, a2, a3); pushValue(l, ret); return(1); } else if (matchType(l, 2, typeof(UnityEngine.Texture2D[]), typeof(int))) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Texture2D[] a1; checkType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); UnityEngine.Rect[] ret = self.PackTextures(a1, a2); pushValue(l, ret); return(1); } LuaDLL.luaL_error(l, "No matched override function to call"); return(0); } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return(0); } }
static int PackTextures(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(UnityEngine.Texture2D[]), typeof(int))) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1); UnityEngine.Texture2D[] arg0 = ToLua.CheckObjectArray <UnityEngine.Texture2D>(L, 2); int arg1 = (int)LuaDLL.lua_tonumber(L, 3); UnityEngine.Rect[] o = obj.PackTextures(arg0, arg1); ToLua.Push(L, o); return(1); } else if (count == 4 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(UnityEngine.Texture2D[]), typeof(int), typeof(int))) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1); UnityEngine.Texture2D[] arg0 = ToLua.CheckObjectArray <UnityEngine.Texture2D>(L, 2); int arg1 = (int)LuaDLL.lua_tonumber(L, 3); int arg2 = (int)LuaDLL.lua_tonumber(L, 4); UnityEngine.Rect[] o = obj.PackTextures(arg0, arg1, arg2); ToLua.Push(L, o); return(1); } else if (count == 5 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(UnityEngine.Texture2D[]), typeof(int), typeof(int), typeof(bool))) { UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1); UnityEngine.Texture2D[] arg0 = ToLua.CheckObjectArray <UnityEngine.Texture2D>(L, 2); int arg1 = (int)LuaDLL.lua_tonumber(L, 3); int arg2 = (int)LuaDLL.lua_tonumber(L, 4); bool arg3 = LuaDLL.lua_toboolean(L, 5); UnityEngine.Rect[] o = obj.PackTextures(arg0, arg1, arg2, arg3); ToLua.Push(L, o); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Texture2D.PackTextures")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int QPYX_PackTextures_YXQP(IntPtr L_YXQP) { try { int QPYX_count_YXQP = LuaDLL.lua_gettop(L_YXQP); if (QPYX_count_YXQP == 3) { UnityEngine.Texture2D QPYX_obj_YXQP = (UnityEngine.Texture2D)ToLua.CheckObject(L_YXQP, 1, typeof(UnityEngine.Texture2D)); UnityEngine.Texture2D[] QPYX_arg0_YXQP = ToLua.CheckObjectArray <UnityEngine.Texture2D>(L_YXQP, 2); int QPYX_arg1_YXQP = (int)LuaDLL.luaL_checknumber(L_YXQP, 3); UnityEngine.Rect[] QPYX_o_YXQP = QPYX_obj_YXQP.PackTextures(QPYX_arg0_YXQP, QPYX_arg1_YXQP); ToLua.Push(L_YXQP, QPYX_o_YXQP); return(1); } else if (QPYX_count_YXQP == 4) { UnityEngine.Texture2D QPYX_obj_YXQP = (UnityEngine.Texture2D)ToLua.CheckObject(L_YXQP, 1, typeof(UnityEngine.Texture2D)); UnityEngine.Texture2D[] QPYX_arg0_YXQP = ToLua.CheckObjectArray <UnityEngine.Texture2D>(L_YXQP, 2); int QPYX_arg1_YXQP = (int)LuaDLL.luaL_checknumber(L_YXQP, 3); int QPYX_arg2_YXQP = (int)LuaDLL.luaL_checknumber(L_YXQP, 4); UnityEngine.Rect[] QPYX_o_YXQP = QPYX_obj_YXQP.PackTextures(QPYX_arg0_YXQP, QPYX_arg1_YXQP, QPYX_arg2_YXQP); ToLua.Push(L_YXQP, QPYX_o_YXQP); return(1); } else if (QPYX_count_YXQP == 5) { UnityEngine.Texture2D QPYX_obj_YXQP = (UnityEngine.Texture2D)ToLua.CheckObject(L_YXQP, 1, typeof(UnityEngine.Texture2D)); UnityEngine.Texture2D[] QPYX_arg0_YXQP = ToLua.CheckObjectArray <UnityEngine.Texture2D>(L_YXQP, 2); int QPYX_arg1_YXQP = (int)LuaDLL.luaL_checknumber(L_YXQP, 3); int QPYX_arg2_YXQP = (int)LuaDLL.luaL_checknumber(L_YXQP, 4); bool QPYX_arg3_YXQP = LuaDLL.luaL_checkboolean(L_YXQP, 5); UnityEngine.Rect[] QPYX_o_YXQP = QPYX_obj_YXQP.PackTextures(QPYX_arg0_YXQP, QPYX_arg1_YXQP, QPYX_arg2_YXQP, QPYX_arg3_YXQP); ToLua.Push(L_YXQP, QPYX_o_YXQP); return(1); } else { return(LuaDLL.luaL_throw(L_YXQP, "invalid arguments to method: UnityEngine.Texture2D.PackTextures")); } } catch (Exception e_YXQP) { return(LuaDLL.toluaL_exception(L_YXQP, e_YXQP)); } }
public static int PackTextures2_wrap(long L) { try { long nThisPtr = FCLibHelper.fc_get_inport_obj_ptr(L); UnityEngine.Texture2D obj = get_obj(nThisPtr); UnityEngine.Texture2D[] arg0 = null; arg0 = FCCustomParam.GetArray(ref arg0, L, 0); int arg1 = FCLibHelper.fc_get_int(L, 1); Rect[] ret = obj.PackTextures(arg0, arg1); long ret_ptr = FCLibHelper.fc_get_return_ptr(L); FCCustomParam.ReturnArray(ret, ret_ptr); } catch (Exception e) { Debug.LogException(e); } return(0); }
private static void BakeEmojiAtlas() { string pathToEmojis = Application.dataPath + "/Textures/Emojis"; string pathToEmojiInfo = Application.dataPath + "/EmojiInfo/info.txt"; string pathToBakedAtlas = Application.dataPath + "/Textures/Baked/BakedEmojis.png"; string[] emojiFileNames = Directory.GetFiles(pathToEmojis, "*.png"); // Load each PNG file as separate Texture2D Texture2D[] emojiTextures = new Texture2D[emojiFileNames.Length]; for (int i = 0; i < emojiFileNames.Length; i++) { // Create a texture. Texture size does not matter, since // LoadImage will replace with with incoming image size. Texture2D tex = new Texture2D(2, 2); if (!tex.LoadImage(File.ReadAllBytes(emojiFileNames[i]))) { Debug.LogError("Cannot load file " + emojiFileNames[i] + " via tex.LoadImage!!!"); return; } emojiTextures[i] = tex; } // Create atlas Texture2D atlas = new Texture2D(2048, 2048); Rect[] rects = atlas.PackTextures(emojiTextures, 1, 2048); // Save atlas byte[] atlasBytes = atlas.EncodeToPNG(); File.WriteAllBytes(pathToBakedAtlas, atlasBytes); // Save EmojiInfo StringBuilder sb = new StringBuilder(); for (int i = 0; i < emojiFileNames.Length; i++) { sb.AppendLine(Path.GetFileNameWithoutExtension(emojiFileNames[i]) + " " + rects[i].x + " " + rects[i].y + " " + rects[i].width + " " + rects[i].height ); } File.WriteAllText(pathToEmojiInfo, sb.ToString()); Debug.Log("Baked " + emojiFileNames.Length + " emojis into " + pathToBakedAtlas); }
void GenerateAtlas() { foreach (Texture2D t in textures) ConfigureForAtlas(AssetDatabase.GetAssetPath(t)); Texture2D texture = new Texture2D(1, 1, TextureFormat.ARGB32, false); Rect[] uvs = texture.PackTextures(textures, padding, 4096); string assetPath = AssetDatabase.GenerateUniqueAssetPath("Assets/" + AtlasName + ".png"); byte[] bytes = texture.EncodeToPNG(); System.IO.File.WriteAllBytes(assetPath, bytes); bytes = null; UnityEngine.Object.DestroyImmediate(texture); AssetDatabase.ImportAsset(assetPath); texture = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)) as Texture2D; ConfigureSpriteAtlas(texture, uvs); }
// ---------------------------------------------------------------------------------- public static NcSpriteFactory.NcFrameInfo[] TileToTrimTexture(Material tarMat, int nTileX, int nTileY, int nStartFrame, int nFrameCount, int nMaxAtlasTextureSize) { if (tarMat == null) return null; // split texture Texture2D tileTexture = CloneAtlasTexture(tarMat.mainTexture); List<Texture2D> frameTextures = new List<Texture2D>(); List<Rect> frameRects = new List<Rect>(); bool bFindAlpha; bool bFindBlack; NcSpriteFactory.NcFrameInfo[] frameInfos = NgAtlas.TrimTexture(tileTexture, true, true, nTileX, nTileY, nStartFrame, nFrameCount, ref frameTextures, ref frameRects, out bFindAlpha, out bFindBlack); // free tempTexture Object.DestroyImmediate(tileTexture); // packTextures Color clearColor = new Color(0, 0, 0, (bFindAlpha ? 0 : 1)); Texture2D AtlasTexture = new Texture2D(32, 32, TextureFormat.ARGB32, false); Rect[] uvRects = AtlasTexture.PackTextures(frameTextures.ToArray(), 2, nMaxAtlasTextureSize); // clear for (int x = 0; x < AtlasTexture.width; x++) for (int y = 0; y < AtlasTexture.height; y++) AtlasTexture.SetPixel(x, y, clearColor); // copy for (int n = 0; n < frameInfos.Length; n++) { int nFrameIndex = frameInfos[n].m_nFrameIndex; Rect imageUvRect = frameInfos[n].m_TextureUvOffset = uvRects[frameInfos[n].m_nFrameIndex]; AtlasTexture.SetPixels((int)(imageUvRect.x*AtlasTexture.width), (int)(imageUvRect.y*AtlasTexture.height), (int)(imageUvRect.width*AtlasTexture.width), (int)(imageUvRect.height*AtlasTexture.height), frameTextures[nFrameIndex].GetPixels()); Object.DestroyImmediate(frameTextures[n]); } SaveAtlasTexture(AtlasTexture, tarMat); Object.DestroyImmediate(AtlasTexture); return frameInfos; }
public static UITextureAtlas CreateAtlas(Texture2D[] sprites) { UITextureAtlas atlas = new UITextureAtlas(); atlas.material = new Material(GetUIAtlasShader()); Texture2D texture = new Texture2D(0, 0); Rect[] rects = texture.PackTextures(sprites, 0); for (int i = 0; i < rects.Length; ++i) { Texture2D sprite = sprites[i]; Rect rect = rects[i]; UITextureAtlas.SpriteInfo spriteInfo = new UITextureAtlas.SpriteInfo(); spriteInfo.name = sprite.name; spriteInfo.texture = sprite; spriteInfo.region = rect; spriteInfo.border = new RectOffset(); atlas.AddSprite(spriteInfo); } atlas.material.mainTexture = texture; return atlas; }
// Builds an atlas from the specified texture list void BuildAtlas(AtlasTextureList texList) { Texture2D atlas; atlas = new Texture2D(4, 4); atlas.name = texList.material.name; //============================================= // The following is currently disabled as it // does not seem to work around the Unity bug: //============================================= // To get around the Unity bug where the max texture size is // limited to 1024x1024 when in iPhone mode for newly-created // textures, save this texture to disk as an asset and then // re-import it with modified import settings to set the max // texture size to what we want: byte[] bytes;// = atlas.EncodeToPNG(); string atlasPath = assetPath + "/" + atlas.name + ".png"; // string projectRelativePath = "Assets/" + atlasFolder + "/" + atlas.name + ".png"; // // // Write out the atlas file: // using (FileStream fs = File.Create(atlasPath)) // { // fs.Write(bytes, 0, bytes.Length); // } // // // Make sure the max texture size is set to what we want: // // Get the texture's importer: // TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(projectRelativePath); // if (importer.maxTextureSize < maxAtlasSize || importer.isReadable) // { // // Re-import it with the desired max texture size: // importer.maxTextureSize = maxAtlasSize; // importer.isReadable = true; // AssetDatabase.ImportAsset(projectRelativePath, ImportAssetOptions.ForceSynchronousImport); // } // // // Now re-open the texture asset: // atlas = (Texture2D) AssetDatabase.LoadAssetAtPath(projectRelativePath, typeof(Texture2D)); // Pack the textures to the atlas: texList.uvs = atlas.PackTextures(texList.trimmedTextures.ToArray(), padding, maxAtlasSize); // Check to see if the texture had to be resized to fit: if (texList.uvs[0].width * atlas.width != (texList.trimmedTextures[0]).width || texList.uvs[0].height * atlas.height != (texList.trimmedTextures[0]).height) { EditorUtility.DisplayDialog("WARNING: Textures resized!", "WARNING: Not all textures were able to fit on atlas \"" + atlas.name + "\" at their original sizes. These textures were scaled down to fit. To resolve this, assign some of your sprites to use a different material, or if possible, use a larger maximum texture size.", "Ok"); Debug.LogWarning("WARNING: Textures were resized to fit onto atlas \"" + atlas.name + "\"! To resolve this, assign some of your sprites a different material, or if possible, use a larger maximum texture size."); } // Free our trimmed texture memory: for (int i = 0; i < texList.trimmedTextures.Count; ++i) { // If this isn't stored as an asset, destroy it: if (AssetDatabase.GetAssetPath(texList.trimmedTextures[i]).Length < 1) DestroyImmediate(texList.trimmedTextures[i]); texList.trimmedTextures[i] = null; } texList.trimmedTextures.Clear(); #if !UNITY_IPHONE || (UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9) Resources.UnloadUnusedAssets(); #endif // See if the texture needs to be made square: if (forceSquare && atlas.width != atlas.height) { int size = Mathf.Max(atlas.width, atlas.height); // Create a square texture: Texture2D tempTex = (Texture2D)Instantiate(atlas); tempTex.name = atlas.name; tempTex.Resize(size, size, TextureFormat.ARGB32, false); // Copy the contents: tempTex.SetPixels(0, 0, atlas.width, atlas.height, atlas.GetPixels(0), 0); tempTex.Apply(false); // Scale the UVs to account for this: for (int j = 0; j < texList.uvs.Length; ++j) { // See which side we expanded: if (atlas.width > atlas.height) { texList.uvs[j].y = texList.uvs[j].y * 0.5f; texList.uvs[j].yMax = texList.uvs[j].y + (texList.uvs[j].height * 0.5f); } else { texList.uvs[j].x = texList.uvs[j].x * 0.5f; texList.uvs[j].xMax = texList.uvs[j].x + (texList.uvs[j].width * 0.5f); } } if (atlas != tempTex) DestroyImmediate(atlas); atlas = tempTex; } // See if we need to trim the atlas to fit its content: if (!forceSquare) { Texture2D tempTex = TrimAtlas(atlas); // Scale the UVs to account for this: float widthFactor = ((float)atlas.width) / ((float)tempTex.width); float heightFactor = ((float)atlas.height) / ((float)tempTex.height); for (int j = 0; j < texList.uvs.Length; ++j) { texList.uvs[j].x *= widthFactor; texList.uvs[j].y *= heightFactor; texList.uvs[j].width *= widthFactor; texList.uvs[j].height *= heightFactor; } if (atlas != tempTex) DestroyImmediate(atlas); atlas = tempTex; } // Save the atlas as an asset: bytes = atlas.EncodeToPNG(); // Write out the atlas file: using (FileStream fs = File.Create(atlasPath)) { fs.Write(bytes, 0, bytes.Length); } // Flag this memory to be freed: bytes = null; // Save the atlas path: texList.texPath = "Assets/" + atlasFolder + "/" + atlas.name + ".png"; Debug.Log("Finished building atlas \"" + texList.material.name + "\"..."); }
static public int PackTextures(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if (argc == 3) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Texture2D[] a1; checkArray(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); var ret = self.PackTextures(a1, a2); pushValue(l, true); pushValue(l, ret); return(2); } else if (argc == 4) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Texture2D[] a1; checkArray(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); var ret = self.PackTextures(a1, a2, a3); pushValue(l, true); pushValue(l, ret); return(2); } else if (argc == 5) { UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l); UnityEngine.Texture2D[] a1; checkArray(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); System.Boolean a4; checkType(l, 5, out a4); var ret = self.PackTextures(a1, a2, a3, a4); pushValue(l, true); pushValue(l, ret); return(2); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function PackTextures to call"); return(2); } catch (Exception e) { return(error(l, e)); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif }
/// <summary> /// Pack all of the specified sprites into a single texture, updating the outer and inner rects of the sprites as needed. /// </summary> static void PackTextures (Texture2D tex, List<SpriteEntry> sprites) { Texture2D[] textures = new Texture2D[sprites.Count]; Rect[] rects; if (NGUISettings.unityPacking) { for (int i = 0; i < sprites.Count; ++i) textures[i] = sprites[i].tex; rects = tex.PackTextures(textures, NGUISettings.atlasPadding, 4096); } else { sprites.Sort(Compare); for (int i = 0; i < sprites.Count; ++i) textures[i] = sprites[i].tex; rects = UITexturePacker.PackTextures(tex, textures, 4, 4, NGUISettings.atlasPadding, 4096); } for (int i = 0; i < sprites.Count; ++i) { sprites[i].rect = NGUIMath.ConvertToPixels(rects[i], tex.width, tex.height, true); //BleedTexture(tex, sprites[i].rect); } }
public bool PackTextures(int index) { #if !UNITY_WEBPLAYER int decalCount = decalGroups[index].decals.Count; Texture2D[] imgs = new Texture2D[decalCount]; for(int i = 0; i < decalCount; i++) { imgs[i] = decalGroups[index].decals[i].texture; string path = AssetDatabase.GetAssetPath(imgs[i]); TextureImporter textureImporter = (TextureImporter)TextureImporter.GetAtPath( path ); textureImporter.isReadable = true; textureImporter.textureFormat = TextureImporterFormat.ARGB32; AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); } int maxAtlasSize = 8192; Texture2D packedTexture = new Texture2D(maxAtlasSize, maxAtlasSize, TextureFormat.ARGB32, true); packedTexture.name = decalGroups[index].name; Rect[] coordinates = packedTexture.PackTextures(imgs, decalGroups[index].padding, maxAtlasSize, false); if(coordinates == null) return false; for(int i = 0; i < decalCount; i++) { decalGroups[index].decals[i].atlasRect = coordinates[i]; decalGroups[index].decals[i].isPacked = true; } decalGroups[index].isPacked = true; byte[] png = packedTexture.EncodeToPNG(); if(!Directory.Exists(DECALSHEETS_PATH)) Directory.CreateDirectory(DECALSHEETS_PATH); if(decalGroups[index].material == null) { string matPath = AssetDatabase.GenerateUniqueAssetPath(DECALSHEETS_PATH + decalGroups[index].name + ".mat"); Material mat = new Material( decalGroups[index].shader ); AssetDatabase.CreateAsset(mat, matPath); decalGroups[index].material = mat; } else { if(decalGroups[index].material.name != decalGroups[index].name) { string matPath = AssetDatabase.GetAssetPath(decalGroups[index].material); AssetDatabase.RenameAsset(matPath, decalGroups[index].name); } } string pngPath; if(decalGroups[index].material != null && decalGroups[index].material.mainTexture != null) pngPath = AssetDatabase.GetAssetPath(decalGroups[index].material.mainTexture); else pngPath = AssetDatabase.GenerateUniqueAssetPath(DECALSHEETS_PATH + decalGroups[index].name + ".png"); // http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension%28v=vs.110%29.aspx File.WriteAllBytes(pngPath, png); string curName = Path.GetFileNameWithoutExtension(pngPath); if(curName != decalGroups[index].name) AssetDatabase.RenameAsset(pngPath, decalGroups[index].name); AssetDatabase.Refresh(); decalGroups[index].material.mainTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(pngPath, typeof(Texture2D)); return true; #else return false; #endif }
/// <summary> /// Pack all of the specified sprites into a single texture, updating the outer and inner rects of the sprites as needed. /// </summary> static bool PackTextures (Texture2D tex, List<SpriteEntry> sprites) { Texture2D[] textures = new Texture2D[sprites.Count]; Rect[] rects; #if UNITY_3_5 || UNITY_4_0 int maxSize = 4096; #else int maxSize = SystemInfo.maxTextureSize; #endif #if UNITY_ANDROID || UNITY_IPHONE maxSize = Mathf.Min(maxSize, NGUISettings.allow4096 ? 4096 : 2048); #endif if (NGUISettings.unityPacking) { for (int i = 0; i < sprites.Count; ++i) textures[i] = sprites[i].tex; rects = tex.PackTextures(textures, NGUISettings.atlasPadding, maxSize); } else { sprites.Sort(Compare); for (int i = 0; i < sprites.Count; ++i) textures[i] = sprites[i].tex; rects = UITexturePacker.PackTextures(tex, textures, 4, 4, NGUISettings.atlasPadding, maxSize); } for (int i = 0; i < sprites.Count; ++i) { Rect rect = NGUIMath.ConvertToPixels(rects[i], tex.width, tex.height, true); // Make sure that we don't shrink the textures if (Mathf.RoundToInt(rect.width) != textures[i].width) return false; SpriteEntry se = sprites[i]; se.x = Mathf.RoundToInt(rect.x); se.y = Mathf.RoundToInt(rect.y); se.width = Mathf.RoundToInt(rect.width); se.height = Mathf.RoundToInt(rect.height); } return true; }
/// <summary> /// Create a bitmap font from the specified dynamic font. /// </summary> static public bool CreateFont (Font ttf, int size, int faceIndex, bool kerning, string characters, int padding, out BMFont font, out Texture2D tex) { font = null; tex = null; if (ttf == null || !isPresent) return false; IntPtr lib = IntPtr.Zero; IntPtr face = IntPtr.Zero; if (FT_Init_FreeType(out lib) != 0) { Debug.LogError("Failed to initialize FreeType"); return false; } string fileName = Application.dataPath.Substring(0, Application.dataPath.Length - "Assets".Length) + UnityEditor.AssetDatabase.GetAssetPath(ttf); if (!File.Exists(fileName)) { Debug.LogError("Unable to use the chosen font."); } else if (FT_New_Face(lib, fileName, faceIndex, out face) != 0) { Debug.LogError("Unable to use the chosen font (FT_New_Face)."); } else { font = new BMFont(); font.charSize = size; Color32 white = Color.white; List<int> entries = new List<int>(); List<Texture2D> textures = new List<Texture2D>(); FT_FaceRec faceRec = (FT_FaceRec)Marshal.PtrToStructure(face, typeof(FT_FaceRec)); FT_Set_Pixel_Sizes(face, 0, (uint)size); // Calculate the baseline value that would let the printed font be centered vertically //int ascender = (faceRec.met.ascender >> 6); //int descender = (faceRec.descender >> 6); //int baseline = ((ascender - descender) >> 1); //if ((baseline & 1) == 1) --baseline; //Debug.Log(ascender + " " + descender + " " + baseline); // Space character is not renderable FT_Load_Glyph(face, FT_Get_Char_Index(face, 32), FT_LOAD_DEFAULT); FT_GlyphSlotRec space = (FT_GlyphSlotRec)Marshal.PtrToStructure(faceRec.glyph, typeof(FT_GlyphSlotRec)); // Space is not visible and doesn't have a texture BMGlyph spaceGlyph = font.GetGlyph(32, true); spaceGlyph.offsetX = 0; spaceGlyph.offsetY = 0; spaceGlyph.advance = (space.metrics.horiAdvance >> 6); spaceGlyph.channel = 15; spaceGlyph.x = 0; spaceGlyph.y = 0; spaceGlyph.width = 0; spaceGlyph.height = 0; // Save kerning information if (kerning) { for (int b = 0; b < characters.Length; ++b) { uint ch2 = characters[b]; if (ch2 == 32) continue; FT_Vector vec; if (FT_Get_Kerning(face, ch2, 32, 0, out vec) != 0) continue; int offset = (vec.x >> 6); if (offset != 0) spaceGlyph.SetKerning((int)ch2, offset); } } // Run through all requested characters foreach (char ch in characters) { uint charIndex = FT_Get_Char_Index(face, (uint)ch); FT_Load_Glyph(face, charIndex, FT_LOAD_DEFAULT); FT_GlyphSlotRec glyph = (FT_GlyphSlotRec)Marshal.PtrToStructure(faceRec.glyph, typeof(FT_GlyphSlotRec)); FT_Render_Glyph(ref glyph, FT_Render_Mode.FT_RENDER_MODE_NORMAL); if (glyph.bitmap.width > 0 && glyph.bitmap.rows > 0) { byte[] buffer = new byte[glyph.bitmap.width * glyph.bitmap.rows]; Marshal.Copy(glyph.bitmap.buffer, buffer, 0, buffer.Length); Texture2D texture = new Texture2D(glyph.bitmap.width, glyph.bitmap.rows, UnityEngine.TextureFormat.ARGB32, false); Color32[] colors = new Color32[buffer.Length]; for (int i = 0, y = 0; y < glyph.bitmap.rows; ++y) { for (int x = 0; x < glyph.bitmap.width; ++x) { white.a = buffer[i++]; colors[x + glyph.bitmap.width * (glyph.bitmap.rows - y - 1)] = white; } } // Save the texture texture.SetPixels32(colors); texture.Apply(); textures.Add(texture); entries.Add(ch); // Record the metrics BMGlyph bmg = font.GetGlyph(ch, true); bmg.offsetX = (glyph.metrics.horiBearingX >> 6); bmg.offsetY = -(glyph.metrics.horiBearingY >> 6); bmg.advance = (glyph.metrics.horiAdvance >> 6); bmg.channel = 15; // Save kerning information if (kerning) { for (int b = 0; b < characters.Length; ++b) { uint ch2 = characters[b]; if (ch2 == ch) continue; FT_Vector vec; if (FT_Get_Kerning(face, ch2, ch, 0, out vec) != 0) continue; int offset = (vec.x >> 6); if (offset != 0) bmg.SetKerning((int)ch2, offset); } } } } // Create a packed texture with all the characters tex = new Texture2D(32, 32, TextureFormat.ARGB32, false); Rect[] rects = tex.PackTextures(textures.ToArray(), padding); // Make the RGB channel pure white Color32[] cols = tex.GetPixels32(); for (int i = 0, imax = cols.Length; i < imax; ++i) { Color32 c = cols[i]; c.r = 255; c.g = 255; c.b = 255; cols[i] = c; } tex.SetPixels32(cols); tex.Apply(); font.texWidth = tex.width; font.texHeight = tex.height; int min = int.MaxValue; int max = int.MinValue; // Other glyphs are visible and need to be added for (int i = 0, imax = entries.Count; i < imax; ++i) { // Destroy the texture now that it's a part of an atlas UnityEngine.Object.DestroyImmediate(textures[i]); textures[i] = null; Rect rect = rects[i]; // Set the texture coordinates BMGlyph glyph = font.GetGlyph(entries[i], true); glyph.x = Mathf.RoundToInt(rect.x * font.texWidth); glyph.y = Mathf.RoundToInt(rect.y * font.texHeight); glyph.width = Mathf.RoundToInt(rect.width * font.texWidth); glyph.height = Mathf.RoundToInt(rect.height * font.texHeight); // Flip the Y since the UV coordinate system is different glyph.y = font.texHeight - glyph.y - glyph.height; max = Mathf.Max(max, -glyph.offsetY); min = Mathf.Min(min, -glyph.offsetY - glyph.height); } int baseline = size + min; baseline += ((max - min - size) >> 1); // Offset all glyphs so that they are not using the baseline for (int i = 0, imax = entries.Count; i < imax; ++i) { BMGlyph glyph = font.GetGlyph(entries[i], true); glyph.offsetY += baseline; } } if (face != IntPtr.Zero) FT_Done_Face(face); #if !UNITY_3_5 if (lib != IntPtr.Zero) FT_Done_FreeType(lib); #endif return (tex != null); }
/// <summary> /// Apply an effect to the font. /// </summary> void ApplyEffect (Effect effect, Color foreground, Color background) { BMFont bf = mFont.bmFont; int offsetX = 0; int offsetY = 0; if (mFont.atlas != null) { UISpriteData sd = mFont.atlas.GetSprite(bf.spriteName); if (sd == null) return; offsetX = sd.x; offsetY = sd.y + mFont.texHeight - sd.paddingTop; } string path = AssetDatabase.GetAssetPath(mFont.texture); Texture2D bfTex = NGUIEditorTools.ImportTexture(path, true, true, false); Color32[] atlas = bfTex.GetPixels32(); // First we need to extract textures for all the glyphs, making them bigger in the process List<BMGlyph> glyphs = bf.glyphs; List<Texture2D> glyphTextures = new List<Texture2D>(glyphs.Count); for (int i = 0, imax = glyphs.Count; i < imax; ++i) { BMGlyph glyph = glyphs[i]; if (glyph.width < 1 || glyph.height < 1) continue; int width = glyph.width; int height = glyph.height; if (effect == Effect.Outline || effect == Effect.Shadow || effect == Effect.Border) { width += 2; height += 2; --glyph.offsetX; --glyph.offsetY; } else if (effect == Effect.Crop && width > 2 && height > 2) { width -= 2; height -= 2; ++glyph.offsetX; ++glyph.offsetY; } int size = width * height; Color32[] colors = new Color32[size]; Color32 clear = background; clear.a = 0; for (int b = 0; b < size; ++b) colors[b] = clear; if (effect == Effect.Crop) { for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { int fx = x + glyph.x + offsetX + 1; int fy = y + (mFont.texHeight - glyph.y - glyph.height) + 1; if (mFont.atlas != null) fy += bfTex.height - offsetY; colors[x + y * width] = atlas[fx + fy * bfTex.width]; } } } else { for (int y = 0; y < glyph.height; ++y) { for (int x = 0; x < glyph.width; ++x) { int fx = x + glyph.x + offsetX; int fy = y + (mFont.texHeight - glyph.y - glyph.height); if (mFont.atlas != null) fy += bfTex.height - offsetY; Color c = atlas[fx + fy * bfTex.width]; if (effect == Effect.Border) { colors[x + 1 + (y + 1) * width] = c; } else { if (effect == Effect.AlphaCurve) c.a = Mathf.Clamp01(mCurve.Evaluate(c.a)); Color bg = background; bg.a = (effect == Effect.BackgroundCurve) ? Mathf.Clamp01(mCurve.Evaluate(c.a)) : c.a; Color fg = foreground; fg.a = (effect == Effect.ForegroundCurve) ? Mathf.Clamp01(mCurve.Evaluate(c.a)) : c.a; if (effect == Effect.Outline || effect == Effect.Shadow) { colors[x + 1 + (y + 1) * width] = Color.Lerp(bg, c, c.a); } else { colors[x + y * width] = Color.Lerp(bg, fg, c.a); } } } } // Apply the appropriate affect if (effect == Effect.Shadow) NGUIEditorTools.AddShadow(colors, width, height, NGUISettings.backgroundColor); else if (effect == Effect.Outline) NGUIEditorTools.AddDepth(colors, width, height, NGUISettings.backgroundColor); } Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false); tex.SetPixels32(colors); tex.Apply(); glyphTextures.Add(tex); } // Pack all glyphs into a new texture Texture2D final = new Texture2D(bfTex.width, bfTex.height, TextureFormat.ARGB32, false); Rect[] rects = final.PackTextures(glyphTextures.ToArray(), 1); final.Apply(); // Make RGB channel use the background color (Unity makes it black by default) Color32[] fcs = final.GetPixels32(); Color32 bc = background; for (int i = 0, imax = fcs.Length; i < imax; ++i) { if (fcs[i].a == 0) { fcs[i].r = bc.r; fcs[i].g = bc.g; fcs[i].b = bc.b; } } final.SetPixels32(fcs); final.Apply(); // Update the glyph rectangles int index = 0; int tw = final.width; int th = final.height; for (int i = 0, imax = glyphs.Count; i < imax; ++i) { BMGlyph glyph = glyphs[i]; if (glyph.width < 1 || glyph.height < 1) continue; Rect rect = rects[index++]; glyph.x = Mathf.RoundToInt(rect.x * tw); glyph.y = Mathf.RoundToInt(rect.y * th); glyph.width = Mathf.RoundToInt(rect.width * tw); glyph.height = Mathf.RoundToInt(rect.height * th); glyph.y = th - glyph.y - glyph.height; } // Update the font's texture dimensions mFont.texWidth = final.width; mFont.texHeight = final.height; if (mFont.atlas == null) { // Save the final texture byte[] bytes = final.EncodeToPNG(); NGUITools.DestroyImmediate(final); System.IO.File.WriteAllBytes(path, bytes); AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); } else { // Update the atlas final.name = mFont.spriteName; bool val = NGUISettings.atlasTrimming; NGUISettings.atlasTrimming = false; UIAtlasMaker.AddOrUpdate(mFont.atlas, final); NGUISettings.atlasTrimming = val; NGUITools.DestroyImmediate(final); } // Cleanup for (int i = 0; i < glyphTextures.Count; ++i) NGUITools.DestroyImmediate(glyphTextures[i]); // Refresh all labels mFont.MarkAsChanged(); }
private Texture2D getTextureAndGenerateUVs(FaceNoSC[] faces) { // BASE TEXTURE ATLAS Texture2D TextureAtlas = new Texture2D(1, 1); TextureAtlas.anisoLevel = 0; TextureAtlas.filterMode = FilterMode.Point; //RECOPILATING TEXTURES Texture2D[] AllCubeTextures = new Texture2D[faces.Length]; for (int i = 0; i < faces.Length; i++) AllCubeTextures[i] = (faces[i] as FaceNoSC).Texture; Rect[] posTexturas = TextureAtlas.PackTextures(AllCubeTextures, 0); for (int i = 0; i < faces.Length; i++) faces[i].regenerateUVs(posTexturas[i]); int partialHash = 0; Color[] pixeles = TextureAtlas.GetPixels(); int incr = (pixeles.Length > 1000)? (int) pixeles.Length / 1000 : 1; for(int i = 0; i<pixeles.Length; i = i+incr){ partialHash += pixeles[i].GetHashCode(); } TextureHash = partialHash + ""; return TextureAtlas; }
Rect[] __CreateAtlasesUnityTexturePacker(ProgressUpdateDelegate progressInfo, int numAtlases, List<MB_TexSet> distinctMaterialTextures, List<ShaderTextureProperty> texPropertyNames, bool[] allTexturesAreNullAndSameColor, Material resultMaterial, Texture2D[] atlases, MB2_EditorMethodsInterface textureEditorMethods, int _padding) { Rect[] uvRects; if (distinctMaterialTextures.Count == 1){ if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Only one image per atlas. Will re-use original texture"); uvRects = new Rect[1]; uvRects[0] = new Rect(0f,0f,1f,1f); for (int i = 0; i < numAtlases; i++){ MeshBakerMaterialTexture dmt = distinctMaterialTextures[0].ts[i]; atlases[i] = dmt.t; resultMaterial.SetTexture(texPropertyNames[i].name,atlases[i]); resultMaterial.SetTextureScale(texPropertyNames[i].name,dmt.scale); resultMaterial.SetTextureOffset(texPropertyNames[i].name,dmt.offset); } } else { long estArea = 0; int atlasSizeX = 1; int atlasSizeY = 1; uvRects = null; for (int i = 0; i < numAtlases; i++){ //i is an atlas "MainTex", "BumpMap" etc... //----------------------- Texture2D atlas = null; if (allTexturesAreNullAndSameColor[i]){ atlas = null; } else { if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.LogWarning("Beginning loop " + i + " num temporary textures " + _temporaryTextures.Count); for(int j = 0; j < distinctMaterialTextures.Count; j++){ //j is a distinct set of textures one for each of "MainTex", "BumpMap" etc... MB_TexSet txs = distinctMaterialTextures[j]; int tWidth = txs.idealWidth; int tHeight = txs.idealHeight; Texture2D tx = txs.ts[i].t; if (tx == null) tx = txs.ts[i].t = _createTemporaryTexture(tWidth,tHeight,TextureFormat.ARGB32, true); if (progressInfo != null) progressInfo("Adjusting for scale and offset " + tx, .01f); if (textureEditorMethods != null) textureEditorMethods.SetReadWriteFlag(tx, true, true); tx = GetAdjustedForScaleAndOffset2(txs.ts[i]); //create a resized copy if necessary if (tx.width != tWidth || tx.height != tHeight) { if (progressInfo != null) progressInfo("Resizing texture '" + tx + "'", .01f); if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.LogWarning("Copying and resizing texture " + texPropertyNames[i].name + " from " + tx.width + "x" + tx.height + " to " + tWidth + "x" + tHeight); if (textureEditorMethods != null) textureEditorMethods.SetReadWriteFlag((Texture2D) tx, true, true); tx = _resizeTexture((Texture2D) tx,tWidth,tHeight); } txs.ts[i].t = tx; } Texture2D[] texToPack = new Texture2D[distinctMaterialTextures.Count]; for (int j = 0; j < distinctMaterialTextures.Count;j++){ Texture2D tx = distinctMaterialTextures[j].ts[i].t; estArea += tx.width * tx.height; texToPack[j] = tx; } if (textureEditorMethods != null) textureEditorMethods.CheckBuildSettings(estArea); if (Math.Sqrt(estArea) > 3500f){ if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("The maximum possible atlas size is 4096. Textures may be shrunk"); } atlas = new Texture2D(1,1,TextureFormat.ARGB32,true); if (progressInfo != null) progressInfo("Packing texture atlas " + texPropertyNames[i].name, .25f); if (i == 0){ if (progressInfo != null) progressInfo("Estimated min size of atlases: " + Math.Sqrt(estArea).ToString("F0"), .1f); if (LOG_LEVEL >= MB2_LogLevel.info) Debug.Log("Estimated atlas minimum size:" + Math.Sqrt(estArea).ToString("F0")); _addWatermark(texToPack); if (distinctMaterialTextures.Count == 1){ //don't want to force power of 2 so tiling will still work uvRects = new Rect[1] {new Rect(0f,0f,1f,1f)}; atlas = _copyTexturesIntoAtlas(texToPack,_padding,uvRects,texToPack[0].width,texToPack[0].height); } else { int maxAtlasSize = 4096; uvRects = atlas.PackTextures(texToPack,_padding,maxAtlasSize,false); } if (LOG_LEVEL >= MB2_LogLevel.info) Debug.Log("After pack textures atlas size " + atlas.width + " " + atlas.height); atlasSizeX = atlas.width; atlasSizeY = atlas.height; atlas.Apply(); } else { if (progressInfo != null) progressInfo("Copying Textures Into: " + texPropertyNames[i].name, .1f); atlas = _copyTexturesIntoAtlas(texToPack,_padding,uvRects, atlasSizeX, atlasSizeY); } } atlases[i] = atlas; //---------------------- if (_saveAtlasesAsAssets && textureEditorMethods != null){ textureEditorMethods.SaveAtlasToAssetDatabase(atlases[i], texPropertyNames[i], i, resultMaterial); } resultMaterial.SetTextureOffset(texPropertyNames[i].name, Vector2.zero); resultMaterial.SetTextureScale(texPropertyNames[i].name,Vector2.one); _destroyTemporaryTextures(); // need to save atlases before doing this GC.Collect(); } } return uvRects; }
Texture2D BuildUVSpriteAtlas() { Texture2D[] textures = new Texture2D[m_Sel.m_SpriteList.Count]; Rect[] textureRect = new Rect[m_Sel.m_SpriteList.Count]; for (int n = 0; n < m_Sel.m_SpriteList.Count; n++) { if (m_Sel.m_SpriteList[n].m_bIncludedAtlas == false || m_Sel.m_SpriteList[n].m_TextureGUID == "") { textures[n] = null; continue; } Texture2D selTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(m_Sel.m_SpriteList[n].m_TextureGUID), typeof(Texture2D)); SetSourceTexture(selTexture); m_Sel.m_SpriteList[n].m_nFrameCount = 1; m_Sel.m_SpriteList[n].m_nFrameSize = 1; m_Sel.m_nFrameSize = 1; textures[n] = selTexture; textureRect[n] = new Rect(0, 0, selTexture.width, selTexture.height); } Color clearColor = new Color(0, 0, 0, 0); Texture2D AtlasTexture = new Texture2D(32, 32, TextureFormat.ARGB32, false); Rect[] packRects = AtlasTexture.PackTextures(textures, 3, m_Sel.m_nMaxAtlasTextureSize); m_Sel.m_nTilingX = 1; m_Sel.m_nTilingY = 1; m_Sel.m_fTextureRatio = AtlasTexture.width / (float)AtlasTexture.height; // clear for (int x = 0; x < AtlasTexture.width; x++) for (int y = 0; y < AtlasTexture.height; y++) AtlasTexture.SetPixel(x, y, clearColor); // copy for (int n = 0; n < m_Sel.m_SpriteList.Count; n++) { if (m_Sel.m_SpriteList[n].m_bIncludedAtlas == false || m_Sel.m_SpriteList[n].m_TextureGUID == "") continue; m_Sel.m_SpriteList[n].m_nStartFrame = 0; m_Sel.m_SpriteList[n].m_UvRect = packRects[n]; // Debug.Log(packRects[n]); // Debug.Log(textureRect[n]); // Debug.Log(new Rect((int)(packRects[n].x*AtlasTexture.width), (int)(packRects[n].y*AtlasTexture.height), (int)(packRects[n].width*AtlasTexture.width), (int)(packRects[n].height*AtlasTexture.height))); // 알파조정 처리 Color[] colBuf = textures[n].GetPixels(); for (int an = 0; an < colBuf.Length; an++) if (m_Sel.m_SpriteList[n].m_fMaxTextureAlpha < colBuf[an].a) colBuf[an].a = m_Sel.m_SpriteList[n].m_fMaxTextureAlpha; AtlasTexture.SetPixels((int)(packRects[n].x*AtlasTexture.width), (int)(packRects[n].y*AtlasTexture.height), (int)(packRects[n].width*AtlasTexture.width), (int)(packRects[n].height*AtlasTexture.height), colBuf); } return AtlasTexture; }
/// <summary> /// Packs the original texture using Unity's texture packing method /// </summary> /// <returns>The original texture.</returns> /// <param name="texturePositions">Texture positions.</param> /// <param name="textureAtlas">Texture atlas.</param> /// <param name="atlasInfo">Atlas info.</param> static Rect[] PackOriginalTexture(TexturePosition[] texturePositions, Texture2D textureAtlas, DrawCallMinimizerInfo atlasInfo) { textureAtlas.anisoLevel = atlasInfo.anisoLevel; textureAtlas.filterMode = atlasInfo.filterMode; textureAtlas.wrapMode = atlasInfo.wrapMode; Rect[] UVpositions = textureAtlas.PackTextures(GetTexturesAsArray(texturePositions, 0), atlasInfo.padding, atlasInfo.maxTextureSize, !atlasInfo.readableTexture); for (int i = 0; i < texturePositions.Length; i++) { texturePositions [i].position = UVpositions [i]; } return UVpositions; }
void InitializeTextures() { int numberOfTypes = Enum.GetNames(typeof(BlockType)).Length; Dictionary<int, Texture2D> textureIDMap = new Dictionary<int, Texture2D>(); //Dictionary<int, BlockFacePair> blockfaceIDMap = new Dictionary<int, BlockFacePair>(); int[,] blocktypeTextureMap = new int[numberOfTypes,6]; foreach(BlockDefinition b in blocksDefinition) { foreach (BlockDefinition.TextureFaceMap t in b.specialFaceTextures) { // First, assign the face textures int id = t.texture.GetInstanceID(); blocktypeTextureMap[(int)b.type,(int)t.face] = id; textureIDMap[id] = t.texture; //blockfaceIDMap[id] = new BlockFacePair(b.type, t.face); } // Second, assign the baseTexture for all unfilled faces int baseID = b.baseTexture.GetInstanceID(); textureIDMap[baseID] = b.baseTexture; for (int i=0;i<6;i++) { if (blocktypeTextureMap[(int)b.type,i] == 0) { blocktypeTextureMap[(int)b.type,i] = baseID; } } } Texture2D[] sortedTextures = new Texture2D[textureIDMap.Values.Count]; Dictionary<int, int> idToTextureIndexMap = new Dictionary<int,int>(); int count = 0; foreach (KeyValuePair<int, Texture2D> pair in textureIDMap) { sortedTextures[count] = pair.Value; idToTextureIndexMap[pair.Key] = count; count++; } // @TODO: calculate maxWidth so there is no wasted texture memory int maxWidth = 1024;//(int)(Mathf.Ceil(Mathf.Sqrt(textures.Length)) * textureWidth); textureAtlas = new Texture2D(maxWidth, maxWidth); Rect[] uvs = textureAtlas.PackTextures(sortedTextures, 0, maxWidth); atlasUVs = new Vector2[numberOfTypes, 6, 4]; // @TODO: find a better fix to the UV mapping than this kludgy padding workaround float padding = .001f; // May not scale well with large textures for (int j=0; j<numberOfTypes; j++) { // Sides are defined as for (int k=0;k<6;k++) { int textureInstanceID = blocktypeTextureMap[j,k]; if (textureInstanceID == 0) continue; int l = idToTextureIndexMap[textureInstanceID]; // Atlas UVs are defined 0=bottomLeft, 1=bottomRight, 2=topRight, 3=topLeft atlasUVs[j,k,0] = new Vector2(uvs[l].x+padding, uvs[l].y+padding); atlasUVs[j,k,1] = new Vector2(uvs[l].x+uvs[l].width-padding, uvs[l].y+padding); atlasUVs[j,k,2] = new Vector2(uvs[l].x+uvs[l].width-padding, uvs[l].y+uvs[l].height-padding); atlasUVs[j,k,3] = new Vector2(uvs[l].x+padding, uvs[l].y+uvs[l].height-padding); } } }
/// <summary> /// Combine SkinnedMeshRenderers together and share one skeleton. /// Merge materials will reduce the drawcalls, but it will increase the size of memory. /// </summary> /// <param name="skeleton">combine meshes to this skeleton(a gameobject)</param> /// <param name="meshes">meshes need to be merged</param> /// <param name="combine">merge materials or not</param> public void CombineObject(GameObject skeleton, SkinnedMeshRenderer[] meshes, bool combine = false) { // Fetch all bones of the skeleton List<Transform> transforms = new List<Transform>(); transforms.AddRange(skeleton.GetComponentsInChildren<Transform>(true)); List<Material> materials = new List<Material>();//the list of materials List<CombineInstance> combineInstances = new List<CombineInstance>();//the list of meshes List<Transform> bones = new List<Transform>();//the list of bones // Below informations only are used for merge materilas(bool combine = true) List<Vector2[]> oldUV = null; Material newMaterial = null; Texture2D newDiffuseTex = null; // Collect information from meshes for (int i = 0; i < meshes.Length; i ++) { SkinnedMeshRenderer smr = meshes[i]; materials.AddRange(smr.materials); // Collect materials // Collect meshes for (int sub = 0; sub < smr.sharedMesh.subMeshCount; sub++) { CombineInstance ci = new CombineInstance(); ci.mesh = smr.sharedMesh; ci.subMeshIndex = sub; combineInstances.Add(ci); } // Collect bones for (int j = 0 ; j < smr.bones.Length; j ++) { int tBase = 0; for (tBase = 0; tBase < transforms.Count; tBase ++) { if (smr.bones[j].name.Equals(transforms[tBase].name)) { bones.Add(transforms[tBase]); break; } } } } // merge materials if (combine) { newMaterial = new Material (Shader.Find ("Mobile/Diffuse")); oldUV = new List<Vector2[]>(); // merge the texture List<Texture2D> Textures = new List<Texture2D>(); for (int i = 0; i < materials.Count; i++) { Textures.Add(materials[i].GetTexture(COMBINE_DIFFUSE_TEXTURE) as Texture2D); } newDiffuseTex = new Texture2D(COMBINE_TEXTURE_MAX, COMBINE_TEXTURE_MAX, TextureFormat.RGBA32, true); Rect[] uvs = newDiffuseTex.PackTextures(Textures.ToArray(), 0); newMaterial.mainTexture = newDiffuseTex; // reset uv Vector2[] uva, uvb; for (int j = 0; j < combineInstances.Count; j++) { uva = (Vector2[])(combineInstances[j].mesh.uv); uvb = new Vector2[uva.Length]; for (int k = 0; k < uva.Length; k++) { uvb[k] = new Vector2((uva[k].x * uvs[j].width) + uvs[j].x, (uva[k].y * uvs[j].height) + uvs[j].y); } oldUV.Add(combineInstances[j].mesh.uv); combineInstances[j].mesh.uv = uvb; } } // Create a new SkinnedMeshRenderer SkinnedMeshRenderer oldSKinned = skeleton.GetComponent<SkinnedMeshRenderer> (); if (oldSKinned != null) { GameObject.DestroyImmediate (oldSKinned); } SkinnedMeshRenderer r = skeleton.AddComponent<SkinnedMeshRenderer>(); r.sharedMesh = new Mesh(); r.sharedMesh.CombineMeshes(combineInstances.ToArray(), combine, false);// Combine meshes r.bones = bones.ToArray();// Use new bones if (combine) { r.material = newMaterial; for (int i = 0 ; i < combineInstances.Count ; i ++) { combineInstances[i].mesh.uv = oldUV[i]; } }else { r.materials = materials.ToArray(); } }
public static void RebuildAtlas(RagePixelSpriteSheet spriteSheet, bool atlasIsGrowing, string caller = "nobody") { int frameCount = spriteSheet.GetTotalCellCount(); Texture2D[] textures = new Texture2D[frameCount]; RagePixelCell[] cells = new RagePixelCell[frameCount]; int index = 0; EditorUtility.SetDirty(spriteSheet); Texture2D sourceTexture = spriteSheet.atlas.GetTexture("_MainTex") as Texture2D; if (sourceTexture != null) { foreach (RagePixelRow row in spriteSheet.rows) { foreach (RagePixelCell cell in row.cells) { textures[index] = new Texture2D(row.newPixelSizeX, row.newPixelSizeY); if (cell.uv.width > 0f && cell.uv.height > 0f) { clearPixels(textures[index]); CopyPixels(sourceTexture, cell.uv, textures[index], new Rect(0f, 0f, 1f, 1f)); } else { clearPixels(textures[index]); } cells[index] = cell; index++; } } } Texture2D newAtlasTexture = new Texture2D(defaultAtlasSize, defaultAtlasSize); int atlasPadding = defaultAtlasPadding; if (textures.Length == 1) { atlasPadding = 0; } Rect[] newUvs = newAtlasTexture.PackTextures(textures, atlasPadding, 4096); if (newUvs != null) { float totalAreaOld = 0f; float totalAreaNew = 0f; for (int i = 0; i < cells.Length; i++) { totalAreaOld += cells[i].uv.height * cells[i].uv.width; } for (int i = 0; i < newUvs.Length; i++) { totalAreaNew += newUvs[i].height * newUvs[i].width; } // Checking if the PackTextures() is going to crap all over spritesheet, when going over max texture size if (!(atlasIsGrowing && totalAreaNew < totalAreaOld && sourceTexture.width * sourceTexture.height >= newAtlasTexture.width * newAtlasTexture.height)) { for (int i = 0; i < newUvs.Length && i < cells.Length; i++) { cells[i].uv = newUvs[i]; } saveAtlasPng(defaultAtlasPath, spriteSheet.atlas.name, newAtlasTexture); for (int i = 0; i < textures.Length; i++) { Object.DestroyImmediate(textures[i]); } Object.DestroyImmediate(newAtlasTexture); RagePixelSprite[] sprites = Resources.FindObjectsOfTypeAll(typeof(RagePixelSprite)) as RagePixelSprite[]; EditorUtility.SetDirty(spriteSheet); EditorUtility.SetDirty(spriteSheet.atlas); EditorUtility.SetDirty(spriteSheet.atlas.GetTexture("_MainTex")); foreach (RagePixelRow row in spriteSheet.rows) { row.pixelSizeX = row.newPixelSizeX; row.pixelSizeY = row.newPixelSizeY; } foreach (RagePixelSprite sprite in sprites) { EditorUtility.SetDirty(sprite); sprite.checkKeyIntegrity(); sprite.SnapToIntegerPosition(); sprite.refreshMesh(); } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } else { Debug.Log("ERROR: Too much data for max texture size (Spritesheet: " + spriteSheet.name + ")"); } } else { Debug.Log("ERROR: Atlas PackTextures() failed (Spritesheet: " + spriteSheet.name + ")"); } }