Browse Source

Add color support

Getty Ritter 4 years ago
parent
commit
8f2f1bf47e
2 changed files with 31 additions and 1 deletions
  1. 27 0
      carpet/src/lib.rs
  2. 4 1
      ch2/src/main.rs

+ 27 - 0
carpet/src/lib.rs

@@ -6,6 +6,23 @@ use std::path::Path;
 /// we only care about 16x16 tilesets
 const TILE_SIZE: f32 = 1.0 / 16.0;
 
+#[derive(Eq, PartialEq, Debug, Copy, Clone)]
+pub enum Color {
+    Red,
+    Green,
+    Blue,
+}
+
+impl From<Color> for ggez::graphics::Color {
+    fn from(color: Color) -> ggez::graphics::Color {
+        match color {
+            Color::Red => [1.0, 0.0, 0.0, 1.0].into(),
+            Color::Green => [0.0, 1.0, 0.0, 1.0].into(),
+            Color::Blue => [0.0, 0.0, 1.0, 1.0].into(),
+        }
+    }
+}
+
 pub struct Board {
     size: Size,
     contents: Vec<(u8, SpriteIdx)>,
@@ -93,6 +110,16 @@ impl Board {
         self.tileset.batch.set(self.contents[idx].1, param).unwrap();
     }
 
+    pub fn set_with_color(&mut self, at: impl Into<Coord>, ch: u8, color: impl Into<ggez::graphics::Color>) {
+        let at = at.into();
+        let idx = at.x + at.y * self.size.width;
+        let param = DrawParam::new()
+            .src(Board::sprite_location(ch).into())
+            .dest(self.tileset.to_screen(at))
+            .color(color.into());
+        self.tileset.batch.set(self.contents[idx].1, param).unwrap();
+    }
+
     pub fn get(&mut self, at: impl Into<Coord>) -> u8 {
         let at = at.into();
         let idx = at.x + at.y * self.size.width;

+ 4 - 1
ch2/src/main.rs

@@ -12,6 +12,7 @@ struct Pos {
 #[derive(Component)]
 struct Renderable {
     glyph: u8,
+    color: carpet::Color,
 }
 
 struct Draw;
@@ -26,7 +27,7 @@ impl<'a> System<'a> for Draw {
     fn run(&mut self, (pos, renderable, mut board): Self::SystemData) {
         board.clear();
         for (p, r) in (&pos, &renderable).join() {
-            board.set([p.x, p.y], r.glyph);
+            board.set_with_color([p.x, p.y], r.glyph, r.color);
         }
     }
 }
@@ -96,6 +97,7 @@ fn main() -> Result<(), GameError> {
         .with(Pos { x: 40, y: 25 })
         .with(Renderable {
             glyph: 'A' as u8,
+            color: carpet::Color::Blue,
         })
         .build();
 
@@ -105,6 +107,7 @@ fn main() -> Result<(), GameError> {
             .with(Pos { x: i * 7, y: 20 })
             .with(Renderable {
                 glyph: 'X' as u8,
+                color: carpet::Color::Red,
             })
             .with(MoveLeft)
             .build();