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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! [tego](https://github.com/texel-sensei/tego) is a simple library for loading
//! [Tiled](https://mapeditor.org) maps.
//!
//! It aims to provide a simple, yet flexible API,
//! without forcing any special image format to the user
//! or assuming that data is provided as a file.
//!
//! As a starting point,
//! load a map using any of the *from_\** functions provided in the [Map] type.
//! And inspect the [Layers](Map::layers) inside of it.
//!
//! ```no_run
//! let path = std::path::Path::new("example-maps/default/default_map.tmx");
//! let mymap = tego::Map::from_file(&path)?;
//!
//! println!(
//!     "Map {} is {} by {} pixels.", path.display(),
//!     mymap.size.x * mymap.tile_size.x, mymap.size.y * mymap.tile_size.y
//! );
//!
//! # Ok::<(),tego::Error>(())
//! ```

use std::any::Any;
use std::{fs::File, io::Read};
use core::num::NonZeroU32;

use base64;
use roxmltree::Document;

#[macro_use] extern crate impl_ops;

mod errors;
mod resource_manager;
pub mod math;
pub use resource_manager::ImageLoader;
pub use errors::Error;
pub use errors::Result;

/// Version number consisting out of a MAJOR and MINOR version number, followed by an optional PATCH
#[derive(Debug, PartialEq, Eq)]
pub struct Version(
    /// Major version
    pub u32,
    /// Minor version
    pub u32,
    /// Patch version
    pub Option<u32>
);

impl std::str::FromStr for Version {
    type Err = crate::Error;

    fn from_str(s: &str) -> Result<Self> {
        let mut items = s.split('.');

        use Error::ParseError;
        let major = items.next().ok_or(ParseError("Major version is required but missing".into()))?.parse()?;
        let minor = items.next().ok_or(ParseError("Minor version is required but missing".into()))?.parse()?;
        let patch = if let Some(content) = items.next() {
            Some(content.parse()?)
        } else { None };

        Ok(Version(major, minor, patch))
    }
}

pub enum Orientation {
    Orthogonal,
    Isometric,
    Staggered,
    Hexagonal,
}

impl std::str::FromStr for Orientation {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        use Orientation::*;
        match s {
            "orthogonal" => Ok(Orthogonal),
            "isometric" => Ok(Isometric),
            "staggered" => Ok(Staggered),
            "hexagonal" => Ok(Hexagonal),
            _ => Err(Error::ParseError(format!("Invalid orientation '{}'", s).into()))
        }
    }
}

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Renderorder {
    RightDown,
    RightUp,
    LeftDown,
    LeftUp,
}

impl std::str::FromStr for Renderorder {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        use Renderorder::*;
        match s {
            "right-down" => Ok(RightDown),
            "right-up" => Ok(RightUp),
            "left-down" => Ok(LeftDown),
            "left-up" => Ok(LeftUp),
            _ => Err(Error::ParseError(format!("Invalid render order '{}'", s).into()))
        }
    }
}

impl Default for Renderorder {
    fn default() -> Self {
        Renderorder::RightDown
    }
}

/// Global Tile ID
/// A GID acts as an index into any tileset referenced in the map
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
#[repr(transparent)]
pub struct GID(NonZeroU32);

impl std::str::FromStr for GID {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        Ok(GID(s.parse()?))
    }
}

fn attribute_or<T>(node: &roxmltree::Node, name: &str, alternative: T) -> Result<T>
    where T: Copy + std::str::FromStr,
          T::Err: std::error::Error + 'static
{
    match node.attribute(name) {
        None => Ok(alternative),
        Some(text) => text.parse().map_err(|e: T::Err| Error::ParseError(Box::new(e)))
    }
}

fn attribute_or_default<T>(node: &roxmltree::Node, name: &str) -> Result<T>
    where T: Default + std::str::FromStr,
          T::Err: std::error::Error + 'static
{
    match node.attribute(name) {
        None => Ok(T::default()),
        Some(text) => text.parse().map_err(|e: T::Err| Error::ParseError(Box::new(e)))
    }
}

impl math::ivec2 {
    pub(crate) fn from_tmx_or_default(tmx: &roxmltree::Node, x_attr: &str, y_attr: &str) -> Result<Self> {
        Ok(Self::new(
            attribute_or_default(tmx, x_attr)?,
            attribute_or_default(tmx, y_attr)?
        ))
    }
}

