gemini_engine/ascii/
sprite.rs

1use super::{Text, TextAlign2D};
2use crate::core::{CanDraw, Modifier, Vec2D};
3
4/// The `Sprite` takes a multi-line string as a parameter, and can be used to draw ASCII art to a `Canvas`
5#[non_exhaustive]
6#[derive(Debug, Clone)]
7pub struct Sprite {
8    /// The position from which the sprite will be drawn from
9    pub pos: Vec2D,
10    /// The ACII texture (pun intended) displayed by the `Sprite`
11    pub texture: String,
12    /// A raw [`Modifier`], determining the appearance of the `Sprite`
13    pub modifier: Modifier,
14    /// How the Sprite should align to the position
15    pub align: TextAlign2D,
16}
17
18impl Sprite {
19    /// Create a new `Sprite` struct. All newlines at the beginning of the texture will be removed
20    #[must_use]
21    pub fn new(pos: Vec2D, texture: &str, modifier: Modifier) -> Self {
22        Self {
23            pos,
24            texture: texture.trim_start_matches('\n').into(),
25            modifier,
26            align: TextAlign2D::default(),
27        }
28    }
29
30    /// Return the `Sprite` with an updated `align` property. Consumes the original `Sprite`
31    #[must_use]
32    pub const fn with_align(mut self, align: TextAlign2D) -> Self {
33        self.align = align;
34        self
35    }
36}
37
38impl CanDraw for Sprite {
39    fn draw_to(&self, canvas: &mut impl crate::core::Canvas) {
40        let content_size = Vec2D::new(
41            self.texture.lines().map(str::len).max().unwrap_or(0) as i64,
42            self.texture.lines().count() as i64,
43        );
44        let pos = self.align.apply_to(self.pos, content_size);
45
46        let lines = self.texture.split('\n');
47        for (y, line) in (0..).zip(lines) {
48            Text::new(pos + Vec2D::new(0, y), line, self.modifier).draw_to(canvas);
49        }
50    }
51}