tiled 0.15.0

A rust crate for loading maps created by the Tiled editor
Documentation
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Structures related to Tiled maps.

use std::{
    collections::HashMap,
    fmt,
    path::{Path, PathBuf},
    str::FromStr,
    sync::Arc,
};

use xml::attribute::OwnedAttribute;

use crate::{
    error::{Error, Result},
    layers::{LayerData, LayerTag},
    properties::{parse_properties, Color, Properties},
    tileset::Tileset,
    util::{get_attrs, parse_tag, XmlEventResult},
    EmbeddedParseResultType, Layer, ResourceCache, ResourceReader,
};

pub(crate) struct MapTilesetGid {
    pub first_gid: Gid,
    pub tileset: Arc<Tileset>,
}

/// All Tiled map files will be parsed into this. Holds all the layers and tilesets.
#[derive(PartialEq, Clone)]
pub struct Map {
    version: String,
    /// The path first used in a [`ResourceReader`] to load this map.
    pub source: PathBuf,
    /// The way tiles are laid out in the map.
    pub orientation: Orientation,
    /// Width of the map, in tiles.
    ///
    /// ## Note
    /// There is no guarantee that this value will be the same as the width from its tile layers.
    pub width: u32,
    /// Height of the map, in tiles.
    ///
    /// ## Note
    /// There is no guarantee that this value will be the same as the height from its tile layers.
    pub height: u32,
    /// Tile width, in pixels.
    ///
    /// ## Note
    /// This value along with [`Self::tile_height`] determine the general size of the map, and
    /// individual tiles may have different sizes. As such, there is no guarantee that this value
    /// will be the same as the one from the tilesets the map is using.
    pub tile_width: u32,
    /// Tile height, in pixels.
    ///
    /// ## Note
    /// This value along with [`Self::tile_width`] determine the general size of the map, and
    /// individual tiles may have different sizes. As such, there is no guarantee that this value
    /// will be the same as the one from the tilesets the map is using.
    pub tile_height: u32,
    /// The length of the side of a hexagonal tile in pixels (used by tile layers on hexagonal maps).
    pub hex_side_length: Option<i32>,
    /// The stagger axis of Hexagonal/Staggered map.
    pub stagger_axis: StaggerAxis,
    /// The stagger index of Hexagonal/Staggered map.
    pub stagger_index: StaggerIndex,
    /// The tilesets present on this map.
    tilesets: Vec<Arc<Tileset>>,
    /// The layers present in this map.
    layers: Vec<LayerData>,
    /// The custom properties of this map.
    pub properties: Properties,
    /// The background color of this map, if any.
    pub background_color: Option<Color>,
    infinite: bool,
    /// The type of the map, which is arbitrary and set by the user.
    pub user_type: Option<String>,
}

impl fmt::Debug for Map {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Map")
            .field("version", &self.version)
            .field("orientation", &self.orientation)
            .field("width", &self.width)
            .field("height", &self.height)
            .field("tile_width", &self.tile_width)
            .field("tile_height", &self.tile_height)
            .field("stagger_axis", &self.stagger_axis)
            .field("stagger_index", &self.stagger_index)
            .field("tilesets", &format!("{} tilesets", self.tilesets.len()))
            .field("layers", &format!("{} layers", self.layers.len()))
            .field("properties", &self.properties)
            .field("background_color", &self.background_color)
            .field("infinite", &self.infinite)
            .field("user_type", &self.user_type)
            .finish()
    }
}

impl Map {
    /// The TMX format version this map was saved to. Equivalent to the map file's `version`
    /// attribute.
    pub fn version(&self) -> &str {
        self.version.as_ref()
    }

    /// Whether this map is infinite. An infinite map has no fixed size and can grow in all
    /// directions. Its layer data is stored in chunks. This value determines whether the map's
    /// tile layers are [`FiniteTileLayer`](crate::FiniteTileLayer)s or [`crate::InfiniteTileLayer`](crate::InfiniteTileLayer)s.
    pub fn infinite(&self) -> bool {
        self.infinite
    }
}

impl Map {
    /// Get a reference to the map's tilesets.
    #[inline]
    pub fn tilesets(&self) -> &[Arc<Tileset>] {
        self.tilesets.as_ref()
    }

