Пример #1
0
    private void drawSprite(Rect rect, dfAtlas atlas, dfAtlas.ItemInfo sprite)
    {
        var size     = sprite.sizeInPixels;
        var destRect = rect;

        if (destRect.width < size.x || destRect.height < size.y)
        {
            var newHeight = size.y * rect.width / size.x;
            if (newHeight <= rect.height)
            {
                destRect.height = newHeight;
            }
            else
            {
                destRect.width = size.x * rect.height / size.y;
            }
        }
        else
        {
            destRect.width  = size.x;
            destRect.height = size.y;
        }

        if (destRect.width < rect.width)
        {
            destRect.x = rect.x + (rect.width - destRect.width) * 0.5f;
        }
        if (destRect.height < rect.height)
        {
            destRect.y = rect.y + (rect.height - destRect.height) * 0.5f;
        }

        GUI.DrawTextureWithTexCoords(destRect, atlas.Material.mainTexture, sprite.region);
    }
Пример #2
0
    public static void UpgradeAtlas(dfAtlas atlas)
    {
        try
        {
            var sprites = atlas.Items;
            for (int i = 0; i < sprites.Count; i++)
            {
                var sprite = sprites[i];

                if (sprite.texture != null)
                {
                    var spritePath = AssetDatabase.GetAssetPath(sprite.texture);
                    var guid       = AssetDatabase.AssetPathToGUID(spritePath);

                    sprite.sizeInPixels = new Vector2(sprite.texture.width, sprite.texture.height);
                    sprite.textureGUID  = guid;
                    sprite.texture      = null;
                }
                else if (!string.IsNullOrEmpty(sprite.textureGUID))
                {
                    var path    = AssetDatabase.GUIDToAssetPath(sprite.textureGUID);
                    var texture = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;

                    sprite.sizeInPixels = new Vector2(texture.width, texture.height);
                }
            }

            EditorUtility.SetDirty(atlas);
        }
        catch (Exception err)
        {
            Debug.LogError("Error upgrading atlas " + atlas.name + ": " + err.Message, atlas);
        }
    }
Пример #3
0
        /// <summary>
        /// Builds and adds a new <see cref="dfAtlas.ItemInfo"/> to <paramref name="atlas"/> with the texture of <paramref name="tex"/> and the name of <paramref name="name"/>.
        /// </summary>
        /// <param name="atlas">The <see cref="dfAtlas"/> to add the new <see cref="dfAtlas.ItemInfo"/> to.</param>
        /// <param name="tex">The texture of the new <see cref="dfAtlas.ItemInfo"/>.</param>
        /// <param name="name">The name of the new <see cref="dfAtlas.ItemInfo"/>. If <see langword="null"/>, it will default to <paramref name="tex"/>'s name.</param>
        /// <returns>The built <see cref="dfAtlas.ItemInfo"/>.</returns>
        public static dfAtlas.ItemInfo AddNewItemToAtlas(this dfAtlas atlas, Texture2D tex, string name = null)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = tex.name;
            }
            if (atlas[name] != null)
            {
                return(atlas[name]);
            }
            dfAtlas.ItemInfo item = new dfAtlas.ItemInfo
            {
                border       = new RectOffset(),
                deleted      = false,
                name         = name,
                region       = atlas.FindFirstValidEmptySpace(new IntVector2(tex.width, tex.height)),
                rotated      = false,
                sizeInPixels = new Vector2(tex.width, tex.height),
                texture      = tex,
                textureGUID  = name
            };
            int startPointX = Mathf.RoundToInt(item.region.x * atlas.Texture.width);
            int startPointY = Mathf.RoundToInt(item.region.y * atlas.Texture.height);

            for (int x = startPointX; x < Mathf.RoundToInt(item.region.xMax * atlas.Texture.width); x++)
            {
                for (int y = startPointY; y < Mathf.RoundToInt(item.region.yMax * atlas.Texture.height); y++)
                {
                    atlas.Texture.SetPixel(x, y, tex.GetPixel(x - startPointX, y - startPointY));
                }
            }
            atlas.Texture.Apply();
            atlas.AddItem(item);
            return(item);
        }
Пример #4
0
    private static Texture2D getTexture(dfAtlas atlas, string sprite)
    {
        var spriteInfo = atlas[sprite];

        if (spriteInfo == null)
        {
            return(null);
        }

        var guid = atlas[sprite].textureGUID;

        if (string.IsNullOrEmpty(guid))
        {
            return(null);
        }

        var path = AssetDatabase.GUIDToAssetPath(guid);

        if (string.IsNullOrEmpty(path))
        {
            return(null);
        }

        return(AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D);
    }
Пример #5
0
    private static void DrawSprite(Rect rect, dfAtlas atlas, string sprite)
    {
        var spriteInfo = atlas[sprite];
        var size       = spriteInfo.sizeInPixels;
        var destRect   = rect;

        if (destRect.width < size.x || destRect.height < size.y)
        {
            var newHeight = size.y * rect.width / size.x;
            if (newHeight <= rect.height)
            {
                destRect.height = newHeight;
            }
            else
            {
                destRect.width = size.x * rect.height / size.y;
            }
        }
        else
        {
            destRect.width  = size.x;
            destRect.height = size.y;
        }

        if (destRect.width < rect.width)
        {
            destRect.x = rect.x + (rect.width - destRect.width) * 0.5f;
        }
        if (destRect.height < rect.height)
        {
            destRect.y = rect.y + (rect.height - destRect.height) * 0.5f;
        }

        dfEditorUtil.DrawSprite(destRect, atlas, sprite);
    }
Пример #6
0
        /// <summary>
        /// Resizes <paramref name="atlas"/> and all of it's <see cref="dfAtlas.ItemInfo"/>s.
        /// </summary>
        /// <param name="atlas">The <see cref="dfAtlas"/> to resize/</param>
        /// <param name="newDimensions"><paramref name="atlas"/>'s new size.</param>
        public static void ResizeAtlas(this dfAtlas atlas, IntVector2 newDimensions)
        {
            Texture2D tex = atlas.Texture;

            if (!tex.IsReadable())
            {
                return;
            }
            if (tex.width == newDimensions.x && tex.height == newDimensions.y)
            {
                return;
            }
            foreach (dfAtlas.ItemInfo item in atlas.Items)
            {
                if (item.region != null)
                {
                    item.region.x      = (item.region.x * tex.width) / newDimensions.x;
                    item.region.y      = (item.region.y * tex.height) / newDimensions.y;
                    item.region.width  = (item.region.width * tex.width) / newDimensions.x;
                    item.region.height = (item.region.height * tex.height) / newDimensions.y;
                }
            }
            tex.ResizeBetter(newDimensions.x, newDimensions.y);
            atlas.Material.SetTexture("_MainTex", tex);
        }
Пример #7
0
        public static void HandleSprites(PlayerController player, CustomCharacterData data)
        {
            if (data.minimapIcon != null)
            {
                HandleMinimapIcons(player, data);
            }

            if (data.bossCard != null)
            {
                HandleBossCards(player, data);
            }

            if (data.sprites != null || data.playerSheet != null)
            {
                HandleAnimations(player, data);
            }

            //face card stuff
            uiAtlas = GameUIRoot.Instance.ConversationBar.portraitSprite.Atlas;
            if (data.faceCard != null)
            {
                HandleFacecards(player, data);
            }

            if (data.punchoutFaceCards != null && data.punchoutFaceCards.Count > 0)
            {
                HandlePunchoutFaceCards(data);
            }
        }
Пример #8
0
    private dfMarkupBox createImageBox(dfAtlas atlas, string source, dfMarkupStyle style)
    {
        if (source.ToLowerInvariant().StartsWith("http://"))
        {
            return(null);
        }
        else if (atlas != null && atlas[source] != null)
        {
            var spriteBox = new dfMarkupBoxSprite(this, dfMarkupDisplayType.inline, style);
            spriteBox.LoadImage(atlas, source);

            return(spriteBox);
        }
        else
        {
            var texture = dfMarkupImageCache.Load(source);
            if (texture != null)
            {
                var textureBox = new dfMarkupBoxTexture(this, dfMarkupDisplayType.inline, style);
                textureBox.LoadTexture(texture);

                return(textureBox);
            }
        }

        return(null);
    }
