use std::fmt::{self, Write};
use std::ops::Range;
use std::time::Duration;
use nadir_assets::Handle;
use nadir_core::{Color, Rect, Vec2};
use crate::{Font, TextLayout, Texture, TileLayerDraw, UiList};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Camera2D {
pub position: Vec2,
pub zoom: f32,
pub shake: Vec2,
}
impl Default for Camera2D {
fn default() -> Self {
Self {
position: Vec2::ZERO,
zoom: 1.0,
shake: Vec2::ZERO,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SortMode {
#[default]
YSort,
Fixed(u32),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Flip {
pub x: bool,
pub y: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SpriteDraw {
pub texture: Handle<Texture>,
pub uv: Rect,
pub position: Vec2,
pub size: Vec2,
pub pivot: Vec2,
pub rotation: f32,
pub color: Color,
pub layer: u8,
pub sort: SortMode,
pub flip: Flip,
}
impl SpriteDraw {
pub fn new(texture: Handle<Texture>, position: Vec2, size: Vec2) -> Self {
Self {
texture,
uv: Rect::new(Vec2::ZERO, Vec2::ONE),
position,
size,
pivot: Vec2::new(0.5, 1.0),
rotation: 0.0,
color: Color::WHITE,
layer: 0,
sort: SortMode::YSort,
flip: Flip::default(),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum GlyphMode {
#[default]
Mask,
Rgba,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextDraw {
pub font: Handle<Font>,
pub position: Vec2,
pub pivot: Vec2,
pub layout: TextLayout,
pub color: Color,
pub glyphs: GlyphMode,
pub layer: u8,
pub sort: SortMode,
}
impl TextDraw {
pub fn new(font: Handle<Font>, position: Vec2) -> Self {
Self {
font,
position,
pivot: Vec2::ZERO,
layout: TextLayout::new(),
color: Color::WHITE,
glyphs: GlyphMode::Mask,
layer: 0,
sort: SortMode::YSort,
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextList {
text: String,
draws: Vec<(TextDraw, Range<usize>)>,
}
impl TextList {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, draw: TextDraw, text: &str) {
let start = self.text.len();
self.text.push_str(text);
self.draws.push((draw, start..self.text.len()));
}
pub fn write(&mut self, draw: TextDraw, args: fmt::Arguments<'_>) {
let start = self.text.len();
if self.text.write_fmt(args).is_err() {
self.text.truncate(start);
return;
}
self.draws.push((draw, start..self.text.len()));
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = (&TextDraw, &str)> + '_ {
self.draws
.iter()
.map(|(draw, range)| (draw, &self.text[range.clone()]))
}
pub(crate) fn at(&self, index: usize) -> (&TextDraw, &str) {
let (draw, range) = &self.draws[index];
(draw, &self.text[range.clone()])
}
pub fn len(&self) -> usize {
self.draws.len()
}
pub fn is_empty(&self) -> bool {
self.draws.is_empty()
}
pub fn clear(&mut self) {
self.text.clear();
self.draws.clear();
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
pub struct RenderFrame {
pub camera: Camera2D,
pub clear: Color,
pub sprites: Vec<SpriteDraw>,
pub tile_layers: Vec<TileLayerDraw>,
pub texts: TextList,
pub ui: UiList,
pub time: Duration,
}
impl RenderFrame {
pub fn new() -> Self {
Self {
camera: Camera2D::default(),
clear: Color::BLACK,
sprites: Vec::new(),
tile_layers: Vec::new(),
texts: TextList::new(),
ui: UiList::new(),
time: Duration::ZERO,
}
}
pub fn clear(&mut self) {
self.sprites.clear();
self.tile_layers.clear();
self.texts.clear();
self.ui.clear();
}
}
impl Default for RenderFrame {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use nadir_core::GenIndex;
use super::*;
fn draw(x: f32) -> TextDraw {
let font = Handle::new(GenIndex::new(0, std::num::NonZeroU32::MIN));
TextDraw::new(font, Vec2::new(x, 0.0))
}
#[test]
fn a_text_list_keeps_each_text_with_its_draw() {
let mut texts = TextList::new();
assert!(texts.is_empty());
texts.push(draw(1.0), "Hi");
let score = 42;
texts.write(draw(2.0), format_args!("Score {score}"));
texts.push(draw(3.0), "");
assert_eq!(texts.len(), 3);
let all: Vec<(f32, &str)> = texts.iter().map(|(d, t)| (d.position.x, t)).collect();
assert_eq!(all, [(1.0, "Hi"), (2.0, "Score 42"), (3.0, "")]);
}
#[test]
fn a_text_whose_formatting_fails_is_left_out() {
struct Fails;
impl fmt::Display for Fails {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("half")?;
Err(fmt::Error)
}
}
let mut texts = TextList::new();
texts.push(draw(1.0), "a");
texts.write(draw(2.0), format_args!("{Fails}"));
texts.push(draw(3.0), "b");
let all: Vec<&str> = texts.iter().map(|(_, t)| t).collect();
assert_eq!(all, ["a", "b"]);
}
#[test]
fn a_frame_cleared_and_filled_again_keeps_its_buffers() {
let mut frame = RenderFrame::new();
let fill = |frame: &mut RenderFrame| {
for i in 0..20 {
frame
.texts
.write(draw(i as f32), format_args!("line {i} of the frame"));
}
};
fill(&mut frame);
frame
.ui
.set_view(crate::UiView::new(crate::UiScale::Free(2.0)));
frame.ui.text(draw(0.0), "a");
let capacity = (frame.texts.text.capacity(), frame.texts.draws.capacity());
let pointers = (frame.texts.text.as_ptr(), frame.texts.draws.as_ptr());
frame.clear();
assert!(frame.texts.is_empty());
assert!(frame.ui.is_empty());
assert_eq!(frame.ui.view(), crate::UiView::default());
fill(&mut frame);
assert_eq!(
(frame.texts.text.capacity(), frame.texts.draws.capacity()),
capacity
);
assert_eq!(
(frame.texts.text.as_ptr(), frame.texts.draws.as_ptr()),
pointers
);
}
#[test]
fn a_new_text_is_white_y_sorted_and_a_mask_at_its_top_left() {
let text = draw(5.0);
assert_eq!(
(text.pivot, text.color, text.glyphs),
(Vec2::ZERO, Color::WHITE, GlyphMode::Mask)
);
assert_eq!((text.layer, text.sort), (0, SortMode::YSort));
assert_eq!(text.layout, TextLayout::new());
}
}