pub struct App { /* private fields */ }Expand description
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.
Systems are functions of the world and the tick, or the frame, added to
a stage with a name. They run in stage order, then in the order they
were added (docs/subsystems/ecs.md). The engine adds its own first in
their stages:
nadir::snapshot(tickInput): copies eachTransforminto itsPrevTransform, and gives one to every entity with aSpriteand to the root of every drawn child;nadir::movement(tickMovement): rebuildsCollisionsand moves every entity with aVelocity, sliding the ones with aCollider;nadir::parent_offsets(tickPostMovement): puts each entity with aParentwhere its parent is, plus its offset;nadir::triggers(tickPostMovement): sendsTriggerEnterandTriggerExit;nadir::animate(frameAnimate): advances everyAnimatorand writes its frame into itsSprite, sendsAnimationFinished, mirrors the Sprite of each entity that facesFacing::Left, and unmirrors the rest with aFacing;nadir::sound(frameExtract): puts the listener at theAudioListener, or else the camera, plays eachAudioEmitterat its entity, sends the track of theMusicAreathe listener is in, and callsAudio::update;nadir::extract_sprites(frameExtract): draws everySpriteinto theRenderFrame, between the last two ticks;nadir::extract_level(frameExtract): draws the tile layers of theCurrentLevel, with its background as the clear colour.
So a game sets velocities in Gameplay, and reacts to the moves after
the engine’s, in Movement or PostMovement. It sets Facing and
plays clips in ticks too, and reacts to finished clips in frames.
The engine’s resources:
Input, which latches the keys and buttons into the actions, and holds the pointer and the wheel- with
App::add_actions, the game’sActionMapand itsActionState, latched once a tick before the tick stages AssetServer, loading fromConfig::assetsRenderFrame, emptied before the frame stages, which fill it; the loop then draws it. Itstime, which animated tiles show and animators follow, is how long the simulation has run, ticks andalpha.TileLayers, the game’s tile layers, which the frame’stile_layersname and the loop draws fromFrameStats, what the last frame drewTickStats, how long this frame’s ticks tookCollisions, the collidersClips, the clips that animators playTypeRegistry, the reflected component typesPrefabLibrary, the prefabs the game loads, none until it loads themCollisionLayers, the names of the game’s collision layers, none untilApp::collision_layersgives themCurrentLevel, the levelApp::load_levelloaded, none until it loads oneAudio, the game’s handle on the mixer, whose buses start atConfig::volumes, andAudioState, whatnadir::soundplays- with
App::play_replay,Replay, how far the replay got - the events
TriggerEnter,TriggerExitandAnimationFinished - with the
devfeature,FrameAllocs, what the last frame allocated, andWindowSize, the size of the window the frame is drawn at
use nadir::prelude::*;
struct Spin(f32);
fn simulate(world: &World, tick: &Tick) {
// 60 times a second: move things by `tick.dt`.
world.resource_mut::<Spin>().0 += tick.dt;
}
fn main() -> Result<(), nadir::Error> {
App::new(Config {
title: "My game".into(),
..Config::default()
})
.insert_resource(Spin(0.0))
.add_fixed_system(FixedStage::Gameplay, "simulate", simulate)
.add_frame_system(FrameStage::Ui, "show", |world, frame| {
// Once for each frame, after its ticks.
let _ = (world.resource::<Spin>().0, frame.alpha);
})
.run()
}Implementations§
Source§impl App
impl App
Sourcepub fn new(config: Config) -> Self
pub fn new(config: Config) -> Self
An app with the engine’s resources, components and systems, and no entities.
Its AssetServer loads from Config::assets. With the dev
feature, it reads the loose files there, watches each file loaded
from then on for the hot reload of App::run, and a failed asset
shows its placeholder. Without it, it reads the cook’s pack there,
game.kpak, when there is one, and the loose files otherwise; a
pack that does not open is logged, and every load then fails with
its error (ADR-0041); and a failed asset shows nothing.
Of the engine’s components, Transform, Velocity, Player,
SaveId, Facing, Sprite, Collider and Animator are
reflected, so that prefabs and levels can give them (ADR-0038).
Parent is not yet (roadmap M9.4), and PrevTransform is the
engine’s own. Its resources include a PrefabLibrary with no
prefabs, and CollisionLayers with no names
(App::collision_layers).
It makes the mixer, of AudioConfig::default, and sets each bus
to Config::volumes. AudioListener, AudioEmitter and
MusicArea are not reflected: a game gives them in code.
Sourcepub fn take_mixer(&mut self) -> Option<Mixer>
pub fn take_mixer(&mut self) -> Option<Mixer>
Takes the mixer, for a test or a tool that renders it itself
(Mixer::render): App::run then opens no audio output. Take it
before the first App::update, which drops a mixer the app still
holds: None then, and once it is taken.
Sourcepub fn insert_resource<R: 'static>(self, resource: R) -> Self
pub fn insert_resource<R: 'static>(self, resource: R) -> Self
Adds resource, or replaces the one of its type.
Sourcepub fn add_event<T: Clone + 'static>(self) -> Self
pub fn add_event<T: Clone + 'static>(self) -> Self
Adds the event type T: the resource Events<T>, which the
schedule clears (World::add_event).
Sourcepub fn register_component<T: Component + FromValue>(self) -> Self
pub fn register_component<T: Component + FromValue>(self) -> Self
Adds the reflected component type T to the world and to the
TypeRegistry, under its reflected name. A component that is not
reflected is added with app.world_mut().register::<T>().
§Panics
If another type has the same reflected name.
Sourcepub fn load_level(&mut self, name: &str) -> Result<(), LevelError>
pub fn load_level(&mut self, name: &str) -> Result<(), LevelError>
Loads the level name, levels/<name>.klvl, in place of the one the
world holds, as load_level says: its prefabs
and tile sets are read before this returns, its entities spawned,
and its tile layers drawn from the next frame.
§Errors
A LevelError if it cannot be loaded. The previous level is gone
then, and nothing of the new one is in the world.
Sourcepub fn collision_layers(self, names: &[&str]) -> Self
pub fn collision_layers(self, names: &[&str]) -> Self
Names the game’s collision layers: bit 0 of a
LayerMask the first, bit 1 the next,
and so on, as prefabs and levels write a collider’s layers
(["World", "People"]). It replaces the CollisionLayers
resource, which has no names until then.
§Panics
If there are more than 32 names, one is empty, or two are the same.
Sourcepub fn add_actions<A: ActionSet>(self, map: ActionMap<A>) -> Self
pub fn add_actions<A: ActionSet>(self, map: ActionMap<A>) -> Self
Adds the game’s actions, with their bindings: the resources
ActionMap<A> and ActionState<A>, whose state is latched from
the input once a tick, before the tick stages.
Read edges (just_pressed) in fixed systems. A frame system sees
only the last tick’s: it misses those of a frame’s earlier ticks, and
sees one again when a frame has no tick.
§Panics
An app has one action set: adding another type panics. Adding the
same type again replaces its bindings. Adding actions while a replay
plays panics: App::play_replay comes after add_actions.
Sourcepub fn play_replay<A: ActionSet>(self, replay: InputPlayer<'static, A>) -> Self
pub fn play_replay<A: ActionSet>(self, replay: InputPlayer<'static, A>) -> Self
Plays replay into the game’s actions in place of the live input:
each tick from the next on takes its ActionState<A> from the
replay’s next tick. It adds the resource Replay, which says how
far it got. The replay is read a tick ahead, so it is
Replay::Ended as soon as its last tick has run, and the ticks
after that are latched live.
While it plays, the live input still reaches Input, but not the
actions. The pointer and the wheel stay live: replays do not hold
them, so a fixed system that reads them does not replay. When the
replay ends, the first live tick’s edges are those of the live keys
alone: an action held in the replay’s last tick is not just
released, and a key held all along is held but not just pressed.
A damaged tick ends the replay as Replay::Failed, after an error
in the log; the ticks before it play. A replay with no ticks is
Replay::Ended at once. Playing another replay replaces this one.
§Panics
If the game’s action set, added with App::add_actions, is not
A.
Sourcepub fn world_hash(&self) -> u64
pub fn world_hash(&self) -> u64
The world_hash of the world: the same after
the same ticks of the same replay, from the same start, whatever the
frames were, under the conditions that function gives.
Sourcepub fn add_fixed_system(
self,
stage: FixedStage,
name: &'static str,
system: FixedSystem,
) -> Self
pub fn add_fixed_system( self, stage: FixedStage, name: &'static str, system: FixedSystem, ) -> Self
Adds a system to a stage of each simulation tick, after the stage’s
others. Ticks come TICK_HZ times a second, however fast frames
come.
Sourcepub fn add_frame_system(
self,
stage: FrameStage,
name: &'static str,
system: FrameSystem,
) -> Self
pub fn add_frame_system( self, stage: FrameStage, name: &'static str, system: FrameSystem, ) -> Self
Adds a system to a stage of each frame, after the stage’s others. A frame’s stages run after its ticks.
Sourcepub fn add_debug_window(
self,
toggle: Key,
title: &'static str,
first: Rect,
window: DebugWindow,
) -> Self
pub fn add_debug_window( self, toggle: Key, title: &'static str, first: Rect, window: DebugWindow, ) -> Self
Adds a window to the debug UI, in development builds (feature
dev): toggle shows and hides it, and it starts hidden. While it
shows, window fills it with widgets each frame, after the frame
stages, through the Ui of
nadir::debug.
- It shows at
first, in the debug UI’s units, the first time;App::runkeeps its place, its size and whether it is collapsed from then on, across runs, indebug_ui.jsoncin the game’s settings folder, by its name: its title, or the explicit ID after##in"Title##id". - It is drawn after the game’s UI, over it, in the engine’s own font, at the window’s scale factor rounded to a whole number (until the settings file’s UI scale, roadmap M9.3).
- While the pointer is over a debug window, or a debug widget is held,
the game’s actions do not see the mouse’s buttons or the wheel;
while one of its text fields has the keyboard, they do not see the
keys (
Input::set_capture, which the debug UI then sets; a replay still plays). A press goes where the pointer was when it went down, by the windows drawn in the frame before. toggleworks whenever it is pressed, a text field’s keyboard or not, and the game’s actions see it too, as they see any key no debug field has. One key may toggle several windows.windowgets the world to read, or to change through its resources and storages, as a frame system does.- The engine has five windows of its own, hidden at start: the
stats overlay on F1, named
nadir::stats; the inspector on F2,nadir::inspector, which outlines the entity it shows and writes its prefabs into the folderprefabsbeside the log file; the profiler on F3,nadir::profiler, which writes its traces beside the log file; the debug drawing on F4,nadir::debug_draw, whose ticked overlays draw into the world while it is open; and the console on the backtick,nadir::console(App::add_console_command;docs/subsystems/debug-tools.md). A game’s window on one of those keys shows and hides with it. - F5, F6 and F7 control the game’s time: pause, step a tick, scale (with Shift, down). A game’s window on one of them still shows and hides, and the time changes too.
Only App::run reads and writes debug_ui.jsonc:
App::update and App::offscreen start each window at first.
Sourcepub fn add_console_command(
self,
usage: &str,
help: &str,
command: ConsoleCommand,
) -> Self
pub fn add_console_command( self, usage: &str, help: &str, command: ConsoleCommand, ) -> Self
Adds a command to the debug console, under usage, whose first word
is its name, followed by its arguments, with help, a line of what
it does: in development builds only (feature dev).
- The console is a window of the engine’s on the backtick (
`,Key::Grave), namednadir::console: a command line, with history and Tab completion, under the log’s records and what the commands print. Its commands arehelpand the engine’s (schedule,spawn,tp,timescale,level,reload,profile dump,log level,quit;docs/subsystems/debug-tools.md). - The usage names each argument: a word to type as it is, a value
(
<x>, or[x]if it may be left out), or a choice (<on|off>). A line that does not fit it is refused with why, andcommandis not called. commandgets the world, as a debug window does, the arguments, and where to print. Commands it queues apply after the next tick or the next frame’s stages.- A command of a name already there replaces it, the engine’s too. A
usage that starts with no name (a placeholder, a quote,
help) is logged as an error, and nothing is added.
Sourcepub fn world_mut(&mut self) -> &mut World
pub fn world_mut(&mut self) -> &mut World
The world, for setup: spawning entities, loading assets, registering components that are not reflected.
Sourcepub fn schedule(&self) -> &Schedule
pub fn schedule(&self) -> &Schedule
The systems, in stages: Schedule::describe lists them in the
order they run.
Sourcepub fn update(&mut self, elapsed: Duration, events: &[Event])
pub fn update(&mut self, elapsed: Duration, events: &[Event])
Runs one frame that comes elapsed after the last, with the events
that came before it, without drawing it:
- collects the profile scopes recorded since the last frame
started, with the
profilefeature ofnadir-core, so that they do not pile up; with thedevfeature, which turns it on, it gives them to the profiler with the last frame’s timing; - feeds the events to
Input, holding back from the game’s actions, with thedevfeature, what the debug UI has; - runs the ticks that are due, of a frame
elapsedlong, or with thedevfeature as the time controls leave the game’s time (none while paused but a tick for each F6,elapsedtimes the scale of F7 or the console’stimescale): for each, latches the actions, or takes them from the replay thatApp::play_replayplays, and runs the tick stages, which apply their commands; - sets
TickStats; - empties the
RenderFrame, sets itstimeto how long the simulation has run, and runs the frame stages; - with the
devfeature, fills the open debug windows into theRenderFrame’s UI, after the game’s (App::add_debug_window), and then loads the level the console’slevelasked for, if it did.
The engine’s scopes are nadir::tick (each tick),
nadir::frame_stages and nadir::debug_ui, beside each system’s
(docs/subsystems/ecs.md); App::run adds nadir::render,
nadir::present and nadir::finish_loads for the drawing.
App::run calls it once a frame, then draws the RenderFrame.
Tests, benchmarks and headless runs call it themselves. A frame of
Duration::from_nanos(16_666_667) runs one tick: the third of a
nanosecond it holds past a tick adds up to another only after 50
million frames. Asset loads finish only in a drawn frame, so a
headless run finishes none: tick systems must not depend on whether
an asset has loaded.
It plays no sound. Its first call drops the mixer, unless
App::take_mixer took it, and Audio then
does nothing: so tests, benchmarks, headless runs and
App::offscreen are silent, and App::run after it opens no
audio output.
Sourcepub fn run(self) -> Result<(), Error>
pub fn run(self) -> Result<(), Error>
Opens the log file and the window, and runs the main loop until the
user closes the window, or, with the dev feature, until the
console’s quit.
The log file is nadir.log, in the game’s logs folder: on Linux
~/.local/share/<game>. Each run starts a new file and keeps the
last three runs’ files beside it, as nadir.log.1 to nadir.log.3.
If the file cannot be opened, the game goes on without it.
Where the system has no OpenGL device yet (Windows and macOS, until roadmap M2.6 and M2.7), the error is logged and the game runs without drawing.
It opens the default audio output, 48 kHz stereo, with the mixer,
once the window is open, and closes it when the loop ends, before an
error is shown. Where it does not open (Windows and macOS until
roadmap M6.4 and M6.5, Linux without libasound.so.2), a warning
says why and the game runs without sound; with no mixer left
(App::take_mixer, or an App::update before), the log says so.
A missing device is no error: the output starts without one, and
opens it once it comes.
With the dev feature, it reloads what changes while it runs: the
loaded assets’ files and render’s shaders, after each drawn frame
(the crate’s docs, “Hot reload”); and it keeps the debug windows’
places in debug_ui.jsonc in the game’s settings folder, on Linux
~/.config/<game>, reading them before the loop and writing them
as they change (App::add_debug_window). The renderer times its
passes on the GPU, where the device has timer queries, and the
profiler shows each frame’s GPU time once it is read back, two
renders later or more.
§Errors
Fails if the window cannot be opened, the renderer cannot start, or
a frame cannot be drawn. Before it returns the error, it logs it and
shows it to the player with show_error_dialog.
Sourcepub fn offscreen(self, size: UVec2) -> Result<Offscreen, Error>
pub fn offscreen(self, size: UVec2) -> Result<Offscreen, Error>
Draws the game offscreen, with no window, in frames of size
pixels: Offscreen::frame runs a frame, draws it as a window of
that size would show it, and returns its pixels. For recordings of
the game, such as the demo page’s (ADR-0029). It opens no log file.
§Errors
Error::Render where there is no offscreen OpenGL context
(GfxError::NoOffscreenContext on Windows
and macOS, until roadmap M2.6 and M2.7) or it cannot be made, or the
renderer or a target of size cannot be.