Пример #9
0
        /// <summary>
        /// Gets the pixel regions of <paramref name="atlas"/> and sorts them using <paramref name="sortType"/>.
        /// </summary>
        /// <param name="atlas">The <see cref="dfAtlas"/> to get the pixel regions from.</param>
        /// <param name="sortType">The <see cref="AtlasItemSortType"/> used to sort the list of pixel regions.</param>
        /// <returns>A list with all pixel regions in <paramref name="atlas"/> that is sorted using <paramref name="sortType"/></returns>
        public static List <RectInt> GetSortedPixelRegions(this dfAtlas atlas, AtlasItemSortType sortType)
        {
            List <RectInt> rawList    = atlas.GetPixelRegions();
            List <RectInt> sortedList = new List <RectInt>();

            while (sortedList.Count < rawList.Count)
            {
                RectInt rint             = new RectInt(0, 0, 0, 0);
                bool    rintIsUnassigned = true;
                for (int i = 0; i < rawList.Count; i++)
                {
                    if (!sortedList.Contains(rawList[i]))
                    {
                        if (rintIsUnassigned)
                        {
                            rint             = rawList[i];
                            rintIsUnassigned = false;
                        }
                        else
                        {
                            rint = ((rint.GetPointInRint(sortType).x >= rawList[i].GetPointInRint(sortType).x&& rint.GetPointInRint(sortType).y >= rawList[i].GetPointInRint(sortType).y) ? rawList[i] : rint);
                        }
                    }
                }
                sortedList.Add(rint);
            }
            return(sortedList);
        }
Пример #10
0
    private static void ShowAtlasActions(dfAtlas atlas)
    {
        dfEditorUtil.DrawSeparator();

        EditorGUILayout.BeginHorizontal();
        {
            if (atlas.generator == dfAtlas.TextureAtlasGenerator.TexturePacker)
            {
                if (GUILayout.Button("Reimport"))
                {
                    dfTexturePackerImporter.Reimport(atlas);
                }
            }
            else if (GUILayout.Button("Rebuild"))
            {
                rebuildAtlas(atlas);
            }

            if (GUILayout.Button("Refresh Views"))
            {
                dfGUIManager.RefreshAll(true);
            }
        }
        EditorGUILayout.EndHorizontal();
    }
Пример #11
0
    private void ShowAddTextureOption(dfAtlas atlas)
    {
        dfEditorUtil.DrawSeparator();

        using (dfEditorUtil.BeginGroup("Add Sprites"))
        {
            EditorGUILayout.HelpBox("You can drag and drop textures here to add them to the Texture Atlas", MessageType.Info);

            var evt = Event.current;
            if (evt != null)
            {
                Rect dropRect = GUILayoutUtility.GetLastRect();
                if (evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform)
                {
                    if (dropRect.Contains(evt.mousePosition))
                    {
                        var draggedTexture = DragAndDrop.objectReferences.FirstOrDefault(x => x is Texture2D);
                        DragAndDrop.visualMode = (draggedTexture != null) ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.None;
                        if (evt.type == EventType.DragPerform)
                        {
                            addSelectedTextures(atlas);
                        }
                        evt.Use();
                    }
                }
            }
        }
    }
Пример #12
0
 /// <summary>
 /// Gets the pixel regions of <paramref name="atlas"/>.
 /// </summary>
 /// <param name="atlas">The <see cref="dfAtlas"/> to get the pixel regions from.</param>
 /// <returns>A list with all pixel regions in <paramref name="atlas"/></returns>
 public static List <RectInt> GetPixelRegions(this dfAtlas atlas)
 {
     return(atlas.Items.Convert(delegate(dfAtlas.ItemInfo item)
     {
         return new RectInt(Mathf.RoundToInt(item.region.x * atlas.Texture.width), Mathf.RoundToInt(item.region.y * atlas.Texture.height), Mathf.RoundToInt(item.region.width * atlas.Texture.width),
                            Mathf.RoundToInt(item.region.height * atlas.Texture.height));
     }));
 }
        public static void DumpdfAtlas(dfAtlas atlas)
        {
            string collectionName = atlas.name;

            string    defName;
            Texture2D texture, output;
            int       width, height, minX, minY, maxX, maxY, w, h;

            Color[] pixels;


            var itemSizes = atlas.GetPixelRegions();

            for (int i = 0; i < itemSizes.Count; i++)
            {
                var def = atlas.Items[i];
                if (def == null)
                {
                    continue;
                }


                defName = string.IsNullOrEmpty(def.name) ? collectionName + "_" + i : def.name;


                texture = (Texture2D)atlas.Texture.GetReadable();
                width   = texture.width;
                height  = texture.height;



                minX = itemSizes[i].xMin;
                minY = itemSizes[i].yMin;
                maxX = itemSizes[i].xMax;
                maxY = itemSizes[i].yMax;

                w = maxX - minX;
                h = maxY - minY;


                if (w <= 0 || h <= 0)
                {
                    ToolsCharApi.PrintError <string>($"[{defName}]: is to small. minX: {minX}, minY: {minY}, maxX: {maxX}, maxY: {maxY}");
                    //ToolsCharApi.ExportTexture(new Texture2D(1, 1) { name = defName });
                    continue;
                }
                ;

                pixels = texture.GetPixels(minX, minY, w, h);

                output = new Texture2D(w, h);
                output.SetPixels(pixels);
                output.Apply();
                output.name = def.name;
                //BotsModule.Log(output.name, BotsModule.TEXT_COLOR);
                ToolsCharApi.ExportTexture(output, "SpriteDump/df/" + collectionName);
            }
        }
Пример #14
0
        internal static void PrepareCustomOptions()
        {
            CachedCentralPanel     = Patches.FullOptionsMenuController.Instance.TabGameplay.transform.parent.gameObject.GetComponent <dfPanel>();
            CachedOptionsAtlas     = Patches.FullOptionsMenuController.Instance.TabGameplay.Atlas;
            CachedOptionsScrollbar = Patches.FullOptionsMenuController.Instance.TabGameplay.VertScrollbar;
            CachedCrosshairSelectionDoerControl = Patches.PreOptionsMenuController.Instance.TabGameplaySelector.GetComponent <MenuCrosshairSelectionDoer>().controlToPlace;

            CachedOptionMenuEntry   = Patches.FullOptionsMenuController.Instance.TabGameplay.transform.GetChild(1).gameObject.GetComponent <dfPanel>();
            CachedCheckboxMenuEntry = Patches.FullOptionsMenuController.Instance.TabGameplay.transform.GetChild(0).gameObject.GetComponent <dfPanel>();
        }
Пример #15
0
    private void EditAtlasOptions(dfAtlas atlas)
    {
        if (atlas.generator == dfAtlas.TextureAtlasGenerator.Internal)
        {
            using (dfEditorUtil.BeginGroup("Global Options"))
            {
                var packingMethodConfig = (dfTexturePacker.dfTexturePackingMethod)EditorPrefs.GetInt("DaikonForge.AtlasPackingMethod", (int)dfTexturePacker.dfTexturePackingMethod.RectBestAreaFit);
                var packingMethod       = (dfTexturePacker.dfTexturePackingMethod)EditorGUILayout.EnumPopup("Packing Method", packingMethodConfig);
                if (packingMethod != packingMethodConfig)
                {
                    EditorPrefs.SetInt("DaikonForge.AtlasPackingMethod", (int)packingMethod);
                }

                var sizes         = new string[] { "256", "512", "1024", "2048", "4096" };
                var defaultIndex  = Mathf.Max(0, getIndex(sizes, dfTextureAtlasInspector.MaxAtlasSize.ToString()));
                var selectedIndex = EditorGUILayout.Popup("Max Size", defaultIndex, sizes);
                dfTextureAtlasInspector.MaxAtlasSize = int.Parse(sizes[selectedIndex]);

                var paddingConfig = EditorPrefs.GetInt("DaikonForge.AtlasDefaultPadding", 2);
                var padding       = Mathf.Max(0, EditorGUILayout.IntField("Padding", paddingConfig));
                {
                    if (padding != paddingConfig)
                    {
                        EditorPrefs.SetInt("DaikonForge.AtlasDefaultPadding", padding);
                    }
                }

                ForceSquare = EditorGUILayout.Toggle("Force square", ForceSquare);

                var extrudeSpritesConfig = EditorPrefs.GetBool("DaikonForge.AtlasExtrudeSprites", false);
                var extrudeSprites       = EditorGUILayout.Toggle("Extrude Edges", extrudeSpritesConfig);
                {
                    if (extrudeSprites != extrudeSpritesConfig)
                    {
                        EditorPrefs.SetBool("DaikonForge.AtlasExtrudeSprites", extrudeSprites);
                    }
                }
            }
        }
        else if (atlas.generator == dfAtlas.TextureAtlasGenerator.TexturePacker)
        {
            using (dfEditorUtil.BeginGroup("Imported Texture Atlas"))
            {
                var dataFilePath = AssetDatabase.GUIDToAssetPath(atlas.dataFileGUID);
                var dataFile     = AssetDatabase.LoadAssetAtPath(dataFilePath, typeof(TextAsset)) as TextAsset;
                EditorGUILayout.ObjectField("Image File", atlas.Texture, typeof(Texture2D), false);
                EditorGUILayout.ObjectField("Data File", dataFile, typeof(TextAsset), false);
            }
        }

        using (dfEditorUtil.BeginGroup("Atlas Options"))
        {
            EditAtlasReplacement(atlas);
        }
    }
