public override void boardSetup() {
		
		boardHolder = new GameObject ("Board").transform;
		
		// Generate a map from Cellular Automata.
		// CellularAutomata foo = new CellularAutomata(rows, columns);
		//PureRandom foo = new PureRandom(rows, columns);
		GameObject playerChar = GameObject.FindGameObjectWithTag("Player");
		selectedRule.initializeMap ();
		selectedRule.generateMap ();
		Tile[,] mapConvert = selectedRule.map;

		MapValidationFunctions mvf = new MapValidationFunctions();

		Coord startPoint = new Coord(floodStartX,floodStartY); 
		Coord endPoint = new Coord(floodGoalX, floodGoalY);
		
		mvf.FloodFillCheck(selectedRule.map, startPoint, endPoint);

		// This is the autotiler phase.
		//
		// Let's try this method of instantiating the prefab of our choice...
		GameObject tileInstance = Instantiate(tilesetToUse, new Vector3(0,0,0), Quaternion.identity) as GameObject;
		
		selectedTileset = tileInstance.GetComponent<Tileset>();
		selectedTileset.autoTiler( mapConvert ); 

		if(MapValidationFunctions.clearable) Debug.Log ("The goal has been found!");
		else Debug.Log ("I can't find the goal.");
		
		//convertTiles( mapConvert );
		
	}
Exemplo n.º 2
0
 public void AnimateTileset(Tileset tileset)
 {
     foreach (var tile in tileset)
     {
         AnimateSprite(tile.Sprite);
     }
 }
Exemplo n.º 3
0
 public TileLayer(int[,] tiles, Tileset tileset, int base_x, int base_y)
 {
     this.Tileset = tileset;
     this.BaseX = base_x;
     this.BaseY = base_y;
     this.tiles = tiles;
 }
Exemplo n.º 4
0
        public override bool Convert(ConvertOperation convert)
        {
            bool finishConvertOp = false;
            List<Pixmap> availData = convert.Perform<Pixmap>().ToList();

            // Generate objects
            foreach (Pixmap baseRes in availData)
            {
                if (convert.IsObjectHandled(baseRes)) continue;

                // Find target Resource matching the source - or create one.
                Tileset targetRes =
                    this.FindMatchingResources<Pixmap,Tileset>(baseRes, IsMatch)
                    .FirstOrDefault();
                if (targetRes == null && convert.AllowedOperations.HasFlag(ConvertOperation.Operation.CreateRes))
                {
                    string texPath = PathHelper.GetFreePath(baseRes.FullName, Resource.GetFileExtByType<Tileset>());
                    targetRes = new Tileset();
                    targetRes.RenderConfig.Add(new TilesetRenderInput
                    {
                        SourceData = baseRes
                    });
                    targetRes.Compile();
                    targetRes.Save(texPath);
                }

                if (targetRes == null) continue;
                convert.AddResult(targetRes);
                finishConvertOp = true;
                convert.MarkObjectHandled(baseRes);
            }

            return finishConvertOp;
        }
