Skip to content

Commit 596bed8

Browse files
add ability to provide custom a AssetIo implementation (#1037)
make it easier to override the default asset IO instance
1 parent 841755a commit 596bed8

File tree

4 files changed

+146
-22
lines changed

4 files changed

+146
-22
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,10 @@ path = "examples/asset/asset_loading.rs"
177177
name = "custom_asset"
178178
path = "examples/asset/custom_asset.rs"
179179

180+
[[example]]
181+
name = "custom_asset_io"
182+
path = "examples/asset/custom_asset_io.rs"
183+
180184
[[example]]
181185
name = "audio"
182186
path = "examples/audio/audio.rs"

crates/bevy_asset/src/asset_server.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,10 @@ impl Clone for AssetServer {
6060

6161
impl AssetServer {
6262
pub fn new<T: AssetIo>(source_io: T, task_pool: TaskPool) -> Self {
63+
Self::with_boxed_io(Box::new(source_io), task_pool)
64+
}
65+
66+
pub fn with_boxed_io(asset_io: Box<dyn AssetIo>, task_pool: TaskPool) -> Self {
6367
AssetServer {
6468
server: Arc::new(AssetServerInternal {
6569
loaders: Default::default(),
@@ -69,7 +73,7 @@ impl AssetServer {
6973
handle_to_path: Default::default(),
7074
asset_lifecycles: Default::default(),
7175
task_pool,
72-
asset_io: Box::new(source_io),
76+
asset_io,
7377
}),
7478
}
7579
}

crates/bevy_asset/src/lib.rs

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -51,28 +51,41 @@ impl Default for AssetServerSettings {
5151
}
5252
}
5353

54+
/// Create an instance of the platform default `AssetIo`
55+
///
56+
/// This is useful when providing a custom `AssetIo` instance that needs to
57+
/// delegate to the default `AssetIo` for the platform.
58+
pub fn create_platform_default_asset_io(app: &mut AppBuilder) -> Box<dyn AssetIo> {
59+
let settings = app
60+
.resources_mut()
61+
.get_or_insert_with(AssetServerSettings::default);
62+
63+
#[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))]
64+
let source = FileAssetIo::new(&settings.asset_folder);
65+
#[cfg(target_arch = "wasm32")]
66+
let source = WasmAssetIo::new(&settings.asset_folder);
67+
#[cfg(target_os = "android")]
68+
let source = AndroidAssetIo::new(&settings.asset_folder);
69+
70+
Box::new(source)
71+
}
72+
5473
impl Plugin for AssetPlugin {
5574
fn build(&self, app: &mut AppBuilder) {
56-
let task_pool = app
57-
.resources()
58-
.get::<IoTaskPool>()
59-
.expect("`IoTaskPool` resource not found.")
60-
.0
61-
.clone();
62-
63-
let asset_server = {
64-
let settings = app
65-
.resources_mut()
66-
.get_or_insert_with(AssetServerSettings::default);
67-
68-
#[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))]
69-
let source = FileAssetIo::new(&settings.asset_folder);
70-
#[cfg(target_arch = "wasm32")]
71-
let source = WasmAssetIo::new(&settings.asset_folder);
72-
#[cfg(target_os = "android")]
73-
let source = AndroidAssetIo::new(&settings.asset_folder);
74-
AssetServer::new(source, task_pool)
75-
};
75+
if app.resources().get::<AssetServer>().is_none() {
76+
let task_pool = app
77+
.resources()
78+
.get::<IoTaskPool>()
79+
.expect("`IoTaskPool` resource not found.")
80+
.0
81+
.clone();
82+
83+
let source = create_platform_default_asset_io(app);
84+
85+
let asset_server = AssetServer::with_boxed_io(source, task_pool);
86+
87+
app.add_resource(asset_server);
88+
}
7689

7790
app.add_stage_before(
7891
bevy_app::stage::PRE_UPDATE,
@@ -84,7 +97,6 @@ impl Plugin for AssetPlugin {
8497
stage::ASSET_EVENTS,
8598
SystemStage::parallel(),
8699
)
87-
.add_resource(asset_server)
88100
.register_type::<HandleId>()
89101
.add_system_to_stage(
90102
bevy_app::stage::PRE_UPDATE,

examples/asset/custom_asset_io.rs

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
use bevy::{
2+
asset::{AssetIo, AssetIoError},
3+
prelude::*,
4+
utils::BoxedFuture,
5+
};
6+
use std::path::{Path, PathBuf};
7+
8+
/// A custom asset io implementation that simply defers to the platform default
9+
/// implementation.
10+
///
11+
/// This can be used as a starting point for developing a useful implementation
12+
/// that can defer to the default when needed.
13+
struct CustomAssetIo(Box<dyn AssetIo>);
14+
15+
impl AssetIo for CustomAssetIo {
16+
fn load_path<'a>(&'a self, path: &'a Path) -> BoxedFuture<'a, Result<Vec<u8>, AssetIoError>> {
17+
println!("load_path({:?})", path);
18+
self.0.load_path(path)
19+
}
20+
21+
fn read_directory(
22+
&self,
23+
path: &Path,
24+
) -> Result<Box<dyn Iterator<Item = PathBuf>>, AssetIoError> {
25+
println!("read_directory({:?})", path);
26+
self.0.read_directory(path)
27+
}
28+
29+
fn is_directory(&self, path: &Path) -> bool {
30+
println!("is_directory({:?})", path);
31+
self.0.is_directory(path)
32+
}
33+
34+
fn watch_path_for_changes(&self, path: &Path) -> Result<(), AssetIoError> {
35+
println!("watch_path_for_changes({:?})", path);
36+
self.0.watch_path_for_changes(path)
37+
}
38+
39+
fn watch_for_changes(&self) -> Result<(), AssetIoError> {
40+
println!("watch_for_changes()");
41+
self.0.watch_for_changes()
42+
}
43+
}
44+
45+
/// A plugin used to execute the override of the asset io
46+
struct CustomAssetIoPlugin;
47+
48+
impl Plugin for CustomAssetIoPlugin {
49+
fn build(&self, app: &mut AppBuilder) {
50+
// must get a hold of the task pool in order to create the asset server
51+
52+
let task_pool = app
53+
.resources()
54+
.get::<bevy::tasks::IoTaskPool>()
55+
.expect("`IoTaskPool` resource not found.")
56+
.0
57+
.clone();
58+
59+
let asset_io = {
60+
// the platform default asset io requires a reference to the app
61+
// builder to find its configuration
62+
63+
let default_io = bevy::asset::create_platform_default_asset_io(app);
64+
65+
// create the custom asset io instance
66+
67+
CustomAssetIo(default_io)
68+
};
69+
70+
// the asset server is constructed and added the resource manager
71+
72+
app.add_resource(AssetServer::new(asset_io, task_pool));
73+
}
74+
}
75+
76+
fn main() {
77+
App::build()
78+
.add_plugins_with(DefaultPlugins, |group| {
79+
// the custom asset io plugin must be inserted in-between the
80+
// `CorePlugin' and `AssetPlugin`. It needs to be after the
81+
// CorePlugin, so that the IO task pool has already been constructed.
82+
// And it must be before the `AssetPlugin` so that the asset plugin
83+
// doesn't create another instance of an assert server. In general,
84+
// the AssetPlugin should still run so that other aspects of the
85+
// asset system are initialized correctly.
86+
group.add_before::<bevy::asset::AssetPlugin, _>(CustomAssetIoPlugin)
87+
})
88+
.add_startup_system(setup)
89+
.run();
90+
}
91+
92+
fn setup(
93+
commands: &mut Commands,
94+
asset_server: Res<AssetServer>,
95+
mut materials: ResMut<Assets<ColorMaterial>>,
96+
) {
97+
let texture_handle = asset_server.load("branding/icon.png");
98+
commands
99+
.spawn(Camera2dBundle::default())
100+
.spawn(SpriteBundle {
101+
material: materials.add(texture_handle.into()),
102+
..Default::default()
103+
});
104+
}

0 commit comments

Comments
 (0)