Пример #16
0
    private void ShowModifiedTextures(dfAtlas atlas)
    {
        dfEditorUtil.DrawSeparator();

        var atlasPath = AssetDatabase.GetAssetPath(atlas.Texture);

        if (string.IsNullOrEmpty(atlasPath) || !File.Exists(atlasPath))
        {
            EditorGUILayout.HelpBox("Could not find the path associated with the Atlas texture", MessageType.Error);
            return;
        }

        var atlasModified = File.GetLastWriteTime(atlasPath);

        var modifiedSprites = new List <dfAtlas.ItemInfo>();

        for (int i = 0; i < atlas.Items.Count; i++)
        {
            var sprite = atlas.Items[i];

            var spriteTexturePath = AssetDatabase.GUIDToAssetPath(sprite.textureGUID);
            if (string.IsNullOrEmpty(spriteTexturePath) || !File.Exists(spriteTexturePath))
            {
                continue;
            }

            var spriteModified = File.GetLastWriteTime(spriteTexturePath);
            if (spriteModified > atlasModified)
            {
                modifiedSprites.Add(sprite);
            }
        }

        if (modifiedSprites.Count == 0)
        {
            return;
        }

        using (dfEditorUtil.BeginGroup("Modified Sprites"))
        {
            var list    = string.Join("\n\t", modifiedSprites.Select(s => s.name).ToArray());
            var message = string.Format("The following textures have been modified:\n\t{0}", list);

            EditorGUILayout.HelpBox(message, MessageType.Info);

            var performUpdate = GUILayout.Button("Refresh Modified Sprites");
            dfEditorUtil.DrawSeparator();

            if (performUpdate)
            {
                rebuildAtlas(atlas);
            }
        }
    }
Пример #17
0
 internal void LoadImage(dfAtlas atlas, string source)
 {
     dfAtlas.ItemInfo item = atlas[source];
     if (item == null)
     {
         throw new InvalidOperationException(string.Concat("Sprite does not exist in atlas: ", source));
     }
     this.Atlas    = atlas;
     this.Source   = source;
     this.Size     = item.sizeInPixels;
     this.Baseline = (int)this.Size.y;
 }
Пример #18
0
 internal void LoadImage(dfAtlas atlas, string source)
 {
     dfAtlas.ItemInfo item = atlas[source];
     if (item == null)
     {
         throw new InvalidOperationException(string.Concat("Sprite does not exist in atlas: ", source));
     }
     this.Atlas = atlas;
     this.Source = source;
     this.Size = item.sizeInPixels;
     this.Baseline = (int)this.Size.y;
 }
Пример #19
0
 internal static bool Equals(dfAtlas lhs, dfAtlas rhs)
 {
     if (object.ReferenceEquals(lhs, rhs))
     {
         return(true);
     }
     if (lhs == null || rhs == null)
     {
         return(false);
     }
     return(lhs.material == rhs.material);
 }
Пример #20
0
 internal void LoadImage(dfAtlas atlas, string source)
 {
     dfAtlas.ItemInfo info = atlas[source];
     if (info == null)
     {
         throw new InvalidOperationException("Sprite does not exist in atlas: " + source);
     }
     this.Atlas    = atlas;
     this.Source   = source;
     base.Size     = info.sizeInPixels;
     base.Baseline = (int)this.Size.y;
 }
Пример #21
0
    public bool AddTexture(dfAtlas atlas, params Texture2D[] newTextures)
    {
        try
        {
            selectedTextures.Clear();

            var addedItems = new List <dfAtlas.ItemInfo>();

            for (int i = 0; i < newTextures.Length; i++)
            {
                // Grab reference to existing item, if it exists, to preserve border information
                var existingItem = atlas[newTextures[i].name];

                // Remove the existing item if it already exists
                atlas.Remove(newTextures[i].name);

                // Keep the texture size available
                var size = new Vector2(newTextures[i].width, newTextures[i].height);

                // Determine the guid for the texture
                var spritePath = AssetDatabase.GetAssetPath(newTextures[i]);
                var guid       = AssetDatabase.AssetPathToGUID(spritePath);

                // Add the new texture to the Items collection
                var newItem = new dfAtlas.ItemInfo()
                {
                    textureGUID  = guid,
                    name         = newTextures[i].name,
                    border       = (existingItem != null) ? existingItem.border : new RectOffset(),
                    sizeInPixels = size
                };
                addedItems.Add(newItem);
                atlas.AddItem(newItem);
            }

            if (!rebuildAtlas(atlas))
            {
                atlas.Items.RemoveAll(i => addedItems.Contains(i));
                return(false);
            }

            return(true);
        }
        catch (Exception err)
        {
            Debug.LogError(err.ToString(), atlas);
            EditorUtility.DisplayDialog("Error Adding Sprite", err.Message, "OK");
        }

        return(false);
    }
Пример #22
0
    private string buildItemTooltip( dfAtlas.ItemInfo sprite )
    {
        if( sprite == null )
            return "";

        var width = (int)sprite.sizeInPixels.x;
        var height = (int)sprite.sizeInPixels.y;

        return string.Format(
            "Atlas: {3}  Sprite: {0}  Size: {1}x{2}",
            sprite.name,
            width,
            height,
            atlas.name
        );
    }
Пример #23
0
    private static void previewAtlasTexture(dfAtlas atlas, Rect rect)
    {
        if (atlas == null)
        {
            return;
        }

        var texture = atlas.Texture;

        if (texture == null)
        {
            return;
        }

        var size = new Vector2(texture.width, texture.height);

        var destRect = rect;

        if (destRect.width < size.x || destRect.height < size.y)
        {
            var newHeight = size.y * rect.width / size.x;
            if (newHeight <= rect.height)
            {
                destRect.height = newHeight;
            }
            else
            {
                destRect.width = size.x * rect.height / size.y;
            }
        }
        else
        {
            destRect.width  = size.x;
            destRect.height = size.y;
        }

        if (destRect.width < rect.width)
        {
            destRect.x = rect.x + (rect.width - destRect.width) * 0.5f;
        }
        if (destRect.height < rect.height)
        {
            destRect.y = rect.y + (rect.height - destRect.height) * 0.5f;
        }

        GUI.DrawTexture(destRect, texture);
    }
    public static void Show( string title, dfAtlas atlas, string sprite, SelectionCallback callback )
    {
        if( atlas == null )
            throw new Exception( "No Texture Atlas was specified" );

        // Detect whether the user has deleted the textures after adding them to the Atlas
        if( atlas.Texture == null )
            throw new Exception( "The Texture Atlas does not have a texture or the texture was deleted" );

        var dialog = ScriptableWizard.DisplayWizard<dfSpriteSelectionDialog>( title );
        dialog.atlas = atlas;
        dialog.selectedSprite = sprite;
        dialog.minSize = new Vector2( 300, 200 );
        dialog.callback = callback;
        dialog.selectionShown = string.IsNullOrEmpty( sprite );
        dialog.ShowAuxWindow();
    }
Пример #25
0
        public void DoLocalize_dfSprite(string MainTranslation, string SecondaryTranslation)
        {
            if (mTarget_dfSprite.SpriteName == MainTranslation)
            {
                return;
            }

            //--[ Localize Atlas ]----------
            dfAtlas newAtlas = GetSecondaryTranslatedObj <dfAtlas>(ref MainTranslation, ref SecondaryTranslation);

            if (newAtlas != null)
            {
                mTarget_dfSprite.Atlas = newAtlas;
            }

            mTarget_dfSprite.SpriteName = MainTranslation;
            mTarget_dfSprite.MakePixelPerfect();
        }
