Ejemplo n.º 1
0
        private void Initialize(XDocument document, bool makeUnique, string fullPath, string mapPath, Material baseTileMaterial, int sortingOrder)
        {
            XElement mapNode = document.Root;
            Version = mapNode.Attribute("version").Value;
            Orientation = (Orientation)Enum.Parse(typeof(Orientation), mapNode.Attribute("orientation").Value, true);
            Width = int.Parse(mapNode.Attribute("width").Value, CultureInfo.InvariantCulture);
            Height = int.Parse(mapNode.Attribute("height").Value, CultureInfo.InvariantCulture);
            TileWidth = int.Parse(mapNode.Attribute("tilewidth").Value, CultureInfo.InvariantCulture);
            TileHeight = int.Parse(mapNode.Attribute("tileheight").Value, CultureInfo.InvariantCulture);

            if (_mapName == null)
                _mapName = "Map";

            if (!mapPath.EndsWith("/"))
                mapPath = mapPath + "/";

            MapObject = new GameObject(_mapName);
            MapObject.transform.parent = Parent.transform;
            MapObject.transform.localPosition = Vector3.zero;

            DefaultSortingOrder = sortingOrder;

            XElement propertiesElement = mapNode.Element("properties");
            if (propertiesElement != null)
                Properties = new PropertyCollection(propertiesElement);

            TileSets = new List<TileSet>();
            Tiles = new Dictionary<int, Tile>();
            foreach (XElement tileSet in mapNode.Descendants("tileset"))
            {
                if (tileSet.Attribute("source") != null)
                {
                    TextAsset externalTileSetTextAsset = (TextAsset)Resources.Load(mapPath + Path.GetFileNameWithoutExtension(tileSet.Attribute("source").Value));

                    XDocument externalTileSet = XDocument.Parse(externalTileSetTextAsset.text);

                    XElement externalTileSetNode = externalTileSet.Element("tileset");

                    TileSet t = new TileSet(externalTileSetNode, mapPath);
                    TileSets.Add(t);
                    foreach (KeyValuePair<int, Tile> item in t.Tiles)
                    {
                        this.Tiles.Add(item.Key, item.Value);
                    }
                }
                else
                {
                    TileSet t = new TileSet(tileSet, mapPath);
                    TileSets.Add(t);
                    foreach (KeyValuePair<int, Tile> item in t.Tiles)
                    {
                        this.Tiles.Add(item.Key, item.Value);
                    }
                }
            }
            // Generate Materials for Map batching
            List<Material> materials = new List<Material>();
            // Generate Materials
            int i = 0;
            for (i = 0; i < TileSets.Count; i++)
            {
                Material layerMat = new Material(baseTileMaterial);
                layerMat.mainTexture = TileSets[i].Texture;
                materials.Add(layerMat);
            }

            Layers = new List<Layer>();
            i = 0;

            foreach (XElement layerNode in
                mapNode.Elements("layer").Concat(
                mapNode.Elements("objectgroup").Concat(
                mapNode.Elements("imagelayer")))
                )
            {
                Layer layerContent;

                int layerDepth = 1 - (LayerDepthSpacing * i);

                if (layerNode.Name == "layer")
                {
                    layerContent = new TileLayer(layerNode, this, layerDepth, makeUnique, materials);
                }
                else if (layerNode.Name == "objectgroup")
                {
                    layerContent = new MapObjectLayer(layerNode, this, layerDepth, materials);
                }
                else if (layerNode.Name == "imagelayer")
                {
                    layerContent = new ImageLayer(layerNode, this, mapPath, baseTileMaterial);
                }
                else
                {
                    throw new Exception("Unknown layer name: " + layerNode.Name);
                }

                // Layer names need to be unique for our lookup system, but Tiled
                // doesn't require unique names.
                string layerName = layerContent.Name;
                int duplicateCount = 2;

                // if a layer already has the same name...
                if (Layers.Find(l => l.Name == layerName) != null)
                {
                    // figure out a layer name that does work
                    do
                    {
                        layerName = string.Format("{0}{1}", layerContent.Name, duplicateCount);
                        duplicateCount++;
                    } while (Layers.Find(l => l.Name == layerName) != null);

                    // log a warning for the user to see
                    Debug.Log("Renaming layer \"" + layerContent.Name + "\" to \"" + layerName + "\" to make a unique name.");

                    // save that name
                    layerContent.Name = layerName;
                }
                layerContent.LayerDepth = layerDepth;
                Layers.Add(layerContent);
                namedLayers.Add(layerName, layerContent);
                i++;
            }
        }
