Skip to main content

nadir_render/
lib.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//! The 2D renderer of the Nadir engine: y-sorted, batched sprites, tile
16//! layers drawn in chunks, bitmap text, a pixel-perfect camera, a UI drawn
17//! at the window's resolution, and the texture, atlas and font assets.
18//!
19//! It draws with [`nadir_gfx`] and finds its textures in a
20//! [`nadir_assets::AssetServer`]. It knows nothing of entities: each frame
21//! it draws a [`RenderFrame`], a list of what to draw. Games use it through
22//! [nadir_engine](https://docs.rs/nadir_engine), which re-exports it as
23//! `nadir::render`, and whose `nadir::prelude` holds the types a game fills
24//! in. There the engine's `App` makes the [`Renderer`] for the window, its
25//! systems draw the entities' sprites into the `RenderFrame`, a world
26//! resource, and the game keeps its tile layers in the world resource
27//! [`TileLayers`]. Depend on this crate directly to draw with a device of
28//! your own.
29//!
30//! # The API
31//!
32//! **Drawing.** A [`Renderer`] is made on a [`nadir_gfx::Device`] with a
33//! [`RenderConfig`], its virtual resolution. [`Renderer::render`] draws a
34//! [`RenderFrame`] into an [`Output`], the window or a render target, and
35//! says what it drew in [`FrameStats`]. [`Renderer::upscale`] gives where
36//! the virtual image lands in an output ([`Upscale`]), and
37//! [`Renderer::screen_to_world`] and [`Renderer::world_to_screen`] map
38//! points between the two. [`Renderer::ui_space`], or [`UiSpace::new`]
39//! with no renderer, gives where the UI lands at a [`UiScale`], and maps
40//! the pointer to UI units. Failures are [`RenderError`]s.
41//!
42//! **Timing.** [`Renderer::set_gpu_timing`] has each render time its
43//! passes on the GPU, where the device has timer queries, and
44//! [`Renderer::gpu_times`] gives the [`GpuTimes`] of earlier renders that
45//! the last one read back: two renders later, so that reading never waits
46//! for the GPU.
47//!
48//! **Reloading.** [`Renderer::reload_program`] builds one of the renderer's
49//! [`Program`]s again from GLSL it is given, such as its files under
50//! [`SHADER_DIR`] after an edit, and keeps the program it had when the
51//! sources do not build or do not declare the program's interface. A
52//! texture reloaded behind its handle through `nadir-assets` needs nothing
53//! of the renderer: each frame looks its textures up again, so the new
54//! texels are drawn from the first frame after the finish that swaps them
55//! in. The engine's facade does both in development builds, under its
56//! `dev` feature (roadmap M5.8).
57//!
58//! **What a frame draws.** A [`RenderFrame`] holds the [`Camera2D`], the
59//! clear color, the [`SpriteDraw`]s (each with a [`SortMode`] and a
60//! [`Flip`]), the [`TileLayerDraw`]s, the texts in a [`TextList`], the UI
61//! in a [`UiList`], and the time that animated tiles show.
62//!
63//! **The UI.** A [`UiList`] holds sprites and texts in UI units, drawn on
64//! the output after the world, in the order they are pushed, each in the
65//! [`UiView`] set before it: a [`UiScale`], pixel UI or a free scale, and a
66//! clip. [`UiList::iter`] gives them back as [`UiDraw`]s, each with its
67//! view.
68//!
69//! **Text.** A [`TextDraw`] draws a text in a [`Font`]: laid out with a
70//! [`TextLayout`] (a width to wrap at, an [`Align`]ment, and the color
71//! markup, which [`Escaped`] keeps from a player's text), in a color, its
72//! glyphs a mask or their own colors ([`GlyphMode`]). [`Font::layout`]
73//! gives each [`PlacedGlyph`] of a text, and [`Font::measure`] its block,
74//! with no GPU.
75//!
76//! **Tiles.** A [`TileLayer`] is a grid of cells, each empty or a [`Tile`]
77//! of its [`TileSet`]. The game keeps its layers in a [`TileLayers`] store,
78//! which the renderer is given beside each frame.
79//!
80//! **Assets**, loaded through `nadir-assets`:
81//!
82//! - [`Texture`]: a QOI file, decoded on a worker into a
83//!   [`DecodedTexture`], then made on the device, which must be in the
84//!   [`FinalizeCtx`](nadir_assets::FinalizeCtx).
85//! - [`Atlas`]: a cooked atlas file, `atlas/<group>.kbj`: its
86//!   [`AtlasPage`]s, and its [`AtlasSprite`]s by name, each with its
87//!   [`AtlasFrame`]s and its [`AtlasClip`]s of [`AtlasClipFrame`]s. It
88//!   needs no GPU.
89//! - [`Font`]: a cooked font file, `atlas/<font>.font.kbj`: its metrics, its
90//!   [`Glyph`]s by character, each a frame of a sprite of its atlas, and its
91//!   kerning. It needs no GPU; [`Font::load_now_in`] loads it with its atlas
92//!   and pages, which drawing it needs.
93//!
94//! **For measuring without a GPU:** [`SpriteBatcher`], the renderer's work
95//! on the CPU for sprites, and [`TileLayer::pack_chunk`], for tiles. Their
96//! instances are [`SPRITE_INSTANCE_FLOATS`] and [`TILE_INSTANCE_FLOATS`]
97//! floats each.
98//!
99//! # Example: drawing a frame
100//!
101//! The renderer draws inside a frame of the device. Into the window, the
102//! output is [`PassTarget::Surface`](nadir_gfx::PassTarget::Surface), and
103//! its size the window's drawable size:
104//!
105//! ```
106//! use nadir_assets::AssetServer;
107//! use nadir_core::UVec2;
108//! use nadir_gfx::{Device, PassTarget};
109//! use nadir_render::{FrameStats, Output, RenderError, RenderFrame, Renderer, TileLayers};
110//!
111//! /// Draws `frame` into the window, `window` pixels large. Call it between
112//! /// the device's `begin_frame` and `end_frame`.
113//! fn draw(
114//!     renderer: &mut Renderer,
115//!     device: &mut Device,
116//!     assets: &AssetServer,
117//!     tiles: &TileLayers,
118//!     frame: &RenderFrame,
119//!     window: UVec2,
120//! ) -> Result<FrameStats, RenderError> {
121//!     let output = Output {
122//!         target: PassTarget::Surface,
123//!         size: window,
124//!     };
125//!     renderer.render(device, assets, tiles, frame, output)
126//! }
127//! ```
128//!
129//! Keep one [`RenderFrame`], and clear it each frame, so that its lists keep
130//! their capacity:
131//!
132//! ```
133//! use nadir_core::{Color, Vec2};
134//! use nadir_render::{Camera2D, RenderFrame};
135//!
136//! let mut frame = RenderFrame::new();
137//! frame.clear = Color::rgb(30, 30, 46);
138//! frame.camera = Camera2D {
139//!     position: Vec2::new(160.0, 90.0),
140//!     zoom: 2.0,
141//!     shake: Vec2::ZERO,
142//! };
143//! // Each frame: empty the lists, then fill them again.
144//! frame.clear();
145//! assert!(frame.sprites.is_empty() && frame.tile_layers.is_empty());
146//! assert_eq!(frame.camera.zoom, 2.0, "the camera stays");
147//! ```
148//!
149//! # Example: a sprite from an atlas
150//!
151//! The cook packs a game's images into atlases. A frame of an atlas's
152//! sprite is drawn from its page, with its trimmed size, and its pivot
153//! placed in the trimmed quad so that its pixels land where the untrimmed
154//! cell's would:
155//!
156//! ```
157//! use nadir_assets::{AssetError, AssetServer, FinalizeCtx, Scope};
158//! use nadir_core::Vec2;
159//! use nadir_render::{Atlas, SpriteDraw};
160//!
161//! /// The first frame of `sprites/hero`, with its pivot at `position`.
162//! fn hero(server: &mut AssetServer, position: Vec2) -> Result<Option<SpriteDraw>, AssetError> {
163//!     // An atlas needs no GPU, so it can be made at once, before a window
164//!     // opens.
165//!     let atlas = server.load_now::<Atlas>("atlas/sprites.kbj", &mut FinalizeCtx::new())?;
166//!     let Some(atlas) = server.get(atlas).cloned() else {
167//!         return Ok(None);
168//!     };
169//!     // Its pages are textures, in the order of `Atlas::pages`.
170//!     let pages = atlas.load_pages(server, Scope::Global);
171//!     let Some(sprite) = atlas.sprite("sprites/hero") else {
172//!         return Ok(None);
173//!     };
174//!     let (Some(frame), Some(pivot)) = (sprite.frame(0), sprite.pivot()) else {
175//!         return Ok(None);
176//!     };
177//!     let mut draw = SpriteDraw::new(pages[frame.page()], position, frame.size().as_vec2());
178//!     draw.uv = frame.uv();
179//!     draw.pivot = frame.pivot_in(pivot);
180//!     Ok(Some(draw))
181//! }
182//! ```
183//!
184//! # Example: a text
185//!
186//! A font is loaded with its atlas and the atlas's pages, which its glyphs
187//! are drawn from. Each frame, texts are pushed into the frame's
188//! [`TextList`], formatted ones with no allocation once it is warm:
189//!
190//! ```
191//! use nadir_assets::{AssetError, AssetServer, FinalizeCtx, Handle, Scope};
192//! use nadir_core::{Color, Vec2};
193//! use nadir_render::{Align, Font, RenderFrame, TextDraw};
194//!
195//! /// Loads the font the cook made of `fonts/ui.fnt`, and the atlas and
196//! /// pages of its glyphs.
197//! fn ui_font(server: &mut AssetServer) -> Result<Handle<Font>, AssetError> {
198//!     let mut ctx = FinalizeCtx::new();
199//!     Font::load_now_in(server, "atlas/fonts/ui.font.kbj", Scope::Global, &mut ctx)
200//! }
201//!
202//! /// The score, centred at the top of a panel 120 wide at (20, 10), in
203//! /// layer 5, above the world's sprites.
204//! fn score(frame: &mut RenderFrame, font: Handle<Font>, score: u32) {
205//!     let mut text = TextDraw::new(font, Vec2::new(20.0, 10.0));
206//!     text.layout.max_width = Some(120);
207//!     text.layout.align = Align::Center;
208//!     text.layer = 5;
209//!     frame.texts.write(text, format_args!("Score {{c:#ff0}}{score}{{/c}}"));
210//! }
211//!
212//! let mut frame = RenderFrame::new();
213//! let font = Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN));
214//! score(&mut frame, font, 120);
215//! let (_, text) = frame.texts.iter().next().expect("a text");
216//! assert_eq!(text, "Score {c:#ff0}120{/c}");
217//! # let _ = (ui_font, Color::WHITE);
218//! ```
219//!
220//! # Example: a UI
221//!
222//! A HUD in pixel UI, the virtual image's own pixels, and a window at the
223//! settings' free scale over it, its list clipped inside it. The pointer,
224//! in the window's pixels, is mapped to each view's units for hit tests:
225//!
226//! ```
227//! use nadir_assets::Handle;
228//! use nadir_core::{Rect, UVec2, Vec2};
229//! use nadir_render::{
230//!     Font, RenderFrame, SpriteDraw, TextDraw, Texture, UiDraw, UiScale, UiSpace, UiView,
231//! };
232//!
233//! /// A sprite of all of `texture` over `rect`, by its top-left corner.
234//! fn panel(texture: Handle<Texture>, rect: Rect) -> SpriteDraw {
235//!     let mut sprite = SpriteDraw::new(texture, rect.min, rect.size());
236//!     sprite.pivot = Vec2::ZERO;
237//!     sprite
238//! }
239//!
240//! fn ui(frame: &mut RenderFrame, white: Handle<Texture>, font: Handle<Font>, scale: f32) {
241//!     // The HUD: a panel, then its label over it.
242//!     frame.ui.set_view(UiView::new(UiScale::Pixel(1)));
243//!     frame.ui.sprite(panel(white, Rect::new(Vec2::new(4.0, 4.0), Vec2::new(60.0, 14.0))));
244//!     frame.ui.write(TextDraw::new(font, Vec2::new(6.0, 6.0)), format_args!("HP {}", 12));
245//!     // A window, drawn after the HUD, so over it; its rows cut to its
246//!     // list, which is cut to the window.
247//!     let window = UiView::new(UiScale::Free(scale));
248//!     let area = Rect::new(Vec2::new(10.0, 10.0), Vec2::new(210.0, 160.0));
249//!     frame.ui.set_view(window);
250//!     frame.ui.sprite(panel(white, area));
251//!     frame.ui.set_view(window.clipped(area).clipped(Rect::new(
252//!         Vec2::new(14.0, 30.0),
253//!         Vec2::new(206.0, 156.0),
254//!     )));
255//!     for row in 0..20 {
256//!         let at = Vec2::new(16.0, 30.0 + 12.0 * row as f32);
257//!         frame.ui.write(TextDraw::new(font, at), format_args!("entity {row}"));
258//!     }
259//! }
260//!
261//! let mut frame = RenderFrame::new();
262//! let (white, font) = (Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN)),
263//!                      Handle::new(nadir_core::GenIndex::new(1, std::num::NonZeroU32::MIN)));
264//! ui(&mut frame, white, font, 2.0);
265//! assert_eq!(frame.ui.len(), 23);
266//! assert!(matches!(frame.ui.iter().nth(1), Some((UiDraw::Text(_, "HP 12"), _))));
267//!
268//! // A 1280 × 720 window over a 320 × 180 world: the pointer at (60, 70)
269//! // is over the window, at the free scale of 2.
270//! let window = UiSpace::new(UiScale::Free(2.0), UVec2::new(320, 180), UVec2::new(1280, 720));
271//! assert_eq!(window.to_ui(Vec2::new(60.0, 70.0)), Vec2::new(30.0, 35.0));
272//! let hud = UiSpace::new(UiScale::Pixel(1), UVec2::new(320, 180), UVec2::new(1280, 720));
273//! assert_eq!(hud.to_ui(Vec2::new(60.0, 70.0)), Vec2::new(15.0, 17.5));
274//! ```
275//!
276//! # Example: reloading a shader
277//!
278//! The renderer reads no file. A game that watches its shader files reads
279//! the one that changed, and gives the program's sources to the renderer:
280//!
281//! ```
282//! use std::fs;
283//! use std::path::Path;
284//!
285//! use nadir_gfx::{Device, ShaderSource};
286//! use nadir_render::{Program, Renderer, SHADER_DIR};
287//!
288//! /// Builds `program` again from its files, or says why it could not, in
289//! /// which case the renderer goes on drawing with the program it had.
290//! fn reload(
291//!     renderer: &mut Renderer,
292//!     device: &mut Device,
293//!     program: Program,
294//! ) -> Result<(), String> {
295//!     let read = |file: &str| {
296//!         fs::read_to_string(Path::new(SHADER_DIR).join(file)).map_err(|error| error.to_string())
297//!     };
298//!     let vertex = read(program.vertex_file())?;
299//!     let fragment = read(program.fragment_file())?;
300//!     let source = ShaderSource {
301//!         glsl_vs: &vertex,
302//!         glsl_fs: &fragment,
303//!         msl: "",
304//!     };
305//!     renderer
306//!         .reload_program(device, program, source)
307//!         .map_err(|error| error.to_string())
308//! }
309//!
310//! // Each program's files are in the folder.
311//! for &program in Program::ALL {
312//!     assert!(Path::new(SHADER_DIR).join(program.vertex_file()).is_file());
313//!     assert!(Path::new(SHADER_DIR).join(program.fragment_file()).is_file());
314//! }
315//! ```
316//!
317//! # Order
318//!
319//! Sprites are drawn by [`SpriteDraw::layer`], lowest first; within a
320//! layer, by depth: the pivot's y for [`SortMode::YSort`], so that lower
321//! on screen is in front, or the number of [`SortMode::Fixed`]. `Fixed(0)`
322//! is behind and `Fixed(u32::MAX)` in front of every y-sorted sprite of
323//! its layer. Sprites of one depth are grouped by texture, and then keep
324//! the order they were added in, so the same frame draws the same way
325//! every time. A tile layer is drawn at its [`TileLayerDraw::layer`] and
326//! [`TileLayerDraw::depth`], before the sprites of the same layer and
327//! depth. A text's glyphs are drawn at its layer, and at its depth, its
328//! position's y or its fixed depth: at one depth, after every sprite, the
329//! texts in the order they were pushed.
330//!
331//! Consecutive sprites of one texture are one instanced draw, and so are
332//! consecutive glyphs of one page. Y-sorting interleaves textures, so
333//! sprites that share an atlas page draw in fewer batches
334//! ([`FrameStats::batches`]).
335//!
336//! # Pixel-perfect mode
337//!
338//! The renderer has one mode so far: the world is drawn into an image of
339//! exactly [`RenderConfig::virtual_resolution`], which is then scaled up
340//! into the output by the largest whole factor that fits, at least 1, and
341//! centred, with bars of the clear color around it; an output smaller than
342//! the image crops it. The camera's zoom is rounded to a whole number, at
343//! least 1. The view's top-left corner, the top-left corner of each
344//! unrotated sprite and glyph, and each tile layer's origin are moved to
345//! whole virtual pixels, so that texels land on whole pixels (ADR-0018).
346//!
347//! # The UI
348//!
349//! After the blit, the frame's [`UiList`] is drawn on the output, at its
350//! resolution: by layer, then by a [`SortMode::Fixed`] depth
351//! ([`SortMode::YSort`] is 0 there), then in the order pushed, sprites and
352//! texts alike, so a later window is over an earlier one (ADR-0055). The
353//! camera plays no part. Each sprite and text is in its [`UiView`]'s
354//! [`UiScale`]:
355//!
356//! - [`UiScale::Pixel`]: a UI unit is a whole number of the virtual
357//!   image's pixels, from the image's corner, cut to the image; corners
358//!   snap to whole UI units, so the UI's texels line up as the world's.
359//! - [`UiScale::Free`]: output pixels a unit, from the output's corner,
360//!   bars included; corners snap to whole output pixels.
361//!
362//! Both corners of an unrotated sprite snap, so sprites that share an edge
363//! share it on the output at any scale; a glyph's corner snaps and keeps
364//! its size. A view's clip cuts what it draws, as a scissor; a quad wholly
365//! outside it is not drawn nor counted. [`UiSpace`] gives where a scale
366//! puts the UI, and maps the pointer to UI units.
367//!
368//! # Textures that are not ready
369//!
370//! A sprite whose texture is still loading is not drawn, and is counted in
371//! [`FrameStats::skipped`]. One whose texture failed shows all of the
372//! texture's placeholder, an 8 × 8 magenta and black checker, whatever its
373//! `uv`, when the server shows placeholders
374//! ([`OnFailure::Placeholder`](nadir_assets::OnFailure::Placeholder));
375//! otherwise it is skipped too. A tile layer does the same with its tile
376//! set's texture, and a text's glyphs with their page: a glyph whose page
377//! is not ready, or was never loaded, is not drawn, and is counted in
378//! [`FrameStats::skipped`]. A text whose font, atlas or sprite is not ready
379//! or does not fit is not drawn at all ([`FrameStats::skipped_texts`]). An
380//! atlas or a page never loaded, and an atlas that lacks the glyphs'
381//! frames, are logged once for the font. A character a font lacks draws
382//! the font's fallback glyph, and is logged once. The UI's sprites and
383//! texts are the same, counted with the world's in the same fields.
384//!
385//! # Tile layers
386//!
387//! The renderer packs a chunk of [`TileLayer::CHUNK`] × [`TileLayer::CHUNK`]
388//! cells into a GPU buffer the first time the view shows it, and again only
389//! after one of its cells changes ([`TileLayer::set`]). It draws only the
390//! chunks in view, each in one instanced draw ([`FrameStats::chunks`]).
391//! Animated tiles change frame on the GPU, from [`RenderFrame::time`] in
392//! whole milliseconds, with no work on the CPU. A layer's buffers are freed
393//! at the first frame after it leaves the [`TileLayers`].
394//!
395//! # Errors
396//!
397//! [`Renderer::new`] and [`Renderer::render`] fail with
398//! [`RenderError::Gfx`] when the device refuses a call, and
399//! [`Renderer::new`] with [`RenderError::BadConfig`] for an empty virtual
400//! resolution. [`Renderer::reload_program`] fails with
401//! [`RenderError::Gfx`] when the sources declare another interface, do not
402//! compile or link, or the device refuses, and keeps the program it had.
403//! [`TileLayer::new`] panics on a tile size that is not a finite
404//! number above 0, and [`TileLayer::set`] on a cell outside the layer.
405//! [`Font::load_now_in`] fails with the font's or its atlas's
406//! [`AssetError`](nadir_assets::AssetError), or when the atlas lacks the
407//! glyphs' frames.
408//!
409//! # Allocation and threading
410//!
411//! The renderer's lists and buffers are reused from frame to frame, the
412//! frame's texts' one buffer of characters too, and its [`UiList`]'s. Its
413//! instance buffer, of the world's sprites and glyphs and then the UI's,
414//! grows by doubling and never shrinks; a steady frame allocates nothing
415//! on the heap. The renderer runs on the device's
416//! thread, as the [`nadir_gfx::Device`] stays there.
417//!
418//! # Platforms
419//!
420//! It draws wherever `nadir-gfx` has a device: on Linux so far. Windows
421//! and macOS have no OpenGL context yet (roadmap M2.6 and M2.7). What needs
422//! no GPU, such as frames, tile layers, atlases, fonts and their layout, and
423//! the [`SpriteBatcher`], works on all three.
424//!
425//! # Not built yet
426//!
427//! A debug draw list (M7.6 draws the facade's overlays as sprites,
428//! ADR-0064), post effects, camera rotation, the smooth-camera and
429//! native-resolution modes, and the Metal shaders (M10.3).
430//!
431//! # Features
432//!
433//! `headless-test` builds the crate's own tests that draw on an offscreen
434//! OpenGL context, for the workspace's CI. A user does not need it.
435//!
436//! The design is in
437//! [`docs/subsystems/render.md`](https://github.com/jabbott-iii/Nadir/blob/main/docs/subsystems/render.md).
438
439mod atlas;
440mod batcher;
441mod chunks;
442mod error;
443mod font;
444mod frame;
445mod glyphs;
446mod instance;
447mod plan;
448mod renderer;
449mod shader;
450mod sort;
451mod text;
452mod texture;
453mod tiles;
454mod timing;
455mod ui;
456mod view;
457
458// The README's examples are compiled as doc tests too.
459#[cfg(doctest)]
460#[doc = include_str!("../README.md")]
461struct ReadmeDoctests;
462
463pub use atlas::{Atlas, AtlasClip, AtlasClipFrame, AtlasFrame, AtlasPage, AtlasSprite};
464pub use batcher::SpriteBatcher;
465pub use error::RenderError;
466pub use font::{Font, Glyph};
467pub use frame::{Camera2D, Flip, GlyphMode, RenderFrame, SortMode, SpriteDraw, TextDraw, TextList};
468pub use instance::SPRITE_INSTANCE_FLOATS;
469pub use renderer::{FrameStats, Output, RenderConfig, Renderer};
470pub use shader::{Program, SHADER_DIR};
471pub use text::{Align, Escaped, PlacedGlyph, TextLayout};
472pub use texture::{DecodedTexture, Texture};
473pub use tiles::{TILE_INSTANCE_FLOATS, Tile, TileLayer, TileLayerDraw, TileLayers, TileSet};
474pub use timing::GpuTimes;
475pub use ui::{UiDraw, UiList, UiScale, UiSpace, UiView};
476pub use view::Upscale;