    /// Get an iterator over top-level layers in the map in ascending order of their layer index.
    ///
    /// Note: "top-level" means that if a map has layers of `LayerDataType::Group` type, you
    /// need to recursively enumerate those group layers.
    ///
    /// ## Example
    /// ```
    /// # use tiled::Loader;
    /// #
    /// # fn main() {
    /// # struct Renderer;
    /// # impl Renderer {
    /// #     fn render(&self, _: tiled::TileLayer) {}
    /// # }
    /// # let my_renderer = Renderer;
    /// # let map = Loader::new()
    /// #     .load_tmx_map("assets/tiled_group_layers.tmx")
    /// #     .unwrap();
    /// #
    /// let tile_layers = map.layers().filter_map(|layer| match layer.layer_type() {
    ///     tiled::LayerType::Tiles(layer) => Some(layer),
    ///     _ => None,
    /// });
    ///
    /// for layer in tile_layers {
    ///     my_renderer.render(layer);
    /// }
    /// # }
    /// ```
    #[inline]
    pub fn layers(&self) -> impl ExactSizeIterator<Item = Layer> {
        self.layers.iter().map(move |layer| Layer::new(self, layer))
    }

    /// Returns the top-level layer that has the specified index, if it exists.
    pub fn get_layer(&self, index: usize) -> Option<Layer> {
        self.layers.get(index).map(|data| Layer::new(self, data))
    }
}

impl Map {
    pub(crate) fn parse_xml(
        parser: &mut impl Iterator<Item = XmlEventResult>,
        attrs: Vec<OwnedAttribute>,
        map_path: &Path,
        reader: &mut impl ResourceReader,
        cache: &mut impl ResourceCache,
    ) -> Result<Map> {
        let (
            (c, infinite, user_type, user_class, stagger_axis, stagger_index, hex_side_length),
            (v, o, w, h, tw, th),
        ) = get_attrs!(
            for v in attrs {
                Some("backgroundcolor") => colour ?= v.parse(),
                Some("infinite") => infinite = v == "1",
                Some("type") => user_type ?= v.parse(),
                Some("class") => user_class ?= v.parse(),
                Some("staggeraxis") => stagger_axis ?= v.parse::<StaggerAxis>(),
                Some("staggerindex") => stagger_index ?= v.parse::<StaggerIndex>(),
                Some("hexsidelength") => hex_side_length ?= v.parse(),
                "version" => version = v,
                "orientation" => orientation ?= v.parse::<Orientation>(),
                "width" => width ?= v.parse::<u32>(),
                "height" => height ?= v.parse::<u32>(),
                "tilewidth" => tile_width ?= v.parse::<u32>(),
                "tileheight" => tile_height ?= v.parse::<u32>(),
            }
            ((colour, infinite, user_type, user_class, stagger_axis, stagger_index, hex_side_length), (version, orientation, width, height, tile_width, tile_height))
        );

        let infinite = infinite.unwrap_or(false);
        let user_type = user_type.or(user_class);
        let stagger_axis = stagger_axis.unwrap_or_default();
        let stagger_index = stagger_index.unwrap_or_default();

        // We can only parse sequentally, but tilesets are guaranteed to appear before layers.
        // So we can pass in tileset data to layer construction without worrying about unfinished
        // data usage.
        let mut layers = Vec::new();
        let mut properties = HashMap::new();
        let mut tilesets = Vec::new();

        parse_tag!(parser, "map", {
            "tileset" => |attrs: Vec<OwnedAttribute>| {
                let res = Tileset::parse_xml_in_map(parser, &attrs, map_path,  reader, cache)?;
                match res.result_type {
                    EmbeddedParseResultType::ExternalReference { tileset_path } => {
                        let tileset = if let Some(ts) = cache.get_tileset(&tileset_path) {
                            ts
                        } else {
                            let tileset = Arc::new(crate::parse::xml::parse_tileset(&tileset_path,  reader, cache)?);
                            cache.insert_tileset(tileset_path.clone(), tileset.clone());
                            tileset
                        };

                        tilesets.push(MapTilesetGid{first_gid: res.first_gid, tileset});
                    }
                    EmbeddedParseResultType::Embedded { tileset } => {
                        tilesets.push(MapTilesetGid{first_gid: res.first_gid, tileset: Arc::new(tileset)});
                    },
                };
                Ok(())
            },
            "layer" => |attrs| {
                layers.push(LayerData::new(
                    parser,
                    attrs,
                    LayerTag::Tiles,
                    infinite,
                    map_path,
                    &tilesets,
                    None,
                    reader,
                    cache
                )?);
                Ok(())
            },
            "imagelayer" => |attrs| {
                layers.push(LayerData::new(
                    parser,
                    attrs,
                    LayerTag::Image,
                    infinite,
                    map_path,
                    &tilesets,
                    None,
                    reader,
                    cache
                )?);
                Ok(())
            },
            "objectgroup" => |attrs| {
                layers.push(LayerData::new(
                    parser,
                    attrs,
                    LayerTag::Objects,
                    infinite,
                    map_path,
                    &tilesets,
                    None,
                    reader,
                    cache
                )?);
                Ok(())
            },
            "group" => |attrs| {
                layers.push(LayerData::new(
                    parser,
                    attrs,
                    LayerTag::Group,
                    infinite,
                    map_path,
                    &tilesets,
                    None,
                    reader,
                    cache
                )?);
                Ok(())
            },
            "properties" => |_| {
                properties = parse_properties(parser)?;
                Ok(())
            },
        });

        // We do not need first GIDs any more
        let tilesets = tilesets.into_iter().map(|ts| ts.tileset).collect();

        Ok(Map {
            version: v,
            source: map_path.to_owned(),
            orientation: o,
            width: w,
            height: h,
            tile_width: tw,
            tile_height: th,
            hex_side_length,
            stagger_axis,
            stagger_index,
            tilesets,
            layers,
            properties,
            background_color: c,
            infinite,
            user_type,
        })
    }
}