Ejemplo n.º 2
0
        protected GameObject Generate3DTileCollision(TileLayer layer, int counter, Transform parent, List<Vector2> points, bool isTrigger = false, float zDepth = 1, float colliderWidth = 1, bool innerCollision = false)
        {
            GameObject newSubCollider = new GameObject("Tile Collisions " + layer.Name + "_" + counter);
            newSubCollider.transform.parent = parent;
            newSubCollider.transform.localPosition = new Vector3(0, 0, zDepth);

            Mesh colliderMesh = new Mesh();
            colliderMesh.name = "TileCollider_" + layer.Name + "_" + counter;
            MeshCollider mc = newSubCollider.AddComponent<MeshCollider>();

            mc.isTrigger = isTrigger;

            List<Vector3> vertices = new List<Vector3>();
            List<int> triangles = new List<int>();

            GenerateVerticesAndTris(points, vertices, triangles, zDepth, colliderWidth, innerCollision, true, true);

            // Connect last point with first point (create the face between them)
            triangles.Add(vertices.Count - 1);
            triangles.Add(1);
            triangles.Add(0);

            triangles.Add(0);
            triangles.Add(vertices.Count - 2);
            triangles.Add(vertices.Count - 1);

            FillFaces(points, triangles);

            colliderMesh.vertices = vertices.ToArray();
            colliderMesh.uv = new Vector2[colliderMesh.vertices.Length];
            colliderMesh.uv2 = colliderMesh.uv;
            colliderMesh.uv2 = colliderMesh.uv;
            colliderMesh.triangles = triangles.ToArray();
            colliderMesh.RecalculateNormals();

            mc.sharedMesh = colliderMesh;

            newSubCollider.isStatic = true;

            return newSubCollider;
        }