Exemplo n.º 5
0
 protected TileToolBase(Application application, Tileset Tileset, TileSelection selection)
 {
     this.application = application;
     this.Tileset = Tileset;
     this.selection = selection;
     selection.Changed += OnSelectionChanged;
 }
        public FormLoadSettings(Tileset[] tilesets)
        {
            InitializeComponent();

            this.tilesets = tilesets;

            foreach (var tileset in tilesets)
            {
                Node node = new Node(tileset.File);

                if (String.IsNullOrEmpty(tileset.File))
                {
                    node.Text = String.Format("Not Specified [w: {0}, h: {1}]", tileset.Size.X, tileset.Size.Y);
                }

                node.Cells.Add(new Cell("<browse for file>"));

                node.Cells[0].Editable = false;
                node.Cells[1].Editable = false;

                node.NodeDoubleClick += node_NodeDoubleClick;

                tilesetFilesList.Nodes.Add(node);
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// Create a new, empty brush
 /// </summary>
 public TileBrush(int width, int height, Tileset tileset)
 {
     this.width = width;
     this.height = height;
     this.patterns = new List<TileBlock>();
     this.tileset = tileset;
 }
Exemplo n.º 8
0
 public ItemObject(TmxObject obj, Tileset tileset) : base(obj, tileset)
 {
     if (ScriptId == -1)
     {
         Item = Global.GetItem(int.Parse(obj.Properties["item"]));
         Quantity = obj.Properties.ContainsKey("quantity") ? int.Parse(obj.Properties["quantity"]) : 1;
     }
 }
    public void CreateTileset(Tileset t)
    {
        AssetDatabase.DeleteAsset(_path);
        AssetDatabase.CreateAsset(t, _path);

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
Exemplo n.º 10
0
 public BrushEditor(IEditorApplication application, Tilemap Tilemap, Tileset Tileset, string brushFile)
 {
     selection = new Selection();
     selection.Changed += OnSelectionChanged;
     this.application = application;
     this.Tilemap = Tilemap;
     brush = Brush.loadFromFile(brushFile, Tileset);
 }
Exemplo n.º 11
0
 public CaveBlock(Game game, Vector2 position, Color color,AMaterialStats stats,bool gtbS,Tileset tset,Color glowcolour)
     : base(game, position, color, stats,tset,glowcolour)
 {
     NeighbourList =  new List<CaveBlock>();
     GoingtobeSolid = gtbS;
     krypton = Game.Services.GetService<KryptonEngine>();
     _world = Game.Services.GetService<World>();
 }
Exemplo n.º 12
0
 public FillEditor(IEditorApplication application, Tilemap Tilemap, Tileset Tileset, Selection selection)
 {
     this.application = application;
     this.Tilemap = Tilemap;
     this.Tileset = Tileset;
     this.selection = selection;
     application.TilemapChanged += OnTilemapChanged;
     selection.Changed += OnSelectionChanged;
 }
Exemplo n.º 13
0
        public Tileset Load(FilePath path)
        {
            var tileset = new Tileset();

            tileset.FilePath = path;

            var doc = XDocument.Load(path.Absolute);
            var reader = doc.Element("Tileset");
            if (reader == null)
                throw new Exception("The specified tileset definition file does not contain a Tileset tag.");

            var sheetPath = FilePath.FromRelative(reader.Attribute("tilesheet").Value, path.BasePath);
            tileset.ChangeSheetPath(sheetPath.Absolute);

            int size;
            if (!int.TryParse(reader.Attribute("tilesize").Value, out size))
                throw new Exception("The tileset definition does not contain a valid tilesize attribute.");
            tileset.TileSize = size;

            var propParent = reader.Element("TileProperties");
            if (propParent != null)
            {
                foreach (XElement propNode in propParent.Elements("Properties"))
                {
                    var prop = new TileProperties(propNode);
                    tileset.AddProperties(prop);
                }
            }

            foreach (XElement tileNode in reader.Elements("Tile"))
            {
                int id = int.Parse(tileNode.Attribute("id").Value);
                string name = tileNode.Attribute("name").Value;

                var spriteNode = tileNode.Element("Sprite");
                if (spriteNode == null)
                    throw new GameXmlException(tileNode, "All Tile tags must contain a Sprite tag.");

                var sprite = LoadSprite(spriteNode);
                var tileSprite = new TileSprite(tileset, sprite);

                Tile tile = new Tile(id, tileSprite);

                string propName = "Default";
                XAttribute propAttr = tileNode.Attribute("properties");
                if (propAttr != null)
                    propName = propAttr.Value;

                tile.Properties = tileset.GetProperties(propName);

                tile.Sprite.Play();
                tileset.Add(tile);
            }

            return tileset;
        }
Exemplo n.º 14
0
        public ScreenInfo(string name, Tileset tileset)
        {
            this.Name = name;
            this.Tileset = tileset;

            BlockPatterns = new List<BlockPatternInfo>();
            Teleports = new List<TeleportInfo>();
            Layers = new List<ScreenLayerInfo>();
            Commands = new List<SceneCommandInfo>();
        }
Exemplo n.º 15
0
 public FacilityConnectors(Tileset tileset, int row, int column)
 {
     northConnector = row > 0;
     westConnector = column > 0;
     southConnector = row < (6 - tileset.RowCount / 10);
     eastConnector = column < (6 - tileset.ColumnCount / 10);
     var isAlienGarden = alienGardens.Contains(tileset);
     northWall = (byte)(isAlienGarden ? 54 : 86);
     westWall = (byte)(isAlienGarden ? 55 : 87);
     //TODO: Set correct ground tile when taking out south/east "objects" (unless dirt looks okay for some facilities...)
 }
Exemplo n.º 16
0
        public TileMap(Tileset tileSet, MapLayer baseLayer)
        {
            Tilesets = new List<Tileset>();
            Tilesets.Add(tileSet);

            MapLayers = new List<ILayer>();
            MapLayers.Add(baseLayer);

            mapWidth = baseLayer.Width;
            mapHeight = baseLayer.Height;
        }
Exemplo n.º 17
0
        public EditTilesetTileInputAction(Tileset tileset, RawList<TileInput> tileInput, RawList<bool> tileInputMask)
        {
            if (tileset == null) throw new ArgumentNullException("tileset");
            if (tileInput == null) throw new ArgumentNullException("tileInput");
            if (tileInputMask == null) throw new ArgumentNullException("tileInputMask");
            if (tileInputMask.Count != tileInput.Count) throw new ArgumentException("Input Mask needs to be the same size as input.", "tileInputMask");

            this.tileset = tileset;
            this.tileInput = tileInput;
            this.tileInputMask = tileInputMask;
        }
 public void ProcessBackground(Tileset ts, XmlNode xnNode)
 {
     XmlElement xe = (XmlElement)xnNode;
     List<BGLayer> bglList = new List<BGLayer>(10);
     ProcessBGFilename(ts, xe.GetElementsByTagName("bgFilename")[0]);
     XmlNodeList xnl = xe.GetElementsByTagName("layer");
     foreach (XmlNode node in xnl)
     {
         bglList.Add(ProcessLayer(node));
     }
     ts.LayerList = bglList;
 }
Exemplo n.º 19
0
        public override void Do()
        {
            // Make a backup of the tileset in its current state
            if (this.backupBeforeApply == null)
                this.backupBeforeApply = this.targetTileset.DeepClone(BackupCloneContext);

            // Compile the tileset so all the changes become visible
            this.targetTileset.Compile();

            // Notify the editor we changes our target tileset
            this.OnNotifyPropertyChanged();
        }
        public TilesetViewPaintTilesEventArgs(
			Graphics graphics, 
			Rectangle clipRect,
			Tileset tileset,
			Bitmap sourceImage, 
			RawList<TilesetViewPaintTileData> paintedTiles)
            : base(graphics, clipRect)
        {
            this.tileset = tileset;
            this.sourceImage = sourceImage;
            this.paintedTiles = paintedTiles;
        }
Exemplo n.º 21
0
        public TilesetDocument CreateNew(FilePath filePath)
        {
            var tileset = new Tileset()
            {
                FilePath = filePath,
                TileSize = 16
            };

            var document = new TilesetDocument(tileset);
            AddDefaultTileProperties(document);

            return document;
        }
Exemplo n.º 22
0
        public override void Do()
        {
            // Make a backup of the tileset in its current state
            if (this.backupBeforeRevert == null)
                this.backupBeforeRevert = this.targetTileset.DeepClone(BackupCloneContext);

            // Revert the tileset back to its unchanged state. No need to compile it,
            // this is meant to un-do changed that were done without compiling yet.
            this.backupBeforeChanges.DeepCopyTo(this.targetTileset);

            // Notify the editor we changes our target tileset
            this.OnNotifyPropertyChanged();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Determines the default tile index of the specified <see cref="Tileset"/>
        /// depending on the role of the <see cref="Tilemap"/> in which it is used.
        /// </summary>
        /// <param name="tileset"></param>
        /// <param name="isUpperLayer"></param>
        /// <returns></returns>
        public static int GetDefaultTileIndex(Tileset tileset, bool isUpperLayer)
        {
            if (tileset == null) return 0;

            for (int i = 0; i < tileset.TileData.Count; i++)
            {
                // Use solid tiles for the base layer, but transparent tiles
                // for all upper layers.
                if (tileset.TileData[i].IsVisuallyEmpty == isUpperLayer)
                    return i;
            }

            return 0;
        }
Exemplo n.º 24
0
 public FacilityConnectors(Tileset[,] tilesets, int row, int column)
 {
     var facility = tilesets[row, column];
     var northFacility = row == 0 ? null : tilesets[row - 1, column];
     var sourthFacility = row == 5 ? null : tilesets[row + 1, column];
     var eastFacility = column == 5 ? null : tilesets[row, column + 1];
     var westFacility = column == 0 ? null : tilesets[row, column - 1];
     northConnector = AreVerticallyConnected(northFacility, facility);
     southConnector = AreVerticallyConnected(facility, sourthFacility);
     eastConnector = AreHorizontallyConnected(facility, eastFacility);
     westConnector = AreHorizontallyConnected(westFacility, facility);
     northWall = 14;
     westWall = 15;
 }
Exemplo n.º 25
0
 /// <summary>
 /// Check a tile block for nonexistent tile ids.
 /// </summary>
 /// <param name="tiles">TileBlock to check</param>
 /// <param name="Tileset">Tileset where the ids should be defined</param>
 /// <returns>List of invalid tile ids.</returns>
 public static List<int> CheckIds(TileBlock tiles, Tileset Tileset)
 {
     List<int> invalidTiles = new List<int>();
     for (int y = 0; y < tiles.Height; ++y) {
         for (int x = 0; x < tiles.Width; ++x) {
             int TileId = tiles[x, y];
             if (!Tileset.IsValid(TileId)) {
                 if (invalidTiles.IndexOf(TileId) == -1)
                     invalidTiles.Add(TileId);
             }
         }
     }
     return invalidTiles;
 }
Exemplo n.º 26
0
        public EditTilesetTileInputAction(Tileset tileset, int tileIndex, TileInput tileInput)
        {
            if (tileset == null) throw new ArgumentNullException("tileset");

            this.tileset = tileset;

            this.tileInput = new RawList<TileInput>(tileIndex + 1);
            this.tileInput.Count = tileIndex + 1;
            this.tileInput.Data[tileIndex] = tileInput;

            this.tileInputMask = new RawList<bool>(tileIndex + 1);
            this.tileInputMask.Count = tileIndex + 1;
            this.tileInputMask.Data[tileIndex] = true;
        }
Exemplo n.º 27
0
        public EditTilesetAutoTileItemAction(Tileset tileset, TilesetAutoTileInput autoTile, int tileIndex, TilesetAutoTileItem tileInput)
        {
            if (tileset == null) throw new ArgumentNullException("tileset");
            if (autoTile == null) throw new ArgumentNullException("autoTile");

            this.tileset = tileset;
            this.autoTile = autoTile;

            this.tileInput = new RawList<TilesetAutoTileItem>(tileIndex + 1);
            this.tileInput.Count = tileIndex + 1;
            this.tileInput.Data[tileIndex] = tileInput;

            this.tileInputMask = new RawList<bool>(tileIndex + 1);
            this.tileInputMask.Count = tileIndex + 1;
            this.tileInputMask.Data[tileIndex] = true;
        }
Exemplo n.º 28
0
        public static List<RoomSprite> FillRect(Game _game, Rectangle wall,Color colour,Tileset tset,Color glowcolour)
        {
            List<RoomSprite> _roomSpriteList = new List<RoomSprite>();

            int x = (int)(wall.Width / Globals.SmallGridSize.X);
            int y = (int)(wall.Height / Globals.SmallGridSize.Y);
            for (int i = 1; i <= x; i++)
            {
                for (int j = 1; j <= y; j++)
                {
                    var wallblock = new SmallBlock01(_game, new Vector2(wall.Location.X + (i * Globals.SmallGridSize.X) - Globals.SmallGridSize.X,
                                                                        wall.Location.Y - (j * Globals.SmallGridSize.Y))
                                                                        , colour,tset,glowcolour);
                    _roomSpriteList.Add(wallblock);
                }
            }
            return _roomSpriteList;
        }
Exemplo n.º 29
0
    public Tilemap(Tileset Tileset, Lisp.List Data)
    {
        this.Tileset = Tileset;

        Properties Props = new Properties(Data);
        uint Width = 0;
        uint Height = 0;
        Props.Get("width", ref Width);
        Props.Get("height", ref Height);
        if(Width == 0 || Height == 0)
            throw new Exception("Width or Height of Tilemap invalid");

        List<uint> Tiles = new List<uint>();
        Props.GetUIntList("tiles", Tiles);
        if(Tiles.Count != (int) (Width * Height))
            throw new Exception("TileCount != Width*Height");
        Props.Get("solid", ref Solid);
        Props.PrintUnusedWarnings();

        Field = new Field<uint>(Tiles, Width, Height);
    }
Exemplo n.º 30
0
        public void ChangeTileset(Tileset tileset)
        {
            Clear();
            Tileset = tileset;
            if (tileset == null) brushes = null;
            else if (brushSets.ContainsKey(tileset.FilePath.Absolute))
            {
                brushes = brushSets[tileset.FilePath.Absolute];
            }
            else
            {
                brushes = new List<ITileBrush>();
                brushSets.Add(tileset.FilePath.Absolute, brushes);
                LoadBrushes();
            }

            if (brushes != null)
            {
                foreach (var brush in brushes) AddBrushPanel(brush);
            }
        }
        private static void CreateFromSpriteEditorScene(TiledMapSave tiledMapSave, float scale, float zOffset, FileReferenceType referenceType, ReducedTileMapInfo toReturn)
        {
            var ses = tiledMapSave.ToSceneSave(scale, referenceType);

            // This is not a stable sort!
            //ses.SpriteList.Sort((first, second) => first.Z.CompareTo(second.Z));
            ses.SpriteList = ses.SpriteList.OrderBy(item => item.Z).ToList();

            ReducedLayerInfo reducedLayerInfo = null;

            float z = float.NaN;


            int textureWidth  = 0;
            int textureHeight = 0;

            AbstractMapLayer currentLayer = null;
            int indexInLayer = 0;


            foreach (var spriteSave in ses.SpriteList)
            {
                if (spriteSave.Z != z)
                {
                    indexInLayer = 0;
                    z            = spriteSave.Z;


                    int layerIndex       = FlatRedBall.Math.MathFunctions.RoundToInt(z - zOffset);
                    var abstractMapLayer = tiledMapSave.MapLayers[layerIndex];
                    currentLayer = abstractMapLayer;

                    reducedLayerInfo = new ReducedLayerInfo
                    {
                        Z          = spriteSave.Z,
                        Texture    = spriteSave.Texture,
                        Name       = abstractMapLayer.Name,
                        TileWidth  = FlatRedBall.Math.MathFunctions.RoundToInt(spriteSave.ScaleX * 2),
                        TileHeight = FlatRedBall.Math.MathFunctions.RoundToInt(spriteSave.ScaleY * 2)
                    };

                    var mapLayer = abstractMapLayer as MapLayer;
                    // This should have data:
                    if (mapLayer != null)
                    {
                        var     idOfTexture  = mapLayer.data[0].tiles.FirstOrDefault(item => item != 0);
                        Tileset tileSet      = tiledMapSave.GetTilesetForGid(idOfTexture);
                        var     tilesetIndex = tiledMapSave.Tilesets.IndexOf(tileSet);

                        textureWidth  = tileSet.Images[0].width;
                        textureHeight = tileSet.Images[0].height;

                        reducedLayerInfo.TextureId = tilesetIndex;
                        toReturn.Layers.Add(reducedLayerInfo);
                    }


                    var objectGroup = tiledMapSave.MapLayers[layerIndex] as mapObjectgroup;

                    // This code only works based on the assumption that only one tileset will be used in any given object layer's image objects
                    var mapObjectgroupObject = [email protected](o => o.gid != null);

                    if (mapObjectgroupObject?.gid != null)
                    {
                        var     idOfTexture  = mapObjectgroupObject.gid.Value;
                        Tileset tileSet      = tiledMapSave.GetTilesetForGid(idOfTexture);
                        var     tilesetIndex = tiledMapSave.Tilesets.IndexOf(tileSet);

                        textureWidth  = tileSet.Images[0].width;
                        textureHeight = tileSet.Images[0].height;
                        reducedLayerInfo.TextureId = tilesetIndex;
                        toReturn.Layers.Add(reducedLayerInfo);
                    }
                }

                ReducedQuadInfo quad = ReducedQuadInfo.FromSpriteSave(spriteSave, textureWidth, textureHeight);

                if (currentLayer is mapObjectgroup)
                {
                    var asMapObjectGroup = currentLayer as mapObjectgroup;
                    var objectInstance   = asMapObjectGroup.@object[indexInLayer];

                    // skip over any non-sprite objects:
                    while (objectInstance.gid == null)
                    {
                        indexInLayer++;
                        if (indexInLayer >= [email protected])
                        {
                            objectInstance = null;
                            break;
                        }
                        else
                        {
                            objectInstance = asMapObjectGroup.@object[indexInLayer];
                        }
                    }

                    if (objectInstance != null && objectInstance.properties.Count != 0)
                    {
                        var nameProperty = objectInstance.properties.FirstOrDefault(item => item.StrippedNameLower == "name");
                        if (nameProperty != null)
                        {
                            quad.Name = nameProperty.value;
                        }
                        else
                        {
                            quad.Name = spriteSave.Name;

                            bool needsName = string.IsNullOrEmpty(spriteSave.Name);
                            if (needsName)
                            {
                                quad.Name = $"_{currentLayer.Name}runtime{indexInLayer}";
                            }
                        }

                        List <NamedValue> list = new List <NamedValue>();

                        foreach (var property in objectInstance.properties)
                        {
                            list.Add(
                                new NamedValue
                            {
                                Name  = property.StrippedName,
                                Value = property.value,
                                Type  = property.Type
                            }
                                );
                        }

                        quad.QuadSpecificProperties = list;
                    }
                }

                reducedLayerInfo?.Quads.Add(quad);

                indexInLayer++;
            }
        }
        private static void CreateFromTiledMapSave(TiledMapSave tiledMapSave, string directory, FileReferenceType referenceType,
                                                   ReducedTileMapInfo reducedTileMapInfo)
        {
            ReducedLayerInfo reducedLayerInfo = null;

            for (int i = 0; i < tiledMapSave.MapLayers.Count; i++)
            {
                var tiledLayer = tiledMapSave.MapLayers[i];

                string texture = null;

                uint    tileIdOfTexture = 0;
                Tileset tileSet         = null;
                uint?   firstGid        = null;

                if (tiledLayer is MapLayer)
                {
                    var mapLayer = tiledLayer as MapLayer;

                    if (mapLayer.data.Length != 0)
                    {
                        firstGid = mapLayer.data[0].tiles.FirstOrDefault(item => item != 0);
                    }
                }
                else
                {
                    var objectLayer = tiledLayer as mapObjectgroup;

                    var firstObjectWithTexture = [email protected](item => item.gid != 0);

                    firstGid = firstObjectWithTexture?.gid;
                }

                if (firstGid > 0)
                {
                    tileSet = tiledMapSave.GetTilesetForGid(firstGid.Value);
                    if (tileSet != null)
                    {
                        if (referenceType == FileReferenceType.NoDirectory)
                        {
                            texture = tileSet.Images[0].sourceFileName;
                        }
                        else if (referenceType == FileReferenceType.Absolute)
                        {
                            if (!string.IsNullOrEmpty(tileSet.SourceDirectory) && tileSet.SourceDirectory != ".")
                            {
                                directory += tileSet.SourceDirectory;

                                directory = FlatRedBall.IO.FileManager.RemoveDotDotSlash(directory);
                            }

                            texture = FlatRedBall.IO.FileManager.RemoveDotDotSlash(directory + tileSet.Images[0].Source);
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                    }



                    int tileWidth  = FlatRedBall.Math.MathFunctions.RoundToInt(tiledMapSave.tilewidth);
                    int tileHeight = FlatRedBall.Math.MathFunctions.RoundToInt(tiledMapSave.tileheight);

                    reducedLayerInfo = new ReducedLayerInfo
                    {
                        Z          = i,
                        Texture    = texture,
                        Name       = tiledLayer.Name,
                        TileWidth  = tileWidth,
                        TileHeight = tileHeight,
                    };

                    reducedTileMapInfo.Layers.Add(reducedLayerInfo);

                    var tilesetIndex = tiledMapSave.Tilesets.IndexOf(tileSet);
                    reducedLayerInfo.TextureId = tilesetIndex;


                    // create the quad here:
                    if (tiledLayer is MapLayer)
                    {
                        AddTileLayerTiles(tiledMapSave, reducedLayerInfo, i, tiledLayer, tileSet, tileWidth, tileHeight);
                    }

                    else if (tiledLayer is mapObjectgroup)
                    {
                        AddObjectLayerTiles(reducedLayerInfo, tiledLayer, tileSet, firstGid, tileWidth, tileHeight);
                    }
                }
            }
        }
Exemplo n.º 33
0
        private void PerformUserDrawAction()
        {
            Tileset tileset = this.SelectedTileset.Res;

            if (tileset == null)
            {
                return;
            }

            TilesetAutoTileInput autoTile = this.currentAutoTile;

            if (autoTile == null)
            {
                return;
            }

            int tileIndex = this.TilesetView.HoveredTileIndex;

            if (tileIndex < 0 || tileIndex > tileset.TileCount)
            {
                return;
            }

            // Determine data before the operation, and set up data for afterwards
            bool lastIsBaseTile           = autoTile.BaseTileIndex == tileIndex;
            bool newIsBaseTile            = lastIsBaseTile;
            TilesetAutoTileItem lastInput = (autoTile.TileInput.Count > tileIndex) ?
                                            autoTile.TileInput[tileIndex] :
                                            default(TilesetAutoTileItem);
            TilesetAutoTileItem newInput = lastInput;

            // Determine how data is modified due to our user operation
            if (this.userDrawMode == AutoTileDrawMode.Add)
            {
                if (this.isExternalDraw)
                {
                    newInput.Neighbours         = TileConnection.None;
                    newInput.ConnectsToAutoTile = true;
                    newInput.IsAutoTile         = false;
                    newIsBaseTile = false;
                }
                else if (this.isBaseTileDraw)
                {
                    newInput.Neighbours         = TileConnection.All;
                    newInput.IsAutoTile         = true;
                    newInput.ConnectsToAutoTile = false;
                    newIsBaseTile = true;
                }
                else
                {
                    newInput.Neighbours        |= this.hoveredArea;
                    newInput.IsAutoTile         = true;
                    newInput.ConnectsToAutoTile = false;
                }
            }
            else if (this.userDrawMode == AutoTileDrawMode.Remove)
            {
                if (this.isExternalDraw || this.isBaseTileDraw || this.hoveredArea == TileConnection.None)
                {
                    newInput.Neighbours         = TileConnection.None;
                    newInput.ConnectsToAutoTile = false;
                    newInput.IsAutoTile         = false;
                    newIsBaseTile = false;
                }
                else
                {
                    newInput.Neighbours &= ~this.hoveredArea;
                }
            }

            // Apply the new, modified data to the actual data using an UndoRedo operation
            if (newIsBaseTile != lastIsBaseTile)
            {
                UndoRedoManager.Do(new EditPropertyAction(
                                       null,
                                       TilemapsReflectionInfo.Property_TilesetAutoTileInput_BaseTile,
                                       new object[] { autoTile },
                                       new object[] { newIsBaseTile?tileIndex: -1 }));
            }
            if (!object.Equals(lastInput, newInput))
            {
                UndoRedoManager.Do(new EditTilesetAutoTileItemAction(
                                       tileset,
                                       autoTile,
                                       tileIndex,
                                       newInput));
            }
        }
        /// <summary>
        /// Converts a TiledMapSave to a ReducedTileMapInfo object
        /// </summary>
        /// <param name="tiledMapSave">The TiledMapSave to convert</param>
        /// <param name="scale">The amount to scale by - default of 1</param>
        /// <param name="zOffset">The zOffset</param>
        /// <param name="directory">The directory of the file associated with the tiledMapSave, used to find file references.</param>
        /// <param name="referenceType">How the files in the .tmx are referenced.</param>
        /// <returns></returns>
        public static ReducedTileMapInfo FromTiledMapSave(TiledMapSave tiledMapSave, float scale, float zOffset, string directory, FileReferenceType referenceType)
        {
            var toReturn = new ReducedTileMapInfo();

            toReturn.NumberCellsTall = tiledMapSave.Height;
            toReturn.NumberCellsWide = tiledMapSave.Width;

            var ses = tiledMapSave.ToSceneSave(scale, referenceType);

            ses.SpriteList.Sort((first, second) => first.Z.CompareTo(second.Z));

            ReducedLayerInfo reducedLayerInfo = null;

            // If we rely on the image, it's both slow (have to open the images), and
            // doesn't work at runtime in games:
            //Dictionary<string, Point> loadedTextures = new Dictionary<string, Point>();
            //SetCellWidthAndHeight(tiledMapSave, directory, toReturn, ses, loadedTextures);

            toReturn.CellHeightInPixels = (ushort)tiledMapSave.tileheight;
            toReturn.CellWidthInPixels  = (ushort)tiledMapSave.tilewidth;


            SetQuadWidthAndHeight(toReturn, ses);

            float z = float.NaN;


            int textureWidth  = 0;
            int textureHeight = 0;


            for (int i = 0; i < ses.SpriteList.Count; i++)
            {
                SpriteSave spriteSave = ses.SpriteList[i];

                if (spriteSave.Z != z)
                {
                    z = spriteSave.Z;
                    reducedLayerInfo         = new ReducedLayerInfo();
                    reducedLayerInfo.Z       = spriteSave.Z;
                    reducedLayerInfo.Texture = spriteSave.Texture;

                    int layerIndex = FlatRedBall.Math.MathFunctions.RoundToInt(z - zOffset);
                    var mapLayer   = tiledMapSave.Layers[layerIndex];


                    // This should have data:

                    var     idOfTexture  = mapLayer.data[0].tiles.FirstOrDefault(item => item != 0);
                    Tileset tileSet      = tiledMapSave.GetTilesetForGid(idOfTexture);
                    var     tilesetIndex = tiledMapSave.Tilesets.IndexOf(tileSet);

                    textureWidth  = tileSet.Images[0].width;
                    textureHeight = tileSet.Images[0].height;

                    reducedLayerInfo.Name      = mapLayer.Name;
                    reducedLayerInfo.TextureId = tilesetIndex;
                    toReturn.Layers.Add(reducedLayerInfo);
                }

                ReducedQuadInfo quad = ReducedQuadInfo.FromSpriteSave(spriteSave, textureWidth, textureHeight);
                reducedLayerInfo.Quads.Add(quad);
            }
            return(toReturn);
        }
Exemplo n.º 35
0
 private extern void orig_ReadInto(patch_TerrainType data, Tileset tileset, XmlElement xml);
Exemplo n.º 36
0
 public void SetTileset(Tileset to)
 {
     tilesetsComboBox.SelectedItem = to;
     tileSelector.Tileset          = to;
 }
        private static void AddObjectLayerTiles(ReducedLayerInfo reducedLayerInfo, AbstractMapLayer tiledLayer, Tileset tileSet, uint?gid, int tileWidth, int tileHeight)
        {
            var asMapLayer = tiledLayer as mapObjectgroup;

            foreach (var objectInstance in asMapLayer.@object)
            {
                if (objectInstance.gid > 0)
                {
                    ReducedQuadInfo quad = new DataTypes.ReducedQuadInfo();

                    quad.LeftQuadCoordinate   = (float)objectInstance.x;
                    quad.BottomQuadCoordinate = (float)-objectInstance.y;

                    quad.RotationDegrees = (float)objectInstance.Rotation;

                    quad.FlipFlags = (byte)(gid.Value & 0xf0000000 >> 7);

                    var valueWithoutFlip = gid.Value & 0x0fffffff;

                    int leftPixelCoord;
                    int topPixelCoord;
                    int rightPixelCoord;
                    int bottomPixelCoord;
                    TiledMapSave.GetPixelCoordinatesFromGid(gid.Value, tileSet,
                                                            out leftPixelCoord, out topPixelCoord, out rightPixelCoord, out bottomPixelCoord);

                    quad.LeftTexturePixel = (ushort)Math.Min(leftPixelCoord, rightPixelCoord);
                    quad.TopTexturePixel  = (ushort)Math.Min(topPixelCoord, bottomPixelCoord);

                    quad.Name = objectInstance.Name;
                    if (string.IsNullOrEmpty(quad.Name))
                    {
                        var prop = quad.QuadSpecificProperties.FirstOrDefault(quadProp => quadProp.Name.ToLowerInvariant() == "name");
                        quad.Name = (string)prop.Value;
                    }

                    reducedLayerInfo?.Quads.Add(quad);
                }
            }
        }
Exemplo n.º 38
0
 public static string GetAmbientDaySound(Tileset tileset)
 {
     return($"{GetAmbientSound(tileset)}Day");
 }
Exemplo n.º 39
0
        public override void BuildMainFunction(string path, float left, float right, float top, float bottom, Tileset light, SoundEnvironment sound, params string[] initFunctions)
        {
            var fileSyntax = new LuaCompilationUnitSyntax();

            fileSyntax.AddStatement(GetMainFunctionSyntax(left, right, top, bottom, light, sound, initFunctions));
            RenderFunctionToFile(path, fileSyntax);
        }
Exemplo n.º 40
0
        public static Tile GetRandomTile(AssetHandler assetHandler, DebugForm debugForm, int salt, Tileset tileset)
        {
            Random tempRand = new Random(salt);
            Tile   randTile = new Tile();

            int rand = tempRand.Next(0, 1000);

            if (debugForm != null)
            {
                debugForm.WriteLine("Random-Value: " + rand);
            }

            if (rand < 250)
            {
                randTile.isEnterable    = true;
                randTile.isInteractable = false;
                randTile.tileBitmap     = tileset.TileIcons[(int)Tiles.Plain_0];
                randTile.tileName       = "Plain_0";
            }
            else if (rand < 500)
            {
                randTile.isEnterable    = true;
                randTile.isInteractable = false;
                randTile.tileBitmap     = tileset.TileIcons[(int)Tiles.Plain_1];
                randTile.tileName       = "Plain_1";
            }
            else if (rand < 750)
            {
                randTile.isEnterable    = true;
                randTile.isInteractable = false;
                randTile.tileBitmap     = tileset.TileIcons[(int)Tiles.Plain_2];
                randTile.tileName       = "Plain_2";
            }
            else if (rand < 940)
            {
                randTile.isEnterable    = true;
                randTile.isInteractable = false;
                randTile.tileBitmap     = tileset.TileIcons[(int)Tiles.Plain_3];
                randTile.tileName       = "Plain_3";
            }
            else if (rand < 965)
            {
                randTile.isEnterable    = false;
                randTile.isInteractable = false;
                randTile.tileBitmap     = tileset.TileIcons[(int)Tiles.Plain_4];
                randTile.tileName       = "Plain_4";
            }
            else if (rand < 985)
            {
                randTile.isEnterable    = true;
                randTile.isInteractable = true;
                randTile.tileBitmap     = tileset.TileIcons[(int)Tiles.Plain_House_0];
                randTile.tileName       = "Plain_House_0";

                //randTile.interaction = new GetItemInteraction(Weapon.GetRandomWeapon(assetHandler),"Dorfbesuch","Willkommen im Dummy-Dorf, hier ist ein Item-Test!");
                randTile.interaction = GetItemInteraction.GetRandomItemInteraction(assetHandler);
            }
            else if (rand < 998)
            {
                randTile.isEnterable    = true;
                randTile.isInteractable = true;
                randTile.tileBitmap     = tileset.TileIcons[(int)Tiles.Plain_House_1];
                randTile.tileName       = "Plain_House_1";
            }
            else if (rand < 1000)
            {
                randTile.isEnterable    = true;
                randTile.isInteractable = false;
                randTile.tileBitmap     = tileset.TileIcons[(int)Tiles.Plain_Castle_0];
                randTile.tileName       = "Plain_Castle_0";
            }
            else
            {
                randTile.isEnterable    = true;
                randTile.isInteractable = true;
                randTile.tileBitmap     = tileset.TileIcons[(int)Tiles.Dummy];
                randTile.tileName       = "DUMMY";
            }



            return(randTile);
        }
Exemplo n.º 41
0
        public static Tileset CreateTilesetFromTmx(string tmxFilePath, string dstPath)
        {
            string     tmxFileName = Path.GetFileNameWithoutExtension(tmxFilePath);
            TmxTilemap tilemap     = TmxTilemap.LoadFromFile(tmxFilePath);

            if (tilemap.DicTilesetTex2D.Values.Count == 0)
            {
                return(null);
            }

            //NOTE: calling this after PackTextures will make the atlasTexture to be null sometimes
            Tileset tilesetAsset = ScriptableObject.CreateInstance <Tileset>();

            AssetDatabase.CreateAsset(tilesetAsset, Path.Combine(dstPath, tmxFileName + "Tileset.asset"));
            Texture2D atlasTexture;

            Rect[] tilesetRects;
            if (tilemap.DicTilesetTex2D.Values.Count == 1)
            {
                atlasTexture = tilemap.DicTilesetTex2D.Values.ToArray()[0];
                tilesetRects = new Rect[] { new Rect(0, 0, atlasTexture.width, atlasTexture.height) };
            }
            else
            {
                atlasTexture = new Texture2D(8192, 8192, TextureFormat.ARGB32, false, false);
                tilesetRects = atlasTexture.PackTextures(tilemap.DicTilesetTex2D.Values.ToArray(), 0);
            }
            string atlasPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(tilesetAsset)) + "/" + tmxFileName + "Atlas.png";

            AssetDatabase.CreateAsset(atlasTexture, atlasPath);
            File.WriteAllBytes(atlasPath, atlasTexture.EncodeToPNG());
            ImportTexture(atlasPath);
            AssetDatabase.Refresh();

            // Link Atlas with asset to be able to save it in the prefab
            tilesetAsset.AtlasTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(Texture2D));

            tilesetAsset.TilePxSize = new Vector2(tilemap.Map.Tilesets[0].TileWidth, tilemap.Map.Tilesets[0].TileHeight);
            int         tilesetIdx = 0;
            List <Tile> tileList   = new List <Tile>();

            foreach (Texture2D tilesetTexture in tilemap.DicTilesetTex2D.Values)
            {
                TmxTileset    tmxTileset       = tilemap.Map.Tilesets[tilesetIdx];
                Vector2       tileSize         = new Vector2(tilemap.Map.Tilesets[tilesetIdx].TileWidth, tilemap.Map.Tilesets[tilesetIdx].TileHeight);
                Rect[]        tileRects        = GenerateGridSpriteRectangles(tilesetTexture, new Vector2(tmxTileset.Margin, tmxTileset.Margin), tileSize, new Vector2(tmxTileset.Spacing, tmxTileset.Spacing));
                TileSelection tilesetSelection = new TileSelection(Enumerable.Range(tileList.Count, tileRects.Length).Select(i => (uint)i).ToList(), tmxTileset.Columns);
                foreach (Rect tileRect in tileRects)
                {
                    Rect uv = tileRect;
                    uv.xMin     /= tilesetAsset.AtlasTexture.width;
                    uv.xMax     /= tilesetAsset.AtlasTexture.width;
                    uv.yMin     /= tilesetAsset.AtlasTexture.height;
                    uv.yMax     /= tilesetAsset.AtlasTexture.height;
                    uv.position += tilesetRects[tilesetIdx].position;
                    tileList.Add(new Tile()
                    {
                        uv = uv
                    });
                }
                tilesetIdx++;
                tilesetAsset.TileViews.Add(new TileView(tilesetTexture.name, tilesetSelection));
            }
            tilesetAsset.SetTiles(tileList);
            return(tilesetAsset);
        }
Exemplo n.º 42
0
        public static void ImportTmxIntoTheScene(string tmxFilePath, Tileset tileset)
        {
            string     tmxFileName = Path.GetFileNameWithoutExtension(tmxFilePath);
            TmxTilemap tilemap     = TmxTilemap.LoadFromFile(tmxFilePath);

            if (tilemap.DicTilesetTex2D.Values.Count == 0)
            {
                return;
            }

            GameObject   tilemapGroupObj = new GameObject(tmxFileName);
            TilemapGroup tilemapGroup    = tilemapGroupObj.AddComponent <TilemapGroup>();
            int          orderInLayer    = 0;

            foreach (TmxLayer layer in tilemap.Map.Layers)
            {
                GameObject tilemapObj = new GameObject(layer.Name);
                tilemapObj.transform.SetParent(tilemapGroupObj.transform);
                Tilemap tilemapBhv = tilemapObj.AddComponent <Tilemap>();
                tilemapBhv.Tileset      = tileset;
                tilemapBhv.OrderInLayer = orderInLayer++;
                tilemapBhv.IsVisible    = layer.Visible;
                tilemapBhv.TintColor    = new Color(1f, 1f, 1f, layer.Opacity);
                for (int gx = 0; gx < layer.Width; gx++)
                {
                    for (int gy = 0; gy < layer.Height; gy++)
                    {
                        int          tileIdx = gy * layer.Width + gx;
                        TmxLayerTile tile    = layer.Tiles[tileIdx];

                        //skip non valid tiles
                        if (tile.GId == 0)
                        {
                            continue;
                        }

                        int  tileId   = tilemap.GetTileAbsoluteId(tile);
                        uint tileData = tileId >= 0 ? (uint)tileId : Tileset.k_TileData_Empty;
                        if (tileData != Tileset.k_TileData_Empty)
                        {
                            // add tile flags
                            if ((tile.GId & k_FLIPPED_HORIZONTALLY_FLAG) != 0)
                            {
                                tileData |= Tileset.k_TileFlag_FlipH;
                            }
                            if ((tile.GId & k_FLIPPED_VERTICALLY_FLAG) != 0)
                            {
                                tileData |= Tileset.k_TileFlag_FlipV;
                            }
                            if ((tile.GId & k_FLIPPED_DIAGONALLY_FLAG) != 0)
                            {
                                tileData |= Tileset.k_TileFlag_Rot90;
                            }
                            //convert from tiled flip diagonal to rot90
                            if ((tileData & Tileset.k_TileFlag_Rot90) != 0)
                            {
                                if (((tile.GId & k_FLIPPED_HORIZONTALLY_FLAG) != 0) != ((tile.GId & k_FLIPPED_VERTICALLY_FLAG) != 0))
                                {
                                    tileData ^= Tileset.k_TileFlag_FlipH;
                                }
                                else
                                {
                                    tileData ^= Tileset.k_TileFlag_FlipV;
                                }
                            }
                        }
                        tilemapBhv.SetTileData(gx, layer.Height - gy - 1, tileData);
                    }
                }
                tilemapBhv.UpdateMesh();
            }
            tilemapGroup.Refresh();
        }
Exemplo n.º 43
0
        private ScreenLayerInfo LoadScreenLayer(XElement node, string stagePath, string name, Tileset tileset, int tileStartX, int tileStartY, bool foreground)
        {
            var tileFilePath = Path.Combine(stagePath, name + ".scn");

            var tileArray = LoadTiles(tileFilePath);
            var tileLayer = new TileLayer(tileArray, tileset, tileStartX, tileStartY);

            var entities = new List <EntityPlacement>();

            foreach (XElement entity in node.Elements("Entity"))
            {
                EntityPlacement info = LoadEntityPlacement(entity);
                entities.Add(info);
            }

            var keyframes = new List <ScreenLayerKeyframe>();

            foreach (var keyframeNode in node.Elements("Keyframe"))
            {
                var frame = LoadScreenLayerKeyFrame(keyframeNode);
                keyframes.Add(frame);
            }

            return(new ScreenLayerInfo(name, tileLayer, foreground, entities, keyframes));
        }
Exemplo n.º 44
0
    private void OnNew(Tileset tileset)
    {
        var instanceID = tileset.GetInstanceID();

        _tsWindow.SetTileSet(instanceID);
    }
Exemplo n.º 45
0
        /// <summary>
        ///
        /// </summary>
        public static void Load()
        {
            Packer packer = new Packer();

            packer.Padding = 0;

            // Load the main font.
            Font         = new SpriteFont(Path() + "fonts/dogica.ttf", 6, ASCII, TextureFilter.Nearest);
            Font.LineGap = 4;

            int packIndex = 0;

            #region Load sprites

            List <SpriteInfo> spriteInfo = new List <SpriteInfo>();

            // Get all sprites.
            string spritePath = Path() + "sprites/";
            foreach (string it in Directory.EnumerateFiles(spritePath))
            {
                if (!it.EndsWith(".ase"))
                {
                    continue;
                }

                SpriteInfo info = new SpriteInfo();
                info.Aseprite  = new Aseprite(it);
                info.Name      = System.IO.Path.GetFileNameWithoutExtension(it);
                info.PackIndex = packIndex;

                foreach (var frame in info.Aseprite.Frames)
                {
                    packer.AddBitmap(packIndex.ToString(), frame.Bitmap);
                    packIndex++;
                }

                spriteInfo.Add(info);
            }

            #endregion

            #region Load tilesets

            List <SpriteInfo> tilesetInfo = new List <SpriteInfo>();

            // Get all tilesets.
            string tilesetPath = Path() + "tilesets/";
            foreach (string it in Directory.EnumerateFiles(tilesetPath))
            {
                if (!it.EndsWith(".ase"))
                {
                    continue;
                }

                SpriteInfo info = new SpriteInfo();
                info.Aseprite  = new Aseprite(it);
                info.Name      = System.IO.Path.GetFileNameWithoutExtension(it);
                info.PackIndex = packIndex;

                var frame   = info.Aseprite.Frames[0];
                var columns = frame.Bitmap.Width / Game.TileWidth;
                var rows    = frame.Bitmap.Height / Game.TileHeight;

                for (int x = 0; x < columns; x++)
                {
                    for (int y = 0; y < rows; y++)
                    {
                        var subrect  = new RectInt(x * Game.TileWidth, y * Game.TileHeight, Game.TileWidth, Game.TileHeight);
                        var subimage = frame.Bitmap.GetSubBitmap(subrect);
                        packer.AddBitmap(packIndex.ToString(), subimage);
                        packIndex++;
                    }
                }

                tilesetInfo.Add(info);
            }

            #endregion

            // Build the atlas.
            packer.Pack();
            SpriteAtlas = new Atlas(packer);

            #region Add sprites

            foreach (SpriteInfo info in spriteInfo)
            {
                Sprite sprite = new Sprite();
                sprite.Name       = info.Name;
                sprite.Origin     = Vector2.Zero;
                sprite.Animations = new List <Sprite.Animation>();

                if (info.Aseprite.Slices.Count > 0 && info.Aseprite.Slices[0].Pivot.HasValue)
                {
                    sprite.Origin = new Vector2(
                        info.Aseprite.Slices[0].Pivot.Value.X,
                        info.Aseprite.Slices[0].Pivot.Value.Y
                        );
                }

                foreach (var tag in info.Aseprite.Tags)
                {
                    Sprite.Animation anim = new Sprite.Animation();
                    anim.Name   = tag.Name;
                    anim.Frames = new List <Sprite.Frame>();

                    for (int i = tag.From; i <= tag.To; i++)
                    {
                        Sprite.Frame frame = new Sprite.Frame();
                        frame.Duration = info.Aseprite.Frames[i].Duration / 1000.0f;
                        frame.Image    = SpriteAtlas.Subtextures[(info.PackIndex + i).ToString()];
                        anim.Frames.Add(frame);
                    }

                    sprite.Animations.Add(anim);
                }

                Sprites.Add(sprite);
            }

            #endregion

            #region Add Tilesets

            foreach (SpriteInfo info in tilesetInfo)
            {
                var frame = info.Aseprite.Frames[0];

                Tileset tileset = new Tileset();
                tileset.Name    = info.Name;
                tileset.Columns = frame.Bitmap.Width / Game.TileWidth;
                tileset.Rows    = frame.Bitmap.Height / Game.TileHeight;

                for (int x = 0, i = info.PackIndex; x < tileset.Columns; x++)
                {
                    for (int y = 0; y < tileset.Rows; y++)
                    {
                        tileset.Tiles[x + y * tileset.Columns] = SpriteAtlas.Subtextures[i.ToString()];
                        i++;
                    }
                }

                Tilesets.Add(tileset);
            }

            #endregion

            // Load the rooms.
            string mapPath = Path() + "map/";
            foreach (string it in Directory.EnumerateFiles(mapPath))
            {
                if (!it.EndsWith(".png"))
                {
                    continue;
                }

                var name  = System.IO.Path.GetFileNameWithoutExtension(it);
                var point = name.Split('x');
                if (point.Length != 2)
                {
                    continue;
                }

                RoomInfo info;
                info.Cell.X = int.Parse(point[0]);
                info.Cell.Y = int.Parse(point[1]);
                info.Image  = new Bitmap(it);

                Debug.Assert(info.Image.Width == Game.Columns, "Room is incorrect width!");
                Debug.Assert(info.Image.Height == Game.Rows, "Room is incorrect height!");

                Rooms.Add(info);
            }
        }
Exemplo n.º 46
0
 public TileSetTilesetAction(TileLayer tileLayer, Tileset setTo)
     : base(tileLayer)
 {
     this.setTo = setTo;
 }
Exemplo n.º 47
0
        public override void Draw(Microsoft.Xna.Framework.GameTime time)
        {
            spriteBatch.Begin();

            int x = 0;
            int y = 0;

            try {
                foreach (TileLogicScript logic in TileLogicManager.Instance.logics)
                {
                    Tileset _s_0 = EditorEngine.Instance.GetTilesetByName(logic.s_0);
                    int     _s_1 = logic.s_1;

                    if ((x << 4) + 16 > this.Width)
                    {
                        y++;
                        x = 0;
                    }

                    Rectangle srcRect    = _s_0.Texture.GetSource(_s_1);
                    Rectangle targetRect = new Rectangle(x << 4, (y << 4) - scrollbar.Value, 16, 16);

                    spriteBatch.Draw(_s_0.Texture.Texture, targetRect, srcRect, Color.White);
                    x += 1;
                }

                this.yMax = y << 4;

                if (!initializedYMax)
                {
                    initializedYMax = true;
                    refreshScrollbar();
                }
            } catch (Exception e) {
                Console.WriteLine("Bullshit occured: " + e);
            }

            Selection selection = new Selection();

            selection.Start(new Vector2(xt << 4, yt << 4));
            selection.End(new Vector2(xt << 4, yt << 4));

            SelectionUtil.DrawRectangle(
                spriteBatch,
                Color.Black,
                new Rectangle(
                    selection.Region.X * 16 + 1,
                    selection.Region.Y * 16 + 1 - this.scrollbar.Value,
                    selection.Region.Width * 16,
                    selection.Region.Height * 16));

            SelectionUtil.DrawRectangle(
                spriteBatch,
                Color.White,
                new Rectangle(
                    selection.Region.X * 16,
                    selection.Region.Y * 16 - this.scrollbar.Value,
                    selection.Region.Width * 16,
                    selection.Region.Height * 16));
            spriteBatch.End();
        }
Exemplo n.º 48
0
 public UnknownTile(Tileset tileset) : base(-1, new TileSprite(tileset))
 {
 }
Exemplo n.º 49
0
 public ApplyTilesetChangesAction(Tileset targetTileset, Tileset backupBeforeChanges)
 {
     this.targetTileset       = targetTileset;
     this.backupBeforeChanges = backupBeforeChanges;
 }
Exemplo n.º 50
0
    void OnGUI()
    {
        //EditorGUILayout.Space(10);
        GUILayout.BeginHorizontal();
        {
            GUILayout.Space(10);
            GUILayout.BeginVertical();
            {
                GUILayout.Space(10);
                GUILayout.Label("SMW Tileset Creation", EditorStyles.boldLabel);
                GUILayout.BeginHorizontal();
                {
                    GUILayout.BeginVertical();
                    {
                        GUILayout.Label("Tileset from Sprite", EditorStyles.boldLabel);
                        //						EditorGUILayout.LabelField("Sprite");
                        EditorGUI.BeginChangeCheck();
                        w_TilesetSprite = EditorGUILayout.ObjectField("Sprite", w_TilesetSprite, typeof(Sprite), false, GUILayout.ExpandWidth(true)) as Sprite;
                        if (EditorGUI.EndChangeCheck())
                        {
                            if (w_TilesetSprite != null)
                            {
                                w_TilesetName = Path.GetFileNameWithoutExtension(AssetDatabase.GetAssetPath(w_TilesetSprite));
                            }
                            else
                            {
                                w_TilesetName = "";
                            }

                            if (w_TilesetTileTypesList != null)
                            {
                                w_TilesetTileTypesList.Clear();
                                w_TilesetTileTypesList = null;
                            }
                        }
                        EditorGUILayout.LabelField("TilesetName: " + w_TilesetName, EditorStyles.boldLabel);
                        w_TargetColor      = EditorGUILayout.ColorField("Target Color:", w_TargetColor);
                        w_ReplacementColor = EditorGUILayout.ColorField("Replacement Color:", w_ReplacementColor);
                        if (w_TilesetSprite == null)
                        {
                            GUI.enabled = false;
                        }
                        if (GUILayout.Button("Prepare Sprite Texture"))
                        {
                            w_TilesetSprite = PrepareSpriteTexture(w_TilesetSprite, 32, w_TargetColor, w_ReplacementColor);
                        }
                        if (GUILayout.Button("Select Tileset's TileTypeFile"))
                        {
                            if (OnGUI_OpenFile(out m_LastFilePath, "tls"))
                            {
                                // file slected and openeed
                                w_TilesetTileTypeFilePath = m_LastFilePath;
                                m_FileOpened           = true;
                                w_TilesetTileTypesList = ReadTileTypes(w_TilesetTileTypeFilePath);
                                if (w_TilesetTileTypesList == null)
                                {
                                    Debug.LogError("w_TilesetTileTypesList == null");
                                }
                                else
                                {
                                    for (int i = 0; i < w_TilesetTileTypesList.Count; i++)
                                    {
                                        Debug.Log(Path.GetDirectoryName(m_LastFilePath) + "/" + Path.GetFileName(m_LastFilePath) + " " + w_TilesetTileTypesList[i] + " - " + w_TilesetTileTypesList[i].ToString());                                        // + " " + w_TilesetTileTypes[i]);
                                    }
                                }
                            }
                            else
                            {
                                // file open dialouge cancled
                                w_TilesetTileTypesList.Clear();
                                w_TilesetTileTypesList    = null;
                                w_TilesetTileTypeFilePath = "";
                                m_FileOpened = false;
                            }
                        }
                        EditorGUILayout.LabelField("Tileset's Tile Type File Path = " + w_TilesetTileTypeFilePath, GUILayout.ExpandWidth(true));

                        bool current = GUI.enabled;
                        w_TileSpriteAlignment = (SpriteAlignment)EditorGUILayout.EnumPopup("Pivot", w_TileSpriteAlignment);

                        if (w_TileSpriteAlignment != SpriteAlignment.Custom)
                        {
                            // deaktiviere custom Offset
                            GUI.enabled = false;
                        }
                        // GUI: Custom Pivot
                        w_customTilePivotOffset = EditorGUILayout.Vector2Field("Custom Offset", w_customTilePivotOffset);
                        GUI.enabled             = current;

                        w_TilePixelWidth  = EditorGUILayout.IntField("Tile Width (px)", w_TilePixelWidth);
                        w_TilePixelHeight = EditorGUILayout.IntField("Tile Height (px)", w_TilePixelHeight);
                        if (w_TilesetSprite != null)
                        {
                            GUI.enabled = true;
                            GUILayout.Label("Spritename = " + w_TilesetSprite.name);
                            if (GUILayout.Button("Slice & Prepare Tileset Sprite", GUILayout.ExpandWidth(false)))
                            {
                                TextureImporter textureImporter = (TextureImporter)UnityEditor.TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(w_TilesetSprite));
                                PerformMetaSlice(w_TilesetSprite.texture, textureImporter, w_TileSpriteAlignment, w_customTilePivotOffset, w_TilePixelWidth, w_TilePixelHeight, w_TilesetPixelPerUnit);
                            }
                            Color temp = GUI.color;
                            if (w_TilesetSprite.pixelsPerUnit == 32)
                            {
                                GUI.color = Color.green;
                                //								EditorGUILayout.LabelField("<color=green>PixelPerUnit = " + w_TilesetSprite.pixelsPerUnit + "</color>");
                            }
                            else
                            {
                                GUI.color = Color.red;
                                //								EditorGUILayout.LabelField("<color=red>PixelPerUnit = " + w_TilesetSprite.pixelsPerUnit + "</color>");
                            }
                            EditorGUILayout.LabelField("PixelPerUnit = " + w_TilesetSprite.pixelsPerUnit);
                            GUI.color = temp;
                        }
                        else
                        {
                            GUILayout.Label("no Sprite selected", EditorStyles.boldLabel);
                            GUI.enabled = false;
                        }
                        if (!m_FileOpened)
                        {
                            if (GUI.enabled)
                            {
                                GUILayout.Label("no Tileset TileTypeFile selected", EditorStyles.boldLabel);
                                GUI.enabled = false;
                            }
                        }
                        if (w_TilesetTileTypesList == null)
                        {
                            if (GUI.enabled)
                            {
                                GUILayout.Label("no Tileset TileTypeFile in List", EditorStyles.boldLabel);
                                GUI.enabled = false;
                            }
                        }
                        GUILayout.BeginHorizontal();
                        if (GUILayout.Button("Create Tileset from Sprite & TLS File", GUILayout.ExpandWidth(false)))
                        {
                            currentTileset = Create(w_TilesetName, w_TilesetSprite, w_TilesetTileTypesList, GetPivotValue(w_TileSpriteAlignment, w_customTilePivotOffset));
                            //							EditorUtility.FocusProjectWindow();							<-- Satck Overflow
                            //							Selection.activeObject = currentTileset;
                        }
                        bool lastState = GUI.enabled;
                        if (true)
                        {
                            //TODO
                            GUI.enabled = true;
                        }
                        if (GUILayout.Button("Create Tileset from Sprite without TLS File", GUILayout.ExpandWidth(false)))
                        {
                            currentTileset = Create(w_TilesetName, w_TilesetSprite, null, GetPivotValue(w_TileSpriteAlignment, w_customTilePivotOffset));
                            //							EditorUtility.FocusProjectWindow();							<-- Satck Overflow
                            //							Selection.activeObject = currentTileset;
                        }
                        GUI.enabled = lastState;
                        GUILayout.EndHorizontal();
                    }
                    GUILayout.EndVertical();
                    GUI.enabled = true;
                    if (GUILayout.Button("Create empty Tileset SO", GUILayout.ExpandWidth(false)))
                    {
                        currentTileset = CreateEmpty();
                    }
                }
                GUILayout.EndHorizontal();
                GUILayout.Space(10);
                GUILayout.Label("Current Tileset", EditorStyles.boldLabel);
                currentTileset = EditorGUILayout.ObjectField("Tileset ", currentTileset, typeof(Tileset), false) as Tileset;
                GUILayout.Space(10);
                GUILayout.Label("Tileset Tile Preview", EditorStyles.boldLabel);

                w_TilesetPixelPerUnit = EditorGUILayout.IntField("Tileset Pixel per Unit", w_TilesetPixelPerUnit);

                w_SubTilePosX = EditorGUILayout.IntField("X (iCol)", w_SubTilePosX);
                w_SubTilePosY = EditorGUILayout.IntField("Y (iRow)", w_SubTilePosY);

                //				if (GUILayout.Button("Show Tile (SubSprite)", GUILayout.ExpandWidth(false)))
                //				{
                //					CreateGameObjectWithSubSprite(w_SubTilePosX, w_SubTilePosY);
                //				}
                if (GUILayout.Button("Show Tile (NewSprite)", GUILayout.ExpandWidth(false)))
                {
                    CreateGameObjectWithNewSprite(w_SubTilePosX, w_SubTilePosY);
                }
                if (GUILayout.Button("Show Tile (AssetSlicedSprite)", GUILayout.ExpandWidth(false)))
                {
                    CreateGameObjectWithAssetSprite(w_SubTilePosX, w_SubTilePosY);
                }
            }
            GUILayout.EndVertical();
        }
        GUILayout.EndHorizontal();
        //		Repaint();
    }
Exemplo n.º 51
0
 public static string GetAmbientNightSound(Tileset tileset)
 {
     return($"{GetAmbientSound(tileset)}Night");
 }
Exemplo n.º 52
0
 public MapEnvironment(Tileset tileset, uint width, uint height, int cliffLevel)
     : this(tileset, width, height, cliffLevel, new RectangleMargins(6, 6, 4, 8))
 {
 }
Exemplo n.º 53
0
        private LuaVariableListDeclarationSyntax GetMainFunctionSyntax(float left, float right, float top, float bottom, Tileset tileset, SoundEnvironment sound, params string[] initFunctions)
        {
            var localLeft = new LuaBinaryExpressionSyntax(
                new LuaFloatLiteralExpressionSyntax(left),
                LuaSyntaxNode.Tokens.Plus,
                new LuaInvocationExpressionSyntax("GetCameraMargin", "CAMERA_MARGIN_LEFT"));
            var localRight = new LuaBinaryExpressionSyntax(
                new LuaFloatLiteralExpressionSyntax(right),
                LuaSyntaxNode.Tokens.Sub,
                new LuaInvocationExpressionSyntax("GetCameraMargin", "CAMERA_MARGIN_RIGHT"));
            var localTop = new LuaBinaryExpressionSyntax(
                new LuaFloatLiteralExpressionSyntax(top),
                LuaSyntaxNode.Tokens.Sub,
                new LuaInvocationExpressionSyntax("GetCameraMargin", "CAMERA_MARGIN_TOP"));
            var localBottom = new LuaBinaryExpressionSyntax(
                new LuaFloatLiteralExpressionSyntax(bottom),
                LuaSyntaxNode.Tokens.Plus,
                new LuaInvocationExpressionSyntax("GetCameraMargin", "CAMERA_MARGIN_BOTTOM"));
            var locals = new[]
            {
                localLeft,
                localRight,
                localTop,
                localBottom,
            };

            var statements = new List <LuaStatementSyntax>
            {
                new LuaLocalDeclarationStatementSyntax(new LuaLocalVariablesStatementSyntax(
                                                           new[]
                {
                    new LuaSymbolNameSyntax(new LuaIdentifierLiteralExpressionSyntax("left")),
                    new LuaSymbolNameSyntax(new LuaIdentifierLiteralExpressionSyntax("right")),
                    new LuaSymbolNameSyntax(new LuaIdentifierLiteralExpressionSyntax("top")),
                    new LuaSymbolNameSyntax(new LuaIdentifierLiteralExpressionSyntax("bottom")),
                },
                                                           locals)),
                new LuaExpressionStatementSyntax(
                    new LuaInvocationExpressionSyntax(
                        "SetCameraBounds",
                        "left",
                        "bottom",
                        "right",
                        "top",
                        "left",
                        "top",
                        "right",
                        "bottom")),
                new LuaExpressionStatementSyntax(new LuaInvocationExpressionSyntax(
                                                     "SetDayNightModels",
                                                     new LuaStringLiteralExpressionSyntax(LightEnvironmentProvider.GetTerrainLightEnvironmentModel(tileset)),
                                                     new LuaStringLiteralExpressionSyntax(LightEnvironmentProvider.GetUnitLightEnvironmentModel(tileset)))),
                new LuaExpressionStatementSyntax(new LuaInvocationExpressionSyntax("NewSoundEnvironment", new LuaStringLiteralExpressionSyntax(SoundEnvironmentProvider.GetSoundEnvironment(sound)))),
                new LuaExpressionStatementSyntax(new LuaInvocationExpressionSyntax("SetAmbientDaySound", new LuaStringLiteralExpressionSyntax(SoundEnvironmentProvider.GetAmbientDaySound(tileset)))),
                new LuaExpressionStatementSyntax(new LuaInvocationExpressionSyntax("SetAmbientNightSound", new LuaStringLiteralExpressionSyntax(SoundEnvironmentProvider.GetAmbientNightSound(tileset)))),
                new LuaExpressionStatementSyntax(new LuaInvocationExpressionSyntax(
                                                     "SetMapMusic",
                                                     new LuaStringLiteralExpressionSyntax("Music"),
                                                     LuaIdentifierLiteralExpressionSyntax.False,
                                                     LuaNumberLiteralExpressionSyntax.Zero)),
            };

            foreach (var initFunction in initFunctions)
            {
                statements.Add(new LuaExpressionStatementSyntax(new LuaInvocationExpressionSyntax(initFunction)));
            }

            var functionSyntax = new LuaFunctionExpressionSyntax();

            functionSyntax.AddStatements(statements);

            var mainFunctionDeclarator = new LuaVariableDeclaratorSyntax("main", functionSyntax);

            mainFunctionDeclarator.IsLocalDeclaration = false;

            var globalFunctionSyntax = new LuaVariableListDeclarationSyntax();

            globalFunctionSyntax.Variables.Add(mainFunctionDeclarator);

            return(globalFunctionSyntax);
        }
Exemplo n.º 54
0
        public void LoadMinecart()
        {
            // if mode7 map
            if (Index < 2)
            {
                labelStartXY.Visible = true;
                startX.Visible       = true;
                startY.Visible       = true;
                startX.Value         = Bits.GetShort(Model.ROM, 0x039670);
                startY.Value         = Bits.GetShort(Model.ROM, 0x039679);

                // Create map elements
                PaletteSet = Model.M7PaletteSet;
                Tileset    = new Tileset(Model.M7PaletteSet, TilesetType.Mode7);
                if (Index == 0)
                {
                    Tilemap = new Mode7Tilemap(Model.M7TilemapA, Tileset, PaletteSet);
                }
                else
                {
                    Tilemap = new Mode7Tilemap(Model.M7TilemapB, Tileset, PaletteSet);
                }

                // Load the screens
                toggleScreens.Enabled = false;
                ScreensForm.Hide();
                ObjectsForm.Hide();
            }
            // if side-scrolling map
            else
            {
                labelStartXY.Visible = false;
                startX.Visible       = false;
                startY.Visible       = false;

                // Create map elements
                PaletteSet            = Model.SSPaletteSet;
                Tileset               = new Tileset(Model.SSTileset, Model.SSGraphics, PaletteSet, 16, 16, TilesetType.SideScrolling);
                Tilemap               = new SideTilemap(Model.SSTilemap, null, Tileset, PaletteSet);
                toggleScreens.Enabled = true;
                ScreensForm.LoadScreens();

                // ObjectsForm
                toggleScreens.Enabled = true;
                ScreensForm.Show(dockPanel, DockState.DockTop);
                ObjectsForm.Left = this.Right + 10;
                ObjectsForm.Top  = this.Top;
                ObjectsForm.Show(ScreensForm.Pane, DockAlignment.Right, 0.25);
                ObjectsForm.InitializeObjects();
            }

            // (Re)load editors and forms
            ReloadPaletteEditor();
            ReloadGraphicEditor();
            ReloadSpritePaletteEditor();
            ReloadSpriteGraphicEditor();
            LoadTilesetEditor();
            LoadTilemapEditor();

            // Rails properties
            TilesetForm.Rails = state.Rails && Index < 2;
        }
Exemplo n.º 55
0
        public MapEnvironment(Tileset tileset, uint width, uint height, int cliffLevel, RectangleMargins cameraBoundsComplements)
            : this()
        {
            if (!Enum.IsDefined(typeof(Tileset), tileset))
            {
                throw new ArgumentOutOfRangeException(nameof(tileset));
            }

            var maxx = width - 1;

            if ((maxx % 32) != 0 || width == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(width));
            }

            var maxy = height - 1;

            if ((maxy % 32) != 0 || height == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(height));
            }

            if (cameraBoundsComplements is null)
            {
                throw new ArgumentNullException(nameof(cameraBoundsComplements));
            }

            _tileset = tileset;
            _version = LatestVersion;
            _width   = width;
            _height  = height;
            _left    = MapWidth / -2f;
            _bottom  = MapHeight / -2f;

            _terrainTypes = GetDefaultTerrainTypes().ToList();
            _cliffTypes   = GetDefaultCliffTypes().ToList();

            var edgeLeft   = cameraBoundsComplements.Left;
            var edgeRight  = maxx - cameraBoundsComplements.Right;
            var edgeBottom = cameraBoundsComplements.Bottom;
            var edgeTop    = maxy - cameraBoundsComplements.Top;

            for (var y = 0; y < _width; y++)
            {
                for (var x = 0; x < _height; x++)
                {
                    var tile = new MapTile();

                    tile.CliffLevel     = cliffLevel;
                    tile.CliffTexture   = 15;
                    tile.CliffVariation = 0;

                    tile.Height      = 0;
                    tile.IsBlighted  = false;
                    tile.IsBoundary  = false;
                    tile.IsEdgeTile  = x != maxx && y != maxy && (x < edgeLeft || x >= edgeRight || y < edgeBottom || y >= edgeTop);
                    tile.IsRamp      = false;
                    tile.IsWater     = false;
                    tile.Texture     = 0;
                    tile.Variation   = 0;
                    tile.WaterHeight = 0;

                    _tiles.Add(tile);
                }
            }
        }