// Specifies whether the odd or even rows/columns are shifted half a tile
// right/down. Only applies to Staggered and Hexagonal map orientations.
#[derive(Debug, PartialEq, Eq, Copy, Clone, Default)]
#[allow(missing_docs)]
pub enum StaggerIndex {
    Even,
    #[default]
    Odd,
}

#[derive(Debug)]
/// An error arising from trying to parse an [`StaggerIndex`] that is not valid.
pub struct StaggerIndexError {
    /// The invalid string found.
    pub str_found: String,
}

impl std::fmt::Display for StaggerIndexError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "failed to parse stagger index, valid options are `even`, `odd` \
        but got `{}` instead",
            self.str_found
        ))
    }
}

impl FromStr for StaggerIndex {
    type Err = StaggerIndexError;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "even" => Ok(StaggerIndex::Even),
            "odd" => Ok(StaggerIndex::Odd),
            _ => Err(StaggerIndexError {
                str_found: s.to_owned(),
            }),
        }
    }
}

// Specifies which axis is staggered. Only applies to Staggered and Hexagonal
// map orientations.
#[derive(Debug, PartialEq, Eq, Copy, Clone, Default)]
#[allow(missing_docs)]
pub enum StaggerAxis {
    X,
    #[default]
    Y,
}

#[derive(Debug)]
/// An error arising from trying to parse an [`StaggerAxis`] that is not valid.
pub struct StaggerAxisError {
    /// The invalid string found.
    pub str_found: String,
}

impl std::fmt::Display for StaggerAxisError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "failed to parse stagger axis, valid options are `x`, `y` \
        but got `{}` instead",
            self.str_found
        ))
    }
}

impl FromStr for StaggerAxis {
    type Err = StaggerAxisError;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "x" => Ok(StaggerAxis::X),
            "y" => Ok(StaggerAxis::Y),
            _ => Err(StaggerAxisError {
                str_found: s.to_owned(),
            }),
        }
    }
}

/// Represents the way tiles are laid out in a map.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[allow(missing_docs)]
pub enum Orientation {
    Orthogonal,
    Isometric,
    Staggered,
    Hexagonal,
}

#[derive(Debug)]
/// An error arising from trying to parse an [`Orientation`] that is not valid.
pub struct OrientationParseError {
    /// The invalid string found.
    pub str_found: String,
}

impl std::fmt::Display for OrientationParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("failed to parse orientation, valid options are `orthogonal`, `isometric`, `staggered` \
        and `hexagonal` but got `{}` instead", self.str_found))
    }
}

impl std::error::Error for OrientationParseError {}

impl FromStr for Orientation {
    type Err = OrientationParseError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "orthogonal" => Ok(Orientation::Orthogonal),
            "isometric" => Ok(Orientation::Isometric),
            "staggered" => Ok(Orientation::Staggered),
            "hexagonal" => Ok(Orientation::Hexagonal),
            _ => Err(OrientationParseError {
                str_found: s.to_owned(),
            }),
        }
    }
}

impl fmt::Display for Orientation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Orientation::Orthogonal => write!(f, "orthogonal"),
            Orientation::Isometric => write!(f, "isometric"),
            Orientation::Staggered => write!(f, "staggered"),
            Orientation::Hexagonal => write!(f, "hexagonal"),
        }
    }
}

/// A Tiled global tile ID.
///
/// These are used to identify tiles in a map. Since the map may have more than one tileset, an
/// unique mapping is required to convert the tiles' local tileset ID to one which will work nicely
/// even if there is more than one tileset.
///
/// Tiled also treats GID 0 as empty space, which means that the first tileset in the map will have
/// a starting GID of 1.
///
/// See also: <https://doc.mapeditor.org/en/latest/reference/global-tile-ids/>
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Gid(pub u32);

impl Gid {
    /// The GID representing an empty tile in the map.
    #[allow(dead_code)]
    pub const EMPTY: Gid = Gid(0);
}