Skip to main content

Crate nadir

Crate nadir 

Source
Expand description

The Nadir game engine: App and its main loop, the engine’s components and systems, and the subsystems a game uses.

Nadir is a 2D engine for top-down games on Windows, macOS and Linux, written in Rust with no third-party crates. This crate is its facade, the one a game depends on: its package is nadir_engine, and code names it nadir. It re-exports the subsystems as modules, and prelude holds what most games use. A game needs only this crate:

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()
}

This is version 0.4, and the API will change before 1.0. The engine draws and plays sound on Linux (X11, ALSA). On Windows and macOS a game runs, but its window stays empty until roadmap tasks M2.6 and M2.7, and it plays no sound until M6.4 and M6.5. Text is drawn in the world (nadir::render::Font, RenderFrame::texts), and on the window with the UI’s sprites (RenderFrame::ui); development builds show a debug UI of the game’s own windows and the engine’s debug tools; gamepads and saves are not built yet. The README is a guide to how the parts fit together, with a game that walks a hero about a tile map.

§The app and the main loop

App holds the game’s Config, its world and its systems. A game adds resources, actions and systems with its builder methods, sets its world up through App::world_mut, and calls App::run, which opens the log file, the window and the audio output and runs the main loop until the window is closed. Each frame, the loop:

  1. hands the window’s Events to Input;
  2. runs the ticks that are due, TICK_HZ a second however fast the frames come: each latches the game’s actions, then runs the tick stages;
  3. sets TickStats, and runs the frame stages, which fill the RenderFrame;
  4. draws it, and makes the assets that the workers have loaded.

A frame counts for at most 250 ms: after a stall the simulation falls behind real time rather than running a burst of ticks.

§The world, systems and stages

The game’s state is a World of entities, components and resources, from ecs. Systems are plain functions: a FixedSystem, fn(&World, &Tick), runs in a FixedStage of each tick, added with App::add_fixed_system; a FrameSystem, fn(&World, &Frame), in a FrameStage of each frame, added with App::add_frame_system. They run in stage order, then in the order they were added, after the engine’s own, which App lists with the resources the engine adds.

§The engine’s components

ComponentWhat it is
TransformWhere an entity is, in world pixels, +Y down
VelocityHow fast it moves, in pixels a second: the engine moves it each tick
ColliderWhat it collides with, solid or a trigger
SpriteWhat it looks like, drawn at its Transform
AnimatorPlays a Clip on its Sprite
FacingWhich way it faces: facing left mirrors its Sprite
ParentPuts it at another entity’s position, plus an offset
PlayerA tag for the entity the player controls
SaveIdIts id in saves, which come with roadmap M9.4
PrevTransformWhere it was at the start of the last tick, for drawing between ticks: the engine keeps it
AudioListenerWhere the game hears from, in place of the camera
AudioEmitterA sound that plays at it, and follows it
MusicAreaA box whose music plays while the listener is in it

Transform, Velocity, Player, SaveId, Facing, Sprite, Collider and Animator are reflected, so prefabs and levels can give them; Parent, AudioListener, AudioEmitter and MusicArea are not yet (M9.4 brings Parent), and PrevTransform is the engine’s own, and is never in data. A Sprite is written with its texture’s path, and a prefab may name a frame of a cooked atlas instead, {"atlas": "atlas/sprites.kbj", "sprite": "sprites/hero", "frame": 0}; a Collider’s layers by the names App::collision_layers gives them, ["World", "People"]; an Animator as its clip’s name in the Clips. The world hash leaves out what nadir::animate writes: a sprite’s texture, uv, size, pivot and flip.x (ADR-0038).

§Prefabs

A prefab is a set of component values, cooked from assets/data/prefabs/<name>.jsonc to data/prefabs/<name>.kbj, that may extend another. The PrefabLibrary resource loads prefabs and their bases, and spawns entities of them; loading_context gives it a reflect context with what the engine’s components need, the asset server, the clips and the collision layers, and reflect_context one for writing them, as a hash or a save does.

