gemini_engine/primitives/
rect.rs

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
use crate::{containers::CanCollide, core::{CanDraw, ColChar, Vec2D}};

/// A rectangle primitive which implements [`CanDraw`], and so can be drawn to [Canvas](crate::core::Canvas)es
pub struct Rect {
    /// The position of the top-left corner of the `Rect`
    pub pos: Vec2D,
    /// The size of the `Rect`, extending from `pos`
    pub size: Vec2D,
    /// The [`ColChar`] used to fill the rectangle
    pub fill_char: ColChar,
}

impl Rect {
    /// Create a new `Rect` using a position and size
    #[must_use]
    pub const fn new(pos: Vec2D, size: Vec2D, fill_char: ColChar) -> Self {
        Self {
            pos,
            size,
            fill_char,
        }
    }

    /// Create a new `Rect` using two positions
    #[must_use]
    pub fn new_from_to(top_left: Vec2D, bottom_right: Vec2D, fill_char: ColChar) -> Self {
        Self::new(top_left, bottom_right - top_left + Vec2D::ONE, fill_char)
    }

    /// Return the coordinates of the bottom right point
    #[must_use]
    pub fn bottom_right(&self) -> Vec2D {
        self.pos + self.size - Vec2D::ONE
    }
}

impl CanDraw for Rect {
    fn draw_to(&self, canvas: &mut impl crate::core::Canvas) {
        for x in 0..self.size.x {
            for y in 0..self.size.y {
                canvas.plot(self.pos + Vec2D::new(x, y), self.fill_char);
            }
        }
    }
}

impl CanCollide for Rect {
    fn collides_with_pos(&self, pos: Vec2D) -> bool {
        pos.cmpge(self.pos).all() && pos.cmple(self.bottom_right()).all()
    }
}