furmint-runtime 0.1.0

Main package of furmint game engine providing higher level API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::path::PathBuf;
use std::sync::mpsc::Sender;
use std::time::{Duration, Instant};

use log::{debug, error, info, warn};

use crate::error::{RuntimeError, RuntimeResult};
use crate::events::{AppEvent, AppEventReceivingSystem, Events};
use crate::plugins::{Plugin, PluginBuildContext, PluginUpdateContext};
use crate::scenes::{
    ActiveScene, Scene, SceneCommand, SceneCommands, SceneLibrary, SceneLoader, SceneSystem,
};
use crate::time;
use crate::time::Time;
use furmint_registry::{ComponentFactory, ComponentRegistry};
use furmint_resources::assets::{AssetServer, Handle};
use serde::{Deserialize, Serialize};
use specs::{Component, Dispatcher, DispatcherBuilder, World, WorldExt};

/// Alias for system registration closure
pub type SystemRegistration = Box<dyn FnOnce(&mut DispatcherBuilder<'static, 'static>) + Send>;

/// The application struct which contains [`World`] and `specs`
/// `Dispatcher`
pub struct App {
    /// ECS world
    world: World,
    /// ECS dispatchers, keyed by stage
    dispatchers: HashMap<Stage, Dispatcher<'static, 'static>>,
    /// App plugins
    plugins: Vec<Box<dyn Plugin + 'static + Send + Sync>>,
    /// Is the app running?
    running: bool,
}

/// Builder for [`App`]
#[derive(Default)]
pub struct AppBuilder {
    config: &'static str,
    world: World,
    component_registry: ComponentRegistry,
    dispatcher_builders: HashMap<Stage, DispatcherBuilder<'static, 'static>>,
    dispatcher_config: HashMap<Stage, Vec<SystemRegistration>>,
    plugins: Vec<Box<dyn Plugin + Send + Sync>>,
}

/// Execution stages for systems in a frame
///
/// Systems are grouped by stage and run in this order:
/// `PreUpdate` -> `Update` -> `PostUpdate` -> `Runtime`
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Stage {
    /// Runs before game logic. Use for input handling and preparation
    PreUpdate,
    /// Main game logic. Most user systems should be here
    Update,
    /// Runs after game logic. Use for cleanup or derived updates
    PostUpdate,
    /// Internal engine systems (e.g. scene management)`
    Runtime,
}

impl Stage {
    /// Order of stages
    pub const ORDER: [Stage; 4] = [
        Stage::PreUpdate,
        Stage::Update,
        Stage::PostUpdate,
        Stage::Runtime,
    ];
}

/// Application config defined by user
#[derive(Deserialize, Serialize, Debug)]
struct Config {
    /// Path to assets directory
    assets_path: String,
    /// First scene to display
    initial_scene: String,
    /// ECS system dispatch tick rate
    tick_period: u64,
}

impl App {
    /// Runs the event loop. Must be called only once.
    pub fn run(mut self) -> RuntimeResult<()> {
        self.running = true;
        while self.running {
            self.run_frame()?;
        }
        Ok(())
    }

    fn run_frame(&mut self) -> RuntimeResult<()> {
        let frame_start = Instant::now();

        self.handle_app_events();
        self.dispatch_stage(Stage::PreUpdate);
        self.dispatch_stage(Stage::Update);
        self.dispatch_stage(Stage::PostUpdate);

        self.handle_scene_commands();
        self.dispatch_stage(Stage::Runtime);

        self.world.maintain();

        let dt = self.finish_tick(frame_start.elapsed());

        self.update_plugins(dt);

        Ok(())
    }

    fn handle_app_events(&mut self) {
        let mut receiver = self.world.write_resource::<Events<AppEvent>>();
        receiver.update();
        for ev in receiver.iter() {
            debug!("app event: {:?}", ev);
            match ev {
                AppEvent::ExitRequested => {
                    info!("got ExitRequested, exiting app");
                    self.running = false;
                }
            }
        }
    }

    fn dispatch_stage(&mut self, stage: Stage) {
        self.dispatchers
            .get_mut(&stage)
            .expect("stage dispatcher missing")
            .dispatch(&self.world);
    }

    fn update_plugins(&mut self, dt_seconds: f64) {
        let mut ctx = PluginUpdateContext::new(dt_seconds, &mut self.world);
        for plugin in &mut self.plugins {
            if let Err(e) = plugin.update(&mut ctx) {
                error!("failed to update plugin: {e}");
            }
        }
    }