§Levels

The cook makes a level file, levels/<name>.klvl, of each level of an LDtk project. App::load_level (or load_level on a world) loads one in place of the last: its prefabs are read and checked before it returns, its assets load in Scope::Level, its tall tiles and entities spawn, its tile layers go into the TileLayers and its grid into the Collisions, and the engine draws its tile layers each frame, its background the clear colour. CurrentLevel says what it made, and the next load removes it whole; a LevelError says why one did not load (ADR-0038).

§Collision

Collisions is the resource of the colliders, which the engine rebuilds and moves each tick: systems query its world, a CollisionWorld, and turn the collider indices it gives into entities with Collisions::entity. Its tile grid, Collisions::set_grid, is how tiles collide. TriggerEnter and TriggerExit are the events of colliders that start and stop overlapping a trigger. collision has the shapes, the layers and the queries.

§Animation

A Clip is a list of ClipFrames, each a region of a texture shown for a time, maybe with its own Placement. It loops or plays once (Playback). The resource Clips keeps the clips by handle and name, and Clips::add_atlas adds a cooked atlas’s, from Aseprite’s tags. An Animator plays one on its entity’s Sprite, and sends AnimationFinished when a clip that plays once ends. ClipError says why a clip could not be made or added.

§Sound

The resource Audio, from audio, is the game’s handle on the mixer: it plays a Sound, cooked to a .kpcm or .qoa file, on a Bus, at a position in the world or not, and crossfades from one Music track to another. Config::volumes sets each bus’s volume as the game starts (Volumes). App::run opens the audio output with it, while App::update and App::offscreen play nothing, and App::take_mixer hands a test the mixer to render itself.

The engine’s nadir::sound plays the world’s sound each frame. An AudioEmitter plays its sound at its entity, panned and fading by where it is from the listener: the first AudioListener, or else the camera. When the listener comes into a MusicArea, the music crossfades to its track, and AudioState says whose track was sent last. An emitter and an area wait for what they play to load; a sound played once as something happens, a footstep say, is lost if it has not loaded, so load it first with AssetServer::load_now.

§Input, drawing and assets

§Hot reload

With the dev feature, App::run reloads the files that change while the game runs, such as those cargo xtask cook --watch cooks again, and nadir-render’s shaders, from its shaders/ folder (SHADER_DIR). Watchers look at the files’ times of change every 250 ms, and an edit is drawn a frame or two after it is seen; a shader edited before the loop starts is seen at its next save. The handles the game holds stay good (ADR-0043):

  • a texture’s handle draws its new texels;
  • an atlas’s clips are replaced by name under their handles, so its animators play the new frames on from their time;
  • a prefab is replaced in the PrefabLibrary under its name;
  • the current level is made again from its files, behind the handles of its assets, tile layers and clips, once its file, an atlas or a prefab changed; its entities are spawned anew;
  • a program is rebuilt from its shader files.

A file that fails to load, a level that cannot be made again, or shaders that do not compile or fit their program are logged, and what they would replace stays. Each reload is logged with its time. What the game copied out of an asset, such as an atlas’s regions into its own sprites, and the entities it spawned of prefabs itself, do not change. App::offscreen and App::update never reload, so recordings stay the same, and builds without dev hold none of the reload.

§The debug UI

With the dev feature, a game adds windows of its own to a debug UI with App::add_debug_window, each shown and hidden by a key, and fills them each frame with the widgets of nadir::debug, the nadir-debug crate: labels, buttons, checkboxes, sliders, text fields, lists, trees, plots. They are drawn over the game’s UI in the engine’s own pixel font; they drag, collapse, resize and scroll; while one has the pointer, or one of their text fields the keys, the game’s actions do not see them; and App::run keeps their places in debug_ui.jsonc in the game’s settings folder. The resource WindowSize is the window’s size. The engine’s own windows are the stats overlay (F1), the inspector (F2), the profiler (F3), the debug drawing (F4), whose overlays draw into the world, and the console (the backtick), which runs the engine’s commands and those a game adds with App::add_console_command. F5 pauses the game’s time and runs it again, F6 steps it a tick, and F7 and Shift+F7 scale it, a label at the top-right saying so.

