use super::{remove_leading_newlines, Text, TextAlign2D};
use crate::elements::{
view::{Modifier, ViewElement},
Pixel, Vec2D,
};
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct Sprite {
pub pos: Vec2D,
pub texture: String,
pub modifier: Modifier,
pub align: TextAlign2D,
}
impl Sprite {
#[must_use]
pub fn new(pos: Vec2D, texture: &str, modifier: Modifier) -> Self {
Self {
pos,
texture: remove_leading_newlines(texture),
modifier,
align: TextAlign2D::default(),
}
}
#[must_use]
pub const fn with_align(self, align: TextAlign2D) -> Self {
let mut tmp = self;
tmp.align = align;
tmp
}
#[must_use]
pub fn draw(pos: Vec2D, texture: &str, modifier: Modifier) -> Vec<Pixel> {
let mut pixels = vec![];
let lines = texture.split('\n');
for (y, line) in (0isize..).zip(lines) {
pixels.extend(Text::draw(pos + Vec2D::new(0, y), line, modifier));
}
pixels
}
#[must_use]
pub fn draw_with_align(
pos: Vec2D,
texture: &str,
align: TextAlign2D,
modifier: Modifier,
) -> Vec<Pixel> {
let content_size = Vec2D::new(
texture.lines().count() as isize,
texture.lines().map(str::len).max().unwrap_or(0) as isize,
);
let pos = align.apply_to(pos, content_size);
Self::draw(pos, texture, modifier)
}
}
impl ViewElement for Sprite {
fn active_pixels(&self) -> Vec<Pixel> {
Self::draw_with_align(self.pos, &self.texture, self.align, self.modifier)
}
}