    fn finish_tick(&mut self, elapsed: Duration) -> f64 {
        let elapsed_nanos = elapsed.as_nanos() as u64;
        let mut time = self.world.write_resource::<Time>();

        let frame_nanos = if elapsed_nanos < time.tick_period {
            let remaining = time.tick_period - elapsed_nanos;
            std::thread::sleep(Duration::from_nanos(remaining));
            time.tick_period
        } else {
            warn!(
                "cannot keep up, tick took {} > {} nanoseconds",
                elapsed_nanos, time.tick_period
            );
            elapsed_nanos
        };

        let dt = frame_nanos as f64 / time::NANOS_PER_SECOND;
        time.ticks += 1;
        time.delta_seconds = dt;
        time.total_elapsed_time += dt;

        dt
    }

    fn handle_scene_commands(&mut self) {
        let commands = {
            let mut scene_commands = self.world.write_resource::<SceneCommands>();
            scene_commands.drain().collect::<Vec<_>>()
        };

        for command in commands {
            match command {
                SceneCommand::SwitchTo(new_scene) => {
                    let old_entities = {
                        let mut active_scene = self.world.write_resource::<ActiveScene>();
                        std::mem::take(&mut active_scene.entities)
                    };
                    for entity in old_entities {
                        let _ = self.world.delete_entity(entity);
                    }
                    let mut active_scene = self.world.write_resource::<ActiveScene>();
                    active_scene.set(new_scene);
                }
                _ => todo!(),
            }
        }
    }
}

impl AppBuilder {
    /// Create a new [`AppBuilder`]
    pub fn new() -> AppBuilder {
        let mut dispatcher_builders = HashMap::new();
        let mut dispatcher_config = HashMap::new();

        for stage in Stage::ORDER {
            dispatcher_builders.insert(stage, DispatcherBuilder::new());
            dispatcher_config.insert(stage, Vec::new());
        }

        Self {
            config: "",
            world: World::new(),
            component_registry: ComponentRegistry::new(),
            dispatcher_builders,
            dispatcher_config,
            plugins: Vec::new(),
        }
    }

    /// Set the application config
    pub fn with_config(mut self, path: &'static str) -> AppBuilder {
        self.config = path;
        self
    }

    /// Register a system in the default gameplay stage ([`Stage::Update`])
    pub fn with_system<S>(self, sys: S) -> Self
    where
        for<'a> S: specs::System<'a> + Send + 'static,
    {
        self.with_system_in_stage(Stage::Update, sys)
    }

    /// Register a system in a specific stage
    pub fn with_system_in_stage<S>(mut self, stage: Stage, sys: S) -> Self
    where
        for<'a> S: specs::System<'a> + Send + 'static,
    {
        push_system_registration(
            self.dispatcher_config
                .get_mut(&stage)
                .expect("stage config missing"),
            sys,
            &[],
        );

        self
    }