use nadir::prelude::*;

/// A note the developer types in.
#[derive(Default)]
struct Note(String);

let app = App::new(Config::default())
    .insert_resource(Note::default())
    .add_debug_window(
        Key::F8,
        "Notes",
        Rect::new(Vec2::new(16.0, 16.0), Vec2::new(216.0, 116.0)),
        |world, ui| {
            ui.text_input("Note", &mut world.resource_mut::<Note>().0);
            let ticks = world.resource::<TickStats>().ticks;
            ui.label(format_args!("{ticks} ticks this frame"));
        },
    );

§Replays and determinism

App::play_replay plays a recording of the game’s actions, made with an InputRecorder, in place of the live input, and the resource Replay says how far it got. world_hash and App::world_hash hash the reflected components, so that a test can check that a replay reaches the same world, tick after tick.

§The modules

ModuleCrateWhat it holds
assetsnadir-assetsHandles, the asset server, sources and scopes
audionadir-audioSounds, music, the mixer, its buses and voices
collisionnadir-collisionShapes, layers, the tile grid, move-and-slide, triggers, queries
ecsnadir-ecsThe world, components, resources, events, commands, the schedule
inputnadir-inputActions, bindings, their state, replays
rendernadir-renderThe frame to draw, sprites, tiles, the camera, textures, atlases
scenenadir-sceneReflection: the macros that define reflected types, and the type registry
lognadir-coreThe log macros, error! to trace!
clinadir-coreA small parser of command lines

Vec2, IVec2, UVec2, Rect, Color, Key, MouseButton, Pcg32 and the time types Tick, Frame and Stopwatch are in the prelude; the rest of nadir-core, such as its matrices and linear colours, is a dependency of its own. The OS layer, the GPU layer and the codecs are the engine’s own, and a game does not use them, except for the window’s Events, which App::update takes.

§Examples

A frame of one tick moves an entity by its velocity, with no window:

use std::time::Duration;

use nadir::prelude::*;

let mut app = App::new(Config::default());
let ball = app
    .world_mut()
    .spawn()
    .with(Transform::at(Vec2::ZERO))
    .with(Velocity(Vec2::new(60.0, 0.0)))
    .id();
// 1/60 of a second, rounded up to the nanosecond: one tick.
app.update(Duration::from_nanos(16_666_667), &[]);
let at = app.world().read::<Transform>().get(ball).map(|it| it.position);
assert_eq!(at, Some(Vec2::new(1.0, 0.0)));

A trigger counts who steps on it, in a tick system after the engine’s nadir::triggers:

use std::time::Duration;

use nadir::prelude::*;

/// How many times something stepped on the plate.
#[derive(Default)]
struct Steps(usize);

fn count_steps(world: &World, _tick: &Tick) {
    let entered = world.resource::<Events<TriggerEnter>>().tick_events().len();
    world.resource_mut::<Steps>().0 += entered;
}

let mut app = App::new(Config::default())
    .insert_resource(Steps::default())
    .add_fixed_system(FixedStage::PostMovement, "count_steps", count_steps);
let world = app.world_mut();
// A plate 8 pixels across at x = 20.
world
    .spawn()
    .with(Transform::at(Vec2::new(20.0, 0.0)))
    .with(Collider::trigger(Shape::Aabb { half: Vec2::splat(4.0) }));