Пример #26
0
 public dfMarkupStyle(dfDynamicFont Font, int FontSize, UnityEngine.FontStyle FontStyle)
 {
     this.Host               = null;
     this.Atlas              = null;
     this.Font               = Font;
     this.FontSize           = FontSize;
     this.FontStyle          = FontStyle;
     this.Align              = dfMarkupTextAlign.Left;
     this.VerticalAlign      = dfMarkupVerticalAlign.Baseline;
     this.Color              = UnityEngine.Color.white;
     this.BackgroundColor    = UnityEngine.Color.clear;
     this.TextDecoration     = dfMarkupTextDecoration.None;
     this.PreserveWhitespace = false;
     this.Preformatted       = false;
     this.WordSpacing        = 0;
     this.CharacterSpacing   = 0;
     this.lineHeight         = 0;
     this.Opacity            = 1f;
 }
Пример #27
0
 private dfMarkupBox createImageBox(dfAtlas atlas, string source, dfMarkupStyle style)
 {
     if (!source.ToLowerInvariant().StartsWith("http://"))
     {
         if ((atlas != null) && (atlas[source] != null))
         {
             dfMarkupBoxSprite sprite = new dfMarkupBoxSprite(this, dfMarkupDisplayType.inline, style);
             sprite.LoadImage(atlas, source);
             return(sprite);
         }
         Texture texture = dfMarkupImageCache.Load(source);
         if (texture != null)
         {
             dfMarkupBoxTexture texture2 = new dfMarkupBoxTexture(this, dfMarkupDisplayType.inline, style);
             texture2.LoadTexture(texture);
             return(texture2);
         }
     }
     return(null);
 }
Пример #28
0
    public static void Show(string title, dfAtlas atlas, string sprite, SelectionCallback callback)
    {
        if (atlas == null)
        {
            throw new Exception("No Texture Atlas was specified");
        }

        // Detect whether the user has deleted the textures after adding them to the Atlas
        if (atlas.Texture == null)
        {
            throw new Exception("The Texture Atlas does not have a texture or the texture was deleted");
        }

        var dialog = ScriptableWizard.DisplayWizard <dfSpriteSelectionDialog>(title);

        dialog.atlas          = atlas;
        dialog.selectedSprite = sprite;
        dialog.minSize        = new Vector2(300, 200);
        dialog.callback       = callback;
        dialog.selectionShown = string.IsNullOrEmpty(sprite);
        dialog.ShowAuxWindow();
    }
Пример #29
0
    private void addSelectedTextures(dfAtlas atlas)
    {
        var textures    = DragAndDrop.objectReferences.Where(x => x is Texture2D).Cast <Texture2D>().ToList();
        var notReadable = textures.Where(x => !isReadable(x)).OrderBy(x => x.name).Select(x => x.name).ToArray();
        var readable    = textures.Where(x => isReadable(x)).OrderBy(x => x.name).ToArray();

        if (!AddTexture(atlas, readable))
        {
            return;
        }

        var message = string.Format("{0} texture(s) added.", readable.Length);

        if (notReadable.Length > 0)
        {
            message += "\nThe following textures were not set to Read/Write and could not be added:\n\n\t";
            message += string.Join("\n\t", notReadable);
        }

        EditorUtility.DisplayDialog("Add Sprites", message, "OK");

        SelectedSprite = (readable.Length > 0) ? readable.First().name : "";
    }
Пример #30
0
    private bool showDeleteSelectedButton(dfAtlas atlas)
    {
        if (selectedTextures.Count > 0)
        {
            dfEditorUtil.DrawHorzLine();

            var buttonLabel = string.Format("Delete {0} sprites", selectedTextures.Count);
            if (GUILayout.Button(buttonLabel))
            {
                foreach (var key in selectedTextures.Keys)
                {
                    atlas[key].deleted = true;
                }

                rebuildAtlas(atlas);

                selectedTextures.Clear();

                return(true);
            }
        }

        return(false);
    }
        public static T SetupDfSpriteFromTexture <T>(this GameObject obj, Texture2D texture, Shader shader) where T : dfSprite
        {
            T       sprite = obj.GetOrAddComponent <T>();
            dfAtlas atlas  = obj.GetOrAddComponent <dfAtlas>();

            atlas.Material             = new Material(shader);
            atlas.Material.mainTexture = texture;
            atlas.Items.Clear();
            dfAtlas.ItemInfo info = new dfAtlas.ItemInfo
            {
                border       = new RectOffset(),
                deleted      = false,
                name         = "main_sprite",
                region       = new Rect(Vector2.zero, new Vector2(1, 1)),
                rotated      = false,
                sizeInPixels = new Vector2(texture.width, texture.height),
                texture      = null,
                textureGUID  = "main_sprite"
            };
            atlas.AddItem(info);
            sprite.Atlas      = atlas;
            sprite.SpriteName = "main_sprite";
            return(sprite);
        }
Пример #32
0
 internal static bool Equals(dfAtlas lhs, dfAtlas rhs)
 {
     return(object.ReferenceEquals(lhs, rhs) || (((lhs != null) && (rhs != null)) && (lhs.material == rhs.material)));
 }
