Exemple #1
0
    private void RefreshMaps()
    {
        _tilerMaps = Object.FindObjectsOfType(typeof(TilerMap)).Cast <TilerMap>().OrderBy(tile => tile.Layer).ToList();
        //_mapNames = _tilerMaps.Select(t => t.name).ToArray();

        var mIndex = -1;

        if (TilerMap != null)
        {
            var instanceID = TilerMap.GetInstanceID();

            for (int index = 0; index < _tilerMaps.Count; index++)
            {
                if (instanceID == _tilerMaps[index].GetInstanceID())
                {
                    mIndex = index;
                    break;
                }
            }
        }

        if (mIndex == -1)
        {
            if (_tilerMaps.Count > 0)
            {
                mIndex = 0;
            }
            SetMap(mIndex);
        }

        Repaint();
    }
    public static Cell Create(Point p, TilerMap tilerMap)
    {
        var cellName = GetName(p);

        var go = new GameObject(cellName);
        go.isStatic = true;
        var tr = go.transform;

        tr.parent = tilerMap.transform;

        var position = new Vector3
                           {
                               x = p.X * tilerMap.CellSize + tilerMap.TileSize / 2f,
                               y = 0,
                               z = p.Y * tilerMap.CellSize + tilerMap.TileSize / 2f
                           };

        tr.localPosition = position;

        var mf = go.AddComponent<MeshFilter>();

        if (tilerMap.SharedMesh == null)
            tilerMap.SharedMesh = CreatePlane.Create("_MESH", tilerMap.CellSize, tilerMap.CellSize);
        
        mf.sharedMesh = tilerMap.SharedMesh;

        var mr = go.AddComponent<MeshRenderer>();
        var bc = go.AddComponent<BoxCollider>();
        bc.size = new Vector3(tilerMap.CellSize, 0, tilerMap.CellSize);

        var t = new Texture2D(tilerMap.TextureResolution, tilerMap.TextureResolution, TextureFormat.ARGB32, true);
        var texName = cellName + "_TEX";
        t.name = texName;
        t.wrapMode = TextureWrapMode.Clamp;

        var c = Util.InitilizeArray(tilerMap.TextureResolution, new Color32(205, 205, 205, 0));
        t.SetPixels32(c);
        t.Apply();

        var shader = Shader.Find(tilerMap.DefaultShader);

        var m = new Material(shader);
        var matName = cellName + "_MAT";
        m.name = matName;

        m.mainTexture = t;
        m.renderQueue -= tilerMap.Layer;
        mr.sharedMaterial = m;

        var cell = go.AddComponent<Cell>();
        cell.Setup(tilerMap.TilesPerCell);

        return cell;
    }
Exemple #3
0
    public void OnCreate()
    {
        var go  = TilerMap.Create(Name, TileSize, TilesPerCell, TextureResolution, DefaultShader);
        var pos = go.transform.position;

        pos.y = _height;
        go.transform.position = pos;

        AssetDatabase.DeleteAsset(_path);
        PrefabUtility.CreatePrefab(_path, go, ReplacePrefabOptions.ConnectToPrefab);

        _onCreateCallback(go.GetComponent <TilerMap>());

        Close();
    }
Exemple #4
0
    private void OnNew(Object obj)
    {
        _newMap = obj as TilerMap;

        if (_newMap != null)
        {
            _newMap.Layer = 0;

            // sort by their order
            _tilerMaps.Sort((x, y) => x.Layer.CompareTo(y.Layer));

            foreach (var map in _tilerMaps)
            {
                var l = map.Layer;

                //map.transform.position += new Vector3(0, l * 0.1f, 0);

                foreach (var cell in map.Cells)
                {
                    if (cell.GetComponent <Renderer>() && cell.GetComponent <Renderer>().sharedMaterial)
                    {
                        cell.GetComponent <Renderer>().sharedMaterial.renderQueue += l;
                    }
                }
            }

            // then reset the order
            for (int index = 0; index < _tilerMaps.Count; index++)
            {
                var sort = _tilerMaps[index];
                sort.Layer = (index + 1);
            }

            foreach (var map in _tilerMaps)
            {
                var l = map.Layer;
                //map.transform.position -= new Vector3(0,l * 0.1f, 0);

                foreach (var cell in map.Cells)
                {
                    if (cell.GetComponent <Renderer>() && cell.GetComponent <Renderer>().sharedMaterial)
                    {
                        cell.GetComponent <Renderer>().sharedMaterial.renderQueue -= l;
                    }
                }
            }
        }
    }
