Skip to main content

pebble/
app.rs

1use crate::{
2    assets::required::RequiredResources,
3    ecs::{
4        events::{AsyncEventChannel, Events, drain_async_events},
5        plugin::Plugin,
6        resources::Resources,
7        system::{IntoSystem, System},
8        system_set::IntoSystemSet,
9    },
10};
11use std::collections::{BTreeMap, BinaryHeap, HashMap};
12
13/// Determines when during a frame a system is executed.
14///
15/// There's no dedicated "run once at startup" stage — instead, any system on
16/// any stage can be made to run at most once with [`.once()`](crate::ecs::system::OnceExt::once),
17/// which turns "have I already done this" into the function's own return
18/// value (`Some(())` = done, retire; `None` = not ready, try again next
19/// tick) instead of a special stage with its own rules. A `.once()` system
20/// naturally waits as many ticks as it needs to (an async GPU backend, a
21/// `LazyResource` that isn't built yet) using the exact same requirement
22/// checks as every other system on its stage.
23///
24/// [`AssetSync`](SystemStage::AssetSync)/[`AssetSyncDeps`](SystemStage::AssetSyncDeps)
25/// are prioritized: they're re-run to convergence (repeated until a full
26/// pass produces no new resources) at the front of every tick and again
27/// after every other stage, so newly queued asset/resource work is drained
28/// before gameplay stages continue rather than waiting for the next tick's
29/// front pass. All other stages run once per [`App::update`] tick, in the
30/// order declared below.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
32pub enum SystemStage {
33    /// Before the main update.
34    PreUpdate,
35    /// Main game-logic update.
36    Update,
37    /// After the main update.
38    PostUpdate,
39    /// Prepare rendering data and poll for the GPU backend.
40    /// The backend resource becomes available here on the tick it finishes
41    /// initialising, making it visible to the asset sync stages.
42    PreRender,
43    /// Upload CPU-side source assets to the GPU backend.
44    AssetSync,
45    /// Construct lazy GPU resources and upload assets that depend on other
46    /// processed assets. Runs in a convergence loop so dependency chains
47    /// (e.g. LazyResource A → LazyResource B) resolve within a single tick.
48    AssetSyncDeps,
49    /// Issue draw calls.
50    Render,
51    /// Cleanup or post-processing after rendering.
52    PostRender,
53}
54
55impl SystemStage {
56    /// Returns `true` for stages that are prioritized and re-run until a
57    /// full pass produces no new resources, instead of running once in
58    /// their declared position in the tick order. See the type-level docs
59    /// on [`SystemStage`].
60    pub fn is_convergent(self) -> bool {
61        matches!(self, Self::AssetSync | Self::AssetSyncDeps)
62    }
63}
64
65/// Fixed per-tick order for every stage *except* the convergent ones
66/// (`AssetSync`, `AssetSyncDeps`), which are driven separately by
67/// [`App::reconverge`] — at the front of the tick and again after each of
68/// these — rather than appearing in this list.
69const TICK_STAGES: [SystemStage; 6] = [
70    SystemStage::PreUpdate,
71    SystemStage::Update,
72    SystemStage::PostUpdate,
73    SystemStage::PreRender,
74    SystemStage::Render,
75    SystemStage::PostRender,
76];
77
78/// Whether a system is safe to run right now, given its declared
79/// [`System::requires`]. See [`App::check_readiness`].
80enum Readiness {
81    /// No unmet requirement — go ahead and run it.
82    Ready,
83    /// Missing a resource that some plugin has declared (via
84    /// [`RequiredResources::provides`]) it eventually provides — wait
85    /// quietly, no error, and try again next pass/tick.
86    WaitingOnLazy,
87    /// Missing a resource nothing has ever declared it will provide —
88    /// almost certainly a genuine oversight, not a timing issue.
89    MissingUnprovided {
90        system: &'static str,
91        resource: &'static str,
92        hint: Option<&'static str>,
93    },
94}
95
96/// Callback used to drive the application's main loop.
97///
98/// Set with [`App::set_runner`]. The default runner calls [`App::update`] in
99/// an infinite loop.
100pub type AppRunner = Box<dyn FnOnce(App)>;
101
102/// The central application object.
103///
104/// `App` owns the ECS world, resources, plugins, and systems. The typical
105/// lifecycle is:
106///
107/// 1. Create with [`App::new`].
108/// 2. Register plugins with [`add_plugin`](App::add_plugin).
109/// 3. Call [`build`](App::build) to run all plugin registrations, execute
110///    validate required resources, and settle `AssetSync`/`AssetSyncDeps`
111///    as far as they can go synchronously.
112/// 4. Call [`run`](App::run) to hand control to the runner.
113pub struct App {
114    pub(crate) world: hecs::World,
115    pub(crate) resources: Resources,
116    plugins: Vec<Box<dyn Plugin>>,
117    systems: BTreeMap<SystemStage, Vec<Box<dyn System>>>,
118    runner: Option<AppRunner>,
119    pub(crate) required: RequiredResources,
120    /// One closure per event type registered via [`add_event`](App::add_event),
121    /// each calling that type's [`Events::update`] to age its buffers. Run
122    /// at the front of every [`update`](App::update) tick, before any user
123    /// system, so a reader anywhere in the tick sees a consistent view. Kept
124    /// here rather than as regular systems because they must run before
125    /// every stage, not just one, and ordering that generically against
126    /// arbitrary user systems isn't worth the complexity.
127    event_updaters: Vec<Box<dyn FnMut(&hecs::World, &Resources)>>,
128}
129
130impl Default for App {
131    fn default() -> Self {
132        Self::new()
133    }
134}
135
136impl App {
137    /// Create a new `App` with an empty world and a default infinite-loop runner.
138    pub fn new() -> Self {
139        let mut world = hecs::World::default();
140        let mut resources = Resources::new(&mut world);
141        resources.insert_resource(&mut world, ());
142
143        Self {
144            world: world,
145            resources: resources,
146            plugins: Vec::new(),
147            systems: BTreeMap::new(),
148            runner: Some(Box::new(|mut app| {
149                loop {
150                    app.update();
151                }
152            })),
153            required: RequiredResources::new(),
154            event_updaters: Vec::new(),
155        }
156    }
157
158    /// Check `system` against `required` without running it. See
159    /// [`Readiness`]. Used by [`run_stage_once`](App::run_stage_once) for
160    /// every stage.
161    ///
162    /// A free function (rather than a `&self` method) so it only borrows
163    /// `world`/`resources`/`required` — the specific fields still available
164    /// while a caller holds a `&mut` borrow of `self.systems` to iterate the
165    /// very system being checked.
166    fn check_readiness(
167        world: &hecs::World,
168        resources: &Resources,
169        required: &RequiredResources,
170        system: &dyn System,
171    ) -> Readiness {
172        for req in system.requires() {
173            if (req.present)(world, resources) {
174                continue;
175            }
176            if required.is_provided(req.type_id) {
177                return Readiness::WaitingOnLazy;
178            }
179            return Readiness::MissingUnprovided {
180                system: system.name(),
181                resource: req.name,
182                hint: req.hint,
183            };
184        }
185        Readiness::Ready
186    }
187
188    /// The advice appended to a "missing resource" panic when the
189    /// [`RequiredResource`](crate::ecs::system::RequiredResource) didn't
190    /// supply its own more specific `hint` — the generic fallback,
191    /// appropriate for a plain `Res<T>`/`ResMut<T>` on an arbitrary
192    /// resource type with no dedicated registration method of its own.
193    fn generic_missing_resource_hint(resource: &'static str) -> String {
194        format!(
195            "If `{resource}` genuinely arrives later (an async backend, a LazyResource, \
196             an Asset upload), call `app.required.provides::<{resource}>()` in whichever \
197             plugin inserts it, and this will wait instead of erroring. Otherwise, insert \
198             it via App::add_resource before this stage runs."
199        )
200    }
201
202    /// Panic with a message naming both the offending system and resource,
203    /// plus either its param-specific `hint` (e.g. "call `app.add_event::<T>()`")
204    /// or, absent that, the generic fallback advice.
205    fn panic_missing_unprovided(
206        stage: SystemStage,
207        system: &'static str,
208        resource: &'static str,
209        hint: Option<&'static str>,
210    ) -> ! {
211        let advice = hint
212            .map(str::to_string)
213            .unwrap_or_else(|| Self::generic_missing_resource_hint(resource));
214        panic!(
215            "{stage:?}: system `{system}` requires `{resource}`, which nothing has \
216             registered as provided.\n\n{advice}"
217        );
218    }
219
220    /// Pre-flight check, run once at the end of [`build`](Self::build): walk
221    /// every registered system in every stage and evaluate its
222    /// [`System::requires`] via [`check_readiness`](Self::check_readiness),
223    /// the same logic [`run_stage_once`](Self::run_stage_once) applies lazily
224    /// as each stage actually runs. A system waiting on a resource that
225    /// something else has [declared it provides](RequiredResources::provides)
226    /// is left alone — it'll show up once that plugin's async/lazy work
227    /// settles. A system requiring a resource that *nothing* provides and
228    /// that isn't already present is a genuine configuration mistake, and
229    /// every such mistake across the whole app is collected into one panic
230    /// here — instead of each one surfacing separately, one at a time, the
231    /// first time its particular stage happens to run.
232    fn validate_requirements(&self) {
233        let mut missing = Vec::new();
234
235        for (stage, systems) in self.systems.iter() {
236            for system in systems.iter() {
237                if let Readiness::MissingUnprovided { system, resource, hint } =
238                    Self::check_readiness(&self.world, &self.resources, &self.required, system.as_ref())
239                {
240                    missing.push((*stage, system, resource, hint));
241                }
242            }
243        }
244
245        if missing.is_empty() {
246            return;
247        }
248
249        let mut message = String::from(
250            "Pebble startup validation failed — the following systems require resources \
251             that nothing has registered as provided:\n",
252        );
253        for (stage, system, resource, hint) in &missing {
254            let advice = hint
255                .map(str::to_string)
256                .unwrap_or_else(|| Self::generic_missing_resource_hint(resource));
257            message.push_str(&format!("\n{stage:?}: system `{system}` requires `{resource}`\n  {advice}\n"));
258        }
259        panic!("{message}");
260    }
261
262    /// Run every system in `stage` once, flush the command buffer, and return
263    /// `true` if any resource was newly inserted during this pass.
264    ///
265    /// A system with an unmet hard [`Res`](crate::ecs::system::Res)/[`ResMut`](crate::ecs::system::ResMut)
266    /// requirement is skipped for this pass if the resource is registered as
267    /// [provided](RequiredResources::provides) somewhere (it'll get there —
268    /// just not yet), or panics immediately, naming the system and resource,
269    /// if nothing ever declared it would provide that resource at all.
270    ///
271    /// [`Commands::insert_resource`](crate::ecs::system::Commands::insert_resource)
272    /// bumps the generation counter at queue time, so both direct inserts and
273    /// deferred command-buffer inserts are detected here with no world
274    /// introspection needed after the flush.
275    fn run_stage_once(&mut self, stage: SystemStage) -> bool {
276        let gen_before = self.resources.generation();
277
278        if let Some(systems) = self.systems.get_mut(&stage) {
279            for system in systems.iter_mut() {
280                match Self::check_readiness(&self.world, &self.resources, &self.required, system.as_ref()) {
281                    Readiness::Ready => {}
282                    Readiness::WaitingOnLazy => continue,
283                    Readiness::MissingUnprovided { system, resource, hint } => {
284                        Self::panic_missing_unprovided(stage, system, resource, hint)
285                    }
286                }
287                let _guard = crate::ecs::resources::set_current_system(system.name());
288                system.run(&self.world, &self.resources);
289            }
290        }
291        self.resources.get_command_buffer().run_on(&mut self.world);
292
293        self.resources.generation() != gen_before
294    }
295
296    /// Run `AssetSync`, then `AssetSyncDeps`, repeating both until a full
297    /// pass produces no new resources, up to `max_passes`. Logs a warning if
298    /// the limit is reached — that usually means a [`LazyResource`](crate::assets::singleton_asset::LazyResource)
299    /// whose `construct()` or an [`Asset`](crate::assets::upload::Asset)
300    /// whose `upload()` always returns `None`.
301    ///
302    /// Called at the front of every tick and again after every stage in
303    /// [`update`](App::update) (and once during [`build`](App::build)), so
304    /// newly-queued asset/resource work is drained immediately instead of
305    /// waiting for the next tick's front pass.
306    fn reconverge(&mut self, max_passes: u32) {
307        for pass in 0..max_passes {
308            let gen_before = self.resources.generation();
309
310            self.run_stage_once(SystemStage::AssetSync);
311            self.run_stage_once(SystemStage::AssetSyncDeps);
312
313            if self.resources.generation() == gen_before {
314                return;
315            }
316            if pass == max_passes - 1 {
317                tracing::warn!(
318                    "AssetSync/AssetSyncDeps did not settle after {max_passes} passes — a \
319                     dependency may be permanently unsatisfiable. Check for a LazyResource \
320                     whose construct() or an Asset whose upload() always returns None."
321                );
322            }
323        }
324    }
325
326    /// Queue a plugin to be built during [`build`](App::build).
327    pub fn add_plugin(&mut self, plugin: impl Plugin) -> &mut Self {
328        self.plugins.push(Box::new(plugin));
329        self
330    }
331
332    /// Insert a resource into the world immediately.
333    pub fn add_resource(&mut self, res: impl hecs::Component) -> &mut Self {
334        self.resources.insert_resource(&mut self.world, res);
335        self
336    }
337
338    /// Borrow resource `T`, panicking if it is absent.
339    pub fn get_resource<'a, T: hecs::Component>(&'a self) -> hecs::Ref<'a, T> {
340        self.resources.get_resource(&self.world)
341    }
342
343    /// Mutably borrow resource `T`, panicking if it is absent.
344    pub fn get_resource_mut<'a, T: hecs::Component>(&'a self) -> hecs::RefMut<'a, T> {
345        self.resources.get_resource_mut(&self.world)
346    }
347
348    /// Insert resource `T` only if it is not already present.
349    ///
350    /// Returns `true` if the resource was inserted.
351    pub fn try_insert_resource<T: hecs::Component>(&mut self, res: T) -> bool {
352        self.resources.try_insert(&mut self.world, res)
353    }
354
355    /// Declare that resource type `T` is expected to be inserted later —
356    /// possibly asynchronously (a background thread's result, a hand-rolled
357    /// lazy resource) rather than up front. A system elsewhere with a hard
358    /// `Res<T>`/`ResMut<T>` requirement on `T` will then wait quietly for it
359    /// instead of `App` treating the absence as a configuration mistake and
360    /// panicking.
361    ///
362    /// [`GraphicsPlugin`](crate::rendering::graphics_plugin::GraphicsPlugin)
363    /// and [`LazyResourcePlugin`](crate::assets::singleton_asset::LazyResourcePlugin)
364    /// already call this for the backend and lazy resource types they
365    /// manage — reach for this directly only for your own resource types
366    /// that arrive outside of those.
367    pub fn provides<T: 'static>(&mut self) -> &mut Self {
368        self.required.provides::<T>();
369        self
370    }
371
372    /// Register event type `T`, making [`EventWriter<T>`](crate::ecs::events::EventWriter)
373    /// and [`EventReader<T>`](crate::ecs::events::EventReader) usable as
374    /// system parameters.
375    ///
376    /// Inserts the backing [`Events<T>`] resource (a no-op if `T` was
377    /// already registered) and schedules its per-tick aging, which is what
378    /// gives events sent during tick `N` a consistent two-tick lifetime —
379    /// visible for the rest of `N` and all of `N + 1` — regardless of which
380    /// stage the writer or reader runs in.
381    pub fn add_event<T: hecs::Component>(&mut self) -> &mut Self {
382        self.try_insert_resource(Events::<T>::default());
383        self.event_updaters.push(Box::new(|world, resources| {
384            resources.get_resource_mut::<Events<T>>(world).update();
385        }));
386        self
387    }
388
389    /// Register event type `T` as in [`add_event`](Self::add_event), and
390    /// additionally make [`AsyncEventWriter<T>`](crate::ecs::events::AsyncEventWriter)
391    /// usable as a system parameter — the friendly way to turn a background
392    /// task's result into a `T` event once it resolves, instead of hand-
393    /// rolling a pending-task resource and poll system yourself.
394    ///
395    /// Requires [`BackgroundTasksPlugin`](crate::threading::BackgroundTasksPlugin)
396    /// to be registered before any system using `AsyncEventWriter<T>` runs —
397    /// that's what [`AsyncEventWriter::spawn`](crate::ecs::events::AsyncEventWriter::spawn)
398    /// drives the future through.
399    pub fn add_async_event<T: hecs::Component>(&mut self) -> &mut Self {
400        self.add_event::<T>();
401        self.try_insert_resource(AsyncEventChannel::<T>::new());
402        self.add_system(SystemStage::PreUpdate, drain_async_events::<T>);
403        self
404    }
405
406    /// Register a single system to run at `stage`.
407    pub fn add_system<Marker>(
408        &mut self,
409        stage: SystemStage,
410        system: impl IntoSystem<Marker> + 'static,
411    ) -> &mut Self {
412        self.systems
413            .entry(stage)
414            .or_default()
415            .push(Box::new(system.into_system()));
416        self
417    }
418
419    /// Register multiple systems to run at `stage`.
420    ///
421    /// Accepts a tuple of systems via [`IntoSystemSet`].
422    pub fn add_systems<Marker>(
423        &mut self,
424        stage: SystemStage,
425        systems: impl IntoSystemSet<Marker>,
426    ) -> &mut Self {
427        let entry = self.systems.entry(stage).or_default();
428        entry.extend(systems.into_system_set());
429        self
430    }
431
432    /// Topologically sort `systems` by each system's [`System::after_ids`]/[`System::before_ids`]
433    /// constraints (referencing other systems' [`System::ordering_id`] within
434    /// the same stage), breaking ties by original registration order.
435    ///
436    /// Panics if the constraints form a cycle, naming every system still
437    /// stuck once no more zero-dependency systems remain.
438    fn sort_stage(stage: SystemStage, systems: &mut Vec<Box<dyn System>>) {
439        let id_index: HashMap<std::any::TypeId, usize> = systems
440            .iter()
441            .enumerate()
442            .map(|(i, s)| (s.ordering_id(), i))
443            .collect();
444
445        let n = systems.len();
446        let mut adjacency: Vec<Vec<usize>> = vec![Vec::new(); n];
447        let mut in_degree = vec![0usize; n];
448
449        for (i, system) in systems.iter().enumerate() {
450            for id in system.after_ids() {
451                if let Some(&dep) = id_index.get(id) {
452                    adjacency[dep].push(i);
453                    in_degree[i] += 1;
454                }
455            }
456            for id in system.before_ids() {
457                if let Some(&dependent) = id_index.get(id) {
458                    adjacency[i].push(dependent);
459                    in_degree[dependent] += 1;
460                }
461            }
462        }
463
464        // Min-heap on original index so ties resolve to registration order.
465        let mut ready: BinaryHeap<std::cmp::Reverse<usize>> = in_degree
466            .iter()
467            .enumerate()
468            .filter(|(_, d)| **d == 0)
469            .map(|(i, _)| std::cmp::Reverse(i))
470            .collect();
471
472        let mut order = Vec::with_capacity(n);
473        while let Some(std::cmp::Reverse(u)) = ready.pop() {
474            order.push(u);
475            for &v in &adjacency[u] {
476                in_degree[v] -= 1;
477                if in_degree[v] == 0 {
478                    ready.push(std::cmp::Reverse(v));
479                }
480            }
481        }
482
483        if order.len() != n {
484            let stuck: Vec<&'static str> = (0..n)
485                .filter(|i| in_degree[*i] > 0)
486                .map(|i| systems[i].name())
487                .collect();
488            panic!(
489                "{stage:?}: system ordering constraints form a cycle among: {stuck:?}"
490            );
491        }
492
493        let mut taken: Vec<Option<Box<dyn System>>> = systems.drain(..).map(Some).collect();
494        for i in order {
495            systems.push(taken[i].take().unwrap());
496        }
497    }
498
499    /// Build all plugins and validate required resources.
500    ///
501    /// Plugins may register additional plugins during their `build` call; this
502    /// repeats until no new plugins are added, up to a hard limit of 64 passes
503    /// to catch accidental infinite registration cycles.
504    pub fn build(&mut self) -> &mut Self {
505        let mut iterations = 0;
506        const MAX_PLUGIN_BUILD_ITERATIONS: u32 = 64;
507
508        while !self.plugins.is_empty() {
509            iterations += 1;
510            if iterations > MAX_PLUGIN_BUILD_ITERATIONS {
511                panic!(
512                    "App::build() exceeded {MAX_PLUGIN_BUILD_ITERATIONS} plugin-registration passes — \
513                 likely a cycle where plugins keep registering each other. Check for a plugin whose \
514                 build() unconditionally re-adds itself or another plugin that re-adds it."
515                );
516            }
517            let plugins: Vec<_> = self.plugins.drain(..).collect();
518            for plugin in plugins {
519                plugin.build(self);
520            }
521        }
522
523        for (stage, systems) in self.systems.iter_mut() {
524            Self::sort_stage(*stage, systems);
525        }
526
527        // Resolve as much as possible synchronously (headless/CPU-only
528        // backends, tests) so resources are ready immediately after
529        // build(). Anything still pending (an async GPU backend, say)
530        // keeps getting retried every tick by update().
531        self.reconverge(64);
532
533        self.validate_requirements();
534
535        self
536    }
537
538    /// Run every stage once per tick, in [`TICK_STAGES`] order. Before every
539    /// tick, and again after every stage, [`reconverge`](App::reconverge)
540    /// drains `AssetSync`/`AssetSyncDeps` — so newly-queued asset or
541    /// resource work is handled immediately rather than waiting for the
542    /// next tick's front pass.
543    pub fn update(&mut self) {
544        for updater in self.event_updaters.iter_mut() {
545            updater(&self.world, &self.resources);
546        }
547
548        self.reconverge(64);
549
550        for stage in TICK_STAGES {
551            self.run_stage_once(stage);
552            self.reconverge(64);
553        }
554    }
555
556    /// Replace the default runner with a custom one.
557    ///
558    /// The runner receives ownership of the `App` and is responsible for
559    /// calling [`update`](App::update) at the appropriate cadence (e.g. driven
560    /// by a window event loop).
561    pub fn set_runner<F>(&mut self, runner: F) -> &mut Self
562    where
563        F: FnOnce(App) + 'static,
564    {
565        self.runner = Some(Box::new(runner));
566        self
567    }
568
569    /// Consume the app and hand it to the configured runner.
570    ///
571    /// Panics if no runner has been set.
572    pub fn run(&mut self) {
573        let mut owned_app = std::mem::take(self);
574        let runner = owned_app.runner.take().expect("No runner found!");
575        runner(owned_app);
576    }
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582    use crate::ecs::system::{ResMut, SystemOrderingExt};
583
584    struct Order(Vec<&'static str>);
585
586    fn sys_a(mut o: ResMut<Order>) {
587        o.0.push("a");
588    }
589    fn sys_b(mut o: ResMut<Order>) {
590        o.0.push("b");
591    }
592    fn sys_c(mut o: ResMut<Order>) {
593        o.0.push("c");
594    }
595
596    #[test]
597    fn systems_run_in_declared_order() {
598        let mut app = App::new();
599        app.add_resource(Order(Vec::new()));
600
601        // Registered in a-b-c order, but both a and b declare they must run
602        // after c — the sort should move c first while leaving a before b
603        // (their relative registration order) intact.
604        app.add_system(SystemStage::Update, sys_a.after(sys_c));
605        app.add_system(SystemStage::Update, sys_b.after(sys_c));
606        app.add_system(SystemStage::Update, sys_c);
607
608        app.build();
609        app.update();
610
611        let order = app.get_resource::<Order>();
612        assert_eq!(order.0, vec!["c", "a", "b"]);
613    }
614
615    #[test]
616    #[should_panic(expected = "cycle")]
617    fn cyclic_ordering_constraints_panic() {
618        let mut app = App::new();
619        app.add_resource(Order(Vec::new()));
620
621        app.add_system(SystemStage::Update, sys_a.after(sys_b));
622        app.add_system(SystemStage::Update, sys_b.after(sys_a));
623
624        app.build();
625    }
626}