Skip to main content

nadir/
app.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! [`App`]: the game's configuration, its world and systems, and the main
16//! loop.
17
18use std::any::type_name;
19use std::cell::RefCell;
20use std::path::PathBuf;
21use std::rc::Rc;
22use std::time::{Duration, Instant};
23
24use nadir_assets::{AssetServer, FinalizeCtx, OnFailure};
25use nadir_audio::{AudioConfig, Bus, Mixer};
26use nadir_core::UVec2;
27use nadir_core::log::{debug, error, info, warn};
28use nadir_core::profile::{self, ScopeRecord};
29use nadir_core::profile_scope;
30use nadir_core::time::{FixedClock, Stopwatch};
31use nadir_ecs::{Component, FixedStage, FixedSystem, FrameStage, FrameSystem, Schedule, World};
32use nadir_gfx::{Device, PassTarget, RenderTargetId, TextureFormat};
33use nadir_input::{ActionKind, ActionMap, ActionSet, ActionState, Input, InputPlayer};
34use nadir_platform::{
35    AudioOutputConfig, AudioStream, Event, GpuSurface, ModalFrame, Platform, WindowConfig,
36    open_audio, precise_sleep, show_error_dialog,
37};
38use nadir_render::{FrameStats, Output, RenderConfig, RenderFrame, Renderer, TileLayers};
39use nadir_scene::{FromValue, PrefabLibrary, TypeRegistry};
40
41use crate::animation::AnimationClock;
42use crate::limiter::FrameLimiter;
43use crate::replay::{PlayReplay, ReplayInput};
44use crate::sound::{AudioState, MixerOutput, Tracked};
45use crate::{
46    AnimationFinished, Animator, AudioEmitter, AudioListener, Clips, Collider, CollisionLayers,
47    Collisions, CurrentLevel, Error, Facing, LevelError, MusicArea, Parent, Player, PrevTransform,
48    Replay, SaveId, Sprite, TickStats, Transform, TriggerEnter, TriggerExit, Velocity, glue,
49    log_file,
50};
51
52/// How many times a second the simulation steps.
53pub const TICK_HZ: u32 = 60;
54
55/// The longest that one frame counts for. After a stall, the simulation
56/// falls behind real time by the rest, which is better than a long burst of
57/// ticks to catch up. See [`FixedClock`].
58const MAX_FRAME: Duration = Duration::from_millis(250);
59
60/// How many profile scope records each frame's buffer holds before it
61/// must grow: a frame of 15 ticks of 60 systems each.
62const PROFILE_RECORDS: usize = 1_024;
63
64/// What a game asks of the engine.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct Config {
67    /// The text in the window's title bar.
68    pub title: String,
69    /// Who makes the game. On Windows the game's folders for settings, saves
70    /// and logs are inside a folder of this name.
71    pub studio: String,
72    /// The name of the game's folders for settings, saves and logs. Keep it
73    /// the same from one release to the next, or players lose their
74    /// settings and saves. Two games with the same name and studio share
75    /// their folders.
76    ///
77    /// This and [`studio`](Self::studio) must each be a valid folder name
78    /// on every system (the rules are at [`nadir_platform::user_dirs`]). If
79    /// one is not, the game runs without a log file, and a warning says why.
80    pub game: String,
81    /// The size of the inside of the window, in logical pixels.
82    pub window_size: UVec2,
83    /// The smallest size the user can give the window, in logical pixels.
84    /// A zero means no limit in that direction.
85    pub min_window_size: UVec2,
86    /// Whether the user can resize the window.
87    pub resizable: bool,
88    /// Whether the window starts in borderless fullscreen.
89    pub fullscreen: bool,
90    /// The most frames to run in a second. `None` and `Some(0)` mean no
91    /// limit. With [`vsync`](Self::vsync) the display paces the loop too,
92    /// but some drivers accept vsync and do not wait (llvmpipe, XWayland),
93    /// so the limit stays as a cap. Without either, the loop runs as fast as
94    /// it can and keeps a processor core busy.
95    pub frame_rate_limit: Option<u32>,
96    /// Whether each frame waits for the display's refresh, so that it does
97    /// not tear (a swap interval of 1).
98    pub vsync: bool,
99    /// The size of the image the world is drawn into, in pixels. It is
100    /// scaled up into the window by the largest whole factor that fits
101    /// (pixel-perfect mode, ADR-0018).
102    pub virtual_resolution: UVec2,
103    /// The folder the game's assets are loaded from: the cook's output,
104    /// whose pack `game.kpak` builds without `dev` read when it is there
105    /// ([`App::new`]).
106    pub assets: PathBuf,
107    /// The volume of each of the mixer's buses as the game starts: full,
108    /// by default.
109    pub volumes: Volumes,
110}
111
112impl Default for Config {
113    fn default() -> Self {
114        Self {
115            title: "Nadir".to_string(),
116            studio: "Nadir".to_string(),
117            game: "Nadir".to_string(),
118            window_size: UVec2::new(1280, 720),
119            min_window_size: UVec2::new(320, 180),
120            resizable: true,
121            fullscreen: false,
122            frame_rate_limit: Some(60),
123            vsync: true,
124            virtual_resolution: UVec2::new(480, 270),
125            assets: PathBuf::from("assets"),
126            volumes: Volumes::default(),
127        }
128    }
129}
130
131/// The volume of each of the mixer's buses, in percent of full: 0 to 100,
132/// and more counts as 100. A percent is heard as its square
133/// ([`Volumes::gain`]), so 50 is −12 dB, nearer half as loud than the
134/// −6 dB of half the gain.
135///
136/// [`App::new`] sets the buses to [`Config::volumes`]. A game changes one
137/// while it runs, from its settings say, with
138/// `audio.set_bus_volume(bus, volumes.gain(bus), fade)`
139/// ([`Audio::set_bus_volume`](nadir_audio::Audio::set_bus_volume)).
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub struct Volumes {
142    /// The music's: [`Bus::Music`].
143    pub music: u8,
144    /// The sound effects': [`Bus::Sfx`].
145    pub sfx: u8,
146    /// The interface's sounds': [`Bus::Ui`].
147    pub ui: u8,
148    /// The ambient loops': [`Bus::Ambience`].
149    pub ambience: u8,
150}
151
152impl Default for Volumes {
153    /// Every bus at 100: as its sounds are.
154    fn default() -> Self {
155        Self {
156            music: 100,
157            sfx: 100,
158            ui: 100,
159            ambience: 100,
160        }
161    }
162}
163
164impl Volumes {
165    /// The percent of `bus`.
166    pub const fn get(&self, bus: Bus) -> u8 {
167        match bus {
168            Bus::Music => self.music,
169            Bus::Sfx => self.sfx,
170            Bus::Ui => self.ui,
171            Bus::Ambience => self.ambience,
172        }
173    }
174
175    /// Sets the percent of `bus`: for a menu that goes through
176    /// [`Bus::ALL`].
177    pub fn set(&mut self, bus: Bus, percent: u8) {
178        let volume = match bus {
179            Bus::Music => &mut self.music,
180            Bus::Sfx => &mut self.sfx,
181            Bus::Ui => &mut self.ui,
182            Bus::Ambience => &mut self.ambience,
183        };
184        *volume = percent;
185    }
186
187    /// The gain of `bus`, for
188    /// [`Audio::set_bus_volume`](nadir_audio::Audio::set_bus_volume): its
189    /// percent, at most 100, as a part of 100, squared. 50 is 0.25.
190    pub fn gain(&self, bus: Bus) -> f32 {
191        let part = f32::from(self.get(bus).min(100)) / 100.0;
192        part * part
193    }
194}
195
196impl Config {
197    /// The window this configuration asks for.
198    fn window(&self) -> WindowConfig {
199        WindowConfig {
200            title: self.title.clone(),
201            size: self.window_size,
202            min_size: self.min_window_size,
203            resizable: self.resizable,
204            fullscreen: self.fullscreen,
205            vsync: self.vsync,
206        }
207    }
208}
209
210/// Latches the input into the game's action state.
211pub(crate) type LatchFn = Box<dyn FnMut(&mut Input, &World)>;
212
213/// The game's action set: latches the input into its state once a tick, or
214/// plays a replay into it.
215struct Actions {
216    /// The set's type, for messages, or `None` before the game adds one.
217    set: Option<&'static str>,
218    latch: LatchFn,
219    /// The replay that [`App::play_replay`] plays, until it ends.
220    replay: Option<Box<dyn PlayReplay>>,
221}
222
223impl Actions {
224    /// Before the game adds its actions: a latch into a set of its own, so
225    /// that each tick still ends, and [`Input::wheel`] moves on.
226    fn none() -> Self {
227        Self {
228            set: None,
229            latch: latch_into_nothing(),
230            replay: None,
231        }
232    }
233}
234
235/// A latch of the input into a set of its own, which nothing reads.
236fn latch_into_nothing() -> LatchFn {
237    let map = ActionMap::<NoActions>::new().expect("a set of one action is valid");
238    let mut state = ActionState::new();
239    Box::new(move |input, _| input.latch(&map, &mut state))
240}
241
242/// The action set the input is latched into before the game adds its own:
243/// one action, bound to nothing.
244#[derive(Clone, Copy, Debug, PartialEq, Eq)]
245enum NoActions {
246    Nothing,
247}
248
249impl ActionSet for NoActions {
250    const ALL: &'static [Self] = &[NoActions::Nothing];
251
252    fn index(self) -> usize {
253        0
254    }
255
256    fn name(self) -> &'static str {
257        "nothing"
258    }
259
260    fn kind(self) -> ActionKind {
261        ActionKind::Button
262    }
263}
264
265/// Where the loop gets the window's events from, and the surface it draws
266/// on: the platform in a game, and a script in tests.
267trait EventSource {
268    /// Appends the events that arrived since the last call. Does not wait.
269    fn pump_events(&mut self, out: &mut Vec<Event>);
270
271    /// Sets what to call while the system's own event loop keeps
272    /// [`EventSource::pump_events`] from returning.
273    fn set_modal_frame_callback(&mut self, callback: Box<dyn FnMut(ModalFrame)>);
274
275    /// The surface to draw on, if there is one.
276    fn gpu_surface(&self) -> Option<GpuSurface<'_>> {
277        None
278    }
279
280    /// The size of the inside of the window, in physical pixels.
281    fn window_size(&self) -> UVec2 {
282        UVec2::ZERO
283    }
284}
285
286impl EventSource for Platform {
287    fn pump_events(&mut self, out: &mut Vec<Event>) {
288        Platform::pump_events(self, out);
289    }
290
291    fn set_modal_frame_callback(&mut self, callback: Box<dyn FnMut(ModalFrame)>) {
292        Platform::set_modal_frame_callback(self, callback);
293    }
294
295    fn gpu_surface(&self) -> Option<GpuSurface<'_>> {
296        Some(Platform::gpu_surface(self))
297    }
298
299    fn window_size(&self) -> UVec2 {
300        Platform::window_size(self)
301    }
302}
303
304/// The GPU side of the loop, where there is a device.
305struct Graphics {
306    // The renderer's resources are the device's, so it goes first.
307    renderer: Renderer,
308    device: Device,
309}
310
311impl Graphics {
312    /// Draws the frame the frame systems made, shows it, and then makes the
313    /// assets the workers have decoded, within the asset server's budget.
314    /// Returns how long showing it took: the swap, which may wait for the
315    /// display.
316    fn draw(
317        &mut self,
318        world: &World,
319        surface: GpuSurface<'_>,
320        size: UVec2,
321    ) -> Result<Duration, Error> {
322        self.device.begin_frame(surface)?;
323        {
324            profile_scope!("nadir::render");
325            self.render(world, PassTarget::Surface, size)?;
326        }
327        let shown = Instant::now();
328        {
329            profile_scope!("nadir::present");
330            self.device.end_frame(surface)?;
331        }
332        let present = shown.elapsed();
333        {
334            profile_scope!("nadir::finish_loads");
335            self.finish_loads(world, false);
336        }
337        Ok(present)
338    }
339
340    /// Draws the frame the frame systems made into `target`, of `size`, on
341    /// the device's offscreen context, as [`Graphics::draw`] does on the
342    /// window, and reads it back. It then makes every asset loaded so far,
343    /// waiting for the workers, so that a recording shows the same frames
344    /// each time.
345    fn draw_offscreen(
346        &mut self,
347        world: &World,
348        target: RenderTargetId,
349        size: UVec2,
350    ) -> Result<Vec<u8>, Error> {
351        self.device.begin_offscreen_frame()?;
352        self.render(world, PassTarget::RenderTarget(target), size)?;
353        self.device.end_offscreen_frame()?;
354        self.finish_loads(world, true);
355        Ok(self.device.read_pixels(target)?)
356    }
357
358    /// Renders the frame into `target`, and sets [`FrameStats`].
359    fn render(&mut self, world: &World, target: PassTarget, size: UVec2) -> Result<(), Error> {
360        let stats = {
361            let assets = world.resource::<AssetServer>();
362            let tiles = world.resource::<TileLayers>();
363            let frame = world.resource::<RenderFrame>();
364            let output = Output { target, size };
365            self.renderer
366                .render(&mut self.device, &assets, &tiles, &frame, output)?
367        };
368        *world.resource_mut::<FrameStats>() = stats;
369        Ok(())
370    }
371
372    /// Makes the assets the workers have decoded, and frees those of
373    /// unloaded scopes. With `wait`, it waits for every load first.
374    fn finish_loads(&mut self, world: &World, wait: bool) {
375        let pending = world.resource::<AssetServer>().has_pending();
376        if pending {
377            let mut server = world.resource_mut::<AssetServer>();
378            let mut ctx = FinalizeCtx::new().with(&mut self.device);
379            if wait {
380                server.finish_all_loads(&mut ctx);
381            } else {
382                server.finish_completed_loads(&mut ctx);
383            }
384        }
385    }
386}
387
388/// Everything a frame needs, shared by the main loop and the modal frame
389/// callback.
390struct EngineCore {
391    app: App,
392    stopwatch: Stopwatch,
393    graphics: Option<Graphics>,
394    /// An error that ends the loop, from a frame the loop did not run
395    /// itself (a modal one).
396    error: Option<Error>,
397    /// The main thread's heap use at the end of the last frame.
398    #[cfg(feature = "dev")]
399    allocs_at_frame_end: nadir_platform::AllocCounts,
400    /// The hot reload, where there is a device to draw what it reloads.
401    #[cfg(feature = "dev")]
402    reload: Option<crate::hot_reload::HotReload>,
403}
404
405impl EngineCore {
406    /// Runs one frame, for the time since the last, with the events that
407    /// came before it. Draws it on `window`'s surface, if there is one.
408    fn frame(&mut self, events: &[Event], window: Option<(GpuSurface<'_>, UVec2)>) {
409        let elapsed = self.stopwatch.lap();
410        #[cfg(feature = "dev")]
411        if let Some((_, size)) = window {
412            *self.app.world.resource_mut::<crate::WindowSize>() = crate::WindowSize(size);
413        }
414        self.app.update(elapsed, events);
415        if let (Some(graphics), Some((surface, size))) = (&mut self.graphics, window) {
416            #[cfg(feature = "dev")]
417            let drawing = Instant::now();
418            let drawn = graphics.draw(&self.app.world, surface, size);
419            #[cfg(feature = "dev")]
420            if drawn.is_ok()
421                && let Some(reload) = &mut self.reload
422            {
423                reload.frame(
424                    &mut self.app.world,
425                    &mut graphics.renderer,
426                    &mut graphics.device,
427                );
428            }
429            // The processor's work on the frame, the wait to show it aside;
430            // and the GPU's times this render read back, for the frames
431            // they were timed in. A frame that fails to draw ends the loop.
432            #[cfg(feature = "dev")]
433            if let Ok(present) = drawn {
434                let work = drawing.elapsed().saturating_sub(present);
435                self.app.debug.add_work(work);
436                self.app
437                    .debug
438                    .rendered(drawing, graphics.renderer.gpu_times());
439            }
440            if let Err(error) = drawn {
441                self.error.get_or_insert(error);
442            }
443        }
444        #[cfg(feature = "dev")]
445        {
446            let now = nadir_platform::thread_alloc_counts();
447            let allocs = crate::FrameAllocs(now.since(self.allocs_at_frame_end));
448            *self.app.world.resource_mut::<crate::FrameAllocs>() = allocs;
449            self.allocs_at_frame_end = now;
450        }
451    }
452}
453
454/// A game: its configuration, its [`World`] of entities and resources, and
455/// its systems in stages. [`App::run`] opens the log file and the window,
456/// and runs the main loop; [`App::update`] runs one frame without them.
457///
458/// Systems are functions of the world and the tick, or the frame, added to
459/// a stage with a name. They run in stage order, then in the order they
460/// were added (`docs/subsystems/ecs.md`). The engine adds its own first in
461/// their stages:
462///
463/// - `nadir::snapshot` (tick `Input`): copies each [`Transform`] into its
464///   [`PrevTransform`], and gives one to every entity with a [`Sprite`]
465///   and to the root of every drawn child;
466/// - `nadir::movement` (tick `Movement`): rebuilds [`Collisions`] and
467///   moves every entity with a [`Velocity`], sliding the ones with a
468///   [`Collider`];
469/// - `nadir::parent_offsets` (tick `PostMovement`): puts each entity with
470///   a [`Parent`] where its parent is, plus its offset;
471/// - `nadir::triggers` (tick `PostMovement`): sends [`TriggerEnter`] and
472///   [`TriggerExit`];
473/// - `nadir::animate` (frame `Animate`): advances every [`Animator`] and
474///   writes its frame into its [`Sprite`], sends [`AnimationFinished`],
475///   mirrors the Sprite of each entity that faces [`Facing::Left`], and
476///   unmirrors the rest with a [`Facing`];
477/// - `nadir::sound` (frame `Extract`): puts the listener at the
478///   [`AudioListener`], or else the camera, plays each [`AudioEmitter`] at
479///   its entity, sends the track of the [`MusicArea`] the listener is in,
480///   and calls [`Audio::update`](nadir_audio::Audio::update);
481/// - `nadir::extract_sprites` (frame `Extract`): draws every [`Sprite`]
482///   into the [`RenderFrame`], between the last two ticks;
483/// - `nadir::extract_level` (frame `Extract`): draws the tile layers of the
484///   [`CurrentLevel`], with its background as the clear colour.
485///
486/// So a game sets velocities in `Gameplay`, and reacts to the moves after
487/// the engine's, in `Movement` or `PostMovement`. It sets [`Facing`] and
488/// plays clips in ticks too, and reacts to finished clips in frames.
489///
490/// The engine's resources:
491///
492/// - [`Input`], which latches the keys and buttons into the actions, and
493///   holds the pointer and the wheel
494/// - with [`App::add_actions`], the game's [`ActionMap`] and its
495///   [`ActionState`], latched once a tick before the tick stages
496/// - [`AssetServer`], loading from [`Config::assets`]
497/// - [`RenderFrame`], emptied before the frame stages, which fill it; the
498///   loop then draws it. Its `time`, which animated tiles show and
499///   animators follow, is how long the simulation has run, ticks and
500///   `alpha`.
501/// - [`TileLayers`], the game's tile layers, which the frame's
502///   `tile_layers` name and the loop draws from
503/// - [`FrameStats`], what the last frame drew
504/// - [`TickStats`], how long this frame's ticks took
505/// - [`Collisions`], the colliders
506/// - [`Clips`], the clips that animators play
507/// - [`TypeRegistry`], the reflected component types
508/// - [`PrefabLibrary`], the prefabs the game loads, none until it loads
509///   them
510/// - [`CollisionLayers`], the names of the game's collision layers, none
511///   until [`App::collision_layers`] gives them
512/// - [`CurrentLevel`], the level [`App::load_level`] loaded, none until it
513///   loads one
514/// - [`Audio`](nadir_audio::Audio), the game's handle on the mixer, whose
515///   buses start at [`Config::volumes`], and [`AudioState`], what
516///   `nadir::sound` plays
517/// - with [`App::play_replay`], [`Replay`], how far the replay got
518/// - the events [`TriggerEnter`], [`TriggerExit`] and [`AnimationFinished`]
519/// - with the `dev` feature, `FrameAllocs`, what the last frame allocated,
520///   and `WindowSize`, the size of the window the frame is drawn at
521///
522/// ```no_run
523/// use nadir::prelude::*;
524///
525/// struct Spin(f32);
526///
527/// fn simulate(world: &World, tick: &Tick) {
528///     // 60 times a second: move things by `tick.dt`.
529///     world.resource_mut::<Spin>().0 += tick.dt;
530/// }
531///
532/// fn main() -> Result<(), nadir::Error> {
533///     App::new(Config {
534///         title: "My game".into(),
535///         ..Config::default()
536///     })
537///     .insert_resource(Spin(0.0))
538///     .add_fixed_system(FixedStage::Gameplay, "simulate", simulate)
539///     .add_frame_system(FrameStage::Ui, "show", |world, frame| {
540///         // Once for each frame, after its ticks.
541///         let _ = (world.resource::<Spin>().0, frame.alpha);
542///     })
543///     .run()
544/// }
545/// ```
546pub struct App {
547    config: Config,
548    world: World,
549    schedule: Schedule,
550    actions: Actions,
551    clock: FixedClock,
552    /// The last frame's profile scopes (the `profile` feature of
553    /// `nadir-core`, which `dev` turns on), collected as each frame starts
554    /// so that the recorder keeps its buffer, and with `dev` given to the
555    /// profiler.
556    profile: Vec<ScopeRecord>,
557    /// The folder of the shader files the hot reload watches: render's
558    /// `shaders/`, or a test's.
559    #[cfg(feature = "dev")]
560    shader_dir: PathBuf,
561    /// The mixer that [`Audio`](nadir_audio::Audio) sends to, until
562    /// [`App::run`] hands it to the audio output, [`App::take_mixer`] takes
563    /// it, or [`App::update`] drops it.
564    mixer: Option<Mixer>,
565    /// The debug UI and the game's debug windows.
566    #[cfg(feature = "dev")]
567    debug: crate::debug_ui::DebugTools,
568}
569
570impl App {
571    /// An app with the engine's resources, components and systems, and no
572    /// entities.
573    ///
574    /// Its [`AssetServer`] loads from [`Config::assets`]. With the `dev`
575    /// feature, it reads the loose files there, watches each file loaded
576    /// from then on for the hot reload of [`App::run`], and a failed asset
577    /// shows its placeholder. Without it, it reads the cook's pack there,
578    /// `game.kpak`, when there is one, and the loose files otherwise; a
579    /// pack that does not open is logged, and every load then fails with
580    /// its error (ADR-0041); and a failed asset shows nothing.
581    ///
582    /// Of the engine's components, [`Transform`], [`Velocity`], [`Player`],
583    /// [`SaveId`], [`Facing`], [`Sprite`], [`Collider`] and [`Animator`] are
584    /// reflected, so that prefabs and levels can give them (ADR-0038).
585    /// [`Parent`] is not yet (roadmap M9.4), and [`PrevTransform`] is the
586    /// engine's own. Its resources include a [`PrefabLibrary`] with no
587    /// prefabs, and [`CollisionLayers`] with no names
588    /// ([`App::collision_layers`]).
589    ///
590    /// It makes the mixer, of [`AudioConfig::default`], and sets each bus
591    /// to [`Config::volumes`]. [`AudioListener`], [`AudioEmitter`] and
592    /// [`MusicArea`] are not reflected: a game gives them in code.
593    pub fn new(config: Config) -> Self {
594        let on_failure = if cfg!(feature = "dev") {
595            OnFailure::Placeholder
596        } else {
597            OnFailure::Nothing
598        };
599        let mut world = World::new();
600        world.insert_resource(Input::new());
601        #[cfg_attr(not(feature = "dev"), expect(unused_mut))]
602        let mut server =
603            crate::pack::asset_server(&config.assets, on_failure, !cfg!(feature = "dev"));
604        // Watched from before the game's setup reads a file, so that the
605        // hot reload of `App::run` sees an edit made after the read.
606        #[cfg(feature = "dev")]
607        if let Err(cause) = server.start_watcher() {
608            nadir_core::log::warn!(
609                "the assets will not reload: their watcher did not start: {cause}"
610            );
611        }
612        world.insert_resource(server);
613        world.insert_resource(RenderFrame::new());
614        world.insert_resource(TileLayers::new());
615        world.insert_resource(FrameStats::default());
616        world.insert_resource(TickStats::default());
617        world.insert_resource(Collisions::new());
618        world.insert_resource(Clips::new());
619        world.insert_resource(CollisionLayers::default());
620        world.insert_resource(PrefabLibrary::new());
621        world.insert_resource(CurrentLevel::default());
622        world.insert_resource(AnimationClock::default());
623        let sound = AudioConfig::default();
624        let (audio, mixer) = nadir_audio::new(sound).expect("the default audio config is valid");
625        // Queued, for the mixer's first callback.
626        for bus in Bus::ALL {
627            audio.set_bus_volume(bus, config.volumes.gain(bus), 0);
628        }
629        world.insert_resource(audio);
630        world.insert_resource(AudioState::new(&sound));
631        #[cfg(feature = "dev")]
632        world.insert_resource(crate::FrameAllocs::default());
633        #[cfg(feature = "dev")]
634        world.insert_resource(crate::hot_reload::Reloads::default());
635        #[cfg(feature = "dev")]
636        world.insert_resource(crate::WindowSize::default());
637        world.add_event::<TriggerEnter>();
638        world.add_event::<TriggerExit>();
639        world.add_event::<AnimationFinished>();
640
641        let mut registry = TypeRegistry::new();
642        registry.register_component::<Transform>();
643        registry.register_component::<Velocity>();
644        registry.register_component::<Player>();
645        registry.register_component::<SaveId>();
646        registry.register_component::<Facing>();
647        registry.register_component::<Sprite>();
648        registry.register_component::<Collider>();
649        registry.register_component::<Animator>();
650        registry.register_components(&mut world);
651        world.insert_resource(registry);
652        world.register::<PrevTransform>();
653        world.register::<Sprite>();
654        world.register::<Collider>();
655        world.register::<Parent>();
656        world.register::<Animator>();
657        world.register::<AudioListener>();
658        world.register::<AudioEmitter>();
659        world.register::<MusicArea>();
660        world.register::<Tracked>();
661
662        let mut schedule = Schedule::new();
663        schedule
664            .add_fixed(FixedStage::Input, "nadir::snapshot", glue::snapshot)
665            .add_fixed(FixedStage::Movement, "nadir::movement", glue::movement)
666            .add_fixed(
667                FixedStage::PostMovement,
668                "nadir::parent_offsets",
669                glue::parent_offsets,
670            )
671            .add_fixed(FixedStage::PostMovement, "nadir::triggers", glue::triggers)
672            .add_frame(FrameStage::Animate, "nadir::animate", glue::animate)
673            .add_frame(FrameStage::Extract, "nadir::sound", crate::sound::sound)
674            .add_frame(
675                FrameStage::Extract,
676                "nadir::extract_sprites",
677                glue::extract_sprites,
678            )
679            .add_frame(
680                FrameStage::Extract,
681                "nadir::extract_level",
682                crate::level::extract_level,
683            );
684        Self {
685            config,
686            world,
687            schedule,
688            actions: Actions::none(),
689            clock: FixedClock::new(TICK_HZ, MAX_FRAME),
690            profile: Vec::new(),
691            #[cfg(feature = "dev")]
692            shader_dir: PathBuf::from(nadir_render::SHADER_DIR),
693            mixer: Some(mixer),
694            #[cfg(feature = "dev")]
695            debug: crate::debug_ui::DebugTools::new(),
696        }
697    }
698
699    /// Takes the mixer, for a test or a tool that renders it itself
700    /// ([`Mixer::render`]): [`App::run`] then opens no audio output. Take it
701    /// before the first [`App::update`], which drops a mixer the app still
702    /// holds: `None` then, and once it is taken.
703    pub fn take_mixer(&mut self) -> Option<Mixer> {
704        self.mixer.take()
705    }
706
707    /// Adds `resource`, or replaces the one of its type.
708    #[must_use]
709    pub fn insert_resource<R: 'static>(mut self, resource: R) -> Self {
710        self.world.insert_resource(resource);
711        self
712    }
713
714    /// Adds the event type `T`: the resource `Events<T>`, which the
715    /// schedule clears (`World::add_event`).
716    #[must_use]
717    pub fn add_event<T: Clone + 'static>(mut self) -> Self {
718        self.world.add_event::<T>();
719        self
720    }
721
722    /// Adds the reflected component type `T` to the world and to the
723    /// [`TypeRegistry`], under its reflected name. A component that is not
724    /// reflected is added with `app.world_mut().register::<T>()`.
725    ///
726    /// # Panics
727    ///
728    /// If another type has the same reflected name.
729    #[must_use]
730    pub fn register_component<T: Component + FromValue>(mut self) -> Self {
731        self.world
732            .resource_mut::<TypeRegistry>()
733            .register_component::<T>();
734        self.world.register::<T>();
735        self
736    }
737
738    /// Loads the level `name`, `levels/<name>.klvl`, in place of the one the
739    /// world holds, as [`load_level`](crate::load_level) says: its prefabs
740    /// and tile sets are read before this returns, its entities spawned,
741    /// and its tile layers drawn from the next frame.
742    ///
743    /// # Errors
744    ///
745    /// A [`LevelError`] if it cannot be loaded. The previous level is gone
746    /// then, and nothing of the new one is in the world.
747    pub fn load_level(&mut self, name: &str) -> Result<(), LevelError> {
748        crate::load_level(&mut self.world, name)
749    }
750
751    /// Names the game's collision layers: bit 0 of a
752    /// [`LayerMask`](nadir_collision::LayerMask) the first, bit 1 the next,
753    /// and so on, as prefabs and levels write a collider's layers
754    /// (`["World", "People"]`). It replaces the [`CollisionLayers`]
755    /// resource, which has no names until then.
756    ///
757    /// # Panics
758    ///
759    /// If there are more than 32 names, one is empty, or two are the same.
760    #[must_use]
761    pub fn collision_layers(self, names: &[&str]) -> Self {
762        *self.world.resource_mut::<CollisionLayers>() = CollisionLayers::new(names);
763        self
764    }
765
766    /// Adds the game's actions, with their bindings: the resources
767    /// [`ActionMap<A>`] and [`ActionState<A>`], whose state is latched from
768    /// the input once a tick, before the tick stages.
769    ///
770    /// Read edges (`just_pressed`) in fixed systems. A frame system sees
771    /// only the last tick's: it misses those of a frame's earlier ticks, and
772    /// sees one again when a frame has no tick.
773    ///
774    /// # Panics
775    ///
776    /// An app has one action set: adding another type panics. Adding the
777    /// same type again replaces its bindings. Adding actions while a replay
778    /// plays panics: [`App::play_replay`] comes after `add_actions`.
779    #[must_use]
780    pub fn add_actions<A: ActionSet>(mut self, map: ActionMap<A>) -> Self {
781        let set = type_name::<A>();
782        if let Some(existing) = self.actions.set {
783            assert!(
784                existing == set,
785                "an App has one action set: it has `{existing}`, so it cannot add `{set}`",
786            );
787        }
788        assert!(
789            self.actions.replay.is_none(),
790            "a replay is playing: play_replay must come after add_actions"
791        );
792        self.world.insert_resource(map);
793        self.world.insert_resource(ActionState::<A>::new());
794        self.actions = Actions {
795            set: Some(set),
796            latch: Box::new(|input, world| {
797                let map = world.resource::<ActionMap<A>>();
798                let mut state = world.resource_mut::<ActionState<A>>();
799                input.latch(&map, &mut state);
800            }),
801            replay: None,
802        };
803        self
804    }
805
806    /// Plays `replay` into the game's actions in place of the live input:
807    /// each tick from the next on takes its [`ActionState<A>`] from the
808    /// replay's next tick. It adds the resource [`Replay`], which says how
809    /// far it got. The replay is read a tick ahead, so it is
810    /// [`Replay::Ended`] as soon as its last tick has run, and the ticks
811    /// after that are latched live.
812    ///
813    /// While it plays, the live input still reaches [`Input`], but not the
814    /// actions. The pointer and the wheel stay live: replays do not hold
815    /// them, so a fixed system that reads them does not replay. When the
816    /// replay ends, the first live tick's edges are those of the live keys
817    /// alone: an action held in the replay's last tick is not just
818    /// released, and a key held all along is held but not just pressed.
819    ///
820    /// A damaged tick ends the replay as [`Replay::Failed`], after an error
821    /// in the log; the ticks before it play. A replay with no ticks is
822    /// [`Replay::Ended`] at once. Playing another replay replaces this one.
823    ///
824    /// # Panics
825    ///
826    /// If the game's action set, added with [`App::add_actions`], is not
827    /// `A`.
828    #[must_use]
829    pub fn play_replay<A: ActionSet>(mut self, replay: InputPlayer<'static, A>) -> Self {
830        let set = type_name::<A>();
831        assert!(
832            self.actions.set == Some(set),
833            "a replay of `{set}` plays into those actions: add them with add_actions first"
834        );
835        let replay = ReplayInput::new(replay, latch_into_nothing());
836        let status = match replay.ahead() {
837            Ok(true) => Replay::Playing { ticks: 0 },
838            Ok(false) => Replay::Ended { ticks: 0 },
839            Err(error) => failed(0, error),
840        };
841        self.actions.replay = matches!(status, Replay::Playing { .. })
842            .then(|| Box::new(replay) as Box<dyn PlayReplay>);
843        self.world.insert_resource(status);
844        self
845    }
846
847    /// The [`world_hash`](crate::world_hash) of the world: the same after
848    /// the same ticks of the same replay, from the same start, whatever the
849    /// frames were, under the conditions that function gives.
850    pub fn world_hash(&self) -> u64 {
851        crate::world_hash(&self.world)
852    }
853
854    /// Adds a system to a stage of each simulation tick, after the stage's
855    /// others. Ticks come [`TICK_HZ`] times a second, however fast frames
856    /// come.
857    #[must_use]
858    pub fn add_fixed_system(
859        mut self,
860        stage: FixedStage,
861        name: &'static str,
862        system: FixedSystem,
863    ) -> Self {
864        self.schedule.add_fixed(stage, name, system);
865        self
866    }
867
868    /// Adds a system to a stage of each frame, after the stage's others.
869    /// A frame's stages run after its ticks.
870    #[must_use]
871    pub fn add_frame_system(
872        mut self,
873        stage: FrameStage,
874        name: &'static str,
875        system: FrameSystem,
876    ) -> Self {
877        self.schedule.add_frame(stage, name, system);
878        self
879    }
880
881    /// Adds a window to the debug UI, in development builds (feature
882    /// `dev`): `toggle` shows and hides it, and it starts hidden. While it
883    /// shows, `window` fills it with widgets each frame, after the frame
884    /// stages, through the [`Ui`](nadir_debug::Ui) of
885    /// [`nadir::debug`](crate::debug).
886    ///
887    /// - It shows at `first`, in the debug UI's units, the first time;
888    ///   [`App::run`] keeps its place, its size and whether it is collapsed
889    ///   from then on, across runs, in `debug_ui.jsonc` in the game's
890    ///   settings folder, by its name: its title, or the explicit ID after
891    ///   `##` in `"Title##id"`.
892    /// - It is drawn after the game's UI, over it, in the engine's own
893    ///   font, at the window's scale factor rounded to a whole number
894    ///   (until the settings file's UI scale, roadmap M9.3).
895    /// - While the pointer is over a debug window, or a debug widget is held,
896    ///   the game's actions do not see the mouse's buttons or the wheel;
897    ///   while one of its text fields has the keyboard, they do not see the
898    ///   keys (`Input::set_capture`, which the debug UI then sets; a replay
899    ///   still plays). A press goes where the pointer was when it went
900    ///   down, by the windows drawn in the frame before.
901    /// - `toggle` works whenever it is pressed, a text field's keyboard or
902    ///   not, and the game's actions see it too, as they see any key no
903    ///   debug field has. One key may toggle several windows.
904    /// - `window` gets the world to read, or to change through its
905    ///   resources and storages, as a frame system does.
906    /// - The engine has five windows of its own, hidden at start: the
907    ///   stats overlay on F1, named `nadir::stats`; the inspector on F2,
908    ///   `nadir::inspector`, which outlines the entity it shows and writes
909    ///   its prefabs into the folder `prefabs` beside the log file; the
910    ///   profiler on F3, `nadir::profiler`, which writes its traces beside
911    ///   the log file; the debug drawing on F4, `nadir::debug_draw`, whose
912    ///   ticked overlays draw into the world while it is open; and the
913    ///   console on the backtick, `nadir::console`
914    ///   ([`App::add_console_command`]; `docs/subsystems/debug-tools.md`).
915    ///   A game's window on one of those keys shows and hides with it.
916    /// - F5, F6 and F7 control the game's time: pause, step a tick, scale
917    ///   (with Shift, down). A game's window on one of them still shows
918    ///   and hides, and the time changes too.
919    ///
920    /// Only [`App::run`] reads and writes `debug_ui.jsonc`:
921    /// [`App::update`] and [`App::offscreen`] start each window at `first`.
922    #[cfg(feature = "dev")]
923    #[must_use]
924    pub fn add_debug_window(
925        mut self,
926        toggle: nadir_core::Key,
927        title: &'static str,
928        first: nadir_core::Rect,
929        window: crate::DebugWindow,
930    ) -> Self {
931        self.debug.add(toggle, title, first, window);
932        self
933    }
934
935    /// Adds a command to the debug console, under `usage`, whose first word
936    /// is its name, followed by its arguments, with `help`, a line of what
937    /// it does: in development builds only (feature `dev`).
938    ///
939    /// - The console is a window of the engine's on the backtick (`` ` ``,
940    ///   [`Key::Grave`](nadir_core::Key::Grave)), named `nadir::console`:
941    ///   a command line, with history and Tab completion, under the log's
942    ///   records and what the commands print. Its commands are `help` and
943    ///   the engine's (`schedule`, `spawn`, `tp`, `timescale`, `level`,
944    ///   `reload`, `profile dump`, `log level`, `quit`;
945    ///   `docs/subsystems/debug-tools.md`).
946    /// - The usage names each argument: a word to type as it is, a value
947    ///   (`<x>`, or `[x]` if it may be left out), or a choice (`<on|off>`).
948    ///   A line that does not fit it is refused with why, and `command` is
949    ///   not called.
950    /// - `command` gets the world, as a debug window does, the arguments,
951    ///   and where to print. Commands it queues apply after the next tick
952    ///   or the next frame's stages.
953    /// - A command of a name already there replaces it, the engine's too. A
954    ///   usage that starts with no name (a placeholder, a quote, `help`) is
955    ///   logged as an error, and nothing is added.
956    #[cfg(feature = "dev")]
957    #[must_use]
958    pub fn add_console_command(
959        mut self,
960        usage: &str,
961        help: &str,
962        command: crate::ConsoleCommand,
963    ) -> Self {
964        self.debug.add_command(usage, help, command);
965        self
966    }
967
968    /// The world, to read it.
969    pub fn world(&self) -> &World {
970        &self.world
971    }
972
973    /// The world, for setup: spawning entities, loading assets,
974    /// registering components that are not reflected.
975    pub fn world_mut(&mut self) -> &mut World {
976        &mut self.world
977    }
978
979    /// The debug UI's state, for the tests beside it.
980    #[cfg(all(test, feature = "dev"))]
981    pub(crate) fn debug_tools(&mut self) -> &mut crate::debug_ui::DebugTools {
982        &mut self.debug
983    }
984
985    /// The systems, in stages: [`Schedule::describe`] lists them in the
986    /// order they run.
987    pub fn schedule(&self) -> &Schedule {
988        &self.schedule
989    }
990
991    /// Runs one frame that comes `elapsed` after the last, with the events
992    /// that came before it, without drawing it:
993    ///
994    /// 1. collects the profile scopes recorded since the last frame
995    ///    started, with the `profile` feature of `nadir-core`, so that they
996    ///    do not pile up; with the `dev` feature, which turns it on, it
997    ///    gives them to the profiler with the last frame's timing;
998    /// 2. feeds the events to [`Input`], holding back from the game's
999    ///    actions, with the `dev` feature, what the debug UI has;
1000    /// 3. runs the ticks that are due, of a frame `elapsed` long, or with
1001    ///    the `dev` feature as the time controls leave the game's time
1002    ///    (none while paused but a tick for each F6, `elapsed` times the
1003    ///    scale of F7 or the console's `timescale`): for each,
1004    ///    latches the actions, or takes them from the replay that
1005    ///    [`App::play_replay`] plays, and runs the tick stages, which apply
1006    ///    their commands;
1007    /// 4. sets [`TickStats`];
1008    /// 5. empties the [`RenderFrame`], sets its `time` to how long the
1009    ///    simulation has run, and runs the frame stages;
1010    /// 6. with the `dev` feature, fills the open debug windows into the
1011    ///    `RenderFrame`'s UI, after the game's
1012    ///    ([`App::add_debug_window`]), and then loads the level the
1013    ///    console's `level` asked for, if it did.
1014    ///
1015    /// The engine's scopes are `nadir::tick` (each tick),
1016    /// `nadir::frame_stages` and `nadir::debug_ui`, beside each system's
1017    /// (`docs/subsystems/ecs.md`); [`App::run`] adds `nadir::render`,
1018    /// `nadir::present` and `nadir::finish_loads` for the drawing.
1019    ///
1020    /// [`App::run`] calls it once a frame, then draws the `RenderFrame`.
1021    /// Tests, benchmarks and headless runs call it themselves. A frame of
1022    /// `Duration::from_nanos(16_666_667)` runs one tick: the third of a
1023    /// nanosecond it holds past a tick adds up to another only after 50
1024    /// million frames. Asset loads finish only in a drawn frame, so a
1025    /// headless run finishes none: tick systems must not depend on whether
1026    /// an asset has loaded.
1027    ///
1028    /// It plays no sound. Its first call drops the mixer, unless
1029    /// [`App::take_mixer`] took it, and [`Audio`](nadir_audio::Audio) then
1030    /// does nothing: so tests, benchmarks, headless runs and
1031    /// [`App::offscreen`] are silent, and [`App::run`] after it opens no
1032    /// audio output.
1033    pub fn update(&mut self, elapsed: Duration, events: &[Event]) {
1034        #[cfg(feature = "dev")]
1035        let started = Instant::now();
1036        profile::take_frame(&mut self.profile);
1037        // Records came back, so the feature is on. The recorder gets this
1038        // buffer back next frame: make it big enough that a frame of many
1039        // ticks does not grow it.
1040        if !self.profile.is_empty() {
1041            let more = PROFILE_RECORDS.saturating_sub(self.profile.len());
1042            self.profile.reserve(more);
1043        }
1044        #[cfg(feature = "dev")]
1045        self.debug.start_profile(started, &self.profile);
1046        // Nothing renders it here: dropped, it leaves no queue to fill.
1047        self.mixer = None;
1048        {
1049            let mut input = self.world.resource_mut::<Input>();
1050            #[cfg(feature = "dev")]
1051            self.debug.start_frame(&mut input);
1052            for event in events {
1053                #[cfg(feature = "dev")]
1054                self.debug.handle(&mut input, event);
1055                input.handle(event);
1056            }
1057        }
1058        // The time controls (F5 to F7) and the console's `timescale` pause,
1059        // step and scale the game's time.
1060        #[cfg(feature = "dev")]
1061        let elapsed = self.debug.game_time(elapsed);
1062        let frame = self.clock.begin_frame(elapsed);
1063        let mut stats = TickStats::default();
1064        while let Some(tick) = self.clock.consume_tick() {
1065            profile_scope!("nadir::tick");
1066            let start = Instant::now();
1067            let replayed = {
1068                let mut input = self.world.resource_mut::<Input>();
1069                match &mut self.actions.replay {
1070                    Some(replay) => {
1071                        let ticks = replay.latch(&mut input, &self.world);
1072                        *self.world.resource_mut::<Replay>() = Replay::Playing { ticks };
1073                        true
1074                    }
1075                    None => {
1076                        (self.actions.latch)(&mut input, &self.world);
1077                        false
1078                    }
1079                }
1080            };
1081            self.schedule.run_fixed(&mut self.world, &tick);
1082            if replayed {
1083                self.end_replay_tick();
1084            }
1085            let took = start.elapsed();
1086            stats.ticks += 1;
1087            stats.time += took;
1088            stats.longest = stats.longest.max(took);
1089        }
1090        *self.world.resource_mut::<TickStats>() = stats;
1091        {
1092            let mut out = self.world.resource_mut::<RenderFrame>();
1093            out.clear();
1094            out.time = simulated_time(&self.clock);
1095        }
1096        {
1097            profile_scope!("nadir::frame_stages");
1098            self.schedule.run_frame(&mut self.world, &frame);
1099        }
1100        #[cfg(feature = "dev")]
1101        {
1102            profile_scope!("nadir::debug_ui");
1103            self.debug.frame(
1104                &self.world,
1105                &self.schedule,
1106                self.config.virtual_resolution,
1107                frame.alpha,
1108            );
1109            // The console's `level`, which needs the world whole.
1110            if let Some(name) = self.debug.take_level() {
1111                let result = crate::load_level(&mut self.world, &name);
1112                self.debug.level_loaded(&name, result);
1113            }
1114        }
1115        #[cfg(feature = "dev")]
1116        self.debug.add_work(started.elapsed());
1117    }
1118
1119    /// Opens the log file and the window, and runs the main loop until the
1120    /// user closes the window, or, with the `dev` feature, until the
1121    /// console's `quit`.
1122    ///
1123    /// The log file is `nadir.log`, in the game's logs folder: on Linux
1124    /// `~/.local/share/<game>`. Each run starts a new file and keeps the
1125    /// last three runs' files beside it, as `nadir.log.1` to `nadir.log.3`.
1126    /// If the file cannot be opened, the game goes on without it.
1127    ///
1128    /// Where the system has no OpenGL device yet (Windows and macOS, until
1129    /// roadmap M2.6 and M2.7), the error is logged and the game runs
1130    /// without drawing.
1131    ///
1132    /// It opens the default audio output, 48 kHz stereo, with the mixer,
1133    /// once the window is open, and closes it when the loop ends, before an
1134    /// error is shown. Where it does not open (Windows and macOS until
1135    /// roadmap M6.4 and M6.5, Linux without `libasound.so.2`), a warning
1136    /// says why and the game runs without sound; with no mixer left
1137    /// ([`App::take_mixer`], or an [`App::update`] before), the log says so.
1138    /// A missing device is no error: the output starts without one, and
1139    /// opens it once it comes.
1140    ///
1141    /// With the `dev` feature, it reloads what changes while it runs: the
1142    /// loaded assets' files and render's shaders, after each drawn frame
1143    /// (the crate's docs, "Hot reload"); and it keeps the debug windows'
1144    /// places in `debug_ui.jsonc` in the game's settings folder, on Linux
1145    /// `~/.config/<game>`, reading them before the loop and writing them
1146    /// as they change ([`App::add_debug_window`]). The renderer times its
1147    /// passes on the GPU, where the device has timer queries, and the
1148    /// profiler shows each frame's GPU time once it is read back, two
1149    /// renders later or more.
1150    ///
1151    /// # Errors
1152    ///
1153    /// Fails if the window cannot be opened, the renderer cannot start, or
1154    /// a frame cannot be drawn. Before it returns the error, it logs it and
1155    /// shows it to the player with [`show_error_dialog`].
1156    pub fn run(mut self) -> Result<(), Error> {
1157        log_file::start(&self.config.studio, &self.config.game);
1158        #[cfg(feature = "dev")]
1159        match nadir_platform::user_dirs(&self.config.studio, &self.config.game) {
1160            Ok(dirs) => {
1161                self.debug
1162                    .keep_places_in(dirs.config.join(crate::debug_ui::FILE_NAME));
1163                self.debug.write_traces_in(dirs.logs);
1164            }
1165            Err(error) => {
1166                warn!(
1167                    "the debug UI's windows are not kept, nor the profiler's traces and the \
1168                     inspector's prefabs: {error}"
1169                );
1170            }
1171        }
1172        let title = self.config.title.clone();
1173        let mut platform =
1174            Platform::new(&self.config.window()).map_err(|error| fatal(&title, error.into()))?;
1175        let graphics = match Device::new(platform.gpu_surface()) {
1176            Ok(mut device) => {
1177                let config = RenderConfig {
1178                    virtual_resolution: self.config.virtual_resolution,
1179                };
1180                let renderer = Renderer::new(&mut device, &config)
1181                    .map_err(|error| fatal(&title, error.into()))?;
1182                Some(Graphics { renderer, device })
1183            }
1184            Err(error) => {
1185                error!("no GPU device, so the game draws nothing: {error}");
1186                None
1187            }
1188        };
1189        // The stream stops as it drops, at the end of the block, so that the
1190        // sound stops before an error is shown.
1191        let result = {
1192            let _stream = self.start_audio();
1193            self.run_loop(&mut platform, graphics)
1194        };
1195        result.map_err(|error| fatal(&title, error))
1196    }
1197
1198    /// Opens the audio output with the mixer, if the app still holds it.
1199    /// `None`, after the log says why, where the game plays no sound.
1200    fn start_audio(&mut self) -> Option<AudioStream> {
1201        let Some(mixer) = self.mixer.take() else {
1202            info!(
1203                "the game plays no sound: its mixer was taken (App::take_mixer), or dropped by an \
1204                 App::update before App::run"
1205            );
1206            return None;
1207        };
1208        let config = AudioOutputConfig::default();
1209        match open_audio(&config, Box::new(MixerOutput(mixer))) {
1210            Ok(stream) => Some(stream),
1211            Err(error) => {
1212                warn!("no audio output, so the game plays no sound: {error}");
1213                None
1214            }
1215        }
1216    }
1217
1218    /// The main loop: events, then the frame and its ticks, then drawing.
1219    ///
1220    /// While the system runs an event loop of its own, as Windows does while
1221    /// the window is dragged and macOS while it is resized, the pump does not
1222    /// return. Frames then run from the modal frame callback, unpaced and
1223    /// undrawn: the system calls it every 10 to 16 ms on Windows, and once
1224    /// for each step of the resize on macOS. (Drawing there needs a surface
1225    /// in `ModalFrame`, roadmap M2.6 and M2.7.)
1226    fn run_loop(
1227        self,
1228        window: &mut dyn EventSource,
1229        graphics: Option<Graphics>,
1230    ) -> Result<(), Error> {
1231        debug!("the systems, in the order they run:");
1232        for system in self.schedule.describe() {
1233            debug!("  {system}");
1234        }
1235        #[cfg(feature = "dev")]
1236        let reload = graphics
1237            .is_some()
1238            .then(|| crate::hot_reload::HotReload::start(&self.world, &self.shader_dir));
1239        // The profiler shows the GPU's time over each frame's passes, read
1240        // back two frames later: every render is timed, from the first.
1241        #[cfg(feature = "dev")]
1242        let graphics = graphics.map(|mut graphics| {
1243            graphics.renderer.set_gpu_timing(true);
1244            graphics
1245        });
1246        let mut limiter = FrameLimiter::new(self.config.frame_rate_limit, Instant::now());
1247        let core = Rc::new(RefCell::new(EngineCore {
1248            app: self,
1249            stopwatch: Stopwatch::start(),
1250            graphics,
1251            error: None,
1252            #[cfg(feature = "dev")]
1253            allocs_at_frame_end: nadir_platform::thread_alloc_counts(),
1254            #[cfg(feature = "dev")]
1255            reload,
1256        }));
1257        let modal_core = Rc::clone(&core);
1258        window.set_modal_frame_callback(Box::new(move |_frame| {
1259            // The loop borrows the core only between pumps, and this runs
1260            // during one, so the borrow always succeeds.
1261            if let Ok(mut core) = modal_core.try_borrow_mut() {
1262                core.frame(&[], None);
1263            }
1264        }));
1265        let mut events = Vec::with_capacity(256);
1266        loop {
1267            window.pump_events(&mut events);
1268            if events.contains(&Event::CloseRequested) {
1269                break;
1270            }
1271            {
1272                let mut core = core.borrow_mut();
1273                let surface = window
1274                    .gpu_surface()
1275                    .map(|surface| (surface, window.window_size()));
1276                core.frame(&events, surface);
1277                if let Some(error) = core.error.take() {
1278                    return Err(error);
1279                }
1280                #[cfg(feature = "dev")]
1281                if core.app.debug.quit() {
1282                    info!("the console's `quit` ends the game");
1283                    break;
1284                }
1285            }
1286            events.clear();
1287
1288            if let Some(due) = limiter.end_of_frame(Instant::now()) {
1289                precise_sleep(due);
1290            }
1291        }
1292        Ok(())
1293    }
1294
1295    /// Draws the game offscreen, with no window, in frames of `size`
1296    /// pixels: [`Offscreen::frame`] runs a frame, draws it as a window of
1297    /// that size would show it, and returns its pixels. For recordings of
1298    /// the game, such as the demo page's (ADR-0029). It opens no log file.
1299    ///
1300    /// # Errors
1301    ///
1302    /// [`Error::Render`] where there is no offscreen OpenGL context
1303    /// ([`GfxError::NoOffscreenContext`](nadir_gfx::GfxError) on Windows
1304    /// and macOS, until roadmap M2.6 and M2.7) or it cannot be made, or the
1305    /// renderer or a target of `size` cannot be.
1306    pub fn offscreen(self, size: UVec2) -> Result<Offscreen, Error> {
1307        let mut device = Device::new_headless()?;
1308        let config = RenderConfig {
1309            virtual_resolution: self.config.virtual_resolution,
1310        };
1311        let renderer = Renderer::new(&mut device, &config)?;
1312        let target = device.create_render_target(size, TextureFormat::Rgba8Srgb)?;
1313        Ok(Offscreen {
1314            app: self,
1315            graphics: Graphics { renderer, device },
1316            target,
1317            size,
1318        })
1319    }
1320}
1321
1322/// A game drawn offscreen, a frame at a time, with no window. Made by
1323/// [`App::offscreen`].
1324pub struct Offscreen {
1325    // The app goes first, as in the main loop: its assets are the device's.
1326    app: App,
1327    graphics: Graphics,
1328    /// What each frame is drawn into.
1329    target: RenderTargetId,
1330    size: UVec2,
1331}
1332
1333impl Offscreen {
1334    /// Runs one frame that comes `elapsed` after the last, with the events
1335    /// that came before it, as [`App::update`] does. Then draws it as
1336    /// [`App::run`] does, waits for every asset loaded so far and makes it,
1337    /// and returns the frame's pixels: RGBA8, sRGB-encoded, from the top
1338    /// row, 4 bytes a pixel.
1339    ///
1340    /// Unlike [`App::run`], it waits for the asset server's workers, so that
1341    /// each frame shows every asset loaded before it, and a recording is the
1342    /// same each time. The assets loaded before the first frame are made
1343    /// after it is drawn, so it shows none of them. A first frame of
1344    /// [`Duration::ZERO`] makes them without a tick.
1345    ///
1346    /// # Errors
1347    ///
1348    /// [`Error::Render`] if the frame cannot be drawn or read back.
1349    pub fn frame(&mut self, elapsed: Duration, events: &[Event]) -> Result<Vec<u8>, Error> {
1350        #[cfg(feature = "dev")]
1351        {
1352            *self.app.world.resource_mut::<crate::WindowSize>() = crate::WindowSize(self.size);
1353        }
1354        self.app.update(elapsed, events);
1355        self.graphics
1356            .draw_offscreen(&self.app.world, self.target, self.size)
1357    }
1358
1359    /// The game.
1360    pub fn app(&self) -> &App {
1361        &self.app
1362    }
1363
1364    /// The size of each frame, in pixels.
1365    pub fn size(&self) -> UVec2 {
1366        self.size
1367    }
1368
1369    /// The renderer that draws the frames, as the driver names it: for
1370    /// instance `llvmpipe (LLVM 20.1.2, 256 bits)`.
1371    pub fn renderer(&self) -> &str {
1372        &self.graphics.device.caps().renderer
1373    }
1374}
1375
1376impl App {
1377    /// After a replayed tick: if it was the replay's last, or the next
1378    /// cannot be read, says so in [`Replay`] and lets the live input latch
1379    /// from the next tick on.
1380    fn end_replay_tick(&mut self) {
1381        let Some(replay) = &self.actions.replay else {
1382            return;
1383        };
1384        let ticks = replay.ticks();
1385        let status = match replay.ahead() {
1386            Ok(true) => return,
1387            Ok(false) => Replay::Ended { ticks },
1388            Err(error) => failed(ticks, error),
1389        };
1390        *self.world.resource_mut::<Replay>() = status;
1391        self.actions.replay = None;
1392    }
1393}
1394
1395/// [`Replay::Failed`] after `ticks` ticks, logged.
1396fn failed(ticks: u64, error: &nadir_input::InputError) -> Replay {
1397    error!(
1398        "the replay's tick {} cannot be read: {error}; the input is live from now on",
1399        ticks + 1
1400    );
1401    Replay::Failed {
1402        ticks,
1403        error: error.clone(),
1404    }
1405}
1406
1407/// How long the simulation has run, as a frame shows it: the ticks so far
1408/// and the `alpha` of a tick more. Whatever slows or stops the clock slows
1409/// or stops what follows this, such as animated tiles.
1410fn simulated_time(clock: &FixedClock) -> Duration {
1411    let hz = u128::from(TICK_HZ);
1412    let ticks = u128::from(clock.ticks()) * 1_000_000_000 / hz;
1413    let part = (f64::from(clock.alpha()) * 1e9 / TICK_HZ as f64) as u128;
1414    Duration::from_nanos(u64::try_from(ticks + part).unwrap_or(u64::MAX))
1415}
1416
1417/// Logs an error that ends the game and shows it to the player. Returns it,
1418/// for [`App::run`] to return.
1419fn fatal(title: &str, error: Error) -> Error {
1420    error!("{error}");
1421    show_error_dialog(title, &error.to_string());
1422    error
1423}
1424
1425#[cfg(test)]
1426mod tests {
1427    use std::cell::{Cell, RefCell};
1428    use std::thread;
1429
1430    use nadir_core::time::{Frame, Tick};
1431    use nadir_core::{Key, Vec2};
1432    use nadir_ecs::Entity;
1433    use nadir_input::{Binding, InputRecorder};
1434
1435    use super::*;
1436
1437    /// One tick's length, as a frame: it runs one tick.
1438    const TICK: Duration = Duration::from_nanos(16_666_667);
1439    const MS: Duration = Duration::from_millis(1);
1440
1441    fn app() -> App {
1442        App::new(Config::default())
1443    }
1444
1445    /// What the systems of a test saw, shared with the test through a
1446    /// resource, so that it outlives an app that the loop consumed.
1447    #[derive(Default)]
1448    struct Log {
1449        ticks: Cell<u64>,
1450        frames: Cell<u64>,
1451        seen: RefCell<Vec<String>>,
1452        values: RefCell<Vec<f32>>,
1453    }
1454
1455    type Shared = Rc<Log>;
1456
1457    fn shared() -> Shared {
1458        Rc::default()
1459    }
1460
1461    fn count_ticks(world: &World, _: &Tick) {
1462        let log = world.resource::<Shared>();
1463        log.ticks.set(log.ticks.get() + 1);
1464    }
1465
1466    fn count_frames(world: &World, _: &Frame) {
1467        let log = world.resource::<Shared>();
1468        log.frames.set(log.frames.get() + 1);
1469    }
1470
1471    /// An app whose systems count ticks and frames into `log`.
1472    fn counting_app(log: &Shared) -> App {
1473        app()
1474            .insert_resource(Rc::clone(log))
1475            .add_fixed_system(FixedStage::Gameplay, "count_ticks", count_ticks)
1476            .add_frame_system(FrameStage::Ui, "count_frames", count_frames)
1477    }
1478
1479    /// Runs frames of one length until `total` has passed.
1480    fn simulate(app: &mut App, frame_length: Duration, total: Duration) {
1481        let mut passed = Duration::ZERO;
1482        while passed < total {
1483            let step = frame_length.min(total - passed);
1484            app.update(step, &[]);
1485            passed += step;
1486        }
1487    }
1488
1489    // -- configuration ------------------------------------------------------
1490
1491    #[test]
1492    fn the_default_configuration_is_a_resizable_window_at_60_frames() {
1493        let config = Config::default();
1494        assert_eq!(config.title, "Nadir");
1495        assert_eq!(config.studio, "Nadir");
1496        assert_eq!(config.game, "Nadir");
1497        assert_eq!(config.window_size, UVec2::new(1280, 720));
1498        assert_eq!(config.min_window_size, UVec2::new(320, 180));
1499        assert!(config.resizable);
1500        assert!(!config.fullscreen);
1501        assert_eq!(config.frame_rate_limit, Some(60));
1502        assert!(config.vsync);
1503        assert_eq!(config.virtual_resolution, UVec2::new(480, 270));
1504        assert_eq!(config.assets, PathBuf::from("assets"));
1505        for bus in Bus::ALL {
1506            assert_eq!(config.volumes.get(bus), 100, "{bus:?}");
1507            assert_eq!(config.volumes.gain(bus), 1.0, "{bus:?}");
1508        }
1509    }
1510
1511    #[test]
1512    fn a_volume_is_heard_as_its_square_and_held_to_100() {
1513        let mut volumes = Volumes::default();
1514        volumes.set(Bus::Music, 50);
1515        volumes.set(Bus::Ui, 0);
1516        volumes.set(Bus::Ambience, 250);
1517        assert_eq!(
1518            volumes,
1519            Volumes {
1520                music: 50,
1521                sfx: 100,
1522                ui: 0,
1523                ambience: 250
1524            }
1525        );
1526        // 50 is a quarter of the gain: −12 dB.
1527        assert_eq!(volumes.gain(Bus::Music), 0.25);
1528        assert_eq!(volumes.gain(Bus::Ui), 0.0);
1529        assert_eq!(volumes.gain(Bus::Ambience), 1.0);
1530        assert_eq!(volumes.get(Bus::Ambience), 250);
1531    }
1532
1533    #[test]
1534    fn the_window_is_the_one_the_configuration_asks_for() {
1535        let config = Config {
1536            title: "Sandbox".to_string(),
1537            studio: "Studio".to_string(),
1538            game: "Game".to_string(),
1539            window_size: UVec2::new(960, 540),
1540            min_window_size: UVec2::new(480, 270),
1541            resizable: false,
1542            fullscreen: true,
1543            frame_rate_limit: None,
1544            vsync: false,
1545            virtual_resolution: UVec2::new(320, 180),
1546            assets: PathBuf::from("data"),
1547            volumes: Volumes {
1548                music: 60,
1549                sfx: 80,
1550                ui: 100,
1551                ambience: 40,
1552            },
1553        };
1554        let expected = WindowConfig {
1555            title: "Sandbox".to_string(),
1556            size: UVec2::new(960, 540),
1557            min_size: UVec2::new(480, 270),
1558            resizable: false,
1559            fullscreen: true,
1560            vsync: false,
1561        };
1562        assert_eq!(config.window(), expected);
1563    }
1564
1565    // -- the schedule and the world -----------------------------------------
1566
1567    #[test]
1568    fn the_schedule_prints_the_engines_systems_first_in_their_stages() {
1569        let app = app()
1570            .add_frame_system(FrameStage::Extract, "draw_ground", |_, _| {})
1571            .add_fixed_system(FixedStage::Movement, "bounce", |_, _| {})
1572            .add_fixed_system(FixedStage::Gameplay, "walk", |_, _| {})
1573            .add_frame_system(FrameStage::Camera, "follow", |_, _| {})
1574            .add_frame_system(FrameStage::Animate, "react", |_, _| {});
1575        let printed: Vec<String> = app
1576            .schedule()
1577            .describe()
1578            .map(|system| system.to_string())
1579            .collect();
1580        assert_eq!(
1581            printed,
1582            [
1583                "tick  Input: nadir::snapshot",
1584                "tick  Gameplay: walk",
1585                "tick  Movement: nadir::movement",
1586                "tick  Movement: bounce",
1587                "tick  PostMovement: nadir::parent_offsets",
1588                "tick  PostMovement: nadir::triggers",
1589                "frame Animate: nadir::animate",
1590                "frame Animate: react",
1591                "frame Camera: follow",
1592                "frame Extract: nadir::sound",
1593                "frame Extract: nadir::extract_sprites",
1594                "frame Extract: nadir::extract_level",
1595                "frame Extract: draw_ground",
1596            ]
1597        );
1598    }
1599
1600    #[test]
1601    fn the_engines_components_are_registered_and_eight_are_reflected() {
1602        let app = app();
1603        let world = app.world();
1604        assert!(world.is_registered::<Transform>());
1605        assert!(world.is_registered::<PrevTransform>());
1606        assert!(world.is_registered::<Velocity>());
1607        assert!(world.is_registered::<Sprite>());
1608        assert!(world.is_registered::<Collider>());
1609        assert!(world.is_registered::<Player>());
1610        assert!(world.is_registered::<Parent>());
1611        assert!(world.is_registered::<SaveId>());
1612        assert!(world.is_registered::<Facing>());
1613        assert!(world.is_registered::<Animator>());
1614        assert!(world.is_registered::<AudioListener>());
1615        assert!(world.is_registered::<AudioEmitter>());
1616        assert!(world.is_registered::<MusicArea>());
1617        let registry = world.resource::<TypeRegistry>();
1618        let names: Vec<&str> = registry.iter().map(|it| it.name()).collect();
1619        assert_eq!(
1620            names,
1621            [
1622                "Transform",
1623                "Velocity",
1624                "Player",
1625                "SaveId",
1626                "Facing",
1627                "Sprite",
1628                "Collider",
1629                "Animator"
1630            ]
1631        );
1632        // The engine's own, the prefabs a game loads, no level yet, and
1633        // the mixer's handle, with no music sent.
1634        assert!(world.contains_resource::<CollisionLayers>());
1635        assert!(world.contains_resource::<PrefabLibrary>());
1636        assert_eq!(world.resource::<CurrentLevel>().name(), None);
1637        assert!(world.contains_resource::<nadir_audio::Audio>());
1638        assert_eq!(world.resource::<AudioState>().music_area(), None);
1639    }
1640
1641    nadir_scene::reflect_newtype! {
1642        #[derive(Clone, Copy, Debug, Default, PartialEq)]
1643        struct Score(u32);
1644    }
1645
1646    impl Component for Score {}
1647
1648    #[test]
1649    fn a_game_registers_its_reflected_components_and_events() {
1650        #[derive(Clone)]
1651        struct Scored;
1652        let mut app = app()
1653            .register_component::<Score>()
1654            .add_event::<Scored>()
1655            .add_fixed_system(FixedStage::Gameplay, "score", |world, _| {
1656                world
1657                    .resource_mut::<nadir_ecs::Events<Scored>>()
1658                    .send(Scored);
1659            });
1660        assert!(
1661            app.world()
1662                .resource::<TypeRegistry>()
1663                .get("Score")
1664                .is_some()
1665        );
1666        let entity = app.world_mut().spawn().with(Score(3)).id();
1667        assert_eq!(app.world().read::<Score>().get(entity), Some(&Score(3)));
1668        app.update(TICK, &[]);
1669        let events = app.world().resource::<nadir_ecs::Events<Scored>>();
1670        assert_eq!(events.frame_events().len(), 0, "cleared after the frame");
1671    }
1672
1673    // -- one frame ----------------------------------------------------------
1674
1675    fn note(world: &World, text: String) {
1676        world.resource::<Shared>().seen.borrow_mut().push(text);
1677    }
1678
1679    #[test]
1680    fn a_frame_runs_its_ticks_and_then_its_frame_stages_in_order() {
1681        let log = shared();
1682        let mut app = app()
1683            .insert_resource(Rc::clone(&log))
1684            .add_fixed_system(FixedStage::Gameplay, "a", |world, tick| {
1685                note(world, format!("a tick {}", tick.index));
1686            })
1687            .add_frame_system(FrameStage::Ui, "c", |world, _| note(world, "c".into()))
1688            .add_fixed_system(FixedStage::Input, "b", |world, tick| {
1689                note(world, format!("b tick {}", tick.index));
1690            })
1691            .add_frame_system(FrameStage::Camera, "d", |world, _| note(world, "d".into()));
1692        // 40 ms hold two ticks.
1693        app.update(40 * MS, &[]);
1694        assert_eq!(
1695            *log.seen.borrow(),
1696            ["b tick 0", "a tick 0", "b tick 1", "a tick 1", "d", "c"]
1697        );
1698    }
1699
1700    #[test]
1701    fn a_frame_shorter_than_a_tick_still_runs_the_frame_stages() {
1702        let log = shared();
1703        let mut app = counting_app(&log);
1704        app.update(5 * MS, &[]);
1705        app.update(5 * MS, &[]);
1706        assert_eq!((log.ticks.get(), log.frames.get()), (0, 2));
1707        app.update(10 * MS, &[]);
1708        assert_eq!((log.ticks.get(), log.frames.get()), (1, 3));
1709    }
1710
1711    #[test]
1712    fn systems_get_the_tick_length_and_the_frame_time() {
1713        let log = shared();
1714        let mut app = app()
1715            .insert_resource(Rc::clone(&log))
1716            .add_fixed_system(FixedStage::Gameplay, "tick", |world, tick| {
1717                let log = world.resource::<Shared>();
1718                log.values.borrow_mut().push(tick.dt);
1719            })
1720            .add_frame_system(FrameStage::Ui, "frame", |world, frame| {
1721                let log = world.resource::<Shared>();
1722                log.values.borrow_mut().extend([frame.dt, frame.alpha]);
1723            });
1724        app.update(20 * MS, &[]);
1725        let values = log.values.borrow();
1726        assert_eq!(values[..2], [1.0 / 60.0, 0.02]);
1727        // 20 ms is one tick of 16.67 ms and a fifth of the next.
1728        assert!((values[2] - 0.2).abs() < 1e-6, "{values:?}");
1729    }
1730
1731    #[test]
1732    fn tick_stats_count_this_frames_ticks_for_its_frame_stages() {
1733        let log = shared();
1734        let mut app = app()
1735            .insert_resource(Rc::clone(&log))
1736            .add_fixed_system(FixedStage::Gameplay, "slow", |_, tick| {
1737                if tick.index == 1 {
1738                    thread::sleep(3 * MS);
1739                }
1740            })
1741            .add_frame_system(FrameStage::Ui, "read", |world, _| {
1742                let stats = *world.resource::<TickStats>();
1743                note(world, format!("{}", stats.ticks));
1744            });
1745        app.update(40 * MS, &[]);
1746        let two = *app.world().resource::<TickStats>();
1747        assert_eq!(two.ticks, 2);
1748        assert!(two.longest >= 3 * MS && two.time >= two.longest, "{two:?}");
1749        app.update(5 * MS, &[]);
1750        assert_eq!(*app.world().resource::<TickStats>(), TickStats::default());
1751        assert_eq!(*log.seen.borrow(), ["2", "0"]);
1752    }
1753
1754    // -- the tick rate ------------------------------------------------------
1755
1756    #[test]
1757    fn the_frame_time_is_how_long_the_simulation_has_run() {
1758        let mut app = app();
1759        // A quarter of a tick: no tick yet.
1760        app.update(TICK / 4, &[]);
1761        let time = |app: &App| app.world().resource::<RenderFrame>().time;
1762        let close = |found: Duration, expected: Duration| {
1763            assert!(
1764                found.abs_diff(expected) < Duration::from_micros(1),
1765                "{found:?}, not {expected:?}"
1766            );
1767        };
1768        close(time(&app), TICK / 4);
1769        for _ in 0..3 {
1770            app.update(TICK, &[]);
1771        }
1772        close(time(&app), TICK * 3 + TICK / 4);
1773        // A hitch counts for a quarter of a second, as the ticks do.
1774        app.update(Duration::from_secs(5), &[]);
1775        close(time(&app), TICK * 3 + TICK / 4 + Duration::from_millis(250));
1776        // Emptying the frame for the next leaves the time to the engine.
1777        app.world().resource_mut::<RenderFrame>().clear();
1778        assert!(time(&app) > Duration::ZERO);
1779    }
1780
1781    #[test]
1782    fn ten_seconds_run_600_ticks_whatever_the_frame_rate() {
1783        let frame_lengths = [
1784            TICK,                            // 60 frames a second
1785            Duration::from_nanos(6_944_444), // 144
1786            Duration::from_micros(33_333),   // 30
1787            Duration::from_millis(3),
1788            Duration::from_millis(110),
1789        ];
1790        for frame_length in frame_lengths {
1791            let log = shared();
1792            let mut app = counting_app(&log);
1793            simulate(&mut app, frame_length, Duration::from_secs(10));
1794            // The task asks for 60 Hz within 1%. The clock is exact.
1795            assert_eq!(log.ticks.get(), 600, "frames of {frame_length:?}");
1796            assert!(log.frames.get() >= 90, "frames of {frame_length:?}");
1797        }
1798    }
1799
1800    #[test]
1801    fn a_simulated_hitch_runs_a_quarter_second_of_ticks_and_no_more() {
1802        let log = shared();
1803        let mut app = counting_app(&log);
1804        simulate(&mut app, 10 * MS, Duration::from_secs(1));
1805        assert_eq!(log.ticks.get(), 60);
1806
1807        // One frame takes a whole second.
1808        app.update(Duration::from_secs(1), &[]);
1809        assert_eq!(log.ticks.get(), 60 + 15);
1810
1811        // Nothing is owed afterwards: the next second is an ordinary one.
1812        simulate(&mut app, 10 * MS, Duration::from_secs(1));
1813        assert_eq!(log.ticks.get(), 60 + 15 + 60);
1814    }
1815
1816    // -- the loop -----------------------------------------------------------
1817
1818    /// A window that reports a few events and asks to close when its script
1819    /// says so. During a pump, it can also hold the loop as a system's own
1820    /// event loop does, and run modal frames.
1821    struct Script {
1822        pumps: u32,
1823        close: Box<dyn FnMut(u32) -> bool>,
1824        asked_to_close: bool,
1825        /// How many modal frames to run during the pump of this number.
1826        modal_frames: Box<dyn FnMut(u32) -> u32>,
1827        modal_frame_callback: Option<Box<dyn FnMut(ModalFrame)>>,
1828    }
1829
1830    impl Script {
1831        fn closing_when(close: impl FnMut(u32) -> bool + 'static) -> Self {
1832            Self {
1833                pumps: 0,
1834                close: Box::new(close),
1835                asked_to_close: false,
1836                modal_frames: Box::new(|_| 0),
1837                modal_frame_callback: None,
1838            }
1839        }
1840
1841        fn with_modal_frames(mut self, modal_frames: impl FnMut(u32) -> u32 + 'static) -> Self {
1842            self.modal_frames = Box::new(modal_frames);
1843            self
1844        }
1845    }
1846
1847    impl EventSource for Script {
1848        fn pump_events(&mut self, out: &mut Vec<Event>) {
1849            // A loop that missed the request would never end. Fail instead.
1850            assert!(!self.asked_to_close, "the loop went on after a close");
1851            self.pumps += 1;
1852            let frame = ModalFrame {
1853                size: UVec2::new(800, 600),
1854                scale_factor: 1.0,
1855            };
1856            for _ in 0..(self.modal_frames)(self.pumps) {
1857                let callback = self.modal_frame_callback.as_mut();
1858                (callback.expect("the loop set a modal frame callback"))(frame);
1859            }
1860            // Other events do not end the loop.
1861            out.push(Event::Focused(true));
1862            out.push(Event::Resized(UVec2::new(800, 600)));
1863            if (self.close)(self.pumps) {
1864                self.asked_to_close = true;
1865                out.push(Event::CloseRequested);
1866            }
1867        }
1868
1869        fn set_modal_frame_callback(&mut self, callback: Box<dyn FnMut(ModalFrame)>) {
1870            self.modal_frame_callback = Some(callback);
1871        }
1872    }
1873
1874    #[test]
1875    fn the_loop_runs_until_the_window_asks_to_close() {
1876        let log = shared();
1877        let mut app = counting_app(&log);
1878        app.config.frame_rate_limit = None;
1879        let mut window = Script::closing_when(|pumps| pumps == 8);
1880        app.run_loop(&mut window, None)
1881            .expect("no error without a device");
1882        // Seven frames ran, and the eighth pump ended the loop before its
1883        // frame.
1884        assert_eq!(window.pumps, 8);
1885        assert_eq!(log.frames.get(), 7);
1886    }
1887
1888    #[test]
1889    fn a_close_request_on_the_first_pump_runs_no_frame() {
1890        let log = shared();
1891        let app = counting_app(&log);
1892        app.run_loop(&mut Script::closing_when(|_| true), None)
1893            .expect("no error without a device");
1894        assert_eq!((log.ticks.get(), log.frames.get()), (0, 0));
1895    }
1896
1897    #[test]
1898    fn while_the_system_holds_the_loop_frames_run_from_the_callback() {
1899        let log = shared();
1900        let mut app = counting_app(&log);
1901        app.config.frame_rate_limit = None;
1902        // The second pump holds the loop for five modal frames, as a drag
1903        // of the window does on Windows.
1904        let mut window = Script::closing_when(|pumps| pumps == 3)
1905            .with_modal_frames(|pumps| if pumps == 2 { 5 } else { 0 });
1906        app.run_loop(&mut window, None)
1907            .expect("no error without a device");
1908        // One frame after the first pump, five during the second and one
1909        // after it, and none after the third.
1910        assert_eq!(log.frames.get(), 7);
1911    }
1912
1913    #[test]
1914    fn modal_frames_keep_the_simulation_on_time() {
1915        let log = shared();
1916        let mut app = counting_app(&log)
1917            .add_frame_system(FrameStage::Ui, "wait", |_, _| thread::sleep(10 * MS));
1918        app.config.frame_rate_limit = None;
1919        // The first pump holds the loop for 300 ms or more, in modal frames
1920        // of at least 10 ms.
1921        let start = Instant::now();
1922        let mut window = Script::closing_when(|pumps| pumps == 2)
1923            .with_modal_frames(|pumps| if pumps == 1 { 30 } else { 0 });
1924        app.run_loop(&mut window, None)
1925            .expect("no error without a device");
1926        let elapsed = start.elapsed();
1927        assert_eq!(log.frames.get(), 30 + 1);
1928        // The ticks kept up with real time while the loop was held: 60 a
1929        // second for 300 ms is 18, less one for rounding. Without modal
1930        // frames, the frame after the hold would have counted only a
1931        // quarter of a second: 15.
1932        let ticks = log.ticks.get();
1933        assert!(ticks >= 17, "{ticks} ticks in {elapsed:?}");
1934    }
1935
1936    #[test]
1937    fn the_limiter_paces_the_loop() {
1938        let log = shared();
1939        let mut app = counting_app(&log);
1940        app.config.frame_rate_limit = Some(200);
1941        let start = Instant::now();
1942        app.run_loop(&mut Script::closing_when(|pumps| pumps == 21), None)
1943            .expect("no error without a device");
1944        // Twenty frames of 5 ms each. A busy machine can make them longer,
1945        // but nothing makes them shorter.
1946        assert_eq!(log.frames.get(), 20);
1947        assert!(
1948            start.elapsed() >= Duration::from_millis(100),
1949            "{:?}",
1950            start.elapsed()
1951        );
1952    }
1953
1954    /// What the hitch test's systems saw.
1955    #[derive(Default)]
1956    struct Hitch {
1957        /// Each frame's ticks and `dt`.
1958        frames: RefCell<Vec<(u32, f32)>>,
1959        ticks_this_frame: Cell<u32>,
1960        stalled: Cell<bool>,
1961        frames_since_stall: Cell<u32>,
1962    }
1963
1964    #[test]
1965    fn a_real_hitch_of_one_second_is_clamped_and_does_not_spiral() {
1966        let hitch: Rc<Hitch> = Rc::default();
1967        let app = app()
1968            .insert_resource(Rc::clone(&hitch))
1969            .add_fixed_system(FixedStage::Gameplay, "stall_once", |world, tick| {
1970                let hitch = world.resource::<Rc<Hitch>>();
1971                hitch.ticks_this_frame.set(hitch.ticks_this_frame.get() + 1);
1972                // The hitch: the third tick takes a second.
1973                if tick.index == 2 {
1974                    thread::sleep(Duration::from_secs(1));
1975                    hitch.stalled.set(true);
1976                }
1977            })
1978            .add_frame_system(FrameStage::Ui, "record", |world, frame| {
1979                let hitch = world.resource::<Rc<Hitch>>();
1980                let ticks = hitch.ticks_this_frame.take();
1981                hitch.frames.borrow_mut().push((ticks, frame.dt));
1982                if hitch.stalled.get() {
1983                    hitch
1984                        .frames_since_stall
1985                        .set(hitch.frames_since_stall.get() + 1);
1986                }
1987            });
1988
1989        // Run on for a few frames after the one that stalled. If the stall
1990        // never comes, give up after ten seconds of frames, so that a bug
1991        // fails this test and does not hang it.
1992        let start = Instant::now();
1993        let script = Rc::clone(&hitch);
1994        app.run_loop(
1995            &mut Script::closing_when(move |pumps| {
1996                script.frames_since_stall.get() > 6 || pumps > 600
1997            }),
1998            None,
1999        )
2000        .expect("no error without a device");
2001        let elapsed = start.elapsed();
2002        assert!(hitch.stalled.get(), "the stall never happened");
2003
2004        let frames = hitch.frames.borrow();
2005        let most_ticks = frames.iter().map(|&(ticks, _)| ticks).max();
2006        let longest_dt = frames.iter().map(|&(_, dt)| dt).fold(0.0, f32::max);
2007        let total_ticks: u32 = frames.iter().map(|&(ticks, _)| ticks).sum();
2008
2009        // The frame after the stall saw a second go by. It counted a
2010        // quarter of one: 15 ticks. Unclamped, it would have run 60.
2011        assert_eq!(most_ticks, Some(15), "{frames:?}");
2012        assert_eq!(longest_dt, 0.25, "{frames:?}");
2013
2014        // And the loop did not try to win the lost time back later: over
2015        // the whole run, the ticks stay at least three quarters of a second
2016        // behind real time.
2017        let behind = elapsed.as_secs_f64() - f64::from(total_ticks) / 60.0;
2018        assert!(
2019            behind >= 0.74,
2020            "{behind} s behind after {elapsed:?}: {frames:?}"
2021        );
2022    }
2023
2024    // -- actions, movement and drawing ----------------------------------------
2025
2026    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
2027    enum Act {
2028        Move,
2029    }
2030
2031    impl ActionSet for Act {
2032        const ALL: &'static [Self] = &[Act::Move];
2033
2034        fn index(self) -> usize {
2035            self as usize
2036        }
2037
2038        fn name(self) -> &'static str {
2039            "move"
2040        }
2041
2042        fn kind(self) -> ActionKind {
2043            ActionKind::Axis2
2044        }
2045    }
2046
2047    /// Pixels a second: two a tick.
2048    const SPEED: f32 = 120.0;
2049
2050    /// The entity that moves.
2051    struct Mover(Entity);
2052
2053    /// A texture handle, which nothing loads.
2054    fn texture() -> nadir_assets::Handle<nadir_render::Texture> {
2055        nadir_assets::Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN))
2056    }
2057
2058    /// An app that moves an entity with `Act::Move`, bound to WASD, and
2059    /// notes in `log` where each frame draws it.
2060    fn moving_app(log: &Shared) -> App {
2061        let mut map = ActionMap::<Act>::new().expect("a valid set");
2062        let wasd = Binding::KeyComposite2 {
2063            up: Key::W,
2064            down: Key::S,
2065            left: Key::A,
2066            right: Key::D,
2067        };
2068        map.bind(Act::Move, 0, wasd).expect("fits");
2069        let mut app = app()
2070            .add_actions(map)
2071            .insert_resource(Rc::clone(log))
2072            .add_fixed_system(FixedStage::Gameplay, "steer", |world, _| {
2073                let direction = world.resource::<ActionState<Act>>().axis2(Act::Move);
2074                let mover = world.resource::<Mover>().0;
2075                if let Some(velocity) = world.write::<Velocity>().get_mut(mover) {
2076                    velocity.0 = direction * SPEED;
2077                }
2078            })
2079            .add_frame_system(FrameStage::Extract, "record", |world, _| {
2080                let x = world.resource::<RenderFrame>().sprites[0].position.x;
2081                world.resource::<Shared>().values.borrow_mut().push(x);
2082            });
2083        let mover = app
2084            .world_mut()
2085            .spawn()
2086            .with(Transform::at(Vec2::ZERO))
2087            .with(Velocity::default())
2088            .with(Sprite::new(texture(), Vec2::splat(8.0)))
2089            .id();
2090        app.insert_resource(Mover(mover))
2091    }
2092
2093    fn key(key: Key, pressed: bool) -> Event {
2094        Event::Key {
2095            key,
2096            pressed,
2097            repeat: false,
2098        }
2099    }
2100
2101    fn x(app: &App) -> f32 {
2102        let mover = app.world().resource::<Mover>().0;
2103        app.world()
2104            .read::<Transform>()
2105            .get(mover)
2106            .expect("it is")
2107            .position
2108            .x
2109    }
2110
2111    #[test]
2112    fn a_tap_between_ticks_moves_exactly_one_tick() {
2113        let mut app = moving_app(&shared());
2114        // D goes down and up within a frame too short for a tick.
2115        app.update(5 * MS, &[key(Key::D, true), key(Key::D, false)]);
2116        assert_eq!(x(&app), 0.0, "no tick yet");
2117        // The next frame's tick moves it once.
2118        app.update(12 * MS, &[]);
2119        assert_eq!(x(&app), SPEED / 60.0);
2120        for _ in 0..10 {
2121            app.update(16 * MS, &[]);
2122        }
2123        assert_eq!(x(&app), SPEED / 60.0, "and never again");
2124        // In a frame of two ticks, the second sees no edge either.
2125        app.update(34 * MS, &[key(Key::D, true), key(Key::D, false)]);
2126        assert_eq!(x(&app), 2.0 * SPEED / 60.0);
2127    }
2128
2129    #[test]
2130    fn a_held_key_moves_every_tick() {
2131        let mut app = moving_app(&shared());
2132        app.update(Duration::ZERO, &[key(Key::D, true)]);
2133        // Exactly a second of 60 Hz frames: sixty ticks.
2134        for _ in 0..60 {
2135            app.update(TICK, &[]);
2136        }
2137        assert!((x(&app) - SPEED).abs() < 1e-3, "{}", x(&app));
2138        app.update(Duration::ZERO, &[key(Key::D, false)]);
2139        app.update(20 * MS, &[]);
2140        assert!((x(&app) - SPEED).abs() < 1e-3, "it stops: {}", x(&app));
2141    }
2142
2143    #[test]
2144    fn the_wheel_moves_on_each_tick_without_an_action_set() {
2145        let log = shared();
2146        let mut app = app().insert_resource(Rc::clone(&log)).add_fixed_system(
2147            FixedStage::Input,
2148            "zoom",
2149            |world, _| {
2150                let wheel = world.resource::<Input>().wheel();
2151                world.resource::<Shared>().values.borrow_mut().push(wheel.y);
2152            },
2153        );
2154        // A tick each.
2155        app.update(20 * MS, &[Event::MouseWheel(Vec2::new(0.0, 3.0))]);
2156        app.update(20 * MS, &[]);
2157        assert_eq!(*log.values.borrow(), [3.0, 0.0]);
2158    }
2159
2160    #[test]
2161    fn interpolation_draws_where_the_mover_was_one_tick_ago_at_any_frame_rate() {
2162        // Held from the start, the mover is drawn at SPEED · (t − 1/60): one
2163        // tick behind the clock, so every frame moves it by its own length,
2164        // whatever that is.
2165        let mut irregular = nadir_core::Pcg32::new(7, 1);
2166        let rates: [(&str, Vec<Duration>); 5] = [
2167            ("60", vec![TICK; 120]),
2168            ("59.94", vec![Duration::from_nanos(16_683_350); 120]),
2169            ("144", vec![Duration::from_nanos(6_944_444); 288]),
2170            ("1 ms", vec![MS; 2000]),
2171            (
2172                "irregular",
2173                (0..500)
2174                    .map(|_| Duration::from_micros(u64::from(irregular.range(1000..9000u32))))
2175                    .collect(),
2176            ),
2177        ];
2178        for (name, frames) in rates {
2179            let log = shared();
2180            let mut app = moving_app(&log);
2181            app.update(Duration::ZERO, &[key(Key::D, true)]);
2182            let mut t = Duration::ZERO;
2183            let mut expected = vec![0.0];
2184            for frame in frames {
2185                app.update(frame, &[]);
2186                t += frame;
2187                let x = SPEED as f64 * (t.as_secs_f64() - 1.0 / 60.0).max(0.0);
2188                expected.push(x);
2189            }
2190            let drawn = log.values.borrow();
2191            assert_eq!(drawn.len(), expected.len(), "{name}");
2192            for (i, (&drawn, &expected)) in drawn.iter().zip(&expected).enumerate() {
2193                assert!(
2194                    (f64::from(drawn) - expected).abs() < 2e-3,
2195                    "{name}: frame {i} drew {drawn}, not {expected}"
2196                );
2197            }
2198        }
2199    }
2200
2201    #[test]
2202    #[should_panic(expected = "an App has one action set")]
2203    fn a_second_action_set_is_refused() {
2204        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
2205        enum Menu {
2206            Back,
2207        }
2208
2209        impl ActionSet for Menu {
2210            const ALL: &'static [Self] = &[Menu::Back];
2211
2212            fn index(self) -> usize {
2213                0
2214            }
2215
2216            fn name(self) -> &'static str {
2217                "back"
2218            }
2219
2220            fn kind(self) -> ActionKind {
2221                ActionKind::Button
2222            }
2223        }
2224
2225        let map = ActionMap::<Menu>::new().expect("a valid set");
2226        let _ = moving_app(&shared()).add_actions(map);
2227    }
2228
2229    #[test]
2230    fn the_same_action_set_again_replaces_its_bindings() {
2231        let mut map = ActionMap::<Act>::new().expect("a valid set");
2232        let arrows = Binding::KeyComposite2 {
2233            up: Key::Up,
2234            down: Key::Down,
2235            left: Key::Left,
2236            right: Key::Right,
2237        };
2238        map.bind(Act::Move, 0, arrows).expect("fits");
2239        let mut app = moving_app(&shared()).add_actions(map);
2240        app.update(20 * MS, &[key(Key::D, true)]);
2241        assert_eq!(x(&app), 0.0, "D is no longer bound");
2242        app.update(20 * MS, &[key(Key::Right, true)]);
2243        assert_eq!(x(&app), SPEED / 60.0, "one latch a tick, with the new map");
2244    }
2245
2246    // -- replays ----------------------------------------------------------------
2247
2248    /// The replay of a run of `moving_app` that gets `frames`' events, a
2249    /// frame of one tick each.
2250    fn recording(frames: &[&[Event]]) -> &'static [u8] {
2251        let mut app = moving_app(&shared())
2252            .insert_resource(InputRecorder::<Act>::new().expect("a valid set"))
2253            .add_fixed_system(FixedStage::Input, "record", |world, _| {
2254                let state = world.resource::<ActionState<Act>>();
2255                world.resource_mut::<InputRecorder<Act>>().record(&state);
2256            });
2257        for events in frames {
2258            app.update(TICK, events);
2259        }
2260        let bytes = app
2261            .world()
2262            .resource::<InputRecorder<Act>>()
2263            .bytes()
2264            .to_vec();
2265        Box::leak(bytes.into_boxed_slice())
2266    }
2267
2268    fn replaying(bytes: &'static [u8]) -> App {
2269        let player = InputPlayer::<Act>::new(bytes).expect("a replay of Act");
2270        moving_app(&shared()).play_replay(player)
2271    }
2272
2273    fn replay(app: &App) -> Replay {
2274        app.world().resource::<Replay>().clone()
2275    }
2276
2277    /// `Act::Move`'s held, just pressed and just released, in the last tick.
2278    fn moving(app: &App) -> (bool, bool, bool) {
2279        let state = app.world().resource::<ActionState<Act>>();
2280        (
2281            state.pressed(Act::Move),
2282            state.just_pressed(Act::Move),
2283            state.just_released(Act::Move),
2284        )
2285    }
2286
2287    /// One tick's move at [`SPEED`].
2288    const STEP: f32 = SPEED / 60.0;
2289
2290    #[test]
2291    fn a_replay_moves_as_the_recording_did_whatever_the_live_input() {
2292        let bytes = recording(&[&[key(Key::D, true)], &[], &[]]);
2293        let mut app = replaying(bytes);
2294        assert_eq!(replay(&app), Replay::Playing { ticks: 0 });
2295        // Live input that the recording did not have. Losing the focus
2296        // releases every key, so A goes down after it.
2297        let noise = [
2298            Event::Focused(false),
2299            Event::MouseWheel(Vec2::new(0.0, 3.0)),
2300            Event::MouseMoved(Vec2::new(5.0, 5.0)),
2301            key(Key::A, true),
2302        ];
2303        app.update(TICK, &noise);
2304        assert_eq!(
2305            (x(&app), replay(&app)),
2306            (STEP, Replay::Playing { ticks: 1 })
2307        );
2308        assert_eq!(moving(&app), (true, true, false));
2309        app.update(TICK, &[]);
2310        assert_eq!(replay(&app), Replay::Playing { ticks: 2 });
2311        // The last tick: ended as soon as it has run.
2312        app.update(TICK, &[]);
2313        assert_eq!(
2314            (x(&app), replay(&app)),
2315            (3.0 * STEP, Replay::Ended { ticks: 3 })
2316        );
2317        // Then the live input: A, held since the first tick, with no edge.
2318        app.update(TICK, &[]);
2319        assert_eq!(x(&app), 2.0 * STEP);
2320        assert_eq!(moving(&app), (true, false, false));
2321        assert_eq!(replay(&app), Replay::Ended { ticks: 3 });
2322    }
2323
2324    #[test]
2325    fn a_frame_of_two_ticks_plays_two_replayed_ticks_and_a_short_frame_none() {
2326        let bytes = recording(&[&[key(Key::D, true)], &[], &[], &[]]);
2327        let mut app = replaying(bytes);
2328        app.update(40 * MS, &[]);
2329        assert_eq!(
2330            (x(&app), replay(&app)),
2331            (2.0 * STEP, Replay::Playing { ticks: 2 })
2332        );
2333        app.update(5 * MS, &[]);
2334        assert_eq!(
2335            (x(&app), replay(&app)),
2336            (2.0 * STEP, Replay::Playing { ticks: 2 })
2337        );
2338        app.update(40 * MS, &[]);
2339        assert_eq!(
2340            (x(&app), replay(&app)),
2341            (4.0 * STEP, Replay::Ended { ticks: 4 })
2342        );
2343    }
2344
2345    #[test]
2346    fn after_a_replay_the_live_ticks_have_only_the_live_keys_edges() {
2347        // Held at the replay's end: not just released after it.
2348        let mut app = replaying(recording(&[&[key(Key::D, true)], &[]]));
2349        app.update(TICK, &[]);
2350        app.update(TICK, &[]);
2351        assert_eq!(replay(&app), Replay::Ended { ticks: 2 });
2352        app.update(TICK, &[]);
2353        assert_eq!(moving(&app), (false, false, false));
2354
2355        // A tap during the replay was latched into nothing: no edge after.
2356        let mut app = replaying(recording(&[&[], &[]]));
2357        app.update(TICK, &[key(Key::D, true), key(Key::D, false)]);
2358        app.update(TICK, &[]);
2359        app.update(TICK, &[]);
2360        assert_eq!(moving(&app), (false, false, false));
2361        assert_eq!(x(&app), 0.0);
2362    }
2363
2364    /// What `Replay` said in each tick, as its systems saw it.
2365    #[derive(Default)]
2366    struct SeenReplays(Vec<Replay>);
2367
2368    #[test]
2369    fn each_tick_sees_its_own_count_and_the_first_after_the_end_sees_it_ended() {
2370        let mut app = replaying(recording(&[&[], &[], &[], &[]]))
2371            .insert_resource(SeenReplays::default())
2372            .add_fixed_system(FixedStage::Gameplay, "see", |world, _| {
2373                let replay = world.resource::<Replay>().clone();
2374                world.resource_mut::<SeenReplays>().0.push(replay);
2375            });
2376        // Frames of two ticks and of three: the second runs past the end.
2377        app.update(TICK * 2, &[]);
2378        app.update(TICK * 3, &[]);
2379        let playing = |ticks| Replay::Playing { ticks };
2380        assert_eq!(
2381            app.world().resource::<SeenReplays>().0,
2382            [
2383                playing(1),
2384                playing(2),
2385                playing(3),
2386                playing(4),
2387                Replay::Ended { ticks: 4 }
2388            ]
2389        );
2390    }
2391
2392    #[test]
2393    fn a_damaged_tick_fails_the_replay_and_the_input_goes_live() {
2394        let mut bytes = recording(&[&[key(Key::D, true)], &[], &[]]).to_vec();
2395        // The header is 16 bytes and a kind; each tick a flag byte and an
2396        // x and a y. Bit 7 of the second tick's flags belongs to no action.
2397        bytes[17 + 5] |= 0x80;
2398        let mut app = replaying(Box::leak(bytes.into_boxed_slice()));
2399        app.update(TICK, &[key(Key::A, true)]);
2400        assert_eq!(x(&app), STEP, "the first tick plays");
2401        let Replay::Failed { ticks: 1, error } = replay(&app) else {
2402            panic!("{:?}", replay(&app));
2403        };
2404        assert!(error.to_string().contains("22"), "{error}");
2405        // A, live from now on.
2406        app.update(TICK, &[]);
2407        assert_eq!(x(&app), 0.0);
2408    }
2409
2410    #[test]
2411    fn a_replay_of_no_ticks_ends_at_once() {
2412        let mut app = replaying(recording(&[]));
2413        assert_eq!(replay(&app), Replay::Ended { ticks: 0 });
2414        app.update(TICK, &[key(Key::D, true)]);
2415        assert_eq!(x(&app), STEP, "live");
2416    }
2417
2418    #[test]
2419    #[should_panic(expected = "add them with add_actions first")]
2420    fn a_replay_needs_its_actions_first() {
2421        let bytes = recording(&[&[]]);
2422        let _ = app().play_replay(InputPlayer::<Act>::new(bytes).expect("a replay"));
2423    }
2424
2425    #[test]
2426    #[should_panic(expected = "play_replay must come after add_actions")]
2427    fn the_actions_cannot_be_added_while_a_replay_plays() {
2428        let map = ActionMap::<Act>::new().expect("a valid set");
2429        let _ = replaying(recording(&[&[]])).add_actions(map);
2430    }
2431
2432    #[test]
2433    fn the_world_hash_follows_the_reflected_components_only() {
2434        let mut app = app();
2435        let walker = app
2436            .world_mut()
2437            .spawn()
2438            .with(Transform::at(Vec2::ZERO))
2439            .with(Sprite::new(texture(), Vec2::ONE))
2440            .id();
2441        let start = app.world_hash();
2442        assert_eq!(app.world_hash(), start);
2443        app.world()
2444            .write::<Sprite>()
2445            .get_mut(walker)
2446            .expect("drawn")
2447            .size = Vec2::splat(2.0);
2448        assert_eq!(
2449            app.world_hash(),
2450            start,
2451            "a Sprite's size is left out, as animators write it"
2452        );
2453        app.world()
2454            .write::<Sprite>()
2455            .get_mut(walker)
2456            .expect("drawn")
2457            .layer = 2;
2458        let layered = app.world_hash();
2459        assert_ne!(layered, start, "a Sprite's layer is the game's, and hashed");
2460        app.world()
2461            .write::<Transform>()
2462            .get_mut(walker)
2463            .expect("placed")
2464            .position
2465            .x = 1.0;
2466        assert_ne!(app.world_hash(), layered);
2467    }
2468
2469    #[test]
2470    fn the_render_frame_is_emptied_before_each_frame() {
2471        let log = shared();
2472        let mut app = app().insert_resource(Rc::clone(&log)).add_frame_system(
2473            FrameStage::Camera,
2474            "draw",
2475            |world, _| {
2476                let mut frame = world.resource_mut::<RenderFrame>();
2477                let size = frame.sprites.len() as f32;
2478                world.resource::<Shared>().values.borrow_mut().push(size);
2479                frame.sprites.push(nadir_render::SpriteDraw::new(
2480                    texture(),
2481                    Vec2::ZERO,
2482                    Vec2::ONE,
2483                ));
2484            },
2485        );
2486        for _ in 0..3 {
2487            app.update(16 * MS, &[]);
2488        }
2489        assert_eq!(*log.values.borrow(), [0.0, 0.0, 0.0]);
2490    }
2491
2492    #[test]
2493    fn a_missing_resource_names_the_system_that_asked() {
2494        let mut app = app().add_fixed_system(FixedStage::Gameplay, "needs_a_score", |world, _| {
2495            let _ = world.resource::<u64>();
2496        });
2497        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2498            app.update(20 * MS, &[]);
2499        }));
2500        let payload = result.expect_err("a panic");
2501        let message = payload
2502            .downcast_ref::<String>()
2503            .cloned()
2504            .unwrap_or_default();
2505        assert!(
2506            message.contains("`needs_a_score`") && message.contains("u64"),
2507            "{message}"
2508        );
2509    }
2510
2511    /// A script whose first pump taps D.
2512    struct Tapping {
2513        pumps: u32,
2514    }
2515
2516    impl EventSource for Tapping {
2517        fn pump_events(&mut self, out: &mut Vec<Event>) {
2518            self.pumps += 1;
2519            match self.pumps {
2520                1 => out.extend([key(Key::D, true), key(Key::D, false)]),
2521                // A few frames later, enough for a tick or more.
2522                40 => out.push(Event::CloseRequested),
2523                _ => thread::sleep(MS),
2524            }
2525        }
2526
2527        fn set_modal_frame_callback(&mut self, _callback: Box<dyn FnMut(ModalFrame)>) {}
2528    }
2529
2530    #[test]
2531    fn the_loop_feeds_pumped_keys_to_the_actions() {
2532        let log = shared();
2533        let mut app = moving_app(&log).add_frame_system(FrameStage::Ui, "report", |world, _| {
2534            let mover = world.resource::<Mover>().0;
2535            let x = world
2536                .read::<Transform>()
2537                .get(mover)
2538                .expect("it is")
2539                .position
2540                .x;
2541            world
2542                .resource::<Shared>()
2543                .seen
2544                .borrow_mut()
2545                .push(x.to_string());
2546        });
2547        app.config.frame_rate_limit = None;
2548        app.run_loop(&mut Tapping { pumps: 0 }, None)
2549            .expect("no error without a device");
2550        let seen = log.seen.borrow();
2551        let last: f32 = seen.last().expect("frames ran").parse().expect("a number");
2552        assert_eq!(last, SPEED / 60.0, "the tap moved it one tick");
2553    }
2554
2555    /// A hitch's frame of 15 ticks, after frames of one, allocates nothing:
2556    /// with nadir-core's `profile` feature too, whose records it holds.
2557    #[cfg(feature = "dev")]
2558    #[test]
2559    fn a_frame_of_many_ticks_after_frames_of_one_allocates_nothing() {
2560        let mut app = app();
2561        app.world_mut()
2562            .spawn()
2563            .with(Transform::at(Vec2::ZERO))
2564            .with(Velocity(Vec2::ONE))
2565            .with(Sprite::new(texture(), Vec2::ONE));
2566        for _ in 0..5 {
2567            app.update(TICK, &[]);
2568        }
2569        let start = nadir_platform::thread_alloc_counts();
2570        app.update(Duration::from_secs(1), &[]);
2571        let allocated = nadir_platform::thread_alloc_counts().since(start);
2572        assert_eq!(app.world().resource::<TickStats>().ticks, 15);
2573        assert_eq!(allocated, nadir_platform::AllocCounts::default());
2574    }
2575
2576    /// [`App::offscreen`]: frames drawn with no window, for recordings
2577    /// (ADR-0029). Behind `dev`, as `steady_frames` is, since they need an
2578    /// offscreen context.
2579    #[cfg(feature = "dev")]
2580    mod offscreen_frames {
2581        use std::{env, fs, process};
2582
2583        use nadir_codec::qoi::{self, Channels, ColorSpace, Header};
2584        use nadir_core::{Color, Vec2};
2585        use nadir_gfx::GfxError;
2586        use nadir_render::RenderError;
2587
2588        use super::*;
2589
2590        /// The frames' size: the virtual resolution, so a pixel of the game
2591        /// is a pixel of the frame.
2592        const SIZE: UVec2 = UVec2::new(32, 18);
2593        const CLEAR: [u8; 4] = [0, 0, 255, 255];
2594        const RED: [u8; 4] = [255, 0, 0, 255];
2595
2596        /// An app of one red sprite, 8 pixels square, its feet 4 pixels
2597        /// right of the view's centre, on blue, whose systems count the ticks
2598        /// into `log`. It is off the centre so that a frame upside down or
2599        /// mirrored shows it elsewhere.
2600        fn app(test: &str, log: &Shared) -> App {
2601            let assets = env::temp_dir().join(format!("nadir-engine-{test}-{}", process::id()));
2602            fs::create_dir_all(&assets).expect("make the asset folder");
2603            let header = Header {
2604                width: 8,
2605                height: 8,
2606                channels: Channels::Rgba,
2607                color_space: ColorSpace::Srgb,
2608            };
2609            let bytes = qoi::encode(&header, &RED.repeat(64)).expect("a valid image");
2610            fs::write(assets.join("red.qoi"), bytes).expect("write the texture");
2611            let mut app = App::new(Config {
2612                virtual_resolution: SIZE,
2613                assets,
2614                ..Config::default()
2615            })
2616            .insert_resource(Rc::clone(log))
2617            .add_fixed_system(FixedStage::Gameplay, "count_ticks", count_ticks)
2618            .add_frame_system(FrameStage::Camera, "look", |world, _| {
2619                let mut frame = world.resource_mut::<RenderFrame>();
2620                frame.clear = Color::rgb(CLEAR[0], CLEAR[1], CLEAR[2]);
2621                frame.camera.position = Vec2::ZERO;
2622            });
2623            let red = app
2624                .world()
2625                .resource_mut::<AssetServer>()
2626                .load::<nadir_render::Texture>("red.qoi");
2627            app.world_mut()
2628                .spawn()
2629                .with(Transform::at(Vec2::new(4.0, 0.0)))
2630                .with(Sprite::new(red, Vec2::splat(8.0)));
2631            app
2632        }
2633
2634        /// `app` drawn offscreen, or `None` where this system has no
2635        /// offscreen context yet (Windows and macOS, until M2.6 and M2.7)
2636        /// and `NADIR_EXPECT_GL_RENDERER` asks for none.
2637        fn offscreen(app: App, size: UVec2) -> Option<Offscreen> {
2638            let expected = env::var("NADIR_EXPECT_GL_RENDERER").unwrap_or_default();
2639            let assets = app.config.assets.clone();
2640            match app.offscreen(size) {
2641                Ok(offscreen) => {
2642                    let renderer = offscreen.renderer();
2643                    assert!(renderer.contains(&expected), "{renderer} is not {expected}");
2644                    Some(offscreen)
2645                }
2646                Err(Error::Render(RenderError::Gfx(GfxError::NoOffscreenContext)))
2647                    if expected.is_empty() =>
2648                {
2649                    fs::remove_dir_all(&assets).expect("remove the asset folder");
2650                    None
2651                }
2652                Err(error) => panic!("no offscreen OpenGL context: {error}"),
2653            }
2654        }
2655
2656        /// Removes the app's asset folder, once a frame has waited for its
2657        /// texture to be read: later frames need no file.
2658        fn remove_assets(offscreen: &Offscreen) {
2659            fs::remove_dir_all(&offscreen.app().config.assets).expect("remove the asset folder");
2660        }
2661
2662        fn pixel(frame: &[u8], x: u32, y: u32) -> [u8; 4] {
2663            let at = ((y * SIZE.x + x) * 4) as usize;
2664            frame[at..at + 4].try_into().expect("4 bytes")
2665        }
2666
2667        #[test]
2668        fn each_frame_runs_its_ticks_and_draws_what_a_window_would_show() {
2669            let log = shared();
2670            let Some(mut offscreen) = offscreen(app("offscreen-frames", &log), SIZE) else {
2671                return;
2672            };
2673            assert_eq!(offscreen.size(), SIZE);
2674
2675            // The texture is made after the first frame is drawn, so that
2676            // frame shows only the clear color, and a frame of no time runs
2677            // no tick.
2678            let first = offscreen.frame(Duration::ZERO, &[]).expect("a frame");
2679            remove_assets(&offscreen);
2680            assert_eq!(first.len(), (SIZE.x * SIZE.y * 4) as usize);
2681            assert!(first.as_chunks::<4>().0.iter().all(|&p| p == CLEAR));
2682            assert_eq!(log.ticks.get(), 0);
2683            let stats = *offscreen.app().world().resource::<FrameStats>();
2684            assert_eq!((stats.sprites, stats.skipped), (0, 1));
2685
2686            // Then the sprite: 8 pixels square, its feet at the centre,
2687            // (16, 9), 4 pixels right, so rows 1 to 8 and columns 16 to 23.
2688            let second = offscreen.frame(TICK, &[]).expect("a frame");
2689            assert_eq!(log.ticks.get(), 1);
2690            assert_eq!(offscreen.app().world().resource::<FrameStats>().sprites, 1);
2691            for (x, y, expected) in [
2692                (16, 1, RED),
2693                (23, 8, RED),
2694                (20, 4, RED),
2695                (15, 4, CLEAR),
2696                (24, 4, CLEAR),
2697                (20, 0, CLEAR),
2698                (20, 9, CLEAR),
2699                (0, 0, CLEAR),
2700            ] {
2701                assert_eq!(pixel(&second, x, y), expected, "({x}, {y})");
2702            }
2703            offscreen.frame(TICK * 3, &[]).expect("a frame");
2704            assert_eq!(log.ticks.get(), 4);
2705        }
2706
2707        #[test]
2708        fn a_frame_waits_for_the_textures_asked_for_before_it_ends() {
2709            let log = shared();
2710            let app = app("offscreen-wait", &log);
2711            // Noise, which takes a worker far longer to decode than the rest
2712            // of the frame takes after it asks.
2713            const SIDE: u32 = 512;
2714            let mut seed = 1u32;
2715            let noise: Vec<u8> = (0..SIDE * SIDE)
2716                .flat_map(|_| {
2717                    seed ^= seed << 13;
2718                    seed ^= seed >> 17;
2719                    seed ^= seed << 5;
2720                    let [r, g, b, _] = seed.to_le_bytes();
2721                    [r, g, b, 255]
2722                })
2723                .collect();
2724            let header = Header {
2725                width: SIDE,
2726                height: SIDE,
2727                channels: Channels::Rgba,
2728                color_space: ColorSpace::Srgb,
2729            };
2730            let bytes = qoi::encode(&header, &noise).expect("a valid image");
2731            fs::write(app.config.assets.join("noise.qoi"), bytes).expect("write the texture");
2732            // Each frame shows the noise, asked for just before the frame
2733            // draws and finishes its loads.
2734            let app = app.add_frame_system(FrameStage::Camera, "noise", |world, _| {
2735                let noise = world
2736                    .resource_mut::<AssetServer>()
2737                    .load::<nadir_render::Texture>("noise.qoi");
2738                for (_, sprite) in world.write::<Sprite>().iter_mut() {
2739                    sprite.texture = noise;
2740                }
2741            });
2742            let Some(mut offscreen) = offscreen(app, SIZE) else {
2743                return;
2744            };
2745            offscreen.frame(Duration::ZERO, &[]).expect("a frame");
2746            remove_assets(&offscreen);
2747            offscreen.frame(TICK, &[]).expect("a frame");
2748            let stats = *offscreen.app().world().resource::<FrameStats>();
2749            assert_eq!(
2750                (stats.sprites, stats.skipped),
2751                (1, 0),
2752                "the second frame did not draw the texture the first asked for"
2753            );
2754        }
2755
2756        #[test]
2757        fn frames_bigger_than_the_view_are_scaled_up_by_whole_numbers() {
2758            let log = shared();
2759            let Some(mut offscreen) = offscreen(app("offscreen-scaled", &log), SIZE * 2) else {
2760                return;
2761            };
2762            offscreen.frame(Duration::ZERO, &[]).expect("a frame");
2763            remove_assets(&offscreen);
2764            let frame = offscreen.frame(TICK, &[]).expect("a frame");
2765            let width = SIZE.x * 2;
2766            let at = |x: u32, y: u32| {
2767                let i = ((y * width + x) * 4) as usize;
2768                <[u8; 4]>::try_from(&frame[i..i + 4]).expect("4 bytes")
2769            };
2770            assert_eq!(frame.len(), (width * SIZE.y * 2 * 4) as usize);
2771            assert_eq!(at(32, 2), RED);
2772            assert_eq!(at(47, 17), RED);
2773            assert_eq!(at(31, 2), CLEAR);
2774            assert_eq!(at(32, 1), CLEAR);
2775            assert_eq!(at(48, 17), CLEAR);
2776            assert_eq!(at(47, 18), CLEAR);
2777        }
2778
2779        /// Writes the level `plot` into `assets`: a layer over the whole
2780        /// view of the tile `tile` of a tile set of two tiles of 8 pixels,
2781        /// green then yellow, the texture `tiles.qoi`.
2782        fn write_plot(assets: &std::path::Path, tile: u16) {
2783            use nadir_codec::{Limits, json, kbj};
2784            let write_kbj = |path: &str, text: &str| {
2785                let value = json::parse(text, Limits::default()).expect("the test's JSON");
2786                let bytes = kbj::encode(&value, Limits::default()).expect("KBJ");
2787                let path = assets.join(path);
2788                fs::create_dir_all(path.parent().expect("a folder")).expect("make the folder");
2789                fs::write(path, bytes).expect("write the file");
2790            };
2791            let header = Header {
2792                width: 16,
2793                height: 8,
2794                channels: Channels::Rgba,
2795                color_space: ColorSpace::Srgb,
2796            };
2797            let pixels: Vec<u8> = (0..16 * 8)
2798                .flat_map(|at| if at % 16 < 8 { GREEN } else { YELLOW })
2799                .collect();
2800            let texture = qoi::encode(&header, &pixels).expect("a valid image");
2801            fs::write(assets.join("tiles.qoi"), texture).expect("write the texture");
2802            write_kbj(
2803                "tiles.kbj",
2804                r#"{ "version": 2, "pages": [ { "path": "tiles.qoi", "w": 16, "h": 8 } ],
2805                     "sprites": [ { "name": "tiles", "tiles": [8, 8],
2806                       "frames": [ { "page": 0, "x": 0, "y": 0, "w": 16, "h": 8,
2807                                     "ox": 0, "oy": 0, "sw": 16, "sh": 8 } ] } ] }"#,
2808            );
2809            let cell = 1 + tile;
2810            write_kbj(
2811                "levels/plot.klvl",
2812                &format!(
2813                    r#"{{ "version": 1, "size": [32, 24], "background": [0, 0, 255],
2814                         "assets": ["tiles.kbj"],
2815                         "tilesets": [ {{ "atlas": "tiles.kbj", "sprite": "tiles", "columns": 2,
2816                                          "rows": 1, "animations": [] }} ],
2817                         "layers": [ {{ "tileset": 0, "size": [4, 3], "cell": 8, "origin": [-16, -9],
2818                                        "layer": 0, "depth": 0, "cells": [{}] }} ],
2819                         "tall": [], "entities": [] }}"#,
2820                    vec![cell.to_string(); 12].join(", ")
2821                ),
2822            );
2823        }
2824
2825        const GREEN: [u8; 4] = [0, 255, 0, 255];
2826        const YELLOW: [u8; 4] = [255, 255, 0, 255];
2827
2828        /// How many of a frame's pixels are `color`.
2829        fn count(frame: &[u8], color: [u8; 4]) -> usize {
2830            frame
2831                .as_chunks::<4>()
2832                .0
2833                .iter()
2834                .filter(|&&p| p == color)
2835                .count()
2836        }
2837
2838        #[test]
2839        fn a_level_loaded_again_draws_its_new_layer_at_once() {
2840            let log = shared();
2841            let mut app = app("offscreen-level", &log);
2842            let assets = app.config.assets.clone();
2843            write_plot(&assets, 0);
2844            // The tile set's texture is the game's own, so that loading the
2845            // level again replaces only its layer.
2846            {
2847                let world = app.world();
2848                let mut server = world.resource_mut::<AssetServer>();
2849                let atlas = server
2850                    .load_now::<nadir_render::Atlas>("tiles.kbj", &mut FinalizeCtx::new())
2851                    .expect("the atlas");
2852                let atlas = server.get(atlas).cloned().expect("the atlas");
2853                atlas.load_pages(&mut server, nadir_assets::Scope::Global);
2854            }
2855            app.load_level("plot").expect("the plot");
2856            let Some(mut offscreen) = offscreen(app, SIZE) else {
2857                return;
2858            };
2859            // The texture is made after the first frame.
2860            offscreen.frame(Duration::ZERO, &[]).expect("a frame");
2861            let first = offscreen.frame(TICK, &[]).expect("a frame");
2862            assert!(count(&first, GREEN) > 0, "the green tiles are drawn");
2863            assert_eq!(count(&first, YELLOW), 0);
2864
2865            // The same level, its layer now yellow: the layer it replaces in
2866            // the tile layers is drawn anew in the very next frame.
2867            write_plot(&assets, 1);
2868            offscreen.app.load_level("plot").expect("the plot again");
2869            let second = offscreen.frame(TICK, &[]).expect("a frame");
2870            fs::remove_dir_all(&assets).expect("remove the asset folder");
2871            assert!(count(&second, YELLOW) > 0, "the yellow tiles are drawn");
2872            assert_eq!(count(&second, GREEN), 0, "no green tile is left");
2873            assert_eq!(count(&first, YELLOW) + count(&second, GREEN), 0);
2874        }
2875    }
2876
2877    /// The hot reload, under `dev` (M5.8): files rewritten while the loop
2878    /// runs reach the game behind the handles it holds.
2879    #[cfg(feature = "dev")]
2880    mod hot_reload {
2881        use std::fs::{self, File};
2882        use std::path::{Path, PathBuf};
2883        use std::time::SystemTime;
2884        use std::{env, process};
2885
2886        use nadir_assets::Handle;
2887        use nadir_codec::qoi::{self, Channels, ColorSpace, Header};
2888        use nadir_core::Rect;
2889        use nadir_platform::HeadlessGl;
2890        use nadir_render::{Atlas, Program, SHADER_DIR, Texture, TileLayer};
2891
2892        use super::steady_frames::{headless, write_kbj};
2893        use super::*;
2894        use crate::hot_reload::Reloads;
2895        use crate::{Clip, Clips};
2896
2897        /// The atlas `atlas/sprites.kbj`: a hero of two frames, who walks
2898        /// in `walk`'s steps; a rock, its frame at `rock` pixels across;
2899        /// and a tile set of two tiles of 8 pixels, on a page of its own.
2900        fn atlas(walk: &str, rock: u32) -> String {
2901            format!(
2902                r#"{{ "version": 2,
2903                     "pages": [ {{ "path": "atlas/sprites_0.qoi", "w": 32, "h": 32 }},
2904                                {{ "path": "atlas/ground.qoi", "w": 16, "h": 8 }} ],
2905                     "sprites": [
2906                       {{ "name": "sprites/hero", "pivot": [4.0, 8.0],
2907                          "frames": [ {{ "page": 0, "x": 0, "y": 0, "w": 8, "h": 8, "ox": 0, "oy": 0, "sw": 8, "sh": 8 }},
2908                                      {{ "page": 0, "x": 8, "y": 0, "w": 8, "h": 8, "ox": 0, "oy": 0, "sw": 8, "sh": 8 }} ],
2909                          "clips": [ {{ "name": "walk", "loop": true, "frames": [{walk}] }} ] }},
2910                       {{ "name": "sprites/rock", "pivot": [4.0, 8.0],
2911                          "frames": [ {{ "page": 0, "x": {rock}, "y": 8, "w": 8, "h": 8, "ox": 0, "oy": 0, "sw": 8, "sh": 8 }} ] }},
2912                       {{ "name": "tiles/ground", "tiles": [8, 8],
2913                          "frames": [ {{ "page": 1, "x": 0, "y": 0, "w": 16, "h": 8, "ox": 0, "oy": 0, "sw": 16, "sh": 8 }} ] }} ] }}"#
2914            )
2915        }
2916
2917        /// The prefab `name`: a sprite of the atlas's rock, in `layer`.
2918        fn rock(name: &str, layer: u8) -> String {
2919            format!(
2920                r#"{{ "name": "{name}", "components": {{ "Transform": {{}},
2921                     "Sprite": {{ "atlas": "atlas/sprites.kbj", "sprite": "sprites/rock", "frame": 0,
2922                                  "layer": {layer} }} }} }}"#
2923            )
2924        }
2925
2926        /// The level `yard`: a layer of 4 × 2 cells of the tile `tile`, and
2927        /// an entity of the prefab `prop`.
2928        fn yard(tile: u16, prop: &str) -> String {
2929            let cells = vec![(tile + 1).to_string(); 8].join(", ");
2930            format!(
2931                r#"{{ "version": 1, "size": [32, 16], "background": [0, 0, 255],
2932                     "assets": ["atlas/sprites.kbj"],
2933                     "tilesets": [ {{ "atlas": "atlas/sprites.kbj", "sprite": "tiles/ground",
2934                                      "columns": 2, "rows": 1, "animations": [] }} ],
2935                     "layers": [ {{ "tileset": 0, "size": [4, 2], "cell": 8, "origin": [-16, -8],
2936                                    "layer": 0, "depth": 0, "cells": [{cells}] }} ],
2937                     "tall": [],
2938                     "entities": [ {{ "prefab": "{prop}", "position": [0, 0], "overrides": {{}} }} ] }}"#
2939            )
2940        }
2941
2942        /// A QOI texture of `size`, of one color.
2943        fn texture(size: UVec2) -> Vec<u8> {
2944            let header = Header {
2945                width: size.x,
2946                height: size.y,
2947                channels: Channels::Rgba,
2948                color_space: ColorSpace::Srgb,
2949            };
2950            let pixels = [200, 80, 40, 255].repeat((size.x * size.y) as usize);
2951            qoi::encode(&header, &pixels).expect("a valid image")
2952        }
2953
2954        /// What the last frame saw.
2955        #[derive(Clone, Copy, Debug, Default, PartialEq)]
2956        struct Seen {
2957            /// The size of the atlas's first page.
2958            page: Option<UVec2>,
2959            /// How long the walk lasts, under the handle the game holds.
2960            walk: Option<Duration>,
2961            /// The level's rock: its region, and its layer.
2962            rock: Option<(Rect, u8)>,
2963            /// The level's first layer, and the tile of its first cell.
2964            layer: Option<(Handle<TileLayer>, Option<u16>)>,
2965            reloads: Reloads,
2966        }
2967
2968        type SharedSeen = Rc<RefCell<Seen>>;
2969
2970        /// The game's handles, which `look` reads.
2971        struct Game {
2972            page: Handle<Texture>,
2973            walk: Handle<Clip>,
2974        }
2975
2976        fn look(world: &World, _: &Frame) {
2977            let game = world.resource::<Game>();
2978            let server = world.resource::<AssetServer>();
2979            let current = world.resource::<CurrentLevel>();
2980            let rock = current.entities().first().and_then(|&rock| {
2981                let sprites = world.read::<Sprite>();
2982                sprites.get(rock).map(|sprite| (sprite.uv, sprite.layer))
2983            });
2984            let layer = current.tile_layers().first().map(|draw| {
2985                let layers = world.resource::<TileLayers>();
2986                let tile = layers
2987                    .get(draw.tiles)
2988                    .and_then(|layer| layer.get(nadir_core::IVec2::ZERO))
2989                    .map(|tile| tile.index);
2990                (draw.tiles, tile)
2991            });
2992            *world.resource::<SharedSeen>().borrow_mut() = Seen {
2993                page: server.get(game.page).map(Texture::size),
2994                walk: world.resource::<Clips>().get(game.walk).map(Clip::duration),
2995                rock,
2996                layer,
2997                reloads: *world.resource::<Reloads>(),
2998            };
2999        }
3000
3001        /// An edit, and what shows it was reloaded.
3002        struct Step {
3003            name: &'static str,
3004            edit: fn(&Files),
3005            done: fn(&Seen, &Seen) -> bool,
3006        }
3007
3008        /// Where the game's files are.
3009        struct Files {
3010            assets: PathBuf,
3011            shaders: PathBuf,
3012        }
3013
3014        impl Files {
3015            /// Writes `bytes` at `path` as the cook does, through a file
3016            /// beside it and a rename, with a time of change `ahead`
3017            /// seconds from now, so that a system that keeps coarse times
3018            /// sees each write.
3019            fn write(path: &Path, bytes: &[u8], ahead: u64) {
3020                let temporary = path.with_extension("tmp");
3021                fs::write(&temporary, bytes).expect("write the file");
3022                File::options()
3023                    .write(true)
3024                    .open(&temporary)
3025                    .and_then(|file| {
3026                        file.set_modified(SystemTime::now() + Duration::from_secs(ahead))
3027                    })
3028                    .expect("set its time");
3029                fs::rename(&temporary, path).expect("rename it into place");
3030            }
3031
3032            fn kbj(&self, path: &str, json: &str, ahead: u64) {
3033                let temporary = self.assets.join("edit.kbj");
3034                write_kbj(&temporary, json);
3035                let bytes = fs::read(&temporary).expect("the file just written");
3036                fs::remove_file(&temporary).expect("remove it");
3037                Self::write(&self.assets.join(path), &bytes, ahead);
3038            }
3039
3040            fn sprite_shader(&self) -> PathBuf {
3041                self.shaders.join(Program::Sprite.fragment_file())
3042            }
3043        }
3044
3045        /// The edits, one after another, each waited for.
3046        const STEPS: &[Step] = &[
3047            Step {
3048                name: "a texture of another size",
3049                edit: |files| {
3050                    let page = files.assets.join("atlas/sprites_0.qoi");
3051                    Files::write(&page, &texture(UVec2::new(64, 64)), 10);
3052                },
3053                done: |_, now| now.page == Some(UVec2::new(64, 64)),
3054            },
3055            Step {
3056                name: "an atlas whose walk is longer and whose rock moved",
3057                edit: |files| {
3058                    files.kbj(
3059                        "atlas/sprites.kbj",
3060                        &atlas("[0, 50], [1, 50], [0, 50]", 24),
3061                        20,
3062                    )
3063                },
3064                done: |first, now| {
3065                    now.walk == Some(Duration::from_millis(150))
3066                        && now.rock.map(|rock| rock.0) != first.rock.map(|rock| rock.0)
3067                },
3068            },
3069            Step {
3070                name: "a prefab in another layer",
3071                edit: |files| files.kbj("data/prefabs/rock.kbj", &rock("rock", 3), 30),
3072                done: |_, now| now.rock.map(|rock| rock.1) == Some(3),
3073            },
3074            Step {
3075                name: "a level of other tiles",
3076                edit: |files| files.kbj("levels/yard.klvl", &yard(1, "rock"), 40),
3077                done: |first, now| {
3078                    now.layer.map(|layer| layer.1) == Some(Some(1))
3079                        && now.layer.map(|layer| layer.0) == first.layer.map(|layer| layer.0)
3080                },
3081            },
3082            Step {
3083                name: "a level of a prefab not cooked yet",
3084                edit: |files| files.kbj("levels/yard.klvl", &yard(1, "boulder"), 50),
3085                done: |_, now| now.reloads.levels_refused == 1,
3086            },
3087            Step {
3088                name: "the prefab cooked after its level",
3089                edit: |files| files.kbj("data/prefabs/boulder.kbj", &rock("boulder", 5), 60),
3090                done: |_, now| now.rock.map(|rock| rock.1) == Some(5),
3091            },
3092            Step {
3093                name: "a shader edited",
3094                edit: |files| {
3095                    let path = files.sprite_shader();
3096                    let mut text = fs::read_to_string(&path).expect("the shader");
3097                    text.push_str("\n// Edited.\n");
3098                    Files::write(&path, text.as_bytes(), 70);
3099                },
3100                done: |_, now| now.reloads.shaders == 1,
3101            },
3102            Step {
3103                name: "a shader that does not compile",
3104                edit: |files| {
3105                    let broken =
3106                        "#version 330 core\nout vec4 color;\nvoid main() { color = oops; }\n";
3107                    Files::write(&files.sprite_shader(), broken.as_bytes(), 80);
3108                },
3109                done: |_, now| now.reloads.shaders_refused == 1,
3110            },
3111        ];
3112
3113        /// The window: an offscreen context, which makes each edit once the
3114        /// last is seen, and closes after the last, or once one is not seen
3115        /// in [`PATIENCE`].
3116        struct Editing {
3117            gl: Option<HeadlessGl>,
3118            seen: SharedSeen,
3119            files: Files,
3120            /// What the first frame that drew the page saw.
3121            first: Option<Seen>,
3122            /// The step being waited for, and when its edit was made.
3123            step: usize,
3124            since: Option<Instant>,
3125            /// How long each step took to be seen.
3126            took: Vec<Duration>,
3127            started: Instant,
3128            /// When the last step was seen.
3129            quiet: Option<Instant>,
3130        }
3131
3132        /// How long the loop runs on after the last edit is seen: more than
3133        /// two looks of the watchers.
3134        const QUIET: Duration = Duration::from_millis(600);
3135
3136        /// How long an edit may take to be seen, which a loaded machine
3137        /// running the tests stretches: the watchers look every 250 ms.
3138        const PATIENCE: Duration = Duration::from_secs(5);
3139
3140        impl EventSource for Editing {
3141            fn pump_events(&mut self, out: &mut Vec<Event>) {
3142                let seen = *self.seen.borrow();
3143                let Some(first) = self.first else {
3144                    // The first frames make the assets loaded at setup.
3145                    if seen.page.is_some() {
3146                        self.first = Some(seen);
3147                    } else if self.started.elapsed() > PATIENCE {
3148                        out.push(Event::CloseRequested);
3149                    }
3150                    return;
3151                };
3152                let Some(step) = STEPS.get(self.step) else {
3153                    // A while with no edit, in which nothing more reloads.
3154                    let quiet = self.quiet.get_or_insert_with(Instant::now);
3155                    if quiet.elapsed() > QUIET {
3156                        out.push(Event::CloseRequested);
3157                    }
3158                    return;
3159                };
3160                match self.since {
3161                    None => {
3162                        (step.edit)(&self.files);
3163                        self.since = Some(Instant::now());
3164                    }
3165                    Some(since) if (step.done)(&first, &seen) => {
3166                        self.took.push(since.elapsed());
3167                        self.step += 1;
3168                        self.since = None;
3169                    }
3170                    Some(since) if since.elapsed() > PATIENCE => out.push(Event::CloseRequested),
3171                    Some(_) => {}
3172                }
3173            }
3174
3175            fn set_modal_frame_callback(&mut self, _callback: Box<dyn FnMut(ModalFrame)>) {}
3176
3177            fn gpu_surface(&self) -> Option<GpuSurface<'_>> {
3178                self.gl.as_ref().map(|gl| GpuSurface::Gl(gl))
3179            }
3180
3181            fn window_size(&self) -> UVec2 {
3182                UVec2::new(64, 36)
3183            }
3184        }
3185
3186        #[test]
3187        fn files_rewritten_while_the_game_runs_reach_it_behind_its_handles() {
3188            let expected = env::var("NADIR_EXPECT_GL_RENDERER").unwrap_or_default();
3189            let Some(gl) = headless(&expected) else {
3190                return;
3191            };
3192            let root = env::temp_dir().join(format!("nadir-engine-hot-reload-{}", process::id()));
3193            let files = Files {
3194                assets: root.join("assets"),
3195                shaders: root.join("shaders"),
3196            };
3197            for &program in Program::ALL {
3198                for file in [program.vertex_file(), program.fragment_file()] {
3199                    let to = files.shaders.join(file);
3200                    fs::create_dir_all(to.parent().expect("a folder")).expect("make the folder");
3201                    fs::copy(Path::new(SHADER_DIR).join(file), to).expect("copy the shader");
3202                }
3203            }
3204            let assets = &files.assets;
3205            fs::create_dir_all(assets.join("atlas")).expect("make the folder");
3206            fs::write(
3207                assets.join("atlas/sprites_0.qoi"),
3208                texture(UVec2::splat(32)),
3209            )
3210            .expect("write the page");
3211            fs::write(assets.join("atlas/ground.qoi"), texture(UVec2::new(16, 8)))
3212                .expect("write the page");
3213            write_kbj(
3214                &assets.join("atlas/sprites.kbj"),
3215                &atlas("[0, 100], [1, 100]", 16),
3216            );
3217            write_kbj(&assets.join("data/prefabs/rock.kbj"), &rock("rock", 1));
3218            write_kbj(&assets.join("levels/yard.klvl"), &yard(0, "rock"));
3219
3220            let seen = Rc::new(RefCell::new(Seen::default()));
3221            let mut app = App::new(Config {
3222                assets: assets.clone(),
3223                virtual_resolution: UVec2::new(32, 18),
3224                ..Config::default()
3225            })
3226            .insert_resource(Rc::clone(&seen))
3227            .add_frame_system(FrameStage::Ui, "look", look);
3228            app.shader_dir = files.shaders.clone();
3229            // The game adds the atlas's clips, as the sandbox does, and
3230            // holds the walk's handle and the first page's.
3231            let game = {
3232                let world = app.world();
3233                let mut server = world.resource_mut::<AssetServer>();
3234                let handle = server
3235                    .load_now::<Atlas>("atlas/sprites.kbj", &mut FinalizeCtx::new())
3236                    .expect("the atlas");
3237                let atlas = server.get(handle).cloned().expect("the atlas");
3238                let pages = atlas.load_pages(&mut server, nadir_assets::Scope::Global);
3239                world
3240                    .resource_mut::<Clips>()
3241                    .add_atlas(&atlas, &pages)
3242                    .expect("the clips");
3243                let walk = world
3244                    .resource::<Clips>()
3245                    .find("sprites/hero/walk")
3246                    .expect("walk");
3247                Game {
3248                    page: pages[0],
3249                    walk,
3250                }
3251            };
3252            app = app.insert_resource(game);
3253            app.load_level("yard").expect("the yard");
3254
3255            let mut device = Device::new(GpuSurface::Gl(&gl)).expect("a device");
3256            let config = RenderConfig {
3257                virtual_resolution: UVec2::new(32, 18),
3258            };
3259            let renderer = Renderer::new(&mut device, &config).expect("a renderer");
3260            let mut window = Editing {
3261                gl: Some(gl),
3262                seen: Rc::clone(&seen),
3263                files,
3264                first: None,
3265                step: 0,
3266                since: None,
3267                took: Vec::new(),
3268                started: Instant::now(),
3269                quiet: None,
3270            };
3271            app.run_loop(&mut window, Some(Graphics { renderer, device }))
3272                .expect("the frames draw");
3273            fs::remove_dir_all(&root).expect("remove the test's folder");
3274
3275            let first = window.first.expect("the page loaded");
3276            assert!(first.reloads.started, "the hot reload started");
3277            for (step, took) in STEPS.iter().zip(&window.took) {
3278                nadir_core::log::info!("{}: seen after {} ms", step.name, took.as_millis());
3279            }
3280            let missed = STEPS.get(window.took.len()).map(|step| step.name);
3281            assert_eq!(missed, None, "an edit was not seen within {PATIENCE:?}");
3282            let reloads = seen.borrow().reloads;
3283            assert_eq!(reloads.atlases, 1, "{reloads:?}");
3284            assert_eq!(reloads.prefabs, 1, "{reloads:?}");
3285            assert_eq!(
3286                (reloads.levels, reloads.levels_refused),
3287                (4, 1),
3288                "{reloads:?}"
3289            );
3290            assert_eq!(
3291                (reloads.shaders, reloads.shaders_refused),
3292                (1, 1),
3293                "{reloads:?}"
3294            );
3295        }
3296    }
3297
3298    /// A steady frame of 10,000 sprites allocates nothing (roadmap M3.5),
3299    /// now drawn from entities, over a level's tile layer, which the
3300    /// engine's `nadir::extract_level` draws (M5.6), with the hot reload
3301    /// watching its files and nothing changing (M5.8).
3302    #[cfg(feature = "dev")]
3303    mod steady_frames {
3304        use std::env;
3305        use std::fs;
3306        use std::hint::black_box;
3307        use std::path::PathBuf;
3308        use std::process;
3309
3310        use nadir_codec::qoi::{self, Channels, ColorSpace, Header};
3311        use nadir_codec::{Limits, json, kbj};
3312        use nadir_core::{Color, Rect, Vec2};
3313        use nadir_platform::{
3314            AllocCounts, HeadlessGl, PlatformError, create_headless_gl, thread_alloc_counts,
3315        };
3316
3317        use super::*;
3318        use crate::{Clip, ClipFrame, FrameAllocs, Playback};
3319
3320        /// How many sprites walk about.
3321        const CROWD: usize = 10_000;
3322        /// The ground under them: a tile layer of 64 × 64 cells of 16
3323        /// pixels, so chunks of 32 × 32 cells, a quarter of them animated.
3324        /// Its four chunks meet at the view's centre.
3325        const GROUND: u32 = 64;
3326        /// Frames before the counting starts: the textures are made at the
3327        /// end of the first frame after the workers decode them (the first
3328        /// frame, unless they are slow), the buffers grow in the frames
3329        /// after it, and the camera moves from the ground's first chunk to
3330        /// the view, where four meet, packing three more.
3331        const WARM_UP: usize = 10;
3332        /// The frame of the warm-up from which the camera is where four
3333        /// chunks meet.
3334        const MOVED: usize = 6;
3335        /// Frames counted.
3336        const COUNTED: usize = 100;
3337        /// The view, which the walkers stay inside.
3338        const VIEW: Vec2 = Vec2::new(480.0, 270.0);
3339
3340        /// The frames drawn so far, by which the camera moves.
3341        struct Ground(usize);
3342
3343        /// What each frame saw: the last frame's allocations and drawing,
3344        /// and the ticks so far. Room for every frame is made up front, and
3345        /// the test keeps it when the loop drops the app.
3346        struct Seen {
3347            frames: Vec<(AllocCounts, FrameStats, u64)>,
3348            ticks: u64,
3349            /// Whether the hot reload ran.
3350            reloading: bool,
3351        }
3352
3353        type SharedSeen = Rc<RefCell<Seen>>;
3354
3355        /// The window: an offscreen context, if there is one. It notes the
3356        /// thread's heap use as each pump starts, and closes after the
3357        /// counted frames.
3358        struct Offscreen {
3359            gl: Option<HeadlessGl>,
3360            at_pumps: Vec<AllocCounts>,
3361        }
3362
3363        impl EventSource for Offscreen {
3364            fn pump_events(&mut self, out: &mut Vec<Event>) {
3365                self.at_pumps.push(thread_alloc_counts());
3366                if self.at_pumps.len() > WARM_UP + COUNTED {
3367                    out.push(Event::CloseRequested);
3368                }
3369            }
3370
3371            fn set_modal_frame_callback(&mut self, _callback: Box<dyn FnMut(ModalFrame)>) {}
3372
3373            fn gpu_surface(&self) -> Option<GpuSurface<'_>> {
3374                self.gl.as_ref().map(|gl| GpuSurface::Gl(gl))
3375            }
3376
3377            fn window_size(&self) -> UVec2 {
3378                UVec2::new(960, 540)
3379            }
3380        }
3381
3382        /// An offscreen context, or `None` where `nadir-platform` cannot
3383        /// make one yet (Windows and macOS, until M2.6 and M2.7) and no
3384        /// renderer is asked for in `NADIR_EXPECT_GL_RENDERER`, as for the
3385        /// gfx and render tests. Any other failure fails the test.
3386        pub(super) fn headless(expected: &str) -> Option<HeadlessGl> {
3387            match create_headless_gl() {
3388                Ok(gl) => Some(gl),
3389                Err(PlatformError::Unsupported) if expected.is_empty() => None,
3390                Err(error) => panic!(
3391                    "no offscreen OpenGL context: {error}. With libglvnd, Mesa can be chosen \
3392                     with __EGL_VENDOR_LIBRARY_FILENAMES=/usr/share/glvnd/egl_vendor.d/50_mesa.json"
3393                ),
3394            }
3395        }
3396
3397        /// Writes a texture of one color, opaque.
3398        fn write_texture(path: &PathBuf, size: u32, color: [u8; 4]) {
3399            let header = Header {
3400                width: size,
3401                height: size,
3402                channels: Channels::Rgba,
3403                color_space: ColorSpace::Srgb,
3404            };
3405            let pixels = color.repeat((size * size) as usize);
3406            let bytes = qoi::encode(&header, &pixels).expect("a valid image");
3407            fs::write(path, bytes).expect("write a texture");
3408        }
3409
3410        /// Turns each walker back at the edges of the view, and faces it
3411        /// the way it goes.
3412        fn walk(world: &World, tick: &Tick) {
3413            let transforms = world.read::<Transform>();
3414            let mut velocities = world.write::<Velocity>();
3415            let mut facings = world.write::<Facing>();
3416            for (entity, velocity) in velocities.iter_mut() {
3417                let Some(transform) = transforms.get(entity) else {
3418                    continue;
3419                };
3420                let next = transform.position + velocity.0 * tick.dt;
3421                if !(8.0..=VIEW.x - 8.0).contains(&next.x) {
3422                    velocity.0.x = -velocity.0.x;
3423                }
3424                if !(16.0..=VIEW.y).contains(&next.y) {
3425                    velocity.0.y = -velocity.0.y;
3426                }
3427                if let Some(facing) = facings.get_mut(entity) {
3428                    *facing = facing_of(velocity.0);
3429                }
3430            }
3431            world.resource::<SharedSeen>().borrow_mut().ticks += 1;
3432        }
3433
3434        fn facing_of(velocity: Vec2) -> Facing {
3435            if velocity.x < 0.0 {
3436                Facing::Left
3437            } else {
3438                Facing::Right
3439            }
3440        }
3441
3442        fn move_camera(world: &World, _: &Frame) {
3443            let mut ground = world.resource_mut::<Ground>();
3444            let mut out = world.resource_mut::<RenderFrame>();
3445            // Over the first chunk only, then on the walkers, where four
3446            // chunks meet.
3447            out.camera.position = if ground.0 < MOVED {
3448                VIEW * 0.5 - Vec2::splat(256.0)
3449            } else {
3450                VIEW * 0.5
3451            };
3452            ground.0 += 1;
3453        }
3454
3455        /// Writes `json` as KBJ at `path`.
3456        pub(super) fn write_kbj(path: &std::path::Path, json: &str) {
3457            let value = json::parse(json, Limits::default()).expect("the test's JSON");
3458            let bytes = kbj::encode(&value, Limits::default()).expect("KBJ");
3459            fs::create_dir_all(path.parent().expect("a folder")).expect("make the folder");
3460            fs::write(path, bytes).expect("write the file");
3461        }
3462
3463        /// Writes the ground as the level `ground`: a tile set of 2 × 2
3464        /// tiles of 16 pixels, the texture `ground.qoi`, and a layer of it,
3465        /// a quarter of its tiles animated, with its corner at `corner`.
3466        fn write_ground(assets: &std::path::Path, corner: Vec2) {
3467            write_kbj(
3468                &assets.join("ground.kbj"),
3469                r#"{ "version": 2, "pages": [ { "path": "ground.qoi", "w": 32, "h": 32 } ],
3470                     "sprites": [ { "name": "ground", "tiles": [16, 16],
3471                       "frames": [ { "page": 0, "x": 0, "y": 0, "w": 32, "h": 32,
3472                                     "ox": 0, "oy": 0, "sw": 32, "sh": 32 } ] } ] }"#,
3473            );
3474            let mut cells = Vec::new();
3475            for y in 0..GROUND {
3476                for x in 0..GROUND {
3477                    // Tile 1, animated, or tile 0.
3478                    cells.push(if (x + y) % 4 == 0 { "2" } else { "1" });
3479                }
3480            }
3481            let side = GROUND * 16;
3482            let level = format!(
3483                r#"{{ "version": 1, "size": [{side}, {side}], "background": [0, 0, 0],
3484                     "assets": ["ground.kbj"],
3485                     "tilesets": [ {{ "atlas": "ground.kbj", "sprite": "ground", "columns": 2, "rows": 2,
3486                                      "animations": [ {{ "tile": 1, "frames": 3, "ms": 100 }} ] }} ],
3487                     "layers": [ {{ "tileset": 0, "size": [{GROUND}, {GROUND}], "cell": 16,
3488                                    "origin": [{}, {}], "layer": 0, "depth": 0, "cells": [{}] }} ],
3489                     "tall": [], "entities": [] }}"#,
3490                corner.x as i32,
3491                corner.y as i32,
3492                cells.join(", ")
3493            );
3494            write_kbj(&assets.join("levels/ground.klvl"), &level);
3495        }
3496
3497        fn probe(world: &World, _: &Frame) {
3498            let seen = world.resource::<SharedSeen>();
3499            let mut seen = seen.borrow_mut();
3500            let entry = (
3501                world.resource::<FrameAllocs>().0,
3502                *world.resource::<FrameStats>(),
3503                seen.ticks,
3504            );
3505            seen.frames.push(entry);
3506            seen.reloading = world.resource::<crate::hot_reload::Reloads>().started;
3507            // In a warm-up frame, a known allocation, which that frame's
3508            // count must show.
3509            if seen.frames.len() == 5 {
3510                drop(black_box(Box::new(5u64)));
3511            }
3512        }
3513
3514        /// The scene's app, loading its textures from `assets`, and noting
3515        /// in `seen` what each frame sees.
3516        fn scene(assets: PathBuf, seen: &SharedSeen) -> App {
3517            let mut app = App::new(Config {
3518                assets,
3519                // Frames then sleep in the limiter, which the count covers.
3520                frame_rate_limit: Some(500),
3521                ..Config::default()
3522            })
3523            .insert_resource(Rc::clone(seen))
3524            .add_fixed_system(FixedStage::Gameplay, "walk", walk)
3525            .add_frame_system(FrameStage::Camera, "move_camera", move_camera)
3526            .add_frame_system(FrameStage::Ui, "probe", probe);
3527            let walker = app.world().resource_mut::<AssetServer>().load("walker.qoi");
3528            // Cell (32, 32), the corner of four chunks, at the view's centre.
3529            write_ground(&app.config.assets, VIEW * 0.5 - Vec2::splat(512.0));
3530            app.load_level("ground").expect("the ground's level");
3531            // A walk of 4 frames, the quarters of the walker's texture. Clips
3532            // that play once, and the events they send, are in
3533            // `glue::tests::steady_animation`, whose frames are not timed by
3534            // the clock on the wall.
3535            let quarter = |index: u32| {
3536                let left = index as f32 * 0.25;
3537                let uv = Rect::new(Vec2::new(left, 0.0), Vec2::new(left + 0.25, 1.0));
3538                ClipFrame::new(walker, uv, 100 * MS)
3539            };
3540            let walk = app
3541                .world()
3542                .resource_mut::<Clips>()
3543                .add(Clip::new((0..4).map(quarter).collect(), Playback::Loop));
3544            let mut seed = 1u32;
3545            let mut random = move || {
3546                // A xorshift: the same walkers every run.
3547                seed ^= seed << 13;
3548                seed ^= seed >> 17;
3549                seed ^= seed << 5;
3550                (seed % 10_000) as f32 / 10_000.0
3551            };
3552            for index in 0..CROWD {
3553                let position = Vec2::new(
3554                    8.0 + random() * (VIEW.x - 16.0),
3555                    16.0 + random() * (VIEW.y - 16.0),
3556                );
3557                let velocity = Vec2::new(random() * 120.0 - 60.0, random() * 120.0 - 60.0);
3558                let mut sprite = Sprite::new(walker, Vec2::new(8.0, 16.0));
3559                sprite.layer = 1;
3560                if index % 4 == 0 {
3561                    sprite.color = Color::rgb(255, 200, 200);
3562                }
3563                let phase = 400 * MS * (index % 4) as u32 / 4;
3564                app.world_mut()
3565                    .spawn()
3566                    .with(Transform::at(position))
3567                    .with(Velocity(velocity))
3568                    .with(sprite)
3569                    .with(Animator::starting_at(walk, phase))
3570                    .with(facing_of(velocity));
3571            }
3572            app.insert_resource(Ground(0))
3573        }
3574
3575        #[test]
3576        fn a_steady_frame_of_10k_animated_sprites_and_a_tile_layer_allocates_nothing() {
3577            // The counter is the global allocator, so a known allocation
3578            // shows: a count of zero below means something.
3579            let start = thread_alloc_counts();
3580            drop(black_box(Box::new(0u64)));
3581            assert_eq!(thread_alloc_counts().since(start).allocations, 1);
3582
3583            let assets = env::temp_dir().join(format!("nadir-engine-steady-{}", process::id()));
3584            fs::create_dir_all(&assets).expect("make the asset folder");
3585            write_texture(&assets.join("walker.qoi"), 8, [200, 120, 60, 255]);
3586            write_texture(&assets.join("ground.qoi"), 32, [90, 140, 70, 255]);
3587            let seen = Rc::new(RefCell::new(Seen {
3588                frames: Vec::with_capacity(WARM_UP + COUNTED),
3589                ticks: 0,
3590                reloading: false,
3591            }));
3592            let app = scene(assets.clone(), &seen);
3593
3594            let expected = env::var("NADIR_EXPECT_GL_RENDERER").unwrap_or_default();
3595            let mut window = Offscreen {
3596                gl: headless(&expected),
3597                at_pumps: Vec::with_capacity(WARM_UP + COUNTED + 2),
3598            };
3599            let graphics = window.gl.as_ref().map(|gl| {
3600                let mut device = Device::new(GpuSurface::Gl(gl)).expect("a device");
3601                let renderer = device.caps().renderer.clone();
3602                assert!(renderer.contains(&expected), "{renderer} is not {expected}");
3603                let config = RenderConfig {
3604                    virtual_resolution: VIEW.as_uvec2(),
3605                };
3606                let renderer = Renderer::new(&mut device, &config).expect("a renderer");
3607                Graphics { renderer, device }
3608            });
3609            let drawn = graphics.is_some();
3610            app.run_loop(&mut window, graphics)
3611                .expect("the frames draw");
3612            fs::remove_dir_all(&assets).expect("remove the asset folder");
3613            assert_eq!(
3614                seen.borrow().reloading,
3615                drawn,
3616                "the hot reload runs where it draws"
3617            );
3618            let seen = &seen.borrow().frames;
3619
3620            // Frame f runs after pump f; `seen[f - 1]` is what frame f saw,
3621            // so `seen[f].0` is frame f's own count.
3622            let pumps = &window.at_pumps;
3623            assert_eq!(pumps.len(), WARM_UP + COUNTED + 1);
3624            assert_eq!(seen.len(), WARM_UP + COUNTED);
3625
3626            // The counted frames: the loop between two pumps, from frame
3627            // WARM_UP + 1 to the last.
3628            let counted = pumps[WARM_UP + COUNTED].since(pumps[WARM_UP]);
3629            assert_eq!(
3630                counted,
3631                AllocCounts::default(),
3632                "the steady frames allocated"
3633            );
3634            let ticks = seen[WARM_UP + COUNTED - 1].2 - seen[WARM_UP].2;
3635            assert!(ticks > 0, "no tick ran in the counted frames");
3636
3637            // `FrameAllocs` counts the same as the pumps, frame by frame,
3638            // warm-up included: the probe's allocation in frame 5, and with
3639            // a GPU, the first frame that draws the textures.
3640            for frame in 2..WARM_UP + COUNTED {
3641                let between_pumps = pumps[frame].since(pumps[frame - 1]);
3642                assert_eq!(seen[frame].0, between_pumps, "frame {frame}");
3643            }
3644            assert!(seen[5].0.allocations >= 1, "the probe's allocation");
3645
3646            if drawn {
3647                // A frame makes the textures after it draws, so the first
3648                // to draw them all is the second at the soonest, in the
3649                // frames checked against the pumps above.
3650                let full = (1..WARM_UP)
3651                    .find(|&frame| seen[frame].1.sprites == CROWD as u32)
3652                    .expect("the sprites are drawn in the warm-up");
3653                assert!(full >= 2, "frame {full} drew the sprites");
3654                assert!(
3655                    seen[full].0.allocations > 0,
3656                    "the first full draw grows its lists"
3657                );
3658                let all = FrameStats {
3659                    sprites: CROWD as u32,
3660                    skipped: 0,
3661                    batches: 1,
3662                    tiles: 4 * 32 * 32,
3663                    chunks: 4,
3664                    texts: 0,
3665                    glyphs: 0,
3666                    skipped_texts: 0,
3667                    ui_sprites: 0,
3668                    ui_glyphs: 0,
3669                    ui_texts: 0,
3670                    ui_batches: 0,
3671                };
3672                assert_eq!(seen[WARM_UP].1, all, "drawn before the counting starts");
3673                assert_eq!(seen[WARM_UP + COUNTED - 1].1, all);
3674            }
3675        }
3676    }
3677
3678    /// The profiler shows each drawn frame's GPU time (roadmap M7.12): the
3679    /// main loop times every render, and gives each time read back to the
3680    /// frame it was timed in.
3681    #[cfg(feature = "dev")]
3682    mod gpu_profile {
3683        use std::path::PathBuf;
3684        use std::{env, fs, process};
3685
3686        use nadir_codec::Limits;
3687        use nadir_codec::json::{self, Value};
3688        use nadir_core::MouseButton;
3689        use nadir_platform::HeadlessGl;
3690        use nadir_render::UiDraw;
3691
3692        use super::*;
3693
3694        /// The frame whose click writes the trace.
3695        const FRAMES: u32 = 40;
3696        const SIZE: UVec2 = UVec2::new(640, 360);
3697
3698        fn tap(key: Key) -> [Event; 2] {
3699            [true, false].map(|pressed| Event::Key {
3700                key,
3701                pressed,
3702                repeat: false,
3703            })
3704        }
3705
3706        /// Where the profiler's "Write trace" button is: found by a frame
3707        /// of an app like the test's, with the profiler open.
3708        fn write_trace_button() -> Vec2 {
3709            let mut app = App::new(Config::default());
3710            *app.world_mut().resource_mut::<crate::WindowSize>() = crate::WindowSize(SIZE);
3711            app.update(Duration::ZERO, &tap(Key::F3));
3712            let frame = app.world().resource::<RenderFrame>();
3713            let at = frame.ui.iter().find_map(|(draw, _)| match draw {
3714                UiDraw::Text(draw, "Write trace") => Some(draw.position),
3715                _ => None,
3716            });
3717            at.expect("the button") + Vec2::new(2.0, 2.0)
3718        }
3719
3720        /// The window: an offscreen context. It opens the profiler, clicks
3721        /// "Write trace" in frame `FRAMES`, and closes.
3722        struct Profiling {
3723            gl: HeadlessGl,
3724            pumps: u32,
3725            button: Vec2,
3726        }
3727
3728        impl EventSource for Profiling {
3729            fn pump_events(&mut self, out: &mut Vec<Event>) {
3730                self.pumps += 1;
3731                if self.pumps == 1 {
3732                    out.extend(tap(Key::F3));
3733                } else if self.pumps == FRAMES {
3734                    out.push(Event::MouseMoved(self.button));
3735                    out.extend([true, false].map(|pressed| Event::MouseButton {
3736                        button: MouseButton::Left,
3737                        pressed,
3738                    }));
3739                } else if self.pumps > FRAMES {
3740                    out.push(Event::CloseRequested);
3741                }
3742            }
3743
3744            fn set_modal_frame_callback(&mut self, _callback: Box<dyn FnMut(ModalFrame)>) {}
3745
3746            fn gpu_surface(&self) -> Option<GpuSurface<'_>> {
3747                Some(GpuSurface::Gl(&self.gl))
3748            }
3749
3750            fn window_size(&self) -> UVec2 {
3751                SIZE
3752            }
3753        }
3754
3755        /// A complete event of the trace: its track, name, start and end,
3756        /// and its frame's number, for a frame.
3757        #[derive(Debug)]
3758        struct Span {
3759            tid: i64,
3760            name: String,
3761            start: i64,
3762            end: i64,
3763            index: Option<i64>,
3764        }
3765
3766        fn spans(text: &str) -> (Vec<(i64, String)>, Vec<Span>) {
3767            let value = json::parse(text, Limits::default()).expect("the trace parses");
3768            let events = value
3769                .get("traceEvents")
3770                .and_then(Value::as_array)
3771                .expect("its events");
3772            let (mut threads, mut spans) = (Vec::new(), Vec::new());
3773            for event in events {
3774                let int = |key: &str| event.get(key).and_then(Value::as_i64);
3775                let text =
3776                    |value: Option<&Value>| value.and_then(Value::as_str).map(str::to_string);
3777                let args = event.get("args");
3778                let tid = int("tid").expect("a track");
3779                match text(event.get("ph")).as_deref() {
3780                    Some("M") => {
3781                        let name = text(args.and_then(|args| args.get("name")));
3782                        threads.push((tid, name.expect("a thread's name")));
3783                    }
3784                    Some("X") => {
3785                        let start = int("ts").expect("a start");
3786                        spans.push(Span {
3787                            tid,
3788                            name: text(event.get("name")).expect("a name"),
3789                            start,
3790                            end: start + int("dur").expect("a length"),
3791                            index: args
3792                                .and_then(|args| args.get("index"))
3793                                .and_then(Value::as_i64),
3794                        });
3795                    }
3796                    other => panic!("an event of phase {other:?}"),
3797                }
3798            }
3799            (threads, spans)
3800        }
3801
3802        #[test]
3803        fn the_loop_times_each_render_for_the_profiler_and_its_trace_has_a_gpu_track() {
3804            let expected = env::var("NADIR_EXPECT_GL_RENDERER").unwrap_or_default();
3805            let Some(gl) = super::steady_frames::headless(&expected) else {
3806                return;
3807            };
3808            let button = write_trace_button();
3809            let mut window = Profiling {
3810                gl,
3811                pumps: 0,
3812                button,
3813            };
3814            let mut device = Device::new(GpuSurface::Gl(&window.gl)).expect("a device");
3815            let renderer = device.caps().renderer.clone();
3816            assert!(renderer.contains(&expected), "{renderer} is not {expected}");
3817            if !device.caps().timer_queries {
3818                assert!(expected.is_empty(), "`{renderer}` has no timer queries");
3819                return;
3820            }
3821            let config = RenderConfig {
3822                virtual_resolution: Config::default().virtual_resolution,
3823            };
3824            let renderer = Renderer::new(&mut device, &config).expect("a renderer");
3825            let folder = env::temp_dir().join(format!("nadir-engine-gpu-trace-{}", process::id()));
3826            let _ = fs::remove_dir_all(&folder);
3827            let mut app = App::new(Config::default());
3828            app.debug.write_traces_in(folder.clone());
3829            app.run_loop(&mut window, Some(Graphics { renderer, device }))
3830                .expect("the frames draw");
3831            let files: Vec<PathBuf> = fs::read_dir(&folder)
3832                .expect("the trace's folder")
3833                .map(|entry| entry.expect("an entry").path())
3834                .collect();
3835            let [file] = &files[..] else {
3836                panic!("one trace: {files:?}");
3837            };
3838            let text = fs::read_to_string(file).expect("the trace");
3839            fs::remove_dir_all(&folder).expect("remove the folder");
3840
3841            let (threads, spans) = spans(&text);
3842            assert_eq!(threads, [(1, "main".to_string()), (2, "gpu".to_string())]);
3843            let frames: Vec<&Span> = spans
3844                .iter()
3845                .filter(|span| span.tid == 1 && span.name == "frame")
3846                .collect();
3847            // Frames 0 to 38 were pushed when frame 39 wrote the trace.
3848            assert_eq!(frames.len(), FRAMES as usize - 1);
3849            let gpu: Vec<&Span> = spans.iter().filter(|span| span.tid == 2).collect();
3850            // Each timed frame, then its passes: every frame but the last
3851            // few, whose times were not read back yet (two or three renders
3852            // later, here), and on llvmpipe the first, which it times at
3853            // hours. A render is untimed while the GPU is behind.
3854            assert!(gpu.len().is_multiple_of(3), "{gpu:?}");
3855            let untimed: Vec<i64> = frames
3856                .iter()
3857                .filter_map(|cpu| cpu.index)
3858                .filter(|&index| !gpu.iter().any(|span| span.index == Some(index)))
3859                .collect();
3860            assert!(
3861                untimed.len() <= FRAMES as usize / 4,
3862                "frames without a GPU time: {untimed:?}"
3863            );
3864            let mut free = 0;
3865            let mut last = None;
3866            for passes in gpu.chunks(3) {
3867                let [frame, world, output] = passes else {
3868                    unreachable!()
3869                };
3870                let names = [&frame.name, &world.name, &output.name].map(String::as_str);
3871                assert_eq!(names, ["frame", "world", "output"]);
3872                // The passes fill the frame, one after the other, after the
3873                // frame before on the GPU.
3874                assert_eq!((world.start, world.end), (frame.start, output.start));
3875                assert_eq!(output.end, frame.end);
3876                assert!(frame.start >= free, "{frame:?} starts before {free}");
3877                let index = frame.index.expect("a GPU frame's number");
3878                assert!(last < Some(index), "frame {index} after {last:?}");
3879                last = Some(index);
3880                // Each frame's GPU time is its own, placed from when its
3881                // drawing started: inside the frame on the processor, after
3882                // its update, so its passes start no sooner; and where the
3883                // frame before on the track had ended, then, before the
3884                // renderer's own scope.
3885                let cpu = frames
3886                    .iter()
3887                    .find(|cpu| cpu.index == Some(index))
3888                    .expect("its frame on the processor");
3889                let updated = spans
3890                    .iter()
3891                    .filter(|span| span.tid == 1 && span.name == "nadir::debug_ui")
3892                    .find(|span| cpu.start <= span.start && span.end <= cpu.end)
3893                    .expect("its debug UI's scope");
3894                assert!(frame.start >= updated.end, "{frame:?} before {updated:?}");
3895                if frame.start > free {
3896                    let render = spans
3897                        .iter()
3898                        .filter(|span| span.tid == 1 && span.name == "nadir::render")
3899                        .find(|span| cpu.start <= span.start && span.end <= cpu.end)
3900                        .expect("its render's scope");
3901                    assert!(frame.start <= render.start, "{frame:?} after {render:?}");
3902                }
3903                free = frame.end;
3904            }
3905        }
3906    }
3907}