Exemplo n.º 56
0
 protected override void OnInitialized()
 {
     base.OnInitialized();
     tileset = Environment.Resources.Textures.PenguinWalking;
 }
Exemplo n.º 57
0
 public MapEnvironment(Tileset tileset, uint width, uint height)
     : this(tileset, width, height, DefaultCliffLevel)
 {
 }
        private static void AddTileLayerTiles(TiledMapSave tiledMapSave, ReducedLayerInfo reducedLayerInfo, int i, AbstractMapLayer tiledLayer, Tileset tileSet, int tileWidth, int tileHeight)
        {
            var asMapLayer = tiledLayer as MapLayer;
            var count      = asMapLayer.data[0].tiles.Count;

            for (int dataId = 0; dataId < count; dataId++)
            {
                var dataAtIndex = asMapLayer.data[0].tiles[dataId];

                if (dataAtIndex != 0)
                {
                    ReducedQuadInfo quad = new DataTypes.ReducedQuadInfo();

                    float tileCenterX;
                    float tileCenterY;
                    float tileZ;

                    tiledMapSave.CalculateWorldCoordinates(i, dataId, tileWidth, tileHeight, asMapLayer.width,
                                                           out tileCenterX, out tileCenterY, out tileZ);

                    quad.LeftQuadCoordinate   = tileCenterX - tileWidth / 2.0f;
                    quad.BottomQuadCoordinate = tileCenterY - tileHeight / 2.0f;

                    var gid = dataAtIndex;

                    //quad.FlipFlags = (byte)((gid & 0xf0000000) >> 28);

                    var valueWithoutFlip = gid & 0x0fffffff;

                    spriteSaveForConversion.RotationZ      = 0;
                    spriteSaveForConversion.FlipHorizontal = false;
                    TiledMapSave.SetSpriteTextureCoordinates(gid, spriteSaveForConversion, tileSet, tiledMapSave.orientation);


                    bool isRotated = spriteSaveForConversion.RotationZ != 0;
                    if (isRotated)
                    {
                        quad.FlipFlags = (byte)(quad.FlipFlags | ReducedQuadInfo.FlippedDiagonallyFlag);
                    }

                    var leftTextureCoordinate = System.Math.Min(spriteSaveForConversion.LeftTextureCoordinate, spriteSaveForConversion.RightTextureCoordinate);
                    var topTextureCoordinate  = System.Math.Min(spriteSaveForConversion.TopTextureCoordinate, spriteSaveForConversion.BottomTextureCoordinate);

                    if (spriteSaveForConversion.LeftTextureCoordinate > spriteSaveForConversion.RightTextureCoordinate)
                    {
                        quad.FlipFlags = (byte)(quad.FlipFlags | ReducedQuadInfo.FlippedHorizontallyFlag);
                    }

                    if (spriteSaveForConversion.TopTextureCoordinate > spriteSaveForConversion.BottomTextureCoordinate)
                    {
                        quad.FlipFlags = (byte)(quad.FlipFlags | ReducedQuadInfo.FlippedVerticallyFlag);
                    }

                    quad.LeftTexturePixel = (ushort)FlatRedBall.Math.MathFunctions.RoundToInt(leftTextureCoordinate * tileSet.Images[0].width);
                    quad.TopTexturePixel  = (ushort)FlatRedBall.Math.MathFunctions.RoundToInt(topTextureCoordinate * tileSet.Images[0].height);


                    if (tileSet.TileDictionary.ContainsKey(valueWithoutFlip))
                    {
                        var dictionary = tileSet.TileDictionary[valueWithoutFlip].PropertyDictionary;
                        if (dictionary.ContainsKey("name"))
                        {
                            quad.Name = tileSet.TileDictionary[valueWithoutFlip].PropertyDictionary["name"];
                        }
                        else if (dictionary.ContainsKey("Name"))
                        {
                            quad.Name = tileSet.TileDictionary[valueWithoutFlip].PropertyDictionary["Name"];
                        }
                    }

                    reducedLayerInfo?.Quads.Add(quad);
                }
            }
        }
