Skip to main content

pebble/
app.rs

1use crate::{
2    assets::required::RequiredResources,
3    ecs::{
4        plugin::Plugin,
5        resources::Resources,
6        system::{IntoSystem, System},
7        system_set::IntoSystemSet,
8    },
9};
10use std::collections::BTreeMap;
11
12/// Determines when during a frame a system is executed.
13///
14/// Stages are iterated in the order defined here — [`Startup`](SystemStage::Startup)
15/// runs once during [`App::build`], all others run every [`App::update`] tick.
16///
17/// Asset sync stages ([`AssetSync`](SystemStage::AssetSync),
18/// [`AssetSyncDeps`](SystemStage::AssetSyncDeps)) run **after** [`PreRender`](SystemStage::PreRender)
19/// so that the GPU backend — which is delivered in `PreRender` via a one-shot
20/// channel — is guaranteed to be present before asset upload is attempted.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub enum SystemStage {
23    /// Runs once at startup, before the main loop begins.
24    Startup,
25    /// Runs before the main update.
26    PreUpdate,
27    /// Main game-logic update.
28    Update,
29    /// Runs after the main update.
30    PostUpdate,
31    /// Prepare rendering data and poll for the GPU backend.
32    /// The backend resource becomes available here on the tick it finishes
33    /// initialising, making it visible to the asset sync stages below.
34    PreRender,
35    /// Upload CPU-side source assets to the GPU backend.
36    /// Runs after [`PreRender`](SystemStage::PreRender) so the backend is
37    /// guaranteed to be present.
38    AssetSync,
39    /// Construct lazy GPU resources and upload assets that depend on other
40    /// processed assets. Runs in a convergence loop so dependency chains
41    /// (e.g. LazyResource A → LazyResource B) resolve within a single tick.
42    AssetSyncDeps,
43    /// Issue draw calls.
44    Render,
45    /// Cleanup or post-processing after rendering.
46    PostRender,
47}
48
49impl SystemStage {
50    /// Returns `true` for stages that are re-run until no new resources are
51    /// inserted — collapsing multi-tick dependency chains into one tick.
52    pub fn is_convergent(self) -> bool {
53        matches!(self, Self::AssetSync | Self::AssetSyncDeps)
54    }
55}
56
57/// Callback used to drive the application's main loop.
58///
59/// Set with [`App::set_runner`]. The default runner calls [`App::update`] in
60/// an infinite loop.
61pub type AppRunner = Box<dyn FnOnce(App)>;
62
63/// The central application object.
64///
65/// `App` owns the ECS world, resources, plugins, and systems. The typical
66/// lifecycle is:
67///
68/// 1. Create with [`App::new`].
69/// 2. Register plugins with [`add_plugin`](App::add_plugin).
70/// 3. Call [`build`](App::build) to run all plugin registrations, execute
71///    startup systems, and validate required resources.
72/// 4. Call [`run`](App::run) to hand control to the runner.
73pub struct App {
74    pub(crate) world: hecs::World,
75    pub(crate) resources: Resources,
76    plugins: Vec<Box<dyn Plugin>>,
77    systems: BTreeMap<SystemStage, Vec<Box<dyn System>>>,
78    runner: Option<AppRunner>,
79    pub(crate) required: RequiredResources,
80    /// Runtime stage order, cached once in [`build`](App::build) so
81    /// [`update`](App::update) never heap-allocates per tick.
82    update_stages: Vec<SystemStage>,
83}
84
85impl Default for App {
86    fn default() -> Self {
87        Self::new()
88    }
89}
90
91impl App {
92    /// Create a new `App` with an empty world and a default infinite-loop runner.
93    pub fn new() -> Self {
94        let mut world = hecs::World::default();
95        let mut resources = Resources::new(&mut world);
96        resources.insert_resource(&mut world, ());
97
98        Self {
99            world: world,
100            resources: resources,
101            plugins: Vec::new(),
102            systems: BTreeMap::new(),
103            runner: Some(Box::new(|mut app| {
104                loop {
105                    app.update();
106                }
107            })),
108            required: RequiredResources::new(),
109            update_stages: Vec::new(),
110        }
111    }
112
113    /// Run every system in `stage` once, flush the command buffer, and return
114    /// `true` if any resource was newly inserted during this pass.
115    ///
116    /// [`Commands::insert_resource`](crate::ecs::system::Commands::insert_resource)
117    /// bumps the generation counter at queue time, so both direct inserts and
118    /// deferred command-buffer inserts are detected here with no world
119    /// introspection needed after the flush.
120    fn run_stage_once(&mut self, stage: SystemStage) -> bool {
121        let gen_before = self.resources.generation();
122
123        if let Some(systems) = self.systems.get_mut(&stage) {
124            for system in systems.iter_mut() {
125                system.run(&self.world, &self.resources);
126            }
127        }
128        self.resources.get_command_buffer().run_on(&mut self.world);
129
130        self.resources.generation() != gen_before
131    }
132
133    /// Re-run `stage` until a full pass produces no new resources, up to
134    /// `max_passes`. Logs a warning if the limit is reached — that usually
135    /// means a [`LazyResource`](crate::assets::singleton_asset::LazyResource)
136    /// or [`Asset`](crate::assets::upload::Asset) dependency is permanently
137    /// unsatisfiable.
138    fn run_stage_to_convergence(&mut self, stage: SystemStage, max_passes: u32) {
139        for pass in 0..max_passes {
140            if !self.run_stage_once(stage) {
141                return;
142            }
143            if pass == max_passes - 1 {
144                tracing::warn!(
145                    "{stage:?}: convergence did not settle after {max_passes} passes — \
146                     a dependency may be permanently unsatisfiable. Check for a \
147                     LazyResource whose construct() or an Asset whose upload() \
148                     always returns None."
149                );
150            }
151        }
152    }
153
154    /// Queue a plugin to be built during [`build`](App::build).
155    pub fn add_plugin(&mut self, plugin: impl Plugin) -> &mut Self {
156        self.plugins.push(Box::new(plugin));
157        self
158    }
159
160    /// Insert a resource into the world immediately.
161    pub fn add_resource(&mut self, res: impl hecs::Component) -> &mut Self {
162        self.resources.insert_resource(&mut self.world, res);
163        self
164    }
165
166    /// Borrow resource `T`, panicking if it is absent.
167    pub fn get_resource<'a, T: hecs::Component>(&'a self) -> hecs::Ref<'a, T> {
168        self.resources.get_resource(&self.world)
169    }
170
171    /// Mutably borrow resource `T`, panicking if it is absent.
172    pub fn get_resource_mut<'a, T: hecs::Component>(&'a self) -> hecs::RefMut<'a, T> {
173        self.resources.get_resource_mut(&self.world)
174    }
175
176    /// Insert resource `T` only if it is not already present.
177    ///
178    /// Returns `true` if the resource was inserted.
179    pub fn try_insert_resource<T: hecs::Component>(&mut self, res: T) -> bool {
180        self.resources.try_insert(&mut self.world, res)
181    }
182
183    /// Register a single system to run at `stage`.
184    pub fn add_system<Marker>(
185        &mut self,
186        stage: SystemStage,
187        system: impl IntoSystem<Marker> + 'static,
188    ) -> &mut Self {
189        self.systems
190            .entry(stage)
191            .or_default()
192            .push(Box::new(system.into_system()));
193        self
194    }
195
196    /// Register multiple systems to run at `stage`.
197    ///
198    /// Accepts a tuple of systems via [`IntoSystemSet`].
199    pub fn add_systems<Marker>(
200        &mut self,
201        stage: SystemStage,
202        systems: impl IntoSystemSet<Marker>,
203    ) -> &mut Self {
204        let entry = self.systems.entry(stage).or_default();
205        entry.extend(systems.into_system_set());
206        self
207    }
208
209    /// Build all plugins, run startup systems, and validate required resources.
210    ///
211    /// Plugins may register additional plugins during their `build` call; this
212    /// repeats until no new plugins are added, up to a hard limit of 64 passes
213    /// to catch accidental infinite registration cycles.
214    pub fn build(&mut self) -> &mut Self {
215        let mut iterations = 0;
216        const MAX_PLUGIN_BUILD_ITERATIONS: u32 = 64;
217
218        while !self.plugins.is_empty() {
219            iterations += 1;
220            if iterations > MAX_PLUGIN_BUILD_ITERATIONS {
221                panic!(
222                    "App::build() exceeded {MAX_PLUGIN_BUILD_ITERATIONS} plugin-registration passes — \
223                 likely a cycle where plugins keep registering each other. Check for a plugin whose \
224                 build() unconditionally re-adds itself or another plugin that re-adds it."
225                );
226            }
227            let plugins: Vec<_> = self.plugins.drain(..).collect();
228            for plugin in plugins {
229                plugin.build(self);
230            }
231        }
232
233        self.required.validate();
234
235        // Run startup systems exactly once, then remove them from the map so
236        // they are never re-run by update().
237        self.run_stage_once(SystemStage::Startup);
238        self.systems.remove(&SystemStage::Startup);
239
240        // For synchronous backends (headless, tests, CPU-only assets), drain
241        // the asset pipeline to completion before the first frame. For windowed
242        // GPU apps the backend isn't available yet so these exit immediately.
243        self.run_stage_to_convergence(SystemStage::AssetSync, 64);
244        self.run_stage_to_convergence(SystemStage::AssetSyncDeps, 64);
245
246        // Cache the runtime stage order once — update() reads this slice every
247        // tick without allocating.
248        self.update_stages = self.systems.keys().copied().collect();
249
250        self
251    }
252
253    /// Run all non-startup systems in stage order, flushing the command buffer
254    /// after each stage. Convergent stages ([`AssetSync`](SystemStage::AssetSync),
255    /// [`AssetSyncDeps`](SystemStage::AssetSyncDeps)) are re-run until no new
256    /// resources are inserted, resolving dependency chains within a single tick.
257    pub fn update(&mut self) {
258        // Copy the stage list so the borrow on self.update_stages doesn't
259        // conflict with the &mut self needed by run_stage_once / run_stage_to_convergence.
260        // update_stages is a small, stable Vec (set once in build), so this clone
261        // is cheap and avoids unsafe splitting borrows.
262        let stages = self.update_stages.clone();
263        for stage in stages {
264            if stage.is_convergent() {
265                self.run_stage_to_convergence(stage, 64);
266            } else {
267                self.run_stage_once(stage);
268            }
269        }
270    }
271
272    /// Replace the default runner with a custom one.
273    ///
274    /// The runner receives ownership of the `App` and is responsible for
275    /// calling [`update`](App::update) at the appropriate cadence (e.g. driven
276    /// by a window event loop).
277    pub fn set_runner<F>(&mut self, runner: F) -> &mut Self
278    where
279        F: FnOnce(App) + 'static,
280    {
281        self.runner = Some(Box::new(runner));
282        self
283    }
284
285    /// Consume the app and hand it to the configured runner.
286    ///
287    /// Panics if no runner has been set.
288    pub fn run(&mut self) {
289        let mut owned_app = std::mem::take(self);
290        let runner = owned_app.runner.take().expect("No runner found!");
291        runner(owned_app);
292    }
293}