Ejemplo n.º 3
0
        void ContinueLoadingTiledMapAfterTileSetsLoaded()
        {
            // Generate Materials for Map batching
            List<Material> materials = new List<Material>();
            // Generate Materials
            int i = 0;
            for (i = 0; i < TileSets.Count; i++)
            {
                Material layerMat = new Material(BaseTileMaterial);
                layerMat.mainTexture = TileSets[i].Texture;
                materials.Add(layerMat);
            }

            Layers = new List<Layer>();
            i = 0;
            int tileLayerCount = 0;
            foreach (NanoXMLNode layerNode in MapNode.SubNodes)
            {
                if (!(layerNode.Name.Equals("layer") || layerNode.Name.Equals("objectgroup") || layerNode.Name.Equals("imagelayer")))
                    continue;

                Layer layerContent;

                int layerDepth = 1 - (LayerDepthSpacing * i);

                if (layerNode.Name.Equals("layer"))
                {
                    bool makeUnique = GlobalMakeUniqueTiles;
                    if (PerLayerMakeUniqueTiles != null && tileLayerCount < PerLayerMakeUniqueTiles.Length)
                        makeUnique = PerLayerMakeUniqueTiles[tileLayerCount];

                    layerContent = new TileLayer(layerNode, this, layerDepth, makeUnique, materials);
                    tileLayerCount++;
                }
                else if (layerNode.Name.Equals("objectgroup"))
                {
                    layerContent = new MapObjectLayer(layerNode, this, layerDepth, materials);
                }
                else if (layerNode.Name.Equals("imagelayer"))
                {
                    layerContent = new ImageLayer(layerNode, this, _mapPath, BaseTileMaterial);
                }
                else
                {
                    throw new Exception("Unknown layer name: " + layerNode.Name);
                }

                // Layer names need to be unique for our lookup system, but Tiled
                // doesn't require unique names.
                string layerName = layerContent.Name;
                int duplicateCount = 2;

                // if a layer already has the same name...
                if (Layers.Find(l => l.Name == layerName) != null)
                {
                    // figure out a layer name that does work
                    do
                    {
                        layerName = string.Format("{0}{1}", layerContent.Name, duplicateCount);
                        duplicateCount++;
                    } while (Layers.Find(l => l.Name == layerName) != null);

                    // log a warning for the user to see
                    Debug.Log("Renaming layer \"" + layerContent.Name + "\" to \"" + layerName + "\" to make a unique name.");

                    // save that name
                    layerContent.Name = layerName;
                }
                layerContent.LayerDepth = layerDepth;
                Layers.Add(layerContent);
                namedLayers.Add(layerName, layerContent);
                i++;
            }

            if (OnMapFinishedLoading != null)
                OnMapFinishedLoading(this);
        }
        public static List<List<Vector2>> GenerateClipperPathPoints(TileLayer tileLayer,
			bool simpleTileObjectCalculation = true,
			double clipperArcTolerance = 0.25, double clipperMiterLimit = 2.0,
			ClipperLib.JoinType clipperJoinType = ClipperLib.JoinType.jtRound,
			ClipperLib.EndType clipperEndType = ClipperLib.EndType.etClosedPolygon,
			float clipperDeltaOffset = 0)
        {
            ClipperLib.Clipper clipper = new ClipperLib.Clipper();
            List<List<ClipperLib.IntPoint>> pathsList = new List<List<ClipperLib.IntPoint>>();
            List<List<ClipperLib.IntPoint>> solution = new List<List<ClipperLib.IntPoint>>();
            List<List<Vector2>> points = new List<List<Vector2>>();

            for (int x = 0; x < tileLayer.Tiles.Width; x++)
            {
                for (int y = 0; y < tileLayer.Tiles.Height; y++)
                {
                    Tile t = tileLayer.Tiles[x, y];
                    if (t == null || t.TileSet == null || t.TileSet.TilesObjects == null)
                        continue;
                    if (t.TileSet.TilesObjects.ContainsKey(t.OriginalID))
                    {
                        List<TileObject> tileObjs = t.TileSet.TilesObjects[t.OriginalID];
                        foreach (var tileObj in tileObjs)
                        {
                            pathsList.Add(tileObj.GetPath(x, y, t.SpriteEffects, tileLayer.BaseMap.MapRenderParameter.TileWidth, tileLayer.BaseMap.MapRenderParameter.TileHeight));
                        }
                    }
                }
            }
            // Add the paths to be merged to ClipperLib
            clipper.AddPaths(pathsList, ClipperLib.PolyType.ptSubject, true);
            // Merge it!
            //clipper.PreserveCollinear = false;
            //clipper.ReverseSolution = true;
            clipper.StrictlySimple = simpleTileObjectCalculation;
            if (!clipper.Execute(ClipperLib.ClipType.ctUnion, solution))
                return points;
            clipper.Execute(ClipperLib.ClipType.ctUnion, solution);
            // Now solution should contain all vertices of the collision object, but they are still multiplied by TileObject.ClipperScale!

            #region Implementation of increase and decrease offset polygon.
            if (simpleTileObjectCalculation == false)
            {
                // Link of the example of ClipperLib:
                // http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Classes/ClipperOffset/_Body.htm

                ClipperLib.ClipperOffset co = new ClipperLib.ClipperOffset(clipperMiterLimit, clipperArcTolerance);
                foreach (List<ClipperLib.IntPoint> item in solution)
                {
                    co.AddPath(item, clipperJoinType, clipperEndType);
                }
                solution.Clear();
                co.Execute(ref solution, clipperDeltaOffset * TileObject.ClipperScale);
            }
            #endregion

            for (int i = 0; i < solution.Count; i++)
            {
                if (solution[i].Count < 1)
                    continue;
                points.Add(new List<Vector2>());
                for (int j = 0; j < solution[i].Count; j++)
                {
                    points[i].Add(
                        new Vector2(
                            solution[i][j].X / (float)TileObject.ClipperScale,
                            solution[i][j].Y / (float)TileObject.ClipperScale
                        )
                    );
                }
            }

            return points;
        }