Пример #33
0
        /// <summary>
        /// Gets the first empty space in <paramref name="atlas"/> that has at least the size of <paramref name="pixelScale"/>.
        /// </summary>
        /// <param name="atlas">The <see cref="dfAtlas"/> to find the empty space in.</param>
        /// <param name="pixelScale">The required size of the empty space.</param>
        /// <returns>The rect of the empty space divided by the atlas texture's size.</returns>
        public static Rect FindFirstValidEmptySpace(this dfAtlas atlas, IntVector2 pixelScale)
        {
            if (atlas == null || atlas.Texture == null || !atlas.Texture.IsReadable())
            {
                return(new Rect(0f, 0f, 0f, 0f));
            }
            Vector2Int     point      = new Vector2Int(0, 0);
            int            pointIndex = -1;
            List <RectInt> rects      = atlas.GetPixelRegions();

            //float x = 0;
            //float y = 0;


            while (true)
            {
                bool shouldContinue = false;
                foreach (RectInt rint in rects)
                {
                    if (rint.DoseOverlap(new RectInt(point, pixelScale.ToVector2Int())))
                    {
                        shouldContinue = true;
                        pointIndex++;
                        if (pointIndex >= rects.Count)
                        {
                            return(new Rect(0f, 0f, 0f, 0f));
                        }
                        point = rects[pointIndex].max + Vector2Int.one;
                        if (point.x > atlas.Texture.width || point.y > atlas.Texture.height)
                        {
                            atlas.ResizeAtlas(new IntVector2(atlas.Texture.width * 2, atlas.Texture.height * 2));
                        }
                        break;
                    }
                    bool shouldBreak = false;
                    foreach (RectInt rint2 in rects)
                    {
                        RectInt currentRect = new RectInt(point, pixelScale.ToVector2Int());
                        if (rint2.x < currentRect.x || rint2.y < currentRect.y)
                        {
                            continue;
                        }
                        else
                        {
                            if (currentRect.DoseOverlap(rint2))
                            {
                                shouldContinue = true;
                                shouldBreak    = true;
                                pointIndex++;
                                if (pointIndex >= rects.Count)
                                {
                                    return(new Rect(0f, 0f, 0f, 0f));
                                }
                                point = rects[pointIndex].max + Vector2Int.one;
                                if (point.x > atlas.Texture.width || point.y > atlas.Texture.height)
                                {
                                    atlas.ResizeAtlas(new IntVector2(atlas.Texture.width * 2, atlas.Texture.height * 2));
                                }
                                break;
                            }
                        }
                    }
                    if (shouldBreak)
                    {
                        break;
                    }
                }
                if (shouldContinue)
                {
                    continue;
                }
                RectInt currentRect2 = new RectInt(point, pixelScale.ToVector2Int());
                if (currentRect2.xMax > atlas.Texture.width || currentRect2.yMax > atlas.Texture.height)
                {
                    atlas.ResizeAtlas(new IntVector2(atlas.Texture.width * 2, atlas.Texture.height * 2));
                }
                break;
            }
            RectInt currentRect3 = new RectInt(point, pixelScale.ToVector2Int());
            Rect    rect         = new Rect((float)currentRect3.x / atlas.Texture.width, (float)currentRect3.y / atlas.Texture.height, (float)currentRect3.width / atlas.Texture.width, (float)currentRect3.height / atlas.Texture.height);

            return(rect);
        }
    private void EditAtlasReplacement( dfAtlas atlas )
    {
        var value = atlas.Replacement;

        dfPrefabSelectionDialog.SelectionCallback selectionCallback = delegate( GameObject item )
        {
            var newAtlas = ( item == null ) ? null : item.GetComponent<dfAtlas>();
            dfEditorUtil.MarkUndo( atlas, "Assign replacement Atlas" );
            atlas.Replacement = newAtlas;
        };

        EditorGUILayout.BeginHorizontal();
        {

            EditorGUILayout.LabelField( "Replacement", "", GUILayout.Width( dfEditorUtil.LabelWidth - 6 ) );

            GUILayout.Space( 2 );

            var displayText = value == null ? "[none]" : value.name;
            GUILayout.Label( displayText, "TextField" );

            var evt = Event.current;
            if( evt != null )
            {
                Rect textRect = GUILayoutUtility.GetLastRect();
                if( evt.type == EventType.mouseDown && evt.clickCount == 2 )
                {
                    if( textRect.Contains( evt.mousePosition ) )
                    {
                        if( GUI.enabled && value != null )
                        {
                            Selection.activeObject = value;
                            EditorGUIUtility.PingObject( value );
                        }
                    }
                }
                else if( evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform )
                {
                    if( textRect.Contains( evt.mousePosition ) )
                    {
                        var draggedObject = DragAndDrop.objectReferences.First() as GameObject;
                        var draggedAtlas = draggedObject != null ? draggedObject.GetComponent<dfAtlas>() : null;
                        DragAndDrop.visualMode = ( draggedAtlas != null ) ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.None;
                        if( evt.type == EventType.DragPerform )
                        {
                            selectionCallback( draggedObject );
                        }
                        evt.Use();
                    }
                }
            }

            if( GUI.enabled && GUILayout.Button( new GUIContent( " ", "Edit Atlas" ), "IN ObjectField", GUILayout.Width( 14 ) ) )
            {
                dfEditorUtil.DelayedInvoke( (System.Action)( () =>
                {
                    var dialog = dfPrefabSelectionDialog.Show( "Select Texture Atlas", typeof( dfAtlas ), selectionCallback, dfTextureAtlasInspector.DrawAtlasPreview, null );
                    dialog.previewSize = 200;
                } ) );
            }

        }
        EditorGUILayout.EndHorizontal();

        GUILayout.Space( 2 );
    }
    private void addSelectedTextures( dfAtlas atlas )
    {
        var textures = DragAndDrop.objectReferences.Where( x => x is Texture2D ).Cast<Texture2D>().ToList();
        var notReadable = textures.Where( x => !isReadable( x ) ).OrderBy( x => x.name ).Select( x => x.name ).ToArray();
        var readable = textures.Where( x => isReadable( x ) ).OrderBy( x => x.name ).ToArray();

        if( !AddTexture( atlas, readable ) )
        {
            return;
        }

        var message = string.Format( "{0} texture(s) added.", readable.Length );
        if( notReadable.Length > 0 )
        {
            message += "\nThe following textures were not set to Read/Write and could not be added:\n\n\t";
            message += string.Join( "\n\t", notReadable );
        }

        EditorUtility.DisplayDialog( "Add Sprites", message, "OK" );

        SelectedSprite = ( readable.Length > 0 ) ? readable.First().name : "";
    }
Пример #36
0
        internal void LoadImage( dfAtlas atlas, string source )
        {

        var spriteInfo = atlas[ source ];
        if( spriteInfo == null )
            throw new InvalidOperationException( "Sprite does not exist in atlas: " + source );

        this.Atlas = atlas;
        this.Source = source;

        this.Size = spriteInfo.sizeInPixels;
        this.Baseline = (int)Size.y;

        }
    private static Texture2D getTexture( dfAtlas atlas, string sprite )
    {
        var spriteInfo = atlas[ sprite ];
        if( spriteInfo == null )
            return null;

        var guid = atlas[ sprite ].textureGUID;
        if( string.IsNullOrEmpty( guid ) )
            return null;

        var path = AssetDatabase.GUIDToAssetPath( guid );
        if( string.IsNullOrEmpty( path ) )
            return null;

        return AssetDatabase.LoadAssetAtPath( path, typeof( Texture2D ) ) as Texture2D;
    }
Пример #38
0
    private static void ShowAtlasActions( dfAtlas atlas )
    {
        dfEditorUtil.DrawSeparator();

        EditorGUILayout.BeginHorizontal();
        {

            if( GUILayout.Button( "Rebuild" ) )
            {
                rebuildAtlas( atlas );
            }

            if( GUILayout.Button( "Refresh Views" ) )
            {
                dfGUIManager.RefreshAll( true );
            }

        }
        EditorGUILayout.EndHorizontal();
    }
 protected internal static void SelectFontDefinition( string label, dfAtlas atlas, dfGUIManager view, string propertyName, bool colorizeIfMissing )
 {
     SelectFontDefinition( label, atlas, view, propertyName, colorizeIfMissing, 95 );
 }
