# Objective
The `AssetReader` trait allows customizing the behavior of fetching
bytes for an `AssetPath`, and expects implementors to return `dyn
AsyncRead + AsyncSeek`. This gives implementors of `AssetLoader` great
flexibility to tightly integrate their asset loading behavior with the
asynchronous task system.
However, almost all implementors of `AssetLoader` don't use the async
functionality at all, and just call `AsyncReadExt::read_to_end(&mut
Vec<u8>)`. This is incredibly inefficient, as this method repeatedly
calls `poll_read` on the trait object, filling the vector 32 bytes at a
time. At my work we have assets that are hundreds of megabytes which
makes this a meaningful overhead.
## Solution
Turn the `Reader` type alias into an actual trait, with a provided
method `read_to_end`. This provided method should be more efficient than
the existing extension method, as the compiler will know the underlying
type of `Reader` when generating this function, which removes the
repeated dynamic dispatches and allows the compiler to make further
optimizations after inlining. Individual implementors are able to
override the provided implementation -- for simple asset readers that
just copy bytes from one buffer to another, this allows removing a large
amount of overhead from the provided implementation.
Now that `Reader` is an actual trait, I also improved the ergonomics for
implementing `AssetReader`. Currently, implementors are expected to box
their reader and return it as a trait object, which adds unnecessary
boilerplate to implementations. This PR changes that trait method to
return a pseudo trait alias, which allows implementors to return `impl
Reader` instead of `Box<dyn Reader>`. Now, the boilerplate for boxing
occurs in `ErasedAssetReader`.
## Testing
I made identical changes to my company's fork of bevy. Our app, which
makes heavy use of `read_to_end` for asset loading, still worked
properly after this. I am not aware if we have a more systematic way of
testing asset loading for correctness.
---
## Migration Guide
The trait method `bevy_asset::io::AssetReader::read` (and `read_meta`)
now return an opaque type instead of a boxed trait object. Implementors
of these methods should change the type signatures appropriately
```rust
impl AssetReader for MyReader {
    // Before
    async fn read<'a>(&'a self, path: &'a Path) -> Result<Box<Reader<'a>>, AssetReaderError> {
        let reader = // construct a reader
        Box::new(reader) as Box<Reader<'a>>
    }
    // After
    async fn read<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
        // create a reader
    }
}
```
`bevy::asset::io::Reader` is now a trait, rather than a type alias for a
trait object. Implementors of `AssetLoader::load` will need to adjust
the method signature accordingly
```rust
impl AssetLoader for MyLoader {
    async fn load<'a>(
        &'a self,
        // Before:
        reader: &'a mut bevy::asset::io::Reader,
        // After:
        reader: &'a mut dyn bevy::asset::io::Reader,
        _: &'a Self::Settings,
        load_context: &'a mut LoadContext<'_>,
    ) -> Result<Self::Asset, Self::Error> {
}
```
Additionally, implementors of `AssetReader` that return a type
implementing `futures_io::AsyncRead` and `AsyncSeek` might need to
explicitly implement `bevy::asset::io::Reader` for that type.
```rust
impl bevy::asset::io::Reader for MyAsyncReadAndSeek {}
```
		
	
			
		
			
				
	
	
		
			157 lines
		
	
	
		
			4.0 KiB
		
	
	
	
		
			Rust
		
	
	
	
	
	
			
		
		
	
	
			157 lines
		
	
	
		
			4.0 KiB
		
	
	
	
		
			Rust
		
	
	
	
	
	
//! Implements loader for a custom asset type.
 | 
						|
 | 
						|
use bevy::{
 | 
						|
    asset::{io::Reader, AssetLoader, LoadContext},
 | 
						|
    prelude::*,
 | 
						|
    reflect::TypePath,
 | 
						|
};
 | 
						|
use serde::Deserialize;
 | 
						|
use thiserror::Error;
 | 
						|
 | 
						|
#[derive(Asset, TypePath, Debug, Deserialize)]
 | 
						|
struct CustomAsset {
 | 
						|
    #[allow(dead_code)]
 | 
						|
    value: i32,
 | 
						|
}
 | 
						|
 | 
						|
#[derive(Default)]
 | 
						|
struct CustomAssetLoader;
 | 
						|
 | 
						|
/// Possible errors that can be produced by [`CustomAssetLoader`]
 | 
						|
#[non_exhaustive]
 | 
						|
#[derive(Debug, Error)]
 | 
						|
