gemini_engine/primitives/
rect.rs

1use crate::{
2    containers::CanCollide,
3    core::{CanDraw, ColChar, Vec2D},
4};
5
6/// A rectangle primitive which implements [`CanDraw`], and so can be drawn to [Canvas](crate::core::Canvas)es
7pub struct Rect {
8    /// The position of the top-left corner of the `Rect`
9    pub pos: Vec2D,
10    /// The size of the `Rect`, extending from `pos`
11    pub size: Vec2D,
12    /// The [`ColChar`] used to fill the rectangle
13    pub fill_char: ColChar,
14}
15
16impl Rect {
17    /// Create a new `Rect` using a position and size
18    #[must_use]
19    pub const fn new(pos: Vec2D, size: Vec2D, fill_char: ColChar) -> Self {
20        Self {
21            pos,
22            size,
23            fill_char,
24        }
25    }
26
27    /// Create a new `Rect` using two positions
28    #[must_use]
29    pub fn new_from_to(top_left: Vec2D, bottom_right: Vec2D, fill_char: ColChar) -> Self {
30        Self::new(top_left, bottom_right - top_left + Vec2D::ONE, fill_char)
31    }
32
33    /// Return the coordinates of the bottom right point
34    #[must_use]
35    pub fn bottom_right(&self) -> Vec2D {
36        self.pos + self.size - Vec2D::ONE
37    }
38}
39
40impl CanDraw for Rect {
41    fn draw_to(&self, canvas: &mut impl crate::core::Canvas) {
42        for x in 0..self.size.x {
43            for y in 0..self.size.y {
44                canvas.plot(self.pos + Vec2D::new(x, y), self.fill_char);
45            }
46        }
47    }
48}
49
50impl CanCollide for Rect {
51    fn collides_with_pos(&self, pos: Vec2D) -> bool {
52        pos.cmpge(self.pos).all() && pos.cmple(self.bottom_right()).all()
53    }
54}