Ejemplo n.º 5
0
        protected GameObject Generate2DTileCollision(TileLayer layer, int counter, Transform parent, List<Vector2> points, bool isTrigger = false, float zDepth = 1)
        {
            GameObject newSubCollider = new GameObject("Tile Collisions " + layer.Name + "_" + counter);
            newSubCollider.transform.parent = parent;
            newSubCollider.transform.localPosition = new Vector3(0, 0, zDepth);

            // Add the last point equals to the first to close the collider area
            // it's necessary only if the first point is diffent from the first one
            if (points[0].x != points[points.Count - 1].x || points[0].y != points[points.Count - 1].y)
            {
                points.Add(points[0]);
            }

            EdgeCollider2D edgeCollider = newSubCollider.AddComponent<EdgeCollider2D>();
            edgeCollider.isTrigger = isTrigger;

            Vector2[] pointsVec = points.ToArray();

            for (int j = 0; j < pointsVec.Length; j++)
            {
                pointsVec[j] = TiledPositionToWorldPoint(pointsVec[j]);
            }

            edgeCollider.points = pointsVec;
            return newSubCollider;
        }
        public static GameObject[] GenerateTileCollision3DFromLayer(
			this Map map, TileLayer layer,
			bool isTrigger = false, bool generateClosedPolygon = true, string tag = "Untagged", 
			int physicsLayer = 0, PhysicMaterial physicsMaterial = null, float zDepth = 1, 
			float colliderWidth = 1, bool innerCollision = false,
			bool simpleTileObjectCalculation = true,
			double clipperArcTolerance = 0.25, double clipperMiterLimit = 2.0,
			ClipperLib.JoinType clipperJoinType = ClipperLib.JoinType.jtRound,
			ClipperLib.EndType clipperEndType = ClipperLib.EndType.etClosedPolygon,
			float clipperDeltaOffset = 0)
        {
            if (layer == null)
                return null;

            if (layer.LayerTileCollisions == null)
            {
                layer.LayerTileCollisions = new GameObject(layer.Name + " Tile Collisions");
                Transform t = layer.LayerTileCollisions.transform;
                if (layer.BaseMap != null)
                {
                    t.parent = layer.BaseMap.MapGameObject.transform;
                }
                t.localPosition = Vector3.zero;
                t.localRotation = Quaternion.identity;
                t.localScale = Vector3.one;
                layer.LayerTileCollisions.isStatic = true;
            }
            layer.LayerTileCollisions.tag = tag;
            layer.LayerTileCollisions.layer = physicsLayer;
            layer.LayerTileCollisions.transform.localScale = Vector3.one;

            List<GameObject> newSubCollider = new List<GameObject>();

            List<Vector3> vertices = new List<Vector3>();
            List<int> triangles = new List<int>();
            List<List<Vector2>> points = GenerateClipperPathPoints(layer, simpleTileObjectCalculation, clipperArcTolerance, clipperMiterLimit, clipperJoinType, clipperEndType, clipperDeltaOffset);

            for (int i = 0; i < points.Count; i++)
            {
                newSubCollider.Add(new GameObject("Tile Collisions " + layer.Name + "_" + i));
                newSubCollider[i].transform.parent = layer.LayerTileCollisions.transform;
                newSubCollider[i].transform.localPosition = new Vector3(0, 0, zDepth);
                newSubCollider[i].transform.localScale = Vector3.one;
                newSubCollider[i].transform.localRotation = Quaternion.identity;
                newSubCollider[i].tag = tag;
                newSubCollider[i].layer = physicsLayer;

                vertices.Clear();
                triangles.Clear();
                Mesh colliderMesh = new Mesh();
                colliderMesh.name = "TileCollider_" + layer.Name + "_" + i;
                MeshCollider mc = newSubCollider[i].AddComponent<MeshCollider>();

                mc.isTrigger = isTrigger;

                GenerateVerticesAndTris(map, points[i], vertices, triangles, zDepth, colliderWidth, innerCollision, true, true);

                // Connect last point with first point (create the face between them)
                triangles.Add(vertices.Count - 1);
                triangles.Add(1);
                triangles.Add(0);

                triangles.Add(0);
                triangles.Add(vertices.Count - 2);
                triangles.Add(vertices.Count - 1);

                if (generateClosedPolygon)
                    FillFaces(points[i], triangles);

                colliderMesh.vertices = vertices.ToArray();
                colliderMesh.uv = new Vector2[colliderMesh.vertices.Length];
                //colliderMesh.uv1 = colliderMesh.uv;
                colliderMesh.uv2 = colliderMesh.uv;
                colliderMesh.triangles = triangles.ToArray();
                colliderMesh.RecalculateNormals();

                mc.sharedMesh = colliderMesh;

                if (physicsMaterial != null)
                    mc.sharedMaterial = physicsMaterial;

                newSubCollider[i].isStatic = true;
            }

            return newSubCollider.ToArray();
        }
        public static GameObject[] GenerateTileCollision2DFromLayer(
			this Map map, TileLayer layer,
			bool isTrigger = false, bool generateClosedPolygon = true, string tag = "Untagged",
			int physicsLayer = 0, PhysicsMaterial2D physicsMaterial = null, float zDepth = 1,
			bool simpleTileObjectCalculation = true,
			double clipperArcTolerance = 0.25, double clipperMiterLimit = 2.0,
			ClipperLib.JoinType clipperJoinType = ClipperLib.JoinType.jtRound,
			ClipperLib.EndType clipperEndType = ClipperLib.EndType.etClosedPolygon,
			float clipperDeltaOffset = 0)
        {
            if (layer == null)
                return null;

            if (layer.LayerTileCollisions == null)
            {
                layer.LayerTileCollisions = new GameObject(layer.Name + " Tile Collisions");
                Transform t = layer.LayerTileCollisions.transform;
                if (layer.BaseMap != null)
                {
                    t.parent = layer.BaseMap.MapGameObject.transform;
                }
                t.localPosition = Vector3.zero;
                t.localRotation = Quaternion.identity;
                t.localScale = Vector3.one;
                layer.LayerTileCollisions.isStatic = true;
            }
            layer.LayerTileCollisions.tag = tag;
            layer.LayerTileCollisions.layer = physicsLayer;

            List<GameObject> newSubCollider = new List<GameObject>();

            List<List<Vector2>> points = GenerateClipperPathPoints(layer, simpleTileObjectCalculation, clipperArcTolerance, clipperMiterLimit, clipperJoinType, clipperEndType, clipperDeltaOffset);

            for (int i = 0; i < points.Count; i++)
            {
                newSubCollider.Add(new GameObject("Tile Collisions " + layer.Name + "_" + i));
                newSubCollider[i].transform.parent = layer.LayerTileCollisions.transform;
                newSubCollider[i].transform.localPosition = new Vector3(0, 0, zDepth);
                newSubCollider[i].transform.localScale = Vector3.one;
                newSubCollider[i].transform.localRotation = Quaternion.identity;
                newSubCollider[i].tag = tag;
                newSubCollider[i].layer = physicsLayer;

                // Add the last point equals to the first to close the collider area
                // it's necessary only if the first point is diffent from the first one
                if (points[i][0].x != points[i][points[i].Count - 1].x || points[i][0].y != points[i][points[i].Count - 1].y)
                {
                    points[i].Add(points[i][0]);
                }

                Vector2[] pointsVec = points[i].ToArray();

                for (int j = 0; j < pointsVec.Length; j++)
                {
                    pointsVec[j] = map.TiledPositionToWorldPoint(pointsVec[j]);
                }

                if (generateClosedPolygon)
                {
                    PolygonCollider2D polyCollider = newSubCollider[i].AddComponent<PolygonCollider2D>();
                    polyCollider.isTrigger = isTrigger;
                    polyCollider.points = pointsVec;

                    if (physicsMaterial != null)
                        polyCollider.sharedMaterial = physicsMaterial;
                }
                else
                {
                    EdgeCollider2D edgeCollider = newSubCollider[i].AddComponent<EdgeCollider2D>();
                    edgeCollider.isTrigger = isTrigger;
                    edgeCollider.points = pointsVec;

                    if (physicsMaterial != null)
                        edgeCollider.sharedMaterial = physicsMaterial;
                }
            }
            return newSubCollider.ToArray();
        }