// Someone who walks right across it, at 2 pixels a tick.
world
    .spawn()
    .with(Transform::at(Vec2::ZERO))
    .with(Velocity(Vec2::new(120.0, 0.0)))
    .with(Collider::solid(Shape::Aabb { half: Vec2::splat(2.0) }));
for _ in 0..30 {
    app.update(Duration::from_nanos(16_666_667), &[]);
}
assert_eq!(app.world().resource::<Steps>().0, 1);

An animator shows the frame of its clip that the simulated time has reached. The texture need not have loaded: the clip writes its regions into the sprite all the same.

use std::time::Duration;

use nadir::prelude::*;

let mut app = App::new(Config::default());
let world = app.world_mut();
let sheet = world.resource_mut::<AssetServer>().load::<Texture>("hero.qoi");
// The sheet's left and right halves, 100 ms each, over and over.
let half = |x: f32| {
    let uv = Rect::new(Vec2::new(x, 0.0), Vec2::new(x + 0.5, 1.0));
    ClipFrame::new(sheet, uv, Duration::from_millis(100))
};
let clip = Clip::new(vec![half(0.0), half(0.5)], Playback::Loop);
let walk = world.resource_mut::<Clips>().add(clip);
let hero = world
    .spawn()
    .with(Transform::at(Vec2::ZERO))
    .with(Sprite::new(sheet, Vec2::new(16.0, 16.0)))
    .with(Animator::new(walk))
    .id();
// 9 ticks, 150 ms: the second frame shows.
for _ in 0..9 {
    app.update(Duration::from_nanos(16_666_667), &[]);
}
let uv = app.world().read::<Sprite>().get(hero).map(|it| it.uv.min.x);
assert_eq!(uv, Some(0.5));

§Using it well

  • Threads. The world, the systems, the window and the GPU all live on the thread that runs the app, and systems run one at a time. The asset server reads and decodes files on 1 to 4 worker threads of its own, and the mixer runs on the audio output’s thread, which Audio’s commands reach through a queue. Call App::run on the main thread: macOS opens windows only there.
  • Borrows. Storages and resources are borrowed at run time. A system that borrows one mutably while it is borrowed panics, with the system’s name and the type.
  • Determinism. Ticks have a fixed length, and the clock counts frames’ lengths exactly, so the same frames give the same ticks. Keep gameplay in tick systems. What frames set, such as an Animator’s time, whether an asset has loaded, and the pointer and the wheel differ from run to run: world_hash gives the conditions under which a replay reproduces the world.
  • Assets. Loads finish only in drawn frames, so App::update finishes none, and a tick system must not depend on whether an asset has loaded. Before the window opens there is no GPU device, so only assets that need none, such as an Atlas, can be made then, with AssetServer::load_now.
  • Allocation. The engine’s own systems and drawing do not allocate in a steady frame: its tests count a frame of 10,000 animated sprites and a tile layer with the dev feature’s counter. Systems are function pointers; keep their buffers in resources and reuse them.
  • Errors and logs. App::run logs an Error and shows it to the player before it returns it: on standard error on Linux, and in a message box on Windows or an alert on macOS. The log macros write to standard error, and App::run also writes the log to nadir.log in the game’s logs folder, named by Config::studio and Config::game.
  • Platforms. On Linux the engine needs X11, or XWayland, and OpenGL 3.3, which it loads at run time, and plays sound through ALSA’s libasound.so.2, loaded at run time too: without it the game is silent. On Windows and macOS it has no OpenGL context yet: App::run logs that and runs the game without drawing, and so without reloading, and App::offscreen fails; nor has it audio output, so the game is silent there.

§Features

  • dev: development builds. The assets are the loose files of Config::assets, not the cook’s pack there, which builds without dev read when it is there (ADR-0041). A texture that failed to load shows a placeholder rather than nothing, and the global allocator counts allocations: the resource FrameAllocs holds the last frame’s, and thread_alloc_counts and process_alloc_counts give the counts so far, as AllocCounts. No other crate in the program may then declare a #[global_allocator]. App::run reloads what changes while it runs (“Hot reload”, above), and the game’s debug windows show (“The debug UI”, above), with nadir::debug, App::add_debug_window, DebugWindow and WindowSize. Turn it on from a feature of the game, never from a normal dependency, so that release builds leave it out.