impl math::fvec2 {
    pub(crate) fn from_tmx_or_default(tmx: &roxmltree::Node, x_attr: &str, y_attr: &str) -> Result<Self> {
        Ok(Self::new(
            attribute_or_default(tmx, x_attr)?,
            attribute_or_default(tmx, y_attr)?
        ))
    }
}

#[derive(Debug)]
pub enum ImageStorage {
    SpriteSheet(Box<dyn Any>),
}

pub struct TileSet {
    pub firstgid: GID,
    pub name: String,
    pub tile_size: math::ivec2,
    pub spacing: usize,
    pub margin: usize,
    pub tilecount: usize,
    pub columns: usize,
    pub image: ImageStorage,
}

impl TileSet {
    pub fn from_xml(node: &roxmltree::Node, loader: &mut dyn ImageLoader) -> Result<Self> {
        let map_attr = |name: &str| {
            node.attribute(name).ok_or_else(||{Error::StructureError{
                tag: node.tag_name().name().to_string(),
                msg: format!("Required attribute '{}' missing", name)
            }})
        };

        if let Some(source) = node.attribute("source") {
            return Err(Error::UnsupportedFeature(format!("Extern tileset at: {}", source)));
        }

        let image_storage;
        use ImageStorage::*;
        if let Some(image) = node.children().filter(|n| n.tag_name().name() == "image").next() {
            image_storage = SpriteSheet(
                loader.load(image.attribute("source").ok_or_else(|| Error::StructureError{
                    tag: image.tag_name().name().into(),
                    msg: "Missing 'source' tag on image".into(),
                })?)?
            );
        } else {
            return Err(Error::UnsupportedFeature("Image collection tilesets are not implemented yet".into()))
        }

        Ok(Self{
            firstgid: map_attr("firstgid")?.parse()?,
            name: map_attr("name")?.into(),
            tile_size: math::ivec2::new(
                map_attr("tilewidth")?.parse()?,
                map_attr("tileheight")?.parse()?
            ),
            spacing: attribute_or_default(node, "spacing")?,
            margin: attribute_or_default(node, "margin")?,
            tilecount: map_attr("tilecount")?.parse()?,
            columns: map_attr("columns")?.parse()?,
            image: image_storage,
        })
    }
}

/// Helper function to read the binary data contained in a "data" tag
/// # Panics
/// The given node has no "encoding" attribute
fn read_data_tag(data_node: &roxmltree::Node) -> Result<Vec<u8>> {
    assert_eq!(data_node.tag_name().name(), "data");
    assert!(data_node.attribute("encoding").is_some());

    match data_node.attribute("encoding").unwrap() {
        "csv" => todo!{"Implement csv parsing"},
        "base64" => {
            // helper macro for decoding compressed data using libflate
            macro_rules! decode_with {
                ($input:ident $compression:ident) => {{
                    use std::io::Read;
                    let mut decoded = Vec::new();
                    let mut decoder = libflate::$compression::Decoder::new(&$input[..])?;
                    decoder.read_to_end(&mut decoded)?;
                    decoded
                }};
            }

            let raw_bytes = base64::decode(data_node.text().unwrap_or_default().trim())
                .map_err(|e| Error::ParseError(Box::new(e)))?
                ;
            let raw_bytes = match data_node.attribute("compression") {
                None => raw_bytes,
                Some("zlib") => decode_with!(raw_bytes zlib),
                Some("gzip") => decode_with!(raw_bytes gzip),
                Some(compression) => Err(Error::StructureError{
                    tag: data_node.tag_name().name().to_string(),
                    msg: format!("Unsupported data compression '{}'", compression)
                })?,
            };
            Ok(raw_bytes)
        },
        encoding => Err(Error::StructureError{
            tag: data_node.tag_name().name().to_string(),
            msg: format!("Unsupported data encoding '{}'", encoding)
        })
    }
}

/// This enum contains the different types of layers that can be found in a map
pub enum Layer{
    /// A layer containing a grid of tiles
    Tile(TileLayer),

    /// A layer grouping mutiple other layer together.
    /// Group Layers may be nested,
    /// forming a tree of layers.
    Group(GroupLayer),

    /// A layer containing objects.
    /// Objects are not aligned to the tile grid.
    /// They can be used for example to mark regions of interest.
    ///
    /// Object layers are also called object  groups.
    Object(ObjectLayer),
}

