bevy/crates/bevy_asset/src/event.rs
Brian Reavis c9e1fcdb35
Added AssetLoadFailedEvent, UntypedAssetLoadFailedEvent (#11369)
# Objective

This adds events for assets that fail to load along with minor utility
methods to make them useful. This paves the way for users writing their
own error handling and retry systems, plus Bevy including robust retry
handling: #11349.

* Addresses #11288
* Needed for #11349

# Solution

```rust
/// An event emitted when a specific [`Asset`] fails to load.
#[derive(Event, Clone, Debug)]
pub struct AssetLoadFailedEvent<A: Asset> {
    pub id: AssetId<A>,
    /// The original handle returned when the asset load was requested.
    pub handle: Option<Handle<A>>,
    /// The asset path that was attempted.
    pub path: AssetPath<'static>,
    /// Why the asset failed to load.
    pub error: AssetLoadError,
}
```

I started implementing `AssetEvent::Failed` like suggested in #11288,
but decided it was better as its own type because:

* I think it makes sense for `AssetEvent` to only refer to assets that
actually exist.
* In order to return `AssetLoadError` in the event (which is useful
information for error handlers that might attempt a retry) we would have
to remove `Copy` from `AssetEvent`.
* There are numerous places in the render app that match against
`AssetEvent`, and I don't think it's worth introducing extra noise about
assets that don't exist.

I also introduced `UntypedAssetLoadErrorEvent`, which is very useful in
places that need to support type flexibility, like an Asset-agnostic
retry plugin.

# Changelog

* **Added:** `AssetLoadFailedEvent<A>`
* **Added**: `UntypedAssetLoadFailedEvent`
* **Added:** `AssetReaderError::Http` for status code information on
HTTP errors. Before this, status codes were only available by parsing
the error message of generic `Io` errors.
* **Added:** `asset_server.get_path_id(path)`. This method simply gets
the asset id for the path. Without this, one was left using
`get_path_handle(path)`, which has the overhead of returning a strong
handle.
* **Fixed**: Made `AssetServer` loads return the same handle for assets
that already exist in a failed state. Now, when you attempt a `load`
that's in a `LoadState::Failed` state, it'll re-use the original asset
id. The advantage of this is that any dependent assets created using the
original handle will "unbreak" if a retry succeeds.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-17 21:12:00 +00:00

125 lines
4.7 KiB
Rust

use crate::{Asset, AssetId, AssetLoadError, AssetPath, UntypedAssetId};
use bevy_ecs::event::Event;
use std::fmt::Debug;
/// An event emitted when a specific [`Asset`] fails to load.
///
/// For an untyped equivalent, see [`UntypedAssetLoadFailedEvent`].
#[derive(Event, Clone, Debug)]
pub struct AssetLoadFailedEvent<A: Asset> {
pub id: AssetId<A>,
/// The asset path that was attempted.
pub path: AssetPath<'static>,
/// Why the asset failed to load.
pub error: AssetLoadError,
}
impl<A: Asset> AssetLoadFailedEvent<A> {
/// Converts this to an "untyped" / "generic-less" asset error event that stores the type information.
pub fn untyped(&self) -> UntypedAssetLoadFailedEvent {
self.into()
}
}
/// An untyped version of [`AssetLoadFailedEvent`].
#[derive(Event, Clone, Debug)]
pub struct UntypedAssetLoadFailedEvent {
pub id: UntypedAssetId,
/// The asset path that was attempted.
pub path: AssetPath<'static>,
/// Why the asset failed to load.
pub error: AssetLoadError,
}
impl<A: Asset> From<&AssetLoadFailedEvent<A>> for UntypedAssetLoadFailedEvent {
fn from(value: &AssetLoadFailedEvent<A>) -> Self {
UntypedAssetLoadFailedEvent {
id: value.id.untyped(),
path: value.path.clone(),
error: value.error.clone(),
}
}
}
/// Events that occur for a specific loaded [`Asset`], such as "value changed" events and "dependency" events.
#[derive(Event)]
pub enum AssetEvent<A: Asset> {
/// Emitted whenever an [`Asset`] is added.
Added { id: AssetId<A> },
/// Emitted whenever an [`Asset`] value is modified.
Modified { id: AssetId<A> },
/// Emitted whenever an [`Asset`] is removed.
Removed { id: AssetId<A> },
/// Emitted when the last [`super::Handle::Strong`] of an [`Asset`] is dropped.
Unused { id: AssetId<A> },
/// Emitted whenever an [`Asset`] has been fully loaded (including its dependencies and all "recursive dependencies").
LoadedWithDependencies { id: AssetId<A> },
}
impl<A: Asset> AssetEvent<A> {
/// Returns `true` if this event is [`AssetEvent::LoadedWithDependencies`] and matches the given `id`.
pub fn is_loaded_with_dependencies(&self, asset_id: impl Into<AssetId<A>>) -> bool {
matches!(self, AssetEvent::LoadedWithDependencies { id } if *id == asset_id.into())
}
/// Returns `true` if this event is [`AssetEvent::Added`] and matches the given `id`.
pub fn is_added(&self, asset_id: impl Into<AssetId<A>>) -> bool {
matches!(self, AssetEvent::Added { id } if *id == asset_id.into())
}
/// Returns `true` if this event is [`AssetEvent::Modified`] and matches the given `id`.
pub fn is_modified(&self, asset_id: impl Into<AssetId<A>>) -> bool {
matches!(self, AssetEvent::Modified { id } if *id == asset_id.into())
}
/// Returns `true` if this event is [`AssetEvent::Removed`] and matches the given `id`.
pub fn is_removed(&self, asset_id: impl Into<AssetId<A>>) -> bool {
matches!(self, AssetEvent::Removed { id } if *id == asset_id.into())
}
/// Returns `true` if this event is [`AssetEvent::Unused`] and matches the given `id`.
pub fn is_unused(&self, asset_id: impl Into<AssetId<A>>) -> bool {
matches!(self, AssetEvent::Unused { id } if *id == asset_id.into())
}
}
impl<A: Asset> Clone for AssetEvent<A> {
fn clone(&self) -> Self {
*self
}
}
impl<A: Asset> Copy for AssetEvent<A> {}
impl<A: Asset> Debug for AssetEvent<A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Added { id } => f.debug_struct("Added").field("id", id).finish(),
Self::Modified { id } => f.debug_struct("Modified").field("id", id).finish(),
Self::Removed { id } => f.debug_struct("Removed").field("id", id).finish(),
Self::Unused { id } => f.debug_struct("Unused").field("id", id).finish(),
Self::LoadedWithDependencies { id } => f
.debug_struct("LoadedWithDependencies")
.field("id", id)
.finish(),
}
}
}
impl<A: Asset> PartialEq for AssetEvent<A> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Added { id: l_id }, Self::Added { id: r_id })
| (Self::Modified { id: l_id }, Self::Modified { id: r_id })
| (Self::Removed { id: l_id }, Self::Removed { id: r_id })
| (Self::Unused { id: l_id }, Self::Unused { id: r_id })
| (
Self::LoadedWithDependencies { id: l_id },
Self::LoadedWithDependencies { id: r_id },
) => l_id == r_id,
_ => false,
}
}
}
impl<A: Asset> Eq for AssetEvent<A> {}