Пример #40
0
 internal static void DrawSprite( Rect rect, dfAtlas atlas, string sprite )
 {
     var spriteInfo = atlas[ sprite ];
     GUI.DrawTextureWithTexCoords( rect, atlas.Material.mainTexture, spriteInfo.region, true );
 }
    private static Texture2D getTexture( dfAtlas atlas, string sprite )
    {
        var guid = atlas[ sprite ].textureGUID;
        var path = AssetDatabase.GUIDToAssetPath( guid );

        return AssetDatabase.LoadAssetAtPath( path, typeof( Texture2D ) ) as Texture2D;
    }
    private static void previewAtlasTexture( dfAtlas atlas, Rect rect )
    {
        if( atlas == null )
            return;

        var texture = atlas.Texture;
        if( texture == null )
            return;

        var size = new Vector2( texture.width, texture.height );

        var destRect = rect;

        if( destRect.width < size.x || destRect.height < size.y )
        {

            var newHeight = size.y * rect.width / size.x;
            if( newHeight <= rect.height )
                destRect.height = newHeight;
            else
                destRect.width = size.x * rect.height / size.y;

        }
        else
        {
            destRect.width = size.x;
            destRect.height = size.y;
        }

        if( destRect.width < rect.width ) destRect.x = rect.x + ( rect.width - destRect.width ) * 0.5f;
        if( destRect.height < rect.height ) destRect.y = rect.y + ( rect.height - destRect.height ) * 0.5f;

        GUI.DrawTexture( destRect, texture );
    }
    private static void ShowAtlasActions( dfAtlas atlas )
    {
        dfEditorUtil.DrawSeparator();

        EditorGUILayout.BeginHorizontal();
        {

            if( atlas.generator == dfAtlas.TextureAtlasGenerator.TexturePacker )
            {
                if( GUILayout.Button( "Reimport" ) )
                {
                    dfTexturePackerImporter.Reimport( atlas );
                }
            }
            else if( GUILayout.Button( "Rebuild" ) )
            {
                rebuildAtlas( atlas );
            }

            if( GUILayout.Button( "Refresh Views" ) )
            {
                dfGUIManager.RefreshAll( true );
            }

        }
        EditorGUILayout.EndHorizontal();
    }
    private void ShowAddTextureOption( dfAtlas atlas )
    {
        dfEditorUtil.DrawSeparator();

        using( dfEditorUtil.BeginGroup( "Add Sprites" ) )
        {

            EditorGUILayout.HelpBox( "You can drag and drop textures here to add them to the Texture Atlas", MessageType.Info );

            var evt = Event.current;
            if( evt != null )
            {
                Rect dropRect = GUILayoutUtility.GetLastRect();
                if( evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform )
                {
                    if( dropRect.Contains( evt.mousePosition ) )
                    {
                        var draggedTexture = DragAndDrop.objectReferences.FirstOrDefault( x => x is Texture2D );
                        DragAndDrop.visualMode = ( draggedTexture != null ) ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.None;
                        if( evt.type == EventType.DragPerform )
                        {
                            addSelectedTextures( atlas );
                        }
                        evt.Use();
                    }
                }
            }

        }
    }
    private void EditAtlasOptions( dfAtlas atlas )
    {
        if( atlas.generator == dfAtlas.TextureAtlasGenerator.Internal )
        {

                using( dfEditorUtil.BeginGroup( "Global Options" ) )
                {

                    var packingMethodConfig = (dfTexturePacker.dfTexturePackingMethod)EditorPrefs.GetInt( "DaikonForge.AtlasPackingMethod", (int)dfTexturePacker.dfTexturePackingMethod.RectBestAreaFit );
                    var packingMethod = (dfTexturePacker.dfTexturePackingMethod)EditorGUILayout.EnumPopup( "Packing Method", packingMethodConfig );
                    if( packingMethod != packingMethodConfig )
                    {
                        EditorPrefs.SetInt( "DaikonForge.AtlasPackingMethod", (int)packingMethod );
                    }

                    var sizes = new string[] { "256", "512", "1024", "2048", "4096" };
                        var defaultIndex = Mathf.Max( 0, getIndex( sizes, dfTextureAtlasInspector.MaxAtlasSize.ToString() ) );
                        var selectedIndex = EditorGUILayout.Popup( "Max Size", defaultIndex, sizes );
                        dfTextureAtlasInspector.MaxAtlasSize = int.Parse( sizes[ selectedIndex ] );

                    var paddingConfig = EditorPrefs.GetInt( "DaikonForge.AtlasDefaultPadding", 2 );
                    var padding = Mathf.Max( 0, EditorGUILayout.IntField( "Padding", paddingConfig ) );
                    {
                        if( padding != paddingConfig )
                        {
                            EditorPrefs.SetInt( "DaikonForge.AtlasDefaultPadding", padding );
                        }
                    }

                    ForceSquare = EditorGUILayout.Toggle( "Force square", ForceSquare );

                    var extrudeSpritesConfig = EditorPrefs.GetBool( "DaikonForge.AtlasExtrudeSprites", false );
                    var extrudeSprites = EditorGUILayout.Toggle( "Extrude Edges", extrudeSpritesConfig );
                    {
                        if( extrudeSprites != extrudeSpritesConfig )
                        {
                            EditorPrefs.SetBool( "DaikonForge.AtlasExtrudeSprites", extrudeSprites );
                        }
                    }

                }

        }
        else if( atlas.generator == dfAtlas.TextureAtlasGenerator.TexturePacker )
        {

            using( dfEditorUtil.BeginGroup( "Imported Texture Atlas" ) )
            {

                var dataFilePath = AssetDatabase.GUIDToAssetPath( atlas.dataFileGUID );
                var dataFile = AssetDatabase.LoadAssetAtPath( dataFilePath, typeof( TextAsset ) ) as TextAsset;
                EditorGUILayout.ObjectField( "Image File", atlas.Texture, typeof( Texture2D ), false );
                EditorGUILayout.ObjectField( "Data File", dataFile, typeof( TextAsset ), false );

            }

        }

        using( dfEditorUtil.BeginGroup( "Atlas Options" ) )
        {
            EditAtlasReplacement( atlas );
        }
    }
    private bool showDeleteSelectedButton( dfAtlas atlas )
    {
        if( selectedTextures.Count > 0 )
        {

            dfEditorUtil.DrawHorzLine();

            var buttonLabel = string.Format( "Delete {0} sprites", selectedTextures.Count );
            if( GUILayout.Button( buttonLabel ) )
            {

                foreach( var key in selectedTextures.Keys )
                {
                    atlas[ key ].deleted = true;
                }

                rebuildAtlas( atlas );

                selectedTextures.Clear();

                return true;

            }

        }

        return false;
    }
    internal static void Reimport( dfAtlas atlas )
    {
        var textureFilePath = AssetDatabase.GUIDToAssetPath( atlas.imageFileGUID );
        if( !File.Exists( textureFilePath ) )
        {
            Debug.LogError( string.Format( "The image file for atlas {0} could not be found", atlas.name ), atlas );
            return;
        }

        var dataFilePath = AssetDatabase.GUIDToAssetPath( atlas.dataFileGUID );
        if( !File.Exists( dataFilePath ) )
        {
            Debug.LogError( string.Format( "The data file for atlas {0} could not be found", atlas.name ), atlas );
            return;
        }

        var dataFile = AssetDatabase.LoadAssetAtPath( dataFilePath, typeof( TextAsset ) ) as TextAsset;
        if( dataFile == null )
        {
            Debug.LogError( string.Format( "Faile to open the data file for the {0} atlas", atlas.name ), atlas );
            return;
        }

        var textureFile = AssetDatabase.LoadAssetAtPath( textureFilePath, typeof( Texture2D ) ) as Texture2D;
        if( textureFile == null )
        {
            Debug.LogError( string.Format( "Faile to open the image file for the {0} atlas", atlas.name ), atlas );
            return;
        }

        dfTextureAtlasInspector.setAtlasTextureSettings( textureFilePath, false );

        var uvx = 1f / textureFile.width;
        var uvy = 1f / textureFile.height;

        var newSprites = new List<dfAtlas.ItemInfo>();
        var oldSprites = atlas.Items;

        var data = JSON.JsonDecode( dataFile.text ) as DICT;
        var frames = data[ "frames" ] as DICT;
        foreach( var key in frames.Keys )
        {

            var itemData = frames[ key ] as DICT;

            var spriteName = Path.GetFileNameWithoutExtension( key );

            var isRotated = (bool)itemData[ "rotated" ];
            if( isRotated )
            {
                Debug.LogError( string.Format( "Sprite '{0}' is rotated. Rotated sprites are not yet supported", spriteName ) );
                continue;
            }

            var frameRect = extractUVRect( itemData[ "frame" ] as DICT, textureFile );
            var spriteSize = new Vector2( frameRect.width / uvx, frameRect.height / uvy );

            var sprite = new dfAtlas.ItemInfo()
            {
                name = spriteName,
                border = new RectOffset(),
                deleted = false,
                region = frameRect,
                rotated = false,
                sizeInPixels = spriteSize
            };
            newSprites.Add( sprite );

            for( int i = 0; i < oldSprites.Count; i++ )
            {
                var old = oldSprites[ i ];
                if( string.Equals( old.name, spriteName, StringComparison.OrdinalIgnoreCase ) )
                {
                    sprite.border = old.border;
                    break;
                }
            }

        }

        newSprites.Sort();
        atlas.Items.Clear();
        atlas.Items.AddRange( newSprites );

        var prefabPath = AssetDatabase.GetAssetPath( atlas );
        var go = atlas.gameObject;

        #region Delay execution of object selection to work around a Unity issue

        // Declared with null value to eliminate "uninitialized variable"
        // compiler error in lambda below.
        EditorApplication.CallbackFunction callback = null;

        callback = () =>
        {
            EditorUtility.FocusProjectWindow();
            go = AssetDatabase.LoadMainAssetAtPath( prefabPath ) as GameObject;
            Selection.objects = new UnityEngine.Object[] { go };
            EditorGUIUtility.PingObject( go );
            Debug.Log( "Texture Atlas prefab re-imported at " + prefabPath, go );
            EditorApplication.delayCall -= callback;
        };

        EditorApplication.delayCall += callback;

        #endregion
    }
Пример #48
0
    private dfMarkupBox createImageBox( dfAtlas atlas, string source, dfMarkupStyle style )
    {
        if( source.ToLowerInvariant().StartsWith( "http://" ) )
        {
            return null;
        }
        else if( atlas != null && atlas[ source ] != null )
        {

            var spriteBox = new dfMarkupBoxSprite( this, dfMarkupDisplayType.inline, style );
            spriteBox.LoadImage( atlas, source );

            return spriteBox;

        }
        else
        {
            var texture = dfMarkupImageCache.Load( source );
            if( texture != null )
            {

                var textureBox = new dfMarkupBoxTexture( this, dfMarkupDisplayType.inline, style );
                textureBox.LoadTexture( texture );

                return textureBox;

            }
        }

        return null;
    }
Пример #49
0
    public dfMarkupStyle( dfDynamicFont Font, int FontSize, FontStyle FontStyle )
    {
        Host = null;
        Atlas = null;

        this.Font = Font;
        this.FontSize = FontSize;
        this.FontStyle = FontStyle;

        Align = dfMarkupTextAlign.Left;
        VerticalAlign = dfMarkupVerticalAlign.Baseline;
        Color = UnityEngine.Color.white;
        BackgroundColor = UnityEngine.Color.clear;
        TextDecoration = dfMarkupTextDecoration.None;

        PreserveWhitespace = false;
        Preformatted = false;
        WordSpacing = 0;
        CharacterSpacing = 0;
        lineHeight = 0;
        Opacity = 1f;
    }