enum CustomAssetLoaderError {
 | 
						|
    /// An [IO](std::io) Error
 | 
						|
    #[error("Could not load asset: {0}")]
 | 
						|
    Io(#[from] std::io::Error),
 | 
						|
    /// A [RON](ron) Error
 | 
						|
    #[error("Could not parse RON: {0}")]
 | 
						|
    RonSpannedError(#[from] ron::error::SpannedError),
 | 
						|
}
 | 
						|
 | 
						|
impl AssetLoader for CustomAssetLoader {
 | 
						|
    type Asset = CustomAsset;
 | 
						|
    type Settings = ();
 | 
						|
    type Error = CustomAssetLoaderError;
 | 
						|
    async fn load<'a>(
 | 
						|
        &'a self,
 | 
						|
        reader: &'a mut dyn Reader,
 | 
						|
        _settings: &'a (),
 | 
						|
        _load_context: &'a mut LoadContext<'_>,
 | 
						|
    ) -> Result<Self::Asset, Self::Error> {
 | 
						|
        let mut bytes = Vec::new();
 | 
						|
        reader.read_to_end(&mut bytes).await?;
 | 
						|
        let custom_asset = ron::de::from_bytes::<CustomAsset>(&bytes)?;
 | 
						|
        Ok(custom_asset)
 | 
						|
    }
 | 
						|
 | 
						|
    fn extensions(&self) -> &[&str] {
 | 
						|
        &["custom"]
 | 
						|
    }
 | 
						|
}
 | 
						|
 | 
						|
#[derive(Asset, TypePath, Debug)]
 | 
						|
struct Blob {
 | 
						|
    bytes: Vec<u8>,
 | 
						|
}
 | 
						|
 | 
						|
#[derive(Default)]
 | 
						|
struct BlobAssetLoader;
 | 
						|
 | 
						|
/// Possible errors that can be produced by [`BlobAssetLoader`]
 | 
						|
#[non_exhaustive]
 | 
						|
#[derive(Debug, Error)]
 | 
						|
enum BlobAssetLoaderError {
 | 
						|
    /// An [IO](std::io) Error
 | 
						|
    #[error("Could not load file: {0}")]
 | 
						|
    Io(#[from] std::io::Error),
 | 
						|
}
 | 
						|
 | 
						|
impl AssetLoader for BlobAssetLoader {
 | 
						|
    type Asset = Blob;
 | 
						|
    type Settings = ();
 | 
						|
    type Error = BlobAssetLoaderError;
 | 
						|
 | 
						|
    async fn load<'a>(
 | 
						|
        &'a self,
 | 
						|
        reader: &'a mut dyn Reader,
 | 
						|
        _settings: &'a (),
 | 
						|
        _load_context: &'a mut LoadContext<'_>,
 | 
						|
    ) -> Result<Self::Asset, Self::Error> {
 | 
						|
        info!("Loading Blob...");
 | 
						|
        let mut bytes = Vec::new();
 | 
						|
        reader.read_to_end(&mut bytes).await?;
 | 
						|
 | 
						|
        Ok(Blob { bytes })
 | 
						|
    }
 | 
						|
}
 | 
						|
 | 
						|
fn main() {
 | 
						|
    App::new()
 | 
						|
        .add_plugins(DefaultPlugins)
 | 
						|
        .init_resource::<State>()
 | 
						|
        .init_asset::<CustomAsset>()
 | 
						|
        .init_asset::<Blob>()
 | 
						|
        .init_asset_loader::<CustomAssetLoader>()
 | 
						|
        .init_asset_loader::<BlobAssetLoader>()
 | 
						|
        .add_systems(Startup, setup)
 | 
						|
        .add_systems(Update, print_on_load)
 | 
						|
        .run();
 | 
						|
}
 | 
						|
 | 
						|
#[derive(Resource, Default)]
 | 
						|
struct State {
 | 
						|
    handle: Handle<CustomAsset>,
 | 
						|
    other_handle: Handle<CustomAsset>,
 | 
						|
    blob: Handle<Blob>,
 | 
						|
    printed: bool,
 | 
						|
}
 | 
						|
 | 
						|
fn setup(mut state: ResMut<State>, asset_server: Res<AssetServer>) {
 | 
						|
    // Recommended way to load an asset
 | 
						|
    state.handle = asset_server.load("data/asset.custom");
 | 
						|
 | 
						|
    // File extensions are optional, but are recommended for project management and last-resort inference
 | 
						|
    state.other_handle = asset_server.load("data/asset_no_extension");
 | 
						|
 | 
						|
    // Will use BlobAssetLoader instead of CustomAssetLoader thanks to type inference
 | 
						|
    state.blob = asset_server.load("data/asset.custom");
 | 
						|
}
 | 
						|
 | 
						|
fn print_on_load(
 | 
						|
    mut state: ResMut<State>,
 | 
						|
    custom_assets: Res<Assets<CustomAsset>>,
 | 
						|
    blob_assets: Res<Assets<Blob>>,
 | 
						|
) {
 | 
						|
    let custom_asset = custom_assets.get(&state.handle);
 | 
						|
    let other_custom_asset = custom_assets.get(&state.other_handle);
 | 
						|
    let blob = blob_assets.get(&state.blob);
 | 
						|
 | 
						|
    // Can't print results if the assets aren't ready
 | 
						|
    if state.printed {
 | 
						|
        return;
 | 
						|
    }
 | 
						|
 | 
						|
    if custom_asset.is_none() {
 | 
						|
        info!("Custom Asset Not Ready");
 | 
						|
        return;
 | 
						|
    }
 | 
						|
 | 
						|
    if other_custom_asset.is_none() {
 | 
						|
        info!("Other Custom Asset Not Ready");
 | 
						|
        return;
 | 
						|
    }
 | 
						|
 | 
						|
    if blob.is_none() {
 | 
						|
        info!("Blob Not Ready");
 | 
						|
        return;
 | 
						|
    }
 | 
						|
 | 
						|
    info!("Custom asset loaded: {:?}", custom_asset.unwrap());
 | 
						|
    info!("Custom asset loaded: {:?}", other_custom_asset.unwrap());
 | 
						|
    info!("Blob Size: {:?} Bytes", blob.unwrap().bytes.len());
 | 
						|
 | 
						|
    // Once printed, we won't print again
 | 
						|
    state.printed = true;
 | 
						|
}
 |