bevy_asset/io/file/
mod.rs

1#[cfg(feature = "file_watcher")]
2mod file_watcher;
3
4#[cfg(feature = "multi_threaded")]
5mod file_asset;
6#[cfg(not(feature = "multi_threaded"))]
7mod sync_file_asset;
8
9use bevy_utils::tracing::{debug, error};
10#[cfg(feature = "file_watcher")]
11pub use file_watcher::*;
12
13use std::{
14    env,
15    path::{Path, PathBuf},
16};
17
18pub(crate) fn get_base_path() -> PathBuf {
19    if let Ok(manifest_dir) = env::var("BEVY_ASSET_ROOT") {
20        PathBuf::from(manifest_dir)
21    } else if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
22        PathBuf::from(manifest_dir)
23    } else {
24        env::current_exe()
25            .map(|path| path.parent().map(ToOwned::to_owned).unwrap())
26            .unwrap()
27    }
28}
29
30/// I/O implementation for the local filesystem.
31///
32/// This asset I/O is fully featured but it's not available on `android` and `wasm` targets.
33pub struct FileAssetReader {
34    root_path: PathBuf,
35}
36
37impl FileAssetReader {
38    /// Creates a new `FileAssetIo` at a path relative to the executable's directory, optionally
39    /// watching for changes.
40    ///
41    /// See `get_base_path` below.
42    pub fn new<P: AsRef<Path>>(path: P) -> Self {
43        let root_path = Self::get_base_path().join(path.as_ref());
44        debug!(
45            "Asset Server using {} as its base path.",
46            root_path.display()
47        );
48        Self { root_path }
49    }
50
51    /// Returns the base path of the assets directory, which is normally the executable's parent
52    /// directory.
53    ///
54    /// To change this, set [`AssetPlugin.file_path`].
55    pub fn get_base_path() -> PathBuf {
56        get_base_path()
57    }
58
59    /// Returns the root directory where assets are loaded from.
60    ///
61    /// See `get_base_path`.
62    pub fn root_path(&self) -> &PathBuf {
63        &self.root_path
64    }
65}
66
67pub struct FileAssetWriter {
68    root_path: PathBuf,
69}
70
71impl FileAssetWriter {
72    /// Creates a new `FileAssetIo` at a path relative to the executable's directory, optionally
73    /// watching for changes.
74    ///
75    /// See `get_base_path` below.
76    pub fn new<P: AsRef<Path> + core::fmt::Debug>(path: P, create_root: bool) -> Self {
77        let root_path = get_base_path().join(path.as_ref());
78        if create_root {
79            if let Err(e) = std::fs::create_dir_all(&root_path) {
80                error!(
81                    "Failed to create root directory {:?} for file asset writer: {:?}",
82                    root_path, e
83                );
84            }
85        }
86        Self { root_path }
87    }
88}