summaryrefslogtreecommitdiff
path: root/src/lowlevel/layer_tile.rs
blob: bca5daf589b47e4a7a49f71ae9d3b62a0311f562 (plain) (blame)
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
// Bits on the far end of the 32-bit global tile ID are used for tile flags
const FLIPPED_HORIZONTALLY_FLAG: u32 = 0x80000000;
const FLIPPED_VERTICALLY_FLAG: u32 = 0x40000000;
const FLIPPED_DIAGONALLY_FLAG: u32 = 0x20000000;

#[derive(Debug, Default, PartialEq)]
pub struct TileFlip {
    // whether tile is flipped diagonally (should be the first operation)
    pub diagonally: bool,
    // whether tile is flipped horizontally (should be the second operation)
    pub horizontally: bool,
    // whether tile is flipped vertically (should be the third operation)
    pub vertically: bool,
}

impl TileFlip {
    fn new(diagonally: bool, horizontally: bool, vertically: bool) -> Self {
        Self {
            diagonally,
            horizontally,
            vertically,
        }
    }
}

#[derive(Debug)]
pub struct LayerTile(u32);

impl LayerTile {
    /// Global Tile Id
    pub fn gid(&self) -> u32 {
        // Clear the flags
        self.0 & !(FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG | FLIPPED_DIAGONALLY_FLAG)
    }

    pub fn get_flip(&self) -> TileFlip {
        // Read out the flags
        TileFlip {
            diagonally: (self.0 & FLIPPED_DIAGONALLY_FLAG) > 0,
            horizontally: (self.0 & FLIPPED_HORIZONTALLY_FLAG) > 0,
            vertically: (self.0 & FLIPPED_VERTICALLY_FLAG) > 0,
        }
    }
}

#[cfg(test)]
mod test_layer_tile {
    use crate::lowlevel::{layer_tile::*};

    #[test]
    fn test_get_flip() {
        assert_eq!(LayerTile(13).get_flip(), TileFlip::default());
        assert_eq!(
            LayerTile(3451 | FLIPPED_DIAGONALLY_FLAG).get_flip(),
            TileFlip::new(true, false, false)
        );
    }

    #[test]
    fn test_gid() {
        assert_eq!(LayerTile(5).gid(), 5);
        assert_eq!(
            LayerTile(
                52 | (FLIPPED_HORIZONTALLY_FLAG
                    | FLIPPED_VERTICALLY_FLAG
                    | FLIPPED_DIAGONALLY_FLAG)
            )
            .gid(),
            52
        );
        assert_eq!(LayerTile(798 | (FLIPPED_DIAGONALLY_FLAG)).gid(), 798);
    }
}