1use 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
52pub const TICK_HZ: u32 = 60;
54
55const MAX_FRAME: Duration = Duration::from_millis(250);
59
60const PROFILE_RECORDS: usize = 1_024;
63
64#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct Config {
67 pub title: String,
69 pub studio: String,
72 pub game: String,
81 pub window_size: UVec2,
83 pub min_window_size: UVec2,
86 pub resizable: bool,
88 pub fullscreen: bool,
90 pub frame_rate_limit: Option<u32>,
96 pub vsync: bool,
99 pub virtual_resolution: UVec2,
103 pub assets: PathBuf,
107 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub struct Volumes {
142 pub music: u8,
144 pub sfx: u8,
146 pub ui: u8,
148 pub ambience: u8,
150}
151
152impl Default for Volumes {
153 fn default() -> Self {
155 Self {
156 music: 100,
157 sfx: 100,
158 ui: 100,
159 ambience: 100,
160 }
161 }
162}
163
164impl Volumes {
165 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 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 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 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
210pub(crate) type LatchFn = Box<dyn FnMut(&mut Input, &World)>;
212
213struct Actions {
216 set: Option<&'static str>,
218 latch: LatchFn,
219 replay: Option<Box<dyn PlayReplay>>,
221}
222
223impl Actions {
224 fn none() -> Self {
227 Self {
228 set: None,
229 latch: latch_into_nothing(),
230 replay: None,
231 }
232 }
233}
234
235fn 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#[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
265trait EventSource {
268 fn pump_events(&mut self, out: &mut Vec<Event>);
270
271 fn set_modal_frame_callback(&mut self, callback: Box<dyn FnMut(ModalFrame)>);
274
275 fn gpu_surface(&self) -> Option<GpuSurface<'_>> {
277 None
278 }
279
280 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
304struct Graphics {
306 renderer: Renderer,
308 device: Device,
309}
310
311impl Graphics {
312 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 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 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 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
388struct EngineCore {
391 app: App,
392 stopwatch: Stopwatch,
393 graphics: Option<Graphics>,
394 error: Option<Error>,
397 #[cfg(feature = "dev")]
399 allocs_at_frame_end: nadir_platform::AllocCounts,
400 #[cfg(feature = "dev")]
402 reload: Option<crate::hot_reload::HotReload>,
403}
404
405impl EngineCore {
406 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 #[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
454pub struct App {
547 config: Config,
548 world: World,
549 schedule: Schedule,
550 actions: Actions,
551 clock: FixedClock,
552 profile: Vec<ScopeRecord>,
557 #[cfg(feature = "dev")]
560 shader_dir: PathBuf,
561 mixer: Option<Mixer>,
565 #[cfg(feature = "dev")]
567 debug: crate::debug_ui::DebugTools,
568}
569
570impl App {
571 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 #[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 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 pub fn take_mixer(&mut self) -> Option<Mixer> {
704 self.mixer.take()
705 }
706
707 #[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 #[must_use]
717 pub fn add_event<T: Clone + 'static>(mut self) -> Self {
718 self.world.add_event::<T>();
719 self
720 }
721
722 #[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 pub fn load_level(&mut self, name: &str) -> Result<(), LevelError> {
748 crate::load_level(&mut self.world, name)
749 }
750
751 #[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 #[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 #[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 pub fn world_hash(&self) -> u64 {
851 crate::world_hash(&self.world)
852 }
853
854 #[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 #[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 #[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 #[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 pub fn world(&self) -> &World {
970 &self.world
971 }
972
973 pub fn world_mut(&mut self) -> &mut World {
976 &mut self.world
977 }
978
979 #[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 pub fn schedule(&self) -> &Schedule {
988 &self.schedule
989 }
990
991 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 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 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 #[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 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 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 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 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 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 #[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 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 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
1322pub struct Offscreen {
1325 app: App,
1327 graphics: Graphics,
1328 target: RenderTargetId,
1330 size: UVec2,
1331}
1332
1333impl Offscreen {
1334 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 pub fn app(&self) -> &App {
1361 &self.app
1362 }
1363
1364 pub fn size(&self) -> UVec2 {
1366 self.size
1367 }
1368
1369 pub fn renderer(&self) -> &str {
1372 &self.graphics.device.caps().renderer
1373 }
1374}
1375
1376impl App {
1377 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
1395fn 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
1407fn 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
1417fn 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 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 #[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 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 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 #[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 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 #[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 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 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 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 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 #[test]
1757 fn the_frame_time_is_how_long_the_simulation_has_run() {
1758 let mut app = app();
1759 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 app.update(Duration::from_secs(5), &[]);
1775 close(time(&app), TICK * 3 + TICK / 4 + Duration::from_millis(250));
1776 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, Duration::from_nanos(6_944_444), Duration::from_micros(33_333), 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 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 app.update(Duration::from_secs(1), &[]);
1809 assert_eq!(log.ticks.get(), 60 + 15);
1810
1811 simulate(&mut app, 10 * MS, Duration::from_secs(1));
1813 assert_eq!(log.ticks.get(), 60 + 15 + 60);
1814 }
1815
1816 struct Script {
1822 pumps: u32,
1823 close: Box<dyn FnMut(u32) -> bool>,
1824 asked_to_close: bool,
1825 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 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 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 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 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 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 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 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 assert_eq!(log.frames.get(), 20);
1947 assert!(
1948 start.elapsed() >= Duration::from_millis(100),
1949 "{:?}",
1950 start.elapsed()
1951 );
1952 }
1953
1954 #[derive(Default)]
1956 struct Hitch {
1957 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 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 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 assert_eq!(most_ticks, Some(15), "{frames:?}");
2012 assert_eq!(longest_dt, 0.25, "{frames:?}");
2013
2014 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 #[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 const SPEED: f32 = 120.0;
2049
2050 struct Mover(Entity);
2052
2053 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 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 app.update(5 * MS, &[key(Key::D, true), key(Key::D, false)]);
2116 assert_eq!(x(&app), 0.0, "no tick yet");
2117 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 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 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 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 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 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 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 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 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 app.update(TICK, &[]);
2313 assert_eq!(
2314 (x(&app), replay(&app)),
2315 (3.0 * STEP, Replay::Ended { ticks: 3 })
2316 );
2317 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 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 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 #[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 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 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 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 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 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 #[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 #[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 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 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 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 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 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 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 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 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 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 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 {
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 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 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 #[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 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 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 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 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 #[derive(Clone, Copy, Debug, Default, PartialEq)]
2956 struct Seen {
2957 page: Option<UVec2>,
2959 walk: Option<Duration>,
2961 rock: Option<(Rect, u8)>,
2963 layer: Option<(Handle<TileLayer>, Option<u16>)>,
2965 reloads: Reloads,
2966 }
2967
2968 type SharedSeen = Rc<RefCell<Seen>>;
2969
2970 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 struct Step {
3003 name: &'static str,
3004 edit: fn(&Files),
3005 done: fn(&Seen, &Seen) -> bool,
3006 }
3007
3008 struct Files {
3010 assets: PathBuf,
3011 shaders: PathBuf,
3012 }
3013
3014 impl Files {
3015 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 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 struct Editing {
3117 gl: Option<HeadlessGl>,
3118 seen: SharedSeen,
3119 files: Files,
3120 first: Option<Seen>,
3122 step: usize,
3124 since: Option<Instant>,
3125 took: Vec<Duration>,
3127 started: Instant,
3128 quiet: Option<Instant>,
3130 }
3131
3132 const QUIET: Duration = Duration::from_millis(600);
3135
3136 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 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 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 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 #[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 const CROWD: usize = 10_000;
3322 const GROUND: u32 = 64;
3326 const WARM_UP: usize = 10;
3332 const MOVED: usize = 6;
3335 const COUNTED: usize = 100;
3337 const VIEW: Vec2 = Vec2::new(480.0, 270.0);
3339
3340 struct Ground(usize);
3342
3343 struct Seen {
3347 frames: Vec<(AllocCounts, FrameStats, u64)>,
3348 ticks: u64,
3349 reloading: bool,
3351 }
3352
3353 type SharedSeen = Rc<RefCell<Seen>>;
3354
3355 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 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 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 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 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 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 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 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 if seen.frames.len() == 5 {
3510 drop(black_box(Box::new(5u64)));
3511 }
3512 }
3513
3514 fn scene(assets: PathBuf, seen: &SharedSeen) -> App {
3517 let mut app = App::new(Config {
3518 assets,
3519 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 write_ground(&app.config.assets, VIEW * 0.5 - Vec2::splat(512.0));
3530 app.load_level("ground").expect("the ground's level");
3531 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 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 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 let pumps = &window.at_pumps;
3623 assert_eq!(pumps.len(), WARM_UP + COUNTED + 1);
3624 assert_eq!(seen.len(), WARM_UP + COUNTED);
3625
3626 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 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 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 #[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 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 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 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 #[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 assert_eq!(frames.len(), FRAMES as usize - 1);
3849 let gpu: Vec<&Span> = spans.iter().filter(|span| span.tid == 2).collect();
3850 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 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 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}