    /// Register a system with dependencies in the default gameplay stage
    pub fn with_system_deps<S>(self, sys: S, deps: &'static [&'static str]) -> Self
    where
        for<'a> S: specs::System<'a> + Send + 'static,
    {
        self.with_system_deps_in_stage(Stage::Update, sys, deps)
    }

    /// Register a system with dependencies in a specific stage
    pub fn with_system_deps_in_stage<S>(
        mut self,
        stage: Stage,
        sys: S,
        deps: &'static [&'static str],
    ) -> Self
    where
        for<'a> S: specs::System<'a> + Send + 'static,
    {
        push_system_registration(
            self.dispatcher_config
                .get_mut(&stage)
                .expect("stage config missing"),
            sys,
            deps,
        );

        self
    }

    /// Register a component in the ECS
    pub fn with_component<C: Component, F: ComponentFactory + Default + 'static>(
        mut self,
    ) -> AppBuilder
    where
        <C as Component>::Storage: Default,
    {
        self.world.register::<C>();
        self.component_registry
            .register(F::name(), Box::new(F::default()));
        self
    }

    /// Register a plugin
    pub fn with_plugin<C: Plugin + 'static + Send + Sync>(mut self, plugin: C) -> AppBuilder {
        self.plugins.push(Box::new(plugin));
        self
    }

    /// Builds an [`App`]
    pub fn build(mut self) -> RuntimeResult<App> {
        if self.config.is_empty() {
            return Err(RuntimeError::EmptyConfigPath);
        }

        let config_reader =
            fs::read(self.config).map_err(|source| RuntimeError::ConfigIo { source })?;

        let config: Config = toml::from_slice(&config_reader)?;

        let mut asset_server = AssetServer::with_root(config.assets_path.clone());
        asset_server.register_loader::<Scene>(Box::new(SceneLoader));

        self.world.register::<Handle<Scene>>();

        self.world.insert(Time {
            ticks: 0,
            tick_period: config.tick_period,
            total_elapsed_time: 0.0,
            delta_seconds: 0.0,
        });

        self.world.insert(SceneCommands::default());

        self.load_scenes(&config, &mut asset_server)?;

        self.world.insert(ActiveScene {
            name: Some(config.initial_scene),
            loaded: false,
            entities: Vec::new(),
        });

        self.world.insert(asset_server);
        self.world.insert(Events::<AppEvent>::default());

        self.register_internal_systems();
        self.build_plugins()?;
        self.build_dispatcher_configs();

        let dispatchers = self.build_dispatchers();
        let sender = self.world.write_resource::<Sender<AppEvent>>().clone();
        ctrlc::set_handler(move || {
            sender
                .send(AppEvent::ExitRequested)
                .expect("failed to send exit request message");
        })
        .expect("error setting Ctrl-C handler");

        self.world.insert(self.component_registry);
        // systems shouldn't have access to this, and it already got passed to plugins by this point
        self.world.remove::<Sender<AppEvent>>();

        Ok(App {
            world: self.world,
            dispatchers,
            plugins: self.plugins,
            running: false,
        })
    }

    fn load_scenes(
        &mut self,
        config: &Config,
        asset_server: &mut AssetServer,
    ) -> RuntimeResult<()> {
        let scenes_path = PathBuf::from(&config.assets_path).join("scenes");

        debug!("config.assets_path={}", config.assets_path);
        debug!("scenes_path={}", scenes_path.display());

        let mut library = SceneLibrary::default();

        for entry in fs::read_dir(scenes_path)? {
            let entry = entry?;
            let mut reader = File::open(entry.path())?;

            let scene = asset_server.load_reader::<Scene>(
                entry
                    .file_name()
                    .to_str()
                    .expect("failed to convert scene path to str"),
                &mut reader,
            )?;
            let name = scene.read().name.clone();
            library.scenes.insert(name.clone(), scene);
        }

        self.world.insert(library);

        Ok(())
    }

    fn build_plugins(&mut self) -> RuntimeResult<()> {
        for plugin in self.plugins.iter_mut() {
            let event_sender = self.world.write_resource::<Sender<AppEvent>>().clone();
            let mut ctx = PluginBuildContext {
                world: &mut self.world,
                dispatcher_config: &mut self.dispatcher_config,
                component_registry: &mut self.component_registry,
                event_sender,
            };

            plugin.build(&mut ctx).map_err(|source| {
                error!("failed to build plugin `{}`: {}", plugin.name(), source);

                RuntimeError::PluginSetup {
                    plugin: plugin.name().to_string(),
                    source,
                }
            })?;

            debug!("registered plugin {}", plugin.name());
        }

        Ok(())
    }

    fn register_internal_systems(&mut self) {
        let (sender, receiver) = std::sync::mpsc::channel::<AppEvent>();
        self.world.insert(sender);

        let runtime = self
            .dispatcher_builders
            .get_mut(&Stage::Runtime)
            .expect("runtime dispatcher builder missing");

        runtime.add(SceneSystem, "furmint.scene_system", &[]);

        let pre_update = self
            .dispatcher_builders
            .get_mut(&Stage::PreUpdate)
            .expect("pre-update dispatcher builder missing");
        pre_update.add(
            AppEventReceivingSystem::new(receiver),
            "furmint.app_event_receiving",
            &[],
        );
    }

    fn build_dispatcher_configs(&mut self) {
        for stage in Stage::ORDER {
            let builder = self
                .dispatcher_builders
                .get_mut(&stage)
                .expect("dispatcher builder missing");

            let regs = self
                .dispatcher_config
                .get_mut(&stage)
                .expect("dispatcher config missing");

            for reg in regs.drain(..) {
                reg(builder);
            }

            #[cfg(debug_assertions)]
            {
                debug!("system graph for stage {:?}:", stage);
                builder.print_par_seq();
            }
        }
    }

    fn build_dispatchers(&mut self) -> HashMap<Stage, Dispatcher<'static, 'static>> {
        let mut dispatchers = HashMap::new();

        for stage in Stage::ORDER {
            let builder = self
                .dispatcher_builders
                .remove(&stage)
                .expect("dispatcher builder missing");

            dispatchers.insert(stage, builder.build());
        }

        dispatchers
    }
}

pub(crate) fn push_system_registration<S>(
    config: &mut Vec<SystemRegistration>,
    sys: S,
    deps: &'static [&'static str],
) where
    for<'a> S: specs::System<'a> + Send + 'static,
{
    config.push(Box::new(move |builder| {
        let name = std::any::type_name::<S>();
        builder.add(sys, name, deps);
    }));
}