Ejemplo n.º 8
0
        void Initialize(XmlDocument document, bool makeUnique, string fullPath, string mapPath)
        {
            XmlNode mapNode = document["map"];
            Version = mapNode.Attributes["version"].Value;
            Orientation = (Orientation)Enum.Parse(typeof(Orientation), mapNode.Attributes["orientation"].Value, true);
            Width = int.Parse(mapNode.Attributes["width"].Value, CultureInfo.InvariantCulture);
            Height = int.Parse(mapNode.Attributes["height"].Value, CultureInfo.InvariantCulture);
            TileWidth = int.Parse(mapNode.Attributes["tilewidth"].Value, CultureInfo.InvariantCulture);
            TileHeight = int.Parse(mapNode.Attributes["tileheight"].Value, CultureInfo.InvariantCulture);

            XmlNode propertiesNode = document.SelectSingleNode("map/properties");
            if (propertiesNode != null)
            {
                Properties = new PropertyCollection(propertiesNode);//Property.ReadProperties(propertiesNode);
            }

            TileSets = new List<TileSet>();
            Tiles = new Dictionary<int, Tile>();
            foreach (XmlNode tileSet in document.SelectNodes("map/tileset"))
            {
                if (tileSet.Attributes["source"] != null)
                {
                    //TileSets.Add(new ExternalTileSetContent(tileSet, context));
                    XmlDocument externalTileSet = new XmlDocument();

                    TextAsset externalTileSetTextAsset = (TextAsset)Resources.Load(mapPath + Path.GetFileNameWithoutExtension(tileSet.Attributes["source"].Value));

                    //externalTileSet.Load(fullPath + "/" + tileSet.Attributes["source"].Value);
                    externalTileSet.LoadXml(externalTileSetTextAsset.text);
                    XmlNode externalTileSetNode = externalTileSet["tileset"];
                    //Debug.Log(externalTileSet.Value);
                    TileSet t = new TileSet(externalTileSetNode, mapPath);
                    TileSets.Add(t);
                    foreach (KeyValuePair<int, Tile> item in t.Tiles)
                    {
                        this.Tiles.Add(item.Key, item.Value);
                    }
                    //this.Tiles.AddRange(t.Tiles);
                }
                else
                {
                    TileSet t = new TileSet(tileSet, mapPath);
                    TileSets.Add(t);
                    foreach (KeyValuePair<int, Tile> item in t.Tiles)
                    {
                        this.Tiles.Add(item.Key, item.Value);
                    }
                }
            }
            // Generate Materials for Map batching
            List<Material> materials = new List<Material>();
            // Generate Materials
            int i = 0;
            for (i = 0; i < TileSets.Count; i++)
            {
                Material layerMat = new Material(Shader.Find("Unlit/Transparent"));
                layerMat.mainTexture = TileSets[i].Texture;
                materials.Add(layerMat);
            }

            Layers = new List<Layer>();
            i = 0;
            foreach (XmlNode layerNode in document.SelectNodes("map/layer|map/objectgroup"))
            {
                Layer layerContent;

                float layerDepth = 1f - (LayerDepthSpacing * i);

                if (layerNode.Name == "layer")
                {
                    layerContent = new TileLayer(layerNode, this, layerDepth, makeUnique, materials);
                    //((TileLayer)layerContent).GenerateLayerMesh(MeshRendererPrefab);
                }
                else if (layerNode.Name == "objectgroup")
                {
                    layerContent = new MapObjectLayer(layerNode, TileWidth, TileHeight);
                }
                else
                {
                    throw new Exception("Unknown layer name: " + layerNode.Name);
                }

                // Layer names need to be unique for our lookup system, but Tiled
                // doesn't require unique names.
                string layerName = layerContent.Name;
                int duplicateCount = 2;

                // if a layer already has the same name...
                if (Layers.Find(l => l.Name == layerName) != null)
                {
                    // figure out a layer name that does work
                    do
                    {
                        layerName = string.Format("{0}{1}", layerContent.Name, duplicateCount);
                        duplicateCount++;
                    } while (Layers.Find(l => l.Name == layerName) != null);

                    // log a warning for the user to see
                    Debug.Log("Renaming layer \"" + layerContent.Name + "\" to \"" + layerName + "\" to make a unique name.");

                    // save that name
                    layerContent.Name = layerName;
                }
                layerContent.LayerDepth = layerDepth;
                Layers.Add(layerContent);
                namedLayers.Add(layerName, layerContent);
                i++;
            }
        }
