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
#![deny(missing_docs)]

//! Patchwork: A convenient crate for drawing tiles from a tilesheet using 
//! a 'SpriteBatch'.
//! An update to the 'Mosaic' crate by Repnop(https://github.com/repnop/mosaic),
//! which is no longer maintained.
//! [`ggez`](https://crates.io/crates/ggez).
//!

extern crate ggez;
extern crate nalgebra;

use ggez::graphics::{self, spritebatch::SpriteBatch, Color, DrawParam, Image, Rect};
use nalgebra::{Point2, Vector2};
use std::{collections::HashMap, hash::Hash};

/// A set of tiles made from a tilesheet image.
pub struct TileSet<Key: Hash + Eq> {
    tile_size: Vector2<i32>,
    tile_cache: HashMap<Key, Point2<i32>>,
    sheet_dimensions: Vector2<i32>,
    spritebatch: SpriteBatch,
}

impl<Key: Hash + Eq> TileSet<Key> {
    /// Create a new `TileSet` from an image and tile size.
    pub fn new<S: Into<Vector2<i32>>>(sheet: Image, tile_size: S) -> Self {
        let tile_size = tile_size.into();
        let sheet_dimensions = Vector2::new(
            sheet.width() as i32 / tile_size.x,
            sheet.height() as i32 / tile_size.y);

        Self {
            tile_size,
            tile_cache: HashMap::new(),
            sheet_dimensions,
            spritebatch: SpriteBatch::new(sheet),
        }
    }

    /// Register a tile from the tilesheet to the `TileSet` with the lookup
    /// value of `key`.
    pub fn register_tile<I: Into<Point2<i32>>>(
        &mut self,
        key: Key,
        index: I,
    ) -> Result<(), TileSetError> {
        let index = index.into();

        if index.x > self.sheet_dimensions.x || index.y > self.sheet_dimensions.y {
            return Err(TileSetError::OutOfRange);
        }

        self.tile_cache.insert(key, index);

        Ok(())
    }

    /// Queue a tile with the lookup value `key` to be drawn at `draw_location`,
    /// with extra drawing options.
    pub fn queue_tile<P: Into<Point2<i32>>, TP: Into<TileParams>>(
        &mut self,
        key: Key,
        draw_location: P,
        options: Option<TP>,
    ) -> Result<(), TileSetError> {
        let tile = self.tile_cache.get(&key).ok_or(TileSetError::TileNotFound)?;

        let options = options.map(|tp| tp.into()).unwrap_or(TileParams {
            color: None,
            scale: None,
        });

        let coords = draw_location.into();
        let normal_x = 1.0 / self.sheet_dimensions.x as f32;
        let normal_y = 1.0 / self.sheet_dimensions.y as f32;

        let d = DrawParam::default().dest(nalgebra::Point2::new(
            (coords.x * self.tile_size.x) as f32,
            (coords.y * self.tile_size.y) as f32,
        )).src(Rect::new(
            normal_x * tile.x as f32,
            normal_y * tile.y as f32,
            normal_x,
            normal_y,
        )).color(options.color.unwrap_or(graphics::WHITE)).scale(options.scale.unwrap_or(Vector2::new(1.0, 1.0)));

        self.spritebatch.add(d);

        Ok(())
    }

    /// Clear the tile queue.
    pub fn clear_queue(&mut self) {
        self.spritebatch.clear();
    }

    /// Draw the tiles using `ctx` && 'spritebatch'. Default parameters
    /// are given to the batch.
    pub fn draw(&self, ctx: &mut ggez::Context) -> ggez::GameResult {
        graphics::draw(ctx, &self.spritebatch, DrawParam::default())
    }
}

/// Additional parameters for drawing tiles.
pub struct TileParams {
    /// The optional color to draw the tile with.
    pub color: Option<Color>,
    /// Scale factor for drawing. Default is `1.0` (no scaling).
    pub scale: Option<Vector2<f32>>,
}

impl From<(Option<Color>, Option<Vector2<f32>>)> for TileParams {
    fn from((color, scale): (Option<Color>, Option<Vector2<f32>>)) -> TileParams {
        TileParams { color, scale }
    }
}

impl From<(Option<Color>, Vector2<f32>)> for TileParams {
    fn from((color, scale): (Option<Color>, Vector2<f32>)) -> TileParams {
        TileParams {
            color,
            scale: Some(scale),
        }
    }
}

impl From<(Color, Option<Vector2<f32>>)> for TileParams {
    fn from((color, scale): (Color, Option<Vector2<f32>>)) -> TileParams {
        TileParams {
            color: Some(color),
            scale,
        }
    }
}

impl From<(Color, Vector2<f32>)> for TileParams {
    fn from((color, scale): (Color, Vector2<f32>)) -> TileParams {
        TileParams {
            color: Some(color),
            scale: Some(scale),
        }
    }
}

/// Possible errors from `TileSet` operations.
#[derive(Debug, Clone, Copy)]
pub enum TileSetError {
    /// The tile position to register was outside the tilesheet bounds.
    OutOfRange,
    /// Tile not found.
    TileNotFound,
}

impl std::fmt::Display for TileSetError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                TileSetError::OutOfRange => "Position out of range of tilesheet dimensions",
                TileSetError::TileNotFound => "Tile not found during lookup",
            }
        )
    }
}

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