aboutsummaryrefslogtreecommitdiff
path: root/src/resources.rs
blob: c14596029811b558a46c9824aca320c8c56473cc (plain)
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
use std::{
    fs,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use bevy::prelude::*;

use crate::events::DirworldNavigationEvent;

/// Configuration for Dirworld.
#[derive(Resource)]
pub struct DirworldConfig {
    root: PathBuf,
}

impl DirworldConfig {
    /// Construct a new dirworld config with the given root path. Will panic if the provided path
    /// cannot be canonicalized.
    // TODO: Don't panic? lol
    pub fn new(root: PathBuf) -> Self {
        Self {
            root: fs::canonicalize(root).expect("Failed to canonicalize path!"),
        }
    }

    ///
    pub fn root(&self) -> &PathBuf {
        &self.root
    }
}

/// Contains the dirworld state.
#[derive(Resource)]
pub struct Dirworld {
    /// Current active directory.
    pub path: PathBuf,

    /// Entities local to the current room.
    pub tracked_entities: Vec<Entity>,
}

impl FromWorld for Dirworld {
    fn from_world(world: &mut World) -> Self {
        let config = world.remove_resource::<DirworldConfig>().unwrap();
        world.send_event(DirworldNavigationEvent::EnteredRoom {
            path: config.root().clone(),
        });
        let result = Self {
            path: config.root().clone(),
            tracked_entities: vec![],
        };
        world.insert_resource(config);
        result
    }
}

impl Dirworld {
    /// Move into a new room.
    // TODO: Clear tracked entities?
    // TODO: Make into command extension trait?
    pub fn navigate_to(
        &mut self,
        path: PathBuf,
        event_writer: &mut EventWriter<DirworldNavigationEvent>,
    ) -> Result<()> {
        event_writer.send(DirworldNavigationEvent::LeftRoom {
            path: self.path.clone(),
        });
        self.path = Path::new(&self.path)
            .join(path)
            .to_str()
            .context("Path not valid UTF-8")?
            .into();
        event_writer.send(DirworldNavigationEvent::EnteredRoom {
            path: self.path.clone(),
        });
        Ok(())
    }
}