Ejemplo n.º 9
0
        void ContinueLoadingTiledMapAfterTileSetsLoaded()
        {
            Layers = new List<Layer>();
            int i = 0;
            foreach (NanoXMLNode layerNode in MapNode.SubNodes)
            {
                if (!(layerNode.Name.Equals("layer") || layerNode.Name.Equals("objectgroup") || layerNode.Name.Equals("imagelayer")))
                    continue;

                Layer layerContent;

                int layerDepth = 1 - (XUniTMXConfiguration.Instance.LayerDepthSpacing * i);

                if (layerNode.Name.Equals("layer"))
                {
                    layerContent = new TileLayer(layerNode, this, layerDepth, GlobalMakeUniqueTiles);
                }
                else if (layerNode.Name.Equals("objectgroup"))
                {
                    layerContent = new MapObjectLayer(layerNode, this, layerDepth);
                }
                else if (layerNode.Name.Equals("imagelayer"))
                {
                    layerContent = new ImageLayer(layerNode, this, _mapPath);
                }
                else
                {
                    throw new Exception("Unknown layer name: " + layerNode.Name);
                }

                // Layer names need to be unique for our lookup system, but Tiled
                // doesn't require unique names.
                string layerName = layerContent.Name;
                int duplicateCount = 2;

                // if a layer already has the same name...
                if (Layers.Find(l => l.Name == layerName) != null)
                {
                    // figure out a layer name that does work
                    do
                    {
                        layerName = string.Format("{0}{1}", layerContent.Name, duplicateCount);
                        duplicateCount++;
                    } while (Layers.Find(l => l.Name == layerName) != null);

                    // log a warning for the user to see
                    Debug.Log("Renaming layer \"" + layerContent.Name + "\" to \"" + layerName + "\" to make a unique name.");

                    // save that name
                    layerContent.Name = layerName;
                }
                layerContent.LayerDepth = layerDepth;
                Layers.Add(layerContent);
                namedLayers.Add(layerName, layerContent);
                i++;
            }

            if (OnMapFinishedLoading != null)
                OnMapFinishedLoading(this);
        }