impl Layer {
    pub fn try_from_xml(node: &roxmltree::Node) -> Option<Result<Self>> {
        use Layer::*;
        match node.tag_name().name() {
            "layer" => Some(TileLayer::from_xml(node).map(|l| Tile(l))),
            "group" => Some(GroupLayer::from_xml(node).map(|l| Group(l))),
            "objectgroup" => Some(ObjectLayer::from_xml(node).map(|l| Object(l))),
            _ => None,
        }
    }
}

pub struct TileIterator<'map, 'layer> {
    map: &'map Map,
    layer: &'layer TileLayer,
    pos: math::ivec2,
}

impl<'map, 'layer> TileIterator<'map, 'layer> {
    pub(crate) fn new(map: &'map Map, layer: &'layer TileLayer) -> Self { Self { map, layer, pos: math::ivec2::new(0, 0) } }
}

impl<'a,'b> Iterator for TileIterator<'a,'b> {
    type Item = (math::ivec2, Option<GID>);

    fn next(&mut self) -> Option<Self::Item> {
        assert_eq!(
            self.map.renderorder,
            Renderorder::RightDown,
            "Only right-down renderorder is implemented right now"
        );
        if self.pos.x >= self.layer.size.x {
            self.pos.x = 0;
            self.pos.y += 1;
        }
        if self.pos.y >= self.layer.size.y {
            return None;
        }

        let idx = self.pos.x + self.layer.size.x * self.pos.y;
        let element = Some((self.pos, self.layer.tiles[idx as usize]));
        self.pos.x += 1;
        element
    }
}

/// A layer to group multiple sub-layers
pub struct GroupLayer {
    pub id: usize,
    pub name: String,
    pub offset: math::ivec2,
    pub opacity: f32,
    pub visible: bool,
    // pub tintcolor: TODO
    pub content: Vec<Layer>
}

impl GroupLayer {
    /// Load a group layer from a TMX "group" node
    pub fn from_xml(node: &roxmltree::Node) -> Result<Self> {
        assert_eq!(node.tag_name().name(), "group");
        let map_attr = |name: &str| {
            node.attribute(name).ok_or_else(||{Error::StructureError{
                tag: node.tag_name().name().to_string(),
                msg: format!("Required attribute '{}' missing", name)
            }})
        };

        let content = node.children().filter_map(|c| Layer::try_from_xml(&c)).collect::<Result<Vec<_>>>();

        Ok(Self{
            id: map_attr("id")?.parse()?,
            name: node.attribute("name").unwrap_or_default().to_string(),
            offset: math::ivec2::from_tmx_or_default(node, "offsetx", "offsety")?,
            opacity: attribute_or(node, "opacity", 1.)?,
            visible: attribute_or(node, "opacity", true)?,
            content: content?,
        })
    }
}

pub struct TileLayer {
    pub id: usize,
    pub name: String,
    pub size: math::ivec2,
    pub tiles: Vec<Option<GID>>
}

impl TileLayer {

    fn parse_data(data_node: &roxmltree::Node) -> Result<Vec<Option<GID>>> {
        assert_eq!(data_node.tag_name().name(), "data");

        match data_node.attribute("encoding") {
            None => todo!{"Tag based tile data loading not yet implemented"},
            Some(_) => {
                let raw_bytes = read_data_tag(data_node)?;

                const BYTE_SIZE: usize = std::mem::size_of::<u32>();
                assert!(raw_bytes.len() % BYTE_SIZE == 0);

                // convert chunk of bytes into GIDS (via u32)
                Ok(
                    raw_bytes.chunks_exact(BYTE_SIZE)
                    .map(|c| Some(GID(NonZeroU32::new(u32::from_le_bytes(c.try_into().unwrap()))?)))
                    .collect()
                )
            }
        }
    }

    pub fn from_xml(tmx: &roxmltree::Node) -> Result<Self> {
        let map_attr = |name: &str| {
            tmx.attribute(name).ok_or_else(||{Error::StructureError{
                tag: tmx.tag_name().name().to_string(),
                msg: format!("Required attribute '{}' missing", name)
            }})
        };
        Ok(Self{
            id: map_attr("id")?.parse()?,
            name: tmx.attribute("name").unwrap_or_default().to_string(),
            size: math::ivec2::new(
                map_attr("width")?.parse()?,
                map_attr("height")?.parse()?
            ),
            tiles: Self::parse_data(&tmx.children().find(|n| n.tag_name().name() == "data").unwrap())?,
        })
    }