Exemple #5
0
    private void GetGridPoint()
    {
        Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

        var   plane = new Plane(Vector3.up, Vector3.zero);
        float dist;

        if (!plane.Raycast(ray, out dist))
        {
            throw new UnityException("Ray missed. Shouldn't happen.");
        }

        var hitPoint = ray.GetPoint(dist);

        _currentPoint = TilerMap.GetWorldTileIDFromWorldCoords(hitPoint);

        Repaint();
    }
Exemple #6
0
    private void OnHierachyChange()
    {
        RefreshMaps();

        foreach (var map in _tilerMaps)
        {
            // check cells that are null
            var cells = map.Cells;
            for (var i = 0; i < cells.Count; i++)
            {
                var cell = cells[i];

                if (cell == null)
                {
                    cells.Remove(cell);
                    i--;
                }
            }
        }

        if (DuplicateCheck())
        {
            return;
        }

        // If new map has been set, match it
        if (_newMap)
        {
            for (var index = 0; index < _tilerMaps.Count; index++)
            {
                var m = _tilerMaps[index];

                if (_newMap == m)
                {
                    SetMap(index);
                    break;
                }
            }
            _newMap = null;
        }
    }
 public void Setup(TilerMap map)
 {
     _map = map;
 }
    /*private void Backup(TilerMap map)
    {
        var prefab = PrefabUtility.GetPrefabParent(map.gameObject);
        var mapPath = AssetDatabase.GetAssetPath(prefab);

        if (string.IsNullOrEmpty(mapPath))
        {
            return;
        }

        // Potential Backup
        var backupMapPath = mapPath + ".backup.prefab";
        var backup = AssetDatabase.LoadAssetAtPath(backupMapPath, typeof (GameObject)) as GameObject;

        if (backup == null)
        {
            PrefabUtility.CreatePrefab(backupMapPath, TilerMap.gameObject);
        }
        else
        {
            PrefabUtility.ReplacePrefab((GameObject)prefab, backup);
        }
    }*/

    private void SaveMap(TilerMap map)
    {
        var prefab = PrefabUtility.GetPrefabParent(map.gameObject);
        var mapPath = AssetDatabase.GetAssetPath(prefab);

        if (string.IsNullOrEmpty(mapPath))
        {
            Debug.LogError("Unable to save \"" + map.name + "\": Prefab has been deleted. Create a prefab, attach the gameobject and try save again.");

            // Set all cells to dirty so when attached, all will save out.
            foreach (var cell in map.Cells)
                cell.IsDirty = true;
            return;
        }

        // Check if we actually save anything. If not don't override prefab. This greatly improves performance.
        var isDoUpdate = false;

        // Setup paths
        var fullPath = Application.dataPath;
        var strippedPath = Path.GetDirectoryName(mapPath) + "/" + Path.GetFileNameWithoutExtension(mapPath) + "/";

        var index = fullPath.IndexOf("Assets", StringComparison.Ordinal);
        if (index == -1)
            return;

        fullPath = fullPath.Substring(0, index);
        fullPath += strippedPath;

        // Check if directory exists, if not create it
        if (!Directory.Exists(fullPath))
            Directory.CreateDirectory(fullPath);

        // We share the mesh between all cells
        if (!map.SharedMesh) return;

        if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(map.SharedMesh)))
        {
            AssetDatabase.DeleteAsset(strippedPath + map.SharedMesh.name + ".asset");
            AssetDatabase.CreateAsset(map.SharedMesh, strippedPath + map.SharedMesh.name + ".asset");
        }

        var meshAsset = (Mesh)AssetDatabase.LoadAssetAtPath(strippedPath + map.SharedMesh.name + ".asset", typeof(Mesh));

        foreach (var cell in map.Cells)
        {
            if (cell == null) continue;

            var go = cell.gameObject;
            if (!go.GetComponent<Renderer>()) continue;
            var mat = go.GetComponent<Renderer>().sharedMaterial;
            if (!mat) continue;

            // Render queue doesn't serialize out so we save it seperately.
            int renderQueue = mat.renderQueue;

            // Only update texture on changes
            if (cell.IsDirty)
            {
                cell.IsDirty = false;
                isDoUpdate = true;

                // Save the mesh as it may not have been done
                go.GetComponent<MeshFilter>().sharedMesh = meshAsset;

                var tex = (Texture2D) mat.mainTexture;

                // Store data before destroying
                var bytes = tex.EncodeToPNG();
                var texName = tex.name;

                // Clean up old texture - stop memory leaks
                Object.DestroyImmediate(tex, true);

                // First we save the texture as a png, this lets us modify import properties compared to saving it as an asset
                Util.SaveTextureToFile(bytes, strippedPath + texName + ".png");
                AssetDatabase.Refresh();
                // Load the now saved png 
                var texAsset = (Texture2D)AssetDatabase.LoadAssetAtPath(strippedPath + texName + ".png", typeof(Texture2D));

                // Assign texture importer settings
                var path = AssetDatabase.GetAssetPath(texAsset);
                EditorUtil.SetTextureImportSettings(path, TilerMap.TextureResolution);

                // Assign this new texture to the material
                mat.mainTexture = texAsset;

                // If material doesn't exist
                if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(mat)))
                {
                    AssetDatabase.DeleteAsset(strippedPath + mat.name + ".mat");
                    AssetDatabase.CreateAsset(mat, strippedPath + mat.name + ".mat");

                    // Load the new material
                    var matAsset = (Material) AssetDatabase.LoadAssetAtPath(strippedPath + mat.name + ".mat", typeof (Material));

                    // Assign this new material/mesh to the go
                    go.GetComponent<Renderer>().sharedMaterial = matAsset;
                }
            }

            // Always apply renderqueue update
            go.GetComponent<Renderer>().sharedMaterial.renderQueue = renderQueue;
        }

        var prefabMap = ((GameObject) prefab).GetComponent<TilerMap>();
        // do a check of tilermap properties to see if we need to update
        if (prefabMap.Layer != map.Layer || 
            prefabMap.DefaultShader != map.DefaultShader)
        {
            isDoUpdate = true;
        }

        // Only replace if something changed. Adds a lot of annoying checks but much better performance
        if (isDoUpdate)
            PrefabUtility.ReplacePrefab(map.gameObject, prefab, ReplacePrefabOptions.ConnectToPrefab);
    }
    private void OnHierachyChange()
    {
        RefreshMaps();

        foreach (var map in _tilerMaps)
        {
            // check cells that are null
            var cells = map.Cells;
            for (var i = 0; i < cells.Count; i++)
            {
                var cell = cells[i];

                if (cell == null)
                {
                    cells.Remove(cell);
                    i--;
                }
            }
        }

        if (DuplicateCheck()) return;

        // If new map has been set, match it
        if (_newMap)
        {
            for (var index = 0; index < _tilerMaps.Count; index++)
            {
                var m = _tilerMaps[index];

                if (_newMap == m)
                {
                    SetMap(index);
                    break;
                }
            }
            _newMap = null;
        }
    }
    private void OnNew(Object obj)
    {
        _newMap = obj as TilerMap;

        if (_newMap != null)
        {
            _newMap.Layer = 0;

            // sort by their order
            _tilerMaps.Sort((x, y) => x.Layer.CompareTo(y.Layer));

            foreach (var map in _tilerMaps)
            {
                var l = map.Layer;

                //map.transform.position += new Vector3(0, l * 0.1f, 0);

                foreach (var cell in map.Cells)
                {
                    if (cell.GetComponent<Renderer>() && cell.GetComponent<Renderer>().sharedMaterial)
                        cell.GetComponent<Renderer>().sharedMaterial.renderQueue += l;
                }
            }

            // then reset the order
            for (int index = 0; index < _tilerMaps.Count; index++)
            {
                var sort = _tilerMaps[index];
                sort.Layer = (index + 1);
            }

            foreach (var map in _tilerMaps)
            {
                var l = map.Layer;
                //map.transform.position -= new Vector3(0,l * 0.1f, 0);

                foreach (var cell in map.Cells)
                {
                    if (cell.GetComponent<Renderer>() && cell.GetComponent<Renderer>().sharedMaterial)
                        cell.GetComponent<Renderer>().sharedMaterial.renderQueue -= l;
                }
            }
        }
    }