Ejemplo n.º 10
0
        void Initialize(XmlDocument document, bool makeUnique, string fullPath, string mapPath)
        {
            XmlNode mapNode = document["map"];

            Version     = mapNode.Attributes["version"].Value;
            Orientation = (Orientation)Enum.Parse(typeof(Orientation), mapNode.Attributes["orientation"].Value, true);
            Width       = int.Parse(mapNode.Attributes["width"].Value, CultureInfo.InvariantCulture);
            Height      = int.Parse(mapNode.Attributes["height"].Value, CultureInfo.InvariantCulture);
            TileWidth   = int.Parse(mapNode.Attributes["tilewidth"].Value, CultureInfo.InvariantCulture);
            TileHeight  = int.Parse(mapNode.Attributes["tileheight"].Value, CultureInfo.InvariantCulture);

            XmlNode propertiesNode = document.SelectSingleNode("map/properties");

            if (propertiesNode != null)
            {
                Properties = new PropertyCollection(propertiesNode);                //Property.ReadProperties(propertiesNode);
            }

            TileSets = new List <TileSet>();
            Tiles    = new Dictionary <int, Tile>();
            foreach (XmlNode tileSet in document.SelectNodes("map/tileset"))
            {
                if (tileSet.Attributes["source"] != null)
                {
                    //TileSets.Add(new ExternalTileSetContent(tileSet, context));
                    XmlDocument externalTileSet = new XmlDocument();

                    TextAsset externalTileSetTextAsset = (TextAsset)Resources.Load(mapPath + Path.GetFileNameWithoutExtension(tileSet.Attributes["source"].Value));

                    //externalTileSet.Load(fullPath + "/" + tileSet.Attributes["source"].Value);
                    externalTileSet.LoadXml(externalTileSetTextAsset.text);
                    XmlNode externalTileSetNode = externalTileSet["tileset"];
                    //Debug.Log(externalTileSet.Value);
                    TileSet t = new TileSet(externalTileSetNode, mapPath);
                    TileSets.Add(t);
                    foreach (KeyValuePair <int, Tile> item in t.Tiles)
                    {
                        this.Tiles.Add(item.Key, item.Value);
                    }
                    //this.Tiles.AddRange(t.Tiles);
                }
                else
                {
                    TileSet t = new TileSet(tileSet, mapPath);
                    TileSets.Add(t);
                    foreach (KeyValuePair <int, Tile> item in t.Tiles)
                    {
                        this.Tiles.Add(item.Key, item.Value);
                    }
                }
            }
            // Generate Materials for Map batching
            List <Material> materials = new List <Material>();
            // Generate Materials
            int i = 0;

            for (i = 0; i < TileSets.Count; i++)
            {
                Material layerMat = new Material(Shader.Find("Unlit/Transparent"));
                layerMat.mainTexture = TileSets[i].Texture;
                materials.Add(layerMat);
            }

            Layers = new List <Layer>();
            i      = 0;
            foreach (XmlNode layerNode in document.SelectNodes("map/layer|map/objectgroup"))
            {
                Layer layerContent;

                float layerDepth = 1f - (LayerDepthSpacing * i);

                if (layerNode.Name == "layer")
                {
                    layerContent = new TileLayer(layerNode, this, layerDepth, makeUnique, materials);
                    //((TileLayer)layerContent).GenerateLayerMesh(MeshRendererPrefab);
                }
                else if (layerNode.Name == "objectgroup")
                {
                    layerContent = new MapObjectLayer(layerNode, TileWidth, TileHeight);
                }
                else
                {
                    throw new Exception("Unknown layer name: " + layerNode.Name);
                }

                // Layer names need to be unique for our lookup system, but Tiled
                // doesn't require unique names.
                string layerName      = layerContent.Name;
                int    duplicateCount = 2;

                // if a layer already has the same name...
                if (Layers.Find(l => l.Name == layerName) != null)
                {
                    // figure out a layer name that does work
                    do
                    {
                        layerName = string.Format("{0}{1}", layerContent.Name, duplicateCount);
                        duplicateCount++;
                    } while (Layers.Find(l => l.Name == layerName) != null);

                    // log a warning for the user to see
                    Debug.Log("Renaming layer \"" + layerContent.Name + "\" to \"" + layerName + "\" to make a unique name.");

                    // save that name
                    layerContent.Name = layerName;
                }
                layerContent.LayerDepth = layerDepth;
                Layers.Add(layerContent);
                namedLayers.Add(layerName, layerContent);
                i++;
            }
        }