    /// Iterate over the tiles inside of this layer in the order in which they would be rendered.
    /// See [Map::renderorder]. This iterator yields the GID and xy coordinates of the tiles in the
    /// layer, with a None GID for empty tiles.
    ///
    /// # Panics
    ///
    /// At the moment, this function is only implemented for a renderorder of RightDown.
    /// Other render orders result in a panic.
    pub fn tiles_in_renderorder<'a, 'b>(&'b self, map: &'a Map) -> TileIterator<'a, 'b> {
        TileIterator::new(map, &self)
    }
}

/// An ObjectLayer is a container of Objects.
/// Objects are not aligned to the tile grid,
/// and can be used to include extra information in a map.
///
/// Check the [Tiled Documentation](https://doc.mapeditor.org/en/stable/manual/objects/)
/// for more information on objects.
pub struct ObjectLayer {
    pub id: usize,
    pub name: String,
    pub opacity: f32,
    pub visible: bool,
    pub offset: math::ivec2,

    /// The [Objects](Object) contained in this layer
    pub content: Vec<Object>,
}

impl ObjectLayer {
    pub fn from_xml(tmx: &roxmltree::Node) -> Result<Self> {
        assert_eq!(tmx.tag_name().name(), "objectgroup");

        let map_attr = |name: &str| {
            tmx.attribute(name).ok_or_else(||{Error::StructureError{
                tag: tmx.tag_name().name().to_string(),
                msg: format!("Required attribute '{}' missing", name)
            }})
        };

        let content = tmx.children()
            .filter(|t| t.tag_name().name() == "object")
            .map(|t| Object::from_xml(&t))
            .collect::<Result<_>>()?
        ;

        Ok(Self{
            id: map_attr("id")?.parse()?,
            name: tmx.attribute("name").unwrap_or_default().to_string(),
            opacity: attribute_or(tmx, "opacity", 1.)?,
            visible: attribute_or(tmx, "opacity", true)?,
            offset: math::ivec2::from_tmx_or_default(tmx, "offsetx", "offsety")?,
            content
        })
    }

}

/// An element of an [ObjectLayer].
/// Objects do not need to be aligned to the normal tile grid.
/// Objects can have different kinds,
/// (e.g. rect, ellipse, text).
/// See [ObjectKind] for more info.
pub struct Object {
    pub id: usize,
    pub name: String,
    pub type_: String,
    pub pos: math::fvec2,
    pub size: math::fvec2,
    pub rotation: f32,
    pub tile_id: Option<GID>,
    pub visible: bool,
    pub kind: ObjectKind,
}

impl Object {
    fn from_xml(tmx: &roxmltree::Node) -> Result<Self> {
        let map_attr = |name: &str| {
            tmx.attribute(name).ok_or_else(||{Error::StructureError{
                tag: tmx.tag_name().name().to_string(),
                msg: format!("Required attribute '{}' missing", name)
            }})
        };

        let tile_id = if let Some(txt) = tmx.attribute("gid") {
            Some(txt.parse()?)
        } else {
            None
        };

        Ok(Object{
            id: map_attr("id")?.parse()?,
            name: attribute_or_default(tmx, "name")?,
            type_: attribute_or_default(tmx, "type")?,
            pos: math::fvec2::from_tmx_or_default(tmx, "x", "y")?,
            size: math::fvec2::from_tmx_or_default(tmx, "width", "height")?,
            rotation: attribute_or_default(tmx, "rotation")?,
            tile_id,
            visible: attribute_or(tmx, "visible", true)?,
            kind: ObjectKind::from_xml(tmx)?,
        })
    }
}

pub enum ObjectKind {
    Rect,
    Ellipse,
    Point,
    Polygon {
        points: Vec<math::fvec2>
    },
    Polyline {
        points: Vec<math::fvec2>
    },
    Text {
        content: String
        // todo
    },
}

trait AsPointListExt { fn as_point_list(&self) -> Result<Vec<math::fvec2>>; }

impl AsPointListExt for &str {
    fn as_point_list(&self) -> Result<Vec<math::fvec2>> {
        let mut points = vec![];
        for point in self.split_ascii_whitespace() {
            let mut coords = point.split(',');
            if let (Some(x), Some(y), None) = (coords.next(), coords.next(), coords.next()) {
                points.push(math::fvec2::new(x.parse()?,y.parse()?));
            } else {
                return Err(Error::ParseError(format!("{} is not a valid point", point).into()));
            }
        }
        Ok(points)
    }
}

