Skip to main content

nadir_render/
frame.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! What the game asks the renderer to draw in a frame.
16
17use std::fmt::{self, Write};
18use std::ops::Range;
19use std::time::Duration;
20
21use nadir_assets::Handle;
22use nadir_core::{Color, Rect, Vec2};
23
24use crate::{Font, TextLayout, Texture, TileLayerDraw, UiList};
25
26/// The view of the world: what is at the centre of the screen, and how
27/// large.
28#[derive(Clone, Copy, Debug, PartialEq)]
29pub struct Camera2D {
30    /// The world point at the centre of the view.
31    pub position: Vec2,
32    /// Virtual pixels per world unit. Pixel-perfect rendering rounds it to
33    /// a whole number, at least 1.
34    pub zoom: f32,
35    /// An offset added to the position, for screen shake.
36    pub shake: Vec2,
37}
38
39impl Default for Camera2D {
40    fn default() -> Self {
41        Self {
42            position: Vec2::ZERO,
43            zoom: 1.0,
44            shake: Vec2::ZERO,
45        }
46    }
47}
48
49/// How a sprite is ordered among the others of its layer.
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
51pub enum SortMode {
52    /// By its pivot's y: lower on screen is drawn later, in front.
53    #[default]
54    YSort,
55    /// At a fixed depth, for ground decals and the like. `Fixed(0)` is
56    /// behind every y-sorted sprite of its layer, and `Fixed(u32::MAX)` in
57    /// front of every one.
58    Fixed(u32),
59}
60
61/// Which way a sprite or a tile is mirrored: a sprite about its pivot
62/// ([`SpriteDraw::flip`]), a tile in its cell.
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
64pub struct Flip {
65    /// Left to right.
66    pub x: bool,
67    /// Top to bottom.
68    pub y: bool,
69}
70
71/// One sprite to draw in the world.
72#[derive(Clone, Copy, Debug, PartialEq)]
73pub struct SpriteDraw {
74    /// The texture, usually an atlas page.
75    pub texture: Handle<Texture>,
76    /// The region of the texture, normalized: (0, 0) to (1, 1) is all of
77    /// it. A texture that failed to load shows all of its placeholder
78    /// instead.
79    pub uv: Rect,
80    /// Where the pivot is in the world.
81    pub position: Vec2,
82    /// The size in world units.
83    pub size: Vec2,
84    /// The point of the sprite at `position`, normalized: (0.5, 1) is the
85    /// middle of its bottom edge, its feet.
86    pub pivot: Vec2,
87    /// Radians, clockwise on screen, about the pivot.
88    pub rotation: f32,
89    /// A tint, sRGB, multiplied with the texture in linear light.
90    pub color: Color,
91    /// Higher layers are drawn in front of lower ones.
92    pub layer: u8,
93    /// How it is ordered within its layer.
94    pub sort: SortMode,
95    /// Which way it is mirrored, about its pivot, so that a trimmed frame
96    /// mirrors as its untrimmed cell would: one whose pivot is in the middle
97    /// of its width mirrors in place left to right, and one with its pivot
98    /// at its feet hangs below them when mirrored top to bottom.
99    pub flip: Flip,
100}
101
102impl SpriteDraw {
103    /// A sprite of all of `texture`, `size` large, with its feet at
104    /// `position`: untinted, unrotated, y-sorted in layer 0.
105    pub fn new(texture: Handle<Texture>, position: Vec2, size: Vec2) -> Self {
106        Self {
107            texture,
108            uv: Rect::new(Vec2::ZERO, Vec2::ONE),
109            position,
110            size,
111            pivot: Vec2::new(0.5, 1.0),
112            rotation: 0.0,
113            color: Color::WHITE,
114            layer: 0,
115            sort: SortMode::YSort,
116            flip: Flip::default(),
117        }
118    }
119}
120
121/// How a text's glyphs are colored.
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
123pub enum GlyphMode {
124    /// The glyphs' alpha is a mask, in the text's color: the `text`
125    /// program. A page's glyphs may then be any color: only their alpha is
126    /// read.
127    #[default]
128    Mask,
129    /// The glyphs' own colors times the text's color, as a sprite's: for a
130    /// font whose pages hold colors, such as an outline darker than its
131    /// glyphs (BMFont's `alphaChnl=2`).
132    Rgba,
133}
134
135/// A text to draw in the world, in a [`Font`]: what [`TextList::push`]
136/// takes with the text itself.
137///
138/// Its glyphs are drawn as sprites of its layer at its depth, unrotated,
139/// each glyph's corner on a whole virtual pixel: grouped by page, and in
140/// the order its characters are laid out on each, so that the glyphs of a
141/// font of two pages that overlap may draw out of their order.
142#[non_exhaustive]
143#[derive(Clone, Copy, Debug, PartialEq)]
144pub struct TextDraw {
145    /// The font.
146    pub font: Handle<Font>,
147    /// Where the pivot is in the world.
148    pub position: Vec2,
149    /// The point of the text's block at `position`, normalized over the
150    /// block [`Font::measure`] gives: (0, 0) is its top-left corner, and
151    /// (0.5, 1) the middle of its bottom edge. The block's corner is then
152    /// moved by whole pixels, so that its glyphs stay on whole pixels.
153    pub pivot: Vec2,
154    /// How it is laid out: wrapping, alignment and markup.
155    pub layout: TextLayout,
156    /// Its color, sRGB, which tints the glyphs; a markup run's color takes
157    /// its place, with its alpha times this one's.
158    pub color: Color,
159    /// Whether the glyphs are a mask in the color, or keep their own.
160    pub glyphs: GlyphMode,
161    /// Higher layers are drawn in front of lower ones.
162    pub layer: u8,
163    /// How it is ordered within its layer: [`SortMode::YSort`] by
164    /// `position.y`, as a sprite by its pivot. At one depth, the sprites go
165    /// first, then the texts in the order they were pushed. A shadow drawn
166    /// under its text needs the same depth, pushed first: one pixel lower,
167    /// a y-sorted shadow would be in front.
168    pub sort: SortMode,
169}
170
171impl TextDraw {
172    /// A text in `font` with its block's top-left corner at `position`:
173    /// laid out with [`TextLayout::new`], white, its glyphs a mask, y-sorted
174    /// in layer 0.
175    pub fn new(font: Handle<Font>, position: Vec2) -> Self {
176        Self {
177            font,
178            position,
179            pivot: Vec2::ZERO,
180            layout: TextLayout::new(),
181            color: Color::WHITE,
182            glyphs: GlyphMode::Mask,
183            layer: 0,
184            sort: SortMode::YSort,
185        }
186    }
187}
188
189/// The texts of a frame, each a [`TextDraw`] with its text, kept in one
190/// buffer of characters, so that a frame that pushes the texts of the last
191/// allocates nothing, formatted ones included ([`TextList::write`]).
192#[derive(Clone, Debug, Default, PartialEq)]
193pub struct TextList {
194    text: String,
195    draws: Vec<(TextDraw, Range<usize>)>,
196}
197
198impl TextList {
199    /// An empty list.
200    pub fn new() -> Self {
201        Self::default()
202    }
203
204    /// Adds `text`, drawn as `draw` says.
205    pub fn push(&mut self, draw: TextDraw, text: &str) {
206        let start = self.text.len();
207        self.text.push_str(text);
208        self.draws.push((draw, start..self.text.len()));
209    }
210
211    /// Adds the text `args` formats, drawn as `draw` says, with no
212    /// allocation once the list has held as much:
213    /// `texts.write(draw, format_args!("Score {score}"))`. A text whose
214    /// formatting fails is left out.
215    pub fn write(&mut self, draw: TextDraw, args: fmt::Arguments<'_>) {
216        let start = self.text.len();
217        if self.text.write_fmt(args).is_err() {
218            self.text.truncate(start);
219            return;
220        }
221        self.draws.push((draw, start..self.text.len()));
222    }
223
224    /// The texts, in the order they were added.
225    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&TextDraw, &str)> + '_ {
226        self.draws
227            .iter()
228            .map(|(draw, range)| (draw, &self.text[range.clone()]))
229    }
230
231    /// The `index`th text, which must be one of the list's.
232    pub(crate) fn at(&self, index: usize) -> (&TextDraw, &str) {
233        let (draw, range) = &self.draws[index];
234        (draw, &self.text[range.clone()])
235    }
236
237    /// How many texts there are.
238    pub fn len(&self) -> usize {
239        self.draws.len()
240    }
241
242    /// Whether there are none.
243    pub fn is_empty(&self) -> bool {
244        self.draws.is_empty()
245    }
246
247    /// Empties the list, keeping its capacity.
248    pub fn clear(&mut self) {
249        self.text.clear();
250        self.draws.clear();
251    }
252}
253
254/// Everything the renderer draws in a frame. Keep one and clear it each
255/// frame, so that its lists keep their capacity.
256///
257/// It is `#[non_exhaustive]`, so that the fields that come with later tasks
258/// break nothing: make it with [`RenderFrame::new`].
259#[non_exhaustive]
260#[derive(Clone, Debug, PartialEq)]
261pub struct RenderFrame {
262    /// The view of the world.
263    pub camera: Camera2D,
264    /// The background, and the color of the bars around an upscaled image.
265    pub clear: Color,
266    /// The sprites of the world, in any order.
267    pub sprites: Vec<SpriteDraw>,
268    /// The tile layers of the world, in any order: each in the
269    /// [`TileLayers`](crate::TileLayers) the renderer is given.
270    pub tile_layers: Vec<TileLayerDraw>,
271    /// The texts of the world, in any order.
272    pub texts: TextList,
273    /// The UI: sprites and texts drawn on the output after the world is
274    /// scaled up into it, each in its [`UiView`](crate::UiView)'s scale and
275    /// clip, by layer and depth and then in the order they are pushed.
276    pub ui: UiList,
277    /// The time animated tiles show. The shader reads it in whole
278    /// milliseconds, which wrap after 2^32 (49.7 days).
279    pub time: Duration,
280}
281
282impl RenderFrame {
283    /// An empty frame with a black background, at time 0.
284    pub fn new() -> Self {
285        Self {
286            camera: Camera2D::default(),
287            clear: Color::BLACK,
288            sprites: Vec::new(),
289            tile_layers: Vec::new(),
290            texts: TextList::new(),
291            ui: UiList::new(),
292            time: Duration::ZERO,
293        }
294    }
295
296    /// Empties the lists for the next frame, keeping their capacity, and
297    /// puts the UI's view back to the default. The camera, the clear color
298    /// and the time stay as they are.
299    pub fn clear(&mut self) {
300        self.sprites.clear();
301        self.tile_layers.clear();
302        self.texts.clear();
303        self.ui.clear();
304    }
305}
306
307impl Default for RenderFrame {
308    fn default() -> Self {
309        Self::new()
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use nadir_core::GenIndex;
316
317    use super::*;
318
319    fn draw(x: f32) -> TextDraw {
320        let font = Handle::new(GenIndex::new(0, std::num::NonZeroU32::MIN));
321        TextDraw::new(font, Vec2::new(x, 0.0))
322    }
323
324    #[test]
325    fn a_text_list_keeps_each_text_with_its_draw() {
326        let mut texts = TextList::new();
327        assert!(texts.is_empty());
328        texts.push(draw(1.0), "Hi");
329        let score = 42;
330        texts.write(draw(2.0), format_args!("Score {score}"));
331        texts.push(draw(3.0), "");
332        assert_eq!(texts.len(), 3);
333        let all: Vec<(f32, &str)> = texts.iter().map(|(d, t)| (d.position.x, t)).collect();
334        assert_eq!(all, [(1.0, "Hi"), (2.0, "Score 42"), (3.0, "")]);
335    }
336
337    #[test]
338    fn a_text_whose_formatting_fails_is_left_out() {
339        struct Fails;
340        impl fmt::Display for Fails {
341            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342                f.write_str("half")?;
343                Err(fmt::Error)
344            }
345        }
346        let mut texts = TextList::new();
347        texts.push(draw(1.0), "a");
348        texts.write(draw(2.0), format_args!("{Fails}"));
349        texts.push(draw(3.0), "b");
350        let all: Vec<&str> = texts.iter().map(|(_, t)| t).collect();
351        assert_eq!(all, ["a", "b"]);
352    }
353
354    #[test]
355    fn a_frame_cleared_and_filled_again_keeps_its_buffers() {
356        let mut frame = RenderFrame::new();
357        let fill = |frame: &mut RenderFrame| {
358            for i in 0..20 {
359                frame
360                    .texts
361                    .write(draw(i as f32), format_args!("line {i} of the frame"));
362            }
363        };
364        fill(&mut frame);
365        frame
366            .ui
367            .set_view(crate::UiView::new(crate::UiScale::Free(2.0)));
368        frame.ui.text(draw(0.0), "a");
369        let capacity = (frame.texts.text.capacity(), frame.texts.draws.capacity());
370        let pointers = (frame.texts.text.as_ptr(), frame.texts.draws.as_ptr());
371        frame.clear();
372        assert!(frame.texts.is_empty());
373        assert!(frame.ui.is_empty());
374        assert_eq!(frame.ui.view(), crate::UiView::default());
375        fill(&mut frame);
376        assert_eq!(
377            (frame.texts.text.capacity(), frame.texts.draws.capacity()),
378            capacity
379        );
380        assert_eq!(
381            (frame.texts.text.as_ptr(), frame.texts.draws.as_ptr()),
382            pointers
383        );
384    }
385
386    #[test]
387    fn a_new_text_is_white_y_sorted_and_a_mask_at_its_top_left() {
388        let text = draw(5.0);
389        assert_eq!(
390            (text.pivot, text.color, text.glyphs),
391            (Vec2::ZERO, Color::WHITE, GlyphMode::Mask)
392        );
393        assert_eq!((text.layer, text.sort), (0, SortMode::YSort));
394        assert_eq!(text.layout, TextLayout::new());
395    }
396}