What Nadir is
Nadir is a game engine for 2D games seen from above, such as action adventures and dungeon crawlers. You write the game in Rust, as a program that depends on one crate, nadir_engine, which your code calls nadir. The engine opens the window, runs the game loop, draws, plays sound, and loads files. Your game adds its data, and systems: plain functions that the loop calls.
Nadir is built from the ground up, with no third-party crates. It has its own bindings to each operating system, its own OpenGL renderer, its own entity component system (ECS, explained below), and its own collision, file formats, and tools. So building a game downloads nothing but Nadir's own crates.
This guide describes the engine at commit 5d93716, version 0.4.0. Each Rust program on this page is one of the engine's examples, in crates/engine/examples, which every build of the engine compiles, so the code here compiles against that commit. Version 0.4.0 is still in development: its API will change before 1.0.
What works today
- Linux, under X11 or under Wayland through XWayland: everything in this guide.
- Windows 10 and later, and macOS 12 and later: a game builds and opens its window, but the window stays empty, the game is silent, and it reads no gamepads. The engine cannot draw, play sound, or read pads there until its OpenGL contexts (roadmap tasks M2.6 and M2.7), its audio output (M6.4 and M6.5), and its gamepad readers (M8.2 and M8.3) on those systems are built. The window code there also still waits to be checked by hand.
- Not built yet: a settings file (roadmap task M9.3), a kit for menus (M9.2), and packages and installers for players (M11).
What you need
- Rust, from rustup, at edition 2024. The engine is built and tested with the stable toolchain its repository pins, 1.99.0 at this commit; older versions are not tested.
- On Linux: an X11 session, or Wayland with XWayland, and a graphics driver with OpenGL 3.3. The engine loads
libX11,libEGL, and OpenGL while the game runs, and ALSA'slibasoundfor sound, so building needs no development packages. Withoutlibasound, the game runs, silent. - On Windows: the MSVC build tools and the Windows SDK. On macOS: the Xcode command-line tools.
- For art and sound: any image editor that saves PNG; Aseprite for animated sprites; LDtk 1.5.3, a level editor, for levels; a BMFont generator for bitmap fonts; and WAV files for sound. Nadir's asset cook turns all of these into the engine's own formats (see Assets and the cook).
Make a project
Make a binary crate, and depend on the engine:
cargo new my-game
cd my-game
[package]
name = "my-game"
version = "0.1.0"
edition = "2024"
[dependencies]
nadir_engine = "0.4"
[features]
dev = ["nadir_engine/dev"]
The package is nadir_engine, since the name nadir was taken on crates.io, and its library is nadir. The requirement "0.4" means 0.4.0 or any later 0.4 release. The dev feature is for development builds: they reload what you change while the game runs, and show the debug tools (see Development builds). Making it a feature of your own game, rather than turning it on in [dependencies], keeps it out of release builds.
Then a first game, in src/main.rs:
use nadir::prelude::*;
fn main() -> Result<(), nadir::Error> {
App::new(Config::default())
.add_fixed_system(FixedStage::Gameplay, "hello", |_, tick| {
if tick.index == 0 {
nadir::log::info!("the first tick");
}
})
.run()
}
cargo run opens a window and runs the game until you close it. The log prints the first tick to the terminal, and to a log file (see Logs, errors, and crash reports). cargo run --features dev runs a development build.
How the game loop runs
A Nadir game keeps two clocks:
- Ticks are the simulation's steps, exactly 60 a second, each 1/60 s of game time. Gameplay runs in ticks, so it behaves the same however fast the computer is.
- Frames are what the screen shows, as often as the display allows (60 a second by default). A frame draws each moving thing part of the way from where it was at the start of the last tick to where that tick left it. This interpolation keeps motion smooth when frames and ticks do not line up.
Each frame, App::run:
- hands the window's events, keys and mouse, to the input;
- runs the ticks that are due, none or several; each tick first reads the game's actions from the input, then runs the tick's stages;
- runs the frame's stages once, which fill the
RenderFrame, the list of what to draw; - draws it, and finishes the files that worker threads have loaded.
A frame counts for at most 250 ms of game time, so after a long pause the game falls behind instead of running a burst of ticks to catch up.
Stages, and the engine's own systems
Systems run in stages, in a fixed order. A tick's stages are Input, Gameplay, Movement, PostMovement, and Cleanup; a frame's are Animate, Camera, Ui, and Extract. Within a stage, systems run in the order they were added, and the engine adds its own first:
| Stage | Engine system | What it does |
|---|---|---|
tick Input | nadir::snapshot | Keeps each entity's position from the start of the tick, for interpolation |
tick Movement | nadir::movement | Moves each entity by its Velocity; one with a Collider slides along what it meets |
tick PostMovement | nadir::parent_offsets | Puts each entity with a Parent at its parent's position, plus its offset |
tick PostMovement | nadir::triggers | Sends TriggerEnter and TriggerExit events |
tick PostMovement | nadir::navigation | Finds the paths asked of Navigation, within a budget a tick |
frame Animate | nadir::animate | Advances each Animator, and mirrors the sprites that face left |
frame Extract | nadir::sound | Plays each AudioEmitter at its entity, and the music of the area the listener is in |
frame Extract | nadir::extract_sprites | Draws each Sprite, between the last two ticks |
frame Extract | nadir::extract_level | Draws the current level's tile layers, with its background color |
So a game sets velocities in Gameplay, and reacts to the moves after the engine's, in Movement or PostMovement. Put gameplay in tick systems, and what only shows, such as the camera and the interface, in frame systems. A tick system must not decide anything by what a frame system set: frames come at no fixed rate, so the game would play differently on another computer.
The configuration
Config sets the window (title, window_size, min_window_size, resizable, fullscreen), the pacing (frame_rate_limit, 60 by default, and vsync), the size of the image the world is drawn into (virtual_resolution, 480 × 270 by default), the folder the assets load from (assets), and each sound bus's starting volume (volumes). studio and game name the folders the game writes into: its log, its crash reports, and the debug tools' settings.
The world: entities, components, resources, and events
Nadir keeps the game's state in a World, organized as an entity component system:
- An entity is an ID, a thing in the game, with no data of its own.
- A component is data an entity has, such as a
Transform(its position) or aSprite. Any type is a component once it hasimpl Component for MyType {}and is registered withworld.register::<MyType>(). - A resource is a value the world holds one of, such as the score or the asset server.
- An event is a message one system sends and others read.
App::add_event::<T>()adds its queue, the resourceEvents<T>. A tick system readstick_events(), the tick's own; a frame system readsframe_events(), all those sent since the last frame.
A system is a function fn(&World, &Tick) for a tick's stage, or fn(&World, &Frame) for a frame's. It reads and writes through the world: world.read::<T>() and world.write::<T>() for a component's storage, and world.resource::<R>() and world.resource_mut::<R>() for a resource. These are borrowed while the game runs, so borrowing one storage mutably twice at once panics, naming the system and the type. A system keeps its state in resources, never in globals.
Inside a system, spawn and despawn through world.commands(): commands apply after the tick's stages, or the frame's, so no system sees the world change under it. During setup, world.spawn() spawns at once.
use nadir::prelude::*;
/// Hit points: a component of the game's own.
struct Health(u32);
impl Component for Health {}
/// The score: a resource, the world's one value of its type.
#[derive(Default)]
struct Score(u32);
/// An event: one system sends it, and others read it.
#[derive(Clone)]
struct Defeated {
points: u32,
}
fn main() -> Result<(), nadir::Error> {
let mut app = App::new(Config::default())
.insert_resource(Score::default())
.add_event::<Defeated>()
.add_fixed_system(FixedStage::Gameplay, "wear_down", wear_down)
.add_fixed_system(FixedStage::Cleanup, "keep_score", keep_score);
let world = app.world_mut();
world.register::<Health>();
for hit_points in [30, 60, 90] {
world.spawn().with(Health(hit_points));
}
app.run()
}
/// Takes a hit point from each entity every tick. One that reaches 0 is
/// despawned after the tick, and worth 10 points.
fn wear_down(world: &World, _tick: &Tick) {
let mut healths = world.write::<Health>();
let mut commands = world.commands();
let mut defeated = world.resource_mut::<Events<Defeated>>();
for (entity, health) in healths.iter_mut() {
health.0 = health.0.saturating_sub(1);
if health.0 == 0 {
commands.despawn(entity);
defeated.send(Defeated { points: 10 });
}
}
}
/// Adds up this tick's points.
fn keep_score(world: &World, _tick: &Tick) {
let points: u32 = world
.resource::<Events<Defeated>>()
.tick_events()
.iter()
.map(|event| event.points)
.sum();
world.resource_mut::<Score>().0 += points;
}
Reflected components
A component that prefabs and levels set, that saves keep, and that the inspector edits must be reflected: its fields readable and writable by name. Define it with nadir::scene::reflect_struct! (or reflect_enum! and reflect_newtype!), and register it with App::register_component instead of world.register. The world hash, which checks that two runs simulated the same thing (see Testing a game), covers the reflected components.
use nadir::prelude::*;
use nadir::scene::reflect_struct;
reflect_struct! {
/// Hit points. In a prefab: `"Health": { "max": 12 }`, with
/// `current` left at its default.
#[derive(Clone, Debug, Default, PartialEq)]
struct Health {
current: i32,
max: i32,
}
}
impl Component for Health {}
fn main() -> Result<(), nadir::Error> {
let mut app = App::new(Config::default()).register_component::<Health>();
app.world_mut().spawn().with(Health {
current: 12,
max: 12,
});
app.run()
}
Input actions
Gameplay reads actions, never keys, so that players can rebind them and replays can play them back:
- Name the actions with an enum that implements
ActionSet. Each has a kind:Button,Axis1(one value from 0 to 1), orAxis2(a direction no longer than 1). - Bind keys, mouse buttons, and gamepads to them in an
ActionMap, up to four bindings an action:Binding::Key,Binding::MouseButton, orBinding::KeyComposite2, four keys that make a direction; and a pad'sBinding::PadButton(GamepadButton::A),Binding::PadStick(Stick::Left)for a direction, orBinding::PadAxis { axis, sign }, half of a stick's axis or a trigger, for a button or a value from 0 to 1. - Add the map with
App::add_actions.
Each tick, before its stages, the input is latched into the resource ActionState<A>: copied once, so every system of the tick sees the same state. It answers pressed, just_pressed, just_released, value, and axis2. A key pressed and released between two ticks is still seen. Read edges such as just_pressed in tick systems: a frame system sees only the last tick's. The resource Input also holds the pointer and the mouse wheel. A walking hero and Game states below show actions in use.
Gamepads work on Linux. Every connected pad drives the bindings, so a player can pick up any of them. A pad's face buttons are named by their place, so GamepadButton::A is the bottom one on every pad. Its sticks and triggers have deadzones, the part of their travel that reads as 0, so that a stick at rest moves nothing: a stick counts from 0.2 of the way out and reads full length from 0.95, the length rescaled in between, and a trigger counts from 0.1. A half of an axis bound to a button presses at 0.5 and lets go below 0.4, so it does not flicker. Input::set_deadzones changes them. While the window is in the background, the pads are held at rest. Input::active_device says whether the keyboard and mouse or a pad was used last, so a game can show the right prompts.
Assets and the cook
The engine does not read PNG, Aseprite, LDtk, or WAV files while the game runs. Its asset cook, nadir-cook, turns them into the engine's own formats ahead of time: fast to load, checked once, and packed into one file for release. Install it and cook a folder:
cargo install nadir-cook
nadir-cook assets cooked
nadir-cook [--force] SOURCE OUT cooks the files below SOURCE into OUT, and skips each job whose files did not change since the last cook into OUT, unless --force.
| Source | What it makes |
|---|---|
| A folder's PNG images, Aseprite exports, and BMFont fonts | An atlas named after the folder: its images packed into a few large textures, its pages (atlas/<folder>_<n>.qoi), and an index of where each went (atlas/<folder>.kbj). sprites/hero.png becomes the sprite sprites/hero. |
An image's sidecar, <name>.sprite.jsonc | Cuts the image into frames and sets their pivot, { "frames": [12, 20], "pivot": [6, 20] }, or makes it a tile set, { "tiles": [16, 16] } |
An Aseprite export: the JSON of aseprite -b hero.aseprite --sheet hero.png --data hero.json --format json-array --list-tags | A sprite of its frames, each of its tags a clip, such as sprites/hero/walk |
A BMFont font in the text format, .fnt, and its pages | The font's glyphs in its folder's atlas, and its font file, atlas/<folder>/<name>.font.kbj |
A WAV file below audio/ | A sound, audio/<path>.kpcm; below audio/music/, a music track, audio/music/<name>.qoa, compressed. A sidecar <name>.sound.jsonc can set its format, its rate, and whether it loops. |
A JSONC file below data/ (JSON with comments) | The same data in the engine's binary JSON, data/<path>.kbj; one below data/prefabs/ is checked as a prefab |
An LDtk 1.5.3 project, .ldtk, and its level files | A level file of each level, levels/<name>.klvl (see Levels and prefabs) |
Every file the cook writes also goes into one pack, game.kpak: each file found by its path, checked as it is read, and compressed where that makes it smaller. Asset paths are lowercase.
Point Config::assets at the cooked folder. A relative path is found from the folder the game runs in. A build without dev reads the pack there when there is one, and the loose files otherwise; a build with dev reads the loose files, so that it can reload them.
Loading assets
The resource AssetServer loads them:
server.load::<Texture>(path)returns a handle at once: a small ID that stands for the asset. A worker thread reads and decodes the file, and the main loop finishes it, a couple of milliseconds' worth each frame. A sprite whose texture has not loaded yet is not drawn.server.load_nowmakes the asset before it returns, for what the game needs to set up. Before the window opens there is no GPU, so only an asset that needs none, such as anAtlasbut not aTexture, can be made then.- The asset types are
Texture(a QOI image),Atlas,nadir::render::Font,SoundandMusic, andnadir::scene'sLevelandPrefabAsset. - Assets load in a
Scope,Global,Level, orTransient, andunload_scopefrees those of one: a level's assets go when the next level replaces it.
Loads finish only in drawn frames, at no frame known in advance, so a tick system must not depend on whether an asset has loaded yet.
Sprites, the camera, and animation
An entity with a Transform and a Sprite is drawn. Its position is the sprite's pivot, the middle of its bottom edge unless the sidecar sets another: its feet. Sprites are sorted by layer, higher in front, and within a layer they are y-sorted: drawn in the order of their pivots down the screen, so that a character lower on the screen covers one above it, as in a scene seen from above. Sprite::new(texture, size) shows a whole texture, and Sprite::from_atlas a frame of a cooked atlas.
The world is drawn into an image of Config::virtual_resolution pixels, scaled up into the window by the largest whole factor that fits, with bars of RenderFrame::clear's color around it, so pixel art stays sharp. The camera is the RenderFrame's camera: a frame system in the Camera stage sets its position, the world point at the middle of the view. World space has +x to the right and +y down, in pixels, as tile editors have it.
To move an entity at once, with nothing drawn on the way, write both its Transform and its PrevTransform, the position the engine interpolates from.
A Clip is a list of frames, each shown for a time, that loops or plays once. The resource Clips keeps them: add_atlas adds every clip of a cooked atlas, named after the sprite and the Aseprite tag. An Animator plays a clip on its entity's sprite. Animator::play does nothing if that clip is already playing, so a tick system can call it every tick. An entity whose Facing is Left has its sprite mirrored, and a clip that plays once sends AnimationFinished when it ends.
A walking hero
This game has a hero who walks with WASD or the arrow keys, animated and facing the way they go, on a field of grass walled in by stone that they collide with, and a camera that follows them. Its art is cooked from these files:
assets/sprites/hero.png the hero's sheet, exported from Aseprite
assets/sprites/hero.json its frames and its tags, `stand` and `walk`
assets/sprites/tiles.png a tile set: grass is tile 0, stone tile 1
assets/sprites/tiles.sprite.jsonc
{ "tiles": [16, 16] }: cut it into 16-pixel tiles
use std::error::Error;
use nadir::assets::Scope;
use nadir::prelude::*;
/// What the player does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Act {
Move,
}
impl ActionSet for Act {
const ALL: &'static [Self] = &[Act::Move];
fn index(self) -> usize {
self as usize
}
fn name(self) -> &'static str {
"move"
}
fn kind(self) -> ActionKind {
ActionKind::Axis2
}
}
/// The hero's clips: the tags of their Aseprite export.
struct Gait {
stand: Handle<Clip>,
walk: Handle<Clip>,
}
/// The ground's tile layer.
struct Ground(Handle<TileLayer>);
/// How fast the hero walks, in pixels a second.
const SPEED: f32 = 120.0;
/// The field's size in tiles, and a tile's side in pixels.
const WIDTH: u32 = 30;
const HEIGHT: u32 = 17;
const TILE: f32 = 16.0;
fn main() -> Result<(), Box<dyn Error>> {
let mut map = ActionMap::<Act>::new()?;
let keys = |up, down, left, right| Binding::KeyComposite2 {
up,
down,
left,
right,
};
map.bind(Act::Move, 0, keys(Key::W, Key::S, Key::A, Key::D))?;
map.bind(
Act::Move,
1,
keys(Key::Up, Key::Down, Key::Left, Key::Right),
)?;
let mut app = App::new(Config {
title: "My game".into(),
game: "My game".into(),
assets: "cooked".into(),
..Config::default()
})
.add_actions(map)
.add_fixed_system(FixedStage::Gameplay, "walk", walk)
.add_frame_system(FrameStage::Camera, "follow", follow)
.add_frame_system(FrameStage::Extract, "draw_ground", draw_ground);
let world = app.world_mut();
// The cooked atlas, made now, and its pages, which load in the
// background and are drawn once they have.
let (atlas, pages) = {
let mut server = world.resource_mut::<AssetServer>();
let atlas = server.load_now::<Atlas>("atlas/sprites.kbj", &mut FinalizeCtx::new())?;
let atlas = server.get(atlas).cloned().ok_or("the atlas did not load")?;
let pages = atlas.load_pages(&mut server, Scope::Global);
(atlas, pages)
};
let page = |sprite: &AtlasSprite| {
let first = sprite.frames().first().ok_or("a sprite with no frame")?;
pages.get(first.page()).copied().ok_or("a frame on no page")
};
let gait = {
let mut clips = world.resource_mut::<Clips>();
clips.add_atlas(&atlas, &pages)?;
Gait {
stand: clips.find("sprites/hero/stand").ok_or("no clip `stand`")?,
walk: clips.find("sprites/hero/walk").ok_or("no clip `walk`")?,
}
};
let hero = atlas
.sprite("sprites/hero")
.ok_or("no sprite `sprites/hero`")?;
let hero = Sprite::from_atlas(page(hero)?, hero, 0).ok_or("the hero has no frame")?;
let tiles = atlas
.sprite("sprites/tiles")
.ok_or("no sprite `sprites/tiles`")?;
let set = tiles
.tile_set(page(tiles)?)
.ok_or("`sprites/tiles` is not a tile set")?;
// The ground to draw, and the grid of solid cells to collide with.
let mut ground = TileLayer::new(set, UVec2::new(WIDTH, HEIGHT), TILE, Vec2::ZERO);
let mut grid = TileGrid::new(WIDTH, HEIGHT, TILE, Vec2::ZERO);
for y in 0..HEIGHT {
for x in 0..WIDTH {
let cell = IVec2::new(x as i32, y as i32);
let stone = x == 0 || y == 0 || x == WIDTH - 1 || y == HEIGHT - 1;
ground.set(cell, Some(Tile::new(if stone { 1 } else { 0 })));
grid.set_solid(cell, stone);
}
}
let ground = world.resource_mut::<TileLayers>().add(ground);
world.resource_mut::<Collisions>().set_grid(grid);
world
.spawn()
.with(Player)
.with(Transform::at(Vec2::new(240.0, 136.0)))
.with(Velocity::default())
.with(hero)
.with(Animator::new(gait.stand))
.with(Facing::Right)
// A box at the hero's feet, which their Transform is.
.with(Collider::solid(Shape::Aabb {
half: Vec2::new(5.0, 3.0),
}));
world.insert_resource(gait);
world.insert_resource(Ground(ground));
app.run()?;
Ok(())
}
/// Walks the hero by the `Move` action, faces them the way they go, and
/// plays their walk while they go. The engine's `nadir::movement`, after
/// this in the tick, moves them and slides them along the walls.
fn walk(world: &World, _tick: &Tick) {
let direction = world.resource::<ActionState<Act>>().axis2(Act::Move);
let gait = world.resource::<Gait>();
let players = world.read::<Player>();
let mut velocities = world.write::<Velocity>();
let mut facings = world.write::<Facing>();
let mut animators = world.write::<Animator>();
for (player, _) in players.iter() {
if let Some(velocity) = velocities.get_mut(player) {
velocity.0 = direction * SPEED;
}
if let Some(facing) = facings.get_mut(player) {
if direction.x < 0.0 {
*facing = Facing::Left;
} else if direction.x > 0.0 {
*facing = Facing::Right;
}
}
if let Some(animator) = animators.get_mut(player) {
animator.play(if direction == Vec2::ZERO {
gait.stand
} else {
gait.walk
});
}
}
}
/// Centers the camera on the hero, where this frame draws them: part of the
/// way from where the last tick started to where it left them.
fn follow(world: &World, frame: &Frame) {
let Some(player) = world.read::<Player>().entities().first().copied() else {
return;
};
let Some(now) = world.read::<Transform>().get(player).map(|it| it.position) else {
return;
};
let then = world
.read::<PrevTransform>()
.get(player)
.map_or(now, |it| it.0.position);
world.resource_mut::<RenderFrame>().camera.position = then.lerp(now, frame.alpha);
}
/// Draws the ground, behind every sprite.
fn draw_ground(world: &World, _frame: &Frame) {
let ground = world.resource::<Ground>().0;
world
.resource_mut::<RenderFrame>()
.tile_layers
.push(TileLayerDraw::new(ground));
}
Tile layers, levels, and prefabs
A TileLayer is a grid of cells that show tiles of a TileSet, a texture cut into equal cells. Tile::animated cycles through tiles with no work on the CPU. Add the layer to the resource TileLayers, and push a TileLayerDraw of its handle into RenderFrame::tile_layers each frame, in the Extract stage, as the hero's game does. Tiles do not collide by themselves: the collision grid is a separate TileGrid, set with Collisions::set_grid.
A level made in LDtk does all of this for you. The cook turns each level of a project into a level file, by these conventions:
- The IntGrid layer named
Collisionis the collision grid. - A tile's custom data
{"frames": 4, "ms": 250}animates it, and{"tall": [1, 2]}marks the top of a tall sprite, such as a tree, which is drawn y-sorted with the characters instead of flat on the ground. - Each entity spawns the prefab of its name, in snake_case, and its fields named
Component__fieldset that component's field.
A prefab is a template for an entity: its components and their values, in data/prefabs/<name>.jsonc. A prefab can "extends" another and change only what differs. This rock stands on its feet, y-sorted among the characters, with a box at its feet that stops what walks into it:
{
"name": "rock",
"components": {
"Sprite": { "atlas": "atlas/sprites.kbj", "sprite": "sprites/rock", "frame": 0, "layer": 1 },
"Collider": {
"shape": { "Aabb": { "half": [7, 4] } },
"offset": [0, -4],
"layer": ["World"],
"mask": ["World"]
}
}
}
The collision layers' names, "World" here, are the game's: App::collision_layers(&["World", "People"]) names bit 0, then bit 1. app.load_level("field") loads levels/field.klvl during setup, in place of the last level: its tile layers drawn, its grid collided with, and its tall tiles and entities spawned. During play, the Loading game state loads one behind a loading screen (see Game states).
Collision and paths
Collision is kinematic: things move where the game says, with no forces or bouncing bodies. A Collider is a box or a circle (Shape) on collision layers (LayerMask), offset from its entity's position. Collider::solid stops what moves into it; Collider::trigger only notices it, and the engine sends TriggerEnter and TriggerExit events when something starts and stops overlapping it.
The resource Collisions holds the colliders, rebuilt each tick. Its world() answers queries, point, aabb, circle, nearest, and the casts segment, sweep_aabb, and sweep_circle, with collider indices, which Collisions::entity turns into entities.
The resource Navigation finds paths across the tile grid with A*, a search that tries the most promising cells first. A system asks for one with request(entity, PathRequest::new(from, to)), adding with_clearance(half) for the entity's size. The engine searches within a budget of steps each tick, shared by every request, oldest first, and path(entity) gives the result from the next tick on, or later if the budget ran out: the points to walk through, smoothed where the entity can see past a corner. A crowd heading for one place follows a nadir::collision::FlowField instead: the way to it from every cell. The sandbox's guards and pack of enemies use both.
Text and sound
A cooked font is a nadir::render::Font. Font::load_now_in loads it with its atlas, and a system pushes a TextDraw and its text into RenderFrame::texts, drawn in the world among the sprites, or into RenderFrame::ui, drawn on the window after the world, for the interface. Their write formats a text without allocating memory once the list has held as much.
The resource Audio is the game's handle on the mixer, which runs on the audio output's own thread. play plays a Sound on a bus, a group with its own volume: music, sound effects, the interface, or ambience. play_at plays one at a place in the world, panned and faded by where it is from the listener, and play_music crossfades from one Music track to another. Config::volumes sets each bus's starting volume in percent, heard as its square: 50 is −12 dB.
Entities make sound too, through the engine's nadir::sound: an AudioEmitter plays its sound at its entity, following it, while it is within 800 pixels of the listener; the listener is the first entity with an AudioListener, or else the camera; and a MusicArea is a box whose track plays while the listener is in it. A sound played once, as something happens, plays only if it has loaded, so load it with load_now during setup.
use std::error::Error;
use nadir::assets::Scope;
use nadir::prelude::*;
use nadir::render::{Font, TextDraw};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Act {
Jump,
}
impl ActionSet for Act {
const ALL: &'static [Self] = &[Act::Jump];
fn index(self) -> usize {
self as usize
}
fn name(self) -> &'static str {
"jump"
}
fn kind(self) -> ActionKind {
ActionKind::Button
}
}
/// What the game loaded for its interface and its sound.
struct Hud {
font: Handle<Font>,
jump: Handle<Sound>,
jumps: u32,
}
fn main() -> Result<(), Box<dyn Error>> {
let mut map = ActionMap::<Act>::new()?;
map.bind(Act::Jump, 0, Binding::Key(Key::Space))?;
let mut app = App::new(Config {
assets: "cooked".into(),
..Config::default()
})
.add_actions(map)
.add_fixed_system(FixedStage::Gameplay, "jump", jump)
.add_frame_system(FrameStage::Ui, "hud", draw_hud);
// A font and a sound the game needs from its first frame, loaded now.
let hud = {
let mut server = app.world().resource_mut::<AssetServer>();
let mut ctx = FinalizeCtx::new();
let font = Font::load_now_in(
&mut server,
"atlas/fonts/pixel.font.kbj",
Scope::Global,
&mut ctx,
)?;
let jump = server.load_now::<Sound>("audio/sfx/jump.kpcm", &mut ctx)?;
Hud {
font,
jump,
jumps: 0,
}
};
app.world_mut().insert_resource(hud);
app.run()?;
Ok(())
}
/// Plays the jump's sound on Space, once a press.
fn jump(world: &World, _tick: &Tick) {
if world.resource::<ActionState<Act>>().just_pressed(Act::Jump) {
let mut hud = world.resource_mut::<Hud>();
hud.jumps += 1;
let assets = world.resource::<AssetServer>();
world
.resource::<Audio>()
.play(&assets, hud.jump, PlayParams::default());
}
}
/// Writes the count in the top-left corner of the window, over the world.
fn draw_hud(world: &World, _frame: &Frame) {
let hud = world.resource::<Hud>();
let mut frame = world.resource_mut::<RenderFrame>();
frame.ui.write(
TextDraw::new(hud.font, Vec2::new(8.0, 8.0)),
format_args!("Jumps: {}", hud.jumps),
);
}
Game states
The resource StateMachine holds the game's GameState: Boot as it starts, Loading(level), MainMenu, InGame, or Paused. A system queues a change with StateMachine::set, and the engine makes it after the tick, or the frame stages, that queued it, so a tick always runs to its end in the state it started in.
App::add_fixed_system_inandApp::add_frame_system_inadd a system that runs in one kind of state only. Systems added without one run in every state.App::on_exitandApp::on_enteradd systems that run once as a kind of state is left or entered, given theTransition, from where to where.- In
Loading(level), no tick runs and the world is not drawn: the game's frame systems ofStateKind::Loadingdraw its loading screen. The level loads a frame after that screen first shows, and once no asset is still loading, the game goes on toInGameby itself. A level that does not load endsApp::runwithnadir::Error::Level, after telling the player. - In
Paused, ticks still come, so that a pause menu's systems see the input, but the engine moves nothing, fires no trigger, finds no path, and holds the animations still.
use nadir::log::info;
use nadir::prelude::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Act {
Start,
Pause,
}
impl ActionSet for Act {
const ALL: &'static [Self] = &[Act::Start, Act::Pause];
fn index(self) -> usize {
self as usize
}
fn name(self) -> &'static str {
match self {
Act::Start => "start",
Act::Pause => "pause",
}
}
fn kind(self) -> ActionKind {
ActionKind::Button
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut map = ActionMap::<Act>::new()?;
map.bind(Act::Start, 0, Binding::Key(Key::Enter))?;
map.bind(Act::Pause, 0, Binding::Key(Key::Escape))?;
App::new(Config::default())
.insert_resource(StateMachine::new(GameState::MainMenu))
.add_actions(map)
.add_fixed_system_in(StateKind::MainMenu, FixedStage::Gameplay, "menu", menu)
.add_fixed_system_in(StateKind::InGame, FixedStage::Gameplay, "pause", pause)
.add_fixed_system_in(StateKind::Paused, FixedStage::Gameplay, "resume", pause)
.on_enter(StateKind::InGame, "log_start", |_, transition| {
info!("playing, from {:?}", transition.from);
})
.run()?;
Ok(())
}
/// Enter loads the level `field`, behind the loading screen, then plays it.
fn menu(world: &World, _tick: &Tick) {
if world
.resource::<ActionState<Act>>()
.just_pressed(Act::Start)
{
let level = LevelId::new("field");
world
.resource_mut::<StateMachine>()
.set(GameState::Loading(level));
}
}
/// Escape pauses the game, and resumes it.
fn pause(world: &World, _tick: &Tick) {
if world
.resource::<ActionState<Act>>()
.just_pressed(Act::Pause)
{
let mut states = world.resource_mut::<StateMachine>();
let next = if states.is(StateKind::Paused) {
GameState::InGame
} else {
GameState::Paused
};
states.set(next);
}
}
Development builds
cargo run --features dev builds your game with the engine's dev feature, through the feature your Cargo.toml forwards. A development build:
- reads the loose cooked files, not the pack;
- reloads what changes while it runs: cook again, and a texture draws its new pixels behind the handle the game holds, an atlas's clips are replaced by name, a prefab is replaced, the current level is rebuilt with its entities spawned anew, and the engine's shaders are rebuilt. Whatever fails to reload is logged, and what it would replace stays. What the game copied out of an asset itself does not change;
- shows a magenta and black checkerboard in place of a texture that failed to load, instead of nothing;
- counts memory allocations each frame: the resource
FrameAllocs; - and shows the debug tools, windows drawn over the game in the engine's own pixel font, which keep their places across runs:
| Key | Tool |
|---|---|
| F1 | The stats overlay: the frame rate, the frame's and the ticks' times, draw calls, sprites, entities, memory allocated, and sound voices |
| F2 | The inspector: the world's entities and their components, each reflected field editable; components added and removed, an entity despawned or written out as a prefab |
| F3 | The profiler: graphs of the last 300 frames' CPU and GPU times, each frame's timed scopes as a tree, and a button that writes them as a trace file for the Perfetto UI, trace-<time>.json beside the log |
| F4 | Debug drawing: colliders, triggers, the collision grid, the navigation grid, paths, the spatial hash, tile chunks, and the camera |
` (backtick) | The console, over the log, with history and Tab completion. Its commands are help, schedule, spawn, tp, timescale, level, reload, profile dump, log level, and quit, and the game's own |
| F5, F6, F7 | Time: pause, step one tick, and scale the game's time up (with Shift, down) |
A game adds windows of its own with App::add_debug_window, built from the widgets of nadir::debug, and console commands with App::add_console_command. These, and nadir::debug itself, exist only with dev, so put that code behind #[cfg(feature = "dev")], as here:
use nadir::prelude::*;
/// The score, which the debug window shows and the console sets.
#[derive(Default)]
struct Score(u32);
fn main() -> Result<(), nadir::Error> {
let app = App::new(Config::default())
.insert_resource(Score::default())
.add_fixed_system(FixedStage::Gameplay, "score", score);
#[cfg(feature = "dev")]
let app = debug::add(app);
app.run()
}
/// A point a second.
fn score(world: &World, tick: &Tick) {
if tick.index % 60 == 59 {
world.resource_mut::<Score>().0 += 1;
}
}
/// The game's debug tools, in development builds only: `nadir::debug`
/// and the methods that take its windows exist only with `dev`.
#[cfg(feature = "dev")]
mod debug {
use nadir::debug::{Args, ConsoleError, ConsoleOut, Ui};
use nadir::prelude::*;
use super::Score;
pub(super) fn add(app: App) -> App {
let first = Rect::new(Vec2::new(8.0, 8.0), Vec2::new(168.0, 98.0));
app.add_debug_window(Key::F8, "My game", first, score_window)
.add_console_command("score <points>", "sets the score", set_score)
}
/// A window of the game's own, shown and hidden by F8.
fn score_window(world: &World, ui: &mut Ui<'_>) {
ui.label(format_args!("score: {}", world.resource::<Score>().0));
}
/// `score 120`, typed in the console, sets the score to 120.
fn set_score(
world: &World,
args: &Args<'_>,
out: &mut ConsoleOut<'_>,
) -> Result<(), ConsoleError> {
let text = args.get(0).unwrap_or_default();
let points = text
.parse()
.map_err(|_| ConsoleError::Failed(format!("`{text}` is not a whole number")))?;
world.resource_mut::<Score>().0 = points;
out.print(format_args!("the score is {points}"));
Ok(())
}
}
Logs, errors, and crash reports
Log with nadir::log::{error, warn, info, debug, trace}. Records go to the terminal, and App::run also writes them to nadir.log in the game's logs folder, keeping the last three runs' files beside it: on Linux ~/.local/share/<game>, on Windows %LOCALAPPDATA%\<studio>\<game>, and on macOS ~/Library/Logs/<game>.
App::run returns a nadir::Error when the window cannot open, the renderer cannot start, a frame cannot be drawn, or a level cannot load. It logs the error and shows it to the player first: in the terminal on Linux, in a message box on Windows, and in an alert on macOS.
From the start of App::run, every panic, on any thread, writes a crash report into the folder crashes of the game's data folder, on Linux ~/.local/share/<game>/crashes, named after the time, such as 2026-11-19_12-34-56.txt. It holds the panic's message and place, a backtrace, the engine's version, the system, the GPU, and the log's last 200 records. A panic that ends App::run is shown to the player once the window has closed, with where its report is, and the next launch tells the player of the reports written since the last one. A panic hook the game set before App::run still runs, first. A panic during the game's own setup, before App::run, gets no report.
Testing a game
App::update runs one frame, with the window events you give it, and draws nothing: a test drives the game tick by tick, with no window or GPU.
use std::time::Duration;
use nadir::prelude::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Act {
Move,
}
impl ActionSet for Act {
const ALL: &'static [Self] = &[Act::Move];
fn index(self) -> usize {
self as usize
}
fn name(self) -> &'static str {
"move"
}
fn kind(self) -> ActionKind {
ActionKind::Axis2
}
}
fn walk(world: &World, _tick: &Tick) {
let direction = world.resource::<ActionState<Act>>().axis2(Act::Move);
let players = world.read::<Player>();
let mut velocities = world.write::<Velocity>();
for (player, _) in players.iter() {
if let Some(velocity) = velocities.get_mut(player) {
velocity.0 = direction * 120.0;
}
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut map = ActionMap::<Act>::new()?;
let wasd = Binding::KeyComposite2 {
up: Key::W,
down: Key::S,
left: Key::A,
right: Key::D,
};
map.bind(Act::Move, 0, wasd)?;
let mut app = App::new(Config::default())
.add_actions(map)
.add_fixed_system(FixedStage::Gameplay, "walk", walk);
let player = app
.world_mut()
.spawn()
.with(Player)
.with(Transform::at(Vec2::ZERO))
.with(Velocity::default())
.id();
// D goes down, and a frame of one tick runs: 120 pixels a second is 2
// a tick.
let tick = Duration::from_nanos(16_666_667);
let d = nadir::Event::Key {
key: Key::D,
pressed: true,
repeat: false,
};
app.update(tick, &[d]);
let at = app
.world()
.read::<Transform>()
.get(player)
.map(|it| it.position);
assert_eq!(at, Some(Vec2::new(2.0, 0.0)));
Ok(())
}
App::offscreen(size) draws frames with no window, and Offscreen::frame returns each one's pixels. It needs an OpenGL context, which Linux has without a display through EGL. The recordings on the demo page are made this way, on a CI server with no GPU.
Replays check that the game is deterministic, the same input giving the same simulation. nadir::input::InputRecorder records the game's ActionState tick by tick, and App::play_replay plays a recording in place of the live input. App::world_hash hashes the reflected components: after the same ticks of the same replay, from the same start, it is the same however the frames fell, as long as frame systems change no reflected component and spawn or despawn nothing, and tick systems decide nothing by what frames set, by whether an asset has loaded, or by the pointer or the wheel.
Shipping a game
- Cook the assets, and build without
dev:cargo build --release. - Ship the executable with the pack,
game.kpak, in the folderConfig::assetsnames. A release build needs nothing else of the cooked folder. The sandbox looks for itsassetsfolder beside its executable first, which is what its download does. - Ship the engine's
LICENSEandNOTICEwith it: Nadir is under the Apache License 2.0, which asks that copies of the engine carry them.
For now a game draws only on Linux. Packages, installers, and signing for all three systems are roadmap tasks M11.1 and M11.2, not built yet.
Where to read more
- The API reference, on docs.rs, with the
devfeature's items. - The engine crate's README, the reference this guide follows.
- The sandbox, the full example, which every feature is built for: the field, its enemies, its sound, and the stress scenes on the demo page.
- The cook's README: every source format, and the cache.
- The architecture: the crates, the main loop, and its threads; and each subsystem's design.
- The roadmap, every task with its acceptance criteria, and the decisions behind the design.