use std::any::type_name;
use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;
use std::time::{Duration, Instant};
use nadir_assets::{AssetServer, FinalizeCtx, OnFailure};
use nadir_core::UVec2;
use nadir_core::log::{debug, error};
use nadir_core::profile::{self, ScopeRecord};
use nadir_core::time::{FixedClock, Stopwatch};
use nadir_ecs::{Component, FixedStage, FixedSystem, FrameStage, FrameSystem, Schedule, World};
use nadir_gfx::{Device, PassTarget, RenderTargetId, TextureFormat};
use nadir_input::{ActionKind, ActionMap, ActionSet, ActionState, Input, InputPlayer};
use nadir_platform::{
Event, GpuSurface, ModalFrame, Platform, WindowConfig, precise_sleep, show_error_dialog,
};
use nadir_render::{FrameStats, Output, RenderConfig, RenderFrame, Renderer, TileLayers};
use nadir_scene::{FromValue, PrefabLibrary, TypeRegistry};
use crate::animation::AnimationClock;
use crate::limiter::FrameLimiter;
use crate::replay::{PlayReplay, ReplayInput};
use crate::{
AnimationFinished, Animator, Clips, Collider, CollisionLayers, Collisions, Error, Facing,
Parent, Player, PrevTransform, Replay, SaveId, Sprite, TickStats, Transform, TriggerEnter,
TriggerExit, Velocity, glue, log_file,
};
pub const TICK_HZ: u32 = 60;
const MAX_FRAME: Duration = Duration::from_millis(250);
const PROFILE_RECORDS: usize = 1_024;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Config {
pub title: String,
pub studio: String,
pub game: String,
pub window_size: UVec2,
pub min_window_size: UVec2,
pub resizable: bool,
pub fullscreen: bool,
pub frame_rate_limit: Option<u32>,
pub vsync: bool,
pub virtual_resolution: UVec2,
pub assets: PathBuf,
}
impl Default for Config {
fn default() -> Self {
Self {
title: "Nadir".to_string(),
studio: "Nadir".to_string(),
game: "Nadir".to_string(),
window_size: UVec2::new(1280, 720),
min_window_size: UVec2::new(320, 180),
resizable: true,
fullscreen: false,
frame_rate_limit: Some(60),
vsync: true,
virtual_resolution: UVec2::new(480, 270),
assets: PathBuf::from("assets"),
}
}
}
impl Config {
fn window(&self) -> WindowConfig {
WindowConfig {
title: self.title.clone(),
size: self.window_size,
min_size: self.min_window_size,
resizable: self.resizable,
fullscreen: self.fullscreen,
vsync: self.vsync,
}
}
}
pub(crate) type LatchFn = Box<dyn FnMut(&mut Input, &World)>;
struct Actions {
set: Option<&'static str>,
latch: LatchFn,
replay: Option<Box<dyn PlayReplay>>,
}
impl Actions {
fn none() -> Self {
Self {
set: None,
latch: latch_into_nothing(),
replay: None,
}
}
}
fn latch_into_nothing() -> LatchFn {
let map = ActionMap::<NoActions>::new().expect("a set of one action is valid");
let mut state = ActionState::new();
Box::new(move |input, _| input.latch(&map, &mut state))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NoActions {
Nothing,
}
impl ActionSet for NoActions {
const ALL: &'static [Self] = &[NoActions::Nothing];
fn index(self) -> usize {
0
}
fn name(self) -> &'static str {
"nothing"
}
fn kind(self) -> ActionKind {
ActionKind::Button
}
}
trait EventSource {
fn pump_events(&mut self, out: &mut Vec<Event>);
fn set_modal_frame_callback(&mut self, callback: Box<dyn FnMut(ModalFrame)>);
fn gpu_surface(&self) -> Option<GpuSurface<'_>> {
None
}
fn window_size(&self) -> UVec2 {
UVec2::ZERO
}
}
impl EventSource for Platform {
fn pump_events(&mut self, out: &mut Vec<Event>) {
Platform::pump_events(self, out);
}
fn set_modal_frame_callback(&mut self, callback: Box<dyn FnMut(ModalFrame)>) {
Platform::set_modal_frame_callback(self, callback);
}
fn gpu_surface(&self) -> Option<GpuSurface<'_>> {
Some(Platform::gpu_surface(self))
}
fn window_size(&self) -> UVec2 {
Platform::window_size(self)
}
}
struct Graphics {
renderer: Renderer,
device: Device,
}
impl Graphics {
fn draw(&mut self, world: &World, surface: GpuSurface<'_>, size: UVec2) -> Result<(), Error> {
self.device.begin_frame(surface)?;
self.render(world, PassTarget::Surface, size)?;
self.device.end_frame(surface)?;
self.finish_loads(world, false);
Ok(())
}
fn draw_offscreen(
&mut self,
world: &World,
target: RenderTargetId,
size: UVec2,
) -> Result<Vec<u8>, Error> {
self.device.begin_offscreen_frame()?;
self.render(world, PassTarget::RenderTarget(target), size)?;
self.device.end_offscreen_frame()?;
self.finish_loads(world, true);
Ok(self.device.read_pixels(target)?)
}
fn render(&mut self, world: &World, target: PassTarget, size: UVec2) -> Result<(), Error> {
let stats = {
let assets = world.resource::<AssetServer>();
let tiles = world.resource::<TileLayers>();
let frame = world.resource::<RenderFrame>();
let output = Output { target, size };
self.renderer
.render(&mut self.device, &assets, &tiles, &frame, output)?
};
*world.resource_mut::<FrameStats>() = stats;
Ok(())
}
fn finish_loads(&mut self, world: &World, wait: bool) {
let pending = world.resource::<AssetServer>().has_pending();
if pending {
let mut server = world.resource_mut::<AssetServer>();
let mut ctx = FinalizeCtx::new().with(&mut self.device);
if wait {
server.finish_all_loads(&mut ctx);
} else {
server.finish_completed_loads(&mut ctx);
}
}
}
}
struct EngineCore {
app: App,
stopwatch: Stopwatch,
graphics: Option<Graphics>,
error: Option<Error>,
#[cfg(feature = "dev")]
allocs_at_frame_end: nadir_platform::AllocCounts,
}
impl EngineCore {
fn frame(&mut self, events: &[Event], window: Option<(GpuSurface<'_>, UVec2)>) {
let elapsed = self.stopwatch.lap();
self.app.update(elapsed, events);
if let (Some(graphics), Some((surface, size))) = (&mut self.graphics, window)
&& let Err(error) = graphics.draw(&self.app.world, surface, size)
{
self.error.get_or_insert(error);
}
#[cfg(feature = "dev")]
{
let now = nadir_platform::thread_alloc_counts();
let allocs = crate::FrameAllocs(now.since(self.allocs_at_frame_end));
*self.app.world.resource_mut::<crate::FrameAllocs>() = allocs;
self.allocs_at_frame_end = now;
}
}
}
pub struct App {
config: Config,
world: World,
schedule: Schedule,
actions: Actions,
clock: FixedClock,
profile: Vec<ScopeRecord>,
}
impl App {
pub fn new(config: Config) -> Self {
let on_failure = if cfg!(feature = "dev") {
OnFailure::Placeholder
} else {
OnFailure::Nothing
};
let mut world = World::new();
world.insert_resource(Input::new());
world.insert_resource(AssetServer::new(&config.assets, on_failure));
world.insert_resource(RenderFrame::new());
world.insert_resource(TileLayers::new());
world.insert_resource(FrameStats::default());
world.insert_resource(TickStats::default());
world.insert_resource(Collisions::new());
world.insert_resource(Clips::new());
world.insert_resource(CollisionLayers::default());
world.insert_resource(PrefabLibrary::new());
world.insert_resource(AnimationClock::default());
#[cfg(feature = "dev")]
world.insert_resource(crate::FrameAllocs::default());
world.add_event::<TriggerEnter>();
world.add_event::<TriggerExit>();
world.add_event::<AnimationFinished>();
let mut registry = TypeRegistry::new();
registry.register_component::<Transform>();
registry.register_component::<Velocity>();
registry.register_component::<Player>();
registry.register_component::<SaveId>();
registry.register_component::<Facing>();
registry.register_component::<Sprite>();
registry.register_component::<Collider>();
registry.register_component::<Animator>();
registry.register_components(&mut world);
world.insert_resource(registry);
world.register::<PrevTransform>();
world.register::<Sprite>();
world.register::<Collider>();
world.register::<Parent>();
world.register::<Animator>();
let mut schedule = Schedule::new();
schedule
.add_fixed(FixedStage::Input, "nadir::snapshot", glue::snapshot)
.add_fixed(FixedStage::Movement, "nadir::movement", glue::movement)
.add_fixed(
FixedStage::PostMovement,
"nadir::parent_offsets",
glue::parent_offsets,
)
.add_fixed(FixedStage::PostMovement, "nadir::triggers", glue::triggers)
.add_frame(FrameStage::Animate, "nadir::animate", glue::animate)
.add_frame(
FrameStage::Extract,
"nadir::extract_sprites",
glue::extract_sprites,
);
Self {
config,
world,
schedule,
actions: Actions::none(),
clock: FixedClock::new(TICK_HZ, MAX_FRAME),
profile: Vec::new(),
}
}
#[must_use]
pub fn insert_resource<R: 'static>(mut self, resource: R) -> Self {
self.world.insert_resource(resource);
self
}
#[must_use]
pub fn add_event<T: Clone + 'static>(mut self) -> Self {
self.world.add_event::<T>();
self
}
#[must_use]
pub fn register_component<T: Component + FromValue>(mut self) -> Self {
self.world
.resource_mut::<TypeRegistry>()
.register_component::<T>();
self.world.register::<T>();
self
}
#[must_use]
pub fn collision_layers(self, names: &[&str]) -> Self {
*self.world.resource_mut::<CollisionLayers>() = CollisionLayers::new(names);
self
}
#[must_use]
pub fn add_actions<A: ActionSet>(mut self, map: ActionMap<A>) -> Self {
let set = type_name::<A>();
if let Some(existing) = self.actions.set {
assert!(
existing == set,
"an App has one action set: it has `{existing}`, so it cannot add `{set}`",
);
}
assert!(
self.actions.replay.is_none(),
"a replay is playing: play_replay must come after add_actions"
);
self.world.insert_resource(map);
self.world.insert_resource(ActionState::<A>::new());
self.actions = Actions {
set: Some(set),
latch: Box::new(|input, world| {
let map = world.resource::<ActionMap<A>>();
let mut state = world.resource_mut::<ActionState<A>>();
input.latch(&map, &mut state);
}),
replay: None,
};
self
}
#[must_use]
pub fn play_replay<A: ActionSet>(mut self, replay: InputPlayer<'static, A>) -> Self {
let set = type_name::<A>();
assert!(
self.actions.set == Some(set),
"a replay of `{set}` plays into those actions: add them with add_actions first"
);
let replay = ReplayInput::new(replay, latch_into_nothing());
let status = match replay.ahead() {
Ok(true) => Replay::Playing { ticks: 0 },
Ok(false) => Replay::Ended { ticks: 0 },
Err(error) => failed(0, error),
};
self.actions.replay = matches!(status, Replay::Playing { .. })
.then(|| Box::new(replay) as Box<dyn PlayReplay>);
self.world.insert_resource(status);
self
}
pub fn world_hash(&self) -> u64 {
crate::world_hash(&self.world)
}
#[must_use]
pub fn add_fixed_system(
mut self,
stage: FixedStage,
name: &'static str,
system: FixedSystem,
) -> Self {
self.schedule.add_fixed(stage, name, system);
self
}
#[must_use]
pub fn add_frame_system(
mut self,
stage: FrameStage,
name: &'static str,
system: FrameSystem,
) -> Self {
self.schedule.add_frame(stage, name, system);
self
}
pub fn world(&self) -> &World {
&self.world
}
pub fn world_mut(&mut self) -> &mut World {
&mut self.world
}
pub fn schedule(&self) -> &Schedule {
&self.schedule
}
pub fn update(&mut self, elapsed: Duration, events: &[Event]) {
{
let mut input = self.world.resource_mut::<Input>();
for event in events {
input.handle(event);
}
}
let frame = self.clock.begin_frame(elapsed);
let mut stats = TickStats::default();
while let Some(tick) = self.clock.consume_tick() {
let start = Instant::now();
let replayed = {
let mut input = self.world.resource_mut::<Input>();
match &mut self.actions.replay {
Some(replay) => {
let ticks = replay.latch(&mut input, &self.world);
*self.world.resource_mut::<Replay>() = Replay::Playing { ticks };
true
}
None => {
(self.actions.latch)(&mut input, &self.world);
false
}
}
};
self.schedule.run_fixed(&mut self.world, &tick);
if replayed {
self.end_replay_tick();
}
let took = start.elapsed();
stats.ticks += 1;
stats.time += took;
stats.longest = stats.longest.max(took);
}
*self.world.resource_mut::<TickStats>() = stats;
{
let mut out = self.world.resource_mut::<RenderFrame>();
out.clear();
out.time = simulated_time(&self.clock);
}
self.schedule.run_frame(&mut self.world, &frame);
profile::take_frame(&mut self.profile);
if !self.profile.is_empty() {
let more = PROFILE_RECORDS.saturating_sub(self.profile.len());
self.profile.reserve(more);
}
}
pub fn run(self) -> Result<(), Error> {
log_file::start(&self.config.studio, &self.config.game);
let title = self.config.title.clone();
let mut platform =
Platform::new(&self.config.window()).map_err(|error| fatal(&title, error.into()))?;
let graphics = match Device::new(platform.gpu_surface()) {
Ok(mut device) => {
let config = RenderConfig {
virtual_resolution: self.config.virtual_resolution,
};
let renderer = Renderer::new(&mut device, &config)
.map_err(|error| fatal(&title, error.into()))?;
Some(Graphics { renderer, device })
}
Err(error) => {
error!("no GPU device, so the game draws nothing: {error}");
None
}
};
self.run_loop(&mut platform, graphics)
.map_err(|error| fatal(&title, error))
}
fn run_loop(
self,
window: &mut dyn EventSource,
graphics: Option<Graphics>,
) -> Result<(), Error> {
debug!("the systems, in the order they run:");
for system in self.schedule.describe() {
debug!(" {system}");
}
let mut limiter = FrameLimiter::new(self.config.frame_rate_limit, Instant::now());
let core = Rc::new(RefCell::new(EngineCore {
app: self,
stopwatch: Stopwatch::start(),
graphics,
error: None,
#[cfg(feature = "dev")]
allocs_at_frame_end: nadir_platform::thread_alloc_counts(),
}));
let modal_core = Rc::clone(&core);
window.set_modal_frame_callback(Box::new(move |_frame| {
if let Ok(mut core) = modal_core.try_borrow_mut() {
core.frame(&[], None);
}
}));
let mut events = Vec::with_capacity(256);
loop {
window.pump_events(&mut events);
if events.contains(&Event::CloseRequested) {
break;
}
{
let mut core = core.borrow_mut();
let surface = window
.gpu_surface()
.map(|surface| (surface, window.window_size()));
core.frame(&events, surface);
if let Some(error) = core.error.take() {
return Err(error);
}
}
events.clear();
if let Some(due) = limiter.end_of_frame(Instant::now()) {
precise_sleep(due);
}
}
Ok(())
}
pub fn offscreen(self, size: UVec2) -> Result<Offscreen, Error> {
let mut device = Device::new_headless()?;
let config = RenderConfig {
virtual_resolution: self.config.virtual_resolution,
};
let renderer = Renderer::new(&mut device, &config)?;
let target = device.create_render_target(size, TextureFormat::Rgba8Srgb)?;
Ok(Offscreen {
app: self,
graphics: Graphics { renderer, device },
target,
size,
})
}
}
pub struct Offscreen {
app: App,
graphics: Graphics,
target: RenderTargetId,
size: UVec2,
}
impl Offscreen {
pub fn frame(&mut self, elapsed: Duration, events: &[Event]) -> Result<Vec<u8>, Error> {
self.app.update(elapsed, events);
self.graphics
.draw_offscreen(&self.app.world, self.target, self.size)
}
pub fn app(&self) -> &App {
&self.app
}
pub fn size(&self) -> UVec2 {
self.size
}
pub fn renderer(&self) -> &str {
&self.graphics.device.caps().renderer
}
}
impl App {
fn end_replay_tick(&mut self) {
let Some(replay) = &self.actions.replay else {
return;
};
let ticks = replay.ticks();
let status = match replay.ahead() {
Ok(true) => return,
Ok(false) => Replay::Ended { ticks },
Err(error) => failed(ticks, error),
};
*self.world.resource_mut::<Replay>() = status;
self.actions.replay = None;
}
}
fn failed(ticks: u64, error: &nadir_input::InputError) -> Replay {
error!(
"the replay's tick {} cannot be read: {error}; the input is live from now on",
ticks + 1
);
Replay::Failed {
ticks,
error: error.clone(),
}
}
fn simulated_time(clock: &FixedClock) -> Duration {
let hz = u128::from(TICK_HZ);
let ticks = u128::from(clock.ticks()) * 1_000_000_000 / hz;
let part = (f64::from(clock.alpha()) * 1e9 / TICK_HZ as f64) as u128;
Duration::from_nanos(u64::try_from(ticks + part).unwrap_or(u64::MAX))
}
fn fatal(title: &str, error: Error) -> Error {
error!("{error}");
show_error_dialog(title, &error.to_string());
error
}
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
use std::thread;
use nadir_core::time::{Frame, Tick};
use nadir_core::{Key, Vec2};
use nadir_ecs::Entity;
use nadir_input::{Binding, InputRecorder};
use super::*;
const TICK: Duration = Duration::from_nanos(16_666_667);
const MS: Duration = Duration::from_millis(1);
fn app() -> App {
App::new(Config::default())
}
#[derive(Default)]
struct Log {
ticks: Cell<u64>,
frames: Cell<u64>,
seen: RefCell<Vec<String>>,
values: RefCell<Vec<f32>>,
}
type Shared = Rc<Log>;
fn shared() -> Shared {
Rc::default()
}
fn count_ticks(world: &World, _: &Tick) {
let log = world.resource::<Shared>();
log.ticks.set(log.ticks.get() + 1);
}
fn count_frames(world: &World, _: &Frame) {
let log = world.resource::<Shared>();
log.frames.set(log.frames.get() + 1);
}
fn counting_app(log: &Shared) -> App {
app()
.insert_resource(Rc::clone(log))
.add_fixed_system(FixedStage::Gameplay, "count_ticks", count_ticks)
.add_frame_system(FrameStage::Ui, "count_frames", count_frames)
}
fn simulate(app: &mut App, frame_length: Duration, total: Duration) {
let mut passed = Duration::ZERO;
while passed < total {
let step = frame_length.min(total - passed);
app.update(step, &[]);
passed += step;
}
}
#[test]
fn the_default_configuration_is_a_resizable_window_at_60_frames() {
let config = Config::default();
assert_eq!(config.title, "Nadir");
assert_eq!(config.studio, "Nadir");
assert_eq!(config.game, "Nadir");
assert_eq!(config.window_size, UVec2::new(1280, 720));
assert_eq!(config.min_window_size, UVec2::new(320, 180));
assert!(config.resizable);
assert!(!config.fullscreen);
assert_eq!(config.frame_rate_limit, Some(60));
assert!(config.vsync);
assert_eq!(config.virtual_resolution, UVec2::new(480, 270));
assert_eq!(config.assets, PathBuf::from("assets"));
}
#[test]
fn the_window_is_the_one_the_configuration_asks_for() {
let config = Config {
title: "Sandbox".to_string(),
studio: "Studio".to_string(),
game: "Game".to_string(),
window_size: UVec2::new(960, 540),
min_window_size: UVec2::new(480, 270),
resizable: false,
fullscreen: true,
frame_rate_limit: None,
vsync: false,
virtual_resolution: UVec2::new(320, 180),
assets: PathBuf::from("data"),
};
let expected = WindowConfig {
title: "Sandbox".to_string(),
size: UVec2::new(960, 540),
min_size: UVec2::new(480, 270),
resizable: false,
fullscreen: true,
vsync: false,
};
assert_eq!(config.window(), expected);
}
#[test]
fn the_schedule_prints_the_engines_systems_first_in_their_stages() {
let app = app()
.add_frame_system(FrameStage::Extract, "draw_ground", |_, _| {})
.add_fixed_system(FixedStage::Movement, "bounce", |_, _| {})
.add_fixed_system(FixedStage::Gameplay, "walk", |_, _| {})
.add_frame_system(FrameStage::Camera, "follow", |_, _| {})
.add_frame_system(FrameStage::Animate, "react", |_, _| {});
let printed: Vec<String> = app
.schedule()
.describe()
.map(|system| system.to_string())
.collect();
assert_eq!(
printed,
[
"tick Input: nadir::snapshot",
"tick Gameplay: walk",
"tick Movement: nadir::movement",
"tick Movement: bounce",
"tick PostMovement: nadir::parent_offsets",
"tick PostMovement: nadir::triggers",
"frame Animate: nadir::animate",
"frame Animate: react",
"frame Camera: follow",
"frame Extract: nadir::extract_sprites",
"frame Extract: draw_ground",
]
);
}
#[test]
fn the_engines_components_are_registered_and_eight_are_reflected() {
let app = app();
let world = app.world();
assert!(world.is_registered::<Transform>());
assert!(world.is_registered::<PrevTransform>());
assert!(world.is_registered::<Velocity>());
assert!(world.is_registered::<Sprite>());
assert!(world.is_registered::<Collider>());
assert!(world.is_registered::<Player>());
assert!(world.is_registered::<Parent>());
assert!(world.is_registered::<SaveId>());
assert!(world.is_registered::<Facing>());
assert!(world.is_registered::<Animator>());
let registry = world.resource::<TypeRegistry>();
let names: Vec<&str> = registry.iter().map(|it| it.name()).collect();
assert_eq!(
names,
[
"Transform",
"Velocity",
"Player",
"SaveId",
"Facing",
"Sprite",
"Collider",
"Animator"
]
);
assert!(world.contains_resource::<CollisionLayers>());
assert!(world.contains_resource::<PrefabLibrary>());
}
nadir_scene::reflect_newtype! {
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Score(u32);
}
impl Component for Score {}
#[test]
fn a_game_registers_its_reflected_components_and_events() {
#[derive(Clone)]
struct Scored;
let mut app = app()
.register_component::<Score>()
.add_event::<Scored>()
.add_fixed_system(FixedStage::Gameplay, "score", |world, _| {
world
.resource_mut::<nadir_ecs::Events<Scored>>()
.send(Scored);
});
assert!(
app.world()
.resource::<TypeRegistry>()
.get("Score")
.is_some()
);
let entity = app.world_mut().spawn().with(Score(3)).id();
assert_eq!(app.world().read::<Score>().get(entity), Some(&Score(3)));
app.update(TICK, &[]);
let events = app.world().resource::<nadir_ecs::Events<Scored>>();
assert_eq!(events.frame_events().len(), 0, "cleared after the frame");
}
fn note(world: &World, text: String) {
world.resource::<Shared>().seen.borrow_mut().push(text);
}
#[test]
fn a_frame_runs_its_ticks_and_then_its_frame_stages_in_order() {
let log = shared();
let mut app = app()
.insert_resource(Rc::clone(&log))
.add_fixed_system(FixedStage::Gameplay, "a", |world, tick| {
note(world, format!("a tick {}", tick.index));
})
.add_frame_system(FrameStage::Ui, "c", |world, _| note(world, "c".into()))
.add_fixed_system(FixedStage::Input, "b", |world, tick| {
note(world, format!("b tick {}", tick.index));
})
.add_frame_system(FrameStage::Camera, "d", |world, _| note(world, "d".into()));
app.update(40 * MS, &[]);
assert_eq!(
*log.seen.borrow(),
["b tick 0", "a tick 0", "b tick 1", "a tick 1", "d", "c"]
);
}
#[test]
fn a_frame_shorter_than_a_tick_still_runs_the_frame_stages() {
let log = shared();
let mut app = counting_app(&log);
app.update(5 * MS, &[]);
app.update(5 * MS, &[]);
assert_eq!((log.ticks.get(), log.frames.get()), (0, 2));
app.update(10 * MS, &[]);
assert_eq!((log.ticks.get(), log.frames.get()), (1, 3));
}
#[test]
fn systems_get_the_tick_length_and_the_frame_time() {
let log = shared();
let mut app = app()
.insert_resource(Rc::clone(&log))
.add_fixed_system(FixedStage::Gameplay, "tick", |world, tick| {
let log = world.resource::<Shared>();
log.values.borrow_mut().push(tick.dt);
})
.add_frame_system(FrameStage::Ui, "frame", |world, frame| {
let log = world.resource::<Shared>();
log.values.borrow_mut().extend([frame.dt, frame.alpha]);
});
app.update(20 * MS, &[]);
let values = log.values.borrow();
assert_eq!(values[..2], [1.0 / 60.0, 0.02]);
assert!((values[2] - 0.2).abs() < 1e-6, "{values:?}");
}
#[test]
fn tick_stats_count_this_frames_ticks_for_its_frame_stages() {
let log = shared();
let mut app = app()
.insert_resource(Rc::clone(&log))
.add_fixed_system(FixedStage::Gameplay, "slow", |_, tick| {
if tick.index == 1 {
thread::sleep(3 * MS);
}
})
.add_frame_system(FrameStage::Ui, "read", |world, _| {
let stats = *world.resource::<TickStats>();
note(world, format!("{}", stats.ticks));
});
app.update(40 * MS, &[]);
let two = *app.world().resource::<TickStats>();
assert_eq!(two.ticks, 2);
assert!(two.longest >= 3 * MS && two.time >= two.longest, "{two:?}");
app.update(5 * MS, &[]);
assert_eq!(*app.world().resource::<TickStats>(), TickStats::default());
assert_eq!(*log.seen.borrow(), ["2", "0"]);
}
#[test]
fn the_frame_time_is_how_long_the_simulation_has_run() {
let mut app = app();
app.update(TICK / 4, &[]);
let time = |app: &App| app.world().resource::<RenderFrame>().time;
let close = |found: Duration, expected: Duration| {
assert!(
found.abs_diff(expected) < Duration::from_micros(1),
"{found:?}, not {expected:?}"
);
};
close(time(&app), TICK / 4);
for _ in 0..3 {
app.update(TICK, &[]);
}
close(time(&app), TICK * 3 + TICK / 4);
app.update(Duration::from_secs(5), &[]);
close(time(&app), TICK * 3 + TICK / 4 + Duration::from_millis(250));
app.world().resource_mut::<RenderFrame>().clear();
assert!(time(&app) > Duration::ZERO);
}
#[test]
fn ten_seconds_run_600_ticks_whatever_the_frame_rate() {
let frame_lengths = [
TICK, Duration::from_nanos(6_944_444), Duration::from_micros(33_333), Duration::from_millis(3),
Duration::from_millis(110),
];
for frame_length in frame_lengths {
let log = shared();
let mut app = counting_app(&log);
simulate(&mut app, frame_length, Duration::from_secs(10));
assert_eq!(log.ticks.get(), 600, "frames of {frame_length:?}");
assert!(log.frames.get() >= 90, "frames of {frame_length:?}");
}
}
#[test]
fn a_simulated_hitch_runs_a_quarter_second_of_ticks_and_no_more() {
let log = shared();
let mut app = counting_app(&log);
simulate(&mut app, 10 * MS, Duration::from_secs(1));
assert_eq!(log.ticks.get(), 60);
app.update(Duration::from_secs(1), &[]);
assert_eq!(log.ticks.get(), 60 + 15);
simulate(&mut app, 10 * MS, Duration::from_secs(1));
assert_eq!(log.ticks.get(), 60 + 15 + 60);
}
struct Script {
pumps: u32,
close: Box<dyn FnMut(u32) -> bool>,
asked_to_close: bool,
modal_frames: Box<dyn FnMut(u32) -> u32>,
modal_frame_callback: Option<Box<dyn FnMut(ModalFrame)>>,
}
impl Script {
fn closing_when(close: impl FnMut(u32) -> bool + 'static) -> Self {
Self {
pumps: 0,
close: Box::new(close),
asked_to_close: false,
modal_frames: Box::new(|_| 0),
modal_frame_callback: None,
}
}
fn with_modal_frames(mut self, modal_frames: impl FnMut(u32) -> u32 + 'static) -> Self {
self.modal_frames = Box::new(modal_frames);
self
}
}
impl EventSource for Script {
fn pump_events(&mut self, out: &mut Vec<Event>) {
assert!(!self.asked_to_close, "the loop went on after a close");
self.pumps += 1;
let frame = ModalFrame {
size: UVec2::new(800, 600),
scale_factor: 1.0,
};
for _ in 0..(self.modal_frames)(self.pumps) {
let callback = self.modal_frame_callback.as_mut();
(callback.expect("the loop set a modal frame callback"))(frame);
}
out.push(Event::Focused(true));
out.push(Event::Resized(UVec2::new(800, 600)));
if (self.close)(self.pumps) {
self.asked_to_close = true;
out.push(Event::CloseRequested);
}
}
fn set_modal_frame_callback(&mut self, callback: Box<dyn FnMut(ModalFrame)>) {
self.modal_frame_callback = Some(callback);
}
}
#[test]
fn the_loop_runs_until_the_window_asks_to_close() {
let log = shared();
let mut app = counting_app(&log);
app.config.frame_rate_limit = None;
let mut window = Script::closing_when(|pumps| pumps == 8);
app.run_loop(&mut window, None)
.expect("no error without a device");
assert_eq!(window.pumps, 8);
assert_eq!(log.frames.get(), 7);
}
#[test]
fn a_close_request_on_the_first_pump_runs_no_frame() {
let log = shared();
let app = counting_app(&log);
app.run_loop(&mut Script::closing_when(|_| true), None)
.expect("no error without a device");
assert_eq!((log.ticks.get(), log.frames.get()), (0, 0));
}
#[test]
fn while_the_system_holds_the_loop_frames_run_from_the_callback() {
let log = shared();
let mut app = counting_app(&log);
app.config.frame_rate_limit = None;
let mut window = Script::closing_when(|pumps| pumps == 3)
.with_modal_frames(|pumps| if pumps == 2 { 5 } else { 0 });
app.run_loop(&mut window, None)
.expect("no error without a device");
assert_eq!(log.frames.get(), 7);
}
#[test]
fn modal_frames_keep_the_simulation_on_time() {
let log = shared();
let mut app = counting_app(&log)
.add_frame_system(FrameStage::Ui, "wait", |_, _| thread::sleep(10 * MS));
app.config.frame_rate_limit = None;
let start = Instant::now();
let mut window = Script::closing_when(|pumps| pumps == 2)
.with_modal_frames(|pumps| if pumps == 1 { 30 } else { 0 });
app.run_loop(&mut window, None)
.expect("no error without a device");
let elapsed = start.elapsed();
assert_eq!(log.frames.get(), 30 + 1);
let ticks = log.ticks.get();
assert!(ticks >= 17, "{ticks} ticks in {elapsed:?}");
}
#[test]
fn the_limiter_paces_the_loop() {
let log = shared();
let mut app = counting_app(&log);
app.config.frame_rate_limit = Some(200);
let start = Instant::now();
app.run_loop(&mut Script::closing_when(|pumps| pumps == 21), None)
.expect("no error without a device");
assert_eq!(log.frames.get(), 20);
assert!(
start.elapsed() >= Duration::from_millis(100),
"{:?}",
start.elapsed()
);
}
#[derive(Default)]
struct Hitch {
frames: RefCell<Vec<(u32, f32)>>,
ticks_this_frame: Cell<u32>,
stalled: Cell<bool>,
frames_since_stall: Cell<u32>,
}
#[test]
fn a_real_hitch_of_one_second_is_clamped_and_does_not_spiral() {
let hitch: Rc<Hitch> = Rc::default();
let app = app()
.insert_resource(Rc::clone(&hitch))
.add_fixed_system(FixedStage::Gameplay, "stall_once", |world, tick| {
let hitch = world.resource::<Rc<Hitch>>();
hitch.ticks_this_frame.set(hitch.ticks_this_frame.get() + 1);
if tick.index == 2 {
thread::sleep(Duration::from_secs(1));
hitch.stalled.set(true);
}
})
.add_frame_system(FrameStage::Ui, "record", |world, frame| {
let hitch = world.resource::<Rc<Hitch>>();
let ticks = hitch.ticks_this_frame.take();
hitch.frames.borrow_mut().push((ticks, frame.dt));
if hitch.stalled.get() {
hitch
.frames_since_stall
.set(hitch.frames_since_stall.get() + 1);
}
});
let start = Instant::now();
let script = Rc::clone(&hitch);
app.run_loop(
&mut Script::closing_when(move |pumps| {
script.frames_since_stall.get() > 6 || pumps > 600
}),
None,
)
.expect("no error without a device");
let elapsed = start.elapsed();
assert!(hitch.stalled.get(), "the stall never happened");
let frames = hitch.frames.borrow();
let most_ticks = frames.iter().map(|&(ticks, _)| ticks).max();
let longest_dt = frames.iter().map(|&(_, dt)| dt).fold(0.0, f32::max);
let total_ticks: u32 = frames.iter().map(|&(ticks, _)| ticks).sum();
assert_eq!(most_ticks, Some(15), "{frames:?}");
assert_eq!(longest_dt, 0.25, "{frames:?}");
let behind = elapsed.as_secs_f64() - f64::from(total_ticks) / 60.0;
assert!(
behind >= 0.74,
"{behind} s behind after {elapsed:?}: {frames:?}"
);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Act {
Move,
}
impl ActionSet for Act {
const ALL: &'static [Self] = &[Act::Move];
fn index(self) -> usize {
self as usize
}
fn name(self) -> &'static str {
"move"
}
fn kind(self) -> ActionKind {
ActionKind::Axis2
}
}
const SPEED: f32 = 120.0;
struct Mover(Entity);
fn texture() -> nadir_assets::Handle<nadir_render::Texture> {
nadir_assets::Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN))
}
fn moving_app(log: &Shared) -> App {
let mut map = ActionMap::<Act>::new().expect("a valid set");
let wasd = Binding::KeyComposite2 {
up: Key::W,
down: Key::S,
left: Key::A,
right: Key::D,
};
map.bind(Act::Move, 0, wasd).expect("fits");
let mut app = app()
.add_actions(map)
.insert_resource(Rc::clone(log))
.add_fixed_system(FixedStage::Gameplay, "steer", |world, _| {
let direction = world.resource::<ActionState<Act>>().axis2(Act::Move);
let mover = world.resource::<Mover>().0;
if let Some(velocity) = world.write::<Velocity>().get_mut(mover) {
velocity.0 = direction * SPEED;
}
})
.add_frame_system(FrameStage::Extract, "record", |world, _| {
let x = world.resource::<RenderFrame>().sprites[0].position.x;
world.resource::<Shared>().values.borrow_mut().push(x);
});
let mover = app
.world_mut()
.spawn()
.with(Transform::at(Vec2::ZERO))
.with(Velocity::default())
.with(Sprite::new(texture(), Vec2::splat(8.0)))
.id();
app.insert_resource(Mover(mover))
}
fn key(key: Key, pressed: bool) -> Event {
Event::Key {
key,
pressed,
repeat: false,
}
}
fn x(app: &App) -> f32 {
let mover = app.world().resource::<Mover>().0;
app.world()
.read::<Transform>()
.get(mover)
.expect("it is")
.position
.x
}
#[test]
fn a_tap_between_ticks_moves_exactly_one_tick() {
let mut app = moving_app(&shared());
app.update(5 * MS, &[key(Key::D, true), key(Key::D, false)]);
assert_eq!(x(&app), 0.0, "no tick yet");
app.update(12 * MS, &[]);
assert_eq!(x(&app), SPEED / 60.0);
for _ in 0..10 {
app.update(16 * MS, &[]);
}
assert_eq!(x(&app), SPEED / 60.0, "and never again");
app.update(34 * MS, &[key(Key::D, true), key(Key::D, false)]);
assert_eq!(x(&app), 2.0 * SPEED / 60.0);
}
#[test]
fn a_held_key_moves_every_tick() {
let mut app = moving_app(&shared());
app.update(Duration::ZERO, &[key(Key::D, true)]);
for _ in 0..60 {
app.update(TICK, &[]);
}
assert!((x(&app) - SPEED).abs() < 1e-3, "{}", x(&app));
app.update(Duration::ZERO, &[key(Key::D, false)]);
app.update(20 * MS, &[]);
assert!((x(&app) - SPEED).abs() < 1e-3, "it stops: {}", x(&app));
}
#[test]
fn the_wheel_moves_on_each_tick_without_an_action_set() {
let log = shared();
let mut app = app().insert_resource(Rc::clone(&log)).add_fixed_system(
FixedStage::Input,
"zoom",
|world, _| {
let wheel = world.resource::<Input>().wheel();
world.resource::<Shared>().values.borrow_mut().push(wheel.y);
},
);
app.update(20 * MS, &[Event::MouseWheel(Vec2::new(0.0, 3.0))]);
app.update(20 * MS, &[]);
assert_eq!(*log.values.borrow(), [3.0, 0.0]);
}
#[test]
fn interpolation_draws_where_the_mover_was_one_tick_ago_at_any_frame_rate() {
let mut irregular = nadir_core::Pcg32::new(7, 1);
let rates: [(&str, Vec<Duration>); 5] = [
("60", vec![TICK; 120]),
("59.94", vec![Duration::from_nanos(16_683_350); 120]),
("144", vec![Duration::from_nanos(6_944_444); 288]),
("1 ms", vec![MS; 2000]),
(
"irregular",
(0..500)
.map(|_| Duration::from_micros(u64::from(irregular.range(1000..9000u32))))
.collect(),
),
];
for (name, frames) in rates {
let log = shared();
let mut app = moving_app(&log);
app.update(Duration::ZERO, &[key(Key::D, true)]);
let mut t = Duration::ZERO;
let mut expected = vec![0.0];
for frame in frames {
app.update(frame, &[]);
t += frame;
let x = SPEED as f64 * (t.as_secs_f64() - 1.0 / 60.0).max(0.0);
expected.push(x);
}
let drawn = log.values.borrow();
assert_eq!(drawn.len(), expected.len(), "{name}");
for (i, (&drawn, &expected)) in drawn.iter().zip(&expected).enumerate() {
assert!(
(f64::from(drawn) - expected).abs() < 2e-3,
"{name}: frame {i} drew {drawn}, not {expected}"
);
}
}
}
#[test]
#[should_panic(expected = "an App has one action set")]
fn a_second_action_set_is_refused() {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Menu {
Back,
}
impl ActionSet for Menu {
const ALL: &'static [Self] = &[Menu::Back];
fn index(self) -> usize {
0
}
fn name(self) -> &'static str {
"back"
}
fn kind(self) -> ActionKind {
ActionKind::Button
}
}
let map = ActionMap::<Menu>::new().expect("a valid set");
let _ = moving_app(&shared()).add_actions(map);
}
#[test]
fn the_same_action_set_again_replaces_its_bindings() {
let mut map = ActionMap::<Act>::new().expect("a valid set");
let arrows = Binding::KeyComposite2 {
up: Key::Up,
down: Key::Down,
left: Key::Left,
right: Key::Right,
};
map.bind(Act::Move, 0, arrows).expect("fits");
let mut app = moving_app(&shared()).add_actions(map);
app.update(20 * MS, &[key(Key::D, true)]);
assert_eq!(x(&app), 0.0, "D is no longer bound");
app.update(20 * MS, &[key(Key::Right, true)]);
assert_eq!(x(&app), SPEED / 60.0, "one latch a tick, with the new map");
}
fn recording(frames: &[&[Event]]) -> &'static [u8] {
let mut app = moving_app(&shared())
.insert_resource(InputRecorder::<Act>::new().expect("a valid set"))
.add_fixed_system(FixedStage::Input, "record", |world, _| {
let state = world.resource::<ActionState<Act>>();
world.resource_mut::<InputRecorder<Act>>().record(&state);
});
for events in frames {
app.update(TICK, events);
}
let bytes = app
.world()
.resource::<InputRecorder<Act>>()
.bytes()
.to_vec();
Box::leak(bytes.into_boxed_slice())
}
fn replaying(bytes: &'static [u8]) -> App {
let player = InputPlayer::<Act>::new(bytes).expect("a replay of Act");
moving_app(&shared()).play_replay(player)
}
fn replay(app: &App) -> Replay {
app.world().resource::<Replay>().clone()
}
fn moving(app: &App) -> (bool, bool, bool) {
let state = app.world().resource::<ActionState<Act>>();
(
state.pressed(Act::Move),
state.just_pressed(Act::Move),
state.just_released(Act::Move),
)
}
const STEP: f32 = SPEED / 60.0;
#[test]
fn a_replay_moves_as_the_recording_did_whatever_the_live_input() {
let bytes = recording(&[&[key(Key::D, true)], &[], &[]]);
let mut app = replaying(bytes);
assert_eq!(replay(&app), Replay::Playing { ticks: 0 });
let noise = [
Event::Focused(false),
Event::MouseWheel(Vec2::new(0.0, 3.0)),
Event::MouseMoved(Vec2::new(5.0, 5.0)),
key(Key::A, true),
];
app.update(TICK, &noise);
assert_eq!(
(x(&app), replay(&app)),
(STEP, Replay::Playing { ticks: 1 })
);
assert_eq!(moving(&app), (true, true, false));
app.update(TICK, &[]);
assert_eq!(replay(&app), Replay::Playing { ticks: 2 });
app.update(TICK, &[]);
assert_eq!(
(x(&app), replay(&app)),
(3.0 * STEP, Replay::Ended { ticks: 3 })
);
app.update(TICK, &[]);
assert_eq!(x(&app), 2.0 * STEP);
assert_eq!(moving(&app), (true, false, false));
assert_eq!(replay(&app), Replay::Ended { ticks: 3 });
}
#[test]
fn a_frame_of_two_ticks_plays_two_replayed_ticks_and_a_short_frame_none() {
let bytes = recording(&[&[key(Key::D, true)], &[], &[], &[]]);
let mut app = replaying(bytes);
app.update(40 * MS, &[]);
assert_eq!(
(x(&app), replay(&app)),
(2.0 * STEP, Replay::Playing { ticks: 2 })
);
app.update(5 * MS, &[]);
assert_eq!(
(x(&app), replay(&app)),
(2.0 * STEP, Replay::Playing { ticks: 2 })
);
app.update(40 * MS, &[]);
assert_eq!(
(x(&app), replay(&app)),
(4.0 * STEP, Replay::Ended { ticks: 4 })
);
}
#[test]
fn after_a_replay_the_live_ticks_have_only_the_live_keys_edges() {
let mut app = replaying(recording(&[&[key(Key::D, true)], &[]]));
app.update(TICK, &[]);
app.update(TICK, &[]);
assert_eq!(replay(&app), Replay::Ended { ticks: 2 });
app.update(TICK, &[]);
assert_eq!(moving(&app), (false, false, false));
let mut app = replaying(recording(&[&[], &[]]));
app.update(TICK, &[key(Key::D, true), key(Key::D, false)]);
app.update(TICK, &[]);
app.update(TICK, &[]);
assert_eq!(moving(&app), (false, false, false));
assert_eq!(x(&app), 0.0);
}
#[derive(Default)]
struct SeenReplays(Vec<Replay>);
#[test]
fn each_tick_sees_its_own_count_and_the_first_after_the_end_sees_it_ended() {
let mut app = replaying(recording(&[&[], &[], &[], &[]]))
.insert_resource(SeenReplays::default())
.add_fixed_system(FixedStage::Gameplay, "see", |world, _| {
let replay = world.resource::<Replay>().clone();
world.resource_mut::<SeenReplays>().0.push(replay);
});
app.update(TICK * 2, &[]);
app.update(TICK * 3, &[]);
let playing = |ticks| Replay::Playing { ticks };
assert_eq!(
app.world().resource::<SeenReplays>().0,
[
playing(1),
playing(2),
playing(3),
playing(4),
Replay::Ended { ticks: 4 }
]
);
}
#[test]
fn a_damaged_tick_fails_the_replay_and_the_input_goes_live() {
let mut bytes = recording(&[&[key(Key::D, true)], &[], &[]]).to_vec();
bytes[17 + 5] |= 0x80;
let mut app = replaying(Box::leak(bytes.into_boxed_slice()));
app.update(TICK, &[key(Key::A, true)]);
assert_eq!(x(&app), STEP, "the first tick plays");
let Replay::Failed { ticks: 1, error } = replay(&app) else {
panic!("{:?}", replay(&app));
};
assert!(error.to_string().contains("22"), "{error}");
app.update(TICK, &[]);
assert_eq!(x(&app), 0.0);
}
#[test]
fn a_replay_of_no_ticks_ends_at_once() {
let mut app = replaying(recording(&[]));
assert_eq!(replay(&app), Replay::Ended { ticks: 0 });
app.update(TICK, &[key(Key::D, true)]);
assert_eq!(x(&app), STEP, "live");
}
#[test]
#[should_panic(expected = "add them with add_actions first")]
fn a_replay_needs_its_actions_first() {
let bytes = recording(&[&[]]);
let _ = app().play_replay(InputPlayer::<Act>::new(bytes).expect("a replay"));
}
#[test]
#[should_panic(expected = "play_replay must come after add_actions")]
fn the_actions_cannot_be_added_while_a_replay_plays() {
let map = ActionMap::<Act>::new().expect("a valid set");
let _ = replaying(recording(&[&[]])).add_actions(map);
}
#[test]
fn the_world_hash_follows_the_reflected_components_only() {
let mut app = app();
let walker = app
.world_mut()
.spawn()
.with(Transform::at(Vec2::ZERO))
.with(Sprite::new(texture(), Vec2::ONE))
.id();
let start = app.world_hash();
assert_eq!(app.world_hash(), start);
app.world()
.write::<Sprite>()
.get_mut(walker)
.expect("drawn")
.size = Vec2::splat(2.0);
assert_eq!(
app.world_hash(),
start,
"a Sprite's size is left out, as animators write it"
);
app.world()
.write::<Sprite>()
.get_mut(walker)
.expect("drawn")
.layer = 2;
let layered = app.world_hash();
assert_ne!(layered, start, "a Sprite's layer is the game's, and hashed");
app.world()
.write::<Transform>()
.get_mut(walker)
.expect("placed")
.position
.x = 1.0;
assert_ne!(app.world_hash(), layered);
}
#[test]
fn the_render_frame_is_emptied_before_each_frame() {
let log = shared();
let mut app = app().insert_resource(Rc::clone(&log)).add_frame_system(
FrameStage::Camera,
"draw",
|world, _| {
let mut frame = world.resource_mut::<RenderFrame>();
let size = frame.sprites.len() as f32;
world.resource::<Shared>().values.borrow_mut().push(size);
frame.sprites.push(nadir_render::SpriteDraw::new(
texture(),
Vec2::ZERO,
Vec2::ONE,
));
},
);
for _ in 0..3 {
app.update(16 * MS, &[]);
}
assert_eq!(*log.values.borrow(), [0.0, 0.0, 0.0]);
}
#[test]
fn a_missing_resource_names_the_system_that_asked() {
let mut app = app().add_fixed_system(FixedStage::Gameplay, "needs_a_score", |world, _| {
let _ = world.resource::<u64>();
});
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
app.update(20 * MS, &[]);
}));
let payload = result.expect_err("a panic");
let message = payload
.downcast_ref::<String>()
.cloned()
.unwrap_or_default();
assert!(
message.contains("`needs_a_score`") && message.contains("u64"),
"{message}"
);
}
struct Tapping {
pumps: u32,
}
impl EventSource for Tapping {
fn pump_events(&mut self, out: &mut Vec<Event>) {
self.pumps += 1;
match self.pumps {
1 => out.extend([key(Key::D, true), key(Key::D, false)]),
40 => out.push(Event::CloseRequested),
_ => thread::sleep(MS),
}
}
fn set_modal_frame_callback(&mut self, _callback: Box<dyn FnMut(ModalFrame)>) {}
}
#[test]
fn the_loop_feeds_pumped_keys_to_the_actions() {
let log = shared();
let mut app = moving_app(&log).add_frame_system(FrameStage::Ui, "report", |world, _| {
let mover = world.resource::<Mover>().0;
let x = world
.read::<Transform>()
.get(mover)
.expect("it is")
.position
.x;
world
.resource::<Shared>()
.seen
.borrow_mut()
.push(x.to_string());
});
app.config.frame_rate_limit = None;
app.run_loop(&mut Tapping { pumps: 0 }, None)
.expect("no error without a device");
let seen = log.seen.borrow();
let last: f32 = seen.last().expect("frames ran").parse().expect("a number");
assert_eq!(last, SPEED / 60.0, "the tap moved it one tick");
}
#[cfg(feature = "dev")]
#[test]
fn a_frame_of_many_ticks_after_frames_of_one_allocates_nothing() {
let mut app = app();
app.world_mut()
.spawn()
.with(Transform::at(Vec2::ZERO))
.with(Velocity(Vec2::ONE))
.with(Sprite::new(texture(), Vec2::ONE));
for _ in 0..5 {
app.update(TICK, &[]);
}
let start = nadir_platform::thread_alloc_counts();
app.update(Duration::from_secs(1), &[]);
let allocated = nadir_platform::thread_alloc_counts().since(start);
assert_eq!(app.world().resource::<TickStats>().ticks, 15);
assert_eq!(allocated, nadir_platform::AllocCounts::default());
}
#[cfg(feature = "dev")]
mod offscreen_frames {
use std::{env, fs, process};
use nadir_codec::qoi::{self, Channels, ColorSpace, Header};
use nadir_core::{Color, Vec2};
use nadir_gfx::GfxError;
use nadir_render::RenderError;
use super::*;
const SIZE: UVec2 = UVec2::new(32, 18);
const CLEAR: [u8; 4] = [0, 0, 255, 255];
const RED: [u8; 4] = [255, 0, 0, 255];
fn app(test: &str, log: &Shared) -> App {
let assets = env::temp_dir().join(format!("nadir-engine-{test}-{}", process::id()));
fs::create_dir_all(&assets).expect("make the asset folder");
let header = Header {
width: 8,
height: 8,
channels: Channels::Rgba,
color_space: ColorSpace::Srgb,
};
let bytes = qoi::encode(&header, &RED.repeat(64)).expect("a valid image");
fs::write(assets.join("red.qoi"), bytes).expect("write the texture");
let mut app = App::new(Config {
virtual_resolution: SIZE,
assets,
..Config::default()
})
.insert_resource(Rc::clone(log))
.add_fixed_system(FixedStage::Gameplay, "count_ticks", count_ticks)
.add_frame_system(FrameStage::Camera, "look", |world, _| {
let mut frame = world.resource_mut::<RenderFrame>();
frame.clear = Color::rgb(CLEAR[0], CLEAR[1], CLEAR[2]);
frame.camera.position = Vec2::ZERO;
});
let red = app
.world()
.resource_mut::<AssetServer>()
.load::<nadir_render::Texture>("red.qoi");
app.world_mut()
.spawn()
.with(Transform::at(Vec2::new(4.0, 0.0)))
.with(Sprite::new(red, Vec2::splat(8.0)));
app
}
fn offscreen(app: App, size: UVec2) -> Option<Offscreen> {
let expected = env::var("NADIR_EXPECT_GL_RENDERER").unwrap_or_default();
let assets = app.config.assets.clone();
match app.offscreen(size) {
Ok(offscreen) => {
let renderer = offscreen.renderer();
assert!(renderer.contains(&expected), "{renderer} is not {expected}");
Some(offscreen)
}
Err(Error::Render(RenderError::Gfx(GfxError::NoOffscreenContext)))
if expected.is_empty() =>
{
fs::remove_dir_all(&assets).expect("remove the asset folder");
None
}
Err(error) => panic!("no offscreen OpenGL context: {error}"),
}
}
fn remove_assets(offscreen: &Offscreen) {
fs::remove_dir_all(&offscreen.app().config.assets).expect("remove the asset folder");
}
fn pixel(frame: &[u8], x: u32, y: u32) -> [u8; 4] {
let at = ((y * SIZE.x + x) * 4) as usize;
frame[at..at + 4].try_into().expect("4 bytes")
}
#[test]
fn each_frame_runs_its_ticks_and_draws_what_a_window_would_show() {
let log = shared();
let Some(mut offscreen) = offscreen(app("offscreen-frames", &log), SIZE) else {
return;
};
assert_eq!(offscreen.size(), SIZE);
let first = offscreen.frame(Duration::ZERO, &[]).expect("a frame");
remove_assets(&offscreen);
assert_eq!(first.len(), (SIZE.x * SIZE.y * 4) as usize);
assert!(first.as_chunks::<4>().0.iter().all(|&p| p == CLEAR));
assert_eq!(log.ticks.get(), 0);
let stats = *offscreen.app().world().resource::<FrameStats>();
assert_eq!((stats.sprites, stats.skipped), (0, 1));
let second = offscreen.frame(TICK, &[]).expect("a frame");
assert_eq!(log.ticks.get(), 1);
assert_eq!(offscreen.app().world().resource::<FrameStats>().sprites, 1);
for (x, y, expected) in [
(16, 1, RED),
(23, 8, RED),
(20, 4, RED),
(15, 4, CLEAR),
(24, 4, CLEAR),
(20, 0, CLEAR),
(20, 9, CLEAR),
(0, 0, CLEAR),
] {
assert_eq!(pixel(&second, x, y), expected, "({x}, {y})");
}
offscreen.frame(TICK * 3, &[]).expect("a frame");
assert_eq!(log.ticks.get(), 4);
}
#[test]
fn a_frame_waits_for_the_textures_asked_for_before_it_ends() {
let log = shared();
let app = app("offscreen-wait", &log);
const SIDE: u32 = 512;
let mut seed = 1u32;
let noise: Vec<u8> = (0..SIDE * SIDE)
.flat_map(|_| {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
let [r, g, b, _] = seed.to_le_bytes();
[r, g, b, 255]
})
.collect();
let header = Header {
width: SIDE,
height: SIDE,
channels: Channels::Rgba,
color_space: ColorSpace::Srgb,
};
let bytes = qoi::encode(&header, &noise).expect("a valid image");
fs::write(app.config.assets.join("noise.qoi"), bytes).expect("write the texture");
let app = app.add_frame_system(FrameStage::Camera, "noise", |world, _| {
let noise = world
.resource_mut::<AssetServer>()
.load::<nadir_render::Texture>("noise.qoi");
for (_, sprite) in world.write::<Sprite>().iter_mut() {
sprite.texture = noise;
}
});
let Some(mut offscreen) = offscreen(app, SIZE) else {
return;
};
offscreen.frame(Duration::ZERO, &[]).expect("a frame");
remove_assets(&offscreen);
offscreen.frame(TICK, &[]).expect("a frame");
let stats = *offscreen.app().world().resource::<FrameStats>();
assert_eq!(
(stats.sprites, stats.skipped),
(1, 0),
"the second frame did not draw the texture the first asked for"
);
}
#[test]
fn frames_bigger_than_the_view_are_scaled_up_by_whole_numbers() {
let log = shared();
let Some(mut offscreen) = offscreen(app("offscreen-scaled", &log), SIZE * 2) else {
return;
};
offscreen.frame(Duration::ZERO, &[]).expect("a frame");
remove_assets(&offscreen);
let frame = offscreen.frame(TICK, &[]).expect("a frame");
let width = SIZE.x * 2;
let at = |x: u32, y: u32| {
let i = ((y * width + x) * 4) as usize;
<[u8; 4]>::try_from(&frame[i..i + 4]).expect("4 bytes")
};
assert_eq!(frame.len(), (width * SIZE.y * 2 * 4) as usize);
assert_eq!(at(32, 2), RED);
assert_eq!(at(47, 17), RED);
assert_eq!(at(31, 2), CLEAR);
assert_eq!(at(32, 1), CLEAR);
assert_eq!(at(48, 17), CLEAR);
assert_eq!(at(47, 18), CLEAR);
}
}
#[cfg(feature = "dev")]
mod steady_frames {
use std::env;
use std::fs;
use std::hint::black_box;
use std::path::PathBuf;
use std::process;
use nadir_assets::Handle;
use nadir_codec::qoi::{self, Channels, ColorSpace, Header};
use nadir_core::{Color, Rect, Vec2};
use nadir_platform::{
AllocCounts, HeadlessGl, PlatformError, create_headless_gl, thread_alloc_counts,
};
use nadir_render::{Tile, TileLayer, TileLayerDraw, TileSet};
use super::*;
use crate::{Clip, ClipFrame, FrameAllocs, Playback};
const CROWD: usize = 10_000;
const GROUND: u32 = 64;
const WARM_UP: usize = 10;
const MOVED: usize = 6;
const COUNTED: usize = 100;
const VIEW: Vec2 = Vec2::new(480.0, 270.0);
struct Ground(Handle<TileLayer>, usize);
struct Seen {
frames: Vec<(AllocCounts, FrameStats, u64)>,
ticks: u64,
}
type SharedSeen = Rc<RefCell<Seen>>;
struct Offscreen {
gl: Option<HeadlessGl>,
at_pumps: Vec<AllocCounts>,
}
impl EventSource for Offscreen {
fn pump_events(&mut self, out: &mut Vec<Event>) {
self.at_pumps.push(thread_alloc_counts());
if self.at_pumps.len() > WARM_UP + COUNTED {
out.push(Event::CloseRequested);
}
}
fn set_modal_frame_callback(&mut self, _callback: Box<dyn FnMut(ModalFrame)>) {}
fn gpu_surface(&self) -> Option<GpuSurface<'_>> {
self.gl.as_ref().map(|gl| GpuSurface::Gl(gl))
}
fn window_size(&self) -> UVec2 {
UVec2::new(960, 540)
}
}
fn headless(expected: &str) -> Option<HeadlessGl> {
match create_headless_gl() {
Ok(gl) => Some(gl),
Err(PlatformError::Unsupported) if expected.is_empty() => None,
Err(error) => panic!(
"no offscreen OpenGL context: {error}. With libglvnd, Mesa can be chosen \
with __EGL_VENDOR_LIBRARY_FILENAMES=/usr/share/glvnd/egl_vendor.d/50_mesa.json"
),
}
}
fn write_texture(path: &PathBuf, size: u32, color: [u8; 4]) {
let header = Header {
width: size,
height: size,
channels: Channels::Rgba,
color_space: ColorSpace::Srgb,
};
let pixels = color.repeat((size * size) as usize);
let bytes = qoi::encode(&header, &pixels).expect("a valid image");
fs::write(path, bytes).expect("write a texture");
}
fn walk(world: &World, tick: &Tick) {
let transforms = world.read::<Transform>();
let mut velocities = world.write::<Velocity>();
let mut facings = world.write::<Facing>();
for (entity, velocity) in velocities.iter_mut() {
let Some(transform) = transforms.get(entity) else {
continue;
};
let next = transform.position + velocity.0 * tick.dt;
if !(8.0..=VIEW.x - 8.0).contains(&next.x) {
velocity.0.x = -velocity.0.x;
}
if !(16.0..=VIEW.y).contains(&next.y) {
velocity.0.y = -velocity.0.y;
}
if let Some(facing) = facings.get_mut(entity) {
*facing = facing_of(velocity.0);
}
}
world.resource::<SharedSeen>().borrow_mut().ticks += 1;
}
fn facing_of(velocity: Vec2) -> Facing {
if velocity.x < 0.0 {
Facing::Left
} else {
Facing::Right
}
}
fn draw_ground(world: &World, _: &Frame) {
let mut ground = world.resource_mut::<Ground>();
let mut out = world.resource_mut::<RenderFrame>();
out.camera.position = if ground.1 < MOVED {
VIEW * 0.5 - Vec2::splat(256.0)
} else {
VIEW * 0.5
};
ground.1 += 1;
out.tile_layers.push(TileLayerDraw::new(ground.0));
}
fn probe(world: &World, _: &Frame) {
let seen = world.resource::<SharedSeen>();
let mut seen = seen.borrow_mut();
let entry = (
world.resource::<FrameAllocs>().0,
*world.resource::<FrameStats>(),
seen.ticks,
);
seen.frames.push(entry);
if seen.frames.len() == 5 {
drop(black_box(Box::new(5u64)));
}
}
fn scene(assets: PathBuf, seen: &SharedSeen) -> App {
let mut app = App::new(Config {
assets,
frame_rate_limit: Some(500),
..Config::default()
})
.insert_resource(Rc::clone(seen))
.add_fixed_system(FixedStage::Gameplay, "walk", walk)
.add_frame_system(FrameStage::Extract, "draw_ground", draw_ground)
.add_frame_system(FrameStage::Ui, "probe", probe);
let (walker, ground) = {
let mut server = app.world().resource_mut::<AssetServer>();
(server.load("walker.qoi"), server.load("ground.qoi"))
};
let set = TileSet {
texture: ground,
columns: 2,
rows: 2,
};
let corner = VIEW * 0.5 - Vec2::splat(512.0);
let mut layer = TileLayer::new(set, UVec2::splat(GROUND), 16.0, corner);
for y in 0..GROUND as i32 {
for x in 0..GROUND as i32 {
let tile = if (x + y) % 4 == 0 {
Tile::animated(1, 3, 100)
} else {
Tile::new(0)
};
layer.set(nadir_core::IVec2::new(x, y), Some(tile));
}
}
let ground = app.world().resource_mut::<TileLayers>().add(layer);
let quarter = |index: u32| {
let left = index as f32 * 0.25;
let uv = Rect::new(Vec2::new(left, 0.0), Vec2::new(left + 0.25, 1.0));
ClipFrame::new(walker, uv, 100 * MS)
};
let walk = app
.world()
.resource_mut::<Clips>()
.add(Clip::new((0..4).map(quarter).collect(), Playback::Loop));
let mut seed = 1u32;
let mut random = move || {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
(seed % 10_000) as f32 / 10_000.0
};
for index in 0..CROWD {
let position = Vec2::new(
8.0 + random() * (VIEW.x - 16.0),
16.0 + random() * (VIEW.y - 16.0),
);
let velocity = Vec2::new(random() * 120.0 - 60.0, random() * 120.0 - 60.0);
let mut sprite = Sprite::new(walker, Vec2::new(8.0, 16.0));
sprite.layer = 1;
if index % 4 == 0 {
sprite.color = Color::rgb(255, 200, 200);
}
let phase = 400 * MS * (index % 4) as u32 / 4;
app.world_mut()
.spawn()
.with(Transform::at(position))
.with(Velocity(velocity))
.with(sprite)
.with(Animator::starting_at(walk, phase))
.with(facing_of(velocity));
}
app.insert_resource(Ground(ground, 0))
}
#[test]
fn a_steady_frame_of_10k_animated_sprites_and_a_tile_layer_allocates_nothing() {
let start = thread_alloc_counts();
drop(black_box(Box::new(0u64)));
assert_eq!(thread_alloc_counts().since(start).allocations, 1);
let assets = env::temp_dir().join(format!("nadir-engine-steady-{}", process::id()));
fs::create_dir_all(&assets).expect("make the asset folder");
write_texture(&assets.join("walker.qoi"), 8, [200, 120, 60, 255]);
write_texture(&assets.join("ground.qoi"), 32, [90, 140, 70, 255]);
let seen = Rc::new(RefCell::new(Seen {
frames: Vec::with_capacity(WARM_UP + COUNTED),
ticks: 0,
}));
let app = scene(assets.clone(), &seen);
let expected = env::var("NADIR_EXPECT_GL_RENDERER").unwrap_or_default();
let mut window = Offscreen {
gl: headless(&expected),
at_pumps: Vec::with_capacity(WARM_UP + COUNTED + 2),
};
let graphics = window.gl.as_ref().map(|gl| {
let mut device = Device::new(GpuSurface::Gl(gl)).expect("a device");
let renderer = device.caps().renderer.clone();
assert!(renderer.contains(&expected), "{renderer} is not {expected}");
let config = RenderConfig {
virtual_resolution: VIEW.as_uvec2(),
};
let renderer = Renderer::new(&mut device, &config).expect("a renderer");
Graphics { renderer, device }
});
let drawn = graphics.is_some();
app.run_loop(&mut window, graphics)
.expect("the frames draw");
fs::remove_dir_all(&assets).expect("remove the asset folder");
let seen = &seen.borrow().frames;
let pumps = &window.at_pumps;
assert_eq!(pumps.len(), WARM_UP + COUNTED + 1);
assert_eq!(seen.len(), WARM_UP + COUNTED);
let counted = pumps[WARM_UP + COUNTED].since(pumps[WARM_UP]);
assert_eq!(
counted,
AllocCounts::default(),
"the steady frames allocated"
);
let ticks = seen[WARM_UP + COUNTED - 1].2 - seen[WARM_UP].2;
assert!(ticks > 0, "no tick ran in the counted frames");
for frame in 2..WARM_UP + COUNTED {
let between_pumps = pumps[frame].since(pumps[frame - 1]);
assert_eq!(seen[frame].0, between_pumps, "frame {frame}");
}
assert!(seen[5].0.allocations >= 1, "the probe's allocation");
if drawn {
let full = (1..WARM_UP)
.find(|&frame| seen[frame].1.sprites == CROWD as u32)
.expect("the sprites are drawn in the warm-up");
assert!(full >= 2, "frame {full} drew the sprites");
assert!(
seen[full].0.allocations > 0,
"the first full draw grows its lists"
);
let all = FrameStats {
sprites: CROWD as u32,
skipped: 0,
batches: 1,
tiles: 4 * 32 * 32,
chunks: 4,
};
assert_eq!(seen[WARM_UP].1, all, "drawn before the counting starts");
assert_eq!(seen[WARM_UP + COUNTED - 1].1, all);
}
}
}
}