# Objective - Fixes #8140 ## Solution - Added Explicit Error Typing for `AssetLoader` and `AssetSaver`, which were the last instances of `anyhow` in use across Bevy. --- ## Changelog - Added an associated type `Error` to `AssetLoader` and `AssetSaver` for use with the `load` and `save` methods respectively. - Changed `ErasedAssetLoader` and `ErasedAssetSaver` `load` and `save` methods to use `Box<dyn Error + Send + Sync + 'static>` to allow for arbitrary `Error` types from the non-erased trait variants. Note the strict requirements match the pre-existing requirements around `anyhow::Error`. ## Migration Guide - `anyhow` is no longer exported by `bevy_asset`; Add it to your own project (if required). - `AssetLoader` and `AssetSaver` have an associated type `Error`; Define an appropriate error type (e.g., using `thiserror`), or use a pre-made error type (e.g., `anyhow::Error`). Note that using `anyhow::Error` is a drop-in replacement. - `AssetLoaderError` has been removed; Define a new error type, or use an alternative (e.g., `anyhow::Error`) - All the first-party `AssetLoader`'s and `AssetSaver`'s now return relevant (and narrow) error types instead of a single ambiguous type; Match over the specific error type, or encapsulate (`Box<dyn>`, `thiserror`, `anyhow`, etc.) ## Notes A simpler PR to resolve this issue would simply define a Bevy `Error` type defined as `Box<dyn std::error::Error + Send + Sync + 'static>`, but I think this type of error handling should be discouraged when possible. Since only 2 traits required the use of `anyhow`, it isn't a substantive body of work to solidify these error types, and remove `anyhow` entirely. End users are still encouraged to use `anyhow` if that is their preferred error handling style. Arguably, adding the `Error` associated type gives more freedom to end-users to decide whether they want more or less explicit error handling (`anyhow` vs `thiserror`). As an aside, I didn't perform any testing on Android or WASM. CI passed locally, but there may be mistakes for those platforms I missed.
145 lines
3.8 KiB
Rust
145 lines
3.8 KiB
Rust
use bevy_asset::{io::Reader, AssetLoader, AsyncReadExt, LoadContext};
|
|
use bevy_ecs::prelude::{FromWorld, World};
|
|
use thiserror::Error;
|
|
|
|
use crate::{
|
|
renderer::RenderDevice,
|
|
texture::{Image, ImageFormat, ImageType, TextureError},
|
|
};
|
|
|
|
use super::CompressedImageFormats;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
/// Loader for images that can be read by the `image` crate.
|
|
#[derive(Clone)]
|
|
pub struct ImageLoader {
|
|
supported_compressed_formats: CompressedImageFormats,
|
|
}
|
|
|
|
pub(crate) const IMG_FILE_EXTENSIONS: &[&str] = &[
|
|
#[cfg(feature = "basis-universal")]
|
|
"basis",
|
|
#[cfg(feature = "bmp")]
|
|
"bmp",
|
|
#[cfg(feature = "png")]
|
|
"png",
|
|
#[cfg(feature = "dds")]
|
|
"dds",
|
|
#[cfg(feature = "tga")]
|
|
"tga",
|
|
#[cfg(feature = "jpeg")]
|
|
"jpg",
|
|
#[cfg(feature = "jpeg")]
|
|
"jpeg",
|
|
#[cfg(feature = "ktx2")]
|
|
"ktx2",
|
|
#[cfg(feature = "webp")]
|
|
"webp",
|
|
#[cfg(feature = "pnm")]
|
|
"pam",
|
|
#[cfg(feature = "pnm")]
|
|
"pbm",
|
|
#[cfg(feature = "pnm")]
|
|
"pgm",
|
|
#[cfg(feature = "pnm")]
|
|
"ppm",
|
|
];
|
|
|
|
#[derive(Serialize, Deserialize, Default)]
|
|
pub enum ImageFormatSetting {
|
|
#[default]
|
|
FromExtension,
|
|
Format(ImageFormat),
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
pub struct ImageLoaderSettings {
|
|
pub format: ImageFormatSetting,
|
|
pub is_srgb: bool,
|
|
}
|
|
|
|
impl Default for ImageLoaderSettings {
|
|
fn default() -> Self {
|
|
Self {
|
|
format: ImageFormatSetting::default(),
|
|
is_srgb: true,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[non_exhaustive]
|
|
#[derive(Debug, Error)]
|
|
pub enum ImageLoaderError {
|
|
#[error("Could load shader: {0}")]
|
|
Io(#[from] std::io::Error),
|
|
#[error("Could not load texture file: {0}")]
|
|
FileTexture(#[from] FileTextureError),
|
|
}
|
|
|
|
impl AssetLoader for ImageLoader {
|
|
type Asset = Image;
|
|
type Settings = ImageLoaderSettings;
|
|
type Error = ImageLoaderError;
|
|
fn load<'a>(
|
|
&'a self,
|
|
reader: &'a mut Reader,
|
|
settings: &'a ImageLoaderSettings,
|
|
load_context: &'a mut LoadContext,
|
|
) -> bevy_utils::BoxedFuture<'a, Result<Image, Self::Error>> {
|
|
Box::pin(async move {
|
|
// use the file extension for the image type
|
|
let ext = load_context.path().extension().unwrap().to_str().unwrap();
|
|
|
|
let mut bytes = Vec::new();
|
|
reader.read_to_end(&mut bytes).await?;
|
|
let image_type = match settings.format {
|
|
ImageFormatSetting::FromExtension => ImageType::Extension(ext),
|
|
ImageFormatSetting::Format(format) => ImageType::Format(format),
|
|
};
|
|
Ok(Image::from_buffer(
|
|
&bytes,
|
|
image_type,
|
|
self.supported_compressed_formats,
|
|
settings.is_srgb,
|
|
)
|
|
.map_err(|err| FileTextureError {
|
|
error: err,
|
|
path: format!("{}", load_context.path().display()),
|
|
})?)
|
|
})
|
|
}
|
|
|
|
fn extensions(&self) -> &[&str] {
|
|
IMG_FILE_EXTENSIONS
|
|
}
|
|
}
|
|
|
|
impl FromWorld for ImageLoader {
|
|
fn from_world(world: &mut World) -> Self {
|
|
let supported_compressed_formats = match world.get_resource::<RenderDevice>() {
|
|
Some(render_device) => CompressedImageFormats::from_features(render_device.features()),
|
|
|
|
None => CompressedImageFormats::NONE,
|
|
};
|
|
Self {
|
|
supported_compressed_formats,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// An error that occurs when loading a texture from a file.
|
|
#[derive(Error, Debug)]
|
|
pub struct FileTextureError {
|
|
error: TextureError,
|
|
path: String,
|
|
}
|
|
impl std::fmt::Display for FileTextureError {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
|
write!(
|
|
f,
|
|
"Error reading image file {}: {}, this is an error in `bevy_render`.",
|
|
self.path, self.error
|
|
)
|
|
}
|
|
}
|