Exemplo n.º 59
0
    void Start()
    {
        Physics2D.IgnoreLayerCollision(10, 11);
        nextLevelData = new AssetProxy(typeof(NextLevelData)).LoadAsset("Objects/NextData.asset");
        gamData       = new AssetProxy(typeof(GameData)).LoadAsset("Objects/Data.asset");
        Debug.Log(nextLevelData);
        nextLevelData.GenerateNextLevelData();
        Vector2Int ms       = nextLevelData.GetMapSize();
        int        MapSizeX = ms.x;
        int        MapSizeY = ms.y;

        System.DateTime start = System.DateTime.Now;

        edgeCollider        = GetComponent <EdgeCollider2D>();
        edgeCollider.points = new Vector2[] { new Vector2(-MapSizeX / 2, -MapSizeY / 2), new Vector2(-MapSizeX / 2, MapSizeY / 2), new Vector2(MapSizeX / 2, MapSizeY / 2), new Vector2(MapSizeX / 2, -MapSizeY / 2), new Vector2(-MapSizeX / 2, -MapSizeY / 2) };
        GameMap map = new GameMap(MapSizeX, MapSizeY);

        map.ground      = GetComponentsInChildren <Tilemap>()[0];
        map.decorations = GetComponentsInChildren <Tilemap>()[1];
        map.structures  = GetComponentsInChildren <Tilemap>()[2];

        TilesetCreator tilesetCreator;

        Locations location = nextLevelData.GetLocation();

        switch (location)
        {
        case Locations.Forest:
            tilesetCreator = new ForestTilesetCreator();
            break;

        case Locations.Desert:
            tilesetCreator = new DesertTilesetCreator();
            break;

        case Locations.Village:
            tilesetCreator = new VillageTilesetCreator();
            break;

        default:
            tilesetCreator = new ForestTilesetCreator();
            break;
        }

        Tileset ts = tilesetCreator.CreateTileset();

        MapBuilder builder;

        MapType type = nextLevelData.GetMapType();

        switch (type)
        {
        case MapType.Dungeon:
            builder = new DungeonMapBuilder(new Rect(-MapSizeX / 2, -MapSizeY / 2, MapSizeX, MapSizeY), map, ts);
            break;

        case MapType.Ruins:
            builder = new RuinsMapBuilder(new Rect(-MapSizeX / 2, -MapSizeY / 2, MapSizeX, MapSizeY), map, ts);
            break;

        case MapType.Village:
            tilesetCreator = new VillageTilesetCreator();
            ts             = tilesetCreator.CreateTileset();
            builder        = new VillageMapBuilder(new Rect(-MapSizeX / 2, -MapSizeY / 2, MapSizeX, MapSizeY), map, ts);
            break;

        default:
            builder = new DungeonMapBuilder(new Rect(-MapSizeX / 2, -MapSizeY / 2, MapSizeX, MapSizeY), map, ts);
            break;
        }
        //MapBuilder builder = new VillageMapBuilder(new Rect(-MapSizeX / 2, -MapSizeY / 2, MapSizeX, MapSizeY), map);


        MapGenerator mapGen = new MapGenerator(builder);

        mapGen.Generate();
        builder.GetMap();
        Spawner spawner = new Spawner();

        spawner.Spawn(map, ts);
        BuffSpawner buffSpawner = new BuffSpawner();

        buffSpawner.Spawn(map, ts);
        System.TimeSpan timeItTook = System.DateTime.Now - start;
        Debug.Log(string.Format("Map generated, {0}", timeItTook));
    }
Exemplo n.º 60
0
 public MapEnvironment(Tileset tileset, uint width, uint height, RectangleMargins cameraBoundsComplements)
     : this(tileset, width, height, DefaultCliffLevel, cameraBoundsComplements)
 {
 }