Re-exports§

pub use nadir_debug as debug;
pub use nadir_assets as assets;
pub use nadir_audio as audio;
pub use nadir_collision as collision;
pub use nadir_ecs as ecs;
pub use nadir_input as input;
pub use nadir_render as render;
pub use nadir_scene as scene;

Modules§

cli
A minimal command-line argument parser for xtask, the cook tool and the game binary.
log
Logging: the [error!], [warn!], [info!], [debug!] and [trace!] macros, a level filter, and three sinks.
prelude
What most games use, for one use nadir::prelude::*.

Structs§

AllocCounts
Counts of heap use, on one thread or in the whole process.
AnimationFinished
A clip that plays once reached its end in this frame: nadir::animate sends it, first in the frame stage Animate.
Animator
Plays a Clip on its entity’s Sprite.
App
A game: its configuration, its World of entities and resources, and its systems in stages. App::run opens the log file and the window, and runs the main loop; App::update runs one frame without them.
AudioEmitter
A sound that plays at its entity, and follows it as it moves: the system nadir::sound starts it once its sound has loaded, while the entity has a Transform and is within AudioConfig::max_dist of the listener (AudioListener), 800 pixels, where it can be heard. It stops, fading out over 100 ms, when the entity is despawned or loses the emitter or its Transform, or is more than 64 pixels past that distance; back within it, it starts again. A sound that does not loop plays once each time it starts.
AudioListener
Where the game hears from: the first entity with one and a Transform, where it is drawn, between ticks part of the way from its PrevTransform. With none, the camera’s position (RenderFrame::camera) is.
AudioState
What the engine’s nadir::sound keeps of the game’s sound from frame to frame: a resource of every App, for the game to read.
Clip
An animation: frames shown one after another, looping or once.
ClipFrame
One frame of a Clip: a region of a texture, shown for duration, and maybe the size and pivot of its quad.
Clips
The clips, by handle, and by name for those that have one: a resource that the engine adds. An Animator names its clip by the handle that Clips::add, Clips::add_named or Clips::add_atlas gives.
Collider
What an entity collides with: a nadir_collision::Collider, offset from its Transform. The engine builds the Collisions world from these each tick.
CollisionLayers
The names of the game’s collision layers: the layer of bit n of a LayerMask is named by the n-th, so that prefabs and levels write ["World", "People"] for a collider’s layers. A resource of every App, with no names until App::collision_layers gives them.
Collisions
The colliders of the entities that have a Collider and a Transform, in a CollisionWorld: a resource that the engine rebuilds each tick, in the system nadir::movement.
Config
What a game asks of the engine.
CurrentLevel
The level the world holds, if any: what load_level made of it. A resource of every App, empty until a level loads.
FrameAllocs
What the main thread allocated in the last frame: a resource of development builds (feature dev).
MusicArea
A box, its entity’s position ± half in pixels, whose music plays while the listener (AudioListener) is in it: the system nadir::sound crossfades to music over crossfade_ms when the listener comes into it. Where areas overlap, the one playing stays while the listener is in it, and otherwise the first of them that holds it plays. Outside every area, the music plays on; coming back into the area of the track that plays, it goes on as it is (ADR-0046).
Offscreen
A game drawn offscreen, a frame at a time, with no window. Made by App::offscreen.
Parent
Puts an entity at another’s position plus offset: the system nadir::parent_offsets writes its Transform after each tick’s movement, and frames draw it at its parent’s drawn position plus the offset.
Placement
The size and pivot of a frame’s quad, as Sprite::size and Sprite::pivot hold them.
Player
The entity the player controls: a tag.
PrevTransform
Where an entity was at the start of the last tick: a frame between two ticks draws it part of the way from there to its Transform, by the frame’s alpha.
SaveId
An entity’s id in saves, which stays the same from one run to the next, unlike its Entity. Saves (roadmap M9.4) store only entities that have one.
Sprite
What an entity looks like: a sprite drawn at its Transform, between ticks part of the way from its PrevTransform.
TickStats
How many ticks the frame ran, and how long they took: a resource.
Transform
Where an entity is, in world pixels (+Y down), as the last tick left it. For a sprite, it is where its pivot is: its feet.
TriggerEnter
A collider began to overlap a trigger, in this tick. The system nadir::triggers sends it, in the tick stage PostMovement.
TriggerExit
A collider stopped overlapping a trigger, in this tick, or one of the two left: lost its collider or its Transform, or was despawned. The system nadir::triggers sends it, in the tick stage PostMovement. Either entity may be dead by then: check with World::is_alive.
Velocity
How fast an entity moves, in pixels a second. The system nadir::movement moves it by velocity × dt each tick: with a Collider, it slides along what it meets.
Volumes
The volume of each of the mixer’s buses, in percent of full: 0 to 100, and more counts as 100. A percent is heard as its square (Volumes::gain), so 50 is −12 dB, nearer half as loud than the −6 dB of half the gain.
WindowSize
The size of the inside of the window, in physical pixels: what the frame is drawn into, and what the UI’s views (RenderFrame::ui) cover. A resource of development builds (feature dev).