impl ObjectKind {
    fn from_xml(tmx: &roxmltree::Node) -> Result<Self> {
        use ObjectKind::*;
        use Error::StructureError;
        for child in tmx.children() {
            match child.tag_name().name() {
                "ellipse" => return Ok(Ellipse),
                "point" => return Ok(Point),
                poly @ ("polygon" | "polyline") => {
                    let points = child
                        .attribute("points")
                        .ok_or(StructureError{
                            tag: child.tag_name().name().into(),
                            msg: "Missing attribute points".into()
                        })?
                        .as_point_list()?
                    ;
                    return Ok(match poly {
                        "polygon" => Polygon { points },
                        "polyline" => Polyline { points },
                        _ => unreachable!(),
                    });
                }
                "text" => {
                    return Ok(Text {
                        content: child.text().unwrap_or_default().into()
                    });
                },
                _ => continue,
            }
        }
        Ok(Rect)
    }
}


/// The Map struct is the top level container for all relevant data inside of a Tiled map.
/// A Map consists of [TileSets](TileSet) and [Layers](Layer).
/// Stacking the layers in iteration order creates the final map image.
/// Each layer contains indices ([GIDs](GID)) referencing a specific tile in a tile sets.
pub struct Map {
    pub version: Version,
    pub editor_version: Option<Version>,
    pub orientation: Orientation,
    pub renderorder: Renderorder,
    pub size: math::ivec2,
    pub tile_size: math::ivec2,
    pub tilesets: Vec<TileSet>,
    /// The Layers that make up this map.
    /// The final map image is rendered by stacking the layers in iteration order.
    pub layers: Vec<Layer>,
}

impl Map {
    pub fn from_file(path: &std::path::Path) -> Result<Self> {
        let mut loader = resource_manager::LazyLoader {};
        Self::from_file_with_loader(path, &mut loader)
    }

    pub fn from_file_with_loader(path: &std::path::Path, image_loader: &mut dyn resource_manager::ImageLoader) -> Result<Self> {
        let mut file = File::open(path)?;

        let mut file_xml = String::new();
        file.read_to_string(&mut file_xml)?;

        Self::from_xml_str(&file_xml, image_loader)
    }

    /// Parse a map from xml data
    pub fn from_xml_str(tmx: &str, image_loader: &mut dyn resource_manager::ImageLoader) -> Result<Self> {
        let document = Document::parse(&tmx)?;

        let map_node = document.root_element();

        if map_node.tag_name().name() != "map" {
            return Err(Error::StructureError{
                tag: map_node.tag_name().name().to_string(),
                msg: format!("Expected tag 'map' at root level, got '{}'.", map_node.tag_name().name())
            });
        }

        let map_attr = |name: &str| {
            map_node.attribute(name).ok_or_else(||{Error::StructureError{
                tag: map_node.tag_name().name().to_string(),
                msg: format!("Required attribute '{}' missing", name)
            }})
        };

        let tilesets = map_node.children()
            .filter(|n| n.tag_name().name() == "tileset")
            .map(|n| TileSet::from_xml(&n, image_loader))
            .collect::<Result<Vec<_>>>()?
        ;

        let mut map = Map {
            version: map_attr("version")?.parse()?,
            editor_version: None,
            orientation: map_attr("orientation")?.parse()?,
            renderorder: attribute_or_default(&map_node, "renderorder")?,
            size: math::ivec2::new(
                map_attr("width")?.parse()?,
                map_attr("height")?.parse()?
            ),
            tile_size: math::ivec2::new(
                map_attr("tilewidth")?.parse()?,
                map_attr("tileheight")?.parse()?
            ),
            tilesets,
            layers:
                map_node.children().filter_map(|c| Layer::try_from_xml(&c)).collect::<Result<Vec<_>>>()?
        };
        if map_node.attribute("tiledversion").is_some() {
            map.editor_version = Some(map_attr("tiledversion")?.parse()?);
        }
        Ok(map)
    }

