void AddTileToLayerMenu(TileAtlas atlas, TileAtlas.TagLayer layer, Event e)
        {
            GenericMenu menu = new GenericMenu();

            menu.AddDisabledItem(new GUIContent("Tile from other layer [Not Implemented]"));
            menu.AddDisabledItem(new GUIContent("Tile from project files [Not Implemented]"));
            menu.AddDisabledItem(new GUIContent("Generate Tile from Gameobject [Not Implemented]"));
            menu.AddItem(new GUIContent("Drag and Drop files here!"), true, () => { });
            menu.ShowAsContext();
            e.Use();
        }
 bool CheckForRequirements()
 {
     if (!t)
     {
         EditorGUILayout.HelpBox("Please Create LevelBuilder in Scene", MessageType.Warning);
         if (GUILayout.Button("Create LevelBuilder"))
         {
             var go = new GameObject("Level Builder");
             _t = go.AddComponent <LevelBuilder>();
         }
         return(false);
     }
     if (!t.tileSet)
     {
         EditorGUILayout.HelpBox("Please Apply TileAtlas to LevelBuilder", MessageType.Warning);
         if (GUILayout.Button("Create New Tile Atlas"))
         {
             var tileAtlas = CreateInstance <TileAtlas>();
             var path      = EditorUtility.SaveFilePanelInProject("New TileAtlas", "My Tile Atlas", "asset", "Choose destination of new asset");
             AssetDatabase.CreateAsset(tileAtlas, path);
             AssetDatabase.Refresh();
             t.tileSet = (TileAtlas)AssetDatabase.LoadAssetAtPath(path, typeof(TileAtlas));
             EditorGUIUtility.PingObject(t.tileSet);
         }
         TileAtlas chosen = null;
         chosen = (TileAtlas)EditorGUILayout.ObjectField("Use Preexisting ", chosen, typeof(TileAtlas), false);
         if (chosen)
         {
             t.tileSet = chosen;
         }
         return(false);
     }
     if (t.tileSet.tiles == null || t.tileSet.tiles.Count == 0)
     {
         EditorGUILayout.HelpBox("Please add Tiles to TileAtlas", MessageType.Warning);
         if (GUILayout.Button("Ping Atlas"))
         {
             EditorGUIUtility.PingObject(t.tileSet);
         }
         return(false);
     }
     if (t.tileSet.TileFromGuid == null || t.tileSet.TileFromGuid.Keys.Count == 0)
     {
         EditorGUILayout.HelpBox("Please click 'Dictionary from List' in TileAtlas", MessageType.Warning);
         if (GUILayout.Button("Ping Atlas"))
         {
             EditorGUIUtility.PingObject(t.tileSet);
         }
         return(false);
     }
     return(true);
 }
        void LayerRightClickMenu(Event e, int index, TileAtlas atlas)
        {
            GenericMenu menu = new GenericMenu();

            menu.AddItem(new GUIContent("Remove Layer " + index + ":" + atlas.layers[index].name), false, () =>
            {
                atlas.RemoveLayer(atlas.layers[index]);
                t.RemoveLayer(index);
                paletteIndex = 0;
                layerIndex--;
            });
            menu.AddItem(new GUIContent("Delete all objects at " + index + ":" + atlas.layers[index].name), false, () =>
            {
                t.ClearLayer(index);
            });
            menu.AddItem(new GUIContent("Change Layer Color"), false, () =>
            {
                atlas.layers[index].color = UnityEngine.Random.ColorHSV(0f, 1f, 0.5f, 0.5f, 0.6f, 0.8f);
            });
            menu.ShowAsContext();
            e.Use();
        }
 public void ChangeTileToLayer(TileAtlas atlas, int i2, TileObject buttonTileObject)
 {
     Debug.Log(i2 + ":" + atlas.layers.Count + " obj: " + buttonTileObject.name);
     atlas.layers[i2].layerObjects.Add(buttonTileObject);
 }
        void TileRightClickMenu(Event e, TileObject buttonTileObject, TileAtlas atlas)
        {
            GenericMenu menu = new GenericMenu();

            menu.AddItem(new GUIContent("Select Tile Object"), false, () =>
            {
                Selection.activeObject = buttonTileObject;
            });

            menu.AddItem(new GUIContent("Select linked Prefab"), false, () =>
            {
                Selection.activeObject = buttonTileObject.prefabs[0];
            });

            for (int i = 0; i < atlas.layers.Count; i++)
            {
                if (i == layerIndex)
                {
                    continue;
                }
                int weird = i;
                menu.AddItem(new GUIContent("Move to Layer/Layer " + weird + " : " + atlas.layers[weird].name), false, () =>
                {
                    Debug.Log(weird + ":" + atlas.layers.Count + " obj: " + buttonTileObject.name);
                    atlas.MoveTileToLayer(buttonTileObject, atlas.layers[weird]);
                    t.MoveExistingTilesToLayer(buttonTileObject, layerIndex, weird);
                });
            }

            menu.AddItem(new GUIContent("Remove/Clear Tiles from Layer"), false, () =>
            {
                if (layerIndex > 0 && layerIndex < atlas.layers.Count)
                {
                    t.RemovePlacedTiles(buttonTileObject, layerIndex);
                }
            });
            menu.AddItem(new GUIContent("Remove/Clear Tiles from Layer and move to Unsorted"), false, () =>
            {
                if (layerIndex > 0 && layerIndex < atlas.layers.Count)
                {
                    t.RemovePlacedTiles(buttonTileObject, layerIndex);
                    atlas.RemoveTileFromLayer(buttonTileObject, atlas.layers[layerIndex]);
                }
            });
            menu.AddItem(new GUIContent("Remove/Clear Tiles and remove from Atlas"), false, () =>
            {
                if (layerIndex > 0 && layerIndex < atlas.layers.Count)
                {
                    t.RemovePlacedTiles(buttonTileObject, layerIndex);
                    atlas.RemoveTileFromLayer(buttonTileObject, atlas.layers[layerIndex]);
                }
                atlas.RemoveFromAtlas(buttonTileObject);
            });
            // ----------------- disabled multi layer support for now and see if a need arises -----------------//
            //for (int i = 0; i < atlas.layers.Count; i++)
            //{
            //    if (i == layerIndex) continue;
            //    int weird = i;
            //    menu.AddItem(new GUIContent("Add to Layer/Layer " + weird +" : "+atlas.layers[weird].name), false, () =>
            //    {
            //        Debug.Log(weird + ":" + atlas.layers.Count + " obj: " + buttonTileObject.name);
            //        atlas.MoveTileToLayer(buttonTileObject, atlas.layers[weird], true);
            //    });
            //}
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("Move to and create new Layer"), false, () =>
            {
                atlas.AddTagLayer();
                atlas.MoveTileToLayer(buttonTileObject, atlas.layers[atlas.layers.Count - 1]);
            });
            menu.ShowAsContext();

            e.Use();
        }
        void DrawOnScreenPalette()
        {
            bool      guiChangedBefore = GUI.changed;
            TileAtlas atlas            = t.tileSet;

            TileAtlas.TagLayer activeLayer = layerIndex == -1 ? atlas.defaultLayer : (layerIndex < atlas.layers.Count) ? atlas.layers[layerIndex] : atlas.defaultLayer;
            if (activeLayer == atlas.defaultLayer)
            {
                return;
            }

            float scrollBarSize = GUI.skin.verticalScrollbar.fixedWidth;

            ChangeVerticalScrollbar(6);

            onScreenPaletteScroll = EditorGUILayout.BeginScrollView(onScreenPaletteScroll, GUILayout.Width(52));
            List <GUIContent> paletteIcons = new List <GUIContent>();

            int maximumPreviewImages = 60;

            for (int i = 0; i < atlas.layers.Count; i++)
            {
                var layer = atlas.layers[i];
                if (paletteVisibility == null || paletteVisibility.Length == 0)
                {
                    _paletteVis = new bool[t.tileSet.layers.Count];
                }
                if (paletteVisibility[i] || layer == activeLayer)
                {
                    foreach (var atlasTile in layer.layerObjects)
                    {
                        // Get a preview for the prefab
                        if (!atlasTile || atlasTile.prefabs.Length == 0)
                        {
                            continue;
                        }
                        if (layer.layerObjects.Count > maximumPreviewImages)
                        {
                            paletteIcons.Add(new GUIContent(atlasTile.name));
                        }
                        else
                        {
                            Texture2D texture = AssetPreview.GetAssetPreview(atlasTile.prefabs[0]);
                            paletteIcons.Add(new GUIContent(texture));
                        }
                    }
                }
            }
            Rect    screenPaletteBox   = GUILayoutUtility.GetRect(40, paletteIcons.Count * 40, "CN Box");
            int     previousItems      = 0;
            Vector2 layerIndicatorSize = new Vector2(5, 40);

            for (int i = 0; i < atlas.layers.Count; i++)
            {
                if (paletteVisibility[i] || i == layerIndex)
                {
                    for (int j = 0; j < atlas.layers[i].layerObjects.Count; j++)
                    {
                        if (i == layerIndex && j == paletteIndex)
                        {
                            EditorGUI.DrawRect(new Rect(screenPaletteBox.position + Vector2.up * previousItems * 40, layerIndicatorSize), atlas.layers[i].color + Color.gray);
                        }
                        else
                        {
                            EditorGUI.DrawRect(new Rect(screenPaletteBox.position + Vector2.up * previousItems * 40, layerIndicatorSize), atlas.layers[i].color);
                        }
                        previousItems++;
                    }
                }
            }
            screenPaletteBox.position += Vector2.right * 5;
            int gridIndex = GUI.SelectionGrid(screenPaletteBox, GetIndexFromPaletteIndex(paletteIndex), paletteIcons.ToArray(), 1, "CN Box");
            int layerIndexFromPalette;

            EditorGUILayout.EndScrollView();
            ChangeVerticalScrollbar(scrollBarSize);
            if (!guiChangedBefore && GUI.changed)
            {
                paletteIndex = GetPaletteIndexFromIndex(gridIndex, out layerIndexFromPalette);
                layerIndex   = layerIndexFromPalette;
                Repaint();
            }

            int GetPaletteIndexFromIndex(int i, out int newLayerIndex)
            {
                int indexInPalette = 0;
                int itemsBefore    = 0;

                for (int layer = 0; layer < paletteVisibility.Length; layer++)
                {
                    if (paletteVisibility[layer] || layer == layerIndex)
                    {
                        itemsBefore += atlas.layers[layer].layerObjects.Count;
                        if (itemsBefore > i)
                        {
                            indexInPalette = i - (itemsBefore - atlas.layers[layer].layerObjects.Count);
                            newLayerIndex  = layer;
                            //Debug.Log(newLayerIndex);
                            return(indexInPalette);
                        }
                    }
                }
                newLayerIndex = 0;
                return(0);
            }

            int GetIndexFromPaletteIndex(int pIndex)
            {
                int offset = 0;

                for (int i = 0; i < layerIndex; i++)
                {
                    if (paletteVisibility[i])
                    {
                        offset += atlas.layers[i].layerObjects.Count;
                    }
                }
                return(pIndex + offset);
            }
        }
        void DrawPalette(TileAtlas atlas, Event e)
        {
            TileAtlas.TagLayer activeLayer = layerIndex == -1 ? atlas.defaultLayer : (layerIndex < atlas.layers.Count) ? atlas.layers[layerIndex] : atlas.defaultLayer;
            //DragTest
            //Rect myRect = GUILayoutUtility.GetRect(100, 40, GUILayout.ExpandWidth(true));
            //GUI.Box(myRect, "Drag and Drop Prefabs to this Box!");
            //if (myRect.Contains(e.mousePosition))
            //{
            //    if (e.type == EventType.DragUpdated)
            //    {
            //        DragAndDrop.visualMode = DragAndDropVisualMode.Move;
            //        //Debug.Log("Drag Updated!");
            //        e.Use();
            //    }
            //    else if (e.type == EventType.DragPerform)
            //    {
            //        DragAndDrop.AcceptDrag();
            //        Debug.Log("Drag Perform!");
            //        Debug.Log(DragAndDrop.objectReferences.Length);
            //        if (atlas.layers.Count > 0)
            //            for (int i = 0; i < DragAndDrop.objectReferences.Length; i++)
            //            {
            //                atlas.layers[0].layerObjects.Add(DragAndDrop.objectReferences[i] as TileObject);
            //            }
            //        e.Use();
            //    }
            //}
            //if (e.type == EventType.DragExited || e.type == EventType.MouseUp)
            //{
            //    //Debug.Log("Drag exited");
            //    DragAndDrop.PrepareStartDrag();
            //}
            //------
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.BeginVertical();
            Color guiColor = GUI.color;

            //EditorGUIUtility.IconContent("Settings")
            if (GUILayout.Button("Ξ", GUILayout.Width(18), GUILayout.Height(activeLayer == atlas.defaultLayer ? 60 : 30)))
            {
                layerIndex = -1;
            }
            for (int i = 0; i < atlas.layers.Count; i++)
            {
                int index = i;
                GUI.color = atlas.layers[i].color;
                Rect buttonRect = GUILayoutUtility.GetRect(new GUIContent(i.ToString()), "Button", GUILayout.Width(18), GUILayout.Height(activeLayer == atlas.layers[i] ? 60 : 30));
                if (GUI.Button(buttonRect, i.ToString()))
                {
                    layerIndex = i;
                    if (e.button == 1)
                    {
                        LayerRightClickMenu(e, index, atlas);
                    }
                }
            }
            GUI.color = guiColor;
            if (GUILayout.Button("+", GUILayout.Width(18), GUILayout.Height(18)))
            {
                atlas.AddTagLayer();
            }
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical();
            if (activeLayer != atlas.defaultLayer)
            {
                bool changedBefore = GUI.changed;
                activeLayer.name = EditorGUILayout.TextField(activeLayer.name);
                if (!changedBefore && GUI.changed)
                {
                    UnityEditor.EditorUtility.SetDirty(atlas);
                }
            }
            else
            {
                EditorGUILayout.HelpBox("Unsorted objects, rightclick and move to a layer to use.", MessageType.Info, true);
            }

            if (layerIndex >= 0 && layerIndex < atlas.layers.Count)
            {
                //activeLayer.rasterSize = EditorGUILayout.Vector3Field("raster ", activeLayer.rasterSize);
                bool changedBefore = GUI.changed;
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Rastersize");
                activeLayer.rasterSize.x = EditorGUILayout.DelayedFloatField(activeLayer.rasterSize.x);
                activeLayer.rasterSize.y = EditorGUILayout.DelayedFloatField(activeLayer.rasterSize.y);
                activeLayer.rasterSize.z = EditorGUILayout.DelayedFloatField(activeLayer.rasterSize.z);
                EditorGUILayout.EndHorizontal();
                if (!changedBefore && GUI.changed)
                {
                    t.UpdateTilePositionsOnLayer(activeLayer, layerIndex);
                }
            }

            if (activeLayer != atlas.defaultLayer && activeLayer.layerObjects.Count == 0)
            {
                EditorGUILayout.HelpBox("Drag and Drop Tiles here.", MessageType.Info, true); return;
            }

            //-----
            EditorGUILayout.Vector2Field("scroll", paletteScroll);
            float columnCount = 4f;
            float panelSize   = (position.width - 60) / columnCount;

            paletteScroll = EditorGUILayout.BeginScrollView(paletteScroll);
            List <GUIContent> paletteIcons     = new List <GUIContent>();
            float             enumerationCount = 0;

            if (activeLayer == atlas.defaultLayer)
            {
                foreach (var atlasTile in atlas.TileFromGuid.Values)
                {
                    // Get a preview for the prefab
                    if (!atlasTile)
                    {
                        continue;
                    }

                    Vector2 yValues = new Vector2(Mathf.Floor(enumerationCount / columnCount) * panelSize,
                                                  Mathf.Floor(enumerationCount / columnCount) * panelSize + panelSize);
                    if (yValues.x < paletteScroll.y - panelSize || yValues.y > paletteScroll.y + panelSize * 4 + panelSize) //(atlas.tiles.Count > maximumPreviewImages)
                    {
                        paletteIcons.Add(new GUIContent(atlasTile.name));
                    }
                    else
                    {
                        Texture2D texture = null;
                        if (atlasTile.prefabs.Length != 0)
                        {
                            texture = AssetPreview.GetAssetPreview(atlasTile.prefabs[0]);
                        }
                        paletteIcons.Add(texture ? new GUIContent(texture) : new GUIContent("No Preview Available"));
                    }
                    enumerationCount++;
                }
                if (paletteIcons.Count == 0)
                {
                    EditorGUILayout.HelpBox("No unsorted tiles in atlas", MessageType.Info);
                }
            }
            else
            {
                foreach (var atlasTile in activeLayer.layerObjects)
                {
                    // Get a preview for the prefab
                    if (!atlasTile)
                    {
                        continue;
                    }
                    Vector2 yValues = new Vector2(Mathf.Floor(enumerationCount / columnCount) * panelSize,
                                                  Mathf.Floor(enumerationCount / columnCount) * panelSize + panelSize);
                    if (yValues.x < paletteScroll.y - panelSize || yValues.y > paletteScroll.y + panelSize * 4 + panelSize)
                    {
                        paletteIcons.Add(new GUIContent(atlasTile.name));
                        //paletteIcons.Add(new GUIContent($"{enumerationCount} : {yValues}"));
                    }
                    else
                    {
                        Texture2D texture = null;
                        if (atlasTile.prefabs.Length != 0)
                        {
                            texture = AssetPreview.GetAssetPreview(atlasTile.prefabs[0]);
                        }
                        paletteIcons.Add(texture ? new GUIContent(texture) : new GUIContent("No Preview Available"));
                    }
                    enumerationCount++;
                }
            }

            if (activeLayer != atlas.defaultLayer)
            {
                paletteIcons.Add(EditorGUIUtility.IconContent("Toolbar Plus"));
            }
            // Display the grid

            //paletteIndex = GUILayout.SelectionGrid(paletteIndex, paletteIcons.ToArray(), 4, GUILayout.Width(position.width-38));

            EditorGUILayout.BeginHorizontal();
            GUIStyle iconLabel = new GUIStyle("Label");

            iconLabel.alignment        = TextAnchor.UpperCenter;
            iconLabel.normal.textColor = Color.grey;
            for (int i = 0; i < paletteIcons.Count; i++)
            {
                Rect       buttonRect       = GUILayoutUtility.GetRect(paletteIcons[i], "Button", GUILayout.Width(panelSize), GUILayout.Height(panelSize));
                TileObject buttonTileObject = activeLayer == atlas.defaultLayer ? atlas.tiles[i] : i < activeLayer.layerObjects.Count ? activeLayer.layerObjects[i] : null;
                bool       clickHere        = false;
                if (buttonRect.Contains(e.mousePosition))
                {
                    switch (e.type)
                    {
                    //case EventType.MouseDrag:
                    //    DragAndDrop.PrepareStartDrag();

                    //    DragAndDrop.SetGenericData("TileObject", buttonTileObject);
                    //    DragAndDrop.objectReferences = new Object[] { buttonTileObject };
                    //    DragAndDrop.StartDrag("Drag");
                    //    break;
                    //case EventType.DragExited:
                    //    clickHere = true;
                    //    break;
                    case EventType.MouseDown:
                        clickHere = true;
                        break;
                    }
                }
                TileAtlas.TagLayer tileLayer = null;
                foreach (var layer in atlas.layers)
                {
                    if (layer.layerObjects.Contains(buttonTileObject))
                    {
                        tileLayer = layer;
                        break;
                    }
                }

                GUI.backgroundColor = tileLayer != null?tileLayer.color:guiColor;
                GUI.Toggle(buttonRect, paletteIndex == i, paletteIcons[i], "Button");
                if (buttonTileObject)
                {
                    GUI.Label(buttonRect, buttonTileObject.name, iconLabel);
                }
                if (clickHere)
                {
                    paletteIndex = i;
                    if (activeLayer == atlas.defaultLayer)
                    {
                        Selection.activeObject = buttonTileObject;
                    }
                    if (activeLayer != atlas.defaultLayer && i == paletteIcons.Count - 1)
                    {
                        AddTileToLayerMenu(atlas, activeLayer, e);
                        paletteIndex = 0;
                    }
                    else if (e.button == 1)  // rightclick
                    {
                        TileRightClickMenu(e, buttonTileObject, atlas);
                    }
                }
                if (i % (int)(columnCount) == columnCount - 1)// && i != 0)
                {
                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.BeginHorizontal();
                }
            }
            EditorGUILayout.EndHorizontal();

            if (activeLayer == atlas.defaultLayer)
            {
                selectedTileGuid = atlas.tiles[paletteIndex].guid;
            }
            else
            {
                if (paletteIndex >= activeLayer.layerObjects.Count)
                {
                    paletteIndex = 0;
                }
                if (activeLayer.layerObjects[paletteIndex])
                {
                    selectedTileGuid = activeLayer.layerObjects[paletteIndex].guid;
                }
                else
                {
                    selectedTileGuid = "";
                }
            }
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndHorizontal();
            GUI.backgroundColor = guiColor;
        }