Enums§

ClipError
Why a clip could not be made or added.
Error
Errors that end App::run.
Event
Something that happened to the window or to an input device.
Facing
Which way an entity faces. Art is drawn facing right: the system nadir::animate mirrors the Sprite of an entity that faces left (flip.x), and unmirrors it whichever other way it faces. Only the entity’s own Sprite: a Parent’s children need their own.
LevelError
Why a level could not be loaded. The previous level is gone then, and nothing of the new one is in the world but the prefabs it read, which the PrefabLibrary keeps.
Playback
What a Clip does at its end.
Replay
How the replay that App::play_replay plays is going: a resource that it adds.

Constants§

TICK_HZ
How many times a second the simulation steps.

Functions§

load_level
Loads the level name into world, the world of an App, in place of the one it holds (ADR-0038):
loading_context
Runs f with a ReflectContext for source that reads the engine’s components too: as reflect_context, with the AssetServer to load each handle read in scope (ReflectContext::loading). For spawning prefabs and a level’s entities (PrefabLibrary).
process_alloc_counts
The heap use of every thread since the process started.
reflect_context
Runs f with a ReflectContext for source that has what the engine’s components need to be written: the AssetServer, the Clips and the CollisionLayers of world, each if world has it. For writing values, such as a save’s, or, with ReflectContext::hashing, a hash’s, as world_hash does; it never loads, so it cannot read a handle.
thread_alloc_counts
The heap use of this thread since it started.
unload_level
Removes the level world holds, if any, and returns whether there was one: despawns the entities it spawned, takes its tile layers out of TileLayers, lets go of its atlases’ clips in Clips (Clips::release_atlas), empties the grid it set, puts back the clear colour it replaced, and unloads Scope::Level. The prefabs it read stay in the PrefabLibrary.
world_hash
A hash of every reflected component of world, as TypeRegistry::hash_world takes it, with the context the engine gives it. Determinism tests compare it run against run, tick after tick.

Type Aliases§

ConsoleCommand
A command of the game’s in the debug console: a function of the world, the arguments typed, checked against the command’s usage, and where to print, added with App::add_console_command. An error it returns (ConsoleError::Failed with why) is printed in red.
DebugWindow
A window of the debug UI, which fills it with widgets each frame it is open: a function of the world and the window’s Ui, added with App::add_debug_window.