summaryrefslogtreecommitdiff
path: root/Plugins/MonoGame.Extended/source/MonoGame.Extended.Tiled/TiledMapTileset.cs
blob: ed14e158eddb131ab54bb0035ab6c17bc4f1ba0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.Extended.TextureAtlases;

namespace MonoGame.Extended.Tiled
{
    public interface ITileset
    {
        int ActualWidth { get; }
        int Columns { get; }
        int ActualHeight { get; }
        int Rows { get; }
        int TileWidth { get; }
        int TileHeight { get; }
        Texture2D Texture { get; }
        TextureRegion2D GetRegion(int column, int row);
    }

    public class TiledMapTileset : ITileset
    {
        public TiledMapTileset(Texture2D texture, string type, int tileWidth, int tileHeight, int tileCount, int spacing, int margin, int columns)
        {
            Texture = texture;
            Type = type;
            TileWidth = tileWidth;
            TileHeight = tileHeight;
            TileCount = tileCount;
            Spacing = spacing;
            Margin = margin;
            Columns = columns;
            Properties = new TiledMapProperties();
            Tiles = new List<TiledMapTilesetTile>();
        }

        public string Name => Texture.Name;
        public Texture2D Texture { get; }

        public TextureRegion2D GetRegion(int column, int row)
        {
            var x = Margin + column * (TileWidth + Spacing);
            var y = Margin + row * (TileHeight + Spacing);
            return new TextureRegion2D(Texture, x, y, TileWidth, TileHeight);
        }

        public string Type { get; }
        public int TileWidth { get; }
        public int TileHeight { get; }
        public int Spacing { get; }
        public int Margin { get; }
        public int TileCount { get; }
        public int Columns { get; }
        public List<TiledMapTilesetTile> Tiles { get; }
        public TiledMapProperties Properties { get; }

        public int Rows => (int)Math.Ceiling((double) TileCount / Columns);
        public int ActualWidth => TileWidth * Columns;
        public int ActualHeight => TileHeight * Rows;

        public Rectangle GetTileRegion(int localTileIdentifier)
        {
            return Texture is not null
                ? TiledMapHelper.GetTileSourceRectangle(localTileIdentifier, TileWidth, TileHeight, Columns, Margin,
                    Spacing)
                : Tiles.FirstOrDefault(x => x.LocalTileIdentifier == localTileIdentifier).Texture.Bounds;
        }
    }
}