Exemple #11
0
 public void Setup(TilerMap map)
 {
     _map = map;
 }
Exemple #12
0
    /*private void Backup(TilerMap map)
     * {
     *  var prefab = PrefabUtility.GetPrefabParent(map.gameObject);
     *  var mapPath = AssetDatabase.GetAssetPath(prefab);
     *
     *  if (string.IsNullOrEmpty(mapPath))
     *  {
     *      return;
     *  }
     *
     *  // Potential Backup
     *  var backupMapPath = mapPath + ".backup.prefab";
     *  var backup = AssetDatabase.LoadAssetAtPath(backupMapPath, typeof (GameObject)) as GameObject;
     *
     *  if (backup == null)
     *  {
     *      PrefabUtility.CreatePrefab(backupMapPath, TilerMap.gameObject);
     *  }
     *  else
     *  {
     *      PrefabUtility.ReplacePrefab((GameObject)prefab, backup);
     *  }
     * }*/

    private void SaveMap(TilerMap map)
    {
        var prefab  = PrefabUtility.GetPrefabParent(map.gameObject);
        var mapPath = AssetDatabase.GetAssetPath(prefab);

        if (string.IsNullOrEmpty(mapPath))
        {
            Debug.LogError("Unable to save \"" + map.name + "\": Prefab has been deleted. Create a prefab, attach the gameobject and try save again.");

            // Set all cells to dirty so when attached, all will save out.
            foreach (var cell in map.Cells)
            {
                cell.IsDirty = true;
            }
            return;
        }

        // Check if we actually save anything. If not don't override prefab. This greatly improves performance.
        var isDoUpdate = false;

        // Setup paths
        var fullPath     = Application.dataPath;
        var strippedPath = Path.GetDirectoryName(mapPath) + "/" + Path.GetFileNameWithoutExtension(mapPath) + "/";

        var index = fullPath.IndexOf("Assets", StringComparison.Ordinal);

        if (index == -1)
        {
            return;
        }

        fullPath  = fullPath.Substring(0, index);
        fullPath += strippedPath;

        // Check if directory exists, if not create it
        if (!Directory.Exists(fullPath))
        {
            Directory.CreateDirectory(fullPath);
        }

        // We share the mesh between all cells
        if (!map.SharedMesh)
        {
            return;
        }

        if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(map.SharedMesh)))
        {
            AssetDatabase.DeleteAsset(strippedPath + map.SharedMesh.name + ".asset");
            AssetDatabase.CreateAsset(map.SharedMesh, strippedPath + map.SharedMesh.name + ".asset");
        }

        var meshAsset = (Mesh)AssetDatabase.LoadAssetAtPath(strippedPath + map.SharedMesh.name + ".asset", typeof(Mesh));

        foreach (var cell in map.Cells)
        {
            if (cell == null)
            {
                continue;
            }

            var go = cell.gameObject;
            if (!go.GetComponent <Renderer>())
            {
                continue;
            }
            var mat = go.GetComponent <Renderer>().sharedMaterial;
            if (!mat)
            {
                continue;
            }

            // Render queue doesn't serialize out so we save it seperately.
            int renderQueue = mat.renderQueue;

            // Only update texture on changes
            if (cell.IsDirty)
            {
                cell.IsDirty = false;
                isDoUpdate   = true;

                // Save the mesh as it may not have been done
                go.GetComponent <MeshFilter>().sharedMesh = meshAsset;

                var tex = (Texture2D)mat.mainTexture;

                // Store data before destroying
                var bytes   = tex.EncodeToPNG();
                var texName = tex.name;

                // Clean up old texture - stop memory leaks
                Object.DestroyImmediate(tex, true);

                // First we save the texture as a png, this lets us modify import properties compared to saving it as an asset
                Util.SaveTextureToFile(bytes, strippedPath + texName + ".png");
                AssetDatabase.Refresh();
                // Load the now saved png
                var texAsset = (Texture2D)AssetDatabase.LoadAssetAtPath(strippedPath + texName + ".png", typeof(Texture2D));

                // Assign texture importer settings
                var path = AssetDatabase.GetAssetPath(texAsset);
                EditorUtil.SetTextureImportSettings(path, TilerMap.TextureResolution);

                // Assign this new texture to the material
                mat.mainTexture = texAsset;

                // If material doesn't exist
                if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(mat)))
                {
                    AssetDatabase.DeleteAsset(strippedPath + mat.name + ".mat");
                    AssetDatabase.CreateAsset(mat, strippedPath + mat.name + ".mat");

                    // Load the new material
                    var matAsset = (Material)AssetDatabase.LoadAssetAtPath(strippedPath + mat.name + ".mat", typeof(Material));

                    // Assign this new material/mesh to the go
                    go.GetComponent <Renderer>().sharedMaterial = matAsset;
                }
            }

            // Always apply renderqueue update
            go.GetComponent <Renderer>().sharedMaterial.renderQueue = renderQueue;
        }

        var prefabMap = ((GameObject)prefab).GetComponent <TilerMap>();

        // do a check of tilermap properties to see if we need to update
        if (prefabMap.Layer != map.Layer ||
            prefabMap.DefaultShader != map.DefaultShader)
        {
            isDoUpdate = true;
        }

        // Only replace if something changed. Adds a lot of annoying checks but much better performance
        if (isDoUpdate)
        {
            PrefabUtility.ReplacePrefab(map.gameObject, prefab, ReplacePrefabOptions.ConnectToPrefab);
        }
    }