Пример #50
0
    private void drawSprite( Rect rect, dfAtlas.ItemInfo sprite )
    {
        var size = sprite.sizeInPixels;
        var destRect = rect;

        if( destRect.width < size.x || destRect.height < size.y )
        {

            var newHeight = size.y * rect.width / size.x;
            if( newHeight <= rect.height )
                destRect.height = newHeight;
            else
                destRect.width = size.x * rect.height / size.y;

        }
        else
        {
            destRect.width = size.x;
            destRect.height = size.y;
        }

        if( destRect.width < rect.width ) destRect.x = rect.x + ( rect.width - destRect.width ) * 0.5f;
        if( destRect.height < rect.height ) destRect.y = rect.y + ( rect.height - destRect.height ) * 0.5f;

        GUI.DrawTextureWithTexCoords( destRect, atlas.Material.mainTexture, sprite.region, true );
    }
    private void drawSprite( Rect areaRect, dfAtlas.ItemInfo sprite )
    {
        var size = sprite.sizeInPixels;
        var renderRect = areaRect;

        if( renderRect.width < size.x || renderRect.height < size.y )
        {

            var newHeight = size.y * areaRect.width / size.x;
            if( newHeight <= areaRect.height )
                renderRect.height = newHeight;
            else
                renderRect.width = size.x * areaRect.height / size.y;

        }
        else
        {
            renderRect.width = size.x;
            renderRect.height = size.y;
        }

        if( renderRect.width < areaRect.width ) renderRect.x = areaRect.x + ( areaRect.width - renderRect.width ) * 0.5f;
        if( renderRect.height < areaRect.height ) renderRect.y = areaRect.y + ( areaRect.height - renderRect.height ) * 0.5f;

        GUI.DrawTextureWithTexCoords( renderRect, atlas.Material.mainTexture, sprite.region, true );
    }
    protected internal static void SelectFontDefinition( string label, dfAtlas atlas, dfGUIManager view, string propertyName, bool colorizeIfMissing, int labelWidth )
    {
        var savedColor = GUI.color;
        var showDialog = false;

        try
        {

            GUI.enabled = ( atlas != null );

            var value = (dfFontBase)getValue( view, propertyName );

            if( value == null && colorizeIfMissing )
                GUI.color = EditorGUIUtility.isProSkin ? Color.yellow : Color.red;

            dfPrefabSelectionDialog.FilterCallback filterCallback = delegate( GameObject item )
            {

                if( atlas == null )
                    return false;

                var font = item.GetComponent<dfFontBase>();
                if( font == null )
                    return false;

                if( font is dfFont )
                {
                    var bitmappedFont = (dfFont)font;
                    if( bitmappedFont.Atlas == null || !dfAtlas.Equals( bitmappedFont.Atlas, atlas ) )
                        return false;
                }

                return true;

            };

            dfPrefabSelectionDialog.SelectionCallback selectionCallback = delegate( GameObject item )
            {
                var font = ( item == null ) ? null : item.GetComponent<dfFontBase>();
                dfEditorUtil.MarkUndo( view, "Change Font" );
                setValue( view, propertyName, font );
            };

            EditorGUILayout.BeginHorizontal();
            {

                EditorGUILayout.LabelField( label, "", GUILayout.Width( labelWidth ) );

                var displayText = value == null ? "[none]" : value.name;
                GUILayout.Label( displayText, "TextField" );

                var evt = Event.current;
                if( evt != null )
                {
                    Rect textRect = GUILayoutUtility.GetLastRect();
                    if( evt.type == EventType.mouseDown && evt.clickCount == 2 )
                    {
                        if( textRect.Contains( evt.mousePosition ) )
                        {
                            if( GUI.enabled && value != null )
                            {
                                Selection.activeObject = value;
                                EditorGUIUtility.PingObject( value );
                            }
                        }
                    }
                    else if( evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform )
                    {
                        if( textRect.Contains( evt.mousePosition ) )
                        {

                            var draggedObject = DragAndDrop.objectReferences.First() as GameObject;
                            var draggedFont =
                                ( draggedObject != null )
                                ? draggedObject.GetComponent<dfFontBase>()
                                : null;

                            DragAndDrop.visualMode =
                                ( draggedFont != null )
                                ? DragAndDropVisualMode.Copy
                                : DragAndDropVisualMode.None;

                            if( evt.type == EventType.DragPerform )
                            {
                                selectionCallback( draggedObject );
                            }

                            evt.Use();

                        }
                    }
                }

                if( GUI.enabled && GUILayout.Button( new GUIContent( " ", "Edit Font" ), "IN ObjectField", GUILayout.Width( 14 ) ) )
                {
                    showDialog = true;
                }

            }
            EditorGUILayout.EndHorizontal();

            if( value is dfDynamicFont || ( value is dfFont && !dfAtlas.Equals( atlas, ( (dfFont)value ).Atlas ) ) )
            {
                GUI.color = Color.white;
                EditorGUILayout.HelpBox( "The specified font uses a different Material, which could result in an additional draw call each time it is used.", MessageType.Warning );
            }

            GUILayout.Space( 2 );

            if( showDialog )
            {
                dfEditorUtil.DelayedInvoke( (System.Action)( () =>
                {
                    dfPrefabSelectionDialog.Show(
                        "Select Font",
                        typeof( dfFontBase ),
                        selectionCallback,
                        dfFontDefinitionInspector.DrawFontPreview,
                        filterCallback
                    );
                } ) );
            }

        }
        finally
        {
            GUI.enabled = true;
            GUI.color = savedColor;
        }
    }
 public void RemoveSprite( dfAtlas atlas, string spriteName )
 {
     selectedTextures.Clear();
     atlas[ spriteName ].deleted = true;
     rebuildAtlas( atlas );
 }
    internal static bool rebuildAtlas( dfAtlas atlas )
    {
        try
        {

            EditorUtility.DisplayProgressBar( "Rebuilding Texture Atlas", "Processing changes to the texture atlas...", 0 );

            var sprites = atlas.Items
                .Where( i => i != null && !i.deleted )
                .Select( i => new { source = i, texture = getTexture( i.textureGUID ) } )
                .Where( i => i.texture != null )
                .OrderByDescending( i => i.texture.width * i.texture.height )
                .ToList();

            var textures = sprites.Select( i => i.texture ).ToList();

            var oldAtlasTexture = atlas.Material.mainTexture;
            var texturePath = AssetDatabase.GetAssetPath( oldAtlasTexture );

            var padding = EditorPrefs.GetInt( "DaikonForge.AtlasDefaultPadding", 2 );

            var newAtlasTexture = new Texture2D( 0, 0, TextureFormat.RGBA32, false );
            var newRects = newAtlasTexture.PackTextures2( textures.ToArray(), padding, dfTextureAtlasInspector.MaxAtlasSize, dfTextureAtlasInspector.ForceSquare );

            byte[] bytes = newAtlasTexture.EncodeToPNG();
            System.IO.File.WriteAllBytes( texturePath, bytes );
            bytes = null;
            DestroyImmediate( newAtlasTexture );

            setAtlasTextureSettings( texturePath, false );

            // Fix up the new sprite locations
            for( int i = 0; i < sprites.Count; i++ )
            {
                sprites[ i ].source.region = newRects[ i ];
                sprites[ i ].source.sizeInPixels = new Vector2( textures[ i ].width, textures[ i ].height );
                sprites[ i ].source.texture = null;
            }

            // Remove any deleted sprites
            atlas.Items.RemoveAll( i => i.deleted );

            // Re-sort the Items collection
            atlas.Items.Sort();
            atlas.RebuildIndexes();

            EditorUtility.SetDirty( atlas );
            EditorUtility.SetDirty( atlas.Material );

            dfGUIManager.RefreshAll( true );

            return true;

        }
        catch( Exception err )
        {

            Debug.LogError( err.ToString(), atlas );
            EditorUtility.DisplayDialog( "Error Rebuilding Texture Atlas", err.Message, "OK" );

            return false;

        }
        finally
        {
            EditorUtility.ClearProgressBar();
        }
    }
    private void ShowModifiedTextures( dfAtlas atlas )
    {
        dfEditorUtil.DrawSeparator();

        var atlasPath = AssetDatabase.GetAssetPath( atlas.Texture );
        if( string.IsNullOrEmpty( atlasPath ) || !File.Exists( atlasPath ) )
        {
            EditorGUILayout.HelpBox( "Could not find the path associated with the Atlas texture", MessageType.Error );
            return;
        }

        var atlasModified = File.GetLastWriteTime( atlasPath );

        var modifiedSprites = new List<dfAtlas.ItemInfo>();

        for( int i = 0; i < atlas.Items.Count; i++ )
        {

            var sprite = atlas.Items[ i ];

            var spriteTexturePath = AssetDatabase.GUIDToAssetPath( sprite.textureGUID );
            if( string.IsNullOrEmpty( spriteTexturePath ) || !File.Exists( spriteTexturePath ) )
                continue;

            var spriteModified = File.GetLastWriteTime( spriteTexturePath );
            if( spriteModified > atlasModified )
            {
                modifiedSprites.Add( sprite );
            }

        }

        if( modifiedSprites.Count == 0 )
            return;

        using( dfEditorUtil.BeginGroup( "Modified Sprites" ) )
        {

            var list = string.Join( "\n\t", modifiedSprites.Select( s => s.name ).ToArray() );
            var message = string.Format( "The following textures have been modified:\n\t{0}", list );

            EditorGUILayout.HelpBox( message, MessageType.Info );

            var performUpdate = GUILayout.Button( "Refresh Modified Sprites" );
            dfEditorUtil.DrawSeparator();

            if( performUpdate )
            {
                rebuildAtlas( atlas );
            }

        }
    }