    /// Fetch the image that belongs to a given GID. Returns the image and the pixel coordinates
    /// where the tile image is inside of that image.
    pub fn tile_image(&self, id: GID) -> Option<(&dyn std::any::Any, math::Rect)> {
        use math::ivec2;
        let tileset = self.tilesets.iter().rfind(|t| t.firstgid <= id)?;


        let size = ivec2::new(tileset.tile_size.x, tileset.tile_size.y);
        let stride = tileset.spacing as i32;
        let stride = size + ivec2::new(stride, stride);

        let lid = (id.0.get() - tileset.firstgid.0.get()) as i32;
        let tile_id = ivec2::new(lid % tileset.columns as i32, lid / tileset.columns as i32);
        let upper_left = ivec2::new(tileset.margin as i32, tileset.margin as i32) + tile_id * stride;

        match &tileset.image {
            ImageStorage::SpriteSheet(spritesheet) => {
                Some((&**spritesheet, math::Rect::new(upper_left, size)))
            },
        }
    }

    /// Iterate over all the layers in this map recursively.
    /// All layers are visited in depth-first pre-order manner.
    /// The iterator yields the group layers, as well as all of their sub-layers.
    ///
    /// In addition to the layer, a number of "pops" is also returned with each item.
    /// This is the number of group layers that was left with this iteration step.
    /// Some attributes of group layers affect all containing layers.
    /// If those attributes are accumulated in a stack,
    /// then the number of pops is the number of elemets to remove from the top of the stack.
    ///
    /// # Example
    ///
    /// Rendering layers under consideration of the group opacity:
    ///
    /// ```ignore
    /// let opacities = vec![1.];
    /// for (layer, pops) in map.iter_layers() {
    ///     opacities.truncate(opacities.len() - pops);
    ///     match layer {
    ///         Layer::Group(group) => { opacities.push(opacities.last().unwrap() * group.opacity) },
    ///         Layer::Tile(tile) => { render_layer(tile, opacities.last()) }
    ///     }
    /// }
    /// ```
    pub fn iter_layers(&self) -> impl Iterator<Item=(&Layer, usize)> {
        LayerIterator::new(&self.layers)
    }
}

struct LayerIterator<'a> {
    iter_stack: Vec<std::slice::Iter<'a, Layer>>
}

impl<'a> LayerIterator<'a> {
    fn new(layers: &'a [Layer]) -> Self { Self { iter_stack: vec![layers.iter()] } }
}

impl<'a> Iterator for LayerIterator<'a> {
    type Item = (&'a Layer, usize);

    fn next(&mut self) -> Option<Self::Item> {
        let mut pops = 0;
        while let Some(iter) = self.iter_stack.last_mut() {
            if let Some(layer) = iter.next() {
                if let Layer::Group(group) = layer {
                    self.iter_stack.push(group.content.iter());
                }
                return Some((layer, pops));
            } else {
                pops += 1;
                self.iter_stack.pop();
            }
        }
        None
    }
}



#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_version_parsing() -> Result<()> {
        assert_eq!("1.0".parse::<Version>()?, Version(1,0,None));
        assert_eq!("4.5.3".parse::<Version>()?, Version(4,5,Some(3)));
        Ok(())
    }

    #[test]
    fn test_default_render_order() -> Result<()> {
        // explicitly no renderorder
        let map_xml = r#"
            <map
                version="1.5"
                orientation="orthogonal"
                width="1"
                height="1"
                tilewidth="1"
                tileheight="1"
            />
        "#;

        let map = Map::from_xml_str(&map_xml, &mut resource_manager::LazyLoader{})?;
        assert_eq!(map.renderorder, Renderorder::RightDown);
        Ok(())
    }

    #[test]
    fn test_gid_size_optimization() {
        use std::mem::size_of;
        assert_eq!(size_of::<Option<GID>>(), size_of::<u32>());
    }

    #[test]
    fn test_layer_iterator() {
        use Layer::*;
        macro_rules! layer {
            (tile) => {Tile(TileLayer{id: 0, name: "".into(), size: math::ivec2::new(0,0), tiles: vec![]})};
            (group $layers:expr) => {Group(GroupLayer{id:0, name: "".into(), offset: math::ivec2::new(0,0), opacity: 0., visible:false, content: $layers})};
        }

        let layers = vec![
            layer!(tile),
            layer!(group vec![]),
            layer!(tile),
            layer!(group vec![
                layer!(group vec![
                    layer!(tile),
                    layer!(tile),
                ])
            ]),
        ];

        let result: Vec<_> = LayerIterator::new(&layers).collect();
        assert_eq!(result.len(), 7);

        // check that we get the group
        assert!(std::ptr::eq(result[2].0, &layers[2]));

        // no pops on a top level tile layer
        assert_eq!(result[0].1, 0);

        // one pop after the empty group
        assert_eq!(result[2].1, 1);
    }
}