Exemple #13
0
    private void MouseEvents()
    {
        var e = Event.current;

        var rect = Parent.position;

        rect.x      += 2;
        rect.y      += ToolbarHeight + 2;
        rect.width  -= RightWidth + 4;
        rect.height -= ToolbarHeight + 4;

        var mousePos = GUIUtility.GUIToScreenPoint(e.mousePosition);

        if (!rect.Contains(mousePos))
        {
            return;
        }

        // Left mouse button events
        if (Event.current.button == 0 && !NoRightMouseAltInput())
        {
            if (e.type == EventType.MouseDown)
            {
                TilerMapEditFunctions.Undo.NewUndo();

                Paint();
                _lastPlaced = _currentPoint;
                _isPainting = true;
            }
            if (e.type == EventType.MouseDrag)
            {
                if (_isPainting && _lastPlaced != _currentPoint)
                {
                    Paint();
                    _lastPlaced = _currentPoint;
                }
            }
        }

        // Right mouse button events
        if (Event.current.button == 1 || NoRightMouseAltInput())
        {
            if (e.type == EventType.MouseDown)
            {
                _isDraggingCopy = true;
                _startCopyPoint = _currentPoint;
            }
            if (e.type == EventType.MouseUp)
            {
                if (_isDraggingCopy)
                {
                    var properties = new List <Brush>();

                    var start = new Point
                    {
                        X = Math.Min(_currentPoint.X, _startCopyPoint.X),
                        Y = Math.Min(_currentPoint.Y, _startCopyPoint.Y)
                    };

                    var count = new Point
                    {
                        X = Math.Abs(_currentPoint.X - _startCopyPoint.X) + 1,
                        Y = Math.Abs(_currentPoint.Y - _startCopyPoint.Y) + 1
                    };

                    for (var y = start.Y; y < start.Y + count.Y; y++)
                    {
                        for (var x = start.X; x < start.X + count.X; x++)
                        {
                            var p = new Point(x, y);
                            properties.Add(TilerMap.GetTileBrush(p));
                        }
                    }

                    var copy = new CopyBrush(properties.ToArray(), new Point(count.X, count.Y));

                    if (DrawTool is PaintTool)
                    {
                        DrawTool.SetBrush(copy);
                    }
                    else
                    {
                        DrawTool = new PaintTool(this, copy);
                    }

                    Repaint();

                    _isDraggingCopy = false;
                }
            }
        }

        if (e.type == EventType.MouseDrag)
        {
            if (Event.current.button == 2)
            {
                PanWindow();
                Repaint();
            }
        }
        else if (e.type == EventType.ScrollWheel)
        {
            _height += Event.current.delta.y / 10f;
            _height  = Mathf.Clamp(_height, -1, 5);
            SetCameraHeight();
            Repaint();
        }

        if (e.type == EventType.MouseDrag || e.type == EventType.MouseMove || e.type == EventType.ScrollWheel)
        {
            GetGridPoint();
        }
    }
