Skip to main content

App

Struct App 

Source
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 (tick Input): copies each Transform into its PrevTransform, and gives one to every entity with a Sprite and to the root of every drawn child;
  • nadir::movement (tick Movement): rebuilds Collisions and moves every entity with a Velocity, sliding the ones with a Collider;
  • nadir::parent_offsets (tick PostMovement): puts each entity with a Parent where its parent is, plus its offset;
  • nadir::triggers (tick PostMovement): sends TriggerEnter and TriggerExit;
  • nadir::animate (frame Animate): advances every Animator and writes its frame into its Sprite, sends AnimationFinished, mirrors the Sprite of each entity that faces Facing::Left, and unmirrors the rest with a Facing;
  • nadir::sound (frame Extract): puts the listener at the AudioListener, or else the camera, plays each AudioEmitter at its entity, sends the track of the MusicArea the listener is in, and calls Audio::update;
  • nadir::extract_sprites (frame Extract): draws every Sprite into the RenderFrame, between the last two ticks;
  • nadir::extract_level (frame Extract): draws the tile layers of the CurrentLevel, 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:

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

Source

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.

Source

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.

Source

pub fn insert_resource<R: 'static>(self, resource: R) -> Self

Adds resource, or replaces the one of its type.

Source

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).

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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::run keeps its place, its size and whether it is collapsed from then on, across runs, in debug_ui.jsonc in 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.
  • toggle works 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.
  • window gets 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 folder prefabs beside 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.

Source

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), named nadir::console: a command line, with history and Tab completion, under the log’s records and what the commands print. Its commands are help and 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, and command is not called.
  • command gets 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.
Source

pub fn world(&self) -> &World

The world, to read it.

Source

pub fn world_mut(&mut self) -> &mut World

The world, for setup: spawning entities, loading assets, registering components that are not reflected.

Source

pub fn schedule(&self) -> &Schedule

The systems, in stages: Schedule::describe lists them in the order they run.

Source

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:

  1. collects the profile scopes recorded since the last frame started, with the profile feature of nadir-core, so that they do not pile up; with the dev feature, which turns it on, it gives them to the profiler with the last frame’s timing;
  2. feeds the events to Input, holding back from the game’s actions, with the dev feature, what the debug UI has;
  3. runs the ticks that are due, of a frame elapsed long, or with the dev feature as the time controls leave the game’s time (none while paused but a tick for each F6, elapsed times the scale of F7 or the console’s timescale): for each, latches the actions, or takes them from the replay that App::play_replay plays, and runs the tick stages, which apply their commands;
  4. sets TickStats;
  5. empties the RenderFrame, sets its time to how long the simulation has run, and runs the frame stages;
  6. with the dev feature, fills the open debug windows into the RenderFrame’s UI, after the game’s (App::add_debug_window), and then loads the level the console’s level asked 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.

Source

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.

Source

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.

Auto Trait Implementations§

§

impl !Freeze for App

§

impl !RefUnwindSafe for App

§

impl !Send for App

§

impl !Sync for App

§

impl !UnwindSafe for App

§

impl Forget for App

§

impl Move for App

§

impl Unpin for App

§

impl UnsafeUnpin for App

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.