~starkingdoms/starkingdoms

ref: 05fbfecfb41273eb861531bc69beed8f4f72f026 starkingdoms/crates/unified/src/server/world_config.rs -rw-r--r-- 1.6 KiB
05fbfecf — core feat(netcode): aeronet 5 months ago
                                                                                
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
use crate::config::world::GlobalWorldConfig;
use bevy::asset::Handle;
use bevy::prelude::*;

pub fn world_config_plugin(app: &mut App) {
    app.init_resource::<WorldConfigResource>()
        .add_systems(Startup, start_loading_planets)
        .add_systems(Update, update_planets);
}

#[derive(Resource, Default)]
pub struct WorldConfigResource {
    handle: Option<Handle<GlobalWorldConfig>>,
    pub config: Option<GlobalWorldConfig>,
}

fn start_loading_planets(assets: Res<AssetServer>, mut planets: ResMut<WorldConfigResource>) {
    planets.handle = Some(assets.load("config/world.wc.toml"));
}

pub fn update_planets(
    commands: Commands,
    mut ev_config: EventReader<AssetEvent<GlobalWorldConfig>>,
    assets: ResMut<Assets<GlobalWorldConfig>>,
    mut resource: ResMut<WorldConfigResource>,
) {
    let Some(handle) = resource.handle.as_ref() else {
        return;
    };

    let waiting_for_asset_id = handle.id();

    for ev in ev_config.read() {
        match ev {
            AssetEvent::Added { id } => {
                if *id == waiting_for_asset_id {
                    info!("world config loaded");
                    let world_config = assets.get(*id).unwrap();
                    resource.config = Some(world_config.clone());
                }
            }
            AssetEvent::Modified { id } => {
                if *id == waiting_for_asset_id {
                    info!("world config modified - reloading");
                    let world_config = assets.get(*id).unwrap();
                    resource.config = Some(world_config.clone());
                }
            }
            _ => {}
        }
    }
}