Exemple #14
0
 public TilerMapEdit(TilerMap tilerMap)
 {
     _tilerMap = tilerMap;
     Undo      = new UndoPaint(this);
 }
 public TilerMapEdit(TilerMap tilerMap)
 {
     _tilerMap = tilerMap;
     Undo = new UndoPaint(this);
 }
    public static Cell Create(Point p, TilerMap tilerMap)
    {
        var cellName = GetName(p);

        var go = new GameObject(cellName);

        go.isStatic = true;
        var tr = go.transform;

        tr.parent = tilerMap.transform;

        var position = new Vector3
        {
            x = p.X * tilerMap.CellSize + tilerMap.TileSize / 2f,
            y = 0,
            z = p.Y * tilerMap.CellSize + tilerMap.TileSize / 2f
        };

        tr.localPosition = position;

        var mf = go.AddComponent <MeshFilter>();

        if (tilerMap.SharedMesh == null)
        {
            tilerMap.SharedMesh = CreatePlane.Create("_MESH", tilerMap.CellSize, tilerMap.CellSize);
        }

        mf.sharedMesh = tilerMap.SharedMesh;

        var mr = go.AddComponent <MeshRenderer>();
        var bc = go.AddComponent <BoxCollider>();

        bc.size = new Vector3(tilerMap.CellSize, 0, tilerMap.CellSize);

        var t       = new Texture2D(tilerMap.TextureResolution, tilerMap.TextureResolution, TextureFormat.ARGB32, true);
        var texName = cellName + "_TEX";

        t.name     = texName;
        t.wrapMode = TextureWrapMode.Clamp;

        var c = Util.InitilizeArray(tilerMap.TextureResolution, new Color32(205, 205, 205, 0));

        t.SetPixels32(c);
        t.Apply();

        var shader = Shader.Find(tilerMap.DefaultShader);

        var m       = new Material(shader);
        var matName = cellName + "_MAT";

        m.name = matName;

        m.mainTexture     = t;
        m.renderQueue    -= tilerMap.Layer;
        mr.sharedMaterial = m;

        var cell = go.AddComponent <Cell>();

        cell.Setup(tilerMap.TilesPerCell);

        return(cell);
    }