Пример #56
0
 private dfMarkupBox createImageBox(dfAtlas atlas, string source, dfMarkupStyle style)
 {
     if (source.ToLowerInvariant().StartsWith("http://"))
     {
         return null;
     }
     if (atlas != null && atlas[source] != null)
     {
         dfMarkupBoxSprite _dfMarkupBoxSprite = new dfMarkupBoxSprite(this, dfMarkupDisplayType.inline, style);
         _dfMarkupBoxSprite.LoadImage(atlas, source);
         return _dfMarkupBoxSprite;
     }
     Texture texture = dfMarkupImageCache.Load(source);
     if (texture == null)
     {
         return null;
     }
     dfMarkupBoxTexture _dfMarkupBoxTexture = new dfMarkupBoxTexture(this, dfMarkupDisplayType.inline, style);
     _dfMarkupBoxTexture.LoadTexture(texture);
     return _dfMarkupBoxTexture;
 }
Пример #57
0
    private void drawItem( Rect viewport, Rect rect, string name, dfAtlas.ItemInfo sprite )
    {
        if( !selectionShown && name == selectedSprite )
        {

            selectionShown = true;

            if( rect.yMax > viewport.yMax )
            {
                currentScrollPos = new Vector2( 0, rect.y - viewport.height + rect.height );
            }

        }

        var labelStyle = "ObjectPickerResultsGridLabel";
        if( name == selectedSprite )
        {

            var outlineRect = new Rect( rect.x - 3, rect.y - 3, rect.width + 6, rect.height + 6 );
            DrawBox( outlineRect, Color.blue );

            outlineRect = new Rect( rect.x - 1, rect.y - 1, rect.width + 2, rect.height + 2 );
            DrawBox( outlineRect, Color.white );

        }

        GUI.Box( rect, "", "ObjectPickerBackground" );
        if( sprite != null )
        {
            drawSprite( rect, sprite );
        }

        var savedColor = GUI.color;
        if( !string.IsNullOrEmpty( name ) && sprite == null )
        {
            labelStyle = "minibutton";
            GUI.color = Color.red;
        }

        var labelRect = new Rect( rect.x, rect.y + rect.height, rect.width, 18f );
        GUI.Label( labelRect, string.IsNullOrEmpty( name ) ? "None" : name, labelStyle );

        GUI.color = savedColor;

        var evt = Event.current;
        if( evt != null && evt.type == EventType.mouseDown )
        {

            if( rect.Contains( evt.mousePosition ) || labelRect.Contains( evt.mousePosition ) )
            {

                selectedSprite = name;
                this.Repaint();

                if( evt.clickCount == 2 )
                {
                    selectSprite( name );
                }

            }

        }
    }
    private void showSprites( dfAtlas atlas )
    {
        EditorGUILayout.Separator();

        GUILayout.Label( "Sprites", "HeaderLabel" );
        {

            if( showDeleteSelectedButton( atlas ) )
            {
                return;
            }

            for( int i = 0; i < atlas.Items.Count; i++ )
            {

                var sprite = atlas.Items[ i ];

                dfEditorUtil.DrawSeparator();

                EditorGUILayout.BeginHorizontal();
                {

                    bool isSelected = selectedTextures.ContainsKey( sprite.name );
                    if( EditorGUILayout.Toggle( isSelected, GUILayout.Width( 25 ) ) )
                    {
                        selectedTextures[ sprite.name ] = true;
                    }
                    else
                    {
                        selectedTextures.Remove( sprite.name );
                    }

                    var label = string.Format( "{0} ({1} x {2})", sprite.name, (int)sprite.sizeInPixels.x, (int)sprite.sizeInPixels.y );
                    GUILayout.Label( label, GUILayout.ExpandWidth( true ) );

                }
                EditorGUILayout.EndHorizontal();

                var removeSprite = false;
                EditorGUILayout.BeginHorizontal();
                {

                    if( GUILayout.Button( "Edit", GUILayout.Width( 75 ) ) )
                    {
                        SelectedSprite = sprite.name;
                    }

                    if( atlas.generator == dfAtlas.TextureAtlasGenerator.Internal && GUILayout.Button( "Delete", GUILayout.Width( 75 ) ) )
                    {
                        removeSprite = true;
                    }

                }
                EditorGUILayout.EndHorizontal();

                if( removeSprite )
                {
                    RemoveSprite( atlas, sprite.name );
                    continue;
                }

                var size = 75; // Mathf.Min( 75, Mathf.Max( sprite.sizeInPixels.x, sprite.sizeInPixels.y ) );
                var rect = GUILayoutUtility.GetRect( size, size );

                drawSprite( rect, atlas, sprite );

            }

        }

        showDeleteSelectedButton( atlas );
    }
    public bool AddTexture( dfAtlas atlas, params Texture2D[] newTextures )
    {
        try
        {

            selectedTextures.Clear();

            var addedItems = new List<dfAtlas.ItemInfo>();

            for( int i = 0; i < newTextures.Length; i++ )
            {

                // Grab reference to existing item, if it exists, to preserve border information
                var existingItem = atlas[ newTextures[ i ].name ];

                // Remove the existing item if it already exists
                atlas.Remove( newTextures[ i ].name );

                // Keep the texture size available
                var size = new Vector2( newTextures[ i ].width, newTextures[ i ].height );

                // Determine the guid for the texture
                var spritePath = AssetDatabase.GetAssetPath( newTextures[ i ] );
                var guid = AssetDatabase.AssetPathToGUID( spritePath );

                // Add the new texture to the Items collection
                var newItem = new dfAtlas.ItemInfo()
                {
                    textureGUID = guid,
                    name = newTextures[ i ].name,
                    border = ( existingItem != null ) ? existingItem.border : new RectOffset(),
                    sizeInPixels = size
                };
                addedItems.Add( newItem );
                atlas.AddItem( newItem );

            }

            if( !rebuildAtlas( atlas ) )
            {
                atlas.Items.RemoveAll( i => addedItems.Contains( i ) );
                return false;
            }

            return true;

        }
        catch( Exception err )
        {
            Debug.LogError( err.ToString(), atlas );
            EditorUtility.DisplayDialog( "Error Adding Sprite", err.Message, "OK" );
        }

        return false;
    }
    private static void DrawSprite( Rect rect, dfAtlas atlas, string sprite )
    {
        var spriteInfo = atlas[ sprite ];
        var size = spriteInfo.sizeInPixels;
        var destRect = rect;

        if( destRect.width < size.x || destRect.height < size.y )
        {

            var newHeight = size.y * rect.width / size.x;
            if( newHeight <= rect.height )
                destRect.height = newHeight;
            else
                destRect.width = size.x * rect.height / size.y;

        }
        else
        {
            destRect.width = size.x;
            destRect.height = size.y;
        }

        if( destRect.width < rect.width ) destRect.x = rect.x + ( rect.width - destRect.width ) * 0.5f;
        if( destRect.height < rect.height ) destRect.y = rect.y + ( rect.height - destRect.height ) * 0.5f;

        dfEditorUtil.DrawSprite( destRect, atlas, sprite );
    }